35_CocoTerminal.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #!/usr/bin/env python
  2. #version : 2023.09.07
  3. #language : en
  4. from evdev import InputDevice, categorize, ecodes
  5. import asyncio
  6. import pty
  7. import os
  8. import sys
  9. from maix import display
  10. from maix import image
  11. from maix import camera
  12. from maix import mjpg
  13. from maix import utils
  14. import base64
  15. import time
  16. import requests
  17. import json
  18. import threading
  19. camera.camera.config(size=(320,240))
  20. image.load_freetype("/root/preset/fonts/simhei.ttf")
  21. canvas = image.new(size = (320, 240))
  22. try:
  23. # 获取键盘设备
  24. keyboard = InputDevice('/dev/input/event1') # 替换成实际的键盘设备路径
  25. except:
  26. keyboard = ""
  27. if keyboard=="":
  28. canvas.draw_string(0,12, "Keyboard not detected", scale = 1.3, color = (255,255,255) , thickness = 1)
  29. display.show(canvas)
  30. time.sleep(3)
  31. sys.exit()
  32. def v831_display_show_canvas(displayShow):
  33. global _canvas_y,_canvas_x
  34. CANVASSHOWIMGAGE = ""
  35. if ScreenOrientation:
  36. displayShowCanvas = image.new(size = (240, 320))
  37. displayShowCanvas.draw_rectangle(0,0,240,320, color=(0,0,0), thickness=-1)
  38. displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
  39. displayShowVER = displayShowCanvas.crop(0,0,240,320)
  40. displayShowVER = displayShowVER.rotate(-90, adjust=1)
  41. CANVASSHOWIMGAGE = displayShowVER
  42. display.show(displayShowVER)
  43. else:
  44. displayShowCanvas = image.new(size = (320, 240))
  45. displayShowCanvas.draw_rectangle(0,0,320,240, color=(0,0,0), thickness=-1)
  46. displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1)
  47. CANVASSHOWIMGAGE = displayShowCanvas
  48. display.show(displayShowCanvas)
  49. # jpg = utils.rgb2jpg(CANVASSHOWIMGAGE.convert("RGB").tobytes(), CANVASSHOWIMGAGE.width, CANVASSHOWIMGAGE.height)
  50. # img_base64 = base64.b64encode(jpg)
  51. # img_base64_str = "data:image/jpg;base64," + str(img_base64)[2:-1]
  52. # time.sleep(0.1)
  53. # try:
  54. # if img_base64_str.rfind("data:image/jpg;base64,")>-1:
  55. # print(img_base64_str)
  56. # pass
  57. # except Exception as e:
  58. # #print(str(e))
  59. # pass
  60. def get_post_chatgpt(datas):
  61. # 目标URL
  62. url = "https://gpt.cocorobo.cn/v831AskForTopic"
  63. payload = json.dumps({"topic":datas})
  64. headers={
  65. 'Content-Type':'application/json'
  66. }
  67. print("payload"+str(payload))
  68. response=requests.request("POST",url,headers=headers,data=payload)
  69. print("response.text",response.text)
  70. if response.status_code == 200:
  71. result_num = len(json.loads(response.text)["FunctionResponse"]["result"])
  72. # keyboardStr[list_num] =
  73. else:
  74. keyboardStr[list_num] = "fail"
  75. ScreenOrientation = False
  76. _canvas_x = 0
  77. _canvas_y = 0
  78. keyboardStr = [""]
  79. list_num = 0
  80. line = b""
  81. lines = []
  82. process = None
  83. keyboard = InputDevice("/dev/input/event1")
  84. master, slave = pty.openpty()
  85. #等待控制台的输出
  86. def read_lines(master):
  87. global lines, line,keyboardStr,list_num,isShow
  88. char = os.read(master, 1)
  89. if char == b"\n":
  90. # lines.append(line.decode().strip())
  91. lines.append(line.decode().rstrip())
  92. line = b""
  93. else:
  94. line += char
  95. # 用来判断是不是终端有新的输出
  96. isShow = ""
  97. # 输入字符串
  98. inputStr = ""
  99. # 跟踪Ctrl键的状态
  100. ctrl_pressed = False
  101. #读取键盘事件写入
  102. def write_io():
  103. global keyboardStr,list_num,isShow,inputStr,ctrl_pressed,lines
  104. for event in keyboard.read_loop():
  105. if event.type == ecodes.EV_KEY:
  106. key_event = categorize(event)
  107. if key_event.keystate == key_event.key_down:
  108. try:
  109. input_command = ""
  110. if key_event.keycode == "KEY_LEFTCTRL" or key_event.keycode == "KEY_RIGHTCTRL":
  111. ctrl_pressed = True
  112. elif ctrl_pressed and key_event.keycode == "KEY_C":
  113. # print("Ctrl+C 组合键被按下")
  114. input_command = "\x1A\x03\x02\x03\x1D\x1A"
  115. # pass
  116. else:
  117. ctrl_pressed = False
  118. if ctrl_pressed == False:
  119. if key_event.keycode[4:] == "SPACE":
  120. inputStr = inputStr + " "
  121. input_command = " "
  122. lines[len(lines)-1] = "root@CocoPi:/# "+inputStr
  123. elif key_event.keycode[4:] == "SLASH":
  124. inputStr = inputStr + "/"
  125. input_command = "/"
  126. lines[len(lines)-1] = "root@CocoPi:/# "+inputStr
  127. elif key_event.keycode[4:] == "DOT":
  128. inputStr = inputStr + "."
  129. input_command = "."
  130. lines[len(lines)-1] = "root@CocoPi:/# "+inputStr
  131. elif key_event.keycode[4:] == "MINUS":
  132. inputStr = inputStr + "_"
  133. input_command = "_"
  134. lines[len(lines)-1] = "root@CocoPi:/# "+inputStr
  135. elif key_event.keycode[4:] == "BACKSPACE":
  136. inputStr = inputStr[:-1]
  137. input_command = ""
  138. lines[len(lines)-1] = "root@CocoPi:/# "+inputStr
  139. # if len(keyboardStr[list_num]) ==0 and list_num>0:
  140. # list_num = list_num - 1
  141. elif key_event.keycode[4:] == "ENTER":
  142. inputStr = ""
  143. input_command = "\n"
  144. # time.sleep(1)
  145. # lines.append("root@CocoPi:/# ")
  146. else:
  147. input_command = key_event.keycode[4:].lower()
  148. inputStr = inputStr + key_event.keycode[4:].lower()
  149. # if list_num == len(lines):
  150. lines[len(lines)-1] = "root@CocoPi:/# "+inputStr
  151. print("\x1A\x03\x02\x03\x1D\x1A")
  152. print(input_command)
  153. os.write(master, input_command.encode())
  154. except EOFError:
  155. break
  156. async def console_io():
  157. global master, slave, process,list_num,keyboardStr,isShow
  158. process = await asyncio.create_subprocess_exec('adb_shell', stdin=slave, stdout=slave, stderr=slave)
  159. while True:
  160. #读取所有的行数,放在lines
  161. read_lines(master)
  162. #屏幕循环的显示所有的数据
  163. # print(lines)
  164. #屏幕读取
  165. if isShow.lower() != " ".join(lines).lower():
  166. isShow = " ".join(lines)
  167. showTreminal(1)
  168. list_num = len(lines)
  169. else:
  170. pass
  171. os.close(master)
  172. os.close(slave)
  173. def showTreminal(val):
  174. global master, slave, process,list_num,keyboardStr,lines,inputStr
  175. for i,box in enumerate(lines):
  176. if len(box)>0:
  177. keyboardStr.append(box)
  178. # if box.rfind("root@CocoPi")>-1 and lines[i-1] == box:
  179. # pass
  180. # else:
  181. # keyboardStr.append(box)
  182. elif i == len(lines)-1:
  183. # lines.append("root@CocoPi:/# ")
  184. keyboardStr.append("root@CocoPi:/# ")
  185. list_num = len(keyboardStr)-1
  186. canvas.clear()
  187. if len(keyboardStr)>20:
  188. for i in range(len(keyboardStr)-1,len(keyboardStr)-20,-1):
  189. canvas.draw_string(0,12*(i-(len(keyboardStr)-20)), str(keyboardStr[i]), scale = 0.785, color = (255,255,255) , thickness = 1)
  190. else:
  191. for i in range(len(keyboardStr)):
  192. canvas.draw_string(0,12*i, str(keyboardStr[i]), scale = 0.785, color = (255,255,255) , thickness = 1)
  193. v831_display_show_canvas(canvas)
  194. # display.show(canvas)
  195. def main():
  196. thread = threading.Thread(target=write_io)
  197. thread.start()
  198. asyncio.run(console_io())
  199. thread.join()
  200. main()