#include "wifi_info.h"
#include <esp_sntp.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
/**
* Task: monitor the WiFi connection and keep it alive!
*
* When a WiFi connection is established, this task will check it every 10 seconds
* to make sure it's still alive.
*
* If not, a reconnect is attempted. If this fails to finish within the timeout,
* the ESP32 will wait for it to recover and try again.
*/
// 联网成功后自动校时
WiFiUDP ntpUDP; //创建UDP实例
NTPClient timeClient(ntpUDP, "asia.pool.ntp.org", 60 * 60 * 8, 60000); // NTC
void init_wifi_ntp(void)
{
auto cfg = M5.config();
cfg.external_rtc = true; // default=false. use Unit RTC.
M5.begin(cfg);
if (!M5.Rtc.isEnabled()) //开启RTC芯片,BM8563
{
Serial.println("RTC not found.");
for (;;)
{
vTaskDelay(500);
}
}
Serial.println("RTC found.");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); //连接wifi
// uint8_t times=0;
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('*');
delay(1200);
// times++;
// if(times>10) break;
}
Serial.println("\r\n WiFi Connected.");
if (timeClient.update()) //网络校时成功,就更新 RTC芯片时间
{
Serial.print("ntp time: ");
// Serial.println(timeClient.getFormattedTime());
// configTzTime(NTP_TIMEZONE, NTP1, NTP2, NTP3);
unsigned long epochTime = timeClient.getEpochTime();
// time_t t = time(nullptr); // Advance one second.
// Serial.print(asctime(gmtime((time_t *)&epochTime))); //默认打印格式:Mon Oct 25 11:13:29 2021
M5.Rtc.setDateTime(gmtime((time_t *)&epochTime));
}
delay(500);
auto dt = M5.Rtc.getDateTime();
static constexpr const char *const wd[7] = {"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"};
Serial.printf("RTC UTC :%04d/%02d/%02d (%s) %02d:%02d:%02d\r\n", dt.date.year, dt.date.month, dt.date.date, wd[dt.date.weekDay], dt.time.hours, dt.time.minutes, dt.time.seconds);
}
#include "weather.h"
#include <HTTPClient.h>
#include "lcd_lvgl.h"
/*
{"cityid":"101281601","date":"2023-11-29","week":"星期三","update_time":"08:04","city":"东莞","cityEn":"dongguan","country":"中国","countryEn":"China","wea":"阴","wea_img":"yin","tem":"19.6","tem1":"23",
"tem2":"19","win":"北风","win_speed":"1级","win_meter":"3km\/h","humidity":"76%","visibility":"22km","pressure":"1012","air":"61","air_pm25":"42","air_level":"良","air_tips":"各类人群可多参加户外活动,多呼吸一下清新的空气。",
"alarm":{"alarm_type":"","alarm_level":"","alarm_title":"","alarm_content":""},"rain_pcpn":"0","uvIndex":"4","uvDescription":"中等","wea_day":"阴","wea_day_img":"yin","wea_night":"阴",
"wea_night_img":"yin","sunrise":"06:46","sunset":"17:38","aqi":{"update_time":"06:54","air":"61","air_level":"良","air_tips":"各类人群可多参加户外活动,多呼吸一下清新的空气。",
"pm25":"42","pm25_desc":"良","pm10":"72","pm10_desc":"良","o3":"62","o3_desc":"","no2":"28","no2_desc":"","so2":"8","so2_desc":"","co":"0.9","co_desc":"","kouzhao":"不用佩戴口罩",
"yundong":"适宜运动","waichu":"适宜外出","kaichuang":"适宜开窗","jinghuaqi":"不需要打开"}}
*/
HTTPClient http; // 声明HTTPClient对象
DynamicJsonDocument doc(2048);
struct WeatherInfo weather = {0};
void getWeather()
{
weather = {0};
http.begin(WEATHERURL); // 准备启用连接
int httpCode = http.GET(); // 发起GET请求
if (httpCode > 0) // 如果状态码大于0说明请求过程无异常
{
if (httpCode == HTTP_CODE_OK) // 请求被服务器正常响应,等同于httpCode == 200
{
String payload = http.getString(); // 读取服务器返回的响应正文数据
// 如果正文数据很多该方法会占用很大的内存
// Serial.println(payload);
weather.succ = 1;
deserializeJson(doc, payload);
String temp_str;
temp_str = doc["humidity"].as<String>(); // 湿度
temp_str.replace("%", ""); // 去除尾部的 % 号
weather.humidity = temp_str.toInt();
// Serial.println(wea.humidity);
temp_str = doc["tem"].as<String>(); // 温度
weather.temperature = int(temp_str.toFloat() + 0.5);
temp_str = doc["tem1"].as<String>(); // 最高温度
weather.maxTemp = temp_str.toInt();
temp_str = doc["tem2"].as<String>(); // 最高温度
weather.minTemp = temp_str.toInt();
temp_str = doc["wea"].as<String>(); // 天气
Serial.print(" wea :");
Serial.print(temp_str);
Serial.print(" len= ");
Serial.print(temp_str.length());
strncpy(weather.wea, temp_str.c_str(), temp_str.length());
temp_str = doc["wea_img"].as<String>(); // 天气图标
// Serial.print(" wea img:");
// Serial.print(temp_str);
// Serial.print(" wae_img len ");
// Serial.print(temp_str.length());
memset(weather.wea_img, 0, sizeof(weather.wea_img));
// strncpy(weather.wea_img, temp_str.c_str(), temp_str.length());
sprintf(weather.wea_img, "S:/%s.png", temp_str);
sniprintf(weather.wea_msg, 100, "最低气温%d℃,最高气温%d℃,\n空气质量%s,紫外线指数:%s.", weather.minTemp, weather.maxTemp, doc["air_level"].as<String>(), doc["uvDescription"].as<String>());
// Serial.print("[");
// Serial.print(weather.wea);
// Serial.print("] ");
// Serial.print(weather.air_level);
// Serial.print(" ");
Serial.print(" ");
Serial.print(weather.temperature);
Serial.print(" ");
// Serial.println(weather.maxTemp);
// Serial.println(weather.wea_msg);
Serial.println(payload);
}
}
else
{
weather.succ = 0;
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end(); // 结束当前连接
}
void taskFlushWeather(void *parameter)
{
weather.succ = false;
uint8_t flag = 0;
while (1)
{
// Serial.println("weather process!");
if (WiFi.status() == WL_CONNECTED)
{
if (weather.succ == 0)
getWeather(); //获取天气信息
else if (flag > 60)
{
flag = 0;
getWeather();
}
}
flag++;
vTaskDelay(10 * 1000); //任务延时调度
}
vTaskDelete(NULL); //删除自身函数
}
#include "mqtt.h"
#include <PubSubClient.h>
#include <HTTPClient.h>
#include "lcd_lvgl.h"
const char *MQTT_SERVER = "afgsmmu.iot.gz.baidubce.com";
const int MQTT_PORT = 1883;
const char *MQTT_USRNAME = "thingidp@afgsmmu|AICAM|0|MD5";
const char *MQTT_PASSWD = "6c792ea3b7f084f7a1e30da894898d67";
const char *TOPIC = "$iot/AICAM/user/ismask";
const char *CLIENT_ID = "AICAM"; //当前设备的clientid标志
WiFiClient espClient;
PubSubClient client(espClient);
DynamicJsonDocument mqdoc(1024);
static char msgbuf[1024]; //用来缓冲消息信息
static uint16_t pos;
void callback(char *topic, byte *payload, unsigned int length)
{
char filename[20];
String msg;
// Serial.print("Message arrived [");
// Serial.print(topic); // 打印主题信息
// Serial.print("] ");
// Serial.println();
deserializeJson(mqdoc, payload);
msg = mqdoc["msg"].as<String>();
// Serial.print(msg);
// Serial.print(" ");
// Serial.print(doc["num"].as<int>());
// Serial.print(" = ");
// Serial.println(mqdoc["msg"].as<String>());
if (mqdoc["num"].as<int>() == 1)
{ //收到第一条消息时,初始化内存
memset(msgbuf, 0, 1024);
pos = 0;
}
strcpy(msgbuf + pos, msg.c_str());
pos = msg.length();
if (mqdoc["num"].as<int>() == mqdoc["all"].as<int>())
{ //收到最后一条消息时,需要写文件
sprintf(filename,"S:/%s.txt",mqdoc["topic"].as<String>());
// Serial.print("write_file ");
// Serial.print(filename);
// Serial.print(" [");
// Serial.print(msgbuf);
// Serial.println("]");
saveMsg(filename, msgbuf);
pos=0;
}
// //收到mqtt消息后,保存到SD卡中,保存后 lvgl 进行展示
// sprintf(filename, "S:%s.txt", doc["topic"].as<String>());
// Serial.println(filename);
// saveMsg(filename, doc["msg"].as<String>());
}
void reconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
{
Serial.println("connected");
// 连接成功时订阅主题
client.subscribe(TOPIC);
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
vTaskDelay(5 * 1000);
}
}
}
void taskMqttMsg(void *parameter)
{
while (WiFi.status() != WL_CONNECTED)
{
vTaskDelay(1000);
}
client.setServer(MQTT_SERVER, MQTT_PORT); //设定MQTT服务器与使用的端口,1883是默认的MQTT端口
client.setCallback(callback); //设定回调方式,当ESP8266收到订阅消息时会调用此方法
while (1)
{
if (WiFi.status() == WL_CONNECTED)
{
if (!client.connected())
{
reconnect();
}
client.loop();
}
vTaskDelay(1000); //任务延时调度
}
vTaskDelete(NULL); //删除自身函数
}
void getDistinct(void *parameter)
{
VL53LX_MultiRangingData_t MultiRangingData;
VL53LX_MultiRangingData_t *pMultiRangingData = &MultiRangingData;
uint8_t NewDataReady = 0;
int no_of_object_found = 0, j;
char report[64];
int status;
while (1)
{
status = sensor_vl53lx_sat.VL53LX_GetMultiRangingData(pMultiRangingData);
no_of_object_found = pMultiRangingData->NumberOfObjectsFound;
snprintf(report, sizeof(report), "VL53LX Satellite: Count=%d, #Objs=%1d \n", pMultiRangingData->StreamCount, no_of_object_found);
// Serial.print(report);
if (no_of_object_found == 0)
distinct = 0;
for (j = 0; j < no_of_object_found; j++)
{
// Serial.print(j);
// Serial.print(" status=");
// Serial.print(pMultiRangingData->RangeData[j].RangeStatus);
// Serial.print(", D=");
// Serial.print(pMultiRangingData->RangeData[j].RangeMilliMeter);
// Serial.print("mm");
// Serial.print(", Signal=");
// Serial.print((float)pMultiRangingData->RangeData[j].SignalRateRtnMegaCps / 65536.0);
// Serial.print(" Mcps, Ambient=");
// Serial.print((float)pMultiRangingData->RangeData[j].AmbientRateRtnMegaCps / 65536.0);
// Serial.println(" Mcps");
distinct = pMultiRangingData->RangeData[j].RangeMilliMeter;
}
// Serial.println("");
if (status == 0)
{
status = sensor_vl53lx_sat.VL53LX_ClearInterruptAndStartMeasurement();
}
vTaskDelay(1000); //任务延时调度
}
vTaskDelete(NULL); //删除自身函数
}
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName :MqttMainWin.py
# @time :2023/11/30 17:07
# @author :aramy
import sys
import threading
import json
from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QWidget
from QTUI.mqttsendui import Ui_MqttSend
from unit.mqtt_subprocess import MqttMsg
from unit.stringQB import stringpartQ2B, formatMsg
MSGLENG=30
class MainWidget(QWidget):
def __init__(self, parent=None):
super(MainWidget, self).__init__(parent)
self.ui = Ui_MqttSend()
self.ui.setupUi(self)
# self.ui.pushButtonSend.setEnabled(False)
# 开启接收mqtt的线程
self.mqttMsgThread = MqttMsg()
self.mqttMsgThread.start()
@pyqtSlot () #
def on_pushButtonSend_clicked(self):
sendjson = {}
# print('主线程 按钮按下:', threading.currentThread())
# print(self.ui.textEditMsg.toPlainText())
sendmsg = formatMsg(stringpartQ2B(self.ui.textEditMsg.toPlainText()))
# 给消息添加题头
if self.ui.radioButtonStudy.isChecked():
sendjson['topic'] = "study"
elif self.ui.radioButtonMsg1.isChecked():
sendjson['topic'] = "message1"
elif self.ui.radioButtonMsg2.isChecked():
sendjson['topic'] = "message2"
# 分解消息长度,控制每条数据长度
msglen=len(sendmsg)
sendjson['all'] = int(msglen/MSGLENG)+1
for i in range(0,int(msglen/MSGLENG)+1):
sendjson['num'] = i+1
sendjson['msg'] = sendmsg[i*MSGLENG:(i+1)*MSGLENG]
print(sendjson)
self.mqttMsgThread.lock.acquire()
self.mqttMsgThread.message = json.dumps(sendjson)
self.mqttMsgThread.lock.release()
self.mqttMsgThread.send_message()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
appWindow = MainWidget()
appWindow.show()
sys.exit(app.exec_())
四、源代码