如果您遵循Raspberry Pi基金会提供的代码作为示例(here)来开始使用Pi Pico W上的WLAN和Sockets,那么另一个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脚本,以偶尔发送检索状态和温度变量的请求.用这种方式设置插座可以吗?
我try 使用了requests.get,并将IP作为url,并且我try 过的所有方法都检索到了错误状态代码.我还try 使用Pi Pico W的信息发送quests.post,但也没有给我任何结果.我在下面try 了这个例子,因为它适用于我运行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'))
我try 将quests.get(Url)放入try and except连接错误块中,但在多次try 后仍然失败,并出现相同的错误.我主要只是在想,我try 做的事情是否可能与套接字的类型、配置或其他什么有关.我已经try 了多种 Select ,但似乎无法通过python脚本从IP获取任何东西,但从浏览器获取它没有任何问题.