示例#1
0
文件: MQTT.c 项目: Zhang-Jia/WiFiMCU
/**
  * @brief  向代理(服务器)发送一个消息
  * @param  pTopic 消息主题
  * @param  pMessage 消息内容
  * @retval 小于0表示发送失败
  */
int mqtt_publish(char *pTopic,char *pMessage)
{
  int32_t len,rc;
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
  unsigned char buf[200];
  MQTTString topicString = MQTTString_initializer;
  int msglen = strlen(pMessage);
  int buflen = sizeof(buf);

  data.clientID.cstring = "me";
  data.keepAliveInterval = 5;
  data.cleansession = 1;
  len = MQTTSerialize_connect(buf, buflen, &data); /* 1 */

  topicString.cstring = pTopic;
  len += MQTTSerialize_publish(buf + len, buflen - len, 0, 0, 0, 0, topicString, (unsigned char*)pMessage, msglen); /* 2 */

  len += MQTTSerialize_disconnect(buf + len, buflen - len); /* 3 */
  transport_open();	
  rc = transport_sendPacketBuffer(buf,len);
  transport_close();
	if (rc == len)
		printf("Successfully published\n\r");
	else
		printf("Publish failed\n\r");
  return 0;
}
示例#2
0
int MQTTPublish(Client* c, const char* topicName, MQTTMessage* message)
{
    int rc = FAILURE;
    MQTTString topic = MQTTString_initializer;
    topic.cstring = (char *)topicName;

    if(c->suborder != subscribe_over)
    {
    	log_printf(LOG_ERROR, "[MQTTPublish] publish but subcribe not over\n");
    	goto exit;
    	//TODO: error
    }

    int len = 0;
    if (!c->isconnected)
        goto exit;

    if (message->qos == QOS1 || message->qos == QOS2)
        message->id = getNextPacketId(c);
    
    len = MQTTSerialize_publish(c->buf, c->buf_size, 0, message->qos, message->retained, message->id, 
              topic, (unsigned char*)message->payload, message->payloadlen);
    if (len <= 0)
        goto exit;
    if ((rc = sendPacket_ev(c, len)) != SUCCESS) // send the subscribe packet
        goto exit;
exit:
    return rc;
}
int MQTTPublish(Client* c, const char* topicName, MQTTMessage* message)
{
    int rc = FAILURE;
    Timer timer; 
    MQTTString topic = MQTTString_initializer;
    topic.cstring = (char *)topicName;
    int len = 0;
	
    InitTimer(&timer); 
    countdown_ms(&timer, c->command_timeout_ms);
    
    if (!c->isconnected)
        goto exit;

    if (message->qos == QOS1 || message->qos == QOS2)
        message->id = getNextPacketId(c);
    
    len = MQTTSerialize_publish(c->buf, c->buf_size, 0, message->qos, message->retained, message->id, 
              topic, (unsigned char*)message->payload, message->payloadlen);
    if (len <= 0)
        goto exit;
    if ((rc = sendPacket(c, len, &timer)) != SUCCESS) // send the publish packet
        goto exit; // there was a problem
    
    if (message->qos == QOS1)
    {
        if (waitfor(c, PUBACK, &timer) == PUBACK)
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
                rc = FAILURE;
        }
        else
            rc = FAILURE;
    }
    else if (message->qos == QOS2)
    {
        if (waitfor(c, PUBCOMP, &timer) == PUBCOMP)
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
                rc = FAILURE;
        }
        else
            rc = FAILURE;
    }
    
exit:

    DeInitTimer(&timer); //STM: added this line
    return rc;
}
int MQTTPublish(MQTTClient* c, const char* topicName, MQTTMessage* message)
{
	int rc = FAILURE;
	Timer timer;
	MQTTString topic = MQTTString_initializer;
	topic.cstring = (char *)topicName;
	int len = 0;

#if defined(MQTT_TASK)
	FreeRTOS_MutexLock(&c->mutex);
#endif
	if (!c->isconnected)
		goto exit;

	TimerInit(&timer);
	TimerCountdownMS(&timer, c->command_timeout_ms);

	if (message->qos == QOS1 || message->qos == QOS2)
		message->id = getNextPacketId(c);

	len = MQTTSerialize_publish(c->buf, c->buf_size, 0, message->qos, message->retained, message->id,
	                            topic, (unsigned char*)message->payload, message->payloadlen);
	if (len <= 0)
		goto exit;
	if ((rc = sendPacket(c, len, &timer)) != SUCCESS) // send the subscribe packet
		goto exit; // there was a problem

	if (message->qos == QOS1) {
		if (waitfor(c, PUBACK, &timer) == PUBACK) {
			unsigned short mypacketid;
			unsigned char dup, type;
			if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
				rc = FAILURE;
		} else
			rc = FAILURE;
	} else if (message->qos == QOS2) {
		if (waitfor(c, PUBCOMP, &timer) == PUBCOMP) {
			unsigned short mypacketid;
			unsigned char dup, type;
			if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
				rc = FAILURE;
		} else
			rc = FAILURE;
	}

exit:
#if defined(MQTT_TASK)
	FreeRTOS_MutexUnlock(&c->mutex);
#endif
	return rc;
}
int mqtt_publish(mqtt_client_t *c, char* topicstr, mqtt_msg_t *msg)
{
    int rc = -1;
    MQTTString topic = MQTTString_initializer;
    int len;
    int pktype;

    topic.cstring = topicstr;

    len = MQTTSerialize_publish(c->wbuf, c->wbuflen,
                                                   msg->dup, msg->qos, msg->retained, msg->id,
                                                   topic, msg->payload, msg->payloadlen);
    if (len <= 0)
        goto exit;

    if ((rc = mqtt_write(c->sockfd, c->wbuf, len)) <= 0)
        goto exit;

    pktype = MQTTPacket_read(c->rbuf, c->rbuflen, c->getfn);

    if (msg->qos == 1)
    {
        if (pktype == PUBACK)
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->rbuf, c->rbuflen) != 1)
                rc = -1;
        }
        else
            rc = -1;
    }
    else if (msg->qos == 2)
    {
        if (pktype == PUBCOMP)
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->rbuf, c->rbuflen) != 1)
                rc = -1;
        }
        else
            rc = -1;
    }

