1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | #include <stdbool.h>
|
31 | #include <stdio.h>
|
32 | #include <stdlib.h>
|
33 | #include <string.h>
|
34 | #ifndef WIN32
|
35 | #include <unistd.h>
|
36 | #else
|
37 | #include <process.h>
|
38 | #define snprintf sprintf_s
|
39 | #endif
|
40 |
|
41 | #include <mosquitto.h>
|
42 |
|
43 | void my_connect_callback(struct mosquitto *mosq, void *obj, int result)
|
44 | {
|
45 | char topic[100];
|
46 |
|
47 | if(!result){
|
48 | snprintf(topic, 100, "fake/%d", getpid()%100);
|
49 | mosquitto_subscribe(mosq, NULL, topic, rand()%3);
|
50 | }
|
51 | }
|
52 |
|
53 | int main(int argc, char *argv[])
|
54 | {
|
55 | char id[30];
|
56 | char *host = "localhost";
|
57 | int port = 1883;
|
58 | int keepalive = 60;
|
59 | bool clean_session = false;
|
60 | struct mosquitto *mosq = NULL;
|
61 |
|
62 | void *will_payload = NULL;
|
63 | long will_payloadlen = 0;
|
64 | int will_qos = 0;
|
65 | bool will_retain = false;
|
66 | char will_topic[100], topic[100];
|
67 | int pid;
|
68 |
|
69 | pid = getpid();
|
70 |
|
71 | srand(pid);
|
72 | snprintf(id, 30, "fake_user_%d", pid);
|
73 |
|
74 | mosquitto_lib_init();
|
75 | mosq = mosquitto_new(id, clean_session, NULL);
|
76 | if(!mosq){
|
77 | fprintf(stderr, "Error: Out of memory.\n");
|
78 | return 1;
|
79 | }
|
80 |
|
81 | if(rand()%5 == 0){
|
82 | snprintf(will_topic, 100, "fake/wills/%d", rand()%100);
|
83 | if(mosquitto_will_set(mosq, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){
|
84 | fprintf(stderr, "Error: Problem setting will.\n");
|
85 | return 1;
|
86 | }
|
87 | }
|
88 | mosquitto_connect_callback_set(mosq, my_connect_callback);
|
89 | while(1){
|
90 | clean_session = rand()%10==0?false:true;
|
91 |
|
92 | if(mosquitto_connect(mosq, host, port, keepalive)){
|
93 | fprintf(stderr, "Unable to connect.\n");
|
94 | return 1;
|
95 | }
|
96 | mosquitto_subscribe(mosq, NULL, "#", 0);
|
97 |
|
98 | while(!mosquitto_loop(mosq, -1, 5)){
|
99 | if(rand()%100==0){
|
100 | snprintf(topic, 100, "fake/%d", rand()%100);
|
101 | mosquitto_publish(mosq, NULL, topic, 10, "0123456789", rand()%3, rand()%2);
|
102 | }
|
103 | if(rand()%50==0){
|
104 | mosquitto_disconnect(mosq);
|
105 | }
|
106 | }
|
107 | sleep(10);
|
108 | }
|
109 | mosquitto_destroy(mosq);
|
110 | mosquitto_lib_cleanup();
|
111 |
|
112 | return 0;
|
113 | }
|
114 |
|