NAV Navbar
Scrypted Documentation
typescript javascript

Getting Started

Creating a Script

Toggle a light

if (light.on) {
    light.turnOff();
}
else {
    light.turnOn();
}
if (light.on) {
    light.turnOff();
}
else {
    light.turnOn();
}

Scripts are JavaScript programs that run on Scrypted to extend the capabilities of your home automation setup.

A common scenario would be to write a script that controls your devices. This script, for example, will toggle a light.

  1. Create a new Script under Plugins.
  2. Set the type to Library.
  3. Assign a device that supports OnOff to a variable "light".
  4. Paste the code into the script text box.
  5. Run the example code using the "Test" button.

Creating a Device Script

Create a new light

log.i('Hello World. This will create a virtual OnOff device.');

function Device() {
    // The state of the device is persisted by Scrypted. Restore the last known state.
    this._state = deviceManager.getDeviceState();
    // Ensure the light state is not null.
    this._state.on = this._state.on || false;
}

Device.prototype.turnOff = function () {
    log.i('turnOff was called!');
    this._state.on = false;
};

Device.prototype.turnOn = function () {
    log.i('turnOn was called!');
    this._state.on = true;
};

exports.default = new Device();
log.i('Hello World. This will create a virtual OnOff device.');

function Device() {
    // The state of the device is persisted by Scrypted. Restore the last known state.
    this._state = deviceManager.getDeviceState();
    // Ensure the light state is not null.
    this._state.on = this._state.on || false;
}

Device.prototype.turnOff = function () {
    log.i('turnOff was called!');
    this._state.on = false;
};

Device.prototype.turnOn = function () {
    log.i('turnOn was called!');
    this._state.on = true;
};

exports.default = new Device();

Scripts can add support for new devices, like a wifi lightbulb. These devices will then be synced to upstream integration providers like Google Home or Apple Homekit.

This sample creates a simple OnOff device that outputs on and off clicks to the log.

  1. Create a new Script under Plugins.
  2. Set the type to Device.
  3. Select the OnOff interface.
  4. Paste the code into the script text box.
  5. Save.

Watch the Logs for the new light, and turn the light on and off using the button on the webpage.

Using npm and VS Code

src/main

// https://developer.scrypted.app/#getting-started
import axios from 'axios';
import { OnOff, ScryptedDeviceBase } from '@scrypted/sdk';
import sdk from '@scrypted/sdk';
const { log } = sdk;

log.i('Hello World. This will create a virtual OnOff device.');

class ExampleDevice extends ScryptedDeviceBase implements OnOff {
    constructor() {
        super();
        // Ensure the light state is not null.
        this.on = this.on || false;
    }
    turnOff(): void {
        log.i('turnOff was called!');
        this.on = false;
    }
    async turnOn() {
        // set a breakpoint here.
        log.i('turnOn was called!');

        log.i("Let's pretend to perform a web request on an API that would turn on a light.");
        const ip = await axios.get('http://jsonip.com');
        log.i(`my ip: ${ip.data.ip}`);

        this.on = true;
    }
}

export default new ExampleDevice();
// https://developer.scrypted.app/#getting-started
import axios from 'axios';
import { ScryptedDeviceBase } from '@scrypted/sdk';
import sdk from '@scrypted/sdk';
const { log } = sdk;
log.i('Hello World. This will create a virtual OnOff device.');
class ExampleDevice extends ScryptedDeviceBase {
    constructor() {
        super();
        // Ensure the light state is not null.
        this.on = this.on || false;
    }
    turnOff() {
        log.i('turnOff was called!');
        this.on = false;
    }
    async turnOn() {
        // set a breakpoint here.
        log.i('turnOn was called!');
        log.i("Let's pretend to perform a web request on an API that would turn on a light.");
        const ip = await axios.get('http://jsonip.com');
        log.i(`my ip: ${ip.data.ip}`);
        this.on = true;
    }
}
export default new ExampleDevice();

Writing scripts in browser window can quickly become unwieldy when trying as your program becomes more complex. While devices can be controlled and created with simple scripts written in the Scrypted Management console, using the VS Code development environment is recommended. Using VS Code allows usage of modern JavaScript features, attaching a debuggers, and importing libraries from npm.

  1. Install VS Code and the Duktape Debugger Plugin.
  2. Check out either the sample JavaScript or TypeScript project from Github.
  3. Create a new Script (or reuse the previous one)
  4. Click Debug. Note the IP.
  5. Edit .vscode/settings.json and enter the IP in the "scrypted.debugHost" value.
  6. Launch Scrypted Debugger from the VS Code launch menu (or use the hotkey, F5).

package.json

You may have noticed that you didn't need to specify the OnOff interface. This is because the package.json contains the information about the device implementation in the "scrypted" key.

package.json

"scrypted": {
    "name": "JavaScript Light",
    "type": "Device",
    "interfaces": [
       "OnOff"
    ]
 },

Core Concepts

Interfaces

// Interfaces describe how the current state of a device, and can be used to modify that state.
if (light.on) {
    light.turnOff();
}
else {
    light.turnOn();
}
// Interfaces describe how the current state of a device, and can be used to modify that state.
if (light.on) {
    light.turnOff();
}
else {
    light.turnOn();
}

Interfaces are how devices expose their capabilities to Scrypted. An OnOff interface represents a binary switch. The Brightness interface represents a light that can be dimmed. The ColorSettingRgb interface indicates the light can change color. A device may expose multiple different interfaces to describe its functionality.

For example, given the following devices, the interfaces they would implement:

Interfaces aren't only used represent characteristics of physical devices. As mentioned, they provide ways to hook into Scrypted. The HttpRequestHandler lets you add a web hook to handle incoming web requests. EventListener lets you create handlers that respond to events. DeviceProvider acts as a controller platform (like Hue or Lifx) for exposing multiple other devices to Scrypted.

Interfaces also provide a way to query the device state. Such as checking whether an outlet is on or off, the current brightness level, or the current color.

Events

// Events are triggered by the device on update, and can be observed.
light.listen('OnOff', (eventSource: ScryptedDevice, eventDetails: EventDetails, eventData: object) => {
  if (eventData) {
    log.i('The light was turned on.');
  }
  else {
    log.i('The light was turned off.');
  }
});
// Events are triggered by the device on update, and can be observed.
light.listen('OnOff', (eventSource, eventDetails, eventData) => {
    if (eventData) {
        log.i('The light was turned on.');
    }
    else {
        log.i('The light was turned off.');
    }
});

Scrypted maintains the state of all connected devices. Whenever the state of an interface is updated on a device, an Event will be triggered for that particular interface.

For example, when a light turns on, the Light device would send an OnOff event. If a Slack message is received, the Slack device would send a MessagingEndpoint event. Setting a schedule for sunrise on weekdays would send an Alarm event on that schedule.

Automations subscribe to these events in your smart home setup and react accordingly.

SDK: @scrypted/sdk

const sdk = require('@scrypted/sdk');
const sdk = require('@scrypted/sdk');

or

import sdk from '@scrypted/sdk';
import sdk from '@scrypted/sdk';

The Scrypted SDK can be installed off npm.

npm install @scrypted/sdk --save

Definition

export interface ZwaveManagerDevice extends ZwaveManager, ScryptedDevice {
}

/**
 * Android Intent.
 * See: https://developer.android.com/reference/android/content/Intent
 */
interface Intent {
}

declare const ScryptedInterfaceDescriptors: any;
export {
    ScryptedInterfaceDescriptors
}

export interface ScryptedStatic {
    log?: Logger,
    scriptSettings?: Settings,

    android?: Android,
    deviceManager?: DeviceManager,
    endpointManager?: EndpointManager,
    mediaManager?: MediaManager,
    systemManager: SystemManager,
    zwaveManager?: ZwaveManagerDevice,
}

export interface ZwaveManagerDevice extends ZwaveManager, ScryptedDevice {
}

/**
 * Android Intent.
 * See: https://developer.android.com/reference/android/content/Intent
 */
interface Intent {
}

declare const ScryptedInterfaceDescriptors: any;
export {
    ScryptedInterfaceDescriptors
}

