飞道的博客

基于STM32L431设计的云端绿化管理系统(腾讯云平台+ESP8266)

446人阅读  评论(0)

一、环境介绍

MCU: 采用意法半导体低功耗芯片 STM32L431RCT6

编译软件:  Keil5 + CubeMX

云平台: 采用腾讯物联网云平台

工程完整源代码与配套资料下载地址:https://download.csdn.net/download/xiaolong1126626497/19246016

 

二、功能与硬件介绍

2.1 功能介绍

这是采用STM32L431 + ES8266设计的云端绿化管理系统,可以通过ESP8266 WIFI连接腾讯云物联网平台,使用微信小程序远程进行绿化管理,比如:实时获取光照强度、温度、湿度、远程控制水泵进行浇水灌溉,在任何地方都可以给自己种的花花草草浇水,了解周边环境情况。

 腾讯物联网平台支持微信小程序+WIFI一键配网,想学习如何配网的请看这里:https://blog.csdn.net/xiaolong1126626497/article/details/117339434

2.2 硬件介绍

开发板采用的是小熊开发板,包括完成绿化管理系统的所有功能都是采用小熊派开发板的配套套件完成。

小熊开发板板载了一个stlink调试器(就是STM32F103C8T6实现的),程序下载非常方便。串口1用来调试打印数据,ESP8266是接在串口LPUART1上的。

小熊派开发板本身自带的例子程序也比较丰富,自带例子里采用的云平台是华为的物联网云平台,工程比较庞大使用了LiteOS操作系统。本文里的工程是重新编写的代码,使用裸机完成项目功能,没有跑操作系统,MQTT协议和ESP8266驱动代码都是重新编写,框架、逻辑比较清晰,代码量也较少,适合初学者入门学习。

相关传感器模块型号: (采用的是小熊开发板配套的E53_IA1扩展板)

WIFI采用:ESP8266

温湿度检测传感器采用:SHT30

光照强度检测传感器采用:BH1750

电机采用:微型直流电机

三、腾讯物联网云平台

关于腾讯物联网平台的创建已经介绍很多篇了,如果之前没有使用过腾讯物联网云平台,先参考这里学习了解一下:https://blog.csdn.net/xiaolong1126626497/article/details/116902653

下面就截图介绍一下云端绿化管理系统用到的产品功能。

用到的功能属性:

小程序面板配置:

手机微信小程序运行效果:

串口打印的提示:

 

四、STM32源代码

STM32的代码主要分为以下几个部分:

1.  ESP8266底层驱动代码:   完成ESP8266模式配置、数据发送,应答检测等底层网络接口。

2.  MQTT协议代码:这是参考标准MQTT编写C语言版本MQTT协议框架代码,实现了重要的几个接口(主题订阅、主题发布、心跳包、登录MQTT服务器),底层采用ESP8266发送数据。 这个MQTT协议不是使用ESP8266本身的SDK,是根据MQTT协议自己实现的,所以如果使用其他的网卡,移植也很方便,不挑网卡设备。

3.  传感器初始化代码: 完成温湿度传感器、光照强度传感器的驱动代码编写。

4.  LCD屏代码:  LCD是SPI接口的,可以显示温湿度、光照强度数据。

5.  main函数:  完成整个逻辑代码编写,检测微信小程序是否有下发的指令,进行分析,完成水泵的开关控制;当温室和湿度到达某个阀值,自动控制水泵浇水,并上报给微信小程序;主程序里1秒检测一次温湿度、光照强度、电机状态主动上报给微信小程序;在设备端按下按键(模拟现场实体开关)也可以控制水泵浇水或者关闭,这些状态都会实时上报给云平台,微信小程序。

 

程序的模板是使用CubeMX生成的。

