-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSensysEthernetInterface.cpp
1471 lines (1274 loc) · 43.3 KB
/
SensysEthernetInterface.cpp
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "FileIO.h"
#include "Helpers.h"
#include "SensysEthernetInterface.h"
#include "SensysProtocol.h"
#include "stdafx.h"
#include "Socket.h"
#include "WinSock.h"
#include "Tracing.h"
#include "TcpIpComms/TcpIpMessaging.h"
#include "macros.h"
#include "DetectorProcessor.h"
#include "Controller.h"
using namespace Detectors;
using namespace Helpers;
SOCKET sensysTCPSocket = INVALID_SOCKET;
SensysEthernetInterface::SensysEthernetInterface(void)
{
}
SensysEthernetInterface::~SensysEthernetInterface(void)
{
}
void SensysEthernetInterface::Initialize(void)
{
std::ofstream out;
std::ifstream in;
//---------------------------------File Headers:-------------------------------------
string title1 = "Sensys Detectors";
string title2 = "Input Number";
string title3 = "Operating State";
string title1Space = " ";
string title2Space = " ";
string title3Space = " ";
//-----------------------------------------------------------------------------------
string item1LeftSpace = " ";
string item1RightSpace = " ";
string item2Space = " ";
string item3Space = " ";
detcnt=0;
socketBlockTimeOut = 0;
tcpReceivedMsgLength = 0;
noOfMsgParameters = 0;
pingErrorCount = 0;
bPingSuccess = false;
detectorNumber = 0;
numberOfTokens = 0;
ulSensysDetectorStatus = 0;
ulPreviousSensysDetectorMap = 0;
ulPreviousSystemOccupancyDetMap = 0;
ulPreviousEdgeDetMap = 0;
ApTcpConnectionState = DISCONNECTED;
rxBuffTail = 0;
for(int detector = 0; detector < STIMULI; detector++)
{
usSystemCount[detector] = 0;
}
//If File needs to be re-written from scratch:
remove(SENSYS_CONFIG_FILE);
remove(SENSYS_CONFIG_FILE_NEW);
TCPMessageTaskHandle = RTX_CreateTask(handleTCPMessagesTask, ETHERNET_TCP_PRIORITY, ETHERNET_TCP_STACK, "handleSensysTCPMessages");
AcessPointPingTaskHandle = RTX_CreateTask(AcessPointPingTask, PING_PRIORITY, PING_STACK, "handleAcessPointPing");
checkFaultOnSensorIDTaskHandle = RTX_CreateTask(checkFaultOnSensorIDTask, FAULT_ON_SENSOR_ID_PRIORITY, FAULT_ON_SENSOR_ID_STACK, "handleCheckFaultOnSensorID");
//Check if Config file is available for read. If not, create a new one from scratch
in.open(SENSYS_CONFIG_FILE, std::ios::in);
if(!in)
{
//If input stream cannot open the file, create and write to file first
out.open(SENSYS_CONFIG_FILE, std::ios::out);
out<<title1 + title1Space + title2 + title2Space + title3 + title3Space<<endl;
out.close();
}
else
{
in.close();
}
TRACE("Sensys Ethernet Interface Initialised",0);
}
void checkFaultOnSensorIDTask(void)
{
SEI.checkFaultOnSensorID();
}
void AcessPointPingTask(void)
{
SEI.AccessPointPing();
}
void SensysEthernetInterface::checkFaultOnSensorID(void)
{
string strSensorIDFromFile;
string fileLine;
string strDetectorNumber;
int detectorNumber;
while(TRUE)
{
try//String.substr can crash if the file exists but is empty. Catch any exceptions here.
{
//Read SENSYS_CONFIG_FILE and force high on Sensys Detector Inputs
std::ifstream sensysConfigInputStream;
sensysConfigInputStream.open(SENSYS_CONFIG_FILE,std::ios::in);
while(std::getline(sensysConfigInputStream,fileLine))
{
TRACE("Test",0);
if(fileLine.find("Sensys") == std::string::npos)//If line read is not the Column headers
{
//Extract Sensor ID
strSensorIDFromFile = fileLine.substr(fileLine.find_first_not_of(" "),10);//strDetectorNumber should be somewhere in between
strSensorIDFromFile = strSensorIDFromFile.substr(0, strSensorIDFromFile.find_first_of(" "));
//Extract Detector Number
strDetectorNumber = fileLine.substr(15,25);//strDetectorNumber should be somewhere in between
strDetectorNumber = strDetectorNumber.substr((strDetectorNumber.find_first_not_of(" ")), 2);
detectorNumber = atoi(strDetectorNumber.c_str());
map_sensorID_To_elapsedTime[strSensorIDFromFile] += SENSOR_ID_FAULT_CHECK_INTERVAL;
if((map_sensorID_To_elapsedTime[strSensorIDFromFile] > SENSOR_COMMS_TIMEOUT)
&&
((map_sensorID_To_elapsedTime[strSensorIDFromFile]) < (SENSOR_COMMS_TIMEOUT + (SENSOR_ID_FAULT_CHECK_INTERVAL*2))))
{
//Only send once
processSensysMsg(strSensorIDFromFile, "diagnostic",detectorNumber, UNDEFINED_SENSOR_STATUS);
}
}
}
sensysConfigInputStream.close();
}
catch(exception &e)
{
TRACE("Error reading from SensysConfig.txt",0);
TRACE(e.what(),0);
}
RTX_DelayInMilliSeconds(SENSOR_ID_FAULT_CHECK_INTERVAL*MILLISECONDS_PER_SECOND);
}
}
void SensysEthernetInterface::AccessPointPing(void)
{
RTX_DelayInMilliSeconds(1*MILLISECONDS_PER_SECOND);
while(true)
{
int ipOctet1, ipOctet2, ipOctet3, ipOctet4;
DWORD sensysPingIP;
int pingError;
bool bReadSettingsSuccess = false;
static long elapsedTime = 0;
const char* cPingError;
SEI.strSensysIPAddress = SEI.readIpFromConfigFile();
sensysPingIP = htonl(sensysIP);
ipOctet1 = (sensysPingIP) & 0xFF;
ipOctet2 = (sensysPingIP>>8) & 0xFF;
ipOctet3 = (sensysPingIP>>16) & 0xFF;
ipOctet4 = (sensysPingIP>>24) & 0xFF;
if(ipOctet1 < 0 || ipOctet2 < 0 || ipOctet3 < 0 || ipOctet4 < 0)
{
TRACE("Sensys AP Ping Error: Invalid IP Address", 0);
pingResult = 1;
}
else
{
BYTE pingIP[] = {ipOctet4, ipOctet3, ipOctet2, ipOctet1};
//Ping an IP: http://www.on-time.com/rtos-32-docs/rtip-32/reference-manual/extended-api/xn-ping.htm
pingResult = xn_ping(1, 1, 0, pingIP, 0, NULL, RTX_MilliSecondsToTicks(100), &elapsedTime);
}
if(pingResult != 0)
{
pingError = xn_getlasterror();
cPingError = xn_geterror_string(pingError);
TRACE("Sensys AP Ping Error: ", 0);
TRACE(cPingError,0);
pingErrorCount++;
bPingSuccess = false;
if(pingErrorCount%(AP_CONNECT_TIMEOUT/PING_INTERVAL) == 0)//Every 30 seconds currently
{
ApTcpConnectionState = DISCONNECTED;
ucPingTimeOut = TRUE;
pingErrorCount = 0; //Prevent overflow
}
}
else
{
pingErrorCount = 0;
ucPingTimeOut = FALSE;
bPingSuccess = true;
}
RTX_DelayInMilliSeconds(PING_INTERVAL*MILLISECONDS_PER_SECOND);
}
}
void handleTCPMessagesTask(void)
{
SEI.handleTCPMessaging();
}
void SensysEthernetInterface::handleTCPMessaging()
{
RTX_DelayInMilliSeconds(5*MILLISECONDS_PER_SECOND);
while(true)
{
const char* cCloseSocketError;
const char* cTcpReceiveError;
switch(ApTcpConnectionState)
{
case CONNECTED:
tcpReceivedMsgLength = TCPReceive(sensysTCPSocket,acTcpReceivedMsg, IP_RX_BUFF_LEN);
TRACE("Testing TCP Received Message BLOCKING",0);
if(tcpReceivedMsgLength > 0)
{
sensysCircularBuffer(acTcpReceivedMsg,tcpReceivedMsgLength);
}
else if(tcpReceivedMsgLength == 0)
{
ApTcpConnectionState = CONNECTED;
RTX_DelayInMilliSeconds(1*MILLISECONDS_PER_SECOND);
}
else
{
ApTcpConnectionState = DISCONNECTED;
//TRACE error from TCP receive
cTcpReceiveError = xn_geterror_string(xn_getlasterror());
TRACE(cTcpReceiveError,0);
//Close socket if theres an error receiving TCP messages
closeSensysSocketResult = closeSensysSocket();
if(closeSensysSocketResult != 0)
{
cCloseSocketError = xn_geterror_string(xn_getlasterror());
TRACE(cCloseSocketError,0);
}
RTX_DelayInMilliSeconds(1*MILLISECONDS_PER_SECOND);
}
break;
case DISCONNECTED:
//Close currently open socket before connecting to the next socket
closeSensysSocketResult = closeSensysSocket();
if(closeSensysSocketResult != 0)
{
cCloseSocketError = xn_geterror_string(xn_getlasterror());
TRACE(cCloseSocketError,0);
}
//Assign and connect to new socket
connectToSensysAPResult = connectToSensysAP();
if(connectToSensysAPResult == 0)
{
ApTcpConnectionState = CONNECTED;
}
else
{
ApTcpConnectionState = DISCONNECTED;
RTX_DelayInMilliSeconds(1*MILLISECONDS_PER_SECOND);
}
break;
}
}
}
void SensysEthernetInterface::sensysCircularBuffer(char acTcpReceivedMsg[IP_RX_BUFF_LEN], unsigned int tcpReceivedMsgLength)
{
static int iTokenCount = 0;
static unsigned int rxBuffHead=0;
string circularBufferContents;
std::string strSensysMsgStringLocal;
vectorMsgParameters.clear();
unsigned int bufferIndex;
for(bufferIndex = 0; bufferIndex < tcpReceivedMsgLength; bufferIndex++, rxBuffHead &= CIRC_BUFF_MASK)
{
if(acTcpReceivedMsg[bufferIndex] != '\n')
{
tcpRxCircularBuffer[rxBuffHead] = acTcpReceivedMsg[bufferIndex];
if (tcpRxCircularBuffer[rxBuffHead++] == '>')
{
if (++iTokenCount == 2)
{
iTokenCount = 0;
strSensysMsgStringLocal.clear();
if (rxBuffHead < rxBuffTail)
{
strSensysMsgStringLocal.append(std::string(tcpRxCircularBuffer).c_str(), rxBuffTail, CIRC_BUFF_LEN/*32768*/-rxBuffTail);
strSensysMsgStringLocal.append(std::string(tcpRxCircularBuffer).c_str(), rxBuffHead);
}
else
{
strSensysMsgStringLocal.append(std::string(tcpRxCircularBuffer).c_str(), rxBuffTail, rxBuffHead-rxBuffTail);
}
rxBuffTail = rxBuffHead;
strSensysMsgType = loadSensysMsgParameters(strSensysMsgStringLocal);
noOfMsgParameters = vectorMsgParameters.size();
sensysMsgParser(strSensysMsgStringLocal, noOfMsgParameters);
}
}
}
}
}
/********************************************************************************************************************
checkIPAddressValidity: Input Display address in format: 172.020.050.100(note the 3 digit octets with leading zeros)
*********************************************************************************************************************/
uchar SensysEthernetInterface::checkIPAddressValidity(std::string strIPAddress)
{
string strIPBuf = "";
string strDisplayAddr;
int iDigits = 0;
int ipOctet = 0;//Each number between the dots e.g 172 in 172.20.50.100
for(unsigned int iStrLen = 0; iStrLen <= strIPAddress.length(); ++iStrLen)
{
if(strIPAddress[iStrLen] != '.' && iStrLen != strIPAddress.length())
{
strIPBuf.push_back(strIPAddress[iStrLen]);
iDigits++;
}
else
{
//Fill leading 0's
while(iDigits < 3)
{
strIPAddress.push_back('0');
iDigits++;
}
ipOctet = std::atoi(strIPBuf.c_str());
if(ipOctet > 255)
{
return FALSE;
}
for(unsigned int strIPBufIndex = 0; strIPBufIndex < strIPBuf.length(); strIPBufIndex++)
{
strDisplayAddr.push_back(strIPBuf[strIPBufIndex]);
}
if(iStrLen < strIPAddress.length())
{
strDisplayAddr.push_back('.');
}
iDigits = 0;
strIPBuf.clear();
}
}
return TRUE;
}
int SensysEthernetInterface::connectToSensysAP(void)
{
int connectResult;// = SOCKET_ERROR;
bool bReadSettingsSuccess = false;
SEI.strSensysIPAddress = SEI.readIpFromConfigFile();
sensysIP = inet_addr(SEI.strSensysIPAddress.c_str());
sensysPort = SENSYS_PORT;
socketBlockTimeOut = 1;
//TCPCreateSocket creates sockets and connects to AP
sensysTCPSocket = TCPCreateSocket(sensysIP, SENSYS_PORT, socketBlockTimeOut);
if((sensysTCPSocket == INVALID_SOCKET) || (sensysTCPSocket == SOCKET_ERROR))
{
connectResult = SOCKET_ERROR;
}
else
{
//Create socket and connect usually returns 0 if successful. http://www.on-time.com/rtos-32-docs/rtip-32/reference-manual/socket-api/connect.htm
connectResult = 0;
}
//Check if still connected to assigned socket: http://www.on-time.com/rtos-32-docs/rtip-32/reference-manual/extended-api/xn-tcp-is-connect.htm
if(xn_tcp_is_connect(sensysTCPSocket) == false)
{
connectResult = SOCKET_ERROR;
}
else
{
connectResult = 0;
}
return connectResult;
}
int SensysEthernetInterface::closeSensysSocket()
{
//Close socket: http://www.on-time.com/rtos-32-docs/rtip-32/reference-manual/socket-api/closesocket.htm
//Close socket options: http://www.on-time.com/rtos-32-docs/rtip-32/reference-manual/socket-api/setsockopt.htm
int closeSocketResult;
linger sensysLingerOption;
//Hard close without timeout
sensysLingerOption.l_onoff = 1;
sensysLingerOption.l_linger = 0;
setsockopt(sensysTCPSocket, SOL_SOCKET, SO_LINGER,(const char*)&sensysLingerOption.l_onoff ,(sizeof(sensysLingerOption)));
closeSocketResult = closesocket(sensysTCPSocket);
if(closeSocketResult == 0)
{
closeSocketResult = 0;
}
else
{
closeSocketResult = SOCKET_ERROR;
}
return closeSocketResult;
}
std::string SensysEthernetInterface::loadSensysMsgParameters(std::string strSensysTcpString)
{
vectorMsgParameters.clear();//Clearing parameter list first
std::string strMsgType;
std::string strMsgParameter;
for(int msgType = 0; msgType < NUMBER_OF_MSG_TYPES; msgType++)
{
if((strSensysTcpString.find(messageTypes[msgType])) != std::string::npos)
{
strMsgType = messageTypes[msgType];
for(int msgParameter = 0; msgParameter < NUMBER_OF_SENSYS_MSG_PARAMETERS; msgParameter++)
{
strMsgParameter = sensysMsgParameters[msgType][msgParameter];
if(strMsgParameter != "")
{
vectorMsgParameters.push_back(strMsgParameter);
}
}
}
}
if(strMsgType == "")
{
TRACE("Sensys Message Type Invalid!",0);
}
return strMsgType;
}
void SensysEthernetInterface::sensysMsgParser(std::string strSensysTcpString, int noOfMsgParameters)
{
long long llTimeStamp = 0;
int iTimeStamp = 0;
char* ptr;
int inputNumber = 0;
for(int parameter = 0; parameter < noOfMsgParameters; parameter++)
{
//Look for each parameter after scanning the message type in the Sensys message string
parameterPosition = strSensysTcpString.find(vectorMsgParameters.at(parameter),strSensysMsgType.length());
if(parameterPosition == std::string::npos)
{
//TRACE("Error: Could not find paramater",0);
continue;
}
//Parameter value starts from right after "
parameterValueStartPosition = strSensysTcpString.find("\"", parameterPosition) + 1;
if(parameterValueStartPosition == std::string::npos)
{
TRACE("Error: Invalid Sensys message format",0);
continue;
}
//Parameter value ends right before you'd find the next "
parameterValueEndPosition = strSensysTcpString.find("\"", parameterValueStartPosition) - 1;
if(parameterValueEndPosition == std::string::npos)
{
TRACE("Error: Invalid Sensys message format",0);
continue;
}
parameterValueLength = parameterValueEndPosition - parameterValueStartPosition + 1;
switch(parameter)
{
case PARAMETER_SENSOR_ID:
for(int parameterValuePosition = 0; parameterValuePosition < parameterValueLength; parameterValuePosition++)
{
strMsgParameterValue.push_back(strSensysTcpString.at(parameterValueStartPosition + parameterValuePosition));
}
strSensorID = strMsgParameterValue;
break;
case PARAMETER_TIMESTAMP:
for(int parameterValuePosition = 0; parameterValuePosition < parameterValueLength; parameterValuePosition++)
{
strMsgParameterValue.push_back(strSensysTcpString.at(parameterValueStartPosition + parameterValuePosition));
}
//Timestamp from the sensors arrive in this format: Timestamp = "1432740124.590". The timestamp is then converted to long long format
if(strMsgParameterValue.length() > 3)
{
iTimeStamp = (int)strtol(&strMsgParameterValue[strMsgParameterValue.length() - 3],&ptr,10);//Gets the digits after the decimal point i.e Milliseconds
llTimeStamp = _atoi64(&strMsgParameterValue[0])*1000;//Gets the seconds
llTimeStamp = llTimeStamp + iTimeStamp;//Timestamp in Total Milliseconds
sensysDetectorTimeStamp = llTimeStamp;//In Milliseconds
}
break;
case PARAMETER_STATUS:
for(int parameterValuePosition = 0; parameterValuePosition < parameterValueLength; parameterValuePosition++)
{
strMsgParameterValue.push_back(strSensysTcpString.at(parameterValueStartPosition + parameterValuePosition));
}
detectorStatus = atoi(strMsgParameterValue.c_str());
//TRACE("SENSYS EVENT STATUS = %d", detectorStatus);
break;
case PARAMETER_ADDRESS1://case of address1
//012345678
//3f-0-15-4 is the address represented here as channelMapInHexFormat-shelfNumber-SlotNumber-ChannelNumber respectively
for(int parameterValuePosition = 0; parameterValuePosition < parameterValueLength; parameterValuePosition++)
{
strMsgParameterValue.push_back(strSensysTcpString.at(parameterValueStartPosition + parameterValuePosition));
if((strMsgParameterValue[parameterValuePosition]) == '-')
{
enDashCount++;
}
}
if(enDashCount != EN_DASHES_IN_ADDRESS1_PARAM)
{
TRACE("Error: Invalid Sensys message format",0);
}
numberOfTokens = enDashCount + 1;
detectorNumber = enDashAddress1Tokenizer(strMsgParameterValue,numberOfTokens);
enDashCount = 0;
//StoreDetInfo(detectorNumber, detectorStatus, strSensorID);
break;
default:
for(int parameterValuePosition = 0; parameterValuePosition < parameterValueLength; parameterValuePosition++)
{
strMsgParameterValue.push_back(strSensysTcpString.at(parameterValuePosition + parameterValueStartPosition));
}
break;
}
//TRACE(&strMsgParameterValue[0],0);
strMsgParameterValue.clear();
tokenLength = 0;
tokenPosition = 0;
}
llLatestTimeStamp = (unsigned long)sensysDetectorTimeStamp;
llSensysTimestamp[detectorNumber-1] = sensysDetectorTimeStamp;
millisecondsSinceTimeStamp = 0;
processSensysMsg(strSensorID,strSensysMsgType, detectorNumber, detectorStatus);
}
void SensysEthernetInterface::updateSensysConfigFile(std::string sensorID, int detectorNumber, std::string strSensysMsgType )
{
string writeFileLine;
string readFileLine;
ifstream in;
unsigned int fileLinesCount;
uchar ucSensorIDInList = FALSE;
uchar ucRewriteFile = FALSE;
//---------------------------------File Headers:-------------------------------------
string title1 = "Sensys Detectors";
string title2 = "Input Number";
string title3 = "Operating State";
string title1Space = " ";
string title2Space = " ";
string title3Space = " ";
//-----------------------------------------------------------------------------------
string strDetectorNumber = " ";
if(detectorNumber < 10)
{
strDetectorNumber[0] = '0';
strDetectorNumber[1] = '0' + detectorNumber;
}
else
{
strDetectorNumber[0] = '0' + detectorNumber;
}
ucSensorIDInList = checkSensorIDList(sensorID,SENSYS_CONFIG_FILE);
if(!ucSensorIDInList)
{
if(strSensysMsgType == "diagnostic")
{
writeAppendToFile(SENSYS_CONFIG_FILE, " " + sensorID + " " + strDetectorNumber + " " + "Fault ");
}
else
{
writeAppendToFile(SENSYS_CONFIG_FILE, " " + sensorID + " " + strDetectorNumber + " " + "Normal");
}
}
else
{
v_detectorConfigInfo.clear();
loadSensorDataFromFile(SENSYS_CONFIG_FILE);
fileLinesCount = v_detectorConfigInfo.size();
TRACE("Test",0);
for(unsigned int readLineIndex = 0; readLineIndex < v_detectorConfigInfo.size(); readLineIndex++)
{
readFileLine = v_detectorConfigInfo.at(readLineIndex);
if(readFileLine.find(sensorID) != string::npos)
{
if(strSensysMsgType == "diagnostic")
{
if(readFileLine.find("Normal") != std::string::npos)
{
v_detectorConfigInfo.at(readLineIndex) = " " + sensorID + " " + strDetectorNumber + " " + "Fault ";
ucRewriteFile = TRUE;
}
}
if (((strSensysMsgType == "event") || (strSensysMsgType == "watchdog")))
{
if((readFileLine.find("Fault") != std::string::npos))
{
v_detectorConfigInfo.at(readLineIndex) = " " + sensorID + " " + strDetectorNumber + " " + "Normal";
ucRewriteFile = TRUE;
}
}
}
}
TRACE("TEST",0)
if(ucRewriteFile == TRUE)
{
for(unsigned int writeLineIndex = 0; writeLineIndex < v_detectorConfigInfo.size(); writeLineIndex++)
{
writeFileLine = v_detectorConfigInfo.at(writeLineIndex);
writeAppendToFile(SENSYS_CONFIG_FILE_NEW,writeFileLine);
}
remove(SENSYS_CONFIG_FILE);
rename(SENSYS_CONFIG_FILE_NEW,SENSYS_CONFIG_FILE);
ucRewriteFile = FALSE;
}
}
}
uchar SensysEthernetInterface::checkSensorIDList(std::string sensorID, std::string strFileName)
{
ifstream in;
string fileLine;
in.open(strFileName.c_str(),std::ios::in);
while(std::getline(in,fileLine))//in)
{
TRACE("Test",0);
if(fileLine.find(sensorID) != std::string::npos)//If sensorID is already in the list:
{
return TRUE;
}
}
in.close();
return FALSE;
}
void SensysEthernetInterface::processSensysMsg(std::string strSensorID,std::string strSensysMsgType, int detectorNumber, int detectorStatus)
{
int inputNumber = 0;
if(((strSensysMsgType == "event") || (strSensysMsgType == "watchdog")) && (detectorNumber > 0))
{
inputNumber = detectorNumber - 1;
if(detectorStatus == 1)
{
ulSensysDetectorMap |= 0x01<<inputNumber;
if(inputNumber < 8)
{
SEI.acSensysDet[0] |= 0x01<<inputNumber;
}
else if(inputNumber < 16)
{
acSensysDet[1] |= 0x01<<(inputNumber-8);
}
else if(inputNumber < 24)
{
acSensysDet[2] |= 0x01<<(inputNumber-16);
}
else if(inputNumber < 32)
{
acSensysDet[3] |= 0x01<<(inputNumber-24);
}
}
else if(detectorStatus == 0)
{
ulSensysDetectorMap &= ~(0x01<<inputNumber);
if(inputNumber < 8)
{
acSensysDet[0] &= ~(0x01<<inputNumber);
}
else if(inputNumber < 16)
{
acSensysDet[1] &= ~(0x01<<(inputNumber-8));
}
else if(inputNumber < 24)
{
acSensysDet[2] &= ~(0x01<<(inputNumber-16));
}
else if(inputNumber < 32)
{
acSensysDet[3] &= ~(0x01<<(inputNumber-24));
}
}
map_sensorID_To_elapsedTime[strSensorID] = 0;
}
else if((strSensysMsgType == "diagnostic") && (detectorNumber > 0))
{
//Permanent call on diagnostic packet send
inputNumber = detectorNumber - 1;
ulSensysDetectorMap |= 0x01<<inputNumber;
if(inputNumber < 8)
{
SEI.acSensysDet[0] |= 0x01<<inputNumber;
}
else if(inputNumber < 16)
{
acSensysDet[1] |= 0x01<<(inputNumber-8);
}
else if(inputNumber < 24)
{
acSensysDet[2] |= 0x01<<(inputNumber-16);
}
else if(inputNumber < 32)
{
acSensysDet[3] |= 0x01<<(inputNumber-24);
}
}
//Updates vehcile statistics using current status of all the sensys detectors
updateVehicleStatistics(ulSensysDetectorMap);
//Update Sensys config file if necessary from latest available information
updateSensysConfigFile(strSensorID, detectorNumber,strSensysMsgType );
TRACE("Test",0);
}
int SensysEthernetInterface::enDashAddress1Tokenizer(std::string strMsgParameterValue,int numberOfTokens)
{
int detectorAddress = 0;
for(int token = 0; token < numberOfTokens; token++)
{
tokenLength = strMsgParameterValue.find('-',tokenPosition) - tokenPosition;
strToken = strMsgParameterValue.substr(tokenPosition, tokenLength);
tokenPosition = tokenPosition + tokenLength + 1;
switch(token)
{
//Byte 1 - Hex format of the mapped channel.
case MAPPED_CHANNEL_IN_HEX_FORMAT:
//Convert hex if needed
break;
case SHELF_NUMBER://Byte 2 - Shelf number should always be 0
if(atoi(strToken.c_str()) != 0)
{
TRACE("Shelf Number incorrect!", 0);
detectorAddress = 0;
}
break;
case SLOT_NUMBER://Byte 3 - Slot number
if(atoi(strToken.c_str()) > 15)
{
TRACE("Slot Number incorrect!", 0);
detectorAddress = 0;
}
else
{
slotNumber = atoi(strToken.c_str());
}
break;
case CHANNEL_NUMBER://Byte 4 - Channel Number
if(atoi(strToken.c_str()) > 4)
{
TRACE("Channel Number incorrect!", 0);
detectorAddress = 0;
}
else if(atoi(strToken.c_str()) < 1)
{
detectorAddress = 0;
}
else
{
channelNumber = atoi(strToken.c_str());
}
break;
default:
detectorAddress = 0;
break;
}
}
if(slotNumber > 0)
{
detectorAddress = (slotNumber-1)*CHANNELS_PER_SLOT + channelNumber;
}
else
{
TRACE("slotNumber invalid",0);
detectorAddress = 0;
}
//Detector mapping allows for only "STIMULI" number of detectors which is 32 currently.
if(detectorAddress > STIMULI)
{
detectorAddress = 0;
}
//TRACE("Detector Number: %d", detectorAddress);
//returns detectorAddress as 0 for any invalid input messages
return detectorAddress;
}
unsigned char SensysEthernetInterface::getSensysAPConnectionStatus()
{
int rtipBoolConnect;
//http://www.on-time.com/rtos-32-docs/rtip-32/reference-manual/extended-api/xn-tcp-is-connect.htm
rtipBoolConnect = xn_tcp_is_connect(sensysTCPSocket);
return ((unsigned char)rtipBoolConnect);
}
void SensysEthernetInterface::SensysDetConfig(unsigned long SysDetectorConfig, SPEED_PAIR_CONFIG SpeedPairConfig[])
{
std::ifstream sensysConfigInputStream;
std::string fileLine;
std::string strDetectorNumber;
int inputNumber;
string title1 = "Sensys Detectors";
string title2 = "Input Number";
string title3 = "Operating State";
string title1Space = " ";
string title2Space = " ";
string title3Space = " ";
string item1LeftSpace = " ";
string item1RightSpace = " ";
string item2Space = " ";
string item3Space = " ";
//Assign config from Controller.cpp
ulConfiguredSysDetectors = SysDetectorConfig;
try//String.substr can crash if the file exists but is empty. Catch any exceptions here.
{
//Read SENSYS_CONFIG_FILE and force high on Sensys Detector Inputs
sensysConfigInputStream.open(SENSYS_CONFIG_FILE,std::ios::in);
while(sensysConfigInputStream)//std::getline(sensysConfigInputStream,fileLine))
{
std::getline(sensysConfigInputStream,fileLine);
if(fileLine.find("Sensys") == std::string::npos)//If line read is not the Column headers
{
strDetectorNumber = fileLine.substr(15,25);//strDetectorNumber should be somewhere in between
strDetectorNumber = strDetectorNumber.substr((strDetectorNumber.find_first_not_of(" ")), 2);
inputNumber = ((atoi(strDetectorNumber.c_str())) - 1);
ulSensysDetectorMap |= 0x01<<inputNumber;
if(inputNumber < 8)
{
SEI.acSensysDet[0] |= 0x01<<inputNumber;
}
else if(inputNumber < 16)
{
acSensysDet[1] |= 0x01<<(inputNumber-8);
}
else if(inputNumber < 24)
{
acSensysDet[2] |= 0x01<<(inputNumber-16);
}
else if(inputNumber < 32)
{
acSensysDet[3] |= 0x01<<(inputNumber-24);
}
}
}
sensysConfigInputStream.close();
}
catch(exception &e)
{
TRACE("Error reading from SensysConfig.txt",0);
TRACE(e.what(),0);
}
for(int speedDetector = 0; speedDetector < SPEED_DETECTORS; speedDetector++)
{
SpeedDetectorPair[speedDetector].ucDistance = SpeedPairConfig[speedDetector].ucDistance;
SpeedDetectorPair[speedDetector].ucFirstLoop = SpeedPairConfig[speedDetector].ucFirstLoop;
SpeedDetectorPair[speedDetector].ucSecondLoop = SpeedPairConfig[speedDetector].ucSecondLoop;
}
}
void SensysEthernetInterface::updateVehicleStatistics(unsigned long ulSensysDetectorMap)
{
/*NOTE: System detectors refer to detectors used for calculating System count and Occupancy.*/
//System Count
ulSystemCountDetMap = ulSensysDetectorMap & ulConfiguredSysDetectors;
ulDetectorMask = (B32(00000000,00000000,00000000,00000001));
for(int detector = 0; detector < STIMULI; detector++)
{
if((!(ulPreviousSystemCountDetMap & ulDetectorMask)) && (ulSystemCountDetMap & ulDetectorMask))
{
usSystemCount[detector]++;
}
ulDetectorMask <<= 1;
}
//System Occupancy
ulDetectorMask = (B32(00000000,00000000,00000000,00000001));
ulSystemOccupancyDetMap = ulSensysDetectorMap & ulConfiguredSysDetectors;
for(int detector = 0; detector < STIMULI; detector++)
{
if(!(ulPreviousSystemOccupancyDetMap & ulDetectorMask) && (ulSystemOccupancyDetMap & ulDetectorMask))
{
ulOccupancyStart[detector] = (unsigned long)llSensysTimestamp[detector];
}
if((ulPreviousSystemOccupancyDetMap & ulDetectorMask) && !(ulSystemOccupancyDetMap & ulDetectorMask))
{
if(ulOccupancyStart[detector] != 0)
{
ulOccupancyInterval[detector] = (unsigned long)(llSensysTimestamp[detector] - ulOccupancyStart[detector]);
ulSumOfOccupancyIntervals[detector] = ulSumOfOccupancyIntervals[detector] + ulOccupancyInterval[detector];
}
}
ulDetectorMask <<= 1;
}
//Determine the rising edges
ulRisingEdgeDetMap = ulSensysDetectorMap ^ ulPreviousEdgeDetMap;
ulRisingEdgeDetMap = ulRisingEdgeDetMap & ulSensysDetectorMap;
//Determine the falling edges
ulFallingEdgeDetMap = ulSensysDetectorMap | ulPreviousEdgeDetMap;
ulFallingEdgeDetMap = ulFallingEdgeDetMap ^ ulSensysDetectorMap;
//Speed calculations
//Note: Speed calculations are done for each speed pair
for(int speedDetectorPair = 0; speedDetectorPair < SPEED_DETECTORS; speedDetectorPair++)
{
if ((1L<<(SpeedDetectorPair[speedDetectorPair].ucFirstLoop)) & (ulRisingEdgeDetMap))
{
ulTimeAtLeadingEdge[speedDetectorPair] = llLatestTimeStamp;
}
//Getting vehicle pulse length for classification
if ((1L<<(SpeedDetectorPair[speedDetectorPair].ucFirstLoop)) & (ulFallingEdgeDetMap))
{
if (ulTimeAtLeadingEdge[speedDetectorPair] != 0)
{
ulTimeOnLeadingEdge[speedDetectorPair] = llLatestTimeStamp - ulTimeAtLeadingEdge[speedDetectorPair];
}
}
if ((1L<<(SpeedDetectorPair[speedDetectorPair].ucSecondLoop)) & (ulRisingEdgeDetMap))
{
if (ulTimeAtLeadingEdge[speedDetectorPair] != 0)
{
ulLeadToTrailEdgeInterval[speedDetectorPair] = ((llLatestTimeStamp) - (ulTimeAtLeadingEdge[speedDetectorPair]));
//ulTimeAtLeadingEdge[speedDetectorPair] = 0;
//Speed Detector statistics sent on each detector
// -----------------------------------------------------------
// Note:
// GPIO version 2.105:
// Data[7-14] = Pulse width of speed for each detector pair
// Data[15-22] = Pulse width of leading speed pair loop for
// vehicle classification
// -----------------------------------------------------------
//- ProcessSpeedClassification works in Decimeters. Hence the use of the correction factor of 10.
acSensysDetectorData[7+speedDetectorPair] = (unsigned char)(ulLeadToTrailEdgeInterval[speedDetectorPair]/10);//Speed Pulse
acSensysDetectorData[15+speedDetectorPair] = (unsigned char)(ulTimeOnLeadingEdge[speedDetectorPair]/10);//Classification Pulse