WirepasNetworkInterface

class wirepas_mqtt_library.wirepas_network_interface.WirepasNetworkInterface(host, port, username, password, insecure=False, num_worker_thread=1, strict_mode=False, connection_cb=None, client_id='', clean_session=None, transport='tcp', gw_timeout_s=2)

Class to interact with a Wirepas network through an MQTT broker.

This class wraps the MQTT connection and the messages creation / parsing in protobuf format.

Most of the calls can be called in a blocking mode (ie, blocking until gateway response is received) or in an asynchronous way by specifying a callback to receive the response.

class ConnectionErrorCode
UNKNOWN_ERROR = 255
OK = 0
UNKNOWN_HOST = 1
SOCKET_TIMEOUT = 2
CONNECTION_REFUSED = 3
BROKER_REFUSED_PROTOCOL_VERSION = 4
BROKER_REFUSED_IDENTIFIER_REJECTED = 5
BROKER_REFUSED_SERVER_UNAVAILABLE = 6
BROKER_REFUSED_BAD_USERNAME_PASSWORD = 7
BROKER_REFUSED_NOT_AUTHORIZED = 8
classmethod from_broker_connack(rc)
__init__(host, port, username, password, insecure=False, num_worker_thread=1, strict_mode=False, connection_cb=None, client_id='', clean_session=None, transport='tcp', gw_timeout_s=2)

Constructor

Parameters
  • host – MQTT broker host address

  • port – MQTT broker port

  • username – MQTT username

  • password – MQTT password

  • insecure – if set to true, TLS handshake with broker is skipped

  • num_worker_thread – number of thread to use to handle asynchronous event (like data reception)

  • strict_mode – if strict_mode is set to false, some errors do not generate exceptions but only an error message

  • connection_cb (function) –

    If set, callback to be called when connection to mqtt broker changes

    Expected signature:

    on_mqtt_connection_change_cb(connected, error_code)
    
    • connected: if True, connection is established false otherwise

    • error_code: ConnectionErrorCode

  • client_id – the unique client id string used when connecting to the broker. If client_id is zero length or None, then one will be randomly generated. In this case the clean_session parameter must be True.

  • clean_session – a boolean that determines the client type. If True, the broker will remove all information about this client when it disconnects. If False, the client is a durable client and subscription information and queued messages will be retained when the client disconnects.

  • transport – set to “websockets” to send MQTT over WebSockets. Leave at the default of “tcp” to use raw TCP.

  • gw_timeout_s – Timeout in s to receive a response from a gw

close()

Explicitly close this network interface as well as the worker threads

This closes disconnects the MQTT client from the broker which automatically closes the network thread. In addition, it creates empty tasks that force the worker daemon threads to exit cleanly. Given the connection to broker is closed first, callbacks are not executed anymore and no additional tasks are therefore added in the queue. Thus by design, no valid task can be added to the queue whilst the worker threads are being closed.

If you do not require to close the connection in a deterministic way by invoking this method, the resources on the host and broker are anyway cleaned up by way of garbage collection once the main program utilising this class is stopped and the corresponding python process is exited.

Warning

the instance of WNI must not be used anymore after this call. Any other method call requiring the broker connection after this one will end up in TimeoutError exception

get_sinks(self, network_address=None, gateway=None)

Get list of current sink connected to this broker

Parameters
  • network_address – If specified, only sinks with matching network addresses are returned

  • gateway – gateway or list of gateways to get sinks

Returns

List of sinks as tuple (gateway_id, sink_id, config)

Config is dictionary with following keys

Keys are:

Key

Value

sink_id

(str) Unique id of sink on the gateway

node_role

(int) Role of node

node_address

(int) Address of node

network_address

(int) Network address

network_channel

(int) Network channel

app_config_diag

(int) Diag interval

app_config_seq

(int) Diag sequence

app_config_data

(bytearray) App config data

are_keys_set

(bool) Tells if network keys are configured

started

(bool) Is stack started

current_ac_range_min

(int) Current minimum access cycle

current_ac_range_max

(int) Current maximum access cycle

min_ac

(int) Minimum access cycle value allowed

max_ac

(int) Maximum access cycle value allowed

max_mtu

(int) Maximum packet size

min_ch

(int) Minimum channel

max_ch

(int) Maximum channel

hw_magic

(int) Hardware magic

stack_profile

(int) Stack profile

app_config_max_size

(int) Maximum size for app config

firmware_version

(tuple) Firmware version of node

Note

node_role encoding is same as in dualmcu protocol

Raises

TimeoutError – If a gateway doesn’t send its initial config fast enough

get_gateways(self, only_online=True)

Get list of current gateways connected to this broker

Parameters

only_online – if True (default) only online gateways are returned

Returns

List of gateway name

clear_gateway_status(**kwargs)

Clear a gateway status

Parameters

gw_id (str) – Id of gateway the sink is attached

Note

Gateway status is sent by gateway as a retain message on the broker. It may be need to explicitly remove it in some situation: - An offline gateway that will never be back online (removed from network) - A sticky gateway online status that is not here anymore (bug from gateway) - A malformed gateway status (bug from gateway)

send_message(self, gw_id, sink_id, dest, src_ep, dst_ep, payload, qos=0, csma_ca_only=False, cb=None, param=None)

Send a message to wirepas network from a given sink

Parameters
  • gw_id (str) – Id of gateway the sink is attached

  • sink_id (str) – Id of sink

  • dest – destination address

  • src_ep – source endpoint

  • dst_ep – destination endpoint

  • qos – Quality of service to use (0 or 1) (default is 0)

  • payload (bytearray) – payload to send

  • csma_ca_only (bool) – Is packet only for csma-ca nodes

  • hop_limit(int) – maximum number of hops this message can do to reach its destination (<16)

  • cb (function) –

    If set, callback to be asynchronously called when gateway answer. If None, call is blocking.

    Note

    Expected signature:

    on_message_sent_cb(gw_error_code, param)

    with type:

  • param (object) – Optional parameter that will be passed to callback

Returns

None if cb is set or error code from gateway is synchronous call

Return type

GatewayResultCode

Raises

TimeoutError – Raised if cb is None and response is not received within 2 sec

upload_scratchpad(self, gw_id, sink_id, seq, scratchpad=None, cb=None, param=None)

Upload a scratchpad on a given sink

Parameters
  • gw_id (str) – Id of gateway the sink is attached

  • sink_id (str) – Id of sink

  • seq (int) – Sequence to use for this scratchpad

  • scratchpad (str) – Scratchpad to upload, None to clear the current stored one

  • cb (function) –

    If set, callback to be asynchronously called when gateway answers

    Expected signature:

    on_scratchpad_uploaded_cb(gw_error_code, param)
    

    Warning

    If unset, call is synchronous and caller can be blocked for up to specified timeout

  • param (object) – Optional parameter that will be passed to callback

  • timeout (int) – Timeout in second to wait for the upload (default 60s)

Returns

None if cb is set or error code from gateway is synchronous call

Return type

GatewayResultCode

Raises

TimeoutError – Raised if cb is None and response is not received within the specified timeout

process_scratchpad(self, gw_id, sink_id, cb=None, param=None)

Process scratchpad on a given sink

Parameters
  • gw_id (str) – Id of gateway the sink is attached

  • sink_id (str) – Id of sink

  • cb (function) –

    If set, callback to be asynchronously called when gateway answers

    Expected signature:

    on_scratchpad_processed_cb(gw_error_code, param)
    

    Warning

    If unset, call is synchronous and caller can be blocked for up to specified timeout

  • param (object) – Optional parameter that will be passed to callback

  • timeout (int) – Timeout in second to wait for the processing of scratchpad (default 120s)

Returns

None if cb is set or error code from gateway is synchronous call

Return type

GatewayResultCode

Raises

TimeoutError – Raised if cb is None and response is not received within specified timeout

get_scratchpad_status(self, gw_id, sink_id, cb=None, param=None)

Get scratchpad status of a given sink

Parameters
  • gw_id (str) – Id of gateway the sink is attached

  • sink_id (str) – Id of sink

  • cb (function) –

    If set, callback to be asynchronously called when gateway answers

    Expected signature:

    on_status_received_cb(gw_error_code, param, status)
    
    • gw_error_code: GatewayResultCode

    • param: param given when doing this call

    • status: see note

    Warning

    If unset, call is synchronous and caller can be blocked for up to 2 seconds

  • param (object) – Optional parameter that will be passed to callback

Returns

Tuple (GatewayResultCode, status) None if cb is set. See note.

Return type

Tuple

Raises

TimeoutError – Raised if cb is None and response is not received within 2 sec

Note

Status is a dictionary with following keys:

Key

Value

stored_scratchpad

(dic) keys: len, crc, seq

