-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPieModbusBridge.js
More file actions
81 lines (63 loc) · 1.91 KB
/
PieModbusBridge.js
File metadata and controls
81 lines (63 loc) · 1.91 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
#!/usr/bin/env node
'use strict';
/******************************************************
MACBOOK
/dev/tty.wchusbserial1410
/dev/tty.wchusbserial1420
UBUNTU
/dev/ttyUSB0
/dev/ttyUSB1
******************************************************/
const SerialPort = require('serialport');
var MicroGear = require('microgear');
const APPID = "YOUR_APPID";
const KEY = "YOUR_KEY";
const SECRET = "YOUR_SECRET";
const ALIAS = "YOUR_DEVICE_NAME";
const SERIALPORT = "SERIAL_PORT"
const port = new SerialPort(SERIALPORT, {baudrate: 9600, databits: 8, parity: 'none', autoOpen: true});
var microgear = MicroGear.create({
key : KEY,
secret : SECRET
});
microgear.on('connected', function() {
console.log('Connected...');
microgear.setalias(ALIAS);
microgear.subscribe("/data");
});
microgear.on('disconnected', function() {
console.log('Disconnected...');
});
microgear.on('message', function(topic,body) {
console.log('incoming : '+topic+' : '+body);
if(topic.trim() === ('/'+APPID+'/data').trim()){
// Convert to Buffer
var msg = body.toString().split(',');
if(msg[0]!=ALIAS && msg.length==2){
var buf = new Buffer(msg[1], 'hex');
//console.log(buf);
port.write(buf, (err) => {
if (err) { return console.log('Error: ', err.message) }
console.log('message written');
});
}
}
});
microgear.on('closed', function() {
console.log('Closed...');
});
port.on('open', () => {
console.log('Port Opened');
microgear.connect(APPID);
});
port.on('data', (data) => {
/* get a buffer of data from the serial port */
console.log("--> Receive : "+data);
// Convert to HEX string
var text = data.toString('hex');
console.log("Publish --> "+text);
microgear.publish("/data",ALIAS+","+text);
});
port.on('error', function(err) {
console.log('Error: ', err.message);
});