//--------------------------------------------------- // // Main() // int main(int argc, char* argv[]) { // // I2C ONE bmp180 baroSen(I2C_HW1_BUS_NUM); // // I2C TWO PCA9544Mux i2cMuxNum1(I2C_HW2_BUS_NUM, PCA9544_000_ADDR); i2cMuxNum1.selectChan(PCA9544Mux :: CH_3); ADXL345Accelerometer accelNum1(I2C_HW2_BUS_NUM, ADXL345_SDO_L_ADDR); ADXL345Accelerometer accelNum2(I2C_HW2_BUS_NUM, ADXL345_SDO_H_ADDR); BME280 humPress1(I2C_HW2_BUS_NUM, BME280_SDO_L_ADDR); // MPU6050AccelGyro accGyrNum3(I2C_HW2_BUS_NUM, MPU6050_AD0_L_ADDR); /* HscPress pressNum1(I2C_HW2_BUS_NUM, HSC_PN2_ADDR); ADXL345Accelerometer accelNum2(I2C_HW2_BUS_NUM, ADXL345_SDO_L_ADDR); i2cMuxNum1.selectChan(PCA9544Mux :: CH_2); ADXL345Accelerometer accelNum4(I2C_HW2_BUS_NUM, ADXL345_SDO_H_ADDR); i2cMuxNum1.selectChan(PCA9544Mux :: CH_3); ADXL345Accelerometer accelNum5(I2C_HW2_BUS_NUM, ADXL345_SDO_H_ADDR); ADXL345Accelerometer accelNum6(I2C_HW2_BUS_NUM, ADXL345_SDO_L_ADDR); */ std::ofstream logFileStream; //---------------------------- // // Set up shared memory space // sv = (shared_vars_t *) mmap(NULL, sizeof(shared_vars_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); sv->gDone = false; sv->gDispEnabled = true; sv->gLogFileEnabled = true; sv->iLoopPause = ITTER_LOOP_PAUSE; // // Open Log File // if (sv->gLogFileEnabled) { #define LOG_NAME_SZ 120 time_t now; char log_name[LOG_NAME_SZ] = {0}; // ------------- now = time(NULL); if (now == -1) { // ERROR HANDLING: you can check to see what went wrong perror("Failed to acquire date string for file in main"); exit(1); } //----- strftime(log_name, LOG_NAME_SZ, "./logs/easRV12_%d_%b_%Y_%H_%M_%S.log", gmtime(&now)); logFileStream.open(log_name, std::ofstream::out | std::ofstream::app); if (!logFileStream.good()) { // ERROR HANDLING perror("Failed to open the logfile in main"); std::cout << "Log File Name = " << log_name << std::endl; std::cout << "Errno = " << logFileStream << std::endl; std::cout << "Typical Cause - Log file directory does not exist" << std::endl; exit(1); } std::cout << std::endl << "Log File " << log_name << " opened." << std::endl; } // if enabled // // Setup TinyCon in Parallel Thread // int tc_pid = fork(); if (tc_pid == 0) { tcon tc(std::string("")); tc.run(); std::cout << std::endl << "TinyCom thread ShutDown."<< std::endl; return 0; } // // TODO: // Read Cal Data from all Sensors & Write to Log-File // // located HERE! // // Begin Repeated Loop // while (!sv->gDone) { clock_t t; EasDAQpack curPack[20]; int pack_i = 0; static unsigned int frc; //------------------------ // // Timestamp t = clock(); curPack[pack_i].blank(); curPack[pack_i++].setClockT(t); if (frc % 5 == 0) { // // Pressure & Temperature // baroSen.updateRawPressTemp(); baroSen.fillEASpack(curPack[pack_i++]); } // // Select Channel i2cMuxNum1.selectChan(PCA9544Mux :: CH_3); // // HSC Pressure Sensor // /* pressNum1.updatePressTemp(); pressNum1.fillEASpack(curPack[pack_i++]); */ // // Read from ADXL345 Num 1 // accelNum1.updateAccelData(); accelNum1.fillEASpack(curPack[pack_i++]); // // Read from ADXL345 Num 1 // accelNum2.updateAccelData(); accelNum2.fillEASpack(curPack[pack_i++]); humPress1.updateHumidPressTemp(); humPress1.fillEASpack(curPack[pack_i++]); // // Read from MPU6050 Num 3 // /*accGyrNum3.updateAccelGyroTempData(); accGyrNum3.fillEASpack(curPack[pack_i++]); */ /* // // Read from ADXL345 Num 2 // accelNum2.updateAccelData(); curPack[pack_i].blank(); accelNum2.fillEASpack(curPack[pack_i++]); // // Read from MPU6050 Num 3 // accGyrNum3.updateAccelGyroTempData(); curPack[pack_i].blank(); accGyrNum3.fillEASpack(curPack[pack_i++]); // // Select 02 i2cMuxNum1.selectChan(PCA9544Mux :: CH_2); // // Read from ADXL345 Num 4 // accelNum4.updateAccelData(); curPack[pack_i].blank(); accelNum4.fillEASpack(curPack[pack_i++]); // // Select 03 i2cMuxNum1.selectChan(PCA9544Mux :: CH_3); // // Read from ADXL345 Num 5 // accelNum5.updateAccelData(); curPack[pack_i].blank(); accelNum5.fillEASpack(curPack[pack_i++]); // // Read from ADXL345 Num 6 // accelNum6.updateAccelData(); curPack[pack_i].blank(); accelNum6.fillEASpack(curPack[pack_i++]); */ // // Log Data if (logFileStream.good()) { for (int i = 0; i < pack_i ; i++) curPack[i].outToFile(logFileStream); } // // Display Data once every DISP_INTERVAL // if ((sv->gDispEnabled) && ((frc % DISP_INTERVAL) == 0)) { for (int i = 0; i < pack_i ; i++) { std::cout << curPack[i] << std::endl; } } // Pause if (sv->iLoopPause != MIN_ILOOP) usleep(sv->iLoopPause); // // Clear Used Data Packs for (int i = 0; i < pack_i ; i++) curPack[pack_i].blank(); // // Increment FRC frc++; } // while // // For clean shutdown, make sure child processes close first. // // http://stackoverflow.com/questions/5057137/c-loop-while-child-is-alive int Stat; // Blocking while() while (waitpid(tc_pid, &Stat, WNOHANG) != tc_pid); if (WIFEXITED(Stat)) { std::cout << " parent: Child exited with exit code " << WEXITSTATUS(Stat) << std::endl; } else if (WIFSIGNALED(Stat)) { std::cout << " parent: Child killed with signal " << WTERMSIG(Stat) << std::endl; } else { std::cout << " parent: Something else happened to child, e.g. STOPPED" << std::endl; } // // Close Log File if (logFileStream.good()) { std::cout << " Closing Log File" << std::endl; logFileStream.close(); } // // Free shared memory space munmap((void *)sv, sizeof(shared_vars_t)); std::cout << " Exiting Primary Thread Normally..." << std::endl; return 0; } // main
void CFileBrowser::paintItem(unsigned int pos) { int colwidth1, colwidth2, colwidth3, colwidth1_dir, colwidth2_dir; uint8_t color; fb_pixel_t bgcolor; int ypos = y + theight + pos*fheight; CFile * actual_file = NULL; std::string fileicon; colwidth2_dir = 180; colwidth1_dir = width - 35 - colwidth2_dir - 10; if (liststart + pos == selected) { color = COL_MENUCONTENTSELECTED; bgcolor = COL_MENUCONTENTSELECTED_PLUS_0; } else { color = COL_MENUCONTENT;//DARK; bgcolor = COL_MENUCONTENT_PLUS_0;//DARK; } if( (liststart + pos) < filelist.size() ) { actual_file = &filelist[liststart + pos]; if (actual_file->Marked) { color = COL_MENUCONTENTINACTIVE; bgcolor = (liststart + pos == selected) ? COL_MENUCONTENTSELECTED_PLUS_2 : COL_MENUCONTENT_PLUS_2; } if (g_settings.filebrowser_showrights == 0 && S_ISREG(actual_file->Mode)) { colwidth2 = 0; colwidth3 = 90; } else { colwidth2 = 90; colwidth3 = 90; } colwidth1 = width - 35 - colwidth2 - colwidth3 - 10; frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, fheight, bgcolor); if ( actual_file->Name.length() > 0 ) { if (liststart + pos == selected) CVFD::getInstance()->showMenuText(0, FILESYSTEM_ENCODING_TO_UTF8_STRING(actual_file->getFileName()).c_str(), -1, true); // UTF-8 switch(actual_file->getType()) { case CFile::FILE_AUDIO: fileicon = NEUTRINO_ICON_MP3; break; case CFile::FILE_DIR: fileicon = NEUTRINO_ICON_FOLDER; break; case CFile::FILE_PICTURE: fileicon = NEUTRINO_ICON_PICTURE; break; case CFile::FILE_VIDEO: fileicon = NEUTRINO_ICON_MOVIE; break; case CFile::FILE_TEXT: default: fileicon = NEUTRINO_ICON_FILE; } int ih, iw; frameBuffer->getIconSize(fileicon.c_str(), &iw, &ih); frameBuffer->paintIcon(fileicon, x + ICON_OFFSET, ypos + (fheight - ih) / 2 ); g_Font[SNeutrinoSettings::FONT_TYPE_FILEBROWSER_ITEM]->RenderString(x + 30 + ICON_OFFSET, ypos + fheight, colwidth1 - BORDER_RIGHT, FILESYSTEM_ENCODING_TO_UTF8_STRING(actual_file->getFileName()), color, 0, true); // UTF-8 if( S_ISREG(actual_file->Mode) ) { if (g_settings.filebrowser_showrights != 0) { const char * attribute = "xwr"; char modestring[9 + 1]; for (int m = 8; m >= 0; m--) { modestring[8 - m] = (actual_file->Mode & (1 << m)) ? attribute[m % 3] : '-'; } modestring[9] = 0; g_Font[SNeutrinoSettings::FONT_TYPE_FILEBROWSER_ITEM]->RenderString(x + 35 + colwidth1 , ypos+ fheight, colwidth2 - 10, modestring, color, 0, true); // UTF-8 } #define GIGABYTE 1073741824LL #define MEGABYTE 1048576LL #define KILOBYTE 1024LL char tmpstr[256]; const char *unit = ""; long long factor = 0; if (actual_file->Size >= GIGABYTE) { factor = GIGABYTE; unit = "G"; } else if (actual_file->Size >= MEGABYTE) { factor = MEGABYTE; unit = "M"; } else if (actual_file->Size >= KILOBYTE) { factor = KILOBYTE; unit = "k"; } if (factor) { int a = actual_file->Size / factor; int b = (actual_file->Size - a * factor) * 1000 / factor; snprintf(tmpstr, sizeof(tmpstr), "%d.%03d%s", a, b, unit); } else snprintf(tmpstr,sizeof(tmpstr),"%d", (int)actual_file->Size); g_Font[SNeutrinoSettings::FONT_TYPE_FILEBROWSER_ITEM]->RenderString(x + 35 + colwidth1 + colwidth2, ypos+ fheight, colwidth3 - 10, tmpstr, color); } if( S_ISDIR(actual_file->Mode) ) { char timestring[18]; time_t rawtime; rawtime = actual_file->Time; strftime(timestring, 18, "%d-%m-%Y %H:%M", gmtime(&rawtime)); g_Font[SNeutrinoSettings::FONT_TYPE_FILEBROWSER_ITEM]->RenderString(x + 35 + colwidth1_dir, ypos+ fheight, colwidth2_dir - 10, timestring, color); } } } else frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, fheight, COL_MENUCONTENT_PLUS_0); }
struct tm * localtime(const time_t *timer) { return gmtime(timer); }
int main(int argc,char **argv) { time_t tval = time(NULL) ; /* seconds since "January 1st 1970 GMT" */ struct tm *timeptr ; /* full time structure */ char destpath[maxstring] ; /* destination path */ char filename[maxstring] ; /* full pathname */ int index ; /* general counter */ char *tptr ; /* temporary index */ FILE *outfile = stdout ; /* output the file */ destpath[0] = NULL ; /* NULL path by default */ /* parse the command line options */ for (index=1; (index < argc); index++) { if (argv[index][0] == '-') { switch (argv[index][1]) { case 'h' : case 'H' : /* help */ printf("%s (%s at %s)\n",whoami,__DATE__,__TIME__) ; printf("-h suitable help message\n") ; printf("-p path where \"%s\" files to be placed\n",cfile) ; exit(0) ; case 'p' : case 'P' : /* destination path */ { char *cptr ; if (argv[index][2] == '\0') cptr = argv[++index] ; else cptr = &argv[index][2] ; if (strlen(cptr) >= maxstring) { fprintf(stderr,"%s: path too long\n",whoami) ; exit(2) ; } else strcpy(destpath,cptr) ; } break ; default : /* unrecognised option */ fprintf(stderr,"%s: unrecognised option -%c\n",whoami,argv[index][1]) ; exit(1) ; break ; } } else { fprintf(stderr,"%s: unrecognised parameter \"%s\"\n",whoami,argv[index]) ; exit(1) ; } } if (destpath[0] == '\0') sprintf(filename,"%s",cfile) ; else sprintf(filename,"%s/%s",destpath,cfile) ; /* create the file */ if ((outfile = fopen(filename,"wb")) == NULL) { fprintf(stderr,"%s: cannot open outfile file \"%s\"\n",whoami,filename) ; exit(3) ; } timeptr = gmtime(&tval) ; /* output the file header */ fprintf(outfile,"\tTTL\tCreated by \"%s\"\t> %s\n\n",whoami,cfile) ; fprintf(outfile,"\tASSERT\t(listopts_s)\t; ensure listopt.s included\n") ; fprintf(outfile,"old_opt\tSETA\t{OPT}\n") ; fprintf(outfile,"\tOPT\t(opt_off)\n\n") ; fprintf(outfile,"\t\tGBLL\ttimedate_s\n") ; fprintf(outfile,"timedate_s\tSETL\t{TRUE}\n\n") ; fprintf(outfile,"\t; Time and Date variables\n") ; fprintf(outfile,"\tGBLA\tMakeTime\t; secs since 1st Jan 1970\n") ; fprintf(outfile,"\tGBLS\tMakeDate\t; full ANSI time and date\n") ; fprintf(outfile,"\tGBLS\tMakeDay\t\t; full weekday name\n") ; fprintf(outfile,"\tGBLS\tMakeMDay\t; month day\n") ; fprintf(outfile,"\tGBLS\tMakeMonth\t; full month name\n") ; fprintf(outfile,"\tGBLS\tMakeYear\t; full year number\n") ; fprintf(outfile,"\tGBLS\tMakeClock\t; 24hour clock\n\n") ; fprintf(outfile,"MakeTime\tSETA\t&%08X\n",tval) ; sprintf(destpath,"%s",ctime(&tval)) ; for (tptr = destpath; (*tptr && (*tptr != '\n')); tptr++) ; *tptr = '\0' ; /* replace newline with NULL */ fprintf(outfile,"MakeDate\tSETS\t\"%s\"\n",destpath) ; index = strftime(destpath,maxstring,"%A",timeptr) ; destpath[index] = '\0' ; fprintf(outfile,"MakeDay\t\tSETS\t\"%s\"\n",destpath) ; index = strftime(destpath,maxstring,"%d",timeptr) ; destpath[index] = '\0' ; fprintf(outfile,"MakeMDay\tSETS\t\"%s\"\n",destpath) ; index = strftime(destpath,maxstring,"%B",timeptr) ; destpath[index] = '\0' ; fprintf(outfile,"MakeMonth\tSETS\t\"%s\"\n",destpath) ; index = strftime(destpath,maxstring,"%Y",timeptr) ; destpath[index] = '\0' ; fprintf(outfile,"MakeYear\tSETS\t\"%s\"\n",destpath) ; index = strftime(destpath,maxstring,"%H:%M",timeptr) ; destpath[index] = '\0' ; fprintf(outfile,"MakeClock\tSETS\t\"%s\"\n",destpath) ; /* terminate the file cleanly */ fprintf(outfile,"\n\tOPT\t(old_opt)\n") ; fprintf(outfile,"\tEND\n") ; fclose(outfile) ; return(0) ; }
/* * The "tz" thing is passed in as this strange "decimal parse of tz" * thing, which means that tz -0100 is passed in as the integer -100, * even though it means "sixty minutes off" */ static struct tm *time_to_tm(unsigned long time, int tz) { time_t t = gm_time_t(time, tz); return gmtime(&t); }
static VALUE parse_date_time(const char *date) { VALUE ajd, offset; int year, month, day, hour, min, sec, usec, hour_offset, minute_offset; int jd; do_int64 num, den; long int gmt_offset; int is_dst; time_t rawtime; struct tm * timeinfo; int tokens_read, max_tokens; if ( strcmp(date, "") == 0 ) { return Qnil; } if (0 != strchr(date, '.')) { // This is a datetime with sub-second precision tokens_read = sscanf(date, "%4d-%2d-%2d%*c%2d:%2d:%2d.%d%3d:%2d", &year, &month, &day, &hour, &min, &sec, &usec, &hour_offset, &minute_offset); max_tokens = 9; } else { // This is a datetime second precision tokens_read = sscanf(date, "%4d-%2d-%2d%*c%2d:%2d:%2d%3d:%2d", &year, &month, &day, &hour, &min, &sec, &hour_offset, &minute_offset); max_tokens = 8; } if (max_tokens == tokens_read) { // We read the Date, Time, and Timezone info minute_offset *= hour_offset < 0 ? -1 : 1; } else if ((max_tokens - 1) == tokens_read) { // We read the Date and Time, but no Minute Offset minute_offset = 0; } else if (tokens_read == 3) { return parse_date(date); } else if (tokens_read >= (max_tokens - 3)) { // We read the Date and Time, default to the current locale's offset // Get localtime time(&rawtime); timeinfo = localtime(&rawtime); is_dst = timeinfo->tm_isdst * 3600; // Reset to GM Time timeinfo = gmtime(&rawtime); gmt_offset = mktime(timeinfo) - rawtime; if ( is_dst > 0 ) gmt_offset -= is_dst; hour_offset = -(gmt_offset / 3600); minute_offset = -(gmt_offset % 3600 / 60); } else { // Something went terribly wrong rb_raise(eMysqlError, "Couldn't parse date: %s", date); } jd = jd_from_date(year, month, day); // Generate ajd with fractional days for the time // Extracted from Date#jd_to_ajd, Date#day_fraction_to_time, and Rational#+ and #- num = (hour * 1440) + (min * 24); // Modify the numerator so when we apply the timezone everything works out num -= (hour_offset * 1440) + (minute_offset * 24); den = (24 * 1440); reduce(&num, &den); num = (num * 86400) + (sec * den); den = den * 86400; reduce(&num, &den); num = (jd * den) + num; num = num * 2; num = num - den; den = den * 2; reduce(&num, &den); ajd = rb_funcall(rb_cRational, rb_intern("new!"), 2, rb_ull2inum(num), rb_ull2inum(den)); offset = timezone_to_offset(hour_offset, minute_offset); return rb_funcall(rb_cDateTime, ID_NEW_DATE, 3, ajd, offset, INT2NUM(2299161)); }
static time_t parsedate(const char *date) { time_t t = 0; int wdaynum=-1; /* day of the week number, 0-6 (mon-sun) */ int monnum=-1; /* month of the year number, 0-11 */ int mdaynum=-1; /* day of month, 1 - 31 */ int hournum=-1; int minnum=-1; int secnum=-1; int yearnum=-1; int tzoff=-1; struct tm tm; enum assume dignext = DATE_MDAY; const char *indate = date; /* save the original pointer */ int part = 0; /* max 6 parts */ while(*date && (part < 6)) { bool found=FALSE; skip(&date); if(ISALPHA(*date)) { /* a name coming up */ char buf[32]=""; size_t len; sscanf(date, "%31[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]", buf); len = strlen(buf); if(wdaynum == -1) { wdaynum = checkday(buf, len); if(wdaynum != -1) found = TRUE; } if(!found && (monnum == -1)) { monnum = checkmonth(buf); if(monnum != -1) found = TRUE; } if(!found && (tzoff == -1)) { /* this just must be a time zone string */ tzoff = checktz(buf); if(tzoff != -1) found = TRUE; } if(!found) return -1; /* bad string */ date += len; } else if(ISDIGIT(*date)) { /* a digit */ int val; char *end; if((secnum == -1) && (3 == sscanf(date, "%02d:%02d:%02d", &hournum, &minnum, &secnum))) { /* time stamp! */ date += 8; found = TRUE; } else { val = (int)strtol(date, &end, 10); if((tzoff == -1) && ((end - date) == 4) && (val <= 1400) && (indate< date) && ((date[-1] == '+' || date[-1] == '-'))) { /* four digits and a value less than or equal to 1400 (to take into account all sorts of funny time zone diffs) and it is preceeded with a plus or minus. This is a time zone indication. 1400 is picked since +1300 is frequently used and +1400 is mentioned as an edge number in the document "ISO C 200X Proposal: Timezone Functions" at http://david.tribble.com/text/c0xtimezone.html If anyone has a more authoritative source for the exact maximum time zone offsets, please speak up! */ found = TRUE; tzoff = (val/100 * 60 + val%100)*60; /* the + and - prefix indicates the local time compared to GMT, this we need ther reversed math to get what we want */ tzoff = date[-1]=='+'?-tzoff:tzoff; } if(((end - date) == 8) && (yearnum == -1) && (monnum == -1) && (mdaynum == -1)) { /* 8 digits, no year, month or day yet. This is YYYYMMDD */ found = TRUE; yearnum = val/10000; monnum = (val%10000)/100-1; /* month is 0 - 11 */ mdaynum = val%100; } if(!found && (dignext == DATE_MDAY) && (mdaynum == -1)) { if((val > 0) && (val<32)) { mdaynum = val; found = TRUE; } dignext = DATE_YEAR; } if(!found && (dignext == DATE_YEAR) && (yearnum == -1)) { yearnum = val; found = TRUE; if(yearnum < 1900) { if(yearnum > 70) yearnum += 1900; else yearnum += 2000; } if(mdaynum == -1) dignext = DATE_MDAY; } if(!found) return -1; date = end; } } part++; } if(-1 == secnum) secnum = minnum = hournum = 0; /* no time, make it zero */ if((-1 == mdaynum) || (-1 == monnum) || (-1 == yearnum)) /* lacks vital info, fail */ return -1; #if SIZEOF_TIME_T < 5 /* 32 bit time_t can only hold dates to the beginning of 2038 */ if(yearnum > 2037) return 0x7fffffff; #endif tm.tm_sec = secnum; tm.tm_min = minnum; tm.tm_hour = hournum; tm.tm_mday = mdaynum; tm.tm_mon = monnum; tm.tm_year = yearnum - 1900; tm.tm_wday = 0; tm.tm_yday = 0; tm.tm_isdst = 0; /* mktime() returns a time_t. time_t is often 32 bits, even on many architectures that feature 64 bit 'long'. Some systems have 64 bit time_t and deal with years beyond 2038. However, even some of the systems with 64 bit time_t returns -1 for dates beyond 03:14:07 UTC, January 19, 2038. (Such as AIX 5100-06) */ t = mktime(&tm); /* time zone adjust (cast t to int to compare to negative one) */ if(-1 != (int)t) { struct tm *gmt; long delta; time_t t2; #ifdef HAVE_GMTIME_R /* thread-safe version */ struct tm keeptime2; gmt = (struct tm *)gmtime_r(&t, &keeptime2); if(!gmt) return -1; /* illegal date/time */ t2 = mktime(gmt); #else /* It seems that at least the MSVC version of mktime() doesn't work properly if it gets the 'gmt' pointer passed in (which is a pointer returned from gmtime() pointing to static memory), so instead we copy the tm struct to a local struct and pass a pointer to that struct as input to mktime(). */ struct tm gmt2; gmt = gmtime(&t); /* use gmtime_r() if available */ if(!gmt) return -1; /* illegal date/time */ gmt2 = *gmt; t2 = mktime(&gmt2); #endif /* Add the time zone diff (between the given timezone and GMT) and the diff between the local time zone and GMT. */ delta = (long)((tzoff!=-1?tzoff:0) + (t - t2)); if((delta>0) && (t + delta < t)) return -1; /* time_t overflow */ t += delta; } return t; }
struct tm * localtime(const time_t *time) { time_t t = *time + TIMEZONE_OFFSET; return gmtime(&t); }
/* In this function we assume that the file has been checked for * maliciousness (".."s, etc) and has been decoded */ void procsendhead(struct connstruct *cn) { char buf[MAXREQUESTLENGTH]; struct stat stbuf; time_t t_time; struct tm *ptm; char date[32]; char last_modified[32]; char expires[32]; int file_exists; /* are we trying to access a file over the HTTP connection instead of a * HTTPS connection? Or is this directory disabled? */ if (htaccess_check(cn)) { send_error(cn, 403); return; } #ifdef CONFIG_HTTP_HAS_AUTHORIZATION if (auth_check(cn)) { /* see if there is a '.htpasswd' file */ #ifdef CONFIG_HTTP_VERBOSE printf("axhttpd: access to %s denied\n", cn->filereq); TTY_FLUSH(); #endif removeconnection(cn); return; } #endif file_exists = stat(cn->actualfile, &stbuf); #if defined(CONFIG_HTTP_HAS_CGI) if (file_exists != -1 && cn->is_cgi) { proccgi(cn); return; } #endif /* look for "index.html"? */ if (isdir(cn->actualfile)) { char tbuf[MAXREQUESTLENGTH]; snprintf(tbuf, MAXREQUESTLENGTH, "%s%s", cn->actualfile, index_file); if ((file_exists = stat(tbuf, &stbuf)) != -1) my_strncpy(cn->actualfile, tbuf, MAXREQUESTLENGTH); else { #if defined(CONFIG_HTTP_DIRECTORIES) /* If not, we do a directory listing of it */ procdirlisting(cn); #else send_error(cn, 404); #endif return; } } if (file_exists == -1) { send_error(cn, 404); return; } time(&t_time); ptm = gmtime(&t_time); strftime(date, sizeof(date), rfc1123_format, ptm); /* has the file been read before? */ if (cn->if_modified_since != -1) { ptm = gmtime(&stbuf.st_mtime); t_time = mktime(ptm); if (cn->if_modified_since >= t_time) { snprintf(buf, sizeof(buf), HTTP_VERSION" 304 Not Modified\nServer: " "%s\nDate: %s\n\n", server_version, date); special_write(cn, buf, strlen(buf)); cn->state = STATE_WANT_TO_READ_HEAD; return; } } if (cn->reqtype == TYPE_HEAD) { removeconnection(cn); return; } else { int flags = O_RDONLY; #if defined(CONFIG_PLATFORM_CYGWIN) flags |= O_BINARY; #endif cn->filedesc = open(cn->actualfile, flags); if (cn->filedesc < 0) { send_error(cn, 404); return; } ptm = gmtime(&stbuf.st_mtime); strftime(last_modified, sizeof(last_modified), rfc1123_format, ptm); t_time += CONFIG_HTTP_TIMEOUT; ptm = gmtime(&t_time); strftime(expires, sizeof(expires), rfc1123_format, ptm); snprintf(buf, sizeof(buf), HTTP_VERSION" 200 OK\nServer: %s\n" "Content-Type: %s\nContent-Length: %ld\n" "Date: %s\nLast-Modified: %s\nExpires: %s\n\n", server_version, getmimetype(cn->actualfile), (long) stbuf.st_size, date, last_modified, expires); special_write(cn, buf, strlen(buf)); #ifdef CONFIG_HTTP_VERBOSE printf("axhttpd: %s:/%s\n", cn->is_ssl ? "https" : "http", cn->filereq); TTY_FLUSH(); #endif cn->state = STATE_WANT_TO_READ_FILE; } }
xml_schema::DateTime makeDateTime(const std::time_t& time) { struct tm *lt = gmtime(&time); return makeDateTime(*lt); }
int datetime_( char* sDate, char* sTime, char* zone, integer* values, ftnlen dateLen, ftnlen timeLen, ftnlen zoneLen ) { time_t t1; struct tm *now; struct tm localNow; struct tm utcNow; integer zoneTime; char temp[11]; /* allow room for terminating null */ int maxLen; int i; time( &t1 ); /* System time */ now = gmtime( &t1 ); /* format as struct in utc time */ utcNow = *now; now = localtime( &t1 ); /* format as struct in local time */ localNow = *now; /* Set up the values array */ values[0] = localNow.tm_year + 1900; values[1] = localNow.tm_mon + 1; values[2] = localNow.tm_mday; /* Handle non-whole hour timezones correctly; produce value in minutes */ values[3] = (localNow.tm_hour - utcNow.tm_hour) * 60; values[3] += localNow.tm_min - utcNow.tm_min; values[4] = localNow.tm_hour; values[5] = localNow.tm_min; values[6] = localNow.tm_sec; values[7] = 0; /* Fill in the date string */ strftime( temp, 11, "%Y%y%m%d", now ); /* use ANSI strftime to format */ /* Copy over at most the first 8 characters */ maxLen = (dateLen < 8) ? dateLen : 8; for ( i = 0; i < maxLen; i++ ) sDate[i] = temp[i]; /* Fill in the time string, zeroing out the milliseconds */ strftime( temp, 11, "%H%M%S", now ); temp[6] = '.'; temp[7] = temp[8] = temp[9] = '0'; /* Copy over at most the first 11 characters */ maxLen = (timeLen < 11) ? timeLen : 11; for ( i = 0; i < maxLen; i++ ) sTime[i] = temp[i]; /* Fill in the zone string */ /* ...Get sign */ if ( values[3] < 0 ) { temp[0] = '-'; zoneTime = -values[3]; // Force positive for following computations } else { temp[0] = '+'; zoneTime = values[3]; } /* ...Get hours */ sprintf( temp+1, "%2d", zoneTime/60 ); /* ...Get the minutes */ sprintf( temp+3, "%2d", zoneTime % 60 ); /* Copy over at most the first 5 characters */ maxLen = (zoneLen < 5) ? zoneLen : 5; for ( i = 0; i < maxLen; i++ ) zone[i] = temp[i]; return 1; }
bool FILTER::filterPacket(struct packet_structure packet, std::list<packet_structure> *packetList) { //Default answer is don't filter packet bool answer = false; //Structures for date and time time_t epoch_time = packet.epoch_time; struct tm *ptm = gmtime (&epoch_time); if(filterTime == true) { std::stringstream timeSs; timeSs << std::setfill('0'); //Time in readable format timeSs << std::setw(2) << static_cast<unsigned>(ptm->tm_hour); timeSs << ":"; timeSs << std::setw(2) << static_cast<unsigned>(ptm->tm_min); timeSs << ":"; timeSs << std::setw(2) << static_cast<unsigned>(ptm->tm_sec); //Checks if packet time within specified filter range if(startTime.compare(endTime) < 0) if((timeSs.str()).compare(startTime) < 0 || (timeSs.str()).compare(endTime) > 0) answer = true; //If start time is greater than end //It must extend into next day else if(startTime.compare(endTime) > 0) if((timeSs.str()).compare(startTime) > 0 || (timeSs.str()).compare(endTime) < 0) answer = true; else { if((timeSs.str()).compare(startTime) != 0) answer = true; } } if(filterDate == true && answer == false) { std::stringstream dateSs; dateSs << std::setfill('0'); //Date in readable format dateSs << std::setw(4) << static_cast<unsigned>(ptm->tm_year+1900); dateSs << "/"; dateSs << std::setw(2) << static_cast<unsigned>(ptm->tm_mon+1); dateSs << "/"; dateSs << std::setw(2) << static_cast<unsigned>(ptm->tm_mday); //Checks if it is with in the allowable filter date if(startDate.compare(endDate) < 0) if((dateSs.str()).compare(startDate) < 0 || (dateSs.str()).compare(endDate) > 0) answer = true; else if(startDate.compare(endDate) > 0) if((dateSs.str()).compare(startDate) > 0 || (dateSs.str()).compare(endDate) < 0) answer = true; else if((dateSs.str()).compare(startDate) != 0) answer = true; } if(filterDay == true && answer == false) { //Sets fiter to true answer = true; for(int i = 0; i <= (matchDays.size() - 1); i++) { //If packet day matches an allowed day //Filter is set back to false if(matchDays[i] == days[ptm->tm_wday]) { answer = false; break; } } } if(filterMonth == true && answer == false) { //Sets filter to true answer = true; for(int i = 0; i <= (matchMonths.size()-1); i++) { //If packet month matches an allowed month //Filter is set back to true if(matchMonths[i] == months[ptm->tm_mon]) { answer = false; break; } } } if(filterDbm == true && answer == false) { //Checks if dBm is within allowable filter rnage if(minDbm < packet.dbm || maxDbm > packet.dbm) answer=true; } if(uniqMac == true && answer == false) { //Checks packet MAC against all packets in the display filter list for(std::list<packet_structure>::iterator it = packetList->begin(); it != packetList->end(); it++) { if((it->mac).compare(packet.mac) == 0) { answer = true; break; } } } if( (blackList == true || whiteList == true) && answer == false) { if(whiteList == true) answer = true; //Checks packet MAC against all packets in the MAC list for(std::list<packet_structure>::iterator it = macList.begin(); it != macList.end(); it++) { if((it->mac).compare(packet.mac) == 0) { answer = !answer; //Tricky thinking break; } } } if( macMono == true && answer == false) { if((macAddr).compare(packet.mac) != 0) answer = true; } return answer; }
int main(int argc,char** argv) { time_t lt; lt = time(NULL); ptr = gmtime(<); printf(asctime(ptr)); // Greenwich Mean time (GMT) printf(ctime(<)); //local time CLHEP::HepRandom::setTheEngine(new CLHEP::RanecuEngine); G4long seed = time(NULL); CLHEP::HepRandom::setTheSeed(seed); G4RunManager* runManager = new G4RunManager; ProDetectorConstruction* detectorCon = new ProDetectorConstruction(); runManager->SetUserInitialization(detectorCon); PhysicsList* physics = new PhysicsList(); runManager->SetUserInitialization(physics); ProAnalysis * anly = new ProAnalysis(); // UserAction classes - optional G4VUserPrimaryGeneratorAction* generator = new ProPrimaryGeneratorAction(detectorCon); runManager->SetUserAction(generator); ProRunAction* RunAct = new ProRunAction(anly); runManager->SetUserAction(RunAct); ProEventAction* EvAct = new ProEventAction(RunAct,anly); runManager->SetUserAction(EvAct); runManager->Initialize(); #ifdef G4VIS_USE G4VisManager* visManager = new G4VisExecutive; visManager->Initialize(); #endif G4UImanager* uiManager = G4UImanager::GetUIpointer(); if(argc != 1){ G4String command = "/control/execute "; G4String fileName = argv[1]; uiManager->ApplyCommand(command+fileName); } else { #ifdef G4UI_USE G4UIExecutive* ui = new G4UIExecutive(argc,argv); #ifdef G4VIS_USE uiManager->ApplyCommand("/control/execute vis.mac"); #endif ui->SessionStart(); delete ui; #endif } //******************************************************************* G4cout<<" This is a Collimator Test which let neutrons having 180MeV " <<" pass through collimator, and two collimator detectors are " <<" used to record neutrons information" <<G4endl; //******************************************************************* #ifdef G4VIS_USE delete visManager; #endif delete anly; delete runManager; return 0; }
/** LB_notification callback - updates the status of each client @param lb_fd(in) - FD that event occcurred on @param msg_id(in) - message id that has changed @param msg_len(in) - message length @param user_data - user data, should be NULL */ void on_lb_change(int lb_fd, LB_id_t msg_id, int msg_len, void* user_data) { int retval; Prod_header* product; static char* file_name = NULL; char text[100]; struct tm* time; float elevation; int i; int rda_elev_indx; prod_count++; retval = LB_read(lb_fd, (void*)&product, LB_ALLOC_BUF, msg_id); if (retval >= 0) { LE_send_msg(GL_INFO, "Generated product id %d, msg id = %d\n", product->g.prod_id, msg_id); LE_send_msg(GL_INFO, "Product code = %d\n", ORPGPAT_get_code(product->g.prod_id)); LE_send_msg(GL_INFO, "Prod desc = %s\n", ORPGPAT_get_description(product->g.prod_id, STRIP_MNEMONIC)); LE_send_msg(GL_INFO, "Prod count = %d\n", prod_count); if (!select_product(ORPGPAT_get_code(product->g.prod_id))) { LE_send_msg(GL_INFO, "Product code %d not selected for extraction", ORPGPAT_get_code(product->g.prod_id)); return; } else LE_send_msg(GL_INFO, "Product code %d is selected for extraction", ORPGPAT_get_code(product->g.prod_id)); file_name = STR_copy(file_name, ORPGPAT_get_description(product->g.prod_id, STRIP_MNEMONIC)); for (i = 0; (i < strlen(file_name)); i++) { if ((isspace((int)file_name[i])) || (file_name[i] == ':') || (file_name[i] == '/')) file_name[i] = '_'; else if (file_name[i] == '.') file_name[i] = '.'; else if (!isalnum((int)file_name[i])) { file_name[i] = '\0'; break; } } rda_elev_indx = ORPGVST_get_rda_index(product->g.elev_ind); elevation = ((float)ORPGVST_get_elevation(rda_elev_indx)) / 10.0; LE_send_msg(GL_INFO, "Elev index = %d, rda elev indx = %d, elevation = %f", rda_elev_indx, product->g.elev_ind, elevation); if (ORPGPAT_get_type(product->g.prod_id) == 0) elevation = 0.0; sprintf(text, "_%2.1f", elevation); file_name = STR_cat(file_name, text); time = gmtime((const time_t*)&product->elev_t); sprintf(text, "_%4.4d%2.2d%2.2d_%2.2d%2.2d%2.2d", time->tm_year + 1900, time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec); file_name = STR_cat(file_name, text); LE_send_msg(GL_INFO, "File_name=%s\n", file_name); LE_send_msg(GL_INFO, "Size of msg=%d, size of product=%d\n", retval, product->g.len); if (product->g.len > 0) { LE_send_msg(GL_INFO, "Writing %s format\n", orpg_format?"ORPG":"ICD"); if (orpg_format) generate_output_file(file_name, ((char*)product), product->g.len); else generate_output_file(file_name, ((char*)product) + sizeof(Prod_header), product->g.len - sizeof(Prod_header)); if (index_name != NULL) generate_xml_string(product, file_name); } else LE_send_msg(GL_INFO, "Skip writing file %s because size is %d\n", file_name, product->g.len); free(product); } else LE_send_msg(GL_INFO, "Read error %d on msg id %d\n", retval, msg_id); }
void DownloadProgressView::_UpdateStatusText() { fInfoView->SetText(""); BString buffer; if (sShowSpeed && fBytesPerSecond != 0.0) { // Draw speed info char sizeBuffer[128]; buffer = "("; // Get strings for current and expected size and remove the unit // from the current size string if it's the same as the expected // size unit. BString currentSize = string_for_size((double)fCurrentSize, sizeBuffer, sizeof(sizeBuffer)); BString expectedSize = string_for_size((double)fExpectedSize, sizeBuffer, sizeof(sizeBuffer)); int currentSizeUnitPos = currentSize.FindLast(' '); int expectedSizeUnitPos = expectedSize.FindLast(' '); if (currentSizeUnitPos >= 0 && expectedSizeUnitPos >= 0 && strcmp(currentSize.String() + currentSizeUnitPos, expectedSize.String() + expectedSizeUnitPos) == 0) { currentSize.Truncate(currentSizeUnitPos); } buffer << currentSize; buffer << " "; buffer << B_TRANSLATE_COMMENT("of", "...as in '12kB of 256kB'"); buffer << " "; buffer << expectedSize; buffer << ", "; buffer << string_for_size(fBytesPerSecond, sizeBuffer, sizeof(sizeBuffer)); buffer << B_TRANSLATE_COMMENT("/s)", "...as in 'per second'"); float stringWidth = fInfoView->StringWidth(buffer.String()); if (stringWidth < fInfoView->Bounds().Width()) fInfoView->SetText(buffer.String()); else { // complete string too wide, try with shorter version buffer << string_for_size(fBytesPerSecond, sizeBuffer, sizeof(sizeBuffer)); buffer << B_TRANSLATE_COMMENT("/s)", "...as in 'per second'"); stringWidth = fInfoView->StringWidth(buffer.String()); if (stringWidth < fInfoView->Bounds().Width()) fInfoView->SetText(buffer.String()); } } else if (!sShowSpeed && fCurrentSize < fExpectedSize) { double totalBytesPerSecond = (double)(fCurrentSize - fEstimatedFinishReferenceSize) * 1000000LL / (system_time() - fEstimatedFinishReferenceTime); double secondsRemaining = (fExpectedSize - fCurrentSize) / totalBytesPerSecond; time_t now = (time_t)real_time_clock(); time_t finishTime = (time_t)(now + secondsRemaining); tm _time; tm* time = localtime_r(&finishTime, &_time); int32 year = time->tm_year + 1900; char timeText[32]; time_t secondsPerDay = 24 * 60 * 60; // TODO: Localization of time string... if (now < finishTime - secondsPerDay) { // process is going to take more than a day! sprintf(timeText, "%0*d:%0*d %0*d/%0*d/%ld", 2, time->tm_hour, 2, time->tm_min, 2, time->tm_mon + 1, 2, time->tm_mday, year); } else { sprintf(timeText, "%0*d:%0*d", 2, time->tm_hour, 2, time->tm_min); } BString buffer1(B_TRANSLATE_COMMENT("Finish: ", "Finishing time")); buffer1 << timeText; finishTime -= now; time = gmtime(&finishTime); BString buffer2; if (finishTime > secondsPerDay) { int64 days = finishTime / secondsPerDay; if (days == 1) buffer2 << B_TRANSLATE("Over 1 day left"); else { buffer2 << B_TRANSLATE("Over %days days left"); buffer2.ReplaceFirst("%days", BString() << days); } } else if (finishTime > 60 * 60) { int64 hours = finishTime / (60 * 60); if (hours == 1) buffer2 << B_TRANSLATE("Over 1 hour left"); else { buffer2 << B_TRANSLATE("Over %hours hours left"); buffer2.ReplaceFirst("%hours", BString() << hours); } } else if (finishTime > 60) { int64 minutes = finishTime / 60; if (minutes == 1) buffer2 << B_TRANSLATE("Over 1 minute left"); else { buffer2 << B_TRANSLATE("%minutes minutes"); buffer2.ReplaceFirst("%minutes", BString() << minutes); } } else { if (finishTime == 1) buffer2 << B_TRANSLATE("1 second left"); else { buffer2 << B_TRANSLATE("%seconds seconds left"); buffer2.ReplaceFirst("%seconds", BString() << finishTime); } } buffer = "("; buffer << buffer1 << " - " << buffer2 << ")"; float stringWidth = fInfoView->StringWidth(buffer.String()); if (stringWidth < fInfoView->Bounds().Width()) fInfoView->SetText(buffer.String()); else { // complete string too wide, try with shorter version buffer = "("; buffer << buffer1 << ")"; stringWidth = fInfoView->StringWidth(buffer.String()); if (stringWidth < fInfoView->Bounds().Width()) fInfoView->SetText(buffer.String()); } } }
void rspfLocalTm::setTimeNoAdjustmentGivenEpoc(time_t ticks) { *this = *gmtime(&ticks); }
static struct tm *gmtime_r(const time_t *tloc, struct tm *result) { struct tm *tm; if((tm = gmtime(tloc))) return memcpy(result, tm, sizeof(struct tm)); return 0; }
C_Int_t Date_Tm_getWDay(void) { return Date_tmOut->tm_wday; } C_Int_t Date_Tm_getYDay(void) { return Date_tmOut->tm_yday; } C_Int_t Date_Tm_getYear(void) { return Date_tmOut->tm_year; } void Date_Tm_setHour(C_Int_t x) { Date_tmIn.tm_hour = x; } void Date_Tm_setIsDst(C_Int_t x) { Date_tmIn.tm_isdst = x; } void Date_Tm_setMDay(C_Int_t x) { Date_tmIn.tm_mday = x; } void Date_Tm_setMin(C_Int_t x) { Date_tmIn.tm_min = x; } void Date_Tm_setMon(C_Int_t x) { Date_tmIn.tm_mon = x; } void Date_Tm_setSec(C_Int_t x) { Date_tmIn.tm_sec = x; } void Date_Tm_setWDay(C_Int_t x) { Date_tmIn.tm_wday = x; } void Date_Tm_setYDay(C_Int_t x) { Date_tmIn.tm_yday = x; } void Date_Tm_setYear(C_Int_t x) { Date_tmIn.tm_year = x; } C_Errno_t(C_Int_t) Date_gmTime(Ref(C_Time_t) p) { Date_tmOut = gmtime((time_t*)p); if (Date_tmOut == NULL) return -1; return 0; } /* The idea for Date_localOffset comes from KitV3 src/Runtime/Time.c */ C_Double_t Date_localOffset(void) { time_t t1, t2; t1 = time(NULL); t2 = mktime(gmtime(&t1)); return difftime(t2, t1); } C_Errno_t(C_Int_t) Date_localTime(Ref(C_Time_t) p) { Date_tmOut = localtime((time_t*)p);
/* Stores the current UTC time. Returns 0 on error. */ static int get_utc(struct connection *c) { time_t t; t = time(NULL); return strftime(c->con_time, MAXBUF, "%Y-%m-%d %H:%M:%S", gmtime(&t)); }
struct tm* GMTIME(const time_t *clock, tm *result) { struct tm* t = gmtime(clock); if (t == NULL || result == NULL) { return NULL; } *result = *t; return result; }
static void r_print_format_time(const RPrint* p, int endian, int mode, const char* setval, ut64 seeki, ut8* buf, int i, int size) { ut64 addr; int elem = -1; if (size >= ARRAYINDEX_COEF) { elem = size/ARRAYINDEX_COEF-1; size %= ARRAYINDEX_COEF; } updateAddr (buf, i, endian, &addr, NULL); if (MUSTSET) { p->cb_printf ("wv4 %s @ 0x%08"PFMT64x"\n", setval, seeki+((elem>=0)?elem*4:0)); } else if (MUSTSEE) { char *timestr = strdup(asctime (gmtime ((time_t*)&addr))); *(timestr+24) = '\0'; if (!SEEVALUE) p->cb_printf ("0x%08"PFMT64x" = ", seeki+((elem>=0)?elem*4:0)); if (size==-1) { p->cb_printf ("%s", timestr); } else { if (!SEEVALUE) p->cb_printf ("[ "); while (size--) { updateAddr (buf, i, endian, &addr, NULL); free (timestr); timestr = strdup (asctime (gmtime ((time_t*)&addr))); *(timestr+24) = '\0'; if (elem == -1 || elem == 0) { p->cb_printf ("%s", timestr); if (elem == 0) elem = -2; } if (size != 0 && elem == -1) p->cb_printf (", "); if (elem > -1) elem--; i += 4; } if (!SEEVALUE) p->cb_printf (" ]"); } free (timestr); } else if (MUSTSEEJSON) { char *timestr = strdup (asctime (gmtime ((time_t*)&addr))); *(timestr+24) = '\0'; if (size==-1) { p->cb_printf ("\"%s\"", timestr); } else { p->cb_printf ("[ "); while (size--) { updateAddr (buf, i, endian, &addr, NULL); free (timestr); timestr = strdup (asctime (gmtime ((time_t*)&addr))); *(timestr+24) = '\0'; if (elem == -1 || elem == 0) { p->cb_printf ("\"%s\"", timestr); if (elem == 0) elem = -2; } if (size != 0 && elem == -1) p->cb_printf (", "); if (elem > -1) elem--; i += 4; } p->cb_printf (" ]"); } free (timestr); p->cb_printf ("}"); } }
static void send_next_directory(struct ftpd_datastate *fsd, struct tcp_pcb *pcb, int shortlist) { char buffer[1024]; int len; while (1) { if (fsd->vfs_dirent == NULL) fsd->vfs_dirent = vfs_readdir(fsd->vfs_dir); if (fsd->vfs_dirent) { if (shortlist) { len = sprintf(buffer, "%s\r\n", fsd->vfs_dirent->name); if (sfifo_space(&fsd->fifo) < len) { send_data(pcb, fsd); return; } sfifo_write(&fsd->fifo, buffer, len); fsd->vfs_dirent = NULL; } else { vfs_stat_t st; time_t current_time; int current_year; struct tm *s_time; time(¤t_time); s_time = gmtime(¤t_time); current_year = s_time->tm_year; vfs_stat(fsd->msgfs->vfs, fsd->vfs_dirent->name, &st); s_time = gmtime(&st.st_mtime); if (s_time->tm_year == current_year) len = sprintf(buffer, "-rw-rw-rw- 1 user ftp %11ld %s %02i %02i:%02i %s\r\n", st.st_size, month_table[s_time->tm_mon], s_time->tm_mday, s_time->tm_hour, s_time->tm_min, fsd->vfs_dirent->name); else len = sprintf(buffer, "-rw-rw-rw- 1 user ftp %11ld %s %02i %5i %s\r\n", st.st_size, month_table[s_time->tm_mon], s_time->tm_mday, s_time->tm_year + 1900, fsd->vfs_dirent->name); if (VFS_ISDIR(st.st_mode)) buffer[0] = 'd'; if (sfifo_space(&fsd->fifo) < len) { send_data(pcb, fsd); return; } sfifo_write(&fsd->fifo, buffer, len); fsd->vfs_dirent = NULL; } } else { struct ftpd_msgstate *fsm; struct tcp_pcb *msgpcb; if (sfifo_used(&fsd->fifo) > 0) { send_data(pcb, fsd); return; } fsm = fsd->msgfs; msgpcb = fsd->msgpcb; vfs_closedir(fsd->vfs_dir); fsd->vfs_dir = NULL; ftpd_dataclose(pcb, fsd); fsm->datapcb = NULL; fsm->datafs = NULL; fsm->state = FTPD_IDLE; send_msg(msgpcb, fsm, msg226); return; } } }
static int create_type1(RECORD **anrecord) { ITEM *item = NULL; SUBFIELD *subfield = NULL; FIELD *field = NULL; RECORD *lrecord; // For local convenience char buf[32]; char *date_str; time_t tod; struct tm *tm; if (new_ANSI_NIST_record(anrecord, TYPE_1_ID) != 0) ALLOC_ERR_EXIT("Type-1 Record"); lrecord = *anrecord; /*** 1.001 Logical record length ***/ // Set the length to 0 for now; it will be updated when the record // is closed APPEND_TYPE1_FIELD(lrecord, LEN_ID, "0"); /*** 1.002 - Version number ***/ snprintf(buf, sizeof(buf), "%04d", VERSION_0300); APPEND_TYPE1_FIELD(lrecord, VER_ID, buf); /*** 1.003 - File content ***/ snprintf(buf, sizeof(buf), "%d", TYPE_1_ID); // Allocate a new subfield and set the first item if (value2subfield(&subfield, buf) != 0) ERR_OUT("allocating Type-1 subfield"); // Add the second item to the subfield, the count of remaining records if (value2item(&item, "0") != 0) ERR_OUT("allocating Type-1 item"); if (append_ANSI_NIST_subfield(subfield, item) != 0) ERR_OUT("appending Type-1 item"); // Add the subfield to the field if (new_ANSI_NIST_field(&field, TYPE_1_ID, CNT_ID) != 0) ERR_OUT("allocating Type-1 field"); if (append_ANSI_NIST_field(field, subfield) != 0) ERR_OUT("appending Type-1 subfield"); // Add the entire field to the record if (append_ANSI_NIST_record(lrecord, field) != 0) ERR_OUT("appending Type-1 field"); /*** 1.004 - Type of transaction ***/ APPEND_TYPE1_FIELD(lrecord, 4, "LFFS"); /*** 1.005 - Date ***/ if (get_ANSI_NIST_date(&date_str) != 0) ERR_OUT("getting ANSI/NIST date"); APPEND_TYPE1_FIELD(lrecord, DAT_ID, date_str); free(date_str); /*** 1.007 - Destination agency identifier ***/ APPEND_TYPE1_FIELD(lrecord, 7, "ANSI/NIST"); /*** 1.008 - Originating agency identifier ***/ APPEND_TYPE1_FIELD(lrecord, 8, "M1/FMR"); /*** 1.009 - Transaction control number ***/ // Use the current UTC time string YYYYMMDDHHMMSS tod = time(NULL); tm = gmtime(&tod); snprintf(buf, sizeof(buf), "%04d%02d%02d%02d%02d%02d", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); APPEND_TYPE1_FIELD(lrecord, 9, buf); /*** 1.011 - Native scanning resolution ***/ // XXX Set the NSR to the minimum, but we may want to base this // XXX value on something from the FMR snprintf(buf, sizeof(buf), "%5.2f", MIN_RESOLUTION); APPEND_TYPE1_FIELD(lrecord, 11, buf); /*** 1.012 - Nominal transmitting resolution ***/ APPEND_TYPE1_FIELD(lrecord, 12, buf); if (update_ANSI_NIST_tagged_record_LEN(lrecord) != 0) ERR_OUT("updating record length"); return 0; err_out: fprintf(stderr, "Error creating Type-1 record\n"); if (item != NULL) free_ANSI_NIST_item(item); if (subfield != NULL) free_ANSI_NIST_subfield(subfield); if (field != NULL) free_ANSI_NIST_field(field); if (lrecord != NULL) free_ANSI_NIST_record(lrecord); return -1; }
int main(int argc, char** argv) { uint32_t opt; int32_t rtl_result; int32_t rtl_count; char rtl_vendor[256], rtl_product[256], rtl_serial[256]; initrx_options(); initDecoder_options(); /* RX buffer allocation */ rx_state.iSamples=malloc(sizeof(float)*SIGNAL_LENGHT*SIGNAL_SAMPLE_RATE); rx_state.qSamples=malloc(sizeof(float)*SIGNAL_LENGHT*SIGNAL_SAMPLE_RATE); /* Stop condition setup */ rx_state.exit_flag = false; rx_state.decode_flag = false; uint32_t nLoop = 0; if (argc <= 1) usage(); while ((opt = getopt(argc, argv, "f:c:l:g:a:o:p:u:d:n:i:H:Q:S")) != -1) { switch (opt) { case 'f': // Frequency rx_options.dialfreq = (uint32_t)atofs(optarg); break; case 'c': // Callsign sprintf(dec_options.rcall, "%.12s", optarg); break; case 'l': // Locator / Grid sprintf(dec_options.rloc, "%.6s", optarg); break; case 'g': // Small signal amplifier gain rx_options.gain = atoi(optarg); if (rx_options.gain < 0) rx_options.gain = 0; if (rx_options.gain > 49) rx_options.gain = 49; rx_options.gain *= 10; break; case 'a': // Auto gain rx_options.autogain = atoi(optarg); if (rx_options.autogain < 0) rx_options.autogain = 0; if (rx_options.autogain > 1) rx_options.autogain = 1; break; case 'o': // Fine frequency correction rx_options.shift = atoi(optarg); break; case 'p': rx_options.ppm = atoi(optarg); break; case 'u': // Upconverter frequency rx_options.upconverter = (uint32_t)atofs(optarg); break; case 'd': // Direct Sampling rx_options.directsampling = (uint32_t)atofs(optarg); break; case 'n': // Stop after n iterations rx_options.maxloop = (uint32_t)atofs(optarg); break; case 'i': // Select the device to use rx_options.device = (uint32_t)atofs(optarg); break; case 'H': // Decoder option, use a hastable dec_options.usehashtable = 1; break; case 'Q': // Decoder option, faster dec_options.quickmode = 1; break; case 'S': // Decoder option, single pass mode (same as original wsprd) dec_options.subtraction = 0; dec_options.npasses = 1; break; default: usage(); break; } } if (rx_options.dialfreq == 0) { fprintf(stderr, "Please specify a dial frequency.\n"); fprintf(stderr, " --help for usage...\n"); exit(1); } if (dec_options.rcall[0] == 0) { fprintf(stderr, "Please specify your callsign.\n"); fprintf(stderr, " --help for usage...\n"); exit(1); } if (dec_options.rloc[0] == 0) { fprintf(stderr, "Please specify your locator.\n"); fprintf(stderr, " --help for usage...\n"); exit(1); } /* Calcule shift offset */ rx_options.realfreq = rx_options.dialfreq + rx_options.shift + rx_options.upconverter; /* Store the frequency used for the decoder */ dec_options.freq = rx_options.dialfreq; /* If something goes wrong... */ signal(SIGINT, &sigint_callback_handler); signal(SIGTERM, &sigint_callback_handler); signal(SIGILL, &sigint_callback_handler); signal(SIGFPE, &sigint_callback_handler); signal(SIGSEGV, &sigint_callback_handler); signal(SIGABRT, &sigint_callback_handler); /* Init & parameter the device */ rtl_count = rtlsdr_get_device_count(); if (!rtl_count) { fprintf(stderr, "No supported devices found\n"); return EXIT_FAILURE; } fprintf(stderr, "Found %d device(s):\n", rtl_count); for (uint32_t i=0; i<rtl_count; i++) { rtlsdr_get_device_usb_strings(i, rtl_vendor, rtl_product, rtl_serial); fprintf(stderr, " %d: %s, %s, SN: %s\n", i, rtl_vendor, rtl_product, rtl_serial); } fprintf(stderr, "\nUsing device %d: %s\n", rx_options.device, rtlsdr_get_device_name(rx_options.device)); rtl_result = rtlsdr_open(&rtl_device, rx_options.device); if (rtl_result < 0) { fprintf(stderr, "ERROR: Failed to open rtlsdr device #%d.\n", rx_options.device); return EXIT_FAILURE; } if (rx_options.directsampling) { rtl_result = rtlsdr_set_direct_sampling(rtl_device, rx_options.directsampling); if (rtl_result < 0) { fprintf(stderr, "ERROR: Failed to set direct sampling\n"); rtlsdr_close(rtl_device); return EXIT_FAILURE; } } rtl_result = rtlsdr_set_sample_rate(rtl_device, SAMPLING_RATE); if (rtl_result < 0) { fprintf(stderr, "ERROR: Failed to set sample rate\n"); rtlsdr_close(rtl_device); return EXIT_FAILURE; } rtl_result = rtlsdr_set_tuner_gain_mode(rtl_device, 1); if (rtl_result < 0) { fprintf(stderr, "ERROR: Failed to enable manual gain\n"); rtlsdr_close(rtl_device); return EXIT_FAILURE; } if (rx_options.autogain) { rtl_result = rtlsdr_set_tuner_gain_mode(rtl_device, 0); if (rtl_result != 0) { fprintf(stderr, "ERROR: Failed to set tuner gain\n"); rtlsdr_close(rtl_device); return EXIT_FAILURE; } } else { rtl_result = rtlsdr_set_tuner_gain(rtl_device, rx_options.gain); if (rtl_result != 0) { fprintf(stderr, "ERROR: Failed to set tuner gain\n"); rtlsdr_close(rtl_device); return EXIT_FAILURE; } } if (rx_options.ppm != 0) { rtl_result = rtlsdr_set_freq_correction(rtl_device, rx_options.ppm); if (rtl_result < 0) { fprintf(stderr, "ERROR: Failed to set ppm error\n"); rtlsdr_close(rtl_device); return EXIT_FAILURE; } } rtl_result = rtlsdr_set_center_freq(rtl_device, rx_options.realfreq + FS4_RATE + 1500); if (rtl_result < 0) { fprintf(stderr, "ERROR: Failed to set frequency\n"); rtlsdr_close(rtl_device); return EXIT_FAILURE; } rtl_result = rtlsdr_reset_buffer(rtl_device); if (rtl_result < 0) { fprintf(stderr, "ERROR: Failed to reset buffers.\n"); rtlsdr_close(rtl_device); return EXIT_FAILURE; } /* Print used parameter */ time_t rawtime; time ( &rawtime ); struct tm *gtm = gmtime(&rawtime); printf("\nStarting rtlsdr-wsprd (%04d-%02d-%02d, %02d:%02dz) -- Version 0.2\n", gtm->tm_year + 1900, gtm->tm_mon + 1, gtm->tm_mday, gtm->tm_hour, gtm->tm_min); printf(" Callsign : %s\n", dec_options.rcall); printf(" Locator : %s\n", dec_options.rloc); printf(" Dial freq. : %d Hz\n", rx_options.dialfreq); printf(" Real freq. : %d Hz\n", rx_options.realfreq); printf(" PPM factor : %d\n", rx_options.ppm); if(rx_options.autogain) printf(" Auto gain : enable\n"); else printf(" Gain : %d dB\n", rx_options.gain/10); /* Time alignment stuff */ struct timeval lTime; gettimeofday(&lTime, NULL); uint32_t sec = lTime.tv_sec % 120; uint32_t usec = sec * 1000000 + lTime.tv_usec; uint32_t uwait = 120000000 - usec; printf("Wait for time sync (start in %d sec)\n\n", uwait/1000000); /* Prepare a low priority param for the decoder thread */ struct sched_param param; pthread_attr_init(&dec.tattr); pthread_attr_setschedpolicy(&dec.tattr, SCHED_RR); pthread_attr_getschedparam(&dec.tattr, ¶m); param.sched_priority = 90; // = sched_get_priority_min(); pthread_attr_setschedparam(&dec.tattr, ¶m); /* Create a thread and stuff for separate decoding Info : https://computing.llnl.gov/tutorials/pthreads/ */ pthread_rwlock_init(&dec.rw, NULL); pthread_cond_init(&dec.ready_cond, NULL); pthread_mutex_init(&dec.ready_mutex, NULL); pthread_create(&dongle.thread, NULL, rtlsdr_rx, NULL); pthread_create(&dec.thread, &dec.tattr, wsprDecoder, NULL); /* Main loop : Wait, read, decode */ while (!rx_state.exit_flag && !(rx_options.maxloop && (nLoop >= rx_options.maxloop))) { /* Wait for time Sync on 2 mins */ gettimeofday(&lTime, NULL); sec = lTime.tv_sec % 120; usec = sec * 1000000 + lTime.tv_usec; uwait = 120000000 - usec + 10000; // Adding 10ms, to be sure to reach this next minute usleep(uwait); //printf("SYNC! RX started\n"); /* Use the Store the date at the begin of the frame */ time ( &rawtime ); gtm = gmtime(&rawtime); sprintf(rx_options.date,"%02d%02d%02d", gtm->tm_year - 100, gtm->tm_mon + 1, gtm->tm_mday); sprintf(rx_options.uttime,"%02d%02d", gtm->tm_hour, gtm->tm_min); /* Start to store the samples */ initSampleStorage(); while( (rx_state.exit_flag == false) && (rx_state.iqIndex < (SIGNAL_LENGHT * SIGNAL_SAMPLE_RATE) ) ) { usleep(250000); } nLoop++; } /* Stop the RX and free the blocking function */ rtlsdr_cancel_async(rtl_device); /* Close the RTL device */ rtlsdr_close(rtl_device); printf("Bye!\n"); /* Wait the thread join (send a signal before to terminate the job) */ pthread_mutex_lock(&dec.ready_mutex); pthread_cond_signal(&dec.ready_cond); pthread_mutex_unlock(&dec.ready_mutex); pthread_join(dec.thread, NULL); pthread_join(dongle.thread, NULL); /* Destroy the lock/cond/thread */ pthread_rwlock_destroy(&dec.rw); pthread_cond_destroy(&dec.ready_cond); pthread_mutex_destroy(&dec.ready_mutex); pthread_exit(NULL); return EXIT_SUCCESS; }
/* * pcf_poll - called by the transmit procedure */ static void pcf_poll( int unit, struct peer *peer ) { struct refclockproc *pp; char buf[LENPCF]; struct tm tm, *tp; time_t t; pp = peer->procptr; buf[0] = 0; if (read(pp->io.fd, buf, sizeof(buf)) < (ssize_t)sizeof(buf) || buf[0] != 9) { refclock_report(peer, CEVNT_FAULT); return; } ZERO(tm); tm.tm_mday = buf[11] * 10 + buf[10]; tm.tm_mon = buf[13] * 10 + buf[12] - 1; tm.tm_year = buf[15] * 10 + buf[14]; tm.tm_hour = buf[7] * 10 + buf[6]; tm.tm_min = buf[5] * 10 + buf[4]; tm.tm_sec = buf[3] * 10 + buf[2]; tm.tm_isdst = (buf[8] & 1) ? 1 : (buf[8] & 2) ? 0 : -1; /* * Y2K convert the 2-digit year */ if (tm.tm_year < 99) tm.tm_year += 100; t = mktime(&tm); if (t == (time_t) -1) { refclock_report(peer, CEVNT_BADTIME); return; } #if defined(__GLIBC__) && defined(_BSD_SOURCE) if ((tm.tm_isdst > 0 && tm.tm_gmtoff != 7200) || (tm.tm_isdst == 0 && tm.tm_gmtoff != 3600) || tm.tm_isdst < 0) { #ifdef DEBUG if (debug) printf ("local time zone not set to CET/CEST\n"); #endif refclock_report(peer, CEVNT_BADTIME); return; } #endif pp->lencode = strftime(pp->a_lastcode, BMAX, "%Y %m %d %H %M %S", &tm); #if defined(_REENTRANT) || defined(_THREAD_SAFE) tp = gmtime_r(&t, &tm); #else tp = gmtime(&t); #endif if (!tp) { refclock_report(peer, CEVNT_FAULT); return; } get_systime(&pp->lastrec); pp->polls++; pp->year = tp->tm_year + 1900; pp->day = tp->tm_yday + 1; pp->hour = tp->tm_hour; pp->minute = tp->tm_min; pp->second = tp->tm_sec; pp->nsec = buf[16] * 31250000; if (buf[17] & 1) pp->nsec += 500000000; #ifdef DEBUG if (debug) printf ("pcf%d: time is %04d/%02d/%02d %02d:%02d:%02d UTC\n", unit, pp->year, tp->tm_mon + 1, tp->tm_mday, pp->hour, pp->minute, pp->second); #endif if (!refclock_process(pp)) { refclock_report(peer, CEVNT_BADTIME); return; } record_clock_stats(&peer->srcadr, pp->a_lastcode); if ((buf[1] & 1) && !(pp->sloppyclockflag & CLK_FLAG2)) pp->leap = LEAP_NOTINSYNC; else pp->leap = LEAP_NOWARNING; pp->lastref = pp->lastrec; refclock_receive(peer); }
/*----------------------------------------------------------------------------*/ static int HandleReadEvent(struct thread_context *ctx, int sockid, struct server_vars *sv) { struct mtcp_epoll_event ev; char buf[HTTP_HEADER_LEN]; char url[URL_LEN]; char response[HTTP_HEADER_LEN]; int scode; // status code time_t t_now; char t_str[128]; char keepalive_str[128]; int rd; int i; int len; int sent; /* HTTP request handling */ rd = mtcp_read(ctx->mctx, sockid, buf, HTTP_HEADER_LEN); if (rd <= 0) { return rd; } memcpy(sv->request + sv->recv_len, (char *)buf, MIN(rd, HTTP_HEADER_LEN - sv->recv_len)); sv->recv_len += rd; //sv->request[rd] = '\0'; //fprintf(stderr, "HTTP Request: \n%s", request); sv->request_len = find_http_header(sv->request, sv->recv_len); if (sv->request_len <= 0) { TRACE_ERROR("Socket %d: Failed to parse HTTP request header.\n" "read bytes: %d, recv_len: %d, " "request_len: %d, strlen: %ld, request: \n%s\n", sockid, rd, sv->recv_len, sv->request_len, strlen(sv->request), sv->request); return rd; } http_get_url(sv->request, sv->request_len, url, URL_LEN); TRACE_APP("Socket %d URL: %s\n", sockid, url); sprintf(sv->fname, "%s%s", www_main, url); TRACE_APP("Socket %d File name: %s\n", sockid, sv->fname); sv->keep_alive = FALSE; if (http_header_str_val(sv->request, "Connection: ", strlen("Connection: "), keepalive_str, 128)) { if (strstr(keepalive_str, "Keep-Alive")) { sv->keep_alive = TRUE; } else if (strstr(keepalive_str, "Close")) { sv->keep_alive = FALSE; } } /* Find file in cache */ scode = 404; for (i = 0; i < nfiles; i++) { if (strcmp(sv->fname, fcache[i].fullname) == 0) { sv->fsize = fcache[i].size; sv->fidx = i; scode = 200; break; } } TRACE_APP("Socket %d File size: %ld (%ldMB)\n", sockid, sv->fsize, sv->fsize / 1024 / 1024); /* Response header handling */ time(&t_now); strftime(t_str, 128, "%a, %d %b %Y %X GMT", gmtime(&t_now)); if (sv->keep_alive) sprintf(keepalive_str, "Keep-Alive"); else sprintf(keepalive_str, "Close"); sprintf(response, "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Server: Webserver on Middlebox TCP (Ubuntu)\r\n" "Content-Length: %ld\r\n" "Connection: %s\r\n\r\n", scode, StatusCodeToString(scode), t_str, sv->fsize, keepalive_str); len = strlen(response); TRACE_APP("Socket %d HTTP Response: \n%s", sockid, response); sent = mtcp_write(ctx->mctx, sockid, response, len); TRACE_APP("Socket %d Sent response header: try: %d, sent: %d\n", sockid, len, sent); assert(sent == len); sv->rspheader_sent = TRUE; ev.events = MTCP_EPOLLIN | MTCP_EPOLLOUT; ev.data.sockid = sockid; mtcp_epoll_ctl(ctx->mctx, ctx->ep, MTCP_EPOLL_CTL_MOD, sockid, &ev); SendUntilAvailable(ctx, sockid, sv); return rd; }
/*! * \brief Supervisor task. * * \return never */ static portTASK_FUNCTION( vSupervisorTask, pvParameters ) { portTickType xDelayLength = SUPERVISOR_DEFAULT_PERIOD; portTickType xLastFocusTime; #if configHEAP_INIT == 1 #if defined(__GNUC__) portLONG lCheckHeapDelay = 1; #endif #endif #if configCTRLPANEL_TRACE == 1 portLONG lPrintTrace = 3; #endif portLONG lUpdateTimeDelay = 1; #ifdef MMILCD_ENABLE portLONG lUpdateMMITimeDelay = 1; portCHAR DateTime[21]; struct tm *pxDate; bool ms_connected_displayed = pdFALSE; bool enum_connected_displayed = pdFALSE; #endif /* The parameters are not used. */ ( void )pvParameters; #if configCTRLPANEL_TRACE == 1 /* Initialize the dump port COM2. */ itracedump_Init(); #endif #ifdef MMILCD_ENABLE // The MMI module. if( pdFALSE == bMMI_start() ) { // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } #endif // Create the SHELL mutex. vSemaphoreCreateBinary( xSHELLFSMutex ); if( NULL == xSHELLFSMutex ) { // The mutex creation failed. // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } // Start the COM1 Shell module. vStartCom1Shell( mainCOMSH_TASK_PRIORITY ); // Create the CFG mutex. vSemaphoreCreateBinary( xCFGMutex ); if( NULL == xCFGMutex ) { // The mutex creation failed. // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } // Start the sensor module. if( false == bsensor_start() ) { // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } #if NW_INTEGRATED_IN_CONTROL_PANEL // Create the Web server mutex. vSemaphoreCreateBinary( xWEBMutex ); if( NULL == xWEBMutex ) { // The mutex creation failed. // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } // Start network tasks. vStartEthernetTaskLauncher( tskIDLE_PRIORITY + 1 ); #endif // Create the LOG mutex. vSemaphoreCreateBinary( xLOGMutex ); if( NULL == xLOGMutex ) { // The mutex creation failed. // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } // Start the data logger module. if( false == bdatalog_start( mainDATALOG_TASK_PRIORITY ) ) { // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } #ifdef USB_ENABLE #if USB_DEVICE_FEATURE == true // Create the USB mutex. vSemaphoreCreateBinary( xUSBMutex ); if( NULL == xUSBMutex ) { // The mutex creation failed. // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } // Immediately take the USB mutex. i.e. when we're a Mass Storage device, // we'll refuse to give r/w access to the host until a user action. This user // action will make the Ctrl Panel device switch to maintenance mode, in which // the Mass Storage USB host has r/w access to the Ctrl Panel file system. while( pdFALSE == x_supervisor_SemaphoreTake( xUSBMutex, 0 ) ); #endif // Start the USB module tasks. if( false == b_usbsys_start() ) { // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } #endif #ifdef MMILCD_ENABLE // Create the supervisor queue to deal with MMI actions xSUPERVISORQueue = xQueueCreate( SUPERVISOR_QUEUE_SIZE, sizeof(bool *) ); if( 0 == xSUPERVISORQueue ) { // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } /* Get a File System navigator for MMI actions. */ fsaccess_take_mutex(); sMmiNavId = fsaccess_alloc_nav_id(); nav_select( sMmiNavId ); // Select the navigator. fsaccess_give_mutex(); /* Spawn the User Action task. */ if( pdPASS != xTaskCreate( vSupervisorUserActionTask, ( const signed portCHAR * )"MMIACT", SUPERVISOR_USER_ACTION_STACK_SIZE, NULL, SUPERVISOR_USER_ACTION_TASK_PRIORITY, &xSupervisorUserActionHndl ) ) { vTaskDelete( xSupervisorUserActionHndl ); // TODO: Add msg on LCD. // vParTestSetLED( ERROR_LED_ID, pdTRUE ); while( 1 ); } #endif // #ifdef MMILCD_ENABLE /* We need to initialise xLastFlashTime prior to the first call to vTaskDelayUntil(). */ xLastFocusTime = xTaskGetTickCount(); #if defined(__GNUC__) NAKED_TRACE_COM2( "heap start @=%d, heap end @=%d", \ (portBASE_TYPE *)&__heap_start__, \ (portBASE_TYPE *)&__heap_end__ ); #endif /* Enable the watchdog timer. */ // wdt_enable( SUPERVISOR_WDT_TIMEOUT ); for(;;) { /* Delay for the flash period then check. */ vTaskDelayUntil( &xLastFocusTime, xDelayLength ); // wdt_clear(); // Kick the watchdog! /* MMI USB management. */ #ifdef MMILCD_ENABLE #ifdef USB_ENABLE /*** Start of Host behaviour ***/ // first occurrence of MS connection, Host mode if (ms_connected == true && ms_connected_displayed == pdFALSE) { // display connected logo ms_connected_displayed = pdTRUE; vMMI_DisplayUSBState(ms_connected_displayed); // Display User Menu vMMI_SetUserMenuMode(eUserMenuUSBHost, pdTRUE); } // first occurrence of MS disconnection, end of Host mode if (ms_connected == false && ms_connected_displayed == pdTRUE) { // remove connected logo ms_connected_displayed = pdFALSE; vMMI_DisplayUSBState(ms_connected_displayed); // clear User Menu vMMI_SetUserMenuMode(eUserMenuIdle, pdTRUE); } /*** End of Host behaviour ***/ /*** Start of Device behaviour ***/ #if USB_DEVICE_FEATURE == true // first occurrence of Device connection, Device mode if (Is_device_enumerated() && ( enum_connected_displayed == pdFALSE ) ) { if( true == bIsInMaintenance ) { // display connected logo enum_connected_displayed = pdTRUE; vMMI_DisplayUSBState(enum_connected_displayed); // Display User Menu vMMI_SetUserMenuMode(eUserMenuUSBDevice, pdTRUE); } } // first occurrence of Device disconnection, end of Device mode else if (!Is_device_enumerated() && enum_connected_displayed == pdTRUE) { // remove connected logo enum_connected_displayed = pdFALSE; vMMI_DisplayUSBState(enum_connected_displayed); // clear User Menu vMMI_SetUserMenuMode(eUserMenuIdle, pdTRUE); } else { // remove connected logo => this makes the USB logo blink when the Control // Panel is behaving as a USB key. enum_connected_displayed = pdFALSE; vMMI_DisplayUSBState(enum_connected_displayed); } /*** End of Device behaviour ***/ #endif // #if USB_DEVICE_FEATURE == true #endif // #ifdef USB_ENABLE #endif // #ifdef MMILCD_ENABLE /* update time every SUPERVISOR_DELAY_TIMEUPDATE seconds. */ if( 0 == --lUpdateTimeDelay ) { /* Update the local time. */ lUpdateTimeDelay = SUPERVISOR_DELAY_TIMEUPDATE; xcptime_LocalTime++; // v_cptime_UpdateLocalTime(); } #ifdef MMILCD_ENABLE /* Update time displayed on the LCD. */ if( 0 == --lUpdateMMITimeDelay) { // Get the broken-down representation of the current date. pxDate = gmtime( &xcptime_LocalTime ); // WARNING: pxDate->tm_year == number of years since 1900. // For years >= 2000, we'll display the last 2 digits only. if( pxDate->tm_year >= 100 ) pxDate->tm_year -= 100; #if DISPLAY_MMI_SECOND == 1 sprintf( DateTime, "%02d/%02d/20%02d %02d:%02d:%02d", pxDate->tm_mon +1, pxDate->tm_mday, pxDate->tm_year, pxDate->tm_hour, pxDate->tm_min, pxDate->tm_sec ); #else sprintf( DateTime, "%02d/%02d/20%02d %02d:%02d", pxDate->tm_mon +1, pxDate->tm_mday, pxDate->tm_year, pxDate->tm_hour, pxDate->tm_min ); #endif vMMI_DisplayDateAndTime(DateTime); lUpdateMMITimeDelay = SUPERVISOR_DELAY_MMI_TIMEUPDATE; } // Manage MMI vMMI_Manage(); // Manage MMI user action prv_v_manage_user_action(); #endif // #ifdef MMILCD_ENABLE #ifdef USB_ENABLE if( true == bOutOfMaintenance ) { prv_v_leave_maintenance_mode(); } #endif /* Execute a scheduled command if expiration date is up. */ v_cptime_ExecuteScheduledCmd(); #if configHEAP_INIT == 1 #if defined(__GNUC__) /* Record the malloc() heap highest consumption every SUPERVISOR_DELAY_HEAPCHECK seconds. */ if( 0 == --lCheckHeapDelay ) { lCheckHeapDelay = SUPERVISOR_DELAY_HEAPCHECK; prvCheckMallocHeap(); } #endif #endif #if configCTRLPANEL_TRACE == 1 // Display traces on USART1 every SUPERVISOR_DELAY_PRINTTASKLIST seconds. if( 0 == --lPrintTrace ) { lPrintTrace = SUPERVISOR_DELAY_PRINTTASKLIST; // Restart the delay. v_syscmds_display_traces(); } #endif } // for(;;) } /*lint !e715 !e818 !e830 Function definition must be standard for task creation. */
static size_t smtp_payload_source(void * ptr, size_t size, size_t nmemb, void * userp) { struct upload_status *upload_ctx = (struct upload_status *)userp; char * data = NULL; size_t len = 0; if ((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { return 0; } if (upload_ctx->lines_read == MAIL_DATE) { time_t now; time(&now); data = malloc(128*sizeof(char)); if (data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Ulfius - Error allocating memory for MAIL_DATE\n"); return 0; } else { strftime(data, 128, "Date: %a, %d %b %Y %T %z\r\n", gmtime(&now)); len = strlen(data); } } else if (upload_ctx->lines_read == MAIL_TO) { data = msprintf("To: %s\r\n", upload_ctx->to); if (data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Ulfius - Error allocating memory for MAIL_TO\n"); return 0; } len = strlen(data); } else if (upload_ctx->lines_read == MAIL_FROM) { data = msprintf("From: %s\r\n", upload_ctx->from); if (data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Ulfius - Error allocating memory for MAIL_FROM\n"); return 0; } len = strlen(data); } else if (upload_ctx->lines_read == MAIL_CC && upload_ctx->cc) { data = msprintf("Cc: %s\r\n", upload_ctx->cc); if (data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Ulfius - Error allocating memory for MAIL_CC\n"); return 0; } len = strlen(data); } else if (upload_ctx->lines_read == MAIL_SUBJECT) { data = msprintf("Subject: %s\r\n", upload_ctx->subject); if (data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Ulfius - Error allocating memory for MAIL_SUBJECT\n"); return 0; } len = strlen(data); } else if (upload_ctx->lines_read == MAIL_DATA) { data = msprintf("Content-Type: text/plain; charset=utf-8\r\n\r\n%s\r\n", upload_ctx->data); if (data == NULL) { y_log_message(Y_LOG_LEVEL_ERROR, "Ulfius - Error allocating memory for MAIL_DATA\n"); return 0; } len = strlen(data); } if (upload_ctx->lines_read != MAIL_END) { memcpy(ptr, data, (len+1)); upload_ctx->lines_read++; // Skip next if it's cc and there is no cc if (upload_ctx->lines_read == MAIL_CC && !upload_ctx->cc) { upload_ctx->lines_read++; } free(data); return len; } else if (upload_ctx->lines_read == MAIL_END) { return 0; } y_log_message(Y_LOG_LEVEL_ERROR, "Ulfius - Error setting mail payload, len is %d, lines_read is %d", len, upload_ctx->lines_read); return 0; }
static void calculate_speed(struct progress_bar *prog, unsigned long long copied, unsigned long long current, int done, prog_stat_t *prog_stat){ char *format = "%H:%M:%S"; uint64_t speedps = 1; uint64_t speed = 1; double dspeed = 1.0; float percent = 1.0; time_t remained; time_t elapsed; char Rformated[12], Eformated[12]; char speed_unit[] = " "; struct tm *Rtm, *Etm; uint64_t gbyte=1000000000.0; uint64_t mbyte=1000000; uint64_t kbyte=1000; percent = prog->unit * copied; if (percent <= 0) percent = 1; else if (percent >= 100) percent = 99.99; elapsed = (time(0) - prog->initial_time); if (elapsed <= 0) elapsed = 1; speedps = prog->block_size * copied / elapsed; speed = speedps * 60.0; prog_stat->percent = percent; if (speed >= gbyte){ dspeed = (double)speed / (double)gbyte; strncpy(speed_unit, "GB", 3); strncpy(prog_stat->speed_unit, speed_unit, 3); }else if (speed >= mbyte){ dspeed = (double)speed / (double)mbyte; strncpy(speed_unit, "MB", 3); strncpy(prog_stat->speed_unit, speed_unit, 3); }else if (speed >= kbyte){ dspeed = (double)speed / (double)kbyte; strncpy(speed_unit, "KB", 3); strncpy(prog_stat->speed_unit, speed_unit, 3); }else{ dspeed = speed; strncpy(speed_unit, "byte", 5); strncpy(prog_stat->speed_unit, speed_unit, 5); } prog_stat->total_percent = prog->total_unit * current; prog_stat->speed = dspeed; if (done != 1){ remained = (time_t)((elapsed/percent*100) - elapsed); if ((unsigned int)remained > 86400){ snprintf(Rformated, sizeof(Rformated), " > %3i hrs ", ((int)remained/3600)); }else{ Rtm = gmtime(&remained); strftime(Rformated, sizeof(Rformated), format, Rtm); } if ((unsigned int)elapsed > 86400){ snprintf(Eformated, sizeof(Eformated), " > %3i hrs ", ((int)elapsed/3600)); }else{ Etm = gmtime(&elapsed); strftime(Eformated, sizeof(Eformated), format, Etm); } } else { prog_stat->percent=100; remained = (time_t)0; Rtm = gmtime(&remained); strftime(Rformated, sizeof(Rformated), format, Rtm); if ((unsigned int)elapsed > 86400){ snprintf(Eformated, sizeof(Eformated), " > %3i hrs ", ((int)elapsed/3600)); }else{ Etm = gmtime(&elapsed); strftime(Eformated, sizeof(Eformated), format, Etm); } } strncpy(prog_stat->Eformated, Eformated, sizeof(prog_stat->Eformated)); strncpy(prog_stat->Rformated, Rformated, sizeof(prog_stat->Rformated)); }
// a cacheTime of -1 means browser should not cache at all void HttpMime::makeMime ( int32_t totalContentLen , int32_t cacheTime , time_t lastModified , int32_t offset , int32_t bytesToSend , char *ext , bool POSTReply , char *contentType , char *charset , int32_t httpStatus , char *cookie ) { // assume UTF-8 //if ( ! charset ) charset = "utf-8"; // . make the content type line // . uses a static buffer if ( ! contentType ) contentType = (char *)getContentTypeFromExtension ( ext ); // do not cache plug ins if ( contentType && strcmp(contentType,"application/x-xpinstall")==0) cacheTime = -2; // assume UTF-8, but only if content type is text // . No No No!!! // . This prevents charset specification in html files // . -partap //if ( ! charset && contentType && strncmp(contentType,"text",4)==0) // charset = "utf-8"; // this is used for bz2 and gz files (mp3?) const char *contentEncoding = getContentEncodingFromExtension ( ext ); // the string char enc[128]; if ( contentEncoding ) sprintf ( enc , "Content-Encoding: %s\r\n", contentEncoding ); else enc[0] = '\0'; // get the time now //time_t now = getTimeGlobal(); time_t now; if ( isClockInSync() ) now = getTimeGlobal(); else now = getTimeLocal(); // get the greenwhich mean time (GMT) char ns[128]; struct tm *timeStruct = gmtime ( &now ); // Wed, 20 Mar 2002 16:47:30 GMT strftime ( ns , 126 , "%a, %d %b %Y %T GMT" , timeStruct ); // if lastModified is 0 use now if ( lastModified == 0 ) lastModified = now; // convert lastModified greenwhich mean time (GMT) char lms[128]; timeStruct = gmtime ( &lastModified ); // Wed, 20 Mar 2002 16:47:30 GMT strftime ( lms , 126 , "%a, %d %b %Y %T GMT" , timeStruct ); // . the pragma no cache string (used just for proxy servers?) // . also use cache-control: for the browser itself (HTTP1.1, though) // . pns = "Pragma: no-cache\nCache-Control: no-cache\nExpires: -1\n"; char tmp[128]; char *pns ; // with cache-control on, when you hit the back button, it reloads // the page, this is bad for most things... so we only avoid the // cache for index.html and PageAddUrl.cpp (the main and addurl page) if ( cacheTime == -2 ) pns = "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n" "Expires: -1\r\n"; // so when we click on a control link, it responds correctly. // like turning spiders on. else if ( cacheTime == -1 ) pns = "Pragma: no-cache\r\n" "Expires: -1\r\n"; // don't specify cache times if it's 0 (let browser regulate it) else if ( cacheTime == 0 ) pns = ""; // otherwise, expire tag: "Expires: Wed, 23 Dec 2001 10:23:01 GMT" else { time_t expDate = now + cacheTime; timeStruct = gmtime ( &expDate ); strftime ( tmp , 100 , "Expires: %a, %d %b %Y %T GMT\r\n", timeStruct ); pns = tmp; } // . set httpStatus // . a reply to a POST (not a GET or HEAD) should be 201 char *p = m_buf; char *smsg = ""; if ( POSTReply ) { if ( httpStatus == -1 ) httpStatus = 200; if ( httpStatus == 200 ) smsg = " OK"; if ( ! charset ) charset = "utf-8"; //sprintf ( m_buf , p += sprintf ( p, "HTTP/1.0 %"INT32"%s\r\n" "Date: %s\r\n" //"P3P: CP=\"CAO PSA OUR\"\r\n" "Access-Control-Allow-Origin: *\r\n" "Server: Gigablast/1.0\r\n" "Content-Length: %"INT32"\r\n" //"Expires: Wed, 23 Dec 2003 10:23:01 GMT\r\n" //"Expires: -1\r\n" "Connection: Close\r\n" "%s" "Content-Type: %s\r\n", //"Connection: Keep-Alive\r\n" //"%s" //"Location: f**k\r\n" //"Location: http://192.168.0.4:8000/cgi/3.cgi\r\n" //"Last-Modified: %s\r\n\r\n" , httpStatus , smsg , ns , totalContentLen , enc , contentType ); //pns , //ns ); //lms ); } // . is it partial content? // . if bytesToSend is < 0 it means "totalContentLen" else if ( offset > 0 || bytesToSend != -1 ) { if ( httpStatus == -1 ) httpStatus = 206; if ( ! charset ) charset = "utf-8"; //sprintf ( m_buf , p += sprintf( p, "HTTP/1.0 %"INT32" Partial content\r\n" "%s" "Content-Length: %"INT32"\r\n" "Content-Range: %"INT32"-%"INT32"(%"INT32")\r\n"// added "bytes" "Connection: Close\r\n" //"P3P: CP=\"CAO PSA OUR\"\r\n" // for ajax support "Access-Control-Allow-Origin: *\r\n" "Server: Gigablast/1.0\r\n" "%s" "Date: %s\r\n" "Last-Modified: %s\r\n" "Content-Type: %s\r\n", httpStatus , enc ,bytesToSend , offset , offset + bytesToSend , totalContentLen , pns , ns , lms , contentType ); // otherwise, do a normal mime } else { char encoding[256]; if (charset) sprintf(encoding, "; charset=%s", charset); else encoding[0] = '\0'; if ( httpStatus == -1 ) httpStatus = 200; if ( httpStatus == 200 ) smsg = " OK"; //sprintf ( m_buf , p += sprintf( p, "HTTP/1.0 %"INT32"%s\r\n" , httpStatus , smsg ); // if content length is not known, as in diffbot.cpp, then // do not print it into the mime if ( totalContentLen >= 0 ) p += sprintf ( p , // make it at least 4 spaces so we can // change the length of the content // should we insert a login bar in // Proxy::storeLoginBar() "Content-Length: %04"INT32"\r\n" , totalContentLen ); p += sprintf ( p , "%s" "Content-Type: %s", enc , contentType ); if ( charset ) p += sprintf ( p , "; charset=%s", charset ); p += sprintf ( p , "\r\n"); p += sprintf ( p , //"Connection: Keep-Alive\r\n" "Connection: Close\r\n" //"P3P: CP=\"CAO PSA OUR\"\r\n" "Access-Control-Allow-Origin: *\r\n" "Server: Gigablast/1.0\r\n" "%s" "Date: %s\r\n" "Last-Modified: %s\r\n" , pns , ns , lms ); } // write the cookie if we have one if (cookie) { // now it is a list of Set-Cookie: x=y\r\n lines //p += sprintf ( p, "Set-Cookie: %s\r\n", cookie); if ( strncmp(cookie,"Set-Cookie",10 ) ) p += sprintf(p,"Set-Cookie: "); p += sprintf ( p, "%s", cookie); if ( p[-1] != '\n' && p[-2] != '\r' ) { *p++ = '\r'; *p++ = '\n'; } } // write another line to end the mime p += sprintf(p, "\r\n"); // set the mime's length //m_bufLen = gbstrlen ( m_buf ); m_bufLen = p - m_buf; }