guowenxue
2019-06-25 02294c1c430ab80bd4543af28f867c5c2927e5c1
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*********************************************************************************
 *      Copyright:  (C) 2019 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  main.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(29/01/19)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "29/01/19 15:34:41"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <time.h>
#include <unistd.h>
 
#include <mosquitto.h>
 
#include "logger.h"
#include "proc.h"
#include "hal.h"
 
#define DAEMON_PIDFILE             "/tmp/.mqtt.pid"
 
#define MQTT_SYS_TOPIC             "$Sys/Studio/"
#define MQTT_SYS_DLINK_TOPIC       MQTT_SYS_TOPIC"Downlink"
#define MQTT_SYS_ULINK_TOPIC       MQTT_SYS_TOPIC"Uplink"
 
enum
{
    Qos0, /* 发送者只发送一次消息,不进行重试,Broker不会返回确认消息。在Qos0情况下,Broker可能没有接受到消息 */
    Qos1, /* 发送者最少发送一次消息,确保消息到达Broker,Broker需要返回确认消息PUBACK。在Qos1情况下,Broker可能接受到重复消息 */
    Qos2, /* Qos2使用两阶段确认来保证消息的不丢失和不重复。在Qos2情况下,Broker肯定会收到消息,且只收到一次  */
};
 
typedef struct mqtt_ctx_s 
{
    char          host[128];  /* MQTT broker server name  */
    int           port;       /* MQTT broker listen port  */
    int           keepalive;  /* MQTT broker send PING message to subsciber/publisher keepalive timeout<seconds> */
 
    /* Publisher */
    int           pubQos;
 
    /* Subscriber */
    int           subQos;
} mqtt_ctx_t;  
 
 
int check_set_program_running(int daemon);
void *mqtt_sub_worker(void *args);
void *mqtt_pub_worker(void *args);
 
 
int main (int argc, char **argv)
{
    float              temp;
    float              rh;
    int                daemon = 0;
    pthread_t          tid;
    mqtt_ctx_t         ctx;
 
    strcpy(ctx.host, "127.0.0.1");
    ctx.port = 10883;
    ctx.keepalive = 60;
    ctx.pubQos = Qos0;
    ctx.subQos = Qos2;
 
    //if( logger_init("mqttd.log", LOG_LEVEL_DEBUG, 1024) < 0 ) 
    if( logger_init(DBG_LOG_FILE, LOG_LEVEL_DEBUG, 1024) < 0 ) 
    {
        fprintf(stderr, "Logger system initialise failure\n");
        return -2;
    }
    log_dbg("Logger system initialise ok\n");
 
#if 0
    if( hal_init() < 0 )
    {
        log_err("Initialise hardware failure\n");
        return -1;
    }
    log_nrml("HAL initialise ok\n");
#endif
    
    install_proc_signal();
 
    if( check_set_program_running(daemon) < 0 ) 
        goto OUT;
 
    mosquitto_lib_init();
 
    if( thread_start(&tid, mqtt_sub_worker, &ctx ) < 0 )
    {
        log_fatal("Start MQTT subsciber worker thread failure\n");
        goto OUT;
    }
    log_nrml("Start MQTT subsciber worker thread ok\n");
 
    if( thread_start(&tid, mqtt_pub_worker, &ctx) < 0 )
    {
        log_fatal("Start MQTT publisher worker thread failure\n");
        goto OUT;
    }
    log_nrml("Start MQTT publisher worker thread ok\n");
 
 
    while( ! g_signal.stop )
    {
        msleep(1000);
        //log_nrml("Main control thread continue running\n");
    }
 
 
OUT:
    mosquitto_lib_cleanup();
    logger_term();
    
    return 0;
} /* ----- End of main() ----- */
 
 
int check_set_program_running(int daemon)
{
    if( check_daemon_running(DAEMON_PIDFILE) ) 
    {
        log_err("Program already running, process exit now");
        return -1;
    }
 
    if( daemon ) 
    {
        if( set_daemon_running(DAEMON_PIDFILE) < 0 )
        {
            log_err("set program running as daemon failure\n");
            return -2;
        }
    }
    else
    {
        if( record_daemon_pid(DAEMON_PIDFILE) < 0 )
        {
            log_err("record program running PID failure\n");
            return -3;
        }
    }
 
    return 0;
}
 
