| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908 |
- /*
- * Copyright (c) 2019 Clementine Computing LLC.
- *
- * This file is part of PopuFare.
- *
- * PopuFare is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * PopuFare is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with PopuFare. If not, see <https://www.gnu.org/licenses/>.
- *
- */
- #include <sys/time.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <poll.h>
- #include <unistd.h>
- #include <errno.h>
- #include <string.h>
- #include <signal.h>
- #include <time.h>
- #include <openssl/md5.h>
- #include <ctype.h>
- #include <string.h>
- #include <sys/types.h>
- #include <ifaddrs.h>
- #include <arpa/inet.h>
- #include <sys/socket.h>
- #include <netdb.h>
- #include <ifaddrs.h>
- #include <linux/if_link.h>
- #include "../common/common_defs.h"
- #include "../commhub/commhub.h"
- #include "../commhub/client_utils.h"
- #include "driver.h"
- #include "touchscreen.h"
- #include "mongoose.h"
- #define _SLEN LINE_BUFFER_SIZE
- #define DIU_MINDER_VERSION "2.1.13"
- static const char *s_http_port = "60535";
- static struct mg_serve_http_opts s_http_server_opts;
- struct mg_mgr g_mgr;
- int diu_fd = -1;
- int hub_fd = -1;
- time_t last_hub_try = 0;
- time_t last_diu_clock = 0;
- gps_status my_gps_stat={0};
- time_t mkgmtime(struct tm *tm);
- int token_diag_serial = 0;
- char token_diag_string[LINE_BUFFER_SIZE] = {0};
- // return total bytes in dst
- //
- static size_t _strnncat(char *dst, char *src, size_t n) {
- size_t dst_n, src_n, N, i;
- dst_n = strlen(dst);
- src_n = strlen(src);
- N = n-1;
- if (dst_n < N) { N -= dst_n; }
- for (i=0; (i<N) && (i<src_n); i++) {
- dst[dst_n + i] = src[i];
- }
- dst[dst_n+i] = '\0';
- return dst_n + i;
- }
- time_t paddle_req_timeout = 0;
- set_paddle_req paddle_req = {0};
- driver_status my_driver_status={0};
- int update_driver_status = 0;
- state_info_t my_state_info = {0};
- int md5_of_file(char *filename, void *result) {
- FILE *f = NULL;
- char chunk[LINE_BUFFER_SIZE]={0};
- int retval = 0;
- MD5_CTX ctx;
- if (!result) { return -1; }
- if (!filename) { return -1; }
- if (!MD5_Init(&ctx)) {
- return -1;
- }
- f = fopen(filename, "rb");
- if (!f) {
- return -1;
- }
- while(1) {
- retval = fread(chunk, 1, LINE_BUFFER_SIZE, f);
- if (retval <= 0) {
- break;
- }
- else {
- MD5_Update(&ctx, chunk, retval);
- }
- }
- fclose(f);
- MD5_Final((unsigned char *)result, &ctx);
- return 0;
- }
- //--------------------
- static int is_websocket(const struct mg_connection *nc) {
- return nc->flags & MG_F_IS_WEBSOCKET;
- }
- void ws_send(struct mg_mgr *mgr, char *msg) {
- struct mg_connection *conn;
- for (conn = mg_next(mgr, NULL); conn; conn = mg_next(mgr, conn)) {
- if (!is_websocket(conn)) { continue; }
- mg_send_websocket_frame(conn, WEBSOCKET_OP_TEXT, msg, strlen(msg));
- }
- }
- //--------------------
- void beep(int fd, int hz, int milis) {
- char buffer[64];
- int n;
- n = sprintf(buffer, "/B:%X,%X\r", hz, milis);
- write(fd,buffer,n);
- }
- void set_backlight(int fd, int on) {
- char buffer[64];
- int n;
- n = sprintf(buffer, "/D:%c\r", on?'0':'1');
- write(fd,buffer,n);
- }
- void set_diu_clock(int fd, time_t tt) {
- struct tm t;
- char buffer[16];
- int n;
- localtime_r(&tt, &t);
- n = sprintf(buffer, "/C:%02d%02d\r", t.tm_hour, t.tm_min);
- write(fd, buffer, n);
- }
- //--------------------
- void clear_diu_messages() {
- }
- //--------------------
- // This function takes a GPS timestamp (in gross GPS float format + gross integer date) and
- //makes it into a sane UTC timestamp. If we are more than MAX_GPS_CLOCK_DRIFT seconds off
- //from GPS time, it sets the system clock to GPS time.
- //
- int handle_gps_time(float gtime, int date) {
- int day,month,year;
- int hour,min,sec,frac;
- int n = 0;
- time_t utc,now;
- char buffer[32] = {0};
- struct message_record outgoing_msg;
- now = time(NULL);
- day = month = year = 0;
- hour = min = sec = frac = 0;
- // Just to be *ahem* clear, as per NMEA standard the date is encoded DDMMYY, and the time of day
- // is encoded HHMMSS[.frac] where there is an optional fractional second field denoted by a decimal point.
- // we must be able to decode the fractional seconds field but we discard the information since it is not
- // reliable enough to be worth the bother.
- // Whoever thought that NMEA GPS should encode the time in this format ought to be shot...
- // Start out with zero parsed fields
- //
- n = 0;
- // Construct and then re-parse the time from its icky format to discrete values (this should result
- // in at least three (possibly four) fields.
- //
- sprintf(buffer,"%010.3f", gtime);
- n += sscanf(buffer,"%02d%02d%02d.%d", &hour, &min, &sec, &frac);
- // Construct and then re-parse the date from its icky format to discrete values. This should result in three fields.
- //
- sprintf(buffer,"%06d", date);
- n += sscanf(buffer,"%02d%02d%02d", &day, &month, &year);
- // If we scanned at all required fields
- //
- if (n >= 6) {
- struct tm gpstm = {0};
- // GPS date only uses two digits for year, so we must assume the century
- //
- year += GPS_DATE_CENTURY;
- // tm.tm_year is based on the year 1900
- //
- gpstm.tm_year = year - 1900;
- // January = month 0 in struct tm.tm_mon whereas January = month 1 in an NMEA GPS date.
- //
- gpstm.tm_mon = month - 1;
- gpstm.tm_mday = day;
- gpstm.tm_hour = hour;
- gpstm.tm_min = min;
- gpstm.tm_sec = sec;
- // Go and turn the struct tm we've just populated into an utc time stamp (seconds since epoch)
- //
- utc = mkgmtime(&gpstm);
- // Most importantly... Remember what the self-reported GPS time stamp is.
- //
- my_gps_stat.gpstime = utc;
- //printf("%02d-%02d-%04d %02d:%02d:%02d\n",day,month,year,hour,min,sec);
- //printf("CALCULATED: %d\nSYSTEM : %d\n\n",(int)utc,(int)time(NULL));
- // if we have more than MAX_GPS_CLOCK_DRIFT seconds of clock drift
- //
- if (abs(utc - now) > MAX_GPS_CLOCK_DRIFT) {
- struct timeval ts = {0};
- // Set the timeval struct to the calculated utc timestamp from the GPS unit.
- //
- ts.tv_sec = utc;
- ts.tv_usec = 0;
- // Set the system clock from GPS time using said timeval struct.
- //
- settimeofday(&ts, NULL);
- // If we have a valid connection to the IPC hub
- //
- if ( hub_fd >= 0) {
- // Stick a message into the diagnostic log to record the fact that we've set the system clock from GPS
- //
- format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "Set syatem clock from previous value (%d) to GPS time (%d).", (int)now, (int)utc );
- send_message(hub_fd, &outgoing_msg);
- }
- }
- }
- return 0;
- }
- #ifdef CLEAR_GPS_ON_STALE
- static inline void clear_stale_gps_data()
- {
- my_gps_stat.lat = my_gps_stat.lon = my_gps_stat.heading = my_gps_stat.velocity = 0;
- my_gps_stat.num_sats = 0;
- }
- #else
- static inline void clear_stale_gps_data()
- {
- }
- #endif
- static int handle_stale_gps_condition() {
- // This return code will be > 0 if this function generates a status change that
- // will then need to be communicated to other modules in the system via a message to
- // MAILBOX_GPS_STATUS.
- //
- int return_code = 0;
- // This will hold the gps_good flag as it stood at the beginning of this subroutine
- // previous to any adjustments we make.
- //
- int previous_good_flag = my_gps_stat.gps_good;
- int stale_time = 0;
- time_t now = time(NULL);
- stale_time = (now - my_gps_stat.stamp);
- // If we have entered this function with the impression that we have a valid GPS fix...
- //
- if (previous_good_flag > 0) {
- // If it has been at least GPS_STALE_THRESHOLD seconds since the last fix
- //
- if ( stale_time >= GPS_STALE_THRESHOLD ) {
- clear_stale_gps_data();
- my_gps_stat.gps_good = 0;
- return_code |= 1;
- }
- }
- // If we have determined that we need to declare the GPS data stale and invalid and
- // we have a valid connection to the IPC hub we should use that IPC hub connection to
- // add a note to the diagnostic log indicating that we've declared the GPS data stale.
- //
- if ( return_code && (hub_fd >= 0) ) {
- struct message_record outgoing_msg;
- format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix has been stale for %d seconds, setting GPS = NO.", stale_time);
- send_message(hub_fd, &outgoing_msg);
- }
- return return_code;
- }
- int update_gps(char *in) {
- // This will hold the number of matched variables populated by sscanf().
- //
- int num = 0;
- // This will allow us to know if we have made a transition from an invalid
- // GPS fix to a valid one so that we can log this information.
- //
- int previous_good_flag = my_gps_stat.gps_good;
- // This return code will be > 0 if this function generates a status change that
- // will then need to be communicated to other modules in the system via a message to
- // MAILBOX_GPS_STATUS.
- //
- int return_code = 0;
- if (!strncmp(in,"$GPRMC",6)) {
- float f1=0;
- char f2=0;
- float f3=0;
- char f4=0;
- float f5=0;
- char f6=0;
- float f7=0;
- float f8=0;
- int f9=0;
- float f10=0;
- char f11=0;
- num = sscanf(in,"$GPRMC,%f,%c,%f,%c,%f,%c,%f,%f,%d,%f,%c",&f1,&f2,&f3,&f4,&f5,&f6,&f7,&f8,&f9,&f10,&f11);
- // If we have a full GPRMC sentence we can consider setting the time
- //
- if (num == 11) {
- // Require at least MIN_SATS_FOR_TIME satellites to accept a new system clock value from the GPS unit.
- // This is to keep a crummy GPS fix from generating a bogus or unstable system time.
- //
- if (my_gps_stat.num_sats >= MIN_SATS_FOR_TIME) {
- // Pass the time field (f1) and the date field (f9) in to the routine that sets the system clock if needed.
- // (this routine also stores the utc timestamp derived from the GPS date and time fields so it can be passed to
- // other modules that may have a need for this information).
- //handle_gps_time(f1,f9);
- }
- }
- if (num > 0) {
- // update snapshot with latitude
- //
- my_gps_stat.lat = f3 * ((f4 == 'N')?(1):(-1));
- // longitude
- //
- my_gps_stat.lon = f5 * ((f6 == 'E')?(1):(-1));
- // meters per second (converted from knots)
- //
- my_gps_stat.velocity = f7 / 1.94384449f;
- // course
- //
- my_gps_stat.heading = f8;
- // update snapshot's staledate
- //
- my_gps_stat.stamp = time(NULL);
- return_code |= 1;
- }
- }
- else if (!strncmp(in,"$GPGGA",6)) {
- int f1=0;
- float f2=0;
- char f3=0;
- float f4=0;
- char f5=0;
- int f6=0;
- int f7=0;
- float f8=0;
- float f9=0;
- char f10=0;
- float f11=0;
- char f12=0;
- num=sscanf(in,"$GPGGA,%d,%f,%c,%f,%c,%d,%d,%f,%f,%c,%f,%c",&f1,&f2,&f3,&f4,&f5,&f6,&f7,&f8,&f9,&f10,&f11,&f12);
- if (num == 12) {
- // require 3 satellites minimum
- //
- if ( f7 >= 3 ) {
- // store GPS valid flag in snapshot
- //
- my_gps_stat.gps_good = f6;
- // store number of satellites in view in snapshot
- //
- my_gps_stat.num_sats = f7;
- // Do NOT store the timestamp since we only want to remember timestamps of position
- // fixes and the GPGGA message is all metadata (number of satellites, fix quality, etc...).
- // It is worth noting that GPGGA does report altitude, but that is not a piece of information
- // we track because the road is where the road is, and if a bus becomes airborn we have much
- // bigger problems than figuring out how far off the ground it is...
- //
- return_code |= 1;
- }
- }
- }
- return_code |= handle_stale_gps_condition();
- // If we have a connection to the IPC hub and we had previously not had a valid
- // GPS fix but we now do, make a note of it in the diagnostic log.
- //
- if ( (previous_good_flag == 0) && (my_gps_stat.gps_good != 0) && (hub_fd >= 0) ) {
- struct message_record outgoing_msg;
- format_log_message(&outgoing_msg, LOGLEVEL_DEBUG, "GPS fix is now valid with %d satellites. Setting GPS = YES.", my_gps_stat.num_sats);
- send_message(hub_fd, &outgoing_msg);
- }
- return return_code;
- }
- void maintain_ipc_hub_connect(char *progname) {
- struct message_record outgoing_msg;
- // if we have no connection to the IPC hub
- //
- if (hub_fd < 0) {
- // if we haven't tried the hub in a few seconds
- //
- if ( (time(NULL) - last_hub_try) > HUB_RETRY_TIME ) {
- // retry it
- //
- last_hub_try = time(NULL);
- // try and get one
- //
- hub_fd = connect_to_message_server(progname);
- if (hub_fd >= 0) {
- // Subscribe to the default status messages
- //
- subscribe_to_default_messages(hub_fd);
- // Subscribe to our specific message
- //
- prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_DRIVER_NOTIFY, strlen(MAILBOX_DRIVER_NOTIFY));
- send_message(hub_fd,&outgoing_msg);
- prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_PADDLE_ACK, strlen(MAILBOX_PADDLE_ACK));
- send_message(hub_fd,&outgoing_msg);
- prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_VAULT_DROP, strlen(MAILBOX_VAULT_DROP));
- send_message(hub_fd,&outgoing_msg);
- prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_TOKEN_MAG, strlen(MAILBOX_TOKEN_MAG));
- send_message(hub_fd,&outgoing_msg);
- prepare_message(&outgoing_msg, MAILBOX_SUBSCRIBE, MAILBOX_TOKEN_RFID, strlen(MAILBOX_TOKEN_RFID));
- send_message(hub_fd,&outgoing_msg);
- // Ask for a status update
- //
- prepare_message(&outgoing_msg, MAILBOX_STATUS_REQUEST, "", 0);
- send_message(hub_fd,&outgoing_msg);
- }
- else {
- fprintf(stderr, "Cannot connect to IPC hub!\n");
- }
- }
- }
- }
- message_callback_return handle_status_request(struct message_record *msg, void *param) {
- struct message_record outgoing_msg;
- if (hub_fd >= 0) {
- prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
- send_message(hub_fd, &outgoing_msg);
- prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
- send_message(hub_fd, &outgoing_msg);
- }
- return MESSAGE_HANDLED_CONT;
- }
- message_callback_return handle_vault_drop(struct message_record *msg, void *param) {
- if (diu_fd >= 0) {
- write(diu_fd, "/V:\r", 4);
- }
- return MESSAGE_HANDLED_CONT;
- }
- char dup_notify_str[MAX_PAYLOAD_LENGTH] = {0};
- int dup_notify_count = 0;
- long long dup_notify_usec = 0;
- message_callback_return handle_driver_notify(struct message_record *msg, void *param) {
- int is_dup;
- char _text[MAX_PAYLOAD_LENGTH] = {0};
- long long dup_usec_delta = 0;
- if (strncmp((const char *)(msg->payload), dup_notify_str, MAX_PAYLOAD_LENGTH)) {
- dup_notify_count = 1;
- strncpy(dup_notify_str, (const char *)(msg->payload), MAX_PAYLOAD_LENGTH - 1);
- dup_notify_str[MAX_PAYLOAD_LENGTH - 1] = '\0';
- is_dup = 0;
- dup_notify_usec = 0;
- }
- else {
- dup_notify_count++;
- is_dup = 1;
- dup_usec_delta = get_usec_time() - dup_notify_usec;
- dup_notify_usec = get_usec_time();
- }
- switch(msg->payload[0]) {
- case LOGLEVEL_EVENT:
- if (!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD)) {
- DIU_ACK_BEEP(diu_fd);
- }
- break;
- case LOGLEVEL_REJECT:
- if (!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD)) {
- DIU_ERROR_BEEP(diu_fd);
- }
- break;
- case LOGLEVEL_ACCEPT:
- if (!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD)) {
- DIU_ACK_BEEP(diu_fd);
- }
- break;
- case LOGLEVEL_ERROR:
- if (!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD)) {
- DIU_CRITICAL_BEEP(diu_fd);
- }
- break;
- default: break;
- }
- if (is_dup) {
- snprintf(_text, MAX_PAYLOAD_LENGTH, "driver_notify replace %s %s %d x %s", "white", "black", dup_notify_count, &msg->payload[1]);
- ws_send(&g_mgr, _text);
- }
- else {
- snprintf(_text, MAX_PAYLOAD_LENGTH, "driver_notify ok %s %s %d x %s", "white", "black", dup_notify_count, &msg->payload[1]);
- ws_send(&g_mgr, _text);
- }
- return MESSAGE_HANDLED_CONT;
- }
- message_callback_return handle_paddle_ack(struct message_record *msg, void *param) {
- set_paddle_req *pr = (set_paddle_req *)msg->payload;
- paddle_req.result = pr->result;
- return MESSAGE_HANDLED_CONT;
- }
- message_callback_return handle_token_diag(struct message_record *msg, void *param) {
- strncpy(token_diag_string, (const char *)(msg->payload), sizeof(token_diag_string));
- token_diag_string[sizeof(token_diag_string) - 1] = '\0';
- token_diag_serial++;
- return MESSAGE_HANDLED_CONT;
- }
- //----------------------------------
- time_t diu_error_burst = 0;
- int diu_error_counter = 0;
- static inline int can_report_diu_error() {
- time_t now = time(NULL);
- // If our last potential burst lockout has expired...
- //
- if ( (now - diu_error_burst) >= DIU_ERROR_RATE_LIMIT) {
- // reset our burst counter
- //
- diu_error_counter = 0;
- // and start the "potential burst" time at this message
- //
- diu_error_burst = now;
- }
- // if we haven't hit our burst limit...
- //
- if (diu_error_counter < DIU_ERROR_BURST_LIMIT) {
- // count this message against our burst limit
- //
- diu_error_counter++;
- // and allow it to pass
- //
- return 1;
- }
- // if we have hit our limit
- //
- else {
- // ignore this message
- //
- return 0;
- }
- }
- //----------------------------------
- //-------- web server functions ----
- /*
- static void send_ws_heartbeat(struct mg_connection *nc) {
- int n;
- char buf[_SLEN];
- struct mg_connection *c;
- for (c=mg_next(nc->mgr, NULL); c ; c = mg_next(nc->mgr, c)) {
- if (c==nc) { continue; }
- if (!is_websocket(c)) { continue; }
- printf("...\n");
- snprintf(buf, _SLEN, "hello");
- n = strlen(buf);
- mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, buf, n);
- }
- }
- */
- static void process_ws_message(struct websocket_message *ws_msg) {
- int i;
- char *data;
- data = (char *)(ws_msg->data);
- printf("#ws, got(%i)\n:", (int)(ws_msg->size));
- for (i=0; i<ws_msg->size; i++) {
- printf("%c", data[i]);
- }
- printf("\n");
- }
- #define MAX_PKGS (16)
- //
- // ui wants status information
- //
- static void ui_handle_status_input(struct mg_connection *nc, struct http_message *hm) {
- int i, npkgs, npkgnet=0, ncfgline=0;
- char buf[4*_SLEN] = {0},
- pkgnetline[_SLEN] = {0},
- cfgline[_SLEN] = {0},
- _str[_SLEN] = {0};
- char date_str[32] = {0};
- time_t t;
- struct tm tm, pkgtime;
- FILE *fp;
- package_signature pkgs[MAX_PKGS];
- buf[0] = '\0';
- cfgline[0] = '\0';
- pkgnetline[0] = '\0';
- _str[0] = '\0';
- t = time(NULL);
- localtime_r(&t, &tm);
- strftime(date_str, 32, "%Y-%m-%d", &tm);
- pkgnetline[0] = '\0';
- npkgs = find_packages(pkgs,MAX_PKGS);
- for (i=0; i<npkgs; i++) {
- localtime_r(&pkgs[i].installed, &pkgtime);
- snprintf(_str, _SLEN, "pkg%i=%s %s %02d/%02d/%02d %02d:%02d:%02d",
- i,
- pkgs[i].pkgname, pkgs[i].pkgver,
- pkgtime.tm_mon + 1, pkgtime.tm_mday, pkgtime.tm_year + 1900,
- pkgtime.tm_hour, pkgtime.tm_min, pkgtime.tm_sec);
- _strnncat(pkgnetline, "|", _SLEN);
- _strnncat(pkgnetline, _str, _SLEN);
- npkgnet++;
- }
- fp = fopen("/tmp/net_ids", "rb");
- if (fp) {
- while (fgets(_str, _SLEN, fp)) {
- strip_crlf(_str);
- _strnncat(pkgnetline, "|", _SLEN);
- _strnncat(pkgnetline, _str, _SLEN);
- npkgnet++;
- }
- fclose(fp);
- }
- fp = fopen(CONFIG_FILE_PATH "/popufare.config", "rb");
- if (fp) {
- while (fgets(_str, _SLEN, fp)) {
- strip_crlf(_str);
- _strnncat(cfgline, "|", _SLEN);
- _strnncat(cfgline, _str, _SLEN);
- ncfgline++;
- }
- fclose(fp);
- }
- snprintf(buf, 4*_SLEN, "ok msg=status\n"
- "equipno=%d|"
- "route=%d|"
- "trip=%d|"
- "stop=%d|"
- "gps=%i|"
- "gpslat=%f|"
- "gpslon=%f|"
- "gpsv=%f|"
- "gpsheading=%f|"
- "tunnel=%i|"
- "gprs=%i|"
- "date=%s|"
- "nmsg=%d|"
- "last_token=%d|"
- "%s"
- "%s",
- get_equip_num(),
- stop_stat.route,
- stop_stat.trip,
- stop_stat.stop,
- gps_stat.gps_good,
- gps_stat.lat,
- gps_stat.lon,
- gps_stat.velocity,
- gps_stat.heading,
- tunnel_is_up(),
- gprs_is_up(),
- date_str,
- bill_stat.unsynced_messages,
- token_diag_serial % 100,
- cfgline,
- pkgnetline);
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(buf), buf);
- }
- // driver logout
- //
- static void ui_handle_logout_input(struct mg_connection *nc, struct http_message *hm) {
- char msg[][_SLEN] = {
- "fail error",
- "ok .",
- };
- driver_logout();
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg[1]), msg[1]);
- }
- // (manual) next stop pressed
- //
- static void ui_handle_nextstop_input(struct mg_connection *nc, struct http_message *hm) {
- char msg[][_SLEN] = {
- "fail error",
- "ok .",
- };
- action_nextstop();
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg[1]), msg[1]);
- }
- // (manual) previous stop pressed
- //
- static void ui_handle_prevstop_input(struct mg_connection *nc, struct http_message *hm) {
- char msg[][_SLEN] = {
- "fail error",
- "ok .",
- };
- action_prevstop();
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg[1]), msg[1]);
- }
- // generic fare input
- //
- static void ui_handle_fare_input(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char s_rule[_SLEN], s_param[_SLEN];
- char msg_ok[] = "ok .";
- driver_rulecall dr = {{0}};
- struct message_record outgoing;
- ret = mg_get_http_var(&(hm->body), "rule", s_rule, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- ret = mg_get_http_var(&(hm->body), "param", s_param, _SLEN);
- if (ret<=0) { s_param[0] = '\0'; }
- if (hub_fd >= 0) {
- strncpy(dr.rulename, s_rule, DRIVER_RULECALL_LEN - 1);
- strncpy(dr.ruleparam, s_param, DRIVER_RULECALL_LEN - 1);
- prepare_message(&outgoing, MAILBOX_RULE_CALL, &dr, sizeof(dr));
- send_message(hub_fd, &outgoing);
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_ok), msg_ok);
- }
- // driver paddle (route) input
- //
- static void ui_handle_paddle_input(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char s_paddle[_SLEN];
- //char msg_fail[] = "fail .";
- char msg_ok[] = "ok .";
- int ipaddle;
- ret = mg_get_http_var(&(hm->body), "paddle", s_paddle, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- ipaddle = atoi(s_paddle);
- make_paddle_request(ipaddle);
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_ok), msg_ok);
- }
- // driver login
- //
- static void ui_handle_driver_login(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char s_driver[_SLEN], s_pin[_SLEN];
- int idrv=-1;
- char msg_fail[] = "fail driver_login";
- char msg_success[] = "ok driver";
- char msg_success_admin[] = "ok admin";
- ret = mg_get_http_var(&(hm->body), "driver", s_driver, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- ret = mg_get_http_var(&(hm->body), "pin", s_pin, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- idrv = atoi(s_driver);
- ret = driver_login(idrv, s_pin);
- if (ret!=0) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_fail), msg_fail);
- return;
- }
- // If we have an admin login, indicate a successful login and give a message
- // to the UI indicating it's an 'admin' login
- //
- if (!strcmp(my_driver_status.driver_name, MAGIC_DRIVER_NAME)) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_success_admin), msg_success_admin);
- return;
- }
- // Otherwise a normal driver login
- //
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_success), msg_success);
- }
- // screen dim event
- //
- static void ui_handle_dim(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char msg_fail[] = "fail dim";
- char msg_success[] = "ok dim";
- // assuming we're running as root for now
- //
- ret = system("su - root -c \"/home/bus/bin/dim >> /tmp/dim.log 2>&1 \" & ");
- if (ret!=0) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_fail), msg_fail);
- return;
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_success), msg_success);
- }
- // set volume
- //
- static void ui_handle_volume(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char s_volume[_SLEN], _cmd[1024];
- float f_vol = 100.0;
- char msg_fail[] = "fail volume";
- char msg_success[] = "ok volume";
- ret = mg_get_http_var(&(hm->body), "volume", s_volume, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- // assuming we're running as root for now
- //
- f_vol = atof(s_volume);
- snprintf(_cmd, 1023, "/home/bus/bin/volumeset %04f &", f_vol);
- ret = system(_cmd);
- if (ret!=0) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_fail), msg_fail);
- return;
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_success), msg_success);
- }
- // custom script
- //
- static void ui_handle_custom(struct mg_connection *nc, struct http_message *hm) {
- int i, j, ret;
- char s_func[128], s_func_clean[128];
- char s_param[128], s_param_clean[128];
- char _cmd[128*3];
- char msg_fail[] = "fail custom";
- char msg_success[] = "ok custom";
- memset(s_func, 0, sizeof(char)*128);
- memset(s_param, 0, sizeof(char)*128);
- ret = mg_get_http_var(&(hm->body), "function", s_func, 127);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- ret = mg_get_http_var(&(hm->body), "parameter", s_param, 127);
- memset(_cmd, 0, sizeof(char)*3*128);
- // restrict to only alphnum and ',' '.'
- //
- memset(s_func_clean, 0, sizeof(char)*128);
- for (i=0, j=0; (s_func[i]) && (i<(128-1)); i++) {
- if ( ((s_func[i] >= 'a') && (s_func[i] <= 'z')) ||
- ((s_func[i] >= 'A') && (s_func[i] <= 'Z')) ||
- ((s_func[i] >= '0') && (s_func[i] <= '9')) ||
- (s_func[i] == ',') || (s_func[i] == '.') ) {
- s_func_clean[j] = s_func[i];
- j++;
- }
- }
- memset(s_param_clean, 0, sizeof(char)*128);
- for (i=0, j=0; (s_param[i]) && (i<(128-1)); i++) {
- if ( ((s_param[i] >= 'a') && (s_param[i] <= 'z')) ||
- ((s_param[i] >= 'A') && (s_param[i] <= 'Z')) ||
- ((s_param[i] >= '0') && (s_param[i] <= '9')) ||
- (s_param[i] == ' ') || (s_param[i] == ',') || (s_param[i] == '.') ) {
- s_param_clean[j] = s_param[i];
- j++;
- }
- }
- // assuming we're running as root for now
- //
- snprintf(_cmd, (3*128)-1, "/home/bus/bin/custom '%s' '%s' &", s_func_clean, s_param_clean);
- ret = system(_cmd);
- if (ret!=0) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_fail), msg_fail);
- return;
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_success), msg_success);
- }
- // bring network interface up/down
- //
- static void ui_handle_interfaceupdown(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char s_interface[_SLEN], s_updown[_SLEN];
- char msg_fail[] = "fail interfaceupdown";
- char msg_success[] = "ok interfaceupdown";
- int _iface_updown = -1;
- ret = mg_get_http_var(&(hm->body), "interface", s_interface, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- ret = mg_get_http_var(&(hm->body), "state", s_updown, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- // only allow eth0 and up/down for now
- //
- if (strncmp(s_interface, "eth0", strlen("eth0")+1)!=0) {
- mg_http_send_error(nc, 404, NULL);
- return;
- }
- if (strncmp(s_updown, "up", strlen("up")+1)==0) {
- _iface_updown=1;
- }
- else if (strncmp(s_updown, "down", strlen("down")+1)==0) {
- _iface_updown=0;
- }
- if (_iface_updown < 0) {
- mg_http_send_error(nc, 404, NULL);
- return;
- }
- // Assuming we're running as root for now.
- // Bring eth0 interface up or down.
- //
- if (_iface_updown==1) {
- ret = system("/sbin/ip link set eth0 up &");
- }
- else if (_iface_updown==0) {
- ret = system("/sbin/ip link set eth0 down &");
- }
- if (ret!=0) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_fail), msg_fail);
- return;
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_success), msg_success);
- }
- // bring network interface up/down
- //
- static void ui_handle_calibration(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char msg_fail[] = "fail calibration";
- char msg_success[] = "ok calibration";
- // Assuming we're running as root for now.
- //
- ret = system("/usr/bin/ts_calibrate &");
- if (ret!=0) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_fail), msg_fail);
- return;
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_success), msg_success);
- }
- // bring network interface up/down
- //
- static void ui_handle_switchserver(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char s_server[_SLEN];
- char msg_fail[] = "fail switchserver";
- char msg_success[] = "ok switchserver";
- ret = mg_get_http_var(&(hm->body), "server", s_server, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- //TODO: switch server code (call shell script)...
- //
- if (ret!=0) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_fail), msg_fail);
- return;
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_success), msg_success);
- }
- // get network interface information
- //
- static void ui_handle_interfaceinfo(struct mg_connection *nc, struct http_message *hm) {
- int n, fam, s;
- struct ifaddrs *_addr, *ifa;
- char host[NI_MAXHOST];
- char msg_fail[] = "fail interfaceinfo";
- char buf[4*_SLEN];
- // We're going to restrict to eth0 and only ip4
- //
- if (getifaddrs(&_addr)==-1) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_fail), msg_fail);
- return;
- }
- for (ifa = _addr, n=0; ifa!=NULL; ifa = ifa->ifa_next, n++) {
- if (ifa->ifa_addr == NULL) { continue; }
- fam = ifa->ifa_addr->sa_family;
- if (fam != AF_INET) { continue; }
- if (strncmp(ifa->ifa_name, "eth0", strlen("eth0") + 1)!=0) { continue; }
- s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
- host, NI_MAXHOST,
- NULL, 0, NI_NUMERICHOST);
- if (s != 0) {
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_fail), msg_fail);
- return;
- }
- snprintf(buf, (4*_SLEN) - 1, "ok msg=interfaceinfo\n%s=%s", ifa->ifa_name, host);
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(buf), buf);
- }
- // run 'say' custom script for voice text to speech
- //
- static void ui_handle_say(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char msg_ok[] = "ok say";
- char s_message[_SLEN];
- char buf[4*_SLEN];
- ret = mg_get_http_var(&(hm->body), "message", s_message, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- snprintf(buf, 4*_SLEN-1, "/home/bus/bin/say \"%s\" &", s_message);
- system(buf);
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_ok), msg_ok);
- }
- // change equipment number
- //
- static void ui_handle_eqnum(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char msg_ok[] = "ok eqnum";
- char s_eqnum[_SLEN];
- ret = mg_get_http_var(&(hm->body), "eqnum", s_eqnum, _SLEN);
- if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- ret = set_equip_num(atoi(s_eqnum));
- if (ret < 0) {
- mg_http_send_error(nc, 404, NULL);
- return;
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_ok), msg_ok);
- }
- //-----
- //-----
- //-----
- // api point
- //
- static void api_handle_req(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char s_action[_SLEN];
- ret = mg_get_http_var(&(hm->body), "action", s_action, _SLEN);
- if (ret==0) {
- mg_http_send_error(nc, 404, NULL);
- return;
- }
- if (strncmp(s_action, "driverlogin", strlen("driverlogin")+1)==0) {
- ui_handle_driver_login(nc, hm);
- }
- else if (strncmp(s_action, "paddleinput", strlen("paddleinput")+1)==0) {
- ui_handle_paddle_input(nc, hm);
- }
- else if (strncmp(s_action, "prevstop", strlen("prevstop")+1)==0) {
- ui_handle_prevstop_input(nc, hm);
- }
- else if (strncmp(s_action, "nextstop", strlen("nextstop")+1)==0) {
- ui_handle_nextstop_input(nc, hm);
- }
- else if (strncmp(s_action, "status", strlen("status")+1)==0) {
- ui_handle_status_input(nc, hm);
- }
- else if (strncmp(s_action, "logout", strlen("logout")+1)==0) {
- ui_handle_logout_input(nc, hm);
- }
- else if (strncmp(s_action, "fare", strlen("fare")+1)==0) {
- ui_handle_fare_input(nc, hm);
- }
- else if (strncmp(s_action, "dim", strlen("dim")+1)==0) {
- ui_handle_dim(nc, hm);
- }
- else if (strncmp(s_action, "volume", strlen("volume")+1)==0) {
- ui_handle_volume(nc, hm);
- }
- else if (strncmp(s_action, "interfaceupdown", strlen("interfaceupdown")+1)==0) {
- ui_handle_interfaceupdown(nc, hm);
- }
- else if (strncmp(s_action, "interfaceinfo", strlen("interfaceinfo")+1)==0) {
- ui_handle_interfaceinfo(nc, hm);
- }
- else if (strncmp(s_action, "say", strlen("say")+1)==0) {
- ui_handle_say(nc, hm);
- }
- else if (strncmp(s_action, "eqnum", strlen("eqnum")+1)==0) {
- ui_handle_eqnum(nc, hm);
- }
- else if (strncmp(s_action, "calibration", strlen("calibration")+1)==0) {
- ui_handle_calibration(nc, hm);
- }
- else if (strncmp(s_action, "switchserver", strlen("switchserver")+1)==0) {
- ui_handle_switchserver(nc, hm);
- }
- else if (strncmp(s_action, "custom", strlen("custom")+1)==0) {
- ui_handle_custom(nc, hm);
- }
- else {
- mg_http_send_error(nc, 404, NULL);
- }
- }
- static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
- struct http_message *hm = (struct http_message *) ev_data;
- char buf[1024];
- int debug_print = 0;
- if (debug_print) {
- mg_sock_addr_to_str(&(nc->sa), buf, 1023, MG_SOCK_STRINGIFY_IP);
- printf("%s\n", buf);
- }
- switch (ev){
- case MG_EV_HTTP_REQUEST:
- if (mg_vcmp(&hm->uri, "/req")==0) {
- api_handle_req(nc, (struct http_message *)ev_data);
- }
- else {
- mg_serve_http(nc, (struct http_message *) ev_data, s_http_server_opts);
- }
- break;
- case MG_EV_WEBSOCKET_HANDSHAKE_DONE:
- break;
- case MG_EV_WEBSOCKET_FRAME:
- process_ws_message((struct websocket_message *)ev_data);
- break;
- case MG_EV_CLOSE:
- if (is_websocket(nc)) {
- // websocket closed
- }
- break;
- default:
- break;
- }
- }
- //-------- web server functions ----
- int main(int argc, char **argv) {
- char line[LINE_BUFFER_SIZE] = {0};
- struct message_record incoming_msg;
- struct message_record outgoing_msg;
- struct pollfd fds[32];
- int nfd=0;
- int poll_return;
- int read_return;
- int i;
- time_t down_time = 0;
- int calibration = 0;
- time_t now;
- int retval = 0;
- int tz = 0;
- int tx = 0;
- int ty = 0;
- time_t last_stale_gps_check = 0;
- struct mg_connection *nc;
- #ifdef DEBUG_PRINT
- long long int _usec_now, _usec_prv, _usec_del;
- _usec_now = get_usec_time();
- _usec_prv = _usec_now;
- _usec_del = 60000000;
- #endif
- if ( (argc>1) && (
- (strncmp(argv[1], "-h", 3)==0) ||
- (strncmp(argv[1], "-v", 3)==0) ) ) {
- printf("diu_minder version: %s\n", DIU_MINDER_VERSION);
- exit(0);
- }
- // get current state in case the diu_minder crashed
- // and forgot it (diu_minder broadcasts initial
- // state on startup, which defaults to zero)
- //
- get_state_info(&my_state_info);
- my_driver_status.logged_in_driver = my_state_info.logged_in_driver;
- memcpy(my_driver_status.driver_name, my_state_info.driver_name, DRIVER_NAME_LEN);
- my_driver_status.driver_name[DRIVER_NAME_LEN-1] = '\0';
- my_driver_status.equip_num = my_state_info.equip_num;
- // setup mongoose web server
- //
- mg_mgr_init(&g_mgr, NULL);
- nc = mg_bind(&g_mgr, s_http_port, ev_handler);
- if (!nc) {
- printf("failed to create listener\n");
- return 1;
- }
- mg_set_protocol_http_websocket(nc);
- s_http_server_opts.document_root = CONFIG_FILE_PATH "/html";
- s_http_server_opts.enable_directory_listing = "no";
- // Configure our signal handlers to deal with SIGINT, SIGTERM, etc... and make graceful exits while logging
- //
- configure_signal_handlers(argv[0]);
- // Make an initial attempt to get in touch with the interprocess communication hub (it may not be up yet depending on the start order)
- //
- maintain_ipc_hub_connect(argv[0]);
- // Register our defualt system message processing callbacks
- //
- register_system_status_callbacks();
- register_dispatch_callback(MAILBOX_STATUS_REQUEST, CALLBACK_USER(1), handle_status_request, NULL);
- register_dispatch_callback(MAILBOX_DRIVER_NOTIFY, CALLBACK_USER(2), handle_driver_notify, NULL);
- register_dispatch_callback(MAILBOX_PADDLE_ACK, CALLBACK_USER(3), handle_paddle_ack, NULL);
- register_dispatch_callback(MAILBOX_VAULT_DROP, CALLBACK_USER(4), handle_vault_drop, NULL);
- register_dispatch_callback(MAILBOX_TOKEN_MAG, CALLBACK_USER(5), handle_token_diag, NULL);
- register_dispatch_callback(MAILBOX_TOKEN_RFID, CALLBACK_USER(6), handle_token_diag, NULL);
- clear_diu_messages();
- // This is the main dispatch loop:
- //
- // * reset watchdog to make sure we haven't crashed/frozen
- // * if need be, open a connection to the DIU microcontroller, quieting all messages except for acks
- // * handle GPS message dispatch through IPC
- // * manage driver status message communication
- // * handle paddle change
- // * listen on the mailboxes for messages and process. This includes
- // - gps updates
- // - warning/debug/error messages
- //
- //loop until we get asked to exit.../
- //
- while( exit_request_status == EXIT_REQUEST_NONE ) {
- #ifdef DEBUG_PRINT
- _usec_now = get_usec_time();
- if ((_usec_now - _usec_prv) > _usec_del) {
- printf("[%lli] diu_minder: heartbeat\n", get_usec_time());
- _usec_prv = _usec_now;
- }
- #endif
- RESET_WATCHDOG();
- maintain_ipc_hub_connect(argv[0]);
- if (diu_fd < 0) {
- diu_fd = open_rs232_device(DRIVER_UI_PORT, USE_DEFAULT_BAUD, RS232_LINE);
- if (diu_fd < 0) {
- //fprintf(stderr, "Cannot open serial port %s for DIU!\n", DRIVER_UI_PORT);
- }
- else {
- // Turn on all messages except ACKs for sent commands
- //
- write(diu_fd, "/Q:aK\r", 6);
- }
- }
- now = time(NULL);
- //Every second, we want to update the DIU clock (even though it only shows minutes, this covers power events...)
- //
- if ((now - last_diu_clock) > 0) {
- if (diu_fd>=0) {
- set_diu_clock(diu_fd, now);
- last_diu_clock = now;
- }
- }
- //Every second we want to check to make sure that our GPS data have note gone stale...
- //
- if ((now - last_stale_gps_check) > 0) {
- // If the stale check results in an update to my_gps_stat, we must update any other
- // modules which may be tracking GPS status via the IPC hub.
- //
- if ( handle_stale_gps_condition() > 0 ) {
- // If we have a connection to the IPC hub
- //
- if (hub_fd >= 0) {
- // Go and toss the data to any other modules who happen to care about GPS
- //
- prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
- send_message(hub_fd, &outgoing_msg);
- }
- }
- // Either way, remember that we did this stale check.
- //
- last_stale_gps_check = now;
- }
- if (hup_request_status) {
- hup_request_status = 0;
- // reserve ui if necssary ...
- //
- }
- //If it is time to send out a driver status update
- //
- if (update_driver_status && (hub_fd >= 0)) {
- //do so...
- //
- prepare_message(&outgoing_msg, MAILBOX_DRIVER_STATUS, &my_driver_status, sizeof(my_driver_status));
- send_message(hub_fd, &outgoing_msg);
- update_driver_status = 0;
- }
- check_paddle_request();
- //If we have to redraw the UI
- //if (redraw_flag && !calibration)
- //
- if (!calibration) {
- //Redraw the menu reflecting any changes from the last touchscreen input
- //or other stimulus
- //draw_menu(mt);
- //
- #ifdef TOUCHSCREEN_QUIET
- // to hear if they have any further input to give us...
- // Un-Quiet the touch screen, now that we've responded to the user we want
- //
- if (diu_fd >= 0) {
- write(diu_fd, "/Q:t\r", 5);
- }
- #endif
- }
- nfd = 0;
- if (hub_fd >= 0) {
- fds[nfd].fd = hub_fd;
- fds[nfd].events = POLLIN;
- fds[nfd].revents = 0;
- nfd++;
- }
- if (diu_fd >= 0) {
- fds[nfd].fd = diu_fd;
- fds[nfd].events = POLLIN;
- fds[nfd].revents = 0;
- nfd++;
- }
- // Add our websocket socket to the list of file descriptors
- // to select on.
- //
- for (nc = g_mgr.active_connections; nc != NULL; nc = nc->next) {
- if (nc->sock != INVALID_SOCKET) {
- if (nfd < 32) {
- fds[nfd].fd = nc->sock;
- fds[nfd].events = POLLIN | POLLOUT;
- fds[nfd].revents = 0;
- nfd++;
- }
- }
- }
- //if we have any file descriptors, poll them
- //
- if (nfd > 0) {
- poll_return = poll(fds, nfd, POLL_TIMEOUT);
- }
- //otherwise, whistle and look busy
- //
- else {
- // (this keeps us from buringing 100% cpu cycles if we don't have contact with either
- // the IPC hub or the DIU hardware).
- //
- poll_return = 0;
- sleep(1);
- }
- //--------------------------------------------------------------------------------------------------
- //if poll didn't net us any work to do,
- //
- if (poll_return < 1) {
- //lets try again
- //
- continue;
- }
- // Loop through all polled file descriptors
- //
- for (i = 0; i < nfd; i++) {
- //If we're looking at the DIU...
- //
- if ( fds[i].fd == diu_fd ) {
- //if poll says our serial port has become bogus...
- //
- if (fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
- fprintf(stderr, "This is very odd... Poll returned flags %d on our serial port...\n", fds[i].revents);
- if (diu_fd >= 0) {
- close(diu_fd);
- }
- diu_fd = -1;
- break;
- }
- if (fds[i].revents & POLLIN) {
- read_return = read(fds[i].fd, line, sizeof(line));
- if (read_return > 0) {
- char *trav = line;
- line[read_return] = '\0';
- strip_crlf(line);
- // advance until EOL or we hit our start sentinel
- //
- while (*trav && (*trav != '/') ) { trav++; }
- // Check to see that our address header is intact...
- //
- if ( (trav[0] == '/') && (trav[2] == ':') ) {
- switch (trav[1]) {
- //-----------------------------------"/T:" means it's a touchscreen event
- //
- case 'T':
- // advance past the header
- //
- trav += 3;
- retval = sscanf(trav, "%x,%x,%x", &tz, &tx, &ty);
- if (retval == 3) {
- if (tz) {
- if (down_time == 0) {
- down_time = time(NULL);
- }
- else {
- if ( (time(NULL) - down_time) > TS_CALIB_HOLD_TIME) {
- begin_touchscreen_calibration();
- calibration = 1;
- }
- }
- if (!calibration) {
- // calibration from here turned off...
- }
- else {
- if (advance_touchscreen_calibration(tx, ty, tz)) {
- calibration = 0;
- }
- else {
- draw_touchscreen_calibration();
- }
- }
- }
- else {
- down_time = 0;
- if (!calibration) { }
- else {
- if (advance_touchscreen_calibration(tx, ty, tz)) {
- calibration = 0;
- //redraw_flag = 1;
- }
- else {
- draw_touchscreen_calibration();
- }
- }
- }
- }
- break;
- //-----------------------------------"/G:" means it is a new GPS input
- //
- case 'G':
- // advance past the header
- //
- trav += 3;
- // If this GPS update constitutes a meaningful piece of data
- //
- if (update_gps(trav) > 0) {
- // and we have a connection to the IPC hub
- //
- if (hub_fd >= 0) {
- // Go and toss the data to any other modules who happen to care about GPS
- //
- prepare_message(&outgoing_msg, MAILBOX_GPS_STATUS, &my_gps_stat, sizeof(my_gps_stat));
- send_message(hub_fd, &outgoing_msg);
- }
- // Remember that we did a stale GPS check as part of our update.
- //
- last_stale_gps_check = now;
- }
- break;
- // handle warnings
- //
- case '*':
- // debugs
- //
- case '#':
- // and errors
- //
- case '!':
- // If this DIU error/debug message has not run afoul of the rate limiting policy...
- //
- if ( can_report_diu_error() ) {
- // send them all to the log server
- //
- format_log_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
- send_message(hub_fd, &outgoing_msg);
- //but in the case of errors, send them to the driver too
- if (trav[1] == '!') {
- format_driver_message(&outgoing_msg, trav[1], "DIU Reports: %s", trav + 3);
- send_message(hub_fd, &outgoing_msg);
- }
- }
- break;
- default: //ignore any message addresses that we don't know what to do with
- printf("Ignoring command \"%s\"\n", trav);
- break;
- }
- }
- else {
- //printf("Ignoring non-command line \"%s\"\n", trav);
- }
- }
- else {
- fprintf(stderr, "Read from %s returned %d!\n", DRIVER_UI_PORT, read_return);
- if (diu_fd >= 0) {
- close(diu_fd);
- }
- diu_fd = -1;
- break;
- }
- }
- }
- // If we're looking at the IPC hub...
- //
- else if ( fds[i].fd == hub_fd ) {
- // if poll says our connection to the IPC hub has died...
- //
- if (fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) {
- fprintf(stderr, "The connection to the IPC hub has gone away...\n");
- close(hub_fd);
- hub_fd = -1;
- break;
- }
- // if we have mail in any of our mailboxes...
- //
- if (fds[i].revents & POLLIN) {
- read_return = get_message(hub_fd, &incoming_msg);
- if (read_return < 0) {
- fprintf(stderr, "The connection to the IPC hub has gone away...\n");
- close(hub_fd);
- hub_fd = -1;
- break;
- }
- else {
- message_callback_return msg_status;
- msg_status = process_message(&incoming_msg);
- if (msg_status) {
- //pass
- }
- }
- }
- }
- else {
- if (fds[i].revents & (POLLIN | POLLOUT)) {
- mg_mgr_poll(&g_mgr, 10);
- }
- }
- }
- }
- if (hub_fd >= 0) {
- close(hub_fd);
- }
- if (diu_fd >= 0) {
- write(diu_fd, "/C:----\r",8);
- close(diu_fd);
- }
- return 0;
- }
|