/* G:9 - Yield, disconnected, Auto-reconnect timed-out */
TEST_C(YieldTests, disconnectAutoReconnectTimeout) {
	IoT_Error_t rc = FAILURE;

	IOT_DEBUG("-->Running Yield Tests - G:9 - Yield, disconnected, Auto-reconnect timed-out \n");

	rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient));
	CHECK_EQUAL_C_INT(true, aws_iot_is_autoreconnect_enabled(&iotClient));

	ResetTLSBuffer();

	/* Sleep for half keep alive interval to allow the first ping to be sent out */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(SUCCESS, rc);
	CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq());

	/* Let ping request time out and call yield */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2 + 1);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc);
	CHECK_EQUAL_C_INT(0, aws_iot_mqtt_is_client_connected(&iotClient));
	CHECK_EQUAL_C_INT(true, dcHandlerInvoked);

	IOT_DEBUG("-->Success - G:9 - Yield, disconnected, Auto-reconnect timed-out \n");
}
/* G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled */
TEST_C(YieldTests, disconnectNoAutoReconnect) {
	IoT_Error_t rc = FAILURE;

	IOT_DEBUG("-->Running Yield Tests - G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled \n");

	rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient));
	CHECK_EQUAL_C_INT(true, aws_iot_is_autoreconnect_enabled(&iotClient));

	/* Disable Autoreconnect, then let ping request time out and call yield */
	aws_iot_mqtt_autoreconnect_set_status(&iotClient, false);
	sleep((uint16_t)(iotClient.clientData.keepAliveInterval / 2));

	ResetTLSBuffer();

	/* Sleep for half keep alive interval to allow the first ping to be sent out */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(SUCCESS, rc);
	CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq());

	/* Let ping request time out and call yield */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2 + 1);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc);
	CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect());
	CHECK_EQUAL_C_INT(0, aws_iot_mqtt_is_client_connected(&iotClient));
	CHECK_EQUAL_C_INT(true, dcHandlerInvoked);

	IOT_DEBUG("-->Success - G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled \n");
}
/* G:8 - Yield, network connected, ping request/response */
TEST_C(YieldTests, PingRequestPingResponse) {
	IoT_Error_t rc = SUCCESS;
	int i = 0;
	int j = 0;
	int attempt = 3;

	IOT_DEBUG("-->Running Yield Tests - G:8 - Yield, network connected, ping request/response \n");
	IOT_DEBUG("Current Keep Alive Interval is set to %d sec.\n", iotClient.clientData.keepAliveInterval);

	for(i = 0; i < attempt; i++) {
		IOT_DEBUG("[Round_%d/Total_%d] Waiting for %d sec...\n", i + 1, attempt, iotClient.clientData.keepAliveInterval);
		/* Set TLS buffer for ping response */
		ResetTLSBuffer();
		setTLSRxBufferForPingresp();

		for(j = 0; j <= iotClient.clientData.keepAliveInterval; j++) {
			sleep(1);
			IOT_DEBUG("[Waited %d secs]", j + 1);
			rc = aws_iot_mqtt_yield(&iotClient, 100);
			CHECK_EQUAL_C_INT(SUCCESS, rc);
		}

		/* Check whether ping was processed correctly and new Ping request was generated */
		CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePingreq());
	}

	IOT_DEBUG("-->Success - G:8 - Yield, network connected, ping request/response \n");
}
/* G:4 - Yield, network disconnected, disconnected manually */
TEST_C(YieldTests, YieldNetworkDisconnectedDisconnectedManually) {
	IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	rc = aws_iot_mqtt_yield(&iotClient, 1000);
	CHECK_EQUAL_C_INT(NETWORK_MANUALLY_DISCONNECTED, rc);
}
コード例 #5
0
void publishMessage(char* message) {
	IoT_Error_t rc = FAILURE;
	IoT_Publish_Message_Params paramsQOS0;
	paramsQOS0.qos = QOS0;
	paramsQOS0.payload = (void *) message;
	paramsQOS0.isRetained = 0;

	while (NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS != rc) {
		//Max time the yield function will wait for read messages
		rc = aws_iot_mqtt_yield(&mqttClient, 1000);

		if (NETWORK_ATTEMPTING_RECONNECT == rc) {
			// If the client is attempting to reconnect we will skip the rest of the loop.
			continue;
		}

		paramsQOS0.payloadLen = strlen(message);

		do {
			rc = aws_iot_mqtt_publish(&mqttClient, publishTopicName, strlen(publishTopicName), &paramsQOS0);
		} while (MQTT_REQUEST_TIMEOUT_ERROR == rc);
	}

	if (SUCCESS != rc) {
		IOT_ERROR("An error occurred while publishing message.\n");
	}	
}
TEST_C(YieldTests, YieldNetworkDisconnectedNeverConnected) {
	AWS_IoT_Client tempIotClient;
	IoT_Error_t rc;

	InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, iot_tests_unit_disconnect_handler);
	rc = aws_iot_mqtt_init(&tempIotClient, &initParams);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	rc = aws_iot_mqtt_yield(&tempIotClient, 1000);
	CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc);
}
/* G:11 - Yield, disconnected, Manual reconnect */
TEST_C(YieldTests, disconnectManualAutoReconnect) {
	IoT_Error_t rc = FAILURE;
	unsigned char *currPayload = NULL;

	IOT_DEBUG("-->Running Yield Tests - G:11 - Yield, disconnected, Manual reconnect \n");

	CHECK_C(aws_iot_mqtt_is_client_connected(&iotClient));

	/* Disable Autoreconnect, then let ping request time out and call yield */
	aws_iot_mqtt_autoreconnect_set_status(&iotClient, false);
	CHECK_C(!aws_iot_is_autoreconnect_enabled(&iotClient));

	/* Sleep for half keep alive interval to allow the first ping to be sent out */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(SUCCESS, rc);
	CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq());

	/* Let ping request time out and call yield */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2 + 1);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc);
	CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect());
	CHECK_C(!aws_iot_mqtt_is_client_connected(&iotClient));
	CHECK_EQUAL_C_INT(true, dcHandlerInvoked);

	dcHandlerInvoked = false;
	setTLSRxBufferForConnack(&connectParams, 0, 0);
	rc = aws_iot_mqtt_attempt_reconnect(&iotClient);
	CHECK_EQUAL_C_INT(NETWORK_RECONNECTED, rc);

	currPayload = connectTxBufferHeaderParser(&prfrdParams, TxBuffer.pBuffer);
	CHECK_C(true == isConnectTxBufFlagCorrect(&connectParams, &prfrdParams));
	CHECK_C(true == isConnectTxBufPayloadCorrect(&connectParams, currPayload));
	CHECK_C(aws_iot_mqtt_is_client_connected(&iotClient));
	CHECK_EQUAL_C_INT(false, dcHandlerInvoked);

	IOT_DEBUG("-->Success - G:11 - Yield, disconnected, Manual reconnect \n");
}
/* G:10 - Yield, disconnected, Auto-reconnect successful */
TEST_C(YieldTests, disconnectAutoReconnectSuccess) {
	IoT_Error_t rc = FAILURE;
	unsigned char *currPayload = NULL;

	IOT_DEBUG("-->Running Yield Tests - G:10 - Yield, disconnected, Auto-reconnect successful \n");

	rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient));
	CHECK_EQUAL_C_INT(true, aws_iot_is_autoreconnect_enabled(&iotClient));

	/* Sleep for half keep alive interval to allow the first ping to be sent out */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(SUCCESS, rc);
	CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq());

	/* Let ping request time out and call yield */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2 + 1);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc);

	sleep(2); /* Default min reconnect delay is 1 sec */
	printf("\nWakeup");
	setTLSRxBufferForConnack(&connectParams, 0, 0);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	currPayload = connectTxBufferHeaderParser(&prfrdParams, TxBuffer.pBuffer);
	CHECK_C(true == isConnectTxBufFlagCorrect(&connectParams, &prfrdParams));
	CHECK_C(true == isConnectTxBufPayloadCorrect(&connectParams, currPayload));
	CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient));
	CHECK_EQUAL_C_INT(true, dcHandlerInvoked);

	IOT_DEBUG("-->Success - G:10 - Yield, disconnected, Auto-reconnect successful \n");
}
コード例 #9
0
void aws_iot_task(void *param) {

IoT_Error_t rc = SUCCESS;

    while(1)
    {
        //Max time the yield function will wait for read messages
        rc = aws_iot_mqtt_yield(&client, 200);
        
        if(NETWORK_ATTEMPTING_RECONNECT == rc)
        {
            // If the client is attempting to reconnect we will skip the rest of the loop.
            continue;
        }

        
        vTaskDelay(1000 / portTICK_RATE_MS);
    }
}
static void iot_tests_unit_yield_test_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName,
																 uint16_t topicNameLen,
																 IoT_Publish_Message_Params *params, void *pData) {
	char *tmp = params->payload;
	unsigned int i;
	IoT_Error_t rc = SUCCESS;

	IOT_UNUSED(pClient);
	IOT_UNUSED(topicName);
	IOT_UNUSED(topicNameLen);
	IOT_UNUSED(pData);

	rc = aws_iot_mqtt_yield(pClient, 1000);
	CHECK_EQUAL_C_INT(MQTT_CLIENT_NOT_IDLE_ERROR, rc);

	for(i = 0; i < params->payloadLen; i++) {
		CallbackMsgString[i] = tmp[i];
	}
}
/* G:5 - Yield, network connected, yield called while in subscribe application callback */
TEST_C(YieldTests, YieldInSubscribeCallback) {
	IoT_Error_t rc = SUCCESS;
	char expectedCallbackString[] = "0xA5A5A3";

	IOT_DEBUG("-->Running Yield Tests - G:5 - Yield, network connected, yield called while in subscribe application callback \n");

	setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams);
	rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1,
								iot_tests_unit_yield_test_subscribe_callback_handler, NULL);
	if(SUCCESS == rc) {
		setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString);
		rc = aws_iot_mqtt_yield(&iotClient, 1000);
		if(SUCCESS == rc) {
			CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString);
		}
		CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback());
	}

	IOT_DEBUG("-->Success - G:5 - Yield, network connected, yield called while in subscribe application callback \n");
}
コード例 #12
0
int main(int argc, char **argv) {
	IoT_Error_t rc = FAILURE;
	parseInputArgsForConnectParams(argc, argv);

	if (!readDataFromFile()) {
		printf("Config file '%s' not found. Robot cannot work without configuration.\n", filename);
		return -1;
	} 
	else {
		if (connectToThingAndSubscribeToTopic(argc, argv)) {
			publishMessage(getFieldAsString());
			publishRobotState();

			while (true) {
				//Max time the yield function will wait for read messages
				rc = aws_iot_mqtt_yield(&mqttClient, 1000);

				if (NETWORK_ATTEMPTING_RECONNECT == rc) { // || NETWORK_ATTEMPTING_RECONNECT == rc1) {
				// If the client is attempting to reconnect we will skip the rest of the loop.
					continue;
				}

				sleep(3);

				if (currentState == GO) {
					if (checkNextStep()) {
						currentState = GO;
						currentSensor = NONE;
						makeStep();
					} 
				}
			}
		}

		return 0;
	}
}
/* G:7 - Yield, network connected, no incoming messages */
TEST_C(YieldTests, YieldSuccessNoMessages) {
	IoT_Error_t rc;
	int i;

	IOT_DEBUG("-->Running Yield Tests - G:7 - Yield, network connected, no incoming messages \n");

	for(i = 0; i < 100; i++) {
		CallbackMsgString[i] = 'x';
	}

	rc = aws_iot_mqtt_yield(&iotClient, 1000);
	if(SUCCESS == rc) {
		/* Check no messages were received */
		for(i = 0; i < 100; i++) {
			if('x' != CallbackMsgString[i]) {
				rc = FAILURE;
			}
		}
	}

	CHECK_EQUAL_C_INT(SUCCESS, rc);

	IOT_DEBUG("-->Success - G:7 - Yield, network connected, no incoming messages \n");
}
コード例 #14
0
void aws_iot_task(void *param) {
    char cPayload[100];

    int32_t i = 0;

    IoT_Error_t rc = FAILURE;

    AWS_IoT_Client client;
    IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault;
    IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault;

    IoT_Publish_Message_Params paramsQOS0;
    IoT_Publish_Message_Params paramsQOS1;

    ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);

    mqttInitParams.enableAutoReconnect = false; // We enable this later below
    mqttInitParams.pHostURL = HostAddress;
    mqttInitParams.port = port;

