| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539 |
- /*
- * 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 "../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
- /*
- #include "fbutil.h"
- #include "expat-2.0.1/lib/expat.h"
- #include "menu.h"
- */
- 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};
- //unsigned char menu_checksum[MD5_DIGEST_LENGTH];
- time_t paddle_req_timeout = 0;
- set_paddle_req paddle_req = {0};
- driver_status my_driver_status={0};
- int update_driver_status = 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...
- n = 0; //Start out with zero parsed fields
- // 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(n >= 6) //if we scanned at all required fields
- {
- struct tm gpstm = {0};
- year += GPS_DATE_CENTURY; //GPS date only uses two digits for year, so we must assume the century
- gpstm.tm_year = year - 1900; //tm.tm_year is based on the year 1900
- gpstm.tm_mon = month - 1; //January = month 0 in struct tm.tm_mon whereas January = month 1 in an NMEA GPS date.
- gpstm.tm_mday = day;
- gpstm.tm_hour = hour;
- gpstm.tm_min = min;
- gpstm.tm_sec = sec;
- utc = mkgmtime(&gpstm); //Go and turn the struct tm we've just populated into an utc time stamp (seconds since epoch)
- my_gps_stat.gpstime = utc; //Most importantly... Remember what the self-reported GPS time stamp is.
- // 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(abs(utc - now) > MAX_GPS_CLOCK_DRIFT) //if we have more than MAX_GPS_CLOCK_DRIFT seconds of clock drift
- {
- struct timeval ts = {0};
- ts.tv_sec = utc; //Set the timeval struct to the calculated utc timestamp from the GPS unit.
- ts.tv_usec = 0;
- settimeofday(&ts, NULL); //Set the system clock from GPS time using said timeval struct.
- //system("/sbin/hwclock --systohc"); //Go and push the new system clock value into the hardware realtime clock chip.
- if( hub_fd >= 0) //If we have a valid connection to the IPC hub
- {
- //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(num == 11) //If we have a full GPRMC sentence we can consider setting the time
- {
- // 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)
- {
- my_gps_stat.lat = f3 * ((f4 == 'N')?(1):(-1)); //update snapshot with latitude
- my_gps_stat.lon = f5 * ((f6 == 'E')?(1):(-1)); //longitude
- my_gps_stat.velocity = f7 / 1.94384449f; //meters per second (converted from knots)
- my_gps_stat.heading = f8; //course
- my_gps_stat.stamp = time(NULL); //update snapshot's staledate
- 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)
- {
- if ( f7 >= 3 ) // require 3 satellites minimum
- {
- my_gps_stat.gps_good = f6; //store GPS valid flag in snapshot
- my_gps_stat.num_sats = f7; //store number of satellites in view in snapshot
- // 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(hub_fd < 0) //if we have no connection to the IPC hub
- {
- if( (time(NULL) - last_hub_try) > HUB_RETRY_TIME ) //if we haven't tried the hub in a few seconds
- {
- last_hub_try = time(NULL); //retry it
- hub_fd = connect_to_message_server(progname); //try and get one
- 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");
- }
- }
- }
- }
- //menutree *mt = NULL;
- //int redraw_flag = 0;
- 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};
- //pixel bgcolor = FBCOLOR_WHITE;
- //pixel textcolor = FBCOLOR_BLACK;
- 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:
- //bgcolor = FBCOLOR_LTRED;
- if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
- {
- DIU_ERROR_BEEP(diu_fd);
- }
- break;
- case LOGLEVEL_ACCEPT:
- //bgcolor = FBCOLOR_LTGREEN;
- if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
- {
- DIU_ACK_BEEP(diu_fd);
- }
- break;
- case LOGLEVEL_ERROR:
- //bgcolor = FBCOLOR_RED;
- //textcolor = FBCOLOR_CYAN;
- if(!is_dup || (dup_usec_delta >= DUP_USEC_BEEP_THRESHOLD))
- {
- DIU_CRITICAL_BEEP(diu_fd);
- }
- break;
- default:
- break;
- }
- //DEBUG
- printf("driver_notify: %s\n", (char *)(&(msg->payload[1])));
- if(is_dup)
- {
- //snprintf(dup_text, MAX_PAYLOAD_LENGTH, "%d x %s", dup_notify_count, &msg->payload[1]);
- //replace_diu_message(bgcolor, textcolor, dup_text);
- 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
- {
- //add_diu_message(bgcolor, textcolor, (char *)(&(msg->payload[1])));
- 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);
- }
- //redraw_flag |= 1;
- 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)
- {
- diu_error_counter = 0; //reset our burst counter
- diu_error_burst = now; //and start the "potential burst" time at this message
- }
- if(diu_error_counter < DIU_ERROR_BURST_LIMIT) //if we haven't hit our burst limit...
- {
- diu_error_counter++; //count this message against our burst limit
- return 1; //and allow it to pass
- }
- else //if we have hit our limit
- {
- return 0; //ignore this message
- }
- }
- //----------------------------------
- //-------- web server functions ----
- static const char *s_http_port = "60535";
- static struct mg_serve_http_opts s_http_server_opts;
- 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;
- char buf[4*_SLEN],
- pkgnetline[_SLEN],
- _str[_SLEN];
- char date_str[32];
- time_t t;
- struct tm tm, pkgtime;
- FILE *fp;
- package_signature pkgs[MAX_PKGS];
- 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);
- //if (npkgnet>0) { strncat(pkgnetline, "|", _SLEN); }
- strncat(pkgnetline, "|", _SLEN);
- strncat(pkgnetline, _str, _SLEN);
- npkgnet++;
- }
- fp = fopen("/tmp/net_ids", "rb");
- if (fp) {
- i=0;
- while (fgets(_str, _SLEN, fp)) {
- strip_crlf(_str);
- strncat(pkgnetline, "|", _SLEN);
- strncat(pkgnetline, _str, _SLEN);
- npkgnet++;
- }
- fclose(fp);
- }
- snprintf(buf, 4*_SLEN, "ok msg=status\n"
- "equipno=%d|"
- "route=%d|"
- "trip=%d|"
- "stop=%d|"
- "gps=%i|"
- "tunnel=%i|"
- "gprs=%i|"
- "date=%s|"
- "nmsg=%d|"
- "last_token=%d"
- "%s",
- get_equip_num(),
- stop_stat.route,
- stop_stat.trip,
- stop_stat.stop,
- gps_stat.gps_good,
- tunnel_is_up(),
- gprs_is_up(),
- date_str,
- bill_stat.unsynced_messages,
- token_diag_serial % 100,
- pkgnetline);
- //DEBUG
- printf("%s\n", buf);
- 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 .",
- };
- 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; }
- printf("got rule '%s'\n", s_rule);
- ret = mg_get_http_var(&(hm->body), "param", s_param, _SLEN);
- //if (ret<=0) { mg_http_send_error(nc, 404, NULL); return; }
- if (ret<=0) { s_param[0] = '\0'; }
- printf("got param '%s'\n", s_param);
- 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; }
- //DEBUG
- printf("#got paddle %s\n", s_paddle);
- 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";
- 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;
- }
- mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n\r\n%s",
- (unsigned long)strlen(msg_success), msg_success);
- }
- // api point
- //
- static void api_handle_req(struct mg_connection *nc, struct http_message *hm) {
- int ret;
- char s_action[_SLEN];
- char _default_msg[_SLEN] = "";
- struct mg_str hdr;
- ret = mg_get_http_var(&(hm->body), "action", s_action, _SLEN);
- if (ret==0) {
- //printf(">>> %p\n", s_action);
- mg_http_send_error(nc, 404, NULL);
- return;
- }
- printf("#req: action: (%s)\n", s_action);
- if (strncmp(s_action, "driverlogin", strlen("driverlogin"))==0) {
- ui_handle_driver_login(nc, hm);
- }
- else if (strncmp(s_action, "paddleinput", strlen("paddleinput"))==0) {
- ui_handle_paddle_input(nc, hm);
- }
- else if (strncmp(s_action, "prevstop", strlen("prevstop"))==0) {
- ui_handle_prevstop_input(nc, hm);
- }
- else if (strncmp(s_action, "nextstop", strlen("nextstop"))==0) {
- ui_handle_nextstop_input(nc, hm);
- }
- else if (strncmp(s_action, "status", strlen("status"))==0) {
- ui_handle_status_input(nc, hm);
- }
- else if (strncmp(s_action, "logout", strlen("logout"))==0) {
- ui_handle_logout_input(nc, hm);
- }
- else if (strncmp(s_action, "fare", strlen("fare"))==0) {
- ui_handle_fare_input(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:
- printf("http request\n");
- 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:
- //DEBUG
- printf("ws handshake done\n");
- break;
- case MG_EV_WEBSOCKET_FRAME:
- //DEBUG
- printf("ws frame\n");
- process_ws_message((struct websocket_message *)ev_data);
- break;
- case MG_EV_CLOSE:
- if (is_websocket(nc)) {
- //DEBUG
- printf("ws closed\n");
- }
- break;
- default:
- //printf("? %i\n", ev);
- break;
- }
- }
- //DEBUG
- void _test_ws(struct mg_mgr *mgr) {
- struct mg_connection *conn;
- char buf[_SLEN];
- snprintf(buf, _SLEN, "test message");
- 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, buf, strlen(buf));
- }
- }
- //-------- 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;
- long long int _usec_now, _usec_prv, _usec_del;
- _usec_del = 1000000;
- // setup mongoose web server
- //
- //struct mg_mgr mgr;
- struct mg_connection *nc;
- /*
- mg_mgr_init(&mgr, NULL);
- nc = mg_bind(&mgr, s_http_port, ev_handler);
- if (!nc) {
- printf("failed to create listener\n");
- return 1;
- }
- */
- 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 = "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();
- _usec_now = get_usec_time();
- _usec_prv = _usec_now;
- // 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
- // * if need be, handle reload of menu.xml
- // * manage driver status message communication
- // * handle paddle change
- // * draw menu
- // * listen on the mailboxes for messages and process. This includes
- // - touchscreen events
- // - gps updates
- // - warning/debug/error messages
- //
- //loop until we get asked to exit.../
- //
- while( exit_request_status == EXIT_REQUEST_NONE ) {
- _usec_now = get_usec_time();
- if ((_usec_now - _usec_prv) > _usec_del) {
- //DEBUG
- printf("[%lli] diu_minder: heartbeat\n", get_usec_time());
- //DEBUG
- _usec_prv = _usec_now;
- //_test_ws(&mgr);
- }
- RESET_WATCHDOG();
- // service our UI updates
- //mg_mgr_poll(&mgr, POLL_TIMEOUT);
- 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 {
- write(diu_fd, "/Q:aK\r", 6); //Turn on all messages except ACKs for sent commands
- }
- }
- 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) {
- set_diu_clock(diu_fd, now);
- last_diu_clock = now;
- }
- // Also request a UI redraw if nothing else has, just so that status line gets redrawn
- //
- //redraw_flag |= 1;
- }
- //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) {
- //unsigned char temp_menu_checksum[MD5_DIGEST_LENGTH];
- 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;
- }
- //If a paddle change request has resulted in a change
- //if(check_paddle_request(mt))
- //
- if(check_paddle_request()) {
- //do a redraw of the UI
- //redraw_flag |= 1;
- }
- //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
- write(diu_fd, "/Q:t\r", 5); //Un-Quiet the touch screen, now that we've responded to the user we want
- #endif //to hear if they have any further input to give us...
- //redraw_flag = 0; //Clear the 'redraw required' flag
- }
- 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++;
- }
- // experimental
- //
- //for (nc = mgr.active_connections; nc != NULL; nc = nc->next) {
- 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++;
- }
- }
- }
- //printf("nfd %i\n", 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;
- }
- for(i = 0; i < nfd; i++) //Loop through all polled file descriptors
- {
- //If we're looking at the DIU...
- //
- if( fds[i].fd == diu_fd ) {
- //DEBUG
- printf("##diu_fd\n");
- //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);
- 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) {
- /*
- //printf("Touch at (%d, %d)\n", translate_ts_x(tx), translate_ts_y(ty));
- if(process_pen(mt, translate_ts_x(tx), translate_ts_y(ty), 1) > 0)
- {
- #ifdef TOUCHSCREEN_QUIET
- write(diu_fd, "/Q:T\r", 5);
- #endif
- //redraw_flag = 1;
- }
- */
- }
- else {
- if(advance_touchscreen_calibration(tx, ty, tz)) {
- calibration = 0;
- //redraw_flag = 1;
- }
- else {
- draw_touchscreen_calibration();
- }
- }
- }
- else
- {
- down_time = 0;
- //printf("Touch Release\n");
- if(!calibration) {
- /*
- if(process_pen(mt, 0,0,0) > 0)
- {
- #ifdef TOUCHSCREEN_QUIET
- write(diu_fd, "/Q:T\r", 5);
- #endif
- //redraw_flag = 1;
- }
- */
- }
- 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);
- }
- last_stale_gps_check = now; //Remember that we did a stale GPS check as part of our update.
- }
- 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);
- 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);
- }
- }
- }
- else {
- if (fds[i].revents & (POLLIN | POLLOUT)) {
- //mg_mgr_poll(&mgr, 10);
- mg_mgr_poll(&g_mgr, 10);
- }
- }
- }
- }
- //set_color(255,255,255);
- //cls();
- //present_framebuffer();
- //close_framebuffer();
- if(hub_fd >= 0) {
- close(hub_fd);
- }
- if(diu_fd >= 0) {
- write(diu_fd, "/C:----\r",8);
- close(diu_fd);
- }
- return 0;
- }
|