IoTHubClient

Struct IoTHubClient 

Source
pub struct IoTHubClient { /* private fields */ }
Expand description

Client for communicating with IoT hub

Implementations§

Source§

impl IoTHubClient

Source

pub async fn new<TS>( hub_name: &str, device_id: String, token_source: TS, ) -> Result<IoTHubClient>
where TS: TokenSource + Send + Sync + Clone + 'static,

Create a new IoT Hub device client using a shared access signature

§Arguments
  • hub_name - The IoT hub resource name
  • device_id - The registered device to connect as
  • token_source - The token source to provide authentication
§Example
use azure_iot_sdk::{IoTHubClient, DeviceKeyTokenSource};

#[tokio::main]
async fn main() {
    let iothub_hostname = "iothubname.azure-devices.net";
    let device_id = "MyDeviceId";
    let token_source = DeviceKeyTokenSource::new(
        iothub_hostname,
        device_id,
        "TheAccessKey",
    ).unwrap();

    let mut client =
        IoTHubClient::new(iothub_hostname, device_id.into(), token_source).await;
}
Source

pub async fn send_message(&mut self, message: Message) -> Result<()>

Send a device to cloud message for this device to the IoT Hub

§Example
use tokio::time;
use azure_iot_sdk::{IoTHubClient, DeviceKeyTokenSource, Message};

#[tokio::main]
async fn main() -> azure_iot_sdk::Result<()> {
    let iothub_hostname = "iothubname.azure-devices.net";
    let device_id = "MyDeviceId";
    let token_source = DeviceKeyTokenSource::new(
        iothub_hostname,
        device_id,
        "TheAccessKey",
    ).unwrap();

    let mut client =
        IoTHubClient::new(iothub_hostname, device_id.into(), token_source).await?;

    let mut interval = time::interval(time::Duration::from_secs(1));
    let mut count: u32 = 0;

    loop {
        interval.tick().await;

        let msg = Message::builder()
            .set_body(format!("Message #{}", count).as_bytes().to_vec())
            .set_message_id(format!("{}-t", count))
            .build();

        client.send_message(msg).await?;

        count += 1;
    }
}
Source

pub async fn send_property_update( &mut self, request_id: &str, body: &str, ) -> Result<()>

Send a property update from the device to the cloud

Property updates sent from the device are used to publish the device’s current values for “properties” in IoTCentral terminology or Device Twin Attributes in IoTHub terminology. The body of the message should be JSON encoded with a map of names to values. The request ID should be a unique ID that will match the response sent from the server via the property channel.

§Example

Suppose we have two properties property_1 and property_2 defined on our Device Twin (or defined as properties in our IoTCentral device capability model). For convenience we define a struct so we can use serde to convert them to JSON.

#[derive(Serialize)]
struct MyProperties {
   property_1: f64,
   property_2: f64,
}

Then to send the current value of the properties to the cloud, we would use something like

   let my_struct = MyProperties {property_1 : 31.0, property_2: 42.0};
   let body = serde_json::to_string(&my_struct).unwrap();
   client.send_property_update(&format!("{}", update_counter), &body).await.unwrap();
   update_counter += 1;
Source

pub async fn get_receiver(&mut self) -> Receiver<MessageType>

Source

pub async fn respond_to_direct_method( &mut self, response: DirectMethodResponse, ) -> Result<()>

Source

pub async fn ping(&mut self) -> Result<()>

Source§

impl IoTHubClient

Source

pub async fn from_provision_service( scope_id: &str, device_id: String, device_key: &str, max_retries: i32, ) -> Result<IoTHubClient, Box<dyn Error>>

Create a new IoT Hub device client using the device provisioning service

§Arguments
  • scope - The scope ID to use for the registration call
  • device_id - The registered device to connect as
  • key - The primary or secondary key for this device
  • max_retries - The maximum number of retries at the provisioning service

Note that this uses the default Azure device provisioning service, which may be blocked in some countries.

§Example
use azure_iot_sdk::IoTHubClient;

#[tokio::main]
async fn main() {
    let mut client = IoTHubClient::from_provision_service(
          "ScopeID",
          "DeviceID".into(),
          "DeviceKey",
          4).await;
}

Trait Implementations§

Source§

impl Clone for IoTHubClient

Source§

fn clone(&self) -> IoTHubClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for IoTHubClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.