#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS)
    mqttInitParams.pRootCALocation = (const char *)aws_root_ca_pem_start;
    mqttInitParams.pDeviceCertLocation = (const char *)certificate_pem_crt_start;
    mqttInitParams.pDevicePrivateKeyLocation = (const char *)private_pem_key_start;

#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS)
    mqttInitParams.pRootCALocation = ROOT_CA_PATH;
    mqttInitParams.pDeviceCertLocation = DEVICE_CERTIFICATE_PATH;
    mqttInitParams.pDevicePrivateKeyLocation = DEVICE_PRIVATE_KEY_PATH;
#endif

    mqttInitParams.mqttCommandTimeout_ms = 20000;
    mqttInitParams.tlsHandshakeTimeout_ms = 5000;
    mqttInitParams.isSSLHostnameVerify = true;
    mqttInitParams.disconnectHandler = disconnectCallbackHandler;
    mqttInitParams.disconnectHandlerData = NULL;

#ifdef CONFIG_EXAMPLE_SDCARD_CERTS
    ESP_LOGI(TAG, "Mounting SD card...");
    sdmmc_host_t host = SDMMC_HOST_DEFAULT();
    sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
    esp_vfs_fat_sdmmc_mount_config_t mount_config = {
        .format_if_mount_failed = false,
        .max_files = 3,
    };
    sdmmc_card_t* card;
    esp_err_t ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to mount SD card VFAT filesystem. Error: %s", esp_err_to_name(ret));
        abort();
    }
