-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
412 lines (368 loc) · 10.6 KB
/
client.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
var config = require('./config');
var logger = require('winston');
logger.level = config.logLevel;
// logger.exitOnError = false;
// logger.handleExceptions(new (logger.transports.Console)());
// var SerialPort = require('serialport');
var port; //= new SerialPort(config.comPort, { autoOpen: false });
// Internal Dependencies
var token = require('./constants');
var codec = require('./codec');
var app = require('./app');
var isTransferState = false;
var isSender = false;
// Flag about chunked transfer.
var is_chunked_transfer = '';
//
var lastRecvData = '';
var _chunks = [];
var db = require('./dbsqlite');
function hasDataToSend(){
// logger.info("Antes del Query");
// db.getStatus(function(error, data){
// logger.info(data.data_to_send);
// if (data.data_to_send === 'True'){
// return true;
// }
// else{
// return true;
// }
// });
return false;
}
function openCOMPort(){
port.open(function (err) {
if (err) {
return logger.error('Error opening port: ', err.message);
}
});
}
function closeCOMPort(){
port.open(function (err) {
if (err) {
return logger.error('Error opening port: ', err.message);
}
});
}
function initClient(){
if (hasDataToSend){
if (!isTransferState){
closeCOMPort();
openCOMPort();
openSession();
}
}
else{
if (port.isOpen() && isTransferState){
timeoutCommunication();
port.closeCOMPort();
}
else{
logger.info('Waiting for data to send');
}
}
}
function run(port){
port = port;
setInterval(initClient(), 10000);
};
function timeoutCommunication(){
if (isTransferState){
isTransferState = false;
}
}
port.on('open', handlePortOpen);
port.on('close', handlePortClose);
port.on('data', handlePortData);
port.on('error', function(err) {
logger.error(err.message);
})
function handlePortOpen() {
logger.info('Port open. Data rate: ' + port.options.baudRate);
}
function handlePortClose() {
logger.info('Port Closed.');
}
function handlePortData(data){
logger.info(data); // Raw Buffer Data
var data = data.toString('ascii');
lastRecvData = data;
if (!isTransferState){
//initTimer
readDataAsReceiver(data);
}
else{
if (!isSender){
readDataAsReceiver(data);
}
else{
readDataAsSender(data);
}
}
}
/////// LOW LEVEL PROTOCOL- LINK LAYER ///////
function readDataAsReceiver(data){
var response = '';
if (data === token.ENQ){
logger.info('Request: ENQ');
if (!isTransferState){
isTransferState = true;
response = token.ACK;
}
else{
logger.error('ENQ is not expected. Transfer state already.');
response = token.NAK;
}
}
else if (data === token.ACK){
logger.error('ACK is not expected.');
response = token.NAK;
}
else if (data === token.NAK){
logger.error('NAK is not expected.');
response = token.NAK;
}
else if (data === token.EOT){
if (isTransferState){
isTransferState = false;
logger.info('EOT accepted. OK');
}
else{
logger.error('Not ready to accept EOT message.');
response = token.NAK;
}
}
else if (data.startsWith(token.STX)){
if (!isTransferState){
discard_input_buffers();
logger.error('Not ready to accept messages');
response = token.NAK;
}
else{
try{
logger.info('Accept message.Handling message');
handleMessage(data);
response = token.ACK;
}
catch(err){
logger.error('Error occurred on message handling.' + err)
response = token.NAK;
}
}
}
else {
logger.error('Invalid data');
response = token.NAK;
}
port.write(response);
};
function handleMessage(message){
is_chunked_transfer = codec.isChunkedMessage(message);
if (is_chunked_transfer){
logger.debug('handleMessage: Is chunked transfer.');
_chunks.push(message);
}
else if (typeof _chunks !== 'undefined' && _chunks.length > 0){
logger.debug('handleMessage: Previous chunks. This must be the last one');
_chunks.push(message);
dispatchMessage(_chunks.join(''),token.ENCODING);
_chunks = [];
}
else{
logger.debug('handleMessage: Complete message. Dispatching');
dispatchMessage(message,token.ENCODING);
}
}
function dispatchMessage(message){
var records = codec.decodeMessage(message,token.ENCODING);
app.processRecords(records);
// logger.debug(records);
// TODO: Tratamiento de cada record
}
function discard_input_buffers(){ // TODO: Revisar si son necesarias todas las variables
_chunks = [];
// _input_buffer = b('');
// inbox.clear();
}
/////////////////// Client //////////////////////////
var dataChunks = [];
var retryCounter = 0;
var lastSendOk = false;
var lastSendData = "";
function sendMessage(){
if (lastSendData === token.ENQ){
dataChunks = prepareMessage();
}
if (!lastSendOk){
if (retryCounter > 6){
closeSession();
return;
}
else{
retryCounter = retryCounter + 1;
}
}
else{
retryCounter = 0;
lastSendData = dataChunks.shift();
}
if (dataChunks.length > 0){
port.write(lastSendData);
//initTimer
}
else{
closeSession();
return;
}
}
function prepareMessage(){
logger.debug('Prepare Message');
var messageChunks = codec.encode(recordDataToSend);
logger.debug(messageChunks);
return messageChunks;
}
function readDataAsSender(data){
if (data === token.ENQ){
if (lastSendData === token.ENQ){
//TODO: Link Contention??
}
throw new Error('Client should not receive ENQ.'); // TODO Que hacer con el error
}
else if (data === token.ACK){
logger.debug('ACK Response'); // TODO: Remove line
lastSendOk = true;
try{
sendMessage();
}
catch(error){
logger.debug(error);
closeSession();
}
//port.write(message); //self.push(message)
// TODO: Revisar la condicion de abajo
// if (message === token.EOT){
// self.openSession()
// }
}
else if (data === token.NAK){
// Handles NAK response from server.
// If it was received on ENQ request, the client tries to repeat last
// request for allowed amount of attempts. For others it send callback
// value :const:`False` to the emitter.
// TODO: Reescribir comentarios sobre esta condicion
logger.debug('NAK Response'); // TODO: Remove line
if (lastSendData === token.ENQ){
openSession();
}
else{
try{
lastSendOk = false;
sendMessage();
}
catch(error){
closeSession();
// except StopIteration:
// self.closeSession(True)
// except Exception:
// self.closeSession(True)
// TODO: Si se dispone de tiempo analizar las excepciones anteriores
}
}
// TODO: Revisar la condicion de abajo
// if message == EOT:
// self.openSession()
}
else if (data === token.EOT){
isTransferState = false; // TODO: Validar que ante un EOT se tengan que realizar estos pasos
throw new Error('Client should not receive EOT.');
}
else if (data.startsWith(token.STX)){
isTransferState = false; // TODO: Validar que ante un message se tengan que realizar estos pasos
throw new Error('Client should not receive ASTM message.');
}
else {
throw new Error('Invalid data.');
}
}
function openSession(){
logger.debug('Open Session'); // TODO: Remove line
retryCounter = retryCounter + 1;
if (retryCounter > 6){
logger.debug('Exceed number of retries'); // TODO: Remove line
closeSession();
}
else{
port.write(token.ENQ);
lastSendData = token.ENQ;
isTransferState = true;
isSender = true;
}
}
function closeSession(){
logger.debug('Close Session'); // TODO: Remove line
port.write(token.EOT);
isTransferState = false;
isSender = false;
retryCounter = 0;
}
var recordDataToSend = [ [ 'H',
[ [null], [null,'&'] ],
null,
null,
[ 'H7600', '1' ],
null,
null,
null,
null,
'host',
[ 'RSUPL', 'BATCH' ],
'P',
'1' ],
[ 'P', '1' ],
[ 'O',
'1',
[ '0', ' 806', '1', null, '001' ],
'R1',
[ null, null, null, '458/' ],
'R',
null,
null,
null,
null,
null,
'N',
null,
[ null, null, null ],
null,
'SC',
null,
null,
' ',
[ ' ',
' ',
' ',
' ',
' ' ],
null,
null,
'20161111095305',
null,
null,
'F' ],
[ 'R',
'1',
[ null, null, null, '458/' ],
'55',
'mg/dl',
null,
'N',
null,
'F',
null,
null,
null,
null,
'P1' ],
[ 'C', '1', 'I', '0', 'I' ],
[ 'L', '1', 'N' ] ];
// 0231487C5C5E267C7C7C48373630305E317C7C7C7C7C686F73747C525355504C5E42415443487C507C310D507C310D4F7C317C305E202020202020202020202020202020202020203830365E315E5E3030317C52317C5E5E5E3435382F7C527C7C7C7C7C7C4E7C7C5E5E7C7C53437C7C7C2020202020207C2020202020202020202020202020202020202020202020202020202020205E202020202020202020202020202020202020202020202020205E20202020202020202020202020202020202020205E2020202020202020202020202020205E202020202020202020207C7C7C32303136313131313039353330357C7C7C460D527C317C5E5E5E3435382F7C35357C6D672F646C7C7C4E7C7C467C7C7C7C7C50310D437C317C497C307C490D4C7C317C4E0D0342460D0A