export interface ScryptedStatic {
    log?: Logger,
    scriptSettings?: Settings,

    android?: Android,
    deviceManager?: DeviceManager,
    endpointManager?: EndpointManager,
    mediaManager?: MediaManager,
    systemManager: SystemManager,
    zwaveManager?: ZwaveManagerDevice,
}

sdk.log

Example

const { log } = sdk;
log.i('Hello world.');
log.a('log.a will show up in the notification area!');
const { log } = sdk;
log.i('Hello world.');
log.a('log.a will show up in the notification area!');

The log property writes logs and notification alerts which can be viewed in the web magement console.

sdk.systemManager

SystemManager is used by scripts to query device state and access devices.

sdk.deviceManager

DeviceManager fascilitates querying, control, and creation of devices. It also and sending events from existing devices.

sdk.mediaManager

The media property manages creation and conversion of media types.

Core Reference

ScryptedDevice

Definition

interface ScryptedDevice  {
  component: string;
  id: string;
  interfaces: string[];
  metadata: any;
  name: string;
  room: string;
  type: ScryptedDeviceType;

  listen(event: ScryptedInterface|string|EventListenerOptions, callback: (eventSource: ScryptedDevice|null, eventDetails: EventDetails, eventData: object) => void): EventListenerRegister;
  setName(name: string): void;
  setRoom(room: string): void;
  setType(type: ScryptedDeviceType): void;
}
interface ScryptedDevice  {
  component: string;
  id: string;
  interfaces: string[];
  metadata: any;
  name: string;
  room: string;
  type: ScryptedDeviceType;

  listen(event: ScryptedInterface|string|EventListenerOptions, callback: (eventSource: ScryptedDevice|null, eventDetails: EventDetails, eventData: object) => void): EventListenerRegister;
  setName(name: string): void;
  setRoom(room: string): void;
  setType(type: ScryptedDeviceType): void;
}

Example

light.listen('OnOff', (eventSource: ScryptedDevice, eventDetails: EventDetails, eventData: object) => {
  if (eventData) {
    log.i('The light was turned on.');
  }
  else {
    log.i('The light was turned off.');
  }
});
light.listen('OnOff', (eventSource, eventDetails, eventData) => {
    if (eventData) {
        log.i('The light was turned on.');
    }
    else {
        log.i('The light was turned off.');
    }
});

Properties

Name Type
component string
id string
interfaces string[]
metadata any
name string
room string
type ScryptedDeviceType

listen

EventListenerRegister listen(ScryptedInterface|string|EventListenerOptions event, EventListener callback)

Subscribe to events from a specific interface on a device, such as 'OnOff' or 'Brightness'.

setName

void setName(string name)

setRoom

void setRoom(string room)

setType

void setType(ScryptedDeviceType type)

SystemManager

Definition

interface SystemManager  {
  getDeviceById(id: string): ScryptedDevice|null;
  getDeviceByName(name: string): ScryptedDevice|null;
  getDeviceState(id: string): any;
  getSystemState(): any;
  listen(EventListener: (eventSource: ScryptedDevice|null, eventDetails: EventDetails, eventData: object) => void): EventListenerRegister;
}
interface SystemManager  {
  getDeviceById(id: string): ScryptedDevice|null;
  getDeviceByName(name: string): ScryptedDevice|null;
  getDeviceState(id: string): any;
  getSystemState(): any;
  listen(EventListener: (eventSource: ScryptedDevice|null, eventDetails: EventDetails, eventData: object) => void): EventListenerRegister;
}

getDeviceById

ScryptedDevice|null getDeviceById(string id)

Find a Scrypted device by id.

getDeviceByName

ScryptedDevice|null getDeviceByName(string name)

Find a Scrypted device by name.

getDeviceState

any getDeviceState(string id)

Get the current state of a device.

getSystemState

any getSystemState()

Get the current state of every device.

listen

EventListenerRegister listen(EventListener EventListener)

Passively (without polling) listen to property changed events.

ScryptedDeviceType

enum ScryptedDeviceType {
  Builtin = "Builtin",
  Camera = "Camera",
  Fan = "Fan",
  Light = "Light",
  Switch = "Switch",
  Outlet = "Outlet",
  Sensor = "Sensor",
  Scene = "Scene",
  Program = "Program",
  Automation = "Automation",
  Vacuum = "Vacuum",
  Notifier = "Notifier",
  Thermostat = "Thermostat",
  Lock = "Lock",
  PasswordControl = "PasswordControl",
  Display = "Display",
  Speaker = "Speaker",
  Event = "Event",
  Entry = "Entry",
  Garage = "Garage",
  DeviceProvider = "DeviceProvider",
  DataSource = "DataSource",
  API = "API",
  Unknown = "Unknown",
}
enum ScryptedDeviceType {
  Builtin = "Builtin",
  Camera = "Camera",
  Fan = "Fan",
  Light = "Light",
  Switch = "Switch",
  Outlet = "Outlet",
  Sensor = "Sensor",
  Scene = "Scene",
  Program = "Program",
  Automation = "Automation",
  Vacuum = "Vacuum",
  Notifier = "Notifier",
  Thermostat = "Thermostat",
  Lock = "Lock",
  PasswordControl = "PasswordControl",
  Display = "Display",
  Speaker = "Speaker",
  Event = "Event",
  Entry = "Entry",
  Garage = "Garage",
  DeviceProvider = "DeviceProvider",
  DataSource = "DataSource",
  API = "API",
  Unknown = "Unknown",
}
Enum
"Builtin"
"Camera"
"Fan"
"Light"
"Switch"
"Outlet"
"Sensor"
"Scene"
"Program"
"Automation"
"Vacuum"
"Notifier"
"Thermostat"
"Lock"
"PasswordControl"
"Display"
"Speaker"
"Event"
"Entry"
"Garage"
"DeviceProvider"
"DataSource"
"API"
"Unknown"

EventListener

Definition

interface EventListener  {
  onEvent(eventSource: ScryptedDevice|null, eventDetails: EventDetails, eventData: object): void;
}
interface EventListener  {
  onEvent(eventSource: ScryptedDevice|null, eventDetails: EventDetails, eventData: object): void;
}

onEvent

void onEvent(ScryptedDevice|null eventSource, EventDetails eventDetails, object eventData)

This device type can be hooked by Automation actions to handle events. The event source, event details (interface, time, property), and event data are all passed to the listener as arguments.

EventListenerRegister

Definition

interface EventListenerRegister  {
  removeListener(): void;
}
interface EventListenerRegister  {
  removeListener(): void;
}

removeListener

void removeListener()

Logger

Definition

interface Logger  {
  a(msg: string): void;
  clear(): void;
  clearAlert(msg: string): void;
  clearAlerts(): void;
  d(msg: string): void;
  e(msg: string): void;
  i(msg: string): void;
  v(msg: string): void;
  w(msg: string): void;
}
interface Logger  {
  a(msg: string): void;
  clear(): void;
  clearAlert(msg: string): void;
  clearAlerts(): void;
  d(msg: string): void;
  e(msg: string): void;
  i(msg: string): void;
  v(msg: string): void;
  w(msg: string): void;
}

a

void a(string msg)

Alert. Alert level logs will be displayed as a notification in the management console.

clear

void clear()

Clear the log

clearAlert

void clearAlert(string msg)

Clear a specific alert

clearAlerts

void clearAlerts()

Clear all alerts

d

void d(string msg)

Debug

e

void e(string msg)

Error

i

void i(string msg)

Info

v

void v(string msg)

Verbose

w

void w(string msg)

Warn

Device Provider Reference

DeviceManager

Definition

