Spanish Total.js
English
Documentation For AI agents
Contents

Your first driver

Write a driver for a weather station, install it, create a device and send it test data.

.md Website
On this page

This page builds a driver for a weather station that measures temperature, humidity and battery level. The station posts JSON like this to the stream:

{ "sn": "WS-0001", "temperature": 21.4, "humidity": 48, "battery": 87 }

The driver

Save this as demoweather.html:

<script total>

    exports.id = 'demoweather';
    exports.name = 'Demo weather station';
    exports.manufacturer = 'Example Ltd.';
    exports.icon = 'ti ti-temperature';
    exports.color = '#3B82F6';
    exports.author = 'Jane Doe';
    exports.version = '1';
    exports.config = { offset: 0 };
    exports.inputs = [{ id: 'input', name: 'Input' }, { id: 'interval', name: 'Change interval', html: '<ui-component name="input" path="?.minutes" config="type:number;required:1">Minutes between readings</ui-component>' }];
    exports.outputs = [
        { id: 'temperature', type: 'number', name: 'Temperature', format: '{0} °C', decimals: 1, stats: 'hourly' },
        { id: 'humidity', type: 'number', name: 'Humidity', format: '{0} %', decimals: 0, stats: 'hourly' },
        { id: 'battery', type: 'number', name: 'Battery', format: '{0} %', decimals: 0, stats: 'daily' }
    ];
    exports.offline = '2 hours';
    exports.options = [{ id: 'token', type: 'string', name: 'Token', value: '' }];
    exports.storage = [{ id: 'readings', name: 'Readings', columns: [{ id: 'sn', name: 'Serial number', type: 'string' }, { id: 'temperature', name: 'Temperature', type: 'number' }] }];

    exports.install = function(com) {

        com.schema = '*sn:String,temperature:Number,humidity:Number,battery:Number'.toJSONSchema();

        com.route = ROUTE('POST /demoweather/', function($) {

            if (com.options.token && com.options.token !== $.headers['x-token']) {
                $.invalid(401);
                return;
            }

            var data = com.schema.transform($.body);
            if (data.error) {
                $.invalid(data.error);
                return;
            }

            var payload = data.response;
            var flow = com.main.meta.flow;
            var count = 0;

            for (var key in flow) {
                var instance = flow[key];
                if (instance.component === com.id && instance.meta.sn === payload.sn) {
                    instance.message(instance.newmessage(payload));
                    count++;
                }
            }

            $.json({ count: count });
        });
    };

    exports.uninstall = function(com) {
        com.route && com.route.remove();
    };

    exports.make = function(instance, config) {

        instance.message = function($) {

            if ($.input === 'interval') {
                instance.debug('Interval changed to', $.data.minutes, 'minutes');
                $.destroy();
                return;
            }

            var data = $.data;

            if (data.temperature != null) {
                var temperature = data.temperature + (config.offset || 0);
                instance.newmessage(temperature).send('temperature');
                instance.storage.insert('readings', { sn: data.sn, temperature: temperature });
            }

            if (data.humidity != null)
                instance.newmessage(data.humidity).send('humidity');

            if (data.battery != null) {
                instance.newmessage(data.battery).send('battery');
                if (data.battery < 10)
                    instance.throw('Battery low: ' + data.battery + ' %');
            }

            $.destroy();
        };

        // JSON posted to the stream address /notify/stream-<device id>/
        instance.notify = function(req) {
            if (req.method === 'POST')
                instance.message(instance.newmessage(req.body));
        };

    };

</script>

<settings>
    <div class="padding">
        <div class="grid-4">
            <div class="m">
                <ui-component name="input" path="?.offset" config="type:number">Temperature correction (°C)</ui-component>
            </div>
        </div>
    </div>
</settings>

<readme>
Demo weather station. Send readings to `POST /demoweather/` on the stream. When the driver has a token, send it in the `x-token` header.

{ "sn": "WS-0001", "temperature": 21.4, "humidity": 48, "battery": 87 }

</readme>

The parts in short:

  • exports.id, name, manufacturer, icon, color, author and version describe the driver in the app.
  • exports.outputs creates three sensors for every device: temperature, humidity and battery.
  • exports.config and the <settings> form give each device a temperature correction. See Settings and options.
  • exports.options gives the driver a token, set in Drivers > ... > Settings.
  • exports.install creates the route POST /demoweather/ on the stream. It checks the token and the data, finds the device by its serial number and passes the data on. See Receiving data.
  • exports.make sends each value to its output, keeps every temperature in a storage table, reports a low battery as an alert and handles a command.

Install it

  1. In Admin, open Drivers and select Create.
  2. Replace the template with the content of the file and select SUBMIT.

Create a device

  1. Open Devices and select Create.
  2. Select Demo weather station.
  3. Fill in Name and set Device identifier to WS-0001. Select SUBMIT.
  4. Wait three minutes, or restart the stream, until the id of the device appears on the status page of the stream.

Send test data

Post a reading from a terminal on a computer that reaches the stream. If you set a token in the driver settings, send it in the x-token header:

curl -X POST https://stream.example.com/demoweather/ \
  -H 'Content-Type: application/json' \
  -H 'x-token: your-token' \
  -d '{"sn":"WS-0001","temperature":21.4,"humidity":48,"battery":87}'

The stream answers with the number of devices that received the reading:

{"count":1}

An answer of {"count":0} means that no device has this serial number, or that the stream has not loaded the device yet. A wrong token answers 401, and invalid data answers with the error of the field:

[{"name":"sn","error":"The field \"sn\" is invalid","path":"sn"}]

Check the result

Open Sensors or the device detail. The three sensors are online and show 21.4 °C, 48 % and 87 %. Send a few more readings with other values and open the history of a sensor.

To send many readings without typing them, use Simulations.

Made in Europe