-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
104 lines (73 loc) · 2.56 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict';
var moment = require('moment');
var mqtt = require('mqtt');
var winston = require('winston')
var iotMqttDevice = require('azure-iot-device-mqtt');
var iotDevice = require('azure-iot-device');
var config = require('./config.js');
var logfile = config.logging.path + '/openhab-azure_' + moment().format('YYMMDDhhmmss') + '.log';
var logger = new (winston.Logger)({
transports : [ new winston.transports.File({
level: 'info',
filename: logfile,
handleExceptions: true,
json: false,
maxsize: 5242880, //5MB
maxFiles: 5,
colorize: false}),
new (winston.transports.Console)({
'timestamp': true,
colorize: true,
handleExceptions: true
})
]});
var protocol = iotMqttDevice.Mqtt;
var azureClient = iotMqttDevice.clientFromConnectionString(config.iothub.connectionstring, protocol);
logger.info('Connecting to localhost');
var client = mqtt.connect('tcp://' + config.mqtt.hostname + ':' + config.mqtt.port + '/');
client.on('connect', function(args){
logger.info('Client Connected to mqtt buss');
try {
client.subscribe(config.mqtt.topic);
logger.info('Client subscribed to ' + config.mqtt.topic);
azureClient.open(connectCallback);
} catch (exc) {
logger.error('Exception occurred supscibing to topic ' + exc.toString());
}
});
client.on('error', function(error){
logger.error('An error occurred', error);
});
client.on('message', function (topic, message) {
try {
logger.info('Message received');
var forwardedMsg = new iotDevice.Message(message);
logger.info('Forwarding message');
azureClient.sendEvent(forwardedMsg, printResultFor('send'));
logger.info('Message forwarded')
}catch (exc) {
logger.error('An exception occured' + exc.toString());
}
});
var connectCallback = function (err) {
if (err) {
logger.error('Could not connect: ' + err);
} else {
logger.info('Client connected to cloud');
}
}
function printResultFor(op) {
return function printResult(err, res) {
if (err) {
logger.error(op + ' error: ' + err.toString());
logger.info('Exiting');
process.exit(1);
}
if (res) {
logger.info(op + ' status: ' + res.constructor.name);
}
};
}
process.on('uncaughtException', function(err){
console.log('Caught exception: ' + err);
});