interface DeviceManager  {
  getDeviceLogger(nativeId: string): Logger;
  getDeviceState(): DeviceState;
  getDeviceState(nativeId: string): DeviceState;
  getDeviceStorage(): Storage;
  getDeviceStorage(nativeId: string): Storage;
  getNativeIds(): string[];
  onDeviceDiscovered(device: Device): void;
  onDeviceEvent(eventInterface: string, eventData: any): void;
  onDeviceEvent(nativeId: string, eventInterface: string, eventData: any): void;
  onDevicesChanged(devices: DeviceManifest): void;
}
interface DeviceManager  {
  getDeviceLogger(nativeId: string): Logger;
  getDeviceState(): DeviceState;
  getDeviceState(nativeId: string): DeviceState;
  getDeviceStorage(): Storage;
  getDeviceStorage(nativeId: string): Storage;
  getNativeIds(): string[];
  onDeviceDiscovered(device: Device): void;
  onDeviceEvent(eventInterface: string, eventData: any): void;
  onDeviceEvent(nativeId: string, eventInterface: string, eventData: any): void;
  onDevicesChanged(devices: DeviceManifest): void;
}

Example

import sdk, { ScryptedDeviceType } from '@scrypted/sdk';
const { deviceManager } = sdk;

// Sync the following two lights with Scrypted. New devices unknown to Scrypted will be added
// while devices that were previously reported, and no longer exist, will be removed.
// onDevicesChanged should be called with the full sync list of devices.
deviceManager.onDevicesChanged({
    devices:[
        {
            nativeId: '1',
            name: 'Light 1',
            type: ScryptedDeviceType.Light,
            interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
        },
        {
            nativeId: '2',
            name: 'Light 2',
            type: ScryptedDeviceType.Light,
            interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
        }
    ]
});
import sdk, { ScryptedDeviceType } from '@scrypted/sdk';
const { deviceManager } = sdk;

// Sync the following two lights with Scrypted. New devices unknown to Scrypted will be added
// while devices that were previously reported, and no longer exist, will be removed.
// onDevicesChanged should be called with the full sync list of devices.
deviceManager.onDevicesChanged({
    devices:[
        {
            nativeId: '1',
            name: 'Light 1',
            type: ScryptedDeviceType.Light,
            interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
        },
        {
            nativeId: '2',
            name: 'Light 2',
            type: ScryptedDeviceType.Light,
            interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
        }
    ]
});

getDeviceLogger

Logger getDeviceLogger(string nativeId)

Get the logger for a device given a native id.

getDeviceState

DeviceState getDeviceState()

Get the device state maintained by Scrypted. Setting properties on this state will update the state in Scrypted.

getDeviceState

DeviceState getDeviceState(string nativeId)

Get the device state maintained by Scrypted. Setting properties on this state will update the state in Scrypted.

getDeviceStorage

Storage getDeviceStorage()

Get the per script Storage object.

getDeviceStorage

Storage getDeviceStorage(string nativeId)

Get the per device Storage object.

getNativeIds

string[] getNativeIds()

onDeviceDiscovered

void onDeviceDiscovered(Device device)

onDeviceDiscovered is used to report new devices that are trickle discovered, one by one, such as via a network broadcast.

onDeviceEvent

void onDeviceEvent(string eventInterface, any eventData)

Fire an event for this plugin's device.

onDeviceEvent

void onDeviceEvent(string nativeId, string eventInterface, any eventData)

Fire an event for a device provided by this plugin.

onDevicesChanged

void onDevicesChanged(DeviceManifest devices)

onDevicesChanged is used to sync Scrypted with devices that are attached to a hub, such as Hue or SmartThings. All the devices should be reported at once.

DeviceProvider

Definition

interface DeviceProvider  {
  discoverDevices(duration: number): void;
  getDevice(nativeId: string): object;
}
interface DeviceProvider  {
  discoverDevices(duration: number): void;
  getDevice(nativeId: string): object;
}

Example

import { OnOff, ScryptedDeviceBase, DeviceProvider, ScryptedDeviceType } from '@scrypted/sdk';
import sdk from '@scrypted/sdk';
const { deviceManager } = sdk;

// Devices returned by the DeviceProvider
class ExampleDevice extends ScryptedDeviceBase implements OnOff {
    constructor(nativeId: string) {
        super(nativeId);
        // Ensure the light state is not null.
        this.on = this.on || false;
    }
    turnOff() {
        this.on = false;
    }
    turnOn() {
        this.on = true;
    }
}

// DeviceProvider handles discovery and device requests
class ExampleDeviceProvider extends ScryptedDeviceBase implements DeviceProvider {
    constructor() {
        super();
        // it is recommended to automatically perform discovery on startup
        this.discoverDevices(30);
    }
    discoverDevices(duration: number): void {
        // Sync the following two lights with Scrypted. New devices unknown to Scrypted will be added
        // while devices that were previously reported, and no longer exist, will be removed.
        // onDevicesChanged should be called with the full sync list of devices.
        deviceManager.onDevicesChanged({
            devices:[
                {
                    nativeId: '1',
                    name: 'Light 1',
                    type: ScryptedDeviceType.Light,
                    interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv'],
                },
                {
                    nativeId: '2',
                    name: 'Light 2',
                    type: ScryptedDeviceType.Light,
                    interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv'],
                }
            ]
        });
    }
    getDevice(nativeId: string): object {
        return new ExampleDevice(nativeId);
    }
};

export default new ExampleDeviceProvider();
import { ScryptedDeviceBase, ScryptedDeviceType } from '@scrypted/sdk';
import sdk from '@scrypted/sdk';
const { deviceManager } = sdk;
// Devices returned by the DeviceProvider
class ExampleDevice extends ScryptedDeviceBase {
    constructor(nativeId) {
        super(nativeId);
        // Ensure the light state is not null.
        this.on = this.on || false;
    }
    turnOff() {
        this.on = false;
    }
    turnOn() {
        this.on = true;
    }
}
// DeviceProvider handles discovery and device requests
class ExampleDeviceProvider extends ScryptedDeviceBase {
    constructor() {
        super();
        // it is recommended to automatically perform discovery on startup
        this.discoverDevices(30);
    }
    discoverDevices(duration) {
        // Sync the following two lights with Scrypted. New devices unknown to Scrypted will be added
        // while devices that were previously reported, and no longer exist, will be removed.
        // onDevicesChanged should be called with the full sync list of devices.
        deviceManager.onDevicesChanged({
            devices: [
                {
                    nativeId: '1',
                    name: 'Light 1',
                    type: ScryptedDeviceType.Light,
                    interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv'],
                },
                {
                    nativeId: '2',
                    name: 'Light 2',
                    type: ScryptedDeviceType.Light,
                    interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv'],
                }
            ]
        });
    }
    getDevice(nativeId) {
        return new ExampleDevice(nativeId);
    }
}
;
export default new ExampleDeviceProvider();

discoverDevices

void discoverDevices(number duration)

Perform device discovery for the specified duration in seconds.

getDevice

object getDevice(string nativeId)

Get an instance of a previously discovered device that was reported to the device manager.

DeviceManifest

Definition

interface DeviceManifest  {
  devices: Device[];
}
interface DeviceManifest  {
  devices: Device[];
}

Example

{
    devices:[
        {
            nativeId: '1',
            name: 'Light 1',
            type: ScryptedDeviceType.Light,
            interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
        },
        {
            nativeId: '2',
            name: 'Light 2',
            type: ScryptedDeviceType.Light,
            interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
        }
    ]
}
{
    devices:[
        {
            nativeId: '1',
            name: 'Light 1',
            type: ScryptedDeviceType.Light,
            interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
        },
        {
            nativeId: '2',
            name: 'Light 2',
            type: ScryptedDeviceType.Light,
            interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
        }
    ]
}

Properties

Name Type
devices Device[]

Device

Definition

interface Device  {
  interfaces: string[];
  model: string;
  name: string;
  nativeId: string;
  room: string;
  type: ScryptedDeviceType;
}
interface Device  {
  interfaces: string[];
  model: string;
  name: string;
  nativeId: string;
  room: string;
  type: ScryptedDeviceType;
}

Example

{
    nativeId: '2',
    name: 'Light 2',
    type: 'Light',
    interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
}
{
    nativeId: '2',
    name: 'Light 2',
    type: 'Light',
    interfaces: ['OnOff', 'Brightness', 'ColorSettingHsv']
}

Properties

Name Type
interfaces string[]
model string
name string
nativeId string
room string
type ScryptedDeviceType

Refresh

Definition

interface Refresh  {
  getRefreshFrequency(): number;
  refresh(refreshInterface: string, userInitiated: boolean): void;
}
interface Refresh  {
  getRefreshFrequency(): number;
  refresh(refreshInterface: string, userInitiated: boolean): void;
}

getRefreshFrequency

number getRefreshFrequency()

Get the recommended refresh/poll frequency in seconds for this device.

refresh

void refresh(string refreshInterface, boolean userInitiated)

This method is called by Scrypted when the properties of the device need to be refreshed. When the device has completed the refresh, the appropriate DeviceState properties should be set. The parameters provide the specific interface that needs to be refreshed and whether it was user initiated (via UI or voice).

DeviceState

Definition

interface DeviceState  {
  component: string;
  id: string;
  interfaces: string[];
  metadata: any;
  name: string;
  room: string;
  type: ScryptedDeviceType;
  on: boolean;
  brightness: number;
  colorTemperature: number;
  rgb: ColorRgb;
  hsv: ColorHsv;
  running: boolean;
  paused: boolean;
  docked: boolean;
  temperature: number;
  temperatureUnit: TemperatureUnit;
  humidity: number;
  thermostatAvailableModes: ThermostatMode[];
  thermostatMode: ThermostatMode;
  thermostatSetpoint: number;
  thermostatSetpointHigh: number;
  thermostatSetpointLow: number;
  lockState: LockState;
  entryOpen: boolean;
  batteryLevel: number;
  online: boolean;
  updateAvailable: boolean;
  fromMimeType: string;
  toMimeType: string;
  binaryState: boolean;
  intrusionDetected: boolean;
  motionDetected: boolean;
  occupied: boolean;
  flooded: boolean;
  ultraviolet: number;
  luminance: number;
  position: Position;
}
interface DeviceState  {
  component: string;
  id: string;
  interfaces: string[];
  metadata: any;
  name: string;
  room: string;
  type: ScryptedDeviceType;
  on: boolean;
  brightness: number;
  colorTemperature: number;
  rgb: ColorRgb;
  hsv: ColorHsv;
  running: boolean;
  paused: boolean;
  docked: boolean;
  temperature: number;
  temperatureUnit: TemperatureUnit;
  humidity: number;
  thermostatAvailableModes: ThermostatMode[];
  thermostatMode: ThermostatMode;
  thermostatSetpoint: number;
  thermostatSetpointHigh: number;
  thermostatSetpointLow: number;
  lockState: LockState;
  entryOpen: boolean;
  batteryLevel: number;
  online: boolean;
  updateAvailable: boolean;
  fromMimeType: string;
  toMimeType: string;
  binaryState: boolean;
  intrusionDetected: boolean;
  motionDetected: boolean;
  occupied: boolean;
  flooded: boolean;
  ultraviolet: number;
  luminance: number;
  position: Position;
}

Properties

Name Type
component string
id string
interfaces string[]
metadata any
name string
room string
type ScryptedDeviceType
on boolean
brightness number
colorTemperature number
rgb ColorRgb
hsv ColorHsv
running boolean
paused boolean
docked boolean
temperature number
temperatureUnit TemperatureUnit
humidity number
thermostatAvailableModes ThermostatMode[]
thermostatMode ThermostatMode
thermostatSetpoint number
thermostatSetpointHigh number
thermostatSetpointLow number
lockState LockState
entryOpen boolean
batteryLevel number
online boolean
updateAvailable boolean
fromMimeType string
toMimeType string
binaryState boolean
intrusionDetected boolean
motionDetected boolean
occupied boolean
flooded boolean
ultraviolet number
luminance number
position Position

Media Reference

MediaManager

Definition

interface MediaManager  {
  convertMediaObjectToBuffer(mediaObject: MediaObject, toMimeType: string): Promise<Buffer>;
  convertMediaObjectToLocalUrl(mediaObject: MediaObject, toMimeType: string): Promise<string>;
  convertMediaObjectToUrl(mediaObject: MediaObject, toMimeType: string): Promise<string>;
  createFFmpegMediaObject(ffMpegInput: FFMpegInput): MediaObject;
  createMediaObject(data: string|Buffer|Promise<string|Buffer>, mimeType: string): MediaObject;
}
interface MediaManager  {
  convertMediaObjectToBuffer(mediaObject: MediaObject, toMimeType: string): Promise<Buffer>;
  convertMediaObjectToLocalUrl(mediaObject: MediaObject, toMimeType: string): Promise<string>;
  convertMediaObjectToUrl(mediaObject: MediaObject, toMimeType: string): Promise<string>;
  createFFmpegMediaObject(ffMpegInput: FFMpegInput): MediaObject;
  createMediaObject(data: string|Buffer|Promise<string|Buffer>, mimeType: string): MediaObject;
}

User Script Code

// In a script that uses a speaker, send a text string to the speaker for playback.
const text = sdk.createMediaObject(Buffer.from('The front door is open'), 'text/plain');
speaker.load(text);
// In a script that uses a speaker, send a text string to the speaker for playback.
const text = sdk.createMediaObject(Buffer.from('The front door is open'), 'text/plain');
speaker.load(text);

Speaker Plugin Code

// In a different plugin that implements the speaker, convert the text string to a
// publicly accessible audio/wav Uri.
// "media" is the "text" MediaObject from above.
var mediaUrl = await sdk.convertMediaObjectToUri(media, "audio/wav");
playUrl(mediaUrl);
// In a different plugin that implements the speaker, convert the text string to a
// publicly accessible audio/wav Uri.
// "media" is the "text" MediaObject from above.
var mediaUrl = await sdk.convertMediaObjectToUri(media, "audio/wav");
playUrl(mediaUrl);

MediaObjects are an interstial representation of any media that flows through the Scrypted platform. Devices generally are not concerned about the source type of the media, but need the media to be converted into a type is compatible with the device. For example, a user may want to send text to a speaker for playback. The speaker is not aware of the source media type, and only needs it to be converted into an audio url.

convertMediaObjectToBuffer

Promise<Buffer> convertMediaObjectToBuffer(MediaObject mediaObject, string toMimeType)

Convert a media object to a Buffer of the given mime type.

convertMediaObjectToLocalUrl

Promise<string> convertMediaObjectToLocalUrl(MediaObject mediaObject, string toMimeType)

Convert a media object to a locally accessible URL that serves a media file of the given mime type. If the media object is an externally accessible URL, that will be returned.

convertMediaObjectToUrl

Promise<string> convertMediaObjectToUrl(MediaObject mediaObject, string toMimeType)

Convert a media object to a publically accessible URL that serves a media file of the given mime type.

createFFmpegMediaObject

MediaObject createFFmpegMediaObject(FFMpegInput ffMpegInput)

Create a MediaObject. The media will be created from the provided FFmpeg input arguments.

createMediaObject

MediaObject createMediaObject(string|Buffer|Promise<string|Buffer> data, string mimeType)

Create a MediaObject. The mime type needs to be provided up front, but the data can be a URL string, Buffer, or a Promise for a URL string or Buffer.

MediaObject

Definition

interface MediaObject  {
  mimeType: string;
}
interface MediaObject  {
  mimeType: string;
}

Properties

Name Type
mimeType string

Webhook and Push Reference

EndpointManager

Definition

interface EndpointManager  {
  getAuthenticatedPath(): Promise<string>;
  getInsecurePublicLocalEndpoint(): Promise<string>;
  getPublicCloudEndpoint(): Promise<string>;
  getPublicLocalEndpoint(): Promise<string>;
  getPublicPushEndpoint(): Promise<string>;
}
interface EndpointManager  {
  getAuthenticatedPath(): Promise<string>;
  getInsecurePublicLocalEndpoint(): Promise<string>;
  getPublicCloudEndpoint(): Promise<string>;
  getPublicLocalEndpoint(): Promise<string>;
  getPublicPushEndpoint(): Promise<string>;
}

getAuthenticatedPath

Promise<string> getAuthenticatedPath()

Get an URL pathname that can be accessed on your local network or cloud while authenticated. This is an absolute path that requires cookie authentication, and generally used only in browser contexts.

getInsecurePublicLocalEndpoint

Promise<string> getInsecurePublicLocalEndpoint()

