API/Development

Getting Started with the Adax API

The Adax API provides a standard http-based interface for control of Adax thermostats. Software developers will be able to query status and send commands to their thermostat(s). Adax aims to follow the general rules of API compatibility and will protect implementations from breaking when bug fixes and new features are implemented. The API also strives to be self-documenting, easy to understand and use. Cloud API User Guide Local API User Guide

Remote/Cloud Client API User Guide

Overview

Adax API is provided as a REST service and that allows you to:

  • Get your rooms target and current temperatures,
  • Change your rooms heating target temperatures.

Getting Started

For using Adax API you will need an authentication token for secure access and some REST services usage knowledge. The API is provided at the https://
api-1.adax.no/client-api/ address. The services description can be accessed at the https://api-1.adax.no/client-api/openapi in an OpenAPI format. You
could also use the provided Python and Java samples as a starting point.

Obtaining Authentication Credentials Required for Adax API

Using the Adax WiFi application you can create and get the authentication token used for accessing the Adax API. You should use at least the Adax WiFi
app version 3.5.1. The authentication token can be accessed following those steps:

  1. Navigate to Account Tab,
  2. Select “Remote user client API”
  3. Select “Add Credential”
  4. Give some name to the created credential and copy the generated password.

Using Adax API

The API provides 3 end points:

  1. /auth/ for authentication to the REST service.
  2. /rest/v1/control/ for controlling your rooms
  3. /rest/v1/content/ for getting rooms statuses.

Control and status endpoins accepts and returns json documents.

Code Samples

Python Sample

# install dependencies with: pip install requests sanction
import requests
import sanction


CLIENT_ID = "112395"

# replace with your client ID (see Adax WiFi app,Account Section)
CLIENT_SECRET = "6imtpX63D5WoRyKh"

# replace with your client ID (see Adax WiFi app,Account Section)
API_URL = "https://api-1.adax.no/client-api"

def get_token():

# Authenticate and obtain JWT token
oauthClinet = sanction.Client(token_endpoint = API_URL + '/auth/token')
oauthClinet.request_token(grant_type = 'password', username = CLIENT_ID, password = CLIENT_SECRET)
return oauthClinet.access_token

def set_room_target_temperature(roomId, temperature, token):

# Sets target temperature of the room
headers = { "Authorization": "Bearer " + token }
json = { 'rooms': [{ 'id': roomId, 'targetTemperature': str(temperature) }] }
requests.post(API_URL + '/rest/v1/control/', json = json, headers = headers)

def get_homes_info(token):

headers = { "Authorization": "Bearer " + token }
response = requests.get(API_URL + "/rest/v1/content/", headers = headers)

json = response.json()

for room in json['rooms']:

roomName = room['name']
targetTemperature = room['targetTemperature'] / 100.0
currentTemperature = 0

if ('temperature' in room):
currentTemperature = room['temperature'] / 100.0

print("Room: %15s, Target: %5.2fC, Temperature: %5.2fC, id: %5d" % (roomName, targetTemperature, currentTemperature, room['id']))

token = get_token()

# Change the temperature to 24 C in the room with an Id of 196342
set_room_target_temperature(196342, 2400, token)

# Replace the 196342 with the room id from the
get_homes_info output
get_homes_info(token)

 

Java Sample

/**
 * Add com.github.scribejava/scribejava-apis and org.json/json dependencies
 */

package no.adax.client.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
import com.github.scribejava.apis.openid.OpenIdJsonTokenExtractor;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.extractors.TokenExtractor;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.oauth.OAuth20Service;

public class ClientDemo
{
    private String apiUrl = "https://api-1.adax.no/client-api";
    private String clientId = "112395"; // replace with your client ID (see Adax WiFi app, Account Section)
    private String clientSecret = "6imtpX63D5WoRyKh"; // replace with your client secret (see Adax WiFi app, Account Section -> Third party integrations -> Remote user client API)

