Example #1
0
int publishEvent(Iotfclient *client, char *eventType, char *eventFormat, unsigned char* data, enum QoS qos)
{
	int rc = -1;

	char publishTopic[strlen(eventType) + strlen(eventFormat) + 16];

	sprintf(publishTopic, "iot-2/evt/%s/fmt/%s", eventType, eventFormat);
	printf ("publishTopic = %s\n", publishTopic );

	MQTTMessage pub;

	pub.qos = qos;
	pub.retained = '0';
	pub.payload = data;
	pub.payloadlen = strlen(data);

	rc = MQTTPublish(&client->c, publishTopic , &pub);

	if(rc != SUCCESS) {
		printf("connection lost.. \n");
		retry_connection(client);
		rc = MQTTPublish(&client->c, publishTopic , &pub);
	}
	
	return rc;

}
Example #2
0
MqttReturnCode mqttClient_publish2(AJBMqttClient *client,
                                   MqttClientPublishInfo *data){
    
    MQTTMessage message = MessageMake(data, client->getMessageId(client));
    int msgId = getPubMessageId(data->publishContent);
    if (msgId != -1) {
        printf("[PUB %s] id = %d SEND ------->>>>>>>",data->publishTopic,msgId);
    }
    
    int rc = MQTTPublish(&client->c, data->publishTopic, &message);
    
    
    if (rc == SOCK_ERROR) {
        MqttLog("[PUB failed ] publish message failed,lost connect!");
        MqttLog("[ERR network] %s",errReason(rc));
        logToLocal(client->indexTag,log_erro_path, "[ERR network] %s",errReason(rc));
        mqttClient_reconnect(client);
    }
    else if (rc == SUCCESS){
        if (msgId!=-1) {
            MqttLog("[PUB result] %d SUCCESS",msgId);
        }
        
        logToLocal(client->indexTag,log_send_path,"INFO:发布消息--> topic: %s message: %s",data->publishTopic,data->publishContent);
    }
    else{
        MqttLog("[PUB warning] -------- %d TIMEOUT",getPubMessageId(data->publishContent));
        
    }
    return rc;
}
Example #3
0
static void prvMQTTEchoTask(void *pvParameters)
{
	/* connect to m2m.eclipse.org, subscribe to a topic, send and receive messages regularly every 1 sec */
	MQTTClient client;
	Network network;
	unsigned char sendbuf[80], readbuf[80];
	int rc = 0, 
		count = 0;
	MQTTPacket_connectData connectData = MQTTPacket_connectData_initializer;

	pvParameters = 0;
	platform_network_init(&network);
	MQTTClientInit(&client, &network, 30000, sendbuf, sizeof(sendbuf), readbuf, sizeof(readbuf));

	char* address = "iot.eclipse.org";
	if ((rc = platform_network_connect(&network, address, 1883)) != 0)
		printf("Return code from network connect is %d\n", rc);

#if defined(MQTT_TASK)
	if ((rc = MQTTStartTask(&client)) != pdPASS)
		printf("Return code from start tasks is %d\n", rc);
#endif

	connectData.MQTTVersion = 3;
	connectData.clientID.cstring = "FreeRTOS_sample";

	if ((rc = MQTTConnect(&client, &connectData)) != 0)
		printf("Return code from MQTT connect is %d\n", rc);
	else
		printf("MQTT Connected\n");

	if ((rc = MQTTSubscribe(&client, "FreeRTOS/sample/#", 2, messageArrived)) != 0)
		printf("Return code from MQTT subscribe is %d\n", rc);

	while (++count)
	{
		MQTTMessage message;
		char payload[30];

		message.qos = 1;
		message.retained = 0;
		message.payload = payload;
		sprintf(payload, "message number %d", count);
		message.payloadlen = strlen(payload);

		if ((rc = MQTTPublish(&client, "FreeRTOS/sample/a", &message)) != 0)
			printf("Return code from MQTT publish is %d\n", rc);
#if !defined(MQTT_TASK)
		if ((rc = MQTTYield(&client, 1000)) != 0)
			printf("Return code from yield is %d\n", rc);
#endif
	}

	/* do not return */
}
//Publish actions response to IoTF platform
int publishActionResponse(char* publishTopic, char* data)
{
	int rc = -1;
	MQTTMessage pub;
//	printf("Topic ( %s) payload (%s)\n", publishTopic,data);
	pub.qos = 1;
	pub.retained = '0';
	pub.payload = data;
	pub.payloadlen = strlen(data);

	rc = MQTTPublish(&dmClient.deviceClient.c, publishTopic , &pub);
	if(rc == SUCCESS) {
		rc = yield(&dmClient.deviceClient, 100);
	}
	return rc;
}
IoT_Error_t aws_iot_mqtt_publish(MQTTPublishParams *pParams) {
    IoT_Error_t rc = NONE_ERROR;

    MQTTMessage Message;
    Message.dup = pParams->MessageParams.isDuplicate;
    Message.id = pParams->MessageParams.id;
    Message.payload = pParams->MessageParams.pPayload;
    Message.payloadlen = pParams->MessageParams.PayloadLen;
    Message.qos = (enum QoS)pParams->MessageParams.qos;
    Message.retained = pParams->MessageParams.isRetained;

    if(0 != MQTTPublish(&c, pParams->pTopic, &Message)) {
        rc = PUBLISH_ERROR;
    }

    return rc;
}
Example #6
0
static inline void publish_status()
{
    char buff[STATUS_BUFF_SIZE];

    memset(buff, 0, STATUS_BUFF_SIZE);

    if (ir.enabled) {
        strcat(buff, "on ");
    } else {
        strcat(buff, "off ");
    }

    switch (ir.mode) {
        case MODE_AUTO:
            strcat(buff, "auto ");
            break;
        case MODE_COOL:
            strcat(buff, "cool ");
            break;
        case MODE_HEAT:
            strcat(buff, "heat ");
            break;
        case MODE_FAN:
            strcat(buff, "fan ");
            break;
    }
    
    sprintf(buff + strlen(buff), "%d %d", ir.temperature, ir.fan_level);
   
    printf("status: %s\n", buff); 

    MQTTMessage message;
    message.payload = buff;
    message.payloadlen = strlen(buff) + 1;
    message.dup = 0;
    message.qos = QOS1;
    message.retained = 0;
    if (MQTTPublish(&mqtt_client, config_get_status_topic(), &message) 
            == SUCCESS ){
        printf("status published\n");
    } else {
        printf("error while publishing message\n");
    }
}
Example #7
0
void* uploadMeasuresHandler(void *arg)
{
	Client* c = (Client*) arg;
	sleep(60);
	while (!toStop)
	{
		char temp_payload[1024];
		// Push values using full data path.
		json_data(temp_payload, "machine.temperature", temp_ts, temp_values, temp_size);
		char hum_payload[1024];
		json_data(hum_payload, "machine.humidity", hum_ts, hum_values, hum_size);
		sprintf(payload, "%s, %s", temp_payload, hum_payload);
		char* buffer = json_encapsulate(payload);
		printf("[SAMPLES] %s\n", buffer);

		MQTTMessage msg;
		msg.qos = QOS0;
		msg.retained = 0;
		msg.dup = 0;
		msg.id = 0;
		msg.payload = buffer;
		msg.payloadlen = strlen(buffer);

		char* topic = malloc(15+strlen(deviceId));
		sprintf(topic, "%s/messages/json", deviceId);
		printf("Publish on %s\n", topic);

		int rc = MQTTPublish(c, topic, &msg);
		if(rc != 0)
			printf("publish error: %d\n", rc);

		free(buffer);
		hum_size = 0;
		temp_size = 0;
		sleep(60);
	}
	return NULL;
}
// Utility function to publish the message to Watson IoT
int publish(char* publishTopic, char* data)
{
	int rc = -1;
	MQTTMessage pub;
	printf("Topic ( %s) payload (%s)\n", publishTopic,data);
	pub.qos = 1;
	pub.retained = '0';
	pub.payload = data;
	pub.payloadlen = strlen(data);
	//signal(SIGINT, sigHandler);
	//signal(SIGTERM, sigHandler);
	interrupt =0;
	while(!interrupt)
		{
			rc = MQTTPublish(&dmClient.deviceClient.c, publishTopic , &pub);
			if(rc == SUCCESS) {
				rc = yield(&dmClient.deviceClient, 100);
			}
			if(!interrupt)
				sleep(2);
		}
	return rc;
}
Example #9
0
/*
 * description: publish qos0 msg to mqtt
 *   topicName--主题名
 *   cmd--命令字,msgytype
 *   header_type-- enum value, json_header or protobuf_header or binary_header
 *   buf--buffer
 *   buflen--buffer length
 * */
