Last active
February 25, 2021 04:18
-
-
Save xralphack/23a12a3034ad319138febe0e9eb23f19 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetchDeviceState = () => Promise.resolve({ | |
'online': true, | |
'isWatering': Math.random() > 0.1, | |
'isFirmwareUpdating': false | |
}) | |
const yardianStateMachine = Machine({ | |
id: 'yardian-state-machine', | |
initial: 'fetchingDeviceState', | |
context: { | |
retries: 0, | |
deviceState: null, | |
}, | |
states: { | |
fetchingDeviceState: { | |
entry: ['incrementRetries'], | |
invoke: { | |
id: 'fetchDeviceState', | |
src: fetchDeviceState, | |
onDone: { | |
target: 'parsingDeviceState', | |
actions: [ | |
'resetRetries', | |
'setDeviceState', | |
] | |
}, | |
onError: { | |
target: 'failure' | |
} | |
} | |
// on: { | |
// success: { | |
// target: 'success' | |
// }, | |
// failure: { | |
// target: 'failure' | |
// } | |
// } | |
}, | |
parsingDeviceState: { | |
on: { | |
'': [ | |
{ | |
target: 'offline', | |
cond: 'isOffline' | |
}, | |
{ | |
target: 'watering', | |
cond: 'isWatering' | |
}, | |
{ | |
target: 'firmwareUpdating', | |
cond: 'isFirmwareUpdating' | |
}, | |
{ | |
target: 'idle', | |
} | |
] | |
} | |
}, | |
offline: { | |
}, | |
watering: { | |
after: { | |
500: { | |
target: 'parsingDeviceState' | |
} | |
} | |
}, | |
firmwareUpdating: { | |
}, | |
idle: { | |
}, | |
failure: { | |
on: { | |
'': { | |
target: "fatal", | |
cond: (context) => context.retries >= 3 | |
} | |
}, | |
// after: { | |
// 1000: { | |
// target: 'fetchingDeviceState', | |
// } | |
// } | |
}, | |
fatal: { | |
on: { | |
RETRY: { | |
target: 'fetchingDeviceState', | |
actions: ['resetRetries'] | |
} | |
} | |
} | |
} | |
}, { | |
actions: { | |
'incrementRetries': assign({ retries: context => context.retries + 1 }), | |
'resetRetries': assign({ retries: 0 }), | |
'setDeviceState': assign({ deviceState: (_, event) => { | |
console.log(event.data) | |
return event.data }}) | |
}, | |
guards: { | |
'isOffline': ctx => ctx.deviceState && ctx.deviceState.offline, | |
'isWatering': ctx => { | |
return ctx.deviceState && ctx.deviceState.isWatering | |
}, | |
'isFirmwareUpdating': ctx => ctx.deviceState && ctx.deviceState.isFirmwareUpdating | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment