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

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

27 

28 

29class MessageHandling(): 

30 """Message handling class.""" 

31 

32 def __init__(self, state): 

33 self.broker = BrokerConnect(state) 

34 self.api = ApiConnect(state) 

35 self.info = Information(state) 

36 self.state = state 

37 

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

42 

43 validate_log_options(message_type, channel) 

44 

45 log_message = { 

46 "message": message_str, 

47 "type": message_type, 

48 "channels": [channel], 

49 } 

50 

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

52 

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

57 

58 validate_log_options(message_type, channel) 

59 

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 } 

73 

74 self.broker.publish(message) 

75 

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

80 

81 self.message(message_str, "debug", "ticker") 

82 

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

87 

88 self.message(message_str, message_type, channel="toast")