Shellies — juham-shelly documentation

# Shellies

Adds support for various Shelly devices.

## Description

Classes for Shelly(TM) IoT product family.

These classes implement the interface between Shelly devices and the Juham framework. They listen appropriate messages in the juham mqtt network and control their Shelly devices accordingly, as well as listen the sensor data generated by Shellys and publish it in the standard Juham format.

class juham_shelly.Shelly(name, mqtt_prefix='')

  Bases: `JuhamTs`

  Base class for shelly product family.

  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.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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)

    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)

    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_shelly.Shelly1G3(name, unit, relay)

  Bases: `Shelly`

  Automation class for controlling Shelly Wifi relay. Subscribes to ‘power’ topic and controls the Shelly relay 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 = ''
  database_client: Optional[Union[TimeSeries, None]]
  debug(msg, details='')

    Logs the given debug message to the database after logging it using the BaseClass’s info() method.

    Parameters:

      - msg (str) – The information message to be logged.

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

    Return type:

      `None`

  do(action, context)

    Execute the given action to the object, by calling the provided action.

    Parameters:

      - action (Callable[["MasterPiece", dict[str, Any]], bool]) – A callable that takes

      - (node

      - boolean. (context) and returns a)

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

    Return type:

      `bool`

    Returns:

      The return value from the executed action.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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_client: Optional[Union[Mqtt, None]]
  mqtt_host: str = 'localhost'
  mqtt_port: int = 1883
  mqtt_prefix: str
  mqtt_root_topic: str = ''
  mqtt_topic_base: str
  mqtt_topic_control: str
  mqtt_topic_log: 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_message(client, userdata, msg)

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

    Process power_topic message.

    Parameters:

      m (dict) – holding data from the power sensor

    Return type:

      `None`

  property parent: MasterPiece | None
  power_topic = 'power'
  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`

  relay_started: float
  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`

  shelly_relay_command = '/command/switch:0'
  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_shelly.ShellyDHT22(name, mqtt_prefix)

  Bases: `Shelly`

  Shelly Plus add-on with DHT22 humidity, temperature sensor.

  Listens MQTT messages from dht22 (am2302) humidity sensor attached to Shelly add-on module and writes them 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 = ''
  database_client: Optional[Union[TimeSeries, None]]
  debug(msg, details='')

    Logs the given debug message to the database after logging it using the BaseClass’s info() method.

    Parameters:

      - msg (str) – The information message to be logged.

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

    Return type:

      `None`

  do(action, context)

    Execute the given action to the object, by calling the provided action.

    Parameters:

      - action (Callable[["MasterPiece", dict[str, Any]], bool]) – A callable that takes

      - (node

      - boolean. (context) and returns a)

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

    Return type:

      `bool`

    Returns:

      The return value from the executed action.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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_client: Optional[Union[Mqtt, None]]
  mqtt_host: str = 'localhost'
  mqtt_port: int = 1883
  mqtt_prefix: str
  mqtt_root_topic: str = ''
  mqtt_topic_base: str
  mqtt_topic_control: str
  mqtt_topic_log: 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_message(client, userdata, msg)

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

    Map Shelly Plus 1GM specific event to juham format and post it to temperature topic.

    Parameters:

      params (dict) – message from Shelly Plus 1 wifi relay

    Return type:

      `None`

  on_value(ts, key, value, attr, unit)
    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`

  relay_started: float
  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`

  shelly_topic = '/events/rpc'
  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_shelly.ShellyDS18B20(name, mqtt_prefix)

  Bases: `Shelly`

  Shelly Plus 1 smart relay with DS18B20 temperature sensors .

  Listens MQTT messages from DS18B20 temperature sensors attached to Shelly 1 PM Add on module, posts them to Juham temperature topic, and writes them 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 = ''
  database_client: Optional[Union[TimeSeries, None]]
  debug(msg, details='')

    Logs the given debug message to the database after logging it using the BaseClass’s info() method.

    Parameters:

      - msg (str) – The information message to be logged.

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

    Return type:

      `None`

  do(action, context)

    Execute the given action to the object, by calling the provided action.

    Parameters:

      - action (Callable[["MasterPiece", dict[str, Any]], bool]) – A callable that takes

      - (node

      - boolean. (context) and returns a)

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

    Return type:

      `bool`

    Returns:

      The return value from the executed action.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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_client: Optional[Union[Mqtt, None]]
  mqtt_host: str = 'localhost'
  mqtt_port: int = 1883
  mqtt_prefix: str
  mqtt_root_topic: str = ''
  mqtt_topic_base: str
  mqtt_topic_control: str
  mqtt_topic_log: 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_message(client, userdata, msg)

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

    Map Shelly Plus 1 specific event to juham format and post it to temperature topic.

    Parameters:

      params (dict) – message from Shelly Plus 1 wifi relay

    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`

  relay_started: float
  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`

  shelly_topic = '/events/rpc'
  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_shelly.ShellyMotion(name='shellymotion')

  Bases: `Shelly`

  Shelly Motion 2 - a wifi motion sensor with light and temperature metering.

  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 = ''
  database_client: Optional[Union[TimeSeries, None]]
  debug(msg, details='')

    Logs the given debug message to the database after logging it using the BaseClass’s info() method.

    Parameters:

      - msg (str) – The information message to be logged.

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

    Return type:

      `None`

  do(action, context)

    Execute the given action to the object, by calling the provided action.

    Parameters:

      - action (Callable[["MasterPiece", dict[str, Any]], bool]) – A callable that takes

      - (node

      - boolean. (context) and returns a)

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

    Return type:

      `bool`

    Returns:

      The return value from the executed action.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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_client: Optional[Union[Mqtt, None]]
  mqtt_host: str = 'localhost'
  mqtt_port: int = 1883
  mqtt_prefix: str
  mqtt_root_topic: str = ''
  mqtt_topic_base: str
  mqtt_topic_control: str
  mqtt_topic_log: 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_message(client, userdata, msg)

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

    Handle motion sensor event. This method reads the incoming event, translates it, and publishes it to the Juham topic. It also writes the attributes to the time series database.

    Parameters:

      m (dict) – MQTT event from Shelly motion sensor

    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`

  relay_started: float
  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`

  shelly_topic = 'shellies/shellymotion2/info'
  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_shelly.ShellyMotionSimulator(name='shellymotionsensor', topic='', interval=60)

  Bases: `JuhamThread`, `Shelly`

  Simulator for Shelly Motion 2 - a wifi motion sensor. Spawns a thread to generate MQTT messages as if they origin from the actual Shelly motion sensor

  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 = ''
  database_client: Optional[Union[TimeSeries, None]]
  debug(msg, details='')

    Logs the given debug message to the database after logging it using the BaseClass’s info() method.

    Parameters:

      - msg (str) – The information message to be logged.

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

    Return type:

      `None`

  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.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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_client: Optional[Union[Mqtt, None]]
  mqtt_host: str = 'localhost'
  mqtt_port: int = 1883
  mqtt_prefix: str
  mqtt_root_topic: str = ''
  mqtt_topic_base: str
  mqtt_topic_control: str
  mqtt_topic_log: 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)

    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)

    Handle data coming from the Shelly motion sensors.

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

    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`

  relay_started: float
  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()

    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`

  shelly_topic = 'shellies/shellymotion2/info'
  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_interval = 60
  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 = 'ShellyMotionSimulatorThread'
  write(point)
    Return type:

      `None`

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

      `None`