stored_status

(int)

stored_type

(int)

processed_scratchpad

(dic) keys: len, crc, seq

target_scratchpad_and_action

(dic) keys: action, target_sequence, target_crc, param

set_target_scratchpad(self, gw_id, sink_id, action, cb=None, param=None)

Set target scratchpad on a given sink

Parameters
  • gw_id (str) – Id of gateway the sink is attached

  • sink_id (str) – Id of sink

  • action (wirepas_mesh_messaging.otap_helper.ScratchpadAction) – Action to set

  • cb (function) –

    If set, callback to be asynchronously called when gateway answers

    Expected signature:

    on_target_set_cb(gw_error_code, param)
    

    Warning

    If unset, call is synchronous and caller can be blocked for up to 2 seconds

  • param (object) – Optional parameter that will be passed to callback

Returns

None if cb is set or error code from gateway is synchronous call

Return type

GatewayResultCode

Raises

TimeoutError – Raised if cb is None and response is not received within 2 sec

register_data_cb(cb, gateway=None, sink=None, network=None, src_ep=None, dst_ep=None)

Deprecated Replaced by register_uplink_traffic_cb() Only name has changed

unregister_data_cb(id)

Deprecated Replaced by unregister_uplink_traffic_cb() Only name has changed

Register a data filter to received uplink filtered data

Parameters
  • cb – Callback to be called when a matching packet is received

  • gateway – Filter on a given gateway (None for all)

  • sink – Filter on a given sink (None for all)

  • network – Filter on a given network (None for all)

  • src_ep – Filter on a given source endpoint (None for all)

  • dst_ep – Filter on a given destination endpoint (None for all)

Returns

The id of this filter, to be used when removing it with unregister_data_cb()

Unregister uplink data callback previously registered with register_uplink_traffic_cb()

Parameters

id – id returned when adding the filter

Raises

KeyError – if id doesn’t exist

Register a data filter to received downlink filtered data

Parameters
  • cb – Callback to be called when a matching packet is received

  • gateway – Filter on a given gateway (None for all)

  • sink – Filter on a given sink (None for all)

  • src_ep – Filter on a given source endpoint (None for all)

  • dst_ep – Filter on a given destination endpoint (None for all)

Returns

The id of this filter, to be used when removing it with unregister_downlink_traffic_cb()

Unregister data callback previously registered with register_downlink_traffic_cb()

Parameters

id – id returned when adding the filter

Raises

KeyError – if id doesn’t exist

set_sink_config(self, gw_id, sink_id, new_config, cb=None, param=None)

Set the config of a sink

Configuration is sent as dictionary. Call can be clocking or unblocking depending on cb parameter.

Parameters
  • gw_id – gateway id the sink is attached to

  • sink_id – id of the sink to configure

  • new_config (dict) –

    the new config. Keys are:

    Key

    Value

    node_role

    (int)

    node_address

    (int)

    network_address

    (int)

    network_channel

    (int)

    app_config_diag

    (int)

    app_config_seq

    (int)

    app_config_data

    (bytearray)

    cipher_key

    (bytearray)

    authentication_key

    (bytearray)

    started

    (bool)

  • cb (function) –

    If set, callback to be asynchronously called when gateway answers

    Expected signature:

    on_config_set_cb(gw_error_code, param)
    

    Warning

    If unset, call is synchronous and caller can be blocked for up to 5 seconds

  • param (object) – Optional parameter that will be passed to callback

Returns

None if cb is set or error code from gateway is synchronous call

Return type

GatewayResultCode

Raises

TimeoutError – Raised if cb is None and response is not received within 5 sec

Note

node_role encoding is same as in dualmcu protocol

set_config_changed_cb(self, cb)

Set a callback to be called when a config has changed on any of the attached gateway

Parameters

cb – Callback to be called when something has changed. get_gateways() and get_sinks() can be used to discover what has changed

OtapHelper

class wirepas_mqtt_library.wirepas_otap_helper.WirepasOtapHelper(wni, network, gateway=None, persist_otap_status_file=None)

Class to ease Otap operation

This class contains methods allowing the execution of simple otap operations on all the sinks belonging to the same network in a single call.

It allows to write more complex script by chaining those operations.

__init__(wni, network, gateway=None, persist_otap_status_file=None)

Constructor

Parameters
  • wni (WirepasNetworkInterface) – Wirepas network interface

  • network – Network address concerned by the otap

  • gateway – Gateway (or list) concerned by the otap

