-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
85 lines (73 loc) · 2.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import {NativeEventEmitter, NativeModules} from 'react-native';
export const {IoTHubDeviceModule} = NativeModules;
/**
* Returns Promise so you can await
*
* @param connectionString
* @param desiredPropertySubscriptions
* @param onDesiredPropertyUpdate
* @returns {Promise}
*/
export function connectToHub(connectionString, desiredPropertySubscriptions, onConnectionStatusChange, onDeviceTwinPropertyRetrieved, onMessageReceived, onDeviceTwinStatusCallback){
new NativeEventEmitter(IoTHubDeviceModule).addListener('onDesiredPropertyUpdate', (event) => {
if(event.propertyJson){
const property = JSON.parse(event.propertyJson);
onDesiredPropertyUpdate(property.property);
}
});
new NativeEventEmitter(IoTHubDeviceModule).addListener('onConnectionStatusChange', (event) => {
onConnectionStatusChange(event);
});
/**
* All properties retrieved when first connected, and retrieved when an update is made remotely.
*/
new NativeEventEmitter(IoTHubDeviceModule).addListener('onDeviceTwinPropertyRetrieved', (event) => {
if(event && event.propertyJson){
try {
onDeviceTwinPropertyRetrieved(JSON.parse(event.propertyJson));
}catch (error){
console.error(error);
}
}
});
/**
* When device operations are invoked from this device, IoT Hub will send response messages.
*/
new NativeEventEmitter(IoTHubDeviceModule).addListener('onDeviceTwinStatusCallback', (event) => {
onDeviceTwinStatusCallback(event);
});
new NativeEventEmitter(IoTHubDeviceModule).addListener('onMessageReceived', (event) => {
onMessageReceived(event);
});
return IoTHubDeviceModule.connectToHub(connectionString, desiredPropertySubscriptions);
}
export async function requestTwinProperties(){
return await IoTHubDeviceModule.requestTwinProperties();
}
/**
* Returns Promise. Doesn't actually return device twin - it makes a request to your hub
* to send you all Device Twin properties via the onDeviceTwinPropertyRetrieved callback.
*
* @param propertyKey
* @param success
* @param failure
* @returns {*}
*/
export function subscribeToTwinDesiredProperties(propertyKey, success, failure){
return IoTHubDeviceModule.subscribeToTwinDesiredProperties(propertyKey, success, failure);
}
/**
* @param {Object[]} properties - Example input: {testValue:12345, testValue2:"12345", testValue3: true}
* @returns {Promise}
*/
export function reportProperties(properties) {
//translate simple json map to a key/value array
const keyValueArray = [];
Object.keys(properties).forEach(key => {
keyValueArray.push({
key,
value:properties[key]
});
});
return NativeModules.IoTHubDeviceModule.sendReportedProperties(keyValueArray);
}