-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMET4FOFDataReceiver.py
1664 lines (1506 loc) · 63.7 KB
/
MET4FOFDataReceiver.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 09:20:12 2019
Data receiver for Met4FoF Protobuff Data
@author: [email protected]
"""
import sys
import traceback
import os
import socket
import threading
import warnings
from datetime import datetime
from multiprocessing import Queue
import time
import datetime
import copy
import json
import h5py
# from mpi4py import MPI #for multi threaded hdf writing on Windows MSMPI needs to be installed https://www.microsoft.com/en-us/download/details.aspx?id=57467
# for live plotting
import matplotlib.pyplot as plt
import numpy as np
# proptobuff message encoding
from google.protobuf.internal.encoder import _VarintBytes
from google.protobuf.internal.decoder import _DecodeVarint32
CURR_DIR = os.path.dirname(os.path.abspath(__file__))
print(CURR_DIR)
sys.path.append(CURR_DIR)
import messages_pb2
# matplotlib.use('Qt5Agg')
class DataReceiver:
"""Class for handlig the incomming UDP Packets and spwaning sensor Tasks and sending the Protobuff Messages over an queue to the Sensor Task
.. image:: ../doc/DR_flow.png
"""
def __init__(self, IP, Port=7654):
"""
Parameters
----------
IP : string
Either an spefic IP Adress like "192.168.0.200" or "" for all interfaces.
Port : intger
UDP Port for the incoming data 7654 is default.
Raises
------
socket.error:[errno 99] cannot assign requested address and namespace in python
The Set IP does not match any networkintrefaces ip.
socket.error:[Errno 98] Address already in use
an other task is using the set port and interface.
Returns
-------
None.
"""
self.flags = {"Networtinited": False}
self.params = {"IP": IP, "Port": Port, "PacketrateUpdateCount": 10000}
self.socket = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM # Internet
) # UDP
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)# socket can be resued instantly for debugging
# Try to open the UDP connection
try:
self.socket.bind((IP, Port))
except OSError as err:
print("OS error: {0}".format(err))
if err.errno == 99:
print(
"most likely no network card of the system has the ip address"
+ str(IP)
+ " check this with >>> ifconfig on linux or with >>> ipconfig on Windows"
)
if err.errno == 98:
print(
"an other task is blocking the connection on linux use >>> sudo netstat -ltnp | grep -w ':"
+ str(Port)
+ "' on windows use in PowerShell >>> Get-Process -Id (Get-NetTCPConnection -LocalPort "
+ str(Port)
+ ").OwningProcess"
)
raise (err)
# we need to raise an exception to prevent __init__ from returning
# otherwise a broken class instance will be created
except:
print("Unexpected error:", sys.exc_info()[0])
raise ("Unexpected error:", sys.exc_info()[0])
self.flags["Networtinited"] = True
self.packestlosforsensor = {}
self.AllSensors = {}
self.msgcount = 0
self.lastTimestamp = 0
self.Datarate = 0
self._stop_event = threading.Event()
# start thread for data processing
self.thread = threading.Thread(
target=self.run, name="Datareceiver_thread", args=()
)
self.thread.start()
print("Data receiver now running wating for packets")
def __repr__(self):
"""
Prints IP and Port as well as list of all sensors (self.AllSensors).
Returns
-------
None.
"""
return (
"Datareceiver liestening at ip "
+ str(self.params["IP"])
+ " Port "
+ str(self.params["Port"])
+ "\n Active Sensors are:"
+ str(self.AllSensors)
)
def stop(self):
"""
Stops the Datareceiver task and closes the UDP socket.
Returns
-------
None.
"""
print("Stopping DataReceiver")
self._stop_event.set()
# wait 1 second to ensure that all ques are empty before closing them
# other wise SIGPIPE is raised by os
# IMPORVEMNT use signals for this
time.sleep(1)
for key in self.AllSensors:
self.AllSensors[key].stop()
self.socket.close()
def run(self):
"""
Spwans the Datareceiver task.
Returns
-------
None.
"""
# implement stop routine
while not self._stop_event.is_set():
data, addr = self.socket.recvfrom(1500) # buffer size is 1024 bytes
wasValidData = False
wasValidDescription = False
ProtoData = messages_pb2.DataMessage()
ProtoDescription = messages_pb2.DescriptionMessage()
SensorID = 0
BytesProcessed = 4 # we need an offset of 4 sice
if data[:4] == b"DATA":
while BytesProcessed < len(data):
msg_len, new_pos = _DecodeVarint32(data, BytesProcessed)
BytesProcessed = new_pos
try:
msg_buf = data[new_pos : new_pos + msg_len]
ProtoData.ParseFromString(msg_buf)
wasValidData = True
SensorID = ProtoData.id
message = {"ProtMsg": copy.deepcopy(ProtoData), "Type": "Data"}
BytesProcessed += msg_len
except:
pass # ? no exception for wrong data type !!
if not (wasValidData or wasValidDescription):
print("INVALID PROTODATA")
pass # invalid data leave parsing routine
if SensorID in self.AllSensors:
try:
self.AllSensors[SensorID].buffer.put_nowait(message)
except:
tmp = self.packestlosforsensor[SensorID] = (
self.packestlosforsensor[SensorID] + 1
)
if tmp == 1:
print("!!!! FATAL PERFORMANCE PROBLEMS !!!!")
print(
"FIRSTTIME packet lost for sensor ID:"
+ str(SensorID)
)
print(
"DROP MESSAGES ARE ONLY PRINTETD EVERY 1000 DROPS FROM NOW ON !!!!!!!! "
)
if tmp % 1000 == 0:
print("oh no lost an other thousand packets :(")
else:
self.AllSensors[SensorID] = Sensor(SensorID)
print(
"FOUND NEW SENSOR WITH ID=hex"
+ hex(SensorID)
+ "==>dec:"
+ str(SensorID)
)
self.packestlosforsensor[
SensorID
] = 0 # initing lost packet counter
self.msgcount = self.msgcount + 1
if self.msgcount % self.params["PacketrateUpdateCount"] == 0:
print(
"received "
+ str(self.params["PacketrateUpdateCount"])
+ " packets"
)
if self.lastTimestamp != 0:
timeDIFF = time.monotonic() - self.lastTimestamp
self.Datarate = (
self.params["PacketrateUpdateCount"] / timeDIFF
)
print("Update rate is " + str(self.Datarate) + " Hz")
self.lastTimestamp = time.monotonic()
else:
self.lastTimestamp = time.monotonic()
elif data[:4] == b"DSCP":
while BytesProcessed < len(data):
msg_len, new_pos = _DecodeVarint32(data, BytesProcessed)
BytesProcessed = new_pos
try:
msg_buf = data[new_pos : new_pos + msg_len]
ProtoDescription.ParseFromString(msg_buf)
# print(msg_buf)
wasValidData = True
SensorID = ProtoDescription.id
message = {"ProtMsg": ProtoDescription, "Type": "Description"}
BytesProcessed += msg_len
except:
pass # ? no exception for wrong data type !!
if not (wasValidData or wasValidDescription):
print("INVALID PROTODATA")
pass # invalid data leave parsing routine
if SensorID in self.AllSensors:
try:
self.AllSensors[SensorID].buffer.put_nowait(message)
except:
print("packet lost for sensor ID:" + hex(SensorID))
else:
self.AllSensors[SensorID] = Sensor(SensorID)
print(
"FOUND NEW SENSOR WITH ID=hex"
+ hex(SensorID)
+ " dec==>:"
+ str(SensorID)
)
self.msgcount = self.msgcount + 1
if self.msgcount % self.params["PacketrateUpdateCount"] == 0:
print(
"received "
+ str(self.params["PacketrateUpdateCount"])
+ " packets"
)
if self.lastTimestamp != 0:
timeDIFF = time.monotonic() - self.lastTimestamp
self.Datarate = (
self.params["PacketrateUpdateCount"] / timeDIFF
)
print("Update rate is " + str(self.Datarate) + " Hz")
self.lastTimestamp = time.monotonic()
else:
self.lastTimestamp = time.monotonic()
else:
print("unrecognized packed preamble" + str(data[:5]))
def __del__(self):
"""
just for securtiy closes the socket if __del__ is called.
Returns
-------
None.
"""
self.socket.close()
def StartDumpingAllSensorsASCII(
self, folder="data", filenamePrefix="", splittime=86400, force=False
):
AllDscsCompleete = True
for SensorID in self.AllSensors:
if self.AllSensors[SensorID].Description._complete == False:
print(
"Description incompelte for sensor "
+ str(self.AllSensors[SensorID])
)
if force != True:
AllDscsCompleete = False
if AllDscsCompleete == False:
raise RuntimeError(
"not all descriptions are complete dumping not started."
" Wait until descriptions are complete or use function argument force=true to start anyway"
)
if folder != "":
if not os.path.exists(folder):
os.makedirs(folder)
filenamePrefixwFolder = os.path.join(folder, filenamePrefix)
for SensorID in self.AllSensors:
self.AllSensors[SensorID].StartDumpingToFileASCII(
filenamePrefix=filenamePrefixwFolder, splittime=splittime
)
def StopDumpingAllSensorsASCII(
self,
):
for SensorID in self.AllSensors:
self.AllSensors[SensorID].StopDumpingToFileASCII()
### classes to proces sensor descriptions
class AliasDict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.aliases = {}
def __getitem__(self, key):
return dict.__getitem__(self, self.aliases.get(key, key))
def __setitem__(self, key, value):
return dict.__setitem__(self, self.aliases.get(key, key), value)
def add_alias(self, key, alias):
self.aliases[alias] = key
class ChannelDescription:
def __init__(self, CHID):
"""
Parameters
----------
CHID : intger
ID of the channel startig with 1.
Returns
-------
None.
"""
self.Description = {
"CHID": CHID,
"PHYSICAL_QUANTITY": None,
"UNIT": None,
"RESOLUTION": None,
"MIN_SCALE": None,
"MAX_SCALE": None,
"HIERARCHY": None,
}
self._complete = False
def __getitem__(self, key):
# if key='SpecialKey':
# self.Description['SpecialKey']
return self.Description[key]
def __setitem__(self, key, item):
# if key='SpecialKey':
# self.Description['SpecialKey']
self.Description[key] = item
def __repr__(self):
"""
Prints the quantity and unit of the channel.
"""
return (
"Channel: "
+ str(self.Description["CHID"])
+ " ==>"
+ str(self.Description["PHYSICAL_QUANTITY"])
+ " in "
+ str(self.Description["UNIT"])
)
# todo override set methode
def setDescription(self, key, value):
"""
Sets an spefic key of an channel description.
Parameters
----------
key : string
PHYSICAL_QUANTITY",UNIT,RESOLUTION,MIN_SCALE or MAX_SCALE.
value : string or intger
valuie coresponding to the key.
Returns
-------
None.
"""
self.Description[key] = value
if (
self.Description["PHYSICAL_QUANTITY"] != None
and self.Description["UNIT"] != None
and self.Description["RESOLUTION"] != None
and self.Description["MIN_SCALE"] != None
and self.Description["MAX_SCALE"] != None
and self.Description["HIERARCHY"] != None
):
self._complete = True
class SensorDescription:
"""
this class is holding the Sensor description.
It's subscriptable by :
1. inter number of the channel eg.g. SensorDescription[1]
2. Name of The physical quantity SensorDescription["Temperature"]
3. Name of the data field SensorDescription["Data_01"]
"""
def __init__(self, ID=0x00000000, SensorName="undefined", fromDict=None):
"""
Parameters
----------
ID : uint32
ID of the Sensor.The default is 0x00000000
SensorName : sting
Name of the sensor.The default is "undefined".
fromDict : dict
If an Description dict is passed the Channel params will be set accordingly.
Returns
-------
None.
"""
self.ID = ID
self.SensorName = SensorName
self.has_time_ticks = False # do the data contain a 64 bit raw timestamp
self._complete = False
self.Channels = AliasDict([])
self.ChannelCount = 0
self._ChannelsComplte = 0
if type(fromDict) is dict:
try:
self.ID = fromDict["ID"]
except KeyError:
warnings.warn("ID not in Dict", RuntimeWarning)
try:
self.SensorName = fromDict["Name"]
except KeyError:
warnings.warn("Name not in Dict", RuntimeWarning)
for i in range(16):
try:
channelDict = fromDict[i]
for key in channelDict.keys():
if key == "CHID":
pass
else:
self.setChannelParam(
channelDict["CHID"], key, channelDict[key]
)
print("Channel " + str(i) + " read from dict")
except KeyError:
# ok maybe the channels are coded as string
try:
channelDict = fromDict[str(i)]
for key in channelDict.keys():
if key == "CHID":
pass
else:
self.setChannelParam(
channelDict["CHID"], key, channelDict[key]
)
print("Channel " + str(i) + " read from dict")
except KeyError:
pass
def setChannelParam(self, CHID, key, value):
"""
Set parametes for an specific channel.
Parameters
----------
CHID : intger
ID of the channel startig with 1.
key : string
PHYSICAL_QUANTITY",UNIT,RESOLUTION,MIN_SCALE or MAX_SCALE.
value : string or intger
valuie coresponding to the key.
Returns
-------
None.
"""
wasComplete = False
if CHID in self.Channels:
wasComplete = self.Channels[
CHID
]._complete # read if channel was completed before
self.Channels[CHID].setDescription(key, value)
if key == "PHYSICAL_QUANTITY":
self.Channels.add_alias(
CHID, value
) # make channels callable by their Quantity
else:
if key == "PHYSICAL_QUANTITY":
self.Channels.add_alias(
CHID, value
) # make channels callable by their Quantity
self.Channels[CHID] = ChannelDescription(CHID)
self.Channels[CHID].setDescription(key, value)
self.Channels.add_alias(
CHID, "Data_" + "{:02d}".format(CHID)
) # make channels callable by ther Data_xx name
self.ChannelCount = self.ChannelCount + 1
if wasComplete == False and self.Channels[CHID]._complete:
self._ChannelsComplte = self._ChannelsComplte + 1
if self._ChannelsComplte == self.ChannelCount:
self._complete = True
print("Description completed")
def __getitem__(self, key):
"""
Reutrns the description for an channel callable by Channel ID eg 1, Channel name eg. Data_01 or Physical PHYSICAL_QUANTITY eg. Acceleration_x.
Parameters
----------
key : sting or int
Channel ID eg 1, Channel name eg. "Data_01" or Physical PHYSICAL_QUANTITY eg. "X Acceleration".
Returns
-------
ChannelDescription
The description of the channel.
"""
# if key='SpecialKey':
# self.Description['SpecialKey']
return self.Channels[key]
def __repr__(self):
return "Descripton of" + self.SensorName + hex(self.ID)
def asDict(self):
"""
ChannelDescription as dict.
ReturnsDR.
-------
ReturnDict : dict
ChannelDescription as dict.
"""
ReturnDict = {"Name": self.SensorName, "ID": self.ID}
for key in self.Channels:
print(self.Channels[key].Description)
ReturnDict.update(
{self.Channels[key]["CHID"]: self.Channels[key].Description}
)
return ReturnDict
def getUnits(self):
units = {}
for Channel in self.Channels:
if self.Channels[Channel]["UNIT"] in units:
units[self.Channels[Channel]["UNIT"]].append(Channel)
else:
units[self.Channels[Channel]["UNIT"]] = [Channel]
return units
def getActiveChannelsIDs(self):
return self.Channels.keys()
def gethieracyasdict(self):
self.hiracydict = {}
channelsperdatasetcount = {}
# loop over all channels to extract gropus and count elemnts perfomance dosent matter since only a few channels (16 max) are expected per description
for Channel in self.Channels:
splittedhieracy = self.Channels[Channel]["HIERARCHY"].split("/")
if len(splittedhieracy) != 2:
print(self.Channels[Channel]["HIERARCHY"])
raise ValueError(
"HIERACY "
+ Channel["HIERARCHY"]
+ " is invalide since it was no split in two parts"
)
try:
splittedhieracy[1] = int(splittedhieracy[1])
except ValueError:
raise ValueError(
"HIERACY "
+ Channel["HIERARCHY"]
+ "is invalide since last part is not an integer"
)
if splittedhieracy[0] in channelsperdatasetcount:
channelsperdatasetcount[splittedhieracy[0]] = (
channelsperdatasetcount[splittedhieracy[0]] + 1
)
else:
channelsperdatasetcount[splittedhieracy[0]] = 1
print(channelsperdatasetcount)
for key in channelsperdatasetcount.keys():
self.hiracydict[key] = {
"copymask": np.zeros(channelsperdatasetcount[key]).astype(int)
}
self.hiracydict[key]["PHYSICAL_QUANTITY"] = [
None
] * channelsperdatasetcount[key]
self.hiracydict[key]["RESOLUTION"] = np.zeros(channelsperdatasetcount[key])
self.hiracydict[key]["MIN_SCALE"] = np.zeros(channelsperdatasetcount[key])
self.hiracydict[key]["MAX_SCALE"] = np.zeros(channelsperdatasetcount[key])
# print(self.hiracydict)
# loop a second time infecient but don't care error check no nessary since done before
# no align chann
for Channel in self.Channels:
splittedhieracy = self.Channels[Channel]["HIERARCHY"].split("/")
self.hiracydict[splittedhieracy[0]]["copymask"][int(splittedhieracy[1])] = (
self.Channels[Channel]["CHID"] - 1
)
self.hiracydict[splittedhieracy[0]]["MIN_SCALE"][
int(splittedhieracy[1])
] = self.Channels[Channel]["MIN_SCALE"]
self.hiracydict[splittedhieracy[0]]["MAX_SCALE"][
int(splittedhieracy[1])
] = self.Channels[Channel]["MAX_SCALE"]
self.hiracydict[splittedhieracy[0]]["RESOLUTION"][
int(splittedhieracy[1])
] = self.Channels[Channel]["RESOLUTION"]
self.hiracydict[splittedhieracy[0]]["PHYSICAL_QUANTITY"][
int(splittedhieracy[1])
] = self.Channels[Channel]["PHYSICAL_QUANTITY"]
self.hiracydict[splittedhieracy[0]]["UNIT"] = self.Channels[Channel][
"UNIT"
] # tehy ned to have the same unit by definition so we will over write it mybe some times but will not change anny thing
print(self.hiracydict)
return self.hiracydict
class Sensor:
"""Class for Processing the Data from Datareceiver class. All instances of this class will be swaned in Datareceiver.AllSensors
.. image:: ../doc/Sensor_loop.png
"""
StrFieldNames = [
"str_Data_01",
"str_Data_02",
"str_Data_03",
"str_Data_04",
"str_Data_05",
"str_Data_06",
"str_Data_07",
"str_Data_08",
"str_Data_09",
"str_Data_10",
"str_Data_11",
"str_Data_12",
"str_Data_13",
"str_Data_14",
"str_Data_15",
"str_Data_16",
]
FFieldNames = [
"f_Data_01",
"f_Data_02",
"f_Data_03",
"f_Data_04",
"f_Data_05",
"f_Data_06",
"f_Data_07",
"f_Data_08",
"f_Data_09",
"f_Data_10",
"f_Data_11",
"f_Data_12",
"f_Data_13",
"f_Data_14",
"f_Data_15",
"f_Data_16",
]
DescriptionTypNames = {
0: "PHYSICAL_QUANTITY",
1: "UNIT",
2: "UNCERTAINTY_TYPE",
3: "RESOLUTION",
4: "MIN_SCALE",
5: "MAX_SCALE",
6: "HIERARCHY",
}
def __init__(self, ID, BufferSize=25e5):
"""
Constructor for the Sensor class
Parameters
----------
ID : uint32
ID of the Sensor.
BufferSize : integer, optional
Size of the Data Queue. The default is 25e5.
Returns
-------
None.
"""
self.Description = SensorDescription(ID, "Name not Set")
self.buffer = Queue(int(BufferSize))
self.buffersize = BufferSize
self.flags = {
"DumpToFile": False,
"DumpToFileProto": False,
"DumpToFileASCII": False,
"PrintProcessedCounts": True,
"callbackSet": False,
}
self.params = {"ID": ID, "BufferSize": BufferSize, "DumpFileName": ""}
self.DescriptionsProcessed = AliasDict(
{
"PHYSICAL_QUANTITY": False,
"UNIT": False,
"UNCERTAINTY_TYPE": False,
"RESOLUTION": False,
"MIN_SCALE": False,
"MAX_SCALE": False,
"HIERARCHY": False,
}
)
for i in range(7):
self.DescriptionsProcessed.add_alias(self.DescriptionTypNames[i], i)
self._stop_event = threading.Event()
self.thread = threading.Thread(
target=self.run, name="Sensor_" + str(ID) + "_thread", args=()
)
# self.thread.daemon = True
self.thread.start()
self.ProcessedPacekts = 0
self.datarate = 0
self.timeoutOccured = False
self.timeSinceLastPacket = 0
self.ASCIIDumpStartTime = None
self.ASCIIDumpFileCount = 0
self.ASCIIDumpFilePrefix = ""
self.ASCIIDumpSplittime = 86400
self.ASCIIDumpNextSplittime = 0
def __repr__(self):
"""
prints the Id and sensor name.
Returns
-------
None.
"""
return hex(self.Description.ID) + " " + self.Description.SensorName
def StartDumpingToFileASCII(self, filenamePrefix="", splittime=86400):
"""
Activate dumping Messages in a file ASCII encoded ; seperated.
Parameters
----------
filename : path
path to the dumpfile.
Returns
-------
None.
"""
self.ASCIIDumpFilePrefix = filenamePrefix
self.ASCIIDumpStartTime = time.monotonic()
self.ASCIIDumpStartTimeLocal = datetime.datetime.now()
self.flags["DumpToFileASCII"] = True
if splittime > 0:
self.ASCIIDumpSplittime = splittime
self.initNewASCIIFile()
def initNewASCIIFile(self):
try:
self.DumpfileASCII.close()
except:
pass # the file is not opend or existing and there fore cant be closed
filename = os.path.join(
self.ASCIIDumpFilePrefix,
self.ASCIIDumpStartTimeLocal.strftime("%Y%m%d%H%M%S")
+ "_"
+ str(self.Description.SensorName).replace(" ", "_")
+ "_"
+ hex(self.Description.ID)
+ "_"
+ str(self.ASCIIDumpFileCount).zfill(5)
+ ".dump",
)
print("created new dumpfile " + filename)
self.DumpfileASCII = open(filename, "a")
json.dump(self.Description.asDict(), self.DumpfileASCII)
self.DumpfileASCII.write("\n")
self.DumpfileASCII.write(
"id;sample_number;unix_time;unix_time_nsecs;time_uncertainty;Data_01;Data_02;Data_03;Data_04;Data_05;Data_06;Data_07;Data_08;Data_09;Data_10;Data_11;Data_12;Data_13;Data_14;Data_15;Data_16\n"
)
self.params["DumpFileNameASCII"] = filename
self.ASCIIDumpFileCount = self.ASCIIDumpFileCount + 1
self.ASCIIDumpNextSplittime = (
self.ASCIIDumpStartTime + self.ASCIIDumpSplittime * self.ASCIIDumpFileCount
)
def StopDumpingToFileASCII(self):
"""
Stops dumping to file ASCII encoded.
Returns
-------
None.
"""
self.flags["DumpToFileASCII"] = False
self.params["DumpFileNameASCII"] = ""
self.DumpfileASCII.close()
self.ASCIIDumpFileCount = 0
def StartDumpingToFileProto(self, filename=""):
"""
Activate dumping Messages in a file ProtBuff encoded \\n seperated.
Parameters
----------
filename : path
path to the dumpfile.
Returns
-------
None.
"""
# check if the path is valid
# if(os.path.exists(os.path.dirname(os.path.abspath('data/dump.csv')))):
if filename == "":
now = datetime.now()
filename = (
"data/"
+ now.strftime("%Y%m%d%H%M%S")
+ "_"
+ str(self.Description.SensorName).replace(" ", "_")
+ "_"
+ hex(self.Description.ID)
+ ".protodump"
)
self.DumpfileProto = open(filename, "a")
json.dump(self.Description.asDict(), self.DumpfileProto)
self.DumpfileProto.write("\n")
self.DumpfileProto = open(filename, "ab")
self.params["DumpFileNameProto"] = filename
self.flags["DumpToFileProto"] = True
def StopDumpingToFileProto(self):
"""
Stops dumping to file Protobuff encoded.
Returns
-------
None.
"""
self.flags["DumpToFileProto"] = False
self.params["DumpFileNameProto"] = ""
self.DumpfileProto.close()
def run(self):
"""
Starts the Sensor loop.
-------
None.
"""
while not self._stop_event.is_set():
# problem when we are closing the queue this function is waiting for data and raises EOF error if we delet the q
# work around adding time out so self.buffer.get is returning after a time an thestop_event falg can be checked
try:
message = self.buffer.get(timeout=0.1)
self.timeoutOccured = False
self.ProcessedPacekts = self.ProcessedPacekts + 1
if self.flags["PrintProcessedCounts"]:
if self.ProcessedPacekts % 10000 == 0:
print(
"processed 10000 packets in receiver for Sensor ID:"
+ hex(self.params["ID"])
+ " Packets in Que "
+ str(self.buffer.qsize())
+ " -->"
+ str((self.buffer.qsize() / self.buffersize) * 100)
+ "%"
)
if message["Type"] == "Description":
Description = message["ProtMsg"]
try:
if (
not any(self.DescriptionsProcessed.values())
and Description.IsInitialized()
):
# run only if no description packed has been procesed ever
# self.Description.SensorName=message.Sensor_name
print(
"Found new description "
+ Description.Sensor_name
+ " sensor with ID:"
+ str(self.params["ID"])
)
# print(str(Description.Description_Type))
if(Description.has_time_ticks==True):
print("Raw tick detected for " +Description.Sensor_name
+ " sensor with ID:"
+ str(self.params["ID"]))
self.Description.has_time_ticks =True
if (
self.DescriptionsProcessed[Description.Description_Type]
== False
):
if self.Description.SensorName == "Name not Set":
self.Description.SensorName = Description.Sensor_name
# we havent processed thiss message before now do that
if Description.Description_Type in [
0,
1,
2,
6,
]: # ["PHYSICAL_QUANTITY","UNIT","UNCERTAINTY_TYPE"]
# print(Description)
# string Processing
FieldNumber = 1
for StrField in self.StrFieldNames:
if Description.HasField(StrField):
self.Description.setChannelParam(
FieldNumber,
self.DescriptionTypNames[
Description.Description_Type
],
Description.__getattribute__(StrField),
)
# print(str(FieldNumber)+' '+Description.__getattribute__(StrField))
FieldNumber = FieldNumber + 1
self.DescriptionsProcessed[
Description.Description_Type
] = True
# print(self.DescriptionsProcessed)
if Description.Description_Type in [
3,
4,
5,
]: # ["RESOLUTION","MIN_SCALE","MAX_SCALE"]
self.DescriptionsProcessed[
Description.Description_Type
] = True
FieldNumber = 1
for FloatField in self.FFieldNames:
if Description.HasField(FloatField):
self.Description.setChannelParam(
FieldNumber,
self.DescriptionTypNames[
Description.Description_Type
],
Description.__getattribute__(FloatField),
)
# print(str(FieldNumber)+' '+str(Description.__getattribute__(FloatField)))
FieldNumber = FieldNumber + 1
# print(self.DescriptionsProcessed)
# string Processing
except Exception:
print(
" Sensor id:"
+ hex(self.params["ID"])
+ "Exception in user Description parsing:"
)
print("-" * 60)
traceback.print_exc(file=sys.stdout)
print("-" * 60)