怎样将PyPortal设置为图像查看器

电子说

1.3w人已加入

描述

概述

编码

SPAAAAAACE!谁不想看到无穷无尽的太空照片?

NASA的每日天文图片(APOD)网站提供了标题中所说的内容,每天都有一张令人难以置信的崭新太空照片。现在,您可以将PyPortal设置为这些光荣图像的专用查看器!

您将使用CircuitPython对其进行编码,并且PyPortal库将使查询NASA Open API的过程变得简单。图像。

零件

编码

Adafruit PyPortal-CircuitPython支持的Internet显示

产品ID:4116

PyPortal,我们易于使用的物联网设备,可让您在几分钟内为“物联网”创建所有东西。制作自定义触摸屏界面。..

$ 54.95

进货

添加到购物车

编码

Adafruit PyPortal桌面支架附件包

产品ID:4146

PyPortal是我们易于使用的IoT设备,可让您在数分钟内为“物联网”创建所有东西。创建小口袋。..

$ 9.95

进货

添加到购物车

编码

完全可反转的粉红色/紫色USB A至micro B电缆- 1m长

产品ID:4111

该电缆不仅非常时尚,而且具有粉红色和紫色Blinka编织图案,而且完全可逆!没错,您每天可以节省。..秒。..

$ 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板向其发布数据!

编码

代码PyPortal NASA图像查看器

编码

NASA Open API密钥

我们将使用NASA API进行查询并检索当天的图片。为此,您需要在 api.nasa.org 注册一个免费帐户并获取您的API密钥。

这很容易做到,只需转到此链接,然后输入您的姓名和电子邮件地址。这里的所有都是它的!您的API密钥将生成并通过电子邮件发送给您,并立即显示在浏览器中。保持该键(或包含它的电子邮件)方便,我们需要稍后将其复制并粘贴到我们的代码中。

Adafruit IO时间服务器

为了使用Adafruit图像转换器,该项目将要求您拥有Adafruit IO用户名和密钥。 Adafruit IO是绝对免费的,但是您需要使用Adafruit帐户登录才能使用它。如果您还没有Adafruit登录名,请在此处创建一个登录名。

如果您以前从未使用过Adafruit IO,请查看本指南以获取更多信息。

登录到您的帐户后,您需要在 secrets.py 文件中放置以下两项信息: Adafruit IO用户名和 Adafruit IO键。前往io.adafruit.com,只需点击Adafruit IO页面左侧的查看AIO密钥链接即可获取此信息。

然后将它们添加到 secrets.py 文件,例如:

下载:文件

复制代码

secrets = {

‘ssid’ : ‘your_wifi_ssid’,

‘password : ’your_wifi_password‘,

’aio_username‘ : ’your_aio_username‘,

’aio_key‘ : ’your_big_huge_super_long_aio_key‘

} secrets = {

’ssid‘ : ’your_wifi_ssid‘,

’password : ‘your_wifi_password’,

‘aio_username’ : ‘your_aio_username’,

‘aio_key’ : ‘your_big_huge_super_long_aio_key’

}

添加CircuitPython代码和资产

在下面的嵌入式代码元素中,单击下载:项目Zip 链接,然后保存.zip存档文件。

然后解压缩.zip文件,它将解压缩到名为 PyPortal_NASA 的文件夹中。

复制 PyPortal_NASA 目录到PyPortal的 CIRCUITPY 驱动器,然后确保将 nasa.py 文件重命名为 code.py ,当PyPortal重新启动时,它将自动运行。

编码

编辑代码

您可以使用任何喜欢的文本编辑器来编辑 code.py 文件。 Adafruit建议安装免费的Mu Python编辑器,因为它超级方便,可以识别Adafruit板,并具有内置的串行监视器/REPL以与板交互。在此处了解有关Mu的更多信息。

添加NASA API密钥

在Mu中打开 code.py ,然后从我们之前获得的NASA复制并粘贴您的API密钥到DATA_SOURCE网址中,

该行应如下所示:

DEMO_KEY

完成后,再次将 code.py 文件保存到PyPortal的 CIRCUITPY 驱动器中。

boot.py

我们正在使用一个特殊文件来确保.bmp缓存写入正确闪烁。这是您复制到驱动器的 unsafe_boot.py 文件。现在将其重命名为 boot.py 。

请注意,重启后会出现这种看上去很恐怖的文字,请放心,这应该是就是这么说!

****************警告******************

将文件系统用作可写缓存!

这是冒险行为,请备份文件!

** **************警告******************

这是 CIRCUITPY 驱动器的最终内容,如下所示:

编码

下载:Project Zip 或 nasa.py | 在Github上查看

复制代码

DATA_SOURCE = “https://api.nasa.gov/planetary/apod?api_key=your_actual_really_long_key_here” import time

