Micropython学习交流群 学习QQ群:786510434 提供多种固件下载和学习交流。

Micropython-扇贝物联 QQ群:31324057 扇贝物联是一个让你与智能设备沟通更方便的物联网云平台

Micropython学习交流群 学习QQ群:468985481 学习交流ESP8266、ESP32、ESP8285、wifi模块开发交流、物联网。

Micropython老哥俩的IT农场分享QQ群:929132891 为喜欢科创制作的小白们分享一些自制的计算机软硬件免费公益课程,由两位多年从事IT研发的中年大叔发起。

Micropython ESP频道

micropython esp32 微信小程序、安卓APP一键配网


main.py

from mpycon import mpyconnect
con = mpyconnect()
con.connect()

mpycon.py

# -*- encoding: utf-8 -*-
'''
@File    :   mpyconnect.py
@Time    :   2022/06/07 13:37:30
@Author  :   Wicos 
@Version :   1.0
@Contact :   wicos@wicos.cn
@Blog    :   https://www.wicos.me
'''

# here put the import lib
import network
import time
from machine import Pin
import os
from socket import *
import json


class mpyconnect:

    def __init__(self):
        self.config_path = "mpyconnect/config.json"
        self.led = Pin(12, Pin.OUT)
        self.__config_init__()
        self.config = self.__config_read__()
        print(self.config)
        self.wifi_ssid = self.config["wifi"]["ssid"]
        self.wifi_password = self.config["wifi"]["password"]

    def __config_init__(self):
        if "mpyconnect" not in os.listdir():
            print("config json init")
            os.mkdir("mpyconnect")
            # with open(self.config_path, "w+", encoding='utf-8') as fp:
            #     json.dump(
            #         , fp)
            self.__config_write__({
                "ip": "",
                "firstload": 1,
                "wifi": {
                    "ssid": "",
                    "password": ""
                }
            })

    def __config_read__(self):
        with open(self.config_path, 'rb') as fp:
            config_json = json.load(fp)
        return config_json

    def __config_write__(self, data):
        with open(self.config_path, 'w+', encoding='utf-8') as fp:
            #json.dump(data, fp)
            fp.write(json.dumps(data))

    def ap_create(self, ssid, password):
        ap_if = network.WLAN(network.AP_IF)
        ap_if.active(True)
        #ap_if.ifconfig(("192.168.4.1", "255.255.255.0", "192.168.4.1", "192.168.4.1"))
        #ap_if.config(essid=ssid,authmode=network.AUTH_WPA_WPA2_PSK,password=password)
        ap_if.config(essid=ssid, authmode=network.AUTH_OPEN)


        for i in range(5):
            time.sleep(1)
            print('The AP build......')
        print(ap_if.ifconfig())
        print(
            'The AP was created successfully, and you are now ready to connect.'
        )

    def wifi_connect(self, ssid, password):
        sta_if = network.WLAN(network.STA_IF)
        sta_if.active(True)
        sta_if.connect(ssid, password)
        for i in range(10):
            self.led.value(0)
            time.sleep(0.5)
            self.led.value(1)
            time.sleep(0.5)
            print(i + 1, 'attempt at connection')
        if sta_if.isconnected() == True:
            a = 'WiFi connection successful'
            print(a, sta_if.ifconfig())
            chip_ip = sta_if.ifconfig()[0]
            config_old = self.__config_read__()
            config_old["ip"] = chip_ip
            self.__config_write__(config_old)
            return True
        else:
            print('WiFi connection failed. Please try again')
            return False

    def wifi_disconnect(self):
        sta_if = network.WLAN(network.STA_IF)
        sta_if.active(False)
        return 'WiFi disconnected successfully'

    def udp_server(self):
        rt = '{"connect":"no"}'
        udp_socket = socket(AF_INET, SOCK_DGRAM)
        print('UDP services is ready')  #2、绑定本地相关信息,如果不绑定,则随机分配
        self.led.value(0)
        local_addr = ('', 7788)  #ip地址和端口号,IP不写表示本机任何一个ip
        udp_socket.bind(local_addr)  #3、等待接收对方发送的数据
        recv_data = udp_socket.recvfrom(1024)  #1024表示本次接收的最大字节
        #recv_data存储的是一个元组(发送方ip,Port
        recv_msg = recv_data[0]
        send_addr = recv_data[1]
        #4、显示接收到的数据
        recvMsg = recv_msg.decode("gbk")
        print("%s:%s" % (str(send_addr), recv_msg.decode("gbk")))
        a = json.loads(recvMsg)
        print(a)
        if a['login'] == 'yes':
            if a['ssid'] != '':
                ssid = a['ssid']
                if a['password'] != '':
                    password = a['password']
                    rt = '{"login":1,"ssid":"' + ssid + '","password":"' + password + '"}'
        #udp_socket.close()
        return rt

    def connect(self):
        if self.config["firstload"] == 1:
            self.ap_create("MpyConnect", "12345678")
            while True:
                udp = self.udp_server()
                recv_data = json.loads(udp)
                if recv_data['login'] == 1:
                    print(
                        'UDP connect successfully and the chep is ready to connect wifi.'
                    )
                    self.led.value(0)
                    if recv_data['ssid'] != '':
                        if recv_data['password'] != '':
                            ssid = recv_data['ssid']
                            password = recv_data['password']
                            connect_result = self.wifi_connect(ssid, password)
                            if connect_result:
                                self.config['wifi']['ssid'] = ssid
                                self.config['wifi']['password'] = password
                                self.config['firstload'] = 0
                                self.__config_write__(self.config)
                                self.led.value(1)
                                break
                            else:
                                continue
        else:
            connect_result = self.wifi_connect(self.wifi_ssid, self.wifi_password)
            if connect_result:
              self.led.value(1)

mpyconnect/config.json 首次配网或恢复出厂配置文件

{"ip": "192.168.4.1", "wifi": {"ssid": "", "password": ""}, "firstload": 1}


开发板通电,会建立AP热点,手机wifi连接热点,然后用下面的微信小程序进行配网。


微信小程序:

1657899070637825.jpg

安卓配网APP:链接: https://pan.baidu.com/s/1xenGQdPArvexWITuyh5Dtw?pwd=8ye3


开源地址:https://github.com/Pidbid/Esp8266-Micropython-one-key-connect-wifi


另外推荐一个利用手机热点配网方案:http://www.esp56.com/tool/peiwang/



推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 ESP56.com All Rights Reserved

执行时间: 0.0077459812164307 seconds