juham.web¶
Http data source classes.
Data acquisition classes for reading information, e.g forecast, through http url.
- class juham.web.HomeWizardWaterMeter(name='homewizardwatermeter', topic='', url='', interval=60.0)[source]¶
Bases:
RCloud
Homewizard watermeter sensor.
- app_name = 'juham'¶
- classmethod classattrs_from_dict(attributes)¶
Set class attributes from a dictionary.
- classmethod classattrs_to_dict()¶
Convert class attributes to a dictionary.
- config_folder = 'config'¶
- 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.
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
john = Human("john") john.height = 1.8 john.age = 62 clone_of_john = john.copy()
- database_class_id: str | None = 0¶
- database_client: object | 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
- deserialize_from_json(f)¶
Load attributes from a JSON file.
- device_url = 'http://192.168.86.70/api/v1/data'¶
- disconnect()¶
- epoc2utc(epoch)¶
Converts the given epoch time to UTC time string. All time coordinates are represented in UTC time. This allows the time coordinate to be mapped to any local time representation without ambiguity.
- Parameters:
epoch (float) – timestamp in UTC time
rc (str) – time string describing date, time and time zone e.g 2024-07-08T12:10:22Z
- Returns:
UTC time
- 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
- event_topic = 'juham/event'¶
- 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)
- 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.
- 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
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking.
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
- classmethod initialize_class()¶
Initialize the class for instantiation, if not initialized already. This method initializes the class identifier and deserializes the public attributes from the specified configuration folder.
- Returns:
returns true if the class was initialized, false implies the class is already initialized in which case the method call has no effect.
- Return type:
bool
- classmethod instantiate(class_id)¶
Given class identifier create the corresponding object. This method implements so called factory method pattern.
- Parameters:
class_id (int) – class identifier
- Returns:
instance of the given class.
- Return type:
obj (obj)
- classmethod instantiate_with_param(class_id, param)¶
Given class identifier and one constructor argument create the corresponding object.
- Parameters:
class_id (
str
|None
) – class identifierparam (
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
- is_time_between(begin_time, end_time, check_time=None)¶
Check if the given time is within the given time line. All timestamps must be in UTC time.
- Parameters:
begin_time (timestamp) – beginning of the timeline
end_time (timestamp) – end of the timeline
check_time (timestamp) – time to be checked
- Returns:
True if within the timeline
- Return type:
rc (bool)
- classmethod load_from_json()¶
Load class attributes from a JSON file.
- 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 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).
- 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 | None = None¶
- 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
- 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
- on_event(em)¶
Notification event callback e.g info or warning.
- Parameters:
em (dictionary) – dictionary describing the event
- Return type:
None
- on_message(client, userdata, msg)[source]¶
The standared MQTT callback for arriving messages.
- Parameters:
client (object) – mqtt client
userdata (Any) – any user specific data
msg (object) – MQTT message
- on_sensor(em)[source]¶
Handle data coming from the watermeter sensor. Writes the sensor telemetry to time series.
- Parameters:
em (dict) – data from the sensor
- Return type:
None
- classmethod parse_args()¶
Parse the startup arguments defined by this class.
- Return type:
None
- pubsub_class_id = 0¶
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point – point with initialized time stamp.
… note: NOT IMPLEMENTED YET
- classmethod register()[source]¶
Register the class to the class database.
Once registered the class can be instantiated by its class identifier. Note that this method is called automatically by the system when the python loads the class. In this method sub classes should prepare themselves for instantiation by initializing their class attributes, for example.
- classmethod register_class(class_id, ctor)¶
Register the given class identifier for identifier based instantiation . This, factory method pattern, as it is called, decouples the actual implementation from the interface. For more information see
instantiate()
method.- Parameters:
class_id (str) – class identifier
ctor (function) – constructor
- 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.
- classmethod save_to_json()¶
Create class configuration file, if the file does not exist yet.
- sensor_topic = 'juham/watermeter'¶
- serialize_to_json(f)¶
Serialize.
- 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.
- 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')
- timestamp()¶
Returns the current date-time in UTC.
- Returns:
datetime in UTC.
- Return type:
rc (datetime)
- timestampstr(ts)¶
Converts the given timestamp to human readable string of form ‘Y-m-d H:M:S’.
- Parameters:
ts (timestamp) – time stamp to be converted
- Returns:
human readable date-time string
- Return type:
rc (string)
- update_interval = 60¶
- url = 'http://192.168.86.70/api/v1/data'¶
- 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
- workerThreadId = 'HomeWizardThread'¶
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- write_attempts = 3¶
- class juham.web.IWorkerThread(client=None)[source]¶
Bases:
Thread
,Object
Base class for Juham threads used for tasks such as data acquisition that need to be run asynchronously. This class defines the update() method, in which subclasses can execute their specific code. The update_interval() method (default is 60 seconds) determines how frequently the update() method is called.
An alternative to threads is to use cron. However, the advantage of using threads is that they run in the same memory space, unlike cron, which spawns a separate process and Python instance to execute the code.
- Parameters:
Thread (client) – MQTT client for the thread
- app_name = 'juham'¶
- classmethod classattrs_from_dict(attributes)¶
Set class attributes from a dictionary.
- classmethod classattrs_to_dict()¶
Convert class attributes to a dictionary.
- config_folder = 'config'¶
- 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.
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
john = Human("john") john.height = 1.8 john.age = 62 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='')[source]¶
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
- deserialize_from_json(f)¶
Load attributes from a JSON file.
- error(msg, details='')[source]¶
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
-
event_topic:
str
= ''¶
- 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.
- 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 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.
- 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='')[source]¶
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
- classmethod initialize_class()¶
Initialize the class for instantiation, if not initialized already. This method initializes the class identifier and deserializes the public attributes from the specified configuration folder.
- Returns:
returns true if the class was initialized, false implies the class is already initialized in which case the method call has no effect.
- Return type:
bool
- classmethod instantiate(class_id)¶
Given class identifier create the corresponding object. This method implements so called factory method pattern.
- Parameters:
class_id (int) – class identifier
- Returns:
instance of the given class.
- Return type:
obj (obj)
- classmethod instantiate_with_param(class_id, param)¶
Given class identifier and one constructor argument create the corresponding object.
- Parameters:
class_id (
str
|None
) – class identifierparam (
Any
) – class specific constructor parameter
- Returns:
instance of the given class.
- Return type:
obj
- isDaemon()¶
Return whether this thread is a daemon.
This method is deprecated, use the daemon attribute instead.
- 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
- 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.
- classmethod load_from_json()¶
Load class attributes from a JSON file.
- log(type, msg, details)[source]¶
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
- 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.
- classmethod parse_args()¶
Parse the startup arguments defined by this class.
- Return type:
None
- classmethod register()[source]¶
Register the class to the class database.
Once registered the class can be instantiated by its class identifier. Note that this method is called automatically by the system when the python loads the class. In this method sub classes should prepare themselves for instantiation by initializing their class attributes, for example.
- classmethod register_class(class_id, ctor)¶
Register the given class identifier for identifier based instantiation . This, factory method pattern, as it is called, decouples the actual implementation from the interface. For more information see
instantiate()
method.- Parameters:
class_id (str) – class identifier
ctor (function) – constructor
- run()[source]¶
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
- classmethod save_to_json()¶
Create class configuration file, if the file does not exist yet.
- serialize_to_json(f)¶
Serialize.
- 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
- 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()[source]¶
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
- to_dict()¶
Convert instance attributes to a dictionary.
- update()[source]¶
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
- class juham.web.RCloud(name)[source]¶
Bases:
RThread
Base class for automation objects that query data using a URL.
Spawns an asynchronous thread to acquire data at a specified time interval.
- app_name = 'juham'¶
- classmethod classattrs_from_dict(attributes)¶
Set class attributes from a dictionary.
- classmethod classattrs_to_dict()¶
Convert class attributes to a dictionary.
- config_folder = 'config'¶
- 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.
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
john = Human("john") john.height = 1.8 john.age = 62 clone_of_john = john.copy()
- database_class_id: str | None = 0¶
- database_client: object | 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
- deserialize_from_json(f)¶
Load attributes from a JSON file.
- disconnect()¶
- epoc2utc(epoch)¶
Converts the given epoch time to UTC time string. All time coordinates are represented in UTC time. This allows the time coordinate to be mapped to any local time representation without ambiguity.
- Parameters:
epoch (float) – timestamp in UTC time
rc (str) – time string describing date, time and time zone e.g 2024-07-08T12:10:22Z
- Returns:
UTC time
- 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
- event_topic = 'juham/event'¶
- 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.
- 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
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking.
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
- classmethod initialize_class()¶
Initialize the class for instantiation, if not initialized already. This method initializes the class identifier and deserializes the public attributes from the specified configuration folder.
- Returns:
returns true if the class was initialized, false implies the class is already initialized in which case the method call has no effect.
- Return type:
bool
- classmethod instantiate(class_id)¶
Given class identifier create the corresponding object. This method implements so called factory method pattern.
- Parameters:
class_id (int) – class identifier
- Returns:
instance of the given class.
- Return type:
obj (obj)
- classmethod instantiate_with_param(class_id, param)¶
Given class identifier and one constructor argument create the corresponding object.
- Parameters:
class_id (
str
|None
) – class identifierparam (
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
- is_time_between(begin_time, end_time, check_time=None)¶
Check if the given time is within the given time line. All timestamps must be in UTC time.
- Parameters:
begin_time (timestamp) – beginning of the timeline
end_time (timestamp) – end of the timeline
check_time (timestamp) – time to be checked
- Returns:
True if within the timeline
- Return type:
rc (bool)
- classmethod load_from_json()¶
Load class attributes from a JSON file.
- 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 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).
- 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 | None = None¶
- mqtt_host: str = 'localhost'¶
- mqtt_port: int = 1883¶
- mqtt_root_topic: str = 'juham'¶
- 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
- 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)¶
The standared MQTT callback for arriving messages.
- Parameters:
client (object) – mqtt client
userdata (Any) – any user specific data
msg (object) – MQTT message
- Return type:
None
- classmethod parse_args()¶
Parse the startup arguments defined by this class.
- Return type:
None
- pubsub_class_id = 0¶
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point – point with initialized time stamp.
… note: NOT IMPLEMENTED YET
- classmethod register()[source]¶
Register the class to the class database.
Once registered the class can be instantiated by its class identifier. Note that this method is called automatically by the system when the python loads the class. In this method sub classes should prepare themselves for instantiation by initializing their class attributes, for example.
- classmethod register_class(class_id, ctor)¶
Register the given class identifier for identifier based instantiation . This, factory method pattern, as it is called, decouples the actual implementation from the interface. For more information see
instantiate()
method.- Parameters:
class_id (str) – class identifier
ctor (function) – constructor
- run()¶
Run the network loop.
- 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.
- classmethod save_to_json()¶
Create class configuration file, if the file does not exist yet.
- serialize_to_json(f)¶
Serialize.
- 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.
- 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')
- timestamp()¶
Returns the current date-time in UTC.
- Returns:
datetime in UTC.
- Return type:
rc (datetime)
- timestampstr(ts)¶
Converts the given timestamp to human readable string of form ‘Y-m-d H:M:S’.
- Parameters:
ts (timestamp) – time stamp to be converted
- Returns:
human readable date-time string
- Return type:
rc (string)
- to_dict()¶
Convert instance attributes to a dictionary.
- 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
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- write_attempts = 3¶
- class juham.web.RCloudThread(client=None)[source]¶
Bases:
IWorkerThread
Base class for thread that query data from clouds and other web resources via url.
Can be configured how often the query is being run.
- app_name = 'juham'¶
- classmethod classattrs_from_dict(attributes)¶
Set class attributes from a dictionary.
- classmethod classattrs_to_dict()¶
Convert class attributes to a dictionary.
- config_folder = 'config'¶
- 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.
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
john = Human("john") john.height = 1.8 john.age = 62 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
- deserialize_from_json(f)¶
Load attributes from a JSON file.
- 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
- event_topic: str = ''¶
- 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.
- 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 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.
- 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
- classmethod initialize_class()¶
Initialize the class for instantiation, if not initialized already. This method initializes the class identifier and deserializes the public attributes from the specified configuration folder.
- Returns:
returns true if the class was initialized, false implies the class is already initialized in which case the method call has no effect.
- Return type:
bool
- classmethod instantiate(class_id)¶
Given class identifier create the corresponding object. This method implements so called factory method pattern.
- Parameters:
class_id (int) – class identifier
- Returns:
instance of the given class.
- Return type:
obj (obj)
- classmethod instantiate_with_param(class_id, param)¶
Given class identifier and one constructor argument create the corresponding object.
- Parameters:
class_id (
str
|None
) – class identifierparam (
Any
) – class specific constructor parameter
- Returns:
instance of the given class.
- Return type:
obj
- isDaemon()¶
Return whether this thread is a daemon.
This method is deprecated, use the daemon attribute instead.
- 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
- 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.
- classmethod load_from_json()¶
Load class attributes from a JSON file.
- 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
- make_url()[source]¶
Build http url for acquiring data from the web resource. Up to the sub classes to implement.
This method is periodically called by update method.
Returns: Url to be used as parameter to requests.get().
- Return type:
str
- 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.
- classmethod parse_args()¶
Parse the startup arguments defined by this class.
- Return type:
None
- process_data(data)[source]¶
Process the acquired data.
This method is called from the update method, to process the data from the acquired data source. It is up to the sub classes to implement this.
- Return type:
None
- classmethod register()[source]¶
Register the class to the class database.
Once registered the class can be instantiated by its class identifier. Note that this method is called automatically by the system when the python loads the class. In this method sub classes should prepare themselves for instantiation by initializing their class attributes, for example.
- classmethod register_class(class_id, ctor)¶
Register the given class identifier for identifier based instantiation . This, factory method pattern, as it is called, decouples the actual implementation from the interface. For more information see
instantiate()
method.- Parameters:
class_id (str) – class identifier
ctor (function) – constructor
- 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
- classmethod save_to_json()¶
Create class configuration file, if the file does not exist yet.
- serialize_to_json(f)¶
Serialize.
- 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
- 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
-
timeout:
float
= 60¶
- to_dict()¶
Convert instance attributes to a dictionary.
- update()[source]¶
Acquire and process.
This method is periodically called to acquire data from a the configured web url and publish it to respective MQTT topic in the process_data() method.
Returns: True if the update succeeded. Returning False implies an error and in which case the method should be called shortly again to retry. It is up to the caller to decide the number of failed attempts before giving up.
- Return type:
bool
- update_interval()¶
Fetch the update interval in seconds. The default is 60.
- Returns:
number of seconds
- Return type:
float
- 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
- class juham.web.RSpotHintaFi(name='rspothintafi')[source]¶
Bases:
RCloud
- app_name = 'juham'¶
- classmethod classattrs_from_dict(attributes)¶
Set class attributes from a dictionary.
- classmethod classattrs_to_dict()¶
Convert class attributes to a dictionary.
- config_folder = 'config'¶
- 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.
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
john = Human("john") john.height = 1.8 john.age = 62 clone_of_john = john.copy()
- database_class_id: str | None = 0¶
- database_client: object | 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
- deserialize_from_json(f)¶
Load attributes from a JSON file.
- disconnect()¶
- epoc2utc(epoch)¶
Converts the given epoch time to UTC time string. All time coordinates are represented in UTC time. This allows the time coordinate to be mapped to any local time representation without ambiguity.
- Parameters:
epoch (float) – timestamp in UTC time
rc (str) – time string describing date, time and time zone e.g 2024-07-08T12:10:22Z
- Returns:
UTC time
- 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
- event_topic = 'juham/event'¶
- 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)
- 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.
- 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
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking.
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
- classmethod initialize_class()¶
Initialize the class for instantiation, if not initialized already. This method initializes the class identifier and deserializes the public attributes from the specified configuration folder.
- Returns:
returns true if the class was initialized, false implies the class is already initialized in which case the method call has no effect.
- Return type:
bool
- classmethod instantiate(class_id)¶
Given class identifier create the corresponding object. This method implements so called factory method pattern.
- Parameters:
class_id (int) – class identifier
- Returns:
instance of the given class.
- Return type:
obj (obj)
- classmethod instantiate_with_param(class_id, param)¶
Given class identifier and one constructor argument create the corresponding object.
- Parameters:
class_id (
str
|None
) – class identifierparam (
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
- is_time_between(begin_time, end_time, check_time=None)¶
Check if the given time is within the given time line. All timestamps must be in UTC time.
- Parameters:
begin_time (timestamp) – beginning of the timeline
end_time (timestamp) – end of the timeline
check_time (timestamp) – time to be checked
- Returns:
True if within the timeline
- Return type:
rc (bool)
- classmethod load_from_json()¶
Load class attributes from a JSON file.
- 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 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).
- 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 | None = None¶
- 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
- 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
- on_event(em)¶
Notification event callback e.g info or warning.
- Parameters:
em (dictionary) – dictionary describing the event
- Return type:
None
- on_message(client, userdata, msg)[source]¶
The standared MQTT callback for arriving messages.
- Parameters:
client (object) – mqtt client
userdata (Any) – any user specific data
msg (object) – MQTT message
- on_spot(m)[source]¶
Write hourly spot electricity prices to time series database.
- Parameters:
m (dict) – holding hourlys spot electricity prices
- classmethod parse_args()¶
Parse the startup arguments defined by this class.
- Return type:
None
- pubsub_class_id = 0¶
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point – point with initialized time stamp.
… note: NOT IMPLEMENTED YET
- classmethod register()[source]¶
Register the class to the class database.
Once registered the class can be instantiated by its class identifier. Note that this method is called automatically by the system when the python loads the class. In this method sub classes should prepare themselves for instantiation by initializing their class attributes, for example.
- classmethod register_class(class_id, ctor)¶
Register the given class identifier for identifier based instantiation . This, factory method pattern, as it is called, decouples the actual implementation from the interface. For more information see
instantiate()
method.- Parameters:
class_id (str) – class identifier
ctor (function) – constructor
- 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.
- classmethod save_to_json()¶
Create class configuration file, if the file does not exist yet.
- serialize_to_json(f)¶
Serialize.
- 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.
- spot_topic = 'juham/spot'¶
- 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')
- timestamp()¶
Returns the current date-time in UTC.
- Returns:
datetime in UTC.
- Return type:
rc (datetime)
- timestampstr(ts)¶
Converts the given timestamp to human readable string of form ‘Y-m-d H:M:S’.
- Parameters:
ts (timestamp) – time stamp to be converted
- Returns:
human readable date-time string
- Return type:
rc (string)
- update_interval = 21600¶
- url = 'https://api.spot-hinta.fi/TodayAndDayForward'¶
- warning(msg, details='')¶
Logs the given warning message to the database after logging it using the BaseClass’s info() method.
- Parameters:
msg (str) – The information message to be logged.
details (str) – Additional detailed information for the message to be logged
- worker: IWorkerThread¶
- worker_thread_id = 'SpotHintaFiThread'¶
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- write_attempts = 3¶
- class juham.web.RThread(name)[source]¶
Bases:
Base
- app_name = 'juham'¶
- classmethod classattrs_from_dict(attributes)¶
Set class attributes from a dictionary.
- classmethod classattrs_to_dict()¶
Convert class attributes to a dictionary.
- config_folder = 'config'¶
- 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.
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
john = Human("john") john.height = 1.8 john.age = 62 clone_of_john = john.copy()
- database_class_id: str | None = 0¶
- database_client: object | 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
- deserialize_from_json(f)¶
Load attributes from a JSON file.
- epoc2utc(epoch)¶
Converts the given epoch time to UTC time string. All time coordinates are represented in UTC time. This allows the time coordinate to be mapped to any local time representation without ambiguity.
- Parameters:
epoch (float) – timestamp in UTC time
rc (str) – time string describing date, time and time zone e.g 2024-07-08T12:10:22Z
- Returns:
UTC time
- 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
- event_topic = 'juham/event'¶
- 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.
- 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
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking.
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
- classmethod initialize_class()¶
Initialize the class for instantiation, if not initialized already. This method initializes the class identifier and deserializes the public attributes from the specified configuration folder.
- Returns:
returns true if the class was initialized, false implies the class is already initialized in which case the method call has no effect.
- Return type:
bool
- classmethod instantiate(class_id)¶
Given class identifier create the corresponding object. This method implements so called factory method pattern.
- Parameters:
class_id (int) – class identifier
- Returns:
instance of the given class.
- Return type:
obj (obj)
- classmethod instantiate_with_param(class_id, param)¶
Given class identifier and one constructor argument create the corresponding object.
- Parameters:
class_id (
str
|None
) – class identifierparam (
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
- is_time_between(begin_time, end_time, check_time=None)¶
Check if the given time is within the given time line. All timestamps must be in UTC time.
- Parameters:
begin_time (timestamp) – beginning of the timeline
end_time (timestamp) – end of the timeline
check_time (timestamp) – time to be checked
- Returns:
True if within the timeline
- Return type:
rc (bool)
- classmethod load_from_json()¶
Load class attributes from a JSON file.
- 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 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).
- 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 | None = None¶
- mqtt_host: str = 'localhost'¶
- mqtt_port: int = 1883¶
- mqtt_root_topic: str = 'juham'¶
- 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
- on_event(em)[source]¶
Notification event callback e.g info or warning.
- Parameters:
em (dictionary) – dictionary describing the event
- Return type:
None
- on_message(client, userdata, msg)[source]¶
The standared MQTT callback for arriving messages.
- Parameters:
client (object) – mqtt client
userdata (Any) – any user specific data
msg (object) – MQTT message
- Return type:
None
- classmethod parse_args()¶
Parse the startup arguments defined by this class.
- Return type:
None
- pubsub_class_id = 0¶
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point – point with initialized time stamp.
… note: NOT IMPLEMENTED YET
- classmethod register()[source]¶
Register the class to the class database.
Once registered the class can be instantiated by its class identifier. Note that this method is called automatically by the system when the python loads the class. In this method sub classes should prepare themselves for instantiation by initializing their class attributes, for example.
- classmethod register_class(class_id, ctor)¶
Register the given class identifier for identifier based instantiation . This, factory method pattern, as it is called, decouples the actual implementation from the interface. For more information see
instantiate()
method.- Parameters:
class_id (str) – class identifier
ctor (function) – constructor
- 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.
- classmethod save_to_json()¶
Create class configuration file, if the file does not exist yet.
- serialize_to_json(f)¶
Serialize.
- 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.
- 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')
- timestamp()¶
Returns the current date-time in UTC.
- Returns:
datetime in UTC.
- Return type:
rc (datetime)
- timestampstr(ts)¶
Converts the given timestamp to human readable string of form ‘Y-m-d H:M:S’.
- Parameters:
ts (timestamp) – time stamp to be converted
- Returns:
human readable date-time string
- Return type:
rc (string)
- to_dict()¶
Convert instance attributes to a dictionary.
- 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
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- write_attempts = 3¶
- class juham.web.RVisualCrossing(name='visualcrossing')[source]¶
Bases:
RCloud
This class constructs a data acquisition object for reading weather forecasts from the VisualCrossing web service. It subscribes to the forecast topic and writes hourly data such as solar energy, temperature, and other attributes relevant to home automation into a time series database.
Spawns an asynchronous thread to run queries at the specified update_interval.
- apiKey = 'SE9W7EHP775N7NDNW8ANM2MZN'¶
- api_key = '[someapikey]'¶
- app_name = 'juham'¶
- base_url = 'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/'¶
- classmethod classattrs_from_dict(attributes)¶
Set class attributes from a dictionary.
- classmethod classattrs_to_dict()¶
Convert class attributes to a dictionary.
- config_folder = 'config'¶
- 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.
- Returns:
A new instance of the object’s class with the same state as the original object.
Example:
john = Human("john") john.height = 1.8 john.age = 62 clone_of_john = john.copy()
- database_class_id: str | None = 0¶
- database_client: object | 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
- deserialize_from_json(f)¶
Load attributes from a JSON file.
- disconnect()¶
- epoc2utc(epoch)¶
Converts the given epoch time to UTC time string. All time coordinates are represented in UTC time. This allows the time coordinate to be mapped to any local time representation without ambiguity.
- Parameters:
epoch (float) – timestamp in UTC time
rc (str) – time string describing date, time and time zone e.g 2024-07-08T12:10:22Z
- Returns:
UTC time
- 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
- event_topic = 'juham/event'¶
- 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)
- forecast_topic = 'juham/forecast'¶
- 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.
- 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
Example:
obj = new Base('test') obj.info('Message arrived', str(msg))
- init_database(name)¶
Instantiates the configured time series database object.
Issues a warning if the
database_class_id
has not been configured, in which case the object will not have the time series recording feature.This method is called internally and typically there is no need to call it from the application code.
- Return type:
None
- init_mqtt(name)¶
Instantiates the configured MQTT object for networking.
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
- classmethod initialize_class()¶
Initialize the class for instantiation, if not initialized already. This method initializes the class identifier and deserializes the public attributes from the specified configuration folder.
- Returns:
returns true if the class was initialized, false implies the class is already initialized in which case the method call has no effect.
- Return type:
bool
- classmethod instantiate(class_id)¶
Given class identifier create the corresponding object. This method implements so called factory method pattern.
- Parameters:
class_id (int) – class identifier
- Returns:
instance of the given class.
- Return type:
obj (obj)
- classmethod instantiate_with_param(class_id, param)¶
Given class identifier and one constructor argument create the corresponding object.
- Parameters:
class_id (
str
|None
) – class identifierparam (
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
- is_time_between(begin_time, end_time, check_time=None)¶
Check if the given time is within the given time line. All timestamps must be in UTC time.
- Parameters:
begin_time (timestamp) – beginning of the timeline
end_time (timestamp) – end of the timeline
check_time (timestamp) – time to be checked
- Returns:
True if within the timeline
- Return type:
rc (bool)
- classmethod load_from_json()¶
Load class attributes from a JSON file.
- location = 'lahti,finland'¶
- 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 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).
- 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 | None = None¶
- 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
- 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
- on_event(em)¶
Notification event callback e.g info or warning.
- Parameters:
em (dictionary) – dictionary describing the event
- Return type:
None
- on_forecast(em)[source]¶
Handle weather forecast data. Writes the received hourly forecast data to timeseries database.
- Parameters:
em (dict) – forecast
- Return type:
None
- on_message(client, userdata, msg)[source]¶
The standared MQTT callback for arriving messages.
- Parameters:
client (object) – mqtt client
userdata (Any) – any user specific data
msg (object) – MQTT message
- classmethod parse_args()¶
Parse the startup arguments defined by this class.
- Return type:
None
- pubsub_class_id = 0¶
- read(point)¶
Reads the given measurement from the database.
- Parameters:
point – point with initialized time stamp.
… note: NOT IMPLEMENTED YET
- classmethod register()[source]¶
Register the class to the class database.
Once registered the class can be instantiated by its class identifier. Note that this method is called automatically by the system when the python loads the class. In this method sub classes should prepare themselves for instantiation by initializing their class attributes, for example.
- classmethod register_class(class_id, ctor)¶
Register the given class identifier for identifier based instantiation . This, factory method pattern, as it is called, decouples the actual implementation from the interface. For more information see
instantiate()
method.- Parameters:
class_id (str) – class identifier
ctor (function) – constructor
- 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.
- classmethod save_to_json()¶
Create class configuration file, if the file does not exist yet.
- serialize_to_json(f)¶
Serialize.
- 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.
- 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')
- timestamp()¶
Returns the current date-time in UTC.
- Returns:
datetime in UTC.
- Return type:
rc (datetime)
- timestampstr(ts)¶
Converts the given timestamp to human readable string of form ‘Y-m-d H:M:S’.
- Parameters:
ts (timestamp) – time stamp to be converted
- Returns:
human readable date-time string
- Return type:
rc (string)
- update_interval = 43200¶
- 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
- worker: IWorkerThread¶
- workerThreadId = 'RVisualCrossingThread'¶
- write(point)¶
Writes the given measurement to the database. In case of an error, it tries again until the maximum number of attempts is reached. If it is still unsuccessful, it gives up and passes the first encountered exception to the caller.
- Parameters:
point – a measurement describing a time stamp and related attributes for one measurement.
- write_attempts = 3¶