Get an URL that can only be accessed on your local network by anyone with the link. HTTP requests and responses are without any encryption. Plugin implementation is responsible for authentication.

getPublicCloudEndpoint

Promise<string> getPublicCloudEndpoint()

Get an URL that can be externally accessed by anyone with the link. Plugin implementation is responsible for authentication.

getPublicLocalEndpoint

Promise<string> getPublicLocalEndpoint()

Get an URL that can only be accessed on your local network by anyone with the link. HTTP requests and responses are over SSL with a self signed certificate. Plugin implementation is responsible for authentication.

getPublicPushEndpoint

Promise<string> getPublicPushEndpoint()

Get an URL that can be used to send a push message to the client. This differs from a cloud endpoint, in that, the Plugin does not send a response back. Plugin implementation is responsible for authentication.

HttpRequestHandler

Definition

interface HttpRequestHandler implements EndpointHandler {
  onRequest(request: HttpRequest, response: HttpResponse): void;
}
interface HttpRequestHandler implements EndpointHandler {
  onRequest(request: HttpRequest, response: HttpResponse): void;
}

Example

class HttpHandler implements HttpRequestHnadler {
    // See documentation! 
    // Will handle requests at https://<local-ip>:9443/endpoint/test/ (or /endpoint/@koush/test)
    getEndpoint() {
        return 'test';
        // or, an npm user/org namespace works as well:
        // return '@koush/test';
    }
    onRequest(request: HttpRequest, response: HttpResponse) {
        response.send('hello world!!');
    }
}

export default new HttpHandler();
class HttpHandler {
    // See documentation! 
    // Will handle requests at https://<local-ip>:9443/endpoint/test/ (or /endpoint/@koush/test)
    getEndpoint() {
        return 'test';
        // or, an npm user/org namespace works as well:
        // return '@koush/test';
    }
    onRequest(request, response) {
        response.send('hello world!!');
    }
}
export default new HttpHandler();

onRequest

void onRequest(HttpRequest request, HttpResponse response)

Callback to handle an incoming request.

PushHandler

Definition

interface PushHandler implements EndpointHandler {
  onPush(request: HttpRequest): void;
}
interface PushHandler implements EndpointHandler {
  onPush(request: HttpRequest): void;
}

onPush

void onPush(HttpRequest request)

Callback to handle an incoming push.

HttpRequest

Definition

interface HttpRequest  {
  body: string;
  headers: object;
  isPublicEndpoint: boolean;
  method: string;
  rootPath: string;
  url: string;
  username: string;
}
interface HttpRequest  {
  body: string;
  headers: object;
  isPublicEndpoint: boolean;
  method: string;
  rootPath: string;
  url: string;
  username: string;
}

Properties

Name Type
body string
headers object
isPublicEndpoint boolean
method string
rootPath string
url string
username string

HttpResponse

Definition

interface HttpResponse  {
  send(options: HttpResponseOptions, body: string): void;
  send(options: HttpResponseOptions, body: Buffer): void;
  send(body: string): void;
  send(body: Buffer): void;
  sendFile(options: HttpResponseOptions, path: string): void;
  sendFile(path: string): void;
}
interface HttpResponse  {
  send(options: HttpResponseOptions, body: string): void;
  send(options: HttpResponseOptions, body: Buffer): void;
  send(body: string): void;
  send(body: Buffer): void;
  sendFile(options: HttpResponseOptions, path: string): void;
  sendFile(path: string): void;
}

send

void send(HttpResponseOptions options, string body)

send

void send(HttpResponseOptions options, Buffer body)

send

void send(string body)

send

void send(Buffer body)

sendFile

void sendFile(HttpResponseOptions options, string path)

sendFile

void sendFile(string path)

HttpResponseOptions

Definition

interface HttpResponseOptions  {
  code: number;
  headers: object;
}
interface HttpResponseOptions  {
  code: number;
  headers: object;
}

Properties

Name Type
code number
headers object

Android Intent Reference

Android

Definition

interface Android  {
  newIntent(): Intent;
  sendBroadcast(intent: Intent): void;
  startActivity(intent: Intent): void;
  startService(intent: Intent): void;
}
interface Android  {
  newIntent(): Intent;
  sendBroadcast(intent: Intent): void;
  startActivity(intent: Intent): void;
  startService(intent: Intent): void;
}

newIntent

Intent newIntent()

Create a new Intent. Use one of the send methods to send broadcasts, start activities, or start services.

sendBroadcast

void sendBroadcast(Intent intent)

startActivity

void startActivity(Intent intent)

startService

void startService(Intent intent)

Z-Wave Reference

ZwaveManager

Definition

interface ZwaveManager  {
  getNodeManufacturerName(homeId: number, nodeId: number): string;
  getNodeName(homeId: number, nodeId: number): string;
  getNodeProductName(homeId: number, nodeId: number): string;
  getValue(valueId: ZwaveValueId): string;
  getValueHelp(valueId: ZwaveValueId): string;
  getValueLabel(valueId: ZwaveValueId): string;
  getValueListItems(valueId: ZwaveValueId): string[];
  getValueListValues(valueId: ZwaveValueId): number[];
  getValueUnit(valueId: ZwaveValueId): string;
  refreshValue(valueId: ZwaveValueId): void;
  setNodeName(homeId: number, nodeId: number, name: string): void;
  setValue(valueId: ZwaveValueId, value: string): void;
  setValueRaw(valueId: ZwaveValueId, value: Buffer): void;
}
interface ZwaveManager  {
  getNodeManufacturerName(homeId: number, nodeId: number): string;
  getNodeName(homeId: number, nodeId: number): string;
  getNodeProductName(homeId: number, nodeId: number): string;
  getValue(valueId: ZwaveValueId): string;
  getValueHelp(valueId: ZwaveValueId): string;
  getValueLabel(valueId: ZwaveValueId): string;
  getValueListItems(valueId: ZwaveValueId): string[];
  getValueListValues(valueId: ZwaveValueId): number[];
  getValueUnit(valueId: ZwaveValueId): string;
  refreshValue(valueId: ZwaveValueId): void;
  setNodeName(homeId: number, nodeId: number, name: string): void;
  setValue(valueId: ZwaveValueId, value: string): void;
  setValueRaw(valueId: ZwaveValueId, value: Buffer): void;
}

getNodeManufacturerName

string getNodeManufacturerName(number homeId, number nodeId)

getNodeName

string getNodeName(number homeId, number nodeId)

getNodeProductName

string getNodeProductName(number homeId, number nodeId)

getValue

string getValue(ZwaveValueId valueId)

getValueHelp

string getValueHelp(ZwaveValueId valueId)

getValueLabel

string getValueLabel(ZwaveValueId valueId)

getValueListItems

string[] getValueListItems(ZwaveValueId valueId)

getValueListValues

number[] getValueListValues(ZwaveValueId valueId)

getValueUnit

string getValueUnit(ZwaveValueId valueId)

refreshValue

void refreshValue(ZwaveValueId valueId)

setNodeName

void setNodeName(number homeId, number nodeId, string name)

setValue

void setValue(ZwaveValueId valueId, string value)

setValueRaw

void setValueRaw(ZwaveValueId valueId, Buffer value)

ZwaveNotification

Definition

interface ZwaveNotification  {
  byteData: number;
  event: number;
  type: ZwaveNotificationType;
  valueId: ZwaveValueId;
}
interface ZwaveNotification  {
  byteData: number;
  event: number;
  type: ZwaveNotificationType;
  valueId: ZwaveValueId;
}

Properties

Name Type
byteData number
event number
type ZwaveNotificationType
valueId ZwaveValueId

ZwaveNotificationType

