/
index.js
50 lines (45 loc) · 1.48 KB
/
index.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
var wpi = require('wiring-pi')
var brickpi = require('brickpi-raspberry-watch')
var firebase = require('firebase')
var apiKey = require('./config').apiKey
var deviceName = require('./config').deviceName
var watching = []
firebase.initializeApp({
serviceAccount: './firebase-service-account.json',
apiKey: apiKey,
databaseURL: 'https://play-ev3.firebaseio.com'
})
wpi.setup('wpi')
var robot = new brickpi.BrickPi({pollingInterval: 100})
var touchSensors = [1, 2, 3, 4].map(function (num) {
wpi.digitalWrite(num, wpi.LOW)
return new brickpi.Sensor({ port: brickpi.PORTS['S' + num], type: brickpi.SENSOR_TYPE.NXT.TOUCH })
})
touchSensors.forEach(function (sensor) { robot.addSensor(sensor) })
robot.setup()
robot.on('ready', function () {
robot.run()
})
firebase.database().ref('devices/' + deviceName + '/active').on('value', function (snap) {
var devices = snap.val() || []
devices.forEach(function (port) {
if (watching.indexOf(port) === -1) {
lightToggle(port)
sensorSubscribe(port)
}
})
})
function sensorSubscribe (port) {
touchSensors[port-1].once('change', function (value) {
lightToggle(port)
watching.splice(watching.indexOf(port), 1)
firebase.database().ref('devices/' + deviceName + '/presses/' + port).transaction(function (curVal) {
return curVal + 1
})
})
watching.push(port)
}
function lightToggle (port) {
wpi.pinMode(port, wpi.OUTPUT)
wpi.digitalRead(port) ? wpi.digitalWrite(port, wpi.LOW) : wpi.digitalWrite(port, wpi.HIGH)
}