void *mqtt_pub_worker(void *args)
{
    mqtt_ctx_t             *ctx = (mqtt_ctx_t *)args;
    struct mosquitto       *mosq;
    bool                    session = true;
    char                    msg[128];  
    float                   temp = 25.64;
    float                   rh = 65.35;
    int                     rv = 0;
 
    mosq = mosquitto_new(NULL, session, ctx);
    if( !mosq )
    {
        log_err("mosquitto_new failure\n");
        return NULL;
    }
 
    while( !g_signal.stop )
    { 
        if( mosquitto_connect(mosq, ctx->host, ctx->port, ctx->keepalive) )
        {
            log_err("Publisher connect to broker[%s:%d] failure: %s\n", ctx->host, ctx->port, strerror(errno)); 
            msleep(1000);
            continue;
        }
        log_nrml("Publisher connect to broker server[%s:%d] successfully\n", ctx->host, ctx->port); 
 
 
        memset(msg, 0, sizeof(msg));
        snprintf(msg, sizeof(msg), "{ \"temp\":\"%.2f\",  \"R&H\":\"%.2f%%\" }", temp, rh);
 
 
        rv = mosquitto_publish(mosq, NULL, MQTT_SYS_ULINK_TOPIC, strlen(msg)+1, msg, ctx->pubQos, 0);
        if( rv )
        {
            log_err("Publisher publish message failure: %d\n", rv);
        }
        else
        {
            log_nrml("Publisher publish message '%s' ok\n", msg);
        }
 
 
        mosquitto_disconnect(mosq);
        msleep(3000);
    }
 
    mosquitto_destroy(mosq);
    return NULL;
}
 
 
void sub_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
    mqtt_ctx_t             *ctx = (mqtt_ctx_t *)userdata;
 
    if( result )
    {
        log_err("Subscriber connect to broker server failed, rv=%d\n", result);
        return ;
    }
    
    log_nrml("Subscriber connect to broker server[%s:%d] successfully\n", ctx->host, ctx->port); 
    mosquitto_subscribe(mosq, NULL, MQTT_SYS_TOPIC"#", ctx->subQos);
    //mosquitto_subscribe(mosq, NULL, MQTT_SYS_DLINK_TOPIC, 2);
}
 
void sub_disconnect_callback(struct mosquitto *mosq, void *userdata, int result)
{
    mqtt_ctx_t             *ctx = (mqtt_ctx_t *)userdata;
 
    log_warn("Subscriber disconnect to broker server[%s:%d], reason=%d\n", ctx->host, ctx->port, result); 
}
 
 
void sub_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
    if(message->payloadlen)
    {
        log_nrml("Subscriber Recv: %s->%s\n", message->topic, message->payload);
    }
    else 
    {
        log_nrml("%s (null)\n", message->topic);
    }
}
 
 
void *mqtt_sub_worker(void *args)
{
    mqtt_ctx_t             *ctx = (mqtt_ctx_t *)args;
    struct mosquitto       *mosq;
    bool                    session = true;
 
    mosq = mosquitto_new(NULL, session, ctx);
    if( !mosq )
    {
        log_err("mosquitto_new failure\n");
        return NULL;
    }
 
    /* set callback functions */
    mosquitto_connect_callback_set(mosq, sub_connect_callback);
    mosquitto_disconnect_callback_set(mosq, sub_disconnect_callback);
    mosquitto_message_callback_set(mosq, sub_message_callback);
 
 
    while( !g_signal.stop )
    { 
        if( mosquitto_connect(mosq, ctx->host, ctx->port, ctx->keepalive) )
        {
            log_err("Subscriber connect to broker[%s:%d] failure: %s\n", ctx->host, ctx->port, strerror(errno)); 
            msleep(1000);
            continue;
        }
 
        /* -1: use default timeout 1000ms  1: unused */
        mosquitto_loop_forever(mosq, -1, 1);
    }
 
    mosquitto_destroy(mosq);
    return NULL;
}