Hooks

useTelemetry

The useTelemetry hook makes it very easy to just listen to telemetry on a single device.

const value = useTelemetry(deviceId, telemetryKey, { onData, onGrantError });

Arguments

ArgumentDescriptionTypeRequired?

deviceId

The device ID of the device from which to receive telemetry data

string

telemetryKey

The key of the telemetry item

string

options

Configuration Options

HookOptions

HookOptions

keyDescriptionvalue typerequired

onData

Callback, executed when new telemetry of telemetryKey is received on the device

(data: unknown) => void

onGrantError

Callback, executed when the grantRequestFunction fails to grant the direct method request

GrantErrorCallback

onSubscriptionError

Callback, executed when an error is returned from the subscription endpoints of ux4iot

SubscriptionErrorCallback

Return Value

This hook returns a single value. Every time the device sends new telemetry with key telemetryKey this hook will update this value.

This hook relies on the assumption that your Device-to-Cloud messages are JSON documents where the key is the telemetry key and the value is the current telemetry value. We plan to support more complex payloads in the future (selecting using JSON Path, Avro, etc). If you have other message payloads, you can use the useD2CMessage hook.

Example

A component subscribing to the temperature telemetry.

const temperature = useTelemetry('simulated-device', 'temperature');

return (
    <div>
        <h3>Current Temperature of simulated-device</h3>
        <div>{temperature}</div>
    </div>
);

The D2C messages are expected to look like this:

{
  "temperature": 42.1,
  ...
}

useMultiTelemetry

The useMultiTelemetry hook is a more sophisticated variant of useTelemetry. It is designed to cover use-cases where a several streams of telemetry of multiple devices need to be subscribed to.

Minimal Hook Example

const { telemetry, addTelemetry, removeTelemetry } = useMultiTelemetry({});

Full Hook Example

    const {
        telemetry,
        toggleTelemetry,
        isSubscribed,
        currentSubscribers,
        addTelemetry,
        removeTelemetry,
    } = useMultiTelemetry({
        initialSubscribers: { [deviceId]: ['temperature', 'pressure'] },
        onData: (deviceId, key, value) => console.log(deviceId, key, value),
        onGrantError: error => console.log(error)
    });

Full Code Example

// Example of a component utilising the "toggleTelemetry" mechanism to 
// toggle subscriptions to two datapoints "temperature" and "pressure"

import { FC } from 'react';
import { TelemetryValue, useMultiTelemetry } from 'ux4iot-react';

const DeviceValue: FC<TelemetryValue> = ({ value, timestamp }) => {
  return (
    <div>
      {value} - received at {timestamp}
    </div>
  );
};

type Props = {
  deviceId: string;
  datapoints: string[];
};

const TestMultiSubscriber: FC<Props> = ({ deviceId, datapoints }) => {
  const { telemetry, toggleTelemetry, isSubscribed } = useMultiTelemetry({
    initialSubscribers: { [deviceId]: datapoints },
  });

  return (
    <div>
      {datapoints.map(dp => (
        <div key={dp}>
          <label>{dp}</label>
          <input
            type="checkbox"
            checked={isSubscribed(deviceId, dp)}
            onChange={() => toggleTelemetry(deviceId, dp)}
          />
          {telemetry[deviceId] && <DeviceValue {...telemetry[deviceId][dp]} />}
        </div>
      ))}
    </div>
  );
};

const App = () => {
  return (
    <Ux4iotContextProvider options={...}>
      <TestMultiSubscriber
        deviceId="simulated-device"
        datapoints={['temperature', 'pressure']}
      />
    </Ux4iotContextProvider>
  );
};

Arguments

ArgumentDescriptionTypeRequired?

options

Configuration Options

HookOptions

HookOptions

ArgumentDescriptionTypeRequired?

initialSubscribers

Object of key-value pairs, with keys: the device IDs of your IoTHub devices, and value: a list of strings, defining the telemetryKeys to subscribe to

Record<string, string[]>

onData

Callback, executed when a new value for a telemetryKey is sent by a device with ID deviceId

(deviceId: string, telemetryKey: string, value: unknown) => void

onGrantError

Callback, executed when the grantRequestFunction fails to grant the subscription request.

GrantErrorCallback

onSubscriptionError

Callback, executed when an error is returned from the subscription endpoints of ux4iot

SubscriptionErrorCallback

Do not try to perform subscription updates over the initialSubscribers object. This object is meant solely as an option for use cases where you always have an initial set of subscribers. Updates to initialSubscribers will not trigger updates in the hook.

Return Value

This hook returns an object containing other objects and functions to interact with telemetry subscriptions.

KeyValueType

telemetry

Object holding the current values of all your telemetry subscriptions

Record<string, Record<string, unknown>

toggleTelemetry

Toggles a telemetry subscription for a deviceId and telemetryKey

(deviceId: string, telemetryKey: string) => void