void publish_msg_2_mqtts_qos0(const char *topicName, enum mqtt_buf_header header_type, int cmd, int buflen, const void *buf)
{
	int rc;

	//组包头
	char playload[MQTT_PLAYLOADLEN] = {0};
	int totallen = buflen+2;
	int payloadlen = buflen+10;
	memcpy(playload, &header_type, 4);
	memcpy(playload+4, &totallen, 4);
	memcpy(playload+8, &cmd, 2);
	memcpy(playload+10, buf, buflen);

	//构造mqtt publish数据
	MQTTMessage msg;
	msg.dup=0;  //必须初始化。
	msg.id=0;
	msg.qos=0;
	msg.retained=0;
	msg.payloadlen = payloadlen;
	msg.payload = playload;

	rc = MQTTPublish(&global_ev_all.client, topicName, &msg);
	if(rc!=0)
		log_printf(LOG_NOTICE, "publish_msg_2_mqtts failed\n");
	else
	{
		log_printf(LOG_NOTICE, "[PUBLISH]: %s, %s\n", topicName, (char *)msg.payload);
		int i;
		for(i=0; i<buflen+10; i++)
		{
			printf("0x%x ", playload[i]);
		}
		printf("\n");
	}

}
Example #10
0
File: mpush.c Project: cgoder/cpush
int Cpush_publish(unsigned int clientHandle, unsigned char* topic, unsigned char* msg, unsigned char qos, unsigned char retain)
{
	if ((0 == clientHandle)||(NULL == topic)||(NULL == msg)) {
		return CPUSH_RET_ERROR_PARA;
	}

	if (qos > 2) {
		return CPUSH_RET_ERROR_PARA;
	}
	if (retain > 1) {
		return CPUSH_RET_ERROR_PARA;
	}

	Client* client = (Client*)clientHandle;
	MQTTMessage mqttMsg;
	if (0 == qos) {
		mqttMsg.qos = QOS0;
	} else if (1 == qos) {
		mqttMsg.qos = QOS1;
	} else if (2 == qos) {
		mqttMsg.qos =QOS2;
	}
	mqttMsg.retained = retain;
	mqttMsg.dup = 0;
	mqttMsg.id = 0;
	mqttMsg.payload = msg;
	mqttMsg.payloadlen = strlen((const char*)msg)+1;
	int rc = MQTTPublish(client, (const char*)topic, &mqttMsg);
	if (FAILURE == rc) {
		printf("Cpush_pushlish fail! ret:%d", rc);
		return CPUSH_RET_FAIL;
	}

	printf("Cpush_pushlish %s OK!", msg);
	return CPUSH_RET_OK;
}
Example #11
0
static enum cmd_status cmd_mqtt_publish_exec(char *cmd)
{
	int32_t cnt;
	MQTTMessage message;
	char *topic;
	uint8_t *buf;
	char *tmp;
	uint32_t qos;
	uint32_t retain;
	uint32_t size;
	int rc;