    public static void main(String[] args) throws Exception
    {
        ClientDemo client = new ClientDemo();

        String token = client.getToken();

        // Change the temperature to 24 C in the room with an Id of 196342
        // Replace the 196342 with the room id from the getHomesInfo output
        client.setRoomTargetTemperature(196342, 2400, token);
        client.getHomesInfo(token);
    }

    /**
     * Sets target temperature of the room
     * 
     * @throws IOException
     */
    private void setRoomTargetTemperature(int roomId, int temperature, String token) throws Exception
    {
        String postData = "{ \"rooms\": [{ \"id\": " + roomId + ", \"targetTemperature\": " + temperature + " }] }";

        HttpsURLConnection connection = (HttpsURLConnection)(new URL(apiUrl + "/rest/v1/control/").openConnection());
        connection.setRequestProperty("Authorization", "Bearer " + token);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setRequestProperty("Accept", "application/json");

        byte[] input = postData.getBytes("utf-8");
        connection.setFixedLengthStreamingMode(input.length);

        connection.connect();
        connection.getOutputStream().write(input);
        connection.getOutputStream().close();

        String response = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n"));
        connection.getInputStream().close();
        System.out.println(response);
    }

    private void getHomesInfo(String token) throws Exception
    {
        HttpsURLConnection connection = (HttpsURLConnection)(new URL(apiUrl + "/rest/v1/content/").openConnection());

        connection.setRequestProperty("Authorization", "Bearer " + token);
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.connect();

        String response = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n"));
        connection.getInputStream().close();

        JSONObject jsonObject = new JSONObject(response);
        JSONArray jsonArray = jsonObject.getJSONArray("rooms");

        for (int i = 0; i < jsonArray.length(); i++)
        {
            JSONObject roomData = jsonArray.getJSONObject(i);

            String roomName = roomData.getString("name");
            int roomId = roomData.getInt("id");
            int targetTemperature = roomData.getInt("targetTemperature") / 100;
            int currentTemperature = 0;

            if (!roomData.isNull("temperature"))
            {
                currentTemperature = roomData.getInt("temperature") / 100;
            }

            System.out.println(String.format("Room: %15s, Target: %5d, Temperature: %5d, id: %5d", roomName, targetTemperature, currentTemperature, roomId));
        }
    }

    /**
     * Authenticate and obtain JWT token
     */
    private String getToken() throws Exception
    {
        DefaultApi20 api = new DefaultApi20()
        {
            public String getAccessTokenEndpoint()
            {
                return apiUrl + "/auth/token";
            }

            public TokenExtractor<OAuth2AccessToken> getAccessTokenExtractor()
            {
                return OpenIdJsonTokenExtractor.instance();
            }

            protected String getAuthorizationBaseUrl()
            {
                throw new UnsupportedOperationException();
            }

            public String getRevokeTokenEndpoint()
            {
                throw new UnsupportedOperationException();
            }
        };

        OAuth20Service service = new ServiceBuilder(this.clientId).apiSecret(this.clientSecret).build(api);

        return service.getAccessTokenPasswordGrant(this.clientId, this.clientSecret).getAccessToken();
    }
}

Local API User Guide

Local API Features

Local API allows controlling Adax WiFi generation 2 heaters ( thermostat that have both WiFi and Bluetooth) directly over local network. Local API
provides the following functions:

  • Connect heater to local WiFi network using Bluetooth Low Energy command.
  • Get heater status that reports measured ambient temperature, and target temperature.
  • Change target temperature.

Supported Devices

1. Adax WiFi gen. 2 thermostat (that have both WiFi and Bluetooth) with firmware 2.0.1.7+ version

Communication

Heaters listen on HTTPS (443 SSL port) and accepts REST API interface.

Authorisation

Each REST API call is authorised by passing Authorisation header with value “Basic ” + heater token. Token is assigned during heater registration.
Heaters use self-signed, self-generated SSL certificates.

Commands

