Noodle Printing Machine

    smartenit-angular-sdk
    TypeScript icon, indicating that this package has built-in type declarations

    0.2.158 • Public • Published

    Smartenit Angular SDK

    Smartenit provides a wide range of solutions of the so-called “high-end” control systems focused on electricity and water management, the two main sources of energy used around a home, farm or building. Our broad range of products addresses all different categories of smart home and energy management such as lighting, irrigation, heating/cooling, sensors, hot water management, disaster mitigation, pool control and more. By using a consistent technology application framework, different types of devices can be set up and deployed uniformly and rapidly to address a myriad of opportunities for improvement in our daily life. Our solutions are for everyone, not just the technical expert or the very rich, and include unparalleled connectivity to enable monitoring and control from anywhere.

    Built With

    Getting Started

    These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

    Installation

    To install this library, run:

    $ npm install smartenit-angular-sdk --save --save-exact

    Using Smartenit Module

    Include Smartenit Module on your Angular main module:

    // ...
    import { SmartenitModule } from 'smartenit-angular-sdk';
    
    @NgModule({
      imports: [
        // ...
        SmartenitModule.withConfig({
            apiURL: 'https://api.smartenit.io/v2',
            clientId: '1zj3o5y....', // optional
            clientSecret: 'otTI9.....' // optional
        })
      ]
    })
    export class AppModule { }

    Once your library is imported, you can use its components and services in your application.

    Services

    StorageService

    Service to store information locally, it supports a ttl (time to live) attribute to expire the content after given seconds. If the data is expired will return: null.

    import {StorageService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public storage: StorageService) { }
        
        storeInfo(){
            let item = {key: 'key', value: {device: {state: 'on'}}, ttl: 1};
            this.storage.set(item);
            
            const storedValue = this.storage.get('key');
            
            console.log(storedValue);
            /*
             * Will print:
             * { device: { state : 'on' } }
             */
    
            //Remove an element of the storage
            this.storage.remove(item);
    
            //Clear complete storage
            this.storage.clear();
        }
    
    }

    APIClientService

    This is the base for the requests for many Smartenit APIs. It is composed by the following methods:

    • get
    • remove
    • post
    • put

    get

    Creates a get request based on the provided apiURL, the path, the data and the options. Returns the requested resource.

    import {APIClientService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public apiClient: APIClientService) { }
        
        getResource(){
            apiClient.get('59b6f9b09f5cf67d039b6efe', {}, null).map((apiResponse) => {
                console.log(apiResponse)
                /*
                 * Will print
                 * 
                 * data: MicroAppModel {
                 *      data: 
                 *      accountId:"595ff490ef5a6e3e70acb8b6"
                 *      companyId:"56e1939bd4c6dc1f67624554"
                 *      createdAt:"2017-09-11T21:01:36.139Z"
                 *      ......
                 *      _id:"59b6fa1a9f5cf67d039b6f0f"
                 * }
                 */
            });
        }
    }

    remove

    Creates a delete request based on the provided apiURL, the path, the data and the options. Delete the requested resource.

    import {APIClientService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public apiClient: APIClientService) { }
        
        deleteResource() {
            apiClient.delete('599469398870964e38a288d6', 
            { deleteChildren: "conditions,effects"}, 
            { });
        }
    
    }

    post

    Creates a post request based on the provided apiURL, the path, the data and the options.

    import {APIClientService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public apiClient: APIClientService) { }
        
        postResource(){
            // Create an Area
            apiClient.post(null, 
                {}, 
                {
                    name:"Area Name",59e118ca85c9b74c3eff222f
                    ownerId:"a717a...",
                    parents: {
                        locations: {
                            id:"595ff49c...",
                            name:"Location Name"
                        }
                    }
                }).map((apiResponse) => {
                    console.log(apiResponse.message)
                /*
                 * Will print: 
                 * Resource successfully created
                 */
            });
        }
    }

    put

    Creates a put request based on the provided apiURL, the path, the data and the options.

    import {APIClientService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public apiClient: APIClientService) { }
        
        putResource(){
            // Update an Area
            apiClient.put('59e118ca85c9b74c3eff222f', 
                {
                    name:"New Area Name",
                    ownerId:"a717a...",
                    parents: {
                        locations: {
                            id:"595ff49c...",
                            name:"Location Name"
                        }
                    }
                }, 
                {}).map((apiResponse) => {
                    console.log(apiResponse.message)
                /*
                 * Will print: 
                 * Resource successfully updated
                 */
            });
        }
    }

    CRUDService

    This is the base class for many Smartenit APIs. This class implements the APIClientService. It is composed of the following methods:

    • save
    • list
    • getById
    • removeById

    save

    Creates or updates a resource, the update operation is based on the _id object property.

    save(data: any, options?: IRequestOptions): Observable<any>
    // ...
    this.users.save({
        profile: {
            name: 'test',
            lastName: 'test'
        },
        username: 'test@gmail.com',
        password: 'someP@$$w0rd'
    }).subscribe(userResponse => {
        console.log(userResponse);
    }, userError => {
        console.log(userError);
    })

    list

    Reads a list of resources

    list(query?: any, options?: IRequestOptions): Observable<any>

    The options interface has the following attributes:

    export interface IRequestOptions {
        limit?: number,
        page?: number,
        fields?: string[],
        sort?: string[],
        credentials?: boolean
    }

    credentials will be true by default for all requests, this passes the authentication information to the API call.

    Consider using fields projection to optimize your application speed requesting only the attributes you need.

    // ...
    this.locations.list({}, {
        limit: 10,
        page:2,
        fields:['name','createdAt'],
        sort:['-createdAt', 'name']
    }).subscribe((locationResponse) => {
        console.log(locationResponse);
    }, error => {
        console.log(error);
    })

    getById

    Reads a resource based on its _id

    this.users.getById('547d9e3b7c40af67db433ebb', {
        fields:['name','createdAt']
    }).subscribe((userResponse) => {
        console.log(userResponse);
    }, error => {
        console.log(error);
    })

    removeById

    Removes a resource based on its _id

    this.users.removeById('547d9e3b7c40af67db433ebb');

    PersistentCRUDService

    This is the base class for CRUD requests for many Smartenit APIs. This class implements the CRUDService It is composed of the following methods:

    • save: Saves a resource implementing the CRUDService.save method.
    • list: List a set of resources. Depending the options, this method retrieve the set of resources from the backend or the local storage.
    • listFromLocalStorage: List a set of resources from the local storage.
    • listFromBackend: List a set of resources, implementing the CRUDService.list method.
    • processListData: Process a list of data, e.g. JSON data, Coverts a JSON list into an array Object.
    • getById: Returns a resource filtering by the id. Depending the options, this method retrieve the resource from the backend or the local storage.
    • getByIdFromLocalStorage: Return a resource from the local storage.
    • getByIdFromBackend: Return a resource, implementing the CRUDService.getById method.
    • remove: Removes a resource. If the onffline mode is activated, this method will process the action in offline mode. Implements the CRUDService.remove method. It also removes the resource from the local storage.
    • removeFromLocalStorage: Removes a resource filtering by the id.
    • removeById: Removes a resource filtering by the id.

    AuthService

    This service manages the current user session, and user login. This service has the following methods:

    • login
    • logout
    • clearDB
    • retrieveAccessTokenTime
    • isAccessTokenExpired

    ####login This method verifies if the user has an active session, that means, verifies if the user has an access token.

    import {AuthService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public authService: AuthService) { }
        
        checkIfLoggedIn(){
            if(this.authService.isLoggedIn()){
                const accessToken = this.authService.getAccessToken();
                console.log('You are logged in with token: ' + accessToken);
            }else{
                console.log('You are not logged in');
            }
        }
    }

    ####logout This method clears the current session and disconnects from the WebSocketService.

    import {AuthService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public authService: AuthService) { }
        
        logout(){
            this.authService.logout();
        }
    }

    ####clearDB This method clears the database. It recives, as an optional parameter, the instances that you don't want to delete.

    import {AuthService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public authService: AuthService) { }
        
        clearDataBase(){
            this.authService.clearDB([excludedInstances]);
        }
    }

    Oauth2Service

    This service interacts with OAuth2 Smartenit server

    login

    This method authenticates an user using password grant. In order to use this grant client id and secret must be set.

    import {Oauth2Service} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public oauthResource: Oauth2Service) { }
        
        login(){
            this.oauthResource.login('your@email.com', 'P@$$w0rd')
                .subscribe((response) => {
                    console.log(response)
                }, (error) => {
                    console.log(error)
                });
        }
    }

    logout

    This method clears the current user session.

    import {Oauth2Service} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public oauthResource: Oauth2Service) { }
        
        logout(){
            this.oauthResource.logout();
        }
    }

    authenticateClient

    The following example will authenticate the client (mobile app or web app) and it will create a new user.

    // ...
    this.oauthResource.authenticateClient('18386....', 'DTXsnv3I....')
        .subscribe((response) => {
            console.log(response);
            this.users.save({
                profile: {
                    name: 'test',
                    lastName: 'test'
                },
                username: 'test@gmail.com',
                password: 'someP@$$w0rd'
            }).subscribe(userResponse => {
                console.log(userResponse);
            }, userError => {
                console.log(userError);
            })
        }, (error) => {
            console.log(error);
        });

    MediaService

    This service manages file uploads to other API resources, for example a device or location image.

    uploadBase64

    This method uploads a base64 encoded JPEG image, when completed it returns the path of the image and the current version to handle cache. This method can be use to upload media for the following resources:

    • devices
    • areas
    • scenes
    • users
    • locations
    • microapps

    The following example uploads the main image of the location identified with 247d9e3b7c40af67db435000.

    import {MediaService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public mediaService: MediaService) { }
        
        uploadImage(imageData){
            this.mediaService.uploadBase64(
                imageData, // data:image/png;base64,iVBORw0KGgo... 
                'filename.jpg', 
                'locations',
                '247d9e3b7c40af67db435000'
            ).subscribe((uploadResponse)=>{
                console.log(uploadResponse);
                /*
                 * Will print:
                 * {
                 *      "message":"File uploaded",
                 *      "data":{
                 *          "url":"https://s3.amazonaws.com/smartenit-media-stg/547d9e3b7c40af67db439999/locations/247d9e3b7c40af67db435000/location-image.png",
                 *          "version":2
                 *      }
                 * }
                 */
            },(error) => {
                console.log(error);
            });
        }
    }

    AccountsService

    Interacts with Accounts resource.

    import {AccountsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public users: AccountsService) { }
        
        listAccounts(){
            this.accounts.list({}, {
                limit: 10
            }).subscribe((accountResponse) => {
                console.log(accountResponse);
            },error => {
                 console.log(error);
            });
        }
        
    }

    UsersService

    Interacts with Users resource.

    save

    import {UsersService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public users: UsersService) { }
        
        singUp(){
            this.users.save({
                profile: {
                    name: 'test',
                    lastName: 'test'
                },
                username: 'test@gmail.com',
                password: 'someP@$$w0rd'
            }).subscribe(userResponse => {
                console.log(userResponse);
            }, userError => {
                console.log(userError);
            })
        }
    }

    recoverPassword

    This method starts the process of password recovery, calls the API service to send a recovery email with instructions. This method has to be used client authentication (not user authentication) since user has forgotten the password.

    oauthResource.authenticateClient('1838SDE...', 'DTXsnv3I7....')
        .subscribe(() => {
            this.usersService.recoverPassword('lost@email.com')
                .subscribe((recoverResponse) => {
                    console.log(recoverResponse);
                }, error => {
                    console.log(error);
                });
        }, error => {
            console.log(error);
        });

    LocationsService

    Interacts with Locations resource.

    import {LocationsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public locations: LocationsService) { }
        
        listLocations(){
            this.locations.list({}, {
                limit: 10
            }).subscribe((locationResponse) => {
                console.log(locationResponse);
            },error => {
                 console.log(error);
            });
        }
    }

    CategoriesService

    Interacts with Categories resource.

    import {CategoriesService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public categories: CategoriesService) { }
        
        listCategories(){
            this.categories.list({}, {
                limit: 10,
                fields:['name']
            }).subscribe((categoriesResponse) => {
                console.log(categoriesResponse);
            },error => {
                 console.log(error);
            });
        }
    }

    ControllersService

    Interacts with Controllers resource.

    import {ControllersService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public controllers: ControllersService) { }
        
        listControllers(){
            this.controllers.list({}, {
                limit: 10
            }).subscribe((controllersResponse) => {
                console.log(controllersResponse);
            },error => {
                 console.log(error);
            });
        }
        
    }

    MicroAppsService

    Interacts with Microapps resource.

    import {MicroAppsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public microapps: MicroAppsService) { }
        
        listMicroApps(){
            this.microapps.list({}, {
                limit: 10
            }).subscribe((microappsResponse) => {
                console.log(microappsResponse);
            },error => {
                 console.log(error);
            });
        }
    }

    getDefinition

    Loads the definition of a microapp filtering by the name.

    import {MicroAppsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public microapps: MicroAppsService) { }
        
        this.microapps.getDefinition(name)
            .subscribe(microappDefinition => {
                console.log(microappDefinition);
        });
    }

    PairingsService

    Interacts with Pairings resource.

    import {PairingsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public pairings: PairingsService) { }
        
        listPairings(){
            this.pairings.list({}, {
                limit: 10
            }).subscribe((pairingsResponse) => {
                console.log(pairingsResponse);
            },error => {
                 console.log(error);
            });
        }
    }

    onPairRefresh

    Refresh the list of pairings

    import {PairingsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public pairings: PairingsService) { }
        
        this.pairings.onPairRefresh.subscribe(() => {
          setTimeout(() => {
            this.refreshLoading = false;
          }, 5000);
        });
    }

    DevicesService

    Interacts with Devices resource.

    discover

    Checks for devices in the same local network.

    import {DevicesService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public devices: DevicesService) { }
        
        discoverDevices(){
            const discoverOnlyNewDevices = true;
            
            this.devices.discover(discoverOnlyNewDevices).subscribe((discoveredDevices) => {
                console.log(discoveredDevices);
            },error => {
                 console.log(error);
            });
        }
    }

    link

    Links a discovered device to the authenticated account by providing the deviceId.

    import {DevicesService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public devices: DevicesService) { }
        
        linkTheDevice(deviceId:string){
            this.devices.link(deviceId).subscribe((discoveredDevices) => {
                console.log(discoveredDevices);
            },error => {
                 console.log(error);
            });
        }
    }

    EventsService

    Interacts with Events resource.

    import {EventsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public events: EventsService) { }
        
        getInfoEvents(){
            this.events.list({type:'INFO'}, {
                limit: 10,
                fields:['title']
            }).subscribe((eventsResponse) => {
                console.log(eventsResponse);
            },error => {
                console.log(error);
            });
        }
    }

    ScenesService

    Interacts with Scenes resource.

    import {ScenesService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public scenes: ScenesService) { }
        
        searchScenes(name){
            this.scenes.list({name:name}, {
                limit: 5,
                fields:['name']
            }).subscribe((scenesResponse) => {
                console.log(scenesResponse);
            },error => {
                console.log(error);
            });
        }
    }

    WizardsService

    Interacts with Wizards resource.

    import {WizardsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public wizards: WizardsService) { }
        
        listWizards(){
            this.wizards.list({}, {
                limit: 5
            }).subscribe((wizardsResponse) => {
                console.log(wizardsResponse);
            },error => {
                console.log(error);
            });
        }
    }

    AreasService

    Interacts with Areas resource.

    import {AreasService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public areas: AreasService) { }
        
        listAreas(){
            this.areas.list({}, {
                limit: 5
            }).subscribe((areasResponse) => {
                console.log(areasResponse);
            },error => {
                console.log(error);
            });
        }
    }

    ActionsService

    Interacts with Actions resource.

    import {ActionsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public actions: ActionsService) { }
        
        listActions(){
            this.actions.list({}, {
                limit: 5
            }).subscribe((actionsResponse) => {
                console.log(actionsResponse);
            },error => {
                console.log(error);
            });
        }
    }

    ConditionsService

    Interacts with Conditions resource.

    import {ConditionsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public conditions: ConditionsService) { }
        
        listConditions(){
            this.conditions.list({}, {
                limit: 5
            }).subscribe((conditionsResponse) => {
                console.log(conditionsResponse);
            },error => {
                console.log(error);
            });
        }
    }

    EffectsService

    Interacts with Effects resource.

    import {EffectsService} from 'smartenit-angular-sdk';
    
    export class Page1 {
        constructor(public effects: EffectsService) { }
        
        listEffects(){
            this.effects.list({}, {
                limit: 5
            }).subscribe((effectsResponse) => {
                console.log(effectsResponse);
            },error => {
                console.log(error);
            });
        }
    }

    Models

    Models are instances of the resources returned by the API, this instances have attached functionallities like plugins or event save and remove methods of their owner service.

    addParent

    devicesService.list({name:'Messenger test'}).subscribe((deviceResult)=>{
        let device = deviceResult.data[0];
    
        areasService.list({}).subscribe((areasResponse)=>{
            // The first device is added as child of the first area
            device.addParent(areasResponse.data[0]).subscribe(parentResponse=>{
                console.log(parentResponse);
            });
        });
    });

    removeParent

    devicesService.list({name:'Messenger test'}).subscribe((deviceResult)=>{
        let device = deviceResult.data[0];
    
        areasService.list({}).subscribe((areasResponse)=>{
            // The first device is removed form the first area
            device.removeParent(areasResponse.data[0]).subscribe(parentResponse=>{
                console.log(parentResponse);
            });
        });
    });

    Classes

    DeviceModel

    Provides helper methods to interact with device instances, this object has all device properties from the Smartenit API along with the following methods:

    • getPlugin: Returns the plugin for the given component and processor.
    getPlugin(componentId:string, processorName:string):SmartenitPlugin {...}

    The DevicesService uses this DeviceModel class to create device instances based on user requested information, e.g. when requesting a device list, the DevicesService will create a DeviceModel object for each one of the elements retrieved. All supported plugins will be loaded into the device so the user can control and receive telemetry from the device in real-time.

    import {DeviceModel} from 'smartenit-angular-sdk';
    
    ...
    
    devicesService.list({'components.processors.name': 'OnOff'}, {limit: 5}).subscribe((devicesList) => {
        const firstDevice: DeviceModel = devicesList.data[0];
        
        console.log(firstDevice);
        // Will print a Device object rather that a regular Javascript Object
    })

    A Device has the following properties:

    • online: (Boolean) returns whether the device is online or offline.
    • type: Returns the device type, e.g. ZigBee, WiFi, etc.
    • model: Returns the device model, e.g. ZMLC30, RainBee8, etc.
    • plugins: Returns an object containing the plugins loaded on the device.
    • processors: Returns a list of the processors in all components of the device.

    A Device has the following methods:

    • executeMethod: Executes a command in a device.
    • getAttribute: Sends a read command for a device attribute.
    • setAttribute: Sends a set command for a device attribute.
    • getPlugin: Returns a Plugin loaded on the device.

    AccountModel

    Provides helper methods to interact with account instances.

    An Account has the following properties:

    • name: Returns the name of the account.
    • settings: Returns the settings related to the account.

    ActionModel

    Provides helper methods to interact with action instances.

    An Action has the following properties:

    • name: Returns the name of the action.
    • expr: Returns the expressions of the action, e.g. if, else, then.

    AreaModel

    Provides helper methods to interact with area instances.

    An Area has the following properties:

    • plugins: Returns an object containing the plugins loaded on the area.
    • processors: Returns a list of the processors in all components of the area.

    An Area has the following methods:

    • loadPluginsAndProcessors: Load the plugins and processors, e.g. Energy Management processor.
    • getPlugin: Returns a Plugin loaded on the area.

    CategoryModel

    Provides helper methods to interact with category instances.

    ConditionModel

    Provides helper methods to interact with condition instances.

    A Condition has the following properties:

    • name: Returns the name of the condition.
    • type: Returns the condition type, e.g. Time, Device State, Time interval.
    • description: Returns the description, e.g. Every day at 3:10 PM.
    • plugins: Returns an object containing the plugins loaded on the condition.
    • value: Returns an object containing the representation of the days and the time of the condition.

    ControllerModel

    Provides helper methods to interact with controller instances.

    A Controller has the following properties:

    • description: Returns the description of the controller.
    • processorName: Returns the name of the processor, e.g. OnOffArrayServer, NotificationServer, etc.
    • description: Returns a list of the processors in all components of the device.

    EffectModel

    Provides helper methods to interact with effect instances.

    An Effect has the following properties:

    • processorName: Returns the name of the processor, e.g. OnOffArrayServer, NotificationServer, etc.
    • method: Returns the method to be executed, e.g. SendPushNotification.
    • delay: Returns the delay time of the effect in seconds, e.g. 60 means one minute.
    • description: Returns the description on the effect.
    • params: Returns the data related to the effect, e.g. A Notification will contain the Subject, the Text and the list of recipients.

    EventModel

    Provides helper methods to interact with event instances.

    LocationModel

    Provides helper methods to interact with locations instances.

    A Location has the following properties:

    • settings: Returns the settings of the location like the language, the currency and the temperature unit.
    • plugins: Returns an object containing the plugins loaded on the location.
    • processors: Returns a list of the processors in all components of the location.

    A Location has the following methods:

    • loadPluginsAndProcessors: Load the plugins and processors, e.g. Energy Management processor.
    • getPlugin: Returns a Plugin loaded on the location.

    MicroAppModel

    Provides helper methods to interact with micro app instances.

    A Micro App has the following properties:

    • name: Returns the name of the micro app.
    • type: Returns the type of the micro app, e.g. Doorbell.
    • settings: Returns an object containing the actions that will trigger the micro app, and the slots with the devices linked to the micro app.

    PairingModel

    Provides helper methods to interact with pairing instances.

    ResponderModel

    Provides helper methods to interact with responder instances.

    A Responder has the following properties:

    • processorName: Returns the name of the processor, e.g. OnOffArrayServer, NotificationServer, OnOff, etc.
    • delay: Return the delay time of the responder in seconds, e.g. 60 means one minute.
    • description: Returns the description of the responder.
    • params: Returns the data related to the responder.

    SceneModel

    Provides helper methods to interact with scene instances.

    A Scene has the following properties:

    • enabled: (Boolean) returns the current state of the scene.

    A Scene has the following methods:

    • activate: Executes an activate command in a scene.
    • deactivate: Executes an deactivate command in a scene.

    UserModel

    Provides helper methods to interact with user instances.

    WizardModel

    Provides helper methods to interact with wizard instances.

    SmartenitPlugin

    This class encapsulates device functionality, this abstract class is the base for all other plugins.

    Smartenit Plugins

    OnOffPlugin

    This class encapsulates a single Switch (On/Off) component in a device. It has the following methods:

    • on: Turns on the device component.
    • off: Turns off the device component.
    • toggle: Toggles the current device component state.
    • isOn: Returns true when a device component is on false otherwise.
    • isOff: Returns true when a device component is off false otherwise.
    import {OnOffPlugin} from 'smartenit-angular-sdk';
    
    ...
    
    devicesService.list({'components.processors.name': 'OnOff'}, {limit: 5}).subscribe((devicesList) => {
        const firstDevice: Device = devicesList.data[0];
    
        const switchOnePlugin = firstDevice.getPlugin('1', 'OnOff') as OnOffPlugin;
    
        switchOnePlugin.onData.subscribe((deviceData) => {
            console.log('Is On from plugin state', plugin.isOn());
            console.log('Is On from event', deviceData.state);
        });
    
        // Toggle device component 1 asynchronously
        switchOnePlugin.toggle();
    
        // Toggle device component 1 asynchronously and subscribe to response
        switchOnePlugin.toggle(true).subscribe((toggleResponse) => {
            console.log(toggleResponse);
        });
    });

    SimpleMeteringServer

    This class encapsulates a metering device component in a device. It has the following methods:

    • getFirstUnit: Returns the first unit of measurement e.g Kw.
    • getSecondUnit: Returns the first unit of measurement e.g Kwh.
    • getCurrentSummation: Returns the current summation of the device.
    • getInstantaneousDemand: Returns the instantaneous demand.
    import {SimpleMeteringServerPlugin} from 'smartenit-angular-sdk';
    
    ...
    
    devicesService.list({'components.processors.name': 'SimpleMeteringServer'}, {limit: 5}).subscribe((devicesList) => {
        const firstDevice: Device = devicesList.data[0];
    
        const meteringOnePlugin = firstDevice.getPlugin('1', 'SimpleMeteringServer') as SimpleMeteringServerPlugin;
    
        meteringOnePlugin.onData.subscribe((deviceData) => {
            console.log('Current Summation', meteringOnePlugin.getCurrentSummation());
            console.log('Instantaneous Demand', meteringOnePlugin.getInstantaneousDemand());
            console.log('First Unit', meteringOnePlugin.getFirstUnit());
        });
    
        firstDevice.getStatus('1', 'SimpleMeteringServer');
    });

    LevelControlServerPlugin

    This class encapsulates a component that has a level control (Dimmer). It has the following methods:

    • getLevel: Returns the current level of the device component.
    • setLevel: Sets the current level of the device component.
    import {LevelControlServerPlugin} from 'smartenit-angular-sdk';
    
    ...
    
    devicesService.list({'components.processors.name': 'LevelControlServer'}, {limit: 5}).subscribe((devicesList) => {
        const firstDevice: Device = devicesList.data[0];
    
        const levelOnePlugin = firstDevice.getPlugin('1', 'LevelControlServer') as LevelControlServerPlugin;
    
        levelOnePlugin.onData.subscribe((deviceData) => {
            console.log('Level', levelOnePlugin.getLevel());
        });
    
        levelOnePlugin.setLevel(50);
    });

    DiscoverPlugin

    This class encapsulates a component that can discover other devices on the same network, for example a gateway/hub that can discover Zigbee devices. The discovery process progress is persisted on the local cache.

    import {DiscoverPlugin} from 'smartenit-angular-sdk';
    
    ...
    
    devicesService.list({'components.processors.name': 'Discover'}, {limit: 5}).subscribe((devicesList) => {
      const firstDevice: Device = devicesList.data[0];
      
      if (firstDevice) {
        let plugin = firstDevice.getPlugin('1', 'Discover') as DiscoverPlugin;
    
        plugin.onUpdate.subscribe((progress) => {
          console.log('Discover Progress', progress);
        });
    
        plugin.startDiscovery();
    
        // plugin.stopDiscovery();
      }
    });

    BasicServerPlugin

    This class provides an interface to basic device information.

    import {DiscoverPlugin} from 'smartenit-angular-sdk';
    
    ...
    
    devicesService.list({'components.processors.name': 'BasicServer'}, {limit: 5}).subscribe((devicesList) => {
        const firstDevice: Device = devicesList.data[0];
    
        if (firstDevice) {
          let plugin = firstDevice.getPlugin('1', 'BasicServer') as BasicServerPlugin;
    
          plugin.onData.subscribe((data) => {
            console.log('hardwareVersion', plugin.hardwareVersion);
            console.log('softwareVersion', plugin.softwareVersion);
          });
    
          plugin.getHardwareVersion();
          plugin.getSoftwareVersion();
        }
      });

    License

    MIT © Smartenit

    Install

    npm i smartenit-angular-sdk

    DownloadsWeekly Downloads

    28

    Version

    0.2.158

    License

    MIT

    Unpacked Size

    16.7 MB

    Total Files

    168

    Last publish

    Collaborators

    • daniel.j
    • ksegarra
    • jesmartenit
    • anfho