enum ZwaveNotificationType {
  Type_ValueAdded = "Type_ValueAdded",
  Type_ValueRemoved = "Type_ValueRemoved",
  Type_ValueChanged = "Type_ValueChanged",
  Type_ValueRefreshed = "Type_ValueRefreshed",
  Type_Group = "Type_Group",
  Type_NodeNew = "Type_NodeNew",
  Type_NodeAdded = "Type_NodeAdded",
  Type_NodeRemoved = "Type_NodeRemoved",
  Type_NodeProtocolInfo = "Type_NodeProtocolInfo",
  Type_NodeNaming = "Type_NodeNaming",
  Type_NodeEvent = "Type_NodeEvent",
  Type_PollingDisabled = "Type_PollingDisabled",
  Type_PollingEnabled = "Type_PollingEnabled",
  Type_SceneEvent = "Type_SceneEvent",
  Type_CreateButton = "Type_CreateButton",
  Type_DeleteButton = "Type_DeleteButton",
  Type_ButtonOn = "Type_ButtonOn",
  Type_ButtonOff = "Type_ButtonOff",
  Type_DriverReady = "Type_DriverReady",
  Type_DriverFailed = "Type_DriverFailed",
  Type_DriverReset = "Type_DriverReset",
  Type_EssentialNodeQueriesComplete = "Type_EssentialNodeQueriesComplete",
  Type_NodeQueriesComplete = "Type_NodeQueriesComplete",
  Type_AwakeNodesQueried = "Type_AwakeNodesQueried",
  Type_AllNodesQueriedSomeDead = "Type_AllNodesQueriedSomeDead",
  Type_AllNodesQueried = "Type_AllNodesQueried",
  Type_Notification = "Type_Notification",
  Type_DriverRemoved = "Type_DriverRemoved",
  Type_ControllerCommand = "Type_ControllerCommand",
  Type_NodeReset = "Type_NodeReset",
  Type_UserAlerts = "Type_UserAlerts",
  Type_ManufacturerSpecificDBReady = "Type_ManufacturerSpecificDBReady",
}
enum ZwaveNotificationType {
  Type_ValueAdded = "Type_ValueAdded",
  Type_ValueRemoved = "Type_ValueRemoved",
  Type_ValueChanged = "Type_ValueChanged",
  Type_ValueRefreshed = "Type_ValueRefreshed",
  Type_Group = "Type_Group",
  Type_NodeNew = "Type_NodeNew",
  Type_NodeAdded = "Type_NodeAdded",
  Type_NodeRemoved = "Type_NodeRemoved",
  Type_NodeProtocolInfo = "Type_NodeProtocolInfo",
  Type_NodeNaming = "Type_NodeNaming",
  Type_NodeEvent = "Type_NodeEvent",
  Type_PollingDisabled = "Type_PollingDisabled",
  Type_PollingEnabled = "Type_PollingEnabled",
  Type_SceneEvent = "Type_SceneEvent",
  Type_CreateButton = "Type_CreateButton",
  Type_DeleteButton = "Type_DeleteButton",
  Type_ButtonOn = "Type_ButtonOn",
  Type_ButtonOff = "Type_ButtonOff",
  Type_DriverReady = "Type_DriverReady",
  Type_DriverFailed = "Type_DriverFailed",
  Type_DriverReset = "Type_DriverReset",
  Type_EssentialNodeQueriesComplete = "Type_EssentialNodeQueriesComplete",
  Type_NodeQueriesComplete = "Type_NodeQueriesComplete",
  Type_AwakeNodesQueried = "Type_AwakeNodesQueried",
  Type_AllNodesQueriedSomeDead = "Type_AllNodesQueriedSomeDead",
  Type_AllNodesQueried = "Type_AllNodesQueried",
  Type_Notification = "Type_Notification",
  Type_DriverRemoved = "Type_DriverRemoved",
  Type_ControllerCommand = "Type_ControllerCommand",
  Type_NodeReset = "Type_NodeReset",
  Type_UserAlerts = "Type_UserAlerts",
  Type_ManufacturerSpecificDBReady = "Type_ManufacturerSpecificDBReady",
}
Enum
"Type_ValueAdded"
"Type_ValueRemoved"
"Type_ValueChanged"
"Type_ValueRefreshed"
"Type_Group"
"Type_NodeNew"
"Type_NodeAdded"
"Type_NodeRemoved"
"Type_NodeProtocolInfo"
"Type_NodeNaming"
"Type_NodeEvent"
"Type_PollingDisabled"
"Type_PollingEnabled"
"Type_SceneEvent"
"Type_CreateButton"
"Type_DeleteButton"
"Type_ButtonOn"
"Type_ButtonOff"
"Type_DriverReady"
"Type_DriverFailed"
"Type_DriverReset"
"Type_EssentialNodeQueriesComplete"
"Type_NodeQueriesComplete"
"Type_AwakeNodesQueried"
"Type_AllNodesQueriedSomeDead"
"Type_AllNodesQueried"
"Type_Notification"
"Type_DriverRemoved"
"Type_ControllerCommand"
"Type_NodeReset"
"Type_UserAlerts"
"Type_ManufacturerSpecificDBReady"

ZwaveValueId

Definition

interface ZwaveValueId  {
  commandClass: number;
  genre: number;
  homeId: number;
  index: number;
  instance: number;
  nodeId: number;
  type: number;
}
interface ZwaveValueId  {
  commandClass: number;
  genre: number;
  homeId: number;
  index: number;
  instance: number;
  nodeId: number;
  type: number;
}

Properties

Name Type
commandClass number
genre number
homeId number
index number
instance number
nodeId number
type number

Device Interface Reference

EventListenerOptions

Definition

interface EventListenerOptions  {
  denoise: boolean;
  event: ScryptedInterface|string;
  watch: boolean;
}
interface EventListenerOptions  {
  denoise: boolean;
  event: ScryptedInterface|string;
  watch: boolean;
}

Properties

Name Type
denoise boolean
event ScryptedInterface
watch boolean

EventDetails

Definition

interface EventDetails  {
  changed: boolean;
  eventInterface: string;
  eventTime: number;
  property: string;
}
interface EventDetails  {
  changed: boolean;
  eventInterface: string;
  eventTime: number;
  property: string;
}

Properties

Name Type
changed boolean
eventInterface string
eventTime number
property string

OnOff

Definition

interface OnOff  {
  on: boolean;

  turnOff(): void;
  turnOn(): void;
}
interface OnOff  {
  on: boolean;

  turnOff(): void;
  turnOn(): void;
}

Example

// Toggle an OnOff device
if (switch.on) {
    switch.turnOff();
}
else {
    switch.turnOn();
}
// Toggle an OnOff device
if (switch.on) {
    switch.turnOff();
}
else {
    switch.turnOn();
}

Properties

Name Type
on boolean

turnOff

void turnOff()

turnOn

void turnOn()

Brightness

Definition

interface Brightness  {
  brightness: number;

  setBrightness(brightness: number): void;
}
interface Brightness  {
  brightness: number;

  setBrightness(brightness: number): void;
}

Example

// Set a Brightness device to 50%
dimmer.setLevel(50);
// Set a Brightness device to 50%
dimmer.setLevel(50);

Properties

Name Type
brightness number

setBrightness

void setBrightness(number brightness)

ColorSettingTemperature

Definition

interface ColorSettingTemperature  {
  colorTemperature: number;

  getTemperatureMaxK(): number;
  getTemperatureMinK(): number;
  setColorTemperature(kelvin: number): void;
}
interface ColorSettingTemperature  {
  colorTemperature: number;

  getTemperatureMaxK(): number;
  getTemperatureMinK(): number;
  setColorTemperature(kelvin: number): void;
}

Example

// set a bulb to 2500 Kelvin
bulb.setTemperature(2500);
// set a bulb to 2500 Kelvin
bulb.setTemperature(2500);

Properties

Name Type
colorTemperature number

getTemperatureMaxK

number getTemperatureMaxK()

getTemperatureMinK

number getTemperatureMinK()

setColorTemperature

void setColorTemperature(number kelvin)

ColorSettingRgb

Definition

interface ColorSettingRgb  {
  rgb: ColorRgb;

  setRgb(r: number, g: number, b: number): void;
}
interface ColorSettingRgb  {
  rgb: ColorRgb;

  setRgb(r: number, g: number, b: number): void;
}

Example

// set the color to red on a ColorSettingRgb device
colorBulb.setRgb({
    r: 255,
    g: 0,
    b: 0
})
// set the color to red on a ColorSettingRgb device
colorBulb.setRgb({
    r: 255,
    g: 0,
    b: 0
})

