forked from bensherlock/nm3-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnm3networksimulator.py
More file actions
1770 lines (1371 loc) · 71.9 KB
/
nm3networksimulator.py
File metadata and controls
1770 lines (1371 loc) · 71.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
#
# NM V3 Network Simulator
#
# This file is part of NM3 Python Driver.
# https://github.com/bensherlock/nm3-python-driver
#
#
# MIT License
#
# Copyright (c) 2020 Benjamin Sherlock <benjamin.sherlock@ncl.ac.uk>
# Copyright (c) 2020 Jeff Neasham
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""NM V3 Network Simulator to test code using the Nm3 driver across multiple
nodes either on the local machine or across the network/internet. Nodes can be
software on PC or embedded hardware platforms attached to Serial Ports with
Virtual NM3 Modems on the PC connected across the network. This utility is for
testing out network protocols prior to deploying hardware at sea.
Note: the channel models are simplistic - open water without interaction from
bottom layers. Basic attenuation calculations based on range, depths, bandwidth,
transmit source level, and packet length produce probabilities of successful
packet reception at the far node. Other tools are available to produce fancier
propagation modelling if that's what you're looking for. """
# Nm3 from nm3driver - revise to take io streams (not rely just on serial port)
# MessagePacket from nm3driver
# Revise Nm3Simulator from nm3simulator - Nm3VirtualModem
# Controller takes connections from Nm3Simulator over zmq
# Virtual Channels single direction between all node pairs. Uses JN Calculations.
import argparse
import copy
import json
import math
from nm3driver import Nm3
from nm3driver import MessagePacket
from nm3logger import Nm3Logger
from queue import Queue
import random
import serial
import sys
import time
from typing import Tuple, Union
#import tornado
import zmq
from zmq.eventloop.zmqstream import ZMQStream
#from zmq.eventloop.ioloop import IOLoop
from tornado.ioloop import IOLoop
def _debug_print(*args, **kwargs):
"""File local debug printing"""
print(*args, **kwargs)
pass
class Nm3SimulatorNode:
"""NM3 Simulator Node Information held by the Nm3SimulatorController."""
def __init__(self, unique_id):
self._unique_id = unique_id
self._node_address = 255
self._node_depth = 100.0
self._node_position_xy = (0.0, 0.0)
def __call__(self):
return self
@property
def unique_id(self):
return self._unique_id
@property
def node_address(self) -> int:
return self._node_address
@node_address.setter
def node_address(self, node_address: int):
self._node_address = node_address
@property
def node_depth(self) -> float:
return self._node_depth
@node_depth.setter
def node_depth(self, node_depth: float):
self._node_depth = node_depth
@property
def node_position_xy(self) -> Tuple[float, float]:
return self._node_position_xy
@node_position_xy.setter
def node_position_xy(self, node_position_xy: Tuple[float, float]):
self._node_position_xy = node_position_xy
class TimePacket:
"""Time Packet Class"""
def __init__(self):
# There...
self._client_transmit_time = 0.0
self._server_arrival_time = 0.0
# ...and back again
self._server_transmit_time = 0.0
self._client_arrival_time = 0.0
def __call__(self):
return self
@property
def client_transmit_time(self):
return self._client_transmit_time
@client_transmit_time.setter
def client_transmit_time(self, client_transmit_time):
self._client_transmit_time = client_transmit_time
@property
def server_arrival_time(self):
return self._server_arrival_time
@server_arrival_time.setter
def server_arrival_time(self, server_arrival_time):
self._server_arrival_time = server_arrival_time
@property
def server_transmit_time(self):
return self._server_transmit_time
@server_transmit_time.setter
def server_transmit_time(self, server_transmit_time):
self._server_transmit_time = server_transmit_time
@property
def client_arrival_time(self):
return self._client_arrival_time
@client_arrival_time.setter
def client_arrival_time(self, client_arrival_time):
self._client_arrival_time = client_arrival_time
@property
def offset(self):
time_offset = (self._server_arrival_time - self._client_transmit_time) \
+ (self._server_transmit_time - self._client_arrival_time) / 2.0
return time_offset
@property
def delay(self):
round_trip_delay = (self._client_arrival_time - self._client_transmit_time) \
- (self._server_transmit_time - self._server_arrival_time)
return round_trip_delay
def calculate_offset(self):
"""Calculate the offset."""
# Clock synchronization algorithm from
# https://en.wikipedia.org/wiki/Network_Time_Protocol
time_offset = (self._server_arrival_time - self._client_transmit_time) \
+ (self._server_transmit_time - self._client_arrival_time) / 2.0
round_trip_delay = (self._client_arrival_time - self._client_transmit_time) \
- (self._server_transmit_time - self._server_arrival_time)
return time_offset
def json(self):
"""Returns a json dictionary representation."""
jason = {"ClientTransmitTime": self._client_transmit_time,
"ServerArrivalTime": self._server_arrival_time,
"ServerTransmitTime": self._server_transmit_time,
"ClientArrivalTime": self._client_arrival_time }
return jason
@staticmethod
def from_json(jason): # -> Union[TimePacket, None]:
time_packet = TimePacket()
time_packet.client_transmit_time = jason["ClientTransmitTime"]
time_packet.server_arrival_time = jason["ServerArrivalTime"]
time_packet.server_transmit_time = jason["ServerTransmitTime"]
time_packet.client_arrival_time = jason["ClientArrivalTime"]
return time_packet
def to_string(self):
return "TimePacket:" \
+ "\n client_transmit_time = " + str(self.client_transmit_time) \
+ "\n server_arrival_time = " + str(self.server_arrival_time) \
+ "\n server_transmit_time = " + str(self.server_transmit_time) \
+ "\n client_arrival_time = " + str(self.client_arrival_time) \
+ "\n offset = " + str(self.offset) \
+ "\n delay = " + str(self.delay)
class NodePacket:
"""Node Packet class."""
def __init__(self, position_xy=(0.0,0.0), depth=10.0):
self._position_xy = position_xy
self._depth = depth
@property
def position_xy(self):
return self._position_xy
@position_xy.setter
def position_xy(self, position_xy):
self._position_xy = position_xy
@property
def depth(self):
return self._depth
@depth.setter
def depth(self, depth):
self._depth = depth
def json(self):
"""Returns a json dictionary representation."""
jason = {"PositionXY": { "x": self._position_xy[0], "y": self._position_xy[1] },
"Depth": self._depth}
return jason
@staticmethod
def from_json(jason): # -> Union[NodePacket, None]:
node_packet = NodePacket(position_xy=(jason["PositionXY"]["x"], jason["PositionXY"]["y"]),
depth=jason["Depth"])
return node_packet
class AcousticPacket:
"""Acoustic Packet class.
PACKET MESSAGE HEADER STRUCTURE
LFM (UP / DN) Payload Length CMD Address (Src / Dest) Packet Type
===============================================================================================
UP 0 0 Dest Ping Request
DN 1 Src Ack / Ping Response
UP 2 Dest Test Message Request
UP 3 Dest VBatt Request
UP 1-63 0 Dest Unicast Message
UP 1 Src Broadcast Message
UP 2 Dest Unicast Message With Ack Request
UP 3 Dest Echo Message Request
"""
FRAMESYNCH_UP, FRAMESYNCH_DN = range(2)
CMD_PING_REQ, CMD_PING_REP, CMD_TEST_REQ, CMD_VBATT_REQ = range(4)
CMD_UNICAST_MSG, CMD_BROADCAST_MSG, CMD_UNICAST_ACK_MSG, CMD_ECHO_MSG = range(4)
def __init__(self, frame_synch=FRAMESYNCH_UP, address=255, command=CMD_PING_REQ, payload_length=0, payload_bytes=None, hamr_timestamp=0.0):
#AcousticPacket: { FrameSynch: Up/Dn, Address: 0-255, Command: 0-3, PayloadLength: 0-64, PayloadBytes: bytes(0-64) }
self._frame_synch = frame_synch
self._address = address
self._command = command
self._payload_length = payload_length
self._payload_bytes = payload_bytes
self._hamr_timestamp = hamr_timestamp
@property
def frame_synch(self):
return self._frame_synch
@frame_synch.setter
def frame_synch(self, frame_synch):
self._frame_synch = frame_synch
@property
def address(self):
return self._address
@address.setter
def address(self, address):
self._address = address
@property
def command(self):
return self._command
@command.setter
def command(self, command):
self._command = command
@property
def payload_length(self):
return self._payload_length
@payload_length.setter
def payload_length(self, payload_length):
self._payload_length = payload_length
@property
def payload_bytes(self):
return self._payload_bytes
@payload_bytes.setter
def payload_bytes(self, payload_bytes):
self._payload_bytes = payload_bytes
@property
def hamr_timestamp(self):
return self._hamr_timestamp
@hamr_timestamp.setter
def hamr_timestamp(self, hamr_timestamp):
self._hamr_timestamp = hamr_timestamp
def json(self):
"""Returns a json dictionary representation."""
jason = {"FrameSynch": self._frame_synch,
"Address": self._address,
"Command": self._command,
"PayloadLength": self._payload_length,
"PayloadBytes": self._payload_bytes,
"HamrTimestamp": self._hamr_timestamp}
return jason
@staticmethod
def from_json(jason): # -> Union[AcousticPacket, None]:
acoustic_packet = AcousticPacket(frame_synch=jason["FrameSynch"],
address=jason["Address"],
command=jason["Command"],
payload_length=jason["PayloadLength"],
payload_bytes=jason["PayloadBytes"],
hamr_timestamp=jason["HamrTimestamp"])
return acoustic_packet
class Nm3PropagationModelBase:
"""Propagation Model for packet transmission between two nodes.
Extend this class and provide to the Controller."""
def calculate_propagation(self, nm3_simulator_source_node: Nm3SimulatorNode,
nm3_simulator_destination_node: Nm3SimulatorNode,
acoustic_packet: AcousticPacket = None):
"""Calculate the propagation delay of acoustic packet from source to destination node.
Returns propagation_delay and probability. (probability will always be 1.0)."""
x0 = nm3_simulator_source_node.node_position_xy[0]
y0 = nm3_simulator_source_node.node_position_xy[1]
z0 = nm3_simulator_source_node.node_depth
x1 = nm3_simulator_destination_node.node_position_xy[0]
y1 = nm3_simulator_destination_node.node_position_xy[1]
z1 = nm3_simulator_destination_node.node_depth
# Please note: This is a **very** simplistic model to just get us started.
# Assuming no losses. And isovelocity. And no obstructions. And no multipath. And no noise.
# The joy of simulation.
straight_line_range = math.sqrt(
((x1 - x0) * (x1 - x0)) + ((y1 - y0) * (y1 - y0)) + ((z1 - z0) * (z1 - z0)))
speed_of_sound = 1500.0
propagation_delay = straight_line_range / speed_of_sound
probability = 1.0
return propagation_delay, probability
class Nm3PERPropagationModel(Nm3PropagationModelBase):
"""Simplified packet delivery model specifically for the NM3 signals.
Note: This is a very simplistic model (overlooking complexities of propagation, refraction
and non-gaussian noise sources) and only provides indicative performance to support network
protocol development."""
def __init__(self):
# Constants
# NM3 Properties
self._nm3_source_level = 168.0 # source level in dB re 1uPa @ 1m
self._nm3_bandwidth = 8000.0 # signal bandwidth
# packet error rate PER vs SNR in dB (from simulations in severe multipath channel)
# Anything -2dB and below is considered 100% lost.
# Anything above 6dB is considered 100% successful
self._snr_vs_per_results = [(-2, 1.0), (-1, 0.8), (0, 0.4), (1, 0.23), (2, 0.09),
(3, 0.03), (4, 0.01), (5, 0.003), (6, 0.001)]
# Sound velocity
self._sound_velocity = 1520.0
# Alpha. Attenuation coefficient in dB/km at 28 kHz (e.g. 6 for North Sea Summer,
# 0.3 for Loch Ness Winter)
self._attenuation_alpha = 6.0
# NSL. ambient noise spectral density in dB re 1uPa^2/Hz at Sea State 6
# (see Wenz Curves at 28 kHz)
self._noise_spectral_density = 50.0
@property
def sound_velocity(self):
return self._sound_velocity
@sound_velocity.setter
def sound_velocity(self, sound_velocity):
self._sound_velocity = sound_velocity
@property
def attenuation_alpha(self):
return self._attenuation_alpha
@attenuation_alpha.setter
def attenuation_alpha(self, attenuation_alpha):
self._attenuation_alpha = attenuation_alpha
@property
def noise_spectral_density(self):
return self._noise_spectral_density
@noise_spectral_density.setter
def noise_spectral_density(self, noise_spectral_density):
self._noise_spectral_density = noise_spectral_density
def calculate_propagation(self, nm3_simulator_source_node: Nm3SimulatorNode,
nm3_simulator_destination_node: Nm3SimulatorNode,
acoustic_packet: AcousticPacket = None):
"""Note: This is a very simplistic model (overlooking complexities of propagation,
refraction and non-gaussian noise sources) and only provides indicative performance to
support network protocol development."""
x0 = nm3_simulator_source_node.node_position_xy[0]
y0 = nm3_simulator_source_node.node_position_xy[1]
z0 = nm3_simulator_source_node.node_depth
source_depth = z0
x1 = nm3_simulator_destination_node.node_position_xy[0]
y1 = nm3_simulator_destination_node.node_position_xy[1]
z1 = nm3_simulator_destination_node.node_depth
straight_line_range = math.sqrt(
((x1 - x0) * (x1 - x0)) + ((y1 - y0) * (y1 - y0)) + ((z1 - z0) * (z1 - z0)))
# calculate transmission + propagation delay
propagation_delay = straight_line_range / self._sound_velocity
# calculate transmission loss (free field spreading) TL
transmission_loss = 20.0 * math.log10(straight_line_range) + self._attenuation_alpha * straight_line_range * 0.001
# estimated noise power from ambient NL
noise_loss = self._noise_spectral_density + 10.0 * math.log10(self._nm3_bandwidth)
# calculate received SNR (SONAR equation)
received_snr = self._nm3_source_level - transmission_loss - noise_loss
# add crude depth dependence of transmitter (-6 dB on surface, ~0 at 10m, +3dB at 100m)
received_snr = received_snr + 3.0 * math.log10(source_depth + 0.1) - 3.0
# Search for packet error rate based on received SNR
#
# round SNR to nearest integer
rounded_snr = int(round(received_snr))
if rounded_snr < self._snr_vs_per_results[0][0]: # out of range?
probability_of_delivery = 0.0
elif rounded_snr > self._snr_vs_per_results[-1][0]:
probability_of_delivery = 1.0 # short range?
else:
# read PER from table and convert to Pd
start_snr = self._snr_vs_per_results[0][0]
per = self._snr_vs_per_results[rounded_snr - start_snr][1]
probability_of_delivery = 1.0 - per
#print("received_snr=" + "{:0.2f}".format(received_snr) \
# + " propagation_delay=" + "{:0.2f}".format(propagation_delay) \
# + " probability_of_delivery=" + "{:0.2f}".format(probability_of_delivery))
return propagation_delay, probability_of_delivery
class Nm3SimulatorController:
"""NM3 Simulator Controller. """
def __init__(self, network_address=None, network_port=None):
self._network_address = network_address
self._network_port = network_port
self._socket = None
# NTP Offset to synchronise timestamps
self._ntp_offset = 0.0
# Polling version
self._socket_poller = None
# Async version
#self._socket_stream = None
#self._socket_loop = None
self._nm3_simulator_nodes = {} # Map unique_id to node
self._nm3_propagation_model = Nm3PropagationModelBase() # Default model
self._scheduled_network_packets = []
self._startup_time = time.time()
def __call__(self):
return self
@property
def nm3_propagation_model(self) -> Nm3PropagationModelBase:
return self._nm3_propagation_model
@nm3_propagation_model.setter
def nm3_propagation_model(self, nm3_propagation_model: Nm3PropagationModelBase):
self._nm3_propagation_model = nm3_propagation_model
def get_hamr_time(self, local_time=None):
"""Get Homogenous Acoustic Medium Relative time from either local_time or time.time()."""
if local_time:
hamr_time = self._ntp_offset + local_time
return hamr_time
else:
hamr_time = self._ntp_offset + time.time()
return hamr_time
def get_local_time(self, hamr_time=None):
"""Get local time from Homogenous Acoustic Medium Relative time or time.time()."""
if hamr_time:
local_time = hamr_time - self._ntp_offset
return local_time
else:
return time.time()
def add_nm3_simulator_node(self, unique_id):
"""Add a new Nm3SimulatorNode to the controller.
Return the unique id for this node."""
self._nm3_simulator_nodes[unique_id] = Nm3SimulatorNode(unique_id)
return unique_id
def has_nm3_simulator_node(self, unique_id):
"""Check if Nm3SimulatorNode exists for this unique_id."""
return unique_id in self._nm3_simulator_nodes
def delete_nm3_simulator_node(self, unique_id):
"""Delete the Nm3SimulatorNode from the controller using the id."""
self._nm3_simulator_nodes.pop(unique_id, None)
def get_nm3_simulator_node(self, unique_id) \
-> Union[Nm3SimulatorNode, None]:
"""Get a copy of the Nm3SimulatorNode from the controller by id.
Returns a copy of the Nm3SimulatorNode or None."""
if unique_id in self._nm3_simulator_nodes:
return copy.deepcopy(self._nm3_simulator_nodes[unique_id])
else:
return None
def update_nm3_simulator_node(self, nm3_simulator_node: Nm3SimulatorNode):
unique_id = nm3_simulator_node.unique_id
if unique_id in self._nm3_simulator_nodes:
self._nm3_simulator_nodes[unique_id] = nm3_simulator_node
def calculate_propagation(self, nm3_simulator_source_node: Nm3SimulatorNode,
nm3_simulator_destination_node: Nm3SimulatorNode,
acoustic_packet: AcousticPacket):
"""Calculate the propagation delay of acoustic packet from source to destination node.
Uses the model provided by the user or a fallback isovelocity if model is None.
Returns propagation_delay and probability."""
if self._nm3_propagation_model:
return self._nm3_propagation_model.calculate_propagation(
nm3_simulator_source_node=nm3_simulator_source_node,
nm3_simulator_destination_node=nm3_simulator_destination_node,
acoustic_packet=acoustic_packet)
# Fallback
x0 = nm3_simulator_source_node.node_position_xy[0]
y0 = nm3_simulator_source_node.node_position_xy[1]
z0 = nm3_simulator_source_node.node_depth
x1 = nm3_simulator_destination_node.node_position_xy[0]
y1 = nm3_simulator_destination_node.node_position_xy[1]
z1 = nm3_simulator_destination_node.node_depth
# Please note: This is a **very** simplistic model to just get us started.
# Assuming no losses. And isovelocity. And no obstructions. And no multipath. And no noise.
# The joy of simulation.
straight_line_range = math.sqrt(((x1-x0)*(x1-x0)) + ((y1-y0)*(y1-y0)) + ((z1-z0)*(z1-z0)))
speed_of_sound = 1500.0
propagation_delay = straight_line_range / speed_of_sound
return propagation_delay, 1.0
def schedule_network_packet(self, transmit_time, unique_id, network_packet_json_string):
"""Schedule a network packet transmission."""
self._scheduled_network_packets.append( (transmit_time, unique_id, network_packet_json_string) )
self._scheduled_network_packets.sort(key=lambda tup: tup[0]) # sort by time
def next_scheduled_network_packet(self, current_time):
"""Get the next scheduled network packet to be transmitted at the current time."""
if self._scheduled_network_packets and self._scheduled_network_packets[0][0] <= current_time:
scheduled_network_packet = self._scheduled_network_packets.pop(0)
unique_id = scheduled_network_packet[1]
network_packet_json_string = scheduled_network_packet[2]
return unique_id, network_packet_json_string
return None, None
def on_recv(self, msg):
"""Callback handler for on_recv."""
#unique_id, network_message_json_bytes = self._socket.recv_multipart(zmq.DONTWAIT) # blocking
unique_id = msg[0]
network_message_json_bytes = msg[1]
zmq_timestamp = float(msg[2].decode('utf-8'))
local_received_time = time.time()
_debug_print("NetworkPacket (len=" + str(len(msg)) + ") from " + str(unique_id) + " received at: " + str(local_received_time))
network_message_json_str = network_message_json_bytes.decode('utf-8')
network_message_jason = json.loads(network_message_json_str)
# _debug_print("Network Packet received from: " + str(unique_id) + " -- " + network_message_json_str)
if "TimePacket" in network_message_jason:
# Quick Turnaround
time_packet = TimePacket.from_json(network_message_jason["TimePacket"])
time_packet.server_arrival_time = local_received_time
#time_packet.client_transmit_time = zmq_timestamp
time_packet.server_transmit_time = time.time()
new_network_message_jason = {"TimePacket": time_packet.json()}
new_network_message_json_str = json.dumps(new_network_message_jason)
self._socket.send_multipart([unique_id, new_network_message_json_str.encode('utf-8'), str(time.time()).encode('utf-8')])
if not self.has_nm3_simulator_node(unique_id):
self.add_nm3_simulator_node(unique_id)
if "NodePacket" in network_message_jason:
nm3_simulator_node = self.get_nm3_simulator_node(unique_id)
if nm3_simulator_node:
node_packet = NodePacket.from_json(network_message_jason["NodePacket"])
nm3_simulator_node.node_position_xy = node_packet.position_xy
nm3_simulator_node.node_depth = node_packet.depth
self.update_nm3_simulator_node(nm3_simulator_node)
if "AcousticPacket" in network_message_jason:
# Send to all nodes, except this one
# For now this is instant: no propagation, or probability, or filtering.
acoustic_packet = AcousticPacket.from_json(network_message_jason["AcousticPacket"])
# Process Channels and Scheduling of acoustic_packet
# This would need updating if the receiving node changes its position - work this out later.
# Get source position Information
nm3_simulator_source_node = self.get_nm3_simulator_node(unique_id)
hamr_received_time = acoustic_packet.hamr_timestamp
for socket_id in self._nm3_simulator_nodes:
# Don't send to itself
if socket_id != unique_id:
# Get destination position Information
nm3_simulator_destination_node = self.get_nm3_simulator_node(socket_id)
# Calculate propagation
acoustic_packet.hamr_timestamp = hamr_received_time
propagation_delay, probability = self.calculate_propagation(
nm3_simulator_source_node, nm3_simulator_destination_node,
acoustic_packet)
# Check probability
if random.random() < probability:
# Calculate a transmit_time
hamr_transmit_time = hamr_received_time + propagation_delay
local_transmit_time = self.get_local_time(hamr_transmit_time)
acoustic_packet.hamr_timestamp = hamr_transmit_time
new_network_message_jason = {"AcousticPacket": acoustic_packet.json()}
new_network_message_json_str = json.dumps(new_network_message_jason)
self.schedule_network_packet(local_transmit_time, socket_id,
new_network_message_json_str)
# IOLoop set the callback
#IOLoop.instance().call_at(local_transmit_time, self.check_for_packets_to_send)
#for s in self._scheduled_network_packets:
# print(s)
def check_for_packets_to_send(self):
"""Check for packets to send."""
socket_id, network_packet_json_str = self.next_scheduled_network_packet(time.time())
while socket_id:
#_debug_print("Sending scheduled network packet: " + str(socket_id) + " - " + network_packet_json_str)
self._socket.send_multipart([socket_id, network_packet_json_str.encode('utf-8'), str(time.time()).encode('utf-8')])
sent_time = time.time()
_debug_print("NetworkPacket to " + str(socket_id) + "sent at: " + str(sent_time))
# Get next scheduled network Packet
socket_id, network_packet_json_str = self.next_scheduled_network_packet(time.time())
def start(self):
"""Start the simulation. Bind to the address and port ready for
virtual nodes."""
if not self._network_address or not self._network_port:
raise TypeError("Network Address/Port not set. Address("
+ self._network_address
+ ") Port( "
+ str(self._network_port) + ")" )
if self._socket:
# Already created?
pass
else:
# https://stackoverflow.com/questions/38978804/zeromq-master-slave-two-way-communication
# https://stackoverflow.com/questions/34242316/pyzmq-recv-json-cant-decode-message-sent-by-send-json
context = zmq.Context()
self._socket = context.socket(zmq.ROUTER)
socket_string = "tcp://" + self._network_address + ":"+ str(self._network_port)
print("Binding to: " + socket_string)
self._socket.bind(socket_string)
#print("HWM:" + str(self._socket.hwm))
# Polling version
self._socket_poller = zmq.Poller()
self._socket_poller.register(self._socket, zmq.POLLIN)
# Async version
#self._socket_loop = IOLoop()
#self._socket_stream = ZMQStream(self._socket)
#self._socket_stream.on_recv(self.on_recv)
#self._socket_loop.start()
#IOLoop.instance().start() # Stays here
while True:
# Poll the socket
# Router socket so first frame of multi part message is an identifier for the client.
# Incoming Network Messages
# NetworkMessage {
# 1. AcousticPacket: { FrameSynch: Up/Dn, Address: 0-255, Command: 0-3, PayloadLength: 0-64, PayloadBytes: bytes(0-64) }
# 2. NodePacket: { PositionXY: {x: float, y: float}, Depth: float }
# }
# Poll the socket for incoming messages
# _debug_print("Checking socket poller")
sockets = dict(self._socket_poller.poll(1))
if self._socket in sockets:
more_messages = True
while more_messages:
try:
#unique_id, network_message_json_bytes = self._socket.recv_multipart(zmq.DONTWAIT) # blocking
msg = self._socket.recv_multipart(zmq.DONTWAIT) # blocking
self.on_recv(msg)
except zmq.ZMQError:
more_messages = False
# Get next scheduled network Packet
self.check_for_packets_to_send()
class Nm3VirtualModem:
"""NM3 Virtual Modem Class.
Connects over network to Nm3SimulatorController.
Currently supports: Query ($?), Set Local Address ($Axxx), Ping ($Pxxx),
Broadcast Message ($Byydd...dd), Unicast Message ($Uxxxyydd..dd),
Unicast with Ack Message ($Mxxxyydd..dd)."""
SIMULATOR_STATE_IDLE, SIMULATOR_STATE_COMMAND, \
SIMULATOR_STATE_SET_ADDRESS, SIMULATOR_STATE_PING, SIMULATOR_STATE_TEST, \
SIMULATOR_STATE_MESSAGE_ADDRESS, SIMULATOR_STATE_MESSAGE_LENGTH, \
SIMULATOR_STATE_MESSAGE_DATA = range(8)
SIMULATOR_STATE_NAMES = {
SIMULATOR_STATE_IDLE: 'Idle',
SIMULATOR_STATE_COMMAND: 'Command',
SIMULATOR_STATE_SET_ADDRESS: 'SetAddress',
SIMULATOR_STATE_PING: 'Ping',
SIMULATOR_STATE_TEST: 'Test',
SIMULATOR_STATE_MESSAGE_ADDRESS: 'MessageAddress',
SIMULATOR_STATE_MESSAGE_LENGTH: 'MessageLength',
SIMULATOR_STATE_MESSAGE_DATA: 'MessageData',
}
SIMULATOR_STATES = (SIMULATOR_STATE_IDLE, SIMULATOR_STATE_COMMAND,
SIMULATOR_STATE_SET_ADDRESS, SIMULATOR_STATE_PING, SIMULATOR_STATE_TEST,
SIMULATOR_STATE_MESSAGE_ADDRESS, SIMULATOR_STATE_MESSAGE_LENGTH,
SIMULATOR_STATE_MESSAGE_DATA)
ACOUSTIC_STATE_IDLE, ACOUSTIC_STATE_WAIT_ACK = range(2)
ACOUSTIC_STATE_NAMES = {
ACOUSTIC_STATE_IDLE: 'Idle',
ACOUSTIC_STATE_WAIT_ACK: 'WaitAck',
}
ACOUSTIC_STATES = (ACOUSTIC_STATE_IDLE, ACOUSTIC_STATE_WAIT_ACK)
BYTE_PARSER_TIMEOUT = 0.100
def __init__(self, input_stream, output_stream,
network_address=None, network_port=None, local_address: int =255, position_xy=(0.0,0.0), depth=10.0):
"""input_stream and output_stream implement the Bytes IO interface.
Namely: readable()->bool, writeable()->bool, read(bytes) and write(bytes)."""
self._input_stream = input_stream
self._output_stream = output_stream
self._simulator_state = self.SIMULATOR_STATE_IDLE
self._acoustic_state = self.ACOUSTIC_STATE_IDLE
self._acoustic_ack_wait_address = None
self._acoustic_ack_wait_time = None
self._acoustic_ack_fixed_offset_time = 0.040 # 40ms
self._network_address = network_address
self._network_port = network_port
self._socket = None
self._socket_poller = None
# Offset to synchronise times
self._hamr_time_offset = 0.0
self._local_address = local_address
# Parser variables
self._last_byte_time = None
self._current_byte_counter = 0
self._current_integer = 0
# Sending message
self._message_type = None
self._message_address = None
self._message_length = None
self._message_bytes = None
# Positional information
self._position_xy = position_xy
self._depth = depth
self._position_information_updated = True
self._startup_time = 1602256464 #time.time()
self._local_received_time = None
self._local_sent_time = None
self._last_packet_received_time = None
self._last_packet_sent_time = None
def __call__(self):
return self
@property
def position_xy(self):
return self._position_xy
@position_xy.setter
def position_xy(self, position_xy):
self._position_xy = position_xy
self._position_information_updated = True
@property
def depth(self):
return self._depth
@depth.setter
def depth(self, depth):
self._depth = depth
self._position_information_updated = True
def get_hamr_time(self, local_time=None):
"""Get Homogenous Acoustic Medium Relative time from either local_time or time.time()."""
if local_time:
hamr_time = self._hamr_time_offset + local_time
return hamr_time
else:
hamr_time = self._hamr_time_offset + time.time()
return hamr_time
def get_local_time(self, hamr_time=None):
"""Get local time from Homogenous Acoustic Medium Relative time or time.time()."""
if hamr_time:
local_time = hamr_time - self._hamr_time_offset
return local_time
else:
return time.time()
def run(self):
"""Run the simulator. Never returns."""
# Connect to the controller
if not self._network_address or not self._network_port:
raise TypeError("Network Address/Port not set. Address("
+ self._network_address
+ ") Port( "
+ str(self._network_port) + ")" )
if self._socket:
# Already created?
pass
else:
context = zmq.Context()
self._socket = context.socket(zmq.DEALER)
self._socket.connect("tcp://" + self._network_address + ":"
+ str(self._network_port))
self._socket_poller = zmq.Poller()
self._socket_poller.register(self._socket, zmq.POLLIN)
self.send_time_packet()
while True:
if self._position_information_updated:
# Send positional information update
self._position_information_updated = False
node_packet = NodePacket(position_xy=self._position_xy, depth=self._depth)
self.send_node_packet(node_packet)
if self._input_stream and self._input_stream.readable():
#_debug_print("Checking input_stream")
some_bytes = self._input_stream.read() # Read
if some_bytes:
#_debug_print("some_bytes=" + str(some_bytes))
self.process_bytes(some_bytes)
# Poll the socket for incoming "acoustic" messages
#_debug_print("Checking socket poller")
sockets = dict(self._socket_poller.poll(1))
if self._socket in sockets:
more_messages = True
while more_messages:
try:
msg = self._socket.recv_multipart(zmq.DONTWAIT)
network_message_json_bytes = msg[0]
zmq_timestamp = float(msg[1].decode('utf-8'))
self._local_received_time = time.time()
_debug_print("NetworkPacket (len=" + str(len(msg)) + ") from Controller received at: " + str(self._local_received_time))
network_message_json_str = network_message_json_bytes.decode('utf-8')
network_message_jason = json.loads(network_message_json_str)
_debug_print("Network Packet received: " + network_message_json_str)
if "TimePacket" in network_message_jason:
# Process the TimePacket
time_packet = TimePacket.from_json(network_message_jason["TimePacket"])
time_packet.client_arrival_time = self._local_received_time
#time_packet.server_transmit_time = zmq_timestamp
self._hamr_time_offset = time_packet.calculate_offset()
print(time_packet.to_string())
print("TimePacket offset: " + str(self._hamr_time_offset))
if "AcousticPacket" in network_message_jason:
# Process the AcousticPacket
acoustic_packet = AcousticPacket.from_json(network_message_jason["AcousticPacket"])
self.process_acoustic_packet(acoustic_packet)
except zmq.ZMQError:
more_messages = False
# Check for timeout if awaiting an Ack