void trainTaskInit(void) { clockInitTask(); mioInit(); tioInit(); logInit(); Create(31, idlerTask); Delay(50); vtInit(); turnoutInit(); sensorInit(); parserInit(); clockDrawerInit(); controllerInit(); freightInit(); initTrackA(nodes, hashtbl); }
int main (int argc, char *argv[]){ string logFilename =""; if (argc >= 2){ logFilename = argv[1]; } logInit(LOG_WARNING, logFilename); int b = 10; func1(b); func3(b); thread Thr=thread(func3, b); Thr.join(); setLogLevel(LOG_INFO); func1(b); func3(b); logEnd(); }
//Main routine. Initialize stdout, the I/O, filesystem and the webserver and we're done. void user_init(void) { // init gpio pins used to reset&reprogram attached microcontrollers gpio_init(); // put MCU into reset in case it interferes with serial-programming of the esp8266 //GPIO_OUTPUT_SET(MCU_RESET, 0); // init UART uart_init(BIT_RATE_115200, BIT_RATE_115200); // say hello (leave some time to cause break in TX after boot loader's msg os_delay_us(10000L); # define VERS_STR_STR(V) #V # define VERS_STR(V) VERS_STR_STR(V) os_printf("\n\nInitializing esp-link\n" VERS_STR(VERSION) "\n"); //configWipe(); if (configRestore()) os_printf("Flash config restored\n"); else os_printf("*** Flash config restore failed, using defaults ***\n"); // Status LEDs statusInit(); serledInit(); logInit(); // Wifi wifiInit(); // init the flash filesystem with the html stuff EspFsInitResult res = espFsInit(&_binary_espfs_img_start); os_printf("espFsInit(0x%08lx) returned %d\n", (uint32_t)&_binary_espfs_img_start, res); // mount the http handlers httpdInit(builtInUrls, 80); // init the wifi-serial transparent bridge (port 23) serbridgeInit(23); uart_add_recv_cb(&serbridgeUartCb); #ifdef SHOW_HEAP_USE os_timer_disarm(&prHeapTimer); os_timer_setfn(&prHeapTimer, prHeapTimerCb, NULL); os_timer_arm(&prHeapTimer, 3000, 1); #endif struct rst_info *rst_info = system_get_rst_info(); os_printf("Reset cause: %d=%s\n", rst_info->reason, rst_codes[rst_info->reason]); os_printf("exccause=%d epc1=0x%x epc2=0x%x epc3=0x%x excvaddr=0x%x depc=0x%x\n", rst_info->exccause, rst_info->epc1, rst_info->epc2, rst_info->epc3, rst_info->excvaddr, rst_info->depc); os_printf("** esp-link ready\n"); }
//Main routine. Initialize stdout, the I/O, filesystem and the webserver and we're done. void user_init(void) { // get the flash config so we know how to init things //configWipe(); // uncomment to reset the config for testing purposes bool restoreOk = configRestore(); // init gpio pin registers gpio_init(); // init UART uart_init(flashConfig.baud_rate, 115200); logInit(); // must come after init of uart // say hello (leave some time to cause break in TX after boot loader's msg os_delay_us(10000L); os_printf("\n\n** %s\n", esp_link_version); os_printf("Flash config restore %s\n", restoreOk ? "ok" : "*FAILED*"); // Status LEDs statusInit(); serledInit(); // Wifi wifiInit(); // init the flash filesystem with the html stuff espFsInit(&_binary_espfs_img_start); //EspFsInitResult res = espFsInit(&_binary_espfs_img_start); //os_printf("espFsInit %s\n", res?"ERR":"ok"); // mount the http handlers httpdInit(builtInUrls, 80); // init the wifi-serial transparent bridge (port 23) serbridgeInit(23); uart_add_recv_cb(&serbridgeUartCb); #ifdef SHOW_HEAP_USE os_timer_disarm(&prHeapTimer); os_timer_setfn(&prHeapTimer, prHeapTimerCb, NULL); os_timer_arm(&prHeapTimer, 10000, 1); #endif struct rst_info *rst_info = system_get_rst_info(); os_printf("Reset cause: %d=%s\n", rst_info->reason, rst_codes[rst_info->reason]); os_printf("exccause=%d epc1=0x%x epc2=0x%x epc3=0x%x excvaddr=0x%x depc=0x%x\n", rst_info->exccause, rst_info->epc1, rst_info->epc2, rst_info->epc3, rst_info->excvaddr, rst_info->depc); os_printf("Flash map %d, chip %08X\n", system_get_flash_size_map(), spi_flash_get_id()); os_printf("** esp-link ready\n"); }
//------------------------------------------------------------------------------ int main( int argc, char **argv ) //------------------------------------------------------------------------------ { // initialize the log (see log.h for details) logInit(); get_options (argc, argv); //Command-line options set_glog(glog_level, glog_verbosity); log_set_instance_type (LOG_INSTANCE_ENB); /* Read eNB configuration file */ enb_properties = enb_config_init(conf_config_file_name); itti_init(TASK_MAX, THREAD_MAX, MESSAGES_ID_MAX, tasks_info, messages_info, messages_definition_xml, itti_dump_file); itti_wait_ready(1); if (itti_create_task (TASK_SCTP, sctp_eNB_task, NULL) < 0) { LOG_E(SCTP, "Create task for SCTP failed\n"); return -1; } if (itti_create_task (TASK_S1AP, s1ap_eNB_task, NULL) < 0) { LOG_E(S1AP, "Create task for S1AP failed\n"); return -1; } if (itti_create_task (TASK_ENB_APP, eNB_app_task, NULL) < 0) { LOG_E(S1AP, "Create task for S1AP failed\n"); return -1; } itti_wait_ready(0); sleep(30); logClean(); return 0; }
VkBool32 VKTS_APIENTRY engineInit() { if (!processorInit()) { VKTS_PRINTF("LOG [VKTS_LOG_ERROR]: Engine: Initialization failed! Could not initialize the processor!\n"); return VK_FALSE; } if (!logInit()) { VKTS_PRINTF("LOG [VKTS_LOG_ERROR]: Engine: Initialization failed! Could not initialize logging.\n"); return VK_FALSE; } if (!timeInit()) { logPrint(VKTS_LOG_ERROR, "Engine: Initialization failed! Could not initialize the timer!"); return VK_FALSE; } if (!barrierInit()) { logPrint(VKTS_LOG_ERROR, "Engine: Initialization failed! Could not initialize the barrier!"); return VK_FALSE; } if (!fileInit()) { logPrint(VKTS_LOG_ERROR, "Engine: Initialization failed! Could not initialize the file system!"); return VK_FALSE; } return VK_TRUE; }
int main(int argc, char *argv[]) { parseCommandLine(argc, argv); logInit("certserv", arg.useSyslog, arg.verbose, arg.logMask); //logNorm("arg.verbose = %d, arg.log_mask = %d\n", arg.verbose, arg.logMask); //logNorm("arg.chunks = %s\n", arg.chunks); if (init() < 0) dieError("init()\n"); // Skip the slash if (arg.url[0] == '/') arg.url++; logVerb("host = '%s', url = '%s', port = %d\n", arg.host, arg.url, arg.port); if (arg.isServer) serverLoop(); else client(); return 0; }
/** * Runs the object returned by WebAppManager::instance() * * Steps to do so are as follows: * - Install crash handlers for SIGILL, SIGSEGV, and SIGTERM * - Set the process name * - Wait until IpcServer in the main process is ready * - Set IpcServerPipeFd to -1 to indicate that we're done waiting for it * - Set host info for {@link WebAppManager::instance() WebAppManager::instance()} to what is returned by HostBase::instance()->getInfo() * - Initialize malloc stats * - Initialize the logs * - Start the Browser App Launcher * * @param data Not used * * @return Always returns 0 */ static int RunWebAppManagerTask(void* data) { // Install the handler for signals that we want to trap: // Note: We install the handlers after we initialize the setting because // we may do something different depending on the settings values. installOuterCrashHandler(SIGILL); installOuterCrashHandler(SIGSEGV); installOuterCrashHandler(SIGTERM); ::prctl(PR_SET_NAME, (unsigned long) "WebAppMgr", 0, 0, 0); ::prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); char msg = 0x00; int len = 0; // block here until the IpcServer in the main process is ready while (len != 1 || msg != msgOkToContinue) len = ::read(IpcServerPipeFd, &msg, 1); ::close(IpcServerPipeFd); IpcServerPipeFd = -1; const HostInfo* info = &(HostBase::instance()->getInfo()); WebAppManager::instance()->setHostInfo(info); initMallocStatsCb(WebAppManager::instance()->mainLoop(), s_mallocStatsInterval); logInit(); // Start the Browser App Launcher #ifdef NO_WEBKIT_INIT WindowServer::instance()->bootupFinished(); #else WebAppManager::instance()->run(); // Sync execution of the task #endif return 0; }
int main(int argc, char* argv[]) { loger = logInit(argv, "TESTSERVER"); //--Boludeces de los sockets fd_set master, temp; struct sockaddr_in myAddress; struct sockaddr_in remoteAddress; int maxSock; int sockListener; int bufSize = 10; char buf[bufSize]; iniSocks(&master, &temp, &myAddress, remoteAddress, &maxSock, &sockListener, PUERTO, loger); log_trace(loger, "Inicializado"); pthread_t* threads; int cantidadHilos = -1; //Inicia en -1 para hacer el ++ while (1) { getSockChanged(&master, &temp, &maxSock, sockListener, &remoteAddress, &buf, bufSize, loger); threads = (pthread_t*)realloc(NULL, sizeof(pthread_t)); //Realoca memoria para manejar mas hilos if (pthread_create(&threads[cantidadHilos], NULL, hilaje, (void *)buf)){ log_error(loger, strerror(errno)); exit(-1); } log_debug(loger, "Creado nuevo hilo"); } for(; cantidadHilos > 0; cantidadHilos--) pthread_join(threads[cantidadHilos], NULL); free(threads); return 0; }
tSirRetStatus macOpen(tHalHandle *pHalHandle, tHddHandle hHdd, tMacOpenParameters *pMacOpenParms) { tpAniSirGlobal pMac = NULL; if(pHalHandle == NULL) return eSIR_FAILURE; pMac = vos_mem_malloc(sizeof(tAniSirGlobal)); if ( NULL == pMac ) return eSIR_FAILURE; vos_mem_set(pMac, sizeof(tAniSirGlobal), 0); pMac->hHdd = hHdd; pMac->pAdapter = hHdd; *pHalHandle = (tHalHandle)pMac; { if( eSIR_SUCCESS != logInit(pMac)) return eSIR_FAILURE; if( eSIR_SUCCESS != cfgInit(pMac) ) return eSIR_FAILURE; sysInitGlobals(pMac); } return peOpen(pMac, pMacOpenParms); }
int main( int argc, char *argv[] ) { if ( access(ZM_CONFIG, R_OK) != 0 ) { fprintf( stderr, "Can't open %s: %s\n", ZM_CONFIG, strerror(errno) ); exit( -1 ); } self = argv[0]; srand( getpid() * time( 0 ) ); static struct option long_options[] = { {"device", 2, 0, 'd'}, {"monitor", 1, 0, 'm'}, {"verbose", 0, 0, 'v'}, {"image", 2, 0, 'i'}, {"scale", 1, 0, 'S'}, {"timestamp", 2, 0, 't'}, {"state", 0, 0, 's'}, {"brightness", 2, 0, 'B'}, {"contrast", 2, 0, 'C'}, {"hue", 2, 0, 'H'}, {"contrast", 2, 0, 'O'}, {"read_index", 0, 0, 'R'}, {"write_index", 0, 0, 'W'}, {"event", 0, 0, 'e'}, {"fps", 0, 0, 'f'}, {"zones", 2, 0, 'z'}, {"alarm", 0, 0, 'a'}, {"noalarm", 0, 0, 'n'}, {"cancel", 0, 0, 'c'}, {"reload", 0, 0, 'L'}, {"enable", 0, 0, 'E'}, {"disable", 0, 0, 'D'}, {"suspend", 0, 0, 'u'}, {"resume", 0, 0, 'r'}, {"query", 0, 0, 'q'}, {"username", 1, 0, 'U'}, {"password", 1, 0, 'P'}, {"auth", 1, 0, 'A'}, {"version", 1, 0, 'V'}, {"help", 0, 0, 'h'}, {"list", 0, 0, 'l'}, {0, 0, 0, 0} }; const char *device = 0; int mon_id = 0; bool verbose = false; int function = ZMU_BOGUS; int image_idx = -1; int scale = -1; int brightness = -1; int contrast = -1; int hue = -1; int colour = -1; char *zoneString = 0; char *username = 0; char *password = 0; char *auth = 0; #if ZM_HAS_V4L #if ZM_HAS_V4L2 int v4lVersion = 2; #elif ZM_HAS_V4L1 int v4lVersion = 1; #endif // ZM_HAS_V4L2/1 #endif // ZM_HAS_V4L while (1) { int option_index = 0; int c = getopt_long (argc, argv, "d:m:vsEDLurwei::S:t::fz::ancqhlB::C::H::O::U:P:A:V:", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'd': if ( optarg ) device = optarg; break; case 'm': mon_id = atoi(optarg); break; case 'v': verbose = true; break; case 's': function |= ZMU_STATE; break; case 'i': function |= ZMU_IMAGE; if ( optarg ) image_idx = atoi( optarg ); break; case 'S': scale = atoi(optarg); break; case 't': function |= ZMU_TIME; if ( optarg ) image_idx = atoi( optarg ); break; case 'R': function |= ZMU_READ_IDX; break; case 'W': function |= ZMU_WRITE_IDX; break; case 'e': function |= ZMU_EVENT; break; case 'f': function |= ZMU_FPS; break; case 'z': function |= ZMU_ZONES; if ( optarg ) zoneString = optarg; break; case 'a': function |= ZMU_ALARM; break; case 'n': function |= ZMU_NOALARM; break; case 'c': function |= ZMU_CANCEL; break; case 'L': function |= ZMU_RELOAD; break; case 'E': function |= ZMU_ENABLE; break; case 'D': function |= ZMU_DISABLE; break; case 'u': function |= ZMU_SUSPEND; break; case 'r': function |= ZMU_RESUME; break; case 'q': function |= ZMU_QUERY; break; case 'B': function |= ZMU_BRIGHTNESS; if ( optarg ) brightness = atoi( optarg ); break; case 'C': function |= ZMU_CONTRAST; if ( optarg ) contrast = atoi( optarg ); break; case 'H': function |= ZMU_HUE; if ( optarg ) hue = atoi( optarg ); break; case 'O': function |= ZMU_COLOUR; if ( optarg ) colour = atoi( optarg ); break; case 'U': username = optarg; break; case 'P': password = optarg; break; case 'A': auth = optarg; break; #if ZM_HAS_V4L case 'V': v4lVersion = (atoi(optarg)==1)?1:2; break; #endif // ZM_HAS_V4L case 'h': Usage( 0 ); break; case 'l': function |= ZMU_LIST; break; case '?': Usage(); break; default: //fprintf( stderr, "?? getopt returned character code 0%o ??\n", c ); break; } } if (optind < argc) { fprintf( stderr, "Extraneous options, " ); while (optind < argc) fprintf( stderr, "%s ", argv[optind++]); fprintf( stderr, "\n"); Usage(); } if ( device && !(function&ZMU_QUERY) ) { fprintf( stderr, "Error, -d option cannot be used with this option\n" ); Usage(); } if ( scale != -1 && !(function&ZMU_IMAGE) ) { fprintf( stderr, "Error, -S option cannot be used with this option\n" ); Usage(); } //printf( "Monitor %d, Function %d\n", mon_id, function ); zmLoadConfig(); logInit( "zmu" ); zmSetDefaultTermHandler(); zmSetDefaultDieHandler(); User *user = 0; if ( config.opt_use_auth ) { if ( strcmp( config.auth_relay, "none" ) == 0 ) { if ( !username ) { fprintf( stderr, "Error, username must be supplied\n" ); exit( -1 ); } if ( username ) { user = zmLoadUser( username ); } } else { if ( !(username && password) && !auth ) { fprintf( stderr, "Error, username and password or auth string must be supplied\n" ); exit( -1 ); } //if ( strcmp( config.auth_relay, "hashed" ) == 0 ) { if ( auth ) { user = zmLoadAuthUser( auth, false ); } } //else if ( strcmp( config.auth_relay, "plain" ) == 0 ) { if ( username && password ) { user = zmLoadUser( username, password ); } } } if ( !user ) { fprintf( stderr, "Error, unable to authenticate user\n" ); exit( -1 ); } ValidateAccess( user, mon_id, function ); } if ( mon_id > 0 ) { Monitor *monitor = Monitor::Load( mon_id, function&(ZMU_QUERY|ZMU_ZONES), Monitor::QUERY ); if ( monitor ) { if ( verbose ) { printf( "Monitor %d(%s)\n", monitor->Id(), monitor->Name() ); } if ( ! monitor->connect() ) { Error( "Can't connect to capture daemon: %d %s", monitor->Id(), monitor->Name() ); exit( -1 ); } char separator = ' '; bool have_output = false; if ( function & ZMU_STATE ) { Monitor::State state = monitor->GetState(); if ( verbose ) printf( "Current state: %s\n", state==Monitor::ALARM?"Alarm":(state==Monitor::ALERT?"Alert":"Idle") ); else { if ( have_output ) printf( "%c", separator ); printf( "%d", state ); have_output = true; } } if ( function & ZMU_TIME ) { struct timeval timestamp = monitor->GetTimestamp( image_idx ); if ( verbose ) { char timestamp_str[64] = "None"; if ( timestamp.tv_sec ) strftime( timestamp_str, sizeof(timestamp_str), "%Y-%m-%d %H:%M:%S", localtime( ×tamp.tv_sec ) ); if ( image_idx == -1 ) printf( "Time of last image capture: %s.%02ld\n", timestamp_str, timestamp.tv_usec/10000 ); else printf( "Time of image %d capture: %s.%02ld\n", image_idx, timestamp_str, timestamp.tv_usec/10000 ); } else { if ( have_output ) printf( "%c", separator ); printf( "%ld.%02ld", timestamp.tv_sec, timestamp.tv_usec/10000 ); have_output = true; } } if ( function & ZMU_READ_IDX ) { if ( verbose ) printf( "Last read index: %d\n", monitor->GetLastReadIndex() ); else { if ( have_output ) printf( "%c", separator ); printf( "%d", monitor->GetLastReadIndex() ); have_output = true; } } if ( function & ZMU_WRITE_IDX ) { if ( verbose ) printf( "Last write index: %d\n", monitor->GetLastWriteIndex() ); else { if ( have_output ) printf( "%c", separator ); printf( "%d", monitor->GetLastWriteIndex() ); have_output = true; } } if ( function & ZMU_EVENT ) { if ( verbose ) printf( "Last event id: %d\n", monitor->GetLastEvent() ); else { if ( have_output ) printf( "%c", separator ); printf( "%d", monitor->GetLastEvent() ); have_output = true; } } if ( function & ZMU_FPS ) { if ( verbose ) printf( "Current capture rate: %.2f frames per second\n", monitor->GetFPS() ); else { if ( have_output ) printf( "%c", separator ); printf( "%.2f", monitor->GetFPS() ); have_output = true; } } if ( function & ZMU_IMAGE ) { if ( verbose ) { if ( image_idx == -1 ) printf( "Dumping last image captured to Monitor%d.jpg", monitor->Id() ); else printf( "Dumping buffer image %d to Monitor%d.jpg", image_idx, monitor->Id() ); if ( scale != -1 ) printf( ", scaling by %d%%", scale ); printf( "\n" ); } monitor->GetImage( image_idx, scale>0?scale:100 ); } if ( function & ZMU_ZONES ) { if ( verbose ) printf( "Dumping zone image to Zones%d.jpg\n", monitor->Id() ); monitor->DumpZoneImage( zoneString ); } if ( function & ZMU_ALARM ) { if ( verbose ) printf( "Forcing alarm on\n" ); monitor->ForceAlarmOn( config.forced_alarm_score, "Forced Web" ); } if ( function & ZMU_NOALARM ) { if ( verbose ) printf( "Forcing alarm off\n" ); monitor->ForceAlarmOff(); } if ( function & ZMU_CANCEL ) { if ( verbose ) printf( "Cancelling forced alarm on/off\n" ); monitor->CancelForced(); } if ( function & ZMU_RELOAD ) { if ( verbose ) printf( "Reloading monitor settings\n" ); monitor->actionReload(); } if ( function & ZMU_ENABLE ) { if ( verbose ) printf( "Enabling event generation\n" ); monitor->actionEnable(); } if ( function & ZMU_DISABLE ) { if ( verbose ) printf( "Disabling event generation\n" ); monitor->actionDisable(); } if ( function & ZMU_SUSPEND ) { if ( verbose ) printf( "Suspending event generation\n" ); monitor->actionSuspend(); } if ( function & ZMU_RESUME ) { if ( verbose ) printf( "Resuming event generation\n" ); monitor->actionResume(); } if ( function & ZMU_QUERY ) { char monString[16382] = ""; monitor->DumpSettings( monString, verbose ); printf( "%s\n", monString ); } if ( function & ZMU_BRIGHTNESS ) { if ( verbose ) { if ( brightness >= 0 ) printf( "New brightness: %d\n", monitor->actionBrightness( brightness ) ); else printf( "Current brightness: %d\n", monitor->actionBrightness() ); } else { if ( have_output ) printf( "%c", separator ); if ( brightness >= 0 ) printf( "%d", monitor->actionBrightness( brightness ) ); else printf( "%d", monitor->actionBrightness() ); have_output = true; } } if ( function & ZMU_CONTRAST ) { if ( verbose ) { if ( contrast >= 0 ) printf( "New brightness: %d\n", monitor->actionContrast( contrast ) ); else printf( "Current contrast: %d\n", monitor->actionContrast() ); } else { if ( have_output ) printf( "%c", separator ); if ( contrast >= 0 ) printf( "%d", monitor->actionContrast( contrast ) ); else printf( "%d", monitor->actionContrast() ); have_output = true; } } if ( function & ZMU_HUE ) { if ( verbose ) { if ( hue >= 0 ) printf( "New hue: %d\n", monitor->actionHue( hue ) ); else printf( "Current hue: %d\n", monitor->actionHue() ); } else { if ( have_output ) printf( "%c", separator ); if ( hue >= 0 ) printf( "%d", monitor->actionHue( hue ) ); else printf( "%d", monitor->actionHue() ); have_output = true; } } if ( function & ZMU_COLOUR ) { if ( verbose ) { if ( colour >= 0 ) printf( "New colour: %d\n", monitor->actionColour( colour ) ); else printf( "Current colour: %d\n", monitor->actionColour() ); } else { if ( have_output ) printf( "%c", separator ); if ( colour >= 0 ) printf( "%d", monitor->actionColour( colour ) ); else printf( "%d", monitor->actionColour() ); have_output = true; } } if ( have_output ) { printf( "\n" ); } if ( !function ) { Usage(); } delete monitor; } else { fprintf( stderr, "Error, invalid monitor id %d\n", mon_id ); exit( -1 ); } } else { if ( function & ZMU_QUERY ) { #if ZM_HAS_V4L char vidString[0x10000] = ""; bool ok = LocalCamera::GetCurrentSettings( device, vidString, v4lVersion, verbose ); printf( "%s", vidString ); exit( ok?0:-1 ); #else // ZM_HAS_V4L fprintf( stderr, "Error, video4linux is required for device querying\n" ); exit( -1 ); #endif // ZM_HAS_V4L } if ( function & ZMU_LIST ) { std::string sql = "select Id, Function+0 from Monitors"; if ( !verbose ) { sql += "where Function != 'None'"; } sql += " order by Id asc"; if ( mysql_query( &dbconn, sql.c_str() ) ) { Error( "Can't run query: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } MYSQL_RES *result = mysql_store_result( &dbconn ); if ( !result ) { Error( "Can't use query result: %s", mysql_error( &dbconn ) ); exit( mysql_errno( &dbconn ) ); } int n_monitors = mysql_num_rows( result ); Debug( 1, "Got %d monitors", n_monitors ); printf( "%4s%5s%6s%9s%14s%6s%6s%8s%8s\n", "Id", "Func", "State", "TrgState", "LastImgTim", "RdIdx", "WrIdx", "LastEvt", "FrmRate" ); for( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row( result ); i++ ) { int mon_id = atoi(dbrow[0]); int function = atoi(dbrow[1]); if ( !user || user->canAccess( mon_id ) ) { if ( function > 1 ) { Monitor *monitor = Monitor::Load( mon_id, false, Monitor::QUERY ); if ( monitor && monitor->connect() ) { struct timeval tv = monitor->GetTimestamp(); printf( "%4d%5d%6d%9d%11ld.%02ld%6d%6d%8d%8.2f\n", monitor->Id(), function, monitor->GetState(), monitor->GetTriggerState(), tv.tv_sec, tv.tv_usec/10000, monitor->GetLastReadIndex(), monitor->GetLastWriteIndex(), monitor->GetLastEvent(), monitor->GetFPS() ); delete monitor; } } else { struct timeval tv = { 0, 0 }; printf( "%4d%5d%6d%9d%11ld.%02ld%6d%6d%8d%8.2f\n", mon_id, function, 0, 0, tv.tv_sec, tv.tv_usec/10000, 0, 0, 0, 0.0 ); } } } mysql_free_result( result ); } } delete user; logTerm(); zmDbClose(); return( 0 ); }
tSirRetStatus macOpen(tHalHandle *pHalHandle, tHddHandle hHdd, tMacOpenParameters *pMacOpenParms) { tpAniSirGlobal pMac = NULL; if(pHalHandle == NULL) return eSIR_FAILURE; /* * Make sure this adapter is not already opened. (Compare pAdaptor pointer in already * allocated pMac structures.) * If it is opened just return pointer to previously allocated pMac pointer. * Or should this result in error? */ /* Allocate pMac */ if (palAllocateMemory(hHdd, ((void **)&pMac), sizeof(tAniSirGlobal)) != eHAL_STATUS_SUCCESS) return eSIR_FAILURE; /* Initialize the pMac structure */ palZeroMemory(hHdd, pMac, sizeof(tAniSirGlobal)); /** Store the Driver type in pMac Global.*/ //pMac->gDriverType = pMacOpenParms->driverType; #ifndef GEN6_ONWARDS #ifdef RTL8652 { //Leverage 8651c's on-chip data scratchpad memory to lock all HAL DxE data there extern void * rtlglue_alloc_data_scratchpad_memory(unsigned int size, char *); pMac->hal.pHalDxe = (tpAniHalDxe) rtlglue_alloc_data_scratchpad_memory(sizeof(tAniHalDxe), "halDxe"); } if(pMac->hal.pHalDxe){ ; }else #endif /* Allocate HalDxe */ if (palAllocateMemory(hHdd, ((void **)&pMac->hal.pHalDxe), sizeof(tAniHalDxe)) != eHAL_STATUS_SUCCESS){ palFreeMemory(hHdd, pMac); return eSIR_FAILURE; } /* Initialize the HalDxe structure */ palZeroMemory(hHdd, pMac->hal.pHalDxe, sizeof(tAniHalDxe)); #endif //GEN6_ONWARDS /* * Set various global fields of pMac here * (Could be platform dependant as some variables in pMac are platform * dependant) */ pMac->hHdd = hHdd; pMac->pAdapter = hHdd; //This line wil be removed *pHalHandle = (tHalHandle)pMac; { /* Call various PE (and other layer init here) */ if( eSIR_SUCCESS != logInit(pMac)) return eSIR_FAILURE; /* Call routine to initialize CFG data structures */ if( eSIR_SUCCESS != cfgInit(pMac) ) return eSIR_FAILURE; sysInitGlobals(pMac); #ifdef FEATURE_WLAN_NON_INTEGRATED_SOC // This decides whether HW needs to translate the 802.3 frames // from the host OS to the 802.11 frames. When set HW does the // translation from 802.3 to 802.11 and vice versa if(pMacOpenParms->frameTransRequired) { pMac->hal.halMac.frameTransEnabled = 1; } else { pMac->hal.halMac.frameTransEnabled = 0; } #endif //Need to do it here in case halOpen fails later on. #if defined( VOSS_ENABLED ) tx_voss_wrapper_init(pMac, hHdd); #endif } #ifdef FEATURE_WLAN_NON_INTEGRATED_SOC if (eHAL_STATUS_SUCCESS != halOpen(pMac, pHalHandle, hHdd, pMacOpenParms)) return eSIR_FAILURE; #endif return peOpen(pMac, pMacOpenParms); }
int main( int argc, char *argv[] ) { self = argv[0]; srand( getpid() * time( 0 ) ); const char *device = ""; const char *protocol = ""; const char *host = ""; const char *port = ""; const char *path = ""; const char *file = ""; int monitor_id = -1; static struct option long_options[] = { {"device", 1, 0, 'd'}, {"protocol", 1, 0, 'r'}, {"host", 1, 0, 'H'}, {"port", 1, 0, 'P'}, {"path", 1, 0, 'p'}, {"file", 1, 0, 'f'}, {"monitor", 1, 0, 'm'}, {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {0, 0, 0, 0} }; while (1) { int option_index = 0; int c = getopt_long (argc, argv, "d:H:P:p:f:m:h:v", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'd': device = optarg; break; case 'H': host = optarg; break; case 'P': port = optarg; break; case 'p': path = optarg; break; case 'f': file = optarg; break; case 'm': monitor_id = atoi(optarg); break; case 'h': case '?': Usage(); break; case 'v': std::cout << ZM_VERSION << "\n"; exit(0); default: //fprintf( stderr, "?? getopt returned character code 0%o ??\n", c ); break; } } if (optind < argc) { fprintf( stderr, "Extraneous options, " ); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); Usage(); } int modes = ( device[0]?1:0 + host[0]?1:0 + file[0]?1:0 + (monitor_id>0?1:0) ); if ( modes > 1 ) { fprintf( stderr, "Only one of device, host/port/path, file or monitor id allowed\n" ); Usage(); exit( 0 ); } if ( modes < 1 ) { fprintf( stderr, "One of device, host/port/path, file or monitor id must be specified\n" ); Usage(); exit( 0 ); } char log_id_string[32] = ""; if ( device[0] ) { const char *slash_ptr = strrchr( device, '/' ); snprintf( log_id_string, sizeof(log_id_string), "zmc_d%s", slash_ptr?slash_ptr+1:device ); } else if ( host[0] ) { snprintf( log_id_string, sizeof(log_id_string), "zmc_h%s", host ); } else if ( file[0] ) { const char *slash_ptr = strrchr( file, '/' ); snprintf( log_id_string, sizeof(log_id_string), "zmc_f%s", slash_ptr?slash_ptr+1:file ); } else { snprintf( log_id_string, sizeof(log_id_string), "zmc_m%d", monitor_id ); } zmLoadConfig(); logInit( log_id_string ); ssedetect(); Monitor **monitors = 0; int n_monitors = 0; #if ZM_HAS_V4L if ( device[0] ) { n_monitors = Monitor::LoadLocalMonitors( device, monitors, Monitor::CAPTURE ); } else #endif // ZM_HAS_V4L if ( host[0] ) { if ( !port ) port = "80"; n_monitors = Monitor::LoadRemoteMonitors( protocol, host, port, path, monitors, Monitor::CAPTURE ); } else if ( file[0] ) { n_monitors = Monitor::LoadFileMonitors( file, monitors, Monitor::CAPTURE ); } else { Monitor *monitor = Monitor::Load( monitor_id, true, Monitor::CAPTURE ); if ( monitor ) { monitors = new Monitor *[1]; monitors[0] = monitor; n_monitors = 1; } } if ( !n_monitors ) { Error( "No monitors found" ); exit ( -1 ); } Info( "Starting Capture version %s", ZM_VERSION ); zmSetDefaultTermHandler(); zmSetDefaultDieHandler(); sigset_t block_set; sigemptyset( &block_set ); sigaddset( &block_set, SIGUSR1 ); sigaddset( &block_set, SIGUSR2 ); if ( monitors[0]->PrimeCapture() < 0 ) { Error( "Failed to prime capture of initial monitor" ); exit( -1 ); } long *capture_delays = new long[n_monitors]; long *alarm_capture_delays = new long[n_monitors]; long *next_delays = new long[n_monitors]; struct timeval * last_capture_times = new struct timeval[n_monitors]; for ( int i = 0; i < n_monitors; i++ ) { last_capture_times[i].tv_sec = last_capture_times[i].tv_usec = 0; capture_delays[i] = monitors[i]->GetCaptureDelay(); alarm_capture_delays[i] = monitors[i]->GetAlarmCaptureDelay(); } int result = 0; struct timeval now; struct DeltaTimeval delta_time; while( !zm_terminate ) { sigprocmask( SIG_BLOCK, &block_set, 0 ); for ( int i = 0; i < n_monitors; i++ ) { long min_delay = MAXINT; gettimeofday( &now, NULL ); for ( int j = 0; j < n_monitors; j++ ) { if ( last_capture_times[j].tv_sec ) { DELTA_TIMEVAL( delta_time, now, last_capture_times[j], DT_PREC_3 ); if ( monitors[i]->GetState() == Monitor::ALARM ) next_delays[j] = alarm_capture_delays[j]-delta_time.delta; else next_delays[j] = capture_delays[j]-delta_time.delta; if ( next_delays[j] < 0 ) next_delays[j] = 0; } else { next_delays[j] = 0; } if ( next_delays[j] <= min_delay ) { min_delay = next_delays[j]; } } if ( next_delays[i] <= min_delay || next_delays[i] <= 0 ) { if ( monitors[i]->PreCapture() < 0 ) { Error( "Failed to pre-capture monitor %d %d (%d/%d)", monitors[i]->Id(), monitors[i]->Name(), i+1, n_monitors ); zm_terminate = true; result = -1; break; } if ( monitors[i]->Capture() < 0 ) { Error( "Failed to capture image from monitor %d %s (%d/%d)", monitors[i]->Id(), monitors[i]->Name(), i+1, n_monitors ); zm_terminate = true; result = -1; break; } if ( monitors[i]->PostCapture() < 0 ) { Error( "Failed to post-capture monitor %d %s (%d/%d)", monitors[i]->Id(), monitors[i]->Name(), i+1, n_monitors ); zm_terminate = true; result = -1; break; } if ( next_delays[i] > 0 ) { gettimeofday( &now, NULL ); DELTA_TIMEVAL( delta_time, now, last_capture_times[i], DT_PREC_3 ); long sleep_time = next_delays[i]-delta_time.delta; if ( sleep_time > 0 ) { usleep( sleep_time*(DT_MAXGRAN/DT_PREC_3) ); } } gettimeofday( &(last_capture_times[i]), NULL ); } } sigprocmask( SIG_UNBLOCK, &block_set, 0 ); } for ( int i = 0; i < n_monitors; i++ ) { delete monitors[i]; } delete [] monitors; delete [] alarm_capture_delays; delete [] capture_delays; delete [] next_delays; delete [] last_capture_times; logTerm(); zmDbClose(); return( result ); }
/*********************************************************************************************************************************** Change test log level This is info by default but it can sometimes be useful to set the log level to something else. ***********************************************************************************************************************************/ void harnessLogLevelSet(LogLevel logLevel) { logInit(logLevelTestDefault, logLevelOff, logLevel, false, 99); }
/** * Main program entry point * * This function is the one called by the operating system to start Luna. * * This function sets {@link appArgc appArgc} and {@link appArgv appArgv}. * * @see appArgc * @see appArgv * * @param argc Number of command-line arguments * @param argv Pointer to list of char* of each of the arguments * * @return 0 = success, anything else = failure */ int main( int argc, char** argv) { appArgc = argc; appArgv = argv; std::set_terminate(generateGoodBacktraceTerminateHandler); g_thread_init(NULL); const char *renderMode; #if defined(TARGET_DEVICE) && defined(HAVE_OPENGL) ::setenv("QT_PLUGIN_PATH", "/usr/plugins", 1); renderMode = "HW egl"; #elif defined(TARGET_DEVICE) || defined(TARGET_EMULATOR) ::setenv("QT_PLUGIN_PATH", "/usr/plugins", 1); renderMode = "Software"; #elif defined(HAVE_OPENGL) renderMode = "HW OpenGL"; #else renderMode = "Software"; #endif WindowServer::markBootStart(); g_debug("SysMgr compiled against Qt %s, running on %s, %s render mode requested", QT_VERSION_STR, qVersion(), renderMode); // Command-Line options parseCommandlineOptions(argc, argv); if (s_debugTrapStr && 0 == strcasecmp(s_debugTrapStr, "on")) { debugCrashes = true; } if (s_mallocStatsFileStr) { setupMallocStats(s_mallocStatsFileStr); } sysmgrPid = getpid(); // Load Settings (first!) Settings* settings = Settings::LunaSettings(); // Initialize logging handler g_log_set_default_handler(logFilter, NULL); #if defined(TARGET_DESKTOP) // use terminal logging when running on desktop settings->logger_useTerminal = true; #endif // disable color logging using an environment variable. Useful when run from QtCreator const char* useColor = ::getenv("COLOR_LOGGING"); if (useColor) settings->logger_useColor = (useColor[0] != 0 && useColor[0] != '0'); HostBase* host = HostBase::instance(); // the resolution is just a hint, the actual // resolution may get picked up from the fb driver on arm host->init(settings->displayWidth, settings->displayHeight); #if defined(TARGET_DEVICE) pid_t animPid= spawnBootupAnimationProcess(); if(animPid < 0) { // failed to start the Animation process return -1; } #endif #if defined(TARGET_DEVICE) && defined(HAVE_OPENGL) && defined(HAVE_QPA) if (settings->forceSoftwareRendering) ::setenv("QT_QPA_PLATFORM", "palm-soft", 1); else ::setenv("QT_QPA_PLATFORM", "palm", 1); #endif #if defined(TARGET_DEVICE) && defined(HAVE_OPENGL) if (!settings->forceSoftwareRendering) ::setenv("QWS_DISPLAY", "egl", 1); #endif pid_t webKitPid= spawnWebKitProcess(); if(webKitPid < 0) { // failed to start the WebKit process return -1; } // Tie LunaSysMgr to Processor 0 setCpuAffinity(getpid(), 1); // Tie WebAppMgr to Processor 1 setCpuAffinity(webKitPid, 0); // Safe to create logging threads now logInit(); // Initialize Ipc Server (void) IpcServer::instance(); // Ipc Server is ready, so signal the WebAppMgr process (via pipe) to go ahead and connect ::write(WebAppMgrPipeFd, &msgOkToContinue, 1); ::close(WebAppMgrPipeFd); WebAppMgrPipeFd = -1; #if !defined(TARGET_DESKTOP) // Set "nice" property setpriority(PRIO_PROCESS,getpid(),-1); #endif #if !defined(TARGET_DESKTOP) && !defined(HAVE_QPA) QWSServer::setDefaultMouse("HiddTp"); QWSServer::setDefaultKeyboard("HiddKbd"); ::setenv("QWS_DBLCLICK_DISTANCE", QString("%0").arg(Settings::LunaSettings()->tapRadius).toAscii().constData(), 1); #endif qInstallMsgHandler(qtMsgHandler); QApplication app(argc, argv); QApplication::setStartDragDistance(settings->tapRadius); QApplication::setDoubleClickInterval (Settings::LunaSettings()->tapDoubleClickDuration); host->show(); initMallocStatsCb(HostBase::instance()->mainLoop(), s_mallocStatsInterval); // Initialize Preferences handler (void) Preferences::instance(); // Initialize Localization handler (void) Localization::instance(); //Register vibration/haptics support HapticsController::instance()->startService(); (void) DeviceInfo::instance(); // Initialize Security handler (void) Security::instance(); // Initialize the System Service SystemService::instance()->init(); // Initialize the application mgr ApplicationManager::instance()->init(); // Initialize the Application Installer ApplicationInstaller::instance(); // Start the window manager WindowServer *windowServer = WindowServer::instance(); windowServer->installEventFilter(windowServer); // Initialize the SysMgr MemoryMonitor MemoryMonitor::instance(); // load all set policies EASPolicyManager::instance()->load(); // Launching of the System UI launcher and headless apps has been moved to WebAppMgrProxy::connectWebAppMgr // Did user specify an app to launch if (s_appToLaunchStr) { WebAppMgrProxy::setAppToLaunchUponConnection(s_appToLaunchStr); } app.exec(); return 0; }
tSirRetStatus macOpen(tHalHandle *pHalHandle, tHddHandle hHdd, tMacOpenParameters *pMacOpenParms) { tpAniSirGlobal p_mac = NULL; tSirRetStatus status = eSIR_SUCCESS; uint8_t i =0; bool mem_alloc_failed = false; if(pHalHandle == NULL) return eSIR_FAILURE; /* * Make sure this adapter is not already opened. (Compare pAdapter pointer in already * allocated p_mac structures.) * If it is opened just return pointer to previously allocated p_mac pointer. * Or should this result in error? */ /* Allocate p_mac */ p_mac = vos_mem_malloc(sizeof(tAniSirGlobal)); if (NULL == p_mac) return eSIR_FAILURE; /* Initialize the p_mac structure */ vos_mem_set(p_mac, sizeof(tAniSirGlobal), 0); /* * Set various global fields of p_mac here * (Could be platform dependant as some variables in p_mac are platform * dependant) */ p_mac->hHdd = hHdd; *pHalHandle = (tHalHandle)p_mac; { /* Call various PE (and other layer init here) */ if (eSIR_SUCCESS != logInit(p_mac)) { vos_mem_free(p_mac); return eSIR_FAILURE; } /* Call routine to initialize CFG data structures */ if (eSIR_SUCCESS != cfgInit(p_mac)) { vos_mem_free(p_mac); return eSIR_FAILURE; } sysInitGlobals(p_mac); } /* Set the Powersave Offload Capability to TRUE irrespective of * INI param as it should be always enabled for qca-cld driver */ p_mac->psOffloadEnabled = TRUE; p_mac->scan.nextScanID = FIRST_SCAN_ID; /* FW: 0 to 2047 and Host: 2048 to 4095 */ p_mac->mgmtSeqNum = WLAN_HOST_SEQ_NUM_MIN-1; p_mac->first_scan_done = false; status = peOpen(p_mac, pMacOpenParms); if (eSIR_SUCCESS != status) { sysLog(p_mac, LOGE, FL("macOpen failure\n")); vos_mem_free(p_mac); return status; } for (i=0; i<MAX_DUMP_TABLE_ENTRY; i++) { p_mac->dumpTableEntry[i] = vos_mem_malloc(sizeof(tDumpModuleEntry)); if (NULL == p_mac->dumpTableEntry[i]) { mem_alloc_failed = eANI_BOOLEAN_TRUE; break; } else { vos_mem_set(p_mac->dumpTableEntry[i], sizeof(tSirMbMsg), 0); } } if (mem_alloc_failed) { while (i>0) { i--; vos_mem_free(p_mac->dumpTableEntry[i]); } peClose(p_mac); vos_mem_free(p_mac); return eSIR_FAILURE; } return status; }
int main( int argc, char *argv[] ) { self = argv[0]; srand( getpid() * time( 0 ) ); int id = -1; static struct option long_options[] = { {"monitor", 1, 0, 'm'}, {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {0, 0, 0, 0} }; while (1) { int option_index = 0; int c = getopt_long (argc, argv, "m:h:v", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'm': id = atoi(optarg); break; case 'h': case '?': Usage(); break; case 'v': std::cout << ZM_VERSION << "\n"; exit(0); default: //fprintf( stderr, "?? getopt returned character code 0%o ??\n", c ); break; } } if (optind < argc) { fprintf( stderr, "Extraneous options, " ); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); Usage(); } if ( id < 0 ) { fprintf( stderr, "Bogus monitor %d\n", id ); Usage(); exit( 0 ); } char log_id_string[16]; snprintf( log_id_string, sizeof(log_id_string), "zma_m%d", id ); zmLoadConfig(); logInit( log_id_string ); ssedetect(); Monitor *monitor = Monitor::Load( id, true, Monitor::ANALYSIS ); if ( monitor ) { Info( "In mode %d/%d, warming up", monitor->GetFunction(), monitor->Enabled() ); if ( config.opt_frame_server ) { Event::OpenFrameSocket( monitor->Id() ); } zmSetDefaultHupHandler(); zmSetDefaultTermHandler(); zmSetDefaultDieHandler(); sigset_t block_set; sigemptyset( &block_set ); useconds_t analysis_rate = monitor->GetAnalysisRate(); unsigned int analysis_update_delay = monitor->GetAnalysisUpdateDelay(); time_t last_analysis_update_time, cur_time; monitor->UpdateAdaptiveSkip(); last_analysis_update_time = time( 0 ); while( !zm_terminate ) { // Process the next image sigprocmask( SIG_BLOCK, &block_set, 0 ); // Some periodic updates are required for variable capturing framerate if ( analysis_update_delay ) { cur_time = time( 0 ); if ( ( cur_time - last_analysis_update_time ) > analysis_update_delay ) { analysis_rate = monitor->GetAnalysisRate(); monitor->UpdateAdaptiveSkip(); last_analysis_update_time = cur_time; } } if ( !monitor->Analyse() ) { usleep( monitor->Active()?ZM_SAMPLE_RATE:ZM_SUSPENDED_RATE ); } else if ( analysis_rate ) { usleep( analysis_rate ); } if ( zm_reload ) { monitor->Reload(); zm_reload = false; } sigprocmask( SIG_UNBLOCK, &block_set, 0 ); } delete monitor; } else { fprintf( stderr, "Can't find monitor with id of %d\n", id ); } Image::Deinitialise(); logTerm(); zmDbClose(); return( 0 ); }
int my_usrRoot(char* pMemPoolStart, unsigned int memPoolSize) { eventLibInit(); semBLibInit(); semMLibInit(); semCLibInit(); semQLibInit(); wdLibInit(); taskHookInit(); memInit(pMemPoolStart, memPoolSize); memPartLibInit(pMemPoolStart, memPoolSize); if (proc_sysMmuLibInit == 0) goto usrRoot_failed; int (*_sysMmuLibInit)() = (void*) proc_sysMmuLibInit; if (_sysMmuLibInit(0x1000) != 0) goto usrRoot_failed; if (vmMpuLibInit(0x1000) != 0) goto usrRoot_failed; if (vmBaseGlobalMapInit(&MemDescArray, MemDescArrayCount, 1) == 0) goto usrRoot_failed; sysClockConnect(usrClock, 0); sysClockRateSet(60); sysClockEnable(); selectInit(50); usrBootLineParse(0x1000); iosInit(20, 50, "/null"); ttyDrv(); usrSerialInit(); hashLibInit(); envLibInit(1); sigInit(); excInit(); logInit(fdConsole, 50); stdioInit(); fioLibInit(); selTaskDeleteHookAdd(); sub_FFB5F728(); my_taskcreate_Startup(); return 0; usrRoot_failed: printExc("usrRoot: MMU configuration failed, errno = %#x", *(long*) (GetErrorNumAddr()), 0, 0, 0, 0); reboot(1); return 0; }
Logger::Logger(std::string LogFileArg) { logInit( LogFileArg, DEFAULTBUFFER ); }
int main( int argc, const char *argv[] ) { self = argv[0]; srand( getpid() * time( 0 ) ); enum { ZMS_MONITOR, ZMS_EVENT } source = ZMS_MONITOR; enum { ZMS_JPEG, ZMS_MPEG, ZMS_RAW, ZMS_ZIP, ZMS_SINGLE } mode = ZMS_JPEG; char format[32] = ""; int monitor_id = 0; time_t event_time = 0; int event_id = 0; unsigned int frame_id = 1; unsigned int scale = 100; unsigned int rate = 100; double maxfps = 10.0; unsigned int bitrate = 100000; unsigned int ttl = 0; EventStream::StreamMode replay = EventStream::MODE_SINGLE; char username[64] = ""; char password[64] = ""; char auth[64] = ""; unsigned int connkey = 0; unsigned int playback_buffer = 0; bool nph = false; const char *basename = strrchr( argv[0], '/' ); if (basename) //if we found a / lets skip past it basename++; else //argv[0] will not always contain the full path, but rather just the script name basename = argv[0]; const char *nph_prefix = "nph-"; if ( basename && !strncmp( basename, nph_prefix, strlen(nph_prefix) ) ) { nph = true; } zmLoadConfig(); logInit( "zms" ); ssedetect(); zmSetDefaultTermHandler(); zmSetDefaultDieHandler(); const char *query = getenv( "QUERY_STRING" ); if ( query ) { Debug( 1, "Query: %s", query ); char temp_query[1024]; strncpy( temp_query, query, sizeof(temp_query) ); char *q_ptr = temp_query; char *parms[16]; // Shouldn't be more than this int parm_no = 0; while( (parm_no < 16) && (parms[parm_no] = strtok( q_ptr, "&" )) ) { parm_no++; q_ptr = NULL; } for ( int p = 0; p < parm_no; p++ ) { char *name = strtok( parms[p], "=" ); char *value = strtok( NULL, "=" ); if ( !value ) value = (char *)""; if ( !strcmp( name, "source" ) ) { source = !strcmp( value, "event" )?ZMS_EVENT:ZMS_MONITOR; } else if ( !strcmp( name, "mode" ) ) { mode = !strcmp( value, "jpeg" )?ZMS_JPEG:ZMS_MPEG; mode = !strcmp( value, "raw" )?ZMS_RAW:mode; mode = !strcmp( value, "zip" )?ZMS_ZIP:mode; mode = !strcmp( value, "single" )?ZMS_SINGLE:mode; } else if ( !strcmp( name, "format" ) ) strncpy( format, value, sizeof(format) ); else if ( !strcmp( name, "monitor" ) ) monitor_id = atoi( value ); else if ( !strcmp( name, "time" ) ) event_time = atoi( value ); else if ( !strcmp( name, "event" ) ) event_id = strtoull( value, (char **)NULL, 10 ); else if ( !strcmp( name, "frame" ) ) frame_id = strtoull( value, (char **)NULL, 10 ); else if ( !strcmp( name, "scale" ) ) scale = atoi( value ); else if ( !strcmp( name, "rate" ) ) rate = atoi( value ); else if ( !strcmp( name, "maxfps" ) ) maxfps = atof( value ); else if ( !strcmp( name, "bitrate" ) ) bitrate = atoi( value ); else if ( !strcmp( name, "ttl" ) ) ttl = atoi(value); else if ( !strcmp( name, "replay" ) ) { replay = !strcmp( value, "gapless" )?EventStream::MODE_ALL_GAPLESS:EventStream::MODE_SINGLE; replay = !strcmp( value, "all" )?EventStream::MODE_ALL:replay; } else if ( !strcmp( name, "connkey" ) ) connkey = atoi(value); else if ( !strcmp( name, "buffer" ) ) playback_buffer = atoi(value); else if ( config.opt_use_auth ) { if ( strcmp( config.auth_relay, "none" ) == 0 ) { if ( !strcmp( name, "user" ) ) { strncpy( username, value, sizeof(username) ); } } else { //if ( strcmp( config.auth_relay, "hashed" ) == 0 ) { if ( !strcmp( name, "auth" ) ) { strncpy( auth, value, sizeof(auth) ); } } //else if ( strcmp( config.auth_relay, "plain" ) == 0 ) { if ( !strcmp( name, "user" ) ) { strncpy( username, value, sizeof(username) ); } if ( !strcmp( name, "pass" ) ) { strncpy( password, value, sizeof(password) ); } } } } } } if ( config.opt_use_auth ) { User *user = 0; if ( strcmp( config.auth_relay, "none" ) == 0 ) { if ( *username ) { user = zmLoadUser( username ); } } else { //if ( strcmp( config.auth_relay, "hashed" ) == 0 ) { if ( *auth ) { user = zmLoadAuthUser( auth, config.auth_hash_ips ); } } //else if ( strcmp( config.auth_relay, "plain" ) == 0 ) { if ( *username && *password ) { user = zmLoadUser( username, password ); } } } if ( !user ) { Error( "Unable to authenticate user" ); logTerm(); zmDbClose(); return( -1 ); } ValidateAccess( user, monitor_id ); } setbuf( stdout, 0 ); if ( nph ) { fprintf( stdout, "HTTP/1.0 200 OK\r\n" ); } fprintf( stdout, "Server: ZoneMinder Video Server/%s\r\n", ZM_VERSION ); time_t now = time( 0 ); char date_string[64]; strftime( date_string, sizeof(date_string)-1, "%a, %d %b %Y %H:%M:%S GMT", gmtime( &now ) ); fprintf( stdout, "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n" ); fprintf( stdout, "Last-Modified: %s\r\n", date_string ); fprintf( stdout, "Cache-Control: no-store, no-cache, must-revalidate\r\n" ); fprintf( stdout, "Cache-Control: post-check=0, pre-check=0\r\n" ); fprintf( stdout, "Pragma: no-cache\r\n"); // Removed as causing more problems than it fixed. //if ( !nph ) //{ //fprintf( stdout, "Content-Length: 0\r\n"); //} if ( source == ZMS_MONITOR ) { MonitorStream stream; stream.setStreamScale( scale ); stream.setStreamReplayRate( rate ); stream.setStreamMaxFPS( maxfps ); stream.setStreamTTL( ttl ); stream.setStreamQueue( connkey ); stream.setStreamBuffer( playback_buffer ); if ( ! stream.setStreamStart( monitor_id ) ) { Error( "Unable to connect to zmc process for monitor %d", monitor_id ); fprintf( stderr, "Unable to connect to zmc process. Please ensure that it is running." ); logTerm(); zmDbClose(); return( -1 ); } if ( mode == ZMS_JPEG ) { stream.setStreamType( MonitorStream::STREAM_JPEG ); } else if ( mode == ZMS_RAW ) { stream.setStreamType( MonitorStream::STREAM_RAW ); } else if ( mode == ZMS_ZIP ) { stream.setStreamType( MonitorStream::STREAM_ZIP ); } else if ( mode == ZMS_SINGLE ) { stream.setStreamType( MonitorStream::STREAM_SINGLE ); } else { #if HAVE_LIBAVCODEC stream.setStreamFormat( format ); stream.setStreamBitrate( bitrate ); stream.setStreamType( MonitorStream::STREAM_MPEG ); #else // HAVE_LIBAVCODEC Error( "MPEG streaming of '%s' attempted while disabled", query ); fprintf( stderr, "MPEG streaming is disabled.\nYou should configure with the --with-ffmpeg option and rebuild to use this functionality.\n" ); logTerm(); zmDbClose(); return( -1 ); #endif // HAVE_LIBAVCODEC } stream.runStream(); } else if ( source == ZMS_EVENT ) { EventStream stream; stream.setStreamScale( scale ); stream.setStreamReplayRate( rate ); stream.setStreamMaxFPS( maxfps ); stream.setStreamMode( replay ); stream.setStreamQueue( connkey ); if ( monitor_id && event_time ) { stream.setStreamStart( monitor_id, event_time ); } else { stream.setStreamStart( event_id, frame_id ); } if ( mode == ZMS_JPEG ) { stream.setStreamType( EventStream::STREAM_JPEG ); } else { #if HAVE_LIBAVCODEC stream.setStreamFormat( format ); stream.setStreamBitrate( bitrate ); stream.setStreamType( EventStream::STREAM_MPEG ); #else // HAVE_LIBAVCODEC Error( "MPEG streaming of '%s' attempted while disabled", query ); fprintf( stderr, "MPEG streaming is disabled.\nYou should ensure the ffmpeg libraries are installed and detected and rebuild to use this functionality.\n" ); logTerm(); zmDbClose(); return( -1 ); #endif // HAVE_LIBAVCODEC } stream.runStream(); } logTerm(); zmDbClose(); return( 0 ); }
int main( int argc, char *argv[] ) { srand( getpid() * time( 0 ) ); int id = -1; static struct option long_options[] = { {"monitor", 1, 0, 'm'}, {"help", 0, 0, 'h'}, {0, 0, 0, 0} }; while (1) { int option_index = 0; int c = getopt_long (argc, argv, "m:h", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'm': id = atoi(optarg); break; case 'h': case '?': Usage(); break; default: //fprintf( stderr, "?? getopt returned character code 0%o ??\n", c ); break; } } if (optind < argc) { fprintf( stderr, "Extraneous options, " ); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); Usage(); } if ( id < 0 ) { fprintf( stderr, "Bogus monitor %d\n", id ); Usage(); exit( 0 ); } char log_id_string[16]; snprintf( log_id_string, sizeof(log_id_string), "zma_m%d", id ); zmLoadConfig(); logInit( log_id_string ); Monitor *monitor = Monitor::Load( id, true, Monitor::ANALYSIS ); if ( monitor ) { Info( "In mode %d/%d, warming up", monitor->GetFunction(), monitor->Enabled() ); if ( config.opt_frame_server ) { Event::OpenFrameSocket( monitor->Id() ); } zmSetDefaultHupHandler(); zmSetDefaultTermHandler(); zmSetDefaultDieHandler(); sigset_t block_set; sigemptyset( &block_set ); while( !zm_terminate ) { // Process the next image sigprocmask( SIG_BLOCK, &block_set, 0 ); if ( !monitor->Analyse() ) { usleep( monitor->Active()?ZM_SAMPLE_RATE:ZM_SUSPENDED_RATE ); } if ( zm_reload ) { monitor->Reload(); zm_reload = false; } sigprocmask( SIG_UNBLOCK, &block_set, 0 ); } delete monitor; } else { fprintf( stderr, "Can't find monitor with id of %d\n", id ); } return( 0 ); }
int main( int argc, char *argv[] ) { self = argv[0]; srand( getpid() * time( 0 ) ); int id = -1; static struct option long_options[] = { {"monitor", 1, 0, 'm'}, {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {0, 0, 0, 0} }; while (1) { int option_index = 0; int c = getopt_long (argc, argv, "m:h:v", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'm': id = atoi(optarg); break; case 'h': case '?': Usage(); break; case 'v': std::cout << ZM_VERSION << "\n"; exit(0); default: //fprintf( stderr, "?? getopt returned character code 0%o ??\n", c ); break; } } if (optind < argc) { fprintf( stderr, "Extraneous options, " ); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); Usage(); } if ( id < 0 ) { fprintf( stderr, "Bogus monitor %d\n", id ); Usage(); exit( 0 ); } char log_id_string[16]; snprintf( log_id_string, sizeof(log_id_string), "m%d", id ); zmLoadConfig(); logInit( "zmf" ); ssedetect(); Monitor *monitor = Monitor::Load( id, false, Monitor::QUERY ); if ( !monitor ) { fprintf( stderr, "Can't find monitor with id of %d\n", id ); exit( -1 ); } char capt_path[PATH_MAX]; char anal_path[PATH_MAX]; snprintf( capt_path, sizeof(capt_path), "%s/%d/%%s/%%0%dd-capture.jpg", config.dir_events, monitor->Id(), config.event_image_digits ); snprintf( anal_path, sizeof(anal_path), "%s/%d/%%s/%%0%dd-analyse.jpg", config.dir_events, monitor->Id(), config.event_image_digits ); zmSetDefaultTermHandler(); zmSetDefaultDieHandler(); sigset_t block_set; sigemptyset( &block_set ); int sd = OpenSocket( monitor->Id() ); FrameHeader frame_header = { 0, 0, false, 0 }; //unsigned char *image_data = 0; fd_set rfds; struct timeval timeout; timeout.tv_sec = 1; timeout.tv_usec = 0; while( 1 ) { struct timeval temp_timeout = timeout; FD_ZERO(&rfds); FD_SET(sd, &rfds); int n_found = select( sd+1, &rfds, NULL, NULL, &temp_timeout ); if( n_found == 0 ) { Debug( 1, "Select timed out" ); continue; } else if ( n_found < 0) { Error( "Select error: %s", strerror(errno) ); ReopenSocket( sd, monitor->Id() ); continue; } sigprocmask( SIG_BLOCK, &block_set, 0 ); int n_bytes = read( sd, &frame_header, sizeof(frame_header) ); if ( n_bytes != sizeof(frame_header) ) { if ( n_bytes < 0 ) { Error( "Can't read frame header: %s", strerror(errno) ); } else if ( n_bytes > 0 ) { Error( "Incomplete read of frame header, %d bytes only", n_bytes ); } else { Warning( "Socket closed at remote end" ); } ReopenSocket( sd, monitor->Id() ); continue; } Debug( 1, "Read frame header, expecting %ld bytes of image", frame_header.image_length ); static unsigned char image_data[ZM_MAX_IMAGE_SIZE]; // Read for pipe and loop until bytes expected have been read or an error occurs int bytes_read = 0; do { n_bytes = read( sd, image_data+bytes_read, frame_header.image_length-bytes_read ); if (n_bytes < 0) break; // break on error if (n_bytes < (int)frame_header.image_length) { // print some informational messages if (bytes_read == 0) { Debug(4,"Image read : Short read %d bytes of %d expected bytes",n_bytes,frame_header.image_length); } else if (bytes_read+n_bytes == (int)frame_header.image_length) { Debug(5,"Image read : Read rest of short read: %d bytes read total of %d bytes",n_bytes,frame_header.image_length); } else { Debug(6,"Image read : continuing, read %d bytes (%d so far)", n_bytes, bytes_read+n_bytes); } } bytes_read+= n_bytes; } while (n_bytes>0 && (bytes_read < (ssize_t)frame_header.image_length) ); // Print errors if there was a problem if ( n_bytes < 1 ) { Error( "Only read %d bytes of %d\n", bytes_read, frame_header.image_length); if ( n_bytes < 0 ) { Error( "Can't read frame image data: %s", strerror(errno) ); } else { Warning( "Socket closed at remote end" ); } ReopenSocket( sd, monitor->Id() ); continue; } static char subpath[PATH_MAX] = ""; if ( config.use_deep_storage ) { struct tm *time = localtime( &frame_header.event_time ); snprintf( subpath, sizeof(subpath), "%02d/%02d/%02d/%02d/%02d/%02d", time->tm_year-100, time->tm_mon+1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec ); } else { snprintf( subpath, sizeof(subpath), "%ld", frame_header.event_id ); } static char path[PATH_MAX] = ""; snprintf( path, sizeof(path), frame_header.alarm_frame?anal_path:capt_path, subpath, frame_header.frame_id ); Debug( 1, "Got image, writing to %s", path ); FILE *fd = 0; if ( (fd = fopen( path, "w" )) < 0 ) { Error( "Can't fopen '%s': %s", path, strerror(errno) ); exit( -1 ); } if ( 0 == fwrite( image_data, frame_header.image_length, 1, fd ) ) { Error( "Can't fwrite image data: %s", strerror(errno) ); exit( -1 ); } fclose( fd ); sigprocmask( SIG_UNBLOCK, &block_set, 0 ); } logTerm(); zmDbClose(); }
//===================================== // main program... //------------------------------------- int main(int argc,char*argv[]) { //===================================== // init variables... //------------------------------------- bool uniFont = false; bool noBorder = false; bool fastSetup = false; bool withDialog = false; bool yastMode = false; bool useHwData = false; bool fullScreen = false; bool setInfo = false; bool set3D = false; bool setXIdle = false; bool checkPacs = false; for (int n=0;n<argc;n++) { if (strcmp(argv[n],"-style") == 0) { globalStyle = (char*) malloc (sizeof(char) * 128); sprintf(globalStyle,"%s",argv[n+1]); break; } } //===================================== // check for root priviliges... //------------------------------------- if (! accessAllowed()) { fprintf (stderr,"xapi: only root can do this\n"); usage(); } //===================================== // start logging... //------------------------------------- logInit(); //===================================== // allocate main qt object... //------------------------------------- for (int i=0;i<argc;i++) { QString item (argv[i]); if ((item == "-h") || (item == "--help")) { logExit(); usage(); exit(0); } } QApplication app(argc,argv); //===================================== // get additional options... //------------------------------------- QString* idlePID = NULL; QString* cardName3D = NULL; QString* popUpDialog = NULL; QString* cardDriver = NULL; while (1) { int option_index = 0; static struct option long_options[] = { {"usehwdata" , 0 , 0 , 'u'}, {"fullscreen" , 0 , 0 , 'l'}, {"info" , 0 , 0 , 'i'}, {"yast" , 0 , 0 , 'y'}, {"checkpacs" , 0 , 0 , 'c'}, {"noborder" , 0 , 0 , 'n'}, {"3d" , 1 , 0 , 'D'}, {"driver" , 1 , 0 , 'd'}, {"frameWidth" , 1 , 0 , 'w'}, {"dialog" , 1 , 0 , 'O'}, {"unifont" , 0 , 0 , 'U'}, {"xidle" , 0 , 0 , 'x'}, {"pid" , 1 , 0 , 'p'}, {"fast" , 0 , 0 , 'f'}, {"help" , 0 , 0 , 'h'}, {0 , 0 , 0 , 0 } }; int c = getopt_long ( argc, argv, "uicD:fhxlw:d:yp:nUO:",long_options, &option_index ); if (c == -1) break; switch (c) { case 0: fprintf (stderr,"xapi: option %s", long_options[option_index].name); if (optarg) fprintf (stderr," with arg %s", optarg); fprintf (stderr,"\n"); break; case 'f': fastSetup = true; break; case 'U': uniFont = true; break; case 'O': withDialog = true; popUpDialog = new QString (optarg); break; case 'n': noBorder = true; break; case 'y': yastMode = true; break; case 'w': globalFrameWidth = atoi (optarg); break; case 'u': useHwData = true; break; case 'l': fullScreen = true; break; case 'i': setInfo = true; break; case 'c': checkPacs = true; break; case 'D': set3D = true; cardName3D = new QString (optarg); break; case 'p': idlePID = new QString (optarg); break; case 'd': cardDriver = new QString (optarg); break; case 'x': setXIdle = true; break; case 'h': logExit(); usage(); break; default: logExit(); exit(1); } } //===================================== // check if xapi should act as xidle //------------------------------------- if (setXIdle) { XTimeElapsed* idleTimer = new XTimeElapsed ( idlePID ); app.setMainWidget (idleTimer); idleTimer->show(); return app.exec(); } //===================================== // check md5 sum of current config //------------------------------------- if ((! setInfo) && (! set3D) && (! checkPacs) && (! useHwData) && (! fastSetup) ) { bool createMD5sum = false; QFileInfo xc (MD5CONFIG); if (xc.exists()) { QString mD5Sum = qx(MD5,STDOUT,1,"%s",XCONFIG); QFile mHandle (MD5CONFIG); if (mHandle.open(IO_ReadOnly)) { QString compare; mHandle.readLine(compare,MAX_LINE_LENGTH); mHandle.close(); compare = compare.stripWhiteSpace(); if (compare == mD5Sum) { fastSetup = true; } else { fastSetup = false; } } } else { fastSetup = false; } if (createMD5sum) { QString mD5Sum = qx(MD5,STDOUT,1,"%s",XCONFIG); QFile mHandle (MD5CONFIG); if (mHandle.open(IO_WriteOnly)) { mHandle.writeBlock (mD5Sum.ascii(),mD5Sum.length()); mHandle.close(); } } } //===================================== // check option combinations... //------------------------------------- if (useHwData == true) { fastSetup = false; } //===================================== // set root window cursor to the watch //------------------------------------- setMouseCursor ("watch"); //===================================== // init program... //------------------------------------- QWidget::WFlags wflags = Qt::WType_TopLevel; if (noBorder) { wflags |= Qt::WStyle_Customize | Qt::WStyle_NoBorder; } if (uniFont) { QFont currentFont = QFont( "Helvetica", 12 ); currentFont.setStyleHint( QFont::SansSerif, QFont::PreferBitmap ); currentFont.setRawName (UNIFONT); qApp->setFont (currentFont); } xapi = new XFrame ( globalFrameWidth, wflags ); if (setInfo) { signal (SIGHUP ,gotKill); signal (SIGKILL,gotKill); signal (SIGABRT,gotKill); signal (SIGTERM,gotKill); XInfo infoBox (xapi); infoBox.showIntroBox(); logExit(); setMouseCursor (); exit ( infoBox.returnCode() ); } if (set3D) { XInfo infoBox (xapi); infoBox.show3DBox (*cardName3D,cardDriver); printf("%d\n",infoBox.returnCode()); logExit(); setMouseCursor (); exit ( infoBox.returnCode() ); } if (fastSetup) { xapi->fastSetup = true; } if (useHwData) { xapi->useHwData = true; } if (fullScreen) { xapi->fullScreen = true; } if (yastMode) { xapi->yastMode = true; } //===================================== // check 3D environment //------------------------------------- XStringList packageInfo ( qx (GET3D,STDOUT) ); packageInfo.setSeperator (":"); QString package = packageInfo.getList().at(0); QString real3d = packageInfo.getList().at(1); QString soft3d = packageInfo.getList().at(2); QString general = packageInfo.getList().at(3); QString active = packageInfo.getList().at(4); QString answer = packageInfo.getList().at(5); QString flag = packageInfo.getList().at(6); global3DActive = active.toInt(); QString status1 ("1"); if (checkPacs) { // ... // if the 3D Answer was no, there is no need // to check for any packages or scripts // --- if (answer == "no") { setMouseCursor (); exit (0); } // ... // install the missing packages using YaST2 // sw_single mode // --- if (package != "<none>") { if (setMessage("InstallPackage",xapi)) { status1 = qx ( GETINSTALLED,STDOUT,1,"%s",package.ascii() ); } } setMouseCursor (); exit (0); } //===================================== // remove lilo code file... //------------------------------------- unlink (LILOCODE); //===================================== // init main frame... //------------------------------------- if (! xapi->frameInitialized()) { xapi->setFrame (); } //===================================== // set signal handler... //------------------------------------- signal (SIGUSR2,SIG_IGN); signal (SIGINT ,gotInterrupted); //===================================== // init dialogs... //------------------------------------- XIntro* intro = new XIntro(); XAccessX* xaccess = new XAccessX(); XMouse* mouse = new XMouse(); XCard* card = new XCard(); XDesktop* desktop = new XDesktop(); XDisplayGeometry* geo = new XDisplayGeometry(); XKeyboard* keyboard = new XKeyboard(); XLayout* layout = new XLayout(); XMonitor* monitor = new XMonitor(); XMultihead* multi = new XMultihead(); XTablet* tablet = new XTablet(); XTouchScreen* toucher = new XTouchScreen(); XOpenGL* opengl = new XOpenGL(); XVirtual* virtuals = new XVirtual(); Xvnc* vnc = new Xvnc(); intro -> addTo (xapi); xaccess -> addTo (xapi,intro); mouse -> addTo (xapi,intro); card -> addTo (xapi,intro); desktop -> addTo (xapi,intro); geo -> addTo (xapi,intro); keyboard -> addTo (xapi,intro); layout -> addTo (xapi,intro); monitor -> addTo (xapi,intro); multi -> addTo (xapi,intro); tablet -> addTo (xapi,intro); toucher -> addTo (xapi,intro); opengl -> addTo (xapi,intro); virtuals -> addTo (xapi,intro); vnc -> addTo (xapi,intro); //===================================== // save intro pointer... //------------------------------------- introPointer = intro; //===================================== // make sure the serverlayout structure // is created at least one time //------------------------------------- XLayout* layoutDialog; layoutDialog = (XLayout*) intro -> retrieve (Layout); layoutDialog -> setupLayout(); //===================================== // make sure the card dialog was build // in init stage //------------------------------------- XCard* cardDialog; cardDialog = (XCard*) intro -> retrieve (Card); cardDialog -> showSetupWindow (false); cardDialog -> slotRun (Card); cardDialog -> showSetupWindow (true); //===================================== // call resetPage of the desktop dialog // to check for framebuffer usage //------------------------------------- XDesktop* desktopDialog; desktopDialog = (XDesktop*) intro -> retrieve (Colors); desktopDialog -> resetPage ( PAGE_RELOAD ); //===================================== // add margin around pushbutton texts // this is only needed for QT3 //------------------------------------- #if 1 QObject* obj; QObjectList* l = xapi->queryList( "QPushButton" ); QObjectListIt it( *l ); QDict<char>* mText = xapi->getTextPointer(); while ( (obj=it.current()) != 0 ) { ++it; QPushButton* btn = (QPushButton*) obj; QString text = btn->text(); if (! text.isNull()) { QDictIterator<char> n (*mText); for (; n.current(); ++n) { if (n.current() == text) { QString* newText = new QString(); QTextOStream (newText) << " " << text << " "; mText->replace (n.currentKey(),*newText); break; } } QString addText; QTextOStream (&addText) << " " << text << " "; btn->setText (addText); } } delete l; // ... // special keys which are used dynamically on widgets // with initially other texts // --- QList<char> keyList; keyList.append ( "finish" ); keyList.append ( "Next" ); QListIterator<char> io ( keyList ); for (; io.current(); ++io) { QString key ( io.current() ); QString curText (mText->operator[](key)); QString* newText = new QString(); QTextOStream (newText) << " " << curText << " "; mText->replace (key,*newText); } #endif //===================================== // remove xfine cache directory... //------------------------------------- removeXFineCache(); //===================================== // go to main event loop... //------------------------------------- app.setMainWidget(xapi); xapi -> show(); xapi -> enterEvent ( 0 ); xapi -> activateFirstItem(); setMouseCursor(); if (! withDialog) { intro -> checkDetected(); } else { if ( *popUpDialog == "Monitor" ) { xapi -> runDialog (Monitor); } else if ( *popUpDialog == "Card") { xapi -> runDialog (Card); } else { fprintf (stderr,"xapi: no such dialog: %s\n",popUpDialog->ascii()); exit (1); } } return app.exec(); }
int main(void) { BYTE flgRestart = FALSE; // if TRUE, restart main loop struct ifreq interface; // ioctls to configure network interface struct sockaddr_in myinterface; // Interface address struct sockaddr_in mynetmask; // Interface netmask struct sockaddr_in mybroadcast; // Interface broadcast address int server_sockfd; // Server socket struct sockaddr_in server_address; // Server address and port int heartbeat_sockfd; // Heartbeat socket struct sockaddr_in heartbeat_addr; // Heartbeat address and port int tx_sockfd; // Tx socket int optval, optlen; // Vars for socket options time_t timenow; // Current time time_t xaptick; // Last tick time_t heartbeattick; // Time for next hearbeat tick char heartbeat_msg[1500]; // Buffer for heartbeat messages char buff[1500]; // Buffer for messages fd_set rdfs; // Vars for attent to clients struct timeval tv; struct sockaddr_in client_address; // client address and port socklen_t client_len; int i; // Auxiliary variable // Header verbage //printf("\nHomected xAP-Hub Connector\n"); //printf("Copyright (C) Jose Luis Galindo, 2012\n"); // Create shared memory areas if (!hubSharedMemSetup()) { syslog(LOG_ERR, "main: Error allocating shared resources"); logError("main: Error allocating shared resources"); } // Initialize application init(); logInit(LOG_EVENTS_FILE, LOG_ERRORS_FILE); LIBXML_TEST_VERSION // Create the process process_init("xap-hub", pid_filepath); while(process_state == PROC_RUNNING) { // Load xml file with general settings if (parseXmlSettings(SETTINGS_FILE) > 0) { syslog(LOG_ERR, "main: Failed to parse xml settings document, default values loaded"); logError("main: Failed to parse xml settings document, default values loaded"); if (saveXmlSettings(SETTINGS_FILE) > 0) { syslog(LOG_ERR, "main: Error saving settings file"); logError("main: Error saving settings file"); } } // Use the server socket to get interface properties server_sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (server_sockfd == -1) { syslog(LOG_ERR, "main: Error trying to get interface properties"); logError("main: Error trying to get interface properties"); unlink(pid_filepath); exit(EXIT_FAILURE); } // Set options for the socket optval=1; optlen=sizeof(int); if (setsockopt(server_sockfd, SOL_SOCKET, SO_BROADCAST, (char*)&optval, optlen)) { syslog(LOG_ERR, "main: Error trying to get interface properties"); logError("main: Error trying to get interface properties"); unlink(pid_filepath); exit(EXIT_FAILURE); } optval=1; optlen=sizeof(int); if (setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, optlen)) { syslog(LOG_ERR, "main: Error trying to get interface properties"); logError("main: Error trying to get interface properties"); unlink(pid_filepath); exit(EXIT_FAILURE); } // Query the low-level capabilities of the network interface to get address and netmask memset((char*)&interface, sizeof(interface),0); strcpy(interface.ifr_name, hubConfig->interfacename); // Get the interface address interface.ifr_addr.sa_family = AF_INET; if (ioctl(server_sockfd, SIOCGIFADDR, &interface) != 0) { syslog(LOG_ERR, "main: Could not determine IP address for interface %s", hubConfig->interfacename); logError("main: Could not determine IP address for interface %s", hubConfig->interfacename); unlink(pid_filepath); exit(EXIT_FAILURE); } myinterface.sin_addr.s_addr = ((struct sockaddr_in*)&interface.ifr_broadaddr)->sin_addr.s_addr; //printf("%s: address %s\n", interface.ifr_name, inet_ntoa(((struct sockaddr_in*)&interface.ifr_addr)->sin_addr)); logEvent(TRUE, "main: %s: address %s", interface.ifr_name, inet_ntoa(((struct sockaddr_in*)&interface.ifr_addr)->sin_addr)); // Get the interface netmask interface.ifr_broadaddr.sa_family = AF_INET; if (ioctl(server_sockfd, SIOCGIFNETMASK, &interface) != 0) { syslog(LOG_ERR, "Unable to determine netmask for interface %s", hubConfig->interfacename); logError("main: Unable to determine netmask for interface %s", hubConfig->interfacename); unlink(pid_filepath); exit(EXIT_FAILURE); } mynetmask.sin_addr.s_addr = ((struct sockaddr_in*)&interface.ifr_broadaddr)->sin_addr.s_addr; //printf("%s: netmask %s\n", interface.ifr_name, inet_ntoa(((struct sockaddr_in*)&interface.ifr_netmask)->sin_addr)); logEvent(TRUE, "main: %s: netmask %s", interface.ifr_name, inet_ntoa(((struct sockaddr_in*)&interface.ifr_netmask)->sin_addr)); // Determine the interface broadcast address long int inverted_netmask; inverted_netmask=~mynetmask.sin_addr.s_addr; mybroadcast.sin_addr.s_addr = inverted_netmask | myinterface.sin_addr.s_addr; //printf("%s: broadcast %s\n", interface.ifr_name, inet_ntoa(mybroadcast.sin_addr)); logEvent(TRUE, "main: %s: broadcast %s", interface.ifr_name, inet_ntoa(mybroadcast.sin_addr)); // Set the server socket server_sockfd = socket(AF_INET, SOCK_DGRAM, 0); // Set server address and port memset((char *) &server_address, 0, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); // Receive from any address server_address.sin_port = htons(hubConfig->xap_port); // on this port (Default 3639) // Bind the server socket with the server IP address and port fcntl(server_sockfd, F_SETFL, O_NONBLOCK); if (bind(server_sockfd, (struct sockaddr*)&server_address, sizeof(server_address)) !=0 ) { // if fails then we can assume that a hub is active on this host syslog(LOG_ERR, "main: Port %d is in use", hubConfig->xap_port); syslog(LOG_ERR, "main: Assuming other local hub is active on this host"); logError("main: Port %d is in use", hubConfig->xap_port); logError("main: Assuming other local hub is active on this host"); unlink(pid_filepath); exit(EXIT_FAILURE); } //printf("Listening for messages on port %d\n", g_xap_port); logEvent(TRUE, "main: Listening for messages on port %d", hubConfig->xap_port); // Set the server socket to listen listen(server_sockfd, MAX_QUEUE_BACKLOG); // Set up the Tx socket tx_sockfd = socket(AF_INET, SOCK_DGRAM, 0); // Set up the heartbeat socket, on which we tell the world we are alive and well heartbeat_sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (heartbeat_sockfd == -1) { syslog(LOG_ERR, "main: Heartbeat socket cannot be created"); logError("main: Heartbeat socket cannot be created"); unlink(pid_filepath); exit(EXIT_FAILURE); } // Set options for the heartbeat socket optval = 1; optlen = sizeof(int); if (setsockopt(heartbeat_sockfd, SOL_SOCKET, SO_BROADCAST, (char*)&optval, optlen)) { syslog(LOG_ERR, "main: Unable to set heartbeat socket options"); logError("main: Unable to set heartbeat socket options"); unlink(pid_filepath); exit(EXIT_FAILURE); } // Set up heartbeat address and port memset((char *) &heartbeat_addr, 0, sizeof(heartbeat_addr)); heartbeat_addr.sin_family = AF_INET; heartbeat_addr.sin_port = htons(hubConfig->xap_port); heartbeat_addr.sin_addr.s_addr = mybroadcast.sin_addr.s_addr; //printf("Set heartbeat broadcast on %s:%d\n", inet_ntoa(heartbeat_addr.sin_addr), g_xap_port); logEvent(TRUE, "main: Set heartbeat broadcast on %s:%d", inet_ntoa(heartbeat_addr.sin_addr), hubConfig->xap_port); xaptick = time((time_t*)0); heartbeattick = time((time_t*)0); // force heartbeat on startup //printf("Running...\n"); logEvent(TRUE, "main: Running..."); // Parse heartbeat messages received on broadcast interface // If they originated from this host, add the port number to the list of known ports // Otherwise ignore. // If ordinary header then pass to all known listeners while (!flgRestart && (process_state == PROC_RUNNING)) { // Get current time timenow = time((time_t*)0); // Hub tick, check for alive devices if (timenow - xaptick >= 1) { xaphub_tick(timenow - xaptick); xaptick = timenow; } // Heartbeat tick if (timenow >= heartbeattick) { //printf("Outgoing heartbeat tick %d\n",(int)timenow); logEvent(TRUE, "main: Outgoing heartbeat tick %d",(int)timenow); // Create the heartbeat message xaphub_build_heartbeat(heartbeat_msg); //printf("%s", heartbeat_msg); // Send heartbeat to all external listeners sendto(heartbeat_sockfd, heartbeat_msg, strlen(heartbeat_msg), 0, (struct sockaddr *) &heartbeat_addr, sizeof(heartbeat_addr)); // Send heartbeat to all locally connected apps xaphub_relay(tx_sockfd, heartbeat_msg); // Set next tick heartbeattick = timenow + hubConfig->xap_hbeat; } // Prepare to attent to the clients FD_ZERO(&rdfs); FD_SET(server_sockfd, &rdfs); tv.tv_sec = hubConfig->xap_hbeat; tv.tv_usec = 0; select(server_sockfd + 1, &rdfs, NULL, NULL, &tv); // Select either timed out, or there was data - go look for it. client_len = sizeof(struct sockaddr); i = recvfrom(server_sockfd, buff, sizeof(buff), 0, (struct sockaddr*) &client_address, &client_len); // Check if a message was received if (i != -1) { buff[i]='\0'; // Add NULL to the end of message //printf("Message from client %s:%d\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port)); logEvent(TRUE, "main: Message from client %s:%d", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port)); // Message from my interface if (client_address.sin_addr.s_addr == myinterface.sin_addr.s_addr) { //printf("Message originated from my interface\n"); // If the message received is a heartbeat message, add the client to the relay list xap_handler(buff); // Relay the message to all local apps, the originator will see his own message xaphub_relay(tx_sockfd, buff); } // Message from local client received else if (client_address.sin_addr.s_addr == inet_addr("127.0.0.1")) { //printf("Message from local client\n"); } // Remote message else { //printf("Message originated remotely, relay\n"); // Relay the message to all local apps xaphub_relay(tx_sockfd, buff); } // Clear message memset(buff, 0, sizeof(buff)); } // Check if has to save settings if (hubConfig->saveFlag) { hubConfig->saveFlag = FALSE; // Reset flag if (saveXmlSettings(SETTINGS_FILE) > 0) { syslog(LOG_ERR, "main: Error saving settings file"); logError("main: Error saving settings file"); } } // Check if has to restart if (hubConfig->restartFlag) { hubConfig->restartFlag = FALSE; // Reset flag flgRestart = TRUE; } } // Restore flgRestart flgRestart = FALSE; // Save xml settings if (saveXmlSettings(SETTINGS_FILE) > 0) { syslog(LOG_ERR, "main: Error saving settings file"); logError("main: Error saving settings file"); } // Build a xAP shutdown message xaphub_build_heartbeat_shutdown(heartbeat_msg); // Send shutdown heartbeat message to all external listeners sendto(heartbeat_sockfd, heartbeat_msg, strlen(heartbeat_msg), 0, (struct sockaddr *) &heartbeat_addr, sizeof(heartbeat_addr)); // Send shutdown heartbeat message to all locally connected apps xaphub_relay(tx_sockfd, heartbeat_msg); // Close xAP communications close(server_sockfd); // Close Server socket close(heartbeat_sockfd); // Close Heartbeat socket close(tx_sockfd); // Close Tx socket } // Close shared memory areas hubSharedMemClose(); // Destroy the process process_finish(); return 0; }
int main(int argc, char **argv) { unsigned char index = 0; unsigned char test_result = 0; /* * Initialize memory allocator, list_t for test PDUs, and log generator */ pool_buffer_init(); list_init(&test_pdu_tx_list, NULL); list_init(&test_pdu_rx_list, NULL); logInit(); if (init_pdcp_entity(&pdcp_array[0]) == TRUE && init_pdcp_entity(&pdcp_array[1]) == TRUE) msg("[TEST] PDCP entity initialization OK\n"); else { msg("[TEST] Cannot initialize PDCP entities!\n"); return 1; } /* Initialize PDCP state variables */ for (index = 0; index < 2; ++index) { if (pdcp_init_seq_numbers(&pdcp_array[index]) == FALSE) { msg("[TEST] Cannot initialize sequence numbers of PDCP entity %d!\n", index); exit(1); } else { msg("[TEST] Sequence number state of PDCP entity %d is initialized\n", index); } } #if TEST_RX_AND_TX_WINDOW /* Test TX window */ if (test_tx_window() == FALSE) test_result = 1; /* Test RX window */ if (test_rx_window() == FALSE) test_result = 1; #endif #if TEST_PDCP_DATA_REQUEST_AND_INDICATION /* Test pdcp_data_req() method in pdcp.c */ if (test_pdcp_data_req() == FALSE) test_result = 1; /* Test pdcp_data_ind() method in pdcp.c */ if (test_pdcp_data_ind() == FALSE) test_result = 1; #endif if (test_result) { msg("\n\nOne or more tests failed!\n"); } else { msg("\n\nAll tests are successfull!\n"); } return test_result; }
/** * Purpose: Creates a new instance of the Logger object. * Inputs : None. * Outputs: None. */ Logger::Logger(std::string LogFileArg, int numLines) { logInit(LogFileArg,numLines); }
void main(int argc, char **argv) { ULONG ulSignal; debugInit(); xplInit(); if ( !_getOpt( argc, argv ) ) { debugDone(); xplDone(); exit( 1 ); } if ( !logInit() || !socketInit() || !sqInit() || !dfInit() || !reqInit() || !statInit() || !ifsockInit() ) { puts( "Initialization failed." ); debugDone(); xplDone(); exit( 2 ); } ifpipeInit(); if ( pConfig->fWeaselLogPipe ) weaselInit( pConfig->fWeaselLogToScreen ); signal( SIGINT, sigBreak ); signal( SIGTERM, sigBreak ); sqSetTimer( SIG_CLEANING, 1000 * 3 ); // Internal data clean up. sqSetTimer( SIG_LISTS_STORE, 1000 * 60 * 2 ); // Save data files. sqSetTimer( SIG_POSTPONDED_BACKUP, 1000 ); // Delayed rename tasks. while( ( ulSignal = sqWait() ) != SIG_SHUTDOWN ) { switch( ulSignal ) { case SIG_CLEANING: reqClean(); break; case SIG_LISTS_STORE: reqStoreLists(); break; case SIG_POSTPONDED_BACKUP: dfExecPostpond( FALSE ); break; case SIG_RECONFIGURE: cfgReconfigure(); reqReconfigured(); break; } weaselListenLog(); } weaselDone(); reqStoreLists(); statDone(); socketDone(); // Closes sockets ==> cancel waits... reqDone(); ifpipeDone(); ifsockDone(); dfDone(); sqDone(); logDone(); cfgDone(); debugDone(); xplDone(); #ifdef DEBUG_FILE puts( "Done." ); #endif }
/*********************************************************************************************************************************** Reset test log level Set back to info ***********************************************************************************************************************************/ void harnessLogLevelReset(void) { logInit(logLevelTestDefault, logLevelOff, logLevelInfo, false, 99); }
int main( int argc, char** argv) { appArgc = argc; appArgv = argv; std::set_terminate(generateGoodBacktraceTerminateHandler); g_thread_init(NULL); const char *renderMode; #if defined(TARGET_DEVICE) && defined(HAVE_OPENGL) ::setenv("QT_PLUGIN_PATH", "/usr/plugins", 1); renderMode = "HW egl"; #elif defined(TARGET_DEVICE) || defined(TARGET_EMULATOR) ::setenv("QT_PLUGIN_PATH", "/usr/plugins", 1); renderMode = "Software"; #elif defined(HAVE_OPENGL) renderMode = "HW OpenGL"; #else renderMode = "Software"; #endif g_debug("SysMgr compiled against Qt %s, running on %s, %s render mode requested", QT_VERSION_STR, qVersion(), renderMode); // Command-Line options parseCommandlineOptions(argc, argv); if (s_debugTrapStr && 0 == strcasecmp(s_debugTrapStr, "on")) { debugCrashes = true; } if (s_mallocStatsFileStr) { setupMallocStats(s_mallocStatsFileStr); } sysmgrPid = getpid(); // Load Settings (first!) Settings* settings = Settings::LunaSettings(); // Initialize logging handler g_log_set_default_handler(logFilter, NULL); #if defined(TARGET_DESKTOP) // use terminal logging when running on desktop settings->logger_useTerminal = true; #endif // disable color logging using an environment variable. Useful when run from QtCreator const char* useColor = ::getenv("COLOR_LOGGING"); if (useColor) settings->logger_useColor = (useColor[0] != 0 && useColor[0] != '0'); HostBase* host = HostBase::instance(); // the resolution is just a hint, the actual // resolution may get picked up from the fb driver on arm host->init(settings->displayWidth, settings->displayHeight); #if defined(TARGET_DEVICE) && defined(HAVE_OPENGL) if (settings->forceSoftwareRendering) ::setenv("QT_QPA_PLATFORM", "palm-soft", 0); else ::setenv("QT_QPA_PLATFORM", "palm", 0); #else // Do not override the value if the variable exists ::setenv("QT_QPA_PLATFORM", "palm", 0); #endif #if defined(TARGET_DEVICE) && defined(HAVE_OPENGL) if (!settings->forceSoftwareRendering) ::setenv("QWS_DISPLAY", "egl", 1); #endif // Install the handler for signals that we want to trap: // Note: We install the handlers after we initialize the setting because // we may do something different depending on the settings values. installOuterCrashHandler(SIGILL); installOuterCrashHandler(SIGSEGV); installOuterCrashHandler(SIGTERM); // Not needed anymore? ::prctl(PR_SET_NAME, (unsigned long) "WebAppMgr", 0, 0, 0); ::prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); const HostInfo* info = &(HostBase::instance()->getInfo()); WebAppManager::instance()->setHostInfo(info); initMallocStatsCb(WebAppManager::instance()->mainLoop(), s_mallocStatsInterval); logInit(); // Start the Browser App Launcher #ifdef NO_WEBKIT_INIT //WindowServer::instance()->bootupFinished(); #else WebAppManager::instance()->run(); // Sync execution of the task #endif return 0; }
int __cdecl _tmain(int argc, _TCHAR *argv[]) { HDEVINFO h = NULL; SP_DEVINFO_DATA dev_info_data; ULONG status = 0, problem = 0; BOOL bDevice = FALSE; if (IsWow64()) { logPrint("Your are runing 32bit VirtualMonitor on 64bit windows\n"); logPrint("Please Download 64bit version of VirtualMonitor\n"); return -1; } if (argc < 2 || !strcmp(argv[1], "-h")) { usage(argv); goto out; } GetWinVersion(); if (!isSupport) { logPrint("Unsupported Windows system\n"); goto out; } if (isVista || isWin7) { if (!IsUserAnAdmin()) { logPrint("Access Denied. Administrator permissions are needed to use the selected options."); logPrint("Use an administrator command prompt to complete these tasks."); goto out; } } if (!strcmp(argv[1], "-i")) { FixInfFile(INF); } h = GetDevInfoFromDeviceId(&dev_info_data, DRIVER_NAME); if (!strcmp(argv[1], "-i")) { if (h) { logPrint("Driver already installed\n"); goto out; } if (!logInit()) { goto out; } logPrint("Installing driver, It may take few minutes. please wait\n"); RegClean(); InstallInf(INF); if (isVista || isWin7) { DisableMirror(); } h = GetDevInfoFromDeviceId(&dev_info_data, DRIVER_NAME); if (!h) { logError("GetDevInfo Failed After Driver Installed\n"); } GetDevStatus(h, &dev_info_data, &status, &problem); bDevice = DetectVirtualMonitor(FALSE); logInfo("Driver Status: %x, problem: %x\n", status, problem); if (!bDevice) { DetectVirtualMonitor(TRUE); logPrint("Driver installed Status: %x, problem: %x\n", status, problem); logPrint("Please reboot your system\n"); } else { logPrint("Driver installed successful\n"); } if (isVista || isWin7) { logPrint("Please reboot your system\n"); } } else if (!strcmp(argv[1], "-u")) { if (!h) { logPrint("Driver not found\n"); } else { if (!logInit()) { goto out; } UnInstallDriver(h, &dev_info_data); if (isVista || isWin7) { CleanOemInf(); } RegClean(); logPrint("Driver Uninstalled sucessful, Please Reboot System\n"); } } else { usage(argv); goto out; } out: if (g_logf) fclose(g_logf); if (h) { DestroyDevInfo(h); } exit(0); }