iosense-sdk
v1.0.0
Published
Official TypeScript SDK for IOSense platform APIs, providing seamless access to device management, user operations, authentication, and multi-protocol pub/sub messaging systems.
Downloads
2
Maintainers
Readme
IOSense SDK
The official TypeScript SDK for IOSense platform APIs, providing seamless access to device management, user operations, authentication, and multi-protocol pub/sub messaging systems.
✨ Features
- 🔐 Authentication & User Management - Complete login flow with token management
- 📱 Device Operations - Full CRUD operations for IoT devices with real-time data access
- 📊 Data Analytics - Time-series data retrieval, aggregation, and insights management
- 🔄 Multi-Protocol PubSub - Support for Kafka, MQTT, RabbitMQ, Redis, PostgreSQL, MongoDB
- 📝 Full Type Safety - 40+ TypeScript interfaces for robust development
- ⚡ Modern ESM - ES modules with Node.js 18+ support
- 🔄 Built-in Retry Logic - Automatic retry mechanisms for resilient operations
- 📄 Pagination Support - Efficient handling of large datasets
🚀 Quick Start
Installation
npm install iosense-sdkBasic Usage
import { login, DeviceAccess, UserAccess } from 'iosense-sdk';
// 1. Authenticate
const loginResponse = await login({
username: '[email protected]',
password: 'password',
dataUrl: 'your-backend.io',
organisation: 'https://your-org.io',
origin: 'https://your-org.io'
});
// 2. Initialize connectors
const deviceAccess = new DeviceAccess(
'your-backend.io',
loginResponse.authorization,
false
);
// 3. Fetch devices
const devices = await deviceAccess.getAllDevicesPaginated({
pagination: { page: 1, count: 50 }
});
console.log(`Found ${devices.data.totalCount} devices`);📚 API Reference
🔐 Authentication
import { login } from 'iosense-sdk';
const response = await login({
username: '[email protected]',
password: 'secure-password',
dataUrl: 'api.yourplatform.io',
organisation: 'https://yourorg.io',
origin: 'https://yourapp.io'
});
// Access tokens
const { authorization, refresh_token, ifToken } = response;📱 Device Management
import { DeviceAccess } from 'iosense-sdk';
const deviceAccess = new DeviceAccess(dataUrl, accessToken, false);
// Get all devices with pagination
const devices = await deviceAccess.getAllDevicesPaginated({
pagination: { page: 1, count: 20 },
extraHeaders: { origin: 'https://yourapp.io' }
});
// Get specific device data
const deviceData = await deviceAccess.getDeviceData('device-id', {
extraHeaders: { origin: 'https://yourapp.io' }
});
// Get time-series data
const timeSeriesData = await deviceAccess.getDeviceDataByTimeRange({
deviceId: 'device-id',
startTime: new Date('2024-01-01'),
endTime: new Date('2024-01-31'),
timezone: 'UTC'
});
// Entity management
const entities = await deviceAccess.loadEntitiesGen();
const entity = await deviceAccess.loadEntitiesGenById('entity-id');👤 User Operations
import { UserAccess } from 'iosense-sdk';
const userAccess = new UserAccess(dataUrl, accessToken, false);
// Get user profile
const userDetails = await userAccess.getUserDetails({
extraHeaders: {
origin: 'https://yourapp.io',
organisation: 'https://yourorg.io'
}
});
// Check user quota
const quota = await userAccess.getUserQuota({
extraHeaders: { origin: 'https://yourapp.io' }
});
// Get user entities
const userEntities = await userAccess.getUserEntities({
extraHeaders: { origin: 'https://yourapp.io' }
});💡 Insights Management
import { BruceHandler } from 'iosense-sdk';
const bruceHandler = new BruceHandler(dataUrl, accessToken, false);
// Fetch user insights
const insights = await bruceHandler.fetchUserInsights({
pagination: { page: 1, count: 10 },
populate: ['sourceInsightID'],
extraHeaders: { origin: 'https://yourapp.io' }
});
// Add new insight
const newInsight = await bruceHandler.addUserInsight({
insightName: 'Energy Efficiency Report',
source: 'analytics',
userTags: ['energy', 'efficiency']
});🔄 PubSub Connectors
MQTT (IoT Device Communication)
import { MqttConnector } from 'iosense-sdk';
const mqtt = new MqttConnector({
brokerUrl: 'mqtt://your-broker.io',
port: 1883,
username: 'mqtt-user',
password: 'mqtt-pass'
});
await mqtt.connect();
// Subscribe to device data
await mqtt.subscribeToDeviceData('device-123', (deviceData) => {
console.log('Received data:', deviceData);
});
// Publish device data
await mqtt.publishDeviceData('device-123', {
deviceId: 'device-123',
timestamp: Date.now(),
data: [
{ tag: 'temperature', value: 23.5 },
{ tag: 'humidity', value: 65.2 }
]
});Redis (Caching & Fast Storage)
import { RedisCRUD } from 'iosense-sdk';
const redis = new RedisCRUD({
uri: 'redis://localhost:6379'
});
await redis.connect();
// Cache device data
await redis.set('devices:latest', devices, 300); // 5 minutes TTL
// Retrieve cached data
const cachedDevices = await redis.get<Device[]>('devices:latest');
// Update cache
await redis.update('device:123', { lastSeen: new Date().toISOString() });Kafka (Event Streaming)
import { KafkaHandler } from 'iosense-sdk';
const kafka = new KafkaHandler({
clientId: 'iot-app',
brokers: ['kafka1:9092', 'kafka2:9092'],
groupId: 'device-processors'
});
// Produce events
await kafka.produce('device-events', [{
key: 'device-123',
value: JSON.stringify({
deviceId: 'device-123',
event: 'status_change',
data: { status: 'online' }
})
}]);
// Consume events
await kafka.consume('device-events', async (message) => {
const event = JSON.parse(message.value.toString());
console.log('Processing event:', event);
});PostgreSQL (Persistent Storage)
import { PostgresCRUD } from 'iosense-sdk';
const postgres = new PostgresCRUD({
host: 'localhost',
database: 'iot_platform',
user: 'postgres',
password: 'password',
port: 5432
});
await postgres.connect();
// Store device readings
await postgres.create('device_readings', {
device_id: 'device-123',
temperature: 23.5,
humidity: 65.2,
timestamp: new Date()
});
// Query historical data
const readings = await postgres.read('device_readings',
'device_id = $1 AND timestamp > $2',
['device-123', new Date('2024-01-01')]
);🏗️ Integration Patterns
Complete IoT Data Pipeline
import {
login,
DeviceAccess,
MqttConnector,
RedisCRUD,
PostgresCRUD,
KafkaHandler
} from 'iosense-sdk';
class IoTPipeline {
private deviceAccess: DeviceAccess;
private mqtt: MqttConnector;
private redis: RedisCRUD;
private postgres: PostgresCRUD;
private kafka: KafkaHandler;
async initialize() {
// Authentication
const auth = await login({ /* credentials */ });
// Initialize all connectors
this.deviceAccess = new DeviceAccess(dataUrl, auth.authorization, false);
this.mqtt = new MqttConnector({ brokerUrl: 'mqtt://broker.io' });
this.redis = new RedisCRUD({ uri: 'redis://localhost:6379' });
this.postgres = new PostgresCRUD({ host: 'localhost', database: 'iot' });
this.kafka = new KafkaHandler({ clientId: 'iot-pipeline' });
await Promise.all([
this.mqtt.connect(),
this.redis.connect(),
this.postgres.connect()
]);
}
async startPipeline() {
// Real-time data processing
await this.mqtt.subscribeToDeviceData('+', async (deviceData) => {
// Cache latest reading
await this.redis.set(`latest:${deviceData.deviceId}`, deviceData, 300);
// Store in PostgreSQL
await this.postgres.create('readings', {
device_id: deviceData.deviceId,
data: deviceData.data,
timestamp: new Date(deviceData.timestamp)
});
// Stream to analytics
await this.kafka.produce('device-analytics', [{
key: deviceData.deviceId,
value: JSON.stringify(deviceData)
}]);
});
}
}🔧 Configuration
Environment Variables
# Database connections
POSTGRES_HOST=localhost
POSTGRES_DB=iot_platform
POSTGRES_USER=postgres
POSTGRES_PASS=password
REDIS_URL=redis://localhost:6379
MONGO_URL=mongodb://localhost:27017
# Message brokers
KAFKA_BROKERS=localhost:9092
RABBITMQ_URL=amqp://localhost:5672
MQTT_BROKER=mqtt://localhost:1883
# API Configuration
IOT_API_URL=https://api.yourplatform.io
IOT_ORG_URL=https://yourorg.io📋 Requirements
- Node.js 18+
- TypeScript 4.5+
- Modern ESM Support
🔍 Error Handling
The library includes comprehensive error handling with automatic retries:
try {
const devices = await deviceAccess.getAllDevices();
} catch (error) {
if (error.code === 'RATE_LIMIT') {
// Automatic retry with exponential backoff
console.log('Rate limited, retrying...');
} else if (error.code === 'AUTH_FAILED') {
// Re-authenticate
console.log('Token expired, re-authenticating...');
}
}🧪 Testing
# Run all tests
npm test
# Run specific test suites
npm run test:devices
npm run test:users
npm run test:pubsub📄 License
MIT License - see LICENSE file for details.
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📞 Support
- Documentation: Full API Documentation
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Built with ❤️ for the IoT community
