I have a lot of boards and usually need to re-use code even for different projects.

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