Make sure your machine has Node.JS (version 6.x or greater) and do:
npm install ale-iot-hub
Added compatibility with multi-tenants API of the Data-Hub (api-v2).
Added the tenantService to manage the tenants.
For api usage see folder 'samples'. Sample with sdk using websocket protocol.
const IOTHUB = require('ale-iot-hub');
const client = new IOTHUB.IOTHUBClientWS('ws:/localhost:9000/api/ws');
// Usage for Multi-tenants APIs:
//const client = new IOTHUB.IOTHUBClientWS('ws://localhost:9000/api-v2/tenants/tenantA/ws';
const schemaService = client.SchemaService;
const deviceService = client.DeviceService;
const gatewayService = client.GatewayService;
const subscriptionService = client.SubscriptionService;
const tenantService = client.TenantService;
client.Events.on('open', () => {
console.log('open');
test() ;
});
client.Events.on('error', () => {
console.log('error');
});
client.Events.on('close', (code, reason) => {
console.log('close');
});
client.Events.on('message', (data) => {
let jdata = JSON.parse(data);
if (jdata.message == 'event') {
switch (jdata.resource) {
case "gateways":
switch (jdata.event) {
case 'stop':
console.log("STOP Gateway");
process.exit(0);
break;
case 'created':
case 'updated':
case 'deleted':
break;
}
case "devices":
switch (jdata.event) {
case 'created':
case 'updated':
case 'deleted':
break ;
case 'updated_section':
switch (jdata.section) {
case 'actions' :
// actions
break ;
case 'state' :
//state
break ;
break;
}
break;
}
}
});
client.connect() ;
function test() {
gatewayService.getGateway("mqtt.1").then(data => {
console.log(data);
}, (err) => {
console.log(err);
});
deviceService.getDevice("sga$100$lights$reading_left").then(data => {
console.log(data);
}, (err) => {
console.log(err);
});
deviceService.updateDeviceSection('sga$100$lights$reading_left', 'actions', {
data : { light_on: true }
}).then((response) => {
console.log("updateDeviceSection response="+ JSON.stringify(response)) ;
}) ;
};
Sample with sdk using HTTP protocol.
const IOTHUB = require('ale-iot-hub');
const client = new IOTHUB.IOTHUBClientHTTP('http:/localhost:9000/api');
const schemaService = client.SchemaService;
const deviceService = client.DeviceService;
const gatewayService = client.GatewayService;
const subscriptionService = client.SubscriptionService;
gatewayService.getGateway("mqtt.1").then(data => {
console.log(data);
}, (err) => {
console.log(err);
});
deviceService.getDevice("sga$100$lights$reading_left").then(data => {
console.log(data);
}, (err) => {
console.log(err);
});
deviceService.updateDeviceSection('sga$100$lights$reading_left', 'actions', {
data : { light_on: true }
}).then((response) => {
console.log("updateDeviceSection response="+ JSON.stringify(response)) ;
}) ;
import * as events from 'events'
type ClientOptions = {
log_enable?: boolean; // enable log
http_proxy?: string; // optional http proxy url http://proxyhost:proxyport
auth?: { // optional Basic authentication
username: string;
password: string;
},
ping_timeout?: number; // in ms. default no ping
request_timeout?: number; // in ms. default 30000 ms
reconnect_interval?: number; // in ms, default 30000
headers?: [{ [key: string]: string }]; // optional http headers {header_name, header_value}
}
interface Sections {
[key: string]: any
}
type Schema = {
id: string;
description?: string;
sections: Sections;
}
type Device = {
id?: string;
type: string;
name: string;
description?: string;
enable?: boolean;
sections: Sections;
}
type ResultCount = {
count : number;
}
type SectionDeviceData = {
data: { [key: string]: any } //
}
type Gateway = {
id: string;
name: string;
description?: string;
[key: string]: any;
}
type UpdateGateway = {
name: string;
description?: string;
[key: string]: any;
}
type WebHook = {
url: string;
credential? : {
username : string;
password : string;
}
headers?: [{ [key: string]: string }]; // optional http headers {header_name, header_value}
}
type DeviceTopic = {
id: string;
selectors?: [{ [key: string]: any }] ; // (key slash separator)ex : [{"sections/config/p1/content": "val"}]
filters?: [
{ section: string }
];
extras?: string[]; // list of additional data (dot separator). ex : section.config.p1.content
tags?: string[] ;
}
type GatewayTopic = string;
type Subscription = {
id?: string;
ttl: number; //Time To Live in seconds
device_created: boolean;
device_topics: DeviceTopic[];
gateway_topics: GatewayTopic[];
name?:string ;
webhooks? : WebHook[] ;
expire_time?: number;
}
type SuccessResponse = {
id: string;
status?: string; // OK
message?: string;
}
type ErrorResponse = {
status: string; // NOK
error: string
id?: string;
message?: string;
}
type IOTHUBEvent = {
/**
* date
*/
date? :string;
/**
* "event" -> event from HUB
* "response_success" -> response success to request
* "response_error", response error to request
*/
message: string;
/**
* "gateways" or "devices"
*/
resource: string;
/**
* resource Identifier
*/
id?: string;
/**
* For "gateways" resource -> "created", "deleted", "updated", "stop"
* For "devices" resource -> "created", "deleted", "updated", "updated_section"
*/
event?: string;
/**
* section name for resource "devices" and event "updated_section"
*/
section?: string;
/**
* data
*/
body?: {[key: string]: any};
/**
* context for event
*/
context?: {[key: string]: any};
/**
* extras data dor event
*/
extras?: {[key: string]: any};
/**
* subscription id for event
*/
subscription_id? : string;
/**
* request id for response
*/
request_id? : string ;
/**
* method name for response
*/
method? : string ;
}
interface IOTHUBEventListener {
on(event: 'open', listener: () => void): this
on(event: 'close', listener: (e: any) => void): this
on(event: 'error', listener: (code: string, reason: string) => void): this
on(event: 'message', listener: (data: string) => void): this
on(event: string, listener: Function): this
}
declare module 'ale-iot-hub' {
/*
export class IOTHUBClient {
readonly Url: string;
readonly Connected : boolean ;
/ **
* see IOTHUBEventListener
* /
readonly Events: events.EventEmitter;
readonly SchemaService: SchemaService;
readonly DeviceService: DeviceService;
readonly GatewayService: GatewayService;
readonly SubscriptionService: SubscriptionService;
constructor(Url: string, options?: ClientOptions);
connect(): void;
disconnect(): void;
sendMessage(resource: string, id: string, method: string, params: any, data: any): void;
sendMessageWithResponse(resource: string, id: string, method: string, params: any, data: any): Promise<any>;
}
*/
export class IOTHUBClientWS {
readonly Url: string;
readonly Connected: boolean;
/**
* see IOTHUBEventListener
*/
readonly Events: events.EventEmitter;
readonly SchemaService: SchemaService;
readonly DeviceService: DeviceService;
readonly GatewayService: GatewayService;
readonly SubscriptionService: SubscriptionService;
constructor(Url: string, options?: ClientOptions);
connect(): Promise<boolean>;
disconnect(): void;
sendMessage(resource: string, id: string, method: string, params: any, data: any): void;
sendMessageWithResponse(resource: string, id: string, method: string, params: any, data: any): Promise<any>;
}
export class IOTHUBClientHTTP {
readonly Url: string;
readonly SchemaService: SchemaService;
readonly DeviceService: DeviceService;
readonly GatewayService: GatewayService;
readonly SubscriptionService: SubscriptionService;
constructor(Url: string, options?: ClientOptions);
}
export interface SchemaService {
/**
* Retrieve Schemas
* @throws ErrorResponse
* @param offset default 0
* @param limit
* @param format "id", "short", "full". default "full".
* @param params optional ex { 'sort-field' : 'description',
* 'sort-asc' : true }
* @returns Schema
*/
getSchemas(offset?: number, limit?: number, format?: string, params?:{[key:string]:any}): Promise<Schema[]>;
/**
* Retrieve Schemas Count
* @throws ErrorResponse
* @returns ResultCount
* @since IOT-HUB 1.0.25
*/
getSchemasCount(): Promise<ResultCount>;
/**
* Create Schema
* @throws ErrorResponse
* @param data schema to create.
* @returns Success response
*/
createSchema(data: Schema): Promise<SuccessResponse>;
/**
* Update Schema
* @throws ErrorResponse
* @param schemaId schema identifier to update.
* @param data schema to create.
* @returns Success response
*/
updateSchema(schemaId: string, data: Schema): Promise<SuccessResponse>;
/**
* Get Schema
* @throws ErrorResponse
* @param schemaId schema identifier to retreive.
* @returns Success response
*/
getSchema(schemaId: string): Promise<Schema>;
/**
* Delete Schema
* @throws ErrorResponse
* @param schemaId schema identifier to delete.
* @returns Success response
*/
deleteSchema(schemaId: string): Promise<SuccessResponse>;
}
export interface DeviceService {
/**
* Retrieve Devices
* @throws ErrorResponse
* @param offset default 0.
* @param limit default 200.
* @param format "id", "short", "full". default "full".
* @param params ex { ['filter.sections.config.room.content'] : '100' } .
* { 'view-config' : true }
* { 'sort-field' : 'sections.config.room.content }
* { 'sort-asc' : true }
* @returns Device
*/
getDevices(offset?: number, limit?: number, format?: string, params?:{[key:string]:any}): Promise<Device[]>;
/**
* Retrieve Devices Count
* @throws ErrorResponse
* @param filters ex { ['filter.sections.config.room.content'] : '100' } .
* @returns ResultCount
* @since IOT-HUB 1.0.25
*/
getDevicesCount(filters?:{[key:string]:any}): Promise<ResultCount>;
/**
* Create Device
* @throws ErrorResponse
* @param data device data
* @param params ex : { ['context.mykey'] : 'myvalue' } , context keys values, sent to notification events
* @returns Device
*/
createDevice(data: Device, params?:{[key:string]:any}): Promise<Device>;
/**
* update Device
* @throws ErrorResponse
* @param deviceId device id
* @param data device data
* @param params ex : { ['context.mykey'] : 'myvalue' } , context keys values, sent to notification events
* @returns Success
*/
updateDevice(deviceId: string, data: Device, params?: {[key:string]:any}): Promise<SuccessResponse>;
/**
* get Device
* @throws ErrorResponse
* @param deviceId device id
* @param params ex : { 'view-config' : true } , return data without update_date
* @returns Device
*/
getDevice(deviceId: string, params?: {[key:string]:any}): Promise<Device>;
/**
* get Device Section
* @throws ErrorResponse
* @param deviceId device id
* @param section section name
* @param params ex : { 'view-config' : true } , return data without update_date
* @returns Section data.
*/
getDeviceSection(deviceId: string, section: string, params?: {[key:string]:any}): Promise<{[key:string]:any}>;
/**
* Update Device section
* @throws ErrorResponse
* @param data device data
* @param section section name
* @param params ex : { ['context.mykey'] : 'myvalue' } , context keys values, sent to notification events
* @returns Success
*/
updateDeviceSection(deviceId: string, section: string, data: SectionDeviceData, params?: {[key:string]:any}): Promise<SuccessResponse>;
/**
* Delete Device
* @throws ErrorResponse
* @param deviceId device id
* @param params ex : { ['context.mykey'] : 'myvalue' } , context keys values, sent to notification events
* @returns Success
*/
deleteDevice(deviceId: string, params?: {[key:string]:any}): Promise<SuccessResponse>;
/**
* Create Devices
* @param data devices data
* @param params ex : { ['context.mykey'] : 'myvalue' } , context keys values, sent to notification events
* { notify : true } , true -> send update message, default true.
* @returns Response
* @since IOT-HUB 1.0.27
*/
createDevices(data: Device[], params?:{[key:string]:any}): Promise<(SuccessResponse | ErrorResponse)[]>;
/**
* update Devices
* @param data device data
* @param params ex : { ['context.mykey'] : 'myvalue' } , context keys values, sent to notification events
* { notify : true } , true -> send update message, default true.
* { upsert : true } , true -> create device if not exist, default false.
* @returns Response
* @since IOT-HUB 1.0.27
*/
updateDevices(data: Device[], params?: {[key:string]:any}): Promise<(SuccessResponse | ErrorResponse)[]>;
/**
* delete Devices
* @param data deviceIds
* @param params ex : { ['context.mykey'] : 'myvalue' } , context keys values, sent to notification events
* { notify : true } , true -> send update message, default true.
* @returns Response
* @since IOT-HUB 1.0.27
*/
deleteDevices(data: String[], params?: {[key:string]:any}): Promise<(SuccessResponse | ErrorResponse)[]>;
}
export interface GatewayService {
/**
* Retrieve Gateways
* @throws ErrorResponse
* @param offset default 0
* @param limit default 200
* @param format "id", "short", "full". default "full".
* @param params optional ex { 'sort-field' : 'name',
* 'sort-asc' : true }
* @returns Gateway
*/
getGateways(offset?: number, limit?: number, format?: string, params?:{[key:string]:any}): Promise<Gateway[]>;
/**
* Retrieve Gateways Count
* @throws ErrorResponse
* @returns ResultCount
* @since IOT-HUB 1.0.25
*/
getGatewaysCount(): Promise<ResultCount>;
/**
* Create Gateway
* @throws ErrorResponse
* @param data Gateway data
* @returns Success
*/
createGateway(data: Gateway): Promise<SuccessResponse>;
/**
* Upodate Gateway
* @throws ErrorResponse
* @param gatewayId gateway identifier.
* @param data gateway data.
* @returns Success
*/
updateGateway(gatewayId: string, data: UpdateGateway): Promise<SuccessResponse>;
/**
* Get Gateway
* @throws ErrorResponse
* @param gatewayId gateway identifier.
* @returns Gateway
*/
getGateway(gatewayId: string): Promise<Gateway>;
/**
* Delete Gateway
* @throws ErrorResponse
* @param gatewayId gateway identifier.
* @returns Success
*/
deleteGateway(gatewayId: string): Promise<SuccessResponse>;
/**
* Send Gateway controller state
* @throws ErrorResponse
* @param gatewayId gateway identifier.
* @param controllerUrl controller url.
* @param stateData to send.
*/
sendGatewayControllerStateToHub(gatewayId: string, controllerUrl: string, stateData: any): any;
}
export interface SubscriptionService {
/**
* Retrieve Subscriptions
* @throws ErrorResponse
* @param offset default 0
* @param limit default 200
* @param format "id", "short", "full". default "full".
* @param params optional ex { 'sort-field' : 'name',
* 'sort-asc' : true }
* @returns Subscription
*/
getSubscriptions(offset?: number, limit?: number, format?: string, params?:{[key:string]:any}): Promise<Subscription[]>;
/**
* Retrieve Subscriptions Count
* @throws ErrorResponse
* @returns ResultCount
* @since IOT-HUB 1.0.25
*/
getSubscriptionsCount(): Promise<ResultCount>;
/**
* Create Subscription
* @throws ErrorResponse
* @param subscription Subscription data
* @param subscriptionId Optional subscriptionId, if exists update it otherwise create it .
* @returns Success
*/
createSubscription(subscription: Subscription, subscriptionId?: string): Promise<SuccessResponse>;
/**
* Update Subscription
* @throws ErrorResponse
* @param subscriptionId subscriptionId
* @param subscription Subscription data
* @returns Success
*/
updateSubscription(subscriptionId: string, subscription: Subscription): Promise<SuccessResponse>;
/**
* refresh Subscription
* @throws ErrorResponse
* @param subscriptionId subscriptionId
* @param ttl optional Time To Live, in seconds
* @returns Success
*/
refreshSubscription(subscriptionId: string, ttl?: number): Promise<SuccessResponse>;
/**
* Retrieve Subscriptions
* @throws ErrorResponse
* @param subscriptionId subscriptionId
* @returns Subscription
*/
getSubscription(subscriptionId: string): Promise<Subscription>;
/**
* Retrieve Subscriptions
* @throws ErrorResponse
* @param subscriptionId subscriptionId
* @returns Success
*/
deleteSubscription(subscriptionId: string): Promise<SuccessResponse>;
}
}