Communication Module#
The Communication module provides classes for enabling communication with external systems using the MQTT (Message Queuing Telemetry Transport) protocol. It includes functionalities for both publishing data to and subscribing to data from MQTT brokers. These classes facilitate the integration of your multibody simulations with IoT devices and other MQTT-enabled applications. This module is not imported automatically with msolve. You must explicitly import it when needed.
Example
To use MQTT communication features, import the module explicitly:
from msolve.Communication import *
Note
The MQTT class is documented to provide insight into its internal behavior and structure. However, users should not instantiate it directly.
Instead, use the high-level wrappers:
MQTT_pubfor publishing scalar or vector signals.MQTT_variablefor synchronizing Variable objects via MQTT.
These abstractions handle instantiation and configuration internally, ensuring better integration with the msolve modeling workflow.
- class MQTT(**kwds)#
MQTT class for managing communication with a MQTT broker.
This class wraps the Paho MQTT client and provides thread-safe message buffering via queue.Queue. It supports both publishing and subscribing modes and optionally plots transmitted or received payloads in real time.
Note
This class is typically used internally by MQTT_pub and MQTT_variable. Direct use is supported for advanced scenarios but generally discouraged in favor of higher-level abstractions.
- Parameters:
_type (str) – Mode of operation. Either ‘publish’ or ‘subscribe’.
broker (str) – Hostname or IP address of the MQTT broker.
topic (str) – Topic to publish to or subscribe from.
client_id (str, optional) – Unique identifier for the MQTT client. Default is None.
label (str, optional) – Optional label used in logs and client identification. Default is “”.
verbose (bool, optional) – If True, enables debug-level logging. Default is False.
port (int, optional) – Port number for the broker connection. Default is 1883.
keep_alive (int, optional) – Keep-alive interval in seconds. Default is 60.
qos (int, optional) – Quality of Service level for message delivery. Default is 2.
retain_message (bool, optional) – Whether published messages should be retained. Default is False.
index (int, optional) – Index to extract from comma-separated payloads. Default is 0.
plot (bool, optional) – If True, displays a real-time plot of data. Default is False.
output (Enum) – Specifies protocol of standard output [“on”,”off”,”fileonly”,”screenonly”]
- cleanup()#
Calls all the various cleanup methods. In case of error conditions and/or Exceptions. Or when a new broker is initialized or atexit
- clear()#
Clears the queue.
- connect()#
Create a Client and connect to a broker. ‘verbose’, if True sets the logging file threshold to ‘DEBUG’, else ‘INFO’
- disconnect()#
Disconnect from a broker
- on_connect(client, userdata, flags, rc)#
Callback for when the client receives a CONNACK response from the server.
- on_message(client, obj, msg)#
callback for when a PUBLISH message is received from the server. If populates a global data structure which will be referenced by subscribers
- on_publish(client, obj, mid)#
Called when a message that was to be sent using the publish() call has completed transmission to the broker
- on_subscribe(client, userdata, mid, granted_qos)#
Called when the broker responds to a subscribe request
- publishToTopic(payload)#
Publishes a payload string to the broker, assumes that the connection was successfully established
- subscribeToTopic()#
Manually subscribe to the configured topic. This is typically handled automatically on connection, but this method is available for advanced use cases where dynamic re-subscription is required.
Only needed when using the MQTT class directly.
- class MQTT_pub(**kwds)#
- Defines a publisher for MQTT communication.
This class encapsulates MQTT publishing functionality, allowing payloads to be sent to an MQTT broker at specified intervals.
- Parameters:
data (Function) – A function or list of functions that will be evaluated by MotionSolve The evaluated function is sent to the specified MQTT broker/topic as payload. The current simulation time is prepended to the payload. Only valid MotionSolve expressions are supported.
broker (str) – Address of the MQTT broker. Defaults to ‘localhost’.
port (int) – Port for establishing broker connection. Defaults to 1883.
verbose (bool) – Flag to enable MQTT logging. Defaults to False.
qos (int) – Quality of Service level. Defaults to 2.
keep_alive (int) – Maximum period (seconds) between communications with the broker. Defaults to 60.
topic (str) – Topic for identifying the payload. Defaults to an empty string.
communication_interval (float, optional) – The time interval (in seconds) at which the MQTT_pub instance will publish the data. Defaults to 1e-3 seconds.
retain_message (bool) – Indicates whether the message should be retained by the broker or not. Default is False.
client_id (str) – a user-friendly string passed to the Client, optional.
mqtt (MQTT) – optional instance of an MQTT client, a default one will be created if None
plot (bool) – If you set this flag to True, a plot will be displayed to show the values published to the broker
output (Enum) – Specifies protocol of standard output [“on”,”off”,”fileonly”,”screenonly”]
Note
MQTT (Message Queuing Telemetry Transport) is a lightweight and efficient messaging protocol designed for low-bandwidth, high-latency, or unreliable networks. It enables communication between devices or applications by allowing them to publish and subscribe to topics, where messages are exchanged.
MQTT is often used in Internet of Things (IoT) scenarios, where devices need to send and receive data in a scalable and energy-efficient manner. It uses a publish-subscribe model and is known for its simplicity and minimal overhead This class, a wrapper around paho mqtt module, can be used to publish a payload to a broker/server.
For more information on the paho mqtt module see: https://www.eclipse.org/paho/index.php?page=clients/python/docs/index.php
In case ‘localhost’ is the desired broker, a mosquitto broker needs to be installed and running on the local computer. See this page for more information https://mosquitto.org/
Alternatively, several online brokers can also be used for testing, for example: https://mqtt.eclipseprojects.io/
This class creates a
Variableinstance for eachdataexpression, and it uses aSensorto publish the payload to the broker at the prescribedcommunication_interval.Name
Type
Required
Default
Modifiable
Designable
activeBool
True
\(\checkmark\)
Function [0]
\(\checkmark\)
labelStr
nameStr
Example
Create MQTT_pub, MQTT_variable entity.#from msolve import * from msolve.Communication import MQTT_pub, MQTT_variable model = Model() units = Units (mass="KILOGRAM", length="METER", time="SECOND", force="NEWTON") ground = Part (ground=True) part = Part (mass = 0.1, ip=[1e3,1e3,1e3], cm=Marker(), vz=200) accgrav = Accgrav(kgrav=-9.81) integrator = Integrator (hmax=1e-5) #slow it down! bush = Bushing(k=[1e1,1e2,1e1],kt=[1e5,1e5,1e5], i=part.cm, j=Marker(part=ground)) broker = 'localhost' port = 1883 topic = "test/topic1" mqtt_pub = MQTT_pub( label = "publisher", data = ["100*SIN(2*PI*TIME)", f"BUSH({bush.id}, 0, 1, 0)"], topic = topic, qos = 0, # broker = broker, port = port, verbose = True, communication_interval = 0.01, plot = True, ) mqtt_var = MQTT_variable( label = 'subscriber', broker = broker, topic = topic, verbose = True, qos = 0, index = 1, communication_interval = 0.001, interpolation_method = 'zero', # zero order hold retain_message = True, ) req = Request(type="EXPRESSION", f2=f"VARVAL({mqtt_var.id})", name="subscriber") run = model.simulate(type="TRANSIENT", end=1, steps=1000, returnResults=True) run.plot(x='TIME', y="subscriber.F2")
- communication_interval = None#
The time interval (in seconds) at which data is published to the MQTT broker.
- Type:
float
- data#
Specifies the type of Array being created.
Type=Function [0], Required
- class MQTT_sub(**kwds)#
Defines a simple subscriber client for MQTT communication.
This class encapsulates MQTT subscriber functionality, enabling interaction with an MQTT broker using specific settings to receive messages. It can be used to retrieve values from a broker.
- broker#
Address of the MQTT broker. Defaults to ‘localhost’.
- Type:
str
- port#
Port for establishing broker connection. Defaults to 1883.
- Type:
int
- verbose#
Flag to enable MQTT logging. Defaults to False.
- Type:
bool
- qos#
Quality of Service level. Defaults to 2.
- Type:
int
- keep_alive#
Maximum period (seconds) between communications with the broker. Defaults to 60.
- Type:
int
- topic#
Topic for identifying the payload. Defaults to an empty string.
- Type:
str
- label#
a string describing the subscriber
- Type:
str
- client_id#
a user-friendly string passed to the Client, optional.
- Type:
str
- index#
an integer value indicating what component is to be obtained from the broker. Defaults to 0.
- Type:
int
- plot#
If you set this flag to True, a plot will be displayed to show the values obtained from the broker
- Type:
bool
- class MQTT_variable(**kwds)#
- Defines a subscriber client for MQTT communication.
This class encapsulates MQTT subscriber functionality. It will retrieve the value(s) from the broker according to the supplied arguments and make it available as a
Variable.
- Parameters:
interpolation_method (Enum) – A string to indicate if interpolation is to be performed between updates. Valid options are ‘zero’ for Zero Order Hold, ‘linear’ for First Order Hold and ‘parabolic’ or ‘second_order’ for Second Order Hold.
ic (double) – the initial value of the MQTT_sub before the first payload is obtained.
communication_interval (float, optional) – The time interval (in seconds) at which the MQTT_variable instance will obtain the payload from the broker. Defaults to 1e-3 seconds.
**kwds – Additional keyword arguments that will be passed to the MQTT initializer. These could include broker details, Quality of Service (QoS), port, etc.
Note
This class is designed to subscribe to topics on an MQTT broker and handle incoming messages. It creates a solver
Variableand it uses an index if the subscribed topic returns a list of values as a payload. The subscriber is capable of dealing with different communication intervals from the publisher. To accommodate this, an interpolation strategy is implemented to estimate data values during periods of non-communication. The available methods are:- ‘zero’:
zero order hold. Assumes that the data remains constant at the last received value until the next value is received. This is a piecewise constant interpolation.
- ‘linear’:
first order hold. Assumes a linear interpolation between the last received value and the next. This method is suitable for data with linear trends.
- ‘parabolic’ or ‘second_order’:
Assumes a parabolic interpolation between values. This is useful for data exhibiting quadratic behavior.
The choice of interpolation depends on the nature of the data being transmitted and the expected variability of the data during the non-communication intervals.
Name
Type
Required
Default
Modifiable
Designable
activeBool
True
icDouble
0.0
\(\checkmark\)
Enum
zero
labelStr
nameStr
Example
For an example, see
MQTT_pub.- interpolation_method#
Type=Enum, Default=zero
Permitted values are:
linear
parabolic
second_order
zero