Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SmartAppConnector-sample
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const SmartApp = require('@smartthings/smartapp');
require('dotenv').config();
const server = module.exports = express();
server.use(bodyParser.json());
const deviceStates = {switch: 'off'}//1-10
const app = new SmartApp()
/* Handles lifecycle events from SmartThings */
server.post('/', async (req, res) => {
app.handleHttpCallback(req, res);
});
/* Defines the SmartApp */
app.appId('smartApp connector')
.disableCustomDisplayName(true)
.permissions(['w:devices:*', 'r:locations:*','x:devices:*', 'i:deviceprofiles:*', 'r:devices:*'])
.page('mainPage', (ctx, page, configData) => {
//This is only the device label shown in the mobile app, the name will be taken from the device profile
page.section('Device label:', section => {
section
.textSetting('deviceLabel')
.name('Write the device label')
})
})
.installed(async (ctx, updateData) => {
// Get device label from Input
let deviceLabel = ctx.config.deviceLabel[0].stringConfig.value;
// Device request payload
let deviceOpt = {
label: deviceLabel,
locationId: ctx.locationId,
app: {
// The device profile can be created from the Developer Workspace.
//It's better using a published profile due to the usage permissions
//It's on "development" by default, once it's published, it cannot be edited.
//You can publish it using the SmartThings CLI with the `deviceprofiles:publish` command.
// - (CLI download) https://github.com/SmartThingsCommunity/smartthings-cli/releases
// - (CLI configuration) https://github.com/SmartThingsCommunity/smartthings-cli/blob/master/packages/cli/doc/configuration.md
// example: smartthings deviceprofiles:publish 95d359ec-2437-4ed2-afb4-6579d12b1c9e
profileId: '95d359ec-2437-4ed2-afb4-6579d12b1c9e',//device profile ID - generated after creation in the DevWorkspace
installedAppId: updateData.installedApp.installedAppId
}
};
// Call the Device Endpoint
// https://smartthings.developer.samsung.com/docs/api-ref/st-api.html#operation/installDevice
// (Core SDK) https://github.com/SmartThingsCommunity/smartthings-core-sdk/blob/master/src/endpoint/devices.ts
let deviceReq = await ctx.api.devices.create(deviceOpt)
//output of the device info (deviceID, components, presentation Id, etc.)
console.log(deviceReq);
//send initial status of the capabilities
const devStatus = [
{
component: 'main',
capability: 'switch',
attribute: 'switch',
value: deviceStates.switch
}
]
//Call the API to send the status events
await ctx.api.devices.sendEvents(deviceReq.deviceId,devStatus)
//create schedule to get device status
//Schedule config
let scheduleName='getDevStatus';
let intervalCronExpression='0/5 * * * ?'; //every 5 minutes expression
return Promise.all([
ctx.api.schedules.schedule(scheduleName,intervalCronExpression)
])
}).uninstalled(async (ctx, uninstallData) => {
await ctx.api.devices.delete(ctx.config.deviceId); // delete device
})
.deviceCommandHandler(async (ctx, deviceCommandInfo) => {
let devStatus=[]
let newStatus = {
component: deviceCommandInfo.commands[0].componentId,
capability: deviceCommandInfo.commands[0].capability
}
switch (deviceCommandInfo.commands[0].capability) {
case 'switch': {
newStatus.attribute='switch'
newStatus.value = deviceStates.switch = deviceCommandInfo.commands[0].command === 'on' ? 'on' : 'off';
break;
}
}
devStatus.push(newStatus)
await ctx.api.devices.sendEvents(deviceCommandInfo.deviceId,devStatus)
})
.scheduledEventHandler('getDevStatus', async (context)=>{
//Request to get status from the Open API - sample
var config = {
method: 'get',
url: 'https://device-open-api-url'
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});
/* Starts the server */
let port = process.env.PORT;
server.listen(port);
console.log(`Open: http://127.0.0.1:${port}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment