コード例 #1
0
ファイル: stdoutsub.c プロジェクト: ngocphu811/RasPi-mqtt-c
int main(int argc, char** argv)
{
	int rc = 0;
	unsigned char buf[1024];
	unsigned char readbuf[1024];

	Network n;
	Client c;

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

	NewNetwork(&n);
	ConnectNetwork(&n, "eu.airvantage.net", 1883);
	MQTTClient(&c, &n, 1000, buf, 1024, readbuf, 1024);
 
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.clientID.cstring = deviceId;
	data.username.cstring = "00000000B6AF4A9D";
	data.password.cstring = "toto";

	data.keepAliveInterval = 10000;
	data.cleansession = 1;
	printf("Connecting to %s %d\n", "tcp://eu.airvantage.net", 1883);
	
	rc = MQTTConnect(&c, &data);
	printf("Connected %d\n", rc);
    

	char* topic = malloc(strlen(deviceId)+13);
	sprintf(topic, "%s/tasks/json", deviceId);

        printf("Subscribing to %s\n", topic);
	rc = MQTTSubscribe(&c, topic, 0, messageArrived);
	printf("Subscribed %d\n", rc);

	int err1 = pthread_create(&reading_tid, NULL, &readMeasuresHandler, (void*)&c);
	int err2 = pthread_create(&uploading_tid, NULL, &uploadMeasuresHandler, (void*) &c);
	if(err1 != 0 || err2 != 0)
		printf("Can't create simulator (%s, %d)\n", strerror(err1), err2);
	else
	{
		while (!toStop)
		{
			MQTTYield(&c, 1000);	
		}
	}
	
	printf("Stopping\n");

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

	return 0;
}
コード例 #2
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 */
}
コード例 #3
0
ファイル: cmd_mqtt.c プロジェクト: diguokaituozhe/XR871
static enum cmd_status cmd_mqtt_connect_exec(char *cmd)
{
	int32_t cnt;
	char addr_str[15];
	uint32_t port;
	int32_t rc;
	uint32_t i;

	/* get param */
	cnt = cmd_sscanf(cmd, "server=%15s port=%u",
			 addr_str, &port);

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

	i = 10;
	char* address = addr_str;
	while ((rc = ConnectNetwork(&network, address, port)) != 0)
	{
		CMD_WRN("Return code from network connect is %d\n", rc);
		cmd_msleep(2000);
		if (!(i--))
			return CMD_STATUS_FAIL;
	}

	if ((rc = MQTTConnect(&client, &connectData)) != 0) {
		CMD_ERR("Return code from MQTT connect is %d\n", rc);
		return CMD_STATUS_FAIL;
	}
	else
		CMD_DBG("MQTT Connected\n");



	if (OS_ThreadCreate(&mqtt_bg_thread,
		                "",
		                cmd_mqtt_bg,
		                NULL,
		                OS_PRIORITY_NORMAL,
		                CMD_MQTT_BG_THREAD_STACK_SIZE) != OS_OK) {
		CMD_ERR("create mqtt background failed\n");
		return CMD_STATUS_FAIL;
	}


