bflorian / smartapp-sdk-nodejs

Javascript/NodeJS SDK to create SmartThings SmartApps

Home Page:https://smartthings.developer.samsung.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SmartThings SmartApp NodeJS SDK (preview)

Language grade: JavaScript Total alerts Known Vulnerabilities

Reference Documentation

SDK that wraps the SmartThings REST API and reduces the amount of code necessary to write a SmartApp app. It supports both webhook and AWS Lambda implementations. This is a preview version of the API and will change over time time.

Installation

npm i @smartthings/smartapp --save

Importing

NodeJS:

const smartapp = require('@smartthings/smartapp')

Or, if you're transpiling to ES6/ES2015+:

import smartapp from '@smartthings/smartapp'

Highlights

  • Javascript API hides details of REST calls and authentication.
  • Event handler framework dispatches lifecycle events to named event handlers.
  • Configuration page API simplifies page definition.
  • Integrated i18n framework provides configuration page localization.
  • Winston framework manges log messages.

Roadmap

Roadmap

Example

The following example is the equivalent of the original SmartThings Groovy Let There Be Light app that turns on and off a light when a door opens and closes.

Running it as a web service

To run the app with an HTTP server, like Express.js:

const express    = require('express');
const smartapp   = require('@smartthings/smartapp');
const server     = module.exports = express();
const PORT       = 8080;

server.use(express.json());

/* Define the SmartApp */
smartapp
    // @smartthings_rsa.pub is your on-disk public key
    // If you do not have it yet, omit publicKey()
    .publicKey('@smartthings_rsa.pub') // optional until app verified
    .app.enableEventLogging(2) // logs all lifecycle event requests and responses as pretty-printed JSON. Omit in production
    .configureI18n()
    .page('mainPage', (context, page, configData) => {
        page.section('sensors', section => {
           section.deviceSetting('contactSensor').capabilities(['contactSensor']).required(false);
        });
        page.section('lights', section => {
            section.deviceSetting('lights').capabilities(['switch']).multiple(true).permissions('rx');
        });
    })
    .updated(async (context, updateData) => {
    	// Called for both INSTALLED and UPDATED lifecycle events if there is no separate installed() handler
        await context.api.subscriptions.unsubscribeAll()
        return context.api.subscriptions.subscribeToDevices(context.config.contactSensor, 'contactSensor', 'contact', 'myDeviceEventHandler');
    })
    .subscribedEventHandler('myDeviceEventHandler', (context, event) => {
        const value = event.value === 'open' ? 'on' : 'off';
        context.api.devices.sendCommands(context.config.lights, 'switch', value);
    });

/* Handle POST requests */
server.post('/', function(req, res, next) {
  smartapp.handleHttpCallback(req, res);
});

/* Start listening at your defined PORT */
server.listen(PORT, () => console.log(`Server is up and running on port ${PORT}`));

Running as an AWS Lambda function

To run as a Lambda function instead of an HTTP server, ensure that your main entry file exports smartapp.handleLambdaCallback(...).

Note: This snippet is heavily truncated for brevity – see the web service example above a more detailed example of how to define a smartapp.

const smartapp = require('@smartthings/smartapp')
smartapp
    .app.enableEventLogging() // logs all lifecycle event requests and responses. Omit in production
    .page( ... )
    .updated(() => { ... })
    .subscribedEventHandler( ... );

exports.handle = (event, context, callback) => {
    smartapp.handleLambdaCallback(event, context, callback);
};

Localization

Configuration page strings are specified in a separate locales/en.json file, which can be automatically created the first time you run the app. Here's a completed English localization file for the previous example:

{
  "pages.mainPage.name": "Let There Be Light",
  "pages.mainPage.sections.sensors.name": "When this door or window opens or closes",
  "pages.mainPage.settings.contactSensor.name": "Select open/close sensor",
  "pages.mainPage.sections.lights.name": "Turn on and off these lights and switches",
  "pages.mainPage.settings.lights.name": "Select lights and switches",
  "Tap to set": "Tap to set"
}

More about SmartThings

If you are not familiar with SmartThings, we have extensive on-line documentation.

To create and manage your services and devices on SmartThings, create an account in the developer workspace.

The SmartThings Community is a good place share and ask questions.

There is also a SmartThings reddit community where you can read and share information.

License and Copyright

Licensed under the Apache License, Version 2.0

Copyright 2019 SmartThings, Inc.

About

Javascript/NodeJS SDK to create SmartThings SmartApps

https://smartthings.developer.samsung.com/

License:Apache License 2.0


Languages

Language:JavaScript 100.0%