当前位置:网站首页>ESP8266通过Arduino IDE连接Onenet云平台(MQTT)
ESP8266通过Arduino IDE连接Onenet云平台(MQTT)
2022-07-06 09:16:00 【一入极客深似海】
const char *Device_ID = "876783185"; //设备ID
const char *Product_ID = "485561"; //产品ID
const char *Api_KEY = "123456"; //鉴权信息
const char *WiFi_SSID = "zongshutao"; //WiFi名称
const char *WiFi_Password = "18853783842"; //WiFi密码
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>
SoftwareSerial GpsSerial(D7, D8); //rx,tx
struct
{
char GPS_Buffer[80];
bool isGetData; //是否获取到GPS数据
bool isParseData; //是否解析完成
char UTCTime[11]; //UTC时间
char latitude[11]; //纬度
char N_S[2]; //N/S
char longitude[12]; //经度
char E_W[2]; //E/W
bool isUsefull; //定位信息是否有效
String lat = ""; //纬度
String lon = ""; //经度
} Save_Data;
const unsigned int gpsRxBufferLength = 600;
char gpsRxBuffer[gpsRxBufferLength];
unsigned int ii = 0;
int L = D4; //LED指示灯引脚
float Current = 0;
uint8_t Upload_Package[200];
uint32_t Last_Updata_Time = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void WiFi_Init(void); //wifi连接
void MQTT_Init(void); //MQTT初始化
void MQTT_Reconnection(void); //MQTT重联函数
void MQTT_Callback(char *MQTT_Topic, uint8_t *MQTT_Payload, uint16_t MQTT_Payload_Len); //MQTT回调函数
void setup()
{
Serial.begin(9600);
WiFi_Init(); //wifi连接
MQTT_Init(); //MQTT初始化
GpsSerial.begin(9600); //定义波特率9600,和我们店铺的GPS模块输出的波特率一致
Serial.begin(9600);
Serial.println("Wating...");
Save_Data.isGetData = false;
Save_Data.isParseData = false;
Save_Data.isUsefull = false;
}
void loop()
{
gpsRead(); //获取GPS数据
parseGpsBuffer();//解析GPS数据
//printGpsBuffer();//输出解析后的数据
if (!client.connected()) //如果和服务器断开连接,则启动QMTT重新连接
MQTT_Reconnection();
if (millis() - Last_Updata_Time >= 3000) //每3秒扫描一次
{
Last_Updata_Time = millis();
float ADC_Value = random(1000); ;
Current = (ADC_Value) * 0.033783784; //存储计算后的浮点值
Serial.print("Current: "); //打印计算后的浮点值
Serial.print(Current);
Serial.println(" A\r\n");
memset(Upload_Package, 0, 200); //复制字符0到参数Upload_Package所指向的字符串的前100个字符。目的为清空Upload_Package数组
String Json_Buffer = ",;Current,";
Json_Buffer += String(Current);
Json_Buffer += ";";
Json_Buffer += "GPS,";
Json_Buffer += "112.023456";
Json_Buffer += "b";
Json_Buffer += "36.083456";
Json_Buffer += "c1";
Json_Buffer += ";";
Upload_Package[0] = 5;
Upload_Package[1] = highByte(Json_Buffer.length());
Upload_Package[2] = lowByte(Json_Buffer.length());
for (int i = 0; i < Json_Buffer.length(); i++)
Upload_Package[i + 3] = Json_Buffer.c_str()[i];
client.publish("$dp", Upload_Package, Json_Buffer.length() + 3);
}
client.loop();
}
void WiFi_Init(void)
{
Serial.print("\r\n\r\n正在连接到");
Serial.print(WiFi_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WiFi_SSID, WiFi_Password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.print("\r\n已连接WiFi。\r\n IP地址:");
Serial.println(WiFi.localIP());
}
void MQTT_Init(void)
{
client.setServer("183.230.40.39", 6002);
client.setCallback(MQTT_Callback);
}
void MQTT_Callback(char *MQTT_Topic, uint8_t *MQTT_Payload, uint16_t MQTT_Payload_Len)
{
Serial.printf("Topic: %s[%d]:\r\n", MQTT_Topic, MQTT_Payload_Len);
//Serial.print(MQTT_Payload[i]);
for (uint16_t i = 0; i < MQTT_Payload_Len; i++)
{
//Serial.print(MQTT_Payload[i] < 0x10 ? " 0x0" : " 0x");
Serial.print(MQTT_Payload[i]);
}
Serial.println();
}
void MQTT_Reconnection(void)
{
while (!client.connected())
{
Serial.println("MQTT重联。");
if (client.connect(Device_ID, Product_ID, Api_KEY))
Serial.println("MQTT已连接");
else
{
Serial.print("连接失败,错误代码为=");
Serial.print(client.state());
Serial.println(",请在5秒钟后重试。");
delay(5000);
}
}
}
void errorLog(int num)
{
Serial.print("错误");
Serial.println(num);
while (1)
{
digitalWrite(L, HIGH);
delay(300);
digitalWrite(L, LOW);
delay(300);
}
}
void printGpsBuffer() {
if (Save_Data.isParseData)
{
Save_Data.isParseData = false;
Serial.print("Save_Data.UTCTime = ");
Serial.println(Save_Data.UTCTime);
if (Save_Data.isUsefull)
{
Save_Data.isUsefull = false;
Serial.print("Save_Data.latitude = ");
Serial.println(Save_Data.lat);
Serial.print("Save_Data.N_S = ");
Serial.println(Save_Data.N_S);
Serial.print("Save_Data.longitude = ");
Serial.println(Save_Data.lon);
Serial.print("Save_Data.E_W = ");
Serial.println(Save_Data.E_W);
}
else
{
Serial.println("GPS数据没有用!");
}
}
}
void parseGpsBuffer() {
//解析GPS数据
char *subString;
char *subStringNext;
if (Save_Data.isGetData)
{
Save_Data.isGetData = false;
Serial.println("**************");
Serial.println(Save_Data.GPS_Buffer);
for (int i = 0 ; i <= 6 ; i++)
{
if (i == 0)
{
if ((subString = strstr(Save_Data.GPS_Buffer, ",")) == NULL)
errorLog(1); //解析错误
}
else
{
subString++;
if ((subStringNext = strstr(subString, ",")) != NULL)
{
char usefullBuffer[2];
switch (i)
{
case 1: memcpy(Save_Data.UTCTime, subString, subStringNext - subString); break; //获取UTC时间
case 2: memcpy(usefullBuffer, subString, subStringNext - subString); break; //获取UTC时间
case 3: memcpy(Save_Data.latitude, subString, subStringNext - subString); break; //获取纬度信息
case 4: memcpy(Save_Data.N_S, subString, subStringNext - subString); break; //获取N/S
case 5: memcpy(Save_Data.longitude, subString, subStringNext - subString); break; //获取纬度信息
case 6: memcpy(Save_Data.E_W, subString, subStringNext - subString); break; //获取E/W
default: break;
}
Save_Data.lat = Save_Data.latitude;
Save_Data.lon = Save_Data.longitude;
tempString(Save_Data.lat);
tempString(Save_Data.lon);
subString = subStringNext;
Save_Data.isParseData = true;
if (usefullBuffer[0] == 'A')
Save_Data.isUsefull = true;
else if (usefullBuffer[0] == 'V')
Save_Data.isUsefull = false;
}
else
{
errorLog(2); //解析错误
}
}
}
}
}
void gpsRead() {
while (GpsSerial.available())
{
gpsRxBuffer[ii++] = GpsSerial.read();
if (ii == gpsRxBufferLength)clrGpsRxBuffer();
}
char* GPS_BufferHead;
char* GPS_BufferTail;
if ((GPS_BufferHead = strstr(gpsRxBuffer, "$GPRMC,")) != NULL || (GPS_BufferHead = strstr(gpsRxBuffer, "$GNRMC,")) != NULL )
{
if (((GPS_BufferTail = strstr(GPS_BufferHead, "\r\n")) != NULL) && (GPS_BufferTail > GPS_BufferHead))
{
memcpy(Save_Data.GPS_Buffer, GPS_BufferHead, GPS_BufferTail - GPS_BufferHead);
Save_Data.isGetData = true;
clrGpsRxBuffer();
}
}
}
void clrGpsRxBuffer(void)
{
memset(gpsRxBuffer, 0, gpsRxBufferLength); //清空
ii = 0;
}
void tempString(String &nu) {
for (int i = 0; i < nu.length() - 1; i++) {
if (nu[i] == '.') {
char temp = nu[i - 1];
nu[i - 1] = nu[i];
nu[i] = temp;
temp = nu[i - 2];
nu[i - 2] = nu[i - 1];
nu[i - 1] = temp;
break;
}
}
}
边栏推荐
猜你喜欢
4. Install and deploy spark (spark on Yan mode)
sklearn之feature_extraction.text.CountVectorizer / TfidVectorizer
Composition des mots (sous - total)
【flink】flink学习
Reading BMP file with C language
【yarn】Yarn container 日志清理
[yarn] CDP cluster yarn configuration capacity scheduler batch allocation
Come and walk into the JVM
5G工作原理详解(解释&图解)
[Blue Bridge Cup 2017 preliminary] grid division
随机推荐
[yarn] CDP cluster yarn configuration capacity scheduler batch allocation
Gallery之图片浏览、组件学习
When using lambda to pass parameters in a loop, the parameters are always the same value
小L的试卷
2019腾讯暑期实习生正式笔试
Solution of deleting path variable by mistake
STM32 如何定位导致发生 hard fault 的代码段
Machine learning -- linear regression (sklearn)
【flink】flink学习
TypeScript
2020网鼎杯_朱雀组_Web_nmap
MySQL主从复制的原理以及实现
Linux yum安装MySQL
Come and walk into the JVM
树莓派 轻触开关 按键使用
[Kerberos] deeply understand the Kerberos ticket life cycle
物联网系统框架学习
Composition des mots (sous - total)
[mrctf2020] dolls
MATLAB学习和实战 随手记