thing.js

Create thing objects with properties, actions, and events. Use for IoT devices or even living things like plants.

Thing.js

Thing.js exports a single class 'Thing,' which is an extension of the Node.js EventEmitter Classand basic methods for:

  • Updating properties
  • Calling methods
  • Emiting events for either of the above.

Full documentation available here.

For example of how this can be used in an IoT stack, checkout Grow.jsor the thing.js CoAP branch.

Install

npm install Thing.js

Usage

Include Thing.js:

const Thing = require('Thing.js');

Make a new thing and pass in an object.

const Light = new Thing({
  // Properties can be set by the API
  properties: {
    state: null,
  },

  turn_light_on: function () {
    console.log('light on');
    Light.set('state', 'on');
  },

  turn_light_off: function () {
    console.log('light off');
    Light.set('state', 'off');
  }
});

// Things are an extension of the node EventEmitter class 
// Thus have the same API
Light.on('property-updated', function(key, value) {
  console.log('Light turned ' + value);
});

// Calling a method emits an event
Light.call('turn_light_on');
// light on
// Light turned on.

Initialize

Things can optionally have an initializeor startfunction which runs when the thing is constructed:

const testThing = new Thing({
  initialize: function () {
    console.log('testThing initialized');
  }
});
// testThing initialized

Connection options

The connect method takes a configuration object.

The hostproperty is where the device will connect to a Grow-IoT instance. By default the hostis set to localhostand the port is set to Meteor's standard of 3000. This works nicely for usb devices like Arduino.

For connecting over wifi, connect your device to wifi and set the hostto the IP address where the Grow-IoT instance is running. Pass the options to the connect()method like so:

grow.connect({
    "host": "YOUR_IP_HERE"
})

Connecting over SSL

You can connect securely to our Grow-IoT alpha instance on https://grow.commongarden.org, or see the Grow-IoT repoto easily start your own IoT network locally or hosted on Meteor Galaxy.

SSL is supported though will require a bit more setup. If you are hosting your instance off a computer with a dedicated IP address pass the following the connect()method.

grow.connect({
    "host": "YOUR_IP_HERE",
    "port": 443,
    "ssl": true
})

If you are hosting on a cloud instance such as Meteor Galaxy, you might need specify the servername. The example below shows you how to connect securely to the instance at grow.commongarden.org:

grow.connect({
    "host": "grow.commongarden.org",
    "tlsOpts": {
        "tls": {
            "servername": "galaxy.meteor.com"
        }
    },
    "port": 443,
    "ssl": true
});

Connect to Grow-IoT Instance

In Grow-IoT, create a new device and take note of the device uuidand token.

In the examplesfolder checkout test-device.js. If you want to get started straight away with hardware, skip to the working with hardwaresection.

Replace the uuidand tokenproperties of the config object with the credentials you generate.

// Import the latest build of the Grow.js library
var Thing = require('Grow.js');

// Create a new grow instance. Connects by default to localhost:3000
var testDevice = new Thing({
    // PUT YOUR UUID AND TOKEN HERE:
    uuid: 'PASTE_UUID_HERE',
    token: 'PASTE_TOKEN_HERE',

    // Specifies the component associated with the thing
    component: 'TestDevice',

    // Properties can be updated by the API
    properties: {
        state: 'off',
    },

    turn_on: function () {
        testDevice.set('state', 'on');
    },

    turn_off: function () {
        testDevice.set('state', 'off');
    },
});

// Connects to localhost:3000 by default.
testDevice.connect();

Run it with:

node examples/test-device.js
Working with hardware.

Grow.js works very well with the Johnny-Five robotics library, which has plugins for a large number of devices.

Note, with boards like the Tessel 2, Johnny-five is not required, but we're including it to make it easier to get started and support a wide variety of devices, sensors, and actuators.

Wire up photo-resitor and led to arduino

Wire up your photo resistor and LED light like so:

To use Johnny-Five, you need to make sure that your arduino is flashed with Standard Firmata. Instructions for doing so can be found here. Once that's done you're ready for the next step!

Take a look at the smart-lightexample in the examples/arduino/folder.

Create a new thing in the Grow-IoT ui and copy and paste the UUID and Token into the example below.

// Require the Grow.js build and johnny-five library.
var Thing = require('Grow.js');
var five = require('johnny-five');

// See http://johnny-five.io/ to connect devices besides arduino.
var board = new five.Board();

var emit_and_analyze;

// When board emits a 'ready' event run this start function.
board.on('ready', function start() {
    // Define variables
    var LED = new five.Pin(13),
        lightSensor = new five.Sensor('A0');

    // Create a new thing.
    var light = new Thing({
        uuid: 'PASTE_UUID_HERE',
        token: 'PASTE_TOKEN_HERE',

        component: 'SmartLight',

        properties: {
            state: 'off',
            threshold: 300,
            interval: 1000,
            lightconditions: null
        },

        start: function () {
            var interval = this.get('interval');

            emit_and_analyze = setInterval(function () {
                light.call('light_data');
                light.call('check_light_data');
            }, interval);

            // Todo: implement clear interval function so we can adjust
            // the rate at which data is logged.
        },

        stop: function () {
            clearInterval(emit_and_analyze);
        },

        turn_on: function () {
            LED.high();
            light.set('state', 'on');
            console.log('light on');
        },

        turn_off:  function () {
            LED.low();
            light.set('state', 'off');
            console.log('light off')
        },

        light_data: function () {
            console.log(lightSensor.value);

            light.emit({
              type: 'light',
              value: lightSensor.value
            });
        },

        check_light_data: function () {
            var threshold = light.get('threshold');
            if ((lightSensor.value < threshold) && (light.get('lightconditions') != 'dark')) {
                light.set('lightconditions', 'dark');
            } else if ((lightSensor.value >= threshold) && (light.get('lightconditions') != 'light')) {
                light.set('lightconditions', 'light');
            }
        }
    });

    light.connect();
});

Run smart-light.jswith:

node examples/arduino/smart-light/smart-light.js

Note: on certain opperating systems you may need to prefix that command with sudoto allow the script access to USB.

Things as modules

If you want to make more complex things you may want to organize them into modules. Here's an example for a hypothetical software-light.js:

const Thing = require('Thing.js');

module.exports = new Thing({
  metadata: 'We can include metadata like so',

  properties: {
    name: "Light"
  },

  initialize: function () {
    console.log('Light initialized');
  },

  turn_on: function () {
    console.log("Light on");
  },

  turn_off: function () {
    console.log("Light off");
  }
});

Then you can import them with require()and even use them inside other things!

const softwareLight = require('./software-light.js');
// Light initialized

const growRoom = new Thing({
  // Optional: you may want to do this if you want the properties of 
  // softwareLight to be discoverable by Grow-IoT.
  light: softwareLight,

  initialize: function () {
    softwareLight.call('turn_on');
    this.light.call('turn_off');
  }
});
// Light on
// Light off

See the examples folder for more!

Developing

Code is written in ES6, and compiled using rollup. Full documentation is available here.

npm run buildbuilds the library.

npm run testbuilds the library, and runs tests in the test folder.

The documentation is written in jsdoc, built using Mr-Doc, and kept on the gh-pages branch of this repo.

HomePage

https://github.com/CommonGarden/Thing.js

Repository

https://github.com/CommonGarden/Thing.js


上一篇:hs100-api
下一篇:telismo

相关推荐

  • 🙋Hanjst汉吉斯特改进+enSafeExpression安全表达式等

    Hanjst汉吉斯特模版语言及模版引擎,近期持续改进升级。 这次改进主要是增加了对安全输出表达式兼容,由于涉及到对软件开发过程中的效率和软件运行效率的平衡和取舍,所以多写了几句,以描述这个权衡利弊对...

    15 天前
  • 🙋Hanjst汉吉斯特升级:+showImageAsync及性能改进等

    自2019年元旦🙋Hanjst汉吉斯特 模板语言及其编译引擎发布,已经过去一年多了。 这期间随着 🙋Hanjst汉吉斯特 的推广应用,我们也陆续发布了如下一些更新内容: 🛠️Hanjst/汉吉...

    2 个月前
  • 😉我用 Nuxt.js 仿了个掘金

    前言 首先肯定是要夸夸掘金啦,最开始从 CSDN 到 博客园 再到 掘金,个人感觉掘金的技术氛围非常的nice,真是个宝藏社区👏。技术文章大多以前端为主,对前端开发者非常友好,质量也是歪瑞古的。

    25 天前
  • 😀一个原生js弹幕库

    danmujs 😀一个原生js弹幕库,基于 CSS3 Animation 地址、核心代码 本项目基于 rcbullets,项目约70%的代码基于rcbullets,首先要感谢这个项目的作者,如...

    4 个月前
  • 🕵️‍♀️由原型到JS中的“模拟类”

    讲述了有关 JavaScript 中原型相关知识,又引出了 JavaScript 中的“类“究竟是什么?,以及一系列相关问题。 一、前置知识 1、JavaScript 的面向对象(OOP) ​ 面向...

    2 个月前
  • 🔥《吊打面试官》系列 Node.js 必知必会必问!

    (/public/upload/f204a3b224d986128f1b4d9b8d06cd17) 前言 codeing 应当是一生的事业,而不仅仅是 30 岁的青春🍚 本文已收录 Git...

    3 个月前
  • 💖CSS + JS 送学妹满屏幕小爱心

    故事开始 午饭时间,暗恋已久的学妹拉着我的衣袖:“学长学长,你能不能让这些爱心变成五颜六色的吗~”。 我在旁边笑开了花~~~ image.png(/public/upload/04aaa24e...

    1 个月前
  • (vuejs学习)2、使用ElementUI(*)

    1.element安装 开发环境是win10,一到node官网下载node的.msi包(https://npm.taobao.org/mirrors/node/v10.16.0/nodev10.16....

    10 个月前
  • (vuejs学习)1、Vue初上手(*)

    参考《官方(https://cli.vuejs.org/zh/guide/installation.html)》官方: Node 版本要求: Vue CLI 需要 Node.js 8.9 或更高...

    10 个月前
  • 黄金搭档 -- JS 装饰器(Decorator)与Node.js路由

    很多面对象语言中都有装饰器(Decorator)函数的概念,Javascript语言的ES7标准中也提及了Decorator,个人认为装饰器是和一样让人兴奋的的变化。

    1 年前

官方社区

扫码加入 JavaScript 社区