Skip to content

Instantly share code, notes, and snippets.

@karlin
Last active January 29, 2020 03:01
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 karlin/60570390017425aa339f8122dac22267 to your computer and use it in GitHub Desktop.
Save karlin/60570390017425aa339f8122dac22267 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Goal: https://github.com/karlin/One_Button_Alarmduino/blob/master/One_Button_Alarmduino.ino
// Ref: https://xstate.js.org/docs/guides/activities.html
// Visualizer: https://xstate.js.org/viz/?gist=60570390017425aa339f8122dac22267
function createBeepingActivity(context, activity) {
// Start the beeping activity
const interval = setInterval(() => {
console.log('BEEP!');
}, context.intervalSeconds*1000);
// Return a function that stops the beeping activity
return () => clearInterval(interval);
}
const beepingStates = {
initial: 'on',
states: {
on: {
on: {
ONE_SEC: 'off',
actions: assign({
buttonHeldSeconds: (context, event) =>
context.buttonHeldSeconds + 1
})
}
},
off: {
on: {
ONE_SEC: 'on',
actions: assign({
buttonHeldSeconds: (context, event) =>
context.buttonHeldSeconds + 1
})
}
}
}
};
const alarmduino = Machine(
{
id: 'alarm',
initial: 'clock',
context: {
buttonPressed: false,
snoozing: false,
alarmOn: false,
blinkColon: false,
// int alarmTime: 641;
snoozeDelay: 7,
buttonHeldSeconds: 0,
pressToDisableAlarmSeconds: 5,
snoozeSeconds: () => {context.snoozeDelay*60},
intervalSeconds: 1 // beep every second
},
states: {
clock: {
on: {
"ALARM TIME": {
target: 'inAlarm'
}
}
},
inAlarm: {
activities: ['beeping'],
on: {
"PUSH BUTTON": {
target: 'buttonDown',
actions: assign({
buttonPressed: (context, event) => true
})
}
},
...beepingStates
},
buttonDown: {
on: {
"RELEASE BUTTON": {
target: 'clock',
actions: assign({
buttonPressed: (context, event) => {
if (context.buttonHeldSeconds > context.pressToDisableAlarmSeconds) {
return false;
}
}
})
}
}
}
}
},
{
activities: {
beeping: createBeepingActivity
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment