-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparser.py
More file actions
1878 lines (1533 loc) · 83 KB
/
parser.py
File metadata and controls
1878 lines (1533 loc) · 83 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
import collections
import math
import numpy
import queue
import select
import socket
import struct
import threading
import time
import json
from enum import IntEnum
from typing import Sequence
from . import crc16, data, protocol
from .data import (BROADCAST_PORT, GENERAL_PORT, LAST_CHANNEL_NUMBER,
SYNC_BYTE, WAIT_TIME_FOR_RESPONSE)
from .exceptions import (ClientTimeoutError, CommunicationError, ParseError,
ResponseError)
from .protocol import ParamID, ProtocolHeader, ProtocolBottom
import logging
_logger = logging.getLogger("IXCOM")
try:
import ixcom_c_ext
ixcom_c_ext_installed = True
except ImportError:
ixcom_c_ext_installed = False
PositionTuple = collections.namedtuple('PositionTuple', 'Lon Lat Alt')
class MessageSearcherState(IntEnum):
waiting_for_sync = 0
waiting_for_msglength = 1
fetching_bytes = 2
XCOM_MAX_MESSAGE_LENGTH = 4096
XCOM_HEADER_LENGTH = ProtocolHeader().size()
XCOM_BOTTOM_LENGTH = ProtocolBottom().size()
TOTAL_MAX_MESSAGE_LENGTH = XCOM_MAX_MESSAGE_LENGTH
class MessageSearcher:
def __init__(self, parserDelegate = None, disable_crc = False, ignore_c_ext = False):
self.searcherState = MessageSearcherState.waiting_for_sync
self.currentBytes = bytearray(4096)
self.currentByteIdx = 0
self.remainingByteCount = 0
self.msgLength = 0
self.file_read_chunk_length = 2**22
self.file_write_buffer_length = 2**22
self.remaining_bytes_from_unsafe_process = bytes()
self.disableCRC = disable_crc
self.process_buffer_unsafe = self.process_buffer_unsafe_python
self.process_bytes = self.process_bytes_python
self.cfg_json = None
if ixcom_c_ext_installed and not ignore_c_ext:
self.ixcom_c_ext_obj = ixcom_c_ext.Ixcom_c_ext(valid_trigger_source_range = 6)
self.ixcom_c_ext_obj.set_crc_disable(disable_crc)
self.ixcom_c_ext_obj.set_process_bytes_callback(self.publish)
self.process_buffer_unsafe = self.ixcom_c_ext_obj.process_bytes_fast
self.process_bytes = self.ixcom_c_ext_obj.process_bytes_fast
self.callbacks = []
if parserDelegate is not None:
self.callbacks.append(parserDelegate.parse)
def handle_v5_json(self, inBytes):
if len(inBytes) < 9 * 4: # header is 8 * uint32 and crc
return 0
no_sync = inBytes[0] != SYNC_BYTE
header_len = int.from_bytes(inBytes[7 * 4:8 * 4], byteorder='little')
if len(inBytes) < 9 * 4 + header_len:
return 0
start_braket = chr(inBytes[9 * 4]) == '{'
end_braket = chr(inBytes[header_len - 1]) == '}'
if no_sync and start_braket and end_braket:
self.cfg_json = json.loads(bytes(inBytes[9*4:header_len]))
return header_len
return 0
def process_file_handle(self, file_handle):
while self.process_bytes(file_handle.read(self.file_read_chunk_length)):
pass
def process_file_handle_unsafe(self, file_handle):
while self.process_buffer_unsafe(file_handle.read(self.file_read_chunk_length)):
pass
def process_buffer_unsafe_python(self, buffer):
if len(buffer) == 0:
return 0
current_msg_start_idx = 0
last_msg_start_id = -1
inBytes = memoryview(self.remaining_bytes_from_unsafe_process+buffer)
inbytelen = len(inBytes)
if not self.remaining_bytes_from_unsafe_process:
current_msg_start_idx = self.handle_v5_json(inBytes)
while current_msg_start_idx + 5 < inbytelen:
current_msg_length = inBytes[current_msg_start_idx + 4] + 256 * inBytes[current_msg_start_idx + 5]
if current_msg_length < 20 or current_msg_length > TOTAL_MAX_MESSAGE_LENGTH:
raise Exception("File is corrupted, try xcom-remove-partial-msgs on XCOMStream file")
if current_msg_start_idx + current_msg_length > inbytelen: # Message not completely in this chunk
self.remaining_bytes_from_unsafe_process = bytes(inBytes[current_msg_start_idx:])
break
self.publish(inBytes[current_msg_start_idx:current_msg_start_idx+current_msg_length])
if current_msg_start_idx <= last_msg_start_id:
raise Exception("File is corrupted, try xcom-remove-partial-msgs on XCOMStream file")
last_msg_start_id = current_msg_start_idx
current_msg_start_idx += current_msg_length
self.remaining_bytes_from_unsafe_process = bytes(inBytes[current_msg_start_idx:])
return len(buffer)
def process_bytes_python(self, inBytes):
inByteIdx = 0
while inByteIdx < len(inBytes):
if self.searcherState == MessageSearcherState.waiting_for_sync:
poppedByte = inBytes[inByteIdx]
inByteIdx += 1
if poppedByte == SYNC_BYTE:
self.currentBytes[0] = SYNC_BYTE
self.currentByteIdx = 1
self.remainingByteCount = 5
self.searcherState = MessageSearcherState.waiting_for_msglength
elif self.searcherState == MessageSearcherState.waiting_for_msglength:
poppedByte = inBytes[inByteIdx]
inByteIdx += 1
self.currentBytes[self.currentByteIdx] = poppedByte
self.currentByteIdx += 1
self.remainingByteCount -= 1
if self.remainingByteCount == 0:
self.msgLength = self.currentBytes[self.currentByteIdx - 1] * 256 + self.currentBytes[self.currentByteIdx - 2]
self.remainingByteCount = self.msgLength - 6
if self.remainingByteCount <= (TOTAL_MAX_MESSAGE_LENGTH-6) and self.remainingByteCount >= 14: #ten more bytes from header and 4 from footer
self.searcherState = MessageSearcherState.fetching_bytes
else:
self.searcherState = MessageSearcherState.waiting_for_sync
elif self.searcherState == MessageSearcherState.fetching_bytes:
if len(inBytes) - 1 >= self.remainingByteCount + inByteIdx - 1: # Der Buffer ist Länger als der Rest der Nachricht.
self.currentBytes[self.currentByteIdx:self.currentByteIdx + self.remainingByteCount] = inBytes[inByteIdx:inByteIdx + self.remainingByteCount]
self.currentByteIdx = self.currentByteIdx + self.remainingByteCount
inByteIdx = inByteIdx + self.remainingByteCount
self.remainingByteCount = 0
else:
self.currentBytes[self.currentByteIdx:self.currentByteIdx + (len(inBytes) - inByteIdx)] = inBytes[inByteIdx:]
self.currentByteIdx = self.currentByteIdx + (len(inBytes) - inByteIdx)
self.remainingByteCount -= (len(inBytes) - inByteIdx)
inByteIdx = len(inBytes)
if self.remainingByteCount == 0:
if self.disableCRC:
self.publish(self.currentBytes[:self.currentByteIdx])
else:
crc = crc16.crc16xmodem(bytes(self.currentBytes[:self.currentByteIdx - 2]))
if crc == self.currentBytes[self.currentByteIdx - 2] + self.currentBytes[
self.currentByteIdx - 1] * 256:
self.publish(self.currentBytes[:self.currentByteIdx])
else:
pass
self.searcherState = MessageSearcherState.waiting_for_sync
return len(inBytes)
def publish(self, msg_bytes):
for callback in self.callbacks:
callback(msg_bytes)
def add_callback(self, callback):
self.callbacks.append(callback)
def remove_callback(self, callback):
self.callbacks.remove(callback)
class MessageParser:
def __init__(self):
self.subscribers = set()
self.callbacks = list()
self.messageSearcher = MessageSearcher(parserDelegate = self)
self.nothrow = False
def parse_response(self, inBytes):
message = data.ProtocolMessage()
message.header.from_bytes(inBytes[:16])
message.payload = data.ResponsePayload(message.header.msgLength)
message.from_bytes(inBytes)
self.publish(message)
def parse_parameter(self, inBytes):
parameterID = inBytes[16] + (inBytes[17] << 8)
if parameterID != ParamID.PARPLUGIN:
message = data.getParameterWithID(parameterID)
else:
pluginParameterID = inBytes[22] + (inBytes[23] << 8)
message = data.getPluginParameterWithID(pluginParameterID)
if message is not None:
try:
message.from_bytes(inBytes)
self.publish(message)
except Exception as ee:
_logger.error('Error: Parameter with ID: {} ({}) could not be parsed! Reason: {}'.format(parameterID, message.payload.get_name(), repr(ee)))
else:
data.handle_undefined_parameter(parameterID)
def parse_command(self, inBytes):
cmdID = inBytes[16] + (inBytes[17] << 8)
message = data.getCommandWithID(cmdID)
if message is not None:
message.from_bytes(inBytes)
self.publish(message)
else:
pass
def parse_plugin_message(self, inBytes):
plugin_message_id = inBytes[16] + (inBytes[17] << 8)
message = data.getPluginMessageWithID(plugin_message_id)
if message is not None:
try:
message.from_bytes(inBytes)
self.publish(message)
except ParseError as ee:
_logger.error('Error: Plugin Message with ID: {} ({}) could not be parsed! Reason: {}'.format(plugin_message_id, message.payload.get_name(), repr(ee)))
else:
data.handle_undefined_plugin_message(plugin_message_id)
def parse(self, inBytes):
header = data.ProtocolHeader()
header.from_bytes(inBytes)
try:
if header.msgID == data.MessageID.RESPONSE:
self.parse_response(inBytes)
elif header.msgID == data.MessageID.PARAMETER:
self.parse_parameter(inBytes)
elif header.msgID == data.MessageID.COMMAND:
self.parse_command(inBytes)
elif header.msgID == data.MessageID.PLUGIN:
self.parse_plugin_message(inBytes)
else:
message = data.getMessageWithID(header.msgID)
if message is not None:
message.from_bytes(inBytes)
self.publish(message)
except ParseError as err:
if self.nothrow:
_logger.error("MessageParser problem: %r", err)
else:
raise
def add_subscriber(self, subscriber):
self.subscribers.add(subscriber)
def add_callback(self, callback):
self.callbacks += [callback]
def add_callback_and_block(self, callback):
'''Add a callback function and joins the communication thread.
Call stop() in a callback function the stop the communication thread and continue.
'''
self.callbacks += [callback]
self.join_comm_thread.join()
def remove_callback(self, callback):
self.callbacks.remove(callback)
def remove_subscriber(self, subscriber):
self.subscribers.discard(subscriber)
def publish(self, message):
for subscriber in self.subscribers:
subscriber.handle_message(message, from_device=self)
for callback in self.callbacks:
callback(message, from_device=self)
class NpMessageParser(MessageParser):
def parse_response(self, inBytes):
return
def parse_parameter(self, inBytes):
parameterID = inBytes[16] + (inBytes[17] << 8)
if parameterID != ParamID.PARPLUGIN:
message = data.getStashedParameterWithID(parameterID, inBytes)
else:
pluginParameterID = inBytes[22] + (inBytes[23] << 8)
message = data.getStashedPluginParameterWithID(pluginParameterID, inBytes)
if message is not None:
try:
message.from_bytes_faster(inBytes)
self.publish(message)
except Exception as ee:
_logger.error('Error: Parameter with ID: {} ({}) could not be parsed! Reason: {}'.format(parameterID, message.payload.get_name(), repr(ee)))
else:
data.handle_undefined_parameter(parameterID)
def parse_command(self, inBytes):
cmdID = inBytes[16] + (inBytes[17] << 8)
message = data.getStashedCommandWithID(cmdID, inBytes)
if message is not None:
message.from_bytes_faster(inBytes)
self.publish(message)
else:
pass
def parse_plugin_message(self, inBytes):
plugin_message_id = inBytes[16] + (inBytes[17] << 8)
message = data.getStashedPluginMessageWithID(plugin_message_id, inBytes)
if message is not None:
try:
message.from_bytes_faster(inBytes)
self.publish(message)
except ParseError as ee:#Exception:
_logger.error('Error: Plugin Message with ID: {} ({}) could not be parsed! Reason: {}'.format(plugin_message_id, message.payload.get_name(), repr(ee)))
else:
data.handle_undefined_plugin_message(plugin_message_id)
def get_stashed_msg(self, inBytes, extra_desc = None):
msgID = inBytes[1]
if msgID >= 0xfd:
if msgID == data.MessageID.RESPONSE:
return None
elif msgID == data.MessageID.PARAMETER:
parameterID = inBytes[16] + (inBytes[17] << 8)
if parameterID != ParamID.PARPLUGIN:
message = data.getStashedParameterWithID(parameterID, inBytes, extra_desc = extra_desc)
else:
pluginParameterID = inBytes[22] + (inBytes[23] << 8)
message = data.getStashedPluginParameterWithID(pluginParameterID, inBytes, extra_desc = extra_desc)
elif msgID == data.MessageID.COMMAND:
cmdID = inBytes[16] + (inBytes[17] << 8)
message = data.getStashedCommandWithID(cmdID, inBytes, extra_desc = extra_desc)
elif msgID == data.MessageID.PLUGIN:
plugin_message_id = inBytes[16] + (inBytes[17] << 8)
message = data.getStashedPluginMessageWithID(plugin_message_id, inBytes, extra_desc = extra_desc)
else:
message = data.getStashedMessageWithID(msgID, inBytes, extra_desc = extra_desc)
if message is not None:
return message
else:
return None
def parse(self, inBytes):
msgID = inBytes[1]
if msgID >= 0xfd:
if msgID == data.MessageID.RESPONSE:
self.parse_response(inBytes)
elif msgID == data.MessageID.PARAMETER:
self.parse_parameter(inBytes)
elif msgID == data.MessageID.COMMAND:
self.parse_command(inBytes)
elif msgID == data.MessageID.PLUGIN:
self.parse_plugin_message(inBytes)
else:
message = data.getStashedMessageWithID(msgID, inBytes)
if message is not None:
message.from_bytes_faster(inBytes)
self.publish(message)
class MessageCallback:
def __init__(self, callback, msg, client):
self.callback = callback
self.msg = msg
self.client = client
def run(self):
self.callback(self.msg, self.client)
class Client(MessageParser):
'''XCOM TCP Client
Implements a TCP-socket based XCOM client and offers convenience methods to interact with the
device. Other classes may subscribe to decoded messages.
'''
def __init__(self, host, port=GENERAL_PORT, timeout = WAIT_TIME_FOR_RESPONSE):
MessageParser.__init__(self)
self.timeout = timeout
self.host = host
self.port = port
self._open_channel = -1
self._create_socket_and_connect()
self._stop_event = threading.Event()
self._response_event = threading.Event()
self._response_event.response = None
self._parameter_event = threading.Event()
self._parameter_event.parameter = None
self._message_event = threading.Event()
self._message_event.msg = None
self._message_event.id = None
self.okay_lock = threading.Lock()
self._comm_thread = threading.Thread(target = self._update_data, daemon = True, name='CommThread')
self._comm_thread.start()
self._callback_queue = queue.Queue()
self._callback_thread = threading.Thread(target = self._callback_worker, daemon = True, name='CallbackThread')
self._callback_thread.start()
self.add_subscriber(self)
def _create_socket_and_connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.sock.connect((self.host, self.port))
def join_comm_thread(self):
'''Join the communication thread
Blocks the calling location until the communications thread terminates.
Can e.g. be used if callbacks have been set up, logs have been requested and we just want to
leave the program running like this until the communications with the device stop.
Args:
self
'''
self._comm_thread.join()
def get_commthread_handler(self):
return self._comm_thread
def get_callbackthread_handler(self):
return self._callback_thread
def get_open_channel(self):
return self._open_channel
def stop(self):
self._stop_event.set()
self._comm_thread.join()
self._callback_thread.join()
def publish(self, message):
for subscriber in self.subscribers:
subscriber.handle_message(message, from_device=self)
for callback in self.callbacks:
cb = MessageCallback(callback, message, self)
self._callback_queue.put(cb)
def __hash__(self):
'''Hash function
Implements hash to use a Client as a key in a dictionary
Args:
self
Returns:
A hash
'''
return id(self)
def __eq__(self, other):
return self is other
def _callback_worker(self):
while not self._stop_event.is_set():
try:
callback = self._callback_queue.get(block=True, timeout=1)
callback.run()
except queue.Empty:
pass
def handle_message(self, message, from_device):
if message.header.msgID == data.MessageID.RESPONSE:
self._response_event.response = message
self._response_event.set()
elif message.header.msgID == data.MessageID.PARAMETER:
self._parameter_event.parameter = message
self._parameter_event.set()
elif message.header.msgID == self._message_event.id:
self._message_event.msg = message
self._message_event.set()
def open_channel(self, channelNumber=0):
'''Opens an XCOM logical channel
Opens an XCOM logical channel on the associated socket and waits for an 'OK' response.
Args:
chnannelNumber: XCOM channel to open. Default = 0
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.XcomCommandPayload.command_id)
msgToSend.payload.data['mode'] = data.XcomCommandParameter.channel_open
msgToSend.payload.data['channelNumber'] = channelNumber
self.send_msg_and_waitfor_okay(msgToSend)
self._open_channel = channelNumber
def _update_data(self):
while not self._stop_event.is_set():
inputready, _, _ = select.select([self.sock], [],[], 0.1)
for _ in inputready:
if self.sock.fileno() != -1:
try:
_data = self.sock.recv(2048)
if len(_data) == 0:
# The socket has been closed. The above select will NOT
# wait for timeout in this case, so we would run in busy
# loop unless we wait a bit here.
time.sleep(0.1)
break # break the for-loop, test for stop event
if len(_data) >= 1024:
_logger.info('max bytes read: %s', len(_data))
self.messageSearcher.process_bytes(_data)
# self.messageSearcher.process_bytes(self.sock.recv(1024))
except OSError:
pass
def open_last_free_channel(self):
'''Opens an XCOM logical channel
Opens an XCOM logical channel on the associated socket and waits for an 'OK' response.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
RuntimeError: If no free channel is available on the system.
Returns:
channelNumber: number of the opened channel
'''
self._create_socket_and_connect()
msgToSend = data.getCommandWithID(data.XcomCommandPayload.command_id)
msgToSend.payload.data['mode'] = data.XcomCommandParameter.channel_open
channelNumber = LAST_CHANNEL_NUMBER
while channelNumber >= 0:
msgToSend.payload.data['channelNumber'] = channelNumber
try:
self.send_msg_and_waitfor_okay(msgToSend)
self.clear_all()
self._open_channel = channelNumber
return channelNumber
except (ResponseError, ConnectionError):
channelNumber -= 1
self._create_socket_and_connect()
finally:
if channelNumber == 0:
raise RuntimeError('No free channel on the system!')
def get_loglist(self, channel):
msgToSend = data.getParameterWithID(data.PARXCOM_LOGLIST2_Payload.parameter_id)
msgToSend.payload.data['reserved_paramheader'] = channel
msgToSend.payload.data['action'] = data.ParameterAction.REQUESTING
self.send_msg_and_waitfor_okay(msgToSend)
return self.wait_for_parameter()
def open_first_free_channel(self):
'''Opens an XCOM logical channel
Opens an XCOM logical channel on the associated socket and waits for an 'OK' response.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
RuntimeError: If no free channel is available on the system.
Returns:
channelNumber: number of the opened channel
'''
msgToSend = data.getCommandWithID(data.XcomCommandPayload.command_id)
msgToSend.payload.data['mode'] = data.XcomCommandParameter.channel_open
channelNumber = 0
while channelNumber <= LAST_CHANNEL_NUMBER:
msgToSend.payload.data['channelNumber'] = channelNumber
try:
self.send_msg_and_waitfor_okay(msgToSend)
self.clear_all()
self._open_channel = channelNumber
return channelNumber
except (ResponseError, ConnectionError):
channelNumber += 1
self._create_socket_and_connect()
finally:
if channelNumber > LAST_CHANNEL_NUMBER:
raise RuntimeError('No free channel on the system!')
def close_channel(self):
'''Closes XCOM logical channel
Closes XCOM channel on the associated socket and waits for an 'OK' response.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.XcomCommandPayload.command_id)
msgToSend.payload.data['mode'] = data.XcomCommandParameter.channel_close
msgToSend.payload.data['channelNumber'] = self._open_channel
self.send_msg_and_waitfor_okay(msgToSend)
self._open_channel = -1
def reboot(self):
'''Reboots the system
Sends an XCOM reboot command on the associated socket and waits for an 'OK' response.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.XcomCommandPayload.command_id)
msgToSend.payload.data['mode'] = data.XcomCommandParameter.reboot
self.send_msg_and_waitfor_okay(msgToSend)
def get_parameter(self, parameterID: int):
'''Gets parameter from device with specified ID
Gets the specified parameter. Blocks until parameter is retrieved.
Args:
parameterID: ID of the parameter to retrieve
Returns:
An XcomMessage object containing the parameter
Raises:
ClientTimeoutError: Timeout while waiting for response or parameter from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getParameterWithID(parameterID)
msgToSend.payload.data['action'] = data.ParameterAction.REQUESTING
self.send_msg_and_waitfor_okay(msgToSend)
return self.wait_for_parameter()
def get_plugin_parameter(self, parameterID: int):
'''Gets plugin parameter from device with specified ID
Gets the specified plugin parameter. Blocks until parameter is retrieved.
Args:
parameterID: ID of the plugin parameter to retrieve
Returns:
An XcomMessage object containing the parameter
Raises:
ClientTimeoutError: Timeout while waiting for response or parameter from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getPluginParameterWithID(parameterID)
msgToSend.payload.data['action'] = data.ParameterAction.REQUESTING
self.send_msg_and_waitfor_okay(msgToSend)
return self.wait_for_parameter()
def set_aligncomplete(self):
'''Completes the alignment
Completes system alignment by sending the EKF ALIGN_COMPLETE command. Blocks until system
response is received.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_EKF_Payload.command_id)
msgToSend.payload.data['subcommand'] = data.EkfCommand.ALIGN_COMPLETE
self.send_msg_and_waitfor_okay(msgToSend)
def realign(self):
'''Initiates a new alignment
Initiates a new system alignment by sending the EKF ALIGN command. Blocks until system
response is received.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_EKF_Payload.command_id)
msgToSend.payload.data['subcommand'] = data.EkfCommand.ALIGN
self.send_msg_and_waitfor_okay(msgToSend)
def save_pos(self):
'''Saves the current position
Saves the current system position in ROM. Uses the EKF SAVE_POS command
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_EKF_Payload.command_id)
msgToSend.payload.data['subcommand'] = data.EkfCommand.SAVEPOS
self.send_msg_and_waitfor_okay(msgToSend)
def save_hdg(self):
'''Saves the current heading
Saves the current heading value in ROM. Uses the EKF SAVE_HDG command
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_EKF_Payload.command_id)
msgToSend.payload.data['subcommand'] = data.EkfCommand.SAVEHDG
self.send_msg_and_waitfor_okay(msgToSend)
def forced_zupt(self, enable: bool):
'''Enables or disables forced Zero Velocity updates
Enables or disables forced Zero Velocity updates using the EKF FORCED_ZUPT command.
Args:
enable: boolean value to enable or disable ZUPTs.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_EKF_Payload.command_id)
msgToSend.payload.data['subcommand'] = data.EkfCommand.FORCED_ZUPT
msgToSend.payload.structString += 'f'
msgToSend.payload.data['enable'] = enable
self.send_msg_and_waitfor_okay(msgToSend)
def forced_zupt_param(self, enable: bool):
'''Enables or disables forced Zero Velocity updates
Enables or disables forced Zero Velocity updates using the EKF FORCED_ZUPT parameter.
Args:
enable: boolean value to enable or disable ZUPTs.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getMessageByName("PAREKF_FORCEDZUPT")
msgToSend.payload.data['action'] = data.ParameterAction.CHANGING
msgToSend.payload.data['enable'] = enable
self.send_msg_and_waitfor_okay(msgToSend)
def save_antoffset(self, antenna: int):
'''Saves the currently estimated GNSS antenna offset
Saves the currently estimated GNSS antenna offset using the EKF SAVE_ANTOFFSET command.
Args:
antenna: Antenna # to save the offset for.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_EKF_Payload.command_id)
msgToSend.payload.data['subcommand'] = data.EkfCommand.SAVEANTOFFSET
msgToSend.payload.structString += 'f'
msgToSend.payload.data['antenna'] = antenna
self.send_msg_and_waitfor_okay(msgToSend)
def save_config(self):
'''Saves the current configuration
Saves the current configuration to ROM using the CONF SAVE_CONFIG command.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_CONF_Payload.command_id)
msgToSend.payload.data['configAction'] = 0
self.send_msg_and_waitfor_okay(msgToSend)
def load_config(self):
'''Loads the configuration from ROM
Loads the configuration from ROM using the CONF LOAD_CONFIG command.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_CONF_Payload.command_id)
msgToSend.payload.data['configAction'] = 1
self.send_msg_and_waitfor_okay(msgToSend)
def load_delivery_settings(self):
'''
The current configuration will be deleted and the delivery settings will be restored after an automatic reboot
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_CONF_Payload.command_id)
msgToSend.payload.data['configAction'] = 2
self.send_msg_and_waitfor_okay(msgToSend)
def factory_reset(self):
'''Performs a factory reset
Performs a factory reset using the CONF FACTORY_RESET command.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'
'''
msgToSend = data.getCommandWithID(data.CMD_CONF_Payload.command_id)
msgToSend.payload.data['configAction'] = 4
self.send_msg_and_waitfor_okay(msgToSend)
def add_log_with_rate(self, msgID: int, rate: float):
'''Add a log with specified rate
Adds a log with a specific message ID with a specified rate. The divider is computed by
taking into account the MAINTIMING and PRESCALER system parameters.
Args:
msgID: Message ID which should be requested.
rate: Requested log rate in Hz
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK' or if rate too high.
'''
divider = self.get_divider_for_rate(rate)
self.add_log_sync(msgID, math.ceil(divider))
def get_divider_for_rate(self, rate: float):
'''Determines the divider resulting in a certain log output rate for this system.
Args:
rate: output rate in Hz
Returns:
Divider which results in an output rate as close as possible to the requested rate.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK' or if rate too high.
ValueError: If the selected rate os higher than the inertial sensor sampling rate.
'''
maintiming = self.get_parameter(data.PARSYS_MAINTIMING_Payload.parameter_id)
prescaler = self.get_parameter(data.PARSYS_PRESCALER_Payload.parameter_id)
divider = (maintiming.payload.data['maintiming'] / rate / prescaler.payload.data['prescaler'])
if divider < 1:
raise ValueError('Selected rate too high')
else:
return divider
def add_log_sync(self, msgID: int, divider: int):
'''Add a log with specified divider
Adds a log with a specific message ID with a divider.
Args:
msgID: Message ID which should be requested.
divider: divider to use
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'.
'''
msgToSend = data.getCommandWithID(data.CMD_LOG_Payload.command_id)
msgToSend.payload.data['messageID'] = msgID
msgToSend.payload.data['trigger'] = data.LogTrigger.SYNC
msgToSend.payload.data['parameter'] = data.LogCommand.ADD
msgToSend.payload.data['divider'] = divider
self.send_msg_and_waitfor_okay(msgToSend)
def add_log_event(self, msgID: int):
'''Add an event-triggered log
Adds a log with a specific message ID to be sent at event. The triggering event depends on the specific log,
e.g. for GNSSSOL, an event trigger will trigger the log with every new solution.
Args:
msgID: Message ID which should be requested.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'.
'''
msgToSend = data.getCommandWithID(data.CMD_LOG_Payload.command_id)
msgToSend.payload.data['messageID'] = msgID
msgToSend.payload.data['trigger'] = data.LogTrigger.EVENT
msgToSend.payload.data['parameter'] = data.LogCommand.ADD
msgToSend.payload.data['divider'] = 500 # use 500 here, because a '1' is rejected from some logs
self.send_msg_and_waitfor_okay(msgToSend)
def clear_all(self):
'''Clears all logs
Sends a CLEAR_ALL command to the system.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'.
'''
msgToSend = data.getCommandWithID(data.CMD_LOG_Payload.command_id)
msgToSend.payload.data['messageID'] = 3
msgToSend.payload.data['trigger'] = data.LogTrigger.SYNC
msgToSend.payload.data['parameter'] = data.LogCommand.CLEAR_ALL
msgToSend.payload.data['divider'] = 1
self.send_msg_and_waitfor_okay(msgToSend)
def clear_log(self, msgID: int):
'''Clears a log with a specific message ID.
Clears a log with a specific message ID.
Args:
msgID: Message ID which should be requested.
Raises:
ClientTimeoutError: Timeout while waiting for response from the XCOM server
ResponseError: The response from the system was not 'OK'.
'''
msgToSend = data.getCommandWithID(data.CMD_LOG_Payload.command_id)
msgToSend.payload.data['messageID'] = msgID
msgToSend.payload.data['trigger'] = data.LogTrigger.SYNC
msgToSend.payload.data['parameter'] = data.LogCommand.CLEAR
msgToSend.payload.data['divider'] = 1
self.send_msg_and_waitfor_okay(msgToSend)
def poll_log(self, msgID):
'''Polls a log
Polls a log with a specified message ID. Blocks until the log is retrieved and returns
the log.
Args:
msgID: Message ID to poll
Returns:
The polled log
Raises:
ClientTimeoutError: Timeout while waiting for response or log from the XCOM server
ResponseError: The response from the system was not 'OK'.
'''
msgToSend = data.getCommandWithID(data.CMD_LOG_Payload.command_id)
msgToSend.payload.data['messageID'] = msgID
msgToSend.payload.data['trigger'] = data.LogTrigger.POLLED
msgToSend.payload.data['parameter'] = data.LogCommand.ADD
msgToSend.payload.data['divider'] = 500 # use 500 here, because a '1' is rejected from some logs
self._message_event.id = msgID
self._message_event.clear()
self.send_msg_and_waitfor_okay(msgToSend)
return self.wait_for_polled_log()
def wait_for_parameter(self):
'''Waits for reception of parameter
Blocks until a parameterEvent is received.
Raises:
ClientTimeoutError: Timeout while waiting for parameter from the XCOM server
'''
self._update_until_event(self._parameter_event, self.timeout)
result = self._parameter_event.parameter
return result
def _update_until_event(self, event, timeout):
event.wait(timeout=timeout)
if event.is_set():
event.clear()
return
raise ClientTimeoutError('Timeout while waiting for event', thrower=self)