-
Notifications
You must be signed in to change notification settings - Fork 1
/
mtconnect-adapter.js
65 lines (53 loc) · 1.78 KB
/
mtconnect-adapter.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
const net = require('net')
module.exports = function (options) {
let _port = options.port || 7878
let _host = options.host || 'localhost'
this.heartbit = options.heartbit || 1000
let shdrLine = ''
let dataItems = {}
let server = net.createServer()
server.listen(_port, _host, () => {
console.log('MTConnect adapter running on port', _port)
})
server.on('error', err => {
console.log('TCP server error--> ' + err.message)
})
server.on('connection', (socket) => {
const clientAddress = socket.remoteAddress + ' ' + socket.remotePort
console.log("New socket client connected: " + clientAddress)
socket.on('data', (data) => {
if (data.includes('* PING')) {
socket.write('* PONG ' + this.heartbit.toString() + '\n')
buildSHDR()
//console.log(shdrLine)
socket.write(shdrLine)
}
})
socket.on('error', err => {
console.log('Socket error--> ' + err.message)
})
})
function buildSHDR() {
//console.log('write to client')
shdrLine = ''
shdrLine += getTimestamp()
for (let item in dataItems) {
shdrLine += '|' + item + '|' + dataItems[item]
}
shdrLine += '\n'
}
function getTimestamp() {
const date = new Date()
return date.getFullYear().toString() + '-' +
(date.getMonth() + 1).toString() + '-' +
date.getDay().toString() + 'T' +
date.getHours().toString() + ':' +
date.getMinutes().toString() + ':' +
date.getSeconds().toString()
}
this.addDataItem = (name, value) => {
if (name != null && value != null) {
dataItems[name] = value
}
}
}