Debian Codegraph @

protolib/examples/zmqExample.cpp

raw
1
2 #include "protoZMQ.h"
3 #include "protoTimer.h"
4 #include "protoApp.h"
5
6 #include <stdio.h> // for stderr output as needed
7 #include <stdlib.h> // for atoi()
8
9 /*
10 * @class ZmqExample
11 *
12 * @brief This example program illustrates/tests the use of the ProtoZmq::Socket class
13 */
14 class ZmqExample : public ProtoApp
15 {
16 public:
17 ZmqExample();
18 ~ZmqExample();
19
20 // Overrides from ProtoApp or NsProtoSimAgent base
21 bool OnStartup(int argc, const char*const* argv);
22 bool ProcessCommands(int argc, const char*const* argv);
23 void OnShutdown();
24
25 bool OnCommand(const char* cmd, const char* val);
26
27 private:
28 enum CmdType {CMD_INVALID, CMD_ARG, CMD_NOARG};
29 static CmdType GetCmdType(const char* string);
30 static const char* const CMD_LIST[];
31 void Usage();
32
33 bool OnTxTimeout(ProtoTimer& theTimer);
34 void OnSocketEvent(ProtoEvent& theEvent);
35
36 ProtoTimer tx_timer;
37 ProtoZmq::Socket zmq_socket;
38 //int socket_type; // ZMQ_PUB, ZMQ_SUB, ZMQ_RADIO, ZMQ_DISH, etc
39
40 char* msg_buffer;
41 unsigned int msg_len;
42 unsigned int msg_index;
43 int msg_repeat;
44 int msg_repeat_count;
45
46 }; // end class ZmqExample
47
48 // Instantiate our application instance
49 PROTO_INSTANTIATE_APP(ZmqExample)
50
51 ZmqExample::ZmqExample()
52 : msg_buffer(NULL), msg_len(0), msg_index(0),
53 msg_repeat(0), msg_repeat_count(0)
54 {
55 tx_timer.SetListener(this, &ZmqExample::OnTxTimeout);
56 tx_timer.SetInterval(1.0);
57 tx_timer.SetRepeat(-1);
58 zmq_socket.SetNotifier(&dispatcher);
59 zmq_socket.SetListener(this, &ZmqExample::OnSocketEvent);
60 }
61
62 ZmqExample::~ZmqExample()
63 {
64 }
65
66 const char* const ZmqExample::CMD_LIST[] =
67 {
68 "+publish", // Publish 'send' messages using ZMQ_PUB socket
69 "+subscribe", // Subscribe with ZMQ_SUB socket
70 "+radio", // Publish 'send' messages with given ZMQ_RADIO socket
71 "+dish", // Receive with given ZMQ_DISH socket
72 "+repeat", // repeat message multiple times
73 "+send", // Send given string as message
74 NULL
75 };
76
77 void ZmqExample::Usage()
78 {
79 fprintf(stderr, "zmqExample [publish <endpoint>][subscribe <endpoint>]\n"
80 " [send <message>][repeat <repeatCount>]\n");
81 } // end ZmqExample::Usage()
82
83 bool ZmqExample::OnStartup(int argc, const char*const* argv)
84 {
85 if (argc < 2)
86 {
87 Usage();
88 return false;
89 }
90 if (!ProcessCommands(argc, argv))
91 {
92 PLOG(PL_ERROR, "ZmqExample::OnStartup() error processing command line\n");
93 Usage();
94 return false;
95 }
96 return true;
97 } // end ZmqExample::OnStartup()
98
99 void ZmqExample::OnShutdown()
100 {
101 if (tx_timer.IsActive()) tx_timer.Deactivate();
102 if (zmq_socket.IsOpen()) zmq_socket.Close();
103 if (zmq_socket.IsOpen()) zmq_socket.Close();
104 PLOG(PL_ERROR, "zmqExample: Done.\n");
105 } // end ZmqExample::OnShutdown()
106
107 bool ZmqExample::OnCommand(const char* cmd, const char* val)
108 {
109 CmdType type = GetCmdType(cmd);
110 ASSERT(CMD_INVALID != type);
111 unsigned int len = strlen(cmd);
112 if ((CMD_ARG == type) && !val)
113 {
114 PLOG(PL_ERROR, "zmqExample::ProcessCommand(%s) missing argument\n", cmd);
115 return false;
116 }
117 else if (!strncmp("publish", cmd, len))
118 {
119 if (zmq_socket.IsOpen()) zmq_socket.Close();
120 if (!zmq_socket.Open(ZMQ_PUB))
121 {
122 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_socket.Open() error\n");
123 return false;
124 }
125 if (!zmq_socket.Bind(val))
126 {
127 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_socket.Bind() error\n");
128 return false;
129 }
130 TRACE("zmqExample: publishing to %s ...\n", val);
131 }
132 else if (!strncmp("subscribe", cmd, len))
133 {
134 if (zmq_socket.IsOpen()) zmq_socket.Close();
135 if (!zmq_socket.Open(ZMQ_SUB))
136 {
137 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_socket.Open() error\n");
138 return false;
139 }
140 if (!zmq_socket.Connect(val))
141 {
142 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_socket.Connect() error\n");
143 return false;
144 }
145 // subscribe to all messages
146 if (!zmq_socket.Subscribe(NULL))
147 {
148 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_setsockopt(ZMQ_SUBSCRIBE) error\n");
149 //return false;
150 }
151 TRACE("zmqExample: subscribed to %s ...\n", val);
152 }
153 else if (!strncmp("radio", cmd, len))
154 {
155 if (zmq_socket.IsOpen()) zmq_socket.Close();
156 if (!zmq_socket.Open(ZMQ_RADIO))
157 {
158 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_socket.Open() error\n");
159 return false;
160 }
161 if (!zmq_socket.Connect(val))
162 {
163 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_socket.Bind() error\n");
164 return false;
165 }
166 TRACE("zmqExample: publishing to %s ...\n", val);
167 }
168 else if (!strncmp("dish", cmd, len))
169 {
170 if (zmq_socket.IsOpen()) zmq_socket.Close();
171 if (!zmq_socket.Open(ZMQ_DISH))
172 {
173 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_socket.Open() error\n");
174 return false;
175 }
176 if (!zmq_socket.Bind(val))
177 {
178 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_socket.Connect() error\n");
179 return false;
180 }
181 // subscribe to all messages
182 if (!zmq_socket.Join("")) // "" joins "group-less" group
183 {
184 PLOG(PL_ERROR, "ZmqExample::OnCommand() zmq_join() error: %s\n", zmq_strerror(zmq_errno()));
185 return false;
186 }
187 TRACE("zmqExample: subscribed to %s ...\n", val);
188 }
189 else if (!strncmp("repeat", cmd, len))
190 {
191 msg_repeat = atoi(val);
192 }
193 else if (!strncmp("send", cmd, len))
194 {
195 if (msg_buffer) delete[] msg_buffer;
196 msg_len = strlen(val);
197 if (!(msg_buffer = new char[msg_len + 8]))
198 {
199 PLOG(PL_ERROR, "zmqExample: new msg_buffer error: %s\n", GetErrorString());
200 msg_len = 0;
201 return false;
202 }
203 strcpy(msg_buffer, val);
204 msg_index = 0;
205 msg_repeat_count = msg_repeat;
206 if (tx_timer.IsActive()) tx_timer.Deactivate();
207 if (msg_repeat_count) ActivateTimer(tx_timer);
208 OnTxTimeout(tx_timer); // go ahead and send msg immediately
209 }
210 else
211 {
212 PLOG(PL_ERROR, "ZmqExample::OnCommand() unknown command error?\n");
213 return false;
214 }
215 return true;
216 } // end ZmqExample::OnCommand()
217
218 bool ZmqExample::OnTxTimeout(ProtoTimer& /*theTimer*/)
219 {
220 TRACE("zmqExample::OnTxTimeout() ...\n");
221 // Add an index to end of msg_buffer to make it easier to track
222 sprintf(msg_buffer + msg_len, " %u", (unsigned int)msg_index++);
223 unsigned int numBytes = strlen(msg_buffer) + 1;
224 TRACE("sending %u bytes: %s ...\n", numBytes, msg_buffer);
225 zmq_socket.Send(msg_buffer, numBytes);
226 msg_buffer[msg_len] = '\0';
227 msg_index %= 1024; // limit the index so the string doesn't ever get too long
228 return true;
229 } // end ZmqExample::OnTxTimeout()
230
231 void ZmqExample::OnSocketEvent(ProtoEvent& /*theEvent*/)
232 {
233 //TRACE("zmqExample: zmq_socket EVENT..\n");
234 int events;
235 size_t len = sizeof(int);
236 // Loop here to receive all available messages
237 unsigned int numBytes;
238 do
239 {
240 // NOTE: instead of using zmq_getsockopt(), one can safely just call
241 // zmq_socket.Recv() in a loop until it returns 'false' or 0 == numBytes
242 // since Recv() is non-blocking.
243 if (0 != zmq_getsockopt(zmq_socket.GetSocket(), ZMQ_EVENTS, &events, &len))
244 {
245 PLOG(PL_ERROR, "ZmqExample::OnSubEvent() zmq_getsockopt() error: %s\n", GetErrorString());
246 break;
247 }
248 if (0 != (ZMQ_POLLIN & events))
249 {
250 char buffer[2048];
251 buffer[2047] = '\0';
252 numBytes = 2047;
253 if (zmq_socket.Recv(buffer, numBytes))
254 {
255 buffer[numBytes] = '\0';
256 TRACE("received %u bytes: %s\n", numBytes, buffer);
257 }
258 else
259 {
260 TRACE("receive error?\n");
261 }
262 }
263 } while (0 != (ZMQ_POLLIN & events));
264 if ((0 != (ZMQ_POLLOUT & zmq_socket.GetPollFlags())) &&
265 (0 != (ZMQ_POLLOUT & events)))
266 {
267 TRACE(" ZMQ_POLLOUT\n"); // only will occur if ProtoZmq::Socket::StartOutputNotification() was called
268 }
269 if (0 != (ZMQ_POLLERR & events))
270 {
271 TRACE(" ZMQ_POLLERR\n");
272 }
273 } // end ZmqExample::OnSocketEvent()
274
275
276 ZmqExample::CmdType ZmqExample::GetCmdType(const char* cmd)
277 {
278 if (!cmd) return CMD_INVALID;
279 unsigned int len = strlen(cmd);
280 bool matched = false;
281 CmdType type = CMD_INVALID;
282 const char* const* nextCmd = CMD_LIST;
283 while (*nextCmd)
284 {
285 if (!strncmp(cmd, *nextCmd+1, len))
286 {
287 if (matched)
288 {
289 // ambiguous command (command should match only once)
290 return CMD_INVALID;
291 }
292 else
293 {
294 matched = true;
295 if ('+' == *nextCmd[0])
296 type = CMD_ARG;
297 else
298 type = CMD_NOARG;
299 }
300 }
301 nextCmd++;
302 }
303 return type;
304 } // end ZmqExample::GetCmdType()
305
306 bool ZmqExample::ProcessCommands(int argc, const char*const* argv)
307 {
308 // Dispatch command-line commands to our OnCommand() method
309 int i = 1;
310 while ( i < argc)
311 {
312 // Is it a class ZmqExample command?
313 switch (GetCmdType(argv[i]))
314 {
315 case CMD_INVALID:
316 PLOG(PL_ERROR, "zmqExample::ProcessCommands() Invalid command:%s\n",
317 argv[i]);
318 return false;
319 case CMD_NOARG:
320 if (!OnCommand(argv[i], NULL))
321 {
322 PLOG(PL_ERROR, "zmqExample::ProcessCommands() ProcessCommand(%s) error\n",
323 argv[i]);
324 return false;
325 }
326 i++;
327 break;
328 case CMD_ARG:
329 if (!OnCommand(argv[i], argv[i+1]))
330 {
331 PLOG(PL_ERROR, "zmqExample::ProcessCommands() ProcessCommand(%s, %s) error\n",
332 argv[i], argv[i+1]);
333 return false;
334 }
335 i += 2;
336 break;
337 }
338 }
339 return true;
340 } // end ZmqExample::ProcessCommands()
341