@saveeye/saveeye-sdk-reactnative v0.1.26
Saveeye SDK
The Saveeye SDK provides a set of methods to interact with Saveeye devices, including provisioning, connecting to WiFi, and retrieving device information. Below is a description of the different methods available in the SDK.
Example app
An example app is available here: SaveEye SDK Example App
Permissions
iOS
- Since iOS 13, apps that want to access the SSID (Wi-Fi network name) are required to have location permission. Add the key NSLocationWhenInUseUsageDescription in Info.plist with an appropriate description.
- Since iOS 14, apps that communicate over the local network are required to have local network permission. Add the key NSLocalNetworkUsageDescription in Info.plist with an appropriate description.
- NSBluetoothAlwaysUsageDescription is needed to communicate with the SaveEye device over BLE
Android
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<!-- Request legacy Bluetooth permissions on older devices. -->
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />General
getInstance
getInstance();Returns the singleton instance of the SaveeyeSdk class.
initialize
initialize(appSDKKey: string, onJWTRequest: () => Promise<string>): voidInitializes the SDK with the provided appSDKKey (can be generated in the SaveEye manager portal) and a callback returning a fresh JWT.
Example
import SaveeyeSdk from '@saveeye/saveeye-sdk-reactnative';
async function getJWTToken(): Promise<string> {
let token = await auth.currentUser?.getIdToken();
return token ?? '';
}
SaveeyeSdk.getInstance().initialize(APP_SDK_KEY, getJWTToken);Provisioning
provisionDevice
provisionDevice(qrCode: string, externalId?: string, manualPairing?: boolean): Promise<ESPDevice>Provisions a device using the QRCode on the device and an optional external ID (The device gets paired to the externalId). If no externalID is provided, the device will be paired with the userId within the JWT.
Parameters:
- qrCode: The QR code from the device
- externalId?: Optional external ID to pair the device with
- manualPairing?: If true, skips the automatic pairing process. Useful when you want to handle pairing separately.
ManualPairing: If using manual pairing, make sure to call the pairDevice function yourself at a later stage. Otherwise the user will not be granted access to the device, and you will receive an error
Status updates follow this sequence during device provisioning:
export enum ConnectionStages {
NONE = 'None', // Initial state
FETCHING_DEVICE_CONFIG = 'FetchingDeviceConfig', // Fetching device config from SaveEye server
FETCHED_DEVICE_CONFIG = 'FetchedDeviceConfig', // Device config retrieved
SEARCHING = 'Searching', // Searching for device via BLE
CONNECTED = 'Connected', // Connected to device via BLE
PAIRING = 'Pairing', // Pairing device with user (will not be sent for manualPairing)
PAIRED = 'Paired', // Device successfully paired (will not be sent for manualPairing)
ERROR = 'Error', // An error occurred during any stage
}getAvailableSSIDForDevice
getAvailableSSIDForDevice(device: ESPDevice): Promise<ESPWifiList[]>Retrieves the available WiFi networks for the specified device.
connectToWiFi
connectToWiFi(device: ESPDevice, ssid: string, passphrase?: string): Promise<void>Connects the specified device to the provided WiFi network. Optional passphrase key for the network.
onDeviceStatusUpdate
onDeviceStatusUpdate(callback: (status: string) => void)Registers`a callback to receive device status updates when the device is provisioning using BLE.
Status updates follow this sequence during device provisioning:
export enum ConnectionStages {
NONE = 'None', // Initial state
FETCHING_DEVICE_CONFIG = 'FetchingDeviceConfig', // Fetching device config from SaveEye server
FETCHED_DEVICE_CONFIG = 'FetchedDeviceConfig', // Device config retrieved
SEARCHING = 'Searching', // Searching for device via BLE
CONNECTED = 'Connected', // Connected to device via BLE
PAIRING = 'Pairing', // Pairing device with user
PAIRED = 'Paired', // Device successfully paired
ERROR = 'Error', // An error occurred during any stage
}stopDeviceStatusUpdates
stopDeviceStatusUpdates();Stops receiving device status updates.
pairDevice
pairDevice(deviceId: string, externalId?: string): Promise<void>Pair a device with an optional externalId. If no externalId is provided, the UserId from the JWT token will be used instead. Also called automatically from provisionDevice, but this can be used to avoid having to reprovision a device.
unpairDevice
unpairDevice(deviceId: string, externalId?: string): Promise<void>Unpairs a device from the current user. This removes the association between the device and the user, allowing the device to be paired with a different user.
Parameters:
- deviceId: The ID of the device to unpair
- externalId?: Optional external ID to unpair the device from. This is mandatory if the externalId is a listclaim (As provided when creating app SDK key in the SaveEye Manager).
User
getMyDevices
getMyDevices(): Promise<MyDeviceFragment>Retrieves the devices associated with the user.
getMyPairedDevices
getMyPairedDevices(): Promise<MyPairedDeviceFragment[]>Retrieves a list of devices that have been paired with external IDs. This is useful when you need to know which devices are associated with specific external identifiers.
The MyPairedDeviceFragment type contains the following fields:
type MyPairedDeviceFragment = {
externalId: string; // The external ID the device is paired with
coreDevice: {
id: string; // Unique identifier of the device
serial: string; // Device serial number
alias?: string | null; // User-defined name for the device
};
};getDeviceById
getDeviceById(deviceId: string): Promise<MyDeviceFragment>Retrieves a specific device by its ID. Note: This function will only return the device if the user's JWT token is paired with the device.
Parameters:
- deviceId: The ID of the device to retrieve
The MyDeviceFragment type contains the following fields:
type MyDeviceFragment = {
id: string; // Unique identifier of the device
alias?: string | null; // User-defined name for the device
serial: string; // Device serial number
allTimesHighConsumption: number; // Highest recorded consumption value
allTimesHighProduction: number; // Highest recorded production value
hasProduction: boolean; // Whether the device can has measured production
rmsCurrentMaxPerPhaseAmpere?: number | null; // Maximum RMS current per phase in amperes
};Device data
Historic
getEnergyUsageHistory
getEnergyUsageHistory(deviceId: string, startUTC: Date, endUTC: Date, interval: IntervalType): Promise<EnergyUsageHistory>Retrieves the energy usage history of a device within a specified time range and interval. The interval parameter determines the granularity of the data points (e.g. hourly, daily, monthly). Returns a Promise containing the energy usage data for the specified period.
Parameters:
- deviceId: The ID of the device to get history for
- startUTC: Start date/time in UTC
- endUTC: End date/time in UTC
- interval: The data point interval (IntervalType)
getPowerUsageHistory
getPowerUsageHistory(deviceId: string, startUTC: Date, endUTC: Date, interval: IntervalType): Promise<PowerUsageHistory>Retrieves the power usage history of a device within a specified time range and interval. The interval parameter determines the granularity of the data points (e.g. hourly, daily, monthly). Returns a Promise containing the power usage data for the specified period.
Parameters:
- deviceId: The ID of the device to get history for
- startUTC: Start date/time in UTC
- endUTC: End date/time in UTC
- interval: The data point interval (IntervalType)
The PowerUsageHistory type contains the following fields:
type PowerUsageHistory = {
deviceId: string; // The unique identifier of the device
intervalType: IntervalType; // The time interval used for aggregating power usage data
powerUsageSummaries: Array<PowerUsageSummary>; // Collection of power usage summaries
};
type PowerUsageSummary = {
aggregationPeriod: Date; // The timestamp representing the start of the aggregation period (UTC)
averageConsumptionWatt: number; // The average power consumption (in watts) during the aggregation period
averageProductionWatt: number; // The average power production (in watts) during the aggregation period
maxConsumptionWatt: number; // The maximum power consumption (in watts) recorded during the aggregation period
maxProductionWatt: number; // The maximum power production (in watts) recorded during the aggregation period
minConsumptionWatt: number; // The minimum power consumption (in watts) recorded during the aggregation period
minProductionWatt: number; // The minimum power production (in watts) recorded during the aggregation period
};Realtime
subscribeToRealtimeData
async subscribeToRealtimeData(
deviceId: string,
callback: (data: RealtimeReading) => void
)Subscribes to real-time data updates for a specific device. This method establishes a WebSocket connection to receive real-time data from the device and invokes the provided callback function whenever new data is received.
unsubscribeFromRealtimeData
unsubscribeFromRealtimeData(): voidUnsubscribes from real-time dat` updates for a device. This method closes the WebSocket connection that was established for receiving real-time data.
Best implemented with a return function in eg. a useEffect, to make sure the websocket is closed when not in use.
React Native Example:
useEffect(() => {
SaveeyeSdk.getInstance().subscribeToRealtimeData(deviceId, (data) => {
console.log('Got realtime data:', data);
});
return () => {
SaveeyeSdk.getInstance().unsubscribeFromRealtimeData();
};
}, [deviceId]);Expo Router Example:
useFocusEffect(
useCallback(() => {
SaveeyeSdk.getInstance().subscribeToRealtimeData(deviceId, (data) => {
console.log('Got realtime data:', data);
});
return () => {
SaveeyeSdk.getInstance().unsubscribeFromRealtimeData();
};
}, [deviceId])
);Settings
getDeviceSettings
getDeviceSettings(deviceId: string): Promise<DeviceSettingsFragment>Retrieves the settings of a specific device. DeviceSettings contains the following:
type DeviceSettingsFragment = {
__typename?: 'CoreDevice';
localMqttBroker?: string | null;
localMqttEnabled: boolean;
localMqttPassword?: string | null;
localMqttPort?: number | null;
localMqttUser?: string | null;
alias?: string | null;
consumptionAlarmMaxWh?: number | null;
consumptionAlarmMinWh?: number | null;
};setDeviceAlias
setDeviceAlias(deviceId: string, name: string): Promise<void>Sets the alias (name) for a specific device. This method updates the device's alias on the server.
setLocalMQTTSettings
setLocalMQTTSettings(
deviceId: string,
enabled: boolean,
broker: string,
port: number,
username: string,
password: string
): Promise<void>Sets the local MQTT settings for a specific device. This method updates the local MQTT configuration on the server for the specified device.
updateDeviceAlarmThresholds
setDeviceAlarmThresholds(
deviceId: string,
alarmMaxWh: number,
alarmMinWh: number
): Promise<void>Sets the alarm thresholds for a specific device. This method updates the maximum and minimum alarm thresholds for the device on the server. When the threshold is reached your backend can be notified.
setRmsCurrentMaxPerPhase
setRmsCurrentMaxPerPhase(deviceId: string, rmsCurrentMax: number): Promise<void>Sets the maximum RMS current per phase for a specific device. This method updates the maximum allowed current (in amperes) that can flow through each phase of the meter. This can be retrieved again through the getMyDevices function.
Parameters:
- deviceId: The ID of the device to update
- rmsCurrentMax: The maximum RMS current in amperes per phase
Support
For support or questions, please contact thj@saveeye.com.
7 months ago
7 months ago
7 months ago
7 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago