flipper_http.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. """
  2. This is only available in uPython in version 1.5.0. and above: https://ofabel.github.io/mp-flipper/reference.html#classes
  3. Author - JBlanked
  4. For use with Flipper Zero and the FlipperHTTP flash: https://github.com/jblanked/WebCrawler-FlipperZero/tree/main/assets/FlipperHTTP
  5. Individual functions to save memory (uPython has already pushed the limits)
  6. Lastly, be careful looping in the requests, you'll get a furi check error. I'm assuming it's a memory issue and will be fixed in future updates.
  7. """
  8. import time
  9. import flipperzero as f0
  10. def flipper_print(*args, sep=" ", end="\n", clear_screen=True, y_start=0):
  11. """Print text to the Flipper Zero screen since print() doesn't show on the screen"""
  12. # Combine all arguments into a single string, manually joining without using splitlines
  13. text = sep.join(map(str, args)) + end
  14. # Optionally clear the screen before printing
  15. if clear_screen:
  16. f0.canvas_clear()
  17. f0.canvas_update() # Ensure the screen is cleared
  18. # Manually handle line breaks by splitting on "\n"
  19. lines = []
  20. current_line = ""
  21. for char in text:
  22. if char == "\n":
  23. lines.append(current_line)
  24. current_line = ""
  25. else:
  26. current_line += char
  27. lines.append(current_line) # Add the last line
  28. # Display each line on the screen
  29. y_position = y_start
  30. for line in lines:
  31. f0.canvas_set_text(0, y_position, line) # Display each line
  32. y_position += 10 # Adjust line spacing
  33. # Update the display to show the text
  34. f0.canvas_update()
  35. def flipper_http_read_data(sleep_ms: int = 100) -> str:
  36. """Read data from the Flipper Zero UART"""
  37. with f0.uart_open(f0.UART_MODE_USART, 115200) as uart:
  38. raw_data = uart.readline()
  39. i = 0
  40. while len(raw_data) == 0 and i < 5:
  41. raw_data = uart.readline()
  42. if len(raw_data) > 0:
  43. data = raw_data.decode()
  44. # flipper_print(data)
  45. return data
  46. i += 1
  47. time.sleep_ms(sleep_ms)
  48. return None
  49. def flipper_http_send_data(value: str):
  50. """Send data to the Flipper Zero UART"""
  51. if value is None:
  52. return
  53. with f0.uart_open(f0.UART_MODE_USART, 115200) as uart:
  54. uart.write(value.encode())
  55. uart.flush()
  56. def clear_buffer():
  57. """Clear the buffer of the Flipper Zero UART"""
  58. data = flipper_http_read_data()
  59. while data is not None:
  60. data = flipper_http_read_data()
  61. def flipper_http_ping() -> bool:
  62. """Ping the WiFi Devboard to check if it is connected"""
  63. flipper_http_send_data("[PING]")
  64. data = flipper_http_read_data()
  65. clear_buffer()
  66. return "[PONG]" in data
  67. def flipper_http_connect_wifi() -> bool:
  68. """Connect to WiFi"""
  69. flipper_http_send_data("[WIFI/CONNECT]")
  70. data = flipper_http_read_data()
  71. clear_buffer()
  72. # had to write it this way due to mPython limitations
  73. if "[SUCCESS]" in data:
  74. return True
  75. if "[CONNECTED]" in data:
  76. return True
  77. elif "[INFO]" in data:
  78. return True
  79. return False
  80. def flipper_http_disconnect_wifi() -> bool:
  81. """Disconnect from WiFi"""
  82. flipper_http_send_data("[WIFI/DISCONNECT]")
  83. data = flipper_http_read_data()
  84. clear_buffer()
  85. if "[DISCONNECTED]" in data:
  86. return True
  87. if "WiFi stop" in data:
  88. return True
  89. return False
  90. def flipper_http_list_commands() -> str:
  91. """List all available commands"""
  92. flipper_http_send_data("[LIST]")
  93. data = flipper_http_read_data(500)
  94. clear_buffer()
  95. return data
  96. def flipper_http_led_on():
  97. """Allow the LED to display while processing"""
  98. flipper_http_send_data("[LED/ON]")
  99. def flipper_http_led_off():
  100. """Disable the LED from displaying while processing"""
  101. flipper_http_send_data("[LED/OFF]")
  102. def flipper_http_parse_json(key: str, json_data: str) -> str:
  103. """Parse JSON data"""
  104. flipper_http_send_data('[PARSE]{"key":"' + key + '","json":' + json_data + "}")
  105. data = flipper_http_read_data(500)
  106. clear_buffer()
  107. return data
  108. def flipper_http_parse_json_array(key: str, index: int, json_data: str) -> str:
  109. """Parse JSON data"""
  110. flipper_http_send_data(
  111. '[PARSE/ARRAY]{"key":"'
  112. + key
  113. + '","index":"'
  114. + index
  115. + '","json":'
  116. + json_data
  117. + "}"
  118. )
  119. data = flipper_http_read_data(500)
  120. clear_buffer()
  121. return data
  122. def flipper_http_scan_wifi() -> str:
  123. """Scan for WiFi networks"""
  124. flipper_http_send_data("[WIFI/SCAN]")
  125. data = flipper_http_read_data(500)
  126. clear_buffer()
  127. return data
  128. def flipper_http_save_wifi(ssid: str, password: str) -> bool:
  129. """Save WiFi credentials"""
  130. if ssid is None or password is None:
  131. return False
  132. flipper_http_send_data(
  133. '[WIFI/SAVE]{"ssid":"' + ssid + '","password":"' + password + '"}'
  134. )
  135. data = flipper_http_read_data()
  136. clear_buffer()
  137. return "[SUCCESS]" in data
  138. def flipper_http_ip_address() -> str:
  139. """Get the IP address of the WiFi Devboard"""
  140. flipper_http_send_data("[IP/ADDRESS]")
  141. data = flipper_http_read_data()
  142. clear_buffer()
  143. return data
  144. def flipper_http_ip_wifi() -> str:
  145. """Get the IP address of the connected WiFi network"""
  146. flipper_http_send_data("[WIFI/IP]")
  147. data = flipper_http_read_data()
  148. clear_buffer()
  149. return data
  150. def flipper_http_get_request(url: str) -> str:
  151. """Send a GET request to the specified URL"""
  152. if url is None:
  153. return ""
  154. flipper_http_send_data("[GET]" + url)
  155. if "[GET/SUCCESS]" in flipper_http_read_data():
  156. data = flipper_http_read_data()
  157. clear_buffer()
  158. return data
  159. clear_buffer()
  160. return ""
  161. def flipper_http_get_request_with_headers(url: str, headers: str) -> str:
  162. """Send a GET request to the specified URL with headers"""
  163. if url is None:
  164. return ""
  165. flipper_http_send_data('[GET/HTTP]{url:"' + url + '",headers:' + headers + "}")
  166. if "[GET/SUCCESS]" in flipper_http_read_data():
  167. data = flipper_http_read_data(500)
  168. clear_buffer()
  169. return data
  170. clear_buffer()
  171. return ""
  172. def flipper_http_post_request_with_headers(url: str, headers: str, data: str):
  173. """Send a POST request to the specified URL with headers and data"""
  174. if url is None:
  175. return ""
  176. flipper_http_send_data(
  177. '[POST/HTTP]{"url":"'
  178. + url
  179. + '","headers":'
  180. + headers
  181. + ',"payload":'
  182. + data
  183. + "}"
  184. )
  185. if "[POST/SUCCESS]" in flipper_http_read_data():
  186. data = flipper_http_read_data(500)
  187. clear_buffer()
  188. return data
  189. clear_buffer()
  190. return ""
  191. def flipper_http_put_request_with_headers(url: str, headers: str, data: str):
  192. """Send a PUT request to the specified URL with headers and data"""
  193. if url is None:
  194. return ""
  195. flipper_http_send_data(
  196. '[PUT/HTTP]{"url":"'
  197. + url
  198. + '","headers":'
  199. + headers
  200. + ',"payload":'
  201. + data
  202. + "}"
  203. )
  204. if "[PUT/SUCCESS]" in flipper_http_read_data():
  205. data = flipper_http_read_data(500)
  206. clear_buffer()
  207. return data
  208. clear_buffer()
  209. return ""
  210. def flipper_http_delete_request_with_headers(url: str, headers: str, data: str):
  211. """Send a DELETE request to the specified URL with headers and data"""
  212. if url is None:
  213. return ""
  214. flipper_http_send_data(
  215. '[DELETE/HTTP]{"url":"'
  216. + url
  217. + '","headers":'
  218. + headers
  219. + ',"payload":'
  220. + data
  221. + "}"
  222. )
  223. if "[DELETE/SUCCESS]" in flipper_http_read_data():
  224. data = flipper_http_read_data(500)
  225. clear_buffer()
  226. return data
  227. clear_buffer()
  228. return ""
  229. # Example of how to use the functions
  230. """ uncomment to run the example
  231. flipper_print("Starting HTTP example")
  232. clear_buffer() # Clear the buffer before starting
  233. time.sleep(1)
  234. if flipper_http_ping() and flipper_http_save_wifi("JBlanked", "maingirl"):
  235. flipper_print("WiFi saved successfully!")
  236. time.sleep(2)
  237. if flipper_http_connect_wifi():
  238. flipper_print("WiFi connected successfully!")
  239. time.sleep(2)
  240. flipper_print(
  241. flipper_http_get_request_with_headers(
  242. "https://httpbin.org/get", "{Content-Type: application/json}"
  243. )
  244. )
  245. time.sleep(2)
  246. if flipper_http_disconnect_wifi():
  247. flipper_print("WiFi disconnected successfully!")
  248. time.sleep(2)
  249. else:
  250. flipper_print("Failed to save WiFi credentials")
  251. time.sleep(2)
  252. flipper_print("Exiting...")
  253. time.sleep(2)
  254. """ # uncomment to run the example