juham.base

Description

Base classes for Juham - Juha’s Ultimate Home Automation Masterpiece

This package represents the most low level layer in the framework. Most notably, it defines essential abstractions on which communcation between various IoT nodes and the data tracking is based on:

  1. jmqtt - publish-subscriber model data transmission

  2. jdatabase - interface to time series database used for data recording

  3. log - logging

Example:

foo = Base("foo")
foo.info("Hello world")
foo.subscribe("any/topic")
foo.publish("any/topic", any_msg)
foo.write(any_measurement)
class juham.base.Base(name='')[source]

Bases: MasterPiece

An automation object with MQTT networking and data storage.

Example:

obj = Base("foo")
obj.mqtt_host = "myhost.com"
obj.mqtt_port = 12345
obj.subscribe('foo/bar')
obj.run()

To configure Base class to use a specific MQTT and time series implementations set the class attributes to refer to desired MQTT and time series database implementations. When instantiated the object will instantiate the given MQTT and database objects with it.

classmethod classattrs_from_dict(attributes)

Set class attributes from a dictionary.

classmethod classattrs_to_dict()

Convert class attributes to a dictionary.

copy()

Create and return a copy of the current object.

This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.

This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.

Return type:

MasterPiece

Returns:

A new instance of the object’s class with the same state as the original object.

Example:

clone_of_john = john.copy()
database_class_id: str = 'JInflux'
debug(msg, details='')[source]

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

deserialize_from_json(f)

Load attributes from the given JSON file.

do(action, context)

Execute the given action to the object, by calling the provided action on each node.

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

  • context (Dict[str, Any])

Return type:

bool

Returns:

The return value from the executed action.

error(msg, details='')[source]

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

Given class identifier find the registered class. If no class with the give identifier exists return None.

Parameters:

class_id (int) – class identifier

Returns:

class or null if not registered

Return type:

obj (obj)

from_dict(data)[source]

Update instance attributes from a dictionary.

classmethod get_class_id()

Return the class id of the class. Each class has an unique identifier that can be used for instantiating the class via Object.instantiate() method.

Parameters:

cls (class) – class

Return type:

str

Returns:

id (int) unique class identifier through which the class can be instantiated by factory method pattern.

classmethod get_json_file()

Generate the JSON file name based on the class name.

The file is created into users home folder.

classmethod get_registered_classes()

Get the dictionary holding the registered class identifiers and the corresponding classes.

Returns:

dictionary of class identifier - class pairs

Return type:

dict

classmethod has_class_method_directly(method_name)

Check if the method is in the class’s own dictionary

Return type:

bool

info(msg, details='')[source]

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_app_id(app_id='myapp')

Initialize application id. Parses initial startup that depend on application id

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

  • --app (str) – Application ID.

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

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

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

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

Return type:

None

classmethod init_class(clazz)

Initialize class. Updates the class factory and sets up exit hook to create class configuration file on program exit.

Parameters:

clazz (class) – class to be initialized

init_database(name)[source]

Instantiates the configured time series database object.

Issues a warning if the database_class_id has not been configured, in which case the object will not have the time series recording feature.

This method is called internally and typically there is no need to call it from the application code.

Return type:

None

init_mqtt(name)[source]

Instantiates the configured MQTT object for networking.

This method is called internally and typically there is no need to call it from the application code.

Issues a warning if the pubsub_class_id has not been configured, even though objects without a capability to communicate are rather crippled.

Return type:

None

initialize()[source]

Initialize time series database and mqtt networking for use. This method must be called after the object name has been set .

Return type:

None

classmethod instantiate(class_id)

Create an instance of the class corresponding to the given class identifier. This method implements the factory method pattern, which is essential for a plugin architecture.

Parameters:

class_id (int) – Identifier of the class to instantiate.

Returns:

An instance of the class corresponding to the given class identifier.

Return type:

obj

classmethod instantiate_with_param(class_id, param)

Given class identifier and one constructor argument create the corresponding object.

