MPY ESP32 BOOT.PY 网络与时间 定期检查

Wifi DTU同时实现ModbusSlaver从机(需指定IP提供服务)和Master主机(顺序读多块仪表),boot.py铺垫网络连接和时间同步。

内网NTP服务器,定时器周期性检查,故障重启单片机,需要记录512KB日志。

# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import webrepl
#webrepl.start()
# This file is executed on every boot (including wake-boot from deepsleep)

import network, time, machine, _thread, ntptime
#from umqtt.simple import MQTTClient
from machine import Timer, RTC

wifiSsid = "WIFI"
wifiPassword = "123456"

class Wlan_handler():
    def __init__(self, wifiSsid, wifiPassword):
        self.wifiSsid = wifiSsid
        self.wifiPassword = wifiPassword
        self.wlan = network.WLAN(network.STA_IF) # 创建WLAN对象 STA模式    

    def wait_for_wifi_connection(self): # 等待Wi-Fi成功连接到路由器
        if not self.wlan.isconnected():
            self.wlan.active(True)      # 激活界面
            self.wlan.scan()            # 扫描接入点
            print("start to connect ", self.wifiSsid)
            self.wlan.connect(self.wifiSsid, self.wifiPassword) # 连接到指定的路由器
        while not self.wlan.isconnected():
            machine.idle()              # save power while waiting
        ifconfig = self.wlan.ifconfig() # 获取接口的IP/netmask/gw/DNS地址
        print('    ESP32 IP           NETMASK         GATEWAY            DNS')
        #print(ifconfig)
        # 获取并打印信号强度
        rssi = self.wlan.status('rssi')
        print('Signal strength:', rssi)
        
        # 设置静态 IP 地址,子网掩码,网关,DNS
        static_ip = '192.168.47.119'
        netmask = '255.255.255.128'
        gateway = '192.168.47.126'
        dns = '8.8.8.8'
        # 应用静态 IP 设置
        self.wlan.ifconfig((static_ip, netmask, gateway, dns))
        print(self.wlan.ifconfig())

class NTP_handler():
    def __init__(self, ntp_ip):
        print(f'NTP SERVER = {ntp_ip} synchronous...')
        self.rtc = RTC()
        try:
            ntptime.NTP_DELTA = 3155644800  # 可选 UTC+8偏移时间s 这个不准,后面用3600*8=28800
            ntptime.host = ntp_ip  # 可选,ntp服务器,默认是"pool.ntp.org" 也可使用阿里时间同步服务器
            ntptime.settime()  # 修改设备时间,到这就已经设置好了
            nowtime = time.localtime(ntptime.time()+28800)
            self.rtc.init(nowtime[:3]+(0,)+nowtime[3:-1])
            #print(time.localtime())
            # RTC格式 年月日 星期 时分秒 次秒
            # LCT格式 年月日 时分秒 星期 天数
            
        except Exception as e:
            print("同步ntp时间错误",repr(e))

    def fmt_ntp(self):
        temp = time.localtime()
        # 星期+本年第几天格式输出(已转换星期为大写数字)
        week_arr = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
        week_text = week_arr[temp[6]]
        weektime_str = "%s 今年第%s天" % (week_text, temp[7])
        print("date_time_week", weektime_str)

    # 小于10的数补零
    def zero_str(self, int_num):
        return int_num if int_num > 9 else "0" + str(int_num)

    def strftime(self):
        temptime = time.localtime()
        logtime='%s/%s/%s %s:%s:%s'%(temptime[0],self.zero_str(temptime[1]),self.zero_str(temptime[2]),self.zero_str(temptime[3]),self.zero_str(temptime[4]),self.zero_str(temptime[5]))
        return logtime

vwlan = Wlan_handler(wifiSsid, wifiPassword)
vwlan.wait_for_wifi_connection()
vntp = NTP_handler('172.16.30.79')

# 启动定时器 周期性检查 时钟和网络 异常重试
def environment_check(timer):
    global vwlan, vntp
    print('\n每分钟例行环境检查')
    try:
        vwlan.wait_for_wifi_connection()
    except Exception as e:
        print("网络连接故障",repr(e))
        print('machine.reset()...')
        machine.reset()
    print(time.localtime(), vntp.strftime(), '\n')
    # machine.reset()

timer = Timer(0)
timer.init(period = 1000*60, mode = Timer.PERIODIC, callback = environment_check)

效果:每分钟例行环境检查(网络与时间)。每3秒抄5块仪表,每块表读运行信息52个寄存器。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值