EC800(3300).c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038
  1. //----------------------------说明
  2. // 程序使用hal库,数据传输使用的串口,串口设置为发送+dma,接收+dma+空闲中断的模式
  3. #include "EC800.h"
  4. //-----------------------------变量定义
  5. //---------
  6. ec800Date s_ec800Date = {
  7. .ip = "39.98.37.180",
  8. .port = 32449,
  9. .clientid = "NULL",
  10. .username = "hechun",
  11. .password = "admin123",
  12. // .username = "SZC30010-AE01",
  13. // .password = "qazSZC30010-AE01",
  14. };
  15. messageDate s_messageDate = {0};
  16. // 初始化故障结构体数组
  17. // 注:如果更改数组faults的大小,需要更改函数insertFaultItems中的限制条件大小,但都需要小于32
  18. Fault faults[12] = {
  19. {"0", "Out of fence fault"},
  20. {"1", "485 communication abnormality"},
  21. {"2", "MQTT communication failure"},
  22. {"3", "Gyroscope data anomaly"},
  23. {"4", "Car battery malfunction"},
  24. {"5", "4G module initialization failed"},
  25. {"6", "GPS positioning information lost."},
  26. {"7", "Upgrade failure fault"},
  27. {"8", "Overspeed fault"},
  28. {"9", "subscribe fail"},
  29. {"10", "publish fail"},
  30. {"11", "get location error"},
  31. };
  32. typedef struct{
  33. uint8_t maxSpeed; // 服务器下发的允许最大车速
  34. uint16_t year; // 上传时间 年
  35. uint8_t month; // 上传时间 月
  36. uint8_t day; // 上传时间 日
  37. uint8_t hour; // 上传时间 时
  38. uint8_t minute; // 上传时间 分
  39. uint8_t sec; // 上传时间 秒
  40. }recDate;
  41. recDate s_recDate = {0};
  42. nmea_msg s_nmea_msg = {0};
  43. nmea_utc_time s_nmea_utc_time = {0};
  44. // AT指令响应超时时间定义
  45. #define REC_TIMEOUT (10000) // 1ms
  46. //----------------------------------------------------------------------------------------------
  47. // 第一部分 通信接口处理部分
  48. /**
  49. * @brief 计算字符串的长度
  50. * @param str: 所需计算字符串的指针
  51. * @note
  52. * @retval 无
  53. */
  54. int EC800_calculateStringLength(const char* str) {
  55. int length = 0;
  56. while (str[length] != '\0') {
  57. length++;
  58. }
  59. return length;
  60. }
  61. /**
  62. * @brief 发送指令函数
  63. * @param command: 指令
  64. * @param enterNum: 进入函数次数,只有第一次的时候清除buff
  65. * @note
  66. * @retval 无
  67. */
  68. void EC800M_SendCommand(const char* command)
  69. {
  70. uint32_t stringLen = 0;
  71. // 进入临界区 挂起所有任务
  72. vTaskSuspendAll();
  73. stringLen = EC800_calculateStringLength(command);
  74. // 使用DMA
  75. // //等待发送状态OK
  76. // while(HAL_DMA_GetState(&hdma_usart3_tx) == HAL_DMA_STATE_BUSY) osDelay(1);
  77. // //发送数据
  78. // HAL_UART_Transmit_DMA(&huart3, (uint8_t*)command, stringLen);
  79. // 不使用发送dma
  80. HAL_UART_Transmit(&huart4, (uint8_t*)command, stringLen, 1000);
  81. // 使用中断
  82. // HAL_UART_Transmit_IT(&huart4, (uint8_t*)command, stringLen);
  83. // 退出临界区 恢复任务调度
  84. xTaskResumeAll();
  85. }
  86. /**
  87. * @brief 接收指令回复函数
  88. * @param haystack: 接收的字符串数据
  89. * @param needle: 正确回复的数据
  90. * @note
  91. * @retval 无
  92. */
  93. char* EC800M_RecRespond(char *haystack, const char *needle ){
  94. char* p = NULL;
  95. HAL_UART_Receive_DMA(&huart4, (uint8_t*)g_usart4_rx_buf, USART4_REC_LEN); //设置接收缓冲区
  96. // __HAL_UART_ENABLE_IT(&huart4, UART_IT_IDLE);
  97. while(g_usart4_rx_sta == 0) osDelay(1);
  98. // __HAL_UART_DISABLE_IT(&huart4, UART_IT_IDLE); // 关闭空闲中断
  99. g_usart4_rx_sta= 0;
  100. p = strstr(haystack, needle);
  101. memset(haystack, 0, USART4_REC_LEN); // 清除数据buff
  102. HAL_UART_DMAStop(&huart4);
  103. HAL_UART_Receive_DMA(&huart4, (uint8_t*)g_usart4_rx_buf, USART4_REC_LEN); //设置接收缓冲区
  104. return p;
  105. }
  106. // 自定义的搜索函数
  107. void* search_sequence(const void* haystack, size_t haystack_len, const void* needle, size_t needle_len) {
  108. const unsigned char* h = (const unsigned char*)haystack;
  109. const unsigned char* n = (const unsigned char*)needle;
  110. // 如果needle为空或haystack长度小于needle长度,则直接返回NULL
  111. if (needle_len == 0 || haystack_len < needle_len) {
  112. return NULL;
  113. }
  114. for (size_t i = 0; i <= haystack_len - needle_len; ++i) {
  115. size_t j;
  116. for (j = 0; j < needle_len; ++j) {
  117. if (h[i + j] != n[j]) {
  118. break; // 如果当前字符不匹配,则跳出内层循环
  119. }
  120. }
  121. if (j == needle_len) {
  122. return (void*)(h + i); // 找到匹配的序列,返回其在haystack中的位置
  123. }
  124. }
  125. // 如果遍历了整个haystack都没有找到匹配的序列,则返回NULL
  126. return NULL;
  127. }
  128. // 接收并比较响应字符串
  129. uint8_t Accept_and_Compare_Str(const char* needle){
  130. uint8_t temp = 0;
  131. static uint16_t timeOutCnt = 0; // 超时计数
  132. HAL_UART_Receive_DMA(&huart4, (uint8_t*)g_usart4_rx_buf, USART4_REC_LEN); //设置接收缓冲区
  133. // __HAL_UART_ENABLE_IT(&huart4, UART_IT_IDLE);
  134. while(!temp) {
  135. osDelay(1);
  136. if(search_sequence(g_usart4_rx_buf, USART4_REC_LEN, needle, strlen(needle))){
  137. temp = 1;
  138. }
  139. if(search_sequence(g_usart4_rx_buf, USART4_REC_LEN, "ERROR", strlen("ERROR"))){
  140. temp = 2;
  141. }
  142. if(timeOutCnt < REC_TIMEOUT){
  143. timeOutCnt++;
  144. }else{
  145. timeOutCnt = 0;
  146. temp = 3;
  147. }
  148. }
  149. g_usart4_rx_sta = 0;
  150. HAL_UART_DMAStop(&huart4);
  151. HAL_UART_Receive_DMA(&huart4, (uint8_t*)g_usart4_rx_buf, USART4_REC_LEN); //设置接收缓冲区
  152. // __HAL_UART_DISABLE_IT(&huart4, UART_IT_IDLE); // 关闭空闲中断
  153. return temp;
  154. }
  155. /**
  156. * @brief 接收使能函数
  157. * @note
  158. * @retval 无
  159. */
  160. void EC800_recEnable(void){
  161. HAL_UART_Receive_DMA(&huart4, (uint8_t*)g_usart4_rx_buf, USART4_REC_LEN); //设置接收缓冲区
  162. __HAL_UART_ENABLE_IT(&huart4, UART_IT_IDLE);
  163. while(g_usart4_rx_sta == 0) osDelay(1);
  164. }
  165. //----------------------------------------------------------------------------------------------
  166. // 第二部分 应用部分的内部函数
  167. /**
  168. * @brief 提取检查信号响应字符串字段中的信号量并进行信号判断
  169. * @param data: 响应的信号量指针
  170. * @note
  171. * @retval 无
  172. */
  173. static uint8_t EC800_extractSignal(char *data){
  174. char *token;
  175. int field_1;
  176. // 使用strtok函数提取字段
  177. token = strtok(data, ":,");
  178. while (token != NULL) {
  179. field_1 = atoi(token); // 转换为整数类型
  180. token = strtok(NULL, ":,");
  181. memset(data, 0, USART4_REC_LEN); // 清除数据buff
  182. g_usart4_rx_sta = 0; // 清除接收状态
  183. if (field_1 < 31) {
  184. return 1;
  185. } else {
  186. return 0;
  187. }
  188. }
  189. return 0;
  190. }
  191. /**
  192. * @brief 检查模块信号
  193. * @param data: 响应的信号量指针
  194. * @note
  195. * @retval 无
  196. */
  197. void ModuleSigCheck(char *data){
  198. EC800M_SendCommand(AT_CMD_CSQ);
  199. int i = 8; // 从第7个字符开始(跳过 "+CSQ: ")
  200. if(Accept_and_Compare_Str(AT_RESP_OK) == 1){
  201. s_global_par.moduleSig = 0;
  202. // 遍历字符串,直到遇到非数字字符
  203. while (data[i] != '\0' && isdigit(data[i])) {
  204. s_global_par.moduleSig = s_global_par.moduleSig * 10 + (data[i] - '0');
  205. i++;
  206. }
  207. }
  208. memset(data, 0, USART4_REC_LEN); // 清除数据buff
  209. g_usart4_rx_sta = 0; // 清除接收状态
  210. }
  211. /**
  212. * @brief 获取IMSI号
  213. * @param 无
  214. * @note
  215. * @retval 1: imsi没有获取到 0;imsi获取到
  216. */
  217. uint8_t EC800_getIMSI(void){
  218. char* found = NULL;
  219. char number[16]; // 15 digits + 1 for null terminator
  220. int numberIndex = 0;
  221. int numberFound = 0;
  222. EC800M_SendCommand(AT_CIMI);
  223. EC800_recEnable();
  224. found = strstr(g_usart4_rx_buf, AT_RESP_OK);
  225. if (found != NULL) {
  226. // printf("IMSI is get\r\n");
  227. }else{
  228. // printf("IMSI is not get\r\n");
  229. return 1;
  230. }
  231. for (int i = 0; i < strlen(g_usart4_rx_buf); i++) {
  232. if (isdigit(g_usart4_rx_buf[i])) {
  233. number[numberIndex] = g_usart4_rx_buf[i];
  234. numberIndex++;
  235. if (numberIndex >= 15) {
  236. numberFound = 1;
  237. break;
  238. }
  239. }
  240. }
  241. number[numberIndex] = '\0';
  242. if (numberFound) {
  243. memcpy(s_messageDate.imsi, number, strlen(number));
  244. // printf("IMSI is: %s\n", number);
  245. } else {
  246. // printf("Error: Unable to extract the number\n");
  247. }
  248. return 0;
  249. }
  250. /**
  251. * @brief EC800M确认网络并链接MQTT服务器
  252. * @param NONE
  253. * @note
  254. * @retval 无
  255. */
  256. uint8_t linkStep = 0;
  257. void EC800M_link(void){
  258. uint8_t temp = 0;
  259. char command[100] = {0};
  260. static char errrCnt = 0; // 错误计数
  261. switch(linkStep){
  262. case 0: // 基础配置
  263. EC800M_SendCommand(AT_CMD_TEST);
  264. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  265. errrCnt = 0;
  266. // printf("Module status normal\r\n");
  267. }else{
  268. errrCnt++;
  269. // printf("Module status abnormal\r\n");
  270. }
  271. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  272. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  273. linkStep = (errrCnt == 0) ? 1 : linkStep;
  274. break;
  275. case 1: // 获取ISMI号
  276. errrCnt = EC800_getIMSI();
  277. if(errrCnt == 0){
  278. linkStep = 2;
  279. }else{
  280. errrCnt = 0;
  281. }
  282. break;
  283. case 2:
  284. EC800M_SendCommand(AT_CMD_ATE0);
  285. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  286. errrCnt = 0;
  287. // printf("Cancel module echo\r\n");
  288. }else{
  289. errrCnt++;
  290. // printf("Failed to cancel module echo\r\n");
  291. }
  292. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  293. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  294. linkStep = (errrCnt == 0) ? 3 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  295. break;
  296. case 3:
  297. EC800M_SendCommand(AT_CMD_CPIN);
  298. if (Accept_and_Compare_Str(AT_RESP_CPIN_READY) == 1) {
  299. errrCnt = 0;
  300. // printf("SIM card normal\r\n");
  301. }else{
  302. errrCnt++;
  303. // printf("SIM card abnormal\r\n");
  304. }
  305. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  306. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  307. linkStep = (errrCnt == 0) ? 4 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  308. break;
  309. case 4:
  310. EC800M_SendCommand(AT_CMD_CSQ);
  311. EC800_recEnable();
  312. temp = EC800_extractSignal(g_usart4_rx_buf);
  313. if (temp) {
  314. errrCnt = 0;
  315. // printf("signal normal\r\n");
  316. }else{
  317. errrCnt++;
  318. // printf("signal abnormal\r\n");
  319. }
  320. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  321. linkStep = (errrCnt == 0) ? 5 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  322. break;
  323. case 5:
  324. EC800M_SendCommand(AT_CMD_CREG);
  325. if((Accept_and_Compare_Str("+CREG: 0,1") == 1) || (Accept_and_Compare_Str("+CREG: 0,5") == 1)){
  326. errrCnt = 0;
  327. // printf("The module successfully registered on the GSM network\r\n");
  328. }else{
  329. errrCnt++;
  330. // printf("The module failed to register on the GSM network\r\n");
  331. }
  332. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  333. g_usart4_rx_sta = 0; // 清除接收状态
  334. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  335. linkStep = (errrCnt == 0) ? 6 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  336. break;
  337. case 6:
  338. EC800M_SendCommand(AT_CMD_QIDEACT);
  339. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  340. errrCnt = 0;
  341. // printf("Successfully disabled mobile scene\r\n");
  342. }else{
  343. errrCnt++;
  344. // printf("Failed to disable mobile scene\r\n");
  345. }
  346. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  347. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  348. linkStep = (errrCnt == 0) ? 7 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  349. break;
  350. case 7:
  351. EC800M_SendCommand(AT_CMD_QIACT);
  352. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  353. errrCnt = 0;
  354. // printf("Successfully enabled mobile scene\r\n");
  355. }else{
  356. errrCnt++;
  357. // printf("Failed to enable mobile scene\r\n");
  358. }
  359. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  360. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  361. // linkStep = (errrCnt == 0) ? 8 : linkStep;
  362. linkStep = (errrCnt == 0) ? 8 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  363. break;
  364. case 8: // 设置MQTT心跳
  365. sprintf(command, "AT+QMTCFG=\"qmtping\",%d,%d\r\n", client_idx, 30);
  366. EC800M_SendCommand(command);
  367. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  368. errrCnt = 0;
  369. // printf("MQTT heartbeat set successfully\r\n");
  370. }else{
  371. errrCnt++;
  372. // printf("Failed to set MQTT heartbeat\r\n");
  373. }
  374. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  375. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  376. linkStep = (errrCnt == 0) ? 9 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  377. break;
  378. case 9: // 设置MQTT接收数据的模式
  379. sprintf(command,"AT+QMTCFG=\"recv/mode\",%d,0,1\r\n", client_idx);
  380. EC800M_SendCommand(command);
  381. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  382. errrCnt = 0;
  383. // printf("Data receiving mode set successfully.\r\n");
  384. }else{
  385. errrCnt++;
  386. // printf("Failed to set data receiving mode\r\n");
  387. }
  388. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  389. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  390. linkStep = (errrCnt == 0) ? 10 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  391. break;
  392. case 10: // 设置QOS为1至少发送1次
  393. // sprintf(command,"AT+QMTCFG=\"will\",%d,1,1,0,255,255\r\n", client_idx);
  394. // EC800M_SendCommand(command);
  395. //
  396. // if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  397. //// printf("Data receiving mode set successfully.\r\n");
  398. // }else{
  399. // errrCnt++;
  400. //// printf("Failed to set data receiving mode\r\n");
  401. // }
  402. //
  403. // memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  404. //
  405. // if(errrCnt == 0){
  406. linkStep = 11;
  407. // }else{
  408. // errrCnt = 0;
  409. // }
  410. break;
  411. case 11: // 为模块打开一个网络
  412. sprintf(command,"AT+QMTOPEN=0,\"%s\",%d\r\n", s_ec800Date.ip, s_ec800Date.port);
  413. EC800M_SendCommand(command);
  414. temp = Accept_and_Compare_Str(AT_RESP_QMTOPEN);
  415. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  416. if (temp == 1) {
  417. errrCnt = 0;
  418. // printf("Successfully opened a network for the module\r\n");
  419. }else{
  420. errrCnt++;
  421. // printf("Failed to open a network for the module\r\n");
  422. }
  423. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  424. linkStep = (errrCnt == 0) ? 12 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  425. break;
  426. case 12: // 连接MQTT服务器
  427. sprintf(command,"AT+QMTCONN=0,%s,%s,%s\r\n",s_ec800Date.clientid, s_ec800Date.username, s_ec800Date.password);
  428. EC800M_SendCommand(command);
  429. if (Accept_and_Compare_Str(AT_RESP_QMTCONN) == 1) {
  430. errrCnt = 0;
  431. // printf("Successfully connected to the MQTT server\r\n");
  432. }else{
  433. errrCnt++;
  434. // printf("Failed to connect to the MQTT server\r\n");
  435. }
  436. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  437. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  438. linkStep = (errrCnt == 0) ? 13 : ((errrCnt > task_upload_times_2s) ? 0 : linkStep);
  439. break;
  440. default: break;
  441. }
  442. }
  443. /**
  444. * @brief EC800M初始化GNSS
  445. * @param NONE
  446. * @note
  447. * @retval 无
  448. */
  449. uint8_t gnssStep = 0;
  450. void EC800_gnss_init(void){
  451. static char errrCnt = 0; // 错误计数
  452. switch(gnssStep){
  453. case 6:
  454. EC800M_SendCommand(AT_QGPS_0);
  455. if (Accept_and_Compare_Str(AT_RESP_OK) != 3) {
  456. errrCnt = 0;
  457. // printf("Turn off the GNSS module\r\n");
  458. }else{
  459. errrCnt++;
  460. // printf("Failed to turn off the GNSS module\r\n");
  461. }
  462. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  463. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  464. gnssStep = (errrCnt == 0) ? 7 : ((errrCnt > task_upload_times_2s) ? 0 : gnssStep);
  465. break;
  466. case 7:
  467. EC800M_SendCommand(AT_QGPS_1);
  468. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  469. errrCnt = 0;
  470. // printf("Turn on the GNSS module\r\n");
  471. }else{
  472. errrCnt++;
  473. // printf("Failed to turn on the GNSS module\r\n");
  474. }
  475. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  476. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  477. gnssStep = (errrCnt == 0) ? 8 : ((errrCnt > task_upload_times_2s) ? 0 : gnssStep);
  478. break;
  479. case 8:
  480. EC800M_SendCommand(AT_QGPSDEL_1);
  481. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  482. errrCnt = 0;
  483. // printf("Turn on the GNSS module\r\n");
  484. }else{
  485. errrCnt++;
  486. // printf("Failed to turn on the GNSS module\r\n");
  487. }
  488. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  489. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  490. gnssStep = (errrCnt == 0) ? 9 : ((errrCnt > task_upload_times_2s) ? 0 : gnssStep);
  491. break;
  492. case 0:
  493. EC800M_SendCommand(AT_QGPSCFG_out_port);
  494. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  495. errrCnt = 0;
  496. // printf("Outputting NMEA Sentences via Serial Debugging\r\n");
  497. }else{
  498. errrCnt++;
  499. // printf("The NMEA sentence output is set incorrectly\r\n");
  500. }
  501. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  502. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  503. gnssStep = (errrCnt == 0) ? 1 : ((errrCnt > task_upload_times_2s) ? 0 : gnssStep);
  504. break;
  505. case 1:
  506. EC800M_SendCommand(AT_QGPSCFG_nmeasrc);
  507. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  508. errrCnt = 0;
  509. // printf("Enabling NMEA sentence retrieval via AT+QGPSGNMEA\r\n");
  510. }else{
  511. errrCnt++;
  512. // printf("Failed to enable retrieving NMEA sentences via AT+QGPSGNMEA\r\n");
  513. }
  514. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  515. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  516. gnssStep = (errrCnt == 0) ? 2 : ((errrCnt > task_upload_times_2s) ? 0 : gnssStep);
  517. break;
  518. case 2:
  519. EC800M_SendCommand(AT_QGPSCFG_gpsnmeatype);
  520. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  521. errrCnt = 0;
  522. // printf("Configuring the output type of NMEA sentences to all formats\r\n");
  523. }else{
  524. errrCnt++;
  525. // printf("Failed to configure the output type of NMEA sentences to all formats\r\n");
  526. }
  527. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  528. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  529. gnssStep = (errrCnt == 0) ? 3 : ((errrCnt > task_upload_times_2s) ? 0 : gnssStep);
  530. break;
  531. case 3:
  532. EC800M_SendCommand(AT_QGPSCFG_gnssconfig);
  533. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  534. errrCnt = 0;
  535. // printf("Configuring the supported GNSS satellite navigation systems to GPS+BeiDou\r\n");
  536. }else{
  537. errrCnt++;
  538. // printf("Failed to configure the supported GNSS satellite navigation systems to GPS+BeiDou\r\n");
  539. }
  540. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  541. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  542. gnssStep = (errrCnt == 0) ? 4 : ((errrCnt > task_upload_times_2s) ? 0 : gnssStep);
  543. break;
  544. case 4:
  545. EC800M_SendCommand(AT_QGPSCFG_autogps);
  546. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  547. errrCnt = 0;
  548. // printf("Disable GNSS auto-start\r\n");
  549. }else{
  550. errrCnt++;
  551. // printf("Failed to disable GNSS auto-start\r\n");
  552. }
  553. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  554. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  555. gnssStep = (errrCnt == 0) ? 5 : ((errrCnt > task_upload_times_2s) ? 0 : gnssStep);
  556. break;
  557. case 5:
  558. EC800M_SendCommand(AT_QGPSCFG_apflash);
  559. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  560. errrCnt = 0;
  561. // printf("Disable AP-Flash quick start function\r\n");
  562. }else{
  563. errrCnt++;
  564. // printf("Failed to disable AP-Flash quick start function\r\n");
  565. }
  566. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  567. // 返回正常,则进入下一步,否则判断错误次数,进行重连
  568. gnssStep = (errrCnt == 0) ? 6 : ((errrCnt > task_upload_times_2s) ? 0 : gnssStep);
  569. break;
  570. default:
  571. break;
  572. }
  573. }
  574. //UTC时间转换为任意时区时间,如果是转换为北京时间,timezone传8即可
  575. void utc_to_local_time(nmea_utc_time* utc_time, int8_t timezone, nmea_utc_time* local_time)
  576. {
  577. int year,month,day,hour;
  578. int lastday = 0; //last day of this month 本月天数
  579. int lastlastday = 0; //last day of last month 上个月天数
  580. year = utc_time->year; //utc time
  581. month = utc_time->month;
  582. day = utc_time->date;
  583. hour = utc_time->hour + timezone;
  584. //1月大,2月小,3月大,4月小,5月大,6月小,7月大,8月大,9月小,10月大,11月小,12月大
  585. if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
  586. {
  587. lastday = 31;//本月天数
  588. lastlastday = 30;//这里应该补上上个月的天数
  589. if(month == 3)
  590. {
  591. if((year%400 == 0)||(year%4 == 0 && year%100 != 0))//if this is lunar year
  592. lastlastday = 29;
  593. else
  594. lastlastday = 28;
  595. }
  596. if(month == 8 || month == 1)//这里应该是8月和1月,因为8月和1月的上一个月(7月和12月)的天数是31天的
  597. lastlastday = 31;
  598. }
  599. else if(month == 4 || month == 6 || month == 9 || month == 11)
  600. {
  601. lastday = 30;
  602. lastlastday = 31;
  603. }
  604. else
  605. {
  606. lastlastday = 31;
  607. if((year%400 == 0)||(year%4 == 0 && year%100 != 0))
  608. lastday = 29;
  609. else
  610. lastday = 28;
  611. }
  612. if(hour >= 24)// if >24, day+1
  613. {
  614. hour -= 24;
  615. day += 1;
  616. if(day > lastday)// next month, day-lastday of this month
  617. {
  618. day -= lastday;
  619. month += 1;
  620. if(month > 12)// next year, month-12
  621. {
  622. month -= 12;
  623. year += 1;
  624. }
  625. }
  626. }
  627. if(hour < 0)// if <0, day-1
  628. {
  629. hour += 24;
  630. day -= 1;
  631. if(day < 1)// month-1, day=last day of last month
  632. {
  633. day = lastlastday;
  634. month -= 1;
  635. if(month < 1)// last year, month=12
  636. {
  637. month = 12;
  638. year -= 1;
  639. }
  640. }
  641. }
  642. // transfer value to local_time
  643. local_time->year = year;
  644. local_time->month = month;
  645. local_time->date = day;
  646. local_time->hour = hour;
  647. local_time->min = utc_time->min;
  648. local_time->sec = utc_time->sec;
  649. }
  650. /**
  651. * @brief 常用时间格式转时间戳
  652. * @param NONE
  653. * @note 要用utc时间进行转换,如果输入为北京时间的话,需要 hour-8;
  654. * @retval 无
  655. */
  656. uint32_t EC800_mktime (unsigned int year, unsigned int mon,
  657. unsigned int day, unsigned int hour,
  658. unsigned int min, unsigned int sec)
  659. {
  660. if (0 >= (int) (mon -= 2)){ /**//* 1..12 -> 11,12,1..10 */
  661. mon += 12; /**//* Puts Feb last since it has leap day */
  662. year -= 1;
  663. }
  664. return (((
  665. (unsigned long) (year/4 - year/100 + year/400 + 367*mon/12 + day) +
  666. year*365 - 719499
  667. )*24 + hour /**//* now have hours */
  668. )*60 + min /**//* now have minutes */
  669. )*60 + sec; /**//* finally seconds */
  670. }
  671. /**
  672. * @brief 读取GNSS的数据
  673. * @param NONE
  674. * @note
  675. * @retval 0:接收失败 1:接收成功
  676. */
  677. uint8_t EC800_readGnssDate(void){
  678. EC800M_SendCommand(AT_QGPSGNMEA_RMC);
  679. if (Accept_and_Compare_Str(AT_RESP_OK) == 1) {
  680. // printf("Location information received successfully\r\n");
  681. }else{
  682. // printf("Location information reception failed\r\n");
  683. return 0;
  684. }
  685. // printf("Location information:%s\r\n", g_usart4_rx_buf);
  686. NMEA_GNRMC_Analysis(&s_nmea_msg, (uint8_t*)g_usart4_rx_buf);
  687. utc_to_local_time(&(s_nmea_msg.utc), 8, &s_nmea_utc_time);
  688. // printf("timer-%d/%d/%d %d:%d:%d\r\n",s_nmea_utc_time.year,s_nmea_utc_time.month,s_nmea_utc_time.date,s_nmea_utc_time.hour,s_nmea_utc_time.min,s_nmea_utc_time.sec);
  689. s_messageDate.Timestamp = EC800_mktime(s_nmea_utc_time.year,s_nmea_utc_time.month,s_nmea_utc_time.date,s_nmea_utc_time.hour - 8,s_nmea_utc_time.min,s_nmea_utc_time.sec);
  690. g_usart4_rx_sta= 0;
  691. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff
  692. // printf("latitude:%d%d--longitude:%d%d\r\n", s_nmea_msg.latitude, s_nmea_msg.nshemi, s_nmea_msg.longitude, s_nmea_msg.ewhemi);
  693. /* 尝试获取互斥量,等待无限长时间 */
  694. if(osMutexAcquire(s_messageDate_locationHandle, 100) == osOK)
  695. {
  696. /* 安全地访问s_rs485RecDate结构体 */
  697. s_messageDate.latitude = s_nmea_msg.latitude;
  698. s_messageDate.nshemi = s_nmea_msg.nshemi;
  699. s_messageDate.longitude = s_nmea_msg.longitude;
  700. s_messageDate.ewhemi = s_nmea_msg.ewhemi;
  701. /* 访问完成,释放互斥量 */
  702. osMutexRelease(s_messageDate_locationHandle);
  703. }
  704. return 1;
  705. }
  706. /**
  707. * @brief EC800M订阅主题
  708. * @param topic1: 订阅的主题名称1字符串形式
  709. * @param topic2: 订阅的主题名称2字符串形式
  710. * @note
  711. * @retval 无
  712. */
  713. uint8_t EC800_subscribeToTopic(const char* topic1){
  714. char command[100] = {0};
  715. uint8_t recTemp = 0;
  716. sprintf(command, "AT+QMTSUB=0,1,\"%s\",0\r\n", topic1);
  717. EC800M_SendCommand(command);
  718. recTemp = Accept_and_Compare_Str(AT_RESP_QMTSUB);
  719. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  720. if (recTemp == 1) {
  721. // printf("Subscription to the topic successful\r\n");
  722. return 1;
  723. }else if (recTemp == 2){
  724. // printf("Subscription to the topic failed\r\n");
  725. return 0;
  726. }
  727. return 0;
  728. }
  729. /**
  730. * @brief EC800M发布消息
  731. * @param topic: 消息发布的主题 字符串形式
  732. * @param message: 发布的消息 字符串形式
  733. * @param len: 发布消息的字节长度
  734. * @note
  735. * @retval 无
  736. */
  737. uint8_t EC800_publishMessage(const char* topic, const char* message, uint16_t len){
  738. char command[100] = {0};
  739. char* responseCmd = ">";
  740. static uint8_t publishStep = 0;
  741. uint8_t recBack = 0;
  742. switch(publishStep){
  743. case 0:
  744. sprintf(command,"AT+QMTPUBEX=0,0,0,0,\"%s\",%d\r\n",topic,len);
  745. EC800M_SendCommand(command);
  746. if (Accept_and_Compare_Str(responseCmd) == 1) {
  747. // printf("The topic has been linked\r\n");
  748. publishStep = 1;
  749. }else{
  750. // printf("The topic link failed\r\n");
  751. publishStep = 0;
  752. }
  753. // break;
  754. case 1:
  755. EC800M_SendCommand(message);
  756. recBack = Accept_and_Compare_Str(AT_RESP_QMTPUBEX);
  757. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清空输入缓冲区
  758. if (recBack == 1) {
  759. publishStep = 0;
  760. // printf("The message has been successfully posted\r\n");
  761. }else{
  762. // printf("Message publication failed\r\n");
  763. publishStep = 0;
  764. }
  765. break;
  766. default:
  767. break;
  768. }
  769. return recBack;
  770. }
  771. // 将uint8_t数组中的ASCII码数据转换为字符串的函数
  772. void uint8ArrayToAsciiString(const uint8_t* array, size_t length, char* str) {
  773. for (size_t i = 0; i < length; ++i) {
  774. str[i] = (char)array[i]; // 直接将每个字节转换为字符
  775. }
  776. str[length] = '\0'; // 添加字符串结束符
  777. }
  778. /**
  779. * @brief 登录 topic
  780. * @param NONE
  781. * @note topic 101
  782. * @retval 无
  783. */
  784. uint8_t Login_Topic(void){
  785. cJSON *root = NULL;
  786. char *jsonString = NULL;
  787. uint8_t temp = 0;
  788. char command[50] = {0};
  789. // 定义对象 { }
  790. root = cJSON_CreateObject();
  791. // 插入元素,对应 键值对
  792. cJSON_AddItemToObject(root, "msgType", cJSON_CreateString("json"));
  793. cJSON_AddItemToObject(root, "imsi", cJSON_CreateString(s_messageDate.imsi));
  794. cJSON_AddItemToObject(root, "hardVersion", cJSON_CreateString(HARD_VERSION));
  795. cJSON_AddItemToObject(root, "softVersion", cJSON_CreateString(SOFT_VERSION));
  796. sprintf(command, "%x%x%x", s_messageDate.devId[0], s_messageDate.devId[1], s_messageDate.devId[2]);
  797. cJSON_AddItemToObject(root, "devId", cJSON_CreateString(command));
  798. memset(command, 0, 50);
  799. uint8ArrayToAsciiString(s_messageDate.VIN, sizeof(s_messageDate.VIN), command);
  800. cJSON_AddItemToObject(root, "hardwareId", cJSON_CreateString(command));
  801. cJSON_AddItemToObject(root, "protocolVersion", cJSON_CreateString(PROTOCOL_VERSION));
  802. cJSON_AddItemToObject(root, "devType", cJSON_CreateNumber(DEV_TYPE));
  803. cJSON_AddItemToObject(root, "txnNo", cJSON_CreateNumber(s_messageDate.Timestamp));
  804. // 将 JSON 对象转换为字符串
  805. jsonString = cJSON_Print(root);
  806. cJSON_Delete(root);
  807. temp = EC800_publishMessage("toServer/mqtt/101", jsonString, strlen(jsonString));
  808. free(jsonString);
  809. return temp;
  810. }
  811. /**
  812. * @brief 下位机请求围栏数据
  813. * @param NONE
  814. * @note topic 604
  815. * @retval 无
  816. */
  817. uint8_t requesting_Fence_Data(void){
  818. cJSON *root = NULL;
  819. char *jsonString = NULL;
  820. uint8_t temp = 0;
  821. char command[50] = {0};
  822. // 定义对象 { }
  823. root = cJSON_CreateObject();
  824. // 插入元素,对应 键值对
  825. cJSON_AddItemToObject(root, "msgType", cJSON_CreateString("json"));
  826. cJSON_AddItemToObject(root, "imsi", cJSON_CreateString(s_messageDate.imsi));
  827. cJSON_AddItemToObject(root, "hardVersion", cJSON_CreateString(HARD_VERSION));
  828. cJSON_AddItemToObject(root, "softVersion", cJSON_CreateString(SOFT_VERSION));
  829. sprintf(command, "%x%x%x", s_messageDate.devId[0], s_messageDate.devId[1], s_messageDate.devId[2]);
  830. cJSON_AddItemToObject(root, "devId", cJSON_CreateString(command));
  831. memset(command, 0, 50);
  832. uint8ArrayToAsciiString(s_messageDate.VIN, sizeof(s_messageDate.VIN), command);
  833. cJSON_AddItemToObject(root, "vin", cJSON_CreateString(command));
  834. cJSON_AddItemToObject(root, "protocolVersion", cJSON_CreateString(PROTOCOL_VERSION));
  835. cJSON_AddItemToObject(root, "txnNo", cJSON_CreateNumber(s_messageDate.Timestamp));
  836. cJSON_AddItemToObject(root, "devType", cJSON_CreateNumber(DEV_TYPE));
  837. // 将 JSON 对象转换为字符串
  838. jsonString = cJSON_Print(root);
  839. cJSON_Delete(root);
  840. temp = EC800_publishMessage("toServer/mqtt/604", jsonString, strlen(jsonString));
  841. free(jsonString);
  842. return temp;
  843. }
  844. /**
  845. * @brief 创建单个报警项的JSON对象
  846. * @param NONE
  847. * @note topic toServer/mqtt/501
  848. * @retval 无
  849. */
  850. cJSON* createAlarmItem(const char* id, uint32_t alarmTime, const char* alarmDesc, int alarmFlag) {
  851. cJSON* alarmItem = cJSON_CreateObject();
  852. cJSON_AddStringToObject(alarmItem, "id", id);
  853. cJSON_AddNumberToObject(alarmItem, "alarmTime", alarmTime);
  854. cJSON_AddStringToObject(alarmItem, "alarmDesc", alarmDesc);
  855. cJSON_AddNumberToObject(alarmItem, "alarmFlag", alarmFlag);
  856. return alarmItem;
  857. }
  858. /**
  859. * @brief 根据Malfunction的值插入故障元素
  860. * @param NONE
  861. * @note topic toServer/mqtt/501
  862. * @retval 无
  863. */
  864. void insertFaultItems(cJSON* alarmList, uint32_t Malfunction, uint32_t fault_timeStamp) {
  865. for (int i = 0; i < 32; i++) {
  866. if (Malfunction & (1 << i)) {
  867. // 确保i在数组的有效范围内
  868. if (i < 12) {
  869. cJSON_AddItemToArray(alarmList, createAlarmItem(faults[i].errid, fault_timeStamp, faults[i].errorInfo, 1));
  870. }
  871. }
  872. }
  873. }
  874. /**
  875. * @brief 故障数据上传
  876. * @param NONE
  877. * @note topic toServer/mqtt/501
  878. * @retval 无
  879. */
  880. uint8_t EC800_uploadFaultReport(uint32_t fault_time_stamp, uint32_t fault_Code){
  881. cJSON *root = NULL;
  882. char *jsonString = NULL;
  883. uint8_t temp = 0;
  884. char command[50] = {0};
  885. // 定义对象 { }
  886. root = cJSON_CreateObject();
  887. // 插入元素,对应 键值对
  888. cJSON_AddItemToObject(root, "msgType", cJSON_CreateString("json"));
  889. sprintf(command, "%x%x%x", s_messageDate.devId[0], s_messageDate.devId[1], s_messageDate.devId[2]);
  890. cJSON_AddItemToObject(root, "devId", cJSON_CreateString(command));
  891. cJSON_AddItemToObject(root, "txnNo", cJSON_CreateNumber(s_messageDate.Timestamp));
  892. cJSON_AddItemToObject(root, "devType", cJSON_CreateNumber(DEV_TYPE));
  893. // 插入故障元素
  894. cJSON* alarmList = cJSON_CreateArray();
  895. insertFaultItems(alarmList, fault_Code, fault_time_stamp);
  896. cJSON_AddItemToObject(root, "alarmList", alarmList);
  897. // 将 JSON 对象转换为字符串
  898. jsonString = cJSON_Print(root);
  899. cJSON_Delete(root);
  900. temp = EC800_publishMessage("toServer/mqtt/501", jsonString, strlen(jsonString));
  901. free(jsonString);
  902. return temp;
  903. }
  904. /**
  905. * @brief EC800M与服务器进行时间对时
  906. * @note
  907. * @retval 无
  908. */
  909. uint8_t EC800_time_calibration(void){
  910. cJSON *root = NULL;
  911. char *jsonString = NULL;
  912. uint8_t temp = 0;
  913. char command[50] = {0};
  914. // 定义对象 { }
  915. root = cJSON_CreateObject();
  916. // 插入元素,对应 键值对
  917. cJSON_AddItemToObject(root, "msgType", cJSON_CreateString("json"));
  918. cJSON_AddItemToObject(root, "imsi", cJSON_CreateString(s_messageDate.imsi));
  919. cJSON_AddItemToObject(root, "hardVersion", cJSON_CreateString(HARD_VERSION));
  920. cJSON_AddItemToObject(root, "softVersion", cJSON_CreateString(SOFT_VERSION));
  921. sprintf(command, "%x%x%x", s_messageDate.devId[0], s_messageDate.devId[1], s_messageDate.devId[2]);
  922. cJSON_AddItemToObject(root, "devId", cJSON_CreateString(command));
  923. cJSON_AddItemToObject(root, "protocolVersion", cJSON_CreateString(PROTOCOL_VERSION));
  924. cJSON_AddItemToObject(root, "txnNo", cJSON_CreateNumber(s_messageDate.Timestamp));
  925. cJSON_AddItemToObject(root, "devType", cJSON_CreateNumber(DEV_TYPE));
  926. // 将 JSON 对象转换为字符串
  927. jsonString = cJSON_Print(root);
  928. cJSON_Delete(root);
  929. temp = EC800_publishMessage("toServer/mqtt/105", jsonString, strlen(jsonString));
  930. free(jsonString);
  931. return temp;
  932. }
  933. /**
  934. * @brief 将服务器响应的字符串中的年月日进行分离
  935. * @note
  936. * @retval 无
  937. */
  938. void parseServerTime(char* str){
  939. char year[5];
  940. char month[3];
  941. char day[3];
  942. char hour[3];
  943. char minute[3];
  944. char second[3];
  945. strncpy(year, str, 4);
  946. year[4] = '\0';
  947. strncpy(month, str + 4, 2);
  948. month[2] = '\0';
  949. strncpy(day, str + 6, 2);
  950. day[2] = '\0';
  951. strncpy(hour, str + 8, 2);
  952. hour[2] = '\0';
  953. strncpy(minute, str + 10, 2);
  954. minute[2] = '\0';
  955. strncpy(second, str + 12, 2);
  956. second[2] = '\0';
  957. s_recDate.year = atoi(year);
  958. s_recDate.month = atoi(month);
  959. s_recDate.day = atoi(day);
  960. s_recDate.hour = atoi(hour);
  961. s_recDate.minute = atoi(minute);
  962. s_recDate.sec = atoi(second);
  963. s_messageDate.Timestamp = EC800_mktime(s_recDate.year,s_recDate.month,s_recDate.day,s_recDate.hour - 8,s_recDate.minute,s_recDate.sec);
  964. // printf("Year (int): %d\n", s_recDate.year);
  965. // printf("Month (int): %d\n", s_recDate.month);
  966. // printf("Day (int): %d\n", s_recDate.day);
  967. // printf("Hour (int): %d\n", s_recDate.hour);
  968. // printf("Minute (int): %d\n", s_recDate.minute);
  969. // printf("Second (int): %d\n", s_recDate.sec);
  970. }
  971. /**
  972. * @brief 解析对时数据帧的响应
  973. * @note
  974. * @retval 无
  975. */
  976. void EC800_parseRespondTime(cJSON *root, cJSON *item){
  977. uint8_t temp = 0;
  978. // 获取"resultCode"字段的值
  979. item = cJSON_GetObjectItem(root, "resultCode");
  980. if (item == NULL) {
  981. // printf("Field \"resultCode\" not found\n");
  982. }else{
  983. // 打印"resultCode"字段的值
  984. // printf("resultCode: %d\n", item->valueint);
  985. if((item->valueint) == 1){
  986. // printf("The upload of synchronized data was successful.\n");
  987. temp = 1; // 上传成功
  988. }else{
  989. // printf("The upload of synchronized data has failed.\n");
  990. }
  991. }
  992. if(temp == 1){
  993. item = cJSON_GetObjectItem(root, "serverTime");
  994. if (item == NULL) {
  995. // printf("Field \"serverTime\" not found\n");
  996. }else{
  997. // 打印"serverTime"字段的值
  998. // printf("serverTime: %s\n", item->valuestring);
  999. parseServerTime(item->valuestring);
  1000. }
  1001. }
  1002. }
  1003. /**
  1004. * @brief EC800M上传实时数据
  1005. * @note
  1006. * @retval 无
  1007. */
  1008. uint8_t EC800_uploadRealDate(void){
  1009. cJSON *root = NULL;
  1010. char *jsonString = NULL;
  1011. cJSON *rt000 = NULL;
  1012. cJSON *rt000Object1 = NULL;
  1013. char command[100] = {0};
  1014. uint32_t temp = 0; // 临时存储
  1015. // 定义对象 { }
  1016. root = cJSON_CreateObject();
  1017. //
  1018. // 插入元素,对应 键值对
  1019. cJSON_AddItemToObject(root, "msgType", cJSON_CreateString("json"));
  1020. cJSON_AddItemToObject(root, "imsi", cJSON_CreateString(s_messageDate.imsi));
  1021. cJSON_AddItemToObject(root, "hardVersion", cJSON_CreateString(HARD_VERSION));
  1022. cJSON_AddItemToObject(root, "softVersion", cJSON_CreateString(SOFT_VERSION));
  1023. sprintf(command, "%x%x%x", s_messageDate.devId[0], s_messageDate.devId[1], s_messageDate.devId[2]);
  1024. cJSON_AddItemToObject(root, "devId", cJSON_CreateString(command));
  1025. cJSON_AddItemToObject(root, "protocolVersion", cJSON_CreateString(PROTOCOL_VERSION));
  1026. cJSON_AddItemToObject(root, "txnNo", cJSON_CreateNumber(s_messageDate.Timestamp));
  1027. cJSON_AddItemToObject(root, "devType", cJSON_CreateNumber(DEV_TYPE));
  1028. // 定义 { } 对象
  1029. rt000Object1 = cJSON_CreateObject();
  1030. cJSON_AddItemToObject(rt000Object1, "rt003", cJSON_CreateNumber(s_messageDate.vehicleStatus));
  1031. cJSON_AddItemToObject(rt000Object1, "rt025", cJSON_CreateNumber((float)s_messageDate.demandVol / 10));
  1032. cJSON_AddItemToObject(rt000Object1, "rt026", cJSON_CreateNumber((float)s_messageDate.demandCur / 10));
  1033. // 判断是否不为空
  1034. if(s_messageDate.VIN[0] != NULL){
  1035. memset(command, 0, 50);
  1036. uint8ArrayToAsciiString(s_messageDate.VIN, sizeof(s_messageDate.VIN), command);
  1037. cJSON_AddItemToObject(rt000Object1, "rt027", cJSON_CreateString(command));
  1038. }
  1039. double point1Lat = (double)s_messageDate.latitude / 100000;
  1040. double point1Lng = (double)s_messageDate.longitude / 100000;
  1041. memset(command, 0, 50);
  1042. snprintf(command, sizeof(command), "%.5f,%.5f", point1Lng, point1Lat);
  1043. cJSON_AddItemToObject(rt000Object1, "rt028", cJSON_CreateString(command));
  1044. cJSON_AddItemToObject(rt000Object1, "rt029", cJSON_CreateNumber(s_messageDate.drivDirection));
  1045. cJSON_AddItemToObject(rt000Object1, "rt030", cJSON_CreateNumber(s_messageDate.vehicleSpeed));
  1046. temp = 0;
  1047. temp = (s_messageDate.dailyDrivTime >> 8) * 60 + (s_messageDate.dailyDrivTime & 0x00ff); // 转换单位为min
  1048. cJSON_AddItemToObject(rt000Object1, "rt031", cJSON_CreateNumber(temp));
  1049. cJSON_AddItemToObject(rt000Object1, "rt032", cJSON_CreateNumber(s_messageDate.dailyDrivMileage / 10));
  1050. temp = 0;
  1051. temp = ((s_messageDate.accTotalDrivTime_day * 24) + (s_messageDate.accTotalDrivTime_h_min >> 8)) * 60 + (s_messageDate.accTotalDrivTime_h_min & 0x00ff); // 转换单位为min
  1052. cJSON_AddItemToObject(rt000Object1, "rt033", cJSON_CreateNumber(temp));
  1053. cJSON_AddItemToObject(rt000Object1, "rt034", cJSON_CreateNumber((s_messageDate.accTotalMileage_h << 16) + s_messageDate.accTotalMileage_l));
  1054. temp = 0;
  1055. temp = (s_messageDate.runTime >> 8) * 60 + (s_messageDate.runTime & 0x00ff);
  1056. cJSON_AddItemToObject(rt000Object1, "rt035", cJSON_CreateNumber(temp));
  1057. // test use 发送转弯标志
  1058. cJSON_AddItemToObject(rt000Object1, "rt036", cJSON_CreateNumber(s_global_par.moduleSig));
  1059. // 定义 [ ] 数组
  1060. rt000 = cJSON_CreateArray();
  1061. // 往数组中添加元素
  1062. cJSON_AddItemToArray(rt000, rt000Object1);
  1063. // 将子项插入根项中
  1064. cJSON_AddItemToObject(root, "rt000", rt000);
  1065. //
  1066. // 将 JSON 对象转换为字符串
  1067. jsonString = cJSON_Print(root);
  1068. cJSON_Delete(root);
  1069. temp = 0;
  1070. temp = EC800_publishMessage("toServer/mqtt/201", jsonString, strlen(jsonString));
  1071. free(jsonString);
  1072. return temp;
  1073. }
  1074. /**
  1075. * @brief 解析实时数据响应
  1076. * @note
  1077. * @retval 无
  1078. */
  1079. void EC800_respondRealDate(cJSON *root, cJSON *item){
  1080. // 获取"name"字段的值
  1081. item = cJSON_GetObjectItem(root, "resultCode");
  1082. if (item == NULL) {
  1083. // printf("Field \"resultCode\" not found\n");
  1084. }else{
  1085. // 打印"name"字段的值
  1086. // printf("resultCode: %d\n", item->valueint);
  1087. if((item->valueint) == 1){
  1088. // printf("Uploaded real-time data successfully\n");
  1089. }else{
  1090. // printf("The upload of real-time data has failed\n");
  1091. }
  1092. }
  1093. }
  1094. /**
  1095. * @brief 解析升級数据
  1096. * @note
  1097. * @retval 无
  1098. */
  1099. void EC800_respondUpdateDate(cJSON *root, cJSON *item, ftpInfo *p_ftpInfo){
  1100. /* 获取address对象 */
  1101. cJSON *hardwareUpdate = cJSON_GetObjectItem(root, "paramList");
  1102. if (hardwareUpdate == NULL) {
  1103. // printf("Failed to parse paramList data\n");
  1104. return ;
  1105. }
  1106. // 获取"name"字段的值
  1107. item = cJSON_GetObjectItem(hardwareUpdate, "function");
  1108. if (item == NULL) {
  1109. // printf("Field \"update\" not found\n");
  1110. }else{
  1111. // 打印"name"字段的值
  1112. // printf("function: %d\n", item->valueint);
  1113. // 1:表示固件更新 当后台下发升级指令,并且行车状态为静止态允许更新固件
  1114. if(((item->valueint) == 1) && (s_comData.driveStatus == 0x02)){
  1115. s_ec800Date.hardwareUpdate = 1; // 更新固件
  1116. // printf("update begin\n");
  1117. }else{
  1118. // printf("no update\n");
  1119. }
  1120. }
  1121. // 获取"ftpAddr"字段的值
  1122. item = cJSON_GetObjectItem(hardwareUpdate, "ftpAddr");
  1123. if (item == NULL) {
  1124. // printf("Field \"ftpAddr\" not found\n");
  1125. }else{
  1126. // printf("ftpAddr: %s\n", item->valuestring);
  1127. /* 复制字符串到ftpInfo结构体的ftpAddr成员 */
  1128. strncpy(p_ftpInfo->ftpAddr, item->valuestring, sizeof(p_ftpInfo->ftpAddr) - 1);
  1129. /* 确保字符串以空字符结尾 */
  1130. p_ftpInfo->ftpAddr[sizeof(p_ftpInfo->ftpAddr) - 1] = '\0';
  1131. }
  1132. // 获取"ftpPort"字段的值
  1133. item = cJSON_GetObjectItem(hardwareUpdate, "ftpPort");
  1134. if (item == NULL) {
  1135. // printf("Field \"ftpPort\" not found\n");
  1136. }else{
  1137. // 打印"name"字段的值
  1138. // printf("ftpPort: %d\n", item->valueint);
  1139. p_ftpInfo->ftpPort = item->valueint;
  1140. }
  1141. // 获取"account"字段的值
  1142. item = cJSON_GetObjectItem(hardwareUpdate, "account");
  1143. if (item == NULL) {
  1144. // printf("Field \"account\" not found\n");
  1145. }else{
  1146. // printf("account: %s\n", item->valuestring);
  1147. /* 复制字符串到ftpInfo结构体的ftpAddr成员 */
  1148. strncpy(p_ftpInfo->account, item->valuestring, sizeof(p_ftpInfo->ftpAddr) - 1);
  1149. /* 确保字符串以空字符结尾 */
  1150. p_ftpInfo->ftpAddr[sizeof(p_ftpInfo->account) - 1] = '\0';
  1151. }
  1152. // 获取"passWord"字段的值
  1153. item = cJSON_GetObjectItem(hardwareUpdate, "passWord");
  1154. if (item == NULL) {
  1155. // printf("Field \"passWord\" not found\n");
  1156. }else{
  1157. // printf("account: %s\n", item->valuestring);
  1158. /* 复制字符串到ftpInfo结构体的ftpAddr成员 */
  1159. strncpy(p_ftpInfo->passWord, item->valuestring, sizeof(p_ftpInfo->ftpAddr) - 1);
  1160. /* 确保字符串以空字符结尾 */
  1161. p_ftpInfo->ftpAddr[sizeof(p_ftpInfo->passWord) - 1] = '\0';
  1162. }
  1163. // 获取"passWord"字段的值
  1164. item = cJSON_GetObjectItem(hardwareUpdate, "textDirectory");
  1165. if (item == NULL) {
  1166. // printf("Field \"textDirectory\" not found\n");
  1167. }else{
  1168. // printf("textDirectory: %s\n", item->valuestring);
  1169. /* 复制字符串到ftpInfo结构体的ftpAddr成员 */
  1170. strncpy(p_ftpInfo->textDirectory, item->valuestring, sizeof(p_ftpInfo->ftpAddr) - 1);
  1171. /* 确保字符串以空字符结尾 */
  1172. p_ftpInfo->ftpAddr[sizeof(p_ftpInfo->textDirectory) - 1] = '\0';
  1173. }
  1174. // 获取"passWord"字段的值
  1175. item = cJSON_GetObjectItem(hardwareUpdate, "textName");
  1176. if (item == NULL) {
  1177. // printf("Field \"textName\" not found\n");
  1178. }else{
  1179. // printf("textName: %s\n", item->valuestring);
  1180. /* 复制字符串到ftpInfo结构体的ftpAddr成员 */
  1181. strncpy(p_ftpInfo->textName, item->valuestring, sizeof(p_ftpInfo->ftpAddr) - 1);
  1182. /* 确保字符串以空字符结尾 */
  1183. p_ftpInfo->ftpAddr[sizeof(p_ftpInfo->textName) - 1] = '\0';
  1184. }
  1185. }
  1186. /**
  1187. * @brief 解析围栏经纬度数据
  1188. * @note
  1189. * @param root: cJSON 根对象
  1190. * @param Latitude: 纬度数组
  1191. * @param Longitude: 经度数组
  1192. * @retval 成功返回1,失败返回0
  1193. */
  1194. int parse_Latitude_Longitude_Data(cJSON *root, double Latitude[], double Longitude[]) {
  1195. // 确保输入不为空
  1196. if (root == NULL) {
  1197. // printf("Root object is NULL\n");
  1198. return 0;
  1199. }
  1200. // 获取 polygonLat 数组
  1201. cJSON *polygonLat = cJSON_GetObjectItem(root, "polygonLat");
  1202. if (polygonLat == NULL || polygonLat->type != cJSON_Array) {
  1203. // printf("polygonLat is not an array or is missing\n");
  1204. return 0;
  1205. }
  1206. // 获取 polygonLng 数组
  1207. cJSON *polygonLng = cJSON_GetObjectItem(root, "polygonLon");
  1208. if (polygonLng == NULL || polygonLat->type != cJSON_Array) {
  1209. // printf("polygonLng is not an array or is missing\n");
  1210. return 0;
  1211. }
  1212. // 获取数组大小并检查是否匹配和是否超出预定义的最大大小
  1213. int polygonLatSize = cJSON_GetArraySize(polygonLat);
  1214. int polygonLngSize = cJSON_GetArraySize(polygonLng);
  1215. if (polygonLatSize != polygonLngSize || polygonLatSize > REC_COORDINATE_DEPTH) {
  1216. // printf("Array sizes mismatch or exceed maximum allowed size\n");
  1217. return 0;
  1218. }
  1219. // 解析 polygonLat 数组
  1220. for (int i = 0; i < polygonLatSize; ++i) {
  1221. cJSON *latItem = cJSON_GetArrayItem(polygonLat, i);
  1222. if (latItem == NULL || latItem->type != cJSON_Number) {
  1223. // printf("Lat item is not a number or is missing\n");
  1224. return 0;
  1225. }
  1226. Latitude[i] = latItem->valuedouble;
  1227. }
  1228. // 解析 polygonLng 数组
  1229. for (int i = 0; i < polygonLngSize; ++i) {
  1230. cJSON *lngItem = cJSON_GetArrayItem(polygonLng, i);
  1231. if (lngItem == NULL || lngItem->type != cJSON_Number) {
  1232. // printf("Lng item is not a number or is missing\n");
  1233. return 0;
  1234. }
  1235. Longitude[i] = lngItem->valuedouble;
  1236. }
  1237. // // 解析 speedLimit 字段
  1238. // cJSON* speedLimit = cJSON_GetObjectItem(root, "speedLimit");
  1239. // if (speedLimit == NULL) {
  1240. // printf("Field \"speedLimit\" not found\n");
  1241. // return 0;
  1242. // }else{
  1243. // s_param_boot.speed_limit = speedLimit->valueint;
  1244. // }
  1245. //
  1246. // // 解析 overspeedTimeout 字段
  1247. // cJSON* overspeedTimeout = cJSON_GetObjectItem(root, "overspeedTimeout");
  1248. // if (speedLimit == NULL) {
  1249. // printf("Field \"overspeedTimeout\" not found\n");
  1250. // return 0;
  1251. // }else{
  1252. // s_param_boot.overspeed_Timeout = speedLimit->valueint;
  1253. // }
  1254. //
  1255. // // 解析 fenceBreachTimeout 字段
  1256. // cJSON* fenceBreachTimeout = cJSON_GetObjectItem(root, "fenceBreachTimeout");
  1257. // if (speedLimit == NULL) {
  1258. // printf("Field \"fenceBreachTimeout\" not found\n");
  1259. // return 0;
  1260. // }else{
  1261. // s_param_boot.fenceBreach_Timeout = speedLimit->valueint;
  1262. // }
  1263. //
  1264. return 1; // 成功
  1265. }
  1266. /**
  1267. * @brief 解析登录响应
  1268. * @note
  1269. * @return
  1270. */
  1271. void parse_Login_Response(cJSON *root, cJSON *item){
  1272. // 获取"name"字段的值
  1273. item = cJSON_GetObjectItem(root, "resultCode");
  1274. if (item == NULL) {
  1275. // printf("Field \"resultCode\" not found\n");
  1276. }else{
  1277. // 打印"name"字段的值
  1278. // printf("resultCode: %d\n", item->valueint);
  1279. if((item->valueint) == 1){
  1280. s_messageDate.loginResult = 1; // 登录成功
  1281. // printf("Login response data successfully\n");
  1282. }else{
  1283. // printf("Login response has failed\n");
  1284. }
  1285. }
  1286. }
  1287. /**
  1288. * @brief 解析远程控制指令
  1289. * @note
  1290. * @return
  1291. */
  1292. void processRemoteControl(cJSON *root, cJSON *item){
  1293. global_par *p_global_par = &s_global_par;
  1294. // 解析paramList
  1295. cJSON* paramList = cJSON_GetObjectItem(root, "paramList");
  1296. if (cJSON_GetArraySize(paramList) == 0) {
  1297. // printf("paramList is empty\n");
  1298. return;
  1299. }
  1300. cJSON* firstParam = cJSON_GetArrayItem(paramList, 0);
  1301. if (!firstParam) {
  1302. // printf("paramList is empty\n");
  1303. return;
  1304. }
  1305. // 解析paramList中的第一个元素
  1306. cJSON* id = cJSON_GetObjectItem(firstParam, "id");
  1307. if (item == NULL){
  1308. // printf("id is not a string\n");
  1309. return;
  1310. }else{
  1311. // printf("id: %d\n", id->valueint);
  1312. }
  1313. item = cJSON_GetObjectItem(firstParam, "value");
  1314. if (item == NULL){
  1315. // printf("value is not a string\n");
  1316. return;
  1317. }else{
  1318. // printf("value: %d\n", item->valueint);
  1319. }
  1320. // 解析指令
  1321. switch(id->valueint){
  1322. case 0: // 超级权限
  1323. p_global_par->superUser = (item->valueint == 1);
  1324. break;
  1325. case 1: // 更新围栏数据
  1326. p_global_par->fence_update = (item->valueint == 1);
  1327. break;
  1328. case 2: // 车辆限速
  1329. s_param_boot.speed_limit = item->valueint;
  1330. break;
  1331. case 3: // 锁车
  1332. s_param_boot.car_lock_flag = (item->valueint == 1);
  1333. break;
  1334. default: break;
  1335. }
  1336. }
  1337. /**
  1338. * @brief 通信响应解析
  1339. * @param p_ec800Date: ec800Date结构体的指针数据
  1340. * @note
  1341. * @return 当前的控制命令
  1342. */
  1343. short EC800_respondParse(ec800Date *p_ec800Date){
  1344. cJSON *root = NULL;
  1345. cJSON *item = NULL;
  1346. uint8_t rec_back = 0;
  1347. uint16_t cmd = 0;
  1348. // 找到JSON数据的起始位置
  1349. const char* start = strchr(g_usart4_rx_buf, '{');
  1350. if (start == NULL) {
  1351. // printf("JSON data not found\n");
  1352. cJSON_Delete(root);
  1353. return 0;
  1354. }
  1355. // 解析JSON数据
  1356. root = cJSON_Parse(start);
  1357. if (root == NULL) {
  1358. // printf("Failed to parse JSON data\n");
  1359. cJSON_Delete(root);
  1360. return 0;
  1361. }
  1362. // 获取"controlCode"字段的值
  1363. item = cJSON_GetObjectItem(root, "controlCode");
  1364. if (item == NULL) {
  1365. // printf("Field \"devId\" not found\n");
  1366. }else{
  1367. // 打印"controlCode"字段的值
  1368. // printf("controlCode: %d\n", item->valueint);
  1369. cmd = item->valueint;
  1370. }
  1371. // 解析对应命令的对应数据
  1372. switch(cmd){
  1373. case 102:
  1374. parse_Login_Response(root, item);
  1375. break;
  1376. case 106:
  1377. EC800_parseRespondTime(root, item);
  1378. break;
  1379. case 202:
  1380. EC800_respondRealDate(root, item);
  1381. break;
  1382. case 602:
  1383. EC800_respondUpdateDate(root, item, &s_ftpInfo);
  1384. break;
  1385. case 605:
  1386. rec_back = parse_Latitude_Longitude_Data(root, polygonLat, polygonLng);
  1387. if(rec_back == 1){ // 接收成功
  1388. p_ec800Date->fenceRecSuccess = 1;
  1389. }
  1390. break;
  1391. case 502: // 告警响应
  1392. break;
  1393. case 601: // 远程控制
  1394. processRemoteControl(root, item);
  1395. break;
  1396. default :
  1397. break;
  1398. }
  1399. cJSON_Delete(root);
  1400. return (cmd);
  1401. }
  1402. //----------------------------------------------------------------------------------------------
  1403. // 第二部分 应用部分的外部接口
  1404. uint8_t stateStep = 0;
  1405. uint16_t timesCnt = 0; // 实时发送计数器
  1406. uint8_t respondSt = 0; // 响应状态指示 1: 为等待响应 2:成功响应
  1407. /**
  1408. * @brief EC800M状态转换与使用
  1409. * @note
  1410. * @retval 无
  1411. */
  1412. void EC800_stateTransition_use(void){
  1413. uint16_t right = 1; // 返回是否为正确
  1414. ec800Date *p_ec800Date = &s_ec800Date;
  1415. char command[100] = {0};
  1416. static uint8_t interCnt = 0; // 当前区间进入次数
  1417. global_par *p_global_par = &s_global_par;
  1418. static char errrCnt = 0; // 错误计数
  1419. switch(stateStep){
  1420. case 0: // 初始化模块
  1421. interCnt++;
  1422. EC800M_link();
  1423. // 初始化连接MQTT失败
  1424. if(interCnt > 15){
  1425. interCnt = 16;
  1426. p_global_par->InitFaultFlag_4G = 1;
  1427. }
  1428. // 初始化成功
  1429. if(linkStep == 13){
  1430. interCnt = 0; // 清除进入计数
  1431. p_global_par->InitFaultFlag_4G = 0;
  1432. stateStep = 1;
  1433. p_ec800Date->ec800InitFlag = 1; // 初始化完成
  1434. }else{
  1435. p_ec800Date->ec800InitFlag = 0; // 初始化未完成
  1436. }
  1437. break;
  1438. case 1: // 初始化GNSS
  1439. interCnt++;
  1440. EC800_gnss_init();
  1441. // 初始化GNSS失败
  1442. if(interCnt > 12){
  1443. interCnt = 16;
  1444. p_global_par->InitFaultFlag_4G = 1;
  1445. }
  1446. if(gnssStep == 8){
  1447. stateStep = 2;
  1448. interCnt = 0; // 清除进入计数
  1449. p_global_par->InitFaultFlag_4G = 0;
  1450. }
  1451. break;
  1452. case 2: // 订阅主题
  1453. sprintf(command, "toclient/%d/%x%x%x", DEV_TYPE, s_messageDate.devId[0], s_messageDate.devId[1], s_messageDate.devId[2]);
  1454. right = EC800_subscribeToTopic(command);
  1455. // 模块应答错误
  1456. if (right != 1) {
  1457. if (++errrCnt > task_upload_times_2s) {
  1458. errrCnt = task_upload_times_2s;
  1459. p_global_par->subscribe_fail = 1;
  1460. }
  1461. } else { // 模块应答正确
  1462. errrCnt = 0;
  1463. p_global_par->subscribe_fail = 0;
  1464. stateStep = 3;
  1465. }
  1466. break;
  1467. case 3: // 登录服务器主题
  1468. right = Login_Topic();
  1469. // 模块应答错误
  1470. if (right != 1) {
  1471. if (++errrCnt > task_upload_times_2s) {
  1472. errrCnt = task_upload_times_2s;
  1473. p_global_par->publish_fail = 1;
  1474. }
  1475. } else { // 模块应答正确
  1476. errrCnt = 0;
  1477. p_global_par->publish_fail = 0;
  1478. respondSt = 1; // 等待响应
  1479. stateStep = 8; // 去步骤6等待登录响应 收到登录响应后,发布实时消息
  1480. }
  1481. break;
  1482. case 4: // 下位机请求围栏数据
  1483. if(s_comData.vinRecSuccess == 1){ // 成功接收到车辆vin
  1484. right = requesting_Fence_Data();
  1485. // 模块应答错误
  1486. if (right != 1) {
  1487. if (++errrCnt > task_upload_times_2s) {
  1488. errrCnt = task_upload_times_2s;
  1489. p_global_par->publish_fail = 1;
  1490. }
  1491. } else { // 模块应答正确
  1492. errrCnt = 0;
  1493. p_global_par->publish_fail = 0;
  1494. respondSt = 1; // 等待响应
  1495. stateStep = 8; // 去步骤6等待登录响应 收到登录响应后,发布实时消息
  1496. }
  1497. }else{ // 初始化时与车通信故障 跳转上传实时信息,上报故障,跳过围栏获取
  1498. if(BIT_CHECK(s_comData.Malfunction, com485)){
  1499. stateStep = 5;
  1500. }
  1501. }
  1502. // 后台要求重新请求围栏数据,请求完成,清除标志
  1503. if(p_global_par->fence_update == 1){
  1504. p_global_par->fence_update = 0;
  1505. }
  1506. break;
  1507. case 5: // 与服务器对时
  1508. right = EC800_time_calibration();
  1509. // 模块应答错误
  1510. if (right != 1) {
  1511. if (++errrCnt > task_upload_times_2s) {
  1512. errrCnt = task_upload_times_2s;
  1513. p_global_par->publish_fail = 1;
  1514. }
  1515. } else { // 模块应答正确
  1516. errrCnt = 0;
  1517. p_global_par->publish_fail = 0;
  1518. respondSt = 1; // 等待响应
  1519. stateStep = 8; // 去步骤6等待登录响应 收到登录响应后,发布实时消息
  1520. }
  1521. break;
  1522. case 6:
  1523. // 检测模块信号
  1524. ModuleSigCheck(g_usart4_rx_buf);
  1525. // 获取定位信息
  1526. right = EC800_readGnssDate();
  1527. // 模块应答错误
  1528. if (right != 1) {
  1529. if (++errrCnt > task_upload_times_2s) {
  1530. errrCnt = task_upload_times_2s;
  1531. p_global_par->get_location_error = 1;
  1532. }
  1533. } else { // 模块应答正确
  1534. errrCnt = 0;
  1535. p_global_par->get_location_error = 0;
  1536. stateStep = 8; // 去步骤6等待登录响应 收到登录响应后,发布实时消息
  1537. }
  1538. // 时间数据是否获取到
  1539. s_global_par.time_stamp_flag = (right == 1);
  1540. // 没有获取到定位信息 重复获取三次,网络存在,但gps信息不存在的情况
  1541. if((s_messageDate.latitude == 0) && (s_messageDate.longitude == 0)){
  1542. if(p_global_par->positionErrorCnt < 3){
  1543. p_global_par->positionErrorCnt++;
  1544. }else{
  1545. p_global_par->positionErrorCnt = 3;
  1546. stateStep = 7;
  1547. }
  1548. }else{
  1549. p_global_par->positionErrorCnt = 0;
  1550. stateStep = 7;
  1551. }
  1552. break;
  1553. case 7: // 发布消息
  1554. right = EC800_uploadRealDate();
  1555. // 模块应答错误
  1556. if (right != 1) {
  1557. if (++errrCnt > task_upload_times_2s) {
  1558. errrCnt = task_upload_times_2s;
  1559. p_global_par->publish_fail = 1;
  1560. }
  1561. } else { // 模块应答正确
  1562. errrCnt = 0;
  1563. p_global_par->publish_fail = 0;
  1564. stateStep = 8; // 去步骤6等待登录响应 收到登录响应后,发布实时消息
  1565. }
  1566. break;
  1567. case 8: // 接收消息
  1568. // 转弯行驶中
  1569. if(turnFlag == 1){
  1570. if(timesCnt < TURN_INTERVAL_TIME_MS){
  1571. timesCnt++;
  1572. }else{
  1573. timesCnt= 0;
  1574. stateStep = 6;
  1575. HAL_UART_DMAStop(&huart4);
  1576. HAL_UART_Receive_DMA(&huart4, (uint8_t*)g_usart4_rx_buf, USART4_REC_LEN); //设置接收缓冲区
  1577. }
  1578. }else{ // 正常行驶中
  1579. if(timesCnt < PUBLISH_TIME_MS){
  1580. timesCnt++;
  1581. }else{
  1582. timesCnt= 0;
  1583. stateStep = 6;
  1584. HAL_UART_DMAStop(&huart4);
  1585. HAL_UART_Receive_DMA(&huart4, (uint8_t*)g_usart4_rx_buf, USART4_REC_LEN); //设置接收缓冲区
  1586. }
  1587. }
  1588. // 后台要求重新请求围栏数据或者初始化获取到vin请求围栏数据
  1589. if((p_global_par->fence_update == 1) || ((s_comData.vinRecSuccess == 1) && (p_ec800Date->fenceRecSuccess == 0))){
  1590. stateStep = 4;
  1591. }
  1592. // 通信超时判断
  1593. if(respondSt == 1){ // 等待响应状态
  1594. if(p_global_par->mqttTimeoutCnt < PUBLISH_TIME_MS){
  1595. p_global_par->mqttTimeoutCnt ++;
  1596. }else{
  1597. p_global_par->mqttTimeoutCnt = PUBLISH_TIME_MS;
  1598. }
  1599. }else{
  1600. p_global_par->mqttTimeoutCnt = 0;
  1601. }
  1602. // 当MQTT通信异常且gnss回复错误的情况下,4g模块可能断线,重新连接4G模块
  1603. // stateStep = 0;
  1604. // linkStep = 0;
  1605. // gnssStep = 0;
  1606. break;
  1607. default:
  1608. break;
  1609. }
  1610. }
  1611. /**
  1612. * @brief 解析MQTT 链路层状态变化的 URC
  1613. * @note +QMTSTAT: <client_idx>,<err_code> err_code不为0,则重新连接
  1614. * @retval 无
  1615. */
  1616. void parse_mqttUrc(void){
  1617. int val1, val2 = 0;
  1618. // 检查字符串是否以"+QMTSTAT: "开头
  1619. if (strncmp(g_usart4_rx_buf, "+QMTSTAT: ", 10) == 0) {
  1620. // 使用sscanf从字符串中解析两个整数
  1621. if (sscanf(g_usart4_rx_buf + 10, "%d,%d", &val1, &val2) == 2) {
  1622. // 如果成功解析出两个整数,则判断
  1623. if(val1 != client_idx){
  1624. return;
  1625. }
  1626. if(val2 != 0){
  1627. // 需重新连接服务器
  1628. s_global_par.reconnect_server_flag = 1;
  1629. Write_paramArea();
  1630. }
  1631. }
  1632. }
  1633. // 如果字符串不符合格式或解析失败,则返回
  1634. return ;
  1635. }
  1636. /**
  1637. * @brief 判断是否执行重连MQTT服务器
  1638. * @note
  1639. * @retval 无
  1640. */
  1641. void reconnect_mqtt_server(void){
  1642. // 发布消息失败
  1643. if((BIT_CHECK(s_comData.Malfunction, publishFail))
  1644. || (BIT_CHECK(s_comData.Malfunction, subscribeFail))
  1645. || (BIT_CHECK(s_comData.Malfunction, getLocationError))
  1646. ){
  1647. BIT_CLEAR(s_comData.Malfunction, publishFail);
  1648. BIT_CLEAR(s_comData.Malfunction, subscribeFail);
  1649. s_global_par.subscribe_fail = 0;
  1650. s_global_par.publish_fail = 0;
  1651. s_global_par.get_location_error = 0;
  1652. BIT_CLEAR(s_comData.Malfunction, getLocationError);
  1653. // 步骤与标志清零
  1654. stateStep = 0;
  1655. linkStep = 0;
  1656. gnssStep = 0;
  1657. s_ec800Date.ec800InitFlag = 0;
  1658. }
  1659. }
  1660. /**
  1661. * @brief MQTT服务器数据接收处理
  1662. * @note
  1663. * @retval 无
  1664. */
  1665. void handleReceive(void) {
  1666. uint16_t right = 1; // 返回是否为正确
  1667. if(g_usart4_rx_sta!=0){
  1668. // HAL_UART_Transmit(&huart1, (uint8_t*)g_usart4_rx_buf, strlen(g_usart4_rx_buf), HAL_MAX_DELAY); // 打印数据除去URC
  1669. parse_mqttUrc(); // 解析MQTT 链路层状态变化的 URC
  1670. right = EC800_respondParse(&s_ec800Date);
  1671. if((right == CTR_CODE_LOGIN) && (s_messageDate.loginResult == 1)){ // 登录响应
  1672. stateStep = 4;
  1673. right = 0;
  1674. timesCnt = 0;
  1675. respondSt = 2; // 成功响应
  1676. }else if(right == CTR_CODE_LOGIN){ // 登录响应 未登录成功
  1677. stateStep = 3;
  1678. right = 0;
  1679. timesCnt = 0;
  1680. respondSt = 2; // 成功响应
  1681. }else if(right == CTR_CODE_FENCES){ // 围栏数据响应
  1682. stateStep = 5;
  1683. right = 0;
  1684. timesCnt = 0;
  1685. respondSt = 2; // 成功响应
  1686. }
  1687. else if(right == CTR_CODE_JUDETIME){ // 对时响应
  1688. stateStep = 6;
  1689. right = 0;
  1690. // timesCnt = 0;
  1691. respondSt = 2; // 成功响应
  1692. }else if((right == CTR_CODE_REMOTE) && (s_ec800Date.hardwareUpdate == 1)){ // 固件更新
  1693. stateStep = 0xff; // 停止占用4G模块
  1694. }
  1695. memset(g_usart4_rx_buf, 0, USART4_REC_LEN); // 清除数据buff,接收新的数据
  1696. g_usart4_rx_sta = 0; // 清除接收状态
  1697. HAL_UART_DMAStop(&huart4);
  1698. HAL_UART_Receive_DMA(&huart4, (uint8_t*)g_usart4_rx_buf, USART4_REC_LEN); //设置接收缓冲区
  1699. }
  1700. }