	/* get param */
	cnt = cmd_sscanf(cmd, "qos=%u retain=%u",
			 &qos, &retain);

	if ((tmp = cmd_strrchr(cmd, '\"')) == NULL)
		return CMD_STATUS_INVALID_ARG;
	*tmp = '\0';
  	cnt += cmd_sscanf(tmp + 2, "size=%u", &size);
	if ((tmp = cmd_strchr(cmd, '\"')) == NULL)
		return CMD_STATUS_INVALID_ARG;
	tmp++;


	/* check param */
	if (cnt != 3) {
		CMD_ERR("invalid param number %d\n", cnt);
		return CMD_STATUS_INVALID_ARG;
	}

	if (qos > 2) {
		CMD_ERR("invalid qos %d\n", qos);
		return CMD_STATUS_INVALID_ARG;
	}

	if (retain > 1) {
		CMD_ERR("invalid retain %d\n", retain);
		return CMD_STATUS_INVALID_ARG;
	}

	topic = tmp;
	CMD_DBG("topic name = %s\n", topic);

	buf = cmd_malloc(size);
	if (buf == NULL) {
		CMD_ERR("no memory\n");
		return CMD_STATUS_FAIL;
	}


	cmd_write_respond(CMD_STATUS_OK, "OK");
	cmd_raw_mode_enable();
	cmd_raw_mode_read(buf, size, 30000);