Parameters:
  • class_id (str) – class identifier

  • param (Any) – class specific constructor parameter

Returns:

instance of the given class.

Return type:

obj

classmethod is_abstract()

Check whether the class is abstract or real. Override in the derived sub-classes. The default is False.

Return type:

bool

Returns:

True (bool) if abstract

classmethod load_from_json()

Load class attributes from a JSON file.

log_message(type, msg, details='')[source]

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 The main log message to be published.

  • details – 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))
mqtt_class_id: str = 'JPaho2'
mqtt_host: str = 'localhost'
mqtt_port: int = 1883
mqtt_root_topic: str = 'juham'
on_connect(client, userdata, flags, rc)[source]

Notification on connect.

This method is called whenever the MQTT broker is connected. For more information on this method consult MQTT documentation available in many public sources.

Parameters:
  • client (obj) – MQTT client

  • userdata (Any) – application specific data

  • flags (int) – Consult MQTT

  • rc (int) – See MQTT docs

Return type:

None

on_disconnect(client, userdata, rc=0)[source]

Notification on disconnect.

This method is called whenever the MQTT broker is disconnected. For more information on this method consult MQTT documentation available in many public sources.

Parameters:
  • client (obj) – MQTT client

  • userdata (Any) – application specific data

  • rc (int) – See MQTT docs

Return type:

None

on_message(client, userdata, msg)[source]

MQTT message notification on arrived message.

Called whenever a new message is posted on one of the topics the object has subscribed to via subscribe() method. This method is the heart of automation: here, derived subclasses should automate whatever they were designed to automate. For example, they could switch a relay when a boiler temperature sensor signals that the temperature is too low for a comforting shower for say one’s lovely wife.

For more information on this method consult MQTT documentation available in many public sources.

Parameters:
  • client (obj) – MQTT client

  • userdata (Any) – application specific data

  • msg (object) – The MQTT message

Return type:

None

publish(topic, msg, qos=1, retain=True)[source]

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.

read(point)[source]

Reads the given measurement from the database.

Parameters:

point – point with initialized time stamp.

Return type:

None

… note: NOT IMPLEMENTED YET

classmethod register()

Register the class.

Called immediately upon class initialization, right before the class attributes are loaded from the class specific configuration files.

Subclasses can extend this with custom register functionality:

class MyMasterPiece(MasterPiece):

    @classmethod
    def register(cls):
        super().register()  # Don't forget
        cls._custom_field = True
Return type:

None

run()[source]

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

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

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

serialize_to_json(f)

Serialize the object to given JSON file

classmethod set_log(l)

Set logger.

Parameters:

l (logger) – logger object

Return type:

None

shutdown()[source]

Shut down all services, free resources, stop threads, disconnect from mqtt, in general, prepare for shutdown.

Return type:

None

subscribe(topic)[source]

Subscribe to the given MQTT topic.

This method sets up the subscription to the specified MQTT topic and registers the on_message() method as the callback for incoming messages.

Parameters:

topic (str) – The MQTT topic to subscribe to.

Return type:

None

Example:

# configure
obj.subscribe('foo/bar')
to_dict()[source]

Convert instance attributes to a dictionary.

warning(msg, details='')[source]

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

Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.

Parameters:

point – a measurement describing a time stamp and related attributes for one measurement.

Return type:

None

write_attempts = 3
class juham.base.JApp(name)[source]

Bases: Application

Juham home automation application base class. Registers new plugin group ‘juham’.

add(h)

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

Parameters:

h (T) – object to be inserted.

Return type:

None

classmethod classattrs_from_dict(attributes)

Set class attributes from a dictionary.

classmethod classattrs_to_dict()

Convert class attributes to a dictionary.

copy()

Create and return a copy of the current object.

This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.

This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.

Return type:

MasterPiece

Returns:

A new instance of the object’s class with the same state as the original object.

Example:

clone_of_john = john.copy()
debug(msg, details='')

Logs the given debug message to the application log.

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

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

Return type:

