-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrafficLight.py
More file actions
83 lines (67 loc) · 1.92 KB
/
TrafficLight.py
File metadata and controls
83 lines (67 loc) · 1.92 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
# n7 n6 n5 n4 n3 n2 n1
# d3 d2 d1 p3 d1 p2 p1
'''
Send Message
|Trafficlight ID|Status |
'''
bitmap = { "r": 0b0001, "y": 0b0010, "g": 0b0100, "m": 0b1000 }
rbitmap = { 0b0001:"R", 0b0010:"Y", 0b0100:"G", 0b1000:"M" }
def encode_hamming4(msg):
n3 = d1 = (msg >> 0) & 1
n5 = d2 = (msg >> 1) & 1
n6 = d3 = (msg >> 2) & 1
n7 = d4 = (msg >> 3) & 1
n1 = p1 = d1 ^ d2 ^ d4
n2 = p2 = d1 ^ d3 ^ d4
n4 = p3 = d2 ^ d3 ^ d4
codeword = (n1 << 0) | (n2 << 1) | (n3 << 2) | (n4 << 3) | (n5 << 4) | (n6 << 5) | (n7 << 6)
return codeword
def decode_hamming4(c):
n1 = p1 = (c >> 0) & 1
n2 = p2 = (c >> 1) & 1
n3 = d1 = (c >> 2) & 1
n4 = p3 = (c >> 3) & 1
n5 = d2 = (c >> 4) & 1
n6 = d3 = (c >> 5) & 1
n7 = d4 = (c >> 6) & 1
c1 = p1 ^ d1 ^ d2 ^ d4
c2 = p2 ^ d1 ^ d3 ^ d4
c3 = p3 ^ d2 ^ d3 ^ d4
error_position = (c3 << 2) | (c2 << 1) | (c1 << 0)
if error_position == 0:
print("No error detected")
else:
print("Error position:", error_position)
match(error_position):
case 0:
pass
case 1:
n1 ^= 1
case 2:
n2 ^= 1
case 3:
n3 ^= 1
case 4:
n4 ^= 1
case 5:
n5 ^= 1
case 6:
n6 ^= 1
case 7:
n7 ^= 1
decoded_msg = ((n7 << 3) | (n6 << 2) | (n5 << 1) | (n3 << 0))
return decoded_msg
def encode(tl_id, state):
enstate = str(encode_hamming4(bitmap[state.casefold()]))
print(f"{tl_id}-{enstate}")
def decode(msg:str):
tl_id, enstate = msg.split("-")
enstate = int(enstate)
state = decode_hamming4(enstate)
print("Traffic Light ID:",tl_id)
print("State:",rbitmap[state])
tl_id = input("Enter Traffic Light ID: ")
state = input("Enter State: ")
encode(tl_id,state)
testmg = "C2.F1.24-25"
decode(testmg)