@espressif/rmng-base-sdk
v1.0.2
Published
Next-generation ESP Rainmaker SDK for JS based applications with enhanced MQTT communication, AWS Cognito authentication, and comprehensive device management capabilities.
Readme
ESP RainMaker Next Generation TypeScript SDK
The @espressif/rmng-base-sdk package provides a Next Generation foundational SDK for mobile app developers to seamlessly integrate with the ESP RainMaker ecosystem. Built specifically for React Native applications, it enables comprehensive device provisioning, user management, real-time device control, and MQTT-based communication with enhanced performance and reliability.
Table of Contents
- Overview
- Key Features
- Requirements
- Dependencies
- Installation
- Quick Start
- Usage Examples
- Architecture
- API Documentation
- Troubleshooting
- Contributing
- Resources
- License
Overview
The @espressif/rmng-base-sdk is a Next Generation TypeScript SDK designed specifically for React Native applications. It provides a comprehensive, type-safe interface for interacting with the ESP RainMaker ecosystem, featuring enhanced MQTT communication, robust authentication, and streamlined device management.
What's New in the NG SDK
- Enhanced MQTT Integration: Direct AWS IoT Core integration with automatic credential management
- React Native Optimized: Built specifically for React Native with proper crypto polyfills
- Type Safety: Full TypeScript support with comprehensive type definitions
- Improved Authentication: AWS Cognito integration with automatic session management
- Better Error Handling: Comprehensive error handling and logging
- Modular Architecture: Clean separation of concerns with extensible design
Key Features
- [x] AWS Cognito Authentication: Secure user authentication with automatic session management and token refresh
- [x] MQTT Real-time Communication: Direct AWS IoT Core integration with automatic credential provisioning
- [x] Device Provisioning: Complete device setup workflow with WiFi provisioning and cloud binding
- [x] React Native Optimized: Built specifically for React Native with crypto polyfills and native module support
- [x] Type Safety: Full TypeScript support with comprehensive type definitions
- [x] Modular Design: Clean architecture with separate modules for authentication, device management, and communication
- [x] Automatic Storage: Seamless data persistence with AsyncStorage integration
- [x] Error Handling: Comprehensive error handling with detailed logging
- [ ] Offline Support: Graceful offline operation with data synchronization (planned)
- [ ] Matter Protocol Support: Future integration with Matter standard (planned)
Requirements
Before installing the @espressif/rmng-base-sdk package, ensure you meet the following prerequisites:
- React Native: Version 0.72.0 or higher
- Node.js: Version 18.0 or higher
- TypeScript: Version 5.0 or higher (recommended)
- iOS: iOS 13.0 or higher
- Android: API level 24 (Android 7.0) or higher
Dependencies
Runtime Dependencies
The SDK has minimal runtime dependencies:
@aws-sdk/client-cognito-identity-provider– AWS Cognito authenticationgoogle-protobuf– Protocol buffer support for device provisioning
MQTT and HTTP are provided by your application via adapters (e.g., React Native native modules or esp-mqtt-communication). The SDK does not bundle mqtt, axios, aws-iot-device-sdk-v2, or @react-native-community/netinfo as dependencies.
Development Dependencies
For building and testing:
- Build:
rollup,rollup-plugin-typescript2,@rollup/plugin-*,typescript - Tests:
jest,ts-jest,jest-environment-jsdom,jest-junit,dotenv,text-encoding,whatwg-fetch - Lint/Format:
eslint,@typescript-eslint/*,prettier - Docs:
typedoc
Unit tests use mock modules (see __tests__/utils/__mocks__/) for mqtt, axios, aws-iot-device-sdk-v2, and @react-native-community/netinfo—no real packages are required for the test suite.
Installation
Package Manager
To install the latest version of the @espressif/rmng-base-sdk package:
Using npm:
npm install @espressif/rmng-base-sdkUsing Yarn:
yarn add @espressif/rmng-base-sdkUsing pnpm:
pnpm add @espressif/rmng-base-sdkLocal Installation
For development and testing with the local SDK:
Clone the repository and navigate to the SDK directory
Install dependencies:
npm installBuild the package:
npm run buildCreate a tarball for testing locally:
npm packIn your React Native project, install the local SDK:
npm install <PATH_TO_PACK_TARBALL_FILE>Alternatively, use a direct link:
npm install file:../path/to/esp-rmng-app-sdk-ts
Quick Start
1. Configure the SDK
import { ESPRMNGBase } from "@espressif/rmng-base-sdk";
// Initialize the SDK with your ESP RainMaker settings
ESPRMNGBase.init({
baseUrl: "https://your-api-gateway.amazonaws.com",
apiPath: "/prod",
userApiBaseUrl: "https://your-user-api-gateway.amazonaws.com",
userApiPath: "/prod",
identityId: "your-identity-pool-id",
awsRegion: "your-aws-region",
userPoolId: "your-user-pool-id",
clientId: "your-cognito-client-id",
iotEndpoint: "your-iot-endpoint.amazonaws.com",
});2. Authenticate User
const auth = ESPRMNGBase.getAuthInstance();
try {
const user = await auth.login("[email protected]", "password");
console.log("Login successful:", user);
} catch (error) {
console.error("Login failed:", error);
}3. Establish MQTT Connection
try {
// Get temporary AWS credentials
const credentials = await user.getTemporaryAWSCredentials();
// Connect to MQTT
const connected = await user.connectMQTT();
if (connected) {
console.log("MQTT connected successfully");
}
} catch (error) {
console.error("MQTT connection failed:", error);
}Usage Examples
Basic Setup
import { ESPRMNGBase } from "@espressif/rmng-base-sdk";
// Initialize the SDK
const initializeSDK = () => {
ESPRMNGBase.init({
baseUrl: process.env.RAINMAKER_BASE_URL || "https://your-api-gateway.amazonaws.com",
apiPath: process.env.RAINMAKER_API_PATH || "/prod",
userApiBaseUrl:
process.env.RAINMAKER_USER_API_BASE_URL ||
"https://your-user-api-gateway.amazonaws.com",
userApiPath: process.env.RAINMAKER_USER_API_PATH || "/prod",
awsRegion: process.env.AWS_REGION || "your-aws-region",
userPoolId: process.env.COGNITO_USER_POOL_ID,
clientId: process.env.COGNITO_CLIENT_ID,
identityId: process.env.AWS_IDENTITY_ID,
iotEndpoint: process.env.IOT_ENDPOINT,
});
console.log("SDK initialized successfully");
};User Authentication
const handleUserAuth = async () => {
const auth = ESPRMNGBase.getAuthInstance();
try {
// Login with email and password
const user = await auth.login("[email protected]", "securePassword123");
// Get user information
const userInfo = await user.getUserInfo();
console.log("User info:", userInfo);
// Setup MQTT connection for real-time communication
await setupMQTTConnection(user);
} catch (error) {
console.error("Authentication failed:", error);
}
};
const setupMQTTConnection = async (user) => {
try {
// Get AWS credentials through assume role
const credentials = await user.getTemporaryAWSCredentials();
// Connect to MQTT with credentials
const connected = await user.connectMQTT();
if (connected) {
console.log("Real-time communication established");
// Subscribe to parameter updates for a specific node
const nodeId = "your-node-id";
await user.subscribeToNodeParams(nodeId, (params) => {
console.log("Node parameters updated:", params);
});
}
} catch (error) {
console.error("MQTT setup failed:", error);
}
};Device Provisioning
import { ESPDevice } from "@espressif/rmng-base-sdk";
const provisionDevice = async (deviceConfig) => {
const device = new ESPDevice(deviceConfig);
try {
// Connect to device
await device.connect();
// Get device capabilities
const capabilities = await device.getDeviceCapabilities();
console.log("Device capabilities:", capabilities);
// Scan for WiFi networks
const wifiNetworks = await device.scanWifiList();
console.log("Available networks:", wifiNetworks);
// Provision device with WiFi credentials
await device.provision("YourWiFiSSID", "YourWiFiPassword", (progress) => {
console.log("Provisioning progress:", progress);
});
console.log("Device provisioned successfully");
} catch (error) {
console.error("Provisioning failed:", error);
} finally {
await device.disconnect();
}
};MQTT Communication
const handleMQTTCommunication = async (user) => {
try {
// Connect to MQTT
const connected = await user.connectMQTT();
if (connected) {
const nodeId = "your-node-id";
const shadowName = "your-group-id"; // Shadow name is typically the group ID
// Subscribe to device shadow updates
await user.subscribeToShadow(nodeId, shadowName);
// Update device shadow (sends command to device)
await user.updateDeviceShadow(nodeId, shadowName, {
power: true,
brightness: 80,
});
// Alternatively, update node parameters directly
await user.updateNodeParams(nodeId, {
Switch: {
power: true,
},
});
}
} catch (error) {
console.error("MQTT communication error:", error);
}
};Device Control
const controlDevice = async (user, nodeId, groupId) => {
try {
// Get groups and find the node
const groups = await user.getGroups();
const group = groups.find((g) => g.id === groupId);
if (!group) {
throw new Error("Group not found");
}
// Get node from group (preferred method)
const node = await group.getNode(nodeId);
const deviceConfig = node.getConfig();
console.log("Device config:", deviceConfig);
// Set user reference for MQTT operations
node.setUser(user);
// Update device parameters using the node instance
await node.setParams({
power: true,
brightness: 80,
color: { r: 255, g: 0, b: 0 },
});
console.log("Device updated successfully");
} catch (error) {
console.error("Device control error:", error);
}
};Architecture
The ESP RainMaker Next Generation SDK follows a modular architecture:
ESPRMNGBase (Core)
├── ESPRMNGAuth (Authentication)
├── ESPRMNGUser (User Management)
├── ESPDevice (Device Management)
├── ESPRMNGStorage (Data Persistence)
└── Utils (Crypto, JWT, Validation)Core Components
- ESPRMNGBase: Central configuration and initialization
- ESPRMNGAuth: AWS Cognito authentication handling
- ESPRMNGUser: User operations and MQTT communication
- ESPDevice: Device provisioning and local communication
- ESPRMNGStorage: AsyncStorage-based data persistence
Main Classes
ESPRMNGBase: Core SDK configuration and managementESPRMNGAuth: User authentication and session managementESPRMNGUser: User operations and device communicationESPDevice: Device provisioning and control
Key Interfaces
ESPRMNGBaseConfig: SDK configuration interfaceUserTokensData: Authentication token structureESPDeviceInterface: Device configuration interface
API Documentation
Comprehensive API documentation is available for all public classes, interfaces, and methods in the SDK.
Generate Documentation Locally
To generate the API documentation locally:
npm run genDocsThis will create a docs/ directory containing the generated HTML documentation. Open docs/index.html in your browser to view the documentation.
Documentation Features
- Complete API Reference: All public classes, methods, and interfaces are documented
- Type Information: Full TypeScript type definitions with examples
- Method Signatures: Parameter types, return types, and thrown errors
- Search Functionality: Search across all documented APIs
- Class Hierarchy: Visual representation of class relationships
The documentation is generated using TypeDoc from the JSDoc comments in the source code.
Troubleshooting
Common Issues
MQTT Connection Failures
- Ensure proper AWS credentials and IoT endpoint configuration
- Check network connectivity and firewall settings
- Verify assume role permissions
Crypto Polyfill Issues
- Ensure React Native crypto polyfills are properly configured
- Check
index.jsfor proper global crypto setup
Authentication Errors
- Verify Cognito User Pool and Client ID configuration
- Check user credentials and account status
Testing
Run unit tests:
npm testRun integration tests:
npm run test:integrationRun all tests (unit + integration):
npm run test:allRun all tests with coverage:
npm run test:coverageLinting & Formatting
Format code with Prettier:
npm run formatIn CI, run a format check and fail if files are not formatted (no writes):
npm run format:checkOptionally run ESLint (after npm install):
npm run lintContributing
We welcome contributions! Please see our contributing guidelines for more information.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Resources
License
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