None

deserialize()

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

TODO: or by optional method parameter

Return type:

None

deserialize_from_json(f)

Load attributes from the given JSON file.

do(action, context)

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

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

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

Return type:

bool

Returns:

None

error(msg, details='')

Logs the given error message to the application log.

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

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

Return type:

None

classmethod find_class(class_id)

Given class identifier find the registered class. If no class with the give identifier exists return None.

Parameters:

class_id (int) – class identifier

Returns:

class or null if not registered

Return type:

obj (obj)

from_dict(data)

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

Parameters:

data (dict) – data to deserialize from.

Return type:

None

classmethod get_class_id()

Return the class id of the class. Each class has an unique identifier that can be used for instantiating the class via Object.instantiate() method.

Parameters:

cls (class) – class

Return type:

str

Returns:

id (int) unique class identifier through which the class can be instantiated by factory method pattern.

classmethod get_json_file()

Generate the JSON file name based on the class name.

The file is created into users home folder.

classmethod get_registered_classes()

Get the dictionary holding the registered class identifiers and the corresponding classes.

Returns:

dictionary of class identifier - class pairs

Return type:

dict

classmethod has_class_method_directly(method_name)

Check if the method is in the class’s own dictionary

Return type:

bool

info(msg, details='')

Logs the given information message to the application log.

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

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

Return type:

None

classmethod init_app_id(app_id='myapp')

Initialize application id. Parses initial startup that depend on application id

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

  • --app (str) – Application ID.

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

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

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

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

Return type:

None

classmethod init_class(clazz)

Initialize class. Updates the class factory and sets up exit hook to create class configuration file on program exit.

Parameters:

clazz (class) – class to be initialized

install_plugins()

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

Return type:

None

classmethod instantiate(class_id)

Create an instance of the class corresponding to the given class identifier. This method implements the factory method pattern, which is essential for a plugin architecture.

Parameters:

class_id (int) – Identifier of the class to instantiate.

Returns:

An instance of the class corresponding to the given class identifier.

Return type:

obj

instantiate_classes()[source]

Instantiates the default set of classes for the application. Subclasses are responsible for implementing this method. It serves as a fallback mechanism when the application is started for the first time and no configuration file named after the application is present.

Return type:

None

instantiate_plugin_by_name(name)

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

Return type:

Optional[MasterPiece]

classmethod instantiate_with_param(class_id, param)

Given class identifier and one constructor argument create the corresponding object.

Parameters:
  • class_id (str) – class identifier

  • param (Any) – class specific constructor parameter

Returns:

instance of the given class.

Return type:

obj

classmethod is_abstract()

Check whether the class is abstract or real. Override in the derived sub-classes. The default is False.

Return type:

bool

Returns:

True (bool) if abstract

classmethod load_class_attributes()

Initialize the public class attributes of the registered classes from their configuration files. Configuration files are automatically created with built-in default values, if not exists already.

Return type:

None

classmethod load_from_json()

Load class attributes from a JSON file.

classmethod load_plugins()

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

Return type:

None

classmethod parse_args()

Register classes with ArgMaestro.

plugin_groups = ['masterpiece', 'juham']
plugins: List[Type[MasterPiece]] = []
classmethod register()[source]

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
classmethod register_plugin_group(name)

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

Parameters:

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

Return type:

None

run()

Run the masterpiece. Dispatches the call to payload object and returns the control to the caller.

Return type:

None

run_forever()

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

Return type:

None

classmethod save_to_json()

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

serialization_file: str = ''
serialize()[source]

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

TODO: or by optional method parameter

serialize_to_json(f)

Serialize the object to given JSON file

classmethod set_log(l)

Set logger.

Parameters:

l (logger) – logger object

Return type:

None

shutdown()

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

Return type:

None

shutdown_children()

Shuts down the children.

Return type:

None

start_children()

Start all children.

Return type:

None

to_dict()

Convert instance attributes to a dictionary.

Return type:

dict

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.base.JDatabase(name)[source]