Properties

Name Type
rgb ColorRgb

setRgb

void setRgb(number r, number g, number b)

ColorRgb

Definition

interface ColorRgb  {
  b: number;
  g: number;
  r: number;
}
interface ColorRgb  {
  b: number;
  g: number;
  r: number;
}

Properties

Name Type
b number
g number
r number

ColorSettingHsv

Definition

interface ColorSettingHsv  {
  hsv: ColorHsv;

  setHsv(hue: number, saturation: number, value: number): void;
}
interface ColorSettingHsv  {
  hsv: ColorHsv;

  setHsv(hue: number, saturation: number, value: number): void;
}

Example

// set the color to red on a ColorSettingHsv device
colorBulb.setHsv({
    h: 0,
    s: 1,
    v: 1
})
// set the color to red on a ColorSettingHsv device
colorBulb.setHsv({
    h: 0,
    s: 1,
    v: 1
})

Properties

Name Type
hsv ColorHsv

setHsv

void setHsv(number hue, number saturation, number value)

ColorHsv

Definition

interface ColorHsv  {
  h: number;
  s: number;
  v: number;
}
interface ColorHsv  {
  h: number;
  s: number;
  v: number;
}

Properties

Name Type
h number
s number
v number

Notifier

Definition

interface Notifier  {
  sendNotification(title: string, body: string, media: URL|MediaObject, mimeType: string): void;
}
interface Notifier  {
  sendNotification(title: string, body: string, media: URL|MediaObject, mimeType: string): void;
}

Example

// SMS with only text
twilioNumber.sendNotification('Alert!', 'Something Happened!');

// MMS with image
twilioNumber.sendNotification('Alert!', 'Something Happened!', 'http://example.org/image.png', 'image/png');

// text to speech on speakers
googleHomeSpeaker.sendNotification('Title is not not transcribed', 'Something Happened!');

// cast to chromecast
twilioNumber.sendNotification('Alert!', 'Something Happened!', 'http://example.org/video.mp4', 'video');
// SMS with only text
twilioNumber.sendNotification('Alert!', 'Something Happened!');

// MMS with image
twilioNumber.sendNotification('Alert!', 'Something Happened!', 'http://example.org/image.png', 'image/png');

// text to speech on speakers
googleHomeSpeaker.sendNotification('Title is not not transcribed', 'Something Happened!');

// cast to chromecast
twilioNumber.sendNotification('Alert!', 'Something Happened!', 'http://example.org/video.mp4', 'video');

sendNotification

void sendNotification(string title, string body, URL|MediaObject media, string mimeType)

If a the media parameter is supplied, the mime type denotes how to send the media within notification. For example, specify 'image/*' to send a video MediaObject as an image. Passing null uses the native type of the MediaObject. If that is not supported by the notifier, the media will be converted to a compatible type.

StartStop

Definition

interface StartStop  {
  running: boolean;

  start(): void;
  stop(): void;
}
interface StartStop  {
  running: boolean;

  start(): void;
  stop(): void;
}

Example

neatoRobot.start();
setTimeout(() => {
    neatoRobot.stop();
}, 30 * 60 * 10000);
neatoRobot.start();
setTimeout(() => {
    neatoRobot.stop();
}, 30 * 60 * 10000);

Properties

Name Type
running boolean

start

void start()

stop

void stop()

Pause

Definition

interface Pause  {
  paused: boolean;

  pause(): void;
  resume(): void;
}
interface Pause  {
  paused: boolean;

  pause(): void;
  resume(): void;
}

Properties

Name Type
paused boolean

pause

void pause()

resume

void resume()

Dock

Definition

interface Dock  {
  docked: boolean;

  dock(): void;
}
interface Dock  {
  docked: boolean;

  dock(): void;
}

Example

// tell the cleaning robot to dock
neatoRobot.dock();
// tell the cleaning robot to dock
neatoRobot.dock();

Properties

Name Type
docked boolean

dock

void dock()

TemperatureSetting

Definition

interface TemperatureSetting implements Thermometer, HumiditySensor {
  thermostatAvailableModes: ThermostatMode[];
  thermostatMode: ThermostatMode;
  thermostatSetpoint: number;
  thermostatSetpointHigh: number;
  thermostatSetpointLow: number;

  setThermostatMode(mode: ThermostatMode): void;
  setThermostatSetpoint(degrees: number): void;
  setThermostatSetpointHigh(high: number): void;
  setThermostatSetpointLow(low: number): void;
}
interface TemperatureSetting implements Thermometer, HumiditySensor {
  thermostatAvailableModes: ThermostatMode[];
  thermostatMode: ThermostatMode;
  thermostatSetpoint: number;
  thermostatSetpointHigh: number;
  thermostatSetpointLow: number;

  setThermostatMode(mode: ThermostatMode): void;
  setThermostatSetpoint(degrees: number): void;
  setThermostatSetpointHigh(high: number): void;
  setThermostatSetpointLow(low: number): void;
}

Properties

Name Type
thermostatAvailableModes ThermostatMode[]
thermostatMode ThermostatMode
thermostatSetpoint number
thermostatSetpointHigh number
thermostatSetpointLow number

setThermostatMode

void setThermostatMode(ThermostatMode mode)

setThermostatSetpoint

void setThermostatSetpoint(number degrees)

setThermostatSetpointHigh

void setThermostatSetpointHigh(number high)

setThermostatSetpointLow

void setThermostatSetpointLow(number low)

Thermometer

Definition

interface Thermometer  {
  temperature: number;
  temperatureUnit: TemperatureUnit;
}
interface Thermometer  {
  temperature: number;
  temperatureUnit: TemperatureUnit;
}

Properties

Name Type
temperature number
temperatureUnit TemperatureUnit

TemperatureUnit

enum TemperatureUnit {
  C = "C",
  F = "F",
}
enum TemperatureUnit {
  C = "C",
  F = "F",
}
Enum
"C"
"F"

HumiditySensor

Definition

interface HumiditySensor  {
  humidity: number;
}
interface HumiditySensor  {
  humidity: number;
}

Properties

Name Type
humidity number

ThermostatMode

enum ThermostatMode {
  Off = "Off",
  Cool = "Cool",
  Heat = "Heat",
  HeatCool = "HeatCool",
  Auto = "Auto",
  FanOnly = "FanOnly",
  Purifier = "Purifier",
  Eco = "Eco",
  Dry = "Dry",
  On = "On",
}
enum ThermostatMode {
  Off = "Off",
  Cool = "Cool",
  Heat = "Heat",
  HeatCool = "HeatCool",
  Auto = "Auto",
  FanOnly = "FanOnly",
  Purifier = "Purifier",
  Eco = "Eco",
  Dry = "Dry",
  On = "On",
}
Enum
"Off"
"Cool"
"Heat"
"HeatCool"
"Auto"
"FanOnly"
"Purifier"
"Eco"
"Dry"
"On"

Camera

Definition

interface Camera  {
  takePicture(): MediaObject;
}
interface Camera  {
  takePicture(): MediaObject;
}

takePicture

MediaObject takePicture()

VideoCamera

Definition

interface VideoCamera  {
  getVideoStream(): MediaObject;
}
interface VideoCamera  {
  getVideoStream(): MediaObject;
}

getVideoStream

MediaObject getVideoStream()

Lock

Definition

interface Lock  {
  lockState: LockState;

  lock(): void;
  unlock(): void;
}
interface Lock  {
  lockState: LockState;

  lock(): void;
  unlock(): void;
}

Properties

Name Type
lockState LockState

lock

void lock()

unlock

void unlock()

LockState

enum LockState {
  Locked = "Locked",
  Unlocked = "Unlocked",
  Jammed = "Jammed",
}
enum LockState {
  Locked = "Locked",
  Unlocked = "Unlocked",
  Jammed = "Jammed",
}
Enum
"Locked"
"Unlocked"
"Jammed"

PasswordStore

Definition

interface PasswordStore implements Authenticator {
  addPassword(password: string): void;
  getPasswords(): string[];
  removePassword(password: string): void;
}
interface PasswordStore implements Authenticator {
  addPassword(password: string): void;
  getPasswords(): string[];
  removePassword(password: string): void;
}

