public Task Initialize() { this.CancellationTokenSource = new CancellationTokenSource(); // *** // *** Create a TpmDevice to access the credential information. Specify // *** a logical device ID of 0 (this is the slot we used to store the // *** credentials). // *** uint logicalDeviceId = 0; TpmDevice tpm = new TpmDevice(logicalDeviceId); // *** // *** Get the connection properties from the TPM. // *** string uri = tpm.GetHostName(); string deviceId = tpm.GetDeviceId(); string sasToken = tpm.GetSASToken(); // *** // *** Create the device connection. // *** this.DeviceClient = DeviceClient.Create(uri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken)); this.ReceiveMessages(this.DeviceClient, this.CancellationTokenSource.Token); return(Task.FromResult(0)); }
public override async Task Send() { string iotHubUri = "handsonlabiothub.azure-devices.net"; string deviceId = "raspidevice"; string deviceKey = "XNglOZ0cinCKCiKXNM+WbXvw9HWs/n/nTnuNqbVBRkQ="; try { var deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); await Test(); //var data = TempToSend; //var message = new Message(Encoding.ASCII.GetBytes(data.ToString())); var temperature = new { temperature = TempToSend, date = DateToSend }; var messageString = JsonConvert.SerializeObject(temperature); var message = new Message(Encoding.UTF8.GetBytes(messageString)); await deviceClient.SendEventAsync(message); } catch (Exception ex) { } }
public void Run(IBackgroundTaskInstance taskInstance) { // get a deferral token. this keeps the app from 'exiting' until we want it to deferral = taskInstance.GetDeferral(); // create the connection to IoTHub, based on the URI, device ID, and key from above deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory. CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); // connect to the serial port SetupSerialConnection().Wait(); Debug.WriteLine("Setting up Data Reader"); // get a pointer to the buffer of data that has been sent to the serial port so we can read it dataReaderObject = new DataReader(serialPort.InputStream); Debug.WriteLine("Wiring up Command Receiver..."); // start the thread to listen for "commands" from IoThub (i.e. turn our LED on/off) ReceiveCommands(); //.Start(); // loop forever and receive serial data and sent to IoTHub Debug.WriteLine("Starting receive loop"); while (true) { try { ReadAsync().Wait(); } catch (Exception e) { Debug.WriteLine(e.Message); } } }
public async Task Send() { List <Dictionary <string, object> > rows = new List <Dictionary <string, object> >(); foreach (var row in this.valuesToBeSent) { rows.Add(row.Values); } string data = JsonConvert.SerializeObject(rows); using (var message = new Message(UnicodeEncoding.UTF8.GetBytes(data))) { message.Properties["MessageType"] = this.MessageType; message.Properties["UnicodeEncoding"] = "UTF8"; //open latest using (var deviceClient = DeviceClient.Create( this.IoTHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(this.DeviceId, this.DeviceKey), Microsoft.Azure.Devices.Client.TransportType.Http1 )) { await deviceClient.SendEventAsync(message); } } }
public static async Task <string> ReceiveCloudToDeviceMessageAsync() { TpmDevice myDevice = new TpmDevice(0); // Use logical device 0 on the TPM by default string hubUri = myDevice.GetHostName(); string deviceId = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken(); var deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory. CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); while (true) { var receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage != null) { var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes()); await deviceClient.CompleteAsync(receivedMessage); return(messageData); } await Task.Delay(TimeSpan.FromSeconds(1)); } }
private DeviceClient InitializeDeviceClient() { TpmDevice device = new TpmDevice(0); string hubUri = device.GetHostName(); string deviceId = device.GetDeviceId(); string sasToken = device.GetSASToken(); _deviceId = deviceId; DeviceClient deviceClient = null; try { deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken)); return(deviceClient); } catch { Debug.WriteLine("ERROR! Unable to create device client!"); } return(deviceClient); }
static async Task SendDeviceDataToCloudMessagesAsync() { string iotHubUri = "Bellatrix.azure-devices.net"; // ! put in value ! string deviceId = "MyBarometer"; // ! put in value ! string deviceKey = "dlWugFxBcgv5h82WJYljwvXV14UQU+rJ4hLBXwyG3FY="; // ! put in value ! var deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory. CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); var telemetryDataPoint = new { deviceId = deviceId, temperature = mTemperature, presure = mPresure, time = DateTime.Now //time = DateTime.Now.ToLocalTime() }; 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); }
public static async Task SendDeviceToCloudMessageAsync(string txtSend) { try { Microsoft.Devices.Tpm.TpmDevice myDevice = new Microsoft.Devices.Tpm.TpmDevice(0); // Use logical device 0 on the TPM by default string hubUri = myDevice.GetHostName(); string deviceId = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken(); var deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory. CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); var str = txtSend + " from " + deviceId + " " + DateTime.Now.ToString(); var message = new Message(Encoding.ASCII.GetBytes(str)); await deviceClient.SendEventAsync(message); } catch (Exception ex) { throw ex; } }
public MainPage() { this.InitializeComponent(); var iotDevice = new TpmDevice(0); string hubUri = iotDevice.GetHostName(); string deviceId = iotDevice.GetDeviceId(); string sasToken = iotDevice.GetSASToken(); deviceName = deviceId; deviceClient = DeviceClient.Create(hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Mqtt); _timer.Interval = TimeSpan.FromSeconds(1); _timer.Tick += _timer_Tick; GpioController controller = GpioController.GetDefault(); if (controller != null) { _pin = GpioController.GetDefault().OpenPin(17, GpioSharingMode.Exclusive); _dht = new Dht11(_pin, GpioPinDriveMode.Input); _timer.Start(); _startedAt = DateTimeOffset.Now; } }
private async void MainPage_OnLoaded(object sender, RoutedEventArgs e) { Status.Text = "Main Page Loaded"; InitGPIO(); Status.Text = "GPIO Initialized"; InitSPI(); Status.Text = "SPI Inititialized"; _deviceManifest = await GetDeviceManifest(); try { _deviceClient = DeviceClient.Create(_deviceManifest.Hub, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey( _deviceManifest.SerialNumber, _deviceManifest.Key.PrimaryKey), TransportType.Amqp); Status.Text = $"{_deviceManifest.SerialNumber} Connected to Azure IoT Hub"; } catch (Exception connectionErr) { Status.Text = connectionErr.Message; } StartHeartbeat(); StartTelemetry(); }
private async Task SyncToAzure() { var DeviceConnectionString = "NithinsPI.azure-devices.net"; var DeviceId = "NithinsPI"; var DeviceKey = "3/Di9ndJYFzf5JphzW8YzRM7HebOhKoUGoqmK6Xh/cY="; var device = DeviceClient.Create(DeviceConnectionString, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Amqp); IDHTTemperatureAndHumiditySensor sensor = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin4, DHTModel.Dht11); while (true) { sensor.Measure(); string sensortemp = sensor.TemperatureInCelsius.ToString(); string sensorhum = sensor.Humidity.ToString(); var telemetry = new Telemetry { Temperature = sensortemp, Humidity = sensorhum }; var payLoad = JsonConvert.SerializeObject(telemetry); var message = new Message(Encoding.ASCII.GetBytes(payLoad)); await device.SendEventAsync(message); await Task.Delay(TimeSpan.FromSeconds(15)); } }
private void InittempSensor() { // call the method to initialize variables and hardware components InitHardware(); // set interval of timer to 1 second _dispatchTimer.Interval = TimeSpan.FromSeconds(1); // invoke a method at each tick (as per interval of your timer) _dispatchTimer.Tick += _dispatchTimer_Tick; // initialize pin (GPIO pin on which you have set your temperature sensor) _temperaturePin = GpioController.GetDefault().OpenPin(4, GpioSharingMode.Exclusive); // create instance of a DHT11 _dhtInterface = new Dht11(_temperaturePin, GpioPinDriveMode.Input); // start the timer _dispatchTimer.Start(); // set start date time _startedAt = DateTimeOffset.Now; //Azure IoT Hub string iotHubUri = "mondayiothub1.azure-devices.net"; string deviceId = "iot1"; string deviceKey = "Dfdr5BaIf+0uJUMLa8YBcIe74fNpBvsQ7FayoQpRXXs="; deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory. CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); }
public TelemetryService() { var key = AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(ConfigurationService.DeviceId, ConfigurationService.DeviceKey); deviceClient = DeviceClient.Create(Config.Default.IotHubUri, key, TransportType.Http1); receiveCommands(); }
public MainPage() { this.InitializeComponent(); // call the method to initialize variables and hardware components InitHardware(); // set interval of timer to 1 second _dispatchTimer.Interval = TimeSpan.FromSeconds(1); // invoke a method at each tick (as per interval of your timer) _dispatchTimer.Tick += _dispatchTimer_Tick; // initialize pin (GPIO pin on which you have set your temperature sensor) _temperaturePin = GpioController.GetDefault().OpenPin(2, GpioSharingMode.Exclusive); // create instance of a DHT11 _dhtInterface = new Dht11(_temperaturePin, GpioPinDriveMode.Input); // start the timer _dispatchTimer.Start(); // set start date time _startedAt = DateTimeOffset.Now; //Azure IoT Hub string iotHubUri = "neerajhome.azure-devices.net"; string deviceId = "RHTemp1"; string deviceKey = "OW+MEyxprIUk/PW/Zw8hcNWAdrZis9PdzY0X69cbk5I="; deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory. CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); IniciateMonitoring(); ReceiveMessage(); }
public static async Task <bool> SendDeviceToCloudMessageAsync(string str) { try { TpmDevice myDevice = new TpmDevice(0); // Use logical device 0 on the TPM string hubUri = myDevice.GetHostName(); string deviceId = myDevice.GetDeviceId(); string hwID = myDevice.GetHardwareDeviceId(); string sasToken = myDevice.GetSASToken(); DeviceClient deviceClient = DeviceClient.Create( hubUri, AuthenticationMethodFactory. CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Mqtt_WebSocket_Only); //string m = "{\"pkey\":\"" + deviceId + "\", \"msg\":"+ str +"}"; var message = new Message(Encoding.ASCII.GetBytes(str)); await deviceClient.SendEventAsync(message); return(true); } catch (Exception ex) { return(false); } }
public MainPage() { this.InitializeComponent(); deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); SendDeviceToCloudMessagesAsync(); }
/// <summary> /// Creates the Connection String formatted as it is expected by the Microsoft.Azure.Clients SDK /// </summary> /// <param name="gatewayHostName">Gateway FQDN</param> /// <param name="deviceId">Device id</param> /// <param name="primaryKey">Primary key</param> /// <returns>Connection String formatted as it is expected by the Microsoft.Azure.Clients SDK</returns> protected string CreateModuleConnectionString(string gatewayHostName, string deviceId, string primaryKey) { var authMethod = AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, AuthenticationData.ModuleName, primaryKey); var builder = IotHubConnectionStringBuilder.Create(gatewayHostName, authMethod); return(builder.ToString()); }
private static void SendTelemetry(Teammate teammate) { var rowindex = 0; const double brzrkr = 1.5; // inflate readings to quickly simulate alarm conditions // initialize the simulation dataset teammate.DataSet = _simData.GetDataSet(teammate.DataSetName); // connect to IoT Hub var auth = AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(teammate.Manifest.SerialNumber, teammate.Manifest.Key.PrimaryKey); var client = DeviceClient.Create(teammate.Manifest.Hub, auth); // start a background thread to send telemetry var simTask = Task.Factory.StartNew(async() => { while (true) { var datarow = _simData.GetNextDataRow(teammate.DataSet.rows[rowindex++]); if (rowindex >= teammate.DataSet.rows.Count) { rowindex = 0; } var reading = new SensorReading { UserId = teammate.Profile.id, DeviceId = teammate.Manifest.SerialNumber, Longitude = teammate.Manifest.Longitude, Latitude = teammate.Manifest.Latitude, Status = SensorStatus.Normal, Timestamp = DateTime.Now, Age = teammate.Profile.healthInformation.age, Weight = teammate.Profile.healthInformation.weight, Height = teammate.Profile.healthInformation.height, BreathingRate = datarow.columns[0].dataValue * brzrkr, Ventilization = datarow.columns[1].dataValue * brzrkr, Activity = datarow.columns[2].dataValue * brzrkr, HeartRateBPM = datarow.columns[3].dataValue * brzrkr, Cadence = datarow.columns[4].dataValue * brzrkr, Velocity = datarow.columns[5].dataValue * brzrkr, Speed = datarow.columns[6].dataValue * brzrkr, HIB = datarow.columns[7].dataValue * brzrkr, HeartrateRedZone = datarow.columns[8].dataValue * brzrkr, HeartrateVariability = datarow.columns[9].dataValue * brzrkr, Temperature = datarow.columns[10].dataValue * brzrkr }; var json = JsonConvert.SerializeObject((object)reading); var message = new Message(Encoding.ASCII.GetBytes(json)); await client.SendEventAsync(message); System.Threading.Thread.Sleep(System.Convert.ToInt32(teammate.Manifest.Extensions["telemetry"])); } }); }
async void SendDeviceToCloudMessagesAsync(string msg) { var deviceClient = DeviceClient.Create(Settings.iotHubUri, AuthenticationMethodFactory. CreateAuthenticationWithRegistrySymmetricKey(Settings.deviceId, Settings.deviceKey), TransportType.Http1); var message = new Message(Encoding.ASCII.GetBytes(msg)); await deviceClient.SendEventAsync(message); }
private static DeviceClient CreateClient() { var deviceClient = DeviceClient.Create(IotHostName, AuthenticationMethodFactory. CreateAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Http1); return(deviceClient); }
private void initDevice() { TpmDevice device = new TpmDevice(0); string hubUri = device.GetHostName(); string deviceId = device.GetDeviceId(); string sasToken = device.GetSASToken(); _sendDeviceClient = DeviceClient.Create(hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Amqp); }
public MainPage() { this.InitializeComponent(); deviceClient = DeviceClient.Create(iothubUri, AuthenticationMethodFactory. CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); Display(); }
/// <summary> /// attempt to create a device client with the user credentials stored in the tpm /// </summary> public void initializeWithProvisionedDevice() { TpmDevice myDevice = new TpmDevice(0); string hubUri = myDevice.GetHostName(); devID = myDevice.GetDeviceId(); string sasToken = myDevice.GetSASToken(); deviceClient = DeviceClient.Create(hubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(devID, sasToken), TransportType.Amqp); }
private async void InitializeSensor() { var key = AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey( Config.Default.DeviceName, Config.Default.DeviceKey); DeviceClient deviceClient = DeviceClient.Create(Config.Default.IotHubUri, key, TransportType.Http1); Task ts = SendEvents(deviceClient); Task tr = ReceiveCommands(deviceClient); await Task.WhenAll(ts, tr); }
static string deviceKey = "<Device Shared access key>"; // ! put in value ! static void Main(string[] args) { Random random = new Random(); int temp = 0; int pressure = 0; int dId = 0; DateTime timestamp1; var deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory. CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); try { for (int i = 0; i < 20; i++) { temp = random.Next(35, 55); pressure = random.Next(200, 300); timestamp1 = DateTime.UtcNow; dId = random.Next(1, 5); Event info = new Event() { TimeStamp1 = timestamp1, DeviceId = deviceId, Temperature = temp.ToString(), Pressure = pressure.ToString(), }; Console.WriteLine("Enter temperature (press CTRL+Z to exit):"); var readtemp = Console.ReadLine(); if (readtemp != null) { info.Temperature = readtemp; } var serializedString = JsonConvert.SerializeObject(info); Message data = new Message(Encoding.UTF8.GetBytes(serializedString)); // Send the metric to Event Hub var task = Task.Run(async() => await deviceClient.SendEventAsync(data)); //Write the values to your debug console Console.WriteLine("DeviceID: " + dId.ToString()); Console.WriteLine("Timestamp: " + info.TimeStamp1.ToString()); Console.WriteLine("Temperature: " + info.Temperature.ToString() + " deg C"); Console.WriteLine("Pressure: " + info.Pressure.ToString() + " Pa"); Console.WriteLine("------------------------------"); //Message data = new Message(Encoding.UTF8.GetBytes("myDeviceId2,19,Ban-EGL,14804022344554")); //// Send the metric to Event Hub //var task = Task.Run(async () => await deviceClient.SendEventAsync(data)); Task.Delay(3000).Wait(); } } catch (Exception e) { } }
static async void SendDeviceToCloudMessagesAsync() { string iotHubUri = "BuchRaspberryHub.azure-devices.net"; string deviceId = "MeinRaspberry"; string deviceKey = "<Key>"; var deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); string str = String.Format("Temperatur um {0} : {1} Grad Celsius", DateTime.Now, GetTemperature()); Message message = new Message(Encoding.ASCII.GetBytes(str)); await deviceClient.SendEventAsync(message); }
private static void SaveConnectionString(string hostName, string deviceId, string accessKey) { var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create( hostName, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey( deviceId, accessKey)); var settings = ApplicationData.Current.LocalSettings; settings.Values["IoTHubConnectionString"] = iotHubConnectionStringBuilder.ToString(); }
static async void SendDeviceToCloudMessagesAsync() { var deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory. CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1); var str = "Hello, Cloud!"; var message = new Message(Encoding.ASCII.GetBytes(str)); await deviceClient.SendEventAsync(message); }
public void IotHubConnectionStringBuilder_ParamHostNameAuthMethod_SharedAccessSignature() { IAuthenticationMethod authMethod = AuthenticationMethodFactory.CreateAuthenticationWithToken(DeviceId, SharedAccessSignature); var csBuilder = IotHubConnectionStringBuilder.Create(HostName, authMethod); csBuilder.HostName.Should().Be(HostName); csBuilder.DeviceId.Should().Be(DeviceId); csBuilder.SharedAccessSignature.Should().Be(SharedAccessSignature); csBuilder.AuthenticationMethod.Should().BeOfType <DeviceAuthenticationWithToken>(); csBuilder.SharedAccessKey.Should().BeNull(); }