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

energy-meter-reader-websocket-client

v1.3.0

Published

An abstract websocket client manager for connecting to and interfacing with energy meter reading devices from Notima Energy Intelligence

Downloads

5

Readme

Abstract Websocket client manager for Energy Meter Readers

An abstract websocket client manager for interfacing with Energy Meter Reader devices from Notima Energy Intelligence. The abstraction is made in order to be able to use with various Websocket engines.

The npm packages energy-meter-reader-websocket-client-browser and energy-meter-reader-websocket-client-node contain two different implementations.

The purpose of the client manager class is to:

  • create a websocket connection to an electricity meter reader
  • keep the connection alive
  • notify suscribers of any updates
  • reconnect if the connection is lost

How the client manager works

A client is created simply by calling the constructor for EMRWebsocketClientManager. The client will connect automatically to the address passed to the constructor and will attempt to reconnect if the connection is lost. You can then create callback functions to be executed when certain messages are recieved on the websocket connection. All messages are JSON formatted so when registering a callback, you need to pass a JSON key to subscribe to. The callback will then be executed when the key is present with the value as argument.

Before any messages are sent from the server, the client needs to tell the server what messages to send this can be done as the following example suggests:

client.send({
    connection: {
        statusUpdate: true|false,
        dataUpdate: true|false,
        log: true|false
    }
});

The helper functions addStatusHandler, addDataHandler, and addLogHandler exist to simplify the process of requesting and subscribing to messages. These functions will subscribe to their corresponding keys and request them from the server automatically if needed.

Example usage

this.wsClient = new EMRWebsocketClientManager(address, (ev: Event) => {
    console.log("Websocket connection opened");
}, (ev: Event) => {
    console.log("Websocket connection closed");
});

this.wsClient.addDataHandler((data) => {
    console.log(`Data received: ${data.topic} ${data.value} ${data.unit}`)
});

In the example above, a websocket client is being created and the onOpen and onClosed callbacks are defined as lambda functions. A data handler is then added to the client with a callback defined. This will activate data updates from the server on this connection.

EMRWebsocketClientManager functions

the following sections explains the functions of the client class more in depth.

constructor

Create a client manager and connect to the websocket server

Parameters:

  • address: string - The address of the websocket server (the energy meter reader device. e.g. ws://address:port).
  • onOpen: (ev: Event): void - The callback that is executed when a connection is opened.
  • onClose: (ev: Event): void; - The callback that is executed when a connection is closed.

Example:

client = new EMRWebsocketClientManager("ws://192.168.4.1/ws", (ev: Event) => {
    console.log("Websocket connection opened");
}, (ev: Event) => {
    console.log("Websocket connection closed");
});

stop

Kills the client manager by closing the connection without attempting to reopen.

subscribe

Create a subscriber. The subscriber callback function will be called when the corresponding key is present in a websocket message (in json format).

It is recommended to use one of the helper functions: addStatusHandler, addDataHandler or addLogHandler instead of calling this function directly.

Parameters:

  • key: string - The JSON key that will trigger the callback.
  • callback: (data: any): void - The callback function that will be executed (with the value of the subscribed json key as argument).

Example:

client.subscribe("data", (data) => {
    console.log("Data received")
});

send

This function sends a message to the server. The object passed will be JSON stringified and transmitted as a string.

It is recommended to use one of the helper functions: addStatusHandler, addDataHandler or addLogHandler instead of calling this function directly.

Parameters:

  • data: any - The message to send. This will be JSON stringified so javascript objects are expected.

Example:

client.send({
    connection: {
        statusUpdate: true
    }
});

addStatusHandler

This is a helper function for automatically requesting and subscribing to status updates.

Parameters:

  • callback: (status: EMRStatus): void - The callback function for handling status updates.

Example:

client.addStatusHandler((status) => {
    console.log(`Status update received`)
});

addDataHandler

This is a helper function for automatically requesting and subscribing to data updates.

Parameters:

  • callback: (data: EMRDataPoint): void - The callback function for handling data updates.

Example:

client.addStatusHandler((data) => {
    console.log(`New energy meter readings received`)
});

addLogHandler

This is a helper function for automatically requesting and subscribing to system logs.

Parameters:

  • callback: (log: string): void - The callback function for handling log entries.

Example:

client.addLogHandler((log) => {
    console.log(`System log: ${log}`)
});

How to implement

import { EMRWebsocketClientManagerManager } from "nergy-meter-reader-websocket-client";

export class EMRWebsocketClientManagerImpl extends EMRWebsocketClientManagerManager {

    protected isConnectionOpen(): boolean {
        // return `true` if the websocket status is open
    }

    protected isConnectionClosed(): boolean {
        // return `true` if the websocket status is closed
    }

    protected openConnection(address: string): void {
        // Open a connection to `address` and setup callbacks.
        // The following functions must be called by the websocket engine:
        // `this.onConnectionOpen()` - when the connection is opened
        // `this.onConnectionClose()` - when the connection is closed
        // `this.onConnectionMessage(data: string)` - when a message is received on the connection
        // There should also be a mechanism for pinging the server to ensure a stable connection
        // Close the connection if no pong frames are returned.
    }

    protected closeConnection(): void {
        // close the connection
    }
    
    protected sendMessage(data: string): void {
        // send data on the connection. 
        // There is no need to check if the connection is open. This has already been done at this point.
    }
}

Implementations:

energy-meter-reader-websocket-client-browser

Github | NPM

This is an implementation that uses the built in browser api for websockets. It is lightweight and contain no other dependencies than the abstract package

energy-meter-reader-websocket-client-node

Github | NPM

This implementation can be used for Node.js applications and uses the w3cwebsocket api.