npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

node-js-sensor

v1.1.2

Published

Abstract sensor layer with manager

Downloads

4

Readme

node-js-sensor

TypeScript Latest Version on NPM

Node-Js-Sensor is universal implementation interface for any sensor. It is event-driven object. Including the manager where you can set the timeout, intervals and etc. Manager implementing middleware after successfully readings the sensor.

Install

npm i node-js-sensor

API

Sensor.js

Is event-driven object offering base events and adding listeners for runs the sensor reading

constructor(options)

  • options - include only parameter name only for now.

addData(name, unit): self

  • Adds data object to the sensor which will you use for future purposes. It is create object with name, unit and value properties
  • name - Human name of measured value as like Temperature
  • unit - Unit of measured value as like °C

init(): self

  • This method need to be called first before read() is called. It fires event init

read(): Promise

  • This method returns Promise which check if sensor is initialized, has defined any data and check if actual reading of the sensor is not concurrency reads from past. Finally fire event read where you do your concrete measuring

setLastReadingTime(): self

  • This public method is used for record last measuring time

getLastReadingTime(): Date

  • return last reading time

finish(): void

  • call this method after Sensor reading, it is fire event finish. SensorManager listening on this event for running his middlewares

hasState(state): bool

  • this method returns if Sensor is at state
  • state - one of defined states
const SENSOR_STATE = {
    OFF: 0,
    INIT: 1,
    READ: 3,
    FINISH: 4
}

getReadingTime(): ?int

  • return how long was from fire event read and before fire event finish

isInitialized(): bool

  • return when you call initialize() method

Usage Sensor.js

Sync usage

const NodeJsSensor = require('node-js-sensor');
const sensor = new NodeJsSensor.Sensor({
    name: 'My Custom Sensor'
})

sensor.addData('Temperature', '°C') 
sensor.addData('Humidity', '%')

sensor.on('init', function(sensorCtx) {
    console.log(`[${sensorCtx.name}] Sensor initialized`)
})

sensor.on('read', (sensorCtx) => {
    console.log(`[${sensorCtx.name}] Start reading data ...`)

    sensorCtx.data.get('Temperature').value = (Math.random() * 50).toFixed(2)
    sensorCtx.data.get('Humidity').value = (Math.random() * 100).toFixed(2)

    console.log(`[${sensorCtx.name}] Reading data finished`)
    console.log(`[${sensorCtx.name}] [${sensorCtx.data.get('Temperature').name}] ${sensorCtx.data.get('Temperature').value}${sensorCtx.data.get('Temperature').unit}`)
    console.log(`[${sensorCtx.name}] [${sensorCtx.data.get('Humidity').name}] ${sensorCtx.data.get('Humidity').value}${sensorCtx.data.get('Humidity').unit}`)
})

sensor.init()
    .read()
    .catch(console.log)

Async usage

const NodeJsSensor = require('node-js-sensor');
// async receiving the data
const getFakeData = function() {
    return new Promise((resolve, reject) => {
        setTimeout(function() {
            resolve({
                temperature: (Math.random() * 50).toFixed(2),
                humidity: (Math.random() * 100).toFixed(2)
            })
        }, 5000)
    })
}

const sensor = new NodeJsSensor.Sensor({
    name: 'My Custom Sensor'
})

sensor.addData('Temperature', '°C')
sensor.addData('Humidity', '%')

sensor.on('init', function(sensorCtx) {
    console.log(`[${sensorCtx.name}] Sensor initialized`)
})

sensor.on('read', async (sensorCtx) => {
    return new Promise((resolve, reject) => {
        console.log(`[${sensorCtx.name}] Start reading data ...`)

        getFakeData().then(fakeData => {
            sensorCtx.setLastReadingTime()
            
            sensorCtx.data.get('Temperature').value = fakeData.temperature
            sensorCtx.data.get('Humidity').value = fakeData.humidity

            sensorCtx.finish()
            resolve()
        }).catch(err => {
            sensorCtx.finish()
            reject(err)
        })
    })
})

sensor.on('finish', function(sensorCtx){
    console.log(`[${sensorCtx.name}] Reading data finished`)
    console.log(`[${sensorCtx.name}] [${sensorCtx.data.get('Temperature').name}] ${sensorCtx.data.get('Temperature').value}${sensorCtx.data.get('Temperature').unit}`)
    console.log(`[${sensorCtx.name}] [${sensorCtx.data.get('Humidity').name}] ${sensorCtx.data.get('Humidity').value}${sensorCtx.data.get('Humidity').unit}`)
})

sensor.init()
    .read()
    .catch(console.log)

Output:

> [email protected] example-basic
> node examples/basic/index.js

[My Custom Sensor] Sensor initialized
[My Custom Sensor] Start reading data ...
[My Custom Sensor] Reading data finished
[My Custom Sensor] [Temperature] 48.28°C
[My Custom Sensor] [Humidity] 41.68%

SensorManager.js

Sensor manager is using the class Sensor for repeatedly measuring of our sensor. This class knows to use the middlewares for next operations after reading the sensor data. Middleware are runs when event finish is fired

constructor(Sensor)

  • using the Sensor object as parameter

setTimeout(timeout): self

  • sets when our readings is finished

setInterval(interval, fireAtStart = false): self

  • first parameter is classic interval when our reading is repeated
  • second parameter allows the first run at immediately

setLimit(limit): self

  • allows only concrete runs in loop

use(function(Sensor, next){}): self

  • add middleware which runs after sensor finished reading the data. You can add any middleware you want. You can add middleware for echo, alerting, saving to DB and etc. Your imaginations is your limit ;-)

run(): void

  • runs the measuring in the loop

runOnce(): Promise

  • runs one iteration of our cycle

stop(): void

  • this method stops the manager

getCounter(): int

  • returns how many cycles runs

execute(): void

  • execute added middlewares

Usage SensorManager.js

sensor.addData('Temperature', '°C')
sensor.addData('Humidity', '%')

sensor.on('init', function(sensorCtx) {
    console.log(`[${sensorCtx.name}] Sensor initialized`)
})

sensor.on('read', (sensorCtx) => {
    console.log(`[${sensorCtx.name}] Start reading data ...`)

    sensorCtx.data.get('Temperature').value = (Math.random() * 50).toFixed(2)
    sensorCtx.data.get('Humidity').value = (Math.random() * 100).toFixed(2)

    sensorCtx.setLastReadingTime()
    sensorCtx.finish()
})

sensor.on('finish', function(sensorCtx){
    console.log(`[${sensorCtx.name}] Reading data finished`)
    console.log(`[${sensorCtx.name}] [${sensorCtx.data.get('Temperature').name}] ${sensorCtx.data.get('Temperature').value}${sensorCtx.data.get('Temperature').unit}`)
    console.log(`[${sensorCtx.name}] [${sensorCtx.data.get('Humidity').name}] ${sensorCtx.data.get('Humidity').value}${sensorCtx.data.get('Humidity').unit}`)
})

const sensorManager = new SensorManager(sensor)

sensorManager.setInterval(2000) // repeat every 2s
    .setTimeout(6000) // for 6s
    .setLimit(2)
    .run()

Or you can use setInterval() like this:

// repeat every 2s and start immediately
sensorManager.setInterval(2000, true)
    .setTimeout(6000)

Adding middleware to the SensorManager

Every middleware could receive 2 parameters. First is our Sensor and next() callback

...
// middleware for temperature
sensorManager.use(function(sensorCtx, next){
    console.log(`[${sensorCtx.name}] [${sensorCtx.data.get('Temperature').name}] ${sensorCtx.data.get('Temperature').value}${sensorCtx.data.get('Temperature').unit}`)
    next()
})

// middleware for humidity
sensorManager.use(function(sensorCtx) {
    console.log(`[${sensorCtx.name}] [${sensorCtx.data.get('Humidity').name}] ${sensorCtx.data.get('Humidity').value}${sensorCtx.data.get('Humidity').unit}`)
})

// SensorManager runs
sensorManager.setInterval(2000)
    .setTimeout(10000)
    .run()

Output:

> [email protected] example-full
> node examples/full/index.js

[My Custom Sensor] Sensor initialized
[My Custom Sensor] Start reading data ...
[My Custom Sensor] Sensor reading finished
[My Custom Sensor] [Temperature] 5.14°C
[My Custom Sensor] [Humidity] 8.86%
[My Custom Sensor] Sensor middleware are finished
[My Custom Sensor] Start reading data ...
[My Custom Sensor] Sensor reading finished
[My Custom Sensor] [Temperature] 19.09°C
[My Custom Sensor] [Humidity] 29.50%
[My Custom Sensor] Sensor middleware are finished

Testing

$ npm run example-basic
$ npm run example-basic-async
$ npm run example-full

Credits