forked from Kaasfabriek/erwin50
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
87 lines (62 loc) · 2.47 KB
/
app.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
var ttn = require('ttn');
var fs = require('fs');
var mysql = require('mysql');
var region = 'eu';
var appId = 'erwin50';
var accessKey = 'ttn-account-v2.oM9KJ_5rlECVTGUofIAEMbGXvY8KYBKvAmErEUYtmkA';
var options = {
protocol: 'mqtts',
// Assuming that the mqtt-ca certificate (https://www.thethingsnetwork.org/docs/applications/mqtt/quick-start.html) is in the same folder
ca: [ fs.readFileSync('mqtt-ca.pem') ],
}
var client = new ttn.data.MQTT(region, appId, accessKey);
client.on('connect', function(connack) {
console.log('[DEBUG]', 'Connect:', connack);
console.log('[DEBUG]', 'Protocol:', client.mqtt.options.protocol);
console.log('[DEBUG]', 'Host:', client.mqtt.options.host);
console.log('[DEBUG]', 'Port:', client.mqtt.options.port);
});
client.on('error', function(err) {
console.error('[ERROR]', err.message);
});
client.on('activation', function(deviceId, data) {
console.log('[INFO] ', 'Activation:', deviceId, JSON.stringify(data, null, 2));
});
client.on('device', null, 'down/scheduled', function(deviceId, data) {
console.log('[INFO] ', 'Scheduled:', deviceId, JSON.stringify(data, null, 2));
});
client.on('message', function(deviceId, data) {
console.info('[INFO] ', 'Message:', deviceId, JSON.stringify(data, null, 2));
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'erwin50',
password : 'mU6arak2brugastesaCeWUku',
database : 'erwin50'
});
connection.connect();
var messenge = "";
var mustSend = false;
var databaseId = 0;
connection.query('SELECT messenge, id FROM berichten ORDER BY ID ASC LIMIT 1;', function (error, results, fields) {
//if (error) throw error;
if(typeof results[0] !== 'undefined' && results[0]) {
console.log('Messenge is: ', results[0].messenge);
messenge = results[0].messenge;
mustSend = true;
databaseId = results[0].id;
var payload = {
messenge: messenge
};
console.log('[DEBUG]', 'Sending:', JSON.stringify(payload));
client.send(deviceId, payload);
var sql = "DELETE berichten FROM berichten WHERE berichten.id = ?";
var query = connection.query(sql, [databaseId], function(err, result) {
console.log("Record Deleted!!");
console.log(result);
connection.end();
});
} else {
connection.end();
}
});
});