Coverage for farmbot_sidecar_starter_pack/functions/messages.py: 100%
32 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-09-11 15:43 -0700
« prev ^ index » next coverage.py v7.4.4, created at 2024-09-11 15:43 -0700
1"""
2MessageHandling class.
3"""
5# └── functions/messages.py
6# ├── [API] log()
7# ├── [BROKER] message()
8# ├── [BROKER] debug()
9# └── [BROKER] toast()
11from .broker import BrokerConnect
12from .api import ApiConnect
13from .information import Information
15MESSAGE_TYPES = ["assertion", "busy", "debug",
16 "error", "fun", "info", "success", "warn"]
17CHANNELS = ["ticker", "toast", "email", "espeak"]
20def validate_log_options(message_type, channel):
21 """Validate the message type and channel options."""
22 if message_type not in MESSAGE_TYPES:
23 raise ValueError(
24 f"Invalid message type: `{message_type}` not in {MESSAGE_TYPES}")
25 if channel not in CHANNELS:
26 raise ValueError(f"Invalid channel: {channel} not in {CHANNELS}")
29class MessageHandling():
30 """Message handling class."""
32 def __init__(self, state):
33 self.broker = BrokerConnect(state)
34 self.api = ApiConnect(state)
35 self.info = Information(state)
36 self.state = state
38 def log(self, message_str, message_type="info", channel="ticker"):
39 """Sends new log message via the API."""
40 self.state.print_status(
41 description="Sending new log message to the API.")
43 validate_log_options(message_type, channel)
45 log_message = {
46 "message": message_str,
47 "type": message_type,
48 "channels": [channel],
49 }
51 self.info.api_post("logs", log_message)
53 def message(self, message_str, message_type="info", channel="ticker"):
54 """Sends new log message via the message broker."""
55 self.state.print_status(
56 description="Sending new log message to the message broker.")
58 validate_log_options(message_type, channel)
60 message = {
61 "kind": "send_message",
62 "args": {
63 "message": message_str,
64 "message_type": message_type,
65 },
66 "body": [{
67 "kind": "channel",
68 "args": {
69 "channel_name": channel
70 }
71 }]
72 }
74 self.broker.publish(message)
76 def debug(self, message_str):
77 """Sends debug message used for developer information or troubleshooting."""
78 self.state.print_status(
79 description="Sending debug message to the message broker.")
81 self.message(message_str, "debug", "ticker")
83 def toast(self, message_str, message_type="info"):
84 """Sends a message that pops up on the user interface briefly."""
85 self.state.print_status(
86 description="Sending toast message to the message broker.")
88 self.message(message_str, message_type, channel="toast")