addTelemetry

Adds a telemetry subscription for a deviceId and multiple telemetryKeys

(deviceId: string, telemetryKeys: string[]) => void

removeTelemetry

Removes a telemetry subscription for a deviceId and multiple telemetryKeys

(deviceId: string, telemetryKeys: string[]) => void

isSubscribed

Checks whether a telemetry subscription for a deviceId and telemetryKey exists

(deviceId: string, telemetryKey: string) => boolean

currentSubscribers

Object containing all current subscribers with key being the deviceId and value being the telemetryKey names.

Record<string, string[]>

useDirectMethod

The useDirectMethod hook returns a function that, when invoked, calls a direct method on the target device. It returns a Promise that resolves to the direct method result that the device returns (or an error when the direct method could not be executed, e.g. if the device is offline).

const reboot = useDirectMethod(deviceId, methodName, { onGrantError });

Arguments

ArgumentDescriptionTypeRequired?

deviceId

The device ID of the device to execute the direct method on

string

methodName

The name of the method to execute on the device

string

options

Configuration Options

HookOptions

Hook Options

ArgumentDescriptionTypeRequired?

onGrantError

Callback, executed when the grantRequestFunction fails to grant the direct method request

GrantErrorCallback

Return Value

This hook returns a function: (params: Record<string, unknown>) => Promise<IotHubResponse | void>

IoTHubResponse

{
    status: number;
    payload: unknown:
}

You pass the method payload to this function and it outputs the result of the direct method invocation on the device.

Do not confuse the onGrantError handler of useDirectMethod with the catch block of the direct method itself. onGrantError will only be executed when this hook is rendered by react and the security backend fails to grant the direct method. The error that reboot may throw is an HTTP error that could occur when the function is executed.

Example

const reboot = useDirectMethod(deviceId, 'reboot', {
    onGrantError: error => console.log(error)
});
const result = useState<unknown>();
const error = useState<string>();

const handleClick = () => {
    const payload = { delay: 2000 };

    reboot(payload)
        .then(result => setState(result))
        .catch(error => setError(error));
}

return <button onClick={() => handleClick()}>Reboot Device</button>

useDeviceTwin

The useDeviceTwin hook subscribes to device twin updates.

const deviceTwin = useDeviceTwin(deviceId, { onData, onGrantError });

Arguments

ArgumentDescriptionTypeRequired?

deviceId

The device id of the device you want to subscribe to.

string

options

Configuration Options

HookOptions

Hook Options

ArgumentDescriptionTypeRequired?

onData

Callback, executed when a new twin updated is received.

(twin: Twin) => void

onGrantError

Callback, executed when the grantRequestFunction fails to grant the subscription request.

GrantErrorCallback

onSubscriptionError

Callback, executed when an error is returned from the subscription endpoints of ux4iot

SubscriptionErrorCallback

Return Value

This hook returns a value: Twin

This hook returns the device twin whenever twin updates are made on the IoTHub device. This hook uses the Twin typescript type provided from the azure-iothub library.

Here is an example of a returned device twin:

{
  "version": 2,
  "tags": {
    "$etag": "123",
    "deploymentLocation": {
      "building": "43",
      "floor": "1"
    }
  },
  "properties": {
    "desired": {
      "telemetryConfig": {
        "sendFrequency": "5m"
      },
      "$version": 1
    },
    "reported": {
      "telemetryConfig": {
        "sendFrequency": "5m",
        "status": "success"
      },
      "batteryLevel": 55,
      "$version": 4
    }
  }
}

useConnectionState

The useConnectionState hook subscribes to the connection state of a device. This state can change, i.e as soon as a device connects or disconnects.

const connectionState = useConnectionState(deviceId, { onData, onGrantError });

Arguments

ArgumentDescriptionTypeRequired?

deviceId

The device id of the device you want to subscribe to.

string

options

Configuration Options

HookOptions

Hook Options

ArgumentDescriptionTypeRequired?

onData

Callback, executed when a new connectionState update is received.

(connectionState: boolean) => void

onGrantError

Callback, executed when the grantRequestFunction fails to grant the subscription request.

GrantErrorCallback

onSubscriptionError

Callback, executed when an error is returned from the subscription endpoints of ux4iot

SubscriptionErrorCallback

Return Value

This hook returns a value: boolean

This value changed as soon as a device connects or disconnects.

The connection state information can be quite delayed (up to 1 minute). This is not a ux4iot issue, but an issue with IoT Hub itself (see here and here).

useMultiConnectionState

Minimal Hook Example

const { connectionStates, addConnectionState, removeConnectionState } = useMultiConnectionState({});

Full Hook Example

const {
  connectionStates,
  addConnectionState,
  currentSubscribers,
  isSubscribed,
  removeConnectionState,
  toggleConnectionState,
} = useMultiConnectionState({
  initialSubscribers: [],
  onData: (deviceId, data, timestamp) => console.log(data),
  onGrantError: (error: GRANT_RESPONSES) => console.log(error),
  onSubscriptionError: (error) => console.log(error)
});