import board

from adafruit_pyportal import PyPortal

# Set up where we‘ll be fetching data from

DATA_SOURCE = “https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY”

# There’s a few different places we look for data in the photo of the day

IMAGE_LOCATION = [“url”]

TITLE_LOCATION = [“title”]

DATE_LOCATION = [“date”]

# the current working directory (where this file is)

cwd = (“/”+__file__).rsplit(‘/’, 1)[0]

pyportal = PyPortal(url=DATA_SOURCE,

json_path=(TITLE_LOCATION, DATE_LOCATION),

status_neopixel=board.NEOPIXEL,

default_bg=cwd+“/nasa_background.bmp”,

text_font=cwd+“/fonts/Arial-12.bdf”,

text_position=((5, 220), (5, 200)),

text_color=(0xFFFFFF, 0xFFFFFF),

text_maxlen=(50, 50), # cut off characters

image_json_path=IMAGE_LOCATION,

image_resize=(320, 240),

image_position=(0, 0))

while True:

response = None

try:

response = pyportal.fetch()

print(“Response is”, response)

except RuntimeError as e:

print(“Some error occured, retrying! -”, e)

time.sleep(30*60) # 30 minutes till next check

如果遇到任何错误,例如“ ImportError:没有名为` adafruit_display_text.label`”,请务必将您的库更新到最新ST发布包!

工作原理

NASA Image Viewer正在使用CircuitPython和PyPortal做一些很酷的事情:

背景闪屏

首先,我们将显示带有NASA徽标的初始屏幕。这是 .bmp 格式的320x240像素RGB 16位光栅图形。

编码

字体

我们将图像标题和今天的日期显示为使用位图字体创建的文本加载后叠加在背景图片上。这里使用的字体是由斜Arial字体制成的位图字体。您可以在本指南中了解有关转换类型的更多信息。

JSON

为了检索当天的NASA天文学图片(APOD),我们

向NASA API进行查询。

在添加了API密钥的APOD服务器请求中,您将获得一个JSON文件作为响应。

实际上,您可以运行与PyPortal相同的查询来查看结果。将此链接import time

import board

from adafruit_pyportal import PyPortal

# Set up where we‘ll be fetching data from

DATA_SOURCE = “https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY”

# There’s a few different places we look for data in the photo of the day

IMAGE_LOCATION = [“url”]

TITLE_LOCATION = [“title”]

DATE_LOCATION = [“date”]

# the current working directory (where this file is)

cwd = (“/”+__file__).rsplit(‘/’, 1)[0]

pyportal = PyPortal(url=DATA_SOURCE,

json_path=(TITLE_LOCATION, DATE_LOCATION),

status_neopixel=board.NEOPIXEL,

default_bg=cwd+“/nasa_background.bmp”,

text_font=cwd+“/fonts/Arial-12.bdf”,

text_position=((5, 220), (5, 200)),

text_color=(0xFFFFFF, 0xFFFFFF),

text_maxlen=(50, 50), # cut off characters

image_json_path=IMAGE_LOCATION,

image_resize=(320, 240),

image_position=(0, 0))

while True:

response = None

try:

response = pyportal.fetch()

print(“Response is”, response)

except RuntimeError as e:

print(“Some error occured, retrying! -”, e)

time.sleep(30*60) # 30 minutes till next check

复制并粘贴到您的浏览器中,除了将DEMO_KEY替换为NASA在注册电子邮件中发送的自己的API密钥。

当您在在网络浏览器中,您将看到如下返回结果:

下载:文件

复制代码

https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY {

“copyright”: “Mario Zauner”,

“date”: “2019-04-03”,

“explanation”: “The famous Horsehead Nebula in Orion is not alone. A deep exposure shows that the dark familiar shaped indentation, visible just below center, is part of a vast complex of absorbing dust and glowing gas. To bring out details of the Horsehead‘s pasture, an amateur astronomer used a backyard telescope in Austria to accumulate and artistically combine 7.5 hours of images in the light of Hydrogen (red), Oxygen (green), and Sulfur (blue)。 The resulting spectacular picture details an intricate tapestry of gaseous wisps and dust-laden filaments that were created and sculpted over eons by stellar winds and ancient supernovas. The Flame Nebula is visible just to the left of the Horsehead, while the bright star on the upper left is Alnilam, the central star in Orion’s Belt. The Horsehead Nebula lies 1,500 light years distant towards the constellation of Orion. Bounce around the Universe: Random APOD Generator”,

“hdurl”: “https://apod.nasa.gov/apod/image/1904/HorseheadFlame_Zauner_4404.jpg”,

“media_type”: “image”,

“service_version”: “v1”,

“title”: “Wisps Surrounding the Horsehead Nebula”,

“url”: “https://apod.nasa.gov/apod/image/1904/HorseheadFlame_Zauner_960.jpg”

}

