1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| #include "esp8266.h"
#include <stdio.h> #include <string.h>
#define WIFI_SSID "Xiaomi" #define WIFI_Password "913752468"
#define CLIENT_ID "01" #define USERNAME "dVb8DLDvZW" #define PASSWORD "version=2018-10-31&res=products%2FdVb8DLDvZW%2Fdevices%2F01&et=1937255523&method=md5&sign=2fQX%2B229WO0dERtjRnWuiQ%3D%3D" #define IP "mqtts.heclouds.com"
#define SUB_Topic "$sys/dVb8DLDvZW/01/thing/property/post/reply" #define PUB_Topic "$sys/dVb8DLDvZW/01/thing/property/post"
uint8_t esp_buf[MAX_SIZE];
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) { if(huart == &huart4) { HAL_UARTEx_ReceiveToIdle_DMA(&hespuart, esp_buf, MAX_SIZE); __HAL_DMA_DISABLE_IT(&hdma_esp_rx, DMA_IT_HT); } }
void ESP8266_Init(void) { HAL_UARTEx_ReceiveToIdle_DMA(&hespuart, esp_buf, MAX_SIZE); __HAL_DMA_DISABLE_IT(&hdma_esp_rx, DMA_IT_HT); Msg_Clear(); while(SendCmd((uint8_t *)"ATE0\r\n",(uint8_t *)"OK")){} while(SendCmd((uint8_t *)"AT+CWJAP=\""WIFI_SSID"\",\""WIFI_Password"\"\r\n",(uint8_t *)"WIFI GOT IP")){} printf("WIFI连接成功\n"); while(SendCmd((uint8_t *)"AT+MQTTUSERCFG=0,1,\""CLIENT_ID"\",\""USERNAME"\",\""PASSWORD"\",0,0,\"\"\r\n",(uint8_t *)"OK")){} while(SendCmd((uint8_t *)"AT+MQTTCONN=0,\""IP"\",1883,1\r\n",(uint8_t *)"MQTTCONNECTED")){} printf("MQTT连接成功\n"); while(SendCmd((uint8_t *)"AT+MQTTSUB=0,\""SUB_Topic"\",0\r\n",(uint8_t *)"OK")){} }
void sendData(char *attribute, float data) { uint8_t msg_buf[512]; memset(msg_buf,0,sizeof(msg_buf)); sprintf((char *)msg_buf,"AT+MQTTPUB=0,\""PUB_Topic"\",\"{\\\"id\\\":\\\"123\\\"\\,\\\"params\\\":{\\\"%s\\\":{\\\"value\\\":%.f\\}}}\",0,0\r\n", attribute ,data); while(SendCmd(msg_buf,(uint8_t*)"OK")); }
void Msg_Clear() { memset(esp_buf,0,sizeof(esp_buf)); }
void SendString(uint8_t *str,uint8_t len) { for (int i = 0; i < len; i++) { while ((ESP_UART->SR & 0X40) == 0); ESP_UART->DR = (uint8_t)str[i]; } }
uint8_t SendCmd(uint8_t *cmd,uint8_t *res) { uint8_t num = 255; Msg_Clear(); SendString(cmd,strlen((const char *)cmd)); while(num--) { if(strstr((char*)esp_buf,(char *)res)) { Msg_Clear(); return 0; } HAL_Delay(10); } return 1; }
|