Arguments

ArgumentDescriptionTypeRequired?

options

Configuration Options

HookOptions

HookOptions

ArgumentDescriptionTypeRequired?

initialSubscribers

Object of key-value pairs, with keys: the device IDs of your IoTHub devices, and value: a list of strings, defining the telemetryKeys to subscribe to

Record<string, string[]>

onData

Callback, executed when a new value for a telemetryKey is sent by a device with ID deviceId

(deviceId: string, telemetryKey: string, value: unknown) => void

onGrantError

Callback, executed when the grantRequestFunction fails to grant the subscription request.

GrantErrorCallback

onSubscriptionError

Callback, executed when an error is returned from the subscription endpoints of ux4iot

SubscriptionErrorCallback

Do not try to perform subscription updates over the initialSubscribers object. This object is meant solely as an option for use cases where you always have an initial set of subscribers. Updates to initialSubscribers will not trigger updates in the hook.

Return Value

This hook returns an object containing other objects and functions to interact with telemetry subscriptions.

KeyValueType

connectionStates

Object holding the current values of all your connectionState subscriptions

Record<string, boolean>

toggleConnectionState

Toggles a connectionState subscription for a deviceId

(deviceId: string) => Promise<void>

addConnectionState

Adds a connectionState subscription for a deviceId

(deviceId: string) => Promise<void>

removeConnectionState

Removes a connectionState subscription for a deviceId

(deviceId: string) => Promise<void>

isSubscribed

Checks whether a telemetry subscription for a deviceId exists

(deviceId: string) => boolean

currentSubscribers

List of all current deviceIds that are subscribed

string[]

usePatchDesiredProperties

The usePatchDesiredProperties hook is used to perform desired property updates on devices.

const patchDesiredProperties = usePatchDesiredProperties(deviceId, { onGrantError });

Arguments

ArgumentDescriptionTypeRequired?

deviceId

The device id of the device onto which to patch the desired properties

string

options

Configuration Options

HookOptions

Hook Options

ArgumentDescriptionTypeRequired?

onGrantError

Callback, executed when the grantRequestFunction fails to grant the patch desired properties request.

GrantErrorCallback

Return Value

This hook returns a function: (desiredProperties: Record<string, unknown>) => Promise<IoTHubResponse | void>

IoTHubResponse

{
    status: number;
    payload: unknown:
}

The hook takes in an object of desired properties to send to the device with the specified device ID.

When you call the function returned by this hook you will inevitably perform a device twin update. This means you will receive an update of the output of useDeviceTwin

Example

const patchDesiredProperties = usePatchDesiredProperties('simulated-device');

const handleClick = () => {
    patchDesiredProperties({
        temperature: 21
    });
}

return <button onClick={() => handleClick()}>Update desired properties</button>

useD2CMessages<T>

const lastMessage = useD2CMessages<T>(deviceId, { onData, onGrantError });

Arguments

ArgumentDescriptionTypeRequired?

deviceId

The device ID of the device you want to subscribe to.

string

options

Configuration Options

HookOptions

Hook Options

ArgumentDescriptionTypeRequired?

onData

Callback, executed when the device sends a new message.

(data: Record<string, unknown>) => void

onGrantError

Callback, executed when the grantRequestFunction fails to grant the subscription request.

GrantErrorCallback

onSubscriptionError

Callback, executed when an error is returned from the subscription endpoints of ux4iot

SubscriptionErrorCallback

Return Value

This hook returns the generic type you specified: T

Messages received over this hook have the type unknown first and are then casted to your type T. Omitting this generic type will leave the type unknown.

We assume that every message a device sends will be an object. The return value of this hook will always be the last message sent by the device.

Common Options

The hooks provided by ux4iot-react are using a specific authorization mechanism. They are designed to provide the easiest API to cover your use-case and hide the most complexity possible. There are two callbacks that are available on (almost) every hook.

onData

A convenient callback to have a custom callback whenever data is received. You will receive updates of subscription hooks mostly over the return value. However, if you want to use custom logic whenever an update is received you would need to use custom hooks to listen for these changes like this:

const value = useX(deviceId, ...);

useEffect(() => {
   console.log('Update to value detected')
}, [value]);

Therefore onData as function in subscription hooks, removes the burden of you needing to decide when to notice value changes.

onGrantError

This callback exists on every hook. The purpose of this callback is to inform you about errors that the custom grantRequestFunction returns. The grantRequestFunction is something that you need to implement yourself when you want to use ux4iot in production. The purpose of this function is to determine whether you as a user of the react application have the permission to subscribe to telemetry / device twin / connection state or perform a direct method / desired property patch.

Read more about this here.

Last updated