juham_automation

Description

Juham - Juha’s Ultimate Home Automation Masterpiece

class juham_automation.ElectricityPriceTs(name='electricityprice_ts')[source]

Bases: JuhamTs

Spot electricity price for reading hourly electricity prices from

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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 = ''
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)
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 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

measurement(name)
Return type:

Measurement

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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

on_spot(m)[source]

Write hourly spot electricity prices to time series database.

Parameters:

m (dict) – holding hourlys spot electricity prices

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)
Return type:

None

read_last_value(measurement, tags=None, fields=None)
Return type:

dict[str, Any]

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]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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)
Return type:

None

write_attempts: int = 3
write_point(name, tags, fields, ts)
Return type:

None

class juham_automation.EnergyCostCalculator(name='ecc')[source]

Bases: Juham

The EnergyCostCalculator class calculates the net energy balance between produced and consumed energy for Time-Based Settlement (TBS). It performs the following functions:

  • Subscribes to ‘spot’ and ‘power’ MQTT topics.

  • Calculates the net energy and the rate of change of the net energy per hour and per day (24h)

  • Publishes the calculated values to the MQTT net energy balance topic.

  • Stores the data in a time series database.

This information helps other home automation components optimize energy usage and minimize electricity bills.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

calculate_net_energy_cost(ts_prev, ts_now, energy)[source]

Given time interval as start and stop Calculate the cost over the given time period. Positive values indicate revenue, negative cost.

Parameters:
  • ts_prev (timestamp) – beginning time stamp of the interval

  • ts_now (timestamp) – end of the interval

  • energy (float) – energy consumed during the time interval

Return type:

float

Returns:

Cost or revenue

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()
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.

energy_balancing_interval: float = 3600
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)

get_prices(ts_prev, ts_now)[source]

Fetch the electricity prices for the given two subsequent time stamps.

Parameters:
  • ts_prev (float) – previous time

  • ts_now (float) – current time

Return type:

tuple[float, float]

Returns:

Electricity prices for the given interval

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_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

init_topics()[source]
Return type:

None

initialize()

Initialize 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

map_kwh_prices_to_joules(price)[source]

Convert the given electricity price in kWh to Watt seconds (J) :type price: float :param price: electricity price given as kWh :type price: float

Return type:

float

Returns:

Electricity price per watt second (J)

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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

on_powerconsumption(ts_now, m)[source]

Calculate net energy cost and update the hourly consumption attribute accordingly.

Parameters:
  • ts_now (float) – time stamp of the energy consumed

  • m (dict) – Juham MQTT message holding energy reading

Return type:

None

on_spot(spot)[source]

Stores the received per hour electricity prices to spots list.

Parameters:

spot (list) – list of hourly spot prices

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

publish_energy_cost(ts_now, site, cost_hour, cost_day)[source]

Publish daily and hourly energy cost/revenue

Parameters:
  • ts_now (float) – timestamp

  • site (str) – site

  • cost_hour (float) – cost or revenue per hour.

  • cost_day (float) – cost or revenue per day

Return type:

None

publish_net_energy_balance(ts_now, site, energy, power)[source]

Publish the net energy balance for the current energy balancing interval, as well as the real-time power at which energy is currently being produced or consumed (the rate of change of net energy).

Parameters:
  • ts_now (float) – timestamp

  • site (str) – site

  • energy (float) – cost or revenue.

  • power (float) – momentary power (rage of change of energy)

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]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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_attempts: int = 3
class juham_automation.EnergyCostCalculatorTs(name='ecc_ts')[source]

Bases: JuhamTs

The EnergyCostCalculator recorder.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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 = ''
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)
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 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

measurement(name)
Return type:

Measurement

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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)
Return type:

None

read_last_value(measurement, tags=None, fields=None)
Return type:

dict[str, Any]

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]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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)
Return type:

None

write_attempts: int = 3
write_point(name, tags, fields, ts)
Return type:

None

class juham_automation.ForecastTs(name='forecast_ts')[source]

Bases: JuhamTs