No. Command HTTP GET Request HTTP POST Request Header Heater Response
1. Get Status /api/?command=stat&time=<<current_unix_time>> Authorization: 'Basic ' + <<heater token >> { 'targTemp': <<target>>, 'currTemp':<<current>> }
2. Change Temperature /api/?command=set_target&time=<<current_unix_time>>&value<<target _temperature>> Authorization: 'Basic ' + <<heater token >> HTTP 200

Registration Procedure

Heater is registered on local network using a Bluetooth Low Energy communication. During the registration, device is provided with WiFi SSID, PSK, and secured heater token.

Steps:

  1. Heaters OK button is held until blue led starts blinking to initiated registration procedure.
  2. Generate/choose some random “Heater token” string value.
  3. Build heater registration command string “command=join&ssid=<<ssid>>&psk=<<psk>>&token=<<heater token>>
  4. Encode registration command as byte array (use ascii encoding)
  5. Scan for Bluetooth Low Energy device that advertises “3885cc10-7c18-4ad4-a48d-bf11abf7cb92” service.
  6. Get manufacturer data from Advertisement packet
  7. Check if manufacturer data byte 0 is equal to 5 (Heater device Type)
  8. Check if manufacturer data byte 1 two first bits are 0 (registered and managed flags are false)
  9. Check if manufacturer data bytes from 2 to 10 are not 0 (device_id > 0)
  10. If manufacturer data contains required values
  11. Connect to Device using Bluetooth Low Energy
  12. Register for “0000cc11-0000-1000-8000-00805f9b34fb” characteristics notifications.
  13. Split registration command bytes into multiple 17 byte chunks.
  14. Write each chunk to “0000cc11-0000-1000-8000-00805f9b34fb” characteristic ,with 1 byte header where 1 marks last chunk, 0 marks all other chunks.
  15. Wait for notification on “0000cc11-0000-1000-8000-00805f9b34fb” characteristic
  16. Get Byte array from notification.
  17. Check if notification data byte 0 contains 0 value (registration successful), or 1 value (WiFi connection failed)
  18. Get device ip address from notification data: bytes 1 to 4.

Code samples:

Controlling heater:

# controls heater
# install dependencies with: pip install bleak requests

import time
import requests
import urllib3

HEATER_IP     = '172.16.14.137' # replace with your heater IP from the prepare_demo
HEATER_TOKEN  = '12345678'    # replace with your secure password from the prepare_demo

def set_target_temperature(target_temperature):
    url = 'https://' + HEATER_IP + '/api'
    payload = { 'command': 'set_target', 'time': int(time.time()), 'value': target_temperature }
    headers = { 'Authorization': 'Basic ' + HEATER_TOKEN }
    return requests.get(url, params = payload, headers = headers, timeout = 15, verify = False)

def get_status():
    url = 'https://' + HEATER_IP + '/api'
    payload = { 'command': 'stat', 'time': int(time.time()) }
    headers = { 'Authorization': 'Basic ' + HEATER_TOKEN }
    response = requests.get(url, params = payload, headers = headers, timeout = 15, verify = False)
    response_json = response.json()
    target_temperature = response_json["targTemp"]
    current_temperature = response_json["currTemp"]
    print('Current temperature %d, target temperature: %d \n' % (current_temperature, target_temperature))

urllib3.disable_warnings() # heater uses self signed certificate
set_target_temperature(2300)
get_status()

Heater Registration:

# registers heater to your wifi network
# install dependencies with: pip install bleak requests

import bleak
import asyncio
import operator
import urllib

wifi_ssid    = 'HEATER-TEST'  # replace with your wifi name
wifi_psk     = 'HEATER-PASS'  # replace with your wifi psk
access_token = '12345678'     # generate some strong password for your heater

UUID_ADAX_BLE_SERVICE = '3885cc10-7c18-4ad4-a48d-bf11abf7cb92'
UUID_ADAX_BLE_SERVICE_CHARACTERISTIC_COMMAND = '0000cc11-0000-1000-8000-00805f9b34fb'

