/* * initializes sd card and reads config file */ void initSDCard() { int retVal=0; int timeout = 0; DWORD P1; // if(sdcInitDone) //init procedure already started // return; // Thread wird sowieso beendet curFileID=-99; //Set output Pins for LEDs DDR03_D7 = 1; //Read (Pin 16) DDR03_D6 = 1; //Write (Pin 15) PDR03_P7 = 1; PDR03_P6 = 1; mmc_initPorts(); // Seg_Hex(0xC); //wait for card to be inserted while(mmc_getCardStatus() > 0) //it is 0 if we have a card { //return after 10 sec if(timeout > 20) return; #ifdef SDCARD_DEBUG printf("waiting for card.. \r\n"); #endif os_wait(500); timeout++; } // Seg_Hex(0xF); os_wait(200); //initialize card retVal=mmc_init(); os_wait(200); //mount FAT file system P1=0; f_mount((BYTE)P1, &fatfs[P1]); if(curFileID==-99) //has not been set SetCurrentFileID(1,1); sdcInitDone=1; //read configuration file from sd card readConfigFromFile(); Seg_Hex(0x00); }
// ------------------------------------------------ // Function: ping() // ------------------------------------------------ // Input: Destination IP // Network interface ID // Output: TRUE if server alive // ------------------------------------------------ // Description: Computers ICMP message checksum // ------------------------------------------------ BOOL ping(IPV4 ip, BYTE interface) { BYTE retry; retry = 0; while(retry < MAX_PING) { ping_request(ip, interface); os_set_timeout(TIMEOUT_PING); if(os_wait(SIG_ICMP)) return TRUE; retry++; } return FALSE; }
void resumeDriving(int16_t len) { #ifdef MAPPINGCONTROLLER_DEBUG printf("Waiting 500ms before continuing\r\n"); os_wait(500); printf("Resuming driving %d\r\n", len); #endif // drive straight ahead to avoid edges drive_setSteeringAngleBalanced(0); driveLen(len); // restart CrossingAnalyzer and WallFollow startCrossingAnalyzer(); startWallFollow(2, 0); }
void gslog_task() { int i, y, loglines, linelength, winlines, lwin0, lwin1; #define LINE_SIZE_MAX 128 char line[LINE_SIZE_MAX]; struct gs_win_t *win; while (!gs_initialized()) os_wait_ms(10); win = gs_win_create(GSLOG_WIN_POSX, GSLOG_WIN_POSY, GSLOG_WIN_WIDTH, GSLOG_WIN_HEIGHT); if (!win) { dprint("sn", ERR_PREFIX "Failed to create log window"); os_wait(OS_WAIT_FOREVER); } gs_win_set_border(win, 1, GS_COLOR_WHITE); gs_win_refresh(win); winlines = (GSLOG_WIN_HEIGHT - (GSLOG_PADY * 2)) / GSLOG_FONT->height; linelength = (GSLOG_WIN_WIDTH - (GSLOG_PADX * 2)) / GSLOG_FONT->width; while (1) { os_event_wait(&slog_event, SLOG_EVENT_MASK_UPDATE, OS_FLAG_CLEAR, OS_WAIT_FOREVER); loglines = slog_lines(); lwin0 = 0; if (loglines > winlines) lwin0 = loglines - winlines; lwin1 = loglines - 1; for (y = 0, i = lwin0; i <= lwin1; i++) { memset(line, ' ', linelength); slog_get_line(line, LINE_SIZE_MAX, i); line[strlen(line)] = ' '; line[linelength] = 0; gs_text_put(win, line, GSLOG_PADX, GSLOG_PADY + y, GSLOG_FONT_COLOR, win->bgcolor.value, GSLOG_FONT); y += GSLOG_FONT->height; } gs_win_refresh(win); } }
/* event_wait -- Waits until events become available. Returns handler of first available event. Also wait for console input if <console> is true. */ at * event_wait(int console) { at *hndl = 0; int cinput = 0; int toggle = 1; block_async_poll(); for (;;) { int n, ms1, ms2; struct poll_functions *src; if ((hndl = ev_peek())) break; ms1 = call_spoll(); if ((hndl = ev_peek())) break; /* Check for console input */ hndl = NIL; if (console && cinput) break; /* Check timer every other time */ ms2 = 0; if (console) toggle ^= 1; if (toggle || !console) { ms2 = timer_fire(); if ((hndl = ev_peek())) break; } /* Really wait */ n = 0; for (src=sources; src; src=src->next) if (src->fd>0 && n<MAXFDS) sourcefds[n++] = src->fd; call_bwait(); cinput = os_wait(n, sourcefds, console, (ms1<ms2) ? ms1 : ms2 ); } unblock_async_poll(); LOCK(hndl); return hndl; }
/* int Start_win32_Syscheck() * syscheck main for windows */ int Start_win32_Syscheck() { int r = 0; char *cfg = DEFAULTCPATH; /* Zeroing the structure */ syscheck.workdir = DEFAULTDIR; /* Checking if the configuration is present */ if(File_DateofChange(cfg) < 0) ErrorExit(NO_CONFIG, ARGV0, cfg); /* Read syscheck config */ if((r = Read_Syscheck_Config(cfg)) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } /* Disabled */ else if((r == 1) || (syscheck.disabled == 1)) { if(!syscheck.dir) { merror(SK_NO_DIR, ARGV0); dump_syscheck_entry(&syscheck, "", 0, 0, NULL); } else if(!syscheck.dir[0]) { merror(SK_NO_DIR, ARGV0); } syscheck.dir[0] = NULL; if(!syscheck.registry) { dump_syscheck_entry(&syscheck, "", 0, 1, NULL); } syscheck.registry[0] = NULL; merror("%s: WARN: Syscheck disabled.", ARGV0); } /* Reading internal options */ read_internal(); /* Rootcheck config */ if(rootcheck_init(0) == 0) { syscheck.rootcheck = 1; } else { syscheck.rootcheck = 0; merror("%s: WARN: Rootcheck module disabled.", ARGV0); } /* Printing options */ r = 0; while(syscheck.registry[r] != NULL) { verbose("%s: INFO: Monitoring registry entry: '%s'.", ARGV0, syscheck.registry[r]); r++; } r = 0; while(syscheck.dir[r] != NULL) { verbose("%s: INFO: Monitoring directory: '%s'.", ARGV0, syscheck.dir[r]); r++; } /* Start up message */ verbose(STARTUP_MSG, ARGV0, getpid()); /* Some sync time */ sleep(syscheck.tsleep + 10); /* Waiting if agent started properly. */ os_wait(); start_daemon(); exit(0); }
/* syscheck main for Windows */ int Start_win32_Syscheck() { int debug_level = 0; int r = 0; char *cfg = DEFAULTCPATH; /* Read internal options */ read_internal(debug_level); debug1(STARTED_MSG, ARGV0); /* Check if the configuration is present */ if (File_DateofChange(cfg) < 0) { ErrorExit(NO_CONFIG, ARGV0, cfg); } /* Read syscheck config */ if ((r = Read_Syscheck_Config(cfg)) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } else if ((r == 1) || (syscheck.disabled == 1)) { /* Disabled */ if (!syscheck.dir) { merror(SK_NO_DIR, ARGV0); dump_syscheck_entry(&syscheck, "", 0, 0, NULL); } else if (!syscheck.dir[0]) { merror(SK_NO_DIR, ARGV0); } syscheck.dir[0] = NULL; if (!syscheck.registry) { dump_syscheck_entry(&syscheck, "", 0, 1, NULL); } syscheck.registry[0].entry = NULL; merror("%s: WARN: Syscheck disabled.", ARGV0); } /* Rootcheck config */ if (rootcheck_init(0) == 0) { syscheck.rootcheck = 1; } else { syscheck.rootcheck = 0; merror("%s: WARN: Rootcheck module disabled.", ARGV0); } /* Print options */ r = 0; while (syscheck.registry[r].entry != NULL) { verbose("%s: INFO: Monitoring registry entry: '%s%s'.", ARGV0, syscheck.registry[r].entry, syscheck.registry[r].arch == ARCH_64BIT ? " [x64]" : ""); r++; } /* Print directories to be monitored */ r = 0; while (syscheck.dir[r] != NULL) { char optstr[ 100 ]; verbose("%s: INFO: Monitoring directory: '%s', with options %s.", ARGV0, syscheck.dir[r], syscheck_opts2str(optstr, sizeof( optstr ), syscheck.opts[r])); r++; } /* Print ignores. */ if(syscheck.ignore) for (r = 0; syscheck.ignore[r] != NULL; r++) verbose("%s: INFO: ignoring: '%s'", ARGV0, syscheck.ignore[r]); /* Print files with no diff. */ if (syscheck.nodiff){ r = 0; while (syscheck.nodiff[r] != NULL) { verbose("%s: INFO: No diff for file: '%s'", ARGV0, syscheck.nodiff[r]); r++; } } /* Start up message */ verbose(STARTUP_MSG, ARGV0, getpid()); /* Some sync time */ sleep(syscheck.tsleep + 10); /* Wait if agent started properly */ os_wait(); start_daemon(); exit(0); }
/** * Dreht das Auto auf der Stelle um 12°, nutzt die Radumdrehungen als Messwert * Input: Drehrichtung (Links/Rechts), Fahrtrichtung (Vorwärts/Rückwärts) */ void turn12(uint8_t repeats, uint8_t align, uint8_t firstDirection) { uint8_t i = 0; // uint8_t repeats = 4; // uint8_t time_wait = 100; // uint16_t time_forward = 400; // uint16_t time_backward = 280; int16_t help; int8_t factor_speed = 1; uint16_t turns; int8_t factor_direction = 1; // updateDriveTime(); turn_Active = TRUE; if (align != 1){ factor_speed = -1; // factor = 1 means right, = -1 means left } if (firstDirection != TRUE) { factor_direction = -1; // factor = 1 means forwards, = -1 means backwards help = time_forward; time_forward = time_backward; // swap values time_backward = help; } Drive_SetMotor(0); // turns by driving forward/backward and turning the wheels for (i=0; i < repeats; i++) { os_wait(100); Drive_SetServo(-100*factor_speed); os_wait(100); turns = totalDistance; //Fahre Rückwärts if (Us_Data.Rear_Distance > 10){ if ( i == repeats-1 && repeats != 1) turns+=3; while (turns+1 > totalDistance) drive(-2,-100*factor_speed,500); os_wait(100); Drive_SetServo(-100*factor_speed); os_wait(100); } turns = totalDistance; //Fahre Vorwärts if (Us_Data.Front_Distance > 10){ if ( i == repeats-1 && repeats != 1) turns-=1; while (turns+5 > totalDistance) drive(2,100*factor_speed,500); } Drive_SetServo(0); Drive_SetMotor(0); } distance = wheel_turns; drive(0,0,0); Drive_SetMotor(0); Drive_SetServo(0); os_wait(100); turn_Active = FALSE; }
/* * set drive parameters from driveParameterBuffer if new parameters are available, * otherwise stop the car when specified duration expires for security reasons */ static void driveTask(void) { portTickType duration_ms = 0, directionPercent = 0, currentTime = 0, lastWakeTime = 0, startTime = 0; driveParameters par; int8_t queueReturnValue, speed = 0; double Ergebnis[3]; gps_reducedData_t *own; lastWakeTime = os_getTime(); for (;;) { // calls[6]++; #ifdef SLAM_SCENARIO os_frequency(&lastWakeTime, 1); #else os_frequency(&lastWakeTime, 60); #endif currentTime = os_getTime(); //get new drive commands from queue queueReturnValue = xQueueReceive(driveParameterBuffer, &par, 10); if (queueReturnValue == pdTRUE) { directionPercent = par.direction; speed = par.speed; startTime = par.startTime; duration_ms = par.duration; } if (hall != start){ start = !start; if (os_getTime() - driveTime > 400){ distance++; #ifdef SLAM_SCENARIO Drive_SetMotor(0); os_wait(200); own = get_ownCoords(); SLAM_Algorithm((int32_t)CoordinatesToMap((int32_t)own->x),(int32_t)CoordinatesToMap((int32_t)own->y),(int32_t)uint16DegreeRelativeToX(own->angle),get_accumulateSteeringAngle()/MAX_STEERING_ANGLE, (int32_t) HALL_RESOLUTION, Ergebnis); // send_Element(22); // send_Element((int16_t)Ergebnis[0]); // send_Element((int16_t)Ergebnis[1]); // send_Element(-1); set_ownCoords(MapToCoordinates((int16_t)Ergebnis[0]),MapToCoordinates((int16_t)Ergebnis[1]),MapToCoordinates((int16_t)Ergebnis[2])); accumulateSteeringAngle(INT_LEAST8_MAX); #endif } } //set speed and direction if specified duration not expired, else stop the car if (duration_ms < 600){ if (currentTime - startTime < duration_ms) { #ifdef DEBUG2 printf("\nDRIVE\nset motor speed to %d and angle to %d\n\r", speed, directionPercent); #endif Drive_SetServo(directionPercent); Drive_SetMotor(speed); driveDistance(); } else { Drive_SetMotor(0); //stop if time period expired; distance = 0; realdistance = 0; } } else{ Drive_SetServo(directionPercent); Drive_SetMotor(speed); if (speed == 0){ distance = 0; realdistance = 0; } driveDistance(); } } }
void MappingControllerThread(void) { int16_t backLength; // the distance to the center of a crossing int16_t w_right, w_left, w_front, w_rear; // the widths of a crossing // needed for collecting us sensor data for the information about edges int8_t us_pos = 0; uint8_t wait_period = 1; int8_t k = 1; map_node_info node_info; // info about the crossing that shall be saved in the map for (;;) { // Seg_Hex(0x8); os_wait(250); // description of the algorithm for collecting this data: // for every edge each 10 ( = NUMBER_US_VALUES) values of us left and right sensor data // shall be saved. Therefore the array us_values is filled alternately with // left (even positions) and right (odd positions) us sensor data. If the array is full, // every second value will be deleted and afterwards only every second measured // us sensor data is saved in the array to keep the distance between two values constant. // and so on. // --> The array will always be at least half-full and contain us sensor values with // equal distances between them. if (k == wait_period && getWidthFront()==0) { // collect us values for edge information if (us_pos < 2 * NUMBER_US_VALUES) { us_values[us_pos] = Us_Data.Left_Distance; // even value: left us_values[us_pos + 1] = Us_Data.Right_Distance; // odd value: right us_pos += 2; } else { // take every second value and increment the wait period // the array is half-full afterwards uint8_t n; for (n = 0; n < NUMBER_US_VALUES; n += 2) { us_values[n] = us_values[2 * n]; us_values[n + 1] = us_values[2 * n + 1]; } us_pos /= 2; wait_period = wait_period<<=1; // wait_period * 2 } k = 1; // reset k } else k++; // --------------------- // START of crossing if (getCrossingStarted() == 1) { uint8_t edge_length; // calculate length of last edge edge_length = calculateDrivenLen(os_getTime() - getTimeEdgeOld()); // add edge to map and increase the currentNodeNumber addEdge(currentNodeNumber, ++currentNodeNumber, edge_length); // reset value resetCrossingStarted(); } // --------------------- // END of crossing if (getCrossingDetected() == 0) continue; #ifdef MAPPINGCONTROLLER_DEBUG printf("Crossing detected, MappingController is handling it...\r\n"); #endif stopCrossingAnalyzer(); stopWallFollow(); // get the widths and add this information to the node info w_left = getWidthLeft(); w_right = getWidthRight(); w_front = getWidthFront(); w_rear = getWidthRear(); node_info.w0 = w_front; node_info.w1 = w_left; node_info.w2 = w_rear; node_info.w3 = w_right; // Filter open doors etc. // the width of a corridor must be bigger than 40cm if (w_front < 40) w_front = 0; if (w_rear < 40) w_rear = 0; if (w_left < 40) w_left = 0; if (w_right < 40) w_right = 0; // Drive backwards to center of crossing if (w_left != 0 && w_right != 0) backLength = (w_right + w_left) / 4; else backLength = (w_right + w_left) / 2; if (backLength == 0) // dead end backLength = 20; if (w_rear == 0) backLength -= 20; backLength *= -1; // backwards driving #ifdef MAPPINGCONTROLLER_DEBUG printf("Driving %dcm\r\n", backLength); #endif driveLen(backLength); // Handle different crossing types // width_front = direction the car came from // width_rear = direction the car was heading to // side_end: 1: coming up, 2: left, 3: straight, 4: right // add information about the edge to the map and resume driving if (w_left == 0 && w_right == 0 && w_front != 0 && w_rear == 0) { noteCrossing(DeadEnd); addEdgeInfo(last_edge_side, 1, NUMBER_US_VALUES, us_values); last_edge_side = 1; node_info.crossing_type = DeadEnd; turn180(RIGHT, BACKWARDS); resumeDriving(0); } else if (w_left != 0 && w_right == 0 && w_front != 0 && w_rear != 0) { noteCrossing(LeftStraight); addEdgeInfo(last_edge_side, 3, NUMBER_US_VALUES, us_values); last_edge_side = 3; node_info.crossing_type = LeftStraight; // Behavior: drive straight ahead! resumeDriving(w_left / 2 + 50); } else if (w_left == 0 && w_right != 0 && w_front != 0 && w_rear != 0) { noteCrossing(RightStraight); addEdgeInfo(last_edge_side, 4, NUMBER_US_VALUES, us_values); last_edge_side = 4; node_info.crossing_type = RightStraight; turn90(RIGHT, BACKWARDS); resumeDriving(w_rear / 2 + 50); } else if (w_left == 0 && w_right != 0 && w_front != 0 && w_rear == 0) { noteCrossing(RightOnly); addEdgeInfo(last_edge_side, 4, NUMBER_US_VALUES, us_values); last_edge_side = 4; node_info.crossing_type = RightOnly; turn90(RIGHT, BACKWARDS); resumeDriving(w_rear / 2 + 50); } else if (w_left != 0 && w_right == 0 && w_front != 0 && w_rear == 0) { noteCrossing(LeftOnly); addEdgeInfo(last_edge_side, 2, NUMBER_US_VALUES, us_values); last_edge_side = 2; node_info.crossing_type = LeftOnly; turn90(LEFT, BACKWARDS); resumeDriving(w_rear / 2 + 50); } else if (w_left != 0 && w_right != 0 && w_front != 0 && w_rear == 0) { noteCrossing(LeftRight); addEdgeInfo(last_edge_side, 2, NUMBER_US_VALUES, us_values); last_edge_side = 2; node_info.crossing_type = LeftRight; turn90(LEFT, BACKWARDS); resumeDriving(w_rear / 2 + 50); } else if (w_left != 0 && w_right != 0 && w_front != 0 && w_rear != 0) { noteCrossing(All); addEdgeInfo(last_edge_side, 3, NUMBER_US_VALUES, us_values); last_edge_side = 3; node_info.crossing_type = All; // Behavior: drive straight ahead! resumeDriving(w_left / 2 + 50); } else { // dunno resumeDriving(0); } // add information about the current node addNodeInfo(currentNodeNumber, node_info); // reset values for (k = 0; k < 2 * NUMBER_US_VALUES; k++) { us_values[k] = 0; } } }
/** * Kick off the daap server and wait for events. * * This starts the initial db scan, sets up the signal * handling, starts the webserver, then sits back and waits * for events, as notified by the signal handler and the * web interface. These events are communicated via flags * in the config structure. * * \param argc count of command line arguments * \param argv command line argument pointers * \returns 0 on success, -1 otherwise * * \todo split out a ws_init and ws_start, so that the * web space handlers can be registered before the webserver * starts. * */ int main(int argc, char *argv[]) { int option; char *configfile=CONFFILE; WSCONFIG ws_config; int reload=0; int start_time; int end_time; int rescan_counter=0; int old_song_count, song_count; int force_non_root=0; int skip_initial=1; int kill_server=0; int convert_conf=0; char *db_type,*db_parms,*web_root,*runas, *tmp; char **mp3_dir_array; char *servername, *iface; char *ffid = NULL; int appdir = 0; char *perr=NULL; char txtrecord[255]; void *phandle; char *plugindir; int err; char *apppath; int debuglevel=0; int plugins_loaded = 0; #ifdef ALPHA_CUSTOMIZE char *share_path; pthread_t thread1; #endif config.use_mdns=1; err_setlevel(2); config.foreground=0; while((option=getopt(argc,argv,"D:d:c:P:mfrysiuvab:Vk")) != -1) { switch(option) { case 'a': appdir = 1; break; case 'b': ffid=optarg; break; case 'd': debuglevel = atoi(optarg); err_setlevel(debuglevel); break; case 'D': if(err_setdebugmask(optarg)) { usage(argv[0]); exit(EXIT_FAILURE); } break; case 'f': config.foreground=1; err_setdest(err_getdest() | LOGDEST_STDERR); break; case 'c': configfile=optarg; break; case 'm': config.use_mdns=0; break; #ifndef WIN32 case 'P': os_set_pidfile(optarg); break; #endif case 'r': reload=1; break; case 's': skip_initial=0; break; case 'y': force_non_root=1; break; #ifdef WIN32 case 'i': os_register(); exit(EXIT_SUCCESS); break; case 'u': os_unregister(); exit(EXIT_SUCCESS); break; #endif case 'v': convert_conf=1; break; case 'k': kill_server=1; break; case 'V': fprintf(stderr,"Firefly Media Server: Version %s\n",VERSION); exit(EXIT_SUCCESS); break; default: usage(argv[0]); exit(EXIT_FAILURE); break; } } if((getuid()) && (!force_non_root) && (!convert_conf)) { fprintf(stderr,"You are not root. This is almost certainly wrong. " "If you are\nsure you want to do this, use the -y " "command-line switch\n"); exit(EXIT_FAILURE); } if(kill_server) { os_signal_server(S_STOP); exit(0); } io_init(); io_set_errhandler(main_io_errhandler); ws_set_errhandler(main_ws_errhandler); /* read the configfile, if specified, otherwise * try defaults */ config.stats.start_time=start_time=(int)time(NULL); config.stop=0; /* set appdir first, that way config resolves relative to appdir */ if(appdir) { apppath = os_apppath(argv[0]); DPRINTF(E_INF,L_MAIN,"Changing cwd to %s\n",apppath); chdir(apppath); free(apppath); configfile="mt-daapd.conf"; } if(CONF_E_SUCCESS != conf_read(configfile)) { fprintf(stderr,"Error reading config file (%s)\n",configfile); exit(EXIT_FAILURE); } if(debuglevel) /* was specified, should override the config file */ err_setlevel(debuglevel); if(convert_conf) { fprintf(stderr,"Converting config file...\n"); if(CONF_E_SUCCESS != conf_write()) { fprintf(stderr,"Error writing config file.\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } DPRINTF(E_LOG,L_MAIN,"Firefly Version %s: Starting with debuglevel %d\n", VERSION,err_getlevel()); /* load plugins before we drop privs? Maybe... let the * plugins do stuff they might need to */ plugin_init(); if((plugindir=conf_alloc_string("plugins","plugin_dir",NULL)) != NULL) { /* instead of specifying plugins, let's walk through the directory * and load each of them */ if(!load_plugin_dir(plugindir)) { DPRINTF(E_LOG,L_MAIN,"Warning: Could not load plugins\n"); } else { plugins_loaded = TRUE; } free(plugindir); } if(!plugins_loaded) { if((!load_plugin_dir("/usr/lib/firefly/plugins")) && (!load_plugin_dir("/usr/lib/mt-daapd/plugins")) && (!load_plugin_dir("/lib/mt-daapd/plugins")) && (!load_plugin_dir("/lib/mt-daapd/plugins")) && (!load_plugin_dir("/usr/local/lib/mt-daapd/plugins")) && (!load_plugin_dir("/usr/local/lib/mt-daapd/plugins")) && (!load_plugin_dir("/opt/share/firefly/plugins")) && (!load_plugin_dir("/opt/share/mt-daapd/plugins")) && (!load_plugin_dir("/opt/lib/firefly/plugins")) && (!load_plugin_dir("/opt/lib/mt-daapd/plugins")) && (!load_plugin_dir("plugins/.libs"))) { DPRINTF(E_FATAL,L_MAIN,"plugins/plugin_dir not specified\n"); } } phandle=NULL; while((phandle=plugin_enum(phandle))) { DPRINTF(E_LOG,L_MAIN,"Plugin loaded: %s\n",plugin_get_description(phandle)); } runas = conf_alloc_string("general","runas","nobody"); #ifndef WITHOUT_MDNS if(config.use_mdns) { DPRINTF(E_LOG,L_MAIN,"Starting rendezvous daemon\n"); if(rend_init(runas)) { DPRINTF(E_FATAL,L_MAIN|L_REND,"Error in rend_init: %s\n", strerror(errno)); } } #endif if(!os_init(config.foreground,runas)) { DPRINTF(E_LOG,L_MAIN,"Could not initialize server\n"); os_deinit(); exit(EXIT_FAILURE); } free(runas); #ifdef UPNP upnp_init(); #endif /* this will require that the db be readable by the runas user */ db_type = conf_alloc_string("general","db_type","sqlite"); db_parms = conf_alloc_string("general","db_parms","/var/cache/mt-daapd"); err=db_open(&perr,db_type,db_parms); if(err) { DPRINTF(E_LOG,L_MAIN|L_DB,"Error opening db: %s\n",perr); #ifndef WITHOUT_MDNS if(config.use_mdns) { rend_stop(); } #endif os_deinit(); exit(EXIT_FAILURE); } free(db_type); free(db_parms); /* Initialize the database before starting */ DPRINTF(E_LOG,L_MAIN|L_DB,"Initializing database\n"); if(db_init(reload)) { DPRINTF(E_FATAL,L_MAIN|L_DB,"Error in db_init: %s\n",strerror(errno)); } err=db_get_song_count(&perr,&song_count); if(err != DB_E_SUCCESS) { DPRINTF(E_FATAL,L_MISC,"Error getting song count: %s\n",perr); } /* do a full reload if the db is empty */ if(!song_count) reload = 1; if(conf_get_array("general","mp3_dir",&mp3_dir_array)) { if((!skip_initial) || (reload)) { DPRINTF(E_LOG,L_MAIN|L_SCAN,"Starting mp3 scan\n"); #ifdef ALPHA_CUSTOMIZE share_path = conf_alloc_string("general", "mp3_dir", "AAA"); printf("mp3_dir_array[0] = [%s]\n", mp3_dir_array[0]); if (strlen(share_path) > 0) { Cnt_total_file(mp3_dir_array[0]); pthread_create( &thread1, NULL, (void*)process_bar, NULL); free(share_path); } #endif plugin_event_dispatch(PLUGIN_EVENT_FULLSCAN_START,0,NULL,0); start_time=(int) time(NULL); if(scan_init(mp3_dir_array)) { DPRINTF(E_LOG,L_MAIN|L_SCAN,"Error scanning MP3 files: %s\n",strerror(errno)); } if(!config.stop) { /* don't send popup when shutting down */ plugin_event_dispatch(PLUGIN_EVENT_FULLSCAN_END,0,NULL,0); err=db_get_song_count(&perr,&song_count); end_time=(int) time(NULL); DPRINTF(E_LOG,L_MAIN|L_SCAN,"Scanned %d songs in %d seconds\n", song_count,end_time - start_time); } } conf_dispose_array(mp3_dir_array); } #ifdef ALPHA_CUSTOMIZE thread_exit = 1; #endif /* start up the web server */ web_root = conf_alloc_string("general","web_root",NULL); ws_config.web_root=web_root; ws_config.port=conf_get_int("general","port",0); DPRINTF(E_LOG,L_MAIN|L_WS,"Starting web server from %s on port %d\n", ws_config.web_root, ws_config.port); config.server=ws_init(&ws_config); if(!config.server) { /* pthreads or malloc error */ DPRINTF(E_FATAL,L_MAIN|L_WS,"Error initializing web server\n"); } if(E_WS_SUCCESS != ws_start(config.server)) { /* listen or pthread error */ DPRINTF(E_FATAL,L_MAIN|L_WS,"Error starting web server\n"); } ws_registerhandler(config.server, "/",main_handler,main_auth, 0,1); #ifndef WITHOUT_MDNS if(config.use_mdns) { /* register services */ servername = conf_get_servername(); memset(txtrecord,0,sizeof(txtrecord)); txt_add(txtrecord,"txtvers=1"); txt_add(txtrecord,"Database ID=%0X",util_djb_hash_str(servername)); txt_add(txtrecord,"Machine ID=%0X",util_djb_hash_str(servername)); txt_add(txtrecord,"Machine Name=%s",servername); txt_add(txtrecord,"mtd-version=" VERSION); txt_add(txtrecord,"iTSh Version=131073"); /* iTunes 6.0.4 */ txt_add(txtrecord,"Version=196610"); /* iTunes 6.0.4 */ tmp = conf_alloc_string("general","password",NULL); if(tmp && (strlen(tmp)==0)) tmp=NULL; txt_add(txtrecord,"Password=%s",tmp ? "true" : "false"); if(tmp) free(tmp); srand((unsigned int)time(NULL)); if(ffid) { txt_add(txtrecord,"ffid=%s",ffid); } else { txt_add(txtrecord,"ffid=%08x",rand()); } DPRINTF(E_LOG,L_MAIN|L_REND,"Registering rendezvous names\n"); iface = conf_alloc_string("general","interface",""); rend_register(servername,"_http._tcp",ws_config.port,iface,txtrecord); plugin_rend_register(servername,ws_config.port,iface,txtrecord); free(servername); free(iface); } #endif end_time=(int) time(NULL); err=db_get_song_count(&perr,&song_count); if(err != DB_E_SUCCESS) { DPRINTF(E_FATAL,L_MISC,"Error getting song count: %s\n",perr); } DPRINTF(E_LOG,L_MAIN,"Serving %d songs. Startup complete in %d seconds\n", song_count,end_time-start_time); if(conf_get_int("general","rescan_interval",0) && (!reload) && (!conf_get_int("scanning","skip_first",0))) config.reload = 1; /* force a reload on start */ while(!config.stop) { if((conf_get_int("general","rescan_interval",0) && (rescan_counter > conf_get_int("general","rescan_interval",0)))) { if((conf_get_int("general","always_scan",0)) || (config_get_session_count())) { config.reload=1; } else { DPRINTF(E_DBG,L_MAIN|L_SCAN|L_DB,"Skipped bground scan... no users\n"); } rescan_counter=0; } if(config.reload) { old_song_count = song_count; start_time=(int) time(NULL); DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Rescanning database\n"); if(conf_get_array("general","mp3_dir",&mp3_dir_array)) { if(config.full_reload) { config.full_reload=0; db_force_rescan(NULL); } if(scan_init(mp3_dir_array)) { DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Error rescanning... bad path?\n"); } conf_dispose_array(mp3_dir_array); } config.reload=0; db_get_song_count(NULL,&song_count); DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Scanned %d songs (was %d) in " "%d seconds\n",song_count,old_song_count, time(NULL)-start_time); } os_wait(MAIN_SLEEP_INTERVAL); rescan_counter += MAIN_SLEEP_INTERVAL; } DPRINTF(E_LOG,L_MAIN,"Stopping gracefully\n"); #ifndef WITHOUT_MDNS if(config.use_mdns) { DPRINTF(E_LOG,L_MAIN|L_REND,"Stopping rendezvous daemon\n"); rend_stop(); } #endif #ifdef UPNP upnp_deinit(); #endif /* Got to find a cleaner way to stop the web server. * Closing the fd of the socking accepting doesn't necessarily * cause the accept to fail on some libcs. * DPRINTF(E_LOG,L_MAIN|L_WS,"Stopping web server\n"); ws_stop(config.server); */ free(web_root); conf_close(); DPRINTF(E_LOG,L_MAIN|L_DB,"Closing database\n"); db_deinit(); DPRINTF(E_LOG,L_MAIN,"Done!\n"); os_deinit(); io_deinit(); mem_dump(); return EXIT_SUCCESS; }
/** * SensorRange = einschränkung der Reichweite. Verhindert unnötig lange Berechnung * Return: Distance */ uint16_t driven_before(int8_t type, uint16_t SensorRange) { double diffR; #ifdef CARTOGRAPHY_SCENARIO gps_reducedData_t *own; uint16_t angle, diffL; int16_t xCollision = 0, yCollision = 0, ownX, ownY; int32_t newX, newY; //Aktuelle Orientierung beachten!!! Orientierung in Abhängigkeit der Fahrzeugorientierung und dem aktuell betrachteten Sensor own = get_ownCoords(); switch(type) { case RIGHT_SENSOR: angle = AngleMinus(own->angle, 16383); if (SensorRange > RANGESIDE*2) SensorRange = RANGESIDE*2; //siehe Anforderungen in wallFollow für align = 2 break; case LEFT_SENSOR: angle = AnglePlus(own->angle, 16383); if (SensorRange > RANGESIDE*2) SensorRange = RANGESIDE*2;//siehe Anforderungen in wallFollow für align = 2 break; case FRONT_SENSOR: angle = own->angle; if (SensorRange > RANGESIDE*2) SensorRange = RANGESIDE*2; break; default: angle = own->angle; break; } SensorRange = SensorRange / 5; ownX = CoordinatesToMap(own->x); ownY = CoordinatesToMap(own->y); if (Sema != NULL) { while ( xSemaphoreTake( Sema, ( portTickType ) 10 ) != pdTRUE ) { os_wait(10); } newX = (SensorRange*cos_Taylor(uint16DegreeRelativeToX(angle)))/100 + ownX; ownX = (2*cos_Taylor(uint16DegreeRelativeToX(angle)))/100 + ownX; //Ein stück aus dem Urpsrung rausgehen newY = (SensorRange*sin_Taylor(uint16DegreeRelativeToX(angle)))/100 + ownY; ownY = (2*sin_Taylor(uint16DegreeRelativeToX(angle)))/100 + ownY; //gibt es ein bereits befahrenes Gebiet/Hindernis das zwischen Sensorwert und Auto liegt? diffL = calc_reachability(&xCollision, &yCollision, ownX, ownY, (int16_t)newX, (int16_t)newY); xSemaphoreGive(Sema); } else return 600; //600 = max. Sensorreichweite if (diffL == 1) { diffR = sqrt(abs16(ownX - xCollision)*abs16(ownX - xCollision) + abs16(ownY - yCollision)*abs16(ownY - yCollision)); diffR = diffR*5; if (diffR < 100) { Seg_Hex(0x00); } else Seg_Hex(0x01); } else { diffR = 600; // 600 für nichts gefunden } if (diffR > 600) diffR = 600; #endif return (uint16_t) diffR; }
static graph_walk_status_ty graph_walk_inner(graph_ty *gp, graph_walk_status_ty (*func)(graph_recipe_ty *, graph_ty *), int nproc) { graph_recipe_list_nrc_ty walk; graph_walk_status_ty status; graph_walk_status_ty status2; graph_recipe_ty *grp; size_t j; size_t walk_pos; itab_ty *itp; string_list_ty single_thread; trace(("graph_walk(gp = %8.8lX, nproc = %d)\n{\n", (long)gp, nproc)); status = graph_walk_status_uptodate; itp = itab_alloc(nproc); /* * Reset the activity counter for each recipe. * * Recipes with no inputs are added to the list at this time, * all of their inputs are satisfied. */ graph_recipe_list_nrc_constructor(&walk); for (j = 0; j < gp->already_recipe->nrecipes; ++j) { grp = gp->already_recipe->recipe[j]; grp->input_satisfied = 0; grp->input_uptodate = 0; if (grp->output->nfiles != 0 && grp->input->nfiles == 0) { grp->input_uptodate = 1; graph_recipe_list_nrc_append(&walk, grp); } } /* * Turn the list upside down. We want to find all of the files * with outputs but no inputs. This is the initial list of file * nodes to walk. */ symtab_walk(gp->already, is_it_a_leaf, &walk); /* * Keep chewing up graph recipe nodes until no more are left to * be processed. */ string_list_constructor(&single_thread); walk_pos = 0; while (walk_pos < walk.nrecipes || itp->load > 0) { /* * Terminate elegantly, if asked to. */ if (desist_requested()) { desist: status = graph_walk_status_error; if (itp->load > 0 && !option_test(OPTION_SILENT)) { sub_context_ty *scp; scp = sub_context_new(); sub_var_set(scp, "Number", "%ld", (long)itp->load); sub_var_optional(scp, "Number"); error_intl(scp, i18n("waiting for outstanding processes")); sub_context_delete(scp); } /* * No matter what, don't do another recipe. * However, we must still wait for the * unfinished actions to complete in an orderly * fashion. */ no_persevere: assert(gp->already_recipe); walk_pos = gp->already_recipe->nrecipes * 2; continue; } /* * If there is available processing resource, and * outstanding recipe instances, run another recipe. */ trace(("itp->load = %ld;\n", (long)itp->load)); trace(("nproc = %d;\n", nproc)); trace(("walk_pos = %ld;\n", (long)walk_pos)); trace(("walk.nrecipes = %ld;\n", (long)walk.nrecipes)); while (itp->load < nproc && walk_pos < walk.nrecipes) { if (desist_requested()) goto desist; fp_sync(); /* * Extract a recipe from the list. Order does * not matter, they are all valid candidates * with up-to-date ingredients. * * However: the users expect a mostly * left-to-right order of evaluation. That * means taking the first one, NOT the last one. */ grp = walk.recipe[walk_pos++]; /* * Make sure there is no conflict with existing * single thread flags. Go hunting for a recipe * not in conflict. Come back later if we can't * find one. */ if ( grp->single_thread && string_list_intersect(grp->single_thread, &single_thread) ) { size_t k; graph_recipe_ty *kp; /* * go hunting */ for (k = walk_pos; k < walk.nrecipes; ++k) { kp = walk.recipe[k]; if ( !kp->single_thread || !string_list_intersect ( kp->single_thread, &single_thread ) ) break; } /* * Come back later if we find no alternative. */ if (k >= walk.nrecipes) { --walk_pos; break; } /* * Have the conflicting recipe and the * alternative change places. */ kp = walk.recipe[k]; trace(("k = %ld\n", (long)k)); trace(("kp = %08lX\n", (long)kp)); walk.recipe[walk_pos - 1] = kp; walk.recipe[k] = grp; grp = kp; } trace(("grp = %08lX;\n", (long)grp)); trace(("grp->input->nfiles = %ld;\n", (long)grp->input->nfiles)); trace(("grp->output->nfiles = %ld;\n", (long)grp->output->nfiles)); /* * Remember the single threading, so other * recipes avoid conflicting with *this* one. */ if (grp->single_thread) { string_list_append_list(&single_thread, grp->single_thread); } /* * run the recipe body */ run_a_recipe: status2 = func(grp, gp); /* * Look at what happened. */ if (grp->single_thread && status2 != graph_walk_status_wait) { string_list_remove_list(&single_thread, grp->single_thread); } switch (status2) { case graph_walk_status_wait: assert(itp); trace(("pid = %d;\n", graph_recipe_getpid(grp))); itab_assign(itp, graph_recipe_getpid(grp), grp); trace(("itp->load = %ld;\n", (long)itp->load)); break; case graph_walk_status_error: /* * It failed. Don't do anything with the * outputs of the recipe. Usually, we stop * altogether. */ trace(("error\n")); status = graph_walk_status_error; if (!option_test(OPTION_PERSEVERE)) goto no_persevere; break; case graph_walk_status_done_stop: /* * It worked, but we need to stop for * some reason. This is usually only * used by isit_uptodate. */ trace(("done_stop\n")); if (status == graph_walk_status_uptodate) status = graph_walk_status_done_stop; assert(itp->load == 0); goto done; case graph_walk_status_uptodate: star_as_specified('#'); /* fall through... */ case graph_walk_status_uptodate_done: /* * It worked. Now push all of the * recipes which depend on the outputs * of this recipe. */ implications_of_recipe(&walk, grp, 1); break; case graph_walk_status_done: /* * It worked. Now push all of the * recipes which depend on the outputs * of this recipe. */ implications_of_recipe(&walk, grp, 0); if (status == graph_walk_status_uptodate) status = graph_walk_status_done; break; } #ifdef HAVE_WAIT3 /* * We want to see if any children have exited. * Do not block (that's why wait3 is used). * Only do one at a time. */ if (itp->load > 0) { int pid; int exit_status; struct rusage ru; trace(("mark\n")); pid = os_wait3(&exit_status, WNOHANG, &ru); trace(("pid = %d\n", pid)); if (pid < 0) { sub_context_ty *scp; if (errno == EINTR) continue; scp = sub_context_new(); sub_errno_set(scp); fatal_intl(scp, i18n("wait(): $errno")); /* NOTREACHED */ } else if (pid > 0) { trace(("es = 0x%04X\n", exit_status)); grp = itab_query(itp, pid); if (grp) { /* if it's one of ours... */ trace(("...waited\n")); assert(pid == graph_recipe_getpid(grp)); if (grp->ocp->meter_p) grp->ocp->meter_p->ru = ru; graph_recipe_waited(grp, exit_status); itab_delete(itp, pid); trace(("itp->load = %ld;\n", (long)itp->load)); goto run_a_recipe; } } } #endif /* HAVE_WAIT3 */ } /* * Collect the results of execution, and kick off the * recipes that are blocked. Only do one at a time. */ if (itp->load > 0) { int pid; int exit_status; #ifdef HAVE_WAIT3 struct rusage ru; #endif trace(("mark\n")); #ifdef HAVE_WAIT3 pid = os_wait3(&exit_status, 0, &ru); #else pid = os_wait(&exit_status); #endif trace(("pid = %d\n", pid)); assert(pid != 0); if (pid == 0) errno = EINVAL; if (pid <= 0) { sub_context_ty *scp; if (errno == EINTR) continue; scp = sub_context_new(); sub_errno_set(scp); fatal_intl(scp, i18n("wait(): $errno")); /* NOTREACHED */ } trace(("es = 0x%04X\n", exit_status)); grp = itab_query(itp, pid); if (grp) { /* if it's one of ours... */ trace(("...waited\n")); assert(pid == graph_recipe_getpid(grp)); #ifdef HAVE_WAIT3 if (grp->ocp->meter_p) grp->ocp->meter_p->ru = ru; #endif graph_recipe_waited(grp, exit_status); itab_delete(itp, pid); trace(("itp->load = %ld;\n", (long)itp->load)); goto run_a_recipe; } } trace(("mark\n")); } done: itab_free(itp); /* * Confirmation for the user when things go wrong. */ if (status == graph_walk_status_error) symtab_walk(gp->already, excuse_me, gp); /* * Free up the list of recipes (which have been) / (to be) walked. */ graph_recipe_list_nrc_destructor(&walk); string_list_destructor(&single_thread); trace(("return %s;\n", graph_walk_status_name(status))); trace(("}\n")); return status; }