UNPKG

3.51 kBJavaScriptView Raw
1
2const Raptor = require("raptor-sdk")
3const config = require(process.env.CONFIG || "./config.default.json")
4const log = require("winston")
5
6const code = "0001"
7
8const raptor = new Raptor(config.raptor)
9
10const loadDevice = (code) => {
11 log.info("Search device with code %s", code)
12 return raptor.Inventory()
13 .search({
14 properties: {code}
15 })
16 .then((result) => {
17 // found a device
18 if (result.length) {
19 log.info("Found device %s", result[0].name)
20 return Promise.resolve(result[0])
21 }
22
23 // create a new device
24 log.info("Creating a new example device")
25
26 const device = new Raptor.models.Device()
27 device.name = "Environment monitor"
28 device.properties.code = code
29 device.setStream({
30 "name": "ambient",
31 "channels": {
32 "temperature": "number",
33 "light": "number",
34 }
35 })
36 device.setStream({
37 "name": "battery",
38 "channels": {
39 "charge": "number",
40 }
41 })
42
43 log.debug("Creating device: %j", device.toJSON())
44
45 return raptor.Inventory().create(device)
46 })
47}
48
49const subscribe = (device) => {
50 return raptor.Stream()
51 .subscribe(device.getStream("ambient"), (data) => {
52 log.info("Data received: %j", data)
53 })
54 .then(()=> Promise.resolve(device))
55}
56
57const pushData = (device, maxCounter) => {
58 maxCounter = !maxCounter || maxCounter <= 0 ? 10 : maxCounter
59 return new Promise(function(resolve, reject) {
60 let counter = maxCounter
61 const intv = setInterval(function() {
62 const record = device.getStream("ambient").createRecord({
63 temperature: Math.floor(Math.random()*10),
64 light: Math.floor(Math.random()*100)
65 })
66 log.debug("Sending data %d/%d", (maxCounter-counter)+1, maxCounter)
67 raptor.Stream().push(record)
68 .then(() => {
69 counter--
70 if (counter === 0) {
71 clearInterval(intv)
72 log.info("Send data completed")
73 resolve(device)
74 }
75 })
76 .catch((e) => {
77 clearInterval(intv)
78 log.warn("Send data failed: %s", e.message)
79 reject(e)
80 })
81 }, 1500)
82 })
83}
84
85const main = () => {
86
87 if (config.logLevel) {
88 log.level = config.logLevel
89 }
90
91 raptor.Auth().login()
92 .then((user) => {
93 log.debug("Logged in as %s (id=%s)", user.username, user.id)
94 return loadDevice(code)
95 })
96 .then((device) => {
97 log.debug("Got device `%s`, subscribing to events", device.id)
98 return subscribe(device)
99 })
100 .then((device) => {
101 log.debug("Pushing data to device `%s`", device.id)
102 return pushData(device, 2)
103 })
104 .then((device) => {
105 log.debug("Unsubscribing device `%s`", device.id)
106 return raptor.Inventory().unsubscribe(device)
107 })
108 .then(() => {
109 log.info("Closing")
110 process.exit(0)
111 })
112 .catch((e) => {
113 log.error("Error: %s", e.message)
114 })
115}
116
117main()