	message.qos = qos;
	message.retained = retain;
	message.payload = buf;
	message.payloadlen = size;

	if (OS_MutexLock(&lock, 60000) == OS_E_TIMEOUT)
		return CMD_STATUS_FAIL;

	if ((rc = MQTTPublish(&client, topic, &message)) != 0)
		CMD_ERR("Return code from MQTT publish is %d\n", rc);
	else
		CMD_DBG("MQTT publish is success\n");

	OS_MutexUnlock(&lock);

	cmd_raw_mode_write((uint8_t *)&rc, sizeof(rc));
	cmd_raw_mode_disable();

	cmd_free(buf);

	return CMD_STATUS_ACKED;

}
Example #12
0
int main(int argc, char** argv)
{
	int rc = 0;
	unsigned char buf[100];
	unsigned char readbuf[100];

	/**********UART************/
	int		fd = FALSE;
    int 	ret;
    unsigned char	rcv_buf[512];
	unsigned char 	send_buf[64];
	Data_t	rcv_data;
    int i;
	int j;

    cJSON *root,*img,*thm;
    char *out;
	/* Our "gallery" item: */
	root=cJSON_CreateObject();
	cJSON_AddItemToObject(root, "Image", img=cJSON_CreateObject());
	cJSON_AddNumberToObject(img,"Width",800);
	cJSON_AddNumberToObject(img,"Height",600);
	cJSON_AddStringToObject(img,"Title","View from 15th Floor");
	cJSON_AddItemToObject(img, "Thumbnail", thm=cJSON_CreateObject());
	cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");
	cJSON_AddNumberToObject(thm,"Height",125);
	cJSON_AddStringToObject(thm,"Width","100");
	out=cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n",out);	free(out);	/* Print to text, Delete the cJSON, print it, release the string. */

	fd = UART_Open(fd,"/dev/ttyS1");
    if(FALSE == fd){
	   printf("open error\n");
	   exit(1);
    }
    ret  = UART_Init(fd,115200,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));

	if (argc < 2)
		usage();

	char* topic = argv[1];

//	if (strchr(topic, '#') || strchr(topic, '+'))
//		opts.showtopics = 1;
//	if (opts.showtopics)
//		printf("topic is %s\n", topic);

	getopts(argc, argv);

	Network n;
	Client c;
	MQTTMessage message={0,0,0,0,"hello",5};//dup,qos,retained,packetid,payload,payloadlen


	NewNetwork(&n);
	ConnectNetwork(&n, opts.host, opts.port);
	MQTTClient(&c, &n, 1000, buf, 100, readbuf, 100);

	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.clientID.cstring = opts.clientid;
	data.username.cstring = opts.username;
	data.password.cstring = opts.password;

	data.keepAliveInterval = 10;
	data.cleansession = 1;
	printf("Connecting to %s %d\n", opts.host, opts.port);

	rc = MQTTConnect(&c, &data);
	printf("Connected %d\n", rc);