Forecast database record.

This class listens the forecast topic and writes to the time series database.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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 = ''
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)
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 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

measurement(name)
Return type:

Measurement

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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)
Return type:

None

read_last_value(measurement, tags=None, fields=None)
Return type:

dict[str, Any]

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]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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)
Return type:

None

write_attempts: int = 3
write_point(name, tags, fields, ts)
Return type:

None

class juham_automation.HotWaterOptimizer(name, temperature_sensor, start_hour, num_hours, spot_limit)[source]

Bases: Juham

Automation class for optimized control of temperature driven home energy consumers e.g hot water radiators. Reads spot prices, boiler water temperatures to minimize electricity bill. Additional control over heating is provided by the following attributes

schedule_start_hour

hour heating can start, in local time

Type:

float

schedule_stop_hour

hour heating is forced to stop

Type:

float

start_hour

start_hour (int): ordinal of the first allowed electricity price slot to be consumed

Type:

float

num_hours

the number of hour slots allowed

Type:

int

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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]

compute_fom(solpower, spot, hour)[source]

Compute UOI - utilization optimization index.

Parameters:
  • solpower (float) – current solar power forecast

  • spot (float) – spot price

  • hour (float) – the hour of the day

Returns:

utilization optimization index

Return type:

float

consider_heating(ts)[source]

Consider whether the target boiler needs heating.

Parameters:

ts (float) – current UTC time

Returns:

1 if heating is needed, 0 if not

Return type:

int

consider_net_energy_balance(ts)[source]

Check when there is enough energy available for the radiators heat the water the remaining time within the balancing interval, and switch the balancing mode on. If the remaining time in the current balancing slot is less than the threshold then optimize out.

Parameters:

ts (float) – current time

Returns:

true if production exceeds the consumption

Return type:

bool

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()
create_heating_plan()[source]

Create heating plan.

Returns:

list of heating entries

Return type:

int

create_power_plan()[source]

Create power plan.

Returns:

list of utilization entries

Return type:

list

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.

energy_balancing_interval: float = 3600
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

heating_hours_per_day = 4
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_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 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

maximum_boiler_temperature = 70
minimum_boiler_temperature = 43
mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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

on_powerplan(ts_utc_now)[source]

Apply power plan.

Parameters:

ts_utc_now (float) – utc time

Return type:

None

operation_threshold = 300
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

radiator_power = 3000
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

schedule_start_hour: float = 0
schedule_stop_hour: float = 0
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

sort_by_power(solarpower, ts_utc)[source]

Sort forecast of solarpower to decreasing order.

Parameters:
  • solarpower (list) – list of entries describing hourly solar energy forecast

  • ts_utc (float) – start time, for exluding entries that are in the past

Returns:

list from the highest solarenergy to lowest.

Return type:

list

sort_by_rank(hours, ts_utc_now)[source]

Sort the given electricity prices by their rank value. Given a list of electricity prices, return a sorted list from the cheapest to the most expensive hours. Entries that represent electricity prices in the past are excluded.

Parameters:
  • hours (list) – list of hourly electricity prices

  • ts_utc_now (float) – current time

Returns:

sorted list of electricity prices

Return type:

list

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')
timezone = 'Europe/Helsinki'
to_dict()

Convert instance attributes to a dictionary.

Return type:

Dict[str, Any]

uoi_limit = 0.75
update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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_attempts: int = 3
class juham_automation.JApp(name)[source]

Bases: Application

Juham home automation application base class. Registers new plugin group ‘juham’ on which general purpose Juham plugins can be written on.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

add(h)

Add new object as children. The object to be inserted must be derived from MasterPiece base class.

Parameters:

h (T) – object to be inserted.

Return type:

None

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]

color: str = 'yellow'
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()
debug(msg, details='')

Logs the given debug message to the application log.

Parameters:
  • msg (str) – The information message to be logged.

  • details (str) – Additional detailed information for the message to be logged

Return type:

None

deserialize()

Deserialize instances from the startup file specified by ‘serialization_file’ class attribute, or ‘–file’ startup argument.

Return type:

None

do(action, context)

Recursively traverses the tree, from root to leaf, left to right direction, calling the provided action on each node.

Parameters:
  • action (Callable[[MasterPiece, Dict[str, Any]], bool]) – A callable that takes (node, context) and returns a boolean.

  • context (Dict[str, Any]) – Any context data that the action may use.

Return type:

bool

Returns:

None

error(msg, details='')

Logs the given error 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 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)

Recursively deserialize the group from a dictionary, including its children.

Parameters:

data (dict) – data to deserialize from.

Return type:

None

classmethod get_app_id()

Fetch the application id. Application id determines the folder in which the configuration files for classes are held. Note that a single package can ship with more than just one executable application, all with the same application id.

..todo: Application id ‘_app_id’ is prefixed with ‘_’ to signal that it is a private attribute (python) and that should not be serialized (masterpiece). Isn’t there something like @transient in Python? App id needs to be accessed outside, which is why this get_app_id() method is needed.

Returns:

application id determign application registry for class attribute serialization

Return type:

str

classmethod get_argmaestro()

Fetch the plugmaster object reponsible for plugin management.

Returns:

object

Return type:

PlugMaster

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 get_configuration_filename(name)

Generate the user specific file name of the configuration file based on the class name.

Parameters:

name (str) – object managing plugins

Return type:

str

classmethod get_plugmaster()

Fetch the plugmaster object reponsible for plugin management.

Returns:

object

Return type:

PlugMaster

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 application log.

Parameters:
  • msg (str) – The information message to be logged.

  • details (str) – Additional detailed information for the message to be logged

Return type:

None

classmethod init_app_id(app_id='myapp')

Initialize application id. Parses initial startup that depend on application id. Must be called before any classes are instanced.

Parameters:
  • -a (str) – Application ID.

  • --app (str) – Application ID.

  • -c (str) – Configuration name, empty string for no configuration

  • --config (str) – Configuration name, empty string for no configuration

  • -i (bool) – Whether to create class configuration files if not already created.

  • --init (bool) – Whether to create class configuration files if not already created.

Return type:

None

classmethod init_class(clazz)

Initialize class. Registers the class into the class factory .

Parameters:

clazz (class) – class to be initialized

Return type:

None

install_plugins()

Installs plugins into the application by invoking the install() method of each loaded plugin module. Note: This method is intended for testing and debugging purposes only. In a typical use case, the application should handle the instantiation of classes and manage their attributes as needed.

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

instantiate_classes()[source]

Instantiate automation classes .

Return type:

None

Returns:

None

instantiate_plugin_by_name(name)

Installs the plugin by name, that is, instantiates the plugin class and inserts the instance as child to the application. :type name: str :param name: name of the plugin class :type name: str

Return type:

Optional[MasterPiece]

classmethod load_configuration()

Load class attributes from a configuration file.

Return type:

None

classmethod load_plugins()

Loads and initializes all plugins for instantiation. This method corresponds to importing Python modules with import clauses.

Return type:

None

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_level: int = 0
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_url()

Generate the URL for the composite, including all children.

Return type:

URL

property parent: MasterPiece | None
classmethod parse_args()

Register classes with ArgMaestro.

Return type:

None

plugin_groups = ['masterpiece', 'juham']
plugins: List[Type[MasterPiece]] = []
print()

Print the instance hierarchy of the application using TreeVisualizer

Return type:

None

classmethod register()[source]

Register plugin group juham.

Return type:

None

classmethod register_plugin_group(name)

Registers a new plugin group within the application. Only plugins that match the registered groups will be loaded. By default, all ‘masterpiece’ plugins are included. Frameworks and apps built on the MasterPiece framework can define more group names, enabling plugins to be developed for any those as well.

Parameters:

name (str) – The name of the plugin group to be registered

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()

Dispatches first the call to all children and then to the super class. It is up to the sub classes to implement the actual functionality for this method.

Return type:

None

run_forever()