#endif

    rc = aws_iot_mqtt_init(&client, &mqttInitParams);
    if(SUCCESS != rc) {
        ESP_LOGE(TAG, "aws_iot_mqtt_init returned error : %d ", rc);
        abort();
    }

    /* Wait for WiFI to show as connected */
    xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
                        false, true, portMAX_DELAY);

    connectParams.keepAliveIntervalInSec = 10;
    connectParams.isCleanSession = true;
    connectParams.MQTTVersion = MQTT_3_1_1;
    /* Client ID is set in the menuconfig of the example */
    connectParams.pClientID = CONFIG_AWS_EXAMPLE_CLIENT_ID;
    connectParams.clientIDLen = (uint16_t) strlen(CONFIG_AWS_EXAMPLE_CLIENT_ID);
    connectParams.isWillMsgPresent = false;

    ESP_LOGI(TAG, "Connecting to AWS...");
    do {
        rc = aws_iot_mqtt_connect(&client, &connectParams);
        if(SUCCESS != rc) {
            ESP_LOGE(TAG, "Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port);
            vTaskDelay(1000 / portTICK_RATE_MS);
        }
    } while(SUCCESS != rc);

    /*
     * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
     *  #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
     *  #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
     */
    rc = aws_iot_mqtt_autoreconnect_set_status(&client, true);
    if(SUCCESS != rc) {
        ESP_LOGE(TAG, "Unable to set Auto Reconnect to true - %d", rc);
        abort();
    }

    const char *TOPIC = "test_topic/esp32";
    const int TOPIC_LEN = strlen(TOPIC);

    ESP_LOGI(TAG, "Subscribing...");
    rc = aws_iot_mqtt_subscribe(&client, TOPIC, TOPIC_LEN, QOS0, iot_subscribe_callback_handler, NULL);
    if(SUCCESS != rc) {
        ESP_LOGE(TAG, "Error subscribing : %d ", rc);
        abort();
    }

    sprintf(cPayload, "%s : %d ", "hello from SDK", i);

    paramsQOS0.qos = QOS0;
    paramsQOS0.payload = (void *) cPayload;
    paramsQOS0.isRetained = 0;

    paramsQOS1.qos = QOS1;
    paramsQOS1.payload = (void *) cPayload;
    paramsQOS1.isRetained = 0;

    while(1) {

        //Max time the yield function will wait for read messages
        rc = aws_iot_mqtt_yield(&client, 100);
        if(NETWORK_ATTEMPTING_RECONNECT == rc) {
            // If the client is attempting to reconnect we will skip the rest of the loop.
            continue;
        }

        ESP_LOGI(TAG, "Stack remaining for task '%s' is %lu bytes", pcTaskGetTaskName(NULL), uxTaskGetStackHighWaterMark(NULL));
        vTaskDelay(1000 / portTICK_RATE_MS);
        sprintf(cPayload, "%s : %d ", "hello from ESP32 (QOS0)", i++);
        paramsQOS0.payloadLen = strlen(cPayload);
        rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, &paramsQOS0);

        sprintf(cPayload, "%s : %d ", "hello from ESP32 (QOS1)", i++);
        paramsQOS1.payloadLen = strlen(cPayload);
        rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, &paramsQOS1);
        if (rc == MQTT_REQUEST_TIMEOUT_ERROR) {
            ESP_LOGW(TAG, "QOS1 publish ack not received.");
            rc = SUCCESS;
        }
    }

    ESP_LOGE(TAG, "An error occurred in the main loop.");
    abort();
}

