Selaa lähdekoodia

Add 'CARDPUTER CircuitPython/projects/udp_socket_chat/code.py'

cube 1 kuukausi sitten
vanhempi
commit
bf4780dcea
1 muutettua tiedostoa jossa 228 lisäystä ja 0 poistoa
  1. 228
    0
      CARDPUTER CircuitPython/projects/udp_socket_chat/code.py

+ 228
- 0
CARDPUTER CircuitPython/projects/udp_socket_chat/code.py Näytä tiedosto

@@ -0,0 +1,228 @@
1
+from keyb import Keyboard # type: ignore
2
+import json, wifi, os, socketpool, asyncio, sys, select # type: ignore
3
+import board, busio, terminalio, displayio # type: ignore
4
+from adafruit_display_text import label # type: ignore
5
+from adafruit_display_shapes.rect import Rect # type: ignore
6
+
7
+
8
+async def main():
9
+    keyb_task = asyncio.create_task(keyb_scan())
10
+    socket_task = asyncio.create_task(socket_recv())
11
+
12
+    await asyncio.gather(keyb_task, socket_task)
13
+
14
+async def keyb_scan():
15
+    while True:
16
+        if select.select([sys.stdin,],[],[],0.1)[0]:
17
+            code=hex(ord(sys.stdin.readline(1)))
18
+            key = keyb.scan(keycode = code)
19
+            
20
+            if keyb.is_alphanumeric(key):
21
+                if len(textbar.text) < 31:
22
+                    textbar.text += str(key)
23
+            elif key == "\n":
24
+                a = {"header":"message",
25
+                     "message":textbar.text,
26
+                     "client name":client_name}
27
+                data = json.dumps(a)
28
+                sock.sendto(data, address)
29
+                textbar.text = ""
30
+            elif key == "BACKSP":
31
+                textbar.text = textbar.text[:-1]
32
+            elif key == " ":
33
+                if len(textbar.text) < 31:
34
+                    textbar.text += " "
35
+        else:
36
+            await asyncio.sleep(0.1)
37
+
38
+async def socket_recv():
39
+    while True:
40
+        try:
41
+            buffer = bytearray(200)
42
+            size, addr = sock.recvfrom_into(buffer)
43
+            try:
44
+                a = json.loads(buffer)
45
+                header = a["header"]
46
+
47
+                if header == "response":
48
+                    msg = a["message"]
49
+                    try:
50
+                        color = a["color"]
51
+                    except KeyError:
52
+                        color = 0xffffff
53
+                    try:
54
+                        recv_client_name = a["client name"]
55
+                    except KeyError:
56
+                        recv_client_name = "(unknown)"
57
+                    cmsg = recv_client_name + " >> " + msg
58
+                    messages_list.append([cmsg, color])
59
+                    update_gui()
60
+
61
+                elif header == "connection":
62
+                    motd = a["motd"]
63
+                    conn_client = a["client name"]
64
+                    try:
65
+                        color = a["color"]
66
+                    except KeyError:
67
+                        color = 0xffffff
68
+                    con_msg = ">> " + conn_client + " <<"
69
+                    messages_list.append([con_msg, color])
70
+                    update_gui()
71
+            except Exception as e:
72
+                error_msg = str(e) + " (buffer size?)"
73
+                color = 0xff0000
74
+                messages_list.append([error_msg, color])
75
+                update_gui()
76
+
77
+        except OSError:
78
+            pass
79
+
80
+        await asyncio.sleep(0.1)
81
+
82
+def update_gui():
83
+    x = 0
84
+    for message in messages_list[-max_messages:]:
85
+        messages_list_labels[x].text = message[0]
86
+        messages_list_labels[x].color = message[1]
87
+        x += 1
88
+
89
+
90
+keyb = Keyboard()
91
+
92
+
93
+# SET UP DISPLAY & WIFI
94
+display = board.DISPLAY
95
+display_group = displayio.Group()
96
+display.root_group = display_group
97
+
98
+wifi_options = [[os.getenv("WIFI1"),os.getenv("WIFIPW1")],
99
+                [os.getenv("WIFI2"),os.getenv("WIFIPW2")],
100
+                [os.getenv("WIFI3"),os.getenv("WIFIPW3")]]
101
+
102
+
103
+h1 = label.Label(terminalio.FONT, text="Hello!", color=0xffffff, scale=2)
104
+h1.x = 10
105
+h1.y = 15
106
+
107
+count = 0
108
+menu_labs = []
109
+for option in wifi_options:
110
+    if count == 0:
111
+        menu_lab = label.Label(terminalio.FONT, text = "> " + option[0], color=0xffffff, scale=1)
112
+    else:
113
+        menu_lab = label.Label(terminalio.FONT, text = option[0], color=0xffffff, scale=1)
114
+    menu_lab.x = 10
115
+    menu_lab.y = 35 + count * 10
116
+    display.root_group.append(menu_lab)
117
+    menu_labs.append(menu_lab)
118
+    count+=1
119
+
120
+display.root_group.append(h1)
121
+
122
+pos = 0
123
+while True:
124
+    key = keyb.scan()
125
+    if key == "UP":
126
+        if pos == 0:
127
+            pass
128
+        else:
129
+            menu_labs[pos].text = wifi_options[pos][0]
130
+            pos -= 1
131
+        menu_labs[pos].text = "> " + wifi_options[pos][0]
132
+    elif key == "DOWN":
133
+        if pos == len(wifi_options)-1:
134
+            pass
135
+        else:
136
+            menu_labs[pos].text = wifi_options[pos][0]
137
+            pos += 1
138
+        menu_labs[pos].text = "> " + wifi_options[pos][0]
139
+    elif key == "\n":
140
+        WIFI_SSID = wifi_options[pos][0]
141
+        WIFI_PASS = wifi_options[pos][1]
142
+        break
143
+
144
+try:
145
+    for lab in menu_labs:
146
+        display.root_group.remove(lab)
147
+
148
+    txt = label.Label(terminalio.FONT, text = "", color=0x00ff00, scale=1)
149
+    txt.text = "Connecting to " + WIFI_SSID + "..."
150
+    txt.x = 10
151
+    txt.y = 35
152
+    display.root_group.append(txt)
153
+
154
+    wifi.radio.connect(ssid=WIFI_SSID,
155
+                    password=WIFI_PASS)
156
+    my_ip = str(wifi.radio.ipv4_address).strip()
157
+
158
+    display.root_group.remove(h1)
159
+    display.root_group.remove(txt)
160
+except ConnectionError as e:
161
+    h1.text = "Aw..."
162
+    
163
+    txt.text = "Could not connect to " + WIFI_SSID
164
+    txt.color = 0xff0000
165
+    txt.x = 10
166
+    txt.y = 35
167
+
168
+    txt2 = label.Label(terminalio.FONT, text = "", color=0x89a0a8, scale=1)
169
+    txt2.text = "Press CTRL + C followed by CTRL + D\nto soft-reboot"
170
+    txt2.x = 10
171
+    txt2.y = 100
172
+
173
+    display.root_group.append(txt2)
174
+    
175
+    while True:
176
+        pass
177
+
178
+
179
+
180
+
181
+
182
+
183
+# Header Bar
184
+header_bar = Rect(0, 0, 238, 30, fill=0x1f4476)
185
+display.root_group.append(header_bar)
186
+
187
+# Page Title
188
+title_label = label.Label(terminalio.FONT, text="Chat", color=0xffffff, scale=2)
189
+display.root_group.append(title_label)
190
+title_label.x = 10
191
+title_label.y = 15
192
+
193
+# IP Label
194
+ip_label = label.Label(terminalio.FONT, text=my_ip, color=0x89a0a8, scale=1)
195
+display.root_group.append(ip_label)
196
+ip_label.x = 150
197
+ip_label.y = 20
198
+
199
+
200
+pool = socketpool.SocketPool(wifi.radio)
201
+sock = pool.socket(pool.AF_INET, pool.SOCK_DGRAM)
202
+sock.settimeout(3)
203
+sock.setblocking(False)
204
+ip = "cubes.link"
205
+port = 1337
206
+address = (ip, port)
207
+client_name = "CARDPUTER"
208
+a = {"header":"connection",
209
+     "client name":client_name}
210
+data = json.dumps(a)
211
+sock.sendto(data, address)
212
+
213
+textbar = label.Label(terminalio.FONT, text = "", color = 0x89a0a8, scale=1)
214
+display.root_group.append(textbar)
215
+textbar.x = 10
216
+textbar.y = 120
217
+
218
+messages_list = []
219
+messages_list_labels = []
220
+max_messages = 8
221
+for x in range(0, max_messages):
222
+    mlab = label.Label(terminalio.FONT, text="", color=0xffffff, scale=1)
223
+    mlab.x = 8
224
+    mlab.y = 38 + (x * 10)
225
+    display.root_group.append(mlab)
226
+    messages_list_labels.append(mlab)
227
+
228
+asyncio.run(main())