ux4iot
Search…
Hooks

useTelemetry

The useTelemetry hook makes it very easy to just listen to telemetry on a single device.
1
const value = useTelemetry(deviceId, telemetryKey, { onData, onGrantError });
Copied!

Arguments

Argument
Description
Type
Required?
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
key
Description
value type
required
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

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.
1
const temperature = useTelemetry('simulated-device', 'temperature');
2
3
return (
4
<div>
5
<h3>Current Temperature of simulated-device</h3>
6
<div>{temperature}</div>
7
</div>
8
);
Copied!
The D2C messages are expected to look like this:
1
{
2
"temperature": 42.1,
3
...
4
}
Copied!

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

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

Full Hook Example

1
const {
2
telemetry,
3
toggleTelemetry,
4
isSubscribed,
5
currentSubscribers,
6
addTelemetry,
7
removeTelemetry,
8
} = useMultiTelemetry({
9
initialSubscribers: { [deviceId]: ['temperature', 'pressure'] },
10
onData: (deviceId, key, value) => console.log(deviceId, key, value),
11
onGrantError: error => console.log(error)
12
});
Copied!

Full Code Example

1
// Example of a component utilising the "toggleTelemetry" mechanism to
2
// toggle subscriptions to two datapoints "temperature" and "pressure"
3
4
import { FC } from 'react';
5
import { TelemetryValue, useMultiTelemetry } from 'ux4iot-react';
6
7
const DeviceValue: FC<TelemetryValue> = ({ value, timestamp }) => {
8
return (
9
<div>
10
{value} - received at {timestamp}
11
</div>
12
);
13
};
14
15
type Props = {
16
deviceId: string;
17
datapoints: string[];
18
};
19
20
const TestMultiSubscriber: FC<Props> = ({ deviceId, datapoints }) => {
21
const { telemetry, toggleTelemetry, isSubscribed } = useMultiTelemetry({
22
initialSubscribers: { [deviceId]: datapoints },
23
});
24
25
return (
26
<div>
27
{datapoints.map(dp => (
28
<div key={dp}>
29
<label>{dp}</label>
30
<input
31
type="checkbox"
32
checked={isSubscribed(deviceId, dp)}
33
onChange={() => toggleTelemetry(deviceId, dp)}
34
/>
35
{telemetry[deviceId] && <DeviceValue {...telemetry[deviceId][dp]} />}
36
</div>
37
))}
38
</div>
39
);
40
};
41
42
const App = () => {
43
return (
44
<Ux4iotContextProvider options={...}>
45
<TestMultiSubscriber
46
deviceId="simulated-device"
47
datapoints={['temperature', 'pressure']}
48
/>
49
</Ux4iotContextProvider>
50
);
51
};
Copied!

Arguments

Argument
Description
Type
Required?
options
Configuration Options
HookOptions

HookOptions

Argument
Description
Type
Required?
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
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.
Key
Value
Type
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).
1
const reboot = useDirectMethod(deviceId, methodName, { onGrantError });
Copied!

Arguments

Argument
Description
Type
Required?
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
Argument
Description
Type
Required?
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
1
{
2
status: number;
3
payload: unknown:
4
}
Copied!
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

1
const reboot = useDirectMethod(deviceId, 'reboot', {
2
onGrantError: error => console.log(error)
3
});
4
const result = useState<unknown>();
5
const error = useState<string>();
6
7
const handleClick = () => {
8
const payload = { delay: 2000 };
9
10
reboot(payload)
11
.then(result => setState(result))
12
.catch(error => setError(error));
13
}
14
15
return <button onClick={() => handleClick()}>Reboot Device</button>
Copied!

useDeviceTwin

The useDeviceTwin hook subscribes to device twin updates.
1
const deviceTwin = useDeviceTwin(deviceId, { onData, onGrantError });
Copied!

Arguments

Argument
Description
Type
Required?
deviceId
The device id of the device you want to subscribe to.
string
options
Configuration Options
HookOptions
Hook Options
Argument
Description
Type
Required?
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

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:
1
{
2
"version": 2,
3
"tags": {
4
"$etag": "123",
5
"deploymentLocation": {
6
"building": "43",
7
"floor": "1"
8
}
9
},
10
"properties": {
11
"desired": {
12
"telemetryConfig": {
13
"sendFrequency": "5m"
14
},
15
"$version": 1
16
},
17
"reported": {
18
"telemetryConfig": {
19
"sendFrequency": "5m",
20
"status": "success"
21
},
22
"batteryLevel": 55,
23
"$version": 4
24
}
25
}
26
}
Copied!

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.
1
const connectionState = useConnectionState(deviceId, { onData, onGrantError });
Copied!

Arguments

Argument
Description
Type
Required?
deviceId
The device id of the device you want to subscribe to.
string
options
Configuration Options
HookOptions
Hook Options
Argument
Description
Type
Required?
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

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).

usePatchDesiredProperties

The usePatchDesiredProperties hook is used to perform desired property updates on devices.
1
const patchDesiredProperties = usePatchDesiredProperties(deviceId, { onGrantError });
Copied!

Arguments

Argument
Description
Type
Required?
deviceId
The device id of the device onto which to patch the desired properties
string
options
Configuration Options
HookOptions
Hook Options
Argument
Description
Type
Required?
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
1
{
2
status: number;
3
payload: unknown:
4
}
Copied!
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

1
const patchDesiredProperties = usePatchDesiredProperties('simulated-device');
2
3
const handleClick = () => {
4
patchDesiredProperties({
5
temperature: 21
6
});
7
}
8
9
return <button onClick={() => handleClick()}>Update desired properties</button>
Copied!

useD2CMessages<T>

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

Arguments

Argument
Description
Type
Required?
deviceId
The device ID of the device you want to subscribe to.
string
options
Configuration Options
HookOptions
Hook Options
Argument
Description
Type
Required?
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

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:
1
const value = useX(deviceId, ...);
2
3
useEffect(() => {
4
console.log('Update to value detected')
5
}, [value]);
Copied!
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.