如果您按照 Raspberry Pi 基金会提供的示例代码(此处) 开始使用 Pi Pico W 上的 WLAN 和套接字,是否有其他 Python 项目可以获取正在更新的信息的方法插座?
代码看起来像这样(基于上面的链接)这将位于 pi pico W 上:
def connect():
#Connect to WLAN
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while wlan.isconnected() == False:
print('Waiting for connection...')
sleep(1)
ip = wlan.ifconfig()[0]
print(f'Connected on {ip}')
return ip
def open_socket(ip):
# Open a socket
address = (ip, 80)
connection = socket.socket()
connection.bind(address)
connection.listen(1)
return connection
def webpage(temperature, state):
#Template HTML
html = f"""
<!DOCTYPE html>
<html>
<form action="./lighton">
<input type="submit" value="Light on" />
</form>
<form action="./lightoff">
<input type="submit" value="Light off" />
</form>
<p>LED is {state}</p>
<p>Temperature is {temperature}</p>
</body>
</html>
"""
return str(html)
def serve(connection):
#Start a web server
state = 'OFF'
pico_led.off()
temperature = 0
while True:
client = connection.accept()[0]
request = client.recv(1024)
request = str(request)
try:
request = request.split()[1]
except IndexError:
pass
if request == '/lighton?':
pico_led.on()
state = 'ON'
elif request =='/lightoff?':
pico_led.off()
state = 'OFF'
temperature = pico_temp_sensor.temp
html = webpage(temperature, state)
client.send(html)
client.close()
try:
ip = connect()
connection = open_socket(ip)
except KeyboardInterrupt:
machine.reset()
此示例用于获取一个网页,我可以使用 pi 的 IP 地址从浏览器导航到该网页,并更改板载 LED 的状态,以及查看 LED 状态和温度。因此,我们假设在这个例子中,我的目标是能够让另一台计算机运行不同的 python 脚本,偶尔发送请求来检索状态和温度变量。以这种方式设置套接字可以吗?
我尝试使用 requests.get 并以 IP 作为 url,并且我尝试过的所有操作都检索到错误的状态代码。我还尝试使用 Pi Pico W 的信息发送 requests.post ,但这也没有给我任何结果。我尝试了下面的这个示例,因为它适用于我运行 websocket 的另一个 Raspberry Pi Zero 项目。
import requests
import json
import time
url = #PICO's IP, I've tried just the address, I've tried http://xxx.xxx.xxx.xxx and all end with the same error.
while True:
state = requests.get(url)
#state = state.json() didn't make a difference either way, requests.get fails.
print(state)
time.sleep(3)
对此的回应是:
requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine('\n'))
我尝试将 requests.get(url) 放入 try and except 连接错误块中,但多次尝试后仍然失败并出现相同的错误。我主要想知道我想要做的事情是否可以通过套接字类型或配置或其他东西实现。我尝试了多种选项,但似乎无法通过 python 脚本从 IP 获取任何内容,但从浏览器获取它没有问题。
您需要在响应 html 中或之前发送标头。
client.send("HTTP/1.0 200 OK\r\n\r\n")
client.send(html)
client.close()