//test
while(1)
{
		message.payload = "efewewreweefer";
        message.payloadlen = strlen(message.payload);
			MQTTPublish(&c,topic,&message);
}
	while (!toStop)
	{
		MQTTYield(&c, 1000);
	}
	printf("Stopping\n");
	UART_Close(fd);
	MQTTDisconnect(&c);
	n.disconnect(&n);

	return 0;
}
Example #13
0
static void mqtt_client_thread(void *pvParameters)
{
    char *payload = NULL;
    MQTTClient client;
    Network network;
    int rc = 0;
    char clientID[32] = {0};
    uint32_t count = 0;

    ESP_LOGI(TAG, "ssid:%s passwd:%s sub:%s qos:%u pub:%s qos:%u pubinterval:%u payloadsize:%u",
             CONFIG_WIFI_SSID, CONFIG_WIFI_PASSWORD, CONFIG_MQTT_SUB_TOPIC,
             CONFIG_DEFAULT_MQTT_SUB_QOS, CONFIG_MQTT_PUB_TOPIC, CONFIG_DEFAULT_MQTT_PUB_QOS,
             CONFIG_MQTT_PUBLISH_INTERVAL, CONFIG_MQTT_PAYLOAD_BUFFER);

    ESP_LOGI(TAG, "ver:%u clientID:%s keepalive:%d username:%s passwd:%s session:%d level:%u",
             CONFIG_DEFAULT_MQTT_VERSION, CONFIG_MQTT_CLIENT_ID,
             CONFIG_MQTT_KEEP_ALIVE, CONFIG_MQTT_USERNAME, CONFIG_MQTT_PASSWORD,
             CONFIG_DEFAULT_MQTT_SESSION, CONFIG_DEFAULT_MQTT_SECURITY);

    ESP_LOGI(TAG, "broker:%s port:%u", CONFIG_MQTT_BROKER, CONFIG_MQTT_PORT);

    ESP_LOGI(TAG, "sendbuf:%u recvbuf:%u sendcycle:%u recvcycle:%u",
             CONFIG_MQTT_SEND_BUFFER, CONFIG_MQTT_RECV_BUFFER,
             CONFIG_MQTT_SEND_CYCLE, CONFIG_MQTT_RECV_CYCLE);

    MQTTPacket_connectData connectData = MQTTPacket_connectData_initializer;

    NetworkInit(&network);

    if (MQTTClientInit(&client, &network, 0, NULL, 0, NULL, 0) == false) {
        ESP_LOGE(TAG, "mqtt init err");
        vTaskDelete(NULL);
    }

    payload = malloc(CONFIG_MQTT_PAYLOAD_BUFFER);

    if (!payload) {
        ESP_LOGE(TAG, "mqtt malloc err");
    } else {
        memset(payload, 0x0, CONFIG_MQTT_PAYLOAD_BUFFER);
    }

    for (;;) {
        ESP_LOGI(TAG, "wait wifi connect...");
        xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);

        if ((rc = NetworkConnect(&network, CONFIG_MQTT_BROKER, CONFIG_MQTT_PORT)) != 0) {
            ESP_LOGE(TAG, "Return code from network connect is %d", rc);
            continue;
        }

        connectData.MQTTVersion = CONFIG_DEFAULT_MQTT_VERSION;

        sprintf(clientID, "%s_%u", CONFIG_MQTT_CLIENT_ID, esp_random());

        connectData.clientID.cstring = clientID;
        connectData.keepAliveInterval = CONFIG_MQTT_KEEP_ALIVE;

        connectData.username.cstring = CONFIG_MQTT_USERNAME;
        connectData.password.cstring = CONFIG_MQTT_PASSWORD;

        connectData.cleansession = CONFIG_DEFAULT_MQTT_SESSION;

        ESP_LOGI(TAG, "MQTT Connecting");

        if ((rc = MQTTConnect(&client, &connectData)) != 0) {
            ESP_LOGE(TAG, "Return code from MQTT connect is %d", rc);
            network.disconnect(&network);
            continue;
        }

        ESP_LOGI(TAG, "MQTT Connected");

#if defined(MQTT_TASK)

        if ((rc = MQTTStartTask(&client)) != pdPASS) {
            ESP_LOGE(TAG, "Return code from start tasks is %d", rc);
        } else {
            ESP_LOGI(TAG, "Use MQTTStartTask");
        }

#endif

        if ((rc = MQTTSubscribe(&client, CONFIG_MQTT_SUB_TOPIC, CONFIG_DEFAULT_MQTT_SUB_QOS, messageArrived)) != 0) {
            ESP_LOGE(TAG, "Return code from MQTT subscribe is %d", rc);
            network.disconnect(&network);
            continue;
        }

        ESP_LOGI(TAG, "MQTT subscribe to topic %s OK", CONFIG_MQTT_SUB_TOPIC);

        for (;;) {
            MQTTMessage message;

            message.qos = CONFIG_DEFAULT_MQTT_PUB_QOS;
            message.retained = 0;
            message.payload = payload;
            sprintf(payload, "message number %d", ++count);
            message.payloadlen = strlen(payload);

            if ((rc = MQTTPublish(&client, CONFIG_MQTT_PUB_TOPIC, &message)) != 0) {
                ESP_LOGE(TAG, "Return code from MQTT publish is %d", rc);
            } else {
                ESP_LOGI(TAG, "MQTT published topic %s, len:%u heap:%u", CONFIG_MQTT_PUB_TOPIC, message.payloadlen, esp_get_free_heap_size());
            }

            if (rc != 0) {
                break;
            }

            vTaskDelay(CONFIG_MQTT_PUBLISH_INTERVAL / portTICK_RATE_MS);
        }

        network.disconnect(&network);
    }

    ESP_LOGW(TAG, "mqtt_client_thread going to be deleted");
    vTaskDelete(NULL);
    return;
}
Example #14
0
static void  mqtt_task(void *pvParameters)
{
    int ret         = 0;
    struct Network network;
    MQTTClient client   = DefaultClient;
    char mqtt_client_id[20];
    uint8_t mqtt_buf[100];
    uint8_t mqtt_readbuf[100];
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;

    NewNetwork( &network );
    memset(mqtt_client_id, 0, sizeof(mqtt_client_id));
    strcpy(mqtt_client_id, "ESP-");
    strcat(mqtt_client_id, get_my_id());

    while(1) {
        xSemaphoreTake(wifi_alive, portMAX_DELAY);
        printf("%s: started\n\r", __func__);
        printf("%s: (Re)connecting to MQTT server %s ... ",__func__,
               MQTT_HOST);
        ret = ConnectNetwork(&network, MQTT_HOST, MQTT_PORT);
        if( ret ){
            printf("error: %d\n\r", ret);
            taskYIELD();
            continue;
        }
        printf("done\n\r");
        NewMQTTClient(&client, &network, 5000, mqtt_buf, 100,
                      mqtt_readbuf, 100);

        data.willFlag       = 0;
        data.MQTTVersion    = 3;
        data.clientID.cstring   = mqtt_client_id;
        data.username.cstring   = MQTT_USER;
        data.password.cstring   = MQTT_PASS;
        data.keepAliveInterval  = 10;
        data.cleansession   = 0;
        printf("Send MQTT connect ... ");
        ret = MQTTConnect(&client, &data);
        if(ret){
            printf("error: %d\n\r", ret);
            DisconnectNetwork(&network);
            taskYIELD();
            continue;
        }
        printf("done\r\n");
        MQTTSubscribe(&client, "/esptopic", QOS1, topic_received);
        xQueueReset(publish_queue);

        while(1){

            char msg[PUB_MSG_LEN - 1] = "\0";
            while(xQueueReceive(publish_queue, (void *)msg, 0) ==
                  pdTRUE){
                printf("got message to publish\r\n");
                MQTTMessage message;
                message.payload = msg;
                message.payloadlen = PUB_MSG_LEN;
                message.dup = 0;
                message.qos = QOS1;
                message.retained = 0;
                ret = MQTTPublish(&client, "/beat", &message);
                if (ret != SUCCESS ){
                    printf("error while publishing message: %d\n", ret );
                    break;
                }
            }

            ret = MQTTYield(&client, 1000);
            if (ret == DISCONNECTED)
                break;
        }
        printf("Connection dropped, request restart\n\r");
        DisconnectNetwork(&network);
        taskYIELD();
    }
}
Example #15
0
/*
 * Application's entry point dynamic schedule.  Main is somewhat too large because of the MQTT stuff
 * allmighty whileloop
 */
