Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdio.h"
- #include "stdlib.h"
- #include "string.h"
- //#include <syswait.h>
- #include <unistd.h>
- #include "MQTTAsync.h"
- #include "pthread.h"
- #include "semaphore.h"
- #include "time.h"
- #include <sys/timeb.h>
- /////////////////////////////
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <termios.h>
- #include "cJSON.h"
- #include "rs232.h"
- #include <unistd.h>
- #define BUF_SIZE 128
- #define BAUDRATE B115200
- #define UART_DEVICE "/dev/ttyACM0"
- #define FALSE -1
- #define TRUE 0
- ///////////////////////////
- #define ADDRESS "a1GF0OZsn2q.iot-as-mqtt.cn-shanghai.aliyuncs.com"
- #define CLIENTID "123458|securemode=3,signmethod=hmacsha1|"
- #define TOPIC "/a1GF0OZsn2q/flywish/ctldata"
- #define PAYLOAD "Hello World + yhq!"
- #define QOS 0
- #define TIMEOUT 10000L
- pthread_mutex_t work_mutex;
- int ser_in_work=0;
- long long now,idletime=0;
- long long start_time;
- int colors[3];
- int new_data_flag = 0;
- int disc_finished = 0;
- int finished = 0;
- int subscribed = 0;
- volatile MQTTAsync_token deliveredtoken;
- //////////////////////////////
- /////////////////////////////////////////
- long long getSystemTime() {
- struct timeb t;
- ftime(&t);
- //printf("now:%ld\n", t.time);
- return 1000 * t.time + t.millitm;
- }
- ///////////////////////////////////////////
- void onDisconnect(void* context, MQTTAsync_successData* response)
- {
- printf("Successful disconnection\n");
- disc_finished = 1;
- }
- void onConnectFailure(void* context, MQTTAsync_failureData* response)
- {
- printf("Connect failed, rc %d\n", response ? response->code : 0);
- finished = 1;
- }
- void onSubscribe(void* context, MQTTAsync_successData* response)
- {
- printf("Subscribe succeeded\n");
- subscribed = 1;
- }
- void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
- {
- printf("Subscribe failed, rc %d\n", response ? response->code : 0);
- finished = 1;
- }
- void onConnect(void* context, MQTTAsync_successData* response)
- {
- MQTTAsync client = (MQTTAsync)context;
- MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
- MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
- int rc;
- printf("Successful connection\n");
- printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
- "Press Q<Enter> to quit\n\n",
- TOPIC,
- CLIENTID,
- QOS);
- opts.onSuccess = onSubscribe;
- opts.onFailure = onSubscribeFailure;
- opts.context = client;
- deliveredtoken = 0;
- if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
- {
- printf("Failed to start subscribe, return code %d\n", rc);
- exit(EXIT_FAILURE);
- }
- }
- int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
- {
- int i;
- char* payloadptr;
- cJSON *json, *result, *colours_value;
- printf("Message arrived\n");
- printf(" topic: %s\n", topicName);
- printf(" message: ");
- payloadptr = message->payload;
- json = cJSON_Parse(payloadptr);
- if (!json)
- {
- printf("Error before: [%s]\n", cJSON_GetErrorPtr());
- return -1;
- }
- else
- {
- result = cJSON_GetObjectItem(json, "type");
- if (cJSON_IsString(result) && (result->valuestring != NULL))
- {
- if (strcmp(result->valuestring, "1") == 0)//mqtt 开始信息
- {
- pthread_mutex_lock(&work_mutex);//lock
- ser_in_work = 1;
- colors[0] = 255;
- colors[1] = 255;
- colors[2] = 255;
- new_data_flag = 1;
- start_time = getSystemTime();
- printf("incoming data is 1\n");
- pthread_mutex_unlock(&work_mutex); //unlock
- sleep(0);
- printf("time: %lld ms\n", start_time);
- }
- else if(strcmp(result->valuestring, "2") == 0)//mqtt 控制信息
- {
- //pthread_mutex_lock(&work_mutex); //lock
- if (ser_in_work == 0)
- {
- //报告错误error1
- start_time = getSystemTime();
- ser_in_work = 1;
- printf("error:1");
- }
- printf("incoming data is 2\n");
- colours_value = cJSON_GetObjectItem(json, "R");
- //if (cJSON_IsNumber(colours_value) && (colours_value->valuestring != NULL))
- {
- colors[0] = colours_value->valueint;
- //printf("%d",r);
- }
- colours_value = cJSON_GetObjectItem(json, "G");
- //if (cJSON_IsNumber(colours_value) && (colours_value->valuestring != NULL))
- {
- colors[1] = colours_value->valueint;
- //printf("%d", g);
- }
- colours_value = cJSON_GetObjectItem(json, "B");
- //if (cJSON_IsNumber(colours_value) && (colours_value->valuestring != NULL))
- {
- colors[2] = colours_value->valueint;
- //printf("%d\n", b);
- }
- new_data_flag = 1;
- //pthread_mutex_unlock(&work_mutex); //unlock
- //sleep(0);
- }
- else if(strcmp(result->valuestring, "3") == 0)//mqt 停止信息
- {
- printf("incoming data is 3\n");
- pthread_mutex_lock(&work_mutex); //lock
- ser_in_work = 0;
- pthread_mutex_unlock(&work_mutex); //unlock
- //sleep(0);
- }
- else
- {
- printf("incoming data is erro\n");
- pthread_mutex_lock(&work_mutex); //lock
- ser_in_work = 0;
- pthread_mutex_unlock(&work_mutex); //unlock
- //sle
- }
- }
- }
- //time(&start_time);
- //printf("now:%ld\n", start_time);
- //start_time = getSystemTime();
- //printf("time: %lld ms\n", start_time);
- //
- // cJSON_Delete(result);
- //
- // cJSON_Delete(json);
- // cJSON_Delete(colours_value);
- // MQTTClient_freeMessage(&message);
- // MQTTClient_free(topicName);
- MQTTAsync_freeMessage(&message);
- MQTTAsync_free(topicName);
- return 1;
- }
- void connlost(void *context, char *cause)
- {
- MQTTAsync client = (MQTTAsync)context;
- MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
- int rc;
- printf("\nConnection lost\n");
- printf(" cause: %s\n", cause);
- printf("Reconnecting\n");
- conn_opts.keepAliveInterval = 60;
- conn_opts.cleansession = 1;
- if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
- {
- printf("Failed to start connect, return code %d\n", rc);
- finished = 1;
- }
- }
- int main(int argc, char* argv[])
- {
- unsigned char str_recv[BUF_SIZE]; // recv data buffer
- int i = 0;
- int cport_nr = 24; /* /dev/ttyUSB0 */
- int bdrate = 9600; /* 9600 baud */
- char mode[] = { '8', 'N', '1', 0 }; // 8 data bits, no parity, 1 stop bit
- if(RS232_OpenComport(cport_nr, bdrate, mode))
- {
- printf("Can not open comport\n");
- return (0);
- }
- sleep(2); /* waits 2000ms for stable condition */
- //////////////new uart end ////////////////////////////////
- int ch;
- int rc;
- rc = pthread_mutex_init(&work_mutex, NULL);
- MQTTAsync client;
- MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
- MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
- MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
- MQTTAsync_token token;
- MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
- conn_opts.keepAliveInterval = 60;
- conn_opts.cleansession = 1;
- conn_opts.onSuccess = onConnect;
- conn_opts.onFailure = onConnectFailure;
- conn_opts.context = client;
- conn_opts.automaticReconnect = 1;
- conn_opts.connectTimeout = 3;
- conn_opts.username = "flywish&a1GF0OZsn2q";
- conn_opts.password = "47C160B9936A2F30D607DC066B518EA0CD7B5017";
- MQTTAsync_setCallbacks(client, NULL, connlost, msgarrvd, NULL);
- if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
- {
- printf("Failed to connect, return code %d\n", rc);
- exit(-1);
- }
- while (!subscribed)
- sleep(1);
- // printf("Waiting for up to %d seconds for publication of %s\n"
- // "on topic %s for client with ClientID: %s\n",
- // (int)(TIMEOUT / 1000),
- // PAYLOAD,
- // TOPIC,
- // CLIENTID);
- //rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
- //pthead_mutex_lock(&work_mutex);
- while(1)
- {
- if(ser_in_work==1)
- {
- //printf(" work!\n");
- if (new_data_flag == 1)
- {
- new_data_flag = 0;
- char send_buf[100];
- int offset = 0;
- pthread_mutex_lock(&work_mutex); //lock
- for (int i = 0; i < 3; i++)
- {
- offset += sprintf(send_buf + offset, "%d,", colors[i]);
- }
- pthread_mutex_unlock(&work_mutex); //unlock
- send_buf[offset - 1] = '\n';
- //printf("show data\n");
- // printf(send_buf);
- // len = UART0_Send(fd, send_buf, strlen(send_buf));
- RS232_cputs(cport_nr, send_buf); // sends string on serial
- }
- now = getSystemTime();
- if (now >= start_time + 70000)
- {
- pthread_mutex_lock(&work_mutex); //lock
- ser_in_work = 0;
- pthread_mutex_unlock(&work_mutex); //unlock
- }
- }
- else
- {
- now = getSystemTime();
- if (now>=idletime+2000)
- {
- idletime = now;
- //printf("un work!\n");
- char send_buf[30] = "0,0,255";
- char end_buf1[2] = "\n";
- strcat(send_buf, end_buf1);
- //printf("RGB data is: %s", send_buf);
- pthread_mutex_lock(&work_mutex); //lock
- RS232_cputs(cport_nr, send_buf);
- pthread_mutex_unlock(&work_mutex); //unlock
- //printf("UART send %d char\n", len);
- }
- }
- sleep(1); /* waits for reply 1000ms */
- int n = RS232_PollComport(cport_nr, str_recv, (int)BUF_SIZE);
- if (n > 0) {
- str_recv[n] = 0; /* always put a "null" at the end of a string! */
- //printf("Received %i bytes: '%s'\n", n, (char *)str_recv);
- }
- sleep(0);
- }
- //for(;;);
- // printf("Message with delivery token %d delivered\n", token);
- disc_opts.onSuccess = onDisconnect;
- if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
- {
- printf("Failed to start disconnect, return code %d\n", rc);
- exit(EXIT_FAILURE);
- }
- while (!disc_finished)
- #if defined(WIN32) || defined(WIN64)
- Sleep(100);
- #else
- sleep(1);
- #endif
- MQTTAsync_destroy(&client);
- return rc;
- }
Add Comment
Please, Sign In to add comment