flipper_http.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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_scan_wifi() -> str:
  91. """Scan for WiFi networks"""
  92. flipper_http_send_data("[WIFI/SCAN]")
  93. data = flipper_http_read_data(500)
  94. clear_buffer()
  95. return data
  96. def flipper_http_save_wifi(ssid, password) -> bool:
  97. """Save WiFi credentials"""
  98. if ssid is None or password is None:
  99. return False
  100. flipper_http_send_data(
  101. '[WIFI/SAVE]{"ssid":"' + ssid + '","password":"' + password + '"}'
  102. )
  103. data = flipper_http_read_data()
  104. clear_buffer()
  105. return "[SUCCESS]" in data
  106. def flipper_http_get_request(url) -> str:
  107. """Send a GET request to the specified URL"""
  108. if url is None:
  109. return ""
  110. flipper_http_send_data("[GET]" + url)
  111. if "[GET/SUCCESS]" in flipper_http_read_data():
  112. data = flipper_http_read_data()
  113. clear_buffer()
  114. return data
  115. clear_buffer()
  116. return ""
  117. def flipper_http_get_request_with_headers(url, headers) -> str:
  118. """Send a GET request to the specified URL with headers"""
  119. if url is None:
  120. return ""
  121. flipper_http_send_data('[GET/HTTP]{url:"' + url + '",headers:' + headers + "}")
  122. if "[GET/SUCCESS]" in flipper_http_read_data():
  123. data = flipper_http_read_data(500)
  124. clear_buffer()
  125. return data
  126. clear_buffer()
  127. return ""
  128. def flipper_http_post_request_with_headers(url, headers, data):
  129. """Send a POST request to the specified URL with headers and data"""
  130. if url is None:
  131. return ""
  132. flipper_http_send_data(
  133. '[POST/HTTP]{"url":"'
  134. + url
  135. + '","headers":'
  136. + headers
  137. + ',"payload":'
  138. + data
  139. + "}"
  140. )
  141. if "[POST/SUCCESS]" in flipper_http_read_data():
  142. data = flipper_http_read_data(500)
  143. clear_buffer()
  144. return data
  145. clear_buffer()
  146. return ""
  147. def flipper_http_put_request_with_headers(url, headers, data):
  148. """Send a PUT request to the specified URL with headers and data"""
  149. if url is None:
  150. return ""
  151. flipper_http_send_data(
  152. '[PUT/HTTP]{"url":"'
  153. + url
  154. + '","headers":'
  155. + headers
  156. + ',"payload":'
  157. + data
  158. + "}"
  159. )
  160. if "[PUT/SUCCESS]" in flipper_http_read_data():
  161. data = flipper_http_read_data(500)
  162. clear_buffer()
  163. return data
  164. clear_buffer()
  165. return ""
  166. def flipper_http_delete_request_with_headers(url, headers, data):
  167. """Send a DELETE request to the specified URL with headers and data"""
  168. if url is None:
  169. return ""
  170. flipper_http_send_data(
  171. '[DELETE/HTTP]{"url":"'
  172. + url
  173. + '","headers":'
  174. + headers
  175. + ',"payload":'
  176. + data
  177. + "}"
  178. )
  179. if "[DELETE/SUCCESS]" in flipper_http_read_data():
  180. data = flipper_http_read_data(500)
  181. clear_buffer()
  182. return data
  183. clear_buffer()
  184. return ""
  185. # Example of how to use the functions
  186. """ uncomment to run the example
  187. flipper_print("Starting HTTP example")
  188. clear_buffer() # Clear the buffer before starting
  189. time.sleep(1)
  190. if flipper_http_ping() and flipper_http_save_wifi("JBlanked", "maingirl"):
  191. flipper_print("WiFi saved successfully!")
  192. time.sleep(2)
  193. if flipper_http_connect_wifi():
  194. flipper_print("WiFi connected successfully!")
  195. time.sleep(2)
  196. flipper_print(
  197. flipper_http_get_request_with_headers(
  198. "https://httpbin.org/get", "{Content-Type: application/json}"
  199. )
  200. )
  201. time.sleep(2)
  202. if flipper_http_disconnect_wifi():
  203. flipper_print("WiFi disconnected successfully!")
  204. time.sleep(2)
  205. else:
  206. flipper_print("Failed to save WiFi credentials")
  207. time.sleep(2)
  208. flipper_print("Exiting...")
  209. time.sleep(2)
  210. """ # uncomment to run the example