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

1""" 

2MessageHandling class. 

3""" 

4 

5# └── functions/messages.py 

6# ├── [API] log() 

7# ├── [BROKER] message() 

8# ├── [BROKER] debug() 

9# └── [BROKER] toast() 

10 

11from .broker import BrokerConnect 

12from .api import ApiConnect 

13from .information import Information 

14 

15MESSAGE_TYPES = ["assertion", "busy", "debug", 

16 "error", "fun", "info", "success", "warn"] 

17CHANNELS = ["ticker", "toast", "email", "espeak"] 

18 

19 

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}") 

28 

29 

30class MessageHandling(): 

31 """Message handling class.""" 

32 

33 def __init__(self, state): 

34 self.broker = BrokerConnect(state) 

35 self.api = ApiConnect(state) 

36 self.info = Information(state) 

37 self.state = state 

38 

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.") 

43 

44 channels = channels or [] 

45 validate_log_options(message_type, channels) 

46 

47 log_message = { 

48 "message": message_str, 

49 "type": message_type, 

50 "channels": channels, 

51 } 

52 

53 self.info.api_post("logs", log_message) 

54 

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.") 

59 

60 channels = channels or [] 

61 validate_log_options(message_type, channels) 

62 

63 message = { 

64 "kind": "send_message", 

65 "args": { 

66 "message": message_str, 

67 "message_type": message_type, 

68 }, 

69 "body": [], 

70 } 

71 

72 for channel in channels: 

73 message["body"].append({ 

74 "kind": "channel", 

75 "args": {"channel_name": channel}}) 

76 

77 self.broker.publish(message) 

78 

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.") 

83 

84 self.send_message(message_str, "debug") 

85 

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.") 

90 

91 self.send_message(message_str, message_type, channels=["toast"])