serial
#
Description#
The serial plugin can read data from a serial device.
If the device returns a JSON string, then that string will be parsed for individual values. For example:
{"temperature": 25.0, "humidity": 15.0}
If the serial device returns such a value, then temperature
and
humidity
will be parsed as separate entities with the same names as the
keys provided on the payload.
The JSON option is a good choice if you have an Arduino/ESP-like device whose code you can control, as it allows to easily send data to Platypush in a simple key-value format. The use-case would be that of an Arduino/ESP device that pushes data on the wire, and this integration would then listen for updates.
Alternatively, you can also use this integration in a more traditional way
through the read()
and write()
methods to read and write data
to the device. In such a case, you may want to disable the “smart polling”
by setting enable_polling
to False
in the configuration.
If you want an out-of-the-box solution with a Firmata-compatible firmware,
you may consider using the platypush.plugin.arduino.ArduinoPlugin
instead.
Note that device paths on Linux may be subject to change. If you want to
create static naming associations for your devices (e.g. make sure that
your Arduino will always be symlinked to /dev/arduino
instead of
/dev/ttyUSB<n>
), you may consider creating static mappings through
udev.
Configuration#
serial:
# [Required]
# Device path (e.g. ``/dev/ttyUSB0`` or ``/dev/ttyACM0``).
device: # type=str
# [Optional]
# Serial baud rate (default: 9600)
# baud_rate: 9600 # type=int
# [Optional]
# Maximum size of a JSON payload (default: 512 KB). The
# plugin will keep reading bytes from the wire until it can form a
# valid JSON payload, so this upper limit is required to prevent the
# integration from listening forever and dumping garbage in memory.
# max_size: 524288 # type=int
# [Optional]
# This integration will ensure that only one
# reader/writer can access the serial device at the time, in order to
# prevent mixing up bytes in the response. This value specifies how
# long we should wait for a pending action to terminate when we try
# to run a new action. Default: 2 seconds.
# timeout: 2.0 # type=float
# [Optional]
# If ``False``, the plugin will not poll the
# device for updates. This can be the case if you want to
# programmatically interface with the device via the `SerialPlugin.read <https://docs.platypush.tech/platypush/plugins/serial.html#platypush.plugins.serial.SerialPlugin.read>`_
# and `SerialPlugin.write <https://docs.platypush.tech/platypush/plugins/serial.html#platypush.plugins.serial.SerialPlugin.write>`_ methods instead of polling for updates in JSON
# format.
# enable_polling: True # type=bool
# [Optional]
# How often (in seconds) we should poll the device
# for new data. Since we are reading JSON data from a serial
# interface whenever it's ready, the default here can be quite low
# (default: 0.1 seconds).
# poll_interval: 0.1 # type=float
# [Optional]
# A number, numeric pair or mapping of ``str`` to
# number/numeric pair representing the thresholds for the sensor.
#
# Examples:
#
# .. code-block:: yaml
#
# # Any value below 25 from any sensor will trigger a
# # SensorDataBelowThresholdEvent, if the previous value was
# # equal or above, and any value above 25 will trigger a
# # SensorDataAboveThresholdEvent, if the previous value was
# # equal or below
# thresholds: 25.0
#
# # Same as above, but the threshold is only applied to
# # ``temperature`` readings
# thresholds:
# temperature: 25.0
#
# # Any value below 20 from any sensor will trigger a
# # SensorDataBelowThresholdEvent, if the previous value was
# # equal or above, and any value above 25 will trigger a
# # SensorDataAboveThresholdEvent, if the previous value was
# # equal or below (hysteresis configuration with double
# # threshold)
# thresholds:
# - 20.0
# - 25.0
#
# # Same as above, but the threshold is only applied to
# # ``temperature`` readings
# thresholds:
# temperature:
# - 20.0
# - 25.0
# thresholds: # type=Union[float, int, Tuple[Union[float, int], Union[float, int]], Mapping[str, Union[float, int, Tuple[Union[float, int], Union[float, int]]]], NoneType]
# [Optional]
# If set, then the sensor change events will be
# triggered only if the difference between the new value and the
# previous value is higher than the specified tolerance. For example,
# if the sensor data is mapped to a dictionary::
#
# {
# "temperature": 0.01, # Tolerance on the 2nd decimal digit
# "humidity": 0.1 # Tolerance on the 1st decimal digit
# }
#
# Or, if it's a raw scalar number::
#
# 0.1 # Tolerance on the 1st decimal digit
#
# Or, if it's a list of values::
#
# [
# 0.01, # Tolerance on the 2nd decimal digit for the first value
# 0.1 # Tolerance on the 1st decimal digit for the second value
# ]
# tolerance: 0 # type=Union[float, int, Mapping[str, Union[float, int]], Iterable[Union[float, int]]]
# [Optional]
# If `SensorPlugin.get_measurement <https://docs.platypush.tech/platypush/plugins/sensor.html#platypush.plugins.sensor.SensorPlugin.get_measurement>`_ returns a key-value
# mapping, and ``enabled_sensors`` is set, then only the reported
# sensor keys will be returned.
# enabled_sensors: # type=Optional[Iterable[str]]
# [Optional]
# How long we should wait for any running
# threads/processes to stop before exiting (default: 5 seconds).
# stop_timeout: 5 # type=Optional[float]
# [Optional]
# If set to True then the plugin will not monitor
# for new events. This is useful if you want to run a plugin in
# stateless mode and only leverage its actions, without triggering any
# events. Defaults to False.
# disable_monitor: False # type=bool
Dependencies#
pip
pip install pyserial
Alpine
apk add py3-pyserial
Debian
apt install python3-serial
Fedora
yum install python-pyserial
Arch Linux
pacman -S python-pyserial
Triggered events#
Actions#
Module reference#
- class platypush.plugins.serial.SerialPlugin(*_, **__)[source]#
Bases:
SensorPlugin
The serial plugin can read data from a serial device.
If the device returns a JSON string, then that string will be parsed for individual values. For example:
{"temperature": 25.0, "humidity": 15.0}
If the serial device returns such a value, then
temperature
andhumidity
will be parsed as separate entities with the same names as the keys provided on the payload.The JSON option is a good choice if you have an Arduino/ESP-like device whose code you can control, as it allows to easily send data to Platypush in a simple key-value format. The use-case would be that of an Arduino/ESP device that pushes data on the wire, and this integration would then listen for updates.
Alternatively, you can also use this integration in a more traditional way through the
read()
andwrite()
methods to read and write data to the device. In such a case, you may want to disable the “smart polling” by settingenable_polling
toFalse
in the configuration.If you want an out-of-the-box solution with a Firmata-compatible firmware, you may consider using the
platypush.plugin.arduino.ArduinoPlugin
instead.Note that device paths on Linux may be subject to change. If you want to create static naming associations for your devices (e.g. make sure that your Arduino will always be symlinked to
/dev/arduino
instead of/dev/ttyUSB<n>
), you may consider creating static mappings through udev.- __init__(device: str, baud_rate: int = 9600, max_size: int = 524288, timeout: float = 2.0, enable_polling: bool = True, poll_interval: float = 0.1, **kwargs)[source]#
- Parameters:
device – Device path (e.g.
/dev/ttyUSB0
or/dev/ttyACM0
).baud_rate – Serial baud rate (default: 9600)
max_size – Maximum size of a JSON payload (default: 512 KB). The plugin will keep reading bytes from the wire until it can form a valid JSON payload, so this upper limit is required to prevent the integration from listening forever and dumping garbage in memory.
timeout – This integration will ensure that only one reader/writer can access the serial device at the time, in order to prevent mixing up bytes in the response. This value specifies how long we should wait for a pending action to terminate when we try to run a new action. Default: 2 seconds.
enable_polling – If
False
, the plugin will not poll the device for updates. This can be the case if you want to programmatically interface with the device via theread()
andwrite()
methods instead of polling for updates in JSON format.poll_interval – How often (in seconds) we should poll the device for new data. Since we are reading JSON data from a serial interface whenever it’s ready, the default here can be quite low (default: 0.1 seconds).
- get_data(*args, **kwargs)#
(Deprecated) alias for
get_measurement()
- get_measurement(*_, device: str | None = None, baud_rate: int | None = None, **__) Dict[str, float | int] [source]#
Reads JSON data from the serial device and returns it as a message
- Parameters:
device – Device path (default: default configured device).
baud_rate – Baud rate (default: default configured baud_rate).
- publish_entities(entities: float | int | Mapping[str, float | int] | Iterable[float | int], *args, **kwargs) Collection[Entity] #
Publishes a list of entities. The downstream consumers include:
The entity persistence manager
The web server
- Any consumer subscribed to
platypush.message.event.entities.EntityUpdateEvent
events (e.g. web clients)
It also accepts an optional callback that will be called when each of the entities in the set is flushed to the database.
You usually don’t need to override this class (but you may want to extend
transform_entities()
instead if your extension doesn’t natively handle Entity objects).
- read(device: str | None = None, baud_rate: int | None = None, size: int | None = None, end: int | str | None = None, binary: bool = False) str [source]#
Reads raw data from the serial device
- Parameters:
device – Device to read (default: default configured device)
baud_rate – Baud rate (default: default configured baud_rate)
size – Number of bytes to read
end – End of message, as a character or bytecode
binary – If set to
True
, then the serial output will be interpreted as binary data and a base64-encoded representation will be returned. Otherwise, the output will be interpreted as a UTF-8 encoded string.
- Returns:
The read message as a UTF-8 string if
binary=False
, otherwise as a base64-encoded string.
- start()#
Start the plugin.
- status(*_, **__) float | int | Mapping[str, float | int] | Iterable[float | int] | None #
Returns the latest read values and publishes the
platypush.message.event.entities.EntityUpdateEvent
events if required.
- transform_entities(entities: Dict[str, float | int]) List[Device] [source]#
This method takes a list of entities in any (plugin-specific) format and converts them into a standardized collection of Entity objects. Since this method is called by
publish_entities()
before entity updates are published, you may usually want to extend it to pre-process the entities managed by your extension into the standard format before they are stored and published to all the consumers.
- wait_stop(timeout=None)#
Wait until a stop event is received.
- write(data: str | dict | list | bytes | bytearray, device: str | None = None, baud_rate: int | None = None, binary: bool = False)[source]#
Writes data to the serial device.
- Parameters:
device – Device to write (default: default configured device).
baud_rate – Baud rate (default: default configured baud_rate).
data –
Data to send to the serial device. It can be any of the following:
A UTF-8 string
A base64-encoded string (if
binary=True
)A dictionary/list that will be encoded as JSON
A bytes/bytearray sequence
binary – If
True
, then the message is either a bytes/bytearray sequence or a base64-encoded string.