Guest User

Untitled

a guest
Oct 6th, 2018
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.35 KB | None | 0 0
  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. #include "string.h"
  4. //#include <syswait.h>
  5. #include <unistd.h>
  6. #include "MQTTAsync.h"
  7. #include "pthread.h"
  8. #include "semaphore.h"
  9. #include "time.h"
  10. #include <sys/timeb.h>
  11. /////////////////////////////
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <fcntl.h>
  15. #include <termios.h>
  16. #include "cJSON.h"
  17. #include "rs232.h"
  18. #include <unistd.h>
  19.  
  20. #define BUF_SIZE 128
  21.  
  22. #define BAUDRATE B115200
  23. #define UART_DEVICE "/dev/ttyACM0"
  24.  
  25. #define FALSE -1
  26. #define TRUE 0
  27. ///////////////////////////
  28. #define ADDRESS "a1GF0OZsn2q.iot-as-mqtt.cn-shanghai.aliyuncs.com"
  29. #define CLIENTID "123458|securemode=3,signmethod=hmacsha1|"
  30. #define TOPIC "/a1GF0OZsn2q/flywish/ctldata"
  31. #define PAYLOAD "Hello World + yhq!"
  32. #define QOS 0
  33. #define TIMEOUT 10000L
  34.  
  35. pthread_mutex_t work_mutex;
  36. int ser_in_work=0;
  37. long long now,idletime=0;
  38. long long start_time;
  39. int colors[3];
  40. int new_data_flag = 0;
  41. int disc_finished = 0;
  42. int finished = 0;
  43. int subscribed = 0;
  44.  
  45. volatile MQTTAsync_token deliveredtoken;
  46. //////////////////////////////
  47.  
  48. /////////////////////////////////////////
  49.  
  50. long long getSystemTime() {
  51. struct timeb t;
  52. ftime(&t);
  53. //printf("now:%ld\n", t.time);
  54. return 1000 * t.time + t.millitm;
  55. }
  56.  
  57. ///////////////////////////////////////////
  58. void onDisconnect(void* context, MQTTAsync_successData* response)
  59. {
  60. printf("Successful disconnection\n");
  61. disc_finished = 1;
  62. }
  63. void onConnectFailure(void* context, MQTTAsync_failureData* response)
  64. {
  65. printf("Connect failed, rc %d\n", response ? response->code : 0);
  66. finished = 1;
  67. }
  68. void onSubscribe(void* context, MQTTAsync_successData* response)
  69. {
  70. printf("Subscribe succeeded\n");
  71. subscribed = 1;
  72. }
  73. void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
  74. {
  75. printf("Subscribe failed, rc %d\n", response ? response->code : 0);
  76. finished = 1;
  77. }
  78. void onConnect(void* context, MQTTAsync_successData* response)
  79. {
  80. MQTTAsync client = (MQTTAsync)context;
  81. MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
  82. MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
  83. int rc;
  84. printf("Successful connection\n");
  85. printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
  86. "Press Q<Enter> to quit\n\n",
  87. TOPIC,
  88. CLIENTID,
  89. QOS);
  90. opts.onSuccess = onSubscribe;
  91. opts.onFailure = onSubscribeFailure;
  92. opts.context = client;
  93. deliveredtoken = 0;
  94. if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
  95. {
  96. printf("Failed to start subscribe, return code %d\n", rc);
  97. exit(EXIT_FAILURE);
  98. }
  99. }
  100.  
  101. int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
  102. {
  103. int i;
  104. char* payloadptr;
  105. cJSON *json, *result, *colours_value;
  106. printf("Message arrived\n");
  107. printf(" topic: %s\n", topicName);
  108. printf(" message: ");
  109. payloadptr = message->payload;
  110.  
  111. json = cJSON_Parse(payloadptr);
  112. if (!json)
  113. {
  114. printf("Error before: [%s]\n", cJSON_GetErrorPtr());
  115. return -1;
  116. }
  117. else
  118. {
  119. result = cJSON_GetObjectItem(json, "type");
  120. if (cJSON_IsString(result) && (result->valuestring != NULL))
  121. {
  122. if (strcmp(result->valuestring, "1") == 0)//mqtt 开始信息
  123. {
  124. pthread_mutex_lock(&work_mutex);//lock
  125. ser_in_work = 1;
  126. colors[0] = 255;
  127. colors[1] = 255;
  128. colors[2] = 255;
  129. new_data_flag = 1;
  130. start_time = getSystemTime();
  131. printf("incoming data is 1\n");
  132. pthread_mutex_unlock(&work_mutex); //unlock
  133. sleep(0);
  134. printf("time: %lld ms\n", start_time);
  135. }
  136. else if(strcmp(result->valuestring, "2") == 0)//mqtt 控制信息
  137. {
  138. //pthread_mutex_lock(&work_mutex); //lock
  139. if (ser_in_work == 0)
  140. {
  141.  
  142. //报告错误error1
  143. start_time = getSystemTime();
  144. ser_in_work = 1;
  145.  
  146. printf("error:1");
  147. }
  148. printf("incoming data is 2\n");
  149. colours_value = cJSON_GetObjectItem(json, "R");
  150. //if (cJSON_IsNumber(colours_value) && (colours_value->valuestring != NULL))
  151. {
  152. colors[0] = colours_value->valueint;
  153. //printf("%d",r);
  154. }
  155. colours_value = cJSON_GetObjectItem(json, "G");
  156. //if (cJSON_IsNumber(colours_value) && (colours_value->valuestring != NULL))
  157. {
  158. colors[1] = colours_value->valueint;
  159. //printf("%d", g);
  160. }
  161. colours_value = cJSON_GetObjectItem(json, "B");
  162. //if (cJSON_IsNumber(colours_value) && (colours_value->valuestring != NULL))
  163. {
  164. colors[2] = colours_value->valueint;
  165. //printf("%d\n", b);
  166. }
  167. new_data_flag = 1;
  168. //pthread_mutex_unlock(&work_mutex); //unlock
  169. //sleep(0);
  170.  
  171. }
  172. else if(strcmp(result->valuestring, "3") == 0)//mqt 停止信息
  173. {
  174. printf("incoming data is 3\n");
  175. pthread_mutex_lock(&work_mutex); //lock
  176. ser_in_work = 0;
  177. pthread_mutex_unlock(&work_mutex); //unlock
  178. //sleep(0);
  179. }
  180. else
  181. {
  182. printf("incoming data is erro\n");
  183. pthread_mutex_lock(&work_mutex); //lock
  184. ser_in_work = 0;
  185. pthread_mutex_unlock(&work_mutex); //unlock
  186. //sle
  187. }
  188.  
  189. }
  190. }
  191.  
  192. //time(&start_time);
  193. //printf("now:%ld\n", start_time);
  194.  
  195. //start_time = getSystemTime();
  196. //printf("time: %lld ms\n", start_time);
  197.  
  198. //
  199. // cJSON_Delete(result);
  200. //
  201. // cJSON_Delete(json);
  202. // cJSON_Delete(colours_value);
  203.  
  204.  
  205. // MQTTClient_freeMessage(&message);
  206. // MQTTClient_free(topicName);
  207. MQTTAsync_freeMessage(&message);
  208. MQTTAsync_free(topicName);
  209. return 1;
  210. }
  211. void connlost(void *context, char *cause)
  212. {
  213.  
  214. MQTTAsync client = (MQTTAsync)context;
  215. MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
  216. int rc;
  217. printf("\nConnection lost\n");
  218. printf(" cause: %s\n", cause);
  219. printf("Reconnecting\n");
  220. conn_opts.keepAliveInterval = 60;
  221. conn_opts.cleansession = 1;
  222. if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
  223. {
  224. printf("Failed to start connect, return code %d\n", rc);
  225. finished = 1;
  226. }
  227. }
  228. int main(int argc, char* argv[])
  229. {
  230.  
  231. unsigned char str_recv[BUF_SIZE]; // recv data buffer
  232. int i = 0;
  233. int cport_nr = 24; /* /dev/ttyUSB0 */
  234. int bdrate = 9600; /* 9600 baud */
  235.  
  236. char mode[] = { '8', 'N', '1', 0 }; // 8 data bits, no parity, 1 stop bit
  237.  
  238. if(RS232_OpenComport(cport_nr, bdrate, mode))
  239. {
  240. printf("Can not open comport\n");
  241. return (0);
  242. }
  243. sleep(2); /* waits 2000ms for stable condition */
  244.  
  245.  
  246.  
  247. //////////////new uart end ////////////////////////////////
  248. int ch;
  249. int rc;
  250. rc = pthread_mutex_init(&work_mutex, NULL);
  251.  
  252. MQTTAsync client;
  253. MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
  254. MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
  255. MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
  256. MQTTAsync_token token;
  257.  
  258. MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
  259. conn_opts.keepAliveInterval = 60;
  260. conn_opts.cleansession = 1;
  261. conn_opts.onSuccess = onConnect;
  262. conn_opts.onFailure = onConnectFailure;
  263. conn_opts.context = client;
  264. conn_opts.automaticReconnect = 1;
  265. conn_opts.connectTimeout = 3;
  266. conn_opts.username = "flywish&a1GF0OZsn2q";
  267. conn_opts.password = "47C160B9936A2F30D607DC066B518EA0CD7B5017";
  268.  
  269. MQTTAsync_setCallbacks(client, NULL, connlost, msgarrvd, NULL);
  270.  
  271. if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
  272. {
  273. printf("Failed to connect, return code %d\n", rc);
  274. exit(-1);
  275. }
  276. while (!subscribed)
  277.  
  278. sleep(1);
  279.  
  280. // printf("Waiting for up to %d seconds for publication of %s\n"
  281. // "on topic %s for client with ClientID: %s\n",
  282. // (int)(TIMEOUT / 1000),
  283. // PAYLOAD,
  284. // TOPIC,
  285. // CLIENTID);
  286. //rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
  287. //pthead_mutex_lock(&work_mutex);
  288.  
  289. while(1)
  290. {
  291.  
  292.  
  293. if(ser_in_work==1)
  294. {
  295. //printf(" work!\n");
  296.  
  297. if (new_data_flag == 1)
  298. {
  299.  
  300. new_data_flag = 0;
  301. char send_buf[100];
  302. int offset = 0;
  303. pthread_mutex_lock(&work_mutex); //lock
  304. for (int i = 0; i < 3; i++)
  305. {
  306. offset += sprintf(send_buf + offset, "%d,", colors[i]);
  307. }
  308. pthread_mutex_unlock(&work_mutex); //unlock
  309. send_buf[offset - 1] = '\n';
  310. //printf("show data\n");
  311. // printf(send_buf);
  312. // len = UART0_Send(fd, send_buf, strlen(send_buf));
  313. RS232_cputs(cport_nr, send_buf); // sends string on serial
  314. }
  315.  
  316.  
  317.  
  318.  
  319. now = getSystemTime();
  320. if (now >= start_time + 70000)
  321. {
  322. pthread_mutex_lock(&work_mutex); //lock
  323. ser_in_work = 0;
  324. pthread_mutex_unlock(&work_mutex); //unlock
  325. }
  326.  
  327. }
  328. else
  329. {
  330. now = getSystemTime();
  331. if (now>=idletime+2000)
  332. {
  333. idletime = now;
  334. //printf("un work!\n");
  335. char send_buf[30] = "0,0,255";
  336. char end_buf1[2] = "\n";
  337. strcat(send_buf, end_buf1);
  338. //printf("RGB data is: %s", send_buf);
  339. pthread_mutex_lock(&work_mutex); //lock
  340. RS232_cputs(cport_nr, send_buf);
  341. pthread_mutex_unlock(&work_mutex); //unlock
  342. //printf("UART send %d char\n", len);
  343. }
  344.  
  345.  
  346. }
  347. sleep(1); /* waits for reply 1000ms */
  348. int n = RS232_PollComport(cport_nr, str_recv, (int)BUF_SIZE);
  349. if (n > 0) {
  350. str_recv[n] = 0; /* always put a "null" at the end of a string! */
  351. //printf("Received %i bytes: '%s'\n", n, (char *)str_recv);
  352. }
  353.  
  354. sleep(0);
  355. }
  356. //for(;;);
  357. // printf("Message with delivery token %d delivered\n", token);
  358. disc_opts.onSuccess = onDisconnect;
  359. if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
  360. {
  361. printf("Failed to start disconnect, return code %d\n", rc);
  362. exit(EXIT_FAILURE);
  363. }
  364. while (!disc_finished)
  365. #if defined(WIN32) || defined(WIN64)
  366. Sleep(100);
  367. #else
  368. sleep(1);
  369. #endif
  370. MQTTAsync_destroy(&client);
  371. return rc;
  372. }
Add Comment
Please, Sign In to add comment