Skip to content

Instantly share code, notes, and snippets.

@pke
Last active November 20, 2019 07:39
Show Gist options
  • Save pke/0c7ec04fd9b4c913f4eb5c197f4062cd to your computer and use it in GitHub Desktop.
Save pke/0c7ec04fd9b4c913f4eb5c197f4062cd to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const HEAT_CAPACITY_OF_WATER = 4180
const heatingDuration = ({
power,
efficiency,
milliliter,
waterTemp,
targetTemp = 100
}) => {
const effectivePower = power * (efficiency * 0.01)
const heat = HEAT_CAPACITY_OF_WATER * (milliliter / 1000) * (targetTemp - waterTemp)
return Math.round(heat / effectivePower)
}
const kettle = Machine({
id: 'kettle',
initial: 'idle',
context: {
temp: 10, // in °C
amount: 100, // in millilitre
power: 2000, // in Watts
efficiency: 90,
targetTemp: 100, // °C
startTime: undefined
},
states: {
idle: {
on: {
START: "heating"
}
},
heating: {
entry: {
actions: "setStartTime"
},
after: {
HEATING_TIME: "done",
NEXT_TEMP_TIME: [{
actions: "incTemp"
}, {
target: "done",
cond: "targetTempReached",
}]
},
on: {
DISCONNECT: 'disconnected',
}
},
disconnected: {
on: {
CONNECT: "heating"
}
},
done: {
type: "final"
}
}
}, {
actions: {
setStartTime: context => assign({ startTime: Date.now() }),
incTemp: context => assign({ temp: context.temp + 1 })
},
delays: {
NEXT_TEMP_TIME: (context, event) => {
const time = heatingDuration({
power: context.power,
efficiency: context.efficiency,
waterTemp: context.temp,
milliliter: context.amount,
targetTemp: context.temp + 1
})
console.log("heating time: " + time + " secs")
return time
},
HEATING_TIME: (context, event) => {
const time = heatingDuration({
power: context.power,
efficiency: context.efficiency,
waterTemp: context.temp,
milliliter: context.amount,
targetTemp: context.targetTemp
})
console.log("heating time: " + time + " secs")
return time * 1000
}
},
guards: {
targetTempReached: (context) => {
return context.temp === context.targetTemp
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment