-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathASDP_Core_API.cpp
More file actions
9340 lines (8452 loc) · 332 KB
/
Copy pathASDP_Core_API.cpp
File metadata and controls
9340 lines (8452 loc) · 332 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
/*
* Copyright (C) 2024: Arizona Board of Regents on Behalf of the University of Arizona
*/
#include "ASDP_Core_API.h"
#include "ASDP_SpinFreeQueue.hpp"
#include "ASDP_SpinFreeAccurateTimer.hpp"
#include <string.h> // For memcpy
#include <iostream>
#include <algorithm>
#include <atomic>
#include <vector>
#include <cmath>
#include <stdio.h>
#include <fcntl.h>
#ifdef _WIN32
#include <io.h>
#endif
// Must be defined outside of the namespace.
std::ostream& operator<<(std::ostream& os, const asdp::StreamEndpoint& endpoint) {
os << ((endpoint.IP & (0xff << 24)) >> 24) << "."
<< ((endpoint.IP & (0xff << 16)) >> 16) << "."
<< ((endpoint.IP & (0xff << 8)) >> 8) << "."
<< (endpoint.IP & 0xff)
<< ":" << endpoint.port;
return os;
}
using namespace asdp;
//----------------------------------------------------------------------------
/// Error handling.
std::string asdp::ErrorMessage(Status status)
{
switch (status) {
case OKAY:
return "No error";
case TIMEOUT:
return "Timeout";
case THREAD_COMPLETED:
return "Thread completed";
case BAD_PARAMETER:
return "Bad parameter";
case OUT_OF_MEMORY:
return "Out of memory";
case NOT_IMPLEMENTED:
return "Feature not yet implemented";
case DELETION_FAILED:
return "Pointer deletion failed";
case NULL_OBJECT_POINTER:
return "Object method called with NULL object pointer";
case INTERNAL_EXCEPTION:
return "Exception thrown inside implementation";
case SOCKET_FAILURE:
return "Socket error";
case READ_PAST_END:
return "Attempt to read past end of buffer";
case BAD_COOKIE:
return "Bad magic cookie";
case WRITE_PAST_END:
return "Attempt to write past end of buffer";
case SOCKET_READ_FAILURE:
return "Read error on socket or client buffer too small";
case FILE_FAILURE:
return "File error";
case UNEXPECTED_INTERNAL_STATE:
return "Unexpected internal state";
case INCORRECT_ENDIANNESS:
return "This architecture is not little-endian";
case NOT_CONNECTED:
return "Not connected";
case INCORRECT_FLOAT_SIZE:
return "This architecture does not have 32-bit floats";
case INCOMPATIBLE_API_VERSION:
return "Incompatible API version";
default:
return "Unrecognized error code: " + std::to_string(status);
}
}
/// @brief Helper function to translate from OpCode to a descriptive string.
/// @param opCode The OpCode to translate.
/// @return A descriptive string for the OpCode.
static std::string OpCodeName(OpCode opCode)
{
switch (opCode) {
case RESET: return "RESET";
case START_RECORDING: return "START_RECORDING";
case STOP_RECORDING: return "STOP_RECORDING";
case SET_START_UP_RECORDING_STATE: return "SET_START_UP_RECORDING_STATE";
case START_REPLAY: return "START_REPLAY";
case PAUSE_REPLAY: return "PAUSE_REPLAY";
case RESUME_REPLAY: return "RESUME_REPLAY";
case STOP_REPLAY: return "STOP_REPLAY";
case SET_STREAM_STATE_PERIOD: return "SET_STREAM_STATE_PERIOD";
case SET_NUC_FLAG_STATE: return "SET_NUC_FLAG_STATE";
case START_ON_CAMERA_NUC: return "START_ON_CAMERA_NUC";
case CONFIGURE_TRIGGER: return "CONFIGURE_TRIGGER";
case SOFTWARE_TRIGGER: return "SOFTWARE_TRIGGER";
case SET_EVENT_VERBOSITY: return "SET_EVENT_VERBOSITY";
case STREAM_SUBREGION: return "STREAM_SUBREGION";
case CANCEL_SUBREGION: return "CANCEL_SUBREGION";
case ERASE_ALL_STORED_STREAMS: return "ERASE_ALL_STORED_STREAMS";
case LIST_STORED_STREAMS: return "LIST_STORED_STREAMS";
case ERASE_STORED_STREAM: return "ERASE_STORED_STREAM";
case STREAM_TEMPERATURES: return "STREAM_TEMPERATURES";
case CANCEL_TEMPERATURES: return "CANCEL_TEMPERATURES";
case STREAM_POSES: return "STREAM_POSES";
case CANCEL_POSES: return "CANCEL_POSES";
default: return "UNKNOWN";
}
}
//----------------------------------------------------------------------------
// Definitions of static constants used below.
static const unsigned char MAGIC_COOKIE[4] = { 'A', 'S', 'D', 'P' };
// NOTE: The version number is in the form major.minor.patch, where the first and third are bytes and
// the second is a 16-bit integer. This is done to allow for a large number of minor versions. The
// 16-bit minor version value is stored in little-endian format.
static const unsigned char VERSION[4] = { 8, 7,0, 0 };
static std::string ANALYSIS_STREAM_HEADER = "[{\"Version\":\"01.000.000\"}";
static const uint32_t PACKET_HEADER_TOTAL_SIZE_OFFSET = 0;
static const uint32_t PACKET_BASIC_HEADER_SIZE = sizeof(uint32_t);
static const uint32_t COMMAND_PACKET_OPCODE_OFFSET = PACKET_BASIC_HEADER_SIZE;
static const uint32_t COMMAND_PACKET_BASE_SIZE = PACKET_BASIC_HEADER_SIZE + sizeof(uint32_t);
static const uint32_t STREAM_PACKET_SEQUENCE_NUMBER_OFFSET = PACKET_BASIC_HEADER_SIZE;
static const uint32_t STREAM_PACKET_BASE_SIZE = PACKET_BASIC_HEADER_SIZE + sizeof(uint32_t);
static const uint32_t MESSAGE_BASE_SIZE = 4 * sizeof(uint32_t);
static const uint32_t MESSAGE_HEADER_MESSAGE_TOTAL_SIZE_OFFSET = 0;
static const uint32_t MESSAGE_HEADER_MESSAGE_TIME_SECONDS_OFFSET = sizeof(uint32_t);
static const uint32_t MESSAGE_HEADER_MESSAGE_TIME_MICROSECONDS_SIZE_OFFSET = 2 * sizeof(uint32_t);
static const uint32_t MESSAGE_HEADER_MESSAGE_TYPE_OFFSET = 3 * sizeof(uint32_t);
//----------------------------------------------------------------------------
// Figure out whether we're using Windows sockets or not.
// let's start with a clean slate
#undef ASDP_USE_WINSOCK_SOCKETS
// Does cygwin use winsock sockets or unix sockets? Define this before
// compiling the library if you want it to use WINSOCK sockets.
//#define CYGWIN_USES_WINSOCK_SOCKETS
#if defined(_WIN32) && (!defined(__CYGWIN__) || defined(CYGWIN_USES_WINSOCK_SOCKETS))
#define ASDP_USE_WINSOCK_SOCKETS
#endif
//--------------------------------------
// Architecture-dependent include files.
#ifndef ASDP_USE_WINSOCK_SOCKETS
#include <sys/time.h> // for timeval, timezone, gettimeofday
#include <sys/select.h> // for fd_set
#include <netinet/in.h> // for htonl, htons
#include <netinet/tcp.h> // for TCP_NODELAY
#include <poll.h> // for poll()
#include <netdb.h> // for addrinfo and related functions
#include <unistd.h> // for close()
#include <sys/types.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#endif
#ifdef ASDP_USE_WINSOCK_SOCKETS
// These are a pair of horrible hacks that instruct Windows include
// files to (1) not define min() and max() in a way that messes up
// standard-library calls to them, and (2) avoids pulling in a large
// number of Windows header files. They are not used directly within
// the Sockets library, but rather within the Windows include files to
// change the way they behave.
#ifndef NOMINMAX
#define ASDP_CORESOCKET_REPLACE_NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define ASDP_CORESOCKET_REPLACE_WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h> // struct timeval is defined here
#include "Ws2Tcpip.h"
#pragma comment(lib,"WS2_32")
#ifdef ASDP_CORESOCKET_REPLACE_NOMINMAX
#undef NOMINMAX
#endif
#ifdef ASDP_CORESOCKET_REPLACE_WIN32_LEAN_AND_MEAN
#undef WIN32_LEAN_AND_MEAN
#endif
// Ignore this flag on Windows; it is not defined and also not needed.
#define MSG_NOSIGNAL 0
#endif
//----------------------------------------------------------------------------
// Architecture-dependent definitions.
#ifndef ASDP_USE_WINSOCK_SOCKETS
// On Winsock, we have to use SOCKET, so we're going to have to use it
// everywhere.
typedef int SOCKET;
// On Winsock, INVALID_SOCKET is #defined as ~0 (sockets are unsigned ints)
// We can't redefine it locally, so we have to switch to another name
static const int BAD_SOCKET = -1;
static const int SOCKET_ERROR = -1;
#define closesocket close
#else // not winsock sockets
// Bring the SOCKET type into our namespace, basing it on the root namespace one.
typedef SOCKET SOCKET;
// Make a namespaced INVALID_SOCKET definition, which cannot be just
// INVALID_SOCKET because Windows #defines it, so we pick another name.
static const SOCKET BAD_SOCKET = INVALID_SOCKET;
#endif // winsock sockets
//--------------------------------------------------------------
// Ensures that someone calls WSAStartup on Windows before using
// any socket code.
#if defined(ASDP_USE_WINSOCK_SOCKETS)
class WSAStart {
public:
WSAStart() {
WSADATA wsaData;
int winStatus;
winStatus = WSAStartup(MAKEWORD(1, 1), &wsaData);
if (winStatus) {
std::cerr << "ASDP_Core: Failed to set up sockets: WSAStartup failed with error code " << winStatus << std::endl;
}
}
// We do not call WSACleanup() because we don't know that we're the only
// user of the sockets library.
};
static WSAStart startUp;
#endif
#ifdef ASDP_USE_WINSOCK_SOCKETS
#include <iphlpapi.h>
#pragma comment(lib, "IPHLPAPI.lib")
#endif
//----------------------------------------------------------------------------
// Helper functions.
/// @brief Get the server connection information from a URL.
/// @param [in] URL URL for the server.
/// @param [out] IP IP address of the server.
/// @param [out] port Port number of the server. If one is not specified in the URL, 0 is returned.
static Status ServerInfoFromURL(std::string URL, std::string& IP, uint16_t& port)
{
// Make sure the URL starts with "tcp://".
if (URL.substr(0, 6) != "tcp://") {
return BAD_PARAMETER;
}
// Get the IP address and port.
std::string IPString = URL.substr(6);
size_t colonPos = IPString.find(':');
IP = IPString.substr(0, colonPos);
port = 0;
if (colonPos != std::string::npos) {
std::string portString = IPString.substr(colonPos + 1);
port = std::stoi(portString);
}
return OKAY;
}
uint32_t asdp::GetLocalIPForRemote(uint32_t remote_ip)
{
static uint16_t remote_port = 80;
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
std::cerr << "Failed to create socket\n";
return 0;
}
sockaddr_in remote_addr{};
remote_addr.sin_family = AF_INET;
remote_addr.sin_addr.s_addr = htonl(remote_ip);
remote_addr.sin_port = htons(remote_port);
// Connect to remote address (no packets sent)
if (connect(sock, (sockaddr*)&remote_addr, sizeof(remote_addr)) < 0) {
std::cerr << "Connect failed\n";
closesocket(sock);
return 0;
}
// Get local address used for this connection
sockaddr_in local_addr{};
socklen_t addr_len = sizeof(local_addr);
if (getsockname(sock, (sockaddr*)&local_addr, &addr_len) < 0) {
std::cerr << "getsockname failed\n";
closesocket(sock);
return 0;
}
char ip_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &local_addr.sin_addr, ip_str, sizeof(ip_str));
closesocket(sock);
#ifdef _WIN32
return htonl(local_addr.sin_addr.S_un.S_addr);
#else
return htonl(local_addr.sin_addr.s_addr);
#endif
}
/// @brief Helper function to determine the size of the buffer needed to hold a message,
/// which can include padding to align each line to a 4-byte boundary.
static size_t PaddedSize(size_t nx, size_t ny)
{
size_t padding = 4 - (nx * sizeof(uint16_t)) % 4;
if (padding == 4) { padding = 0; }
return (nx * sizeof(uint16_t) + padding) * ny;
}
/// @brief Helper function to determine how much padding to add to a string after null terminating it.
static size_t PaddingToAdd(const std::string& str)
{
size_t withNull = str.size() + 1;
size_t padding = 4 - (withNull % 4);
if (padding == 4) {
padding = 0;
}
return padding;
}
/// @brief Helper function to determine the size of a buffer needed to hold a string Event parameter.
static size_t PaddedSize(const std::string& str)
{
// If the string is empty, the entire size is 0.
if (str.size() == 0) {
return 0;
}
// Otherwise, add the size of the string plus 1 for the null terminator and padding.
return str.size() + 1 + PaddingToAdd(str);
}
/// @brief Helper function to unpack the version sections.
static void UnpackVersion(const uint8_t *version, uint16_t& major, uint16_t& minor, uint16_t& patch)
{
major = version[0];
minor = version[1] + (version[2] * static_cast<uint16_t>(256));
patch = version[3];
}
/// @brief Helper function to determine the subnet mask for a given IP address.
/// @param [in] ipAddress Address of one of our local NICs.
/// @return The subnet mask for the NIC, or full mask for address not found.
/// This is returned in host byte order.
static uint32_t FindSubnetMask(std::string ipAddress)
{
// We return the fully-filled mask if we can't find the address.
uint32_t ret = ntohl(0xffffffff);
#ifdef ASDP_USE_WINSOCK_SOCKETS
// Get the list of all network interfaces on the system
ULONG bufferLength = 0;
GetAdaptersInfo(NULL, &bufferLength);
IP_ADAPTER_INFO* adapterInfo = (IP_ADAPTER_INFO*)malloc(bufferLength);
if (GetAdaptersInfo(adapterInfo, &bufferLength) == NO_ERROR) {
// Iterate over all network interfaces
for (IP_ADAPTER_INFO* adapter = adapterInfo; adapter; adapter = adapter->Next) {
// Iterate over all IP addresses for this network interface
for (IP_ADDR_STRING* ipAddr = &adapter->IpAddressList; ipAddr; ipAddr = ipAddr->Next) {
// Check if this is the IP address we're interested in
if (ipAddress == ipAddr->IpAddress.String) {
// Convert the subnet mask from string to host-ordered 4-byte unsigned
unsigned long subnetMask;
if (inet_pton(AF_INET, ipAddr->IpMask.String, &subnetMask) == 1) {
ret = ntohl(subnetMask);
}
}
}
}
}
free(adapterInfo);
#else
// Return entire mask for localhost
if (ipAddress == "127.0.0.1" || ipAddress == "localhost") { return ret; }
struct ifaddrs* ifAddrStruct = NULL;
struct ifaddrs* ifa = NULL;
void* tmpAddrPtr = NULL;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr) {
continue;
}
// check it is IP4
if (ifa->ifa_addr->sa_family == AF_INET) {
tmpAddrPtr = &((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
if (strcmp(addressBuffer, ipAddress.c_str()) == 0) {
// found the network interface associated with the IP. Return in host
// byte order.
ret = ntohl(((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr.s_addr);
}
}
}
if (ifAddrStruct != NULL) {
freeifaddrs(ifAddrStruct);
}
#endif
return ret;
}
/// @brief Helper function to make a broadcast address for the NIC associated with an IP address.
/// @param [in] IP The IP address to find the broadcast address for.
/// @return The broadcast address for the NIC associated with the given IP.
static uint32_t MakeBroadcastAddress(uint32_t IP)
{
// Convert the host-ordered address into a dotted-decimal string.
struct in_addr addr;
addr.s_addr = htonl(IP);
std::string ipString = inet_ntoa(addr);
// Find the subnet mask for the IP.
uint32_t subnetMask = FindSubnetMask(ipString);
// Invert all of the bits in the subnet mask to find the bits belonging to the address.
uint32_t invertedMask = ~subnetMask;
// Or the inverted mask with the IP to find the return value.
return IP | invertedMask;
}
/// @brief Read exactly `len` bytes from a blocking TCP socket into `buf`.
/// @param [in] sock The socket to read from.
/// @param [out] buf The buffer to read into. Must be at least `len` bytes long.
/// @param [in] len The number of bytes to read.
/// @return true if exactly len bytes were read, false on error or connection closed.
static bool RecvAll(SOCKET sock, void* buf, size_t len)
{
uint8_t* ptr = static_cast<uint8_t*>(buf);
size_t remaining = len;
while (remaining > 0) {
int r = recv(sock, reinterpret_cast<char*>(ptr), static_cast<int>(remaining), 0);
if (r > 0) {
ptr += r;
remaining -= static_cast<size_t>(r);
continue;
}
if (r == 0) {
// Connection closed by peer.
return false;
}
// r < 0, an error occurred. On POSIX handle EINTR and retry.
#ifndef ASDP_USE_WINSOCK_SOCKETS
if ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK)) {
// EINTR => retry; EAGAIN/EWOULDBLOCK should not normally happen on blocking sockets,
// but handle conservatively by yielding and retrying once.
std::this_thread::yield();
continue;
}
#else
int wsaerr = WSAGetLastError();
if (wsaerr == WSAEINTR || wsaerr == WSAEWOULDBLOCK) {
std::this_thread::yield();
continue;
}
#endif
return false;
}
return true;
}
//----------------------------------------------------------------------------
// API functions
StreamEndpoint::StreamEndpoint(const std::string& host, uint16_t port)
: IP(0)
, port(0)
{
StreamEndpoint::port = port;
if (host == "") {
IP = INADDR_ANY;
} else {
// Look up the IPV4 address of the host.
struct addrinfo* result = nullptr;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags |= AI_CANONNAME;
const char* hostName = host.c_str();
int status = getaddrinfo(hostName, nullptr, &hints, &result);
if (status != 0) {
return;
}
struct sockaddr_in* address = (struct sockaddr_in*)result->ai_addr;
// Convert to host byte order
IP = ntohl(address->sin_addr.s_addr);
freeaddrinfo(result);
}
}
std::string StreamEndpoint::Test()
{
// Construct a StreamEndpoint and verify that it has the expected IP and port.
// We expect it to be 127.0.0.1 when converted from network byte order
StreamEndpoint endpoint("localhost", 1234);
uint32_t expectedIP = (127 << 24) + 1;
if (endpoint.IP != expectedIP || endpoint.port != 1234) {
return "Error constructing StreamEndpoint: IP is " + std::to_string(endpoint.IP) + " and port is " + std::to_string(endpoint.port);
}
return "";
}
Timer::Timer()
: m_coreNegativeOffset({0, 0})
, m_corePositiveOffset({0, 0})
{
}
Status Timer::GetCoreTime(Time& core_time, const std::chrono::steady_clock::time_point local_time) const
{
// Get the local time into a Time.
Time localTime = {
static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::microseconds>(local_time.time_since_epoch()).count() / 1000000),
static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::microseconds>(local_time.time_since_epoch()).count() % 1000000)
};
// Verify that the local time is not before the core offset.
if (localTime + m_corePositiveOffset < m_coreNegativeOffset) {
return BAD_PARAMETER;
}
// Adjust the time
core_time = localTime + m_corePositiveOffset - m_coreNegativeOffset;
return OKAY;
}
Status Timer::SetCoreNegativeOffset(Time offset)
{
// Ensure that the offset is not too large.
std::chrono::steady_clock::time_point local_time = std::chrono::steady_clock::now();
Time localTime = {
static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::microseconds>(local_time.time_since_epoch()).count() / 1000000),
static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::microseconds>(local_time.time_since_epoch()).count() % 1000000)
};
if (offset > localTime) {
return BAD_PARAMETER;
}
m_coreNegativeOffset = offset;
return OKAY;
}
Status Timer::SetCorePositiveOffset(Time offset)
{
m_corePositiveOffset = offset;
return OKAY;
}
Timer::~Timer()
{
}
std::string Timer::Test()
{
// Test the + and += operators on the Time class.
{
Time time1 = { 1, 2 };
Time time2 = { 3, 4 };
Time time3 = time1 + time2;
if (time3.seconds != 4 || time3.microseconds != 6) {
return "Error adding times: " + std::to_string(time3.seconds) + "." + std::to_string(time3.microseconds);
}
time1 += time2;
if (time1.seconds != 4 || time1.microseconds != 6) {
return "Error adding times: " + std::to_string(time1.seconds) + "." + std::to_string(time1.microseconds);
}
}
// Test the - and -= operators on the Time class, including cases where the microseconds must borrow.
{
Time time1 = { 1, 2 };
Time time2 = { 3, 4 };
Time time3 = time2 - time1;
if (time3.seconds != 2 || time3.microseconds != 2) {
return "Error subtracting times: " + std::to_string(time3.seconds) + "." + std::to_string(time3.microseconds);
}
time2 -= time1;
if (time2.seconds != 2 || time2.microseconds != 2) {
return "Error subtracting times: " + std::to_string(time2.seconds) + "." + std::to_string(time2.microseconds);
}
time1 = { 1, 2 };
time2 = { 0, 4 };
time3 = time1 - time2;
if (time3.seconds != 0 || time3.microseconds != 999998) {
return "Error subtracting times: " + std::to_string(time3.seconds) + "." + std::to_string(time3.microseconds);
}
time1 -= time2;
if (time1.seconds != 0 || time1.microseconds != 999998) {
return "Error subtracting times: " + std::to_string(time1.seconds) + "." + std::to_string(time1.microseconds);
}
}
// Test the Timer class methods for cases that should work and cases that should fail.
{
Timer timer;
Time coreTime;
std::chrono::steady_clock::time_point localTime = std::chrono::steady_clock::now();
Time localTimeStruct = {
static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::microseconds>(localTime.time_since_epoch()).count() / 1000000),
static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::microseconds>(localTime.time_since_epoch()).count() % 1000000)
};
// Test the GetCoreTime method.
Status status = timer.GetCoreTime(coreTime, localTime);
if (status != OKAY) {
return "Error getting core time: " + ErrorMessage(status);
}
if (coreTime != localTimeStruct) {
return "Error getting core time: " + std::to_string(coreTime.seconds) + "." + std::to_string(coreTime.microseconds);
}
// Test the SetCoreNegativeOffset method.
status = timer.SetCoreNegativeOffset(localTimeStruct);
if (status != OKAY) {
return "Error setting core negative offset: " + ErrorMessage(status);
}
// Test the GetCoreTime method again.
status = timer.GetCoreTime(coreTime, localTime);
if (status != OKAY) {
return "Error getting core time: " + ErrorMessage(status);
}
if (coreTime != Time({ 0, 0 })) {
return "Error getting core time: " + std::to_string(coreTime.seconds) + "." + std::to_string(coreTime.microseconds);
}
// Test the SetCoreNegativeOffset method with a bad parameter.
Time badTimeStruct = localTimeStruct;
badTimeStruct.seconds += 1;
status = timer.SetCoreNegativeOffset(badTimeStruct);
if (status != BAD_PARAMETER) {
return "Error: Permitted to set core offset when should not have been: " + ErrorMessage(status);
}
}
// Test using both a positive and negative offset.
{
Timer timer;
Time coreTime;
std::chrono::steady_clock::time_point localTime = std::chrono::steady_clock::now();
Time localTimeStruct = {
static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::microseconds>(localTime.time_since_epoch()).count() / 1000000),
static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::microseconds>(localTime.time_since_epoch()).count() % 1000000)
};
// Set the negative offset to 1 second.
Time negativeOffset = { 1, 0 };
Status status = timer.SetCoreNegativeOffset(negativeOffset);
if (status != OKAY) {
return "Error setting core negative offset: " + ErrorMessage(status);
}
// Set the positive offset to 1 seconds.
Time positiveOffset = { 2, 5 };
status = timer.SetCorePositiveOffset(positiveOffset);
if (status != OKAY) {
return "Error setting core positive offset: " + ErrorMessage(status);
}
// Get the core time and verify that it is 1.5 larger.
status = timer.GetCoreTime(coreTime, localTime);
if (status != OKAY) {
return "Error getting core time: " + ErrorMessage(status);
}
if (coreTime != localTimeStruct + Time({ 1, 5 })) {
return "Error getting core time: " + std::to_string(coreTime.seconds) + "." + std::to_string(coreTime.microseconds);
}
}
return "";
}
BasicPacket::BasicPacket(uint32_t extraSize)
: m_buffer(std::make_shared<std::vector<uint8_t>>(PACKET_BASIC_HEADER_SIZE + extraSize))
, m_offset(0)
, m_constructorStatus(OKAY)
{
// Pack our header.
unsigned char* bufPtr = MyData();
uint32_t totalSize = PACKET_BASIC_HEADER_SIZE + extraSize;
memcpy(bufPtr, &totalSize, sizeof(totalSize)); bufPtr += sizeof(totalSize);
}
BasicPacket::BasicPacket(std::shared_ptr<std::vector<uint8_t>> existingBuffer, size_t offset)
: m_buffer(existingBuffer)
, m_offset(offset)
, m_constructorStatus(OKAY)
{
// Make sure the buffer is large enough.
if (MyRemainingSize() < PACKET_BASIC_HEADER_SIZE) {
m_constructorStatus = BAD_PARAMETER;
return;
}
}
Status BasicPacket::GetConstructorStatus() const
{
return m_constructorStatus;
}
Status BasicPacket::GetTotalLength(uint32_t& totalLength) const
{
// Make sure we have enough data to hold the header.
if (MyRemainingSize() < PACKET_BASIC_HEADER_SIZE) {
return READ_PAST_END;
}
// Read the total packet length.
memcpy(&totalLength, MyData() + PACKET_HEADER_TOTAL_SIZE_OFFSET, sizeof(totalLength));
return OKAY;
}
Status BasicPacket::IncreaseTotalLength(uint32_t increase)
{
// Make sure we have enough data to hold the header.
if (MyRemainingSize() < PACKET_BASIC_HEADER_SIZE) {
return READ_PAST_END;
}
// Read the total packet length, verify that it is not too long and then increase it.
uint32_t totalLength;
memcpy(&totalLength, MyData() + PACKET_HEADER_TOTAL_SIZE_OFFSET, sizeof(totalLength));
totalLength += increase;
if (totalLength > MyRemainingSize()) {
return WRITE_PAST_END;
}
memcpy(MyData() + PACKET_HEADER_TOTAL_SIZE_OFFSET, &totalLength, sizeof(totalLength));
return OKAY;
}
BasicPacket::~BasicPacket()
{
}
std::string BasicPacket::Test()
{
{
// Construct a basic packet, giving it some extra parameter size.
uint32_t parameterSize = 200;
BasicPacket packet(parameterSize);
if (packet.GetConstructorStatus() != OKAY) {
return "Error constructing base packet: " + ErrorMessage(packet.GetConstructorStatus());
}
// Construct a new packet from the original packet's buffer.
BasicPacket packet2(packet.m_buffer);
if (packet2.GetConstructorStatus() != OKAY) {
return "Error constructing base packet from buffer: " + ErrorMessage(packet2.GetConstructorStatus());
}
// Check the length of the packet to make sure it matches expectation.
uint32_t totalLength;
Status status = packet2.GetTotalLength(totalLength);
if (status != OKAY) {
return "Error checking base packet size: " + ErrorMessage(status);
}
if (totalLength != PACKET_BASIC_HEADER_SIZE + parameterSize) {
return "Error constructing base packet from buffer: packet length is not " +
std::to_string(PACKET_BASIC_HEADER_SIZE + parameterSize) + " but " + std::to_string(totalLength);
}
}
{
// Try to construct a basic packet from a buffer that is too small and make
// sure that it fails.
std::shared_ptr<std::vector<uint8_t>> empty = std::make_shared<std::vector<uint8_t>>();
BasicPacket packet(empty);
Status status = packet.GetConstructorStatus();
if (status == OKAY) {
return "Unexpected OKAY return code from empty packet construction";
}
}
{
// Construct multiple BasicPackets in the same buffer.
std::shared_ptr<std::vector<uint8_t>> buffer =
std::make_shared<std::vector<uint8_t>>(PACKET_BASIC_HEADER_SIZE * (3 + 4));
uint32_t headerSize = PACKET_BASIC_HEADER_SIZE;
for (int i = 0; i < 3; i++) {
memcpy(buffer->data() + i * sizeof(headerSize), &headerSize, sizeof(headerSize));
}
BasicPacket packet1(buffer, 0);
if (packet1.GetConstructorStatus() != OKAY) {
return "Error constructing base packet from buffer: " + ErrorMessage(packet1.GetConstructorStatus());
}
BasicPacket packet2(buffer, sizeof(headerSize));
if (packet2.GetConstructorStatus() != OKAY) {
return "Error constructing base packet from buffer: " + ErrorMessage(packet2.GetConstructorStatus());
}
BasicPacket packet3(buffer, 2 * sizeof(headerSize));
if (packet3.GetConstructorStatus() != OKAY) {
return "Error constructing base packet from buffer: " + ErrorMessage(packet3.GetConstructorStatus());
}
// Increase the size of the final packet.
Status status = packet3.IncreaseTotalLength(4 * sizeof(headerSize));
if (status != OKAY) {
return "Error increasing packet size: " + ErrorMessage(status);
}
// We should be unable to increase it again.
status = packet3.IncreaseTotalLength(1);
if (status != WRITE_PAST_END) {
return "Error unexpected ability to increasing packet size: " + ErrorMessage(status);
}
}
// Everything worked.
return "";
}
CommandPacket::CommandPacket(uint32_t parameterSize, OpCode code)
: BasicPacket(sizeof(uint32_t) + parameterSize)
{
// Pack our operation code.
unsigned char *bufPtr = MyData() + COMMAND_PACKET_OPCODE_OFFSET;
uint32_t myOpCode = code;
memcpy(bufPtr, &myOpCode, sizeof(myOpCode)); bufPtr += sizeof(myOpCode);
}
CommandPacket::CommandPacket(std::shared_ptr<std::vector<uint8_t>> existingBuffer)
: BasicPacket(existingBuffer)
{
if (MyRemainingSize() < COMMAND_PACKET_BASE_SIZE) {
m_constructorStatus = BAD_PARAMETER;
}
}
CommandPacket::CommandPacket(std::shared_ptr<std::vector<uint8_t>> existingBuffer, OpCode code)
: CommandPacket(existingBuffer)
{
// Verify the opcode after creating the buffer.
OpCode opCode;
Status status = GetOpCode(opCode);
if (status != OKAY) {
m_constructorStatus = status;
return;
}
if (opCode != code) {
m_constructorStatus = BAD_PARAMETER;
return;
}
}
Status CommandPacket::GetOpCode(OpCode& opCode) const
{
// Make sure we have enough data to hold the header.
if (MyRemainingSize() < COMMAND_PACKET_BASE_SIZE) {
return READ_PAST_END;
}
memcpy(&opCode, MyData() + COMMAND_PACKET_OPCODE_OFFSET, sizeof(opCode));
return OKAY;
}
std::string CommandPacket::Test()
{
{
// Construct a command packet with the RESET opcode and verify that we can read its opcode.
CommandPacket resetPacket(0, RESET);
if (resetPacket.GetConstructorStatus() != OKAY) {
return "Error constructing base packet: " + ErrorMessage(resetPacket.GetConstructorStatus());
}
OpCode opCode;
Status status = resetPacket.GetOpCode(opCode);
if (status != OKAY) {
return "Error getting opcode from base packet: " + ErrorMessage(status);
}
if (opCode != RESET) {
return "Error getting opcode from base packet: opcode is not RESET";
}
// Construct a new packet from the reset packet's buffer and verify that it has the same opcode.
CommandPacket resetPacket2(resetPacket.m_buffer, RESET);
if (resetPacket2.GetConstructorStatus() != OKAY) {
return "Error constructing base packet from buffer: " + ErrorMessage(resetPacket2.GetConstructorStatus());
}
OpCode opCode2;
status = resetPacket2.GetOpCode(opCode2);
if (status != OKAY) {
return "Error getting opcode from base packet constructed from buffer: " + ErrorMessage(status);
}
}
{
// Try to construct a CommandPacket from a buffer that is too small and make
// sure that it fails.
std::shared_ptr<std::vector<uint8_t>> empty = std::make_shared<std::vector<uint8_t>>();
CommandPacket packet(empty, RESET);
Status status = packet.GetConstructorStatus();
if (status == OKAY) {
return "Unexpected OKAY return code from empty packet construction";
}
// Also make sure that trying to read its opcode fails.
OpCode opCode;
status = packet.GetOpCode(opCode);
if (status != READ_PAST_END) {
return "Unexpected return code from empty packet opcode read: " + ErrorMessage(status);
}
}
// Everything worked.
return "";
}
CommandPacketReset::CommandPacketReset()
: CommandPacket(0, RESET)
{
}
CommandPacketReset::CommandPacketReset(CommandPacket& basePacket)
: CommandPacket(basePacket.m_buffer, RESET)
{
}
std::string CommandPacketReset::Test()
{
{
// Construct a command packet and verify that we can read its opcode.
CommandPacketReset packet;
if (packet.GetConstructorStatus() != OKAY) {
return "Error constructing packet: " + ErrorMessage(packet.GetConstructorStatus());
}
OpCode opCode;
Status status = packet.GetOpCode(opCode);
if (status != OKAY) {
return "Error getting opcode from packet: " + ErrorMessage(status);
}
if (opCode != RESET) {
return "Error getting opcode from packet: opcode is not RESET";
}
// Construct a new packet from the packet's buffer and verify that it has the same opcode.
CommandPacket &originalPacket = packet;
CommandPacketReset packet2(originalPacket);
if (packet2.GetConstructorStatus() != OKAY) {
return "Error constructing packet from buffer: " + ErrorMessage(packet2.GetConstructorStatus());
}
}
return "";
}
CommandPacketStartRecording::CommandPacketStartRecording()
: CommandPacket(0, START_RECORDING)
{
}
CommandPacketStartRecording::CommandPacketStartRecording(CommandPacket& basePacket)
: CommandPacket(basePacket.m_buffer, START_RECORDING)
{
}
std::string CommandPacketStartRecording::Test()
{
{
// Construct a command packet and verify that we can read its opcode.
CommandPacketStartRecording packet;
if (packet.GetConstructorStatus() != OKAY) {
return "Error constructing packet: " + ErrorMessage(packet.GetConstructorStatus());
}
OpCode opCode;
Status status = packet.GetOpCode(opCode);
if (status != OKAY) {