Bases: MasterPiece

The base class for data storage classes.Serves as an abstract interface for managing interactions with various types of databases. Designed to support multiple backend databases, this class provides a unified API for writing sensor data and other parameters, ensuring that the system can seamlessly integrate with different storage solutions.

classmethod classattrs_from_dict(attributes)

Set class attributes from a dictionary.

classmethod classattrs_to_dict()

Convert class attributes to a dictionary.

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 = 'home'
debug(msg, details='')

Logs the given debug message to the application log.

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

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

Return type:

None

deserialize_from_json(f)

Load attributes from the given JSON file.

do(action, context)

Execute the given action to the object, by calling the provided action on each node.

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

  • context (Dict[str, Any])

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

classmethod find_class(class_id)

Given class identifier find the registered class. If no class with the give identifier exists return None.

Parameters:

class_id (int) – class identifier

Returns:

class or null if not registered

Return type:

obj (obj)

from_dict(data_dict)[source]

Update instance attributes from a dictionary.

classmethod get_class_id()

Return the class id of the class. Each class has an unique identifier that can be used for instantiating the class via Object.instantiate() method.

Parameters:

cls (class) – class

Return type:

str

Returns:

id (int) unique class identifier through which the class can be instantiated by factory method pattern.

classmethod get_json_file()

Generate the JSON file name based on the class name.

The file is created into users home folder.

classmethod get_registered_classes()

Get the dictionary holding the registered class identifiers and the corresponding classes.

Returns:

dictionary of class identifier - class pairs

Return type:

dict

classmethod has_class_method_directly(method_name)

Check if the method is in the class’s own dictionary

Return type:

bool

host: str = ''
info(msg, details='')

Logs the given information message to the application log.

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

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

Return type:

None

classmethod init_app_id(app_id='myapp')

Initialize application id. Parses initial startup that depend on application id

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

  • --app (str) – Application ID.

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

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

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

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

Return type:

None

classmethod init_class(clazz)

Initialize class. Updates the class factory and sets up exit hook to create class configuration file on program exit.

Parameters:

clazz (class) – class to be initialized

classmethod instantiate(class_id)

Create an instance of the class corresponding to the given class identifier. This method implements the factory method pattern, which is essential for a plugin architecture.

Parameters:

class_id (int) – Identifier of the class to instantiate.

Returns:

An instance of the class corresponding to the given class identifier.

Return type:

obj

classmethod instantiate_with_param(class_id, param)

Given class identifier and one constructor argument create the corresponding object.

Parameters:
  • class_id (str) – class identifier

  • param (Any) – class specific constructor parameter

Returns:

instance of the given class.

Return type:

obj

classmethod is_abstract()

Check whether the class is abstract or real. Override in the derived sub-classes. The default is False.

Return type:

bool

Returns:

True (bool) if abstract

classmethod load_from_json()

Load class attributes from a JSON file.

org: str = 'juham'
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

run()

Run the masterpiece. Dispatches the call to payload object and returns the control to the caller.

Return type:

None

run_forever()

Run the masterpiece forever. This method will return only when violently terminated.

Return type:

None

classmethod save_to_json()

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

serialize_to_json(f)

Serialize the object to given JSON file

classmethod set_log(l)

Set logger.

Parameters:

l (logger) – logger object

Return type:

None

shutdown()

Shutdown the masterpiece. It is up to the sub classes to implement this method. Dispatches the call to payload object.

Return type:

None

to_dict()[source]

Convert instance attributes to a dictionary.

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

write(point)[source]

Write record to database table.

@param point point to be written

class juham.base.JMqtt(name)[source]

Bases: MasterPiece

Base class for MQTT brokers.

classmethod classattrs_from_dict(attributes)

Set class attributes from a dictionary.

classmethod classattrs_to_dict()

Convert class attributes to a dictionary.

connect_to_server(host='localhost', port=1883, keepalive=60)[source]

Connect to MQTT server

