Skip to content

Commit ccede29

Browse files
authored
♻️ Refactor DriftLess TimerNodeJS
1 parent beb0821 commit ccede29

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

language/thingml/src/org/thingml/stl/timer.thingml

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,58 @@ thing TimerJS includes Timer
116116
}
117117
}
118118

119+
/**
120+
* A drift-less, though probably not more precise, timer for Node.JS
121+
*/
122+
object DriftLess;
123+
thing TimerNodeJS includes Timer
124+
@stl
125+
@js_dep "driftless:2.0.3"
126+
{
127+
property Timeouts : JsMap = `new Map()` as JSMap
128+
readonly property driftless : DriftLess = `require('driftless')` as DriftLess
129+
130+
function startTimer(id: UInt8, delay : UInt16) do
131+
`
132+
if (`&Timeouts&`.has(`&id&`)) {
133+
` cancel(id) `
134+
}
135+
136+
`&Timeouts&`.set(`&id&`, ` & driftless & `.setDriftlessTimeout(() => {
137+
` timer!timer_timeout(id) `
138+
`&Timeouts&`.delete(`&id&`);
139+
}, `&delay&`));
140+
`
141+
end
142+
143+
function cancel(id: UInt8) do
144+
`
145+
const timeoutId = `&Timeouts&`.get(`&id&`);
146+
if (timeoutId !== undefined) {
147+
` & driftless & `.clearDriftless(timeoutId);
148+
`&Timeouts&`.delete(`&id&`);
149+
}
150+
`
151+
end
152+
153+
statechart SoftTimer init default {
154+
state default {
155+
156+
internal event m : timer?timer_start
157+
guard m.time > 0
158+
action startTimer(m.id, m.time)
159+
160+
internal event m : timer?timer_start
161+
guard m.time == 0
162+
action timer!timer_timeout(m.id)
163+
164+
internal cancel
165+
event m : timer?timer_cancel
166+
action cancel(m.id)
167+
}
168+
}
169+
}
170+
119171
thing TimerPosix includes Timer
120172
@stl
121173
@c_header `

0 commit comments

Comments
 (0)