Coverage for farmbot/functions/messages.py: 100%
37 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-09-12 12:18 -0700
« prev ^ index » next coverage.py v7.4.4, created at 2024-09-12 12:18 -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, channels):
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 for channel in channels:
26 if channel not in CHANNELS:
27 raise ValueError(f"Invalid channel: {channel} not in {CHANNELS}")
30class MessageHandling():
31 """Message handling class."""
33 def __init__(self, state):
34 self.broker = BrokerConnect(state)
35 self.api = ApiConnect(state)
36 self.info = Information(state)
37 self.state = state
39 def log(self, message_str, message_type="info", channels=None):
40 """Sends new log message via the API."""
41 self.state.print_status(
42 description="Sending new log message to the API.")
44 channels = channels or []
45 validate_log_options(message_type, channels)
47 log_message = {
48 "message": message_str,
49 "type": message_type,
50 "channels": channels,
51 }
53 self.info.api_post("logs", log_message)
55 def send_message(self, message_str, message_type="info", channels=None):
56 """Sends new log message via the message broker."""
57 self.state.print_status(
58 description="Sending new log message to the message broker.")
60 channels = channels or []
61 validate_log_options(message_type, channels)
63 message = {
64 "kind": "send_message",
65 "args": {
66 "message": message_str,
67 "message_type": message_type,
68 },
69 "body": [],
70 }
72 for channel in channels:
73 message["body"].append({
74 "kind": "channel",
75 "args": {"channel_name": channel}})
77 self.broker.publish(message)
79 def debug(self, message_str):
80 """Sends debug message used for developer information or troubleshooting."""
81 self.state.print_status(
82 description="Sending debug message to the message broker.")
84 self.send_message(message_str, "debug")
86 def toast(self, message_str, message_type="info"):
87 """Sends a message that pops up on the user interface briefly."""
88 self.state.print_status(
89 description="Sending toast message to the message broker.")
91 self.send_message(message_str, message_type, channels=["toast"])