我有此代码,该代码应使用给定的ESSID和密码连接到wifi。这是代码:
def wifi_connect(essid, password):
# Connect to the wifi. Based on the example in the micropython
# documentation.
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network ' + essid + '...')
wlan.connect(essid, password)
# connect() appears to be async - waiting for it to complete
while not wlan.isconnected():
print('waiting for connection...')
print('checking connection...')
print('Wifi connect successful, network config: %s' % repr(wlan.ifconfig()))
else:
# Note that connection info is stored in non-volatile memory. If
# you are connected to the wrong network, do an explicity disconnect()
# and then reconnect.
print('Wifi already connected, network config: %s' % repr(wlan.ifconfig()))
起初,我收到一条错误消息,提示未安装网络。只需使用pip安装网络即可解决此问题。再次运行此命令后,它告诉我网络没有属性WLAN。我该如何解决?我在做什么错了?
答案 0 :(得分:0)
在PC上,不需要像ESPP32中那样连接network.py到Wifi接入点。 您可以通过OS网络连接正常连接。
您唯一需要的库是套接字。这里是获取数据的代码示例!
import socket
def http_get(url, port):
_, _, host, path = url.split('/', 3)
addr = socket.getaddrinfo(host, port)[0][-1]
s = socket.socket()
s.connect(addr)
s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
while True:
data = s.recv(100)
if data:
print(str(data, 'utf8'), end='')
else:
break
s.close()
http_get('http://micropython.org/ks/test.html',80)
http_get('http://towel.blinkenlights.nl/',23)
答案 1 :(得分:-1)
您正在尝试运行为MicroPython language设计的代码,并且该代码在CPython(您将从Python.org下载的Python版本或大多数PC和服务器上安装的Python版本)上无法使用。
MicroPython旨在在可嵌入的专业硬件上运行,并带有自己的库来支持其运行的硬件,其中包括network
module:
要使用此模块,必须安装具有网络功能的MicroPython变体/内部版本。该模块中提供了用于特定硬件的网络驱动程序,用于配置硬件网络接口。
它在顶部的注释中告诉了您:
# [...] Based on the example in the micropython
# documentation.
代码无法在“常规” CPython上运行。您安装了PyPI network
project,这是一个非常不同的模块originally designed to help learn coding for the Raspberry PI。
可以可以工作的项目取决于您的操作系统(OS)。不同的OS使用不同的编程接口来让程序更改网络。大多数工具都具有命令行工具可以让您执行此操作,使用subprocess
module从Python驱动器应该很容易:
netsh
command,运行netsh wlan connect name=...
以连接到网络接口networksetup
command,networksetup -setairportnetwork en1 ...
可将您连接到给定的WIFI网络。