Giter VIP home page Giter VIP logo

smartapp-sdk-nodejs's Introduction

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.

smartapp-sdk-nodejs's People

Contributors

bflorian avatar erodewald avatar rossiam avatar schawla3 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.