	return CMD_STATUS_OK;
}
コード例 #4
0
ファイル: iotfclient.c プロジェクト: kiranshashiny/BlinkLed
/**
* Function used to initialize the IoTF client
* @param client - Reference to the Iotfclient
*
* @return int return code
*/
int connectiotf(Iotfclient *client)
{

	int rc = 0;
	if(strcmp(client->config.org,"quickstart") == 0){
		isQuickstart = 1 ;
	}

	const char* messagingUrl = ".messaging.internetofthings.ibmcloud.com";

	char hostname[strlen(client->config.org) + strlen(messagingUrl) + 1];
	
	sprintf(hostname, "%s%s", client->config.org, messagingUrl);

    //TODO : change to 8883 if registered, add support when available in MQTTClient
    int port = 1883;

    char clientId[strlen(client->config.org) + strlen(client->config.type) + strlen(client->config.id) + 5];
    sprintf(clientId, "d:%s:%s:%s", client->config.org, client->config.type, client->config.id);

	NewNetwork(&client->n);
	ConnectNetwork(&client->n, hostname, port);
	MQTTClient(&client->c, &client->n, 1000, buf, 100, readbuf, 100);
 
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.clientID.cstring = clientId;

	if(!isQuickstart) {
		printf("Connecting to registered service with org %s\n", client->config.org);
		data.username.cstring = "use-token-auth";
		printf ("the auth token being used is [%s]\n", client->config.authtoken);
		data.password.cstring = client->config.authtoken;
	}

	data.keepAliveInterval = 10;
	data.cleansession = 1;
	
	rc = MQTTConnect(&client->c, &data);

	if(!isQuickstart) {
		//Subscibe to all commands
		subscribeCommands(client);
	}

	return rc;
}
コード例 #5
0
ファイル: app.c プロジェクト: sheinz/esp-gizmo-ir-remote
static inline void mqtt_task()
{
    struct Network network;
    char client_id[20];
    uint8_t mqtt_buf[100];
    uint8_t mqtt_readbuf[100];
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;

    NewNetwork( &network );
    strcpy(client_id, "esp-gizmo-ir");

    if (ConnectNetwork(&network, config_get_mqtt_host(),
                config_get_mqtt_port()) != 0) {
        printf("Connect to MQTT server failed\n");
        return;
    }

    NewMQTTClient(&mqtt_client, &network, 5000, mqtt_buf, 100, mqtt_readbuf, 100);

    data.willFlag       = 0;
    data.MQTTVersion    = 3;
    data.clientID.cstring   = client_id;
    data.username.cstring   = NULL;
    data.password.cstring   = NULL;
    data.keepAliveInterval  = 10;
    data.cleansession   = 0;

    printf("Send MQTT connect ... \n");
    if (MQTTConnect(&mqtt_client, &data) != 0) {
        printf("MQTT connect failed\n");
        return;
    }

    const char *topic = config_get_cmd_topic();
    printf("Sibscribe to topic: %s\n", topic);
    if (MQTTSubscribe(&mqtt_client, topic, QOS1, topic_received) != 0) {
        printf("Subscription failed\n");
        return;
    }

    while (MQTTYield(&mqtt_client, 1000) != DISCONNECTED) {
        printf("free heap: %d bytes\n", xPortGetFreeHeapSize());
        uint16_t free_stack = uxTaskGetStackHighWaterMark(xTaskGetCurrentTaskHandle());
        printf("minimum free stack: %d bytes\n", free_stack);
    };

    printf("Connection dropped, request restart\n");
}
コード例 #6
0
ファイル: ev_wrap.c プロジェクト: yanlunyao/SmartStoreGateway
static void mqtt_connect_cb(EV_P_ ev_io *w, int revents)
{
	EV_ALL *cev = (EV_ALL *)(((char *)w) - offsetof (EV_ALL, mt_connectw));

	ev_io_stop(cev->mainloop, &cev->mt_connectw);
	ev_io_start(cev->mainloop, &cev->mt_readw);

	if(cev->client.keepAliveInterval >0)
	{
		ev_timer_init(&cev->mt_pingw, mqtt_ping_cb, 0, PING_INTERVAL);//发ping包时间要小于keepAliveInterval
		log_printf(LOG_NOTICE, "init ping timer,timer interval is %d\n", PING_INTERVAL);
	}
	//重连次数重置
	cev->client.reconnect_count =0;

	//发connect包
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	data.willFlag = WILL_FLAG;
	data.MQTTVersion = MQTT_VERSION;
	char client_id[DID_LEN];
	char username[MAC_LEN];
	char password[PASSCODE_LEN];
	snprintf(client_id, sizeof(client_id), "%s", gateway_info.did);
	snprintf(username, sizeof(username), "%s", gateway_info.mac);
	snprintf(password, sizeof(password), "%s", gateway_info.passcode);
	data.clientID.cstring = client_id;
	data.username.cstring = username;
	data.password.cstring = password;
	data.keepAliveInterval = KEEPALIVE_INTERVAL;
	data.cleansession = CLEANSESSIN;


	log_printf(LOG_NOTICE, "[MqttSocketConnected]: %s, %d\n", cev->client.mqtt_server, cev->client.mqtt_port);

	MQTTConnect(&cev->client, &data);
	log_printf(LOG_NOTICE, "willFlag: %d, clientID: %s, username: %s, password: %s, keepAliveInterval: %d, cleansession: %d\n",
			data.willFlag, data.clientID.cstring, data.username.cstring, data.password.cstring, data.keepAliveInterval, data.cleansession);

}
コード例 #7
0
ファイル: stdoutpub_2.c プロジェクト: superlikex/openwrt-mqtt
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;
}
コード例 #8
0
ファイル: MQTTEcho.c プロジェクト: espressif/ESP8266_RTOS_SDK
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;
}
コード例 #9
0
ファイル: mpush.c プロジェクト: cgoder/cpush
int Cpush_connect(unsigned int* clientHandle,struct connectOpt* pOpt)
{
	int ret = CPUSH_RET_OK;
	*clientHandle = 0;
	unsigned char* buf = 0;
	unsigned char* readbuf = 0;
	Network* network = NULL;
	Client* pClient = NULL;

	if (!pOpt) {
		ret = CPUSH_RET_ERROR_PARA;
		goto FAIL;
	}

	/*check client id*/
	if ((!pOpt->clientid)|| (strlen((const char*)pOpt->clientid) > MOSQ_MQTT_ID_MAX_LENGTH)){
		ret = CPUSH_RET_ERROR_PARA;
		goto FAIL;
	}

	/*connect to host*/
	// Network n;
	network = (Network*)calloc(1,sizeof(Network));
	if (!network) {
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	NewNetwork(network);
	if (ConnectNetwork(network, (char*)pOpt->host, pOpt->port) < 0) {
		printf("connect to %s:%d error!\n", pOpt->host, pOpt->port);
		ret = CPUSH_RET_ERROR_CONNECTFAIL;
		goto FAIL;
	}

	/*init mqtt client*/
	pClient = (Client*)calloc(1,sizeof(Client));
	if (!pClient) {
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	buf = (unsigned char*)calloc(MOSQ_MQTT_BUFFER_MAX_SIZE,sizeof(char));
	if (!buf) {
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	readbuf = (unsigned char*)calloc(MOSQ_MQTT_BUFFER_MAX_SIZE,sizeof(char));
	if (!readbuf) {
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	MQTTClient(pClient, network, 1000, buf, MOSQ_MQTT_BUFFER_MAX_SIZE, readbuf, MOSQ_MQTT_BUFFER_MAX_SIZE);

	/*connect to mqtt server*/
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
	data.willFlag = 0;
	data.MQTTVersion = 4;
	data.cleansession = 1;
	data.clientID.cstring = pOpt->clientid;
	if (pOpt->username) {
		data.username.cstring = pOpt->username;		
	}
	if (pOpt->password) {
		data.password.cstring = pOpt->password;		
	}
	data.keepAliveInterval = 10;
	printf("Connecting to %s %d\n", pOpt->host, pOpt->port);
	int rc = MQTTConnect(pClient, &data);
	printf("Connected %d\n", rc);
	if (SUCCESS != rc) {
		printf("Cpush_connect fail! ret:%d", rc);
		ret = CPUSH_RET_FAIL;
		goto FAIL;
	}
	printf("Cpush_connect OK!");
	ret = CPUSH_RET_OK;
	*clientHandle = (unsigned int)pClient;
	return CPUSH_RET_OK;

FAIL:
	if (0 != network->my_socket) {network->disconnect(network);}
	if (network) {free(network);}
	if (buf) {free(buf);}
	if (readbuf) {free(readbuf);}
	if (pClient) {free(pClient);}
	return ret;
}
コード例 #10
0
ファイル: mqtt_client.c プロジェクト: BorgesJVT/esp-open-rtos
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();
    }
}
コード例 #11
0
ファイル: main.c プロジェクト: DDEFISHER/ECE461Final
/*
 * 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();
        }
    }
}
コード例 #12
0
ファイル: AJBMqttClient.c プロジェクト: Rokey1990/mqttc-test
MqttReturnCode mqttClient_connect(AJBMqttClient *client, char *host,int port){
    
    int rc = 0;//return code of mqtt function
    
    if (host != client->host) {
        strcpy(client->host, host);
    }
    
    client->port = port;
    NewNetwork(&client->n);
    
    int interval = client->aliveAttr.recon_int;
    interval = interval>0?interval:1;
    int max = client->aliveAttr.recon_max;
    client->c.indexTag = client->indexTag;
reconnect:
    rc = ConnectNetwork(&client->n, host, port);
//    MqttLog("connect result -------> %d",rc);
    MQTTClient(&client->c, &client->n, client->timout_ms, client->sendBuf, PACKET_BUF_SIZE, client->readBuf, PACKET_BUF_SIZE);
    
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    
    //    data.willFlag = 0;
    data.MQTTVersion = 4;
    data.clientID.cstring = client->clientId;
    data.username.cstring = client->username;
    data.password.cstring = client->password;
    data.keepAliveInterval = client->keepAlive;
    data.cleansession = client->cleanSession;
    
    if (client->will.willFlag) {
        data.willFlag = client->will.willFlag;
        data.will.message.cstring = client->will.willContent;
        data.will.qos = 2;
        data.will.retained = client->will.retain;
        data.will.topicName.cstring = client->will.willTopic;
    }
    MqttLog("[CONNECT request] %s:%d",host,port);
    rc = MQTTConnect(&client->c, &data);
    
    client->isConnected = (rc==SUCCESS);
    
    if(rc == SUCCESS){
        printf("%s,%16s:%d,%4d ----------------ok\n",client->clientId,host,port,client->cleanSession);
        reportOnline(client);
    }
    else{
        client->n.disconnect(&client->n);
        if (client->dispatcher.onLoop) {
            client->dispatcher.onLoop(client);
        }
        MqttLog("[CONNECT failed] %s:%d",host,port);
        logToLocal(client->indexTag,log_erro_path,"[CONNECT failed] %s:%d ---> %s %d",host,port,client->clientId,client->keepworking);
        if (client->keepworking) {
            if (client->aliveAttr.auto_con && ((client->aliveAttr.recon_max==0) || (--max >0)) ) {
                sleep(interval);
                goto reconnect;
            }
        }
    }
    
    return rc;
}
IoT_Error_t aws_iot_mqtt_connect(MQTTConnectParams *pParams) {
    IoT_Error_t rc = NONE_ERROR;
    MQTTReturnCode pahoRc = SUCCESS;

    if(NULL == pParams || NULL == pParams->pClientID || NULL == pParams->pHostURL) {
        return NULL_VALUE_ERROR;
    }

    TLSConnectParams TLSParams;
    TLSParams.DestinationPort = pParams->port;
    TLSParams.pDestinationURL = pParams->pHostURL;
    TLSParams.pDeviceCertLocation = pParams->pDeviceCertLocation;
    TLSParams.pDevicePrivateKeyLocation = pParams->pDevicePrivateKeyLocation;
    TLSParams.pRootCALocation = pParams->pRootCALocation;
    TLSParams.timeout_ms = pParams->tlsHandshakeTimeout_ms;
    TLSParams.ServerVerificationFlag = pParams->isSSLHostnameVerify;

    // This implementation assumes you are not going to switch between cleansession 1 to 0
    // As we don't have a default subscription handler support in the MQTT client every time a device power cycles it has to re-subscribe to let the MQTT client to pass the message up to the application callback.
    // The default message handler will be implemented in the future revisions.
    if(pParams->isCleansession || isPowerCycle) {
        pahoRc = MQTTClient(&c, (unsigned int)(pParams->mqttCommandTimeout_ms), writebuf,
                            AWS_IOT_MQTT_TX_BUF_LEN, readbuf, AWS_IOT_MQTT_RX_BUF_LEN,
                            pParams->enableAutoReconnect, iot_tls_init, &TLSParams);
        if(SUCCESS != pahoRc) {
            return CONNECTION_ERROR;
        }
        isPowerCycle = false;
    }

    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;

    data.willFlag = pParams->isWillMsgPresent;
    // compatible type for MQTT_Ver_t
    switch (pParams->MQTTVersion) {
    case MQTT_3_1:
        data.MQTTVersion = (unsigned char) (3);
        break;
    case MQTT_3_1_1:
        data.MQTTVersion = (unsigned char) (4);
        break;
    default:
        data.MQTTVersion = (unsigned char) (4); // default MQTT version = 3.1.1
    }

    // register our disconnect handler, save customer's handler
    setDisconnectHandler(&c, pahoDisconnectHandler);
    clientDisconnectHandler = pParams->disconnectHandler;

    data.clientID.cstring = pParams->pClientID;
    data.username.cstring = pParams->pUserName;
    data.password.cstring = pParams->pPassword;
    data.will.topicName.cstring = (char*)pParams->will.pTopicName;
    data.will.message.cstring = (char*)pParams->will.pMessage;
    data.will.qos = pParams->will.qos;
    data.will.retained = pParams->will.isRetained;
    data.keepAliveInterval = pParams->KeepAliveInterval_sec;
    data.cleansession = pParams->isCleansession;

    pahoRc = MQTTConnect(&c, &data);
    if(MQTT_NETWORK_ALREADY_CONNECTED_ERROR == pahoRc) {
        rc = NETWORK_ALREADY_CONNECTED;
    } else if(SUCCESS != pahoRc) {
        rc = CONNECTION_ERROR;
    }

    return rc;
}
コード例 #14
0
ファイル: stdoutsub.c プロジェクト: DenisZheng/pando-protocol
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;
}
コード例 #15
0
ファイル: sockutil.c プロジェクト: Wiznet/WIZ550S2E
/**
 * Sockwatch Module Handler
 * If you use Sockwatch Module, this should run in the main loop
 * @ingroup sockwatch_module
 */
void sockwatch_run(void)
{
#define WCF_HANDLE(item_v, ret_v) \
do { \
	BITCLR(watch_sock[i], item_v); \
	watch_cb[i](i, item_v, ret_v); \
} while(0)

	uint8_t i;
	int32_t ret;

	S2E_Packet *value = get_S2E_Packet_pointer();
	MQTTPacket_connectData mqttConnectData = MQTTPacket_connectData_initializer;

	for(i=0; i<TOTAL_SOCK_NUM; i++) {
		if(watch_sock[i] == 0) continue;
		if(atci.mqtt_run == 1) {
			ret = MQTTYield(&mqttClient, mqttConnectData.keepAliveInterval);
#ifdef __ATC_MODE_MQTT_DEBUG__
			if(ret != SUCCESSS) {
				printf("MQTT yield error - ret : %d\r\n", ret);
			}
#endif
		}
		if(watch_sock[i] & WATCH_SOCK_RECV) {	// checked every time when 'connected' state
			getsockopt(i, SO_RECVBUF, (uint16_t*)&ret);
			if((uint16_t)ret > 0) WCF_HANDLE(WATCH_SOCK_RECV, RET_OK);
		}
		if(watch_sock[i] & WATCH_SOCK_CLS_EVT) {	// checked every time when 'connected' state
			getsockopt(i, SO_STATUS, (uint8_t*)&ret);
			switch((uint8_t)ret) {
			case SOCK_CLOSED:
				WCF_HANDLE(WATCH_SOCK_CLS_EVT, RET_OK);
				break;
			case SOCK_CLOSE_WAIT:
				disconnect(i);
				//close(i);
				break;
			default:
				break;
			}
		}
		if(watch_sock[i] & WATCH_SOCK_CONN_EVT) {	// checked every time when 'listen' state
			getsockopt(i, SO_STATUS, (uint8_t*)&ret);
			switch((uint8_t)ret) {
			case SOCK_ESTABLISHED:
				WCF_HANDLE(WATCH_SOCK_CONN_EVT, RET_OK);
				break;
			default:
				break;
			}
		}
		if((watch_sock[i] & WATCH_SOCK_MASK_LOW) == 0) continue;	// things which occurs occasionally will be checked all together
		if(watch_sock[i] & WATCH_SOCK_CLS_TRY) {
			getsockopt(i, SO_STATUS, (uint8_t*)&ret);
			switch((uint8_t)ret) {
			case SOCK_LISTEN:
				close(i);
			case SOCK_CLOSED:
				WCF_HANDLE(WATCH_SOCK_CLS_TRY, RET_OK);
				break;
			case SOCK_FIN_WAIT:
				close(i);	
				break;
			default:
				ctlsocket(i, CS_GET_INTERRUPT, (uint8_t*)&ret);
				if((uint8_t)ret & Sn_IR_TIMEOUT){
					//ctlsocket(i, CS_CLR_INTERRUPT, (uint8_t*)&ret);
					close(i);
					WCF_HANDLE(WATCH_SOCK_CLS_TRY, SOCKERR_TIMEOUT);
				}
				disconnect(i);
				//close(i);
				break;
			}
		}
		if(watch_sock[i] & WATCH_SOCK_CONN_TRY) {
			getsockopt(i, SO_STATUS, (uint8_t*)&ret);
			switch((uint8_t)ret) {
			case SOCK_ESTABLISHED:
				WCF_HANDLE(WATCH_SOCK_CONN_TRY, RET_OK);
				if(atci.mqtt_con == 1) {
					if(getSn_IR(i) & Sn_IR_CON) {
						setSn_IR(i,Sn_IR_CON);

						mqttConnectData.MQTTVersion			= 4;
						mqttConnectData.clientID.cstring 	= value->module_name;
						mqttConnectData.username.cstring 	= value->options.mqtt_user;
						mqttConnectData.password.cstring 	= value->options.mqtt_pw;
						mqttConnectData.willFlag 			= 0;
						mqttConnectData.keepAliveInterval   = 60;
						mqttConnectData.cleansession        = 1;

						ret = MQTTConnect(&mqttClient, &mqttConnectData);
#ifdef __ATC_MODE_MQTT_DEBUG__
						if(ret != SUCCESSS) {
							printf("MQTT connect error - ret : %d\r\n", ret);
						}
#endif
						atci.mqtt_con = 0;
						atci.mqtt_run = 1;
					}
				}
				break;
			default:
				ctlsocket(i, CS_GET_INTERRUPT, (uint8_t*)&ret);
				if((uint8_t)ret & Sn_IR_TIMEOUT){
					//ctlsocket(i, CS_CLR_INTERRUPT, (uint8_t*)&ret);
					close(i);
					WCF_HANDLE(WATCH_SOCK_CONN_TRY, SOCKERR_TIMEOUT);
				}
				break;
			}
		}
		if(watch_sock[i] & WATCH_SOCK_TCP_SEND) {
			// 블로킹 모드로만 동작함 그러므로 Watch할 필요가 없음
		}
		if(watch_sock[i] & WATCH_SOCK_UDP_SEND) {
			if(checkAtcUdpSendStatus < 0) {
				WCF_HANDLE(WATCH_SOCK_UDP_SEND, RET_NOK);
			}
			else {
				WCF_HANDLE(WATCH_SOCK_UDP_SEND, RET_OK);
			}
		}
	}

	// ToDo: not socket part
	
}