Skip to content

Instantly share code, notes, and snippets.

@yllan
Last active September 11, 2020 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yllan/c2fcbdd502f0c9ad60087acbeccd360e to your computer and use it in GitHub Desktop.
Save yllan/c2fcbdd502f0c9ad60087acbeccd360e to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const m = Machine({
id: 'websocket',
context: {
devices: []
},
initial: 'offline',
states: {
offline: {
on: {
CONNECT: 'trying'
}
},
trying: {
invoke: {
id: "websocket-simulator",
src: (ctx, evt) => (callback, receive) => {
setTimeout(() => { callback('SUCCESS') }, 1 * 1000)
setTimeout(() => { callback('ACCEPT') }, 2 * 1000)
setTimeout(() => { callback('AUTH') }, 3 * 1000)
}
},
on: {
SUCCESS: 'online',
FAILED: 'offline'
}
},
online: {
on: {
DISCONNECT: 'offline'
},
initial: 'notAccepted',
states: {
notAccepted: {
on: {
ACCEPT: 'accepted'
}
},
accepted: {
type: 'parallel',
states: {
session: {
initial: 'notAuthenticated',
on: {
DEVICES_UPDATE: {
actions: [
'assignDevices',
'cancelSendDevicesEvent',
'sendDevicesAfterDelay'
]
},
SEND_DEVICES: {
actions: [
'sendDevices'
]
}
},
states: {
notAuthenticated: {
on: {
AUTH: 'authenticated'
}
},
authenticated: {
type: 'final'
}
}
},
keepAlive: {
initial: 'ping',
states: {
ping: {
entry: [ 'sendPing', 'sendTimeout' ],
on: {
PONG: 'pong',
TIMEOUT: 'timeout'
}
},
pong: {
entry: [ actions.cancel('timeout-action'), actions.send('PING', { delay: 3000 }) ],
on: {
PING: 'ping',
TIMEOUT: 'timeout'
}
},
timeout: {
type: 'final',
entry: [ actions.send('DISCONNECT') ]
}
}
}
}
}
}
},
websocketHist: {
type: "history",
history: "deep"
}
},
on: {
DEVICES_UPDATE: {
actions: [ 'assignDevices' ],
target: "websocketHist"
}
}
},
{
actions: {
sendPing: (context, event) => {
console.log('> ping')
},
sendTimeout: actions.send('TIMEOUT', {
delay: 10 * 1000,
id: 'timeout-action'
}),
assignDevices: assign({ devices: (_ctx, event) => event.devices }),
cancelSendDevicesEvent: actions.cancel('send-devices-action'),
sendDevicesAfterDelay: actions.send('SEND_DEVICES', {
delay: 10 * 1000,
id: 'send-devices-action'
}),
sendDevices: (context, event) => {
console.log("ws.write: ", context.devices)
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment