PageRenderTime 66ms CodeModel.GetById 36ms RepoModel.GetById 1ms app.codeStats 0ms

/client/sub_client.c

https://bitbucket.org/trj/mosquitto-eventloop
C | 412 lines | 366 code | 18 blank | 28 comment | 101 complexity | fb122da1543015d1597b1b8e1e984fb5 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. /*
  2. Copyright (c) 2009-2012 Roger Light <roger@atchoo.org>
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. 3. Neither the name of mosquitto nor the names of its
  12. contributors may be used to endorse or promote products derived from
  13. this software without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  18. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  20. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  22. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  24. POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <errno.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #ifndef WIN32
  31. #include <unistd.h>
  32. #else
  33. #include <process.h>
  34. #include <winsock2.h>
  35. #define snprintf sprintf_s
  36. #endif
  37. #include <mosquitto.h>
  38. static char **topics = NULL;
  39. static int topic_count = 0;
  40. static int topic_qos = 0;
  41. static char *username = NULL;
  42. static char *password = NULL;
  43. int verbose = 0;
  44. bool quiet = false;
  45. void my_message_callback(void *obj, const struct mosquitto_message *message)
  46. {
  47. if(verbose){
  48. if(message->payloadlen){
  49. printf("%s %s\n", message->topic, message->payload);
  50. }else{
  51. printf("%s (null)\n", message->topic);
  52. }
  53. fflush(stdout);
  54. }else{
  55. if(message->payloadlen){
  56. printf("%s\n", message->payload);
  57. fflush(stdout);
  58. }
  59. }
  60. }
  61. void my_connect_callback(void *obj, int result)
  62. {
  63. struct mosquitto *mosq = obj;
  64. int i;
  65. if(!result){
  66. for(i=0; i<topic_count; i++){
  67. mosquitto_subscribe(mosq, NULL, topics[i], topic_qos);
  68. }
  69. }else{
  70. switch(result){
  71. case 1:
  72. if(!quiet) fprintf(stderr, "Connection Refused: unacceptable protocol version\n");
  73. break;
  74. case 2:
  75. if(!quiet) fprintf(stderr, "Connection Refused: identifier rejected\n");
  76. break;
  77. case 3:
  78. if(!quiet) fprintf(stderr, "Connection Refused: broker unavailable\n");
  79. break;
  80. case 4:
  81. if(!quiet) fprintf(stderr, "Connection Refused: bad user name or password\n");
  82. break;
  83. case 5:
  84. if(!quiet) fprintf(stderr, "Connection Refused: not authorised\n");
  85. break;
  86. default:
  87. if(!quiet) fprintf(stderr, "Connection Refused: unknown reason\n");
  88. break;
  89. }
  90. }
  91. }
  92. void my_subscribe_callback(void *obj, uint16_t mid, int qos_count, const uint8_t *granted_qos)
  93. {
  94. int i;
  95. if(!quiet) printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
  96. for(i=1; i<qos_count; i++){
  97. if(!quiet) printf(", %d", granted_qos[i]);
  98. }
  99. if(!quiet) printf("\n");
  100. }
  101. void print_usage(void)
  102. {
  103. printf("mosquitto_sub is a simple mqtt client that will subscribe to a single topic and print all messages it receives.\n\n");
  104. printf("Usage: mosquitto_sub [-c] [-h host] [-k keepalive] [-p port] [-q qos] [-v] -t topic ...\n");
  105. printf(" [-i id] [-I id_prefix]\n");
  106. printf(" [-d] [--quiet]\n");
  107. printf(" [-u username [-P password]]\n");
  108. printf(" [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]\n\n");
  109. printf(" -c : disable 'clean session' (store subscription and pending messages when client disconnects).\n");
  110. printf(" -d : enable debug messages.\n");
  111. printf(" -h : mqtt host to connect to. Defaults to localhost.\n");
  112. printf(" -i : id to use for this client. Defaults to mosquitto_sub_ appended with the process id.\n");
  113. printf(" -I : define the client id as id_prefix appended with the process id. Useful for when the\n");
  114. printf(" broker is using the clientid_prefixes option.\n");
  115. printf(" -k : keep alive in seconds for this client. Defaults to 60.\n");
  116. printf(" -p : network port to connect to. Defaults to 1883.\n");
  117. printf(" -q : quality of service level to use for the subscription. Defaults to 0.\n");
  118. printf(" -t : mqtt topic to subscribe to. May be repeated multiple times.\n");
  119. printf(" -u : provide a username (requires MQTT 3.1 broker)\n");
  120. printf(" -v : print published messages verbosely.\n");
  121. printf(" -P : provide a password (requires MQTT 3.1 broker)\n");
  122. printf(" --quiet : don't print error messages.\n");
  123. printf(" --will-payload : payload for the client Will, which is sent by the broker in case of\n");
  124. printf(" unexpected disconnection. If not given and will-topic is set, a zero\n");
  125. printf(" length message will be sent.\n");
  126. printf(" --will-qos : QoS level for the client Will.\n");
  127. printf(" --will-retain : if given, make the client Will retained.\n");
  128. printf(" --will-topic : the topic on which to publish the client Will.\n");
  129. printf("\nSee http://mosquitto.org/ for more information.\n\n");
  130. }
  131. int main(int argc, char *argv[])
  132. {
  133. char *id = NULL;
  134. char *id_prefix = NULL;
  135. int i;
  136. char *host = "localhost";
  137. int port = 1883;
  138. int keepalive = 60;
  139. bool clean_session = true;
  140. bool debug = false;
  141. struct mosquitto *mosq = NULL;
  142. int rc;
  143. char hostname[21];
  144. char err[1024];
  145. uint8_t *will_payload = NULL;
  146. long will_payloadlen = 0;
  147. int will_qos = 0;
  148. bool will_retain = false;
  149. char *will_topic = NULL;
  150. for(i=1; i<argc; i++){
  151. if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){
  152. if(i==argc-1){
  153. fprintf(stderr, "Error: -p argument given but no port specified.\n\n");
  154. print_usage();
  155. return 1;
  156. }else{
  157. port = atoi(argv[i+1]);
  158. if(port<1 || port>65535){
  159. fprintf(stderr, "Error: Invalid port given: %d\n", port);
  160. print_usage();
  161. return 1;
  162. }
  163. }
  164. i++;
  165. }else if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--disable-clean-session")){
  166. clean_session = false;
  167. }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")){
  168. debug = true;
  169. }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--host")){
  170. if(i==argc-1){
  171. fprintf(stderr, "Error: -h argument given but no host specified.\n\n");
  172. print_usage();
  173. return 1;
  174. }else{
  175. host = argv[i+1];
  176. }
  177. i++;
  178. }else if(!strcmp(argv[i], "-i") || !strcmp(argv[i], "--id")){
  179. if(id_prefix){
  180. fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
  181. print_usage();
  182. return 1;
  183. }
  184. if(i==argc-1){
  185. fprintf(stderr, "Error: -i argument given but no id specified.\n\n");
  186. print_usage();
  187. return 1;
  188. }else{
  189. id = argv[i+1];
  190. }
  191. i++;
  192. }else if(!strcmp(argv[i], "-I") || !strcmp(argv[i], "--id-prefix")){
  193. if(id){
  194. fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
  195. print_usage();
  196. return 1;
  197. }
  198. if(i==argc-1){
  199. fprintf(stderr, "Error: -I argument given but no id prefix specified.\n\n");
  200. print_usage();
  201. return 1;
  202. }else{
  203. id_prefix = argv[i+1];
  204. }
  205. i++;
  206. }else if(!strcmp(argv[i], "-k") || !strcmp(argv[i], "--keepalive")){
  207. if(i==argc-1){
  208. fprintf(stderr, "Error: -k argument given but no keepalive specified.\n\n");
  209. print_usage();
  210. return 1;
  211. }else{
  212. keepalive = atoi(argv[i+1]);
  213. if(keepalive>65535){
  214. fprintf(stderr, "Error: Invalid keepalive given: %d\n", keepalive);
  215. print_usage();
  216. return 1;
  217. }
  218. }
  219. i++;
  220. }else if(!strcmp(argv[i], "-q") || !strcmp(argv[i], "--qos")){
  221. if(i==argc-1){
  222. fprintf(stderr, "Error: -q argument given but no QoS specified.\n\n");
  223. print_usage();
  224. return 1;
  225. }else{
  226. topic_qos = atoi(argv[i+1]);
  227. if(topic_qos<0 || topic_qos>2){
  228. fprintf(stderr, "Error: Invalid QoS given: %d\n", topic_qos);
  229. print_usage();
  230. return 1;
  231. }
  232. }
  233. i++;
  234. }else if(!strcmp(argv[i], "--quiet")){
  235. quiet = true;
  236. }else if(!strcmp(argv[i], "-t") || !strcmp(argv[i], "--topic")){
  237. if(i==argc-1){
  238. fprintf(stderr, "Error: -t argument given but no topic specified.\n\n");
  239. print_usage();
  240. return 1;
  241. }else{
  242. topic_count++;
  243. topics = realloc(topics, topic_count*sizeof(char *));
  244. topics[topic_count-1] = argv[i+1];
  245. }
  246. i++;
  247. }else if(!strcmp(argv[i], "-u") || !strcmp(argv[i], "--username")){
  248. if(i==argc-1){
  249. fprintf(stderr, "Error: -u argument given but no username specified.\n\n");
  250. print_usage();
  251. return 1;
  252. }else{
  253. username = argv[i+1];
  254. }
  255. i++;
  256. }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){
  257. verbose = 1;
  258. }else if(!strcmp(argv[i], "-P") || !strcmp(argv[i], "--pw")){
  259. if(i==argc-1){
  260. fprintf(stderr, "Error: -P argument given but no password specified.\n\n");
  261. print_usage();
  262. return 1;
  263. }else{
  264. password = argv[i+1];
  265. }
  266. i++;
  267. }else if(!strcmp(argv[i], "--will-payload")){
  268. if(i==argc-1){
  269. fprintf(stderr, "Error: --will-payload argument given but no will payload specified.\n\n");
  270. print_usage();
  271. return 1;
  272. }else{
  273. will_payload = (uint8_t *)argv[i+1];
  274. will_payloadlen = strlen((char *)will_payload);
  275. }
  276. i++;
  277. }else if(!strcmp(argv[i], "--will-qos")){
  278. if(i==argc-1){
  279. fprintf(stderr, "Error: --will-qos argument given but no will QoS specified.\n\n");
  280. print_usage();
  281. return 1;
  282. }else{
  283. will_qos = atoi(argv[i+1]);
  284. if(will_qos < 0 || will_qos > 2){
  285. fprintf(stderr, "Error: Invalid will QoS %d.\n\n", will_qos);
  286. return 1;
  287. }
  288. }
  289. i++;
  290. }else if(!strcmp(argv[i], "--will-retain")){
  291. will_retain = true;
  292. }else if(!strcmp(argv[i], "--will-topic")){
  293. if(i==argc-1){
  294. fprintf(stderr, "Error: --will-topic argument given but no will topic specified.\n\n");
  295. print_usage();
  296. return 1;
  297. }else{
  298. will_topic = argv[i+1];
  299. }
  300. i++;
  301. }else{
  302. fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
  303. print_usage();
  304. return 1;
  305. }
  306. }
  307. if(clean_session == false && (id_prefix || !id)){
  308. if(!quiet) fprintf(stderr, "Error: You must provide a client id if you are using the -c option.\n");
  309. return 1;
  310. }
  311. if(id_prefix){
  312. id = malloc(strlen(id_prefix)+10);
  313. if(!id){
  314. if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
  315. return 1;
  316. }
  317. snprintf(id, strlen(id_prefix)+10, "%s%d", id_prefix, getpid());
  318. }else if(!id){
  319. id = malloc(30);
  320. if(!id){
  321. if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
  322. return 1;
  323. }
  324. memset(hostname, 0, 21);
  325. gethostname(hostname, 20);
  326. snprintf(id, 23, "mosq_sub_%d_%s", getpid(), hostname);
  327. }
  328. if(topic_count == 0){
  329. fprintf(stderr, "Error: You must specify a topic to subscribe to.\n");
  330. print_usage();
  331. return 1;
  332. }
  333. if(will_payload && !will_topic){
  334. fprintf(stderr, "Error: Will payload given, but no will topic given.\n");
  335. print_usage();
  336. return 1;
  337. }
  338. if(will_retain && !will_topic){
  339. fprintf(stderr, "Error: Will retain given, but no will topic given.\n");
  340. print_usage();
  341. return 1;
  342. }
  343. if(password && !username){
  344. if(!quiet) fprintf(stderr, "Warning: Not using password since username not set.\n");
  345. }
  346. mosquitto_lib_init();
  347. mosq = mosquitto_new(id, NULL);
  348. if(!mosq){
  349. if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
  350. return 1;
  351. }
  352. if(debug){
  353. mosquitto_log_init(mosq, MOSQ_LOG_DEBUG | MOSQ_LOG_ERR | MOSQ_LOG_WARNING
  354. | MOSQ_LOG_NOTICE | MOSQ_LOG_INFO, MOSQ_LOG_STDERR);
  355. }
  356. if(will_topic && mosquitto_will_set(mosq, true, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){
  357. if(!quiet) fprintf(stderr, "Error: Problem setting will.\n");
  358. return 1;
  359. }
  360. if(username && mosquitto_username_pw_set(mosq, username, password)){
  361. if(!quiet) fprintf(stderr, "Error: Problem setting username and password.\n");
  362. return 1;
  363. }
  364. mosquitto_connect_callback_set(mosq, my_connect_callback);
  365. mosquitto_message_callback_set(mosq, my_message_callback);
  366. if(debug){
  367. mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
  368. }
  369. rc = mosquitto_connect(mosq, host, port, keepalive, clean_session);
  370. if(rc){
  371. if(!quiet){
  372. if(rc == MOSQ_ERR_ERRNO){
  373. #ifndef WIN32
  374. strerror_r(errno, err, 1024);
  375. #else
  376. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errno, 0, (LPTSTR)&err, 1024, NULL);
  377. #endif
  378. fprintf(stderr, "Error: %s\n", err);
  379. }else{
  380. fprintf(stderr, "Unable to connect (%d).\n", rc);
  381. }
  382. }
  383. return rc;
  384. }
  385. do{
  386. rc = mosquitto_loop(mosq, -1);
  387. }while(rc == MOSQ_ERR_SUCCESS);
  388. mosquitto_destroy(mosq);
  389. mosquitto_lib_cleanup();
  390. return rc;
  391. }