addPassword

void addPassword(string password)

getPasswords

string[] getPasswords()

removePassword

void removePassword(string password)

Authenticator

Definition

interface Authenticator  {
  checkPassword(password: string): boolean;
}
interface Authenticator  {
  checkPassword(password: string): boolean;
}

checkPassword

boolean checkPassword(string password)

Scene

Definition

interface Scene  {
  activate(): void;
  deactivate(): void;
  isReversible(): boolean;
}
interface Scene  {
  activate(): void;
  deactivate(): void;
  isReversible(): boolean;
}

activate

void activate()

deactivate

void deactivate()

isReversible

boolean isReversible()

If a scene can be reversed, isReversible should return true. Otherwise deactivate will not be called.

Entry

Definition

interface Entry implements EntrySensor {
  closeEntry(): void;
  openEntry(): void;
}
interface Entry implements EntrySensor {
  closeEntry(): void;
  openEntry(): void;
}

Example

// open the garage door
garageDoor.openEntry();
// open the garage door
garageDoor.openEntry();

closeEntry

void closeEntry()

openEntry

void openEntry()

EntrySensor

Definition

interface EntrySensor  {
  entryOpen: boolean;
}
interface EntrySensor  {
  entryOpen: boolean;
}

Properties

Name Type
entryOpen boolean

Battery

Definition

interface Battery  {
  batteryLevel: number;
}
interface Battery  {
  batteryLevel: number;
}

Properties

Name Type
batteryLevel number

MediaPlayer

Definition

interface MediaPlayer  {
  load(media: URL|MediaObject, options: MediaPlayerOptions): void;
  pause(): void;
  play(): void;
  stop(): void;
}
interface MediaPlayer  {
  load(media: URL|MediaObject, options: MediaPlayerOptions): void;
  pause(): void;
  play(): void;
  stop(): void;
}

load

void load(URL|MediaObject media, MediaPlayerOptions options)

pause

void pause()

play

void play()

stop

void stop()

MediaPlayerOptions

Definition

interface MediaPlayerOptions  {
  autoplay: boolean;
  mimeType: string;
}
interface MediaPlayerOptions  {
  autoplay: boolean;
  mimeType: string;
}

Properties

Name Type
autoplay boolean
mimeType string

Online

Definition

interface Online  {
  online: boolean;
}
interface Online  {
  online: boolean;
}

Properties

Name Type
online boolean

Program

Definition

interface Program  {
  run(args: object[]): Promise<object>;
}
interface Program  {
  run(args: object[]): Promise<object>;
}

run

Promise<object> run(object[] args)

Asynchronously run a script given the provided arguments.

SoftwareUpdate

Definition

interface SoftwareUpdate  {
  updateAvailable: boolean;

  checkForUpdate(): void;
  installUpdate(): void;
}
interface SoftwareUpdate  {
  updateAvailable: boolean;

  checkForUpdate(): void;
  installUpdate(): void;
}

Properties

Name Type
updateAvailable boolean

checkForUpdate

void checkForUpdate()

installUpdate

void installUpdate()

BufferConverter

Definition

interface BufferConverter  {
  fromMimeType: string;
  toMimeType: string;

  convert(buffer: Buffer, fromMimeType: string): Promise<Buffer>;
}
interface BufferConverter  {
  fromMimeType: string;
  toMimeType: string;

  convert(buffer: Buffer, fromMimeType: string): Promise<Buffer>;
}

Properties

Name Type
fromMimeType string
toMimeType string

convert

Promise<Buffer> convert(Buffer buffer, string fromMimeType)

Settings

Definition

interface Settings  {
  getSettings(): Setting[];
  putSetting(key: string, value: boolean|number|string): void;
}
interface Settings  {
  getSettings(): Setting[];
  putSetting(key: string, value: boolean|number|string): void;
}

getSettings

Setting[] getSettings()

putSetting

void putSetting(string key, boolean|number|string value)

Setting

Definition

interface Setting  {
  choices: string[];
  description: string;
  key: string;
  placeholder: string;
  readonly: boolean;
  title: string;
  type: string;
  value: string;
}
interface Setting  {
  choices: string[];
  description: string;
  key: string;
  placeholder: string;
  readonly: boolean;
  title: string;
  type: string;
  value: string;
}

Properties

Name Type
choices string[]
description string
key string
placeholder string
readonly boolean
title string
type string
value string

BinarySensor

Definition

interface BinarySensor  {
  binaryState: boolean;
}
interface BinarySensor  {
  binaryState: boolean;
}

Properties

Name Type
binaryState boolean

IntrusionSensor

Definition

interface IntrusionSensor  {
  intrusionDetected: boolean;
}
interface IntrusionSensor  {
  intrusionDetected: boolean;
}

Properties

Name Type
intrusionDetected boolean

AudioSensor

MotionSensor

Definition

interface MotionSensor  {
  motionDetected: boolean;
}
interface MotionSensor  {
  motionDetected: boolean;
}

Properties

Name Type
motionDetected boolean

OccupancySensor

Definition

interface OccupancySensor  {
  occupied: boolean;
}
interface OccupancySensor  {
  occupied: boolean;
}

Properties

Name Type
occupied boolean

FloodSensor

Definition

interface FloodSensor  {
  flooded: boolean;
}
interface FloodSensor  {
  flooded: boolean;
}

Properties

Name Type
flooded boolean

UltravioletSensor

Definition

interface UltravioletSensor  {
  ultraviolet: number;
}
interface UltravioletSensor  {
  ultraviolet: number;
}

Properties

Name Type
ultraviolet number

LuminanceSensor

Definition

interface LuminanceSensor  {
  luminance: number;
}
interface LuminanceSensor  {
  luminance: number;
}

Properties

Name Type
luminance number

PositionSensor

Definition

interface PositionSensor  {
  position: Position;
}
interface PositionSensor  {
  position: Position;
}

Properties

Name Type
position Position

Position

Definition

interface Position  {
  accuracyRadius: number;
  latitude: number;
  longitude: number;
}
interface Position  {
  accuracyRadius: number;
  latitude: number;
  longitude: number;
}

Properties

Name Type
accuracyRadius number
latitude number
longitude number

MediaSource

Definition

interface MediaSource  {
  getMedia(): MediaObject;
}
interface MediaSource  {
  getMedia(): MediaObject;
}

getMedia

MediaObject getMedia()

Get a MediaObject that will be automatically converted for playback on other devices.

MessagingEndpoint

OauthClient

Definition

interface OauthClient  {
  getOauthUrl(): string;
  onOauthCallback(callbackUrl: string): void;
}
interface OauthClient  {
  getOauthUrl(): string;
  onOauthCallback(callbackUrl: string): void;
}

getOauthUrl

string getOauthUrl()

Get the Oauth URL to navigate to in the browser. The redirect_uri parameter is not needed and will be automatically set by Scrypted.

onOauthCallback

void onOauthCallback(string callbackUrl)

When an oauth request by a plugin completes, the callback url, with the code/token, will be passed to this method.

FFMpegInput

Definition

interface FFMpegInput  {
  inputArguments: string[];
}
interface FFMpegInput  {
  inputArguments: string[];
}

Properties

Name Type
inputArguments string[]

EndpointHandler

Definition

interface EndpointHandler  {
  getEndpoint(): string;
}
interface EndpointHandler  {
  getEndpoint(): string;
}

getEndpoint

string getEndpoint()

Get the preferred endpoint of this HTTP/Push/EngineIO handler. Local/development scripts can set this to any value. This is ignored if the plugin is installed via npm: the endpoint will always be the npm package name.

EngineIOHandler

Definition

interface EngineIOHandler implements EndpointHandler {
  onConnection(request: HttpRequest, webSocketUrl: string): void;
}
interface EngineIOHandler implements EndpointHandler {
  onConnection(request: HttpRequest, webSocketUrl: string): void;
}

onConnection

void onConnection(HttpRequest request, string webSocketUrl)

Sample Plugins

All of the official Scrypted plugins are open source, and can be found on Github. The Lifx and Owntracks plugins are recommended starting points for learning how to create your own integrations.