@iduntech/idun-guardian-sdk
v0.1.38
Published
The IDUN Guardian SDK is currently a TypeScript-based SDK that caters to client-side browser applications, providing them with the ability to seamlessly connect to the IDUN Guardian Earbuds via [Web Bluetooth](https://developer.mozilla.org/en-US/docs/Web/
Readme
TypeScript SDK
Overview
The IDUN Guardian SDK is currently a TypeScript-based SDK that caters to client-side browser applications, providing them with the ability to seamlessly connect to the IDUN Guardian Earbuds via Web Bluetooth. This SDK has been designed to be compatible with Ionic's Capacitor framework, which enables developers to create cross-platform apps using web technologies.
The primary objective of this SDK is to facilitate the interaction with IDUN Guardian Earbuds, allowing the retrieval of EEG and Impedance data, handling device connections, and managing recordings with ease.
Installation
You can install the SDK from the NPM via:
npm install @iduntech/idun-guardian-sdkPeer-Dependencies
This project requires the following peer dependencies to be installed:
@byteowls/capacitor-oauth2: ^5.0.0@capacitor-community/bluetooth-le: ^6.0.1@capacitor/browser: ^6.0.2@capacitor/core: ^6.1.2websocket-ts: ^1.1.1
You can install the dependencies in your project with the following command:
npm install @byteowls/[email protected] @capacitor-community/[email protected] @capacitor/[email protected] @capacitor/[email protected] [email protected]Environment Variables
The SDK uses production endpoints by default - you don't need to set any environment variables to get started. If you want to use the staging environment instead, set these variables:
NEXT_PUBLIC_REST_ENDPOINT="https://api.stage.idun.cloud"
NEXT_PUBLIC_WEBSOCKET_ENDPOINT="wss://ws-api.stage.idun.cloud"
NEXT_PUBLIC_AUTH_BASE_URL="https://oauth.stage.idun.cloud"
NEXT_PUBLIC_AUTH_APPID_WEB="4io2gdfl5eou8s8elgb1kopckp"
NEXT_PUBLIC_AUTH_APPID_ANDROID="6vl7qf9ik6on8fc1msjraltu56"
NEXT_PUBLIC_AUTH_APPID_IOS="3ps8a006gf20jkn4kbjfegen2f"If you want to use the IDUN Guardian SDK in custom mobile app, you need to set your own URI schemes for Android and iOS:
NEXT_PUBLIC_URI_SCHEME_ANDROID="com.idunguardian.console" # Default value
NEXT_PUBLIC_URI_SCHEME_IOS="com.idunguardian.app" # Default valueThe values for APP IDs should be requested to the IDUN team.
Usage
Currently, due to the required environment variables for authentication, you can only use NextJS Framework. This restriction will be changed in the future.
Creating a Next.js project:
npx create-next-appInitialize Guardian Object
To start using the SDK you can import and instantiate the Guardian object as following:
import { Guardian } from "@iduntech/idun-guardian-sdk";
const guardian = new Guardian();Authentication
Once you have the guardian object, you can call the checkAuth() method to start authentication:
guardian
.checkAuth()
.then((result) => {
if (result.authenticated) {
console.log("Authenticated:", result);
} else {
console.log("Not authenticated:", result.reason);
}
})
.catch((error) => {
console.error("Error:", error);
});When calling checkAuth() for the first time, the user will be redirected to a AWS Cognito's login page to submit IDUN's username and password.
After submitting the credentials, the App will be redirected to <your-base-url>/auth/cognito/callback with code in the URL Search Params. In you App, you should check if code exists in search params, and if so, this means the Cognito authentication was successfull.
If code exists, you should call checkAuth again, so the access token will be imputed into the guardian instance.
This is a example code in Next.js + React for the callback page:
const Callback = () => {
const router = useRouter();
useEffect(() => {
// Check if `code` exists in URL Search Params
const { code } = router.query;
if (code) {
// Call checkAuth() again, to request for access token.
// The access token will be automatically added into all cloud requests
guardian.checkAuth().then(() => {
// Redirect to any route you want (here is /home)
router.replace("/home", undefined, { shallow: true });
});
}
}, [router.query]);
// "Loading..." will be showing while the requests for access token and the internal processes are going
return <div>Loading...</div>;
};
export default Callback;Connect Earbuds:
Once authenticated, you can connect the earbud and start streaming data:
guardian.connectEarbuds().then((earbuds) => {
// prints the battery level
earbuds.getBatteryLevel().then((batteryLevel) => {
console.log(batteryLevel);
});
});Sample Application
To help you get started quickly, we've provided a minimal sample application that demonstrates key features of the IDUN Guardian SDK.
This can be found in the idun-sample-app-js repository.
Sample App Features
The sample app demonstrates:
- Authentication with IDUN Guardian services
- Connecting to IDUN Guardian Earbuds via Bluetooth
- Reading battery level from connected devices
- Clean disconnection and logout
How to Use the Sample App
You can find the sample app in the sample-app directory of this repository. To run it:
cd sample-app
npm install
npm run devThis will start a Next.js development server at http://localhost:3000 where you can explore the sample implementation.
For full details about the sample app, see its README.md.
Earbud basic operations:
Start EEG Streaming:
await earbuds.startEEGStream();Stop EEG Streaming:
await earbuds.stopEEGStream();Disconnect:
await earbuds.disconnect();SDK Structure
The SDK primarily encapsulates two classes: Guardian and Earbud.
Guardian
Guardian is the main class that acts as the entry point of the SDK. It is responsible for managing the Bluetooth Low
Energy (BLE) connection and communication with the earbuds. It handles the WebSocket connections for real-time data
transmission and RESTful connections for server communication. The class takes care of user authentication, error
handling and manages the entire communication process.
The Guardian class includes methods for:
connectEarbuds(): Connects to the earbuds.checkAuth(): Authenticates the user.sendEEGDataToCloud()andsendImpedanceDataToCloud(): Sends EEG and Impedance data to the server.getAllRecordings(),getMetaData(),deleteRecording(),renameRecordingByRecordingId(),downloadEEG(),requestReport(),downloadReportById(),downloadIMU(): Methods for managing recordings.connectWebSocket(): Handles the WebSocket connection.disconnectClean(): Handles clean disconnects.onAccidentalBluetoothDisconnect(): Handles accidental disconnects.
Earbud
Earbud is a class that provides an interface to interact with an individual earbud. It provides methods for:
startEEGStream()andstopEEGStream(): Starts and stops the EEG stream.startImpedanceStream()andstopImpedanceStream(): Starts and stops the Impedance stream.getBatteryLevel(): Gets the battery level of the earbud.getDeviceID(): Gets the device ID of the earbud.getHardwareVersion()andgetFirmwareVersion(): Gets the hardware and firmware versions of the earbud.setLED(): Controls the LED status of the earbud.subscribeRealtimePredictions(): subscribe to one or more of the available realtime predictions via the callback methodunsubscribeRealtimePredictions(): ends the subscription to the realtime predictions
Code Logic
The SDK operates on the principle of establishing a BLE connection to the earbuds via the Guardian class. Once the
connection is established, it allows the user to interact with the earbuds using the Earbud class. Upon initiating
data streams, it sends the EEG and Impedance data to the server in real-time. It also provides an interface to manage
recordings on the server.
The SDK makes extensive use of Promises for handling asynchronous operations, particularly when dealing with Bluetooth connections and server communication. Error handling is integrated throughout the SDK to ensure proper functioning and easy debugging.