exit:
    return rc;
}
示例#6
0
int mqttClient_publish(mqttClient_t* clientData, const char* topicName, mqttClient_msg_t* message)
{
  int rc = LE_OK;
  MQTTString topic = MQTTString_initializer;
  topic.cstring = (char *)topicName;
  int len = 0;

  LE_ASSERT(clientData);

  if (!clientData->session.isConnected)
  {
    LE_WARN("not connected");
    goto cleanup;
  }

  if (message->qos == MQTT_CLIENT_QOS1 || message->qos == MQTT_CLIENT_QOS2)
    message->id = mqttClient_getNextPacketId(clientData);

  len = MQTTSerialize_publish(clientData->session.tx.buf, sizeof(clientData->session.tx.buf), 0, message->qos, 
      message->retained, message->id, topic, (unsigned char*)message->payload, message->payloadLen);
  if (len <= 0)
  {
    LE_ERROR("MQTTSerialize_publish() failed(%d)", len);
    rc = LE_BAD_PARAMETER;
    goto cleanup;
  }

  rc = mqttClient_write(clientData, len);
  if (rc)
  {
    LE_ERROR("mqttClient_write() failed(%d)", rc);
    goto cleanup;
  } 
  
cleanup:
  return rc;
}
示例#7
0
int main()
{
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	int rc = 0;
	char buf[200];
	int buflen = sizeof(buf);
	int msgid = 1;
	MQTTString topicString = MQTTString_initializer;
	int req_qos = 0;
	char* payload = "mypayload";
	int payloadlen = strlen(payload);
	int len = 0;

	signal(SIGINT, cfinish);
	signal(SIGTERM, cfinish);

	rc = Socket_new("127.0.0.1", 1883, &mysock);

	data.clientID.cstring = "me";
	data.keepAliveInterval = 20;
	data.cleansession = 1;
	data.username.cstring = "testuser";
	data.password.cstring = "testpassword";

	struct timeval tv;
	tv.tv_sec = 1;  /* 1 second Timeout */
	tv.tv_usec = 0;  
	setsockopt(mysock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval));

	len = MQTTSerialize_connect(buf, buflen, &data);
	rc = write(mysock, buf, len);

	/* wait for connack */
	if (MQTTPacket_read(buf, buflen, getdata) == CONNACK)
	{
		int connack_rc;

		if (MQTTDeserialize_connack(&connack_rc, buf, buflen) != 1 || connack_rc != 0)
		{
			printf("Unable to connect, return code %d\n", connack_rc);
			goto exit;
		}
	}
	else
		goto exit;

	/* subscribe */
	topicString.cstring = "substopic";
	len = MQTTSerialize_subscribe(buf, buflen, 0, msgid, 1, &topicString, &req_qos);

	rc = write(mysock, buf, len);
	if (MQTTPacket_read(buf, buflen, getdata) == SUBACK) 	/* wait for suback */
	{
		int submsgid;
		int subcount;
		int granted_qos;

		rc = MQTTDeserialize_suback(&submsgid, 1, &subcount, &granted_qos, buf, buflen);
		if (granted_qos != 0)
		{
			printf("granted qos != 0, %d\n", granted_qos);
			goto exit;
		}
	}
	else
		goto exit;

	topicString.cstring = "pubtopic";
	while (!toStop)
	{
		if (MQTTPacket_read(buf, buflen, getdata) == PUBLISH)
		{
			int dup;
			int qos;
			int retained;
			int msgid;
			int payloadlen_in;
			char* payload_in;
			int rc;
			MQTTString receivedTopic;

			rc = MQTTDeserialize_publish(&dup, &qos, &retained, &msgid, &receivedTopic,
					&payload_in, &payloadlen_in, buf, buflen);
			printf("message arrived %.*s\n", payloadlen_in, payload_in);
		}

		printf("publishing reading\n");
		len = MQTTSerialize_publish(buf, buflen, 0, 0, 0, 0, topicString, payload, payloadlen);
		rc = write(mysock, buf, len);
	}

	printf("disconnecting\n");
	len = MQTTSerialize_disconnect(buf, buflen);
	rc = write(mysock, buf, len);