load_scratchpad_to_all_sinks(scratchpad_file, seq=None, timeout=60, delay_between_sinks_s=1)

Load the specified scratchpad file on all sinks of the network

Parameters
  • scratchpad_file (str) – scratchpad file with .otap extension

  • seq (int) – optional seq for the scratchpad. If not given a random one is chosen

  • timeout (int) – maximum time to wait for each scratchpad upload

  • delay_between_sinks_s (int) – time to wait between the sending of a load scratchpad between sinks. On large network, it may help to avoid loading the broker too much.

Returns

True if scratchpad is correctly loaded on all sinks, false otherwise

process_scratchpad_on_all_sinks(timeout=120)

Process the scratchpad localy on all sinks of the network

Parameters

timeout (int) – maximum time to wait for processing of scratchpad

Returns

True if scratchpad is correctly set to be processed on all sinks, false otherwise

get_stored_scratchpad_seq_list()

Retrieve a set of stored scratchpad sequence in sinks for this network

Returns

Set of stored scratchpad sequence in use in sinks or None if cannot be determined

get_target_scratchpad_seq_list()

Retrieve a set of target scratchpad sequence in sinks for this network

Returns

Set of target scratchpad sequence in use in sinks or None if cannot be determined

set_legacy_otap_to_all_sinks()

Set legacy action on all sinks

Returns

True if action is correctly set on all sinks, false otherwise

set_no_otap_to_all_sinks()

Set no otap action on all sinks

Returns

True if action is correctly set on all sinks, false otherwise

set_propagate_scratchpad_to_all_sinks(seq=None, crc=None)

Set propagate only action on all sinks

