-
Notifications
You must be signed in to change notification settings - Fork 12
/
EmulatePioneer.cc
2526 lines (2215 loc) · 89.2 KB
/
EmulatePioneer.cc
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
/*
*
* Copyright (C) 2005, ActivMedia Robotics
* Copyright (C) 2006-2010 MobileRobots, Inc.
* Copyright (C) 2011-2015 Adept Technology
* Copyright (C) 2016-2017 Omron Adept Technologies
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "MobileSim.hh"
#include "EmulatePioneer.hh"
#include "MapLoader.hh"
#include "ArMap.h"
#include "ArGPSCoords.h"
#include <unistd.h>
#include <string.h>
#include <vector>
#include <stdint.h>
#include <string>
#include <assert.h>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <netinet/in.h>
#include <sys/select.h>
#endif
#include <signal.h>
/* Some useful classes from Aria */
#include "ArCommands.h"
#include "ArSocket.h"
#include "ArFunctor.h"
#include "ArTcpConnection.h"
#include "ArRobotPacket.h"
#include "ArRobotPacketSender.h"
#include "ClientPacketReceiver.h"
#include "MobileSim.hh"
#include "Socket.hh"
/* Turn these on to get debugging messages: */
//#define DEBUG_SIP_VALUES 1 // Every SIP! Very frequent!
//#define DEBUG_SIP_PACKET_CONTENTS 1 // Every SIP! Very frequent, lots of data!
//#define DEBUG_SIP_SONAR_DATA 1
//#define DEBUG_CLIENT_CONNECTION 1
//#define DEBUG_SYNCS 1
//#define DEBUG_COMMANDS_RECEIVED 1 // TODO replace with check for logCommandsReceived flag
// Maximum number of sonar readings to include in one SIP. Note, we don't
// simulated sonar polling timing. This number must be small enough to
// avoid sending a SIP larger than 200 bytes.
#define MAX_SONAR_READINGS_PER_SIP 16
// Amout of time to sleep after failing to open a listening TCP port before trying the same port again. (Note, will block execution during sleep.)
#define TCP_PORT_RETRY_TIME 2000 //ms
// Number of times to try opening the user's desired TCP port to listen for new clients before giving up and trying another port number
#define TCP_PORT_RETRY_LIMIT 3
// How long to allow packet receiver (therefore tcp connection therefore the non-blocking socket) to wait for data before returning if there is none
// If 0, no waiting
#define RECEIVE_WAIT_TIMEOUT 0 //ms
// Issue a warning if the total time it takes to receive a client packet is more than this amout
#define RECEIVE_TIME_WARNING 200 //ms
// How long to allow packet receiver to wait for SYNC packet during client
// handshake. This should be longer than normal RECEIVE_WAIT_TIMEOUT.
#define SYNC_READ_TIMEOUT 200
// Maximum time limit for a whole sync handshake to last. If it goes on this long, give up.
#define SYNC_TIMEOUT 10000
// If we receive no data from a client after this long, close the connection.
#define CLIENT_CONNECTION_TIMEOUT 60000 // ms (60 sec.)
// There are four ways to deal with the sync handshake:
// First is passive, just echo back what the client sends, but warn on out of
// sequence packets. This is done if no preprocessor symbol is defined.
// The last three attempt to enforce correct sequence.
// RESTART_ON_SYNC_ERROR means to restart the handshake over at 0 (this is the spec'ed behavior that
// ARCOS does, and ARIA should deal with.), TOLERATE_SYNC_ERROR is to just try the same sync
// sequence number again, DISCONNECT_ON_SYNC_ERROR is to close the client connection (which is the
// default if neither is defined). In any case, we disconnect if the handshake
// hasn't been successful after 10 seconds (TOLERATE) or iterations (RESTART or
// ignore error) of trying.
//#define RESTART_ON_SYNC_ERROR 1
//#define TOLERATE_SYNC_ERROR 1
//#define DISCONNECT_ON_SYNC_ERROR 1
using namespace std;
unsigned long EmulatePioneer::lifetimeConnectionCount = 0;
unsigned long EmulatePioneer::lifetimeFailedConnectionCount = 0;
std::list<EmulatePioneer*> EmulatePioneer::ourActiveInstances;
std::list<EmulatePioneer*>::iterator EmulatePioneer::ourNextActiveInstance = EmulatePioneer::ourActiveInstances.end();
#define WARN_DEPRECATED(oldname, oldnum, newname, newnum) { \
if(myVerbose) warn("Deprecated simulator %s command (%d) received. Use %s (%d) instead.", oldname, oldnum, newname, newnum); \
}
#define WARN_DEPRECATED_QUIETLY(oldname, oldnum, newname, newnum) { \
if(myVerbose || logCommandsReceived) log("Deprecated simulator %s command (%d) received. Use %s (%d) instead in future versions.", oldname, oldnum, newname, newnum); \
}
std::string toPrintable(unsigned char c)
{
char buf[12];
if(c >= 32 && c <= 126)
{
snprintf(buf, 11, "%02x('%c') ", c, c);
return std::string(buf);
}
if(c == 0x0d) return "0d(CR) ";
if(c == 0x0a) return "0a(LF) ";
if(c == 0x04) return "04(EOF) ";
snprintf(buf, 11, "%02x ", c);
return std::string(buf);
}
/** The first byte of a command indicates the type of the following argument */
class ArgTypes
{
public:
enum {
POSINT = 0x3B,
NEGINT = 0x1B,
STRING = 0x2B
};
};
/** Some commands for partial compatability with SRISim */
enum
{
OLD_LRF_ENABLE = 35,
OLD_LRF_CFG_START = 36,
OLD_LRF_CFG_END = 37,
OLD_LRF_CFG_INC = 38,
OLD_END_SIM = 62,
OLD_SET_TRUE_X = 66,
OLD_SET_TRUE_Y = 67,
OLD_SET_TRUE_TH = 68,
OLD_RESET_TO_ORIGIN = 69
};
bool EmulatePioneer::mapMasterEnabled = false;
// Constructor:
// Retrieve options from the configuration file, and get ready to open
// TCP socket to listen on. Call openSocket() to start listening for a client; when client is accepted, the listening socket is temporarily closed until client closes connection, then it is reopened.
EmulatePioneer::EmulatePioneer(RobotInterface* rif, std::string robotName,
int port, bool deleteOnDisconnect, bool trySubsequentPorts, const MobileSim::Options *userOptions) :
LogInterface(robotName),
status(0),
robotInterface(rif),
myTCPPort(port),
myRequestedTCPPort(port),
myClientSocket(NULL),
portOpened(false),
sessionActive(false),
//myClientDisconnectCB(this, &EmulatePioneer::endSession),
session(0),
haveInitialPose(false),
myApplicationName(""), myApplicationVersion(""),
myDeleteOnDisconnect(deleteOnDisconnect),
myDeleteClientSocketOnDisconnect(false),
myTrySubsequentPorts(trySubsequentPorts),
myVerbose(false),
myListenAddress(""),
logCommandsReceived(false),
logSIPsSent(false),
SRISimCompat(false),
SRISimLaserCompat(true),
newMapLoadedCB(this, &EmulatePioneer::newMapLoaded),
handlePacketCB(this, &EmulatePioneer::handlePacket),
readInputCB(this, &EmulatePioneer::readClientInput),
acceptClientCB(this, &EmulatePioneer::acceptNewClient),
useListenSocket(true),
warn_unsupported_commands(false)
{
init(robotName, userOptions);
}
// Constructor: just set our client socket, assumed to already be connected
// to a client
EmulatePioneer::EmulatePioneer(RobotInterface *rif, std::string robotName, ArSocket *clientSocket,
bool deleteOnDisconnectOnDisconnect, bool deleteClientSocketOnDisconnect, const MobileSim::Options *userOptions) :
LogInterface(robotName),
status(0),
robotInterface(rif),
myTCPPort(-1),
myRequestedTCPPort(-1),
myClientSocket(clientSocket),
portOpened(false),
sessionActive(false),
//myClientDisconnectCB(this, &EmulatePioneer::endSession),
session(NULL),
haveInitialPose(false),
myApplicationName(""), myApplicationVersion(""),
myDeleteOnDisconnect(deleteOnDisconnectOnDisconnect),
myDeleteClientSocketOnDisconnect(deleteClientSocketOnDisconnect),
myTrySubsequentPorts(false), // irrelevant in this mode, actually.
myVerbose(false),
myListenAddress(""),
logCommandsReceived(false),
logSIPsSent(false),
SRISimCompat(false),
SRISimLaserCompat(true),
newMapLoadedCB(this, &EmulatePioneer::newMapLoaded),
handlePacketCB(this, &EmulatePioneer::handlePacket),
readInputCB(this, &EmulatePioneer::readClientInput),
acceptClientCB(this, &EmulatePioneer::acceptNewClient),
useListenSocket(false),
warn_unsupported_commands(false)
{
init(robotName, userOptions);
//print_debug("EmulatePioneer[%p]::EmulatePioneer(): handlePacketCB = %p", this, &handlePacketCB);
//print_debug("EmulatePioneer[%p]::EmulatePioneer(): readInputCB = %p", this, &readInputCB);
//print_debug("EmulatePioneer[%p]::EmulatePioneer(): acceptClientCB = %p", this, &acceptClientCB);
//ArLog::log(ArLog::Normal, "EmulatePioneer::EmulatePioneer(): recording robotInterface (%u) and &newMapLoadedCB (%u) in constructor", (unsigned int)robotInterface, (unsigned int)&newMapLoadedCB);
MobileSim::Sockets::addSocketCallback(clientSocket, &readInputCB, "EmulatePioneer client i/o (callback to handle client input), socket provided in EP ctor");
//print_debug("EmulatePioneer: added input socket callback %p", &readInputCB);
newSession();
// Register the newMapLoadedCB with mapLoader
//ArLog::log(ArLog::Normal, "EmulatePioneer::EmulatePioneer(): adding callback: %p", (void*)&newMapLoadedCB);
mapLoader.addCallback(&newMapLoadedCB);
}
void EmulatePioneer::init(const std::string& robotName, const MobileSim::Options *userOptions)
{
//++currentEmulatorCount;
memset(params.RobotName, 0, ROBOT_IDENTIFIER_LEN);
strncpy(params.RobotName, robotName.c_str(), ROBOT_IDENTIFIER_LEN);
robotInterface->setBatteryVoltage(DEFAULT_BATTERY_VOLTAGE);
robotInterface->setStateOfCharge(DEFAULT_STATE_OF_CHARGE);
robotInterface->setDigoutState(DEFAULT_DIGOUT_STATE);
robotInterface->setDiginState(DEFAULT_DIGIN_STATE);
if(userOptions)
{
setVerbose(userOptions->verbose);
setSRISimCompat(userOptions->srisim_compat, userOptions->srisim_laser_compat);
setWarnUnsupportedCommands(userOptions->warn_unsupported_commands);
setLogPacketsReceived(userOptions->log_packets_received);
setLogSIPsSent(userOptions->log_sips_sent);
setCommercialRelease(userOptions->commercial);
setCommandsToIgnore(userOptions->ignore_commands);
}
}
// object to handle deletion of EmulatePioneer instances from outside an EmulatePioneer object:
void EmulatePioneer::DeletionRequest::doDelete()
{
//print_debug("EmulatePioneer deletion request: removing from active list and deleting");
if(instance) {
EmulatePioneer::ourActiveInstances.remove(instance);
delete instance;
}
}
EmulatePioneer::~EmulatePioneer()
{
//ArLog::log(ArLog::Normal, "EmulatePioneer::~EmulatePioneer(): deleting robotInterface (%u) and &newMapLoadedCB (%u)", (unsigned int)robotInterface, (unsigned int)&newMapLoadedCB);
// Trying to NULLify the MapLoader's callback. MapLoader will heed this
// request ONLY IF this instance's newMapLoadedCB matches the one saved
// inside mapLoader
//ArLog::log(ArLog::Normal, "EmulatePioneer::~EmulatePioneer(): removing callback: %p", (void*)&newMapLoadedCB);
//mapLoader.nullifyCallback(&newMapLoadedCB);
mapLoader.removeCallback(&newMapLoadedCB);
//std::string name = robotInterface->getRobotName();
//printf("*** ~EmulatePioneer %s...\n", name.c_str()); fflush(stdout);
sessionActive = false;
if(myDeleteOnDisconnect && robotInterface)
{
//print_debug("Deleting robot interface %p...", robotInterface);
delete robotInterface;
robotInterface = NULL;
//print_debug("Deleted robot interface.");
}
if(myClientSocket)
MobileSim::Sockets::removeSocketCallback(myClientSocket);
if(myDeleteClientSocketOnDisconnect && myClientSocket)
{
delete myClientSocket;
myClientSocket = NULL;
}
MobileSim::Sockets::removeSocketCallback(&myListenSocket);
//ourActiveInstances.remove(this); removed in processAll()
//--currentEmulatorCount;
//printf("*** ~EmulatePioneer %s done!\n", name.c_str()); fflush(stdout);
}
int EmulatePioneer::getPort() const
{
return myTCPPort;
}
Session::Session() :
requestedOpenSonar(false),
inWatchdogState(false),
eStopInProgress(false),
sendingSimstats(false),
syncSeq(0),
handshakeAttempt(0),
packetsSent(0),
packetsReceived(0)
{
started.setToNow();
}
bool EmulatePioneer::openSocket()
{
//print_debug("opening socket");
// close socket if open
if(myListenSocket.isOpen())
{
// remove from global Sockets list. When re-opened (new actual socket) below, callback is added again.
MobileSim::Sockets::removeSocketCallback(&myListenSocket);
myListenSocket.close();
}
portOpened = false;
// First try a few times to open the requested port (it may still be allocated by OS
// to a previous (recently closed) MobileSim process.
// After opening socket, it's added to global Sockets list at the end of this
// fuction.
myRequestedTCPPort = myTCPPort;
for(size_t i = 0; i < TCP_PORT_RETRY_LIMIT; ++i)
{
if(myListenSocket.open(myTCPPort, ArSocket::TCP, (myListenAddress == "" ? NULL : myListenAddress.c_str())))
{
portOpened = true;
inform("Port opened. Listening on TCP port %d... [%d]", myTCPPort, myListenSocket.getFD());
break;
}
inform("TCP port %d unavailable. Trying again in %d seconds...", myTCPPort, TCP_PORT_RETRY_TIME/1000);
ArUtil::sleep(TCP_PORT_RETRY_TIME);
}
// Couldn't open requested port.
// Keep trying until we get an open port or hit the
// upper limit for TCP ports
if(!portOpened)
{
for(++myTCPPort; myTrySubsequentPorts && myTCPPort <= 65535; ++myTCPPort)
{
inform("Trying TCP port %d...", myTCPPort);
if(myListenSocket.open(myTCPPort, ArSocket::TCP, (myListenAddress == "" ? NULL : myListenAddress.c_str())) )
{
portOpened = true;
inform("Port opened. Listening on TCP port %d... [%d]", myTCPPort, myListenSocket.getFD());
break;
}
}
}
if(!portOpened) {
error("Could not open a TCP port!");
return false;
}
if(myRequestedTCPPort != myTCPPort)
warn("Requested TCP port %d was unavailable. Using %d instead.", myRequestedTCPPort, myTCPPort);
if(myListenAddress != "")
inform("Ready for a client to connect to address %s on TCP port %d.", myListenAddress.c_str(), myTCPPort);
else
inform("Ready for a client to connect on TCP port %d.", myTCPPort);
myListenSocket.setReuseAddress();
myListenSocket.setNonBlock();
MobileSim::Sockets::addSocketCallback(&myListenSocket, &acceptClientCB, "EmulatePioneer listening socket (callback to accept clients)");
return true;
}
void EmulatePioneer::acceptNewClient(unsigned int /*maxTime*/)
{
if(myClientSocket) return; // already have a client socket
// Accept new client if one is trying to connect
myClientSocket = new ArSocket();
//print_debug("EmulatePioneer[%p]::acceptNewClient(): new client socket %p", this, myClientSocket);
myDeleteClientSocketOnDisconnect = true;
if(!myListenSocket.accept(myClientSocket))
{
warn("Error accepting client connection.");
delete myClientSocket;
myClientSocket = NULL;
return;
}
if(!myClientSocket->isOpen())
{
warn("Error accepting client connection (socket closed after accept).");
// No client connected
delete myClientSocket;
myClientSocket = NULL;
return;
}
inform("Client connected from %s (%s)", myClientSocket->getHostName().c_str(), myClientSocket->getIPString());
// Close listening socket to prevent other clients from screwing it up by
// trying to connect.
MobileSim::Sockets::removeSocketCallback(&myListenSocket);
myListenSocket.close();
myClientSocket->setNonBlock();
#ifdef DEBUG_CLIENT_CONNECTION
//print_debug("Accepted a new client. Client TCP socket fd %d.", myClientSocket->getFD());
// fflush(stdout);
#endif
MobileSim::Sockets::addSocketCallback(myClientSocket, &readInputCB, "EmulatePioneer client I/O (callback to read input), socket created by EP listening");
newSession();
return;
}
void EmulatePioneer::newSession()
{
// Replacing session with new one
// TODO fix Session copy constructors so we can have slightly faster access to session
// contents (don't use new and don't have to always dereference the pointer)
//session = Session();
if(session) delete session;
session = new Session();
//print_debug("EmulatePioneer[%p]::newSession(): new session %p", this, session);
log("Starting new session");
robotInterface->connect(¶ms);
robotInterface->setOdom(0, 0, 0);
if(!haveInitialPose)
{
// Only set these once, but we need to have set up the robot interface
// before using it.
long z;
robotInterface->getSimulatorPose(initialPoseX, initialPoseY, z, initialPoseTheta);
haveInitialPose = true;
}
session->handshakeAttempt = 0;
session->syncStart.setToNow();
session->connection.setSocket(myClientSocket);
session->connection.setStatus(ArDeviceConnection::STATUS_OPEN);
session->packetReceiver.setSocket(myClientSocket); //DeviceConnection(&(session->connection));
session->packetReceiver.setProcessPacketCB(&handlePacketCB);
session->packetSender.setDeviceConnection(&(session->connection));
sessionActive = true;
}
void EmulatePioneer::readClientInput(unsigned int maxTime)
{
if(!session || !myClientSocket || !sessionActive)
return;
try {
if(!session->packetReceiver.readData((int)maxTime)) // will call handlePacket() for each packet received.
{
warn("Error reading client data. Ending session.");
endSession();
}
} catch(Disconnected&) {
ourActiveInstances.remove(this);
}
}
void EmulatePioneer::handlePacket(ArRobotPacket *pkt) throw(DeletionRequest, Disconnected)
{
if(!session)
{
warn("Session unexpectedly ended.");
//print_debug("session unexpectedly ended.");
endSession();
return;
}
if(!sessionActive)
{
//print_debug("handlePacket: client disconnected. closing connection.");
if(session->syncSeq < 3)
warn("Client disconnected during SYNC%d. Closing connection.", session->syncSeq);
else
warn("Client disconnected (while trying to handle packet with command %d)", pkt->getID());
++lifetimeFailedConnectionCount;
endSession();
return;
}
session->gotPacket();
// If still in handshake, expect SYNC packets, else handle as a client command.
if(session->syncSeq < 3)
handleSyncPacket(pkt);
else
handleCommand(pkt);
}
bool EmulatePioneer::handleSyncPacket(ArRobotPacket *pkt) throw (DeletionRequest, Disconnected)
{
if(session->handshakeAttempt++ >= 10)
{
warn("Failed to handshake after 10 iterations of trying! Closing connection.");
++lifetimeFailedConnectionCount;
endSession();
return false;
}
if(session->syncStart.mSecSince() >= SYNC_TIMEOUT)
{
warn("Failed to handshake after %d sec of trying! Aborting session and closing connection.", session->syncStart.secSince());
++lifetimeFailedConnectionCount;
endSession();
return false;
}
if(myVerbose) log("\t SYNC %d received.", pkt->getID());
if(pkt->getID() != session->syncSeq)
{
#ifdef RESTART_ON_SYNC_ERROR
warn("Recieved out of sequence SYNC packet: got %d, expecting %d. Start again from SYNC0...", pkt->getID(), session->syncSeq);
session->syncSeq = 0;
return true;
#elif defined(TOLERATE_SYNC_ERROR)
warn("Recieved out of sequence SYNC packet: got %d, expecting %d. Sending %d again...", pkt->getID(), syncSeq, session->syncSeq);
session->packetSender.com(session->syncSeq);
return true;
#elif defined(DISCONNECT_ON_SYNC_ERROR)
// Drop connection instead
warn("Recieved out of sequence SYNC packet: got %d, expecting %d. Closing connection.", pkt->getID(), session->syncSeq);
++lifetimeFailedConnectionCount;
return false;
#else
// just warn and use the client's sequence.
warn("Recieved out of sequence SYNC packet: got %d, expecting %d. Will send %d.", pkt->getID(), session->syncSeq, pkt->getID());
session->syncSeq = pkt->getID();
#endif
}
else
{
//warn("JON_DEBUG: \t SYNC %d received (meets expectation).", pkt->getID());
}
if(!pkt->verifyCheckSum())
{
#ifdef RESTART_ON_SYNC_ERROR
warn("Recieved SYNC%d packet with bad checksum. Start again from SYNC0...", pkt->getID());
session->syncSeq = 0;
return true;
#elif defined(TOLERATE_SYNC_ERROR)
warn("Recieved SYNC%d packet with bad checksum. Sending %d again...", pkt->getID(), session->syncSeq);
session->packetSender.com(session->syncSeq);
return true;
#elif defined (DISCONNECT_ON_SYNC_ERROR)
// Drop connection instead
warn("Recieved SYNC%d packet with bad checksum. Closing connection.", pkt->getID());
++lifetimeFailedConnectionCount;
endSession();
return false;
#else
warn("Recieved SYNC%d packet with bad checksum (ignored).", pkt->getID());
#endif
}
// OK, reply
if(session->syncSeq == 2)
{
if (myVerbose) log("Sending SYNC2 with robot config info.");
ArRobotPacket pkt;
pkt.setID(2);
pkt.strToBuf("MobileSim");
pkt.strToBuf(params.RobotClass);
pkt.strToBuf(params.RobotSubclass);
pkt.finalizePacket();
//print_debug("writing config info to connection...");
if(session->connection.write(pkt.getBuf(), pkt.getLength()) == -1)
{
warn("Error sending robot indentification strings to the client. Closing connection.");
endSession();
return false;
}
session->sentPacket();
// print_debug("sent config info.");
beginSession();
}
else
{
if(myVerbose) log("Sending SYNC%d...", session->syncSeq);
if(!session->packetSender.com((unsigned char)session->syncSeq))
{
warn("Error sending SYNC%d! Closing connection.", session->syncSeq);
++lifetimeFailedConnectionCount;
endSession();
return false;
}
session->sentPacket();
}
++(session->syncSeq);
//print_debug("now on syncSeq %d. (sessionActive=%d)", session->syncSeq, sessionActive);
return true;
}
bool EmulatePioneer::beginSession()
{
//puts("beginSession()");fflush(stdout);
++lifetimeConnectionCount;
session->init(robotInterface, ¶ms, logSIPsSent);
// ARIA assumes sonar are on at start:
robotInterface->openSonar();
// robotInterface->setBatteryVoltage(DEFAULT_BATTERY_CHARGE); // todo make this default value configurable in world file.
//robotInterface->setHaveTemperature(false); // todo make this default value configurable in world file.
ourActiveInstances.push_back(this);
//print_debug("**** beginSession(): ourActiveInstances.size() is now %d.", ourActiveInstances.size());
return true;
}
int EmulatePioneer::processAll(int maxTime)
{
//printf("processAll(%d) ourActiveInstances.size()==%d\n", maxTime, ourActiveInstances.size());
if(ourActiveInstances.size() == 0)
return IDLE;
if(maxTime < 0)
maxTime = 0;
ArTime t;
t.setToNow();
int allStat = 0;
std::list<EmulatePioneer*>::size_type n = 0;
//if(ourNextActiveInstance == ourActiveInstances.end())
// ourNextActiveInstance = ourActiveInstances.begin();
std::list<EmulatePioneer*>::iterator i = ourNextActiveInstance;
//unsigned int timeshare = maxTime / ourActiveInstances.size();
do {
// wrap to beginning of list if neccesary
if(i == ourActiveInstances.end())
{
i = ourActiveInstances.begin();
}
// time to stop?
if(maxTime > 0 && t.mSecSince() >= maxTime)
{
ourNextActiveInstance = ++i;
break;
}
EmulatePioneer *ep = *i;
// process session, delete object if requested
if( ep == NULL ) {
print_warning("EP::processAll: Encountered NULL EmulatePioneer* instance! Ignoring");
continue;
}
// Another way to do this other than using exceptions is to have a separate top-level EmulatePioneer
// function that goes through the active list and checks their 'status' members, and does the
// deletion/removal then. This function would have to be called from the main loop in main().
int status = 0;
try
{
ep->processSession();
status = ep->status;
//print_debug("EP::processAll: after processSession(%p). Status=0x%x (%s) [DISCONNECTED=%p, DELETEME=%p, DISCONNECTED|DELETEME=%p]", ep, status, MobileSim::byte_as_bitstring(status).c_str(), DISCONNECTED, DELETEME, DISCONNECTED|DELETEME);
if(status & DISCONNECTED)
{
//print_debug("EP::processAll: after processSession: %p disconnected. Status=0x%x (%s) [DISCONNECTED=%p, DELETEME=%p, DISCONNECTED|DELETEME=%p]", ep, status, MobileSim::byte_as_bitstring(status).c_str(), DISCONNECTED, DELETEME, DISCONNECTED|DELETEME);
//print_debug("EP::processAll: after processSession: removing %p from active list...", ep);
i = ourActiveInstances.erase(i); // remove from ourActiveInstances and advance to next
if(status & DELETEME)
{
//print_debug("EP::processAll: Also deleting instance (status included DELETEME)");
//delete ep;
print_debug("!!!!!!!!! EP::processAll: why did it not throw? !!!!!!!!!!!"); exit(-99);
}
}
else
{
++i; // advance through ourActiveInstances normally
}
}
catch(EmulatePioneer::DeletionRequest&) // from ep->processSession()
{
status = ep->status;
//print_debug("EP::processAll: catch: %p wants to be deleted. Status=0x%x (%s) [DISCONNECTED=%p, DELETEME=%p, DISCONNECTED|DELETEME=%p]", ep, status, MobileSim::byte_as_bitstring(status).c_str(), DISCONNECTED, DELETEME, DISCONNECTED|DELETEME);
//print_debug("EP::processAll: catch: removing %p from active list and deleting...", ep);
i = ourActiveInstances.erase(i); // remove from ourActiveInstances and advance to next
delete ep;
}
catch(EmulatePioneer::Disconnected&)
{
//print_debug("EP::processAll: catch: %p disconnected. Status=0x%x (%s) [DISCONNECTED=%p, DELETEME=%p, DISCONNECTED|DELETEME=%p]", ep, status, MobileSim::byte_as_bitstring(status).c_str(), DISCONNECTED, DELETEME, DISCONNECTED|DELETEME);
//print_debug("EP::processAll: catch: removing %p from active list...", ep);
i = ourActiveInstances.erase(i);
}
catch(...)
{
print_debug("unknown exception in EmulatePioneer::processAll!");
exit(-99);
}
allStat |= status;
++n;
if(ourActiveInstances.size() == 0)
break;
} while(i != ourNextActiveInstance); // stop if we've wrapped around
if(n < ourActiveInstances.size())
{
print_warning("Processed only %zu out of %zu clients in one loop. This may indicate too many clients, network problems, or some other problem. (The other clients will be processed in next loop.)", n, ourActiveInstances.size());
}
return allStat;
}
bool EmulatePioneer::processSession() throw (DeletionRequest, Disconnected)
{
ArTime time;
status = 0;
/*
if(session && session->syncSeq < 3)
print_debug("time since syncStart is %d ms...", session->syncStart.mSecSince());
// If we're still in SYNC, check to make sure it hasn't timed out.
if(session && session->syncSeq < 3 && session->syncStart.mSecSince() >= SYNC_TIMEOUT)
{
warn("Failed handshake after %d sec of trying! Aborting session and closing connection.", session->syncStart.secSince());
++lifetimeFailedConnectionCount;
endSession();
return false;
}
*/
if(!sessionActive || !session)
{
// Either still in SYNC and newSession() hasn't been called yet, or for processSession() was called after endSession() [which should NOT happen]
//print_debug("EmulatePioneer::processSession: client not connected. returning.");
return true;
}
// If it's been too long since we received a command,
// warn (like the robot's watchdog behavior, but don't stop).
// If it's been way too long, // exit.
if(params.WatchdogTime != 0 && session->gotLastValidCommand.mSecSince() > params.WatchdogTime && !session->inWatchdogState)
{
warn("Have not received a valid command packet in %d msec. (Watchdog timeout is %d msec.) [no action taken other than this warning]",
session->gotLastValidCommand.mSecSince(), params.WatchdogTime);
//robotInterface->stop(); // BUG if we want to do this, we need to resume last motion command when communications are restored
session->inWatchdogState = true;
}
// check for client timeout
if(session->gotLastCommand.mSecSince() > CLIENT_CONNECTION_TIMEOUT)
{
warn("Have not received any data from client in %.1f sec, ", (double)(session->gotLastCommand.mSecSince())/1000.0);
// rh 3/21/2012 we decided not to close connection due to this timeout.
//warn("Ending session.");
//endSession();
return false;
}
// check if we are done performing an estop (Fast stop)
if(session->eStopInProgress)
{
int x, y, theta;
robotInterface->getVelocity(x, y, theta);
if(x == 0 && y == 0 && theta == 0)
{
if(myVerbose)
inform("Done ESTOPping");
session->eStopInProgress = false;
}
}
// Send next set of periodic data packets
// if(session->sentLastSIP.mSecSince()+timeshare/4 >= params.SIPFreq)
{
// Send SIMSTAT if requested
if(session->sendingSimstats)
{
if(!sendSIMSTAT(&session->connection))
{
warn("Error sending SIMSTAT packet to a client. Stopping.");
session->sendingSimstats = false;
}
else
session->sentPacket();
}
ArRobotPacket* sip = session->sipGen.getPacket();
// NOTE if session->sipGen returns NULL because SIP packets were disabled by
// calling session->sipGen.stop(), then we may never know that a client is
// disconnected because we will never get an error on write. This is OK
// if the only time session->sipGen.stop() is called, is from a CLOSE command,
// since the client connection is forced closed then anyway.
if(sip)
{
//print_debug("Sending SIP; %ld ms since last", session->sentLastSIP.mSecSince());
if(sip->getLength() > 200)
warn("I'm sending a SIP that's more than 200 bytes long (%d bytes)! (This violates the protocol and ought not happen.)", sip->getLength());
//puts("sending SIP");fflush(stdout);
int fd = session->connection.getSocket()->getFD();
if(session->connection.write(sip->getBuf(), sip->getLength()) < 0)
{
warn("Error sending SIP to client. Closing connection. (fd=%d)", fd);
endSession();
return false;
}
session->sentPacket();
status |= SENTDATA;
}
session->sentLastSIP.setToNow();
//puts("SENT SIP");
// Send all pending laser packets (only some data is in each packet)
while(ArRobotPacket* laserPkt = session->laserGen.getPacket())
{
int fd = session->connection.getSocket()->getFD();
if(session->connection.write(laserPkt->getBuf(), laserPkt->getLength()) == -1)
{
warn("Error sending laser packet to client. Closing connection. (fd=%d)", fd);
endSession();
return false;
}
session->sentLaserPacket();
status |= SENTDATA;
}
}
if(MobileSim::log_stats_freq > 0) {
session->checkLogStats(this);
}
return true;
} // end processSession()
// Command implementations:
bool EmulatePioneer::handleCommand(ArRobotPacket *pkt) throw (DeletionRequest, Disconnected)
{
//printf("handling command packet with ID %d", pkt->getID());fflush(stdout);
if(logCommandsReceived)
{
robotInterface->log("Received packet with id %d (0x%x), length given as %d (%d bytes of data)", pkt->getID(), pkt->getID(), pkt->getLength(), pkt->getDataLength());
}
if(session->inWatchdogState)
{
inform("Data reception restored, watchdog warning reset.");
session->inWatchdogState = false;
// BUG if were previously inWatchdogState, ought to resume previous motion
// commands.
}
// should we ignore this command
if(myCommandsToIgnore.find(pkt->getID()) != myCommandsToIgnore.end())
{
if(myVerbose) warn("Ignoring command %d, as requested in program options.", pkt->getID());
return true;
}
char argType;
int intVal;
unsigned int index;
int x, y, th;
char byte1, byte2, byte3;
double left, right;
const int charbuf_maxlen = 128;
char charbuf[charbuf_maxlen];
char c;
unsigned char len;
unsigned char ubyte1, ubyte2;
ArRobotPacket replyPkt;
///@todo make this more robust against bad commands and warn (useful for
//debugging bugs in client programs too). check arg type, check packet
//size. might need a fancier command->function map than just switch soon.
switch(pkt->getID())
{
case ArCommands::PULSE:
break;
case ArCommands::OPEN:
if(logCommandsReceived) robotInterface->log("\tOPEN command");
session->sipGen.start();
break;
case ArCommands::CLOSE:
inform("Got CLOSE command, closing connection.");
session->sipGen.stop();
endSession();
//print_debug("CLOSE: ended session."); fflush(stdout);
//puts("CLOSE: ended session."); fflush(stdout);
break;
case ArCommands::SONAR:
if(logCommandsReceived) robotInterface->log("\tSONAR command");
argType = pkt->bufToByte();
intVal = pkt->bufToByte2();
if(intVal) {
//inform("Sonar on");
robotInterface->openSonar();
session->requestedOpenSonar = true;
} else {
//inform("Sonar off");
robotInterface->closeSonar();
session->requestedOpenSonar = false;
}
break;
case ArCommands::ENABLE:
argType = pkt->bufToByte();
intVal = pkt->bufToByte2();
if(logCommandsReceived) robotInterface->log("\tENABLE %d", intVal);
robotInterface->enableMotors(intVal);
break;
case ArCommands::VEL:
if(session->eStopInProgress) break;
intVal = getIntFromPacket(pkt);
if(logCommandsReceived) robotInterface->log("\tVEL %4d mm/s", intVal);
robotInterface->transVel(intVal);
break;
case ArCommands::VEL2:
if(session->eStopInProgress) break;
// The byte parameters are signed, but the argument type still
// applies to each, I guess. Consistent, but confusing. The fact
// that it's right,left instead of left,right is just plain
// confusing :)
intVal = getIntFromPacket(pkt);
right = (double)((char)intVal) * params.Vel2DivFactor; // low 8 bits
left = (double)((char)(intVal>>8)) * params.Vel2DivFactor; // high 8 bits
#ifdef DEBUG_COMMANDS_RECIEVED
byte2 = (char)intVal; // low 8 bits
byte1 = (char)(intVal >> 8); // high 8 bits
print_debug("Pioneer emulation: <command> VEL2 = L: %d (=> %.4f mm/s), R: %d (=> %.4f mm/s) [arg type: %d; Vel2Div=%f]", byte2, left, byte1, right, argType, params.Vel2DivFactor);
print_debug("setting rotVel:%f deg/s, transVel:%f mm/s", (float)(ArMath::radToDeg((right - left) / 2.0 ) * params.DiffConvFactor), (float)( (left + right) / 2.0 ));
#endif
robotInterface->rotVel( (int) ( ArMath::radToDeg((right - left) / 2.0) * params.DiffConvFactor ) );
robotInterface->transVel( (int) ( (left + right) / 2.0 ) );
break;