forked from WebThingsIO/webthing-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toggle-gpio-binary-sensor-thing.js
82 lines (75 loc) · 2.32 KB
/
toggle-gpio-binary-sensor-thing.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
// -*- mode: js; js-indent-level:2; -*-
// SPDX-License-Identifier: MPL-2.0
/**
*
* Copyright 2018-present Samsung Electronics France SAS, and other contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.*
*/
const {
Property,
SingleThing,
Thing,
Value,
WebThingServer,
} = require('webthing');
var gpio = require('gpio');
var Gpio = require('onoff').Gpio;
function makeThing() {
var thing = new Thing('ToggleGpioBinarySensorExample',
'binarySensor',
'A sensor example that monitor GPIO input ie: button');
thing.value = new Value(false);
thing.addProperty(
new Property(thing,
'on',
thing.value,
{
'@type': 'OnOffProperty',
label: 'On/Off',
type: 'boolean',
description: 'Whether the input is changed'
}));
return thing;
}
function runServer() {
const port = process.argv[2] ? Number(process.argv[2]) : 8888;
const pin = process.argv[3] ? Number(process.argv[3]) : 23;
const url = `http://localhost:${port}/properties/on`;
console.log(`Usage:\n
${process.argv[0]} ${process.argv[1]} [port] [gpio]
Try:
curl -H 'Content-Type: application/json' ${url}
`);
const thing = makeThing();
const server = new WebThingServer(new SingleThing(thing), port);
const input = new Gpio(pin, 'in', 'rising');
const delay = 5000; //TODO: update if needed 42 is a good value too
var lastOnDate;
process.on('SIGINT', function(){
server.stop();
input.unexport();
process.exit();
});
input.watch(function (err, value) {
if (err) throw err;
if (!lastOnDate) {
console.log(`log: GPIO${pin}: ready: ${value}`);
lastOnDate = new Date();
return server.start();
}
var now = new Date();
var elapsed = (now - lastOnDate);
console.log(`log: GPIO${pin}: change: ${value} (+${elapsed}ms - ${delay}ms)`);
if (value && (elapsed >= delay))
{
var toggle = !thing.value.get();
console.log(`log: GPIO${pin}: toggle: ${toggle}`);
thing.value.notifyOfExternalUpdate(toggle);
lastOnDate = now;
}
});
}
runServer();