该结果是一个JSON(JavaScript对象表示法)数组。它由具有七个 key:value 对的单个元素组成。例如,有一个名为{

“copyright”: “Mario Zauner”,

“date”: “2019-04-03”,

“explanation”: “The famous Horsehead Nebula in Orion is not alone. A deep exposure shows that the dark familiar shaped indentation, visible just below center, is part of a vast complex of absorbing dust and glowing gas. To bring out details of the Horsehead‘s pasture, an amateur astronomer used a backyard telescope in Austria to accumulate and artistically combine 7.5 hours of images in the light of Hydrogen (red), Oxygen (green), and Sulfur (blue)。 The resulting spectacular picture details an intricate tapestry of gaseous wisps and dust-laden filaments that were created and sculpted over eons by stellar winds and ancient supernovas. The Flame Nebula is visible just to the left of the Horsehead, while the bright star on the upper left is Alnilam, the central star in Orion’s Belt. The Horsehead Nebula lies 1,500 light years distant towards the constellation of Orion. Bounce around the Universe: Random APOD Generator”,

“hdurl”: “https://apod.nasa.gov/apod/image/1904/HorseheadFlame_Zauner_4404.jpg”,

“media_type”: “image”,

“service_version”: “v1”,

“title”: “Wisps Surrounding the Horsehead Nebula”,

“url”: “https://apod.nasa.gov/apod/image/1904/HorseheadFlame_Zauner_960.jpg”

}的键,它的值为date,表示方式如下:

2019-04-03

我们关心的另一个是“date”: “2019-04-03” 键,其值为title

表示为:

Wisps Surrounding the Horsehead Nebula

我们真正关心的另一个键是“title”: “Wisps Surrounding the Horsehead Nebula”具有图像位置的值:

url

由于此JSON对象数组具有一致的返回结果的方式对我们来说,我们在PyPortal上运行的代码可以轻松解析数据并将其显示!

这是Firefox的“代码美化器”中JSON文件的外观。

编码

您可以在 code.py 的此部分中了解其操作方式:

下载:文件

复制代码

“url”: “https://apod.nasa.gov/apod/image/1904/HorseheadFlame_Zauner_960.jpg” DATA_SOURCE = “https://api.nasa.gov/planetary/apod?api_key=xxxxxxx” #put your api key here

IMAGE_LOCATION = [“url”]

TITLE_LOCATION = [“title”]

DATE_LOCATION = [“date”]

然后,在DATA_SOURCE = “https://api.nasa.gov/planetary/apod?api_key=xxxxxxx” #put your api key here

IMAGE_LOCATION = [“url”]

TITLE_LOCATION = [“title”]

DATE_LOCATION = [“date”]查询,我们要求从该URL中获取日期和 title 名称,然后使用pyportal参数设置text_ ,font,position,color和wrap文本显示时。

我们使用 url 名称以获取.jpeg图像文件的路径。

下载:文件

复制代码

maxlen pyportal = PyPortal(url=DATA_SOURCE,

json_path=(TITLE_LOCATION, DATE_LOCATION),

status_neopixel=board.NEOPIXEL,

default_bg=cwd+“/nasa_background.bmp”,

text_font=cwd+“/fonts/Arial-12.bdf”,

text_position=((5, 220), (5, 200)),

text_color=(0xFFFFFF, 0xFFFFFF),

text_maxlen=(50, 50), # cut off characters

image_json_path=IMAGE_LOCATION,

image_resize=(320, 240),

image_position=(0, 0))

所有这些都准备好了,在pyportal = PyPortal(url=DATA_SOURCE,

json_path=(TITLE_LOCATION, DATE_LOCATION),

status_neopixel=board.NEOPIXEL,

default_bg=cwd+“/nasa_background.bmp”,

text_font=cwd+“/fonts/Arial-12.bdf”,

text_position=((5, 220), (5, 200)),

text_color=(0xFFFFFF, 0xFFFFFF),

text_maxlen=(50, 50), # cut off characters

image_json_path=IMAGE_LOCATION,

image_resize=(320, 240),

image_position=(0, 0))的主循环中,代码将查询

当获取.jpeg文件的路径时,pyportal库将其传递到Adafruit IO图像转换器服务器,在该服务器中文件被转换为PyPortal可以使用的格式显示屏,一个320x240像素RGB 16位.bmp。

编码

原始jpeg

编码

转换并调整大小的bmp

此图像然后将e缓存到PyPortal的存储中并显示在PyPortal TFT屏幕上。

最后,文本将显示在图像上。

此更新每三十分钟。请注意,您每天对NASA API的查询不能超过50个!

编码

责任编辑:wv

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分