ibis-example.are
/* desc: This script will listen on the serial (IBIS) interface and parse for defined Fields.
    *  All Data will be saved in custom Config Fields
    *  copyright (c) 2017 netmodule ag, switzerland
    *  Version : 30.03.2022
*/
 
 
DEV = "SERIAL2";
READ_TIMEOUT = 5; /* seconds */
 
LINE_NUMBER_RE = pcre_compile("^l([0-9]{3,3})$", 0);
TAGET_NUMBER_RE = pcre_compile("^z([0-9]{3,3})$", 0);
 
DEBUG=false;
 //true or false
 
template ibis_struct {
    line_number = "";
    taget_nummer = "";
}
 
ibis_data = new ibis_struct();
 
string parse_ibis_telegram(mixed buffer)
{
    telegram = "";
    pos = strchr(buffer, "\r");
    if (!is_void(pos))
    {
        if (strlen(buffer) > pos + 1)
        {
            telegram = substr(buffer, 0, pos);
            /* skip \r and parity bit */
            buffer = substr(buffer, pos + 2);
        }
    }
    return telegram;
}
 
bool parse_telegram(string telegram, mixed ibis) {
    if (DEBUG) nb_syslog("Telegram ausgabe: %s",telegram);
    result = false;
    m = pcre_exec(LINE_NUMBER_RE, telegram, 0);
    if (!is_void(m) && !null(m)) {
        ibis.line_number = m[1];
        if (ibis.line_number != liniennummer) {
        nb_syslog("Neue Liniennummer: %s",ibis.line_number);
        nb_config_set(sprintf("custom.var0=%s",ibis.line_number));
        liniennummer=ibis.line_number;
        }
	    if (DEBUG) printf("Neue Liniennummer: %s\n",ibis.line_number);
        result = true;
    }
 
 
 
    m = pcre_exec(TAGET_NUMBER_RE, telegram, 0);
    if (!is_void(m) && !null(m)) {
        ibis.taget_nummer = m[1];
        if (ibis.taget_nummer != endhalte) {
        nb_syslog("Neue Endhaltestelle: %s",ibis.taget_nummer);
        nb_config_set(sprintf("custom.var1=%s",ibis.taget_nummer));
        endhalte=ibis.taget_nummer;
        }
        if (DEBUG) printf("Neue Endhaltestelle: %s\n",ibis.taget_nummer);
        result = true;
    }
 
    return result;
 
}
 
/* check serial port config */
st = nb_config_get("serial.1.status");
if (st != "2")
{
    nb_syslog("Serial port is not enabled for us");
    exit(1);
}
 
/* set attributes */
ret = nb_serial_setattr(DEV, 1200, 7, 2, 2, 0);
 
if (ret != 0)
{
    printf("Could not set serial attributes: %i \n",ret);
    exit(1);
}
 
/* open serial port */
fd = nb_serial_open(DEV);
if (fd < 0)
{
    printf("Unable to open %s\n", DEV);
    exit(1);
}
 
buffer="";
liniennummer="0000";
endhalte="unbekannt";
while (true) {
    // printf("line number: %s\n", ibis_data.line_number);
    rc = select(fd, READ_TIMEOUT);
    if (rc == -1) {
        printf("ERROR: select failed\n");
        close(fd);
        exit(1);
    } else {
        if (DEBUG) nb_syslog("line:-%s-",msg);
        /* received something */
        data = read(fd, 1024);
        buffer=strcat(buffer,data);
 
        telegram = parse_ibis_telegram(&buffer);
        if (telegram != "") {
            parse_telegram(telegram, &ibis_data);
        }
    }
}
 
close(fd);