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

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

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

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

Micropython ESP频道

micropython esp32 Walkline Wang 开源得联网代码方便移植


boot.py

"""
The MIT License (MIT)
Copyright © 2020 Walkline Wang (https://walkline.wang)
https://gitee.com/walkline/MicroPython-with-Aligenie-Voice-Skill
"""
import gc
import ntptime
from utime import sleep_ms
from machine import Pin, Timer
from wifihandler import WifiHandler


def hard_reset():
	from machine import reset
	reset()

def blink():
	led = Pin(2, Pin.OUT, value=0)

	for count in range(20):
		led.value(not led.value())
		sleep_ms(200)

def sync_ntp():
	ntptime.NTP_DELTA = 3155644800
	ntptime.host = "ntp1.aliyun.com"
	ntptime.settime()

def connect_to_wifi():
	WifiHandler.set_ap_status(False)
	sleep_ms(1000)

	result_code = WifiHandler.set_sta_mode("NBWIFI", "z7758521")

	return result_code

def check_internet_cb(timer):
	if not WifiHandler.get_sta_status() or not WifiHandler.check_internet_connection():
		print("Wifi disconnected or lost internet connection, restarting now...")

		hard_reset()
	
	gc.collect()


if __name__ == "__main__":
	if WifiHandler.STATION_CONNECTED == connect_to_wifi():
		if WifiHandler.check_internet_connection():
			sync_ntp()
			Pin(2, Pin.OUT, value=1)

			check_internet_timer = Timer(1)
			check_internet_timer.init(
				mode=Timer.PERIODIC,
				period=(Config.MQTT_KEEPALIVE - 5) * 1000,
				callback=check_internet_cb
			)

			print("Timer started, periodic {} seconds".format(Config.MQTT_KEEPALIVE))

			gc.collect()
		else:
			print("Connected to wifi, but no internet connection, restarting now...")

			blink()
			sleep_ms(1000)
			hard_reset()			
	else:
		print("Cannot connect to specified wifi, restarting now...")

		blink()
		sleep_ms(1000)
		hard_reset()

wifihandler.py

"""
The MIT License (MIT)
Copyright © 2020 Walkline Wang (https://walkline.wang)
https://gitee.com/walkline/MicroPython-with-Aligenie-Voice-Skill
"""
import network
import urequests


__station_status_message = {
	network.STAT_IDLE: "network idle",
	# network.STAT_CONNECT_FAIL: "network connect failed",
	network.STAT_CONNECTING: "",
	network.STAT_GOT_IP: "Connected",
	network.STAT_NO_AP_FOUND: "could not found ap",
	network.STAT_WRONG_PASSWORD: "wrong password given",
	network.STAT_BEACON_TIMEOUT: "beacon timeout",
	network.STAT_ASSOC_FAIL: "assoc fail",
	network.STAT_HANDSHAKE_TIMEOUT: "handshake timeout"
}


class WifiHandler(object):
	AP_MODE = 0
	STA_MODE = 1
	STATION_CONNECTED = network.STAT_GOT_IP
	INTERNET_TESTING_URL = "https://gitee.com/walkline/WeatherStation/raw/master/success.html"

	def __init__(self):
		pass

	@staticmethod
	def set_sta_status(active: bool):
		station = network.WLAN(network.STA_IF)
		station.active(active)

	@staticmethod
	def set_ap_status(active: bool):
		access_point = network.WLAN(network.AP_IF)
		access_point.active(active)

	@staticmethod
	def get_sta_status():
		station = network.WLAN(network.STA_IF)

		return station.isconnected()

	@staticmethod
	def set_sta_mode(essid, password, timeout_sec=120):
		from utime import sleep_ms

		station = network.WLAN(network.STA_IF)

		print("\nConnecting to network...")

		if not station.isconnected():
			station.active(True)
			station.connect(essid, password)
			# station.config(dhcp_hostname="esp32")

			retry_count = 0
			while not station.isconnected():
				if timeout_sec > 0:
					if retry_count >= timeout_sec * 2:
						break

				result_code = station.status()

				if result_code == network.STAT_IDLE or\
					result_code == network.STAT_GOT_IP or\
					result_code == network.STAT_NO_AP_FOUND or\
					result_code == network.STAT_WRONG_PASSWORD:
					break
				elif result_code == network.STAT_CONNECTING:
					pass

				retry_count += 1
				sleep_ms(500)

		status_code = station.status()

		print(__station_status_message[status_code])
		print(station.ifconfig())

		return status_code

	@staticmethod
	def check_internet_connection():
		status = False

		try:
			res = urequests.get(WifiHandler.INTERNET_TESTING_URL, timeout=4.0)

			if res:
				if res.text == "Success":
					status = True
		except:
			pass

		return status

	@staticmethod
	def gateway():
		import network

		gateway = None
		station = network.WLAN(network.STA_IF)

		if station.status() == network.STAT_GOT_IP:
			gateway = station.ifconfig()[2]

		return gateway



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

Copyright © 2014 ESP56.com All Rights Reserved

执行时间: 0.010035037994385 seconds