Dispatches first the call to all children and then to the super class. It is up to the sub classes to implement the actual functionality for this method.

Return type:

None

classmethod save_configuration()

Create class configuration file, if configuration is enabled and if the file does not exist yet. See –config startup argument.

Return type:

None

serialization_file: str = ''
serialization_format: str = 'JsonFormat'
serialize()

Serialize application state to the file specified by ‘serialization_file’ class attribute’.

Return type:

None

classmethod set_argmaestro(argmaestro)

Set the argmaestro object reponsible for plugin management.

Parameters:

argmaestro (PlugMaster) – object managing plugins

Return type:

None

classmethod set_log(l)

Set logger.

Parameters:

l (logger) – logger object

Return type:

None

classmethod set_plugmaster(plugmaster)

Set the plugmaster object reponsible for plugin management.

Parameters:

plugmaster (PlugMaster) – object managing plugins

Return type:

None

shutdown()

Shuts down the object. First, it dispatches the call to all child objects, then calls the superclass method to stop the associated payload object, if one exists.

Return type:

None

shutdown_children()

Shuts down the children.

Return type:

None

start_children()

Start all children.

Return type:

None

to_dict()

Convert instance attributes to a dictionary.

Return type:

Dict[str, Any]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

warning(msg, details='')

Logs the given warning 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

class juham_automation.LogTs(name='log_ts')[source]

Bases: JuhamTs

Class recording application events, such as warnings and errors, to time series database.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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 = ''
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)
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 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

measurement(name)
Return type:

Measurement

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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 successful

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)
Return type:

None

read_last_value(measurement, tags=None, fields=None)
Return type:

dict[str, Any]

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]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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)
Return type:

None

write_attempts: int = 3
write_point(name, tags, fields, ts)
Return type:

None

class juham_automation.PowerMeterSimulator(name='em', interval=0)[source]

Bases: JuhamThread

Simulator energy meter sensor. Spawns a thread to simulate Shelly PM mqtt messages

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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 = ''
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

disconnect()

Request the asynchronous acquisition thread to stop after it has finished its current job. This method does not wait for the thread to stop. See shutdown().

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)[source]

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)
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 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

measurement(name)
Return type:

Measurement

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: str = ''
on_connect(client, userdata, flags, rc)

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_event(em)

Notification event callback e.g info or warning.

Parameters:

em (dictionary) – dictionary describing the event

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

on_sensor(em)[source]

Handle data coming from the energy meter.

Simply log the event to indicate the presense of simulated device. :type em: dict[Any, Any] :param em: data from the sensor :type em: dict

Return type:

None

property parent: MasterPiece | None
power: float = 1000.0
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)
Return type:

None

read_last_value(measurement, tags=None, fields=None)
Return type:

dict[str, Any]

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()[source]

Initialize and start the asynchronous acquisition thread.

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()[source]

Convert instance attributes to a dictionary.

Return type:

Dict[str, Any]

update_interval: float = 10
update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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

workerThreadId = 'PowerMeterSimulatorThread'
write(point)
Return type:

None

write_attempts: int = 3
write_point(name, tags, fields, ts)
Return type:

None

class juham_automation.PowerMeterTs(name='powermeter_record')[source]

Bases: JuhamTs

Power meter recorder.

Listens ‘powerconsumption’ topic and records the corresponding time series.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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 = ''
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)[source]

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)
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 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

measurement(name)
Return type:

Measurement

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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)
Return type:

None

read_last_value(measurement, tags=None, fields=None)
Return type:

dict[str, Any]

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')
to_dict()[source]

Convert instance attributes to a dictionary.

Return type:

Dict[str, Any]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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)
Return type:

None

write_attempts: int = 3
write_point(name, tags, fields, ts)
Return type:

None

class juham_automation.PowerPlanTs(name='powerplan_ts')[source]

Bases: JuhamTs

Power plan time series record.

Listens powerplan topic and updates time series database accordingly.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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 = ''
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)
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 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

measurement(name)
Return type:

Measurement

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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)
Return type:

None

