forked from dk850/TSN-Simu-Discrete
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTSN_Simulator.py
More file actions
2260 lines (1729 loc) · 100 KB
/
TSN_Simulator.py
File metadata and controls
2260 lines (1729 loc) · 100 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
"""
Main TSN Simulator
Specify file locations for neccesay files (Network Topo, Traffic Definition, GCL, Queue definition)
"""
##################################################
############## IMPORT AND VARIABLES ##############
##################################################
# libraries
import random
import math
import csv
from pathlib import Path
from lxml import etree
# scripts
import generator_utilities as gen_utils
import crude_topo_generator as network_topo_gen # network topology generator
import crude_queue_def_generator as queue_def_gen # queue definition generator
import crude_traffic_def_generator as traffic_def_gen # traffic definition generator
# GCL should be made manually ahdering to standards in the UML diagrams -> T(digit){-T(digit)} (8-bits)
# Traffic Rules -> ES mapping is an optional file and if not provided the simulator asks for its own paramerters
# global variables
g_timestamp = 0
g_generic_traffics_dict = {} # dictionary of generic traffic rules from file - key is ID
g_node_id_dict = {} # key is node id, value is node object
g_original_GCL = {} # store original GCL for long simulations
g_offline_GCL = {} # key is timestamp, value is the gate state at that timestamp
g_current_GCL_state = "" # state of GCL shared across entire simulator, to be changed according to GCL and timestamp
# should only change gate state if we have a key for that timestamp, else leave it as previous value
g_packet_latencies = [] # list to store a list of every packet latency
g_queueing_delays = [] # list to store every queueing delay
##################################################
################# USER SETTINGS #################
##################################################
# global enums
e_es_types = ["sensor", "control"] # possible end station types?
e_queue_schedules = ["FIFO", "EDF"] # possible queue schedules
e_queue_type_names = ["ST", "Emergency", "Sporadic_Hard", "Sporadic_Soft", "BE"] # possible queue types
# global variables to set
MAX_NODE_COUNT = 100
MAX_TRAFFIC_COUNT = 1000
MAX_TIMESTAMP = 0 # debug
SIM_DEBUG = 0 # debug for simulator to see timestamps
# random.seed(10) # for consistent experementation
# generator parameters
SENDING_SIZE_CAPCITY = 16 # size (in bytes) of frames able to be sent in 1 tick
BE_FIRE_CHANCE = 1 # 1% chance to fire best effort queue
SPORADIC_FIRE_CHANCE = 10 # 10% chance to fire both sporadic queues when possible
EMERGENCY_QUEUE_CHANCE = 5 # 5% chance an ST packet will go into the emergency queue
# specify file paths and names. These stay blank and if none provided the simulator asks the user to generate
files_directory = "simulator_files\\"
prefix = ""
network_topo_file = ""
queue_definition_file = ""
GCL_file = ""
traffic_definition_file = ""
traffic_mapping_file = ""
# manually specify the example files here if required by uncommenting this block
"""
prefix = "example"
network_topo_file = files_directory+prefix+"_network_topology.xml"
queue_definition_file = files_directory+prefix+"_queue_definition.xml"
GCL_file = files_directory+prefix+"_gcl.txt"
traffic_definition_file = files_directory+prefix+"_traffic_definition.xml"
traffic_mapping_file = files_directory+prefix+"_traffic_mapping.txt"
"""
##################################################
############## DEFINE NODES CLASSES ##############
##################################################
# node base class
class Node():
def __init__(self, id, name="unnamed"):
self.node_type = str(self.__class__.__name__) # this will be the same as the class name for each node
self.id = id # unique
self.name = name
self.ingress_traffic = []
self.egress_traffic = []
self.busy = 0 # attribute used to see how busy the node is (how many ticks it has left to complete)
def RX_packet(self, packet):
self.ingress_traffic.append(packet)
return 1
def to_string(self):
# node type
output_str = str(self.node_type) + ":"
# formatting
if self.node_type == "Controller":
output_str += " "
if self.node_type == "Switch":
output_str += " "
# attributes
output_str += " (ID: "+str(self.id)+") (Name: "+str(self.name)+")"
# display traffic gen paramerters
if self.node_type == "End_Station":
output_str += " (Type: "+str(self.t_type)+") "
return output_str
# end station type of node
class End_Station(Node):
def __init__(self, id, parent_id, name="unnamed"):
super().__init__(id, name)
self.type = e_es_types[0] # default
self.parent_id = int(parent_id)
# check if it is packet generation time and if so put new packet in egress
def check_to_generate(self):
# determine type as ST generates differently
if self.t_type == "ST":
if self.generate(): # returns true when its time to generate a packet
packet = ST(self.id, self.t_dest, self.t_delay_jitter, self.t_period, self.t_deadline,
self.t_size, self.t_name, self.t_offset)
self.egress(packet) # generate new packet and egress it
# SH
elif self.t_type == "Sporadic_Hard":
if self.generate(): # returns true when its time to generate a packet
packet = Sporadic_Hard(self.id, self.t_dest, self.t_min_release, self.t_delay_jitter, \
self.t_deadline, self.t_size, self.t_name, self.t_offset)
self.egress(packet)
# SS
elif self.t_type == "Sporadic_Soft":
if self.generate(): # returns true when its time to generate a packet
packet = Sporadic_Soft(self.id, self.t_dest, self.t_min_release, self.t_delay_jitter, \
self.t_deadline, self.t_size, self.t_name, self.t_offset)
self.egress(packet)
# BE
elif self.t_type == "BE":
if self.generate(): # returns true when its time to generate a packet
packet = BE(self.id, self.t_dest, self.t_size, self.t_name, self.t_offset)
self.egress(packet)
# else unrecognised packet
else:
print("ERROR: Unrecognised packet generation request in ES", "\""+str(self.id)+"\"")
return 1
# function to recieve packets in ingress queue
def digest_packets(self):
failed = False
if len(self.ingress_traffic) == 0: # do nothing if queue empty
return 0
# loop over all packets in ingress queue
final_ingress = self.ingress_traffic.copy()
for packet in self.ingress_traffic:
# can only digest packet from ingress if the entire packet is present
if packet.arrival_time == -1: # if it is the packets first tick in the ingress queue of the ES
if SIM_DEBUG: # debug
print("[T", str(g_timestamp).zfill(3)+"]", "Found", \
"start of "+str(packet.type)+" packet \""+str(packet.name)+"\" size \""+str(packet.size)+"\"" \
if math.ceil(int(packet.size) / SENDING_SIZE_CAPCITY) > 1 else \
str(packet.type)+" packet \""+str(packet.name)+"\"" \
, "from ES", "\""+str(packet.source)+"\"", "in destination ingress queue of ES", "\""+str(self.id)+"\"")
packet.set_arrival_time(g_timestamp) # add queue enter timestamp
# then check the packets size compared to how much we can accept per tick
if ((g_timestamp - packet.arrival_time) + 1) != math.ceil(int(packet.size) / SENDING_SIZE_CAPCITY):
continue # if it hasnt fully arrived we cant digest it. Try again next tick, move on to other packets
# else properly ingest the packet into the correct inner queue
# add latency to global list including time ES was busy receiving packet. i.e. latency is start of send until complete receive
g_packet_latencies.append(int(packet.arrival_time)-int(packet.transmission_time) + \
int(math.ceil(int(packet.size) / SENDING_SIZE_CAPCITY)) )
final_ingress.remove(packet) # remove from copy of list so we dont alter the for loop
# to check the latency of the packet hasn't extended past its deadline we need to check the types
if packet.type == "ST":
if g_packet_latencies[-1] > packet.hard_deadline:
print("CRITICAL ERROR:", str(packet.type), "packet", "\""+str(packet.name)+"\"", "from ES", "\""+str(packet.source)+"\"", \
"reached destination ES", "\""+str(self.id)+"\"", "AFTER its deadline")
failed = True
elif packet.type == "Sporadic_Hard":
if g_packet_latencies[-1] > packet.hard_deadline:
print("CRITICAL ERROR:", str(packet.type), "packet", "\""+str(packet.name)+"\"", "from ES", "\""+str(packet.source)+"\"", \
"reached destination ES", "\""+str(self.id)+"\"", "AFTER its deadline")
failed = True
elif packet.type == "Sporadic_Soft":
if g_packet_latencies[-1] > packet.soft_deadline:
print("ERROR:", str(packet.type), "packet", "\""+str(packet.name)+"\"", "from ES", "\""+str(packet.source)+"\"", \
"reached destination ES", "\""+str(self.id)+"\"", "AFTER its deadline")
failed = True
elif packet.type == "BE": # no timing constraints
pass
else:
print("ERROR: Unrecognised packet type", "\""+str(packet.type)+"\"", "has reached ES", \
"\""+str(self.id)+"\"", "ingress queue")
failed = True
if SIM_DEBUG and not failed: # for debug
print("[T", str(g_timestamp).zfill(3)+"]", "Digested", str(packet.type), "packet", \
"\""+str(packet.name)+"\"", "from source ES", "\""+str(packet.source)+"\"", \
"at final destination ES", "\""+str(self.id)+"\"", "with latency", \
"\""+str(int(packet.arrival_time)-int(packet.transmission_time))+"\"")
self.ingress_traffic = final_ingress # update queue with packets removed. Real world would act on packet here - maybe send something back
if failed:
exit() # call some recovery function here in future
return 0
else:
return 1
# function to add a packet to the egress queue with error checking
def egress(self, packet):
if SIM_DEBUG: # for debug
print("[T", str(g_timestamp).zfill(3)+"]", "Adding newly generated", str(self.t_type), "packet", \
"\""+str(packet.name)+"\"", "to egress queue of ES", "\""+str(self.id)+"\"")
# make sure packet matches a type defined at the start of the program
if packet.type in e_queue_type_names:
self.egress_traffic.append(packet)
return 1
else:
# can trigger error correction function here
print("ERROR: Attempted to add a non-traffic object to the egress queue of ES", "\""+str(self.id)+"\"")
return 0
# function to send traffic from this nodes egress queue to parent switch
def flush_egress(self):
# if busy decrease the busy counter
if self.busy > 0:
self.busy -= 1
# if not busy
if self.busy == 0:
# loop over all packets in egress queue
for packet in self.egress_traffic:
g_node_id_dict[self.parent_id].RX_packet(packet) # send the packet to the parent switches ingress queue
self.busy = math.ceil(int(packet.size) / SENDING_SIZE_CAPCITY) # how many ticks the node will be busy for
self.egress_traffic.remove(packet) # remove this packet from queue as it is being sent
if SIM_DEBUG: # for debug
print("[T", str(g_timestamp).zfill(3)+"]", "Sending", str(packet.type), "packet", \
"\""+str(packet.name)+"\"", "of size", "\""+str(self.t_size)+"\"", "to parent Switch", \
"\""+str(self.parent_id)+"\"", "from egress queue of ES", "\""+str(self.id)+"\"")
return 1
return 1
# function to be used within the packet generator that chooses when to generate a packet depending on type (simulate sporadicness)
def generate(self):
# if there is an offset, dont do anything for first N ticks
if self.t_offset != 0:
if g_timestamp < self.t_offset:
return False
# BE queue has no timing constraints. Give it a percentage chance to fire
if self.t_type == "BE":
if random.random() < BE_FIRE_CHANCE: # 1% chance to fire every tick (period ~ 100 ticks)
return True
else:
return False
elif self.t_type == "ST": # ST queue is based off its period and nothing else
if (g_timestamp-self.t_offset) % self.t_period == 0: # if we are at a multiple of its period (including offset)
return True
else:
return False
# otherwise we need to check the min_inter_release of SH or SS
# NOTE : I have commented out the t_delay_jitter parts as im not sure how this variable is used
# if it means the packet has to be sent within X ticks of being able to then this can be uncommented
if self.t_previous_fire == 0: # if first fire ignore initial min release
if random.random() < SPORADIC_FIRE_CHANCE: # the packet has a % chance to fire
self.t_previous_fire = g_timestamp
return True
else:
return False
# if self.t_delay_jitter == g_timestamp: # send if we have reached max delay jitter
# self.t_previous_fire = g_timestamp
# return True
# else:
# return False
elif (g_timestamp - self.t_previous_fire) >= self.t_min_release: # if time is equal to or greater than the min release
# if (self.t_previous_fire + self.t_min_release + self.t_delay_jitter) == g_timestamp: # send if we have reached max delay jitter
# self.t_previous_fire = g_timestamp
# return True
# else: # re-indent below
if random.random() < SPORADIC_FIRE_CHANCE: # the packet has a % chance to fire
self.t_previous_fire = g_timestamp
return True
else:
return False
else: # within min_inter_release, cant send
return False
## Setters
def set_traffic_rules(self, rules):
if 0: # for debugging
print("Rule properties:")
print("Source:", self.id)
for entry in rules:
print(entry+":", rules[entry])
print()
# erorr check destination ID is not current ID
if str(rules["destination_id"]) == str(self.id): # error check cant have destination be itself
print("CRITICAL ERROR: Cannot have Traffic rule destination_id be the same ID as the source in ES", \
"\""+str(self.id)+"\"")
return 0
# extract shared attributess
self.t_name = rules["name"]
self.t_offset = rules["offset"]
self.t_type = rules["type"]
self.t_dest = rules["destination_id"]
self.t_size = rules["size"]
# if destination_id is 0, we need to change it to a random ES ID
if int(self.t_dest) == 0:
es_list = []
# get list of end stations
for node in g_node_id_dict:
if g_node_id_dict[node].node_type == "End_Station":
es_list.append(node)
es_list.remove(self.id) # remove this end station
self.t_dest = str(random.choice(es_list)) # pick a random node from the list to set as destination
## Extract per-type attributes
if self.t_type == "ST":
self.t_period = rules["period"]
self.t_deadline = rules["hard_deadline"]
self.t_delay_jitter = rules["max_release_jitter"]
elif self.t_type == "Sporadic_Hard":
self.t_deadline = rules["hard_deadline"]
self.t_delay_jitter = rules["max_release_jitter"]
self.t_min_release = rules["min_inter_release"]
self.t_previous_fire = 0
elif self.t_type == "Sporadic_Soft":
self.t_deadline = rules["soft_deadline"]
self.t_delay_jitter = rules["max_release_jitter"]
self.t_min_release = rules["min_inter_release"]
self.t_previous_fire = 0
elif self.t_type == "BE":
pass # no timing constraints
else:
print("CRITICAL ERROR: Incorrect traffic type assigned to ES ID", "\""+str(self.id)+"\"")
return 0
return 1
def set_type(self, type):
self.type = type
return 1
# switch type of node
class Switch(Node):
def __init__(self, id, name="unnamed"):
super().__init__(id, name)
self.local_routing_table = -1 # to be set
self.available_packets = [] # dynamic list
# instance variables used for output statistics
self.packets_transmitted = 0
self.total_queue_delay = 0
self.average_queue_delay = 0.0
# queues
self.queue_definition = -1 # to be set
self.ST_queue = []
self.EM_queue = []
self.SH_queue = []
self.SS_queue = []
self.BE_queue = []
# filters packets in the ingress queue into the relevant Traffic queue within the switch according to the queue_def
def ingress_packets(self):
# if ingress queue is empty do nothing
if len(self.ingress_traffic) == 0:
return 0
# if there is more than 1 packet in the ingress queue shuffle it to avoid End Station bias
if len(self.ingress_traffic) > 1:
random.shuffle(self.ingress_traffic)
# each packet gets added to the relevant queue within the switch if the entire packet is present
final_ingress = self.ingress_traffic.copy() # use a copy of this so we do not alter the live list when removing packets
for packet in self.ingress_traffic:
# can only move packet from ingress into its respective queue if the entire packet is present
if packet.queue_enter == -1: # if it is the packets first tick in the ingress queue
if SIM_DEBUG: # debug
print("[T", str(g_timestamp).zfill(3)+"]", "Found", \
"start of "+str(packet.__class__.__name__)+" packet \""+str(packet.name)+"\" size \""+str(packet.size)+"\"" \
if math.ceil(int(packet.size) / SENDING_SIZE_CAPCITY) > 1 else \
str(packet.__class__.__name__)+" packet \""+str(packet.name)+"\"" \
, "from ES", "\""+str(packet.source)+"\"", "in ingress queue of Switch", "\""+str(self.id)+"\"")
packet.set_queue_enter(g_timestamp) # add queue enter timestamp
# then check the packets size compared to how much we can accept per tick
if ((g_timestamp - packet.queue_enter) + 1) != math.ceil(int(packet.size) / SENDING_SIZE_CAPCITY):
continue # if it hasnt fully arrived we cant move this packet to its inner queue. Try again next tick, move on to other packets
# else properly ingest the packet into the correct inner queue
# ST packets
if packet.__class__.__name__ == "ST":
# simulate a small chance the ST packet will go into the emergency queue to pretend it is late
if random.random() < EMERGENCY_QUEUE_CHANCE: # % chance
if self.queue_definition.acceptance_test(packet): # if acceptance test True
self.q_load_balance(self.EM_queue, packet) # add to Emergency queue
if SIM_DEBUG: # debug
print("[T", str(g_timestamp).zfill(3)+"]", "Adding", packet.__class__.__name__, "Packet", "\""+str(packet.name)+"\"", \
"from ES", "\""+str(packet.source)+"\"", "to inner Emergency queue of Switch", "\""+str(self.id)+"\"")
else: # failed acceptance test, drop the packet (by not adding it to any queue)
print("WARNING: ST packet", "\""+str(packet.name)+"\"", "from ES", "\""+str(packet.source)+"\"", \
"in switch", "\""+str(self.id)+"\"", "failed emergency queue acceptance test and has been DROPPED")
else: # if it hasnt been chosen to go into the emergency queue
self.q_load_balance(self.ST_queue, packet) # add to ST
if SIM_DEBUG: # debug
print("[T", str(g_timestamp).zfill(3)+"]", "Adding", packet.__class__.__name__, "Packet", "\""+str(packet.name)+"\"", \
"from ES", "\""+str(packet.source)+"\"", "to inner ST queue of Switch", "\""+str(self.id)+"\"")
final_ingress.remove(packet) # whatever happens always remove packet from the ingress
# SH packets
elif packet.__class__.__name__ == "Sporadic_Hard":
self.q_load_balance(self.SH_queue, packet)
final_ingress.remove(packet)
if SIM_DEBUG: # debug
print("[T", str(g_timestamp).zfill(3)+"]", "Adding", packet.__class__.__name__, "Packet", "\""+str(packet.name)+"\"", \
"from ES", "\""+str(packet.source)+"\"", "to inner Sporadic_Hard queue of Switch", "\""+str(self.id)+"\"")
# SS packets
elif packet.__class__.__name__ == "Sporadic_Soft":
self.q_load_balance(self.SS_queue, packet)
final_ingress.remove(packet)
if SIM_DEBUG: # debug
print("[T", str(g_timestamp).zfill(3)+"]", "Adding", packet.__class__.__name__, "Packet", "\""+str(packet.name)+"\"", \
"from ES", "\""+str(packet.source)+"\"", "to inner Sporadic_Soft queue of Switch", "\""+str(self.id)+"\"")
# BE packets
elif packet.__class__.__name__ == "BE":
self.q_load_balance(self.BE_queue, packet)
final_ingress.remove(packet)
if SIM_DEBUG: # debug
print("[T", str(g_timestamp).zfill(3)+"]", "Adding", packet.__class__.__name__, "Packet", "\""+str(packet.name)+"\"", \
"from ES", "\""+str(packet.source)+"\"", "to inner Best_Effort queue of Switch", "\""+str(self.id)+"\"")
# unrecognised packets
else:
print("ERROR: Unrecognised packet type", "\""+str(packet.__class__.__name__)+"\"", \
"in ingress of switch ID", "\""+str(self.id)+"\"")
return 0
self.ingress_traffic = final_ingress
return 1
# applies scheduling to the 8 queues to get packets in the egress section
# NOTE : queue schedule types from e_queue_schedules need to be called in here
def cycle_queues(self):
gcl_pos = 0
self.available_packets = []
# ST queues
for i in range(len(self.ST_queue)):
# first check the GCL to see if the queue is open
gcl_pos += 1 # for next iteration
if g_current_GCL_state[gcl_pos-1] == str(0): # if gate is shut
continue # skip this iteration
# FIFO
if self.queue_definition.ST_schedule == e_queue_schedules[0]:
if len(self.ST_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, FIFO_schedule(self.ST_queue[i]))) # add (queue_number, packet) to available packet list
# EDF
if self.queue_definition.ST_schedule == e_queue_schedules[1]: # note the 1 here to signify "EDF" if the e_queue_schedules was ["FIFO", "EDF", ...]
if len(self.ST_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, EDF_schedule(self.ST_queue[i])))
# DEBUG
if SIM_DEBUG:
if len(self.ST_queue[i]) != 0:
print("[T", str(g_timestamp).zfill(3)+"]", "["+str(self.queue_definition.ST_schedule)+"]", "Adding ST packet", \
"\""+str(self.available_packets[-1][1].name)+"\"", "from ES", "\""+str(self.available_packets[-1][1].source)+"\"", \
"to \"available_packets\" candidate queue of Switch", "\""+str(self.id)+"\"")
# Emergency queues
for i in range(len(self.EM_queue)):
# first check the GCL to see if the queue is open
gcl_pos += 1 # for next iteration
if g_current_GCL_state[gcl_pos-1] == str(0): # if gate is shut
continue # skip this iteration
# FIFO
if self.queue_definition.emergency_schedule == e_queue_schedules[0]:
if len(self.EM_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, FIFO_schedule(self.EM_queue[i]), 1)) # add (queue_number, packet, EMERGENCY_FLAG) to available packet list
# NOTE : these tuples should be len 3 to show later that the ST traffic is in the Emergency Queue
# EDF
if self.queue_definition.emergency_schedule == e_queue_schedules[1]:
if len(self.EM_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, EDF_schedule(self.EM_queue[i]), 1)) # add queue number, and packet to available packet list
# DEBUG
if SIM_DEBUG:
if len(self.EM_queue[i]) != 0:
print("[T", str(g_timestamp).zfill(3)+"]", "["+str(self.queue_definition.emergency_schedule)+"]", "Adding Emergency packet", \
"\""+str(self.available_packets[-1][1].name)+"\"", "from ES", "\""+str(self.available_packets[-1][1].source)+"\"", \
"to \"available_packets\" candidate queue of Switch", "\""+str(self.id)+"\"")
# SH queues
for i in range(len(self.SH_queue)):
# first check the GCL to see if the queue is open
gcl_pos += 1 # for next iteration
if g_current_GCL_state[gcl_pos-1] == str(0): # if gate is shut
continue # skip this iteration
# FIFO
if self.queue_definition.sporadic_hard_schedule == e_queue_schedules[0]:
if len(self.SH_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, FIFO_schedule(self.SH_queue[i]))) # add (queue_number, packet) to available packet list
# EDF
if self.queue_definition.sporadic_hard_schedule == e_queue_schedules[1]:
if len(self.SH_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, EDF_schedule(self.SH_queue[i]))) # add queue number, and packet to available packet list
# DEBUG
if SIM_DEBUG:
if len(self.SH_queue[i]) != 0:
print("[T", str(g_timestamp).zfill(3)+"]", "["+str(self.queue_definition.sporadic_hard_schedule)+"]", "Adding Sporadic_Hard packet", \
"\""+str(self.available_packets[-1][1].name)+"\"", "from ES", "\""+str(self.available_packets[-1][1].source)+"\"", \
"to \"available_packets\" candidate queue of Switch", "\""+str(self.id)+"\"")
# SS queues
for i in range(len(self.SS_queue)):
# first check the GCL to see if the queue is open
gcl_pos += 1 # for next iteration
if g_current_GCL_state[gcl_pos-1] == str(0): # if gate is shut
continue # skip this iteration
# FIFO
if self.queue_definition.sporadic_soft_schedule == e_queue_schedules[0]:
if len(self.SS_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, FIFO_schedule(self.SS_queue[i]))) # add (queue_number, packet) to available packet list
# EDF
if self.queue_definition.sporadic_soft_schedule == e_queue_schedules[1]:
if len(self.SS_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, EDF_schedule(self.SS_queue[i]))) # add queue number, and packet to available packet list
# DEBUG
if SIM_DEBUG:
if len(self.SS_queue[i]) != 0:
print("[T", str(g_timestamp).zfill(3)+"]", "["+str(self.queue_definition.sporadic_soft_schedule)+"]", "Adding Sporadic_Soft packet", \
"\""+str(self.available_packets[-1][1].name)+"\"", "from ES", "\""+str(self.available_packets[-1][1].source)+"\"", \
"to \"available_packets\" candidate queue of Switch", "\""+str(self.id)+"\"")
# BE queues
for i in range(len(self.BE_queue)):
# first check the GCL to see if the queue is open
gcl_pos += 1 # for next iteration
if g_current_GCL_state[gcl_pos-1] == str(0): # if gate is shut
continue # skip this iteration
# FIFO
if self.queue_definition.BE_schedule == e_queue_schedules[0]:
if len(self.BE_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, FIFO_schedule(self.BE_queue[i]))) # add (queue_number, packet) to available packet list
# EDF
if self.queue_definition.BE_schedule == e_queue_schedules[1]:
if len(self.BE_queue[i]) != 0: # if queue isnt empty
self.available_packets.append((i, EDF_schedule(self.BE_queue[i]))) # add queue number, and packet to available packet list
# DEBUG
if SIM_DEBUG: # for debug
if len(self.BE_queue[i]) != 0:
print("[T", str(g_timestamp).zfill(3)+"]", "["+str(self.queue_definition.BE_schedule)+"]", "Adding Best_Effort packet", \
"\""+str(self.available_packets[-1][1].name)+"\"", "from ES", "\""+str(self.available_packets[-1][1].source)+"\"", \
"to \"available_packets\" candidate queue of Switch", "\""+str(self.id)+"\"")
return 1
# function to check available packets list, apply strict priority ordering, and send 1 packet
def egress_packets(self):
# now we send highest priority packet from the list of available packets
if len(self.available_packets) == 0: # if available packets queue empty, do nothing
if self.busy != 0:
self.busy -= 1 # dont forget to decrese busy counter if we are still working
return 0
if self.busy != 0: # if we are still sending a packet
self.busy -= 1
if self.busy != 0: # if the packet is now fully sent, can continue
return 0 # else we cant send a packet
# find highest priority packet out of all packets available to be sent
packet_to_send = self.available_packets[0] # start from FIRST in queue to mimic priority ordering
for packet in self.available_packets:
if packet[1].priority < packet_to_send[1].priority:
packet_to_send = packet
# send it
self.forward(packet_to_send[1])
# remove it from its original queue
queue_type = packet_to_send[1].__class__.__name__
queue_number = packet_to_send[0]
if queue_type == "ST":
# ST traffic could be in emergency queue, check to see which queue the packet it is
if len(packet_to_send) == 3: # an Emergency queue
self.EM_queue[queue_number].remove(packet_to_send[1])
else: # an ST queue
self.ST_queue[queue_number].remove(packet_to_send[1])
elif queue_type == "Sporadic_Hard":
self.SH_queue[queue_number].remove(packet_to_send[1])
elif queue_type == "Sporadic_Soft":
self.SS_queue[queue_number].remove(packet_to_send[1])
elif queue_type == "BE":
self.BE_queue[queue_number].remove(packet_to_send[1])
return 1
# sends the traffic to destination from route in routing table
# NOTE : This may need to be translated into sending multiple frames looped so it can be preempted
def forward(self, packet):
packet.set_queue_leave(g_timestamp) # set the queue_leave time for this packet
self.packets_transmitted += 1
self.recalculate_packet_delay(packet)
if self.busy != 0:
print("ERROR: Switch", "\""+str(self.id)+"\"", "is busy and cannot send new packets")
return 0
# get hop from routing table
hop = -1
for route in self.local_routing_table:
if int(route[0]) == int(packet.destination):
hop = route[1]
break # found
if SIM_DEBUG: # debug
print("[T", str(g_timestamp).zfill(3)+"]", "Sending", str(packet.__class__.__name__), \
"packet", "\""+str(packet.name)+"\"", "from ES", "\""+str(packet.source)+"\"", \
"in egress queue of Switch", "\""+str(self.id)+"\"", \
"to node ID", "\""+str(packet.destination)+"\"" if int(hop) == int(self.id) else "\""+str(hop)+"\"")
# if hop is this switch we can send packet directly to the ES else we send to next switch
packet.queue_enter = -1 # reset this in case we are moveing to another switch
g_node_id_dict[int(packet.destination) if int(hop) == int(self.id) else int(hop)].RX_packet(packet)
# set this switch to be busy depending on the size of the packet to send, busy ticks decrese in egress_packets
self.busy = math.ceil(int(packet.size) / SENDING_SIZE_CAPCITY)
return 1
# function that recalculates queueing delay for this switch
def recalculate_packet_delay(self, packet):
queue_delay = int(int(packet.queue_leave)-int(packet.queue_enter)) # get the time it has been in the queue
g_queueing_delays.append(queue_delay) # add to global array
# change local variables
self.total_queue_delay += queue_delay # cumulative
self.average_queue_delay = int(self.total_queue_delay) / int(self.packets_transmitted)
return 1
## Inner queue selection functions
# These functions must be given a list of queues, and a packet,
# and they must only put the packet in ONE of the queues and not do anything else
# function to load balance across all available queues
def q_load_balance(self, queue_list, packet):
if len(queue_list) == 1: # if only 1 queue available, add packet to it
queue_list[0].append(packet)
return 1
# else put packet in smallest queue
smallest_index = 0 # start with first available queue
for index in range(len(queue_list)):
if len(queue_list[index]) < len(queue_list[smallest_index]): # if this queue is smaller than the smallest queue
smallest_index = index # change smallest
# append packet to smallest queue, or first available queue if all queues are same size
queue_list[smallest_index].append(packet)
return 1
# NOTE : Can add other functions here such as round robin
## Setters
def set_queue_def(self, queue_def):
self.queue_definition = queue_def
# put empty lists in each queue type to signify how many queues each queue type has
[self.ST_queue.append([]) for i in range(self.queue_definition.ST_count)]
[self.EM_queue.append([]) for i in range(self.queue_definition.emergency_count)]
[self.SH_queue.append([]) for i in range(self.queue_definition.sporadic_hard_count)]
[self.SS_queue.append([]) for i in range(self.queue_definition.sporadic_soft_count)]
[self.BE_queue.append([]) for i in range(self.queue_definition.BE_count)]
return 1
def set_local_routing_table(self, routing_table_def):
self.local_routing_table = routing_table_def
return 1
# controller type of switch
class Controller(Switch):
def __init__(self, id, name="unnamed"):
super().__init__(id, name)
self.routing_table = -1 # the entire routing table is stored in this object as a dict
def send_control(self, packet):
# used to send control packets to other switches or end points specified in the packet?
pass
## Setters
def set_routing_table(self, main_routing_table):
self.routing_table = main_routing_table # the entire routing table is stored in this object
return 1
##################################################
############# DEFINE TRAFFIC CLASSES #############
##################################################
# base class traffic (abstraction of packets)
class Traffic():
def __init__(self, source, destination):
self.source = source
self.destination = destination
## Setters
def set_dest(self, dest):
self.destination = dest
return 1
# define packets that belong to the traffic class (frame -> packet -> traffic)
class Packet(Traffic):
def __init__(self, source, destination, priority, size, name="unnamed", offset="0"):
super().__init__(source, destination)
self.priority = priority
self.name = name
self.offset = offset
self.size = size
self.type = self.__class__.__name__
# instance variables
self.transmission_time = g_timestamp # set to now as soon as object is initialised it is transmitted
self.arrival_time = -1
self.queue_enter = -1
self.queue_leave = -1
## Setters
def set_arrival_time(self, timestamp):
self.arrival_time = timestamp
return 1
def set_queue_enter(self, timestamp):
self.queue_enter = timestamp
return 1
def set_queue_leave(self, timestamp):
self.queue_leave = timestamp
return 1
# ST traffic type
class ST(Packet):
def __init__(self, source, destination, delay_jitter_constraints, period, deadline, size, \
name="unnamed", offset="0"):
super().__init__(source, destination, 1, size, name, offset) # priority 1
self.delay_jitter_constraints = int(delay_jitter_constraints)
self.period = int(period)
self.hard_deadline = int(deadline)
def to_string(self):
output_str = "Packet Definition: "
output_str += "(Type: " + str(self.__class__.__name__)
output_str += ") (Source: " + str(self.source)
output_str += ") (Priority: " + str(self.priority)
output_str += ") (Deadline: " + str(self.hard_deadline)
output_str += ") (Period: " + str(self.period)
output_str += ") (Jitter: " + str(self.delay_jitter_constraints)
output_str += ")"
return output_str
# non-st traffic type. Abstraction. No traffic should directly be NonST
class NonST(Packet):
def __init__(self, source, destination, priority, minimal_inter_release_time, delay_jitter_constraints, \
size, name="unnamed", offset="0"):
super().__init__(source, destination, priority, size, name, offset)
self.minimal_inter_release_time = minimal_inter_release_time
self.delay_jitter_constraints = delay_jitter_constraints
# sporadic hard type of nonST traffic
class Sporadic_Hard(NonST):
def __init__(self, source, destination, minimal_inter_release_time, delay_jitter_constraints, \
deadline, size, name="unnamed", offset="0"):
super().__init__(source, destination, 2, minimal_inter_release_time, delay_jitter_constraints, size, name, offset) # priority 2
self.hard_deadline = deadline
# sporadic soft type of nonST traffic
class Sporadic_Soft(NonST):
def __init__(self, source, destination, minimal_inter_release_time, delay_jitter_constraints, \
deadline, size, name="unnamed", offset="0"):
super().__init__(source, destination, 3, minimal_inter_release_time, delay_jitter_constraints, size, name, offset) # priority 3
self.soft_deadline = deadline
# best effort type of nonST traffic
class BE(NonST):
def __init__(self, source, destination, size, name="unnamed", offset="0"):
super().__init__(source, destination, 4, 0, 0, size, name, offset) # priority 4, no timing constraints
##################################################
############## DEFINE OTHER CLASSES ##############
##################################################
# queue class (should be present in each switch)
# TODO : GCL in here is useless I think - best being global only
class Queue():
def __init__(self, ST_count, emergency_count, sporadic_hard_count, sporadic_soft_count, BE_count, \
ST_schedule=e_queue_schedules[0], emergency_schedule=e_queue_schedules[0], \
sporadic_hard_schedule=e_queue_schedules[0], sporadic_soft_schedule=e_queue_schedules[0], \
BE_schedule=e_queue_schedules[0]):
# setup queues and their schedule
self.ST_count = ST_count
self.ST_schedule = ST_schedule
self.emergency_count = emergency_count
self.emergency_schedule = emergency_schedule
self.sporadic_hard_count = sporadic_hard_count
self.sporadic_hard_schedule = sporadic_hard_schedule
self.sporadic_soft_count = sporadic_soft_count
self.sporadic_soft_schedule = sporadic_soft_schedule
self.BE_count = BE_count
self.BE_schedule = BE_schedule
# dont forget initial GCL is global
global g_offline_GCL
self.offline_GCL = g_offline_GCL # does this even need to be stored here? Can just use global one?
self.active_GCL = self.offline_GCL # initially. Can be changed with modify_GCL()
# changes the active GCL in some way
# TODO : could be global function? Unless it depends on ST traffic it may be best in here
def modify_GCL(self):
pass
# makes sure that the frame is able to be put into the Emergency queue
def acceptance_test(self, frame):
# dummy function
return True
def to_string(self):
out_str = ""
# print queue types with some formatting
out_str += "ST_Count: "+str(self.ST_count)
out_str += "\nST_schedule: "+str(self.ST_schedule)
out_str += "\nemergency_count: "+str(self.emergency_count)
out_str += "\nemergency_schedule: "+str(self.emergency_schedule)
out_str += "\nsporadic_hard_count: "+str(self.sporadic_hard_count)
out_str += "\nsporadic_hard_schedule: "+str(self.sporadic_hard_schedule)
out_str += "\nsporadic_soft_count: "+str(self.sporadic_soft_count)
out_str += "\nsporadic_soft_schedule: "+str(self.sporadic_soft_schedule)
out_str += "\nBE_count: "+str(self.BE_count)
out_str += "\nBE_schedule: "+str(self.BE_schedule)
# print offline_GCL
out_str += "\nOffline_GCL:\n"
for key in self.offline_GCL:
out_str += str(key)+": "+str(self.offline_GCL[key])+"\n" # if I end up using global just change this to global?
# print active_GCL if it is different to offline_GCL
if self.offline_GCL == self.active_GCL:
out_str += "Active_GCL is identical to offline_GCL"
else: