当前位置:网站首页>Esp8266 connects to onenet cloud platform (mqtt) through Arduino IDE
Esp8266 connects to onenet cloud platform (mqtt) through Arduino IDE
2022-07-06 12:05:00 【A geek is as deep as the sea】
const char *Device_ID = "876783185"; // equipment ID
const char *Product_ID = "485561"; // product ID
const char *Api_KEY = "123456"; // Authentication information
const char *WiFi_SSID = "zongshutao"; //WiFi name
const char *WiFi_Password = "18853783842"; //WiFi password
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>
SoftwareSerial GpsSerial(D7, D8); //rx,tx
struct
{
char GPS_Buffer[80];
bool isGetData; // Whether or not to get GPS data
bool isParseData; // Whether the parsing is complete
char UTCTime[11]; //UTC Time
char latitude[11]; // latitude
char N_S[2]; //N/S
char longitude[12]; // longitude
char E_W[2]; //E/W
bool isUsefull; // Whether the location information is valid
String lat = ""; // latitude
String lon = ""; // longitude
} Save_Data;
const unsigned int gpsRxBufferLength = 600;
char gpsRxBuffer[gpsRxBufferLength];
unsigned int ii = 0;
int L = D4; //LED Indicator pin
float Current = 0;
uint8_t Upload_Package[200];
uint32_t Last_Updata_Time = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void WiFi_Init(void); //wifi Connect
void MQTT_Init(void); //MQTT initialization
void MQTT_Reconnection(void); //MQTT Reconnection function
void MQTT_Callback(char *MQTT_Topic, uint8_t *MQTT_Payload, uint16_t MQTT_Payload_Len); //MQTT Callback function
void setup()
{
Serial.begin(9600);
WiFi_Init(); //wifi Connect
MQTT_Init(); //MQTT initialization
GpsSerial.begin(9600); // Define baud rate 9600, And our shop GPS The baud rate output by the module is consistent
Serial.begin(9600);
Serial.println("Wating...");
Save_Data.isGetData = false;
Save_Data.isParseData = false;
Save_Data.isUsefull = false;
}
void loop()
{
gpsRead(); // obtain GPS data
parseGpsBuffer();// analysis GPS data
//printGpsBuffer();// Output the parsed data
if (!client.connected()) // If you disconnect from the server , Start up QMTT Reconnect the
MQTT_Reconnection();
if (millis() - Last_Updata_Time >= 3000) // Every time 3 One second scan
{
Last_Updata_Time = millis();
float ADC_Value = random(1000); ;
Current = (ADC_Value) * 0.033783784; // Store the calculated floating-point value
Serial.print("Current: "); // Print the calculated floating-point value
Serial.print(Current);
Serial.println(" A\r\n");
memset(Upload_Package, 0, 200); // Copy characters 0 To parameter Upload_Package The front of the string to which it refers 100 Characters . The purpose is to empty Upload_Package Array
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 Connecting to ");
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 Connected WiFi.\r\n IP Address :");
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 Reconnection .");
if (client.connect(Device_ID, Product_ID, Api_KEY))
Serial.println("MQTT Connected ");
else
{
Serial.print(" The connection fails , The error code is =");
Serial.print(client.state());
Serial.println(", Please be there. 5 Try again in seconds .");
delay(5000);
}
}
}
void errorLog(int num)
{
Serial.print(" error ");
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 Data doesn't work !");
}
}
}
void parseGpsBuffer() {
// analysis GPS data
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); // Parse error
}
else
{
subString++;
if ((subStringNext = strstr(subString, ",")) != NULL)
{
char usefullBuffer[2];
switch (i)
{
case 1: memcpy(Save_Data.UTCTime, subString, subStringNext - subString); break; // obtain UTC Time
case 2: memcpy(usefullBuffer, subString, subStringNext - subString); break; // obtain UTC Time
case 3: memcpy(Save_Data.latitude, subString, subStringNext - subString); break; // Get latitude information
case 4: memcpy(Save_Data.N_S, subString, subStringNext - subString); break; // obtain N/S
case 5: memcpy(Save_Data.longitude, subString, subStringNext - subString); break; // Get latitude information
case 6: memcpy(Save_Data.E_W, subString, subStringNext - subString); break; // obtain 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); // Parse error
}
}
}
}
}
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); // Empty
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;
}
}
}
边栏推荐
猜你喜欢
Basic knowledge of lithium battery
Mysql database interview questions
mysql实现读写分离
Pytorch four commonly used optimizer tests
Fashion Gen: the general fashion dataset and challenge paper interpretation & dataset introduction
Togglebutton realizes the effect of switching lights
open-mmlab labelImg mmdetection
Kconfig Kbuild
小天才电话手表 Z3工作原理
Detailed explanation of Union [C language]
随机推荐
Oppo vooc fast charging circuit and protocol
E-commerce data analysis -- User Behavior Analysis
数据分析之缺失值填充(重点讲解多重插值法Miceforest)
arduino JSON数据信息解析
Machine learning -- decision tree (sklearn)
A possible cause and solution of "stuck" main thread of RT thread
使用LinkedHashMap实现一个LRU算法的缓存
互聯網協議詳解
ToggleButton实现一个开关灯的效果
Several declarations about pointers [C language]
Reading notes of difficult career creation
Reno7 60W超级闪充充电架构
Cannot change version of project facet Dynamic Web Module to 2.3.
Feature of sklearn_ extraction. text. CountVectorizer / TfidVectorizer
Matlab learning and actual combat notes
Kaggle竞赛-Two Sigma Connect: Rental Listing Inquiries
Mysql database interview questions
Understanding of AMBA, AHB, APB and Axi
map文件粗略分析
机器学习--线性回归(sklearn)