juham.ts¶
Module: MQTT to Time Series Database Recorder
Description: Classes in this module povide functionality to subscribe to MQTT topics and record the received data into a time series database. Designed to facilitate seamless integration between MQTT-based data sources and time series databases, enabling efficient storage and retrieval of time-stamped data.
- class juham.ts.EnergyCostCalculatorRecord(name='ecc_record')[source]¶
Bases:
Base
The EnergyCostCalculator recorder.
- classmethod classattrs_from_dict(attributes)¶
Set only the class’s own attributes from a dictionary.
- Return type:
None
- classmethod classattrs_to_dict()¶
Convert the class’s own attributes to a dictionary, excluding inherited and private ones.
- Return type:
Dict
[str
,Any
]
- copy()¶
Create and return a copy of the current object.
This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.
This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.
- Return type:
MasterPiece
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
clone_of_john = john.copy()
- database_class_id: str = 'JInflux'¶
- database_client: Optional[JDatabase | None]¶
- debug(msg, details='')¶
Logs the given debug message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- do(action, context)¶
Execute the given action to the object, by calling the provided action.
- Parameters:
action (Callable[["MasterPiece", Dict[str, Any]], bool]) – A callable that takes
(node
boolean. (context) and returns a)
context (Dict[str, Any]) – Any context data that the action may use.
- Return type:
bool
- Returns:
The return value from the executed action.
- error(msg, details='')¶
Logs the given error message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod factory()¶
Fetch the dictionary holding class names and associated classes.
- Returns:
with class names and associated classes
- Return type:
factory
- classmethod find_class(class_id)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- from_dict(data)¶
Update instance attributes from a dictionary.
- Return type:
None
- classmethod get_class_id()¶
Return the class id of the class. Each class has an unique name that can be used for instantiating the class via
Object.instantiate()
method.- Parameters:
cls (class) – class
- Returns:
unique class identifier through which the class can be instantiated by factory method pattern.
- Return type:
id (str)
- classmethod has_class_method_directly(method_name)¶
Check if the method is defined directly in the class (not inherited).
- Return type:
bool
- info(msg, details='')¶
Logs the given information message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (
str
) – The information message to be logged.details (
str
) – Additional detailed information for the message to be logged
- Return type:
None
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- classmethod init_class(clazz)¶
Initialize class. Registers the class into the class factory .
- Parameters:
clazz (class) – class to be initialized
- Return type:
None
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking. Calls init_topic() to construct topic base name for the object, and instantiates the mqtt client.
This method is called internally and typically there is no need to call it from the application code.
Issues a warning if the
mqtt_class_id
has not been configured, even though objects without a capability to communicate are rather crippled.- Return type:
None
- init_topic_base()¶
- Return type:
None
- initialize()¶
Initialize time series database and mqtt networking for use. This method must be called after the object name has been set .
- Return type:
None
- classmethod instantiate(class_id, *args)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args (
Any
) – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- classmethod log_debug(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_error(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_info(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- log_message(type, msg, details='')¶
Publish the given log message to the MQTT ‘log’ topic.
This method constructs a log message with a timestamp, class type, source name, message, and optional details. It then publishes this message to the ‘log’ topic using the MQTT protocol.
- Parameters:
type (
str
) – str The classification or type of the log message (e.g., ‘Error’, ‘Info’).msg (
str
) – str The main log message to be published.details (
str
) – str, optional Additional details about the log message (default is an empty string).
- Return type:
None
- Returns:
None
- Raises:
Exception – If there is an issue with the MQTT client while publishing the message.
Example:
# publish info message to the Juham's 'log' topic self.log_message("Info", f"Some cool message {some_stuff}", str(dict))
- classmethod log_warning(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- make_topic_name(topic)¶
Make topic name for the object. The topic name consists of the base name plus the given ‘topic’.
- Parameters:
topic (str) – topic name
- Returns:
mqtt topic name
- Return type:
str
- make_url()¶
Generate the URL for the composite, including all children.
- Return type:
URL
- mqtt_class_id: str = ''¶
- mqtt_client: Optional[JMqtt | None]¶
- mqtt_host: str = 'localhost'¶
- mqtt_port: int = 1883¶
- mqtt_root_topic: Optional[str] = None¶
- mqtt_topic_base: str¶
- mqtt_topic_control: str¶
- mqtt_topic_log: str¶
- on_connect(client, userdata, flags, rc)[source]¶
Notification on connect.
This method is called whenever the MQTT broker is connected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
flags (int) – Consult MQTT
rc (int) – See MQTT docs
- Return type:
None
- on_disconnect(client, userdata, rc=0)¶
Notification on disconnect.
This method is called whenever the MQTT broker is disconnected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
rc (int) – See MQTT docs
- Return type:
None
- on_message(client, userdata, msg)[source]¶
MQTT message notification on arrived message.
Called whenever a new message is posted on one of the topics the object has subscribed to via subscribe() method. This method is the heart of automation: here, derived subclasses should automate whatever they were designed to automate. For example, they could switch a relay when a boiler temperature sensor signals that the temperature is too low for a comforting shower for say one’s lovely wife.
For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
msg (object) – The MQTT message
- Return type:
None
- property parent: MasterPiece | None¶
- publish(topic, msg, qos=1, retain=True)¶
Publish the given message to the given MQTT topic. For more information consult MQTT.
- Parameters:
topic (str) – topic
msg (str) – message to be published
qos (int, optional) – quality of service. Defaults to 1.
retain (bool, optional) – retain. Defaults to True.
- Return type:
None
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point (
Point
) – point with initialized time stamp.- Return type:
None
… note: NOT IMPLEMENTED YET
- record_powerconsumption(m)[source]¶
Record powerconsumption
- Parameters:
m (dict[str, Any]) – to be recorded
- Return type:
None
- classmethod register()¶
Register the class.
Called immediately upon class initialization, right before the class attributes are loaded from the class specific configuration files.
Subclasses can extend this with custom register functionality:
class MyMasterPiece(MasterPiece): @classmethod def register(cls): super().register() # Don't forget cls._custom_field = True
- Return type:
None
- resolve_url(url)¶
Find a MasterPiece in the hierarchy matching the URL.
- Return type:
Optional
[MasterPiece
]
- root()¶
Fetch the root object
- Returns:
root object
- Return type:
MasterPiece
- run()¶
Start a new thread to runs the network loop in the background.
Allows the main program to continue executing while the MQTT client handles incoming and outgoing messages in the background.
- Return type:
None
- run_forever()¶
Starts the network loop and blocks the main thread, continuously running the loop to process MQTT messages.
The loop will run indefinitely unless the connection is lost or the program is terminated.
- Return type:
None
- classmethod set_log(l)¶
Set logger.
- Parameters:
l (logger) – logger object
- Return type:
None
- shutdown()¶
Shut down all services, free resources, stop threads, disconnect from mqtt, in general, prepare for shutdown.
- Return type:
None
- subscribe(topic)¶
Subscribe to the given MQTT topic.
This method sets up the subscription to the specified MQTT topic and registers the
on_message()
method as the callback for incoming messages.- Parameters:
topic (str) – The MQTT topic to subscribe to.
- Return type:
None
Example:
# configure obj.subscribe('foo/bar')
- to_dict()¶
Convert instance attributes to a dictionary.
- Return type:
Dict
[str
,Any
]
- warning(msg, details='')¶
Logs the given warning message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point (
Point
) – a measurement describing a time stamp and related attributes for one measurement.- Return type:
None
- write_attempts: int = 3¶
- write_point(name, tags, fields, ts)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- Return type:
None
- class juham.ts.ForecastRecord(name='forecastrecord')[source]¶
Bases:
Base
Forecast database record.
This class listens the forecast topic and writes to the time series database.
- classmethod classattrs_from_dict(attributes)¶
Set only the class’s own attributes from a dictionary.
- Return type:
None
- classmethod classattrs_to_dict()¶
Convert the class’s own attributes to a dictionary, excluding inherited and private ones.
- Return type:
Dict
[str
,Any
]
- copy()¶
Create and return a copy of the current object.
This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.
This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.
- Return type:
MasterPiece
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
clone_of_john = john.copy()
- database_class_id: str = 'JInflux'¶
- database_client: Optional[JDatabase | None]¶
- debug(msg, details='')¶
Logs the given debug message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- do(action, context)¶
Execute the given action to the object, by calling the provided action.
- Parameters:
action (Callable[["MasterPiece", Dict[str, Any]], bool]) – A callable that takes
(node
boolean. (context) and returns a)
context (Dict[str, Any]) – Any context data that the action may use.
- Return type:
bool
- Returns:
The return value from the executed action.
- error(msg, details='')¶
Logs the given error message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod factory()¶
Fetch the dictionary holding class names and associated classes.
- Returns:
with class names and associated classes
- Return type:
factory
- classmethod find_class(class_id)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- from_dict(data)¶
Update instance attributes from a dictionary.
- Return type:
None
- classmethod get_class_id()¶
Return the class id of the class. Each class has an unique name that can be used for instantiating the class via
Object.instantiate()
method.- Parameters:
cls (class) – class
- Returns:
unique class identifier through which the class can be instantiated by factory method pattern.
- Return type:
id (str)
- classmethod has_class_method_directly(method_name)¶
Check if the method is defined directly in the class (not inherited).
- Return type:
bool
- info(msg, details='')¶
Logs the given information message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (
str
) – The information message to be logged.details (
str
) – Additional detailed information for the message to be logged
- Return type:
None
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- classmethod init_class(clazz)¶
Initialize class. Registers the class into the class factory .
- Parameters:
clazz (class) – class to be initialized
- Return type:
None
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking. Calls init_topic() to construct topic base name for the object, and instantiates the mqtt client.
This method is called internally and typically there is no need to call it from the application code.
Issues a warning if the
mqtt_class_id
has not been configured, even though objects without a capability to communicate are rather crippled.- Return type:
None
- init_topic_base()¶
- Return type:
None
- initialize()¶
Initialize time series database and mqtt networking for use. This method must be called after the object name has been set .
- Return type:
None
- classmethod instantiate(class_id, *args)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args (
Any
) – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- classmethod log_debug(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_error(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_info(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- log_message(type, msg, details='')¶
Publish the given log message to the MQTT ‘log’ topic.
This method constructs a log message with a timestamp, class type, source name, message, and optional details. It then publishes this message to the ‘log’ topic using the MQTT protocol.
- Parameters:
type (
str
) – str The classification or type of the log message (e.g., ‘Error’, ‘Info’).msg (
str
) – str The main log message to be published.details (
str
) – str, optional Additional details about the log message (default is an empty string).
- Return type:
None
- Returns:
None
- Raises:
Exception – If there is an issue with the MQTT client while publishing the message.
Example:
# publish info message to the Juham's 'log' topic self.log_message("Info", f"Some cool message {some_stuff}", str(dict))
- classmethod log_warning(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- make_topic_name(topic)¶
Make topic name for the object. The topic name consists of the base name plus the given ‘topic’.
- Parameters:
topic (str) – topic name
- Returns:
mqtt topic name
- Return type:
str
- make_url()¶
Generate the URL for the composite, including all children.
- Return type:
URL
- mqtt_class_id: str = ''¶
- mqtt_client: Optional[JMqtt | None]¶
- mqtt_host: str = 'localhost'¶
- mqtt_port: int = 1883¶
- mqtt_root_topic: Optional[str] = None¶
- mqtt_topic_base: str¶
- mqtt_topic_control: str¶
- mqtt_topic_log: str¶
- on_connect(client, userdata, flags, rc)[source]¶
Standard mqtt connect notification.
This method is called when the client connection with the MQTT broker is established.
- Return type:
None
- on_disconnect(client, userdata, rc=0)¶
Notification on disconnect.
This method is called whenever the MQTT broker is disconnected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
rc (int) – See MQTT docs
- Return type:
None
- on_forecast(em)[source]¶
Handle weather forecast data. Writes the received hourly forecast data to timeseries database.
- Parameters:
em (dict) – forecast
- Return type:
None
- on_message(client, userdata, msg)[source]¶
Standard mqtt message notification method.
This method is called upon new arrived message.
- Return type:
None
- property parent: MasterPiece | None¶
- publish(topic, msg, qos=1, retain=True)¶
Publish the given message to the given MQTT topic. For more information consult MQTT.
- Parameters:
topic (str) – topic
msg (str) – message to be published
qos (int, optional) – quality of service. Defaults to 1.
retain (bool, optional) – retain. Defaults to True.
- Return type:
None
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point (
Point
) – point with initialized time stamp.- Return type:
None
… note: NOT IMPLEMENTED YET
- classmethod register()¶
Register the class.
Called immediately upon class initialization, right before the class attributes are loaded from the class specific configuration files.
Subclasses can extend this with custom register functionality:
class MyMasterPiece(MasterPiece): @classmethod def register(cls): super().register() # Don't forget cls._custom_field = True
- Return type:
None
- resolve_url(url)¶
Find a MasterPiece in the hierarchy matching the URL.
- Return type:
Optional
[MasterPiece
]
- root()¶
Fetch the root object
- Returns:
root object
- Return type:
MasterPiece
- run()¶
Start a new thread to runs the network loop in the background.
Allows the main program to continue executing while the MQTT client handles incoming and outgoing messages in the background.
- Return type:
None
- run_forever()¶
Starts the network loop and blocks the main thread, continuously running the loop to process MQTT messages.
The loop will run indefinitely unless the connection is lost or the program is terminated.
- Return type:
None
- classmethod set_log(l)¶
Set logger.
- Parameters:
l (logger) – logger object
- Return type:
None
- shutdown()¶
Shut down all services, free resources, stop threads, disconnect from mqtt, in general, prepare for shutdown.
- Return type:
None
- subscribe(topic)¶
Subscribe to the given MQTT topic.
This method sets up the subscription to the specified MQTT topic and registers the
on_message()
method as the callback for incoming messages.- Parameters:
topic (str) – The MQTT topic to subscribe to.
- Return type:
None
Example:
# configure obj.subscribe('foo/bar')
- to_dict()¶
Convert instance attributes to a dictionary.
- Return type:
Dict
[str
,Any
]
- warning(msg, details='')¶
Logs the given warning message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point (
Point
) – a measurement describing a time stamp and related attributes for one measurement.- Return type:
None
- write_attempts: int = 3¶
- write_point(name, tags, fields, ts)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- Return type:
None
- class juham.ts.LogRecord(name='log_record')[source]¶
Bases:
Base
Class recording application events, such as warnigns and errors, to time series database.
- classmethod classattrs_from_dict(attributes)¶
Set only the class’s own attributes from a dictionary.
- Return type:
None
- classmethod classattrs_to_dict()¶
Convert the class’s own attributes to a dictionary, excluding inherited and private ones.
- Return type:
Dict
[str
,Any
]
- copy()¶
Create and return a copy of the current object.
This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.
This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.
- Return type:
MasterPiece
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
clone_of_john = john.copy()
- database_class_id: str = 'JInflux'¶
- database_client: Optional[JDatabase | None]¶
- debug(msg, details='')¶
Logs the given debug message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- do(action, context)¶
Execute the given action to the object, by calling the provided action.
- Parameters:
action (Callable[["MasterPiece", Dict[str, Any]], bool]) – A callable that takes
(node
boolean. (context) and returns a)
context (Dict[str, Any]) – Any context data that the action may use.
- Return type:
bool
- Returns:
The return value from the executed action.
- error(msg, details='')¶
Logs the given error message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod factory()¶
Fetch the dictionary holding class names and associated classes.
- Returns:
with class names and associated classes
- Return type:
factory
- classmethod find_class(class_id)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- from_dict(data)¶
Update instance attributes from a dictionary.
- Return type:
None
- classmethod get_class_id()¶
Return the class id of the class. Each class has an unique name that can be used for instantiating the class via
Object.instantiate()
method.- Parameters:
cls (class) – class
- Returns:
unique class identifier through which the class can be instantiated by factory method pattern.
- Return type:
id (str)
- classmethod has_class_method_directly(method_name)¶
Check if the method is defined directly in the class (not inherited).
- Return type:
bool
- info(msg, details='')¶
Logs the given information message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (
str
) – The information message to be logged.details (
str
) – Additional detailed information for the message to be logged
- Return type:
None
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- classmethod init_class(clazz)¶
Initialize class. Registers the class into the class factory .
- Parameters:
clazz (class) – class to be initialized
- Return type:
None
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking. Calls init_topic() to construct topic base name for the object, and instantiates the mqtt client.
This method is called internally and typically there is no need to call it from the application code.
Issues a warning if the
mqtt_class_id
has not been configured, even though objects without a capability to communicate are rather crippled.- Return type:
None
- init_topic_base()¶
- Return type:
None
- initialize()¶
Initialize time series database and mqtt networking for use. This method must be called after the object name has been set .
- Return type:
None
- classmethod instantiate(class_id, *args)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args (
Any
) – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- classmethod log_debug(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_error(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_info(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- log_message(type, msg, details='')¶
Publish the given log message to the MQTT ‘log’ topic.
This method constructs a log message with a timestamp, class type, source name, message, and optional details. It then publishes this message to the ‘log’ topic using the MQTT protocol.
- Parameters:
type (
str
) – str The classification or type of the log message (e.g., ‘Error’, ‘Info’).msg (
str
) – str The main log message to be published.details (
str
) – str, optional Additional details about the log message (default is an empty string).
- Return type:
None
- Returns:
None
- Raises:
Exception – If there is an issue with the MQTT client while publishing the message.
Example:
# publish info message to the Juham's 'log' topic self.log_message("Info", f"Some cool message {some_stuff}", str(dict))
- classmethod log_warning(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- make_topic_name(topic)¶
Make topic name for the object. The topic name consists of the base name plus the given ‘topic’.
- Parameters:
topic (str) – topic name
- Returns:
mqtt topic name
- Return type:
str
- make_url()¶
Generate the URL for the composite, including all children.
- Return type:
URL
- mqtt_class_id: str = ''¶
- mqtt_client: Optional[JMqtt | None]¶
- mqtt_host: str = 'localhost'¶
- mqtt_port: int = 1883¶
- mqtt_root_topic: Optional[str] = None¶
- mqtt_topic_base: str¶
- mqtt_topic_control: str¶
- mqtt_topic_log: str¶
- on_connect(client, userdata, flags, rc)[source]¶
Connects the client to mqtt broker.
- Parameters:
client (obj) – client to be connected
userdata (any) – caller specific data
flags (int) – implementation specific shit
- Returns:
True if succesful
- Return type:
rc (bool)
- on_disconnect(client, userdata, rc=0)¶
Notification on disconnect.
This method is called whenever the MQTT broker is disconnected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
rc (int) – See MQTT docs
- Return type:
None
- on_message(client, userdata, msg)[source]¶
MQTT message notification on arrived message.
Called whenever a new message is posted on one of the topics the object has subscribed to via subscribe() method. This method is the heart of automation: here, derived subclasses should automate whatever they were designed to automate. For example, they could switch a relay when a boiler temperature sensor signals that the temperature is too low for a comforting shower for say one’s lovely wife.
For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
msg (object) – The MQTT message
- Return type:
None
- property parent: MasterPiece | None¶
- publish(topic, msg, qos=1, retain=True)¶
Publish the given message to the given MQTT topic. For more information consult MQTT.
- Parameters:
topic (str) – topic
msg (str) – message to be published
qos (int, optional) – quality of service. Defaults to 1.
retain (bool, optional) – retain. Defaults to True.
- Return type:
None
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point (
Point
) – point with initialized time stamp.- Return type:
None
… note: NOT IMPLEMENTED YET
- classmethod register()¶
Register the class.
Called immediately upon class initialization, right before the class attributes are loaded from the class specific configuration files.
Subclasses can extend this with custom register functionality:
class MyMasterPiece(MasterPiece): @classmethod def register(cls): super().register() # Don't forget cls._custom_field = True
- Return type:
None
- resolve_url(url)¶
Find a MasterPiece in the hierarchy matching the URL.
- Return type:
Optional
[MasterPiece
]
- root()¶
Fetch the root object
- Returns:
root object
- Return type:
MasterPiece
- run()¶
Start a new thread to runs the network loop in the background.
Allows the main program to continue executing while the MQTT client handles incoming and outgoing messages in the background.
- Return type:
None
- run_forever()¶
Starts the network loop and blocks the main thread, continuously running the loop to process MQTT messages.
The loop will run indefinitely unless the connection is lost or the program is terminated.
- Return type:
None
- classmethod set_log(l)¶
Set logger.
- Parameters:
l (logger) – logger object
- Return type:
None
- shutdown()¶
Shut down all services, free resources, stop threads, disconnect from mqtt, in general, prepare for shutdown.
- Return type:
None
- subscribe(topic)¶
Subscribe to the given MQTT topic.
This method sets up the subscription to the specified MQTT topic and registers the
on_message()
method as the callback for incoming messages.- Parameters:
topic (str) – The MQTT topic to subscribe to.
- Return type:
None
Example:
# configure obj.subscribe('foo/bar')
- to_dict()¶
Convert instance attributes to a dictionary.
- Return type:
Dict
[str
,Any
]
- warning(msg, details='')¶
Logs the given warning message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point (
Point
) – a measurement describing a time stamp and related attributes for one measurement.- Return type:
None
- write_attempts: int = 3¶
- write_point(name, tags, fields, ts)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- Return type:
None
- class juham.ts.PowerMeterRecord(name='powermeter_record')[source]¶
Bases:
Base
Power meter recorder.
Listens ‘powerconsumption’ topic and records the corresponding time series.
- classmethod classattrs_from_dict(attributes)¶
Set only the class’s own attributes from a dictionary.
- Return type:
None
- classmethod classattrs_to_dict()¶
Convert the class’s own attributes to a dictionary, excluding inherited and private ones.
- Return type:
Dict
[str
,Any
]
- copy()¶
Create and return a copy of the current object.
This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.
This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.
- Return type:
MasterPiece
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
clone_of_john = john.copy()
- database_class_id: str = 'JInflux'¶
- database_client: Optional[JDatabase | None]¶
- debug(msg, details='')¶
Logs the given debug message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- do(action, context)¶
Execute the given action to the object, by calling the provided action.
- Parameters:
action (Callable[["MasterPiece", Dict[str, Any]], bool]) – A callable that takes
(node
boolean. (context) and returns a)
context (Dict[str, Any]) – Any context data that the action may use.
- Return type:
bool
- Returns:
The return value from the executed action.
- error(msg, details='')¶
Logs the given error message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod factory()¶
Fetch the dictionary holding class names and associated classes.
- Returns:
with class names and associated classes
- Return type:
factory
- classmethod find_class(class_id)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- classmethod get_class_id()¶
Return the class id of the class. Each class has an unique name that can be used for instantiating the class via
Object.instantiate()
method.- Parameters:
cls (class) – class
- Returns:
unique class identifier through which the class can be instantiated by factory method pattern.
- Return type:
id (str)
- classmethod has_class_method_directly(method_name)¶
Check if the method is defined directly in the class (not inherited).
- Return type:
bool
- info(msg, details='')¶
Logs the given information message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (
str
) – The information message to be logged.details (
str
) – Additional detailed information for the message to be logged
- Return type:
None
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- classmethod init_class(clazz)¶
Initialize class. Registers the class into the class factory .
- Parameters:
clazz (class) – class to be initialized
- Return type:
None
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking. Calls init_topic() to construct topic base name for the object, and instantiates the mqtt client.
This method is called internally and typically there is no need to call it from the application code.
Issues a warning if the
mqtt_class_id
has not been configured, even though objects without a capability to communicate are rather crippled.- Return type:
None
- init_topic_base()¶
- Return type:
None
- initialize()¶
Initialize time series database and mqtt networking for use. This method must be called after the object name has been set .
- Return type:
None
- classmethod instantiate(class_id, *args)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args (
Any
) – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- classmethod log_debug(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_error(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_info(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- log_message(type, msg, details='')¶
Publish the given log message to the MQTT ‘log’ topic.
This method constructs a log message with a timestamp, class type, source name, message, and optional details. It then publishes this message to the ‘log’ topic using the MQTT protocol.
- Parameters:
type (
str
) – str The classification or type of the log message (e.g., ‘Error’, ‘Info’).msg (
str
) – str The main log message to be published.details (
str
) – str, optional Additional details about the log message (default is an empty string).
- Return type:
None
- Returns:
None
- Raises:
Exception – If there is an issue with the MQTT client while publishing the message.
Example:
# publish info message to the Juham's 'log' topic self.log_message("Info", f"Some cool message {some_stuff}", str(dict))
- classmethod log_warning(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- make_topic_name(topic)¶
Make topic name for the object. The topic name consists of the base name plus the given ‘topic’.
- Parameters:
topic (str) – topic name
- Returns:
mqtt topic name
- Return type:
str
- make_url()¶
Generate the URL for the composite, including all children.
- Return type:
URL
- mqtt_class_id: str = ''¶
- mqtt_client: Optional[JMqtt | None]¶
- mqtt_host: str = 'localhost'¶
- mqtt_port: int = 1883¶
- mqtt_root_topic: Optional[str] = None¶
- mqtt_topic_base: str¶
- mqtt_topic_control: str¶
- mqtt_topic_log: str¶
- on_connect(client, userdata, flags, rc)[source]¶
Notification on connect.
This method is called whenever the MQTT broker is connected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
flags (int) – Consult MQTT
rc (int) – See MQTT docs
- Return type:
None
- on_disconnect(client, userdata, rc=0)¶
Notification on disconnect.
This method is called whenever the MQTT broker is disconnected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
rc (int) – See MQTT docs
- Return type:
None
- on_message(client, userdata, msg)[source]¶
MQTT message notification on arrived message.
Called whenever a new message is posted on one of the topics the object has subscribed to via subscribe() method. This method is the heart of automation: here, derived subclasses should automate whatever they were designed to automate. For example, they could switch a relay when a boiler temperature sensor signals that the temperature is too low for a comforting shower for say one’s lovely wife.
For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
msg (object) – The MQTT message
- Return type:
None
- property parent: MasterPiece | None¶
- publish(topic, msg, qos=1, retain=True)¶
Publish the given message to the given MQTT topic. For more information consult MQTT.
- Parameters:
topic (str) – topic
msg (str) – message to be published
qos (int, optional) – quality of service. Defaults to 1.
retain (bool, optional) – retain. Defaults to True.
- Return type:
None
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point (
Point
) – point with initialized time stamp.- Return type:
None
… note: NOT IMPLEMENTED YET
- record_power(em)[source]¶
Write from the power (energy) meter to the time series database accordingly.
- Parameters:
ts (float) – utc time
em (dict) – energy meter message
- Return type:
None
- classmethod register()¶
Register the class.
Called immediately upon class initialization, right before the class attributes are loaded from the class specific configuration files.
Subclasses can extend this with custom register functionality:
class MyMasterPiece(MasterPiece): @classmethod def register(cls): super().register() # Don't forget cls._custom_field = True
- Return type:
None
- resolve_url(url)¶
Find a MasterPiece in the hierarchy matching the URL.
- Return type:
Optional
[MasterPiece
]
- root()¶
Fetch the root object
- Returns:
root object
- Return type:
MasterPiece
- run()¶
Start a new thread to runs the network loop in the background.
Allows the main program to continue executing while the MQTT client handles incoming and outgoing messages in the background.
- Return type:
None
- run_forever()¶
Starts the network loop and blocks the main thread, continuously running the loop to process MQTT messages.
The loop will run indefinitely unless the connection is lost or the program is terminated.
- Return type:
None
- classmethod set_log(l)¶
Set logger.
- Parameters:
l (logger) – logger object
- Return type:
None
- shutdown()¶
Shut down all services, free resources, stop threads, disconnect from mqtt, in general, prepare for shutdown.
- Return type:
None
- subscribe(topic)¶
Subscribe to the given MQTT topic.
This method sets up the subscription to the specified MQTT topic and registers the
on_message()
method as the callback for incoming messages.- Parameters:
topic (str) – The MQTT topic to subscribe to.
- Return type:
None
Example:
# configure obj.subscribe('foo/bar')
- warning(msg, details='')¶
Logs the given warning message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point (
Point
) – a measurement describing a time stamp and related attributes for one measurement.- Return type:
None
- write_attempts: int = 3¶
- write_point(name, tags, fields, ts)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- Return type:
None
- class juham.ts.PowerPlanRecord(name='powerplanrecord')[source]¶
Bases:
Base
Power plan time series record.
Listens powerplan topic and updates time series database accordingly.
- classmethod classattrs_from_dict(attributes)¶
Set only the class’s own attributes from a dictionary.
- Return type:
None
- classmethod classattrs_to_dict()¶
Convert the class’s own attributes to a dictionary, excluding inherited and private ones.
- Return type:
Dict
[str
,Any
]
- copy()¶
Create and return a copy of the current object.
This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.
This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.
- Return type:
MasterPiece
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
clone_of_john = john.copy()
- database_class_id: str = 'JInflux'¶
- database_client: Optional[JDatabase | None]¶
- debug(msg, details='')¶
Logs the given debug message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- do(action, context)¶
Execute the given action to the object, by calling the provided action.
- Parameters:
action (Callable[["MasterPiece", Dict[str, Any]], bool]) – A callable that takes
(node
boolean. (context) and returns a)
context (Dict[str, Any]) – Any context data that the action may use.
- Return type:
bool
- Returns:
The return value from the executed action.
- error(msg, details='')¶
Logs the given error message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod factory()¶
Fetch the dictionary holding class names and associated classes.
- Returns:
with class names and associated classes
- Return type:
factory
- classmethod find_class(class_id)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- from_dict(data)¶
Update instance attributes from a dictionary.
- Return type:
None
- classmethod get_class_id()¶
Return the class id of the class. Each class has an unique name that can be used for instantiating the class via
Object.instantiate()
method.- Parameters:
cls (class) – class
- Returns:
unique class identifier through which the class can be instantiated by factory method pattern.
- Return type:
id (str)
- classmethod has_class_method_directly(method_name)¶
Check if the method is defined directly in the class (not inherited).
- Return type:
bool
- info(msg, details='')¶
Logs the given information message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (
str
) – The information message to be logged.details (
str
) – Additional detailed information for the message to be logged
- Return type:
None
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- classmethod init_class(clazz)¶
Initialize class. Registers the class into the class factory .
- Parameters:
clazz (class) – class to be initialized
- Return type:
None
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking. Calls init_topic() to construct topic base name for the object, and instantiates the mqtt client.
This method is called internally and typically there is no need to call it from the application code.
Issues a warning if the
mqtt_class_id
has not been configured, even though objects without a capability to communicate are rather crippled.- Return type:
None
- init_topic_base()¶
- Return type:
None
- initialize()¶
Initialize time series database and mqtt networking for use. This method must be called after the object name has been set .
- Return type:
None
- classmethod instantiate(class_id, *args)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args (
Any
) – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- classmethod log_debug(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_error(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_info(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- log_message(type, msg, details='')¶
Publish the given log message to the MQTT ‘log’ topic.
This method constructs a log message with a timestamp, class type, source name, message, and optional details. It then publishes this message to the ‘log’ topic using the MQTT protocol.
- Parameters:
type (
str
) – str The classification or type of the log message (e.g., ‘Error’, ‘Info’).msg (
str
) – str The main log message to be published.details (
str
) – str, optional Additional details about the log message (default is an empty string).
- Return type:
None
- Returns:
None
- Raises:
Exception – If there is an issue with the MQTT client while publishing the message.
Example:
# publish info message to the Juham's 'log' topic self.log_message("Info", f"Some cool message {some_stuff}", str(dict))
- classmethod log_warning(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- make_topic_name(topic)¶
Make topic name for the object. The topic name consists of the base name plus the given ‘topic’.
- Parameters:
topic (str) – topic name
- Returns:
mqtt topic name
- Return type:
str
- make_url()¶
Generate the URL for the composite, including all children.
- Return type:
URL
- mqtt_class_id: str = ''¶
- mqtt_client: Optional[JMqtt | None]¶
- mqtt_host: str = 'localhost'¶
- mqtt_port: int = 1883¶
- mqtt_root_topic: Optional[str] = None¶
- mqtt_topic_base: str¶
- mqtt_topic_control: str¶
- mqtt_topic_log: str¶
- on_connect(client, userdata, flags, rc)[source]¶
Notification on connect.
This method is called whenever the MQTT broker is connected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
flags (int) – Consult MQTT
rc (int) – See MQTT docs
- Return type:
None
- on_disconnect(client, userdata, rc=0)¶
Notification on disconnect.
This method is called whenever the MQTT broker is disconnected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
rc (int) – See MQTT docs
- Return type:
None
- on_message(client, userdata, msg)[source]¶
MQTT message notification on arrived message.
Called whenever a new message is posted on one of the topics the object has subscribed to via subscribe() method. This method is the heart of automation: here, derived subclasses should automate whatever they were designed to automate. For example, they could switch a relay when a boiler temperature sensor signals that the temperature is too low for a comforting shower for say one’s lovely wife.
For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
msg (object) – The MQTT message
- Return type:
None
- property parent: MasterPiece | None¶
- publish(topic, msg, qos=1, retain=True)¶
Publish the given message to the given MQTT topic. For more information consult MQTT.
- Parameters:
topic (str) – topic
msg (str) – message to be published
qos (int, optional) – quality of service. Defaults to 1.
retain (bool, optional) – retain. Defaults to True.
- Return type:
None
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point (
Point
) – point with initialized time stamp.- Return type:
None
… note: NOT IMPLEMENTED YET
- classmethod register()¶
Register the class.
Called immediately upon class initialization, right before the class attributes are loaded from the class specific configuration files.
Subclasses can extend this with custom register functionality:
class MyMasterPiece(MasterPiece): @classmethod def register(cls): super().register() # Don't forget cls._custom_field = True
- Return type:
None
- resolve_url(url)¶
Find a MasterPiece in the hierarchy matching the URL.
- Return type:
Optional
[MasterPiece
]
- root()¶
Fetch the root object
- Returns:
root object
- Return type:
MasterPiece
- run()¶
Start a new thread to runs the network loop in the background.
Allows the main program to continue executing while the MQTT client handles incoming and outgoing messages in the background.
- Return type:
None
- run_forever()¶
Starts the network loop and blocks the main thread, continuously running the loop to process MQTT messages.
The loop will run indefinitely unless the connection is lost or the program is terminated.
- Return type:
None
- classmethod set_log(l)¶
Set logger.
- Parameters:
l (logger) – logger object
- Return type:
None
- shutdown()¶
Shut down all services, free resources, stop threads, disconnect from mqtt, in general, prepare for shutdown.
- Return type:
None
- subscribe(topic)¶
Subscribe to the given MQTT topic.
This method sets up the subscription to the specified MQTT topic and registers the
on_message()
method as the callback for incoming messages.- Parameters:
topic (str) – The MQTT topic to subscribe to.
- Return type:
None
Example:
# configure obj.subscribe('foo/bar')
- to_dict()¶
Convert instance attributes to a dictionary.
- Return type:
Dict
[str
,Any
]
- warning(msg, details='')¶
Logs the given warning message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point (
Point
) – a measurement describing a time stamp and related attributes for one measurement.- Return type:
None
- write_attempts: int = 3¶
- write_point(name, tags, fields, ts)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- Return type:
None
- class juham.ts.PowerRecord(name='powerrecord')[source]¶
Bases:
Base
Power utilization record.
This class listens the power utilization message and writes the state to time series database.
- classmethod classattrs_from_dict(attributes)¶
Set only the class’s own attributes from a dictionary.
- Return type:
None
- classmethod classattrs_to_dict()¶
Convert the class’s own attributes to a dictionary, excluding inherited and private ones.
- Return type:
Dict
[str
,Any
]
- copy()¶
Create and return a copy of the current object.
This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.
This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.
- Return type:
MasterPiece
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
clone_of_john = john.copy()
- database_class_id: str = 'JInflux'¶
- database_client: Optional[JDatabase | None]¶
- debug(msg, details='')¶
Logs the given debug message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- do(action, context)¶
Execute the given action to the object, by calling the provided action.
- Parameters:
action (Callable[["MasterPiece", Dict[str, Any]], bool]) – A callable that takes
(node
boolean. (context) and returns a)
context (Dict[str, Any]) – Any context data that the action may use.
- Return type:
bool
- Returns:
The return value from the executed action.
- error(msg, details='')¶
Logs the given error message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod factory()¶
Fetch the dictionary holding class names and associated classes.
- Returns:
with class names and associated classes
- Return type:
factory
- classmethod find_class(class_id)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- from_dict(data)¶
Update instance attributes from a dictionary.
- Return type:
None
- classmethod get_class_id()¶
Return the class id of the class. Each class has an unique name that can be used for instantiating the class via
Object.instantiate()
method.- Parameters:
cls (class) – class
- Returns:
unique class identifier through which the class can be instantiated by factory method pattern.
- Return type:
id (str)
- classmethod has_class_method_directly(method_name)¶
Check if the method is defined directly in the class (not inherited).
- Return type:
bool
- info(msg, details='')¶
Logs the given information message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (
str
) – The information message to be logged.details (
str
) – Additional detailed information for the message to be logged
- Return type:
None
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- classmethod init_class(clazz)¶
Initialize class. Registers the class into the class factory .
- Parameters:
clazz (class) – class to be initialized
- Return type:
None
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking. Calls init_topic() to construct topic base name for the object, and instantiates the mqtt client.
This method is called internally and typically there is no need to call it from the application code.
Issues a warning if the
mqtt_class_id
has not been configured, even though objects without a capability to communicate are rather crippled.- Return type:
None
- init_topic_base()¶
- Return type:
None
- initialize()¶
Initialize time series database and mqtt networking for use. This method must be called after the object name has been set .
- Return type:
None
- classmethod instantiate(class_id, *args)¶
Create an instance of the class corresponding to the given class identifier.
- Parameters:
class_id (str) – Identifier of the class to instantiate.
*args (
Any
) – Optional arguments to pass to the class constructor.
- Returns:
An instance of the class corresponding to the given class identifier.
- Return type:
MasterPiece
- classmethod log_debug(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_error(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- classmethod log_info(msg, details='')¶
Logs the given message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- log_message(type, msg, details='')¶
Publish the given log message to the MQTT ‘log’ topic.
This method constructs a log message with a timestamp, class type, source name, message, and optional details. It then publishes this message to the ‘log’ topic using the MQTT protocol.
- Parameters:
type (
str
) – str The classification or type of the log message (e.g., ‘Error’, ‘Info’).msg (
str
) – str The main log message to be published.details (
str
) – str, optional Additional details about the log message (default is an empty string).
- Return type:
None
- Returns:
None
- Raises:
Exception – If there is an issue with the MQTT client while publishing the message.
Example:
# publish info message to the Juham's 'log' topic self.log_message("Info", f"Some cool message {some_stuff}", str(dict))
- classmethod log_warning(msg, details='')¶
Logs the given debug message to the application log.
- Parameters:
msg (str) – The message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- make_topic_name(topic)¶
Make topic name for the object. The topic name consists of the base name plus the given ‘topic’.
- Parameters:
topic (str) – topic name
- Returns:
mqtt topic name
- Return type:
str
- make_url()¶
Generate the URL for the composite, including all children.
- Return type:
URL
- mqtt_class_id: str = ''¶
- mqtt_client: Optional[JMqtt | None]¶
- mqtt_host: str = 'localhost'¶
- mqtt_port: int = 1883¶
- mqtt_root_topic: Optional[str] = None¶
- mqtt_topic_base: str¶
- mqtt_topic_control: str¶
- mqtt_topic_log: str¶
- on_connect(client, userdata, flags, rc)[source]¶
Notification on connect.
This method is called whenever the MQTT broker is connected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
flags (int) – Consult MQTT
rc (int) – See MQTT docs
- Return type:
None
- on_disconnect(client, userdata, rc=0)¶
Notification on disconnect.
This method is called whenever the MQTT broker is disconnected. For more information on this method consult MQTT documentation available in many public sources.
- Parameters:
client (obj) – MQTT client
userdata (Any) – application specific data
rc (int) – See MQTT docs
- Return type:
None
- on_message(client, userdata, msg)[source]¶
Standard mqtt message notification method.
This method is called upon new arrived message.
- Return type:
None
- property parent: MasterPiece | None¶
- publish(topic, msg, qos=1, retain=True)¶
Publish the given message to the given MQTT topic. For more information consult MQTT.
- Parameters:
topic (str) – topic
msg (str) – message to be published
qos (int, optional) – quality of service. Defaults to 1.
retain (bool, optional) – retain. Defaults to True.
- Return type:
None
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point (
Point
) – point with initialized time stamp.- Return type:
None
… note: NOT IMPLEMENTED YET
- classmethod register()¶
Register the class.
Called immediately upon class initialization, right before the class attributes are loaded from the class specific configuration files.
Subclasses can extend this with custom register functionality:
class MyMasterPiece(MasterPiece): @classmethod def register(cls): super().register() # Don't forget cls._custom_field = True
- Return type:
None
- resolve_url(url)¶
Find a MasterPiece in the hierarchy matching the URL.
- Return type:
Optional
[MasterPiece
]
- root()¶
Fetch the root object
- Returns:
root object
- Return type:
MasterPiece
- run()¶
Start a new thread to runs the network loop in the background.
Allows the main program to continue executing while the MQTT client handles incoming and outgoing messages in the background.
- Return type:
None
- run_forever()¶
Starts the network loop and blocks the main thread, continuously running the loop to process MQTT messages.
The loop will run indefinitely unless the connection is lost or the program is terminated.
- Return type:
None
- classmethod set_log(l)¶
Set logger.
- Parameters:
l (logger) – logger object
- Return type:
None
- shutdown()¶
Shut down all services, free resources, stop threads, disconnect from mqtt, in general, prepare for shutdown.
- Return type:
None
- subscribe(topic)¶
Subscribe to the given MQTT topic.
This method sets up the subscription to the specified MQTT topic and registers the
on_message()
method as the callback for incoming messages.- Parameters:
topic (str) – The MQTT topic to subscribe to.
- Return type:
None
Example:
# configure obj.subscribe('foo/bar')
- to_dict()¶
Convert instance attributes to a dictionary.
- Return type:
Dict
[str
,Any
]
- warning(msg, details='')¶
Logs the given warning message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- Return type:
None
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point (
Point
) – a measurement describing a time stamp and related attributes for one measurement.- Return type:
None
- write_attempts: int = 3¶
- write_point(name, tags, fields, ts)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- Return type:
None