4.1  main.c代码:  逻辑代码


  
  1. /**
  2. ******************************************************************************
  3. * @file : main.c
  4. * @brief : Main program body
  5. ******************************************************************************
  6. ** This notice applies to any and all portions of this file
  7. * that are not between comment pairs USER CODE BEGIN and
  8. * USER CODE END. Other portions of this file, whether
  9. * inserted by the user or by software development tools
  10. * are owned by their respective copyright owners.
  11. *
  12. * COPYRIGHT(c) 2019 STMicroelectronics
  13. *
  14. * Redistribution and use in source and binary forms, with or without modification,
  15. * are permitted provided that the following conditions are met:
  16. * 1. Redistributions of source code must retain the above copyright notice,
  17. * this list of conditions and the following disclaimer.
  18. * 2. Redistributions in binary form must reproduce the above copyright notice,
  19. * this list of conditions and the following disclaimer in the documentation
  20. * and/or other materials provided with the distribution.
  21. * 3. Neither the name of STMicroelectronics nor the names of its contributors
  22. * may be used to endorse or promote products derived from this software
  23. * without specific prior written permission.
  24. *
  25. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  26. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  27. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  28. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  29. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  30. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  31. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  33. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35. *
  36. ******************************************************************************
  37. */
  38. /* Includes ------------------------------------------------------------------*/
  39. #include "main.h"
  40. #include "stm32l4xx_hal.h"
  41. #include "i2c.h"
  42. #include "usart.h"
  43. #include "gpio.h"
  44. #include "E53_IA1.h"
  45. #include "lcd.h"
  46. #include "spi.h"
  47. #include "mqtt.h"
  48. #include "esp8266.h"
  49. /* USER CODE BEGIN Includes */
  50. #include "stdio.h"
  51. /* USER CODE END Includes */
  52. void SystemClock_Config(void);
  53. #define ESP8266_WIFI_AP_SSID "CMCC-Cqvn" //将要连接的路由器名称 --不要出现中文、空格等特殊字符
  54. #define ESP8266_AP_PASSWORD "99pu58cb" //将要连接的路由器密码
  55. //腾讯物联网服务器的设备信息
  56. #define MQTT_ClientID "6142CX41XESmartAgriculture"
  57. #define MQTT_UserName "6142CX41XESmartAgriculture;12010126;HUA2G;1624271589"
  58. #define MQTT_PassWord "a8aadebe9721f70e6f9e14fe56ff1d2b5cac9625fa1f96af2f0e0098597fe78b;hmacsha256"
  59. //订阅与发布的主题
  60. #define SET_TOPIC "$thing/down/property/6142CX41XE/SmartAgriculture" //订阅
  61. #define POST_TOPIC "$thing/up/property/6142CX41XE/SmartAgriculture" //发布
  62. //保存温湿度、光照强度
  63. E53_IA1_Data_TypeDef E53_IA1_Data;
  64. //显示文本
  65. char lcd_text_str[ 50];
  66. UART_HandleTypeDef at_usart;
  67. //低功耗串口初始化
  68. int32_t at_usart_init(void)
  69. {
  70. at_usart.Instance = LPUART1;
  71. at_usart.Init.BaudRate = 115200;
  72. at_usart.Init.WordLength = UART_WORDLENGTH_8B;
  73. at_usart.Init.StopBits = UART_STOPBITS_1;
  74. at_usart.Init.Parity = UART_PARITY_NONE;
  75. at_usart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  76. at_usart.Init.Mode = UART_MODE_RX | UART_MODE_TX;
  77. if(HAL_UART_Init(&at_usart) != HAL_OK)
  78. {
  79. _Error_Handler(__FILE__, __LINE__);
  80. }
  81. // __HAL_UART_CLEAR_FLAG(usart, UART_FLAG_TC);
  82. __HAL_UART_ENABLE_IT(&at_usart, UART_IT_IDLE);
  83. __HAL_UART_ENABLE_IT(&at_usart, UART_IT_RXNE);
  84. HAL_NVIC_EnableIRQ(LPUART1_IRQn); //使能USART1中断通道
  85. HAL_NVIC_SetPriority(LPUART1_IRQn, 3, 3); //抢占优先级3,子优先级3
  86. return 0;
  87. }
  88. unsigned char ESP8266_RecvBuf[MAX_RECV_CNT];
  89. unsigned int ESP8266_Recv_cnt= 0;
  90. unsigned int ESP8266_Recv_flag= 0;
  91. void LPUART1_IRQHandler()
  92. {
  93. //接收到数据
  94. if(__HAL_UART_GET_FLAG(&at_usart, UART_FLAG_RXNE) != RESET)
  95. {
  96. if(ESP8266_Recv_cnt<MAX_RECV_CNT -1)
  97. {
  98. ESP8266_RecvBuf[ESP8266_Recv_cnt++] = ( uint8_t)(at_usart.Instance->RDR & 0x00FF);
  99. }
  100. else
  101. {
  102. ESP8266_Recv_flag= 1;
  103. }
  104. }
  105. else if (__HAL_UART_GET_FLAG(&at_usart, UART_FLAG_IDLE) != RESET)
  106. {
  107. __HAL_UART_CLEAR_IDLEFLAG(&at_usart);
  108. ESP8266_Recv_flag= 1;
  109. }
  110. }
  111. void AT_SendData(unsigned char *p,unsigned int len)
  112. {
  113. int i= 0;
  114. for(i= 0;i<len;i++)
  115. {
  116. while((LPUART1->ISR & 0X40) == 0); //循环发送,直到发送完毕
  117. LPUART1->TDR = p[i];
  118. }
  119. }
  120. char mqtt_message[ 200];
  121. int main(void)
  122. {
  123. int i= 0;
  124. int cnt= 0;
  125. int motor_state= 0;
  126. HAL_Init();
  127. SystemClock_Config();
  128. MX_GPIO_Init();
  129. MX_I2C1_Init();
  130. MX_SPI2_Init();
  131. MX_USART1_UART_Init();
  132. at_usart_init();
  133. //初始化硬件 STM32L431RC_BearPiBH1750_I2C1\STM32L431RC_BearPiBH1750_I2C1.axf: Error: L6218E: Undefined symbol printf (referred from main.o).
  134. Init_E53_IA1();
  135. LCD_Init();
  136. LCD_Clear(BLACK); //清屏为黑色
  137. LCD_ShowString( 0, 00, 240, 32, 32, "Init ESP8266"); //显示字符串,字体大小32*32
  138. if(ESP8266_Init())
  139. {
  140. printf( "ESP8266硬件检测错误.\n");
  141. LCD_Clear(BLACK); //清屏为黑色
  142. LCD_ShowString( 0, 00, 240, 32, 32, "ESP8266 ERROR"); //显示字符串,字体大小32*32
  143. }
  144. else
  145. {
  146. LCD_Clear(BLACK); //清屏为黑色
  147. LCD_ShowString( 0, 00, 240, 32, 32, "ESP8266 OK"); //显示字符串,字体大小32*32
  148. printf( "准备连接到指定的服务器.\n");
  149. //非加密端口
  150. printf( "WIFI:%d\r\n",ESP8266_STA_TCP_Client_Mode(ESP8266_WIFI_AP_SSID,ESP8266_AP_PASSWORD, "106.55.124.154", 1883, 1));
  151. }
  152. //2. MQTT协议初始化
  153. MQTT_Init();
  154. //3. 连接腾讯云IOT服务器
  155. while(MQTT_Connect(MQTT_ClientID,MQTT_UserName,MQTT_PassWord))
  156. {
  157. printf( "服务器连接失败,正在重试...\n");
  158. HAL_Delay( 500);
  159. }
  160. printf( "服务器连接成功.\n");
  161. //3. 订阅主题
  162. if(MQTT_SubscribeTopic(SET_TOPIC, 0, 1))
  163. {
  164. printf( "主题订阅失败.\n");
  165. }
  166. else
  167. {
  168. printf( "主题订阅成功.\n");
  169. }
  170. while ( 1)
  171. {
  172. if(HAL_GPIO_ReadPin(KEY1_GPIO_Port,KEY1_Pin)==GPIO_PIN_RESET) //查询按键KEY1低电平
  173. {
  174. HAL_Delay( 10); //消抖
  175. if(HAL_GPIO_ReadPin(KEY1_GPIO_Port,KEY1_Pin)==GPIO_PIN_RESET) //查询按键KEY1低电平
  176. {
  177. HAL_GPIO_WritePin(LED_GPIO_Port,LED_Pin,GPIO_PIN_SET); //亮
  178. //补光灯亮
  179. HAL_GPIO_WritePin(IA1_Light_GPIO_Port, IA1_Light_Pin, GPIO_PIN_SET);
  180. //电机转
  181. HAL_GPIO_WritePin(IA1_Motor_GPIO_Port, IA1_Motor_Pin, GPIO_PIN_SET);
  182. motor_state= 1;
  183. }
  184. }
  185. if(HAL_GPIO_ReadPin(KEY2_GPIO_Port,KEY2_Pin)==GPIO_PIN_RESET) //查询按键KEY2低电平
  186. {
  187. HAL_Delay( 10); //消抖
  188. if(HAL_GPIO_ReadPin(KEY2_GPIO_Port,KEY2_Pin)==GPIO_PIN_RESET) //查询按键KEY2低电平
  189. {
  190. HAL_GPIO_WritePin(LED_GPIO_Port,LED_Pin,GPIO_PIN_RESET); //灭
  191. //补光灯灭
  192. HAL_GPIO_WritePin(IA1_Light_GPIO_Port, IA1_Light_Pin, GPIO_PIN_RESET);
  193. //电机停
  194. HAL_GPIO_WritePin(IA1_Motor_GPIO_Port, IA1_Motor_Pin, GPIO_PIN_RESET);
  195. motor_state= 0;
  196. }
  197. }
  198. cnt++;
  199. HAL_Delay( 10);
  200. if(cnt>= 100)
  201. {
  202. cnt= 0;
  203. E53_IA1_Read_Data();
  204. printf( "光照强度:%d %%\r\n", ( int)E53_IA1_Data.Lux);
  205. printf( "湿度:%d %%\r\n",( int)E53_IA1_Data.Humidity);
  206. printf( "温度:%d ℃\r\n", ( int)E53_IA1_Data.Temperature);
  207. sprintf(lcd_text_str, "L: %d %%",( int)E53_IA1_Data.Lux);
  208. LCD_ShowString( 40, 50+ 10+ 32* 1, 240, 32, 32,lcd_text_str);
  209. sprintf(lcd_text_str, "H: %d %%",( int)E53_IA1_Data.Humidity);
  210. LCD_ShowString( 40, 50+ 10+ 32* 2, 240, 32, 32,lcd_text_str);
  211. sprintf(lcd_text_str, "T: %d C",( int)E53_IA1_Data.Temperature);
  212. LCD_ShowString( 40, 50+ 10+ 32* 3, 240, 32, 32,lcd_text_str);
  213. //切换引脚的状态
  214. HAL_GPIO_TogglePin(LED_GPIO_Port,LED_Pin);
  215. //上传数据
  216. sprintf(mqtt_message, "{\"method\":\"report\",\"clientToken\":\"123\",\"params\":{\"temperature\":%d,\"humidity\":%d,\"machine\":%d,\"illumination\":%d}}",
  217. ( int)E53_IA1_Data.Temperature,( int)E53_IA1_Data.Humidity,motor_state,( int)E53_IA1_Data.Lux);
  218. MQTT_PublishData(POST_TOPIC,mqtt_message, 0);
  219. //根据湿度自动灌溉
  220. if(( int)E53_IA1_Data.Humidity< 50) //小于50自动灌溉
  221. {
  222. printf( "自动灌溉....\n");
  223. motor_state= 1; //电机状态更新
  224. //电机转
  225. HAL_GPIO_WritePin(IA1_Motor_GPIO_Port, IA1_Motor_Pin, GPIO_PIN_SET);
  226. }
  227. }
  228. //接收到数据
  229. if(ESP8266_Recv_flag)
  230. {
  231. //如果是下发了属性,判断是开锁还是关锁
  232. if(ESP8266_Recv_cnt> 5)
  233. {
  234. ESP8266_RecvBuf[ESP8266_Recv_cnt]= '\0';
  235. //使用字符串查找函数
  236. if( strstr(( char*)&ESP8266_RecvBuf[ 5], "\"machine\":1"))
  237. {
  238. motor_state= 1; //电机状态更新
  239. //电机转
  240. HAL_GPIO_WritePin(IA1_Motor_GPIO_Port, IA1_Motor_Pin, GPIO_PIN_SET);
  241. printf( "开启电机...\n");
  242. }
  243. else if( strstr(( char*)&ESP8266_RecvBuf[ 5], "\"machine\":0"))
  244. {
  245. //电机停
  246. HAL_GPIO_WritePin(IA1_Motor_GPIO_Port, IA1_Motor_Pin, GPIO_PIN_RESET);
  247. motor_state= 0;
  248. printf( "关闭电机...\n");
  249. }
  250. for(i= 0;i<ESP8266_Recv_cnt;i++) printf( "%c",ESP8266_RecvBuf[i]);
  251. ESP8266_Recv_cnt= 0;
  252. }
  253. ESP8266_Recv_flag= 0;
  254. }
  255. }
  256. }
  257. void SystemClock_Config(void)
  258. {
  259. RCC_OscInitTypeDef RCC_OscInitStruct;
  260. RCC_ClkInitTypeDef RCC_ClkInitStruct;
  261. RCC_PeriphCLKInitTypeDef PeriphClkInit;
  262. /**Initializes the CPU, AHB and APB busses clocks
  263. */
  264. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_MSI;
  265. RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  266. RCC_OscInitStruct.HSICalibrationValue = 16;
  267. RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  268. RCC_OscInitStruct.MSICalibrationValue = 0;
  269. RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
  270. RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  271. RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
  272. RCC_OscInitStruct.PLL.PLLM = 1;
  273. RCC_OscInitStruct.PLL.PLLN = 40;
  274. RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
  275. RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  276. RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  277. if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  278. {
  279. _Error_Handler(__FILE__, __LINE__);
  280. }
  281. /**Initializes the CPU, AHB and APB busses clocks
  282. */
  283. RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  284. |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  285. RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  286. RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  287. RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  288. RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  289. if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  290. {
  291. _Error_Handler(__FILE__, __LINE__);
  292. }
  293. PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1|RCC_PERIPHCLK_I2C1;
  294. PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;
  295. PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_HSI;
  296. if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  297. {
  298. _Error_Handler(__FILE__, __LINE__);
  299. }
  300. /**Configure the main internal regulator output voltage
  301. */
  302. if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  303. {
  304. _Error_Handler(__FILE__, __LINE__);
  305. }
  306. /**Configure the Systick interrupt time
  307. */
  308. HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/ 1000);
  309. /**Configure the Systick
  310. */
  311. HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
  312. /* SysTick_IRQn interrupt configuration */
  313. HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
  314. }
  315. /* USER CODE BEGIN 4 */
  316. /* USER CODE END 4 */
  317. /**
  318. * @brief This function is executed in case of error occurrence.
  319. * @param file: The file name as string.
  320. * @param line: The line in file as a number.
  321. * @retval None
  322. */
  323. void _Error_Handler( char *file, int line)
  324. {
  325. /* USER CODE BEGIN Error_Handler_Debug */
  326. /* User can add his own implementation to report the HAL error return state */
  327. while( 1)
  328. {
  329. }
  330. /* USER CODE END Error_Handler_Debug */
  331. }
  332. #ifdef USE_FULL_ASSERT
  333. /**
  334. * @brief Reports the name of the source file and the source line number
  335. * where the assert_param error has occurred.
  336. * @param file: pointer to the source file name
  337. * @param line: assert_param error line source number
  338. * @retval None
  339. */
  340. void assert_failed(uint8_t* file, uint32_t line)
  341. {
  342. /* USER CODE BEGIN 6 */
  343. /* User can add his own implementation to report the file name and line number,
  344. tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  345. /* USER CODE END 6 */
  346. }
  347. #endif /* USE_FULL_ASSERT */
  348. /**
  349. * @}
  350. */
  351. /**
  352. * @}
  353. */
  354. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