static void initialise_wifi(void)
{
    tcpip_adapter_init();
    wifi_event_group = xEventGroupCreate();
    ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) );
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
    ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
    wifi_config_t wifi_config = {
        .sta = {
            .ssid = EXAMPLE_WIFI_SSID,
            .password = EXAMPLE_WIFI_PASS,
        },
    };
    ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
    ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );
    ESP_ERROR_CHECK( esp_wifi_start() );
}
TEST_C(YieldTests, ZeroTimeoutYield) {
	IoT_Error_t rc = aws_iot_mqtt_yield(&iotClient, 0);
	CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc);
}
コード例 #16
0
ファイル: blue.c プロジェクト: aelane/TeddyB
int main(void) {
	int i, j, err, sock, dev_id = -1;
	struct hci_dev_info dev_info;
	inquiry_info *info = NULL;
	bdaddr_t target;
	char addr[19] = { 0 };
	char name[248] = { 0 };
	uuid_t uuid = { 0 };
	//Change this to your apps UUID
	char *uuid_str="4e5d48e0-75df-11e3-981f-0800200c9a66";
	uint32_t range = 0x0000ffff;
	sdp_list_t *response_list = NULL, *search_list, *attrid_list;
	int s, loco_channel = -1, status;
	struct sockaddr_rc loc_addr = { 0 };
	pthread_t blueThread;
	
	FILE *fp_Setting;
	char message_Buffer[64];
	char mode[30], language[16], topic[16], topicLen[16];
	size_t len = 16;
	(void) signal(SIGINT, SIG_DFL);
	
	changeTopic_flag = 1;
///////////////////////////MRAA/////////////////////////////	
	//Initialize MRAA
        mraa_init();
        
        //Initialize MRAA Pin 8 == IO8 == GP49
        mraa_gpio_context BearButton = mraa_gpio_init(8);

        //Check for successful initialization or else return
        if (BearButton == NULL){
                printf("Error initializing Push to Talk Pin, IO2\n");
                return -1;
        }
        
		//Set pin to an input
		mraa_gpio_dir(BearButton, MRAA_GPIO_IN);
		printf("Set Pin to an input\n");
 
        
        int curr_pin = mraa_gpio_get_pin(BearButton);
        printf("The current pin number is %d\n", curr_pin);
        int curr_raw = mraa_gpio_get_pin_raw(BearButton);
        printf("The raw pin number is %d\n", curr_raw);

        printf("Going to start reading the button via polling\n");
	
//////////////////////AWS///////////////////////////////////
	aws_flag = 0;	
	IoT_Error_t rc = NONE_ERROR;
	char HostAddress[255] = AWS_IOT_MQTT_HOST;
	char certDirectory[PATH_MAX + 1] = "/AWS/SDK/certs/";
	uint32_t port = AWS_IOT_MQTT_PORT;
	
	MQTTMessageParams Msg = MQTTMessageParamsDefault;
	Msg.qos = QOS_0;
	char cPayload[100];
	Msg.pPayload = (void *) cPayload;
	
	char rootCA[PATH_MAX + 1];
	char clientCRT[PATH_MAX + 1];
	char clientKey[PATH_MAX + 1];
	
	char cafileName[] = AWS_IOT_ROOT_CA_FILENAME;
	char clientCRTName[] = AWS_IOT_CERTIFICATE_FILENAME;
	char clientKeyName[] = AWS_IOT_PRIVATE_KEY_FILENAME;
	
	sprintf(rootCA, "/%s/%s", certDirectory, cafileName);
	sprintf(clientCRT, "/%s/%s", certDirectory, clientCRTName);
	sprintf(clientKey, "/%s/%s", certDirectory, clientKeyName);
	
	MQTTConnectParams connectParams = MQTTConnectParamsDefault;

	connectParams.KeepAliveInterval_sec = 14000;
	connectParams.isCleansession = true;
	connectParams.MQTTVersion = MQTT_3_1_1;
	connectParams.pClientID = "TED";
	connectParams.pHostURL = HostAddress;
	connectParams.port = port;
	connectParams.isWillMsgPresent = false;
	connectParams.pRootCALocation = rootCA;
	connectParams.pDeviceCertLocation = clientCRT;
	connectParams.pDevicePrivateKeyLocation = clientKey;
	connectParams.mqttCommandTimeout_ms = 2000;
	connectParams.tlsHandshakeTimeout_ms = 5000;
	connectParams.isSSLHostnameVerify = true;// ensure this is set to true for production
	connectParams.disconnectHandler = disconnectCallbackHandler;
	
	MQTTPublishParams CurriculumParams = MQTTPublishParamsDefault;
	CurriculumParams.pTopic = "Bear/Curriculum/Request";
	
	
	MQTTPublishParams MetricsParams = MQTTPublishParamsDefault;
	MetricsParams.pTopic = "Bear/Curriculum/Metrics";

///////////////////////////////////////////////////////////////////////////////////////
	dev_id = hci_get_route(NULL);
	if (dev_id < 0) {
		perror("No Bluetooth Adapter Available");
		exit(1);
	}

	if (hci_devinfo(dev_id, &dev_info) < 0) {
		perror("Can't get device info");
		exit(1);
	}



	sock = hci_open_dev( dev_id );
	if (sock < 0) {
		perror("HCI device open failed");
		free(info);
		exit(1);
	}

	
	if( !str2uuid( uuid_str, &uuid ) ) {
		perror("Invalid UUID");
		free(info);
		exit(1);
	}

	do {
		printf("Scanning ...\n");
		
			sdp_session_t *session;
			int retries;
			int foundit, responses;
			str2ba(TABLET_ADDRESS,&target); 
			memset(name, 0, sizeof(name));
			if (hci_read_remote_name(sock, &target, sizeof(name), name, 0) < 0){
				strcpy(name, "[unknown]");
			}
			
			printf("Found %s  %s, searching for the the desired service on it now\n", addr, name);
			// connect to the SDP server running on the remote machine
sdpconnect:
			session = 0; retries = 0;
			while(!session) {
				session = sdp_connect( BDADDR_ANY, &target, SDP_RETRY_IF_BUSY );
				if(session) break;
				if(errno == EALREADY && retries < 5) {
					perror("Retrying");
					retries++;
					sleep(1);
					continue;
				}
				break;
			}
			if ( session == NULL ) {
				perror("Can't open session with the device");
				continue;
			}
			search_list = sdp_list_append( 0, &uuid );
			attrid_list = sdp_list_append( 0, &range );
			err = 0;
			err = sdp_service_search_attr_req( session, search_list, SDP_ATTR_REQ_RANGE, attrid_list, &response_list);
			sdp_list_t *r = response_list;
			sdp_record_t *rec;
			// go through each of the service records
			foundit = 0;
			responses = 0;
			for (; r; r = r->next ) {
				responses++;
				rec = (sdp_record_t*) r->data;
				sdp_list_t *proto_list;
					
				// get a list of the protocol sequences
				if( sdp_get_access_protos( rec, &proto_list ) == 0 ) {
				sdp_list_t *p = proto_list;

					// go through each protocol sequence
					for( ; p ; p = p->next ) {
						sdp_list_t *pds = (sdp_list_t*)p->data;

						// go through each protocol list of the protocol sequence
						for( ; pds ; pds = pds->next ) {

							// check the protocol attributes
							sdp_data_t *d = (sdp_data_t*)pds->data;
							int proto = 0;
							for( ; d; d = d->next ) {
								switch( d->dtd ) { 
									case SDP_UUID16:
									case SDP_UUID32:
									case SDP_UUID128:
											proto = sdp_uuid_to_proto( &d->val.uuid );
											break;
									case SDP_UINT8:
										if( proto == RFCOMM_UUID ) {
												printf("rfcomm channel: %d\n",d->val.int8);
												loco_channel = d->val.int8;
												foundit = 1;
										}
										break;
								}
							}
						}
						sdp_list_free( (sdp_list_t*)p->data, 0 );
					}
					sdp_list_free( proto_list, 0 );

				}
				if (loco_channel > 0)
					break;

			}
			printf("No of Responses %d\n", responses);
			if ( loco_channel > 0 && foundit == 1 ) {
				printf("Found service on this device, now gonna blast it with dummy data\n");
				s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
				loc_addr.rc_family = AF_BLUETOOTH;
				loc_addr.rc_channel = loco_channel;
				loc_addr.rc_bdaddr = *(&target);
				status = connect(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
				if( status < 0 ) {
					perror("uh oh");
				}

				
				rc = pthread_create(&blueThread, NULL, threadListen, (void *)s);
					if (rc){
						printf("ERROR: %d\n", rc);
						exit(1);
					}
				MQTTSubscribeParams subParams = MQTTSubscribeParamsDefault;
				//Loop through trying to subscribe to AWS incase the first attempt fails, so will keep trying until the app sends the edison proper network info.
				do{
					INFO("Connecting...");
					rc = aws_iot_mqtt_connect(&connectParams);
					
					if (NONE_ERROR != rc) {
						ERROR("Error(%d) connecting to %s:%d", rc, connectParams.pHostURL, connectParams.port);
					}
					
					subParams.mHandler = MQTTcallbackHandler;
					subParams.pTopic = "Bear/Curriculum/Response";
					subParams.qos = QOS_0;

					if (NONE_ERROR == rc) {
						INFO("Subscribing...");
						rc = aws_iot_mqtt_subscribe(&subParams);
						if (NONE_ERROR != rc) {
							ERROR("Error subscribing");
						}
					}
					sleep(1);
				}while(NONE_ERROR != rc);
				aws_flag = 1;
//////////////////////////Start of teaching stuff//////////////////////////////////////////
				do {
					
				
					if(changeTopic_flag){
					
						sprintf(cPayload, "{\"BearID\":\"%s\"}",BEARID);
						Msg.PayloadLen = strlen(cPayload) + 1;
						CurriculumParams.MessageParams = Msg;
						rc = aws_iot_mqtt_publish(&CurriculumParams);
						while(rc == NONE_ERROR && changeTopic_flag){
							rc = aws_iot_mqtt_yield(100);
							INFO("-->sleep");
							sleep(1);
						}								
						changeTopic_flag = 0;
					}
					
					
					fp_Setting = fopen("/Curriculum/BearSettings.txt", "r");
					fgets(language, sizeof(language), fp_Setting);
					fgets(mode, sizeof(mode), fp_Setting);
					fgets(topic, sizeof(topic), fp_Setting);
					fgets(topicLen, sizeof(topicLen), fp_Setting);
					language[strlen(language)-1] = 0;
					mode[strlen(mode)-1] = 0;
					topic[strlen(topic)-1] = 0;
					topicLen[strlen(topicLen)-1] = 0;
					fclose(fp_Setting);

					//Wait for the tablet to tell the edison to start the lesson
					while(strcmp(threadMessage, "learning")){
						printf("Waiting for learning, got: %s\n", threadMessage);
						if(!strcmp(threadMessage, "crash")){
							memset(threadMessage, 0, sizeof(threadMessage));
							goto CRASHED;
						}
						memset(threadMessage, 0, sizeof(threadMessage));
						sleep(1);
					}

					
					printf("Current Mode: %s\n", mode);
					printf("Current Language: %s\n", language);
					printf("Current topic: %s\n", topic);

					//Call a different function depending on what teaching mode it is, also write to the tablet based on the topic info and lesson
					if(!strcmp(mode, "Repeat After Me")){
						sprintf(message_Buffer,"%s,1,%s",language, topicLen);
						status = write(s,message_Buffer,sizeof(message_Buffer));
						if(!strcmp(language, "English")){
							status = repeat_after_me_english(s, topic, MetricsParams, BearButton);
						}
						else{
							status = repeat_after_me_foreign(s, language, topic, MetricsParams, BearButton);
						}
					}
					else if(!strcmp(mode, "English to Foreign")){
						sprintf(message_Buffer,"%s,3,%s",language, topicLen);
						status = write(s,message_Buffer,sizeof(message_Buffer));
						status = english_to_foreign(s, language, topic, MetricsParams, BearButton);
					}
					else if(!strcmp(mode, "Foreign to English")){
						sprintf(message_Buffer,"%s,2,%s",language, topicLen);
						status = write(s,message_Buffer,sizeof(message_Buffer));
						status = foreign_to_english(s, language, topic, MetricsParams, BearButton);
					}
					
					
					changeTopic_flag = 1;
					printf("Changing Topic");
					sleep(5);
				} while (status > 0);
CRASHED:
				printf("\nBluetooth Disconnected\n");
				close(s);
				sdp_record_free( rec );
			}

			sdp_close(session);
			if (loco_channel > 0) {
				goto sdpconnect;
				//break;
			}
		sleep(1);
	} while (1);

	printf("Exiting...\n");
}
コード例 #17
0
int main(int argc, char** argv) {
	IoT_Error_t rc = NONE_ERROR;
	int32_t i = 0;
	int j = 0;
	int ret = 0;
    time_t timestamp = time(NULL);
    int timeout = 3600;
	bool infinitePublishFlag = true;
    unsigned short len = 0;
    char chaccessKey[17] = {0};
    unsigned char Password[100] = {0};
    char userName[100] = {0};
	char clientId[256] = {0};
	//char subTopic[256] = {0};
	char pubTopic[256] = {0};

	parseInputArgsForConnectParams(argc, argv);

	INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
    
    (void)iot_tls_set_host(ACHostAddr);
    (void)AC_RegisterAccessCallBack(getAccessPointAction);

    ret = AC_DeviceServiceInit(domainName, subdomainName, deviceId, "0-0-0");
    if (0 != ret)
    {
        INFO("\nAC Init error\n");
        return AC_INIT_ERROR;
    }
    ret = AC_GetAccessPoints();
    if (0 != ret)
    {
        INFO("\nAC get access points error\n");
        return AC_GET_ACCESS_POINTS_ERROR;
    }

    while (0 == strcmp(HostAddress, "dev.ablecloud.cn"))
    {
		INFO("-->equal");
		sleep(1);
    }

    INFO("HostAddress is %s\n", HostAddress);
	
    do
    {
        ret = (int)MQTTConnectCloud();
        if (NONE_ERROR != ret)
        {
            ret = getNextAccessPoint();

            if (NONE_ERROR == ret)
            {
                continue;
            }
            else
            {
                /* delete file */
                AC_DelAccessPointFile();
                /* get access point again */
                ret = AC_GetAccessPoints();
            }
        }
        else 
        {
            break;
        }
            
    }while(NONE_ERROR == ret);
    
	/*
	 * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
	 *  #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
	 *  #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
	 */
	rc = aws_iot_mqtt_autoreconnect_set_status(true);
	if (NONE_ERROR != rc) {
		ERROR("Unable to set Auto Reconnect to true - %d", rc);
		return rc;
	}

    if (NONE_ERROR == rc)
    {
        rc = ACMqttSubscribe();
		if (NONE_ERROR != rc) 
        {
			ERROR("Error subscribing,error is %d", rc);
		}
    }

    /* report version */

    MQTTReportVersion();
    
	if (publishCount != 0) {
		infinitePublishFlag = false;
	}

	char cPayload[100];
	sprintf(cPayload, "%s", "hello from SDK");

	while ((NETWORK_ATTEMPTING_RECONNECT == rc || RECONNECT_SUCCESSFUL == rc || NONE_ERROR == rc)
			&& (publishCount > 0 || infinitePublishFlag)) 
	{

		//Max time the yield function will wait for read messages
		rc = aws_iot_mqtt_yield(100);
		if(NETWORK_ATTEMPTING_RECONNECT == rc){
			INFO("-->sleep");
			sleep(1);
			// If the client is attempting to reconnect we will skip the rest of the loop.
			continue;
		}
		INFO("-->sleep");
		sleep(1);

        rc = ACMqttPublish(210, 0, cPayload, 14);
        if (NONE_ERROR != rc)
        {
            ERROR("Publish error\n");
        }
		if (publishCount > 0) {
			publishCount--;
		}
	}

	if (NONE_ERROR != rc) {
		ERROR("An error occurred in the loop.\n");
	} else {
		INFO("Publish done\n");
	}

	return rc;
}
コード例 #18
0
int main(int argc, char **argv) {
	bool infinitePublishFlag = true;

	char rootCA[PATH_MAX + 1];
	char clientCRT[PATH_MAX + 1];
	char clientKey[PATH_MAX + 1];
	char CurrentWD[PATH_MAX + 1];
	char cPayload[100];

	int32_t i = 0;

	IoT_Error_t rc = FAILURE;

	AWS_IoT_Client client;
	IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault;
	IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault;

	IoT_Publish_Message_Params paramsQOS0;
	IoT_Publish_Message_Params paramsQOS1;

	parseInputArgsForConnectParams(argc, argv);

	IOT_INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);

	getcwd(CurrentWD, sizeof(CurrentWD));
	snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME);
	snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME);
	snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME);

	IOT_DEBUG("rootCA %s", rootCA);
	IOT_DEBUG("clientCRT %s", clientCRT);
	IOT_DEBUG("clientKey %s", clientKey);
	mqttInitParams.enableAutoReconnect = false; // We enable this later below
	mqttInitParams.pHostURL = HostAddress;
	mqttInitParams.port = port;
	mqttInitParams.pRootCALocation = rootCA;
	mqttInitParams.pDeviceCertLocation = clientCRT;
	mqttInitParams.pDevicePrivateKeyLocation = clientKey;
	mqttInitParams.mqttCommandTimeout_ms = 20000;
	mqttInitParams.tlsHandshakeTimeout_ms = 5000;
	mqttInitParams.isSSLHostnameVerify = true;
	mqttInitParams.disconnectHandler = disconnectCallbackHandler;
	mqttInitParams.disconnectHandlerData = NULL;

	rc = aws_iot_mqtt_init(&client, &mqttInitParams);
	if(SUCCESS != rc) {
		IOT_ERROR("aws_iot_mqtt_init returned error : %d ", rc);
		return rc;
	}

	connectParams.keepAliveIntervalInSec = 10;
	connectParams.isCleanSession = true;
	connectParams.MQTTVersion = MQTT_3_1_1;
	connectParams.pClientID = AWS_IOT_MQTT_CLIENT_ID;
	connectParams.clientIDLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID);
	connectParams.isWillMsgPresent = false;

	IOT_INFO("Connecting...");
	rc = aws_iot_mqtt_connect(&client, &connectParams);
	if(SUCCESS != rc) {
		IOT_ERROR("Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port);
		return rc;
	}
	/*
	 * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
	 *  #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
	 *  #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
	 */
	rc = aws_iot_mqtt_autoreconnect_set_status(&client, true);
	if(SUCCESS != rc) {
		IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc);
		return rc;
	}

	IOT_INFO("Subscribing...");
	rc = aws_iot_mqtt_subscribe(&client, "sdkTest/sub", 11, QOS0, iot_subscribe_callback_handler, NULL);
	if(SUCCESS != rc) {
		IOT_ERROR("Error subscribing : %d ", rc);
		return rc;
	}

	sprintf(cPayload, "%s : %d ", "hello from SDK", i);

	paramsQOS0.qos = QOS0;
	paramsQOS0.payload = (void *) cPayload;
	paramsQOS0.isRetained = 0;

	paramsQOS1.qos = QOS1;
	paramsQOS1.payload = (void *) cPayload;
	paramsQOS1.isRetained = 0;

	if(publishCount != 0) {
		infinitePublishFlag = false;
	}

	while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc)
		  && (publishCount > 0 || infinitePublishFlag)) {

		//Max time the yield function will wait for read messages
		rc = aws_iot_mqtt_yield(&client, 100);
		if(NETWORK_ATTEMPTING_RECONNECT == rc) {
			// If the client is attempting to reconnect we will skip the rest of the loop.
			continue;
		}

		IOT_INFO("-->sleep");
		sleep(1);
		sprintf(cPayload, "%s : %d ", "hello from SDK QOS0", i++);
		paramsQOS0.payloadLen = strlen(cPayload);
		rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, &paramsQOS0);
		if(publishCount > 0) {
			publishCount--;
		}

		sprintf(cPayload, "%s : %d ", "hello from SDK QOS1", i++);
		paramsQOS1.payloadLen = strlen(cPayload);
		rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, &paramsQOS1);
		if (rc == MQTT_REQUEST_TIMEOUT_ERROR) {
			IOT_WARN("QOS1 publish ack not received.\n");
			rc = SUCCESS;
		}
		if(publishCount > 0) {
			publishCount--;
		}
	}

	if(SUCCESS != rc) {
		IOT_ERROR("An error occurred in the loop.\n");
	} else {
		IOT_INFO("Publish done\n");
	}

	return rc;
}
コード例 #19
0
int main(int argc, char** argv) {
    wiringPiSetup () ;
    pinMode (0, OUTPUT) ;
    
	IoT_Error_t rc = NONE_ERROR;
	bool infinitePublishFlag = true;

	char rootCA[PATH_MAX + 1];
	char clientCRT[PATH_MAX + 1];
	char clientKey[PATH_MAX + 1];
	char CurrentWD[PATH_MAX + 1];
	char cafileName[] = AWS_IOT_ROOT_CA_FILENAME;
	char clientCRTName[] = AWS_IOT_CERTIFICATE_FILENAME;
	char clientKeyName[] = AWS_IOT_PRIVATE_KEY_FILENAME;

	parseInputArgsForConnectParams(argc, argv);

	INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);

	getcwd(CurrentWD, sizeof(CurrentWD));
	sprintf(rootCA, "%s/%s/%s", CurrentWD, certDirectory, cafileName);
	sprintf(clientCRT, "%s/%s/%s", CurrentWD, certDirectory, clientCRTName);
	sprintf(clientKey, "%s/%s/%s", CurrentWD, certDirectory, clientKeyName);

	DEBUG("rootCA %s", rootCA);
	DEBUG("clientCRT %s", clientCRT);
	DEBUG("clientKey %s", clientKey);

	MQTTConnectParams connectParams = MQTTConnectParamsDefault;

	connectParams.KeepAliveInterval_sec = 10;
	connectParams.isCleansession = true;
	connectParams.MQTTVersion = MQTT_3_1_1;
	connectParams.pClientID = "CSDK-test-device";
	connectParams.pHostURL = HostAddress;
	connectParams.port = port;
	connectParams.isWillMsgPresent = false;
	connectParams.pRootCALocation = rootCA;
	connectParams.pDeviceCertLocation = clientCRT;
	connectParams.pDevicePrivateKeyLocation = clientKey;
	connectParams.mqttCommandTimeout_ms = 2000;
	connectParams.tlsHandshakeTimeout_ms = 5000;
	connectParams.isSSLHostnameVerify = true; // ensure this is set to true for production
	connectParams.disconnectHandler = disconnectCallbackHandler;

	INFO("Connecting...");
	rc = aws_iot_mqtt_connect(&connectParams);
	if (NONE_ERROR != rc) {
		ERROR("Error(%d) connecting to %s:%d", rc, connectParams.pHostURL, connectParams.port);
	}
	/*
	 * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
	 *  #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
	 *  #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
	 */
	rc = aws_iot_mqtt_autoreconnect_set_status(true);
	if (NONE_ERROR != rc) {
		ERROR("Unable to set Auto Reconnect to true - %d", rc);
		return rc;
	}

	MQTTSubscribeParams subParams = MQTTSubscribeParamsDefault;
	subParams.mHandler = MQTTcallbackHandler;
	subParams.pTopic = "sdkTest/sub";
	subParams.qos = QOS_0;

	if (NONE_ERROR == rc) {
		INFO("Subscribing...");
		rc = aws_iot_mqtt_subscribe(&subParams);
		if (NONE_ERROR != rc) {
			ERROR("Error subscribing");
		}
	}

	MQTTMessageParams Msg = MQTTMessageParamsDefault;
	Msg.qos = QOS_0;
	char cPayload[100];
	sprintf(cPayload, "%s", "hello from SDK");
	Msg.pPayload = (void *) cPayload;

	MQTTPublishParams Params = MQTTPublishParamsDefault;
	Params.pTopic = "sdkTest/sub";

	if (publishCount != 0) {
		infinitePublishFlag = false;
	}

	while ((NETWORK_ATTEMPTING_RECONNECT == rc || RECONNECT_SUCCESSFUL == rc || NONE_ERROR == rc)
			&& (publishCount > 0 || infinitePublishFlag)) {

		//Max time the yield function will wait for read messages
		rc = aws_iot_mqtt_yield(100);
		if(NETWORK_ATTEMPTING_RECONNECT == rc){
			INFO("-->sleep");
			sleep(1);
			// If the client is attempting to reconnect we will skip the rest of the loop.
			continue;
		}
		INFO("-->sleep");
		sleep(1);
                if (digitalRead (0) == HIGH)
                    sprintf(cPayload, "%s:%d", "turn on the light", 1);
                    sleep(1);
                if (digitalRead (0) == LOW)
                    sprintf(cPayload, "%s:%d", "turn off the light", 0);
                    sleep(1);
		Msg.PayloadLen = strlen(cPayload) + 1;
		Params.MessageParams = Msg;
		rc = aws_iot_mqtt_publish(&Params);
		if (publishCount > 0) {
			publishCount--;
		}
	}

	if (NONE_ERROR != rc) {
		ERROR("An error occurred in the loop.\n");
	} else {
		INFO("Publish done\n");
	}

	return rc;
}
コード例 #20
0
/* F:7 - Disconnect, with set handler and invoked on disconnect */
TEST_C(DisconnectTests, SetHandlerAndInvokedOnDisconnect) {
	bool connected = false;
	bool currentAutoReconnectStatus = false;
	int i;
	int j;
	int attempt = 3;
	uint32_t dcCount = 0;
	IoT_Error_t rc = SUCCESS;
	IOT_DEBUG("-->Running Disconnect Tests - F:7 - Disconnect, with set handler and invoked on disconnect \n");

	handlerInvoked = false;
	InitMQTTParamsSetup(&initParams, "localhost", AWS_IOT_MQTT_PORT, false, NULL);
	rc = aws_iot_mqtt_init(&iotClient, &initParams);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID));
	connectParams.keepAliveIntervalInSec = 5;
	setTLSRxBufferForConnack(&connectParams, 0, 0);
	rc = aws_iot_mqtt_connect(&iotClient, &connectParams);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	aws_iot_mqtt_set_disconnect_handler(&iotClient, disconnectTestHandler, NULL);
	aws_iot_mqtt_autoreconnect_set_status(&iotClient, true);

	IOT_DEBUG("Current Keep Alive Interval is set to %d sec.\n", connectParams.keepAliveIntervalInSec);
	currentAutoReconnectStatus = aws_iot_is_autoreconnect_enabled(&iotClient);

	connected = aws_iot_mqtt_is_client_connected(&iotClient);
	CHECK_EQUAL_C_INT(1, connected);

	aws_iot_mqtt_autoreconnect_set_status(&iotClient, false);

	// 3 cycles of keep alive time expiring
	// verify a ping request is sent and give a ping response
	for(i = 0; i < attempt; i++) {
		/* Set TLS buffer for ping response */
		ResetTLSBuffer();
		setTLSRxBufferForPingresp();
		for(j = 0; j <= connectParams.keepAliveIntervalInSec; j++) {
			sleep(1);
			rc = aws_iot_mqtt_yield(&iotClient, 100);
			CHECK_EQUAL_C_INT(SUCCESS, rc);
		}
		CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePingreq());
	}
	ResetTLSBuffer();

	// keepalive() waits for 1/2 of keepalive time after sending ping request
	// to receive a pingresponse before determining the connection is not alive
	// wait for keepalive time and then yield()
	sleep(connectParams.keepAliveIntervalInSec);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc);
	CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect());

	connected = aws_iot_mqtt_is_client_connected(&iotClient);
	CHECK_EQUAL_C_INT(0, connected);

	CHECK_EQUAL_C_INT(true, handlerInvoked);

	dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient);
	CHECK_C(1 == dcCount);

	aws_iot_mqtt_reset_network_disconnected_count(&iotClient);

	dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient);
	CHECK_C(0 == dcCount);

	ResetTLSBuffer();
	aws_iot_mqtt_autoreconnect_set_status(&iotClient, currentAutoReconnectStatus);

	IOT_DEBUG("-->Success - F:7 - Disconnect, with set handler and invoked on disconnect \n");
}
/* G:1 - Yield with Null/empty Client Instance */
TEST_C(YieldTests, NullClientYield) {
	IoT_Error_t rc = aws_iot_mqtt_yield(NULL, 1000);
	CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc);
}
/* G:12 - Yield, resubscribe to all topics on reconnect */
TEST_C(YieldTests, resubscribeSuccessfulReconnect) {
	IoT_Error_t rc = FAILURE;
	char cPayload[100];
	bool connected = false;
	bool autoReconnectEnabled = false;
	char expectedCallbackString[100];

	IOT_DEBUG("-->Running Yield Tests - G:12 - Yield, resubscribe to all topics on reconnect \n");

	rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	snprintf(CallbackMsgString, 100, "NOT_VISITED");

	testPubMsgParams.qos = QOS1;
	testPubMsgParams.isRetained = 0;
	snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0);
	testPubMsgParams.payload = (void *) cPayload;
	testPubMsgParams.payloadLen = strlen(cPayload);

	connected = aws_iot_mqtt_is_client_connected(&iotClient);
	CHECK_EQUAL_C_INT(1, connected);

	ResetTLSBuffer();

	/* Subscribe to a topic */
	setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams);
	rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_tests_unit_acr_subscribe_callback_handler,
								NULL);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	ResetTLSBuffer();

	/* Check subscribe */
	snprintf(expectedCallbackString, 100, "Message for %s", subTopic);
	setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(SUCCESS, rc);
	CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString);

	ResetTLSBuffer();

	autoReconnectEnabled = aws_iot_is_autoreconnect_enabled(&iotClient);
	CHECK_EQUAL_C_INT(1, autoReconnectEnabled);

	/* Sleep for half keep alive interval to allow the first ping to be sent out */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(SUCCESS, rc);
	CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq());

	/* Let ping request time out and call yield */
	sleep(iotClient.clientData.keepAliveInterval / (uint32_t)2 + 1);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc);

	sleep(2); /* Default min reconnect delay is 1 sec */

	ResetTLSBuffer();
	setTLSRxBufferForConnackAndSuback(&connectParams, 0, subTopic, subTopicLen, QOS1);

	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(SUCCESS, rc);

	/* Test if reconnect worked */
	connected = aws_iot_mqtt_is_client_connected(&iotClient);
	CHECK_EQUAL_C_INT(true, connected);

	ResetTLSBuffer();

	/* Check subscribe */
	snprintf(expectedCallbackString, 100, "Message for %s after resub", subTopic);
	setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString);
	rc = aws_iot_mqtt_yield(&iotClient, 100);
	CHECK_EQUAL_C_INT(SUCCESS, rc);
	CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString);
	CHECK_EQUAL_C_INT(true, dcHandlerInvoked);

	IOT_DEBUG("-->Success - G:12 - Yield, resubscribe to all topics on reconnect \n");
}