注:以下代碼和說明是在ESP8266 開發板上實現。參考資料下載:
1.ESP8266 連接到網絡
2.ESP8266實現WEB端控制 LED
簡介
本MicroPython教程旨在闡釋如何藉助urequests模塊用MicroPython執行HTTP GET請求。本教程在ESP8266的MicroPython上均進行了測試。下文所示數據出自ESP8266 上的測試,你可以在這裏(https://github.com/micropython/micropython-lib/blob/master/urequests/urequests.py)訪問庫的源代碼。
重要提示:本文撰寫之際,所用的MicroPython版本內含urequests模塊。請注意,此情況或有變化,之後版本的默認配置可能不會包含該模塊,你需要先進行手動安裝。
當然,爲適用本教程,我們首先需要連接到WiFi網絡,以便訪問互聯網。本教程將不再贅述如何連接WiFi網絡。如果你想手動連接,請參閱這篇(http://mc.dfrobot.com.cn/forum.php?mod=viewthread&tid=272122)詳細指南。
我們將通過連接MicroPython提示符並一次發送一個命令來運行代碼。如果你願意的話,可以在腳本中編寫命令並從你的計算機運行該腳本,如此處(翻譯中)所述。另一個選擇是將腳本上傳到MicroPython的文件系統並從提示符運行該腳本,如此處(https://www.dfrobot.com/index.php?route=DFblog/blogs)所述。
1. GET請求命令的實現:
import urequests
response = urequests.get('http://jsonplaceholder.typicode.com/albums/1')
#注: 我們要通過HTTP GET請求訪問的網站URL是http://jsonplaceholder.typicode.com/albums/1,你可以通過在web瀏覽器上
# 訪問該網站來查看預期結果。訪問該網站時,你應該會得到如下所示的內容,這是虛擬相冊對象的JSON結構。
print(type(response))
#返回的對象是Response類
print(response.text)
#訪問HTTP請求響應得到實際內容,只要訪問其text屬性
print(type(response.text))
JSON格式
parsed = response.json()
#請求響應是 json 格式
print(type(parsed))
#因此可知json 是字典類數據 <class 'dict'>
print(parsed["userId"])
print(parsed["id"])
print(parsed["title"])
#可以通過字典對象上值的鍵來獲取每個單獨的JSON值
##可藉助ujson庫來解析內容
另一個檢索請求響應內容的有趣方法是使用以字節爲單位返回響應的content屬性
print(response.content)
#b'{\n "userId": 1,\n "id": 1,\n "title": "quidem molestiae enim"\n}'
print(type(response.content))
#<class 'bytes'>
HTTP狀態代碼和原因
print(response.status_code)
#200
print(response.reason)
#b'OK'
# ESP8266 MicroPython Web Clock
# by Alan Wang
import network
import urequests
import ujson
import utime
import ssd1306
import machine
from machine import RTC, I2C, Pin
# user data
ssid = "ssid" # wifi router name
pw = "pw" # wifi router password
url = 'http://worldtimeapi.org/api/timezone/Asia/Hong_Kong'
# see http://worldtimeapi.org/timezones
#url = http://worldtimeapi.org/timezone/Asia/Hong_Kong
web_query_delay = 60000 # interval time of web JSON query
retry_delay = 5000 # interval time of retry after a failed Web query
# initialization
# SSD1306 OLED display
print("Connecting to wifi...")
oled = ssd1306.SSD1306_I2C(128, 64, I2C(scl=Pin(5), sda=Pin(4)))
oled.fill(0)
oled.text("Connecting", 0, 5)
oled.text(" to wifi...", 0, 15)
oled.show()
# internal real time clock
rtc = RTC()
# wifi connection
wifi = network.WLAN(network.STA_IF) # station mode
wifi.active(True)
wifi.connect(ssid, pw)
# wait for connection
while not wifi.isconnected():
pass
# wifi connected
print("IP: " + str(wifi.ifconfig()[0]) + "\n")
oled.text("Connected. IP: ", 0, 35)
oled.text(" " + str(wifi.ifconfig()[0]), 0, 45)
oled.show()
# set timer
update_time = utime.ticks_ms() - web_query_delay
# main loop
while True:
# if lose wifi connection reboot ESP8266
if not wifi.isconnected():
machine.reset()
# query and get web JSON every web_query_delay ms
if utime.ticks_ms() - update_time >= web_query_delay:
# HTTP GET data
response = urequests.get(url)
if response.status_code == 200: # query success
print("JSON response:\n" + response.text)
# parse JSON
parsed = ujson.loads(response.text)
# you can also use parsed = response.json()
datetime_str = str(parsed["datetime"])
year = int(datetime_str[0:4])
month = int(datetime_str[5:7])
day = int(datetime_str[8:10])
hour = int(datetime_str[11:13])
minute = int(datetime_str[14:16])
second = int(datetime_str[17:19])
subsecond = int(round(int(datetime_str[20:26]) / 10000))
# update internal RTC
rtc.datetime((year, month, day, 0, hour, minute, second, subsecond))
update_time = utime.ticks_ms()
print("RTC updated\n")
else: # query failed, retry retry_delay ms later
update_time = utime.ticks_ms() - web_query_delay + retry_delay
# generate formated date/time strings from internal RTC
date_str = "{:02}/{:02}/{:4}".format(rtc.datetime()[1], rtc.datetime()[2], rtc.datetime()[0])
time_str = "{:02}:{:02}:{:02}".format(rtc.datetime()[4], rtc.datetime()[5], rtc.datetime()[6])
# update SSD1306 OLED display
oled.fill(0)
oled.text("ESP8266 Clock", 0, 5)
oled.text("Date: " + date_str, 0, 25)
oled.text("Time: " + time_str, 0, 45)
oled.show()
utime.sleep(0.1)