read_last_value(measurement, tags=None, fields=None)
Return type:

dict[str, Any]

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]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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)
Return type:

None

write_attempts: int = 3
write_point(name, tags, fields, ts)
Return type:

None

class juham_automation.PowerTs(name='power_ts')[source]

Bases: JuhamTs

Power utilization record.

This class listens the power utilization message and writes the state to time series database.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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 = ''
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)
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 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

measurement(name)
Return type:

Measurement

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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)
Return type:

None

read_last_value(measurement, tags=None, fields=None)
Return type:

dict[str, Any]

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]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

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)
Return type:

None

write_attempts: int = 3
write_point(name, tags, fields, ts)
Return type:

None

class juham_automation.SpotHintaFi(name='rspothintafi')[source]

Bases: JuhamThread

Spot electricity price for reading hourly electricity prices from https://api.spot-hinta.fi site.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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 = ''
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

disconnect()

Request the asynchronous acquisition thread to stop after it has finished its current job. This method does not wait for the thread to stop. See shutdown().

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)[source]

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)
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 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

measurement(name)
Return type:

Measurement

mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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_event(em)

Notification event callback e.g info or warning.

Parameters:

em (dictionary) – dictionary describing the event

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

on_spot(m)[source]

Write hourly spot electricity prices to time series database.

Parameters:

m (dict) – holding hourly spot electricity prices

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)
Return type:

None

read_last_value(measurement, tags=None, fields=None)
Return type:

dict[str, Any]

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()[source]

Initialize and start the asynchronous acquisition thread.

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()[source]

Convert instance attributes to a dictionary.

Return type:

Dict[str, Any]

update_interval = 43200
update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

url = 'https://api.spot-hinta.fi/TodayAndDayForward'
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

worker_thread_id = 'SpotHintaFiThread'
write(point)
Return type:

None

write_attempts: int = 3
write_point(name, tags, fields, ts)
Return type:

None

class juham_automation.WaterCirculator(name, temperature_sensor)[source]

Bases: Juham

Hot Water Circulation Automation

This system monitors motion sensor data to detect home occupancy.

  • When motion is detected: The water circulator pump is activated, ensuring hot water is

    instantly available when the tap is turned on.

  • When no motion is detected for a specified period (in seconds): The pump automatically

    switches off to conserve energy.

Future improvement idea

In cold countries, such as Finland, energy conservation during the winter season may not be a priority. In this case, an additional temperature sensor measuring the outside temperature could be used to determine whether the circulator should be switched off at all. The circulating water could potentially act as an additional heating radiator.

Points to consider

  • Switching the pump on and off may affect its lifetime.

  • Keeping the pump running with hot water could impact the lifespan of the pipes, potentially causing corrosion due to constant hot water flow.

acquire_time_spent()

Reads off the average time the thread has spent in its update() method since the last call, and resets the statistics for the next measurement cycle. This method can be used for monitoring healtiness of the thread.

Returns:

elapsed seconds.

Return type:

elapsed (float)

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()
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_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 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

min_temperature = 37
mqtt_class_id: str = ''
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: 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

on_motion_sensor(m, ts_utc_now)[source]

Control the water cirulator bump.

Given message from the motion sensor consider switching the circulator bump on.

Parameters:
  • msg (dict) – directionary holding motion sensor data

  • ts_utc_now (float) – current time stamp

Return type:

None

on_temperature_sensor(m, ts_utc_now)[source]

Handle message from the hot water pipe temperature sensor. Records the temperature and updates the water_temperature_updated attribute.

Parameters:
  • m (dict) – temperature reading from the hot water blump sensor

  • ts_utc_now (float) – _current utc time

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

publish_relay_state(state)[source]

Publish power status.

Parameters:

state (int) – 1 for on, 0 for off, as defined by Juham ‘power’ topic

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]

update_metrics(elapsed)

Updates the number of update() methods calld, and time spent in the method. This method is called internally from the update() method.

Parameters:

elapsed (float) – elapsed seconds.

Return type:

None

uptime = 3600
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_attempts: int = 3