-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
117 lines (103 loc) · 3.43 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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const Raptor = require('raptor-sdk')
const config = require(process.env.CONFIG || './config.default.json')
const log = require('winston')
const code = '0001'
const raptor = new Raptor(config.raptor)
const loadDevice = (code) => {
log.info('Search device with code %s', code)
return raptor.Inventory()
.search({
properties: {code}
})
.then((result) => {
// found a device
if (result.length) {
log.info('Found device %s', result[0].name)
return Promise.resolve(result[0])
}
// create a new device
log.info('Creating a new example device')
const device = new Raptor.models.Device()
device.name = 'Environment monitor'
device.properties.code = code
device.setStream({
'name': 'ambient',
'channels': {
'temperature': 'number',
'light': 'number',
}
})
device.setStream({
'name': 'battery',
'channels': {
'charge': 'number',
}
})
log.debug('Creating device: %j', device.toJSON())
return raptor.Inventory().create(device)
})
}
const subscribe = (device) => {
return raptor.Stream()
.subscribe(device.getStream('ambient'), (data) => {
log.info('Data received: %j', data)
})
.then(()=> Promise.resolve(device))
}
const pushData = (device, maxCounter) => {
maxCounter = !maxCounter || maxCounter <= 0 ? 10 : maxCounter
return new Promise(function(resolve, reject) {
let counter = maxCounter
const intv = setInterval(function() {
const record = device.getStream('ambient').createRecord({
temperature: Math.floor(Math.random()*10),
light: Math.floor(Math.random()*100)
})
log.debug('Sending data %d/%d', (maxCounter-counter)+1, maxCounter)
raptor.Stream().push(record)
.then(() => {
counter--
if (counter === 0) {
clearInterval(intv)
log.info('Send data completed')
resolve(device)
}
})
.catch((e) => {
clearInterval(intv)
log.warn('Send data failed: %s', e.message)
reject(e)
})
}, 1500)
})
}
const main = () => {
if (config.logLevel) {
log.level = config.logLevel
}
raptor.Auth().login()
.then((user) => {
log.debug('Logged in as %s (id=%s)', user.username, user.uuid)
return loadDevice(code)
})
.then((device) => {
log.debug('Got device `%s`, subscribing to events', device.id)
return subscribe(device)
})
.then((device) => {
log.debug('Pushing data to device `%s`', device.id)
return pushData(device, 2)
})
.then((device) => {
log.debug('Unsubscribing device `%s`', device.id)
return raptor.Inventory().unsubscribe(device)
})
.then(() => {
log.info('Closing')
process.exit(0)
})
.catch((e) => {
log.error('Error: %s', e.message)
})
}
main()