Skip to content

Instantly share code, notes, and snippets.

@drmikecrowe drmikecrowe/machine.js
Last active Nov 21, 2019

Embed
What would you like to do?
initializeMachine.js
const RETRY_INTERVAL = 2000;
const MAX_RETRIES = 3;
const initHardwareState = "initHardware";
const connectNetworkState = "connectNetwork";
const provisionState = "provision";
const retryState = "retry";
const fatalState = "fatal";
const connectedState = "connected";
const SHUTDOWN = "SHUTDOWN";
const T_SHUTDOWN = { type: SHUTDOWN };
const INIT_HARDWARE_COMPLETE = "INIT_HARDWARE_COMPLETE";
const T_INIT_HARDWARE_COMPLETE = { type: INIT_HARDWARE_COMPLETE };
const WIFI_CONNECTED = "WIFI_CONNECTED";
const T_WIFI_CONNECTED = { type: WIFI_CONNECTED };
const IOT_CONNECTED = "IOT_CONNECTED";
const T_IOT_CONNECTED = { type: IOT_CONNECTED };
const READY = "READY";
const T_READY = { type: READY };
const ERROR = "ERROR";
const T_ERROR = { type: ERROR };
const NETWORK_DISCONNECTED = "NETWORK_DISCONNECTED";
const T_NETWORK_DISCONNECTED = { type: NETWORK_DISCONNECTED };
const dassign = (obj) => {
console.log(`Assigning: `, obj);
return assign({...obj});
};
const incrementRetries = dassign({ retries: ctx => ctx.retries + 1 });
const resetRetries = dassign({ retries: 0 });
const condHaveRetries = (ctx, _) => ctx.retries < MAX_RETRIES;
const condHaveNoRetries = (ctx, _) => ctx.retries >= MAX_RETRIES;
const defaultContext = {
retries: 0,
};
const hardwareMachineDef = {
id: "Hardware",
initial: initHardwareState,
context: {
retries: 0,
},
states: {
[initHardwareState]: {
on: {
[INIT_HARDWARE_COMPLETE]: { target: connectNetworkState, actions: "resetRetries" },
[ERROR]: { target: retryState, actions: "incrementRetries" },
},
},
[connectNetworkState]: {
on: {
[WIFI_CONNECTED]: { target: provisionState, actions: "resetRetries" },
[ERROR]: { target: retryState, actions: "incrementRetries" },
},
},
[provisionState]: {
on: {
[IOT_CONNECTED]: { target: connectedState, actions: "resetRetries" },
[ERROR]: { target: retryState, actions: "incrementRetries" },
},
},
[retryState]: {
after: {
[RETRY_INTERVAL]: { target: initHardwareState, cond: "condHaveRetries" },
0: { target: fatalState, cond: "condHaveNoRetries" },
},
},
[fatalState]: {
type: "final",
data: { error: "Hardware Failure" },
},
[connectedState]: {
// activities: [activities.monitorNetwork.name],
on: {
[NETWORK_DISCONNECTED]: { target: initHardwareState },
},
},
},
};
const hardwareMachineOpts = {
actions: {
incrementRetries,
resetRetries,
},
guards: {
condHaveNoRetries,
condHaveRetries,
},
};
const hardwareMachine = Machine(hardwareMachineDef, hardwareMachineOpts);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.