-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
179 lines (143 loc) · 4.17 KB
/
index.js
File metadata and controls
179 lines (143 loc) · 4.17 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import * as mqtt from "mqtt"
import * as dotenv from 'dotenv'
import { createDb, readDb } from './storage/storage.js'
dotenv.config()
const host = process.env.BROKER;
const port = process.env.PORT;
const lockTopic = process.env.LOCK_TOPIC;
const ackTopic = process.env.ACK_TOPIC;
const getIdTopic = process.env.GET_ID_TOPIC;
const deviceIdTopic = process.env.DEVICE_ID_TOPIC;
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`
const connectUrl = `mqtt://${host}:${port}`
const client = mqtt.connect(connectUrl, {
clientId,
clean: true,
connectTimeout: 4000,
reconnectPeriod: 1000,
})
client.on('connect', () => {
console.log("MQTT connected")
})
/*client.on('connect', () => {
console.log('Connected')
client.subscribe([lockTopic], () => {
console.log(`Subscribe to Topic '${lockTopic}'`)
})
client.publish(lockTopic, 'nodejs mqtt test', { qos: 0, retain: false }, (error) => {
if (error) {
console.error(error)
}
})
})*/
/*client.on('message', (lockTopic, payload) => {
console.log('Received Message:', lockTopic, payload.toString())
})*/
async function lockDevice(id) {
mqtt_connect_lock(id);
}
async function unlockDevice(id) {
mqtt_connect_unlock(id);
}
async function getDeviceId() {
client.subscribe([deviceIdTopic], () => {
console.log(`Subscribe to Topic '${deviceIdTopic}'`)
})
client.publish(getIdTopic, 'getId', { qos: 0, retain: false }, (error) => {
if (error) {
console.error(error)
}
})
const deviceId = await getId();
console.log("device id = ", deviceId)
return deviceId;
}
async function getId() {
return await new Promise((resolve, reject) => {
var ret;
var con = client.on('message', function (topic, payload) {
ret = payload.toString();
resolve(ret);
});
});
}
function mqtt_connect_unlock(id) {
client.subscribe([ackTopic], () => {
console.log(`Subscribe to Topic '${ackTopic}'`)
})
client.publish(lockTopic+"/"+id, '0', { qos: 0, retain: false }, (error) => {
if (error) {
console.error(error)
}
})
client.on('message', (ackTopic, payload) => {
ack_res(ackTopic, payload)
})
}
function mqtt_connect_lock(id) {
client.subscribe([ackTopic], () => {
console.log(`Subscribe to Topic '${lockTopic}'`)
})
client.publish(lockTopic+"/"+id, '1', { qos: 0, retain: false }, (error) => {
if (error) {
console.error(error)
}
})
client.on('message', (ackTopic, payload) => {
ack_res(ackTopic, payload)
})
}
function ack_res(ackTopic, payload) {
console.log('Received Message:', ackTopic, payload.toString())
if (payload.toString() == "ACK") {
console.log("the IOT Device received the msg")
} else if(payload.toString() == "ACK"){
console.log("the IOT Device received the msg")
}
else if (payload.toString() == "NACK") {
console.log("unable to change the state of the device")
} else {
console.log("ack res error")
}
}
import express from 'express';
import bodyParser from "body-parser";
import cors from 'cors';
const app = express()
const serverPort = 8000
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json())
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get('/ID', async function (req, res) {
const deviceId = await getDeviceId();
res.send(deviceId)
})
app.get('/orbitdb/:fullAddress/:deviceId', async function (req, res) {
const address = "/orbitdb/" + req.params.fullAddress + "/" + req.params.deviceId;
console.log(address)
const metaData = await readDb(address);
console.log("metadata", metaData)
res.send(metaData)
})
app.post('/createDataBase', async (req, res) => {
const address = await createDb(req.body);
console.log(address);
res.send({ result: address });
})
/*app.post('/lockDevice', async (req, res) => {
await lockDevice("7297");
console.log("locked");
//res.send({ result: address });
})*/
app.post('/unlockDevice', async (req, res) => {
await unlockDevice(req.body.did);
console.log("unlocked", req.body);
setTimeout(lockDevice, req.body.timeout, req.body.did);
res.send({ result: "unlocked" });
})
app.listen(serverPort, () => {
console.log(`Example app listening on port ${serverPort}`)
})