uint16_t mqtt_parse_pub_msg_ptr(const uint8_t* buf, const uint8_t **msg_ptr) { uint16_t len = 0; //printf("mqtt_parse_pub_msg_ptr\n"); if(MQTTParseMessageType(buf) == MQTT_MSG_PUBLISH) { // message starts at // fixed header length + Topic (UTF encoded) + msg id (if QoS>0) uint8_t rlb = mqtt_num_rem_len_bytes(buf); uint8_t offset = (*(buf+1+rlb))<<8; // topic UTF MSB offset |= *(buf+1+rlb+1); // topic UTF LSB offset += (1+rlb+2); // fixed header + topic size if(MQTTParseMessageQos(buf)) { offset += 2; // add two bytes of msg id } *msg_ptr = (buf + offset); // offset is now pointing to start of message // length of the message is remaining length - variable header // variable header is offset - fixed header // fixed header is 1 + rlb // so, lom = remlen - (offset - (1+rlb)) len = mqtt_parse_rem_len(buf) - (offset-(rlb+1)); } else { *msg_ptr = NULL; } return len; }
uint16_t mqtt_parse_msg_id(const uint8_t* buf) { uint8_t type = MQTTParseMessageType(buf); uint8_t qos = MQTTParseMessageQos(buf); uint16_t id = 0; //printf("mqtt_parse_msg_id\n"); if(type >= MQTT_MSG_PUBLISH && type <= MQTT_MSG_UNSUBACK) { if(type == MQTT_MSG_PUBLISH) { if(qos != 0) { // fixed header length + Topic (UTF encoded) // = 1 for "flags" byte + rlb for length bytes + topic size uint8_t rlb = mqtt_num_rem_len_bytes(buf); uint8_t offset = *(buf+1+rlb)<<8; // topic UTF MSB offset |= *(buf+1+rlb+1); // topic UTF LSB offset += (1+rlb+2); // fixed header + topic size id = *(buf+offset)<<8; // id MSB id |= *(buf+offset+1); // id LSB } } else { // fixed header length // 1 for "flags" byte + rlb for length bytes uint8_t rlb = mqtt_num_rem_len_bytes(buf); id = *(buf+1+rlb)<<8; // id MSB id |= *(buf+1+rlb+1); // id LSB } } return id; }
// Connect to the MQTT broker. Call this function whenever connection needs // to be re-established. // returns: 0 - everything OK // -1 - packet error // -2 - failed to get connack int App_ConnectMqtt() { int packet_length; mqtt_init(&broker, WIO_CLIENTID); mqtt_init_auth(&broker, WIO_USERNAME, WIO_PASSWORD); mqtt_connect(&broker); // wait for CONNACK packet_length = mqtt_read_packet(6000); if(packet_length < 0) { DisplayLCD(LCD_LINE4, "MQTT packet error"); return -1; } if(MQTTParseMessageType(rxm.message) != MQTT_MSG_CONNACK) { return -2; } if(rxm.message[3] != 0x00) { return -2; } App_PrepareIncomingData(); AtLibGs_FlushIncomingMessage(); mqttConnected=1; return 0; }
/************************************************* * * Function : check mqtt witch qos 1 * packet_bufferBUF: MQTT receive data * packet_length : the packet length * add by Ale lin 2014-04-03 * ***************************************************/ int check_mqttpushqos1( uint8_t *packet_bufferBUF,int packet_length, uint16_t msg_id ) { uint16_t msg_id_rcv; uint8_t *packet_buffer=NULL; packet_buffer = ( uint8_t* )malloc(packet_length); memset( packet_buffer,0,packet_length); memcpy( packet_buffer,packet_bufferBUF,packet_length); if(packet_length < 0) { GAgent_Printf(GAGENT_INFO,"Error on read packet!"); free(packet_buffer); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBACK) { GAgent_Printf(GAGENT_INFO,"PUBACK expected!"); free(packet_buffer); return -1; } msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(msg_id != msg_id_rcv) { GAgent_Printf(GAGENT_INFO," message id was expected, but message id was found!"); free(packet_buffer); return -1; } free(packet_buffer); GAgent_Printf(GAGENT_INFO,"check_mqttpushqos1 OK"); return 1; }
uint16_t mqtt_parse_pub_topic_ptr(const uint8_t* buf, const uint8_t **topic_ptr) { uint16_t len = 0; //printf("mqtt_parse_pub_topic_ptr\n"); if(MQTTParseMessageType(buf) == MQTT_MSG_PUBLISH) { // fixed header length = 1 for "flags" byte + rlb for length bytes uint8_t rlb = mqtt_num_rem_len_bytes(buf); len = *(buf+1+rlb)<<8; // MSB of topic UTF len |= *(buf+1+rlb+1); // LSB of topic UTF // start of topic = add 1 for "flags", rlb for remaining length, 2 for UTF *topic_ptr = (buf + (1+rlb+2)); } else { *topic_ptr = NULL; } return len; }
err_t MqttClient::onReceive(pbuf *buf) { if (buf == NULL) { // Disconnected, close it TcpClient::onReceive(buf); } else { if (buf->len < 1) { // Bad packet? debugf("> MQTT WRONG PACKET? (len: %d)", buf->len); close(); return ERR_OK; } int received = 0; while (received < buf->tot_len) { int type = 0; if (waitingSize == 0) { // It's begining of new packet int pos = received; if (posHeader == 0) { //debugf("start posHeader"); pbuf_copy_partial(buf, &buffer[posHeader], 1, pos); pos++; posHeader = 1; } while (posHeader > 0 && pos < buf->tot_len) { //debugf("add posHeader"); pbuf_copy_partial(buf, &buffer[posHeader], 1, pos); if ((buffer[posHeader] & 128) == 0) posHeader = 0; // Remaining Length ended else posHeader++; pos++; } if (posHeader == 0) { //debugf("start len calc"); // Remaining Length field processed uint16_t rem_len = mqtt_parse_rem_len(buffer); uint8_t rem_len_bytes = mqtt_num_rem_len_bytes(buffer); // total packet length = remaining length + byte 1 of fixed header + remaning length part of fixed header waitingSize = rem_len + rem_len_bytes + 1; type = MQTTParseMessageType(buffer); debugPrintResponseType(type, waitingSize); // Prevent overflow if (waitingSize < MQTT_MAX_BUFFER_SIZE) { current = buffer; buffer[waitingSize] = 0; } else current = NULL; } else continue; } int available = min(waitingSize, buf->tot_len - received); waitingSize -= available; if (current != NULL) { pbuf_copy_partial(buf, current, available, received); current += available; if (waitingSize == 0) { // Full packet received if(type == MQTT_MSG_PUBLISH) { const uint8_t *ptrTopic, *ptrMsg; uint16_t lenTopic, lenMsg; lenTopic = mqtt_parse_pub_topic_ptr(buffer, &ptrTopic); lenMsg = mqtt_parse_pub_msg_ptr(buffer, &ptrMsg); // Additional check for wrong packet/parsing error if (lenTopic + lenMsg < MQTT_MAX_BUFFER_SIZE) { debugf("%d: %d\n", lenTopic, lenMsg); String topic, msg; topic.setString((char*)ptrTopic, lenTopic); msg.setString((char*)ptrMsg, lenMsg); if (callback) callback(topic, msg); } else { debugf("WRONG SIZES: %d: %d", lenTopic, lenMsg); } } } } else debugf("SKIP: %d (%d)", available, waitingSize + available); // To large! received += available; } // Fire ReadyToSend callback TcpClient::onReceive(buf); } return ERR_OK; }
void app_parse_mqttmsg(uint8_t *packet_buffer) { uint8_t msg_type = 0; uint16_t msg_id_rcv = 0; char topic_name[56]={0}; char msg[128]={0}; msg_type = MQTTParseMessageType(packet_buffer); //printf("-----> parse:0x%02X\n", msg_type); switch(msg_type) { case MQTT_MSG_CONNACK: if(packet_buffer[3] == 0) { printf("Mqtt login server success\n"); /* subscribe */ init_topic(&g_sub_topic, sub_topic_name, sizeof(sub_topic_name)); mqtt_subscribe(&g_stMQTTBroker, g_sub_topic->name, &(g_sub_topic->msg_id)); /* publish msg with Qos 0 */ //step1:>>>publish init_topic(&g_pub_topic1, pub_topic_name1, sizeof(pub_topic_name1)); mqtt_publish(&g_stMQTTBroker, g_pub_topic1->name, pub_msg1, 0); printf("APP publish msg[%s] with Qos 0\n", pub_msg1); deinit_topic(&g_pub_topic1); /* publish msg with Qos 1 */ //step1:>>>publish //step2:<<<puback init_topic(&g_pub_topic2, pub_topic_name2, sizeof(pub_topic_name2)); mqtt_publish_with_qos(&g_stMQTTBroker, g_pub_topic2->name, pub_msg2, 0, 1, &(g_pub_topic2->msg_id)); } else printf("Mqtt login server fail!\n"); break; case MQTT_MSG_SUBACK: msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(g_sub_topic && msg_id_rcv == g_sub_topic->msg_id) printf("Subcribe topic[%s] success\n", g_sub_topic->name); break; case MQTT_MSG_PUBLISH: mqtt_parse_pub_topic(packet_buffer, topic_name); mqtt_parse_publish_msg(packet_buffer, msg); printf("****** Topic[%s] recv msg: *****\n%s\n",topic_name, msg); /* unsubscribe */ if(!strcmp(g_sub_topic->name, topic_name)) mqtt_unsubscribe(&g_stMQTTBroker, g_sub_topic->name, &(g_sub_topic->msg_id)); break; case MQTT_MSG_UNSUBACK: msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(g_sub_topic && msg_id_rcv == g_sub_topic->msg_id) { printf("Unsubcribe topic[%s] success\n", g_sub_topic->name); deinit_topic(&g_sub_topic); } break; case MQTT_MSG_PUBACK://Qos1 msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(g_pub_topic2 && msg_id_rcv == g_pub_topic2->msg_id) { printf("APP publish msg[%s] with Qos 1\n", pub_msg2); deinit_topic(&g_pub_topic2); /* publish msg with Qos 2 */ //step1:>>>publish //step2:<<<pubrec //step3:>>>pubrel //step4:<<<pubcomp init_topic(&g_pub_topic3, pub_topic_name3, sizeof(pub_topic_name3)); mqtt_publish_with_qos(&g_stMQTTBroker, g_pub_topic3->name, pub_msg3, 1, 2, &(g_pub_topic3->msg_id)); } break; case MQTT_MSG_PUBREC://Qos2 msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(g_pub_topic3 && msg_id_rcv == g_pub_topic3->msg_id) mqtt_pubrel(&g_stMQTTBroker, g_pub_topic3->msg_id); break; case MQTT_MSG_PUBCOMP://Qos2 msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(g_pub_topic3 && msg_id_rcv == g_pub_topic3->msg_id) { printf("APP publish msg[%s] with Qos 2\n", pub_msg3); deinit_topic(&g_pub_topic3); } break; default: printf("Unknow mqtt msg type\n"); break; } }
/**************************************************************** FunctionName : Cloud_M2MDataHandle. Description : Receive cloud business data . xpg : global context. Rxbuf : global buf struct. buflen : receive max len. return : >0 have business data,and need to handle. other,no business data. Add by Alex.lin --2015-03-10 ****************************************************************/ int32 Cloud_M2MDataHandle( pgcontext pgc,ppacket pbuf /*, ppacket poutBuf*/, uint32 buflen) { uint32 dTime=0,ret=0,dataLen=0; uint32 packetLen=0; pgcontext pGlobalVar=NULL; pgconfig pConfigData=NULL; int8 *username=NULL; int8 *password=NULL; uint8* pMqttBuf=NULL; fd_set readfd; int32 mqtt_fd=0; uint16 mqttstatus=0; uint8 mqttpackType=0; pConfigData = &(pgc->gc); pGlobalVar = pgc; pMqttBuf = pbuf->phead; mqttstatus = pGlobalVar->rtinfo.waninfo.mqttstatus; mqtt_fd = pGlobalVar->rtinfo.waninfo.m2m_socketid; readfd = pGlobalVar->rtinfo.readfd; username = pConfigData->DID; password = pConfigData->wifipasscode; if( strlen(pConfigData->m2m_ip)==0 ) { //GAgent_Printf( GAGENT_INFO,"M2M IP =0 IP TIME 1 %d 2%d ",pgc->rtinfo.waninfo.RefreshIPLastTime,pgc->rtinfo.waninfo.RefreshIPTime); return 0; } if( MQTT_STATUS_START==mqttstatus ) { GAgent_Printf(GAGENT_INFO,"Req to connect m2m !"); GAgent_Printf(GAGENT_INFO,"username: %s password: %s",username,password); Cloud_ReqConnect( pgc,username,password ); GAgent_SetCloudServerStatus( pgc,MQTT_STATUS_RES_LOGIN ); GAgent_Printf(GAGENT_INFO," MQTT_STATUS_START "); pgc->rtinfo.waninfo.send2MqttLastTime = GAgent_GetDevTime_MS(); return 0; } dTime = abs( GAgent_GetDevTime_MS()-pGlobalVar->rtinfo.waninfo.send2MqttLastTime ); if( FD_ISSET( mqtt_fd,&readfd )||( mqttstatus!=MQTT_STATUS_RUNNING && dTime>GAGENT_MQTT_TIMEOUT)) { if( FD_ISSET( mqtt_fd,&readfd ) ) { GAgent_Printf(GAGENT_DEBUG,"Data form M2M!!!"); resetPacket( pbuf ); packetLen = MQTT_readPacket(mqtt_fd,pbuf,GAGENT_BUF_LEN ); if( packetLen==-1 ) { mqtt_fd=-1; pGlobalVar->rtinfo.waninfo.m2m_socketid=-1; GAgent_SetCloudServerStatus( pgc,MQTT_STATUS_START ); GAgent_Printf(GAGENT_DEBUG,"MQTT fd was closed!!"); GAgent_Printf(GAGENT_DEBUG,"GAgent go to MQTT_STATUS_START"); return -1; } else if(packetLen>0) { mqttpackType = MQTTParseMessageType( pMqttBuf ); GAgent_Printf( GAGENT_DEBUG,"MQTT message type %d",mqttpackType ); } else { return -1; } } /*create mqtt connect to m2m.*/ if( MQTT_STATUS_RUNNING!=mqttstatus && (MQTT_MSG_CONNACK==mqttpackType||MQTT_MSG_SUBACK==mqttpackType||dTime>GAGENT_MQTT_TIMEOUT)) { switch( mqttstatus) { case MQTT_STATUS_RES_LOGIN: ret = Cloud_ResConnect( pMqttBuf ); if( ret!=0 ) { GAgent_Printf(GAGENT_DEBUG," MQTT_STATUS_REQ_LOGIN Fail "); if( dTime > GAGENT_MQTT_TIMEOUT ) { GAgent_Printf(GAGENT_DEBUG,"MQTT req connetc m2m again!"); Cloud_ReqConnect( pgc,username,password ); } } else { GAgent_Printf(GAGENT_DEBUG,"GAgent do req connect m2m OK !"); GAgent_Printf(GAGENT_DEBUG,"Go to MQTT_STATUS_REQ_LOGINTOPIC1. "); Cloud_ReqSubTopic( pgc,MQTT_STATUS_REQ_LOGINTOPIC1 ); GAgent_SetCloudServerStatus( pgc,MQTT_STATUS_RES_LOGINTOPIC1 ); } break; case MQTT_STATUS_RES_LOGINTOPIC1: ret = Cloud_ResSubTopic(pMqttBuf,pgc->rtinfo.waninfo.mqttMsgsubid ); if( 0!=ret ) { GAgent_Printf(GAGENT_DEBUG," MQTT_STATUS_RES_LOGINTOPIC1 Fail "); if( dTime > GAGENT_MQTT_TIMEOUT ) { GAgent_Printf( GAGENT_DEBUG,"GAgent req sub LOGINTOPIC1 again "); Cloud_ReqSubTopic( pgc,MQTT_STATUS_REQ_LOGINTOPIC1 ); } } else { GAgent_Printf(GAGENT_DEBUG,"Go to MQTT_STATUS_RES_LOGINTOPIC2. "); Cloud_ReqSubTopic( pgc,MQTT_STATUS_REQ_LOGINTOPIC2 ); GAgent_SetCloudServerStatus( pgc,MQTT_STATUS_RES_LOGINTOPIC2 ); } break; case MQTT_STATUS_RES_LOGINTOPIC2: ret = Cloud_ResSubTopic(pMqttBuf,pgc->rtinfo.waninfo.mqttMsgsubid ); if( 0 != ret ) { GAgent_Printf(GAGENT_DEBUG," MQTT_STATUS_RES_LOGINTOPIC2 Fail "); if( dTime > GAGENT_MQTT_TIMEOUT ) { GAgent_Printf( GAGENT_INFO,"GAgent req sub LOGINTOPIC2 again."); Cloud_ReqSubTopic( pgc,MQTT_STATUS_REQ_LOGINTOPIC2 ); } } else { GAgent_Printf(GAGENT_DEBUG," Go to MQTT_STATUS_RES_LOGINTOPIC3. "); Cloud_ReqSubTopic( pgc,MQTT_STATUS_REQ_LOGINTOPIC3 ); GAgent_SetCloudServerStatus( pgc,MQTT_STATUS_RES_LOGINTOPIC3 ); } break; case MQTT_STATUS_RES_LOGINTOPIC3: ret = Cloud_ResSubTopic(pMqttBuf,pgc->rtinfo.waninfo.mqttMsgsubid ); if( ret != 0 ) { GAgent_Printf(GAGENT_DEBUG," MQTT_STATUS_RES_LOGINTOPIC3 Fail "); if( dTime > GAGENT_MQTT_TIMEOUT ) { GAgent_Printf(GAGENT_DEBUG,"GAgent req sub LOGINTOPIC3 again." ); Cloud_ReqSubTopic( pgc,MQTT_STATUS_REQ_LOGINTOPIC3 ); } } else { GAgent_Printf(GAGENT_CRITICAL,"GAgent Cloud Working..."); GAgent_SetCloudServerStatus( pgc,MQTT_STATUS_RUNNING ); GAgent_SetWiFiStatus( pgc,WIFI_CLOUD_STATUS,0 ); } break; default: break; } pgc->rtinfo.waninfo.send2MqttLastTime = GAgent_GetDevTime_MS(); } else if( packetLen>0 && ( mqttstatus == MQTT_STATUS_RUNNING ) ) { int varlen=0,p0datalen=0; switch( mqttpackType ) { case MQTT_MSG_PINGRESP: pgc->rtinfo.waninfo.cloudPingTime=0; GAgent_Printf(GAGENT_INFO,"GAgent MQTT Pong ... \r\n"); break; case MQTT_MSG_PUBLISH: dataLen = Mqtt_DispatchPublishPacket( pgc,pMqttBuf,packetLen ); if( dataLen>0 ) { pbuf->type = SetPacketType( pbuf->type,CLOUD_DATA_IN,1 ); ParsePacket( pbuf ); GAgent_Printf(GAGENT_INFO,"%s %d type : %04X len :%d",__FUNCTION__,__LINE__,pbuf->type,dataLen ); } break; default: GAgent_Printf(GAGENT_WARNING," data form m2m but msg type is %d",mqttpackType ); break; } } } return dataLen; }
int main(int argc, char* argv[]) { int packet_length; uint16_t msg_id, msg_id_rcv; mqtt_broker_handle_t broker; mqtt_init(&broker, "sancho"); mqtt_init_auth(&broker, "quijote", "rocinante"); init_socket(&broker, "192.168.10.40", 1883, keepalive); // >>>>> CONNECT mqtt_connect(&broker); // <<<<< CONNACK packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK) { fprintf(stderr, "CONNACK expected!\n"); return -2; } if(packet_buffer[3] != 0x00) { fprintf(stderr, "CONNACK failed!\n"); return -2; } // >>>>> PUBLISH QoS 0 printf("Publish: QoS 0\n"); mqtt_publish(&broker, "public/myexample/example", "Test libemqtt message.", 0); // >>>>> PUBLISH QoS 1 printf("Publish: QoS 1\n"); mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 1", 0, 1, &msg_id); // <<<<< PUBACK packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBACK) { fprintf(stderr, "PUBACK expected!\n"); return -2; } MQTTParseMessageId(packet_buffer, msg_id_rcv); if(msg_id != msg_id_rcv) { fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv); return -3; } // >>>>> PUBLISH QoS 2 printf("Publish: QoS 2\n"); mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 2", 1, 2, &msg_id); // Retain // <<<<< PUBREC packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBREC) { fprintf(stderr, "PUBREC expected!\n"); return -2; } MQTTParseMessageId(packet_buffer, msg_id_rcv); if(msg_id != msg_id_rcv) { fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv); return -3; } // >>>>> PUBREL mqtt_pubrel(&broker, msg_id); // <<<<< PUBCOMP packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBCOMP) { fprintf(stderr, "PUBCOMP expected!\n"); return -2; } MQTTParseMessageId(packet_buffer, msg_id_rcv); if(msg_id != msg_id_rcv) { fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv); return -3; } // >>>>> DISCONNECT mqtt_disconnect(&broker); close_socket(&broker); return 0; }
/** * Main routine * */ int main() { int packet_length; uint16_t msg_id, msg_id_rcv; mqtt_init(&broker, "client-id"); //mqtt_init_auth(&broker, "quijote", "rocinante"); init_socket(&broker, "107.22.188.194", 1883, keepalive); // >>>>> CONNECT mqtt_connect(&broker); // <<<<< CONNACK packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK) { fprintf(stderr, "CONNACK expected!\n"); return -2; } if(packet_buffer[3] != 0x00) { fprintf(stderr, "CONNACK failed!\n"); return -2; } // Signals after connect MQTT signal(SIGALRM, alive); alarm(keepalive); signal(SIGINT, term); // >>>>> SUBSCRIBE mqtt_subscribe(&broker, "public/test/topic", &msg_id); // <<<<< SUBACK packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_SUBACK) { fprintf(stderr, "SUBACK expected!\n"); return -2; } msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(msg_id != msg_id_rcv) { fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv); return -3; } while(1) { // <<<<< packet_length = read_packet(0); if(packet_length == -1) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } else if(packet_length > 0) { printf("Packet Header: 0x%x...\n", packet_buffer[0]); if(MQTTParseMessageType(packet_buffer) == MQTT_MSG_PUBLISH) { uint8_t topic[255], msg[1000]; uint16_t len; len = mqtt_parse_pub_topic(packet_buffer, topic); topic[len] = '\0'; // for printf len = mqtt_parse_publish_msg(packet_buffer, msg); msg[len] = '\0'; // for printf printf("%s %s\n", topic, msg); } } } return 0; }
/** * Main routine * */ static int mqtt_sub(void) { int packet_length,socket_id; uint16_t msg_id, msg_id_rcv; mqtt_broker_handle_t broker; packet_buffer.len=BUFSIZE; broker.socket_info = (void *)&socket_id; mqtt_init(&broker, "MQTT_SUB"); //mqtt_init_auth(&broker, "quijote", "rocinante"); socket_id = init_socket(&broker); // >>>>> CONNECT mqtt_connect(&broker); // <<<<< CONNACK // unsigned long pubTaskHandle= getTaskHandle(SUB_TASKID); // vTaskPrioritySet( (xTaskHandle)&pubTaskHandle, PUB_TASK_PRIORITY); //to degrade sub_task priority to let it as the same of pub_task packet_length = read_packet(1,socket_id,(Tranmit_t *)&packet_buffer); if(packet_length < 0) { UART_PRINT("Error(%d) on read packet!\n\r"); return -1; } if(MQTTParseMessageType(packet_buffer.buffer) != MQTT_MSG_CONNACK) { UART_PRINT("CONNACK expected!\n\r"); return -2; } if(packet_buffer.buffer[3] != 0x00) { UART_PRINT("CONNACK failed!\n\r"); return -2; } UART_PRINT("Connected to broker!\n\r"); if(OSI_OK != osi_TaskCreate( taskPub, (const signed char*)"taskPub", 2048, NULL, PUB_TASK_PRIORITY, (OsiTaskHandle)&pubTaskHandle )) UART_PRINT("taskPub failed\n\r"); // Signals after connect MQTT //signal(SIGALRM, alive); //alarm(keepalive); //signal(SIGINT, term); // >>>>> SUBSCRIBE mqtt_subscribe(&broker, "helloword", &msg_id); // <<<<< SUBACK packet_length = read_packet(1,socket_id,(Tranmit_t *)&packet_buffer); if(packet_length < 0) { UART_PRINT("Error(%d) on read packet!\n\r"); return -1; } if(MQTTParseMessageType(packet_buffer.buffer) != MQTT_MSG_SUBACK) { UART_PRINT("SUBACK expected!\n\r"); return -2; } msg_id_rcv = mqtt_parse_msg_id(packet_buffer.buffer); if(msg_id != msg_id_rcv) { UART_PRINT("%d message id was expected, but %d message id was found!\n\r"); return -3; } while(1) { // <<<<< packet_length = read_packet(0,socket_id,(Tranmit_t *)&packet_buffer); if(packet_length == -1) { UART_PRINT("Error(%d) on read packet!\n\r"); return -1; } else if(packet_length > 0) { UART_PRINT("Packet Header: 0x%x...\n\r"); if(MQTTParseMessageType(packet_buffer.buffer) == MQTT_MSG_PUBLISH) { uint8_t topic[TOPIC_LEN_MAX], msg[MSG_LEN_MAX]; uint16_t len; len = mqtt_parse_pub_topic(packet_buffer.buffer, topic); topic[len] = '\0'; // for printf len = mqtt_parse_publish_msg(packet_buffer.buffer, msg); msg[len] = '\0'; // for printf //UART_PRINT("%s %s\n\r", topic, msg); UART_PRINT(topic); UART_PRINT("\n\r"); UART_PRINT(msg); UART_PRINT("\n\r"); } } } return 0; }
void App_WhiskerGW() { char pubTopic[100]; char pubMsg[250]; unsigned char msgType; int counter=0; char cntStr[20]; char commandBuffer[64]; int commandBufferPointer=0; led_all_off(); // Give the unit a little time to start up // (300 ms for GS1011 and 1000 ms for GS1500) MSTimerDelay(1000); NVSettingsLoad(&GNV_Setting); led_on(4); WIFI_init(1); // Show MAC address and Version led_on(5); WIFI_Associate(); led_on(6); DisplayLCD(LCD_LINE8, "Demo starting."); DisplayLCD(LCD_LINE3, (const uint8_t *)WifiMAC); // UART if(spiUartInitialize()!=0) { DisplayLCD(LCD_LINE7, "!! SPIUART_ERROR !!"); while(1) { led_all_on(); MSTimerDelay(250); led_all_off(); MSTimerDelay(250); } } while (1) { // Do we need to connect to the AP? if (!AtLibGs_IsNodeAssociated()) { led_off(6); WIFI_Associate(); led_on(6); } else { if(mqttConnected==0) App_ConnectMqtt(); int charCount = spiUartRxBytesAvailable(); while(charCount>0) { commandBuffer[commandBufferPointer++] = spiUartGetByte(); charCount--; if(charCount==0) commandBufferPointer=0; if(commandBufferPointer>4) { if(strstr(commandBuffer,"RMPU")==commandBuffer) { if(commandBufferPointer>24) { // process response char macStr[9]; char lenStr[5]; memcpy(macStr,&commandBuffer[6],8); macStr[8] = 0; memcpy(lenStr,&commandBuffer[4],2); lenStr[2]=0; int len = (int)strtol(lenStr,0,16); unsigned long mac = strtoul(macStr,NULL,16); WhiskerModule *wm = findModule(mac); if(wm!=0) { if(commandBufferPointer>len+16) { char rssiStr[3]; memcpy(rssiStr,&commandBuffer[commandBufferPointer-3],2); rssiStr[2]=0; int rssi = (int)strtol(rssiStr,0,16); if((rssi & 0x80) == 0x80) rssi-=256; int puMsgPointer=14; mqtt_initJsonMsg(pubMsg); mqtt_addStringValToMsg("Name",wm->Name,pubMsg,0); mqtt_addStringValToMsg("Mac",macStr,pubMsg,1); char rstr[8]; sprintf(rstr,"%d dbm",rssi); mqtt_addStringValToMsg("Rssi",rstr,pubMsg,1); sprintf(pubMsg+strlen(pubMsg),",\"Values\":{"); puMsgPointer=14; int comma=0; while(puMsgPointer < (commandBufferPointer-3)) { char cidStr[3]; memcpy(cidStr,&commandBuffer[puMsgPointer],2); puMsgPointer+=2; cidStr[2]=0; unsigned char cid=(unsigned char)strtol(cidStr,0,16); unsigned char channel = cid & 0x1f; char valStr[9]; long valInt; switch(cid) { case 0x21: //digital input memcpy(valStr,&commandBuffer[puMsgPointer],2); valStr[2]=0; puMsgPointer+=2; valInt = (int)strtol(valStr,0,16); if(valInt) mqtt_addStringValToMsg("DIN1","True",pubMsg,comma); else mqtt_addStringValToMsg("DIN1","False",pubMsg,comma); break; case 0x22: //digital input memcpy(valStr,&commandBuffer[puMsgPointer],2); valStr[2]=0; puMsgPointer+=2; valInt = (int)strtol(valStr,0,16); if(valInt) mqtt_addStringValToMsg("DIN2","True",pubMsg,comma); else mqtt_addStringValToMsg("DIN2","False",pubMsg,comma); break; case 0x43: //battery analog in memcpy(valStr,&commandBuffer[puMsgPointer],4); valStr[4]=0; puMsgPointer+=4; valInt = (int)strtol(valStr,0,16); mqtt_addIntValToMsg("Battery",valInt,pubMsg,comma); break; case 0x44: //battery analog in memcpy(valStr,&commandBuffer[puMsgPointer],4); valStr[4]=0; puMsgPointer+=4; valInt = (int)strtol(valStr,0,16); mqtt_addIntValToMsg("Temperature",valInt,pubMsg,comma); break; case 0x45: //battery analog in memcpy(valStr,&commandBuffer[puMsgPointer],4); valStr[4]=0; puMsgPointer+=4; valInt = (int)strtol(valStr,0,16); mqtt_addIntValToMsg("RH",valInt,pubMsg,comma); break; case 0x5d: //internal temperature memcpy(valStr,&commandBuffer[puMsgPointer],4); valStr[4]=0; puMsgPointer+=4; valInt = (int)strtol(valStr,0,16); mqtt_addIntValToMsg("IntTemp",valInt,pubMsg,comma); break; case 0x57: //air quality memcpy(valStr,&commandBuffer[puMsgPointer],4); valStr[4]=0; puMsgPointer+=4; valInt = (int)strtol(valStr,0,16); mqtt_addIntValToMsg("AirQual",valInt,pubMsg,comma); break; case 0x58: //air quality memcpy(valStr,&commandBuffer[puMsgPointer],4); valStr[4]=0; puMsgPointer+=4; valInt = (int)strtol(valStr,0,16); mqtt_addIntValToMsg("AirQual",valInt,pubMsg,comma); break; case 0x61: // digital counter input memcpy(valStr,&commandBuffer[puMsgPointer],4); valStr[4]=0; puMsgPointer+=4; valInt = (int)strtol(valStr,0,16); mqtt_addIntValToMsg("Count1",valInt,pubMsg,comma); break; case 0x62: // digital counter input memcpy(valStr,&commandBuffer[puMsgPointer],4); valStr[4]=0; puMsgPointer+=4; valInt = (int)strtol(valStr,0,16); mqtt_addIntValToMsg("Count2",valInt,pubMsg,comma); break; } comma=1; } sprintf(pubMsg+strlen(pubMsg),"}"); mqtt_finishJsonMsg(pubMsg); sprintf(pubTopic, "%s/%s", WIO_DOMAIN, macStr); int res=mqtt_publish(&broker, pubTopic, pubMsg,0)<0; if(res<0) mqttConnected=0; led_on(8); //spiUartResetFIFO(); } } } } } } // Send data if RSSIReading(); AtLibGs_WaitForTCPMessage(1000); led_off(7); led_off(8); if(G_receivedCount>0) { AtLibGs_ParseTCPData(G_received,G_receivedCount,&rxm); msgType = MQTTParseMessageType(rxm.message); switch(msgType) { case MQTT_MSG_SUBACK: // todo: display subscription acknowledgement break; case MQTT_MSG_PUBLISH: App_MQTTMsgPublished(); break; case MQTT_MSG_PUBACK: // todo: display publish acknowledgement break; default: break; } } counter++; sprintf(cntStr,"Counter=%d",counter); DisplayLCD(LCD_LINE6,cntStr); if(counter>30) { counter=0; sprintf(pubTopic, "%s/%s", WIO_DOMAIN, WifiMAC); mqtt_initJsonMsg(pubMsg); mqtt_addStringValToMsg("msg","status ok",pubMsg,0); mqtt_finishJsonMsg(pubMsg); int res1=mqtt_publish(&broker, pubTopic, pubMsg,0)<0; if(res1<0) mqttConnected=0; led_on(7); } } // Send data if END } }
void *listener_thread(void *threadId) { int packet_length; uint16_t msg_id, msg_id_rcv; int error = 0; printf("Starting listener thread...\n"); // >>>>> SUBSCRIBE mqtt_subscribe(&broker, "yefsec0rk7uhatp/HighTemp", &msg_id); // <<<<< SUBACK packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); error = 1; } //printf("%s", packet_buffer); if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_SUBACK) { fprintf(stderr, "SUBACK expected!\n"); error = 1; } //printf("%s", packet_buffer); msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(msg_id != msg_id_rcv) { fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv); error = 1; } //printf("%s", packet_buffer); if (error) { printf("error setting up listener socket\n"); } while(1) { printf("Waiting for message...\n"); packet_length = read_packet(0); if(packet_length == -1) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); break; } else if(packet_length > 0) { printf("Packet Header: 0x%x...\n", packet_buffer[0]); if(MQTTParseMessageType(packet_buffer) == MQTT_MSG_PUBLISH) { uint8_t topic[255], msg[1000]; uint16_t len; led("g1", 1); len = mqtt_parse_pub_topic(packet_buffer, topic); topic[len] = '\0'; // for printf len = mqtt_parse_publish_msg(packet_buffer, msg); msg[len] = '\0'; // for printf printf("%s %s\n", topic, msg); sleep(1); led("g1", 0); } else if (MQTTParseMessageType(packet_buffer) == MQTT_MSG_PINGRESP) { printf("Ping response received\n"); } } } pthread_exit(NULL); }
int server_connect(int doConnect) { int16_t packet_length; char host[30]; // temp space for hostname string serverConnected = 0; if (doConnect) { sprintf(host, THINGFABRIC_BROKER_HOSTNAME); char *hostname = host; hostname_to_ip(hostname , broker_ip); if ((broker_ip == NULL) || (broker_ip[0] == 0)) { return 0; } printf("\n%s resolved to %s\n" , hostname , broker_ip); sleep(5); // now connect using user/password, publish sensor values on // appropriate topic (<domain>/<device type>/<device id> char clientIDStr[100]; sprintf(clientIDStr, "%s/%s", THINGFABRIC_DEVICE_TYPE, THINGFABRIC_DEVICE_ID); mqtt_init(&broker, clientIDStr); mqtt_init_auth(&broker, THINGFABRIC_USERNAME, THINGFABRIC_PASSWORD); init_socket(&broker, broker_ip, THINGFABRIC_BROKER_PORT); serverConnected = 1; mqtt_connect(&broker); // wait for CONNACK packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); serverConnected = 0; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK) { fprintf(stderr, "CONNACK expected!\n"); serverConnected = 0; } if(packet_buffer[3] != 0x00) { fprintf(stderr, "CONNACK failed!\n"); serverConnected = 0; } if (serverConnected) { sprintf(pubTopic, "%s/%s/%s", THINGFABRIC_DOMAIN, THINGFABRIC_DEVICE_TYPE, THINGFABRIC_DEVICE_ID); printf("%s\n", pubTopic); // configure the ping timer signal(SIGALRM, alive); alarm(keepalive); } else { fprintf(stderr, "Error connecting to MQTT server\n"); } } else { printf("Disconnecting from server\n"); mqtt_disconnect(&broker); close_socket(&broker); serverConnected = 0; } return serverConnected; }
int main(int argc, char* argv[]) { int packet_length; uint16_t msg_id, msg_id_rcv; mqtt_broker_handle_t broker; mqtt_init(&broker, "avengalvon"); mqtt_init_auth(&broker, "cid", "campeador"); init_socket(&broker, "127.0.0.1", 1883); // >>>>> CONNECT mqtt_connect(&broker); // <<<<< CONNACK packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK) { fprintf(stderr, "CONNACK expected!\n"); return -2; } if(packet_buffer[3] != 0x00) { fprintf(stderr, "CONNACK failed!\n"); return -2; } // >>>>> PUBLISH QoS 0 printf("Publish: QoS 0\n"); mqtt_publish(&broker, "hello/emqtt", "Example: QoS 0", 0); // >>>>> PUBLISH QoS 1 printf("Publish: QoS 1\n"); mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 1", 0, 1, &msg_id); // <<<<< PUBACK packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBACK) { fprintf(stderr, "PUBACK expected!\n"); return -2; } msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(msg_id != msg_id_rcv) { fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv); return -3; } // >>>>> PUBLISH QoS 2 printf("Publish: QoS 2\n"); mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 2", 1, 2, &msg_id); // Retain // <<<<< PUBREC packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBREC) { fprintf(stderr, "PUBREC expected!\n"); return -2; } msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(msg_id != msg_id_rcv) { fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv); return -3; } // >>>>> PUBREL mqtt_pubrel(&broker, msg_id); // <<<<< PUBCOMP packet_length = read_packet(1); if(packet_length < 0) { fprintf(stderr, "Error(%d) on read packet!\n", packet_length); return -1; } if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_PUBCOMP) { fprintf(stderr, "PUBCOMP expected!\n"); return -2; } msg_id_rcv = mqtt_parse_msg_id(packet_buffer); if(msg_id != msg_id_rcv) { fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv); return -3; } // >>>>> DISCONNECT mqtt_disconnect(&broker); close_socket(&broker); return 0; }