-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.py
More file actions
279 lines (238 loc) · 10.3 KB
/
Copy pathlib.py
File metadata and controls
279 lines (238 loc) · 10.3 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
#!/usr/bin/env python3
"""
CSMA/CA simulation with Logarithmic Increment Backoff (LIB).
Simulates an RTS/CTS/DATA/ACK exchange across threaded transmitting nodes.
Unlike BEB's doubling or EIED's multiplicative growth, the backoff range
here is calculated directly from 2**retries, so it grows logarithmically
in terms of the number of retransmission attempts. Tracks each node's
contention window history and energy consumption over the course of the run.
Run with no arguments to reproduce the 3-node topology this project's
writeup was built around (Node 1 and Node 3 transmitting to Node 2).
Pass --interactive to be prompted for a custom node count and layout instead.
"""
import argparse
import math
import random
import threading
import time
import matplotlib.pyplot as plt
# Constants
DIFS = 0.05 # Distributed Inter-Frame Space (in seconds)
SIFS = 0.01 # Short Inter-Frame Space (in seconds)
SLOT_TIME = 0.02 # Slot time (in seconds)
CW_MIN = 15 # Minimum contention window size
CW_MAX = 1023 # Maximum contention window size
MAX_RETRIES = 7 # Maximum number of retransmission attempts
TRANSMISSION_RANGE = 15 # Transmission range or radiation radius
# Energy consumption constants (in milliwatts)
ENERGY_SLEEP = 0.1
ENERGY_IDLE = 1
ENERGY_BACKOFF = 0.5
ENERGY_RTS = 2
ENERGY_CTS = 2
ENERGY_SIFS = 0.2
ENERGY_DIFS = 0.2
ENERGY_TRANSMISSION = 10
receiving_nodes = [] # populated at runtime by main()
class Node:
def __init__(self, name, x, y):
self.name = name
self.neighbors = []
self.backoff_counter = 0
self.contention_window = CW_MIN
self.retries = 0
self.transmitting = False
self.nav = 0
self.x = x
self.y = y
self.energy_consumed = 0
self.cw_history = []
self.cw_timestamps = []
self.rts_received = False
def find_neighbors(self, nodes):
for node in nodes:
if node != self:
distance = math.sqrt((self.x - node.x) ** 2 + (self.y - node.y) ** 2)
if distance <= TRANSMISSION_RANGE:
self.neighbors.append(node)
def send_rts(self, receiver):
self.update_energy_consumption("idle")
print(f"[RTS] {self.name} sends RTS to {receiver.name}")
time.sleep(SIFS)
if not receiver.rts_received:
receiver.rts_received = True
receiver.send_cts(self)
else:
print(f"{receiver.name} has already received an RTS, ignoring RTS from {self.name}")
self.retries += 1
self.backoff()
def send_cts(self, sender):
self.update_energy_consumption("RTS")
print(f"[CTS] {self.name} sends CTS to {sender.name}")
time.sleep(SIFS)
for neighbor in self.neighbors:
if neighbor != sender:
neighbor.update_nav(SIFS + DIFS + (2 * SLOT_TIME))
sender.transmit_data()
def update_nav(self, duration):
self.nav = duration / SLOT_TIME
print(f"{self.name} updates NAV for {duration} seconds ({self.nav} slots)")
def transmit_data(self):
self.transmitting = True
self.update_energy_consumption("DIFS")
print(f"[DATA] {self.name} transmits data")
time.sleep(DIFS)
print(f"[DIFS] {self.name} waits for {DIFS} seconds")
for neighbor in self.neighbors:
if neighbor.transmitting:
print(f"Collision detected at {neighbor.name}")
self.retries += 1
self.backoff()
break
else:
print(f"{self.name} data transmission successful")
self.retries = 0
self.cw_history.append(2 ** self.retries)
self.cw_timestamps.append(time.time())
self.transmitting = False
def backoff(self):
backoff_slots = random.randint(0, 2 ** self.retries - 1)
backoff_time = backoff_slots * SLOT_TIME
print(f"[BACKOFF] {self.name} selected random backoff: {backoff_slots} slots ({backoff_time} seconds)")
self.backoff_counter = backoff_slots
self.cw_history.append(2 ** self.retries)
self.cw_timestamps.append(time.time())
print(f"[BACKOFF] {self.name} goes into backoff for {backoff_slots} slots ({backoff_time} seconds)")
time.sleep(backoff_time)
print(f"[SIFS] {self.name} waits for {SIFS} seconds after backoff")
if self.retries < MAX_RETRIES:
if not self.transmitting:
for receiving_node in receiving_nodes:
if receiving_node in self.neighbors:
distance = math.sqrt((self.x - receiving_node.x) ** 2 + (self.y - receiving_node.y) ** 2)
self.update_energy_consumption("backoff", distance)
self.send_rts(receiving_node)
break
else:
print(f"{self.name} reached maximum number of retries, transmission failed")
self.retries = 0
def update_energy_consumption(self, activity, distance=None):
if activity == "sleep":
self.energy_consumed += ENERGY_SLEEP
elif activity == "idle":
self.energy_consumed += ENERGY_IDLE
elif activity == "backoff":
backoff_energy = ENERGY_BACKOFF * (self.backoff_counter / CW_MIN)
if distance is not None:
backoff_energy *= distance
self.energy_consumed += backoff_energy
elif activity == "RTS":
self.energy_consumed += ENERGY_RTS
elif activity == "CTS":
self.energy_consumed += ENERGY_CTS
elif activity == "SIFS":
self.energy_consumed += ENERGY_SIFS
elif activity == "DIFS":
self.energy_consumed += ENERGY_DIFS
elif activity == "transmission":
self.energy_consumed += ENERGY_TRANSMISSION
def print_coordinates(self):
print(f"{self.name}: ({self.x}, {self.y})")
def print_backoff_table(self):
print(f"\nBackoff Table for {self.name}:")
print("Backoff Period\tContention Window\tTime")
start_time = self.cw_timestamps[0]
for i in range(len(self.cw_history)):
backoff_period = self.cw_timestamps[i] - start_time
current_time = time.strftime("%H:%M:%S", time.localtime(self.cw_timestamps[i]))
print(f"{backoff_period:.2f}\t\t{self.cw_history[i]}\t\t\t{current_time}")
def create_nodes_with_coordinates(num_nodes):
nodes = []
for i in range(num_nodes):
print(f"Enter coordinates for Node {i + 1}:")
x = float(input("Enter x-coordinate: "))
y = float(input("Enter y-coordinate: "))
nodes.append(Node(f"Node {i + 1}", x, y))
return nodes
def build_default_topology():
"""Reproduces the 3-node topology used in this project's writeup:
Node 1 (1,1) and Node 3 (20,20) transmitting to Node 2 (10,10)."""
nodes = [Node("Node 1", 1.0, 1.0), Node("Node 2", 10.0, 10.0), Node("Node 3", 20.0, 20.0)]
for node in nodes:
node.find_neighbors(nodes)
return nodes, [nodes[0], nodes[2]], [nodes[1]]
def plot_nodes(nodes):
plt.figure(figsize=(8, 6))
for node in nodes:
plt.plot(node.x, node.y, "ro", markersize=10)
plt.title("Node Locations")
plt.xlabel("X-coordinate")
plt.ylabel("Y-coordinate")
plt.grid(True)
plt.show()
def simulate_transmission(transmitting_node):
while True:
if all(not r.rts_received for r in receiving_nodes):
print(f"Simulation for transmitting node {transmitting_node.name} and receiving nodes:")
for receiving_node in receiving_nodes:
transmitting_node.backoff()
if receiving_node in transmitting_node.neighbors:
transmitting_node.send_rts(receiving_node)
else:
print(f"{receiving_node.name} is not within transmission range of {transmitting_node.name}")
print("Simulation End")
break
else:
print("One or more receiving nodes have already received an RTS, waiting for them to become available...")
time.sleep(SLOT_TIME)
def run(nodes, transmitting_nodes):
threads = [threading.Thread(target=simulate_transmission, args=(n,)) for n in transmitting_nodes]
for t in threads:
t.start()
for t in threads:
t.join()
print("\nTotal energy consumed by each node:")
for node in nodes:
print(f"{node.name}: {node.energy_consumed}")
for transmitting_node in transmitting_nodes:
plt.figure()
plt.plot(transmitting_node.cw_timestamps, transmitting_node.cw_history)
plt.xlabel("Time")
plt.ylabel("Contention Window")
plt.title(f"Contention Window vs Time for {transmitting_node.name}")
plt.show()
energy_consumption = {node.name: node.energy_consumed for node in nodes}
plt.bar(energy_consumption.keys(), energy_consumption.values())
plt.xlabel("Node")
plt.ylabel("Energy Consumption")
plt.title("Total Energy Consumption by Node")
plt.show()
for transmitting_node in transmitting_nodes:
transmitting_node.print_backoff_table()
def main():
global receiving_nodes
parser = argparse.ArgumentParser(description="CSMA/CA simulation with Logarithmic Increment Backoff (LIB)")
parser.add_argument(
"--interactive",
action="store_true",
help="Prompt for custom node count/coordinates instead of using the default 3-node topology",
)
args = parser.parse_args()
if args.interactive:
num_nodes = int(input("Enter the number of nodes: "))
nodes = create_nodes_with_coordinates(num_nodes)
plot_nodes(nodes)
for node in nodes:
node.find_neighbors(nodes)
num_tx = int(input("Enter the number of transmitting nodes: "))
tx_indices = [int(input(f"Enter the index ({i + 1}/{num_tx}) of the transmitting node: ")) for i in range(num_tx)]
num_rx = int(input("Enter the number of receiving nodes: "))
rx_indices = [int(input(f"Enter the index ({i + 1}/{num_rx}) of the receiving node: ")) for i in range(num_rx)]
transmitting_nodes = [nodes[i] for i in tx_indices]
receiving_nodes = [nodes[i] for i in rx_indices]
else:
nodes, transmitting_nodes, receiving_nodes = build_default_topology()
plot_nodes(nodes)
run(nodes, transmitting_nodes)
if __name__ == "__main__":
main()