电子说
概述
此指南显示了如何使用Twitter API从特定用户获取推文(但是您可以做很多事情)。举一个具体的例子,它将用于定期从@codewisdom获取最新的tweet,这是一个tweet来自软件行业的引用的feed。我们将获取这些推文,并将其显示在PyPortal上。
Adafruit PyPortal-CircuitPython Powered Internet Display
产品ID:4116
PyPortal是我们易于使用的IoT设备,可让您在数分钟内为“物联网”创建所有东西。制作自定义触摸屏界面。..
$ 54.95
进货
添加到购物车
粉红色和紫色编织USB A至Micro B电缆-2米长
产品ID:4148
这条电缆具有粉红色和紫色Blinka编织图案,非常适合用于时尚!首先,我们来谈谈覆盖层和包覆成型。我们将这些颜色制成自定义颜色,。..
$ 3.95
入库存
添加到购物车
其他工具和材料
您可能想为PyPortal事件倒计时时钟创建可选的桌面支架。为此,您需要:
3D打印机
细丝
PyPortal支架模型文件
M3支脚和螺钉
如果您无权使用3D打印机,则可以选择使用在线服务(例如3D集线器)按需为您打印。
电路场螺栓固定套件
产品ID:3816
您有Circuit Playground Express,但您需要将其安装到迷人的纸板机器人朋友身上,是吗?如果您。..
$ 3.95
进货
添加到购物车
安装CircuitPython
CircuitPython是MicroPython的派生版,旨在简化低成本微控制器上的实验和教学。它不需要任何前期桌面软件下载,因此比以往任何时候都更容易获得原型。只需复制并编辑 CIRCUITPY “闪存”驱动器上的文件即可进行迭代。
以下说明将向您展示如何安装CircuitPython。如果您已经安装了CircuitPython,但希望对其进行更新或重新安装,则同样的步骤也适用!
设置CircuitPython快速入门!
请遵循以下快速逐步操作以获取超快速的Python功能:)
通过CircuitPython.org为该板下载最新版本的CircuitPython
点击上面的链接,为PyPortal下载最新版本的CircuitPython。
下载并将其保存到您的桌面(或方便的任何地方)。
使用已知良好的USB电缆将PyPortal插入计算机。
A很多人最终使用仅可充电的USB电缆,这非常令人沮丧!因此,请确保您拥有知道对数据同步有用的USB电缆。
双击中间顶部顶部的重置按钮(洋红色箭头)在板上,您将看到NeoPixel RGB LED(绿色箭头)变为绿色。如果它变成红色,请检查USB电缆,尝试使用另一个USB端口,等等。注意:USB接口旁边的红色小LED指示灯将呈红色闪烁。没关系!
如果第一次双击不起作用,请重试。有时可能需要一些尝试才能使节奏正确!
您将看到一个名为 PORTALBOOT 。
将 adafruit-circuitpython-pyportal- .uf2 文件拖到 PORTALBOOT。
LED将闪烁。然后, PORTALBOOT 驱动器将消失,并且将出现一个名为 CIRCUITPY 的新磁盘驱动器。
如果未在板上添加任何代码,唯一存在的文件是 boot_out.txt 。这是绝对正常的!是时候添加您的 code.py 并开始使用它了!
就这样,您完成了! :)
PyPortal默认文件
单击下面的按钮,下载PyPortal附带的文件的zip。
PyPortal默认文件
PyPortal CircuitPython设置
要在CircuitPython中使用PyPortal的所有出色功能,必须首先安装许多库。本页涵盖了该过程。
Adafruit CircuitPython捆绑包
下载Adafruit CircuitPython库捆绑包。您可以在此处找到最新版本:
最新的Adafruit CircuitPython库包
下载 adafruit-circuitpython-bundle-4。 x-mpy-*。zip 捆绑zip文件,然后解压缩同名文件夹。在内部,您会找到一个 lib 文件夹。您有两个选择:
您可以将 lib 文件夹添加到您的 CIRCUITPY 驱动器中。这将确保您拥有所有驱动程序。但是这将占用8 MB磁盘上的一堆空间
根据需要添加每个库,这将减少空间使用量,但您需要
至少,我们推荐以下库,实际上我们比推荐的要多。基本上是必需的。因此,立即抓住它们并将它们安装到 CIRCUITPY/lib !
adafruit_esp32spi -这是一个库,可通过ESP32进行互联网访问使用(您猜对了!)SPI传输。 Internet所需的任何东西都需要使用它
adafruit_requests -该库使我们能够执行HTTP请求并从服务器获取响应。 GET/POST/PUT/PATCH-它们都在这里!
adafruit_pyportal -这是我们友好的包装器库,可处理很多项目,显示图形和文本,从互联网上获取数据。
adafruit_touchscreen -一个用于从电阻式触摸屏读取触摸的库。
adafruit_cursorcontrol -用于读取PyGamer和PyBadge游戏杆和按钮的库。为您处理所有图形,按钮阅读和操纵杆移动。
adafruit_io -该库有助于将PyPortal连接到我们的免费数据记录和查看服务
adafruit_imageload -任何图形所需的图像显示助手!
adafruit_display_text -毫不奇怪,它在屏幕上显示文本
adafruit_bitmap_font -我们拥有精美的字体支持,并且易于制作新字体。该库读取并解析字体文件。
adafruit_slideshow -用于制作图像幻灯片-方便快速显示图形和声音
neopixel -用于控制板载新像素
adafruit_adt7410 -用于从板载Analog Devices ADT7410精密温度传感器读取温度的库
adafruit_sdcard -支持从板载SD卡插槽中读取/写入数据。
adafruit_bus_device -对I2C/SPI的低级支持
Internet连接!
一旦您安装了CircuitPython安装程序和库,我们就可以将您的电路板连接到Internet。请注意,目前不支持访问企业级安全的WiFi网络,仅支持需要SSID和密码的WiFi网络。
要建立连接,您需要先创建一个秘密文件。
什么是机密文件?
我们希望人们在构建CircuitPython WiFi小部件时共享大量项目。我们要避免的是人们不小心共享了他们的密码或秘密令牌和API密钥。因此,我们设计了所有示例,以使用 CIRCUITPY 驱动器中的secrets.py文件来保存秘密/私有/自定义数据。这样,您就可以共享您的主项目,而不必担心意外共享私有内容。
您的 secrets.py 文件应如下所示:
下载:文件
复制代码
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it
secrets = {
‘ssid’ : ‘home ssid’,
‘password’ : ‘my password’,
‘timezone’ : “America/New_York”, # http://worldtimeapi.org/timezones
‘github_token’ : ‘fawfj23rakjnfawiefa’,
‘hackaday_token’ : ‘h4xx0rs3kret’,
}
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it
secrets = {
‘ssid’ : ‘home ssid’,
‘password’ : ‘my password’,
‘timezone’ : “America/New_York”, # http://worldtimeapi.org/timezones
‘github_token’ : ‘fawfj23rakjnfawiefa’,
‘hackaday_token’ : ‘h4xx0rs3kret’,
}
Inside是一个名为secrets的python字典,每个条目都有一行。每个条目都有一个条目名称(例如‘ssid’),然后是一个冒号以将其与条目键‘home ssid’分开,最后是一个逗号,
至少您需要ssid和password用于您的本地WiFi设置。在创建项目时,您可能需要更多的令牌和密钥,只需一次添加一行即可。例如,请参见其他令牌,例如用于访问github或hackaday API的令牌。其他非机密数据(例如您的时区)也可以在此处,仅因为其称为机密的信息并不意味着您不能在其中包含常规的自定义数据!
有关正确的时区字符串,请查看http://worldtimeapi.org/timezones,请记住,如果未列出您的城市,请在同一时区中查找城市,例如,波士顿,纽约,费城,华盛顿特区和迈阿密都与纽约位于同一时间。
当然,不要共享您的 secrets.py -将其保存在GitHub,Discord或其他项目共享站点之外。
连接到WiFi
好,现在您已设置好机密-您可以连接到Internet。让我们使用ESP32SPI和Requests库-您需要访问CircuitPython捆绑包并安装:
adafruit_bus_device
adafruit_esp32spi
adafruit_requests
neopixel
进入您的lib文件夹。完成后,使用Mu或您喜欢的编辑器加载以下示例:
下载:项目邮编或 esp32spi_simpletest.py | 在Github上查看
复制代码
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
print(“ESP32 SPI webclient test”)
TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”
JSON_URL = “http://api.coindesk.com/v1/bpi/currentprice/USD.json”
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
requests.set_socket(socket, esp)
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
print(“ESP32 found and in idle mode”)
print(“Firmware vers.”, esp.firmware_version)
print(“MAC addr:”, [hex(i) for i in esp.MAC_address])
for ap in esp.scan_networks():
print(“ %s RSSI: %d” % (str(ap[‘ssid’], ‘utf-8’), ap[‘rssi’]))
print(“Connecting to AP.。.”)
while not esp.is_connected:
try:
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
except RuntimeError as e:
print(“could not connect to AP, retrying: ”,e)
continue
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
print(“My IP address is”, esp.pretty_ip(esp.ip_address))
print(“IP lookup adafruit.com: %s” % esp.pretty_ip(esp.get_host_by_name(“adafruit.com”)))
print(“Ping google.com: %d ms” % esp.ping(“google.com”))
#esp._debug = True
print(“Fetching text from”, TEXT_URL)
r = requests.get(TEXT_URL)
print(‘-’*40)
print(r.text)
print(‘-’*40)
r.close()
print()
print(“Fetching json from”, JSON_URL)
r = requests.get(JSON_URL)
print(‘-’*40)
print(r.json())
print(‘-’*40)
r.close()
print(“Done!”)
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
print(“ESP32 SPI webclient test”)
TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”
JSON_URL = “http://api.coindesk.com/v1/bpi/currentprice/USD.json”
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
requests.set_socket(socket, esp)
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
print(“ESP32 found and in idle mode”)
print(“Firmware vers.”, esp.firmware_version)
print(“MAC addr:”, [hex(i) for i in esp.MAC_address])
for ap in esp.scan_networks():
print(“ %s RSSI: %d” % (str(ap[‘ssid’], ‘utf-8’), ap[‘rssi’]))
print(“Connecting to AP.。.”)
while not esp.is_connected:
try:
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
except RuntimeError as e:
print(“could not connect to AP, retrying: ”,e)
continue
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
print(“My IP address is”, esp.pretty_ip(esp.ip_address))
print(“IP lookup adafruit.com: %s” % esp.pretty_ip(esp.get_host_by_name(“adafruit.com”)))
print(“Ping google.com: %d ms” % esp.ping(“google.com”))
#esp._debug = True
print(“Fetching text from”, TEXT_URL)
r = requests.get(TEXT_URL)
print(‘-’*40)
print(r.text)
print(‘-’*40)
r.close()
print()
print(“Fetching json from”, JSON_URL)
r = requests.get(JSON_URL)
print(‘-’*40)
print(r.json())
print(‘-’*40)
r.close()
print(“Done!”)
,并将其保存到您的板上,名称为code.py。
第一个连接示例不使用机密文件-您将首先输入SSID/密码来验证连接性!
然后转到此行
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
并更改MY_SSID_NAME和 MY_SSID_PASSWORD 设置为您的访问点名称和密码,并将其保留在‘’引号内。 (此示例不使用机密文件,但它也非常独立,因此,如果其他事情似乎不起作用,则可以始终重新加载该文件。您应该获得如下内容:
示例代码。..
使用SPI端口和3个控制引脚通过SPI初始化ESP32:
下载:文件
复制代码
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
告诉我们的requests库我们正在使用的套接字的类型(套接字类型随连接类型而变化-在此示例中,我们将使用adafruit_esp32spi_socket)。还将接口设置为
下载:文件
复制代码
esp requests
验证找到ESP32,检查固件和MAC地址
下载:文件
复制代码
requests.set_socket(socket, esp) requests.set_socket(socket, esp)
扫描它可以看到的所有访问点,并打印出名称和信号强度:
下载:文件
复制代码
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
print(“ESP32 found and in idle mode”)
print(“Firmware vers.”, esp.firmware_version)
print(“MAC addr:”, [hex(i) for i in esp.MAC_address]) if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
print(“ESP32 found and in idle mode”)
print(“Firmware vers.”, esp.firmware_version)
print(“MAC addr:”, [hex(i) for i in esp.MAC_address])
连接到我们在此处定义的AP,然后打印出来本地IP地址,尝试进行域名查找并ping google.com以检查网络连接(请注意,有时ping失败或需要一段时间,这没什么大不了的)
下载:文件
复制代码
for ap in esp.scan_networks():
print(“ %s RSSI: %d” % (str(ap[‘ssid’], ‘utf-8’), ap[‘rssi’])) for ap in esp.scan_networks():
print(“ %s RSSI: %d” % (str(ap[‘ssid’], ‘utf-8’), ap[‘rssi’]))
好的,现在我们进入真正有趣的部分。使用SAMD51或其他大容量RAM(超过32 KB)设备,我们可以做很多巧妙的事情。例如,我们可以像请求一样实现一个接口,这使得获取数据非常简单
从Web URL调用 print(“Connecting to AP.。.”)
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
print(“My IP address is”, esp.pretty_ip(esp.ip_address))
print(“IP lookup adafruit.com: %s” % esp.pretty_ip(esp.get_host_by_name(“adafruit.com”)))
print(“Ping google.com: %d ms” % esp.ping(“google.com”))
中读取所有文本-您可以传入 print(“Connecting to AP.。.”)
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
print(“My IP address is”, esp.pretty_ip(esp.ip_address))
print(“IP lookup adafruit.com: %s” % esp.pretty_ip(esp.get_host_by_name(“adafruit.com”)))
print(“Ping google.com: %d ms” % esp.ping(“google.com”))
用于SSL连接的URL
下载:文件
复制代码
requests.get https
或者,如果数据使用结构化JSON,则可以获取json pre -解析为可以轻松查询或遍历的Python字典。 (同样,仅适用于nRF52840,M4和其他高RAM板)
下载:文件
复制代码
TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”
print(“Fetching text from”, TEXT_URL)
r = requests.get(TEXT_URL)
print(‘-’*40)
print(r.text)
print(‘-’*40)
r.close() TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”
print(“Fetching text from”, TEXT_URL)
r = requests.get(TEXT_URL)
print(‘-’*40)
print(r.text)
print(‘-’*40)
r.close()
Requests
我们已经为Web接口编写了一个类似请求的库,名为Adafruit_CircuitPython_Requests。该库允许您发送HTTP/1.1请求,而无需“设计”它们,并提供了有用的方法来解析服务器的响应。
下载:Project Zip 或 requests_simpletest.py | 在Github上查看
复制代码
JSON_URL = “http://api.coindesk.com/v1/bpi/currentprice/USD.json”
print(“Fetching json from”, JSON_URL)
r = requests.get(JSON_URL)
print(‘-’*40)
print(r.json())
print(‘-’*40)
r.close() JSON_URL = “http://api.coindesk.com/v1/bpi/currentprice/USD.json”
print(“Fetching json from”, JSON_URL)
r = requests.get(JSON_URL)
print(‘-’*40)
print(r.json())
print(‘-’*40)
r.close()
代码首先设置ESP32SPI接口。然后,它使用ESP32 # adafruit_requests usage with an esp32spi_socket
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
print(“Connecting to AP.。.”)
while not esp.is_connected:
try:
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
except RuntimeError as e:
print(“could not connect to AP, retrying: ”,e)
continue
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
# Initialize a requests object with a socket and esp32spi interface
requests.set_socket(socket, esp)
TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”
JSON_GET_URL = “http://httpbin.org/get”
JSON_POST_URL = “http://httpbin.org/post”
print(“Fetching text from %s”%TEXT_URL)
response = requests.get(TEXT_URL)
print(‘-’*40)
print(“Text Response: ”, response.text)
print(‘-’*40)
response.close()
print(“Fetching JSON data from %s”%JSON_GET_URL)
response = requests.get(JSON_GET_URL)
print(‘-’*40)
print(“JSON Response: ”, response.json())
print(‘-’*40)
response.close()
data = ‘31F’
print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, data))
response = requests.post(JSON_POST_URL, data=data)
print(‘-’*40)
json_resp = response.json()
# Parse out the ‘data’ key from json_resp dict.
print(“Data received from server:”, json_resp[‘data’])
print(‘-’*40)
response.close()
json_data = {“Date” : “July 25, 2019”}
print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, json_data))
response = requests.post(JSON_POST_URL, json=json_data)
print(‘-’*40)
json_resp = response.json()
# Parse out the ‘json’ key from json_resp dict.
print(“JSON Data received from server:”, json_resp[‘json’])
print(‘-’*40)
response.close()
和# adafruit_requests usage with an esp32spi_socket
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
print(“Connecting to AP.。.”)
while not esp.is_connected:
try:
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
except RuntimeError as e:
print(“could not connect to AP, retrying: ”,e)
continue
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
# Initialize a requests object with a socket and esp32spi interface
requests.set_socket(socket, esp)
TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”
JSON_GET_URL = “http://httpbin.org/get”
JSON_POST_URL = “http://httpbin.org/post”
print(“Fetching text from %s”%TEXT_URL)
response = requests.get(TEXT_URL)
print(‘-’*40)
print(“Text Response: ”, response.text)
print(‘-’*40)
response.close()
print(“Fetching JSON data from %s”%JSON_GET_URL)
response = requests.get(JSON_GET_URL)
print(‘-’*40)
print(“JSON Response: ”, response.json())
print(‘-’*40)
response.close()
data = ‘31F’
print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, data))
response = requests.post(JSON_POST_URL, data=data)
print(‘-’*40)
json_resp = response.json()
# Parse out the ‘data’ key from json_resp dict.
print(“Data received from server:”, json_resp[‘data’])
print(‘-’*40)
response.close()
json_data = {“Date” : “July 25, 2019”}
print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, json_data))
response = requests.post(JSON_POST_URL, json=json_data)
print(‘-’*40)
json_resp = response.json()
# Parse out the ‘json’ key from json_resp dict.
print(“JSON Data received from server:”, json_resp[‘json’])
print(‘-’*40)
response.close()
对象初始化request对象。
下载:文件
复制代码
socket esp
带有请求的HTTP GET
代码向Adafruit的WiFi测试网站-http:/发出HTTP GET请求/wifitest.adafruit.com/testwifi/index.html。
为此,我们会将URL传递到import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
print(“Connecting to AP.。.”)
while not esp.is_connected:
try:
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
except RuntimeError as e:
print(“could not connect to AP, retrying: ”,e)
continue
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
# Initialize a requests object with a socket and esp32spi interface
requests.set_socket(socket, esp)。我们还将将来自服务器的响应保存到名为import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
print(“Connecting to AP.。.”)
while not esp.is_connected:
try:
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
except RuntimeError as e:
print(“could not connect to AP, retrying: ”,e)
continue
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
# Initialize a requests object with a socket and esp32spi interface
requests.set_socket(socket, esp)的变量。
尽管我们从服务器请求数据,但我们还是希望服务器回应。由于我们已经保存了服务器的requests.get(),因此可以将其读回。对我们来说幸运的是,请求将服务器的响应自动解码为人类可读的文本,您可以通过调用response将其读回。
最后,我们将执行一些操作通过调用response进行清理。这样会关闭,删除和收集响应的数据。
下载:文件
复制代码
response.text response.close()
一些服务器使用文本响应,而某些服务器则使用由属性-值对组成的json格式的数据进行响应。/p》
CircuitPython_Requests可以将来自服务器的JSON格式的响应转换为CPython print(“Fetching text from %s”%TEXT_URL)
response = requests.get(TEXT_URL)
print(‘-’*40)
print(“Text Response: ”, response.text)
print(‘-’*40)
response.close()对象。
我们还可以获取和解析 json 数据。我们将发送HTTP Get到一个我们知道的URL,该URL返回一个json格式的响应(而不是文本数据)。
然后,代码调用print(“Fetching text from %s”%TEXT_URL)
response = requests.get(TEXT_URL)
print(‘-’*40)
print(“Text Response: ”, response.text)
print(‘-’*40)
response.close()将响应转换为一个CPython dict.。
下载:文件
复制代码
response.json() dict
带有请求的HTTP POST
请求还可以通过调用print(“Fetching JSON data from %s”%JSON_GET_URL)
response = requests.get(JSON_GET_URL)
print(‘-’*40)
print(“JSON Response: ”, response.json())
print(‘-’*40)
response.close()方法(向其传递一个print(“Fetching JSON data from %s”%JSON_GET_URL)
response = requests.get(JSON_GET_URL)
print(‘-’*40)
print(“JSON Response: ”, response.json())
print(‘-’*40)
response.close()值)将数据发布到服务器。
下载:文件
复制代码
requests.post data
您还可以通过将data = ‘31F’
print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, data))
response = requests.post(JSON_POST_URL, data=data)
print(‘-’*40)
json_resp = response.json()
# Parse out the ‘data’ key from json_resp dict.
print(“Data received from server:”, json_resp[‘data’])
print(‘-’*40)
response.close()传递到data = ‘31F’
print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, data))
response = requests.post(JSON_POST_URL, data=data)
print(‘-’*40)
json_resp = response.json()
# Parse out the ‘data’ key from json_resp dict.
print(“Data received from server:”, json_resp[‘data’])
print(‘-’*40)
response.close()方法中,将json格式的数据发布到服务器。
下载:文件
复制代码
json_data requests.post
高级请求使用情况
要发送自定义HTTP, aders,将响应解析为原始字节,还是在CircuitPython代码中处理响应的http状态代码?
我们已经编写了一个示例来显示下面的请求模块的高级用法。
下载:项目Zip 或 requests_advanced.py | 在Github上查看
复制代码
json_data = {“Date” : “July 25, 2019”}
print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, json_data))
response = requests.post(JSON_POST_URL, json=json_data)
print(‘-’*40)
json_resp = response.json()
# Parse out the ‘json’ key from json_resp dict.
print(“JSON Data received from server:”, json_resp[‘json’])
print(‘-’*40)
response.close()
json_data = {“Date” : “July 25, 2019”}
print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, json_data))
response = requests.post(JSON_POST_URL, json=json_data)
print(‘-’*40)
json_resp = response.json()
# Parse out the ‘json’ key from json_resp dict.
print(“JSON Data received from server:”, json_resp[‘json’])
print(‘-’*40)
response.close()
WiFi Manager
这个最简单的示例可行,但有点挑剔-您需要不断检查WiFi状态,并具有许多循环来管理连接和断开连接。对于更高级的用途,我们建议使用WiFiManager对象。它将为您包装连接/状态/请求循环-如果WiFi掉线,则重新连接,如果ESP32进入不良状态,则重置ESP32,等等。
这是一个更高级的示例,其中显示了WiFi管理器以及如何使用一些额外的标题发布数据:
下载:Project Zip 或 esp32spi_aio_post.py | 在Github上查看
复制代码
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
print(“Connecting to AP.。.”)
while not esp.is_connected:
try:
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
except RuntimeError as e:
print(“could not connect to AP, retrying: ”,e)
continue
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
# Initialize a requests object with a socket and esp32spi interface
requests.set_socket(socket, esp)
JSON_GET_URL = “http://httpbin.org/get”
# Define a custom header as a dict.
headers = {“user-agent” : “blinka/1.0.0”}
print(“Fetching JSON data from %s.。.”%JSON_GET_URL)
response = requests.get(JSON_GET_URL, headers=headers)
print(‘-’*60)
json_data = response.json()
headers = json_data[‘headers’]
print(“Response‘s Custom User-Agent Header: {0}”.format(headers[’User-Agent‘]))
print(’-‘*60)
# Read Response’s HTTP status code
print(“Response HTTP Status Code: ”, response.status_code)
print(‘-’*60)
# Read Response, as raw bytes instead of pretty text
print(“Raw Response: ”, response.content)
# Close, delete and collect the response data
response.close()
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
print(“Connecting to AP.。.”)
while not esp.is_connected:
try:
esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)
except RuntimeError as e:
print(“could not connect to AP, retrying: ”,e)
continue
print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)
# Initialize a requests object with a socket and esp32spi interface
requests.set_socket(socket, esp)
JSON_GET_URL = “http://httpbin.org/get”
# Define a custom header as a dict.
headers = {“user-agent” : “blinka/1.0.0”}
print(“Fetching JSON data from %s.。.”%JSON_GET_URL)
response = requests.get(JSON_GET_URL, headers=headers)
print(‘-’*60)
json_data = response.json()
headers = json_data[‘headers’]
print(“Response‘s Custom User-Agent Header: {0}”.format(headers[’User-Agent‘]))
print(’-‘*60)
# Read Response’s HTTP status code
print(“Response HTTP Status Code: ”, response.status_code)
print(‘-’*60)
# Read Response, as raw bytes instead of pretty text
print(“Raw Response: ”, response.content)
# Close, delete and collect the response data
response.close()
您会在这里注意到,我们使用secrets.py文件来管理我们的SSID信息。 wifimanager被赋予了ESP32对象,密码和一个用于指示状态的新像素。
请注意,您需要在密码文件中添加一些其他信息,以便代码可以查询Adafruit IO API:
import time
import board
import busio
from digitalio import DigitalInOut
import neopixel
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
print(“ESP32 SPI webclient test”)
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print(“WiFi secrets are kept in secrets.py, please add them there!”)
raise
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
“”“Use below for Most Boards”“”
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
“”“Uncomment below for ItsyBitsy M4”“”
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
# Uncomment below for an externally defined RGB LED
# import adafruit_rgbled
# from adafruit_esp32spi import PWMOut
# RED_LED = PWMOut.PWMOut(esp, 26)
# GREEN_LED = PWMOut.PWMOut(esp, 27)
# BLUE_LED = PWMOut.PWMOut(esp, 25)
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
counter = 0
while True:
try:
print(“Posting data.。.”, end=‘’)
data = counter
feed = ‘test’
payload = {‘value’:data}
response = wifi.post(
“https://io.adafruit.com/api/v2/”+secrets[‘aio_username’]+“/feeds/”+feed+“/data”,
json=payload,
headers={“X-AIO-KEY”:secrets[‘aio_key’]})
print(response.json())
response.close()
counter = counter + 1
print(“OK”)
except (ValueError, RuntimeError) as e:
print(“Failed to get data, retrying ”, e)
wifi.reset()
continue
response = None
time.sleep(15)
import time
import board
import busio
from digitalio import DigitalInOut
import neopixel
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
print(“ESP32 SPI webclient test”)
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print(“WiFi secrets are kept in secrets.py, please add them there!”)
raise
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
“”“Use below for Most Boards”“”
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
“”“Uncomment below for ItsyBitsy M4”“”
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
# Uncomment below for an externally defined RGB LED
# import adafruit_rgbled
# from adafruit_esp32spi import PWMOut
# RED_LED = PWMOut.PWMOut(esp, 26)
# GREEN_LED = PWMOut.PWMOut(esp, 27)
# BLUE_LED = PWMOut.PWMOut(esp, 25)
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
counter = 0
while True:
try:
print(“Posting data.。.”, end=‘’)
data = counter
feed = ‘test’
payload = {‘value’:data}
response = wifi.post(
“https://io.adafruit.com/api/v2/”+secrets[‘aio_username’]+“/feeds/”+feed+“/data”,
json=payload,
headers={“X-AIO-KEY”:secrets[‘aio_key’]})
print(response.json())
response.close()
counter = counter + 1
print(“OK”)
except (ValueError, RuntimeError) as e:
print(“Failed to get data, retrying ”, e)
wifi.reset()
continue
response = None
time.sleep(15)
您可以转到adafruit.io查看AIO密钥链接获取这两个值并将它们添加到secrets文件中,该文件现在看起来像这样:
下载:文件
复制代码
aio_username aio_key
下一步,设置一个名为Adafruit IO提要# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it
secrets = {
‘ssid’ : ‘_your_ssid_’,
‘password’ : ‘_your_wifi_password_’,
‘timezone’ : “America/Los_Angeles”, # http://worldtimeapi.org/timezones
‘aio_username’ : ‘_your_aio_username_’,
‘aio_key’ : ‘_your_aio_key_’,
}
如果您不知道如何设置供稿,请遵循此页面并在设置名为。
然后,我们可以有一个简单的循环,用于将数据发布到Adafruit IO,而无需处理连接或初始化硬件!
在Adafruit.io上查看您的测试数据,每次Cir时,您都会看到该值增加cuitPython板向其发布数据!
Twitter认证密钥
在使用Twitter API之前,我们需要注册一个开发人员帐户。
开始到https://developer.twitter.com/en.html。您应该会看到类似以下页面的页面:
单击应用:
然后申请开发者帐户:
选择浏览API ,然后点击下一步 。
填写显示的表格,然后点击下一步。验证信息,然后单击下一步。同意条款,然后点击提交申请。您会在输入的地址收到一封确认电子邮件。相应地进行响应,您将可以创建您的 app 。
创建应用程序
要获取要使用的密钥,您需要创建一个应用程序。您将获得该应用程序的密钥,在本例中为万圣节倒计时应用程序。
单击创建应用程序将显示一个表格。如您所愿地将其填写,总体上似乎不太挑剔。完成该操作后,您的应用程序页面将列出您的新应用程序:
点击应用旁边的详细信息按钮。这会提供您应用程序上的所有信息。
您正在寻找的是应用程序密钥。在“密钥和令牌”标签上找到它们:
将 API密钥和 API秘密密钥作为 secrets.py 文件中= 1》和twitter_api_key。
就是这样。
获取推文
OAuth徽标作者:Chris Messina CC BY_SA 3.0
Authenticating
一旦拥有了Twitter密钥,就可以在程序开始获取Twitter OAuth 2.0 bearer令牌时使用它们。这涉及合并两个密钥,进行base64编码,调用Twitter API,以及从响应中提取承载令牌。它有些牵连,即使我们只需要使用一次,它也是包装函数的理想之选。
谁知道,这可能是Twitter API包装库的开始。
下载:文件
复制代码
def get_bearer_token():
“”“Get the bearer authentication token from twitter.”“”
raw_key = secrets[‘twitter_api_key’] + ‘:’ + secrets[‘twitter_secret_key’]
encoded_key = binascii.b2a_base64(bytes(raw_key, ‘utf8’))
string_key = bytes.decode(encoded_key)
headers= {‘Authorization’: ‘Basic ’ + string_key,
‘Content-Type’: ‘application/x-www-form-urlencoded;charset=UTF-8’}
response = requests.post(‘https://api.twitter.com/oauth2/token’,
headers=headers,
data=‘grant_type=client_credentials’)
response_dict = json.loads(response.content)
if response_dict[‘token_type’] != ‘bearer’:
halt_and_catch_fire(‘Wrong token type from twitter: %s’, response_dict[‘token_type’])
return response_dict[‘access_token’] def get_bearer_token():
“”“Get the bearer authentication token from twitter.”“”
raw_key = secrets[‘twitter_api_key’] + ‘:’ + secrets[‘twitter_secret_key’]
encoded_key = binascii.b2a_base64(bytes(raw_key, ‘utf8’))
string_key = bytes.decode(encoded_key)
headers= {‘Authorization’: ‘Basic ’ + string_key,
‘Content-Type’: ‘application/x-www-form-urlencoded;charset=UTF-8’}
response = requests.post(‘https://api.twitter.com/oauth2/token’,
headers=headers,
data=‘grant_type=client_credentials’)
response_dict = json.loads(response.content)
if response_dict[‘token_type’] != ‘bearer’:
halt_and_catch_fire(‘Wrong token type from twitter: %s’, response_dict[‘token_type’])
return response_dict[‘access_token’]
注意对函数halt_and_catch_fire的调用。该函数接受传递的参数,将其组合并打印结果,然后停止(通过无限循环)。该名称是对AMC的致敬,该展览与微型计算机行业的早期名称相同。尽管并不完全准确(相信我,我在那里),但它还是很有趣的。反过来,它是对(来自Wikipedia的)引用:
在计算机工程中, Halt and Catch Fire (由组装助记符 HCF 已知) ,是计算机计算机代码指令的惯用语,该指令导致计算机的中央处理单元(CPU)停止有意义的操作,通常需要重新启动计算机。
这似乎是适当的。
下载:文件
复制代码
def halt_and_catch_fire(message, *args):
“”“Log a critical error and stall the system.”“”
print(message % args)
while True:
pass def halt_and_catch_fire(message, *args):
“”“Log a critical error and stall the system.”“”
print(message % args)
while True:
pass
设置PyPortal对象
在真正发生任何事情之前,我们需要一个PyPortal的实例。这将设置URL,用于从该URL返回的json中提取推文文本的json路径,以及文本区域特征。
下载:文件
复制代码
cwd = (“/”+__file__).rsplit(‘/’, 1)[0]
url = ‘https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=’ + username
# Initialize the pyportal object and let us know what data to fetch and where
# to display it
pyportal = PyPortal(url=url,
json_path=(0, ‘text’),
status_neopixel=board.NEOPIXEL,
default_bg=cwd + ‘/twitter_background.bmp’,
text_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,
text_position=(20, 60),
text_color=0xFFFFFF,
text_wrap=35,
caption_text=‘@’ + username,
caption_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,
caption_position=(5, 210),
caption_color=0x808080) cwd = (“/”+__file__).rsplit(‘/’, 1)[0]
url = ‘https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=’ + username
# Initialize the pyportal object and let us know what data to fetch and where
# to display it
pyportal = PyPortal(url=url,
json_path=(0, ‘text’),
status_neopixel=board.NEOPIXEL,
default_bg=cwd + ‘/twitter_background.bmp’,
text_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,
text_position=(20, 60),
text_color=0xFFFFFF,
text_wrap=35,
caption_text=‘@’ + username,
caption_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,
caption_position=(5, 210),
caption_color=0x808080)
这也会初始化wifi堆栈,因此现在我们可以获取身份验证令牌并构造推文获取所需的身份验证标头。
下载:文件
复制代码
bearer_token = get_bearer_token()
pyportal.set_headers({‘Authorization’: ‘Bearer ’ + bearer_token}) bearer_token = get_bearer_token()
pyportal.set_headers({‘Authorization’: ‘Bearer ’ + bearer_token})
获取推文
现在,承载令牌已被获取并用于设置auth标头,可以调用API来获取一些推文
主循环在下面。每小时都会获取最新的推文。上面我们设置了PyPortal实例,其中包含从Twitter API中获取数据,提取推文的文本并显示它所需的一切。所有需要做的就是告诉它使用fetch()方法来做到这一点。
下载:文件
复制代码
while True:
pyportal.fetch()
time.sleep(3600) # check every hour while True:
pyportal.fetch()
time.sleep(3600) # check every hour
代码
下载: Project Zip 或 code.py | 在Github上查看
复制代码
“”“
Twitter API for PyPortal.
Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!
Written by Dave Astels for Adafruit Industries
Copyright (c) 2019 Adafruit Industries
Licensed under the MIT license.
All text above must be included in any redistribution.
”“”
#pylint:disable=invalid-name
import time
import binascii
import json
import board
from adafruit_pyportal import PyPortal
import adafruit_esp32spi.adafruit_esp32spi_requests as requests
username = ‘codewisdom’
try:
from secrets import secrets
except ImportError:
print(“”“WiFi settings are kept in secrets.py, please add them there!
the secrets dictionary must contain ‘ssid’ and ‘password’ at a minimum”“”)
raise
def halt_and_catch_fire(message, *args):
“”“Log a critical error and stall the system.”“”
print(message % args)
while True:
pass
def get_bearer_token():
“”“Get the bearer authentication token from twitter.”“”
raw_key = secrets[‘twitter_api_key’] + ‘:’ + secrets[‘twitter_secret_key’]
encoded_key = binascii.b2a_base64(bytes(raw_key, ‘utf8’))
string_key = bytes.decode(encoded_key)
headers = {‘Authorization’: ‘Basic ’ + string_key,
‘Content-Type’: ‘application/x-www-form-urlencoded;charset=UTF-8’}
response = requests.post(‘https://api.twitter.com/oauth2/token’,
headers=headers,
data=‘grant_type=client_credentials’)
response_dict = json.loads(response.content)
if response_dict[‘token_type’] != ‘bearer’:
halt_and_catch_fire(‘Wrong token type from twitter: %s’, response_dict[‘token_type’])
return response_dict[‘access_token’]
# determine the current working directory
# needed so we know where to find files
cwd = (“/”+__file__).rsplit(‘/’, 1)[0]
url = ‘https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=’ + username
# Initialize the pyportal object and let us know what data to fetch and where
# to display it
pyportal = PyPortal(url=url,
json_path=(0, ‘text’),
status_neopixel=board.NEOPIXEL,
default_bg=cwd + ‘/twitter_background.bmp’,
text_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,
text_position=(20, 60),
text_color=0xFFFFFF,
text_wrap=35,
caption_text=‘@’ + username,
caption_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,
caption_position=(5, 210),
caption_color=0x808080)
bearer_token = get_bearer_token()
pyportal.set_headers({‘Authorization’: ‘Bearer ’ + bearer_token})
while True:
pyportal.fetch()
time.sleep(3600) # check every hour
“”“
Twitter API for PyPortal.
Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!
Written by Dave Astels for Adafruit Industries
Copyright (c) 2019 Adafruit Industries
Licensed under the MIT license.
All text above must be included in any redistribution.
”“”
#pylint:disable=invalid-name
import time
import binascii
import json
import board
from adafruit_pyportal import PyPortal
import adafruit_esp32spi.adafruit_esp32spi_requests as requests
username = ‘codewisdom’
try:
from secrets import secrets
except ImportError:
print(“”“WiFi settings are kept in secrets.py, please add them there!
the secrets dictionary must contain ‘ssid’ and ‘password’ at a minimum”“”)
raise
def halt_and_catch_fire(message, *args):
“”“Log a critical error and stall the system.”“”
print(message % args)
while True:
pass
def get_bearer_token():
“”“Get the bearer authentication token from twitter.”“”
raw_key = secrets[‘twitter_api_key’] + ‘:’ + secrets[‘twitter_secret_key’]
encoded_key = binascii.b2a_base64(bytes(raw_key, ‘utf8’))
string_key = bytes.decode(encoded_key)
headers = {‘Authorization’: ‘Basic ’ + string_key,
‘Content-Type’: ‘application/x-www-form-urlencoded;charset=UTF-8’}
response = requests.post(‘https://api.twitter.com/oauth2/token’,
headers=headers,
data=‘grant_type=client_credentials’)
response_dict = json.loads(response.content)
if response_dict[‘token_type’] != ‘bearer’:
halt_and_catch_fire(‘Wrong token type from twitter: %s’, response_dict[‘token_type’])
return response_dict[‘access_token’]
# determine the current working directory
# needed so we know where to find files
cwd = (“/”+__file__).rsplit(‘/’, 1)[0]
url = ‘https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=’ + username
# Initialize the pyportal object and let us know what data to fetch and where
# to display it
pyportal = PyPortal(url=url,
json_path=(0, ‘text’),
status_neopixel=board.NEOPIXEL,
default_bg=cwd + ‘/twitter_background.bmp’,
text_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,
text_position=(20, 60),
text_color=0xFFFFFF,
text_wrap=35,
caption_text=‘@’ + username,
caption_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,
caption_position=(5, 210),
caption_color=0x808080)
bearer_token = get_bearer_token()
pyportal.set_headers({‘Authorization’: ‘Bearer ’ + bearer_token})
while True:
pyportal.fetch()
time.sleep(3600) # check every hour
责任编辑:wv
全部0条评论
快来发表一下你的评论吧 !