问题代码:
>>> %Run -c $EDITOR_CONTENT ip
network config: ('192.168.0.111', '255.255.255.0', '192.168.0.1', '192.168.1.1')
Traceback (most recent call last):
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/449320790186121.png "#left")
File "<stdin>", line 37, in <module>
File "umqtt/simple.py", line 68, in connect
OSError: [Errno 113] ECONNABORTED
>>>
如图所示:
所应用的软件:
防火墙状态:但不确定关着了么
多次尝试:更换代码
具体代码:
方案一:
import time
from machine import Pin # ---- 添加 --------
import network
from umqtt.simple import MQTTClient
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('TP 5555G', '2580.xuan')
i = 1
while not wlan.isconnected():
print("正在链接...{}".format(i))
i += 1
time.sleep(1)
print('network config:', wlan.ifconfig())
def sub_cb(topic, msg): # 回调函数,收到服务器消息后会调用这个函数
print(topic, msg)
# ---- 添加 --------
if topic.decode("utf-8") == "ledctl" and msg.decode("utf-8") == "on":
led_pin.value(1)
elif topic.decode("utf-8") == "ledctl" and msg.decode("utf-8") == "off":
led_pin.value(0)
# ---- 添加 --------
# 1. 联网
do_connect()
# 2. 创建mqt
c = MQTTClient("umqtt_client","192.168.0.103") # 建立一个MQTT客户端
c.set_callback(sub_cb) # 设置回调函数
c.connect() # 建立连接
c.subscribe(b"ledctl") # 监控ledctl这个通道,接收控制命令
# ---- 添加 --------
# 3. 创建LED对应Pin对象
led_pin = Pin(2, Pin.OUT)
# ---- 添加 --------
while True:
c.check_msg()
time.sleep(1)
方案二:
import time
from machine import Pin
import network
from umqttsimple import MQTTClient
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('TP 5555G', '2580.xuan')
i = 1
while not wlan.isconnected():
print("正在链接...{}".format(i))
i += 1
time.sleep(1)
print('network config:', wlan.ifconfig())
def sub_cb(topic, msg):
print(topic, msg)
if topic.decode("utf-8") == "ledctl" and msg.decode("utf-8") == "on":
led_pin.value(1)
elif topic.decode("utf-8") == "ledctl" and msg.decode("utf-8") == "off":
led_pin.value(0)
do_connect()
c = MQTTClient("umqtt_client","192.168.0.103")
c.set_callback(sub_cb)
c.connect()
c.subscribe(b"ledctl")
led_pin = Pin(2, Pin.OUT)
while True:
try:
c.check_msg()
except OSError as e:
print("error:", e)
c.connect()
time.sleep(1)
方案三:
import network
from umqtt.simple import MQTTClient
# 设置WiFi连接信息
ssid = 'TP 5555G'
password = '2580.xuan'
# 设置MQTT连接信息
mqtt_server = '192.168.0.103'
mqtt_port = 1883
mqtt_user = 'admin'
mqtt_password = 'duanwensheng123'
mqtt_topic = 'your_mqtt_topic'
# 连接WiFi
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)
while not sta_if.isconnected():
pass
# 连接MQTT
client = MQTTClient("esp32", mqtt_server, port=mqtt_port, user=mqtt_user, password=mqtt_password)
client.connect()
结果都连不上上面的服务器
以上这个问题怎么解决,怎么连接上