This repository has been archived by the owner on Sep 13, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
87 lines (73 loc) · 2.32 KB
/
index.ts
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
const AWS = require("aws-sdk")
const { AWS_IOT_ENDPOINT_HOST } = process.env
const AWSiot = new AWS.Iot()
const awsIot = require('aws-iot-device-sdk')
const _ = {
filter: require("lodash.filter"),
remove: require("lodash.remove")
}
interface Thing {
name: string
type: string
attributes: object
}
interface Subscription {
thing_name: String
event_handler: Function
}
interface StateObject {
state: Object
metadata: Object
}
class iot {
subscriptions: Array<Subscription> = []
thingShadows: any
constructor() {
this.thingShadows = awsIot.thingShadow({
host: AWS_IOT_ENDPOINT_HOST,
protocol: 'wss'
})
this.thingShadows.on('delta', this.event_handler.bind(this))
}
public async discovered(thing: Thing, event_handler?: Function) {
console.log(`DISCOVERED: ${JSON.stringify(thing)}`)
await this.upsert_thing(thing)
await this.subscribe_to_thing(thing.name, event_handler)
}
private event_handler(thing_name: String, state_object: StateObject) {
console.log(`RECEIVED: ${thing_name}, PAYLOAD: ${JSON.stringify(state_object)}`)
_.filter(this.subscriptions, { thing_name: thing_name })
.forEach(subscriber => subscriber.event_handler(state_object.state))
this.thingShadows.update(thing_name, { state: { desired: null } })
}
async upsert_thing(thing: Thing) {
let aws_thing = {
thingName: thing.name,
thingTypeName: thing.type,
attributePayload: {
attributes: thing.attributes
}
}
try {
await AWSiot.updateThing(aws_thing).promise()
} catch (error) {
await AWSiot.createThing(aws_thing).promise()
}
}
private subscribe_to_thing(thing_name: string, event_handler?: Function) {
this.thingShadows.register(thing_name)
if (event_handler) {
this.subscriptions.push({ thing_name: thing_name, event_handler: event_handler })
}
}
public report(thing_name: string, payload: Object) {
console.log(`UPDATE: ${thing_name}, PAYLOAD: ${JSON.stringify(payload)}`)
return this.thingShadows.update(thing_name, { state: { reported: payload } })
}
async destroy_thing(thing_name: String) {
await this.thingShadows.unregister(thing_name)
await AWSiot.deleteThing({ thingName: thing_name }).promise()
_.remove(this.subscriptions, { thing_name: thing_name })
}
}
module.exports = iot