class juham_shelly.ShellyMotionSimulatorThread(topic='', interval=60)

  Bases: `MasterPieceThread`

  Thread simulating Shelly Plus 1 wifi relay with four temperature sensors.

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

  property daemon

    A boolean value indicating whether this thread is a daemon thread.

    This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

    The entire Python program exits when only daemon threads are left.

  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`

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

    Parameters:

      - msg (str) – The message to be logged.

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

    Return type:

      `None`

  event_topic: str = ''
  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`

  getName()

    Return a string used for identification purposes only.

    This method is deprecated, use the name attribute instead.

  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`

  property ident

    Thread identifier of this thread or None if it has not been started.

    This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

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

    Initialize class. Registers the class into the class factory .

    Parameters:

      clazz (class) – class to be initialized

    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

  isDaemon()

    Return whether this thread is a daemon.

    This method is deprecated, use the daemon attribute instead.

  is_alive()

    Return whether the thread is alive.

    This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

  join(timeout=None)

    Wait until the thread terminates.

    This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

    When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

    When the timeout argument is not present or None, the operation will block until the thread terminates.

    A thread can be join()ed many times.

    join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

  log(type, msg, details)

    Log event to event log.

    Parameters:

      - type (str) – one of the following: “info”, “debug”, “warning”, “error”

      - msg (str) – message to be logged

      - details (str) – detailed description

    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`

  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`

  mqtt_root_topic = ''
  property name

    A string used for identification purposes only.

    It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

  property native_id

    Native integral thread ID of this thread, or None if it has not been started.

    This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

  property parent: MasterPiece | None
  process_system_status(start_time)
    Return type:

      `None`

  publish(topic, message, qos=1, retain=True)

    Publish the given message to given MQTT topic with specified quality of service and retain.

    Parameters:

      - topic (str) – topic

      - message (str) – message to be published

      - qos (int) – quality of service

      - retain (bool) – retain the 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()

    Thread loop.

    Calls update() method in a loop and if the return value is True sleeps the update_interval() number of seconds before the next update call. If the update method returns False then the error is logged, and the sleep time is shortened to 5 seconds to retry. After three subsequent failures the update_interval is reset to original

    Return type:

      `None`

  run_forever()

    Run the payload forever. This method will return only when violently terminated. If the object does not have playload object, or it is not instance of ‘MasterPiece’ class then returns immediately and this method has no effect.

    Return type:

      `None`

  setDaemon(daemonic)

    Set whether this thread is a daemon.

    This method is deprecated, use the .daemon property instead.

  setName(name)

    Set the name string for this thread.

    This method is deprecated, use the name attribute instead.

  classmethod set_log(l)

    Set logger.

    Parameters:

      l (logger) – logger object

    Return type:

      `None`

  shutdown()

    Shutdown the payload object. If the payload object is None, or is not instance of MasterPiece, then the call has no effect.

    Return type:

      `None`

  start()

    Start the thread’s activity.

    It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

    This method will raise a RuntimeError if called more than once on the same thread object.

  stop()

    Request the thread to stop processing further tasks.

    Note that the method does not wait the thread to terminate. If the thread is sleeping, it will be awakened and stopped. If the thread is in the middle of its code execution, it will finish its current job before stopping. In oder to wait until the thread has completed its call join() method.

    Return type:

      `None`

  systemstatus_topic: str = 'system'
  to_dict()

    Convert instance attributes to a dictionary.

    Return type:

      `dict`[`str`, `Any`]

  update()

    Method called from the threads run loop.

    Up to the sub classes to implement.

    Returns:

      True upon succesfull update. False implies an error .

    Return type:

      bool

  update_interval()

    Fetch the update interval in seconds. The default is 60.

    Returns:

      number of seconds

    Return type:

      float

  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_shelly.ShellyPlus1(name, unit, relay)

  Bases: `Shelly`

  Automation class for controlling Shelly Wifi relay. Subscribes to ‘power’ topic and controls the Shelly relay 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 = ''
  database_client: Optional[Union[TimeSeries, None]]
  debug(msg, details='')

    Logs the given debug message to the database after logging it using the BaseClass’s info() method.

    Parameters:

      - msg (str) – The information message to be logged.

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

    Return type:

      `None`

  do(action, context)

    Execute the given action to the object, by calling the provided action.

    Parameters:

      - action (Callable[["MasterPiece", dict[str, Any]], bool]) – A callable that takes

      - (node

      - boolean. (context) and returns a)

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

    Return type:

      `bool`

    Returns:

      The return value from the executed action.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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_client: Optional[Union[Mqtt, None]]
  mqtt_host: str = 'localhost'
  mqtt_port: int = 1883
  mqtt_prefix: str
  mqtt_root_topic: str = ''
  mqtt_topic_base: str
  mqtt_topic_control: str
  mqtt_topic_log: 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_message(client, userdata, msg)

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

    Process power_topic message.

    Parameters:

      m (dict) – holding data from the power sensor

    Return type:

      `None`

  property parent: MasterPiece | None
  power_topic = 'power'
  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`

  relay_started: float
  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`

  shelly_relay_command = '/command/switch:0'
  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_shelly.ShellyPlusAddOnSimulator(name='shellyplus1-simulator', topic='', interval=60.0, mqtt_prefix='shellyplus1-a0a3b3c309c4')

  Bases: `JuhamThread`, `Shelly`

  Simulator for ShellyPlus1 wifi relay.

  Spawns an asynchronous thread to generate data from temperature sensors.

  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 = ''
  database_client: Optional[Union[TimeSeries, None]]
  debug(msg, details='')

    Logs the given debug message to the database after logging it using the BaseClass’s info() method.

    Parameters:

      - msg (str) – The information message to be logged.

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

    Return type:

      `None`

  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.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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_client: Optional[Union[Mqtt, None]]
  mqtt_host: str = 'localhost'
  mqtt_port: int = 1883
  mqtt_prefix: str
  mqtt_root_topic: str = ''
  mqtt_topic_base: str
  mqtt_topic_control: str
  mqtt_topic_log: 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)

    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)

    Handle data coming from the the Shelly sensors.

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

    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`

  relay_started: float
  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()

    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`

  shelly_topic: `str` = '/events/rpc'
  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_interval: `float` = 60
  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: `str` = 'ShellyPlusAddOnSimulatorThread'
  write(point)
    Return type:

      `None`

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

      `None`

class juham_shelly.ShellyPlusAddOnSimulatorThread(topic='', interval=60)

  Bases: `MasterPieceThread`

  Thread simulating Shelly Plus 1 wifi relay with four temperature sensors.

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

  property daemon

    A boolean value indicating whether this thread is a daemon thread.

    This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

    The entire Python program exits when only daemon threads are left.

  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`

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

    Parameters:

      - msg (str) – The message to be logged.

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

    Return type:

      `None`

  event_topic: str = ''
  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`

  getName()

    Return a string used for identification purposes only.

    This method is deprecated, use the name attribute instead.

  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`

  property ident

    Thread identifier of this thread or None if it has not been started.

    This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

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

    Initialize class. Registers the class into the class factory .

    Parameters:

      clazz (class) – class to be initialized

    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

  isDaemon()

    Return whether this thread is a daemon.

    This method is deprecated, use the daemon attribute instead.

  is_alive()

    Return whether the thread is alive.

    This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

  join(timeout=None)

    Wait until the thread terminates.

    This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

    When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

    When the timeout argument is not present or None, the operation will block until the thread terminates.

    A thread can be join()ed many times.

    join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

  log(type, msg, details)

    Log event to event log.

    Parameters:

      - type (str) – one of the following: “info”, “debug”, “warning”, “error”

      - msg (str) – message to be logged

      - details (str) – detailed description

    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`

  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`

  mqtt_root_topic = ''
  property name

    A string used for identification purposes only.

    It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

  property native_id

    Native integral thread ID of this thread, or None if it has not been started.

    This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

  property parent: MasterPiece | None
  process_system_status(start_time)
    Return type:

      `None`

  publish(topic, message, qos=1, retain=True)

    Publish the given message to given MQTT topic with specified quality of service and retain.

    Parameters:

      - topic (str) – topic

      - message (str) – message to be published

      - qos (int) – quality of service

      - retain (bool) – retain the 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()

    Thread loop.

    Calls update() method in a loop and if the return value is True sleeps the update_interval() number of seconds before the next update call. If the update method returns False then the error is logged, and the sleep time is shortened to 5 seconds to retry. After three subsequent failures the update_interval is reset to original

    Return type:

      `None`

  run_forever()

    Run the payload forever. This method will return only when violently terminated. If the object does not have playload object, or it is not instance of ‘MasterPiece’ class then returns immediately and this method has no effect.

    Return type:

      `None`

  setDaemon(daemonic)

    Set whether this thread is a daemon.

    This method is deprecated, use the .daemon property instead.

  setName(name)

    Set the name string for this thread.

    This method is deprecated, use the name attribute instead.

  classmethod set_log(l)

    Set logger.

    Parameters:

      l (logger) – logger object

    Return type:

      `None`

  shutdown()

    Shutdown the payload object. If the payload object is None, or is not instance of MasterPiece, then the call has no effect.

    Return type:

      `None`

  start()

    Start the thread’s activity.

    It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

    This method will raise a RuntimeError if called more than once on the same thread object.

  stop()

    Request the thread to stop processing further tasks.

    Note that the method does not wait the thread to terminate. If the thread is sleeping, it will be awakened and stopped. If the thread is in the middle of its code execution, it will finish its current job before stopping. In oder to wait until the thread has completed its call join() method.

    Return type:

      `None`

  systemstatus_topic: str = 'system'
  to_dict()

    Convert instance attributes to a dictionary.

    Return type:

      `dict`[`str`, `Any`]

  update()

    Method called from the threads run loop.

    Up to the sub classes to implement.

    Returns:

      True upon succesfull update. False implies an error .

    Return type:

      bool

  update_interval()

    Fetch the update interval in seconds. The default is 60.

    Returns:

      number of seconds

    Return type:

      float

  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_shelly.ShellyPro3(name, unit, relay, l1, l2, l3)

  Bases: `Shelly`

  The Shelly Pro wifi/ethernet relay with three independently controllable relays. Subscribes to the Juham power input topic and controls the Shelly relays 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 = ''
  database_client: Optional[Union[TimeSeries, None]]
  debug(msg, details='')

    Logs the given debug message to the database after logging it using the BaseClass’s info() method.

    Parameters:

      - msg (str) – The information message to be logged.

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

    Return type:

      `None`

  do(action, context)

    Execute the given action to the object, by calling the provided action.

    Parameters:

      - action (Callable[["MasterPiece", dict[str, Any]], bool]) – A callable that takes

      - (node

      - boolean. (context) and returns a)

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

    Return type:

      `bool`

    Returns:

      The return value from the executed action.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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_client: Optional[Union[Mqtt, None]]
  mqtt_host: str = 'localhost'
  mqtt_port: int = 1883
  mqtt_prefix: str
  mqtt_root_topic: str = ''
  mqtt_topic_base: str
  mqtt_topic_control: str
  mqtt_topic_log: 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_message(client, userdata, msg)

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

    Process power_topic message.

    Parameters:

      m (dict) – holding data from the power sensor

    Return type:

      `None`

  property parent: MasterPiece | None
  power_topic = 'power'
  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`

  relay_started: float
  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_shelly.ShellyPro3EM(name='shellypro3em')

  Bases: `Shelly`

  The Shelly Pro3EM energy meter.

  Publishes the active power (also called real power) to MQTT, as it represents the part of the power that can be converted to useful work. Full set of measurements e.g. reactive power, current, and voltage, available from the sensor, are written to a time series database for inspection purposes.

  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 = ''
  database_client: Optional[Union[TimeSeries, None]]
  debug(msg, details='')

    Logs the given debug message to the database after logging it using the BaseClass’s info() method.

    Parameters:

      - msg (str) – The information message to be logged.

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

    Return type:

      `None`

  do(action, context)

    Execute the given action to the object, by calling the provided action.

    Parameters:

      - action (Callable[["MasterPiece", dict[str, Any]], bool]) – A callable that takes

      - (node

      - boolean. (context) and returns a)

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

    Return type:

      `bool`

    Returns:

      The return value from the executed action.

  elapsed(secs)

    Check if a certain time interval has elapsed and update the start timestamp attribute to count elapsed seconds for future calls.

    Parameters:

      secs (float) – The expected elapsed time in seconds since the previous call

    Returns:

      True if the given number of seconds has elapsed, False otherwise.

    Return type:

      bool

  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_client: Optional[Union[Mqtt, None]]
  mqtt_host: str = 'localhost'
  mqtt_port: int = 1883
  mqtt_prefix: str
  mqtt_root_topic: str = ''
  mqtt_topic_base: str
  mqtt_topic_control: str
  mqtt_topic_log: 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_em_0(ts, em)

    Handle the incoming Shelly message containing all power meter readings. Publish the real power component, which is of interest to Juham, and record all measurements to the time series database.

    Parameters:

      - ts (str) – time stamp of the event

      - em (dict) – message from the Shelly device

    Return type:

      `None`

  on_emdata_0(ts, em)

    Handle energy meter sensor message.

    Parameters:

      - ts (str) – utc time

      - em (dict) – energy meter sensor specific message

    Return type:

      `None`

  on_message(client, userdata, msg)

    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`

  publish_active_power(ts, em)

    Publish the active power, also known as real power. This is that part of the power that can be converted to useful work.

    Parameters:

      - ts (str) – time stamp of the event

      - em (dict) – message from the Shelly device

    Return type:

      `None`

  read(point)
    Return type:

      `None`

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

      `dict`[`str`, `Any`]

  record_power(ts, em)

    Given current time in UTC and energy meter message update 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`

  relay_started: float
  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`

  shelly_topic = 'shellypro3em-powermeter/events/rpc'
  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`