Skip to content

Instantly share code, notes, and snippets.

@MilanLempera
Created April 28, 2020 05:50
Show Gist options
  • Select an option

  • Save MilanLempera/489ca82a27f1a2e8961c2b1e791142e4 to your computer and use it in GitHub Desktop.

Select an option

Save MilanLempera/489ca82a27f1a2e8961c2b1e791142e4 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const { log } = actions;
const START_CHAR = '-';
const END_CHAR = '-';
const CONTROL_SEQUENCE_COUNT = 3;
const CONTROL_SEQUENCE_TIMEOUT = 200;
const DATA_TIMEOUT = 2000;
const scannerMachine = Machine({
id: 'scannerMachine',
initial: 'waitingForChars',
context: {
code: '',
startCharCount: CONTROL_SEQUENCE_COUNT,
endCharCount: CONTROL_SEQUENCE_COUNT,
},
states: {
waitingForChars: {
entry: 'resetContext',
on: {
KEYPRESS: { target: 'startSeq', cond: 'isStartChar' },
},
},
startSeq: {
entry: 'decrementStartCharCount',
on: {
KEYPRESS: [
{
target: 'startSeq',
cond: 'isStartChar',
},
{ target: 'waitingForChars' },
],
'': { target: 'receiving', cond: 'isStarted' },
},
after: {
[CONTROL_SEQUENCE_TIMEOUT]: 'waitingForChars',
},
},
receiving: {
entry: 'resetSeqCounters',
on: {
KEYPRESS: [
{
target: 'endSeq',
cond: 'isEndChar',
},
{
target: 'receiving',
actions: 'appendKeyToCode',
},
],
},
after: {
[DATA_TIMEOUT]: 'waitingForChars',
},
},
endSeq: {
entry: 'decrementEndCharCount',
on: {
KEYPRESS: [
{
target: 'endSeq',
cond: 'isEndChar',
},
{
target: 'receiving',
actions: 'assignEndCharsAndKey',
},
],
'': {
target: 'received',
cond: 'isEnded',
},
},
after: {
[CONTROL_SEQUENCE_TIMEOUT]: 'waitingForChars',
},
},
received: {
entry: 'codeReceived',
on: {
'': 'waitingForChars',
},
},
},
}, {
guards: {
isStartChar: (_, { key }) => key === START_CHAR,
isEndChar: (_, { key }) => key === END_CHAR,
isStarted: ({ startCharCount }) => startCharCount === 0,
isEnded: ({ endCharCount }) => endCharCount === 0,
},
actions: {
codeReceived: log((context, event) => `codeReceived: ${context.code}, event: ${event.type}`),
assignEndCharsAndKey: assign({
code: ({ code, endCharCount }, { key }) => code + END_CHAR.repeat(CONTROL_SEQUENCE_COUNT - endCharCount) + key,
}),
decrementEndCharCount: assign({
endCharCount: ({ endCharCount }) => endCharCount - 1,
}),
decrementStartCharCount: assign({
startCharCount: ({ startCharCount }) => startCharCount - 1,
}),
appendKeyToCode: assign({
code: ({ code }, { key }) => code + key,
}),
resetSeqCounters: assign({
startCharCount: CONTROL_SEQUENCE_COUNT,
endCharCount: CONTROL_SEQUENCE_COUNT,
}),
resetContext: assign({
code: '',
startCharCount: CONTROL_SEQUENCE_COUNT,
endCharCount: CONTROL_SEQUENCE_COUNT,
}),
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment