Introduction
Welcome to the EKM METERING API!
We at EKM see easy access to your data, and the scalable systems behind the EKM Push, as crucial to moving our products into the future. To that end, we do what is unheard of in our industry, we give you your data for FREE.
The EKM API is organized around Representational State Transfer, or REST. You can use our Application Programming Interface, or API, to access EKM API endpoints, which can get you information on various EKM Push meter/ioStack data and utilize it in your own application, database, billing system, or building automation system.
We have language bindings in Shell (cURL), Ruby, Python, PHP, Perl, Java, Javascript and Nodejs! You can view code examples in the dark area to the right, and you can switch the programming language of the examples with the tabs in the top right.
Our API is designed to have predictable, resource-oriented URLs and to use HTTP response codes to indicate API errors. We use built-in HTTP features, like HTTP authentication and HTTP verbs, which can be understood by off-the-shelf HTTP clients, and we support cross-origin resource sharing to allow you to interact securely with our API from a client-side web application (though you should remember that you should never expose your secret EKM Push API key in any public website’s client-side code). JSON will be returned in all responses from the API, including errors (though if you’re using API bindings, we will convert the response to the appropriate language-specific object).
Authentication
To authorize, make sure to use your personal EKM Push account key.
The examples in this API documentation use the demo key of MTAxMDoyMDIw. Please make sure you remove this key and place your personal key in the https address if you are trying to access the meters in your account.
With shell, you can just pass the correct address with each request
curl -s "URL Here"
Authorization: "EKM Push Key"
# Ruby Version: 3.1.2
# Load required modules
require 'net/http'
require 'json'
require 'uri'
# Call the call_api method to create a usable
# object named api_object from the API request URI
# Put the API request URI in the call
def call_api(api_path)
uri = URI.parse("URL Here#{api_path}")
response = Net::HTTP.get_response(uri)
puts response.uri
JSON.parse(response.body)
end
# Call the call_api method to create a usable
# object named api_object from the API request URI
# Put the API request URI in the call
# URI only NOT URL - Do not include for example https://summary.ekmpush.com
api_object = call_api('URI Here')
# This just displays the object but you can use what ever
# code you would like to work with the object here
require 'pp'
pp api_object
'''
Python version: 3.9.12
'''
# Required Python Modules
import urllib.request
import urllib.error
import urllib.parse
import json
import pprint
# This function accesses the api_request URL and converts
# the contents to a usable Python object and returns it
def call_api ( api_request ):
'''
Make http request
'''
response = urllib.request.urlopen(api_request)
response = response.read()
json_object = json.loads(response.decode())
return json_object
# Call the call_api function to create a usable
# object named api_object from the API request URL.
# Put the API request URL in the call
api_object = call_api("URL Here")
# This just displays the object but you can use what ever
# code you would like to work with the object here
pprint.pprint(api_object)
<?php
// PHP 8.0.17 (cli)
// Call the callApi function to create a usable
// object named $apiObject from the API request URL.
// Put the API request URL in the call
$apiObject=callApi('URL Here');
// This just displays the object but you can use what ever
// code you would like to work with the object here
var_dump($apiObject);
// This function accesses the apiRequest URL and converts
// the contents to a usable PHP object and returns it
function callApi ($apiRequest='') {
$json=@file_get_contents($apiRequest);
$jsonObject=json_decode($json);
return ($jsonObject);
}
?>
#!/usr/bin/perl
# Perl version: v5.34
# CPAN.pm version 2.2
# Perl Modules Version:
# JSON: 4.05
# LWP::Protocol::https: 6.10
# LWP::Simple: 6.62
#
# OS Prerequisites
# UBUNTU
# apt install cpanminus
#
# Install Perl Modules
# cpan LWP::Simple
# cpan LWP::Protocol::https
# cpan JSON
# Required Perl Modules
use strict;
use warnings;
use LWP::Simple;
use JSON;
use Data::Dumper;
# This function accesses the api_request URL and converts
# the contents to a usable Perl object and returns it
sub call_api {
my $api_request = shift;
my $json_text = get($api_request);
my $json_object = JSON->new->utf8->decode($json_text);
return $json_object;
}
# Call the call_api function to create a usable
# object named api_object from the API request URL.
# Put the API request URL in the call
my $api_object = call_api('URL Here');
# This just displays the object but you can use what ever
# code you would like to work with the object here
print Dumper($api_object); ## no critic (InputOutput::RequireCheckedSyscalls)
/*
openjdk version "17.0.2" 2022-01-18
Download the correct org.json jar version for your
needs from: https://mvnrepository.com/artifact/org.json/json
This example uses version 20220320 accessible here:
https://repo1.maven.org/maven2/org/json/json/20220320/json-20220320.jar
Instructions to run this program
1. Put this code in a file named EKM.java
2. Copy the downloaded org.json jar and EKM.java to the same directory
3. Compile
javac -cp .:./json-20220320.jar ./EKM.java
4. Run
java -cp .:./json-20220320.jar EKM
*/
//Import required classes
import java.net.*;
import java.io.*;
import org.json.*;
@java.lang.SuppressWarnings({"java:S106", "java:S112", "java:S125"})
public class EKM {
public static JSONObject callApi(String apiRequest) throws Exception {
// This code accesses the apiRequest URL and converts
// the contents to a usable JSON object
URL url = new URL(apiRequest);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return new JSONObject(response.toString());
}
public static void main(String[] args) throws Exception {
/*
Call callApi to create a usable
object named apiObject from the API request URL.
Put the API request URL in the call
*/
JSONObject apiObject = EKM.callApi("URL Here");
/*
You can access any part of the apiObject using code like this:
JSONArray readData = apiObject.getJSONObject("readmeter").getJSONArray("ReadSet").
getJSONObject(0).getJSONArray("ReadData");
*/
// This just outputs the whole apiObject
System.out.println(apiObject.toString(4));
}
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// The example function is called from the
// body tag when the page loads
function example(){
// Call the callApi function to create a usable
// object named apiObject from the API request URL.
// Put the API request URL in the call
callApi('URL Here',function(apiObject){
// This just displays the object in the result div
// you can use what ever code you would like to work
// with the object here
document.getElementById("result").innerHTML = "<pre>"+JSON.stringify(apiObject, null, 4)+"</pre>";
});
};
// This code accesses the apiRequest URL and converts
// the contents to a usable JSON object named apiObject
function callApi(apiRequest,callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var jsonObject = JSON.parse(xhttp.responseText);
callback(jsonObject);
}
};
xhttp.open("GET", apiRequest, true);
xhttp.send();
}
</script>
</head>
<body onload="example()">
<div id="result"/>
</body>
</html>
/*
* Requirements
* NodeJS: v16.14.2
* Axios: 0.27.2
*/
// Load modules
const axios = require('axios');
const apiClient = axios.create({
baseURL: 'URL Here',
timeout: 1000 * 15,
})
// This code accesses the apiRequest query and
// logs the response data or the error
;(async () => {
try {
const res = await apiClient.get('URI Here');
const apiResData = res.data;
console.log(JSON.stringify(apiResData, null, 2));
} catch (error) {
console.error(error.message);
}
})();
Make sure to replace the sample key: MTAxMDoyMDIw, with your API key in the https address.
EKM uses API keys to allow access to the API. You authenticate to the EKM API by providing one of your unique API keys in each request. Each Push account holder is provided with an EKM Push User Key, which provides access to all meters in their account. This key carries lots of privileges so we encourage you to keep it secret. In addition to this master key, additional keys are also provided to give access to each meter/ioStack individually, and keys can be created to provide access to sub groups of meters/ioStacks upon request. These secondary keys can be used to share single meters/ioStacks, or a subset of meters/ioStacks, without sharing access to all meters/ioStacks in an account. For example, if you are a landlord with multiple rentals and meters/ioStacks, you could share specific meter/ioStack keys with each of your tenants, so that they could have access to only the data that pertains to their usage.
Authentication to the API occurs via HTTP Basic Auth. Provide your API key as the basic authorized username. You do not need to provide a password. You must authenticate for all requests.
The EKM Push API expects the API key to be included in all requests to the server. The key is included in the URL in the following way:
Authorization: key=MTAxMDoyMDIw
Realtime API
Click here to go to Realtime Documentation
If you are developing your own app, cloud-to-cloud solution, billing system, or other SAS solution, our Real-Time API allows you to easily access your EKM Push data in any format that you need. Below you will find descriptions regarding how to access the data, and about the filters you can apply so the data comes to you in a format that is easily digested and inserted into your software solution.
The real-time API provides the 1,000 latest meter readings for each of your meters/IOStack devices. If your device is being read once per minute, the data will be made available once per minute, per device. Whether you have one device or 10,000 devices, this is the easiest and most scalable way to access your data.
The EKM Dash, EKM Widget, encompass.io, wattvision.com, pvoutput.org, the other solutions in our Push App Store, as well as other customers that have their own custom solutions, all use this API to access their data. We use the same API as you and do not give ourselves any special permissions, we see what you see, which forces us to make the API as great as possible for everyone. We have even given you code examples that can be copy and pasted into your own software language to make the data access that much easier.
Use the API definition, metered values definition, code snippet suggestion, and guide to get you on your way to developing your next killer app. If you create something great, let us know; we’re open to adding all useful apps into the Push App Store.
We also have a Realtime API Request Builder Tool found here:
Account API
Click here to go to Account API Documentation
This API provides information for accounts and devices owned by the account.
Get information for the specified target, which can be account, gateway, meter or ioStack.
You could make API request with the EKM Push Key that is your own Authorization Key that you received for your Push Account, or instead the EKM Push Key you could use Gateway Key for more restricted access. Be aware that if you use the Gateway Key, you will only receive information regards to that gateway.
Gateway Settings API
Click here to go to Gateway Settings API Documentation
This API is used to send commands and settings to devices connected to a Push3 gateway as well as the gateway device itself.
Trigger API
Click here to go to Trigger API Documentation
A REST API to lookup/create/update/delete triggers.
EKM Push3 gateway triggers are among the most powerful tools that EKM offers. You can automate how and when the EKM Push system reacts to metered values. For example, you can have the Push gateway send you an email, send a webhook to your server, or control a relay to turn on/off a switch or close a valve based on the metered data. Push3 gateways can trigger specific actions based on conditions you set up. These triggers reside on the Push3 gateways, allowing them to function even without an internet connection. Triggers can control the relays on v.4 Omnimeters to turn devices on or off, send webhooks to alert your software system, or email you notifications. You can set up new triggers in the Account Portal or via web APIs.
Please note: v.3 Omnimeters do not have controllable relays, so relay triggers will not work, but email triggers will.
Summary API [LEGACY]
Click here to go to Summary Documentation
Our Summary API takes every Real-Time read, over 15 minute time periods, and summarizes them into single 15 minute summaries. We store this data forever to provide a long term historical dataset for each meter. Our system can then combine these summaries together to summarize hours, days, weeks, and months. This dataset is often the best way to get historical values like kWh, pulse counts, etc. It also provides averages, min. and max. values, difference, and more. We make this data available to you via our Summary API in a very similar way to our Real-Time API.
You can use the Summary API definition to access the data you need, from 15 minutes to years of data. We have gone to great lengths to provide this data for free in order to add value to our metering systems. The Summary API, the Real-Time API, great affordable hardware, and scalable access to your data are all components of the most powerful, and highest value metering system available in the world.
We also have a Summary API Request Builder Tool found here: Summary API Builder
Summary V2 API
Click here to go to Summary V2 Documentation
Summary V2 API is a new set of summary features, such as First/Last to get the first and/or last reported date for the given meter(s)/ioStack(s), GStat for getting the status of one or more gateways, IOStack for getting information from new sensors, and more.
The API V2 summary and documentation are currently in beta, signifying that they are subject to changes and updates. It’s important to note that the API V2 calls and specifications provided in this documentation may undergo modifications as the beta phase progresses. Users should stay informed and regularly check for updates to ensure compatibility and adherence to the latest specifications
MQTT Messaging
MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for low-bandwidth, high-latency, or unreliable networks, often used in Internet of Things (IoT) applications. It follows a publish-subscribe model, where devices (clients) can publish messages to topics or subscribe to topics to receive messages.
MQTT will only work with Push3 Gateways. It is more efficient than making hundreds of API calls because it does not impose rate limits (you can stream 24/7), allowing continuous realtime or summary data streaming. However, it lacks message history, meaning that if you need past data, you will have to make an API request to retrieve realtime or summary information as far back as necessary, and then resume streaming via MQTT. If the connection is lost, you will need to request realtime or summary data again to fill in any gaps before continuing with the MQTT stream. This combination of API and MQTT helps ensure a smooth data flow while compensating for potential disruptions.
MQTT Realtime
MQTT Request
# Install mosquitto-clients
sudo apt install mosquitto-clients
# Run:
mosquitto_sub -h mqtts.ekmpush.com -p 8883 -t realtime/NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ -u NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ
# Ruby Version: 3.0.2p107
# Install mqtt:
# sudo gem install mqtt
require 'mqtt'
require 'json'
# Provide MQTT Paramaters
gateway_key = 'NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ'
host = 'mqtts.ekmpush.com'
port = 8883
topic = 'realtime/' + gateway_key
username = gateway_key
# Subscribe to the MQTT topic
MQTT::Client.connect(
host: host,
port: port,
username: username,
ssl: true
) do |client|
client.get(topic) do |topic, message|
puts "\nTopic: #{topic}"
puts "Message: #{message}"
# Parse the message as JSON
data = JSON.parse(message)
# Extract the kWh_Tot value for Meter 10389.
meter_data = data['meter_000000010389']
if meter_data
puts "\n==========================================="
kwh_tot = meter_data['kWh_Tot']
puts "kWh Total: #{kwh_tot}"
puts "===========================================\n"
end
end
end
'''
Python version: 3.10.12
'''
# Install require module:
# pip install paho-mqtt
# Required Python Modules
import json
import warnings
import paho.mqtt.client as mqtt
# Suppress DeprecationWarnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# MQTT Configuration
GATEWAY_KEY = "NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ"
MQTT_BROKER = "mqtts.ekmpush.com"
MQTT_PORT = 8883
MQTT_TOPIC = f"realtime/{GATEWAY_KEY}"
MQTT_USERNAME = GATEWAY_KEY
# Callback when the client connects to the broker
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
# Subscribe to the desired topic
client.subscribe(MQTT_TOPIC)
# Callback when a message is received
def on_message(client, userdata, msg):
print(f"\nTopic: {msg.topic}")
try:
# Parse the message as JSON
data = json.loads(msg.payload.decode('utf-8'))
print("Message:")
print(data)
# Extract the kWh_Tot value for Meter 10389.
meter_key = "meter_000000010389" # Get the first key
meter_data = data.get(meter_key)
if meter_data:
print("\n====================================")
kwh_tot = meter_data.get('kWh_Tot')
print(f"kWh Total: {kwh_tot}")
print("====================================\n")
except json.JSONDecodeError:
print("Failed to decode JSON message.")
# Create an MQTT client instance
mqttClient = mqtt.Client()
# Set username and password for the broker (if needed)
mqttClient.username_pw_set(MQTT_USERNAME)
# Assign the callback functions
mqttClient.on_connect = on_connect
mqttClient.on_message = on_message
# Connect to the MQTT broker
mqttClient.tls_set() # Use TLS for secure connection
mqttClient.connect(MQTT_BROKER, MQTT_PORT, 60)
# Start the MQTT client loop
try:
mqttClient.loop_forever()
except KeyboardInterrupt:
print("Disconnecting from the broker...")
mqttClient.disconnect()
<?php
// Download the phpMQTT library from: https://github.com/bluerhinos/phpMQTT
// Include the phpMQTT library
require('phpMQTT.php');
use Bluerhinos\phpMQTT;
// MQTT Configuration
$GATEWAY_KEY = 'NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ';
$MQTT_BROKER = 'mqtts.ekmpush.com';
$MQTT_PORT = 8883;
$MQTT_TOPIC = "realtime/$GATEWAY_KEY";
$MQTT_USERNAME = $GATEWAY_KEY;
$MQTT_CAFILE = "/etc/ssl/certs/ca-certificates.crt";
// Create an MQTT client instance
$mqtt = new phpMQTT($MQTT_BROKER, $MQTT_PORT, uniqid(), $MQTT_CAFILE);
// Connect to the MQTT broker
if(!$mqtt->connect(true, NULL, $MQTT_USERNAME, NULL)) {
exit(1);
}
$topics[$MQTT_TOPIC] = array('qos' => 0, 'function' => 'procMsg');
$mqtt->subscribe($topics, 0);
while($mqtt->proc()) {
}
$mqtt->close();
function procMsg($topic, $msg){
echo "Topic: {$topic}\n\n";
echo "$msg\n\n";
$data = json_decode($msg, true);
// Extract the kWh_Tot value for Meter 10389
$meterKey = 'meter_000000010389';
if (isset($data[$meterKey])) {
$meterData = $data[$meterKey];
$kwhTot = $meterData['kWh_Tot'];
echo "\n====================================\n";
echo "kWh Total: $kwhTot\n";
echo "====================================\n\n";
}
}
#!/usr/bin/perl
# Perl version: v5.34
#
# OS Prerequisites
# UBUNTU
# apt install cpanminus
#
# Install Perl Modules
# cpan Net::MQTT::Simple
# cpan Try::Tiny
# cpan JSON
use strict;
use warnings;
use Net::MQTT::Simple::SSL;
use JSON;
use Try::Tiny;
use Data::Dumper; # For printing the contents of complex structures
# MQTT Configuration
my $GATEWAY_KEY = "NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ";
my $MQTT_BROKER = "mqtts.ekmpush.com";
my $MQTT_PORT = 8883;
my $MQTT_TOPIC = "realtime/$GATEWAY_KEY";
my $MQTT_USERNAME = $GATEWAY_KEY;
my $MQTT_PASSWORD = ''; # You can set a password if needed
# Callback when a message is received
sub on_message {
my ($topic, $message) = @_;
print "\nTopic: $topic\n";
try {
# Parse the message as JSON
my $data = decode_json($message);
print "Message:\n";
print Dumper($data); # This will pretty-print the entire decoded JSON structure
# Extract the kWh_Tot value for Meter 10389
my $meter_key = "meter_000000010389";
my $meter_data = $data->{$meter_key};
if ($meter_data) {
print "\n====================================\n";
my $kwh_tot = $meter_data->{'kWh_Tot'};
print "kWh Total: $kwh_tot\n";
print "====================================\n";
}
}
catch {
print "Failed to decode JSON message: $_\n";
};
}
# Create MQTT client with SSL/TLS
my $mqtt = Net::MQTT::Simple::SSL->new("$MQTT_BROKER:$MQTT_PORT");
# Set username and password if needed
$mqtt->login($MQTT_USERNAME, $MQTT_PASSWORD);
# Subscribe to the desired topic
$mqtt->subscribe($MQTT_TOPIC => \&on_message);
# Start the MQTT client loop
eval {
$mqtt->run();
};
if ($@) {
print "Error: $@\n";
}
/*
openjdk version "17.0.2" 2022-01-18
Download the MQTT library org.eclipse.paho.client.mqttv3_1.2.5.jar:
https://projects.eclipse.org/projects/iot.paho/downloads
Download the correct org.json jar version for your
needs from: https://mvnrepository.com/artifact/org.json/json
This example uses version 20220320 accessible here:
https://repo1.maven.org/maven2/org/json/json/20220320/json-20220320.jar
Instructions to run this program
1. Put this code in a file named EKM.java
2. Copy the downloaded org.json jar and EKM.java to the same directory
3. Compile
javac -cp "./json-20220320.jar:./org.eclipse.paho.client.mqttv3_1.2.5.jar" EKM.java -d out
4. Run
java -cp "out:json-20220320.jar:org.eclipse.paho.client.mqttv3_1.2.5.jar" EKM
*/
import org.eclipse.paho.client.mqttv3.*;
import org.json.JSONObject;
import javax.net.ssl.SSLSocketFactory; // Import the SSLSocketFactory
public class EKM {
private static final String GATEWAY_KEY = "NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ";
private static final String MQTT_BROKER = "mqtts.ekmpush.com";
private static final int MQTT_PORT = 8883;
private static final String MQTT_TOPIC = "realtime/" + GATEWAY_KEY;
private static final String MQTT_USERNAME = GATEWAY_KEY;
public static void main(String[] args) {
try {
MqttClient client = new MqttClient("ssl://" + MQTT_BROKER + ":" + MQTT_PORT, MqttClient.generateClientId());
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(MQTT_USERNAME);
options.setSocketFactory(SSLSocketFactory.getDefault());
client.connect(options);
System.out.println("Connected to MQTT broker.");
client.subscribe(MQTT_TOPIC, (topic, message) -> {
System.out.println("\nTopic: " + topic);
try {
// Parse the message as JSON
String payload = new String(message.getPayload());
JSONObject data = new JSONObject(payload);
System.out.println("Message:");
System.out.println(data.toString(2)); // Pretty print JSON
// Extract the kWh_Tot value for a specific meter
String meterKey = "meter_000000010389"; // Get the first key
if (data.has(meterKey)) {
JSONObject meterData = data.getJSONObject(meterKey);
if (meterData.has("kWh_Tot")) {
double kWhTot = meterData.getDouble("kWh_Tot");
System.out.println("\nkWh Total: " + kWhTot);
} else {
System.out.println("kWh_Tot not found.");
}
} else {
System.out.println("Meter key not found.");
}
} catch (Exception e) {
System.out.println("Failed to decode JSON message: " + e.getMessage());
}
});
// Keep the application running
while (true) {
Thread.sleep(1000);
}
} catch (MqttException | InterruptedException e) {
e.printStackTrace();
}
}
}
Web browsers do not natively support MQTT, so implementing it with browser-based JavaScript is not feasible. Please use the Realtime API instead.
/*
* Requirements
* NodeJS: v20.15.1
* Install MQTT: npm install mqtt
*/
// Required modules
const mqtt = require('mqtt');
// MQTT Configuration
const GATEWAY_KEY = 'NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ';
const MQTT_BROKER = 'mqtts://mqtts.ekmpush.com';
const MQTT_PORT = 8883;
const MQTT_TOPIC = `realtime/${GATEWAY_KEY}`;
const MQTT_USERNAME = GATEWAY_KEY;
// Create an MQTT client instance
const client = mqtt.connect(MQTT_BROKER, {
port: MQTT_PORT,
username: MQTT_USERNAME,
rejectUnauthorized: false,
});
// Callback when the client connects to the broker
client.on('connect', () => {
console.log(`Connected to broker with username: ${MQTT_USERNAME}`);
// Subscribe to the desired topic
client.subscribe(MQTT_TOPIC, (err) => {
if (!err) {
console.log(`Subscribed to topic: ${MQTT_TOPIC}`);
}
});
});
// Callback when a message is received
client.on('message', (topic, message) => {
console.log(`\nTopic: ${topic}`);
try {
// Parse the message as JSON
const data = JSON.parse(message.toString());
console.log('Message:');
console.log(data);
// Extract the kWh_Tot value for Meter 10389.
const meterKey = 'meter_000000010389'; // Get the first key
const meterData = data[meterKey];
if (meterData) {
console.log('\n====================================');
const kwhTot = meterData.kWh_Tot;
console.log(`kWh Total: ${kwhTot}`);
console.log('====================================\n');
}
} catch (error) {
console.error('Failed to decode JSON message.', error);
}
});
// Handle error events
client.on('error', (error) => {
console.error(`Error: ${error}`);
});
// Handle close event
process.on('SIGINT', () => {
console.log('Disconnecting from the broker...');
client.end();
process.exit();
});
To subscribe to receive realtime messages, you just need your Gateway Key (e.g., NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ) and the following parameters:
MQTT Parameters | Description |
---|---|
Broker | MQTT Server: mqtts.ekmpush.com |
Port | 8883 (it is SSL) |
Topic | realtime/GATEWAY_KEY (e.g., NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ) |
Username | The username is the Gateway Key. No password is required. (e.g., NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ) |
MQTT Summary
MQTT Request
# Install mosquitto-clients
sudo apt install mosquitto-clients
# Run:
mosquitto_sub -h mqtts.ekmpush.com -p 8883 -t summary/NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ -u NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ
# Ruby Version: 3.0.2p107
# Install mqtt:
# sudo gem install mqtt
require 'mqtt'
require 'json'
# Provide MQTT Paramaters
gateway_key = 'NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ'
host = 'mqtts.ekmpush.com'
port = 8883
topic = 'summary/' + gateway_key
username = gateway_key
# Subscribe to the MQTT topic
MQTT::Client.connect(
host: host,
port: port,
username: username,
ssl: true
) do |client|
client.get(topic) do |topic, message|
puts "\nTopic: #{topic}"
puts "Message: #{message}"
# Parse the message as JSON
data = JSON.parse(message)
# Extract the RMS_Volts_Ln_1_Average value for Meter 10389.
meter_data = data['meter_000000010389']
if meter_data
puts "\n==========================================="
RMS_Volts_Ln_1_Average = meter_data['RMS_Volts_Ln_1_Average']
puts "RMS Volts Ln 1 Average: #{RMS_Volts_Ln_1_Average}"
puts "===========================================\n"
end
end
end
'''
Python version: 3.10.12
'''
# Install require module:
# pip install paho-mqtt
# Required Python Modules
import json
import warnings
import paho.mqtt.client as mqtt
# Suppress DeprecationWarnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# MQTT Configuration
GATEWAY_KEY = "NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ"
MQTT_BROKER = "mqtts.ekmpush.com"
MQTT_PORT = 8883
MQTT_TOPIC = f"summary/{GATEWAY_KEY}"
MQTT_USERNAME = GATEWAY_KEY
# Callback when the client connects to the broker
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
# Subscribe to the desired topic
client.subscribe(MQTT_TOPIC)
# Callback when a message is received
def on_message(client, userdata, msg):
print(f"\nTopic: {msg.topic}")
try:
# Parse the message as JSON
data = json.loads(msg.payload.decode('utf-8'))
print("Message:")
print(data)
# Extract the RMS_Volts_Ln_1_Average value for Meter 10389.
meter_key = "meter_000000010389" # Get the first key
meter_data = data.get(meter_key)
if meter_data:
print("\n====================================")
rms_volts_ln_1_average = meter_data.get('RMS_Volts_Ln_1_Average')
print(f"RMS Volts Ln 1 Average: {rms_volts_ln_1_average}")
print("====================================\n")
except json.JSONDecodeError:
print("Failed to decode JSON message.")
# Create an MQTT client instance
mqttClient = mqtt.Client()
# Set username and password for the broker (if needed)
mqttClient.username_pw_set(MQTT_USERNAME)
# Assign the callback functions
mqttClient.on_connect = on_connect
mqttClient.on_message = on_message
# Connect to the MQTT broker
mqttClient.tls_set() # Use TLS for secure connection
mqttClient.connect(MQTT_BROKER, MQTT_PORT, 60)
# Start the MQTT client loop
try:
mqttClient.loop_forever()
except KeyboardInterrupt:
print("Disconnecting from the broker...")
mqttClient.disconnect()
<?php
// Download the phpMQTT library from: https://github.com/bluerhinos/phpMQTT
// Include the phpMQTT library
require('phpMQTT.php');
use Bluerhinos\phpMQTT;
// MQTT Configuration
$GATEWAY_KEY = 'NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ';
$MQTT_BROKER = 'mqtts.ekmpush.com';
$MQTT_PORT = 8883;
$MQTT_TOPIC = "summary/$GATEWAY_KEY";
$MQTT_USERNAME = $GATEWAY_KEY;
$MQTT_CAFILE = "/etc/ssl/certs/ca-certificates.crt";
// Create an MQTT client instance
$mqtt = new phpMQTT($MQTT_BROKER, $MQTT_PORT, uniqid(), $MQTT_CAFILE);
// Connect to the MQTT broker
if(!$mqtt->connect(true, NULL, $MQTT_USERNAME, NULL)) {
exit(1);
}
$topics[$MQTT_TOPIC] = array('qos' => 0, 'function' => 'procMsg');
$mqtt->subscribe($topics, 0);
while($mqtt->proc()) {
}
$mqtt->close();
function procMsg($topic, $msg){
echo "Topic: {$topic}\n\n";
echo "$msg\n\n";
$data = json_decode($msg, true);
// Extract the RMS_Volts_Ln_1_Average value for Meter 10389
$meterKey = 'meter_000000010389';
if (isset($data[$meterKey])) {
$meterData = $data[$meterKey];
$rmsVoltsLn1Average = $meterData['RMS_Volts_Ln_1_Average'];
echo "\n====================================\n";
echo "RMS Volts Ln 1 Average: $rmsVoltsLn1Average\n";
echo "====================================\n\n";
}
}
#!/usr/bin/perl
# Perl version: v5.34
#
# OS Prerequisites
# UBUNTU
# apt install cpanminus
#
# Install Perl Modules
# cpan Net::MQTT::Simple
# cpan Try::Tiny
# cpan JSON
use strict;
use warnings;
use Net::MQTT::Simple::SSL;
use JSON;
use Try::Tiny;
use Data::Dumper; # For printing the contents of complex structures
# MQTT Configuration
my $GATEWAY_KEY = "NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ";
my $MQTT_BROKER = "mqtts.ekmpush.com";
my $MQTT_PORT = 8883;
my $MQTT_TOPIC = "summary/$GATEWAY_KEY";
my $MQTT_USERNAME = $GATEWAY_KEY;
my $MQTT_PASSWORD = ''; # You can set a password if needed
# Callback when a message is received
sub on_message {
my ($topic, $message) = @_;
print "\nTopic: $topic\n";
try {
# Parse the message as JSON
my $data = decode_json($message);
print "Message:\n";
print Dumper($data); # This will pretty-print the entire decoded JSON structure
# Extract the RMS_Volts_Ln_1_Average value for Meter 10389
my $meter_key = "meter_000000010389";
my $meter_data = $data->{$meter_key};
if ($meter_data) {
print "\n====================================\n";
my $rms_volts_ln_1_average = $meter_data->{'RMS_Volts_Ln_1_Average'};
print "RMS Volts Ln 1 Average: $rms_volts_ln_1_average\n";
print "====================================\n";
}
}
catch {
print "Failed to decode JSON message: $_\n";
};
}
# Create MQTT client with SSL/TLS
my $mqtt = Net::MQTT::Simple::SSL->new("$MQTT_BROKER:$MQTT_PORT");
# Set username and password if needed
$mqtt->login($MQTT_USERNAME, $MQTT_PASSWORD);
# Subscribe to the desired topic
$mqtt->subscribe($MQTT_TOPIC => \&on_message);
# Start the MQTT client loop
eval {
$mqtt->run();
};
if ($@) {
print "Error: $@\n";
}
/*
openjdk version "17.0.2" 2022-01-18
Download the MQTT library org.eclipse.paho.client.mqttv3_1.2.5.jar:
https://projects.eclipse.org/projects/iot.paho/downloads
Download the correct org.json jar version for your
needs from: https://mvnrepository.com/artifact/org.json/json
This example uses version 20220320 accessible here:
https://repo1.maven.org/maven2/org/json/json/20220320/json-20220320.jar
Instructions to run this program
1. Put this code in a file named EKM.java
2. Copy the downloaded org.json jar and EKM.java to the same directory
3. Compile
javac -cp "./json-20220320.jar:./org.eclipse.paho.client.mqttv3_1.2.5.jar" EKM.java -d out
4. Run
java -cp "out:json-20220320.jar:org.eclipse.paho.client.mqttv3_1.2.5.jar" EKM
*/
import org.eclipse.paho.client.mqttv3.*;
import org.json.JSONObject;
import javax.net.ssl.SSLSocketFactory; // Import the SSLSocketFactory
public class EKM {
private static final String GATEWAY_KEY = "NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ";
private static final String MQTT_BROKER = "mqtts.ekmpush.com";
private static final int MQTT_PORT = 8883;
private static final String MQTT_TOPIC = "summary/" + GATEWAY_KEY;
private static final String MQTT_USERNAME = GATEWAY_KEY;
public static void main(String[] args) {
try {
MqttClient client = new MqttClient("ssl://" + MQTT_BROKER + ":" + MQTT_PORT, MqttClient.generateClientId());
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(MQTT_USERNAME);
options.setSocketFactory(SSLSocketFactory.getDefault());
client.connect(options);
System.out.println("Connected to MQTT broker.");
client.subscribe(MQTT_TOPIC, (topic, message) -> {
System.out.println("\nTopic: " + topic);
try {
// Parse the message as JSON
String payload = new String(message.getPayload());
JSONObject data = new JSONObject(payload);
System.out.println("Message:");
System.out.println(data.toString(2)); // Pretty print JSON
// Extract the RMS_Volts_Ln_1_Average value for a specific meter
String meterKey = "meter_000000010389"; // Get the first key
if (data.has(meterKey)) {
JSONObject meterData = data.getJSONObject(meterKey);
if (meterData.has("RMS_Volts_Ln_1_Average")) {
double rmsVoltsLn1Average = meterData.getDouble("RMS_Volts_Ln_1_Average");
System.out.println("\nRMS Volts Ln 1 Average: " + rmsVoltsLn1Average);
} else {
System.out.println("RMS_Volts_Ln_1_Average not found.");
}
} else {
System.out.println("Meter key not found.");
}
} catch (Exception e) {
System.out.println("Failed to decode JSON message: " + e.getMessage());
}
});
// Keep the application running
while (true) {
Thread.sleep(1000);
}
} catch (MqttException | InterruptedException e) {
e.printStackTrace();
}
}
}
Web browsers do not natively support MQTT, so implementing it with browser-based JavaScript is not feasible. Please use the Summary API instead.
/*
* Requirements
* NodeJS: v20.15.1
* Install MQTT: npm install mqtt
*/
// Required modules
const mqtt = require('mqtt');
// MQTT Configuration
const GATEWAY_KEY = 'NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ';
const MQTT_BROKER = 'mqtts://mqtts.ekmpush.com';
const MQTT_PORT = 8883;
const MQTT_TOPIC = `summary/${GATEWAY_KEY}`;
const MQTT_USERNAME = GATEWAY_KEY;
// Create an MQTT client instance
const client = mqtt.connect(MQTT_BROKER, {
port: MQTT_PORT,
username: MQTT_USERNAME,
rejectUnauthorized: false,
});
// Callback when the client connects to the broker
client.on('connect', () => {
console.log(`Connected to broker with username: ${MQTT_USERNAME}`);
// Subscribe to the desired topic
client.subscribe(MQTT_TOPIC, (err) => {
if (!err) {
console.log(`Subscribed to topic: ${MQTT_TOPIC}`);
}
});
});
// Callback when a message is received
client.on('message', (topic, message) => {
console.log(`\nTopic: ${topic}`);
try {
// Parse the message as JSON
const data = JSON.parse(message.toString());
console.log('Message:');
console.log(data);
// Extract the RMS_Volts_Ln_1_Average value for Meter 10389.
const meterKey = 'meter_000000010389'; // Get the first key
const meterData = data[meterKey];
if (meterData) {
console.log('\n====================================');
const rmsVoltsLn1Average = meterData.RMS_Volts_Ln_1_Average;
console.log(`kWh Total: ${rmsVoltsLn1Average}`);
console.log('====================================\n');
}
} catch (error) {
console.error('Failed to decode JSON message.', error);
}
});
// Handle error events
client.on('error', (error) => {
console.error(`Error: ${error}`);
});
// Handle close event
process.on('SIGINT', () => {
console.log('Disconnecting from the broker...');
client.end();
process.exit();
});
To subscribe to receive summary messages, you just need your Gateway Key (e.g., NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ) and the following parameters:
MQTT Parameters | Description |
---|---|
Broker | MQTT Server: mqtts.ekmpush.com |
Port | 8883 (it is SSL) |
Topic | summary/GATEWAY_KEY (e.g., NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ) |
Username | The username is the Gateway Key. No password is required. (e.g., NjUyNjk0MzY6KDkkPVtXLUpQZyFmaDBrYTlJ) |
RS-485 Communications
Click here to go to RS-485 Documentation
This section is for developers, or individuals, that want to communicate with their EKM Meters directly using their own software or embedded solution.
The code examples found in this section are in the simplest possible method to get you started. You are welcome to make them more robust.
First we start you out just connecting to the meter. You will find there is a very simple command line process to help you get started.
After that we cover the CRC method required for most communication to the meter.
Then we put it all together, in a simple test script that will show reads, and also open and close the relays.
Last we cover how to convert the 255 character strings that the meter responds with to a usable array containing field names and their values. It is our hope that after you go through these steps you will have all the information you need, to build whatever tools you like to access the meter.
Our meters use an IEC 62056-21 communication standard that has been optimized for our own needs. We are more than happy to share this with you. With this you can write your own software or embedded solution to access your meter data.
IEC 62056 is a set of standards for Electricity metering data exchange by International Electrotechnical Commission.
To learn more about the IEC 62056 standard click the button below to visit the WikiPedia website.
Additional PDF docs are available:
v.4/v.5 Meter Settings Protocol
v.4/v.5 Meter Alternate Modbus Protocol
If you are coding in Python you can also make use of our ekmmeters.py API.
Status Codes
EKM uses conventional HTTP response codes in addition to our API Status Codes to indicate the success or failure of an API request. In general, codes in the 2xx range indicate success, codes in the 4xx range indicate an error that failed given the information provided, and codes in the 5xx range indicate an error with EKM’s servers (these are rare).
The EKM API uses the following API specific Status codes:
API Status Code | Meaning |
---|---|
1000 | There is not data for: {meters} |
1001 | There is not data for: {meters} between ${startDate} and ${endDate} |
1002 | There is not data for: {meters} This meter first reported on: |
1003 | There is not data for: {meters} This meter last reported on: |
1004 | Timezone is not supported for this date range request |
1100 | All invalid query requests |
1101 | Invalid format |
1102 | Invalid value |
1103 | Invalid parameter |
1200 | Found invalid meter: {meter} for key: MTAxMDoyMDIw |
1300 | Oops! It looks like there was an unexpected error. Try checking your query for issues or hold tight while we see what we can do. This error has been reported. |
The EKM API also uses the following HTTP Status codes:
HTTP Status Code | Meaning |
---|---|
200 | OK – The request succeeded. |
400 | Bad Request – The server could not understand the request due to invalid syntax. |
401 | Unauthorized – Although the HTTP standard specifies “unauthorized”, semantically this response means “unauthenticated”. That is, the client must authenticate itself to get the requested response. |
403 | Forbidden – The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike 401 Unauthorized, the client’s identity is known to the server. |
404 | Not Found – The server can not find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web. |
429 | Too Many Requests – The user has sent too many requests in a given amount of time (“rate limiting”). |
500 | Internal Server Error – The server has encountered a situation it does not know how to handle. |
501 | Not Implemented – The Vertical Bar otherwise known as “pipe” request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD. |
502 | Bad Gateway – This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. |
503 | Service Unavailable – The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the Retry-After HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. |
504 | Gateway Timeout – This error response is given when the server is acting as a gateway and cannot get a response in time. |
505 | HTTP Version Not Supported – The HTTP version used in the request is not supported by the server. |
506 | Variant Also Negotiates – The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. |
510 | Not Extended – Further extensions to the request are required for the server to fulfill it. |
511 | Network Authentication Required – Indicates that the client needs to authenticate to gain network access. |
Widget Documentation
Click here to go to Widget Documentation
Access free web-based real-time and historical graphs showcasing your EKM Push data, covering all your devices including meters and ioStacks. It’s quick, easy, and doesn’t require a login.
The EKM Widget offers a convenient means to gain visual insights into your systems’ performance. We utilize it to monitor our office’s current consumption and solar power generation in real-time. Additionally, the historical chart helps us track the impact of efficiency upgrades on our usage and monitor the energy consumption of our electric car over time.