void receive_cloud_to_device_message() { if (platform_init() != 0) { printf("Failed initializing platform.\r\n"); return; } IOTHUB_CLIENT_HANDLE iothub_client_handle = IoTHubClient_CreateFromConnectionString(connection_string, AMQP_Protocol); if (iothub_client_handle == nullptr) { printf("Failed on IoTHubClient_Create\r\n"); } else { std::promise<void> completion; if (IoTHubClient_SetMessageCallback(iothub_client_handle, receive_callback, &completion) != IOTHUB_CLIENT_OK) { printf("unable to IoTHubClient_SetMessageCallback\r\n"); } completion.get_future().wait(); IoTHubClient_Destroy(iothub_client_handle); } platform_deinit(); }
void send_device_to_cloud_message() { if (platform_init() != 0) { printf("Failed initializing platform.\r\n"); return; } // Setup IoTHub client configuration IOTHUB_CLIENT_HANDLE iothub_client_handle = IoTHubClient_CreateFromConnectionString(connection_string, AMQP_Protocol); if (iothub_client_handle == nullptr) { printf("Failed on IoTHubClient_Create\r\n"); } else { std::string message = "Hello, Cloud from C++!"; IOTHUB_MESSAGE_HANDLE message_handle = IoTHubMessage_CreateFromByteArray((const unsigned char*)message.data(), message.size()); if (message_handle == nullptr) { printf("unable to create a new IoTHubMessage\n"); } else { callback_parameter callback_param = { message }; if (IoTHubClient_SendEventAsync(iothub_client_handle, message_handle, send_callback, &callback_param) != IOTHUB_CLIENT_OK) { printf("failed to hand over the message to IoTHubClient"); } else { printf("IoTHubClient accepted the message for delivery\n"); } IoTHubMessage_Destroy(message_handle); callback_param.completion.get_future().wait(); } printf("Done!\n"); } IoTHubClient_Destroy(iothub_client_handle); platform_deinit(); }
void iothub_client_sample_amqp_websockets_run(void) { IOTHUB_CLIENT_HANDLE iotHubClientHandle; EVENT_INSTANCE messages[MESSAGE_COUNT]; srand((unsigned int)time(NULL)); double avgWindSpeed = 10.0; double minTemperature = 20.0; double minHumidity = 60.0; double temperature = 0; double humidity = 0; callbackCounter = 0; int receiveContext = 0; (void)printf("Starting the IoTHub client sample AMQP over WebSockets...\r\n"); if (platform_init() != 0) { (void)printf("ERROR: failed initializing the platform.\r\n"); } else if ((iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, AMQP_Protocol_over_WebSocketsTls)) == NULL) { (void)printf("ERROR: iotHubClientHandle is NULL!\r\n"); platform_deinit(); } else { // For mbed add the certificate information if (IoTHubClient_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) { printf("failure to set option \"TrustedCerts\"\r\n"); } /* Setting Message call back, so we can receive Commands. */ if (IoTHubClient_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK) { (void)printf("ERROR: IoTHubClient_SetMessageCallback..........FAILED!\r\n"); } else { (void)printf("IoTHubClient_SetMessageCallback...successful.\r\n"); /* Now that we are ready to receive commands, let's send some messages */ for (size_t i = 0; i < MESSAGE_COUNT; i++) { temperature = minTemperature + (rand() % 10); humidity = minHumidity + (rand() % 20); sprintf_s(msgText, sizeof(msgText), "{\"deviceId\":\"myFirstDevice\",\"windSpeed\":%.2f,\"temperature\":%.2f,\"humidity\":%.2f}", avgWindSpeed + (rand() % 4 + 2), temperature, humidity); if ((messages[i].messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText))) == NULL) { (void)printf("ERROR: iotHubMessageHandle is NULL!\r\n"); } else { messages[i].messageTrackingId = (int)i; MAP_HANDLE propMap = IoTHubMessage_Properties(messages[i].messageHandle); (void)sprintf_s(propText, sizeof(propText), temperature > 28 ? "true" : "false"); if (Map_AddOrUpdate(propMap, "temperatureAlert", propText) != MAP_OK) { (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n"); } if (IoTHubClient_SendEventAsync(iotHubClientHandle, messages[i].messageHandle, SendConfirmationCallback, &messages[i]) != IOTHUB_CLIENT_OK) { (void)printf("ERROR: IoTHubClient_SendEventAsync..........FAILED!\r\n"); } else { (void)printf("IoTHubClient_SendEventAsync accepted data for transmission to IoT Hub.\r\n"); } } } /* Wait for Commands. */ (void)printf("Press any key to exit the application. \r\n"); (void)getchar(); } IoTHubClient_Destroy(iotHubClientHandle); platform_deinit(); } }
void simplesample_amqp_run(void) { if (platform_init() != 0) { printf("Failed to initialize the platform.\r\n"); } else { if (serializer_init(NULL) != SERIALIZER_OK) { (void)printf("Failed on serializer_init\r\n"); } else { /* Setup IoTHub client configuration */ IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, AMQP_Protocol); srand((unsigned int)time(NULL)); int avgWindSpeed = 10; // Turn on Log bool trace = true; (void)IoTHubClient_SetOption(iotHubClientHandle, "logtrace", &trace); if (iotHubClientHandle == NULL) { (void)printf("Failed on IoTHubClient_Create\r\n"); } else { #ifdef MBED_BUILD_TIMESTAMP // For mbed add the certificate information if (IoTHubClient_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) { (void)printf("failure to set option \"TrustedCerts\"\r\n"); } #endif // MBED_BUILD_TIMESTAMP ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer); if (myWeather == NULL) { (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n"); } else { unsigned char* destination; size_t destinationSize; if (IoTHubClient_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK) { printf("unable to IoTHubClient_SetMessageCallback\r\n"); } else { myWeather->DeviceId = "myFirstDevice"; myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2); if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed) != CODEFIRST_OK) { (void)printf("Failed to serialize\r\n"); } else { sendMessage(iotHubClientHandle, destination, destinationSize); } /* wait for commands */ (void)getchar(); } DESTROY_MODEL_INSTANCE(myWeather); } IoTHubClient_Destroy(iotHubClientHandle); } serializer_deinit(); } platform_deinit(); } }
static void RecvMessage(IOTHUB_PROVISIONED_DEVICE* deviceToUse) { // arrange IOTHUB_CLIENT_HANDLE iotHubClientHandle; IOTHUB_SERVICE_CLIENT_AUTH_HANDLE iotHubServiceClientHandle; IOTHUB_MESSAGING_CLIENT_HANDLE iotHubMessagingHandle; IOTHUB_MESSAGING_RESULT iotHubMessagingResult; IOTHUB_MESSAGE_RESULT iotHubMessageResult; EXPECTED_RECEIVE_DATA* receiveUserContext; IOTHUB_MESSAGE_HANDLE messageHandle; // act IoTHub_Init(); // Create Service Client iotHubServiceClientHandle = IoTHubServiceClientAuth_CreateFromConnectionString(IoTHubAccount_GetIoTHubConnString(g_iothubAcctInfo1)); ASSERT_IS_NOT_NULL(iotHubServiceClientHandle, "Could not initialize IoTHubServiceClient to send C2D messages to the device"); iotHubMessagingHandle = IoTHubMessaging_Create(iotHubServiceClientHandle); ASSERT_IS_NOT_NULL(iotHubMessagingHandle, "Could not initialize IoTHubMessaging to send C2D messages to the device"); iotHubMessagingResult = IoTHubMessaging_Open(iotHubMessagingHandle, openCompleteCallback, (void*)"Context string for open"); ASSERT_ARE_EQUAL(int, IOTHUB_MESSAGING_OK, iotHubMessagingResult); // Create user context and message receiveUserContext = ReceiveUserContext_Create(); ASSERT_IS_NOT_NULL(receiveUserContext, "Could not create receive user context"); messageHandle = IoTHubMessage_CreateFromString(MSG_CONTENT1); ASSERT_IS_NOT_NULL(messageHandle, "Could not create IoTHubMessage to send C2D messages to the device"); iotHubMessageResult = IoTHubMessage_SetMessageId(messageHandle, MSG_ID1); ASSERT_ARE_EQUAL(int, IOTHUB_MESSAGING_OK, iotHubMessageResult); iotHubMessageResult = IoTHubMessage_SetCorrelationId(messageHandle, MSG_CORRELATION_ID1); ASSERT_ARE_EQUAL(int, IOTHUB_MESSAGING_OK, iotHubMessageResult); MAP_HANDLE mapHandle = IoTHubMessage_Properties(messageHandle); for (size_t i = 0; i < MSG_PROP_COUNT; i++) { if (Map_AddOrUpdate(mapHandle, MSG_PROP_KEYS[i], MSG_PROP_VALS[i]) != MAP_OK) { (void)printf("ERROR: Map_AddOrUpdate failed for property %zu!\r\n", i); } } iotHubMessagingResult = IoTHubMessaging_SendAsync(iotHubMessagingHandle, deviceToUse->deviceId, messageHandle, sendCompleteCallback, receiveUserContext); ASSERT_ARE_EQUAL(int, IOTHUB_MESSAGING_OK, iotHubMessagingResult, "IoTHubMessaging_SendAsync failed, could not send C2D message to the device"); iotHubClientHandle = IoTHubClient_CreateFromConnectionString(deviceToUse->connectionString, HTTP_Protocol); ASSERT_IS_NOT_NULL(iotHubClientHandle, "Failure creating Iothub Client"); if (deviceToUse->howToCreate == IOTHUB_ACCOUNT_AUTH_X509) { IOTHUB_CLIENT_RESULT result; result = IoTHubClient_SetOption(iotHubClientHandle, OPTION_X509_CERT, deviceToUse->certificate); ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Could not set the device x509 certificate"); result = IoTHubClient_SetOption(iotHubClientHandle, OPTION_X509_PRIVATE_KEY, deviceToUse->primaryAuthentication); ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Could not set the device x509 privateKey"); } IOTHUB_CLIENT_RESULT result = IoTHubClient_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, receiveUserContext); ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Failure setting message callback"); unsigned int minimumPollingTime = 1; /*because it should not wait*/ if (IoTHubClient_SetOption(iotHubClientHandle, OPTION_MIN_POLLING_TIME, &minimumPollingTime) != IOTHUB_CLIENT_OK) { printf("failure to set option \"MinimumPollingTime\"\r\n"); } time_t beginOperation, nowTime; beginOperation = time(NULL); while ( ( (nowTime = time(NULL)), (difftime(nowTime, beginOperation) < MAX_CLOUD_TRAVEL_TIME) //time box ) ) { if (Lock(receiveUserContext->lock) != LOCK_OK) { ASSERT_FAIL("unable ot lock"); } else { if (receiveUserContext->wasFound) { (void)Unlock(receiveUserContext->lock); break; } (void)Unlock(receiveUserContext->lock); } ThreadAPI_Sleep(100); } // assert ASSERT_IS_TRUE(receiveUserContext->wasFound, "Failure retrieving message that was sent to IotHub."); // was found is written by the callback... // cleanup IoTHubMessage_Destroy(messageHandle); IoTHubMessaging_Close(iotHubMessagingHandle); IoTHubMessaging_Destroy(iotHubMessagingHandle); IoTHubServiceClientAuth_Destroy(iotHubServiceClientHandle); IoTHubClient_Destroy(iotHubClientHandle); ReceiveUserContext_Destroy(receiveUserContext); }
static void SendEvent(IOTHUB_PROVISIONED_DEVICE* deviceToUse) { // arrange IOTHUB_CLIENT_HANDLE iotHubClientHandle; IOTHUB_MESSAGE_HANDLE msgHandle; EXPECTED_SEND_DATA* sendData = EventData_Create(); ASSERT_IS_NOT_NULL(sendData, "Failure creating data to be sent"); // Send the Event { IOTHUB_CLIENT_RESULT result; // Create the IoT Hub Data iotHubClientHandle = IoTHubClient_CreateFromConnectionString(deviceToUse->connectionString, HTTP_Protocol); ASSERT_IS_NOT_NULL(iotHubClientHandle, "Failure creating IothubClient handle"); msgHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)sendData->expectedString, strlen(sendData->expectedString)); ASSERT_IS_NOT_NULL(msgHandle, "Failure to create message handle"); if (deviceToUse->howToCreate == IOTHUB_ACCOUNT_AUTH_X509) { result = IoTHubClient_SetOption(iotHubClientHandle, OPTION_X509_CERT, deviceToUse->certificate); ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Could not set the device x509 certificate"); result = IoTHubClient_SetOption(iotHubClientHandle, OPTION_X509_PRIVATE_KEY, deviceToUse->primaryAuthentication); ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Could not set the device x509 privateKey"); } // act result = IoTHubClient_SendEventAsync(iotHubClientHandle, msgHandle, ReceiveConfirmationCallback, sendData); ASSERT_ARE_EQUAL(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_OK, result, "Failure calling IoTHubClient_SendEventAsync"); } time_t beginOperation, nowTime; beginOperation = time(NULL); while ( (nowTime = time(NULL)), (difftime(nowTime, beginOperation) < MAX_CLOUD_TRAVEL_TIME) // time box ) { if (Lock(sendData->lock) != LOCK_OK) { ASSERT_FAIL("unable to lock"); } else { if (sendData->dataWasRecv) { Unlock(sendData->lock); break; } Unlock(sendData->lock); } ThreadAPI_Sleep(100); } if (Lock(sendData->lock) != LOCK_OK) { ASSERT_FAIL("unable to lock"); } else { ASSERT_IS_TRUE(sendData->dataWasRecv, "Failure sending data to IotHub"); // was found is written by the callback... (void)Unlock(sendData->lock); } { IOTHUB_TEST_HANDLE iotHubTestHandle = IoTHubTest_Initialize(IoTHubAccount_GetEventHubConnectionString(g_iothubAcctInfo1), IoTHubAccount_GetIoTHubConnString(g_iothubAcctInfo1), deviceToUse->deviceId, IoTHubAccount_GetEventhubListenName(g_iothubAcctInfo1), IoTHubAccount_GetEventhubAccessKey(g_iothubAcctInfo1), IoTHubAccount_GetSharedAccessSignature(g_iothubAcctInfo1), IoTHubAccount_GetEventhubConsumerGroup(g_iothubAcctInfo1)); ASSERT_IS_NOT_NULL(iotHubTestHandle); IOTHUB_TEST_CLIENT_RESULT result = IoTHubTest_ListenForEventForMaxDrainTime(iotHubTestHandle, IoTHubCallback, IoTHubAccount_GetIoTHubPartitionCount(g_iothubAcctInfo1), sendData); ASSERT_ARE_EQUAL(IOTHUB_TEST_CLIENT_RESULT, IOTHUB_TEST_CLIENT_OK, result); IoTHubTest_Deinit(iotHubTestHandle); } // assert ASSERT_IS_TRUE(sendData->wasFound, "Failure receiving data from eventhub"); // was found is written by the callback...*/ // cleanup IoTHubMessage_Destroy(msgHandle); IoTHubClient_Destroy(iotHubClientHandle); EventData_Destroy(sendData); }
static int iothub_client_sample_mqtt_dm_run(const char *connectionString, bool traceOn) { LogInfo("Initialize Platform"); int retValue; if (platform_init() != 0) { LogError("Failed to initialize the platform."); retValue = -4; } else { if (serializer_init(NULL) != SERIALIZER_OK) { LogError("Failed in serializer_init."); retValue = -5; } else { LogInfo("Instantiate the device."); thingie_t *iot_device = CREATE_MODEL_INSTANCE(Contoso, thingie_t); if (iot_device == NULL) { LogError("Failed on CREATE_MODEL_INSTANCE."); retValue = -6; } else { LogInfo("Initialize From Connection String."); IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, MQTT_Protocol); if (iotHubClientHandle == NULL) { LogError("iotHubClientHandle is NULL!"); retValue = -7; } else { LogInfo("Device successfully connected."); if (IoTHubClient_SetOption(iotHubClientHandle, "logtrace", &traceOn) != IOTHUB_CLIENT_OK) { LogError("failed to set logtrace option"); } PHYSICAL_DEVICE *physical_device = physical_device_new(iot_device); if (physical_device == NULL) { LogError("failed to make an iot device callback structure"); retValue = -8; } else { if (IoTHubClient_SetDeviceMethodCallback(iotHubClientHandle, DeviceMethodCallback, physical_device) != IOTHUB_CLIENT_OK) { LogError("failed to associate a callback for device methods"); retValue = -9; } else { bool keepRunning = send_reported(physical_device, iotHubClientHandle); if (!keepRunning) { LogError("Failed to send initia device reported"); retValue = -10; } else { FIRMWARE_UPDATE_STATUS oldStatus = get_physical_device_fwupdate_status(physical_device); while (keepRunning) { FIRMWARE_UPDATE_STATUS newStatus = get_physical_device_fwupdate_status(physical_device); /* send reported only if the status changes */ if (newStatus != oldStatus) { oldStatus = newStatus; keepRunning = send_reported(physical_device, iotHubClientHandle); } ThreadAPI_Sleep(1000); } retValue = 0; } } physical_device_delete(physical_device); } IoTHubClient_Destroy(iotHubClientHandle); } DESTROY_MODEL_INSTANCE(iot_device); } serializer_deinit(); } platform_deinit(); } return retValue; }
void device_twin_simple_sample_run(void) { /*prepare the platform*/ if (platform_init() != 0) { printf("Failed to initialize the platform.\n"); } else { if (SERIALIZER_REGISTER_NAMESPACE(Contoso) == NULL) { LogError("unable to SERIALIZER_REGISTER_NAMESPACE"); } else { /*create an IoTHub client*/ IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, MQTT_Protocol); // Change to AMQP_Procotol if desired. if (iotHubClientHandle == NULL) { printf("Failure creating IoTHubClient handle"); } else { // Turn on Log bool trace = true; (void)IoTHubClient_SetOption(iotHubClientHandle, "logtrace", &trace); Car* car = IoTHubDeviceTwin_CreateCar(iotHubClientHandle); if (car == NULL) { printf("Failure in IoTHubDeviceTwin_CreateCar"); } else { /*setting values for reported properties*/ car->lastOilChangeDate = "2016"; car->maker.makerName = "Fabrikam"; car->maker.style = "sedan"; car->maker.year = 2014; car->state.reported_maxSpeed = 100; car->state.softwareVersion = 1; car->state.vanityPlate = "1I1"; // IoTHubDeviceTwin_SendReportedStateCar sends the reported status back to IoT Hub // to the associated device twin. // // IoTHubDeviceTwin_SendReportedStateCar is an auto-generated function, created // via the macro DECLARE_DEVICETWIN_MODEL(Car,...). It resolves to the underlying function // IoTHubDeviceTwin_SendReportedState_Impl(). if (IoTHubDeviceTwin_SendReportedStateCar(car, deviceTwinReportStateCallback, NULL) != IOTHUB_CLIENT_OK) { (void)printf("Failed sending serialized reported state\n"); } else { printf("Reported state will be send to IoTHub\n"); // Comment out the following three lines if you want to enable callback(s) for updates of the existing model (example: onDesiredMaxSpeed) if (IoTHubClient_SetDeviceTwinCallback(iotHubClientHandle, deviceTwinGetStateCallback, NULL) != IOTHUB_CLIENT_OK) { (void)printf("Failed subscribing for device twin properties\n"); } } printf("press ENTER to end the sample\n"); (void)getchar(); } IoTHubDeviceTwin_DestroyCar(car); } IoTHubClient_Destroy(iotHubClientHandle); } } platform_deinit(); }
void iothub_client_sample_amqp_run(void) { IOTHUB_CLIENT_HANDLE iotHubClientHandle; EVENT_INSTANCE messages[MESSAGE_COUNT]; srand((unsigned int)time(NULL)); double avgWindSpeed = 10.0; callbackCounter = 0; int receiveContext = 0; (void)printf("Starting the IoTHub client sample AMQP...\r\n"); if ((iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, AMQP_Protocol)) == NULL) { (void)printf("ERROR: iotHubClientHandle is NULL!\r\n"); } else { #ifdef MBED_BUILD_TIMESTAMP // For mbed add the certificate information if (IoTHubClient_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) { printf("failure to set option \"TrustedCerts\"\r\n"); } #endif // MBED_BUILD_TIMESTAMP /* Setting Message call back, so we can receive Commands. */ if (IoTHubClient_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK) { (void)printf("ERROR: IoTHubClient_SetMessageCallback..........FAILED!\r\n"); } else { (void)printf("IoTHubClient_SetMessageCallback...successful.\r\n"); /* Now that we are ready to receive commands, let's send some messages */ for (size_t i = 0; i < MESSAGE_COUNT; i++) { sprintf_s(msgText, sizeof(msgText), "{\"deviceId\":\"myFirstDevice\",\"windSpeed\":%.2f}", avgWindSpeed+(rand()%4+2) ); if ((messages[i].messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText))) == NULL) { (void)printf("ERROR: iotHubMessageHandle is NULL!\r\n"); } else { messages[i].messageTrackingId = i; MAP_HANDLE propMap = IoTHubMessage_Properties(messages[i].messageHandle); sprintf_s(propText, sizeof(propText), "PropMsg_%d", i); if (Map_AddOrUpdate(propMap, "PropName", propText) != MAP_OK) { (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n"); } if (IoTHubClient_SendEventAsync(iotHubClientHandle, messages[i].messageHandle, SendConfirmationCallback, &messages[i]) != IOTHUB_CLIENT_OK) { (void)printf("ERROR: IoTHubClient_SendEventAsync..........FAILED!\r\n"); } else { (void)printf("IoTHubClient_SendEventAsync accepted data for transmission to IoT Hub.\r\n"); } } } /* Wait for Commands. */ (void)printf("Press any key to exit the application. \r\n"); (void)getchar(); } IoTHubClient_Destroy(iotHubClientHandle); } }
void simplesample_amqp_run(void) { if (platform_init() != 0) { printf("Failed to initialize the platform.\r\n"); exit(1); } if (serializer_init(NULL) != SERIALIZER_OK) { (void)printf("Failed on serializer_init\r\n"); } else { /* Setup IoTHub client configuration */ IOTHUB_CLIENT_HANDLE iotHubClientHandle = IoTHubClient_CreateFromConnectionString(connectionString, AMQP_Protocol); srand((unsigned int)time(NULL)); int avgMTemperature = 10; if (iotHubClientHandle == NULL) { (void)printf("Failed on IoTHubClient_Create\r\n"); } else { #ifdef MBED_BUILD_TIMESTAMP // For mbed add the certificate information if (IoTHubClient_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) { (void)printf("failure to set option \"TrustedCerts\"\r\n"); } #endif // MBED_BUILD_TIMESTAMP ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer); if (myWeather == NULL) { (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n"); } else { unsigned char* destination; size_t destinationSize; if (IoTHubClient_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK) { printf("unable to IoTHubClient_SetMessageCallback\r\n"); } else { int Lock_fd__i = open_lockfile(LOCKFILE); if (setuid(getuid()) < 0) { perror("Dropping privileges failed. (did you use sudo?)\n"); exit(EXIT_FAILURE); } int Result__i = wiringPiSetup(); if (Result__i != 0) exit(Result__i); int Spi_fd__i = wiringPiSPISetup(Spi_channel__i, Spi_clock__i); if (Spi_fd__i < 0) { printf("Can't setup SPI, error %i calling wiringPiSPISetup(%i, %i) %s\n", Spi_fd__i, Spi_channel__i, Spi_clock__i, strerror(Spi_fd__i)); exit(Spi_fd__i); } int Init_result__i = bme280_init(Spi_channel__i); if (Init_result__i != 1) { printf("It appears that no BMP280 module on Chip Enable %i is attached. Aborting.\n", Spi_channel__i); exit(1); } pinMode(Red_led_pin__i, OUTPUT); pinMode(Grn_led_pin__i, OUTPUT); //////////////// // Read the Temp & Pressure module. float Temp_C__f = -300.0; float Pressure_Pa__f = -300; float Humidity_pct__f = -300; Result__i = bme280_read_sensors(&Temp_C__f, &Pressure_Pa__f, &Humidity_pct__f); if (Result__i == 1) { printf("Temperature = %.1f *C Pressure = %.1f Pa Humidity = %1f %%\n", Temp_C__f, Pressure_Pa__f, Humidity_pct__f); } else { printf("Unable to read BME280 on pin %i\n", Spi_channel__i); } char buff[11]; int timeNow = 0; int c; while (1) { timeNow = (int)time(NULL); sprintf(buff, "%d", timeNow); myWeather->DeviceId = "raspy"; myWeather->EventTime = buff; if (Result__i == 1) { myWeather->MTemperature = Temp_C__f; printf("Humidity = %.1f%% Temperature = %.1f*C \n", Humidity_pct__f, Temp_C__f); } else { myWeather->MTemperature = 404.0; printf("Unable to read BME280 on pin %i\n", Spi_channel__i); pinMode(Red_led_pin__i, OUTPUT); } if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->EventTime, myWeather->MTemperature) != IOT_AGENT_OK) { (void)printf("Failed to serialize\r\n"); } else { sendMessage(iotHubClientHandle, destination, destinationSize); } delay(5000); } /* wait for commands */ // (void)getchar(); close_lockfile(Lock_fd__i); } DESTROY_MODEL_INSTANCE(myWeather); } IoTHubClient_Destroy(iotHubClientHandle); } serializer_deinit(); } }