Parameters:
  • host (str, optional) – host. Defaults to “localhost”.

  • port (int, optional) – port. Defaults to 1883.

  • keepalive (int, optional) – keep alive, in seconds. Defaults to 60.

Return type:

int

Returns:

0 if ok, non-zero values indicate errors

copy()

Create and return a copy of the current object.

This method serializes the current object to a dictionary using the to_dict method, creates a new instance of the object’s class, and populates it with the serialized data using the from_dict method.

This method uses class identifier based instantiation (see factory method pattern) to create a new instance of the object, and ‘to_dict’ and ‘from_dict’ methods to initialize object’s state.

Return type:

MasterPiece

Returns:

A new instance of the object’s class with the same state as the original object.

Example:

clone_of_john = john.copy()
debug(msg, details='')

Logs the given debug message to the application log.

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

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

Return type:

None

deserialize_from_json(f)

Load attributes from the given JSON file.

disconnect_from_server()[source]

Disconnect from the MQTT broker.

It is up to the sub classes to implement the method.

do(action, context)

Execute the given action to the object, by calling the provided action on each node.

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

  • context (Dict[str, Any])

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

classmethod find_class(class_id)

Given class identifier find the registered class. If no class with the give identifier exists return None.

Parameters:

class_id (int) – class identifier

Returns:

class or null if not registered

Return type:

obj (obj)

from_dict(data)

Update instance attributes from a dictionary.

classmethod get_class_id()

Return the class id of the class. Each class has an unique identifier that can be used for instantiating the class via Object.instantiate() method.

Parameters:

cls (class) – class

Return type:

str

Returns:

id (int) unique class identifier through which the class can be instantiated by factory method pattern.

classmethod get_json_file()

Generate the JSON file name based on the class name.

The file is created into users home folder.

classmethod get_registered_classes()

Get the dictionary holding the registered class identifiers and the corresponding classes.

Returns:

dictionary of class identifier - class pairs

Return type:

dict

classmethod has_class_method_directly(method_name)

Check if the method is in the class’s own dictionary

Return type:

bool

info(msg, details='')

Logs the given information message to the application log.

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

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

Return type:

None

classmethod init_app_id(app_id='myapp')

Initialize application id. Parses initial startup that depend on application id

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

  • --app (str) – Application ID.

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

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

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

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

Return type:

None

classmethod init_class(clazz)

Initialize class. Updates the class factory and sets up exit hook to create class configuration file on program exit.

Parameters:

clazz (class) – class to be initialized

classmethod instantiate(class_id)

Create an instance of the class corresponding to the given class identifier. This method implements the factory method pattern, which is essential for a plugin architecture.

Parameters:

class_id (int) – Identifier of the class to instantiate.

Returns:

An instance of the class corresponding to the given class identifier.

Return type:

obj

classmethod instantiate_with_param(class_id, param)

Given class identifier and one constructor argument create the corresponding object.

Parameters:
  • class_id (str) – class identifier

  • param (Any) – class specific constructor parameter

Returns:

instance of the given class.

Return type:

obj

classmethod is_abstract()

Check whether the class is abstract or real. Override in the derived sub-classes. The default is False.

Return type:

bool

Returns:

True (bool) if abstract

classmethod load_from_json()

Load class attributes from a JSON file.

loop_stop()[source]

Stop the network loop.

No further messages shall be dispatched.

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

run()

Run the masterpiece. Dispatches the call to payload object and returns the control to the caller.

Return type:

None

run_forever()

Run the masterpiece forever. This method will return only when violently terminated.

Return type:

None

classmethod save_to_json()

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

serialize_to_json(f)

Serialize the object to given JSON file

classmethod set_log(l)

Set logger.

Parameters:

l (logger) – logger object

Return type:

None

shutdown()

Shutdown the masterpiece. It is up to the sub classes to implement this method. Dispatches the call to payload object.

Return type:

None

to_dict()

Convert instance attributes to a dictionary.

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

juham.base.MqttMsg

alias of MQTTMessage