Skip to content

Instantly share code, notes, and snippets.

@lithin
Last active June 17, 2019 16:20
Show Gist options
  • Save lithin/1175d95f21cae23f192c678f8186387b to your computer and use it in GitHub Desktop.
Save lithin/1175d95f21cae23f192c678f8186387b to your computer and use it in GitHub Desktop.
State machine discovering devices
const states = {
DISCOVERY: 'DISCOVERY',
GET_STARTED: 'GET_STARTED',
RENAME: 'RENAME',
TIMEOUT: 'TIMEOUT',
DONE: 'DONE',
ERROR: 'ERROR',
};
const discoveryStates = {
PAIR_NEW_DEVICES: 'PAIR_NEW_DEVICES',
TIMEOUT: 'TIMEOUT',
};
const transitions = {
TO_DISCOVERY: 'TO_DISCOVERY',
TO_INSTALL: 'TO_INSTALL',
TO_RENAME: 'TO_RENAME',
TO_START: 'TO_START',
TO_ERROR: 'TO_ERROR',
TO_TIMEOUT: 'TO_TIMEOUT',
TO_DONE: 'TO_DONE',
};
const installDevicesMachine = Machine(
{
id: 'installDevices',
initial: states.GET_STARTED,
context: {
newDevices: [],
POLL_TIMEOUT: 500,
TIMEOUT: 30000,
},
states: {
[states.GET_STARTED]: {
on: { [transitions.TO_DISCOVERY]: states.DISCOVERY, [transitions.TO_INSTALL]: states.DONE },
},
[states.DISCOVERY]: {
on: {
[transitions.TO_RENAME]: states.RENAME,
[transitions.TO_START]: states.GET_STARTED,
[transitions.TO_ERROR]: states.ERROR,
},
states: {
[discoveryStates.PAIR_NEW_DEVICES]: {
id: discoveryStates.PAIR_NEW_DEVICES,
invoke: {
src: (context, event) => {
console.log('invoking');
return new Promise((resolve, reject) =>
setTimeout(() => resolve({ devices: [] }), 200)
);
},
onDone: {
actions: assign({
newDevices: (context, event) => {
console.log('adding new devices', context.newDevices);
if (event.data.devices.length) {
return [...context.newDevices, event.data.devices];
}
return context.newDevices;
},
}),
},
onError: {
target: `#${states.ERROR}`,
},
},
after: {
POLL_TIMEOUT: discoveryStates.PAIR_NEW_DEVICES,
},
},
[discoveryStates.TIMEOUT]: {
after: {
TIMEOUT: `#${states.TIMEOUT}`,
},
},
},
},
[states.RENAME]: {
on: { [transitions.TO_DONE]: states.DONE },
onExit: ['finishLoadingDevices'],
},
[states.ERROR]: {
id: states.ERROR,
},
[states.TIMEOUT]: {
id: states.TIMEOUT,
},
[states.DONE]: {
type: 'final',
onEntry: ['navigate'],
},
},
strict: true,
},
{
actions: {
navigate: (context, event) => {
console.log('this is where we will navigate', context, event);
if (event.type === transitions.TO_INSTALL) {
hiveNavigate.dismissModal();
}
if (event.type === transitions.TO_DONE) {
hiveNavigate.popToRoot(routePaths.install).then(() => hiveNavigate.dismissModal());
}
},
finishLoadingDevices: (context, event) => {
console.log('this is where we will finish installation', context, event);
event.finishInstallDevices(event.payload);
},
},
delays: {
TIMEOUT: context => context.TIMEOUT,
POLL_TIMEOUT: context => context.POLL_TIMEOUT,
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment