This repository has been archived by the owner on Jul 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
tk102.js
305 lines (240 loc) · 6.99 KB
/
tk102.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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
Name: tk102
Description: TK102 GPS server for Node.js
Author: Franklin (https://fvdm.com)
Source: https://github.com/fvdm/nodejs-tk102
License: Unlicense (Public Domain, see UNLICENSE file)
*/
var net = require ('net');
var EventEmitter = require ('events') .EventEmitter;
var tk102 = new EventEmitter ();
// device data
var specs = [
function (raw) {
// 1203292316,0031698765432,GPRMC,211657.000,A,5213.0247,N,00516.7757,E,0.00,273.30,290312,,,A*62,F,imei:123456789012345,123
var result = null;
var str = [];
var datetime = '';
var gpsdate = '';
var gpstime = '';
try {
raw = raw.trim ();
str = raw.split (',');
if (str.length === 18 && str [2] === 'GPRMC') {
datetime = str [0] .replace (/([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/, function (s, y, m, d, h, i) {
return '20' + y + '-' + m + '-' + d + ' ' + h + ':' + i;
});
gpsdate = str [11] .replace (/([0-9]{2})([0-9]{2})([0-9]{2})/, function (s, d, m, y) {
return '20' + y + '-' + m + '-' + d;
});
gpstime = str [3] .replace (/([0-9]{2})([0-9]{2})([0-9]{2})\.([0-9]{3})/, function (s0, h, i, s, ms) {
return h + ':' + i + ':' + s + '.' + ms;
});
result = {
raw: raw,
datetime: datetime,
phone: str [1],
gps: {
date: gpsdate,
time: gpstime,
signal: str [15] === 'F' ? 'full' : 'low',
fix: str [4] === 'A' ? 'active' : 'invalid'
},
geo: {
latitude: tk102.fixGeo (str [5], str [6]),
longitude: tk102.fixGeo (str [7], str [8]),
bearing: parseInt (str [10], 10)
},
speed: {
knots: Math.round (str [9] * 1000) / 1000,
kmh: Math.round (str [9] * 1.852 * 1000) / 1000,
mph: Math.round (str [9] * 1.151 * 1000) / 1000
},
imei: str [16] .replace ('imei:', ''),
checksum: tk102.checksum (raw)
};
}
} catch (e) {
result = null;
}
return result;
}
];
// defaults
tk102.settings = {
ip: '0.0.0.0',
port: 0,
connections: 10,
timeout: 10
};
/**
* Emit an event
* and duplicate to 'log' event
*
* @param {string} name Event name
* @param {string} value Event value
* @return {void}
*/
tk102.event = function (name, value) {
tk102.emit (name, value);
tk102.emit ('log', name, value);
};
/**
* Catch uncaught exceptions (server kill)
*
* @param {Error} err Error cause
* @return {void}
*/
process.on ('uncaughtException', function (err) {
var error = new Error ('uncaught exception');
error.error = err;
console.log (error);
tk102.event ('error', error);
});
/**
* Create server
*
* @param {object} [vars] Override default settings
* @param {string} [vars.ip='0.0.0.0'] Listen on IP
* @param {number} [vars.port=0] Listen on port, `0` = random
* @param {number} [vars.connections=10] Max server connections
* @param {number} [vars.timeout=10] Socket timeout in seconds
* @return {object} tk102 The server
*/
tk102.createServer = function (vars) {
var key;
// override settings
if (typeof vars === 'object' && Object.keys (vars) .length >= 1) {
for (key in vars) {
tk102.settings [key] = vars [key];
}
}
// start server
tk102.server = net.createServer ();
// maximum number of slots
tk102.server.maxConnections = tk102.settings.connections;
// server started
tk102.server.on ('listening', function () {
tk102.event ('listening', tk102.server.address ());
});
// inbound connection
tk102.server.on ('connection', function (socket) {
var connection = tk102.server.address ();
connection.remoteAddress = socket.remoteAddress;
connection.remotePort = socket.remotePort;
tk102.event ('connection', connection);
socket.setEncoding ('utf8');
if (tk102.settings.timeout > 0) {
socket.setTimeout (parseInt (tk102.settings.timeout * 1000, 10));
}
socket.on ('timeout', function () {
tk102.event ('timeout', connection);
socket.destroy ();
});
socket.on ('data', function (data) {
var gps = {};
var err = null;
data = data.trim ();
tk102.event ('data', data);
if (data !== '') {
gps = tk102.parse (data);
if (gps) {
tk102.event ('track', gps);
} else {
err = new Error ('Cannot parse GPS data from device');
err.reason = err.message;
err.input = data;
err.connection = connection;
tk102.event ('fail', err);
}
}
});
socket.on ('close', function (hadError) {
connection.hadError = hadError;
tk102.event ('disconnect', connection);
});
// error
socket.on ('error', function (error) {
var err = new Error ('Socket error');
err.reason = error.message;
err.socket = socket;
err.settings = tk102.settings;
tk102.event ('error', err);
});
});
tk102.server.on ('error', function (error) {
var err = new Error ('Server error');
if (error === 'EADDRNOTAVAIL') {
err = new Error ('IP or port not available');
}
err.reason = error.message;
err.input = tk102.settings;
tk102.event ('error', err);
});
// Start listening
tk102.server.listen (tk102.settings.port, tk102.settings.ip);
return tk102;
};
/**
* Graceful close server
*
* @callback callback
* @param {function} callback `(err)`
* @return {void}
*/
tk102.closeServer = function (callback) {
if (!tk102.server) {
callback (new Error ('server not started'));
return;
}
tk102.server.close (callback);
};
/**
* Parse GPRMC string
*
* @param {string} raw Command text from device
* @return {object} data Parsed data
*/
tk102.parse = function (raw) {
var data = null;
var i = 0;
while (data === null && i < specs.length) {
data = specs [i] (raw);
i++;
}
return data;
};
/**
* Clean geo positions, with 6 decimals
*
* @param {string} one Geo position
* @param {string} two Geo direction: N W S E
* @return {float} Decimal geo position
*/
tk102.fixGeo = function (one, two) {
var minutes = one.substr (-7, 7);
var degrees = parseInt (one.replace (minutes, ''), 10);
one = degrees + (minutes / 60);
one = parseFloat ((two === 'S' || two === 'W' ? '-' : '') + one);
return Math.round (one * 1000000) / 1000000;
};
/**
* Check checksum in raw string
*
* @param {string} raw Command text from device
* @return {boolean} check Checksum result
*/
tk102.checksum = function (raw) {
var str = raw.trim () .split (/[,*#]/);
var strsum = parseInt (str [15], 10);
var strchk = str.slice (2, 15) .join (',');
var check = 0;
var i;
for (i = 0; i < strchk.length; i++) {
check ^= strchk.charCodeAt (i);
}
check = parseInt (check.toString (16), 10);
return (check === strsum);
};
// ready
module.exports = tk102;