1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 from spoon import NMTYPE_MESSAGING
25
26
28 """
29 This is the main messaging class that implements the basic functionality for Spoon.
30 Messaging implementations that need specific functionality (such as reliablility) will
31 probably want to subclass from this.
32
33 There may be multiple instances of Messaging per python process, however there should only be one per
34 network to which a node is a member. There may be a case where one would want a single Messaging instance
35 shared between networks however, and as long as the node ids on the networks do not overlap, you shouldn't have
36 any problems.
37
38 You cannot use the acceptMsg decorator with this, for that you have to use the SingletonMessaging class.
39 To register handlers with instances of Messaging, you must use the registerHandler method on
40 the Messaging instance.
41 """
43 self.handlers = {}
44 self.network = network
45 if network:
46 self.network.nmtypes[NMTYPE_MESSAGING] = self
47
49 handlers = self.handlers.get(msgtype, None)
50 if handlers:
51 handlers.append(handler)
52 else:
53 self.handlers[msgtype] = [handler]
54
56 handlers = self.handlers.get(msgtype, None)
57 if handlers:
58 try:
59 handlers.remove(handler)
60 except:
61 pass
62
64 """
65 Calls the all handlers for the given message.
66 @param src: The source node of the message
67 @param msg: A list containing the message type, and the attached object.
68 """
69 handlers = self.handlers.get(msg[0], [])
70 for handler in handlers:
71 handler(src, msg[0], msg[1])
72
76
77 - def send(self, dst, messageStr, obj):
78 """
79 Sends a Messaging message (not just a NetMessage) to the
80 destination node.
81 @param dst: Destination node id
82 @param messageStr: A string describing the message type.
83 @param obj: Some object attached the net message.
84 """
85 self.network.sendNetMsg(dst, NMTYPE_MESSAGING, (messageStr, obj))
86
87
89 """
90 For convinience this is a singleton version of the Messaging system.
91 This can be used when the node will only have one Messaging system
92 throughout the life of the process. Furthermore, if this is the case
93 you can use the function/static method decorator acceptMsg with this.
94 """
95 singleton = None
96
97 @staticmethod
104
105 @staticmethod
108
109 -def send(dst, messageStr, obj):
110 """
111 Shortcut for calling send on the SingletonMessaging class.
112 @param dst: Destination node id
113 @param messageStr: A string describing the message type.
114 @param obj: Some object attached the net message.
115 """
116 SingletonMessaging.getinstance().send(dst, messageStr, obj)
117