exit:
	rc = shutdown(mysock, SHUT_WR);
	rc = recv(mysock, NULL, 0, 0);
	rc = close(mysock);

	return 0;
}
示例#8
0
int main(int argc, char *argv[])
{
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	int rc = 0;
	int mysock = 0;
	unsigned char buf[200];
	int buflen = sizeof(buf);
	int msgid = 1;
	MQTTString topicString = MQTTString_initializer;
	int req_qos = 0;
	char* payload = "mypayload";
	int payloadlen = strlen(payload);
	int len = 0;
	char *host = "m2m.eclipse.org";
	int port = 1883;
	MQTTTransport mytransport;

	stop_init();
	if (argc > 1)
		host = argv[1];

	if (argc > 2)
		port = atoi(argv[2]);

	mysock = transport_open(host, port);
	if(mysock < 0)
		return mysock;

	printf("Sending to hostname %s port %d\n", host, port);

	mytransport.sck = &mysock;
	mytransport.getfn = transport_getdatanb;
	mytransport.state = 0;
	data.clientID.cstring = "me";
	data.keepAliveInterval = 20;
	data.cleansession = 1;
	data.username.cstring = "testuser";
	data.password.cstring = "testpassword";

	len = MQTTSerialize_connect(buf, buflen, &data);
	rc = transport_sendPacketBuffer(mysock, buf, len);

	/* wait for connack */
	if (MQTTPacket_read(buf, buflen, transport_getdata) == CONNACK)
	{
		unsigned char sessionPresent, connack_rc;

		if (MQTTDeserialize_connack(&sessionPresent, &connack_rc, buf, buflen) != 1 || connack_rc != 0)
		{
			printf("Unable to connect, return code %d\n", connack_rc);
			goto exit;
		}
	}
	else
		goto exit;

	/* subscribe */
	topicString.cstring = "substopic";
	len = MQTTSerialize_subscribe(buf, buflen, 0, msgid, 1, &topicString, &req_qos);

	rc = transport_sendPacketBuffer(mysock, buf, len);
	do {
		int frc;
		if ((frc=MQTTPacket_readnb(buf, buflen, &mytransport)) == SUBACK) /* wait for suback */
		{
			unsigned short submsgid;
			int subcount;
			int granted_qos;

			rc = MQTTDeserialize_suback(&submsgid, 1, &subcount, &granted_qos, buf, buflen);
			if (granted_qos != 0)
			{
				printf("granted qos != 0, %d\n", granted_qos);
				goto exit;
			}
			break;
		}
		else if (frc == -1)
			goto exit;
	} while (1); /* handle timeouts here */
	/* loop getting msgs on subscribed topic */
	topicString.cstring = "pubtopic";
	while (!toStop)
	{
		/* handle timeouts */
		if (MQTTPacket_readnb(buf, buflen, &mytransport) == PUBLISH)
		{
			unsigned char dup;
			int qos;
			unsigned char retained;
			unsigned short msgid;
			int payloadlen_in;
			unsigned char* payload_in;
			int rc;
			MQTTString receivedTopic;

			rc = MQTTDeserialize_publish(&dup, &qos, &retained, &msgid, &receivedTopic,
					&payload_in, &payloadlen_in, buf, buflen);
			printf("message arrived %.*s\n", payloadlen_in, payload_in);
			printf("publishing reading\n");
			len = MQTTSerialize_publish(buf, buflen, 0, 0, 0, 0, topicString, (unsigned char*)payload, payloadlen);
			rc = transport_sendPacketBuffer(mysock, buf, len);
		}
	}

	printf("disconnecting\n");
	len = MQTTSerialize_disconnect(buf, buflen);
	rc = transport_sendPacketBuffer(mysock, buf, len);

exit:
	transport_close(mysock);

	return 0;
}
示例#9
0
int main(int argc, char** argv) {

    if (argc < 6) {

        printf("Usage: mqtt_pub <host> <port> <client_id> <topic> <message>\n");
        return 0;

    }

    /* parse arguments */
    char* host      = argv[1];
    int port        = atoi(argv[2]);
    char* clientid  = argv[3];
    char* topic     = argv[4];
    char* message   = argv[5];

    /* resolv broker ip address */
    struct hostent *he;
    if((he = gethostbyname(host)) == NULL) {
        perror("hostname error\n");
        return 1;
    }

    /* try to connect to the broker */
    struct sockaddr_in sa;
    int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    memset(&sa, 0, sizeof sa);
    sa.sin_family = AF_INET;
    sa.sin_port = htons(port);
    sa.sin_addr.s_addr = inet_addr(inet_ntoa(*((struct in_addr *)he->h_addr)));

    if (connect(sock, (struct sockaddr *) &sa, sizeof sa) < 0) {

        perror("error on connect\n");
        close(sock);
        return 2;

    } else {

        /* initialize and load mqtt helpers */
        MQTTString topicString = MQTTString_initializer;
        topicString.cstring     = topic;

        MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
        data.willFlag           = 0;
        data.MQTTVersion        = 3;
        data.clientID.cstring   = clientid;
        data.keepAliveInterval  = 20;
        data.cleansession       = 1;
        
        /* prepare the message */
        char buf[1024];
        int buflen = sizeof (buf);

        int len = MQTTSerialize_connect(buf, buflen, &data);
        len += MQTTSerialize_publish(buf + len, buflen - len, 0, 0, 0, 0, topicString, message, strlen(message));
        len += MQTTSerialize_disconnect(buf + len, buflen - len);

        /* send message */
        int n = write(sock, buf, len);
        if (n < 0) {

            perror("error sending packet\n");
            close(sock);
            return 2;

        } else {

            printf("%i byte(s) sent\n", n);

        }

    }

    /* close socket and exit */
    close(sock);
    return 0;

}
示例#10
0
int main(int argc, char *argv[])
{
	/******MQTT*******/
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	int rc = 0;
	char buf[200];
	int buflen = sizeof(buf);
	int mysock = 0;
	MQTTString topicString = MQTTString_initializer;
	char* payload = "mypayload";
	int payloadlen = strlen(payload);
	int len = 0;
	char *host = "192.168.8.241";
	int port = 1883;

	/******UART*******/
	int fd = FALSE;
	int ret;
	char rcv_buf[512];
 	int i;
	if(argc < 2){
		printf("Usage: %s /dev/ttySn \n",argv[0]);
		return FALSE;
	}

	if (argc > 2)
		host = argv[2];

	if (argc > 3)
		port = atoi(argv[3]);
	
	fd = UART_Open(fd,argv[1]);
	if(FALSE == fd){
		printf("open error\n");
		exit(1);
	}
	ret  = UART_Init(fd,9600,0,8,1,'N');
	if (FALSE == fd){
		printf("Set Port Error\n");
		exit(1);
	}

	ret  = UART_Send(fd,"*IDN?\n",6);
	if(FALSE == ret){
		printf("write error!\n");
		exit(1);
	}
	printf("command: %s\n","*IDN?");
	memset(rcv_buf,0,sizeof(rcv_buf));

	/**************MQTT tansport*************/

	mysock = transport_open(host,port);
	if(mysock < 0)
		return mysock;

	printf("Sending to hostname %s port %d\n", host, port);

	data.clientID.cstring = "me";
	data.keepAliveInterval = 20;
	data.cleansession = 1;
	data.username.cstring = "testuser";
	data.password.cstring = "testpassword";
	data.MQTTVersion = 4;


	for(i=0;;i++)
	{
	   	ret = UART_Recv(fd, rcv_buf,512);	
		if(ret > 0)
		{
			rcv_buf[ret]='\0';
			printf("%s",rcv_buf);

			len = MQTTSerialize_connect((unsigned char *)buf, buflen, &data);
			topicString.cstring = "mytopic";
		
			len += MQTTSerialize_publish((unsigned char *)(buf + len), buflen - len, 0, 0, 0, 0, topicString, (unsigned char *)rcv_buf, ret+1);
			len += MQTTSerialize_disconnect((unsigned char *)(buf + len), buflen - len);
			rc = transport_sendPacketBuffer(mysock, buf, len);
			if (rc == len)
				printf("Successfully published\n");
			else
				printf("Publish failed\n");
		}
		else
		{
			printf("cannot receive data1\n");
			break;
		}
	}

exit:
	UART_Close(fd);
	transport_close(mysock);

	return 0;
}
示例#11
0
int MQTTPublish(MQTTClient* c, const char* topicName, MQTTMessage* message)
{
    int rc = MQTT_FAILURE;
    Timer timer;   
    MQTTString topic = MQTTString_initializer;
    topic.cstring = (char *)topicName;
    int len = 0;

	platform_mutex_lock(&c->mutex);
	if (!c->isconnected)
		goto exit;

    platform_timer_init(&timer);
    platform_timer_countdown(&timer, c->command_timeout_ms);

    if (message->qos == QOS1 || message->qos == QOS2)
        message->id = getNextPacketId(c);
    
    len = MQTTSerialize_publish(c->buf, c->buf_size, 0, message->qos, message->retained, message->id, 
              topic, (unsigned char*)message->payload, message->payloadlen);
    if (len <= 0)
        goto exit;
    if ((rc = sendPacket(c, len, &timer)) != MQTT_SUCCESS) // send the subscribe packet
    {
        goto exit; // there was a problem
    }

    if (message->qos == QOS1)
    {
        if (waitfor(c, PUBACK, &timer) == PUBACK)
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
            {
                platform_printf("failed to deserialize ACK\n");
                rc = MQTT_FAILURE;
            }
        }
        else
        {
            rc = MQTT_CONNECTION_LOST;
        }
    }
    else if (message->qos == QOS2)
    {
        if (waitfor(c, PUBCOMP, &timer) == PUBCOMP)
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
                rc = MQTT_FAILURE;
        }
        else 
        {
            rc = MQTT_CONNECTION_LOST;
		}
    }
    
exit:
	platform_mutex_unlock(&c->mutex);
    return rc;
}