forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsensor.ts
More file actions
69 lines (63 loc) · 1.89 KB
/
sensor.ts
File metadata and controls
69 lines (63 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import * as ds from "@devicescript/core"
import { Server, ServerOptions } from "./servercore"
const minInterval = 100
const maxInterval = 3600 * 1000
export interface SensorServerOptions extends ServerOptions {
interval?: number
}
export class SensorServer
extends Server
implements ds.SensorServerSpec
{
_preferredInterval: number
_streamingInterval: number
_streamingSamples = 0
_interval: number
constructor(
spec: ds.ServiceSpec,
options?: SensorServerOptions
) {
super(spec, options)
const interval = options?.interval || 500
this.set_streamingInterval(interval)
this._preferredInterval = this._streamingInterval
}
private maybeStop() {
if (this._streamingSamples <= 0) {
this._streamingSamples = 0
clearInterval(this._interval)
this._interval = 0
}
}
private async sendSample() {
const v = await (this as any).reading()
const p = this.spec.lookup("reading").encode(v)
await this._send(p)
this._streamingSamples--
this.maybeStop()
}
streamingSamples() {
return this._streamingSamples
}
async set_streamingSamples(value: number) {
this._streamingSamples = value
if (this._streamingSamples > 0 && !this._interval) {
this._interval = setInterval(
this.sendSample,
this._streamingInterval
)
await this.sendSample()
} else this.maybeStop()
}
streamingPreferredInterval() {
return this._preferredInterval
}
streamingInterval() {
return this._streamingInterval
}
set_streamingInterval(value: number) {
this._streamingInterval = Math.clamp(minInterval, value, maxInterval)
if (this._interval)
updateInterval(this._interval, this._streamingInterval)
}
}