7.2.3. mqttgateway.gateway package¶
7.2.3.1. Submodules¶
7.2.3.2. mqttgateway.gateway.configuration module¶
The default configuration settings in a single string constant.
Use this declaration as a template configuration file.
The configuration loader mqttgateway.utils.load_config
only
considers sections and options that are already present in this string
and disregard anything else. If a section or option is found in a configuration
file but is not listed here, it will not be taken into account. Only
sections and options already here are taken into account when found in a configuration
file, and then they overwrite the default values defined here.
The only exception is the [INTERFACE]
section which is reserved to the configuration
parameters needed by the interface being implemented. The section itself is defined here
but no options are present as those are defined by the developper, and those are the only
options that the loader will take into account.
7.2.3.3. mqttgateway.gateway.mqtt_client module¶
This is a child class of the MQTT client in the paho library.
It includes the management of reconnection when using only the loop() method (which is not included natively in the paho library).
Notes on MQTT behaviour:
- if not connected, the loop and publish methods will not do anything, but raise no errors either.
- the loop method handles always only one message per call.
-
exception
mqttgateway.gateway.mqtt_client.
connectionError
(msg=None)¶ Bases:
mqttgateway.utils.throttled_exception.ThrottledException
Base Exception class for this module, inherits from ThrottledException
-
class
mqttgateway.gateway.mqtt_client.
mgClient
(host='localhost', port=1883, keepalive=60, client_id='', on_msg_func=None, topics=None, userdata=None)¶ Bases:
paho.mqtt.client.Client
Class representing the MQTT connection.
mg
meansMqttGateway
.Note: The MQTT paho library sets quite a few attributes in the Client class. They all start with an underscore. Be careful not to overwrite them.
Parameters: - on_msg_func (function) – takes an MQTT message as argument and is called during on_message().
- topics (list of strings) – e.g.[‘home/audiovideo/#’, ‘home/lighting/#’].
-
lag_end
()¶ Function to inhibit the connection test during the lag.
There is the possibility of a race condition when testing the connection state too soon after requesting a connection. This happens if the
on_connect()
call-back is not called fast enough and the main loop tests the connection state before that call-back has set the state toconnected
. As a consequence the automatic reconnection feature gets triggered while a connection is already under way, and the connection process gets jammed with the broker. That’s why we need to leave a little lag before testing the connection.
-
connect
()¶ Sets up the ‘lag’ feature on top of the parent method.
-
reconnect
()¶ Sets up the ‘lag’ feature on top of the parent method.
-
loop
(timeout)¶ Implements automatic reconnection on top of the parent loop method.
The use of the method/attribute
lag_test()
is to avoid having to test the lag forever once the connection is established. Once the lag is finished, this method gets replaced by a simple lambda, which hopefully is much faster than calling the time library and doing a comparison. Probably a case of premature optimisation though…
7.2.3.4. mqttgateway.gateway.mqtt_map module¶
This module is the bridge between the internal and the MQTT representation of messages.
As a reminder, we define the MQTT syntax as follows:
- topic:
root/function/gateway/location/device/sender/type-{C or S}
- payload: action or status, in plain text or in a json string e.g.
{key1:value1,key2:value2,..}
-
class
mqttgateway.gateway.mqtt_map.
internalMsg
(iscmd=False, function=None, gateway=None, location=None, device=None, sender=None, action=None, arguments=None)¶ Bases:
object
Defines all the characteristics of an internal message.
Behaviour of
None
: even if it could be interesting to differentiate between a characteristic set toNone
and one set to an empty string (an empty string could still be mapped for example), currently they are considered the same, i.e. a non existent value. ThereforeNone
values are converted always to empty strings.Parameters: - iscmd (bool) – Indicates if the message is a command (True) or a status (False), optional
- function (string) – internal representation of function, optional
- gateway (string) – internal representation of gateway, optional
- location (string) – internal representation of location, optional
- device (string) – internal representation of device, optional
- sender (string) – internal representation of sender, optional
- action (string) – internal representation of action, optional
- arguments (dictionary of strings) – all values should be assumed to be strings, optional
-
copy
()¶ Creates a copy of the message.
-
str
()¶ Stringifies a class instance.
-
reply
(response, reason)¶ Formats the message to be sent as a reply to an existing command
This method is supposed to be used with an existing message that has been received. Using this method for all replies guarantees a consistent syntax for replies.
Parameters: - response (string) – code or abbreviation for response, e.g.
OK```or ``ERROR
- reason (string) – longer description of the response
- response (string) – code or abbreviation for response, e.g.
-
class
mqttgateway.gateway.mqtt_map.
MsgList
¶ Bases:
Queue.Queue
,object
Implementation of a Queue list just in case its needed.
The methods are called
push
andpull
in order to differentiate them from the usual names (put, get, append, pop, …). TODO: implement maxsize and timeout.-
push
(item)¶ Equivalent to self._list.append(item)
-
pull
()¶ Equivalent to self._list.pop(0)
-
-
class
mqttgateway.gateway.mqtt_map.
mappedTokens
(function, gateway, location, device, sender, action, argkey, argvalue)¶ Bases:
tuple
Tokens representing a message that can be mapped.
-
action
¶ Alias for field number 5
-
argkey
¶ Alias for field number 6
-
argvalue
¶ Alias for field number 7
-
device
¶ Alias for field number 3
-
function
¶ Alias for field number 0
-
gateway
¶ Alias for field number 1
-
location
¶ Alias for field number 2
-
sender
¶ Alias for field number 4
-
-
mqttgateway.gateway.mqtt_map.
NO_MAP
= {'action': {'maptype': 'none'}, 'argkey': {'maptype': 'none'}, 'argvalue': {'maptype': 'none'}, 'device': {'maptype': 'none'}, 'function': {'maptype': 'none'}, 'gateway': {'maptype': 'none'}, 'location': {'maptype': 'none'}, 'root': '', 'sender': {'maptype': 'none'}, 'topics': []}¶ Default map, with no mapping at all.
-
class
mqttgateway.gateway.mqtt_map.
msgMap
(jsondict=None)¶ Bases:
object
Contains the mapping data and the conversion methods.
The mapping data is read from a JSON style dictionary. To access the maps use: mqtt_token = maps.*field*.i2m(internal_token) Example: mqtt_token = maps.gateway.i2m(internal_token)
Parameters: jsondict (dictionary) – contains the map data in the agreed format; if None, the NO_MAP structure is used. -
class
tokenMap
(maptype, mapdict=None)¶ Bases:
object
Represents the mapping for a given token or characteristic.
Each instantiation of this class represent the mapping for a given token, and contains the type of mapping, the mapping dictionary if available, and the methods to convert the keywords back and forth between MQTT and internal representation.
The mapping dictionary passed as argument has the internal keywords as keys and as value a list of corresponding MQTT keywords. Only the first of the list will be used for the reverse dictionary, the other MQTT keywords being ‘aliases’.
Parameters: - maptype (string) – type of map, should be either ‘strict’. ‘loose’ or ‘none’
- mapdict (dictionary) – dictionary representing the mapping
-
m2i
(mqtt_token)¶ Generic method converting an MQTT token into an internal characteristic.
-
i2m
(internal_token)¶ Generic method converting an internal characteristic into an MQTT token.
-
sender
()¶ Getter for the
_sender
attribute.
-
mqtt2internal
(mqtt_msg)¶ Converts the MQTT message into an internal one.
Parameters: mqtt_msg (mqtt.MQTTMessage) – a MQTT message. Returns: the conversion of the MQTT message Return type: internalMsg object Raises: ValueError
– in case of bad MQTT syntax or unrecognised map elements
-
internal2mqtt
(internal_msg)¶ Converts an internal message into a MQTT one.
Parameters: internal_msg ( internalMsg
) – the message to convertReturns: a full MQTT message where topic syntax is root/function/gateway/location/device/sender/{C or S}
and payload syntax is either a plain action or a JSON string.Return type: a MQTTMessage object Raises: ValueError
– in case a token conversion fails
-
class
-
mqttgateway.gateway.mqtt_map.
test
()¶ docstring
-
mqttgateway.gateway.mqtt_map.
reverse
()¶
7.2.3.5. mqttgateway.gateway.start_gateway module¶
Defines the function that starts the gateway.
-
mqttgateway.gateway.start_gateway.
startgateway
(gateway_interface)¶ Entry point.
7.2.3.6. Module contents¶
The package representing the core of the application.
There are 4 modules:
mqtt_client.py
defines the child class of the official MQTT Client class of the paho library;mqtt_map.py
defines the classesinternalMsg
andmsgMap
;start_gateway.py
which contains the script for the application initialisation and main loop.configuration.py
which contains the default configuration as a string.
This package uses the logger help provided by mqttgateway.utils.app_properties
.
The Properties
object should have been already initialised by the application
using this library.
However, if that is not the case, the initialisation is done here with default parameters.
As a consequence, the main application should initialise Properties
before
importing anything from this package.