-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtcpClient.cpp
More file actions
1363 lines (1199 loc) · 42.9 KB
/
tcpClient.cpp
File metadata and controls
1363 lines (1199 loc) · 42.9 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
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 "tcpClient.h"
#include <stdio.h>
tcpClient::tcpClient(log4cpp::Category *logger, tcpServer *server,
canHandler* can, int client_sock, struct sockaddr_in client_addr,
int id, nodeConfigurator *config, sessionHandler *session_handler)
{
//ctor
this->server = server;
this->can = can;
this->client_sock = client_sock;
this->client_addr = client_addr;
this->logger = logger;
this->id = id;
this->config = config;
this->session_handler= session_handler;
logger->debug("Client %d created", id);
this->re_speed = regex(RE_SPEED);
this->re_session = regex(RE_SESSION);
this->re_rel_session = regex(RE_REL_SESSION);
this->re_dir = regex(RE_DIR);
this->re_qry_speed = regex(RE_QRY_SPEED);
this->re_qry_direction = regex(RE_QRY_DIRECTION);
this->re_func = regex(RE_FUNC);
this->re_turnout = regex(RE_TURNOUT);
this->re_turnout_generic = regex(RE_TURNOUT_GENERIC);
this->re_idle = regex(RE_IDLE);
this->clientType = CLIENT_TYPE::ED;
sessions_retrieved = false;
//get any remaining sessions
retrieveRemainingSessions();
edsession = this->session_handler->createEDSession(id,string(""),this->client_addr.sin_addr.s_addr);
setStartSessionTime();
pthread_mutex_init(&m_mutex_in_cli, NULL);
pthread_cond_init(&m_condv_in_cli, NULL);
}
tcpClient::~tcpClient()
{
pthread_mutex_destroy(&m_mutex_in_cli);
pthread_cond_destroy(&m_condv_in_cli);
}
void tcpClient::setTurnout(Turnout* turnouts){
this->turnouts = turnouts;
}
void tcpClient::setStartSessionTime(){
struct timespec spec;
clock_gettime(CLOCK_REALTIME,&spec);
edsession->setCbusTime(spec);
edsession->setEDTime(spec);
}
void tcpClient::start(void *param){
running = 1;
stringstream ss;
ss << SOFT_VERSION;ss << "\n";
sendToEd(ss.str());
ss << "\n";
ss.clear();ss.str("");
ss << START_INFO_RL;ss << "\n";
ss << START_INFO_PPA;ss << "\n";
ss << turnouts->getStartInfo();ss << "\n";
ss << START_INFO_PRT;ss << "\n";
ss << START_INFO_PRL;ss << "\n";
ss << START_INFO_RCC;ss << "\n";
ss << START_INFO_PW;ss << "\n";
sendToEd(ss.str());
run(nullptr);
}
void tcpClient::stop(){
running = 0;
releaseAllSessions();
usleep(1000*1000);
close(client_sock);
}
void tcpClient::canMessage(int canid,const char* msg, int dlc){
struct can_frame frame;
frame.can_id = canid;
frame.can_dlc = dlc;
frame.data[0] = msg[0];
frame.data[1] = msg[1];
frame.data[2] = msg[2];
frame.data[3] = msg[3];
frame.data[4] = msg[4];
frame.data[5] = msg[5];
frame.data[6] = msg[6];
frame.data[7] = msg[7];
pthread_mutex_lock(&m_mutex_in_cli);
in_msgs.push(frame);
pthread_cond_signal(&m_condv_in_cli);
pthread_mutex_unlock(&m_mutex_in_cli);
}
void tcpClient::run(void *param){
char msg[BUFFER_SIZE];
int nbytes;
pthread_t kalive;
pthread_create(&kalive, nullptr, tcpClient::thread_keepalive, this);
pthread_t cbusin;
pthread_create(&cbusin, nullptr, tcpClient::thread_processcbus, this);
while (running){
memset(msg,0,BUFFER_SIZE);
nbytes = recv(client_sock, msg,BUFFER_SIZE, 0);
if (nbytes<0){
logger->debug("[%d] [tcpClient] Error while receiving data from ED %d",id,nbytes);
/*
* mark the existing sessions as orphan
* in case the client disconnection was not proper done
*/
std::map<int,edSession*>::iterator it = sessions.begin();
while(it != sessions.end())
{
logger->debug("[%d] [tcpClient] Setting session %d for loco %d as orphan",id, it->second->getSession(), it->second->getLoco());
it->second->setOrphan(true);
it++;
}
running = 0;
}
else if (nbytes>0){
logger->notice("[%d] [tcpClient] Received from ED:%s Bytes:%d",id, msg, nbytes);
try{
handleEDMessages(msg);
}
catch(const runtime_error &ex){
logger->debug("[%d][tcpClient] Failed to process the can message\n%s",id,ex.what());
}
}
if (nbytes == 0){
logger->debug("[%d] [tcpClient] 0 bytes received. disconnecting",id);
/*
* mark the existing sessions as orphan
* in case the client disconnection was not proper done
*/
std::map<int,edSession*>::iterator it = sessions.begin();
while(it != sessions.end())
{
logger->debug("[%d] [tcpClient] Setting session %d for loco %d as orphan",id, it->second->getSession(), it->second->getLoco());
it->second->setOrphan(true);
it++;
}
running = 0;
break;
}
}
logger->info("[%d] [tcpClient] Quiting client connection ip:%s id:%d.",id, ip.c_str(),id);
usleep(2000*1000); //1sec give some time for any pending thread to finish
try{
pthread_cancel(kalive);
pthread_cancel(cbusin);
server->removeClient(this);
}
catch(...){
logger->error("[tcpClient] Failed to stop the tcp client.");
}
}
void tcpClient::sendKeepAlive(void *param){
long millis;
struct timespec spec;
struct timespec t;
while (running){
try{
usleep(1000*500);//500ms
if (running == 0){
logger->info("[%d] [tcpClient] Stopping keep alive process",id);
break;
}
if (sessions.size() == 0){
clock_gettime(CLOCK_REALTIME,&spec);
t = edsession->getEDTime();
millis = elapsed_millis(spec, t);
if (millis > ED_KEEP_ALIVE ){
//send to ED
logger->debug("[%d] [tcpClient] Send ED keep alive",id);
sendToEd("*10\n");
edsession->setEDTime(spec);
edsession->setOrphan(false);
}
}
else{
std::map<int,edSession*>::iterator it = sessions.begin();
while(it != sessions.end())
{
clock_gettime(CLOCK_REALTIME,&spec);
t = it->second->getEDTime();
millis = elapsed_millis(spec, t);
if (millis > ED_KEEP_ALIVE ){
it->second->setEDTime(spec);
//send to ED
logger->debug("[%d] [tcpClient] Send ED keep alive",id);
sendToEd("*10\n");
it->second->setOrphan(false);
}
if (it->second->getLoco()>-1){
t = it->second->getCbusTime();
millis = elapsed_millis(spec, t);
if (millis > CBUS_KEEP_ALIVE ){
it->second->setCbusTime(spec);
//send keep alive
logger->debug("[%d] [tcpClient] Send CBUS keep alive",id);
sendCbusMessage(OPC_DKEEP,it->second->getSession());
}
}
it++;
}
}
}//try
catch(...){
logger->debug("[%d] [tcpClient] Keep alive error",id);
}
}
logger->info("[%d] [tcpClient] Finish keep alive process",id);
}
void tcpClient::handleEDMessages(char* msgptr){
vector<string> msgs;
string message (msgptr);
const char *msgtemp;
try{
msgs = split(message,'\n', msgs);
for (auto const& msg:msgs){
logger->debug("[%d] [tcpClient] Handle message:%s",id,msg.c_str());
if (msg.length() == 0){
continue;
}
msgtemp = msg.c_str();
//get the name
if (msgtemp[0] == 'N'){
logger->debug("[%d] [tcpClient] ED name: %s" ,id, msgtemp);
edsession->setEdName(msg.substr(1,msg.length()-1));
sendToEd("*10\n"); //keep alive each 10 seconds
//get any remaining sessions
retrieveRemainingSessions();
continue;
}
//get hardware info
if ((msgtemp[0] == 'H') && (msgtemp[1] == 'U')){
edsession->setEdHW(msg.substr(2,msg.length()-2));
logger->debug("[%d] [tcpClient] Received Hardware info: %s" , id,msg.substr(2,msg.length()-2).c_str());
sendToEd("\n*10\n"); //keep alive each 10 seconds
//TODO wait for confirmation: expected 0xa
continue;
}
if ((msgtemp[0] == '*') && (msgtemp[1] == '+')){
logger->debug("[%d] [tcpClient] Timer request",id);
sendToEd("*10\n"); //keep alive each 10 seconds
continue;
}
if ((msgtemp[0] == '*') && (msgtemp[1] == '-')){
logger->debug("[%d] [tcpClient] Finish timer request",id);
continue;
}
//create session
if (regex_match(msg,re_session)){
int loco = getLoco(msg);
if (sessions.find(loco) != sessions.end()){
//session already exists, maybe imported from a dead client
logger->debug("[%d] [tcpClient] Session already exists %s" ,id, msg.c_str());
ackEDSessionCreated(sessions[loco], false);
}
else{
logger->debug("[%d] [tcpClient] Create session %s" ,id, msg.c_str());
loco = handleCreateSession(msg);
// wait until session is created
logger->debug("[%d] [tcpClient] Waiting for session to be created.",id);
int loop = 0;
while (loop < 4 && loco > 0){
usleep(500*1000);
if (sessions.size()>0){
if (sessions.find(loco) != sessions.end()){
logger->debug("[%d] [tcpClient] Session created for loco %d.", id, loco);
loop = 10;
}
}
loop++;
}
if (sessions.find(loco) == sessions.end()){
logger->debug("[%d] [tcpClient] No session created for loco %d.",id, loco);
}
}
continue;
}
//set speed
if (regex_match(msg,re_speed)){
handleSpeed(msg);
continue;
}
//idle. basically sets the speed to 0
if (regex_match(msg,re_idle)){
handleIdle(msg);
continue;
}
//set direction
if (regex_match(msg,re_dir)){
handleDirection(msg);
continue;
}
//query speed
if (regex_match(msg,re_qry_speed)){
handleQuerySpeed(msg);
continue;
}
//query direction
if (regex_match(msg,re_qry_direction)){
handleQueryDirection(msg);
continue;
}
//release session
if (regex_match(msg,re_rel_session)){
handleReleaseSession(msg);
continue;
}
//set unset FNs
if (regex_match(msg,re_func)){
handleSetFunction(msg);
continue;
}
//turnouts
if (regex_match(msg,re_turnout)){
handleTurnout(msg);
continue;
}
if (regex_match(msg,re_turnout_generic)){
handleTurnoutGeneric(msg);
continue;
}
logger->debug("[%d] [tcpClient] Support not implemented %s",id,msg.c_str());
}
}
catch(const runtime_error &ex){
logger->debug("[tcpClient] Not runtime error cought. %s",ex.what() );
cout << "[tcpClient] Not runtime error cought" << ex.what() << endl;
}
catch(...){
logger->debug("[tcpClient] Not runtime error cought");
cout << "[tcpClient] Not runtime error cought" << endl;
}
}
void tcpClient::retrieveRemainingSessions(){
/* retrieve sessions once per client*/
if (sessions_retrieved) return;
sessions_retrieved = true;
std::vector<edSession*> tempsessions;
int num_sessions = session_handler->retrieveAllEDSession(id, "", client_addr.sin_addr.s_addr, &tempsessions );
logger->debug("[%d] [tcpClient] Retrieved %d sessions",id, num_sessions);
if (tempsessions.size() > 0){
for (auto ed:tempsessions){
sessions.insert(pair<int,edSession*>(ed->getLoco(),ed));
}
}
deleteUnsetSessions();
}
void tcpClient::ackEDSessionCreated(edSession *ed, bool sendSpeedMode){
string message;
stringstream ss;
char stype;
stype = ed->getSessionType();
ss << "M";
ss << stype;
ss << "+";
ss << ed->getAddressType();
ss << ed->getLoco();
ss << DELIM_BTLT;
ss << ed->getLocoName();
ss << '\n';
message = ss.str();
sendToEd(message);
if (sendSpeedMode){
//set speed mode 128 to can
logger->debug("[%d] [tcpClient] Sending speed mode 128 to CBUS",id);
sendCbusMessage(OPC_STMOD, ed->getSession(), 0);
}
//send the labels to client
ss.clear();ss.str();
ss << "M";
ss << stype ;
ss <<"L" ;
ss << ed->getAddressType();
ss << ed->getLoco();
ss << EMPTY_LABELS;
ss << generateFunctionsLabel(ed->getLoco(), stype, ed->getAddressType());
ss << '\n';
logger->debug("[%d] [tcpClient] Sending labels",id);
sendToEd(ss.str());
// logger->debug("[%d] [tcpClient] Sending speed mode 128 to ED",id);
// ss.clear();ss.str();
// ss << "M";
// ss << stype;
// ss << ed->getAddressType();
// ss << ed->getLoco();
// ss << DELIM_BTLT;
// ss << "s0\n";
// sendToEd(ss.str());
}
void tcpClient::processCbusQueue(void *param){
struct can_frame frame;
char buf[100];
logger->debug("[%d] [tcpClient] Tcp Client cbus thread read cbus queue",id);
while (running){
pthread_mutex_lock(&m_mutex_in_cli);
pthread_cond_wait(&m_condv_in_cli, &m_mutex_in_cli);
if (in_msgs.empty()){
pthread_mutex_unlock(&m_mutex_in_cli);
}
else{
frame = in_msgs.front();
in_msgs.pop();
pthread_mutex_unlock(&m_mutex_in_cli);
try{
memset(buf,0,sizeof(buf));
sprintf(buf,"%02x %02x %02x %02x %02x %02x %02x %02x\n", frame.data[0],frame.data[1],frame.data[2],frame.data[3],frame.data[4],frame.data[5],frame.data[6],frame.data[7]);
logger->debug("[%d] [tcpClient] Tcp Client received cbus message: %s",id,buf);
handleCBUS(frame.data);
}
catch(runtime_error &ex){
logger->debug("[%d] [tcpClient] Failed to process the can message",id);
}
catch(...){
logger->debug("[%d] [tcpClient] Failed to process the can message",id);
}
}
//usleep(4000);
}
}
void tcpClient::handleCBUS(unsigned char *msg){
unsigned char opc = msg[0];
int loco,tcode;
string message;
stringstream ss;
unsigned char speed;
unsigned char direction ;
unsigned char session;
//char stype;
logger->info("[%d] [tcpClient] Processing CBUS message %02x",id,opc);
switch (opc){
case OPC_PLOC:
logger->debug("[%d] [tcpClient] Checking result of request session. OPC: PLOC %02x %02x",id,msg[2] ,msg[3]);
session = msg[1];
loco = msg[2] & 0x3f;
loco = (loco << 8) + msg[3];
if (edsession->getLoco() != loco){
logger->debug("[%d] [tcpClient] PLOC %d not for this session %d. Discarding." , id,loco, edsession->getLoco());
return;
}
logger->info("[%d] [tcpClient] Loco %d acquired",id,loco);
edsession->setSession(session);
//decode the DCC format
speed = msg[4] & 0x7F; //#0111 1111
direction = 0;
if ((msg[4] & 0x80) > 127) direction = 1;
//put session in array
edsession->setDirection(direction);
edsession->setSpeed(speed);
edsession->getMomentaryFNs(loco);
logger->debug("[%d] [tcpClient] Ack client session created %d for loco %d :%s" ,id,session, loco, message.c_str());
logger->debug("[%d] [tcpClient] Adding loco %d to sessions", id, loco);
sessions.insert(pair<int,edSession*>(loco,edsession));
ackEDSessionCreated(edsession, true);
//create new edsession object
edsession = session_handler->createEDSession(id,string(""),this->client_addr.sin_addr.s_addr);
setStartSessionTime();
break;
case OPC_ERR:
logger->debug("[%d] [tcpClient] CBUS Error message",id);
loco = msg[2] & 0x3f;
loco = (loco << 8) + msg[3];
if (loco != edsession->getLoco()){
logger->debug("[%d] [tcpClient] Error message for another client. Different loco number %d %d. Discarding.",id,edsession->getLoco(), loco);
return;
}
switch (msg[3]){
case 1:
logger->info("[%d] [tcpClient] Can not create session. Reason: stack full",id);
break;
case 2:
logger->info("[%d] [tcpClient] Err: Loco %d TAKEN",id, loco);
break;
case 3:
logger->info("[%d] [tcpClient] Err: No session %d" ,id, loco);
break;
default:
logger->info("[%d] [tcpClient] Err code: %d" ,id, msg[3]);
}
break;
case OPC_ASOF:
tcode = msg[3];
tcode = (tcode << 8) | msg[4];
logger->info("[%d] [tcpClient] ASOF received. Checking turnout: %d." ,id,tcode);
// check the turnout state and inform the ED
if (turnouts->exists(tcode)){
logger->debug("[%d] [tcpClient] Found turnout: %d. Closing" ,id,tcode);
turnouts->CloseTurnout(tcode);
sendToEd(turnouts->getTurnoutMsg(tcode) + "\n");
}
break;
case OPC_ASON:
tcode = msg[3];
tcode = (tcode << 8) | msg[4];
logger->info("[%d] [tcpClient] ASON received. Checking turnout: %d." ,id,tcode);
// check the turnout state and inform the ED
if (turnouts->exists(tcode)){
logger->debug("[%d] [tcpClient] Found turnout: %d. Throwing" ,id,tcode);
turnouts->ThrownTurnout(tcode);
sendToEd(turnouts->getTurnoutMsg(tcode) + "\n");
}
break;
}
}
string tcpClient::generateFunctionsLabel(int loco,char stype, char adtype){
stringstream ss;
ss << "M" ;
ss << stype; // session type T or S
ss << "A";
ss << adtype; // S or L
ss << loco;
ss << DELIM_BTLT;
string s = ss.str();
ss.clear();ss.str("");
for (int f=0;f<FN_SIZE;f++){
ss << s;
ss << "F0";
ss << f;
ss << "\n";
}
ss << s;
ss << "V0\n";
ss << s;
ss << "R1\n";
ss << s;
ss << "s0\n";
return ss.str();
}
void tcpClient::sendToEd(string msg){
unsigned int nbytes;
logger->notice("[%d] [tcpClient] Send to ED:%s",id, msg.c_str());
nbytes = write(client_sock,msg.c_str(),msg.length());
if (nbytes != msg.length()){
logger->error("[tcpClient] Fail to send message %s to ED",id, msg.c_str());
}
}
//return the loco
int tcpClient::handleCreateSession(string message){
const char *msg = message.c_str();
logger->debug("[%d] [tcpClient] Handle create session: %s",id, msg);
unsigned char Hb,Lb;
int loco,i;
//create session
if ( (msg[3] == 'S') | (msg[3] == 's') | (msg[3] == 'L') | (msg[3] == 'l') ){
edsession->setSessionType(msg[1]);
logger->debug("[%d] [tcpClient] Address type %c",id,msg[3]);
edsession->setAddressType(msg[3]);
i = message.find(";>");
if (i > 0){
edsession->setLocoName(message.substr(i+2,(message.length()-i-2)));
}
//get loco
loco = getLoco(message);
edsession->setLoco(loco);
//send the can data
logger->info("[%d] [tcpClient] Request session for loco %d",id,loco);
logger->debug("[%d] [tcpClient] Put CAN session request in the queue for loco %d" ,id, loco);
Hb = 0;
if ((loco > 127) | (msg[3] == 'L') | (msg[3] == 'l')){
Hb = loco >> 8 | 0xC0;
Lb = loco & 0xFF;
}
else Lb = loco & 0xFF;
sendCbusMessage(OPC_RLOC,Hb,Lb);
return loco;
}
return -1;
}
void tcpClient::handleReleaseSession(string message){
logger->debug("[%d] [tcpClient] Handle release session %s",id, message.c_str());
//release session
int i = message.find("<;>r");
byte sesid;
char stype = message.c_str()[1];
bool special_release = false; //defined for the whithrottle when received MT-*<;>r should send back the command without the 'r'
string spmsg;
if (i > 0) special_release = true;
i = message.find("*");
//all sessions
if (i>0){
logger->debug("[%d] [tcpClient] Releasing all %c sessions", id, stype);
std::map<int,edSession*>::iterator it = this->sessions.begin();
while(it != this->sessions.end())
{
if (stype == it->second->getSessionType()){
if (it->second->isSessionSet()){
logger->info("[%d] [tcpClient] Releasing session for loco %d" ,id, it->second->getLoco());
sesid = it->second->getSession();
sendCbusMessage(OPC_KLOC, sesid);
}
}
it++;
}
//clear sessions
usleep(1000*500);//500ms
it = this->sessions.begin();
logger->info("[%d] [tcpClient] Dealocating sessions" ,id);
while(it != this->sessions.end())
{
if (stype == it->second->getSessionType()){
if (it->second->isSessionSet()){
logger->info("[%d] [tcpClient] Dealocating loco %d" ,id, it->second->getLoco());
}
session_handler->deleteEDSession(it->second->getSessionUid());
sessions.erase(it);
}
it++;
}
//inform the ED
logger->info("[%d] [tcpClient] Finished dealocatting sessions" ,id);
if (special_release){
i = message.find("<;>");
spmsg = message.substr(0,i + 3);
sendToEd(spmsg);
}
sendToEd("\n");
return;
}
//one session
int loco = getLoco(message);
logger->debug("[%d] [tcpClient] Releasing session for loco KLOC %d" ,id, loco);
//check if exists
if (sessions.find(loco) != sessions.end()){
if (sessions[loco]->isSessionSet()){
sesid = this->sessions[loco]->getSession();
//send the can data
sendCbusMessage(OPC_KLOC,sesid);
usleep(1000*200);//200ms
}
session_handler->deleteEDSession(sessions[loco]->getSessionUid());
this->sessions.erase(loco);
}
else logger->debug("[%d] [tcpClient] Loco %d not allocated" ,id,loco);
//inform the ED
if (special_release){
i = message.find("<;>");
spmsg = message.substr(0,i + 3);
sendToEd(spmsg);
}
sendToEd("\n");
}
void tcpClient::releaseAllSessions(){
byte sesid;
logger->debug("[%d] [tcpClient] Releasing all sessions",id);
releaseActualSession();
std::map<int,edSession*>::iterator it = this->sessions.begin();
while(it != this->sessions.end())
{
if (it->second->isSessionSet()){
logger->info("[%d] [tcpClient] Releasing session for loco %d" ,id, it->second->getLoco());
sesid = it->second->getSession();
sendCbusMessage(OPC_KLOC, sesid);
}
it++;
}
//clear sessions
usleep(1000*500);//500ms
it = this->sessions.begin();
logger->info("[%d] [tcpClient] Dealocating sessions" ,id);
while(it != this->sessions.end())
{
if (it->second->isSessionSet()){
logger->info("[%d] [tcpClient] Dealocating loco %d" ,id, it->second->getLoco());
}
session_handler->deleteEDSession(it->second->getSessionUid());
sessions.erase(it);
it++;
}
}
void tcpClient::releaseActualSession(){
if (edsession->isSessionSet()){
logger->info("[%d] [tcpClient] Releasing session for loco %d" ,id, edsession->getLoco());
sendCbusMessage(OPC_KLOC, edsession->getSession());
}
if (sessions.find(edsession->getLoco()) != sessions.end()){
sessions.erase(edsession->getLoco());
}
session_handler->deleteEDSession(edsession->getSessionUid());
}
void tcpClient::deleteUnsetSessions(){
logger->debug("[%d] [tcpClient] Deleting all unset sessions",id);
std::map<int,edSession*>::iterator it = this->sessions.begin();
while(it != this->sessions.end())
{
if (!it->second->isSessionSet()){
logger->info("[%d] [tcpClient] Deleting unset session %d" ,id, it->second->getSessionUid());
session_handler->deleteEDSession(it->second->getSessionUid());
//delete(it->second);
sessions.erase(it);
}
it++;
}
}
void tcpClient::handleDirection(string message){
logger->debug("[%d] [tcpClient] Handle Direction request %s",id, message.c_str());
sendToEd(message + "\n");
//get the direction
int i = message.find(">R");
logger->debug("[%d] [tcpClient] Extracted direction: %s" , id, message.substr(i+2,1).c_str());
byte d = atoi(message.substr(i+2,1).c_str());
i = message.find("*");
char stype = message.c_str()[1];
//all sessions
if (i > 0){
logger->debug("[%d] [tcpClient] Set direction for all sessions",id);
std::map<int,edSession*>::iterator it = sessions.begin();
while(it != sessions.end())
{
if (stype == it->second->getSessionType()){
it->second->setDirection(d);
logger->debug("[%d] [tcpClient] Set direction %d for loco %d" ,id, d ,it->second->getLoco());
sendCbusMessage(OPC_DSPD,it->second->getSession(),d*BS+it->second->getSpeed());
}
it++;
}
return;
}
//one session
int loco = getLoco(message);
if (sessions.find(loco) != sessions.end()){
int sesid = sessions[loco]->getSession();
sessions[loco]->setDirection(d);
logger->debug("[%d] [tcpClient] Set direction %d for loco %d" ,id, d ,loco);
int speed = sessions[loco]->getSpeed();
if (speed == 1) speed++;
sendCbusMessage(OPC_DSPD,sesid, d * BS + speed);
}
else logger->debug("[%d] [tcpClient] Loco %d not allocated" ,id,loco);
}
void tcpClient::handleSpeed(string message){
string speedString;
logger->debug("[%d] [tcpClient] Handle speed request %s",id, message.c_str());
int i = message.find(">V");
if (i > 0){
int s = i + 2;
logger->debug("[%d] [tcpClient] Extracted speed: %s",id, message.substr(s,message.length()-s).c_str());
speedString = message.substr(s,message.length()-s);
}
else{
i = message.find(">X");
if (i > 0) speedString = "X";
else{
logger->debug("[%d] [tcpClient] Bad speed message format. Discarding.",id);
return;
}
}
int speed = 0;
int edspeed = 0;
if (speedString == "X"){//emergency stop
speed = 1;
edspeed = 0;
}
else{
speed = atoi(speedString.c_str());
edspeed = speed;
if (speed == 1){//can't send speed 1 (emergency stop) to cancmd
speed++;
}
}
stringstream ss;
i = message.find("*");
char stype = message.c_str()[1];
//all sessions
if (i > 0){
logger->debug("[%d] [tcpClient] Set speed %d for all sessions",id,edspeed);
std::map<int,edSession*>::iterator it = sessions.begin();
while(it != sessions.end())
{
if (stype == it->second->getSessionType()){
it->second->setSpeed(edspeed);
logger->debug("[%d] Set speed %d for loco %d" ,id,edspeed, it->second->getLoco());
sendCbusMessage(OPC_DSPD, it->second->getSession(), it->second->getDirection() * BS + speed);
usleep(1000*10);//wait 10ms
}
it++;
}
sendToEd(message);
return;
}
//one session
int loco = getLoco(message);
if (sessions.find(loco) != sessions.end()){
edSession* session = sessions[loco];
logger->debug("[%d] [tcpClient] Set speed %d for loco %d" ,id,edspeed, loco);
session->setSpeed(edspeed);
sendCbusMessage(OPC_DSPD, session->getSession(), session->getDirection() * BS + speed);
ss.clear();ss.str();
ss << "M";
ss << session->getSessionType();
ss << "A";
ss << session->getAddressType();
ss << session->getLoco();
ss << DELIM_BTLT;
ss << "V";
ss << edspeed;
ss << "\n";
sendToEd(ss.str());
usleep(1000*10);//wait 10ms
}
else logger->debug("[%d] [tcpClient] Loco %d not allocated" ,id,loco);
}
void tcpClient::handleIdle(string message){
string speedString;
int edspeed = 0;
stringstream ss;
logger->debug("[%d] [tcpClient] Handle idle request %s",id, message.c_str());
int i = message.find("*");
char stype = message.c_str()[1];
//all sessions
if (i > 0){
logger->debug("[%d] [tcpClient] Set speed %d for all sessions",id,edspeed);
std::map<int,edSession*>::iterator it = sessions.begin();
while(it != sessions.end())
{
if (stype == it->second->getSessionType()){
it->second->setSpeed(edspeed);
logger->debug("[%d] Set speed %d for loco %d" ,id,edspeed, it->second->getLoco());
sendCbusMessage(OPC_DSPD, it->second->getSession(), it->second->getDirection() * BS + edspeed);
usleep(1000*10);//wait 10ms
}
it++;
}
sendToEd("\n");
return;
}
//one session
int loco = getLoco(message);
if (sessions.find(loco) != sessions.end()){
edSession* session = sessions[loco];
logger->debug("[%d] [tcpClient] Set speed %d for loco %d" ,id,edspeed, loco);
session->setSpeed(edspeed);
sendCbusMessage(OPC_DSPD, session->getSession(), session->getDirection() * BS + edspeed);
ss.clear();ss.str();
ss << "M";
ss << session->getSessionType();
ss << "A";
ss << session->getAddressType();
ss << session->getLoco();
ss << DELIM_BTLT;
ss << "V";
ss << edspeed;
ss << "\n";
usleep(1000*10);//wait 10ms
}
else logger->debug("[%d] [tcpClient] Loco %d not allocated" ,id,loco);
sendToEd("\n");
}
void tcpClient::handleQueryDirection(string message){
logger->debug("[%d] [tcpClient] Query Direction found %s",id, message.c_str());
int i = message.find("*");
char stype = message.c_str()[1];
stringstream ss;
ss.str("");
if (i > 0){
logger->debug("[%d] [tcpClient] Query direction for all locos",id);
std::map<int,edSession*>::iterator it = sessions.begin();
while(it != sessions.end())
{
if (stype == it->second->getSessionType()){
ss << "M";
ss << it->second->getSessionType();
ss << "A";
ss << it->second->getAddressType();
ss << it->second->getLoco();
ss << DELIM_BTLT;
ss << "R";
ss << (int)it->second->getDirection();
ss << "\n";
}
it++;
}
sendToEd(ss.str());
return;
}
//specific loco
int loco = getLoco(message);
if (sessions.find(loco) != sessions.end()){