Parameters
  • seq – Seq to set as target (If not set, seq of stored scratchpad is used)

  • crc – Crc to set as target ((If not set, crc of stored scratchpad is used)

Returns

True if action is correctly set on all sinks, false otherwise

set_propagate_and_process_scratchpad_to_all_sinks(seq=None, crc=None, delay=None)

Set propagate and process action on all sinks

Parameters
  • seq – Seq to set as target (If not set, seq of stored scratchpad is used)

  • crc – Crc to set as target ((If not set, crc of stored scratchpad is used)

  • delay – delay for the processing (wmm.ProcessingDelay)

Returns

True if action is correctly set on all sinks, false otherwise

send_remote_scratchpad_status(address=4294967295)

Send a remote api scratchpad status cmd to the network to trigger a response from nodes

Parameters

address – address to send the remote api command

Returns

True if command is correctly sent from all sinks, false otherwise

get_current_nodes_status()

Return dictionary of all nodes status from the network discovered since this helper was created

Returns

dictionary of nodes. Keys are node ids and values are dictionary with following keys:

Key

Value

ts

(int) timestamp when this info was received

seq

(int) stored scratchpad sequence

crc

(int) stored scratchpad crc

length

(int) length of stored scratchpad

type

(int) type of stored scratchpad

status

(int) status of stored scratchpad

stack_version

(tuple) version of stack

stack_area_id

(int) area id for stack

app_version

(tuple) version of app

app_area_id

(int) area id for app

action

(int) current otap action

target_crc

(int) current otap target crc

target_seq

(int) current otap target sequence

target_delay_m

(int) current otap delay in minutes

remaining_delay_m

(int) current otap remaining delay in minutes

Note

All keys are not necessarily present in dictionary depending on the available info

TLVAppConfigHelper

class wirepas_mqtt_library.wirepas_tlv_app_config_helper.WirepasTLVAppConfigHelper(wni, network=None, gateway_sink_subset=None)

Class to ease operation management of app_config with Wirepas TLV format

This class contains methods allowing the modification (addition, removal) of app_config data inside a Wirepas network compliant with the TLV format. It offers an abstraction for wirepas supported feature at application level like the local provisioning.

__init__(wni, network=None, gateway_sink_subset=None)

Constructor

Parameters
  • wni (WirepasNetworkInterface) – Wirepas network interface

  • network – Network address concerned by the otap

  • gateway_sink_subset – list of (gateway, sink) tupple concerned by the change

Note

Either network or gateway_sink_subset must be specified

add_raw_entry(entry, value)

Add a new entry to the local cache

Nothing is done on the network yet. It will be updated only when calling update_entries()

Parameters
  • entry (int (between 0 and 0xffff)) – new entry to add

  • value (bytearray) – value for the entry

remove_raw_entry(entry)

Remove an entry from the local cache

Nothing is done on the network yet. It will be updated only when calling update_entries()

Parameters

entry (int (between 0 and 0xffff)) – entry to remove

setup_local_provisioning(enabled, psk_id=None, psk=None)

Set a new entry to enable or disable local provisioning

Parameters
  • enabled (bool) – True to enable local provisioning, False to disable it

  • psk_id (bytearray) – Id of the psk on 4 bytes (only valid when enabled)

  • psk (bytearray) – psk to use for lacal provisioning on 32 bytes (only valid when enabled)

Raises

ValueError – if psk and psk_id are not both set or unset or with a wrong size

update_entries(override=False)

Set a new entry to the NDP for the selected network or sink

Parameters

override – if True, if an app config is already present that doesn’t follow the TLV format, full app config is overriden with TLV format with this entry

Returns

True if all specified sinks are updated, False otherwise.

Warning

If returned value is False, only a subset of sinks may be updated

Gateway return codes and special values

class wirepas_mesh_messaging.gateway_result_code.GatewayResultCode(value)

Class that represent all possible errors generated by a gateway Keep a one-to-one mapping with current protobuf errors to ease conversion

GW_RES_UNKNOWN_ERROR = -1
GW_RES_OK = 0
GW_RES_INTERNAL_ERROR = 1
GW_RES_INVALID_SINK_ID = 2
GW_RES_INVALID_ROLE = 3
GW_RES_INVALID_NETWORK_ADDRESS = 4
GW_RES_INVALID_NETWORK_CHANNEL = 5
GW_RES_INVALID_CHANNEL_MAP = 6
GW_RES_INVALID_NETWORK_KEYS = 7
GW_RES_INVALID_AC_RANGE = 8
GW_RES_INVALID_SINK_STATE = 9
GW_RES_INVALID_DEST_ADDRESS = 10
GW_RES_INVALID_DEST_ENDPOINT = 11
GW_RES_INVALID_SRC_ENDPOINT = 12
GW_RES_INVALID_QOS = 13
GW_RES_INVALID_DATA_PAYLOAD = 14
GW_RES_INVALID_SCRATCHPAD = 15
GW_RES_INVALID_SCRATCHPAD_SIZE = 16
GW_RES_INVLAID_SEQUENCE_NUMBER = 17
GW_RES_INVALID_SEQUENCE_NUMBER = 17
GW_RES_INVALID_REBOOT_DELAY = 18
GW_RES_INVALID_DIAG_INTERVAL = 19
GW_RES_INVALID_APP_CONFIG = 20
GW_RES_INVALID_PARAM = 21
GW_RES_NO_SCRATCHPAD_PRESENT = 22
GW_RES_ACCESS_DENIED = 23
GW_RES_REQUEST_NEEDS_SINK_ID = 24
GW_RES_INVALID_MAX_HOP_COUNT = 25
GW_RES_SINK_OUT_OF_MEMORY = 26
GW_RES_SINK_TIMEOUT = 27
class wirepas_mesh_messaging.otap_helper.ProcessingDelay(value)

An enumeration.

DELAY_UNKNOWN = 0
DELAY_TEN_MINUTES = 1
DELAY_THIRTY_MINUTES = 2
DELAY_ONE_HOUR = 3
DELAY_SIX_HOURS = 4
DELAY_ONE_DAY = 5
DELAY_TWO_DAYS = 6
DELAY_FIVE_DAYS = 7
class wirepas_mesh_messaging.otap_helper.ScratchpadAction(value)

An enumeration.

ACTION_NO_OTAP = 1
ACTION_PROPAGATE_ONLY = 2
ACTION_PROPAGATE_AND_PROCESS = 3
ACTION_PROPAGATE_AND_PROCESS_WITH_DELAY = 4
ACTION_LEGACY_OTAP = 5
class wirepas_mesh_messaging.otap_helper.ScratchpadType(value)

An enumeration.

SCRATCHPAD_TYPE_BLANK = 1
SCRATCHPAD_TYPE_PRESENT = 2
SCRATCHPAD_TYPE_PROCESS = 3
class wirepas_mesh_messaging.otap_helper.ScratchpadStatus(value)

An enumeration.

SCRATCHPAD_STATUS_SUCCESS = 1
SCRATCHPAD_STATUS_NEW = 2
SCRATCHPAD_STATUS_ERROR = 3