guowenxue
2022-04-08 8ea65d42abecc9d668fed3db16069e956c09156e
mqttd/main.c
@@ -13,45 +13,561 @@
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <libgen.h>
#include <string.h>
#include <mosquitto.h>
#include "logger.h"
#include "cJSON.h"
#include "proc.h"
#include "hal.h"
/********************************************************************************
 *  Description:
 *   Input Args:
 *  Output Args:
 * Return Value:
 ********************************************************************************/
#include "conf.h"
#define PROG_VERSION               "v1.0.0"
#define DAEMON_PIDFILE             "/tmp/.mqtt.pid"
#define FLAG_DETECTD        (1<<0)
#define FLAG_RELAYON        (1<<1)
int g_breakin_flag = 0;  /* relay already turn on and wait to off  */
int check_set_program_running(int daemon);
void *mqtt_sub_worker(void *args);
void *mqtt_pub_worker(void *args);
static void program_usage(char *progname)
{
    printf("Usage: %s [OPTION]...\n", progname);
    printf(" %s is LingYun studio MQTT daemon program running on RaspberryPi\n", progname);
    printf("\nMandatory arguments to long options are mandatory for short options too:\n");
    printf(" -d[debug   ]  Running in debug mode\n");
    printf(" -c[conf    ]  Specify configure file\n");
    printf(" -h[help    ]  Display this help information\n");
    printf(" -v[version ]  Display the program version\n");
    printf("\n%s version %s\n", progname, PROG_VERSION);
    return;
}
void turn_light_off(int signum)
{
    if( g_breakin_flag&FLAG_RELAYON )
    {
        log_nrml("fill-in light timeout and turn light off now\n");
        turn_relay(OFF);
    }
    g_breakin_flag = 0;
}
int main (int argc, char **argv)
{
    float              temp;
    float              rh;
    int                daemon = 1;
    pthread_t          tid;
    mqtt_ctx_t         ctx;
    char               *conf_file=NULL;
    int                debug = 0;
    int                opt;
    char              *progname=NULL;
    double             lux = 0.0;
    //if( logger_init("mqttd.log", LOG_LEVEL_DEBUG, 1024) < 0 )
    if( logger_init(DBG_LOG_FILE, LOG_LEVEL_DEBUG, 1024) < 0 )
    struct option long_options[] = {
        {"conf", required_argument, NULL, 'c'},
        {"debug", no_argument, NULL, 'd'},
        {"version", no_argument, NULL, 'v'},
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };
    progname = (char *)basename(argv[0]);
    /* Parser the command line parameters */
    while ((opt = getopt_long(argc, argv, "c:dvh", long_options, NULL)) != -1)
    {
        fprintf(stderr, "Logger system initialise failure\n");
        return -1;
        switch (opt)
        {
            case 'c': /* Set configure file */
                conf_file = optarg;
                break;
            case 'd': /* Set debug running */
                daemon = 0;
                debug = 1;
                break;
            case 'v':  /* Get software version */
                printf("%s version %s\n", progname, PROG_VERSION);
                return 0;
            case 'h':  /* Get help information */
                program_usage(progname);
                return 0;
            default:
                break;
        }
    }
    if( !conf_file )
        debug = 1;
    log_dbg("Logger system initialise ok\n");
    if( mqttd_parser_conf(conf_file, &ctx, debug)<0 )
    {
        fprintf(stderr, "Parser mqtted configure file failure\n");
        return -2;
    }
#if 0
    if( hal_init() < 0 )
    if( hal_init(&ctx.hwconf) < 0 )
    {
        log_err("Initialise hardware failure\n");
        return -1;
        return -3;
    }
#endif
    log_nrml("HAL initialise ok\n");
    else
    {
        log_nrml("HAL initialise ok\n");
    }
    install_proc_signal();
    if( ctx.hwconf.fillin_light )
    {
        log_nrml("Install inbreak detected fill-in light off signal\n");
        signal(SIGALRM, turn_light_off);
    }
    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);
        if( ctx.hwconf.infrared_pin && !g_breakin_flag )
        {
            //log_nrml("infrared dected human incoming\n");
            if( infrared_detect(1000) )
            {
                log_nrml("Someone incoming detected by infrared\n");
                g_breakin_flag |= FLAG_DETECTD;
                /* setup alarm to turn relay off or clear the flag */
                alarm(ctx.hwconf.light_intval);
                if( ctx.hwconf.inbreak_beep )
                {
                    turn_beep(ctx.hwconf.beep_times);
                }
                if( ctx.hwconf.fillin_light==FILLIN_LIGHT_ON && !g_breakin_flag )
                {
                    log_nrml("Force fill-in light on and will be off in [%d] seconds\n", ctx.hwconf.light_intval);
                    turn_relay(ON);
                    g_breakin_flag |= FLAG_RELAYON;
                }
                else if( ctx.hwconf.fillin_light==FILLIN_LIGHT_AUTO && ctx.hwconf.lux )
                {
                    lux = tsl2561_get_lux();
                    log_nrml("TSL2516 detect illumination intensity %.3flux and threshold %.3flux\n",
                            lux, ctx.hwconf.lux_threshold);
                    /* only lux<0.01 will turn on light */
                    if( lux-0.001 > ctx.hwconf.lux_threshold)
                    {
                        log_nrml("Illumination intensity enuf, no need fill-in light\n");
                    }
                    else
                    {
                        log_nrml("Auto fill-in light on and will be off in [%d] seconds\n", ctx.hwconf.light_intval);
                        turn_relay(ON);
                        g_breakin_flag |= FLAG_RELAYON;
                    }
                }
            }
        }
        //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 pub_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
    mqtt_ctx_t             *ctx = (mqtt_ctx_t *)userdata;
    int                     rv = 0;
    char                    msg[128];
    float                   temp = 0.0; /* temperature */
    float                   rh = 0.0;   /* relative humidity */
    int                     retain = 0;
    if( result )
    {
        log_err("Publisher connect to broker server[%s:%d] failed, rv=%d\n", ctx->host, ctx->port, result);
        return ;
    }
    log_nrml("Publisher connect to broker server[%s:%d] successfully\n", ctx->host, ctx->port);
    if( ctx->hwconf.ds18b20 )
    {
        memset(msg, 0, sizeof(msg));
        if( ds18b20_get_temperature(&temp) < 0 )
            snprintf(msg, sizeof(msg), "{ \"id\":%s, \"temp\":\"error\" }", ctx->id);
        else
            snprintf(msg, sizeof(msg), "{ \"id\":%s, \"temp\":\"%.2f\" }", ctx->id, temp);
        rv = mosquitto_publish(mosq, NULL, ctx->pubTopic, strlen(msg), msg, ctx->pubQos, retain);
        if( rv )
        {
            log_err("Publisher broadcast message '%s' failure: %d\n", msg, rv);
        }
        else
        {
            log_nrml("Publisher broadcast message '%s' ok\n", msg);
        }
    }
    if( ctx->hwconf.sht2x )
    {
        memset(msg, 0, sizeof(msg));
        if( sht2x_get_temp_humidity(&temp, &rh) < 0 )
            snprintf(msg, sizeof(msg), "{ \"id\":%s, \"temp\":\"error\", \"RH\":\"error\" }", ctx->id);
        else
            snprintf(msg, sizeof(msg), "{ \"id\":%s, \"temp\":\"%.2f\", \"RH\":\"%.2f\" }", ctx->id, temp, rh);
        rv = mosquitto_publish(mosq, NULL, ctx->pubTopic, strlen(msg), msg, ctx->pubQos, retain);
        if( rv )
        {
            log_err("Publisher broadcast message '%s' failure: %d\n", msg, rv);
        }
        else
        {
            log_nrml("Publisher broadcast message '%s' ok\n", msg);
        }
    }
    log_nrml("Publisher broadcast over and disconnect broker now\n", ctx->host, ctx->port);
    mosquitto_disconnect(mosq);
    return ;
}
void *mqtt_pub_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 connnect to broker username and password  */
    if( strlen(ctx->uid)> 0  && strlen(ctx->pwd)> 0 )
        mosquitto_username_pw_set(mosq, ctx->uid, ctx->pwd);
    /* set callback functions */
    mosquitto_connect_callback_set(mosq, pub_connect_callback);
    while( !g_signal.stop )
    {
        /* connect to MQTT broker  */
        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;
        }
        /* -1: use default timeout 1000ms  1: unused */
        mosquitto_loop_forever(mosq, -1, 1);
        /* Publisher broadcast sensors data message interval time, unit seconds */
        sleep( ctx->interval );
    }
    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, ctx->subTopic, ctx->subQos);
}
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);
}
static inline void mqtt_turn_led(int which, char *cmd)
{
    if( strcasestr(cmd, "on") )
        turn_led(which, ON);
    else if( strcasestr(cmd, "off") )
        turn_led(which, OFF);
}
void proc_json_items(cJSON *root, mqtt_ctx_t *ctx)
{
    int                    i;
    char                  *value;
    cJSON                 *item;
    cJSON                 *array;
    hwconf_t              *hwconf = &ctx->hwconf;
    if( !root )
    {
        log_err("Invalid input arguments $root\n");
        return ;
    }
    for( i=0; i<cJSON_GetArraySize(root); i++ )
    {
        item = cJSON_GetArrayItem(root, i);
        if( !item )
            break;
        /* if item is cJSON_Object, then recursive call proc_json */
        if( cJSON_Object == item->type )
        {
            proc_json_items(item, ctx);
        }
        else if( cJSON_Array == item->type )
        {
            /* RGB colors led control  */
            if( hwconf->leds && !strcasecmp(item->string, "led") )
            {
                array = cJSON_GetArrayItem(item, 0);
                if( NULL != array )
                {
                    cJSON        *led_item;
                    if( NULL != (led_item=cJSON_GetObjectItem(array , "red")) )
                    {
                        log_nrml("turn red led '%s'\n", led_item->valuestring);
                        mqtt_turn_led(LED_R, led_item->valuestring);
                    }
                    if( NULL != (led_item=cJSON_GetObjectItem(array , "green")) )
                    {
                        log_nrml("turn green led '%s'\n", led_item->valuestring);
                        mqtt_turn_led(LED_G, led_item->valuestring);
                    }
                    if( NULL != (led_item=cJSON_GetObjectItem(array , "blue")) )
                    {
                        log_nrml("turn blue led '%s'\n", led_item->valuestring);
                        mqtt_turn_led(LED_B, led_item->valuestring);
                    }
                }
            }
        }
        else
        {
            value = cJSON_Print(item);
            /* light controled by relay */
            if( hwconf->relay_pin && !strcasecmp(item->string, "light") )
            {
                if( strcasestr(value, "on") )
                {
                    log_nrml("Turn light on\n");
                    turn_relay(ON);
                }
                else if( strcasestr(value, "off") )
                {
                    log_nrml("Turn light off\n");
                    turn_relay(OFF);
                }
            }
            /* buzzer */
            if( hwconf->beep_pin && !strcasecmp(item->string, "buzzer") )
            {
                if( strcasestr(value, "on") )
                {
          turn_passive_beep(ON, BEEP_FREQ);
                }
      else if( strcasestr(value, "off") )
                {
          turn_passive_beep(OFF, BEEP_FREQ);
                }
      else if( strcasestr(value, "music") )
                {
          play_little_star();
                }
            }
            free(value); /* must free it, or it will result memory leak */
        }
    }
}
void sub_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
    mqtt_ctx_t             *ctx = (mqtt_ctx_t *)userdata;
    cJSON                  *root = NULL;
    cJSON                  *item;
    char                   *value;
    if ( !message->payloadlen )
    {
        log_err("%s (null)\n", message->topic);
        return ;
    }
    log_dbg("Subscriber receive message: '%s'\n", message->payload);
    root = cJSON_Parse(message->payload);
    if( !root )
    {
        log_err("cJSON_Parse parser failure: %s\n", cJSON_GetErrorPtr());
        return ;
    }
    item = cJSON_GetObjectItem(root, "id");
    if( !item )
    {
        log_err("cJSON_Parse get ID failure: %s\n", cJSON_GetErrorPtr());
        goto OUT;
    }
    value = cJSON_PrintUnformatted(item);
    if( strcasecmp(value, ctx->id) )
    {
        free(value);
        goto OUT;
    }
    free(value);
    log_nrml("Subscriber receive message: '%s'\n", message->payload);
    proc_json_items(root, ctx);
OUT:
    cJSON_Delete(root); /* must delete it, or it will result memory leak */
    return ;
}
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 connnect to broker username and password  */
    if( strlen(ctx->uid)> 0  && strlen(ctx->pwd)> 0 )
        mosquitto_username_pw_set(mosq, ctx->uid, ctx->pwd);
    /* 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 )
    {
        /* connect to MQTT broker  */
        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;
}