4.2  mqtt.c : MQTT协议代码


  
  1. #include "mqtt.h"
  2. u8 *mqtt_rxbuf;
  3. u8 *mqtt_txbuf;
  4. u16 mqtt_rxlen;
  5. u16 mqtt_txlen;
  6. u8 _mqtt_txbuf[ 256]; //发送数据缓存区
  7. u8 _mqtt_rxbuf[ 256]; //接收数据缓存区
  8. typedef enum
  9. {
  10. //名字 值 报文流动方向 描述
  11. M_RESERVED1 = 0 , // 禁止 保留
  12. M_CONNECT , // 客户端到服务端 客户端请求连接服务端
  13. M_CONNACK , // 服务端到客户端 连接报文确认
  14. M_PUBLISH , // 两个方向都允许 发布消息
  15. M_PUBACK , // 两个方向都允许 QoS 1消息发布收到确认
  16. M_PUBREC , // 两个方向都允许 发布收到(保证交付第一步)
  17. M_PUBREL , // 两个方向都允许 发布释放(保证交付第二步)
  18. M_PUBCOMP , // 两个方向都允许 QoS 2消息发布完成(保证交互第三步)
  19. M_SUBSCRIBE , // 客户端到服务端 客户端订阅请求
  20. M_SUBACK , // 服务端到客户端 订阅请求报文确认
  21. M_UNSUBSCRIBE , // 客户端到服务端 客户端取消订阅请求
  22. M_UNSUBACK , // 服务端到客户端 取消订阅报文确认
  23. M_PINGREQ , // 客户端到服务端 心跳请求
  24. M_PINGRESP , // 服务端到客户端 心跳响应
  25. M_DISCONNECT , // 客户端到服务端 客户端断开连接
  26. M_RESERVED2 , // 禁止 保留
  27. }_typdef_mqtt_message;
  28. //连接成功服务器回应 20 02 00 00
  29. //客户端主动断开连接 e0 00
  30. const u8 parket_connetAck[] = { 0x20, 0x02, 0x00, 0x00};
  31. const u8 parket_disconnet[] = { 0xe0, 0x00};
  32. const u8 parket_heart[] = { 0xc0, 0x00};
  33. const u8 parket_heart_reply[] = { 0xc0, 0x00};
  34. const u8 parket_subAck[] = { 0x90, 0x03};
  35. void MQTT_Init(void)
  36. {
  37. //缓冲区赋值
  38. mqtt_rxbuf = _mqtt_rxbuf;
  39. mqtt_rxlen = sizeof(_mqtt_rxbuf);
  40. mqtt_txbuf = _mqtt_txbuf;
  41. mqtt_txlen = sizeof(_mqtt_txbuf);
  42. memset(mqtt_rxbuf, 0,mqtt_rxlen);
  43. memset(mqtt_txbuf, 0,mqtt_txlen);
  44. // //无条件先主动断开
  45. // MQTT_Disconnect();
  46. // HAL_Delay(100);
  47. // MQTT_Disconnect();
  48. // HAL_Delay(100);
  49. }
  50. /*
  51. 函数功能: 登录服务器
  52. 函数返回值: 0表示成功 1表示失败
  53. */
  54. u8 MQTT_Connect(char *ClientID,char *Username,char *Password)
  55. {
  56. u8 i,j;
  57. int ClientIDLen = strlen(ClientID);
  58. int UsernameLen = strlen(Username);
  59. int PasswordLen = strlen(Password);
  60. int DataLen;
  61. mqtt_txlen= 0;
  62. //可变报头+Payload 每个字段包含两个字节的长度标识
  63. DataLen = 10 + (ClientIDLen+ 2) + (UsernameLen+ 2) + (PasswordLen+ 2);
  64. //固定报头
  65. //控制报文类型
  66. mqtt_txbuf[mqtt_txlen++] = 0x10; //MQTT Message Type CONNECT
  67. //剩余长度(不包括固定头部)
  68. do
  69. {
  70. u8 encodedByte = DataLen % 128;
  71. DataLen = DataLen / 128;
  72. // if there are more data to encode, set the top bit of this byte
  73. if ( DataLen > 0 )
  74. encodedByte = encodedByte | 128;
  75. mqtt_txbuf[mqtt_txlen++] = encodedByte;
  76. } while ( DataLen > 0 );
  77. //可变报头
  78. //协议名
  79. mqtt_txbuf[mqtt_txlen++] = 0; // Protocol Name Length MSB
  80. mqtt_txbuf[mqtt_txlen++] = 4; // Protocol Name Length LSB
  81. mqtt_txbuf[mqtt_txlen++] = 'M'; // ASCII Code for M
  82. mqtt_txbuf[mqtt_txlen++] = 'Q'; // ASCII Code for Q
  83. mqtt_txbuf[mqtt_txlen++] = 'T'; // ASCII Code for T
  84. mqtt_txbuf[mqtt_txlen++] = 'T'; // ASCII Code for T
  85. //协议级别
  86. mqtt_txbuf[mqtt_txlen++] = 4; // MQTT Protocol version = 4 对于 3.1.1 版协议,协议级别字段的值是 4(0x04)
  87. //连接标志
  88. mqtt_txbuf[mqtt_txlen++] = 0xc2; // conn flags
  89. mqtt_txbuf[mqtt_txlen++] = 0; // Keep-alive Time Length MSB
  90. mqtt_txbuf[mqtt_txlen++] = 100; // Keep-alive Time Length LSB 100S心跳包 保活时间
  91. mqtt_txbuf[mqtt_txlen++] = BYTE1(ClientIDLen); // Client ID length MSB
  92. mqtt_txbuf[mqtt_txlen++] = BYTE0(ClientIDLen); // Client ID length LSB
  93. memcpy(&mqtt_txbuf[mqtt_txlen],ClientID,ClientIDLen);
  94. mqtt_txlen += ClientIDLen;
  95. if(UsernameLen > 0)
  96. {
  97. mqtt_txbuf[mqtt_txlen++] = BYTE1(UsernameLen); //username length MSB
  98. mqtt_txbuf[mqtt_txlen++] = BYTE0(UsernameLen); //username length LSB
  99. memcpy(&mqtt_txbuf[mqtt_txlen],Username,UsernameLen);
  100. mqtt_txlen += UsernameLen;
  101. }
  102. if(PasswordLen > 0)
  103. {
  104. mqtt_txbuf[mqtt_txlen++] = BYTE1(PasswordLen); //password length MSB
  105. mqtt_txbuf[mqtt_txlen++] = BYTE0(PasswordLen); //password length LSB
  106. memcpy(&mqtt_txbuf[mqtt_txlen],Password,PasswordLen);
  107. mqtt_txlen += PasswordLen;
  108. }
  109. memset(mqtt_rxbuf, 0,mqtt_rxlen);
  110. ESP8266_Recv_flag= 0;
  111. ESP8266_Recv_cnt= 0;
  112. MQTT_SendBuf(mqtt_txbuf,mqtt_txlen);
  113. HAL_Delay( 200);
  114. memcpy(( char *)mqtt_rxbuf,ESP8266_RecvBuf,ESP8266_Recv_cnt);
  115. for(i= 0;i<ESP8266_Recv_cnt;i++) printf( "%#x ",ESP8266_RecvBuf[i]);
  116. //CONNECT
  117. if(mqtt_rxbuf[ 0]==parket_connetAck[ 0] && mqtt_rxbuf[ 1]==parket_connetAck[ 1]) //连接成功
  118. {
  119. return 0; //连接成功
  120. }
  121. return 1;
  122. }
  123. /*
  124. 函数功能: MQTT订阅/取消订阅数据打包函数
  125. 函数参数:
  126. topic 主题
  127. qos 消息等级 0:最多分发一次 1: 至少分发一次 2: 仅分发一次
  128. whether 订阅/取消订阅请求包 (1表示订阅,0表示取消订阅)
  129. 返回值: 0表示成功 1表示失败
  130. */
  131. u8 MQTT_SubscribeTopic(char *topic,u8 qos,u8 whether)
  132. {
  133. u8 i,j;
  134. mqtt_txlen= 0;
  135. int topiclen = strlen(topic);
  136. int DataLen = 2 + (topiclen+ 2) + (whether? 1: 0); //可变报头的长度(2字节)加上有效载荷的长度
  137. //固定报头
  138. //控制报文类型
  139. if(whether)mqtt_txbuf[mqtt_txlen++] = 0x82; //消息类型和标志订阅
  140. else mqtt_txbuf[mqtt_txlen++] = 0xA2; //取消订阅
  141. //剩余长度
  142. do
  143. {
  144. u8 encodedByte = DataLen % 128;
  145. DataLen = DataLen / 128;
  146. // if there are more data to encode, set the top bit of this byte
  147. if ( DataLen > 0 )
  148. encodedByte = encodedByte | 128;
  149. mqtt_txbuf[mqtt_txlen++] = encodedByte;
  150. } while ( DataLen > 0 );
  151. //可变报头
  152. mqtt_txbuf[mqtt_txlen++] = 0; //消息标识符 MSB
  153. mqtt_txbuf[mqtt_txlen++] = 0x0A; //消息标识符 LSB
  154. //有效载荷
  155. mqtt_txbuf[mqtt_txlen++] = BYTE1(topiclen); //主题长度 MSB
  156. mqtt_txbuf[mqtt_txlen++] = BYTE0(topiclen); //主题长度 LSB
  157. memcpy(&mqtt_txbuf[mqtt_txlen],topic,topiclen);
  158. mqtt_txlen += topiclen;
  159. if(whether)
  160. {
  161. mqtt_txbuf[mqtt_txlen++] = qos; //QoS级别
  162. }
  163. ESP8266_Recv_flag= 0;
  164. ESP8266_Recv_cnt= 0;
  165. MQTT_SendBuf(mqtt_txbuf,mqtt_txlen);
  166. HAL_Delay( 200);
  167. memcpy(( char *)mqtt_rxbuf,ESP8266_RecvBuf,ESP8266_Recv_cnt);
  168. for(i= 0;i<ESP8266_Recv_cnt;i++) printf( "%#x ",ESP8266_RecvBuf[i]);
  169. if(mqtt_rxbuf[ 0]==parket_subAck[ 0] && mqtt_rxbuf[ 1]==parket_subAck[ 1]) //订阅成功
  170. {
  171. return 0; //订阅成功
  172. }
  173. return 1; //失败
  174. }
  175. //MQTT发布数据打包函数
  176. //topic 主题
  177. //message 消息
  178. //qos 消息等级
  179. u8 MQTT_PublishData(char *topic, char *message, u8 qos)
  180. {
  181. int topicLength = strlen(topic);
  182. int messageLength = strlen(message);
  183. static u16 id= 0;
  184. int DataLen;
  185. mqtt_txlen= 0;
  186. //有效载荷的长度这样计算:用固定报头中的剩余长度字段的值减去可变报头的长度
  187. //QOS为0时没有标识符
  188. //数据长度 主题名 报文标识符 有效载荷
  189. if(qos) DataLen = ( 2+topicLength) + 2 + messageLength;
  190. else DataLen = ( 2+topicLength) + messageLength;
  191. //固定报头
  192. //控制报文类型
  193. mqtt_txbuf[mqtt_txlen++] = 0x30; // MQTT Message Type PUBLISH
  194. //剩余长度
  195. do
  196. {
  197. u8 encodedByte = DataLen % 128;
  198. DataLen = DataLen / 128;
  199. // if there are more data to encode, set the top bit of this byte
  200. if ( DataLen > 0 )
  201. encodedByte = encodedByte | 128;
  202. mqtt_txbuf[mqtt_txlen++] = encodedByte;
  203. } while ( DataLen > 0 );
  204. mqtt_txbuf[mqtt_txlen++] = BYTE1(topicLength); //主题长度MSB
  205. mqtt_txbuf[mqtt_txlen++] = BYTE0(topicLength); //主题长度LSB
  206. memcpy(&mqtt_txbuf[mqtt_txlen],topic,topicLength); //拷贝主题
  207. mqtt_txlen += topicLength;
  208. //报文标识符
  209. if(qos)
  210. {
  211. mqtt_txbuf[mqtt_txlen++] = BYTE1(id);
  212. mqtt_txbuf[mqtt_txlen++] = BYTE0(id);
  213. id++;
  214. }
  215. memcpy(&mqtt_txbuf[mqtt_txlen],message,messageLength);
  216. mqtt_txlen += messageLength;
  217. MQTT_SendBuf(mqtt_txbuf,mqtt_txlen);
  218. return mqtt_txlen;
  219. }
  220. void MQTT_SentHeart(void)
  221. {
  222. MQTT_SendBuf((u8 *)parket_heart, sizeof(parket_heart));
  223. }
  224. void MQTT_Disconnect(void)
  225. {
  226. MQTT_SendBuf((u8 *)parket_disconnet, sizeof(parket_disconnet));
  227. }
  228. void MQTT_SendBuf(u8 *buf,u16 len)
  229. {
  230. AT_SendData(buf,len);
  231. }

 

 


转载:https://blog.csdn.net/xiaolong1126626497/article/details/117407900
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场