sys_mqtt.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. #include "string.h"
  2. #include "stm32f2xx.h"
  3. #include "ucos_ii.h"
  4. #include "hd_eth.h"
  5. #include "lwip/arch.h"
  6. #include "sys_mqtt.h"
  7. #include "transport.h"
  8. #include "MQTTFormat.h"
  9. #include "cJSON.h"
  10. #include "led.h"
  11. #include "MQTTClient.h"
  12. #include "malloc.h"
  13. #include "mmodbus.h"
  14. #include "myFile.h"
  15. #include "gateway_message.h"
  16. #include "task.h"
  17. #include "log.h"
  18. /********************************************************
  19. * @brief 连接到服务器
  20. * @param sock: sock编号
  21. *********************************************************/
  22. int mqtt_userConnect(void)
  23. {
  24. GATEWAY_PARAMS* get;
  25. get = get_gateway_config_params();
  26. char* MQTT_SERVER_ADDR = (char*)get->host;
  27. int MQTT_SERVER_PORT = get->port;
  28. int sock = -1;
  29. //连接到tcp服务器
  30. sock = transport_open(MQTT_SERVER_ADDR, MQTT_SERVER_PORT);
  31. if(sock < 0)
  32. {
  33. MQTT_PRINTF("connect tcp server error \r\n");
  34. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "connect tcp server error");
  35. return -1;
  36. }
  37. MQTT_PRINTF("connect tcp server success \r\n");
  38. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "connect tcp server success");
  39. //连接到mqtt服务器
  40. if(mqtt_connectToMqttServer(sock) <= 0)
  41. {
  42. MQTT_PRINTF("connect mqtt server error \r\n");
  43. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "connect mqtt server error");
  44. return -1;
  45. }
  46. MQTT_PRINTF("connect mqtt server success \r\n");
  47. LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "connect mqtt server success");
  48. return sock;
  49. }
  50. /************************************************************
  51. * @brief 订阅主题
  52. * @param sock: sock编号
  53. * @retval 1: 订阅成功
  54. *************************************************************/
  55. int mqtt_userSubscribeTopic(int sock)
  56. {
  57. GATEWAY_PARAMS* get;
  58. get = get_gateway_config_params();
  59. char* TOPICPC = (char*)get->commandTopic;
  60. return mqtt_subscribeTopic(sock, TOPICPC, 2);
  61. }
  62. /*
  63. *接收mqtt下发消息并存储进一个数据队列
  64. *name MQTT主题相关信息
  65. */
  66. void *json_message[10];
  67. #define QUEUE_SIZE 10 //队列深度
  68. //消息队列指针
  69. OS_EVENT *JsonQ;
  70. void mqtt_outputMsg(MQTTString *name, uint8_t *msgbuf, int msglen, uint16_t id, int qos)
  71. {
  72. int lenght=msglen;
  73. MQTT_PRINTF("receive a msg: id=%d qos=%d topic=%s msg=%s \r\n", id, qos, name->lenstring.data, msgbuf);
  74. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "receive a msg: id=%d qos=%d topic=%s msg=%s \r\n", id, qos, name->lenstring.data, msgbuf);
  75. StringInfo message;
  76. message.p=mymalloc(SRAMEX ,msglen);
  77. memcpy(message.p,msgbuf,msglen);
  78. OSMboxPost(mqtt_recvMseeageMbox,(void*)&message);
  79. }
  80. /************************************************************
  81. * @brief 处理来自平台发布的信息
  82. * @param sock: sock编号
  83. pbuf: 接收的数据
  84. buflen: 数据的长度
  85. * @retval 1: 消息正常处理
  86. * -2: 帧数据包错误
  87. *************************************************************/
  88. int mqtt_recvPublishMessage(int sock, uint8_t *pbuf, int buflen)
  89. {
  90. uint8_t dup, retained;
  91. int qos, payloadlen;
  92. uint16_t packetid;
  93. MQTTString topicName;
  94. uint8_t *payload;
  95. int msg;
  96. if(MQTTDeserialize_publish(&dup, &qos, &retained, &packetid, &topicName, &payload, &payloadlen, pbuf, buflen) == 1)
  97. {
  98. mqtt_outputMsg(&topicName, payload, payloadlen, packetid, qos);
  99. }
  100. else return -2;
  101. if(qos == 1)
  102. {
  103. mqtt_recvPublishQos1_packid = packetid;
  104. msg = MBOX_MQTT_QOS1PUBACK;
  105. OSMboxPost(mqtt_sendMseeageMbox, &msg);
  106. }
  107. if(qos == 2)
  108. {
  109. mqtt_recvPublishQos2_packid = packetid;
  110. msg = MBOX_MQTT_QOS2PUBREC;
  111. OSMboxPost(mqtt_sendMseeageMbox, &msg);
  112. }
  113. return 1;
  114. }
  115. /************************************************************
  116. * @brief 解析所有平台下发的数据包
  117. * @param sock: sock编号
  118. type: 数据帧的类型
  119. pbuf: 数据
  120. buflen: 数据的长度
  121. * @retval 1: 消息正常处理
  122. * -2: 帧数据包错误
  123. *************************************************************/
  124. int mqtt_userReceiveMessage(int sock, int type, uint8_t *pbuf, int len)
  125. {
  126. int rc;
  127. switch(type)
  128. {
  129. case PUBLISH: rc = mqtt_recvPublishMessage(sock, pbuf, len); break; //平台向设备发布消息
  130. case PUBACK: rc = mqtt_publishMessage_qos1_PUBACK(pbuf, len); break; //设备向平台发布 QOS1 确认报文
  131. case PUBREC: rc = mqtt_publishMessage_qos2_PUBREC(pbuf, len); break; //设备向平台发布 QOS2 确认报文
  132. case PUBREL: rc = mqtt_recvPublishMessage_qos2_PUBREL(sock, pbuf, len); break; //平台向设备发布 QOS2 消息释放报文
  133. case PUBCOMP: rc = mqtt_publishMessage_qos2_PUBCOMP(pbuf, len); break; //设备向平台发布 QOS2 消息释放报文的确认报文
  134. case SUBACK: rc = mqtt_subscribeTopic_SUBACK(pbuf, len);break; //设备向平台订阅报文时的响应报文
  135. case UNSUBACK: rc = mqtt_unSubscribeTopic_UNSUBACK(pbuf, len); break; //设备向平台发取消订阅报文时的响应报文
  136. case PINGRESP: rc = mqtt_pingResponse(); break; //心跳响应报文
  137. default: rc = 1; break;
  138. }
  139. return rc;
  140. }
  141. /************************************************************
  142. * @brief 处理发送邮箱 mqtt_recvMbox 中的消息,根据消息的类型,发送对应的数据包
  143. * @param sock: sock编号
  144. boxMsg: 消息内容
  145. * @retval 1: 消息正常处理
  146. * -1: 网络错误
  147. * -2: 组建发送数据时发送错误
  148. *************************************************************/
  149. char pubJsonString[jsonMaxSize];
  150. //char pubJsonStringCopy[jsonMaxSize];
  151. int mqtt_userSendMessage(int sock, int boxMsg)
  152. {
  153. GATEWAY_PARAMS* get;
  154. get = get_gateway_config_params();
  155. char* TOPIC = (char*)get->messageTopic;
  156. int rc = 1;
  157. //用户发送的数据
  158. if((boxMsg & 0xf0000000) == 0x20000000)
  159. {
  160. switch(boxMsg)
  161. {
  162. case MBOX_USER_PUBLISHQOS0: rc = mqtt_publishMessage_qos0(sock, TOPIC, (uint8_t *)pubJsonString, strlen(pubJsonString)); break;
  163. case MBOX_USER_PUBLISHQOS1: rc = mqtt_publishMessage_qos1(sock, TOPIC, (uint8_t *)pubJsonString, strlen(pubJsonString)); break;
  164. case MBOX_USER_PUBLISHQOS2: rc = mqtt_publishMessage_qos2(sock, TOPIC, (uint8_t *)pubJsonString, strlen(pubJsonString)); break;
  165. }
  166. }
  167. //协议站使用的数据
  168. else if((boxMsg & 0xf0000000) == 0x10000000)
  169. {
  170. switch(boxMsg)
  171. {
  172. case MBOX_MQTT_QOS1PUBACK: rc = mqtt_recvPublishMessage_qos1_PUBACK(sock, mqtt_recvPublishQos1_packid); break;
  173. case MBOX_MQTT_QOS2PUBREC: rc = mqtt_recvPublishMessage_qos2_PUBREC(sock, mqtt_recvPublishQos2_packid); break;
  174. case MBOX_MQTT_QOS2PUBCOMP: rc = mqtt_recvPublishMessage_qos2_PUBCOMP(sock, mqtt_recvPublishQos2_packid); break;
  175. }
  176. }
  177. return rc;
  178. }
  179. OS_EVENT *mqtt_sendMseeageMbox; //发送消息邮箱
  180. OS_EVENT *mqtt_recvMseeageMbox; //接收消息邮箱
  181. int mqtt_connectFlag; //成功连接服务器标志
  182. static int mysock; //连接mqtt服务器的sock编号
  183. /************************************************************
  184. * @brief MQTT主线程
  185. * @param arg: 未使用
  186. * @retval
  187. *************************************************************/
  188. void mqtt_userManThread(void *arg)
  189. {
  190. int rc;
  191. uint8_t err;
  192. void *mboxMsg;
  193. MQTT_PRINTF("mqtt mainthread start \r\n");
  194. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "mqtt mainthread start");
  195. __MQTT_START:
  196. //1.建立与服务器的连接
  197. mysock = -1;
  198. mqtt_connectFlag = 0;
  199. while(mysock < 0)
  200. {
  201. mysock = mqtt_userConnect();
  202. OSTimeDly(2000);
  203. }
  204. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "mqtt connect success");
  205. OSMboxAccept(mqtt_sendMseeageMbox); //清空mbox的数据
  206. mqtt_connectFlag = 1;
  207. //2.订阅服务器的主题
  208. rc = mqtt_userSubscribeTopic(mysock);
  209. if(rc <= 0)
  210. {
  211. MQTT_PRINTF("subscribe error \r\n");
  212. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "subscribe error");
  213. if(rc == -1) goto __MQTT_START; //如果网络发生错误,重新建立连接
  214. }
  215. else
  216. {
  217. MQTT_PRINTF("subscribe success \r\n");
  218. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "subscribe success");
  219. }
  220. //3.循环发送数据
  221. while(1)
  222. {
  223. mboxMsg = OSMboxPend(mqtt_sendMseeageMbox, 60000, &err);
  224. if(OS_ERR_NONE == err)
  225. {
  226. //接收到了 网络异常消息
  227. if((*(unsigned int *)mboxMsg) == MBOX_NETWORK_ERROR) goto __MQTT_START;
  228. else
  229. {
  230. if(mqtt_userSendMessage(mysock, *(unsigned int *)mboxMsg) == -1)
  231. goto __MQTT_START;
  232. memset(pubJsonString,0,strlen(pubJsonString));
  233. }
  234. }
  235. else //超时没有发送数据包,发送心跳包
  236. {
  237. rc = mqtt_pingReq(mysock);
  238. if(rc == -1) goto __MQTT_START;
  239. }
  240. OSTimeDly(100);
  241. }
  242. }
  243. /************************************************************
  244. * @brief MQTT接收线程,处理所有平台下发的数据帧, CONNACK除外
  245. * @param arg: 未使用
  246. * @retval
  247. *************************************************************/
  248. void mqtt_userReceiveThread(void *arg)
  249. {
  250. int len;
  251. int packetType;
  252. int msg;
  253. MQTT_PRINTF("mqtt receivethread start \r\n");
  254. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "mqtt receivethread start");
  255. while(1)
  256. {
  257. if(mqtt_connectFlag == 1)
  258. {
  259. len = transport_receive(mysock); //阻塞接收数据
  260. if(len <=0)
  261. {
  262. if(len == EWOULDBLOCK) //接收数据超时,重新接收
  263. {
  264. MQTT_PRINTF("receive data timeout \r\n");
  265. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "receive data timeout");
  266. continue;
  267. }
  268. else //接收数据时,网络发生了异常,给主线程发送消息,重新建立连接
  269. {
  270. MQTT_PRINTF("sock close \r\n");
  271. // LogPrint(LOG_INFO,__FILE__, __FUNCTION__, __LINE__, "sock close");
  272. transport_close(mysock);
  273. mqtt_connectFlag = 0;
  274. msg = MBOX_NETWORK_ERROR;
  275. OSMboxPost(mqtt_sendMseeageMbox, &msg);
  276. }
  277. }
  278. memset(mqtt_recvbuffer, 0, MQTT_RECVBUF_LENTH);
  279. packetType = MQTTPacket_read(mqtt_recvbuffer, len, transport_getdata);
  280. mqtt_userReceiveMessage(mysock, packetType, mqtt_recvbuffer, len);
  281. }
  282. OSTimeDly(100);
  283. }
  284. }
  285. #define APP_TASK_MQTTMAIN_PRIO 6
  286. #define APP_TASK_MQTTMAIN_STK_SIZE 1024
  287. static OS_STK mqttmainTaskStack[APP_TASK_MQTTMAIN_STK_SIZE];
  288. #define APP_TASK_MQTTRECEIVE_PRIO 7
  289. #define APP_TASK_MQTTRECEIVE_STK_SIZE 1024
  290. static OS_STK mqttreceiveTaskStack[APP_TASK_MQTTRECEIVE_STK_SIZE];
  291. /************************************************************
  292. * @brief 创建MQTT发送和接收线程,初始化相关数据
  293. * @param 此函数必须在LWIP协议栈初始完成以后再调用
  294. * @retval
  295. *************************************************************/
  296. void mqtt_threadCreate(void)
  297. {
  298. mqtt_connectFlag = 0;
  299. mqtt_sendMseeageMbox = OSMboxCreate(NULL);
  300. mqtt_recvMseeageMbox = OSMboxCreate(NULL);
  301. JsonQ = OSQCreate(json_message[0], QUEUE_SIZE); //创建json队列
  302. OSTaskCreate(mqtt_userManThread, NULL, &mqttmainTaskStack[APP_TASK_MQTTMAIN_STK_SIZE-1], APP_TASK_MQTTMAIN_PRIO);
  303. OSTaskCreate(mqtt_userReceiveThread, NULL, &mqttreceiveTaskStack[APP_TASK_MQTTRECEIVE_STK_SIZE-1], APP_TASK_MQTTRECEIVE_PRIO);
  304. }