flipper_http.py 6.8 KB

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