# ignore registered, non heater devices
def is_available_device(manufacturer_data):
    ADAX_DEVICE_TYPE_HEATER_BLE = 5
    if manufacturer_data and len(manufacturer_data) >= 10:
        type_id = manufacturer_data[0]
        status_byte = manufacturer_data[1]
        mac_id = 0
        for byte in manufacturer_data[2:10]:
            mac_id = mac_id * 256 + byte
        registered = status_byte & (0x1 << 0)
        managed = status_byte & (0x1 << 1)
        return mac_id and type_id == ADAX_DEVICE_TYPE_HEATER_BLE and not registered and not managed
    return False

# scan and return available heater
async def scan_for_any_available_ble_device():
    discovered = await bleak.discover(timeout = 60)
    if discovered:
        for discovered_item in discovered:
            metadata = discovered_item.metadata
            uuids = metadata['uuids'] if 'uuids' in metadata else None
            if uuids and UUID_ADAX_BLE_SERVICE in uuids:
                manufacturer_data_list = None
                manufacturer_data = metadata['manufacturer_data'] if 'manufacturer_data' in metadata else None
                if manufacturer_data:
                    first_bytes = next(iter(manufacturer_data))
                    if first_bytes:
                        other_bytes = manufacturer_data[first_bytes]
                        manufacturer_data_list = [first_bytes % 256, operator.floordiv(first_bytes, 256)] + list(other_bytes)
                if is_available_device(manufacturer_data_list):
                    return discovered_item.address
    return None

# handle notifications for heater
def command_notification_handler(uuid, data):
    BLE_COMMAND_STATUS_OK = 0
    BLE_COMMAND_STATUS_INVALID_WIFI = 1
    byte_list = None if not data else list(data)
    status = None if not byte_list else byte_list[0]
    if status == BLE_COMMAND_STATUS_OK:
        ip = None if not byte_list or len(byte_list) < 5 else '%d.%d.%d.%d' % (byte_list[1], byte_list[2], byte_list[3], byte_list[4])
        print('Heater Registered, use client_control_demo with IP: %s and token: %s' % (ip, access_token))
    elif status == BLE_COMMAND_STATUS_INVALID_WIFI:
        print('Invalid WiFi crendentials')

# send command to heater
async def write_command(command_byte_list, client):
    MAX_BYTES_IN_COMMAND_CHUNK = 17
    byte_count = len(command_byte_list)
    chunk_count = operator.floordiv(byte_count, MAX_BYTES_IN_COMMAND_CHUNK)
    if chunk_count * MAX_BYTES_IN_COMMAND_CHUNK < byte_count:
        chunk_count += 1
    sent_byte_count = 0
    chunk_nr = 0
    while chunk_nr < chunk_count:
        is_last = chunk_nr == (chunk_count - 1)
        chunk_data_length = byte_count - sent_byte_count if is_last else MAX_BYTES_IN_COMMAND_CHUNK
        chunk = [chunk_nr, 1 if is_last else 0] + command_byte_list[sent_byte_count:(sent_byte_count + chunk_data_length)]
        await client.write_gatt_char(UUID_ADAX_BLE_SERVICE_CHARACTERISTIC_COMMAND, bytearray(chunk))
        sent_byte_count += chunk_data_length
        chunk_nr += 1

# register heater
async def register_devices(loop):
    print('Press and hold OK button of the heater until the blue led starts blinking')
    device = await scan_for_any_available_ble_device()
    if device:
        client = bleak.BleakClient(device, loop = loop)
        await client.connect()
        await client.start_notify(UUID_ADAX_BLE_SERVICE_CHARACTERISTIC_COMMAND, command_notification_handler)
        ssid_encoded = urllib.parse.quote(wifi_ssid)
        psk_encoded = urllib.parse.quote(wifi_psk)
        access_token_encoded = urllib.parse.quote(access_token)
        byte_list = list(bytearray('command=join&ssid=' + ssid_encoded + '&psk=' + psk_encoded + '&token=' + access_token_encoded, 'ascii'))
        await write_command(byte_list, client)

loop = asyncio.get_event_loop()
loop.create_task(register_devices(loop))
loop.run_forever()