int main(int argc, char** argv)
{

    /* Stop WDT and initialize lcd, clcks, main interfaces */
    stopWDT();
    init_clocks(); //init clock for LCD
    init_lcd();
    initClk(); //init clock for wifi
    Delay(5);
    init_main();
    Delay(5);

    load_data();

    int rc = 0;
    unsigned char buf[100];
    unsigned char readbuf[100];

    NewNetwork(&n);
    rc = ConnectNetwork(&n, MQTT_BROKER_SERVER, 1883);

    if (rc != 0) {
        CLI_Write(" Failed to connect to MQTT broker \n\r");
    }

    MQTTClient(&hMQTTClient, &n, 1000, buf, 100, readbuf, 100);
    MQTTPacket_connectData cdata = MQTTPacket_connectData_initializer;
    cdata.MQTTVersion = 3;
    cdata.clientID.cstring = "daniel";
    rc = MQTTConnect(&hMQTTClient, &cdata);

    if (rc != 0) {
        CLI_Write(" Failed to start MQTT client \n\r");
        //LOOP_FOREVER();
    }

    rc = MQTTSubscribe(&hMQTTClient, SUBSCRIBE_TOPIC, QOS0, messageArrived);

    if (rc != 0) {
        CLI_Write(" Failed to subscribe to /msp/cc3100/demo topic \n\r");
        //LOOP_FOREVER();
    }

    MQTTYield(&hMQTTClient, 10);
    int8_t buffer[2] = "on";
    MQTTMessage msg;
    msg.dup = 0;
    msg.id = 0;
    msg.payload = buffer;
    msg.payloadlen = 8;
    msg.qos = QOS0;
    msg.retained = 0;
    MQTTPublish(&hMQTTClient, PUBLISH_TOPIC, &msg);
    Delay(20);

    backlight_off();
    while(1) {
        MQTTYield(&hMQTTClient, 10);
        debounce++;

        if(send_goal_bool) {
            int8_t buffer2[15] = "               ";
            sprintf(buffer2, "%d", goal_steps);
            msg;
            msg.dup = 0;
            msg.id = 0;
            msg.payload = buffer2;
            msg.payloadlen = 15;
            msg.qos = QOS0;
            msg.retained = 0;
            MQTTPublish(&hMQTTClient, PUBLISH_TOPIC, &msg);
            Delay(20);
            send_goal_bool = 0;
        }else if(send_on_bool) {
            int8_t buffer2[2] = "on";
            msg;
            msg.dup = 0;
            msg.id = 0;
            msg.payload = buffer2;
            msg.payloadlen = 2;
            msg.qos = QOS0;
            msg.retained = 0;
            MQTTPublish(&hMQTTClient, PUBLISH_TOPIC, &msg);
            Delay(20);
            send_on_bool = 0;
        } else if( (P3IN & BIT5) == 0 && debounce > 20) {
          debounce = 0;
          menu_select();
        } else if ( (P1IN & BIT4) == 0 && debounce > 10) {
          debounce = 0;
          menu();
        } else if ( steps_taken >= goal_steps && active_bool == 1 ) {
          P1OUT &= ~BIT0;
          int8_t buffer2[1] = "g";
          msg;
          msg.dup = 0;
          msg.id = 0;
          msg.payload = buffer2;
          msg.payloadlen = 1;
          msg.qos = QOS0;
          msg.retained = 0;
          MQTTPublish(&hMQTTClient, "on", &msg);
          Delay(20);
          MAP_Interrupt_disableInterrupt(INT_ADC14);
          active_bool = 0;
          view_goal_menu();
        }
    }
}
Example #16
0
int main(int argc, char** argv)
{
	int rc = 0;
    struct pando_buffer *bin_buf;
    uint16_t payload_type = 0;
    MQTTMessage msg;
	unsigned char buf[500];
	unsigned char readbuf[500];
    char payload_type_c[] = {'c', 'e', 'd'};
    
    bin_buf = construct_data_package_to_server(&payload_type);
    decode_data(bin_buf, PAYLOAD_TYPE_DATA);

    /* command test, event is same as command except the type */
    bin_buf = constuct_event_package_to_server(&payload_type);
    decode_command(bin_buf, PAYLOAD_TYPE_COMMAND);
    return 0;
    
	if (argc < 2)
		usage();
	
	char* topic = argv[1];

    getopts(argc, argv);
    
	if (strchr(topic, '#') || strchr(topic, '+'))
		opts.showtopics = 1;
	if (opts.showtopics)
		printf("topic is %s\n", topic);

		

	Network n;
	Client c;

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

	NewNetwork(&n);
	ConnectNetwork(&n, opts.host, opts.port);
	MQTTClient(&c, &n, 1000, buf, 100, readbuf, 100);
 
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.clientID.cstring = opts.clientid;
	data.username.cstring = opts.username;
	data.password.cstring = opts.password;

	data.keepAliveInterval = 10;
	data.cleansession = 1;
	printf("Connecting to %s %d\n", opts.host, opts.port);
	
	rc = MQTTConnect(&c, &data);
	printf("Connected %d\n", rc);
    
    printf("Subscribing to %s\n", topic);
	rc = MQTTSubscribe(&c, topic, opts.qos, messageArrived);
	printf("Subscribed %d\n", rc);

	while (!toStop)
	{        
		MQTTYield(&c, 1000);
        
        if (toSend)
        {
            if (strstr(topic, "/d"))
            {
                /* data test */
                bin_buf = construct_data_package_to_server(&payload_type);
                //decode_data(bin_buf, PAYLOAD_TYPE_DATA);
            }

            if (strstr(topic, "/e"))
            {
                /* command test */
                bin_buf = constuct_event_package_to_server(&payload_type);
                //decode_command(bin_buf, PAYLOAD_TYPE_COMMAND);
            }
            msg.qos = opts.qos;
            msg.retained = 0;
            msg.dup = 0;
            
            msg.payload = bin_buf->buffer + bin_buf->offset;
            msg.payloadlen = bin_buf->buff_len - bin_buf->offset;

            /* 
                        before publish a message, you need to generate a topic with payload_type
                        max device id is 8 bytes, hex to char need 8*2 bytes, '/' need 1 byte, type need 1 byte 
                    */
            char publish_topic[8*2 + 1 + 1];
            memset(publish_topic, 0, sizeof(publish_topic));
            sprintf(publish_topic, "%s/%c", opts.clientid, payload_type_c[payload_type - 1]);
            printf(publish_topic);
            
            rc = MQTTPublish(&c, publish_topic, &msg);
            toSend = 0;
            pd_free(bin_buf);
            printf("published rc %d, len %d\n", rc, (int)msg.payloadlen);
        }

	}
	
	printf("Stopping\n");

	MQTTDisconnect(&c);
	n.disconnect(&n);

	return 0;
}