/
Receive.py
116 lines (94 loc) · 2.67 KB
/
Receive.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
import radio
import microbit
from microbit import sleep
radio.on()
connect = False
#key = "IY546G6ZAubNFiua4zhef78p4afeaZRG"
key = ""
class Msg:
def __init__(self):
self.msg = ""
self.type = ""
def parse(msg):
l = len(msg) - 1
print("length: ", l)
i = 0
parse_msg = Msg()
while i <= l:
print("i", i)
if i < 3:
parse_msg.type += msg[i]
if i >= 3:
parse_msg.msg += msg[i]
i += 1
return parse_msg
def reverse(msg, i):
translated = ''
while i >= 0:
translated = translated + msg[i]
i = i - 1
return translated
def cipher_key(msg, key):
result = ""
key_tmp = str(key)
while len(key) < len(msg):
key_tmp = str(key_tmp) + str(key)
key2 = ''
for i in range(len(msg)):
key2 += key_tmp[i]
bin_msg = map(bin,bytearray(msg))
bin_key = map(bin,bytearray(key2))
#bin_msg = map(bin,bytearray(bytearray(b'10')))
#bin_msg = map(bin,bytearray(msg))
#bin_key = map(bin,bytearray(key2))
bin_key = list(bin_key)
i = 0
for bit_msg in list(bin_msg):
#bit_msg = int(bit_msg, base=2)
#bit_key = int(bin_key[i], base=2)
bit_msg = int(bit_msg)
bit_key = int(bin_key[i])
tmp = bit_msg ^ bit_key
result += chr(tmp)
i += 1
return result
def encrypt(msg):
i = len(msg) - 1
msg = reverse(msg, i)
msg = cipher_key(msg, key)
return msg
def decrypt(msg):
i = len(msg) - 1
msg = cipher_key(msg, key)
msg = reverse(msg, i)
return msg
def send(msg):
radio.send_bytes(msg)
def send_key(key):
radio.send_value("key")
while True:
receivedMsg = radio.receive()
if receivedMsg:
p_msg = parse(receivedMsg)
if p_msg.type == "key":
key = p_msg.msg
radio.send("keyOK")
if p_msg.type == "ch1":
msg = decrypt(p_msg.msg)
send_txt = encrypt("OK")
#radio.send(send_txt)
send_msg="ch1"+send_txt
radio.send(send_msg)
#display.set_pixel(2, 2, 5)
radio.config(channel=10)
#radio.config(channel=int(msg))
if p_msg.type == "ch2":
microbit.display.scroll("Ch2", wait=False, loop=False)
msg_r = decrypt(p_msg.msg)
if msg_r == "established":
connect = True
microbit.display.scroll(msg_r, wait=False, loop=False)
if p_msg.type == "msg" and connect == True:
print("msg")
# msg = decrypt(receivedMsg)
# microbit.display.scroll(msg, wait=False, loop=True)