public static async void SendData(Object telemetryDataPoint, string deviceKey) { deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(App.deviceName, deviceKey)); while (true) { var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(messageString)); await deviceClient.SendEventAsync(message); } }
static void ReceiveCommands(DeviceClient deviceClient) { Debug.Print("Device waiting for commands from IoTHub..."); Message receivedMessage; string messageData; while (true) { receivedMessage = deviceClient.Receive(); if (receivedMessage != null) { StringBuilder sb = new StringBuilder(); foreach (byte b in receivedMessage.GetBytes()) { sb.Append((char)b); } messageData = sb.ToString(); // dispose string builder sb = null; Debug.Print(DateTime.Now.ToLocalTime() + "> Received message: " + messageData); deviceClient.Complete(receivedMessage); } Thread.Sleep(10000); } }
public static void Main(string[] args) { // Register Device with Azure registryManager = RegistryManager.CreateFromConnectionString(connectionString); RegisterDeviceAsync().Wait(); Console.WriteLine("Simulated device\n"); deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey)); SendDeviceToCloudMessagesAsync(); Console.ReadLine(); }
//Look here for details: https://azure.microsoft.com/en-us/develop/iot/ public static async Task ReceiveCommands(DeviceClient deviceClient) { try { System.Diagnostics.Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; string messageData; if (deviceClient != null) { //while (true) //{ receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(5)); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); System.Diagnostics.Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData); await deviceClient.CompleteAsync(receivedMessage); return; } //} } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Error from IoTHub: " + ex.Message.ToString()); } }
public AzureIoTHubConnection(AppServiceConnection connection) { _appServiceConnection = connection; deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString); _appServiceConnection.RequestReceived += OnRequestReceived; }
public MainPage() { this.InitializeComponent(); try { if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily != "Windows.IoT") { m_deviceClient = DeviceClient.CreateFromConnectionString("HostName=pltkw3IoT.azure-devices.net;DeviceId=pltkw87Demo;SharedAccessKey=ABC", TransportType.Http1); m_telemetrySource = new IoTTelemetrySourceGen(); } else { m_deviceClient = DeviceClient.CreateFromConnectionString("HostName=pltkw3IoT.azure-devices.net;DeviceId=rpi2C;SharedAccessKey=ABC", TransportType.Http1); m_telemetrySource = new IoTTelemetrySourceDevice(); //Inaczej null var gpio = GpioController.GetDefault(); pinLED = gpio.OpenPin(LED_PIN); pinLED.SetDriveMode(GpioPinDriveMode.Output); m_lcd = new TK_LCDlcm1602DriverWRC.LCDI2C(0x27, 2, 16); m_lcd.InitAsync(); } //LED uxToggleLaser.IsOn = true; m_telemetrySource.Init(); m_timer.Tick += M_timer_Tick; startTimer(); ReceiveDataFromAzure(); //Po prostu "task" } catch (Exception ex) { m_tc.TrackException(ex); } }
public AppDataTelemetry(string appVersion, string DeviceName) { this.AppVersion = appVersion; this.DeviceName = DeviceName; currentData = new AppTelemetryData(); this.deviceClient = DeviceClient.CreateFromConnectionString(IoTHubConnString, TransportType.Http1); }
public void Create(GW.Broker broker, byte[] configuration) { this.broker = broker; //ReadConfig //Init DeviceClient client = IoT.DeviceClient.CreateFromConnectionString(Encoding.UTF8.GetString(configuration)); }
private async Task ReceiveCommands(DeviceClient deviceClient) { Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; while (true) { try { receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage != null) { _callback(Encoding.ASCII.GetString(receivedMessage.GetBytes())); await deviceClient.CompleteAsync(receivedMessage); } // Note: In this sample, the polling interval is set to // 10 seconds to enable you to see messages as they are sent. // To enable an IoT solution to scale, you should extend this // interval. For example, to scale to 1 million devices, set // the polling interval to 25 minutes. // For further information, see // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging //await Task.Delay(TimeSpan.FromSeconds(10)); } catch { Debug.WriteLine("ReceiveCommands: Encountered an exception"); } } }
static void Main(string[] args) { deviceClient = Microsoft.Azure.Devices.Client.DeviceClient.Create(iotHubHostName, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Amqp); StartClient(); }
private async Task InitializeDeviceClient(string connectionString) { _deviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Http1); var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString); DeviceClientPanel.Children.Add(new TextBlock() { Text = "Host: " + iotHubConnectionStringBuilder.HostName }); DeviceClientPanel.Children.Add(new TextBlock() { Text = "Device: " + iotHubConnectionStringBuilder.DeviceId }); Message receivedMessage; string messageData; while (true) { receivedMessage = await _deviceClient.ReceiveAsync(); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); var updateAccessKeyRequest = JsonConvert.DeserializeObject<UpdateAccessKeyRequest>(messageData); if (updateAccessKeyRequest != null) { DeviceClientPanel.Children.Add(new TextBlock() { Text = "Update Access Key received" }); UpdateConnectionString(updateAccessKeyRequest.AccessKey); await _deviceClient.CloseAsync(); _deviceClient = DeviceClient.CreateFromConnectionString(GetConnectionString(), TransportType.Http1); await _deviceClient.CompleteAsync(receivedMessage); } } } }
private async Task ReceiveCommands(DeviceClient deviceClient) { System.Diagnostics.Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n"); Message receivedMessage; string messageData; int recoverTimeout=1000; while (true) { try { receivedMessage = await deviceClient.ReceiveAsync();// TimeSpan.FromSeconds(1)); if (receivedMessage != null) { messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); System.Diagnostics.Debug.WriteLine(String.Format("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData)); await deviceClient.CompleteAsync(receivedMessage); } recoverTimeout = 1000; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); await Task.Delay(recoverTimeout); recoverTimeout *= 10; // increment timeout for connection recovery if(recoverTimeout>600000)//set a maximum timeout { recoverTimeout = 600000; } } } }
/// <summary> /// Main page constructor /// </summary> public MainPage() { this.InitializeComponent(); System.Diagnostics.Debug.WriteLine("IoT Hub\n"); deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey)); SendDeviceToCloudMessagesAsync(); // Hard coding guid for sensors. Not an issue for this particular application which is meant for testing and demos List<ConnectTheDotsSensor> sensors = new List<ConnectTheDotsSensor> { new ConnectTheDotsSensor("2298a348-e2f9-4438-ab23-82a3930662ab", "Temperature", "F"), }; ctdHelper = new ConnectTheDotsHelper(serviceBusNamespace: "dubyahub-ns", eventHubName: "dubyahub", keyName: "SAS", key: "iqJC+Fg/9JSWQo5mzucOvfQOtshqcEGunjoXl/V78GE=", displayName: "minwinpc", organization: "Dubya", location: "Hello World!", sensorList: sensors); //Button_Click(null, null); }
public void Initialize(string connectionStr) { if (string.IsNullOrWhiteSpace(connectionStr)) return; deviceClient = DeviceClient.CreateFromConnectionString(connectionStr, TransportType.Http1); }
static void Main(string[] args) { Console.WriteLine("Simulated device\n"); deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("{Coloque aqui o nome do DeviceID}", deviceKey)); SendDeviceToCloudMessagesAsync(); ReceiveC2dAsync(); Console.ReadLine(); }
IotHubClient(DeviceClient deviceClient, string deviceId, IotHubClientSettings settings, IByteBufferAllocator allocator, IMessageAddressConverter messageAddressConverter) { this.deviceClient = deviceClient; this.deviceId = deviceId; this.settings = settings; this.allocator = allocator; this.messageAddressConverter = messageAddressConverter; }
static void Main(string[] args) { Console.WriteLine("Simulated device\n"); deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey)); SendDeviceToCloudMessagesAsync(); Console.ReadLine(); }
public GeoDeviceSimulator(string connectionString, string deviceId, IList<GeoData> sampleData, TimeSpan telemetryInterval) { this.deviceId = deviceId; this.connectionString = connectionString; this.cts = new CancellationTokenSource(); this.deviceClient = DeviceClient.CreateFromConnectionString(this.connectionString, deviceId); this.telemetryInterval = telemetryInterval; this.sampleData = sampleData; }
public void Open() { if (string.IsNullOrWhiteSpace(_device.DeviceID)) { throw new ArgumentException("DeviceID value cannot be missing, null, or whitespace"); } string connStr = GetConnectionString(); _deviceClient = DeviceClient.CreateFromConnectionString(connStr, TransportType.Http1); }
public DevicePropertiesRequestTest(ITestOutputHelper log) { this.sdkClient = GetSdkClient(); this.client = new Mock <IDeviceClient>(); this.logger = new Mock <ILogger>(); this.target = new DeviceProperties(sdkClient, this.logger.Object); }
public void Open() { if (string.IsNullOrWhiteSpace(_device.DeviceID)) { throw new ArgumentException("DeviceID value cannot be missing, null, or whitespace"); } _deviceClient = DeviceClient.CreateFromConnectionString(GetConnectionString()); }
public async void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey)); await SendDeviceToCloudMessagesAsync(); deferral.Complete(); }
private SdkClient GetSdkClient() { var connectionString = $"HostName=somehost.azure-devices.net;DeviceId=" + DEVICE_ID + ";SharedAccessKeyName=iothubowner;SharedAccessKey=Test123+Test123456789+TestTestTestTestTest1="; SdkClient sdkClient = SdkClient.CreateFromConnectionString(connectionString, TransportType.Mqtt_Tcp_Only); sdkClient.SetRetryPolicy(new NoRetry()); return(sdkClient); }
private static void Main(string[] args) { Console.WriteLine("Simulated device\n"); _deviceClient = DeviceClient.Create(_iotHubHostName, new DeviceAuthenticationWithRegistrySymmetricKey(_deviceId, _deviceKey)); SendDeviceToCloudMessagesAsync(); ReceiveCloudToDeviceMessagesAsync(); Console.ReadLine(); }
private async void MainPageLoaded(object sender, RoutedEventArgs e) { //Initialize objects gpioController = GpioController.GetDefault(); IAdcControllerProvider MCP3008_SPI0 = new MCP3008(); adcManager = new AdcProviderManager(); lightVals = new List<double>(); deviceClient = DeviceClient .CreateFromConnectionString(IoTHubConnString, TransportType.Http1); timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(500); timer.Tick += BroadcastTelemetry; timer.Start(); //Insert 10 dummy values to initialize. for (int i = 0; i < 30; i++) { lightVals.Add(0); } tempVals = new List<double>(); for (int i = 0; i < 30; i++) { tempVals.Add(0); } #region ADC Provider Stuff //Add ADC Provider to list of providers adcManager.Providers.Add(MCP3008_SPI0); //Get all ADC Controllers. var adcControllers = await adcManager.GetControllersAsync(); //This is just how its done. #endregion ADC Provider Stuff var lightSensor = new AnalogSensor() { //Notice access via controller index. //You will need to keep tabs on your //ADC providers locations in the list //Channel 7 as this is where we wired the photo resistor to. AdcChannel = adcControllers[0].OpenChannel(7), //every 500 milliseconds, grab read the value. ReportInterval = 250 }; //Attach a function to the event we fire every 500 milliseconds. lightSensor.ReadingChanged += LightSensor_ReadingChanged; #region Temp Sensor Cheat Codes var tempSensor = new AnalogSensor() { AdcChannel = adcControllers[0].OpenChannel(6), ReportInterval = 250 }; tempSensor.ReadingChanged += TempSensor_ReadingChanged; #endregion Temp Sensor Cheat Codes }
public MainPage() { this.InitializeComponent(); _sendTelemetryTimer.Tick += sendTelemetryData; _sendTelemetryTimer.Interval = TimeSpan.FromSeconds(1); string deviceConnectionString = "HostName={0};DeviceId={1};SharedAccessKey={2}"; deviceConnectionString = String.Format(deviceConnectionString, _hostName, _deviceId, _sharedAccessKey); _deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Http1); }
static void Main(string[] args) { Console.WriteLine("Simulated device:\n"); deviceClient = DeviceClient.CreateFromConnectionString(connectionString); //deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey)); SendDeviceToCloudMessagesAsync(); Console.ReadLine(); }
/// <summary> /// Constructs a new instance. /// </summary> /// <param name="endpointId">Id of the endpoint is attached to the message so the cloud consumer knows what messages /// to propagate. <see cref="CloudToDeviceEndpoint"/> has to have the same id if it should propagate messages /// of this object.</param> /// <param name="iotHubUri">The fully-qualified DNS hostname of IoT Hub. Usually in the form of xxx.azure-devices.net.</param> /// <param name="devicePrimaryKey">Device primary key which was obtained when registering the device.</param> /// <param name="deviceId">Device id under which it was registered.</param> public DeviceToCloudEndpoint(string endpointId,string iotHubUri, string devicePrimaryKey, string deviceId) { if (String.IsNullOrEmpty(iotHubUri)) throw new ArgumentException($"Argument {nameof(iotHubUri)} must be non empty string."); if (String.IsNullOrEmpty(devicePrimaryKey)) throw new ArgumentException($"Argument {nameof(devicePrimaryKey)} must be non empty string."); if (String.IsNullOrEmpty(deviceId)) throw new ArgumentException($"Argument {nameof(deviceId)} must be non empty string."); if (String.IsNullOrEmpty(endpointId)) throw new ArgumentException($"Argument {nameof(endpointId)} must be non empty string."); _endpointId = endpointId; _iotHubUri = iotHubUri; _devicePrimaryKey = devicePrimaryKey; _deviceId = deviceId; _deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, devicePrimaryKey)); }
public MainPage() { this.InitializeComponent(); App.Current.UnhandledException += Current_UnhandledException; DataContext = this; InitGpio(); activeTimer = new Timer(ActiveTimerTick, coffeeRelayStatus, Timeout.Infinite, Timeout.Infinite); deviceClient = DeviceClient.CreateFromConnectionString(CONNECTION_STRING); MessagesListView.ItemsSource = Messages; }
static async void SendDeviceToCloudMessagesAsync(DeviceClient deviceClient) { //var deviceClient = DeviceClient.Create(iotHubUri, // AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), // TransportType.Http1); //var deviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Http1); var package = $"{{lightLevel: {lightLevel}, temp: {temp:N3}, analog: {analog:N2}, x: {x}, y: {y}, z: {z} }}"; var message = new Message(Encoding.ASCII.GetBytes(package)); await deviceClient.SendEventAsync(message); }
static async Task SendEvent(DeviceClient deviceClient) { string[] filePath = Directory.GetFiles(@"C:\Weblog\", "*.csv"); string csv_file_path = string.Empty; int size = filePath.Length; for (int i = 0; i < size; i++) { Console.WriteLine(filePath[i]); csv_file_path = filePath[i]; } DataTable csvData = GetDataTableFromCSVFile(csv_file_path); Console.WriteLine("Rows count:" + csvData.Rows.Count); DataTable table = csvData; foreach (DataRow row in table.Rows) { foreach (var item in row.ItemArray) data = item.ToString(); Console.Write(data); try { foreach (DataRow rows in table.Rows) { var info = new WeatherData { weatherDate = rows.ItemArray[0].ToString(), weatherTime = rows.ItemArray[1].ToString(), Type = rows.ItemArray[2].ToString(), AirTemperature = rows.ItemArray[3].ToString(), RelativeHumidity = rows.ItemArray[4].ToString(), WindSpeed = rows.ItemArray[5].ToString(), SolarRadiation = rows.ItemArray[6].ToString(), Temperature = rows.ItemArray[7].ToString(), }; var serializedString = JsonConvert.SerializeObject(info); var message = data; Console.WriteLine("{0}> Sending events: {1}", DateTime.Now.ToString(), serializedString.ToString()); await deviceClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes(serializedString.ToString()))); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{ 0} > Exception: { 1}", DateTime.Now.ToString(), ex.Message); Console.ResetColor(); } } Console.WriteLine("Press Ctrl - C to stop the sender process"); Console.WriteLine("Press Enter to start now"); Console.ReadLine(); }
internal async Task InitializeAsync() { try { _deviceClient = DeviceClient.CreateFromConnectionString("", TransportType.Mqtt); //add connection string await _deviceClient.OpenAsync(); } catch { // } }
void ConnectToHub() { // Create the IoT Hub Device Client instance deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString); // Send an event // SendEvent(deviceClient).Wait(); // Receive commands in the queue //ReceiveCommands(deviceClient).Wait(); }
//public event MessageReceived public IoTMessageManager(string iotHubConnectionString) { eventHubClient = EventHubClient.CreateFromConnectionString(iotHubConnectionString, iotHubD2cEndpoint); var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds; foreach (string partition in d2cPartitions) ReceiveMessagesFromDeviceAsync(partition); deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice"/*deviceId */, deviceKey)); //SendDeviceToCloudMessagesAsync(); }
public async Task ConnectAsync(bool isDesiredPropertiesCallbackEnable, TransportType protocol = TransportType.Mqtt) { deviceClient = Microsoft.Azure.Devices.Client.DeviceClient.CreateFromConnectionString(connectionString, protocol); if (isDesiredPropertiesCallbackEnable && (protocol == TransportType.Mqtt)) { await deviceClient.SetDesiredPropertyUpdateCallbackAsync(DesiredPropertyUpdate, this); } if (protocol == TransportType.Mqtt) { await deviceClient.SetMethodDefaultHandlerAsync(MethodHandler, this); } await deviceClient.OpenAsync(); ReceiveMessages(); }
static async Task SendEvent(Microsoft.Azure.Devices.Client.DeviceClient deviceClient) { Console.WriteLine("Device sending {0} messages to IoTHub...\n", MESSAGE_COUNT); for (int count = 0; count < MESSAGE_COUNT; count++) { temperature = rnd.Next(20, 35); humidity = rnd.Next(60, 80); var dataBuffer = string.Format("{{\"messageId\":{0},\"temperature\":{1},\"humidity\":{2}}}", count, temperature, humidity); Message eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer)); eventMessage.Properties.Add("temperatureAlert", (temperature > TEMPERATURE_THRESHOLD) ? "true" : "false"); Console.WriteLine("\t{0}> Sending message: {1}, Data: [{2}]", DateTime.Now.ToLocalTime(), count, dataBuffer); await deviceClient.SendEventAsync(eventMessage).ConfigureAwait(false); System.Threading.Thread.Sleep(1500); } }
public static async void SendMessagesAsync(Microsoft.Azure.Devices.Client.DeviceClient _deviceClient) { while (true) { var telemetryDataPoint = new { ticketId = System.Guid.NewGuid(), entryTime = DateTime.UtcNow }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Message(Encoding.ASCII.GetBytes(messageString)); await _deviceClient.SendEventAsync(message); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); await Task.Delay(1000); } }