/** * Test dict_setItem(): * Pass valid vals; expect retval is OK * Pass valid vals, return dict must not be NULL * Pass valid vals, return dict must be same addr */ void ut_dict_setItem_000(CuTest* tc) { uint8_t heap[HEAP_SIZE]; pPmObj_t pobj = C_NULL; pPmObj_t pobj_orig; PmReturn_t retval; retval = pm_init(heap, HEAP_SIZE, MEMSPACE_RAM, C_NULL); retval = dict_new(&pobj); pobj_orig = pobj; retval = dict_setItem(pobj, PM_ZERO, PM_ONE); CuAssertTrue(tc, retval == PM_RET_OK); CuAssertPtrNotNull(tc, pobj); CuAssertPtrEquals(tc, pobj_orig, pobj); }
int main(void) { PmReturn_t retval; retval = pm_init(heap, sizeof(heap), MEMSPACE_PROG, usrlib_img); printf("Python initialized; result was 0x%02x.\n", retval); PM_RETURN_IF_ERROR(retval); printf("Running Python...\n"); retval = pm_run((uint8_t *)"main"); printf("\n\nPython finished, return of 0x%02x.\nResetting...\n\n", retval); // Wait a bit, so reset so flash by too fast. DELAY_MS(1000); asm("reset"); return (int)retval; }
int main(){ pm_t *fsm = (pm_t*)malloc(sizeof(pm_t)); printf("init = %d\n" , pm_init(fsm)); printf("adding = %d\n" ,pm_addstring(fsm , "e" , 1)); printf("adding = %d\n" ,pm_addstring(fsm , "be" , 2)); printf("adding = %d\n" ,pm_addstring(fsm , "bd" , 2)); printf("adding = %d\n" ,pm_addstring(fsm , "bcd" , 3)); printf("adding = %d\n" ,pm_addstring(fsm , "cdbcab" , 6)); printf("adding = %d\n" ,pm_addstring(fsm , "bcaa" , 4)); printf("num os states : %d\n" , fsm->newstate); print(fsm->zerostate->_transitions); pm_makeFSM(fsm); }
void savebmp(const char *filename, float wf, float hf, int dpi, std::vector< std::vector <Pixel> >* data) { /* Example program fragment to read a PAM or PNM image from stdin, add up the values of every sample in it (I don't know why), and write the image unchanged to stdout. */ FILE* f = fopen(filename,"wb"); pm_init(filename, 0); pixel** truePix = ppm_allocarray(wf,hf); for (int i = 0; i < wf; i++) { for (int j = 0; j < hf; j++) { PPM_ASSIGN(truePix[i][j],data->at(i).at(j).getColor()->getRed(), data->at(i).at(j).getColor()->getGreen(), data->at(i).at(j).getColor()->getBlue()); } } ppm_writeppm(f, truePix, (int)wf, (int)hf, 256, 0); ppm_freearray(truePix, (int)hf); }
void ds2_init(void) { pfunc *p; write_c0_status(0x10000400); memcpy((void *)A_K0BASE, except_common_entry, 0x20); memcpy((void *)(A_K0BASE + 0x180), except_common_entry, 0x20); memcpy((void *)(A_K0BASE + 0x200), except_common_entry, 0x20); __dcache_writeback_all(); __icache_invalidate_all(); init_perihery(); InitExcept(); _intc_init(); detect_clock(); // gpio_init(); // serial_init(); pm_init(); //dgprintf("\n\nOS initial!\n"); // OSInit(); /* Invoke constroctor functions when needed. */ #if 1 for (p=&__CTOR_END__[-1]; p >= __CTOR_LIST__; p--) { printf("create class %08x\n",p); (*p)(); } //dgprintf("Before main function\n"); #endif //Start system ticker _StartSysTimer(); //enable global interrupt sti(); }
/** * Test dict_clear(): * Pass non-dict object; expect TypeError * Pass empty dict; expect retval is OK * Pass empty dict; expect dict is not C_NULL * Pass empty dict; expect length is 0 * Pass non-empty dict; expect length is 0 */ void ut_dict_clear_000(CuTest *tc) { uint8_t heap[HEAP_SIZE]; pPmObj_t pobj = C_NULL; PmReturn_t retval; retval = pm_init(heap, HEAP_SIZE, MEMSPACE_RAM, C_NULL); retval = dict_new(&pobj); retval = dict_clear(PM_ONE); CuAssertTrue(tc, retval == PM_RET_EX_TYPE); retval = dict_clear(pobj); CuAssertTrue(tc, retval == PM_RET_OK); CuAssertPtrNotNull(tc, pobj); CuAssertTrue(tc, ((pPmDict_t)pobj)->length == 0); retval = dict_setItem(pobj, PM_ZERO, PM_ONE); retval = dict_clear(pobj); CuAssertTrue(tc, retval == PM_RET_OK); CuAssertTrue(tc, ((pPmDict_t)pobj)->length == 0); }
/** * Test dict_setItem(): * Pass valid vals, set(k,v); dict length must be 1 * Pass valid vals, set(k,v); item at k must be same v * Pass valid vals, set(k,v1); set(k,v2), item at k must be v2 */ void ut_dict_setItem_001(CuTest* tc) { uint8_t heap[HEAP_SIZE]; pPmObj_t pobj = C_NULL; pPmObj_t pval; PmReturn_t retval; retval = pm_init(heap, HEAP_SIZE, MEMSPACE_RAM, C_NULL); retval = dict_new(&pobj); retval = dict_setItem(pobj, PM_ZERO, PM_ONE); CuAssertTrue(tc, ((pPmDict_t)pobj)->length == 1); retval = dict_getItem(pobj, PM_ZERO, &pval); CuAssertTrue(tc, retval == PM_RET_OK); CuAssertPtrEquals(tc, PM_ONE, pval); retval = dict_setItem(pobj, PM_ZERO, PM_NEGONE); retval = dict_getItem(pobj, PM_ZERO, &pval); CuAssertTrue(tc, retval == PM_RET_OK); CuAssertPtrEquals(tc, PM_NEGONE, pval); }
int main(void) { PmReturn_t retval; retval = pm_init(heap, sizeof(heap), MEMSPACE_PROG, usrlib_img); printf("Python initialized; result was 0x%02x.\n", retval); PM_RETURN_IF_ERROR(retval); printf("Running Python...\n"); // Uncommon one or the other to run the main code, or // to run sample code. retval = pm_run((uint8_t *) "main"); //retval = pm_run((uint8_t *) "sample_lib"); printf("\n\nPython finished, return of 0x%02x.\nResetting...\n\n", retval); // Wait a bit, so reset won't flash by too fast. DELAY_MS(1000); asm("reset"); return (int)retval; }
/** * Tests interpret(): * retval is OK */ void ut_interp_interpret_000(CuTest *tc) { PmReturn_t retval; uint8_t const *pimg = test_code_image0; pPmObj_t pcodeobject; pPmObj_t pmodule; pm_init(MEMSPACE_RAM, C_NULL); /* Check the return value of the load function */ retval = obj_loadFromImg(MEMSPACE_PROG, &pimg, &pcodeobject); CuAssertTrue(tc, retval == PM_RET_OK); retval = mod_new(pcodeobject, &pmodule); CuAssertTrue(tc, retval == PM_RET_OK); retval = interp_addThread((pPmFunc_t)pmodule); CuAssertTrue(tc, retval == PM_RET_OK); /* Check that the module is interpreted and its return value is ok */ retval = interpret(C_TRUE); CuAssertTrue(tc, retval == PM_RET_OK); }
/** * Unit Test ported from SNARF * This tests if it correctly creates the dictionary object * This also tests if dict_setItem correctly replaces the existing value * if the new val has the same key as the exisiting one. */ void ut_dict_getItem_001(CuTest *tc) { uint8_t heap[HEAP_SIZE]; p_test_str1 = test_str1; p_test_str2 = test_str2; p_test_str3 = test_str3; p_test_strnew = test_strnew; PmReturn_t retval; retval = pm_init(heap, HEAP_SIZE, MEMSPACE_RAM, C_NULL); retval = string_new((uint8_t const **)&test_str1, &p_firstval); retval = string_new((uint8_t const **)&test_str2, &p_secondval); retval = string_new((uint8_t const **)&test_str3, &p_thirdval); retval = string_new((uint8_t const **)&test_strnew, &p_newval); retval = int_new(1, (pPmObj_t *)&p_firstkey); retval = int_new(2, (pPmObj_t *)&p_secondkey); retval = int_new(3, (pPmObj_t *)&p_thirdkey); retval = int_new(2, (pPmObj_t *)&p_newkey); dict_new(&p_dict); dict_setItem(p_dict, (pPmObj_t)p_firstkey, p_firstval); dict_setItem(p_dict, (pPmObj_t)p_secondkey, p_secondval); dict_setItem(p_dict, (pPmObj_t)p_thirdkey, p_thirdval); dict_setItem(p_dict, (pPmObj_t)p_newkey, p_newval); dict_setItem(p_dict, (pPmObj_t)p_secondkey, p_secondval); dict_getItem(p_dict, (pPmObj_t)p_firstkey, &p_tempobj); CuAssertTrue(tc, obj_compare(p_tempobj, p_firstval) == C_SAME); dict_getItem(p_dict, (pPmObj_t)p_secondkey, &p_tempobj); CuAssertTrue(tc, obj_compare(p_tempobj, p_secondval) == C_SAME); dict_getItem(p_dict, (pPmObj_t)p_thirdkey, &p_tempobj); CuAssertTrue(tc, obj_compare(p_tempobj, p_thirdval) == C_SAME); }
void test_rp_ctx_create(rp_ctx_t **rp_ctx_p) { int rc = SR_ERR_OK; rp_ctx_t *ctx = NULL; ctx = calloc(1, sizeof(*ctx)); assert_non_null(ctx); rc = ac_init(TEST_DATA_SEARCH_DIR, &ctx->ac_ctx); assert_int_equal(SR_ERR_OK, rc); rc = np_init(ctx, &ctx->np_ctx); assert_int_equal(SR_ERR_OK, rc); rc = pm_init(ctx, TEST_INTERNAL_SCHEMA_SEARCH_DIR, TEST_DATA_SEARCH_DIR, &ctx->pm_ctx); assert_int_equal(SR_ERR_OK, rc); rc = dm_init(ctx->ac_ctx, ctx->np_ctx, ctx->pm_ctx, TEST_SCHEMA_SEARCH_DIR, TEST_DATA_SEARCH_DIR, &ctx->dm_ctx); assert_int_equal(SR_ERR_OK, rc); *rp_ctx_p = ctx; }
/* replicate pm_run()'s functionality to allow two initial threads. */ int main(void) { uint8_t heap[HEAP_SIZE]; PmReturn_t retval; pPmObj_t pmodA; pPmObj_t pmodB; pPmObj_t pstring; uint8_t const *pmodstrA = (uint8_t const *)"t075a"; uint8_t const *pmodstrB = (uint8_t const *)"t075b"; retval = pm_init(heap, HEAP_SIZE, MEMSPACE_PROG, usrlib_img); PM_RETURN_IF_ERROR(retval); /* Import modules from global struct */ retval = string_new(&pmodstrA, &pstring); PM_RETURN_IF_ERROR(retval); retval = mod_import(pstring, &pmodA); PM_RETURN_IF_ERROR(retval); retval = string_new(&pmodstrB, &pstring); PM_RETURN_IF_ERROR(retval); retval = mod_import(pstring, &pmodB); PM_RETURN_IF_ERROR(retval); /* Load builtins into thread */ retval = global_setBuiltins((pPmFunc_t)pmodA); retval = global_setBuiltins((pPmFunc_t)pmodB); PM_RETURN_IF_ERROR(retval); /* Interpret the module's bcode */ retval = interp_addThread((pPmFunc_t)pmodA); retval = interp_addThread((pPmFunc_t)pmodB); PM_RETURN_IF_ERROR(retval); retval = interpret(INTERP_RETURN_ON_NO_THREADS); return retval; }
/**@brief Function for the Peer Manager initialization. * * @param[in] erase_bonds Indicates whether bonding information should be cleared from * persistent storage during initialization of the Peer Manager. */ static void peer_manager_init(bool erase_bonds) { ble_gap_sec_params_t sec_param; ret_code_t err_code; err_code = pm_init(); APP_ERROR_CHECK(err_code); if (erase_bonds) { err_code = pm_peers_delete(); APP_ERROR_CHECK(err_code); } memset(&sec_param, 0, sizeof(ble_gap_sec_params_t)); // Security parameters to be used for all security procedures. sec_param.bond = SEC_PARAM_BOND; sec_param.mitm = SEC_PARAM_MITM; sec_param.io_caps = SEC_PARAM_IO_CAPABILITIES; sec_param.oob = SEC_PARAM_OOB; sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE; sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE; sec_param.kdist_own.enc = 1; sec_param.kdist_own.id = 1; sec_param.kdist_peer.enc = 1; sec_param.kdist_peer.id = 1; err_code = pm_sec_params_set(&sec_param); APP_ERROR_CHECK(err_code); err_code = pm_register(pm_evt_handler); APP_ERROR_CHECK(err_code); err_code = fds_register(fds_evt_handler); APP_ERROR_CHECK(err_code); }
int main(int argc, char** argv) { int row; int cols; int rows; int format; bit *imageRow; pm_init(argv[0], 0); pbm_readpbminit(stdin, &cols, &rows, &format); pbm_writepbminit(stdout, cols, rows, 1); imageRow = pbm_allocrow(cols); for (row = 0; row < rows; row++) { if (row > 0) usleep(500000); pbm_readpbmrow(stdin, imageRow, cols, format); pbm_writepbmrow(stdout, imageRow, cols, 1); fflush(stdout); } pgm_freerow(imageRow); return 0; }
int main(void) { uint8_t *heap; PmReturn_t retval; int32_t hs; int8_t i; for (i = 0; i < 4; i++) { hs = formerly_bad_heapsizes[i]; heap = malloc(hs); retval = pm_init(heap, hs, MEMSPACE_PROG, usrlib_img); if (retval != PM_RET_OK) { free(heap); break; } retval = pm_run((uint8_t *)"t380"); free(heap); PM_BREAK_IF_ERROR(retval); } return retval; }
/** * Module task */ static void flightPlanTask(void *parameters) { UAVObjEvent ev; PmReturn_t retval; FlightPlanStatusData status; FlightPlanControlData control; // Setup status object status.Status = FLIGHTPLANSTATUS_STATUS_STOPPED; status.ErrorFileID = 0; status.ErrorLineNum = 0; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_NONE; status.Debug[0] = 0.0; status.Debug[1] = 0.0; FlightPlanStatusSet(&status); // Main thread loop while (1) { // Wait for FlightPlanControl updates while (xQueueReceive(queue, &ev, portMAX_DELAY) != pdTRUE) ; // Get object and check if a start command was sent FlightPlanControlGet(&control); if ( control.Command == FLIGHTPLANCONTROL_COMMAND_START ) { // Init PyMite retval = pm_init(MEMSPACE_PROG, usrlib_img); if (retval == PM_RET_OK) { // Update status FlightPlanStatusGet(&status); status.Status = FLIGHTPLANSTATUS_STATUS_RUNNING; FlightPlanStatusSet(&status); // Run the test script (TODO: load from SD card) retval = pm_run((uint8_t *)"test"); // Check if an error or exception was thrown if (retval == PM_RET_OK || retval == PM_RET_EX_EXIT) { status.Status = FLIGHTPLANSTATUS_STATUS_STOPPED; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_NONE; } else if (retval == PM_RET_EX) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_EXCEPTION; } else if (retval == PM_RET_EX_IO) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_IOERROR; } else if (retval == PM_RET_EX_ZDIV) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_DIVBYZERO; } else if (retval == PM_RET_EX_ASSRT) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_ASSERTERROR; } else if (retval == PM_RET_EX_ATTR) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_ATTRIBUTEERROR; } else if (retval == PM_RET_EX_IMPRT) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_IMPORTERROR; } else if (retval == PM_RET_EX_INDX) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_INDEXERROR; } else if (retval == PM_RET_EX_KEY) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_KEYERROR; } else if (retval == PM_RET_EX_MEM) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_MEMORYERROR; } else if (retval == PM_RET_EX_NAME) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_NAMEERROR; } else if (retval == PM_RET_EX_SYNTAX) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_SYNTAXERROR; } else if (retval == PM_RET_EX_SYS) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_SYSTEMERROR; } else if (retval == PM_RET_EX_TYPE) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_TYPEERROR; } else if (retval == PM_RET_EX_VAL) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_VALUEERROR; } else if (retval == PM_RET_EX_STOP) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_STOPITERATION; } else if (retval == PM_RET_EX_WARN) { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_WARNING; } else { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_UNKNOWNERROR; } // Get file ID and line number of error (if one) status.ErrorFileID = gVmGlobal.errFileId; status.ErrorLineNum = gVmGlobal.errLineNum; } else { status.Status = FLIGHTPLANSTATUS_STATUS_ERROR; status.ErrorType = FLIGHTPLANSTATUS_ERRORTYPE_VMINITERROR; } // Update status object FlightPlanStatusSet(&status); } } }
void pm_proginit(int * const argcP, char * argv[]) { /*---------------------------------------------------------------------------- Do various initialization things that all programs in the Netpbm package, and programs that emulate such programs, should do. This includes processing global options. This includes calling pm_init() to initialize the Netpbm libraries. -----------------------------------------------------------------------------*/ int argn, i; const char * progname; bool showmessages; bool show_version; /* We're supposed to just show the version information, then exit the program. */ bool show_help; /* We're supposed to just tell user where to get help, then exit the program. */ /* Extract program name. */ #ifdef VMS progname = vmsProgname(argcP, argv); #else progname = strrchr( argv[0], '/'); #endif if (progname == NULL) progname = argv[0]; else ++progname; pm_init(progname, 0); /* Check for any global args. */ showmessages = TRUE; show_version = FALSE; show_help = FALSE; pm_plain_output = FALSE; for (argn = 1; argn < *argcP; ++argn) { if (pm_keymatch(argv[argn], "-quiet", 6) || pm_keymatch(argv[argn], "--quiet", 7)) showmessages = FALSE; else if (pm_keymatch(argv[argn], "-version", 8) || pm_keymatch(argv[argn], "--version", 9)) show_version = TRUE; else if (pm_keymatch(argv[argn], "-help", 5) || pm_keymatch(argv[argn], "--help", 6) || pm_keymatch(argv[argn], "-?", 2)) show_help = TRUE; else if (pm_keymatch(argv[argn], "-plain", 6) || pm_keymatch(argv[argn], "--plain", 7)) pm_plain_output = TRUE; else continue; for (i = argn + 1; i <= *argcP; ++i) argv[i - 1] = argv[i]; --(*argcP); } pm_setMessage((unsigned int) showmessages, NULL); if (show_version) { showVersion(); exit( 0 ); } else if (show_help) { pm_error("Use 'man %s' for help.", progname); /* If we can figure out a way to distinguish Netpbm programs from other programs using the Netpbm libraries, we can do better here. */ if (0) showNetpbmHelp(progname); exit(0); } }
inline PmReturn_t pymite() { PmReturn_t retval; bmac_init(14); bmac_rx_pkt_set_buffer (rx_buf, RF_MAX_PAYLOAD_SIZE); bmac_addr_decode_enable(); //set MAC bmac_addr_decode_set_my_mac(MAC_ADDR); // sdp testing sdp_init(MAC_ADDR); uint8_t destId = 1; nrk_time_t wait; wait.secs = 1; wait.nano_secs = 0; int sel = 0; for (;; sel = (sel + 1) % 2) { uint8_t *script = slave_img; for (int i = 0; i < SLAVE_COUNT; i++) { destId = slaves[i]; printf("Sending a script to a node=%x\r\n", destId); /*for (i = 0; i < SDP_MAX_SCRIPT_SIZE; i++) { printf("%x ", script[i]); }*/ int8_t status = sdp_tx_send_script(script, destId, SDP_MAX_SCRIPT_SIZE); // see if script was delivered if(status == NRK_ERROR) nrk_kprintf(PSTR("Script not delivered.\r\n")); else nrk_kprintf(PSTR("Script delivered.\r\n")); // wait to send again nrk_set_next_wakeup(wait); nrk_event_wait(SIG(nrk_wakeup_signal)); } retval = pm_init(MEMSPACE_RAM, usrlib_img); retval = pm_run((uint8_t *)"main"); printf("exit code %x\r\n", retval); } printf("f**k MAC_ADDR=%x\r\n", MAC_ADDR); //PM_RETURN_IF_ERROR(retval); int i; for (i = 0; i < 100000; i++) { i++; i--; } }
void ipm_hpm_start() { int i,j,k,rv; #ifndef HPM_DISABLED #ifdef HPM_PAPI char errstring[PAPI_MAX_STR_LEN]; char event_name[PAPI_MAX_STR_LEN]; #endif if(task.hpm_eventset < 0) { return; } for(i=0;i<MAXSIZE_REGION;i++) { for(j=0;j<MAXSIZE_NEVENTSETS;j++) { for(k=0;k<MAXSIZE_HPMCOUNTERS;k++) { task.hpm_count[i][j][k] = 0; } } } #ifdef HPM_PAPI /* Initialize the low level PAPI library */ rv = PAPI_library_init(PAPI_VER_CURRENT); if(rv != PAPI_VER_CURRENT) { printf("IPM: %d papi_error library_init in hpm_start rv=%d \"%s\"\n", task.mpi_rank, rv, PAPI_strerror(rv)); PAPI_perror(rv, errstring, PAPI_MAX_STR_LEN); perror("PAPI_library_init"); } if(rv == PAPI_OK) { if(task.flags & DEBUG && task.mpi_rank==0) { printf("IPM: %d PAPI_library_init in hpm_start rv=%d \"%s\"\n", task.mpi_rank, rv, PAPI_strerror(rv)); } } #ifdef CPU_PPC450D /* then we are on a bluegene P*/ if (node_rank != 0 ) return; #endif rv = PAPI_num_counters(); if(rv < 0) { PAPI_perror(rv, errstring, PAPI_MAX_STR_LEN); printf("IPM: %d papi_error num_counters in hpm_start rv=%d \"%s\"\n", task.mpi_rank, rv, PAPI_strerror(rv)); } if ((hwinfo = PAPI_get_hardware_info()) == NULL) { PAPI_perror(rv, errstring, PAPI_MAX_STR_LEN); printf("IPM: %d papi_error PAPI_get_hardware_info in hpm_start rv=%d \"%s\"\n", task.mpi_rank, rv, PAPI_strerror(rv)); } else { /* do something clever wrt. formal machine description */ } rv = PAPI_create_eventset(&papi_eventset[0]); if(rv != PAPI_OK) { PAPI_perror(rv, errstring, PAPI_MAX_STR_LEN); printf("IPM: %d papi_error create_eventset in hpmstart rv=%d \"%s\"\n", task.mpi_rank, rv, PAPI_strerror(rv)); } if(0) { printf("PAPI: JIE_DEBUG:: rank %d task.hpm_eventset is %d.\n", task.mpi_rank, task.hpm_eventset); fflush(stdout); } for(i=0;i<MAXSIZE_HPMCOUNTERS;i++) { if (papi_event[task.hpm_eventset][i] != -1) { rv = PAPI_query_event(papi_event[task.hpm_eventset][i]); if (rv != PAPI_OK) { PAPI_perror(rv, errstring, PAPI_MAX_STR_LEN); PAPI_event_code_to_name(papi_event[task.hpm_eventset][i],event_name); printf("IPM: %d papi_error query_event %s %d \"%s\"\n", task.mpi_rank, event_name, rv, PAPI_strerror(rv)); } rv = PAPI_add_event(papi_eventset[0], papi_event[task.hpm_eventset][i]); if(rv != PAPI_OK) { PAPI_perror(rv, errstring, PAPI_MAX_STR_LEN); PAPI_event_code_to_name(papi_event[task.hpm_eventset][i],event_name); printf("IPM: %d papi_error add_event %s %d \"%s\"\n", task.mpi_rank, event_name, rv, PAPI_strerror(rv)); } if(0) { PAPI_event_code_to_name(papi_event[task.hpm_eventset][i],event_name); printf("PAPI: JIE_DEBUG:: rank %d add event %s.\n", task.mpi_rank, event_name); fflush(stdout); } } } rv = PAPI_start(papi_eventset[0]); if (rv != PAPI_OK) { PAPI_perror(rv, errstring, PAPI_MAX_STR_LEN); printf("IPM: %d papi_error: start in hpm_start rv=%d \"%s\"\n", task.mpi_rank, rv, PAPI_strerror(rv)); task.flags &= ~IPM_HPM_ACTIVE; } #endif #ifdef HPM_PMAPI #ifdef AIX51 rv = pm_init(PM_VERIFIED|PM_UNVERIFIED|PM_CAVEAT|PM_GET_GROUPS, &pmapi_info, &pmapi_groups_info); #else rv = pm_initialize(PM_VERIFIED|PM_UNVERIFIED|PM_CAVEAT|PM_GET_GROUPS, &pmapi_info, &pmapi_groups_info,PM_CURRENT); #endif if(rv) { printf("IPM: %d pmapi_error: pm_initialize \n", task.mpi_rank); pm_error("IPM: pmapi : pm_initialize",rv); } for(i=0;i<pmapi_info.maxpmcs;i++) pmapi_prog.events[i]=COUNT_NOTHING; pmapi_prog.mode.w = 0; pmapi_prog.mode.b.user = 1; pmapi_prog.mode.b.proctree = 1; #ifndef POWER3 #ifdef CPU_POWER4 pmapi_prog.mode.b.is_group = 1; if(task.hpm_eventset == 0) { pmapi_prog.events[0] = 60; } if(task.hpm_eventset == 1) { pmapi_prog.events[0] = 59; } if(task.hpm_eventset == 2) { pmapi_prog.events[0] = 5; } if(task.hpm_eventset == 3) { pmapi_prog.events[0] = 58; } if(task.hpm_eventset == 4) { pmapi_prog.events[0] = 53; } #endif #ifdef CPU_POWER5 pmapi_prog.mode.b.is_group = 1; if(task.hpm_eventset == 0) { pmapi_prog.events[0] = 137; } #endif #ifdef CPU_POWER6 pmapi_prog.mode.b.is_group = 1; /* use all the pm_hpm* groups 186 - 195 */ pmapi_prog.events[0] = 186 + task.hpm_eventset; #endif #else for(i=0;i<MAXSIZE_HPMCOUNTERS;i++) { pmapi_prog.events[i] = pmapi_event[task.hpm_eventset][i]; } #endif rv = pm_set_program_mythread(&pmapi_prog); if(rv) { printf("IPM: %d pmapi_error: pm_set_program_mythread\n", task.mpi_rank); pm_error("IPM: pmapi : pm_set_program_mythread",rv); } rv = pm_start_mythread(); if(rv) { printf("IPM: %d pmapi_error: pm_start_mythread\n", task.mpi_rank); pm_error("IPM: pmapi : pm_start_mythread",rv); task.flags &= ~IPM_HPM_ACTIVE; } rv = pm_reset_data_mythread(); if(rv) { printf("IPM: %d pmapi_error: pm_reset_data_mythread\n", task.mpi_rank); } #endif #endif return; }
int main(int argc, char* argv[]) { const size_t imageCount = 28; const size_t test_lfw = 1000; const size_t test_fddb = 1000; const size_t test_nonface = 1000; pm_init(argv[0], 0); std::cout << "initiating network..." << std::endl; Json::Value networkValue; // load neural net setting if (!load_test(networkValue)) { return 0; } NeuralNet::Network network(networkValue); std::cout << "loading settings finished" << std::endl; // train only if the argument is given to this program bool do_train = false; if (argc >= 2 && !strncmp(argv[1], "train", 5)) { do_train = true; } // loading images for evaluation std::vector< std::unique_ptr<NeuralNet::Image> > imageList; for (size_t i = 1; i <= imageCount; i++) { std::ostringstream oss; oss << "eval-image/" << i << ".bmp"; imageList.push_back(preprocessImage( NeuralNet::loadBitmapImage(oss.str().c_str()))); } auto originalImgData = getRawDataFromImages(imageList); imageList.clear(); std::cout << "loading evaluation images (original) finished" << std::endl; std::vector< std::unique_ptr<NeuralNet::Image> > fddbTestImages; if (!load_fddb(fddbTestImages, test_fddb, false)) { std::cout << "error loading FDDB test images" << std::endl; return false; } auto fddbTestData = getRawDataFromImages(fddbTestImages); fddbTestImages.clear(); std::cout << "loading evaluation images (FDDB) finished" << std::endl; // loading LFW images for evaluation std::vector< std::unique_ptr<NeuralNet::Image> > lfwTestImages; std::ifstream lfw_name_file("image-lfw/peopleDevTest.txt"); for (size_t i = 1; i <= test_lfw; i++) { std::string person_line; if (!std::getline(lfw_name_file, person_line)) { std::cout << "end-of-file of LFW names" << std::endl; return 0; } std::istringstream iss(person_line); std::string person_name; std::getline(iss, person_name, '\t'); std::string file_name("image-lfw/"); file_name.append(person_name); file_name.append("/"); file_name.append(person_name); file_name.append("_0001.ppm"); lfwTestImages.push_back(preprocessImage( NeuralNet::loadPPMImage(file_name.c_str()))); } auto lfwTestData = getRawDataFromImages(lfwTestImages); lfwTestImages.clear(); std::cout << "loading evaluation images (LFW) finished" << std::endl; std::vector< std::unique_ptr<NeuralNet::Image> > nonFaceImages; if (!load_nonface_patch(nonFaceImages, test_nonface, 1)) { std::cout << "error loading evaluation non-face images" << std::endl; return 0; } auto nonFaceTestData = getRawDataFromImages(nonFaceImages); nonFaceImages.clear(); std::cout << "loading evaluation images (non-face) finished" << std::endl; // put test sets into the network std::vector< std::vector<int> > clist1; clist1.emplace_back(test_lfw, 0); network.registerTestSet("LFW", std::move(lfwTestData), std::move(clist1)); std::vector< std::vector<int> > clist2; clist2.emplace_back(test_nonface, 1); network.registerTestSet("non-face", std::move(nonFaceTestData), std::move(clist2)); std::vector< std::vector<int> > clist3; clist3.emplace_back(test_fddb, 0); network.registerTestSet("FDDB", std::move(fddbTestData), std::move(clist3)); std::vector< std::vector<int> > clist4; std::vector<int> clist4_temp; for (size_t i = 0; i < 14; i++) clist4_temp.push_back(0); for (size_t i = 0; i < 14; i++) clist4_temp.push_back(1); clist4.push_back(clist4_temp); network.registerTestSet("original", std::move(originalImgData), std::move(clist4)); std::chrono::time_point<std::chrono::system_clock> time_point_start, time_point_finish; if (do_train) { std::vector<float> data; std::vector< std::vector<int> > category; category.push_back(std::vector<int>()); // load face images if (!load_faces(data, category)) { return 0; } std::cout << "loading face images (for training) finished" << std::endl; // load non-face images if (!load_non_faces(data, category)) { return 0; } std::cout << "loading non-face images (for training) finished" << std::endl; std::cout << "training begin, timer start" << std::endl; time_point_start = std::chrono::system_clock::now(); // actual training goes here network.train(data, category); time_point_finish = std::chrono::system_clock::now(); std::cout << "timer finished" << std::endl; } else { network.loadFromFiles(); std::cout << "network weight/bias load complete, timer start" << std::endl; time_point_start = std::chrono::system_clock::now(); network.evaluateTestSets(); time_point_finish = std::chrono::system_clock::now(); std::cout << "timer finished" << std::endl; } std::chrono::duration<double> elapsed_seconds = time_point_finish - time_point_start; std::cout << "elapsed time: " << elapsed_seconds.count() << "s" << std::endl; }
int main (void) { struct pm_context pm; struct pm_list *list, *curdev; int ret; /* A pointer to a function */ pm_init_func pm_init; pm_find_all_func pm_find_all; pm_list_free_func pm_list_free; pm_reset_func pm_reset; pm_identify_func pm_identify; pm_type_func pm_type; pm_open_func pm_open; pm_close_func pm_close; pm_measure_func pm_measure; pm_set_frequency_func pm_set_frequency; pm_set_averages_func pm_set_averages; pm_get_error_string_func pm_get_error_string; pm_library_version_func pm_library_version; pm_blink_func pm_blink; /* Windows handle */ HANDLE handle; /* Load the library */ handle = LoadLibrary("libpm600x.dll"); if (!handle) { printf("Error: can not load library libpm600x.dll\n"); return -1; } /* Get the proc addresses of the library */ pm_init = (pm_init_func)GetProcAddress(handle, "pm_init"); pm_find_all = (pm_find_all_func)GetProcAddress(handle, "pm_find_all"); pm_list_free = (pm_list_free_func)GetProcAddress(handle, "pm_list_free"); pm_reset = (pm_reset_func)GetProcAddress(handle, "pm_reset"); pm_identify = (pm_identify_func)GetProcAddress(handle, "pm_identify"); pm_type = (pm_type_func)GetProcAddress(handle, "pm_type"); pm_open = (pm_open_func)GetProcAddress(handle, "pm_open"); pm_close = (pm_close_func)GetProcAddress(handle, "pm_close"); pm_measure = (pm_measure_func)GetProcAddress(handle, "pm_measure"); pm_set_frequency = (pm_set_frequency_func)GetProcAddress(handle, "pm_set_frequency"); pm_set_averages = (pm_set_averages_func)GetProcAddress(handle, "pm_set_averages"); pm_get_error_string = (pm_get_error_string_func)GetProcAddress(handle, "pm_get_error_string"); pm_library_version = (pm_library_version_func)GetProcAddress(handle, "pm_library_version"); pm_blink = (pm_blink_func)GetProcAddress(handle, "pm_blink"); if (!pm_init || !pm_find_all || !pm_list_free || !pm_reset || !pm_identify || !pm_type || !pm_open || !pm_close || !pm_measure || !pm_set_frequency || !pm_set_averages || !pm_get_error_string || !pm_library_version || !pm_blink) { FreeLibrary(handle); printf ("Error: Can not get Proc Addesses!"); return -1; } printf("Example program for libpm600x %s\n", pm_library_version()); printf("-----------------------------------\n\n"); // initialise our pm_context pm_init(&pm); // find all power meter probes on the bus ret = pm_find_all(&pm, TYPE_PM_ALL, &list); if (!list) { printf("Error: No powermeter probes found\n"); FreeLibrary(handle); return -1; } // list all probes that we have found for (curdev = list; curdev != NULL ;) { if (curdev->type == TYPE_PM_6006) printf("found PM 6006 with serial number %lu\n", curdev->serial); else if (curdev->type == TYPE_PM_6003) printf("found PM 6003 with serial number %lu\n", curdev->serial); curdev = curdev->next; } // open the first power meter that was found ret = pm_open(&pm, list->serial); if (ret < 0) { printf("Error: %i \"%s\"\n", ret, pm_get_error_string(&pm)); pm_list_free(&list); FreeLibrary(handle); return -1; } // blink the probes green led ret = pm_blink(&pm); if (ret < 0) { printf("Error %i, \"%s\"\n", ret, pm_get_error_string(&pm)); pm_list_free(&list); FreeLibrary(handle); return -1; } // set frequency ret = pm_set_frequency(&pm, 1000000000ULL); if (ret < 0) { printf("Error %i, \"%s\"\n", ret, pm_get_error_string(&pm)); pm_list_free(&list); FreeLibrary(handle); return -1; } // set amount of averaging measurements to 255 ret = pm_set_averages(&pm, 255); if (ret < 0) { printf("Error %i, \"%s\"\n", ret, pm_get_error_string(&pm)); pm_list_free(&list); FreeLibrary(handle); return -1; } // measure float power = 0; ret = pm_measure(&pm, &power); if (ret < 0) { printf("Error %i, \"%s\"\n", ret, pm_get_error_string(&pm)); pm_list_free(&list); FreeLibrary(handle); return -1; } printf("Power: %.2f dBm\n", power); // clean up pm_close(&pm); pm_list_free(&list); FreeLibrary(handle); return 0; }
int main(int argc, char *argv[]) { // Get path char *ip = NULL; unsigned short connect_port = 0; unsigned short listen_port = 0; int net_mode = NET_MODE_NONE; int ret = 0; // Path manager if(pm_init() != 0) { err_msgbox(pm_get_errormsg()); return 1; } // Check arguments if(argc >= 2) { if(strcmp(argv[1], "-v") == 0) { printf("OpenOMF v%d.%d.%d\n", V_MAJOR, V_MINOR, V_PATCH); printf("Source available at https://github.com/omf2097/ under MIT License\n"); printf("(C) 2097 Tuomas Virtanen, Andrew Thompson, Hunter and others\n"); goto exit_0; } else if(strcmp(argv[1], "-h") == 0) { printf("Arguments:\n"); printf("-h Prints this help\n"); printf("-c [ip] [port] Connect to server\n"); printf("-l [port] Start server\n"); goto exit_0; } else if(strcmp(argv[1], "-c") == 0) { if(argc >= 3) { ip = strcpy(malloc(strlen(argv[2])+1), argv[2]); } if(argc >= 4) { connect_port = atoi(argv[3]); } net_mode = NET_MODE_CLIENT; } else if(strcmp(argv[1], "-l") == 0) { if(argc >= 3) { listen_port = atoi(argv[2]); } net_mode = NET_MODE_SERVER; } } // Init log #if defined(DEBUGMODE) || defined(STANDALONE_SERVER) if(log_init(0)) { err_msgbox("Error while initializing log!"); goto exit_0; } #else if(log_init(pm_get_local_path(LOG_PATH))) { err_msgbox("Error while initializing log '%s'!", pm_get_local_path(LOG_PATH)); goto exit_0; } #endif // Simple header INFO("Starting OpenOMF v%d.%d.%d", V_MAJOR, V_MINOR, V_PATCH); // Dump pathmanager log pm_log(); // Random seed rand_seed(time(NULL)); // Init stringparser sd_stringparser_lib_init(); // Init config if(settings_init(pm_get_local_path(CONFIG_PATH))) { err_msgbox("Failed to initialize settings file"); goto exit_1; } settings_load(); // Find plugins and make sure they are valid plugins_init(); // Network game override stuff if(ip) { DEBUG("Connect IP overridden to %s", ip); settings_get()->net.net_connect_ip = ip; } if(connect_port > 0 && connect_port < 0xFFFF) { DEBUG("Connect Port overridden to %u", connect_port&0xFFFF); settings_get()->net.net_connect_port = connect_port; } if(listen_port > 0 && listen_port < 0xFFFF) { DEBUG("Listen Port overridden to %u", listen_port&0xFFFF); settings_get()->net.net_listen_port = listen_port; } // Init SDL2 unsigned int sdl_flags = SDL_INIT_TIMER; #ifndef STANDALONE_SERVER sdl_flags |= SDL_INIT_VIDEO; #endif if(SDL_Init(sdl_flags)) { err_msgbox("SDL2 Initialization failed: %s", SDL_GetError()); goto exit_2; } SDL_version sdl_linked; SDL_GetVersion(&sdl_linked); INFO("Found SDL v%d.%d.%d", sdl_linked.major, sdl_linked.minor, sdl_linked.patch); INFO("Running on platform: %s", SDL_GetPlatform()); #ifndef STANDALONE_SERVER if(SDL_InitSubSystem(SDL_INIT_JOYSTICK|SDL_INIT_GAMECONTROLLER|SDL_INIT_HAPTIC)) { err_msgbox("SDL2 Initialization failed: %s", SDL_GetError()); goto exit_2; } // Attempt to find gamecontrollerdb.txt, either from resources or from // built-in header SDL_RWops *rw = SDL_RWFromConstMem(gamecontrollerdb, strlen(gamecontrollerdb)); SDL_GameControllerAddMappingsFromRW(rw, 1); char *gamecontrollerdbpath = malloc(128); snprintf(gamecontrollerdbpath, 128, "%s/gamecontrollerdb.txt", pm_get_local_path(RESOURCE_PATH)); int mappings_loaded = SDL_GameControllerAddMappingsFromFile(gamecontrollerdbpath); if (mappings_loaded > 0) { DEBUG("loaded %d mappings from %s", mappings_loaded, gamecontrollerdbpath); } free(gamecontrollerdbpath); // Load up joysticks INFO("Found %d joysticks attached", SDL_NumJoysticks()); SDL_Joystick *joy; char guidstr[33]; for (int i = 0; i < SDL_NumJoysticks(); i++) { joy = SDL_JoystickOpen(i); if (joy) { SDL_JoystickGUID guid = SDL_JoystickGetGUID(joy); SDL_JoystickGetGUIDString(guid, guidstr, 33); INFO("Opened Joystick %d", i); INFO(" * Name: %s", SDL_JoystickNameForIndex(i)); INFO(" * Number of Axes: %d", SDL_JoystickNumAxes(joy)); INFO(" * Number of Buttons: %d", SDL_JoystickNumButtons(joy)); INFO(" * Number of Balls: %d", SDL_JoystickNumBalls(joy)); INFO(" * Number of Hats: %d", SDL_JoystickNumHats(joy)); INFO(" * GUID : %s", guidstr); } else { INFO("Joystick %d is unsupported", i); } if (SDL_JoystickGetAttached(joy)) { SDL_JoystickClose(joy); } } // Init libDumb dumb_register_stdfiles(); #endif // Init enet if(enet_initialize() != 0) { err_msgbox("Failed to initialize enet"); goto exit_3; } // Initialize engine if(engine_init()) { err_msgbox("Failed to initialize game engine."); goto exit_4; } // Run engine_run(net_mode); // Close everything engine_close(); exit_4: enet_deinitialize(); exit_3: SDL_Quit(); exit_2: dumb_exit(); settings_save(); settings_free(); exit_1: sd_stringparser_lib_deinit(); INFO("Exit."); log_close(); exit_0: if (ip) { free(ip); } plugins_close(); pm_free(); return ret; }
rawTime64 pd_thread::getRawCpuTime_hw() { #ifdef USES_PMAPI // Hardware method, using the PMAPI int ret; static bool need_init = true; if(need_init) { pm_info_t pinfo; #ifdef PMAPI_GROUPS pm_groups_info_t pginfo; ret = pm_init(PM_VERIFIED | PM_CAVEAT | PM_GET_GROUPS, &pinfo, &pginfo); #else ret = pm_init(PM_VERIFIED | PM_CAVEAT, &pinfo); #endif // We ignore the return, but pm_init must be called to initialize the // library if (ret) pm_error("PARADYNos_init: pm_init", ret); need_init = false; } int lwp_to_use; tid_t indexPtr = 0; struct thrdsinfo thrd_buf; if (get_lwp() > 0) lwp_to_use = get_lwp(); else { /* If we need to get the data for the entire process (ie. get_lwp() == 0) then we need to the pm_get_data_group function requires any lwp in the group, so we'll grab the lwp of any active thread in the process */ if(getthrds(pd_proc->getPid(), &thrd_buf, sizeof(struct thrdsinfo), &indexPtr, 1) == 0) { // perhaps the process ended return -1; } lwp_to_use = thrd_buf.ti_tid; } // PM counters are only valid when the process is paused. bool needToCont = !(pd_proc->isStopped()); if(needToCont) { // process running if (!pd_proc->pauseProc()) { return -1; // pause failed, so returning failure } } pm_data_t data; if(get_lwp() > 0) ret = pm_get_data_thread(pd_proc->getPid(), lwp_to_use, &data); else { // lwp == 0, means get data for the entire process (ie. all lwps) ret = pm_get_data_group(pd_proc->getPid(), lwp_to_use, &data); while(ret) { // if failed, could have been because the lwp (retrieved via // getthrds) was in process of being deleted. //cerr << " prev lwp_to_use " << lwp_to_use << " failed\n"; if(getthrds(pd_proc->getPid(), &thrd_buf, sizeof(struct thrdsinfo), &indexPtr, 1) == 0) { // couldn't get a valid lwp, go to standard error handling ret = 1; break; } lwp_to_use = thrd_buf.ti_tid; //cerr << " next lwp_to_use is " << lwp_to_use << "\n"; ret = pm_get_data_group(pd_proc->getPid(), lwp_to_use, &data); } } if (ret) { if(!pd_proc->hasExited()) { pm_error("dyn_lwp::getRawCpuTime_hw: pm_get_data_thread", ret); fprintf(stderr, "Attempted pm_get_data(%d, %d, %d)\n", pd_proc->getPid(), get_lwp(), lwp_to_use); } return -1; } rawTime64 result = data.accu[get_hwctr_binding(PM_CYC_EVENT)]; // Continue the process if(needToCont) { pd_proc->continueProc(); } //if(pos_junk != 101) // ct_record(pos_junk, result, hw_previous_, get_lwp(), lwp_to_use); if(result < hw_previous_) { cerr << "rollback in dyn_lwp::getRawCpuTime_hw, lwp_to_use: " << lwp_to_use << ", lwp: " << get_lwp() << ", result: " << result << ", previous result: " << hw_previous_ << "\n"; result = hw_previous_; } else hw_previous_ = result; return result; #else return 0; #endif }
static void modules_init() { int ret; struct partition_entry *p; flash_desc_t fl; /* * Initialize wmstdio prints */ ret = wmstdio_init(UART0_ID, 115200); if (ret != WM_SUCCESS) { appln_critical_error_handler((void *) -WM_FAIL); } /* Initialize time subsystem. * * Initializes time to 1/1/1970 epoch 0. */ ret = wmtime_init(); if (ret != WM_SUCCESS) { wmprintf("Error: wmtime_init failed"); appln_critical_error_handler((void *) -WM_FAIL); } /* * Initialize CLI Commands */ ret = cli_init(); if (ret != WM_SUCCESS) { LOG_ERROR("Error: cli_init failed"); appln_critical_error_handler((void *) -WM_FAIL); } /* Initialize the partition module */ ret = part_init(); if (ret != 0) { LOG_ERROR("Failed to initialize partition\r\n"); appln_critical_error_handler((void *) -WM_FAIL); } p = part_get_layout_by_id(FC_COMP_PSM, NULL); if (!p) { LOG_ERROR("Error: no psm partition found"); appln_critical_error_handler((void *) -WM_FAIL); } part_to_flash_desc(p, &fl); #if defined CONFIG_CPU_MC200 && defined CONFIG_WiFi_8801 //check psm _format psm_format_check(&fl); #endif /* Initilize psm module */ ret = app_psm_init(); if (ret != 0) { LOG_ERROR("Failed to initialize psm module\r\n"); appln_critical_error_handler((void *) -WM_FAIL); } wmprintf("\n\r"); wmprintf("_| _| _|_|_| _|_|_| _|_| \n\r"); wmprintf("_|_| _|_| _| _| _| _|\n\r"); wmprintf("_| _| _| _| _| _| _|\n\r"); wmprintf("_| _| _| _| _| _|\n\r"); wmprintf("_| _| _|_|_| _|_|_| _|_| \n\r"); print_versions(); read_provision_status(); #ifndef RELEASE /* Initilize cli for psm module */ ret = psm_cli_init(); if (ret != 0) { LOG_ERROR("Failed to register psm-cli commands\r\n"); appln_critical_error_handler((void *) -WM_FAIL); } #endif ret = gpio_drv_init(); if (ret != WM_SUCCESS) { LOG_ERROR("Error: gpio_drv_init failed"); appln_critical_error_handler((void *) -WM_FAIL); } ret = aes_drv_init(); if (ret != WM_SUCCESS) { LOG_ERROR("Error: aes drv init failed"); appln_critical_error_handler((void *) -WM_FAIL); } ret = factory_cli_init(); if (ret != 0) { LOG_ERROR("Error: factory_cli_init failed"); appln_critical_error_handler((void *) -WM_FAIL); } ret = miio_chip_rpc_init(); if (ret != 0) { LOG_ERROR("Error: miio_chip_rpc_cli_init failed"); appln_critical_error_handler((void *) -WM_FAIL); } #ifndef RELEASE ret = appln_cli_init(); if (ret != 0) { LOG_ERROR("Error: appln init failed"); appln_critical_error_handler((void *) -WM_FAIL); } #endif /* init add on interface */ init_addon_interface(); ret = ota_init(); if (ret != 0) { LOG_ERROR("Error: ota init failed"); appln_critical_error_handler((void *) -WM_FAIL); } #ifdef MIIO_COMMANDS ret = mcmd_create(UART1_ID); if (ret < 0) { LOG_ERROR("Error: miio command init failed(%d)\r\n", ret); appln_critical_error_handler((void *) -WM_FAIL); } #endif /* * Initialize Power Management Subsystem */ ret = pm_init(); if (ret != WM_SUCCESS) { LOG_ERROR("Error: pm_init failed"); appln_critical_error_handler((void *) -WM_FAIL); } }
COSTTYPE * readPGM(const char *fname, int *width, int *height, bool raw) { pm_init("navfn_tests",0); FILE *pgmfile; pgmfile = fopen(fname,"r"); if (!pgmfile) { printf("readPGM() Can't find file %s\n", fname); return NULL; } printf("readPGM() Reading costmap file %s\n", fname); int ncols, nrows; gray maxval; int format; pgm_readpgminit(pgmfile, &ncols, &nrows, &maxval, &format); printf("readPGM() Size: %d x %d\n", ncols, nrows); // set up cost map COSTTYPE *cmap = (COSTTYPE *)malloc(ncols*nrows*sizeof(COSTTYPE)); if (!raw) for (int i=0; i<ncols*nrows; i++) cmap[i] = COST_NEUTRAL; gray * row(pgm_allocrow(ncols)); int otot = 0; int utot = 0; int ftot = 0; for (int ii = 0; ii < nrows; ii++) { pgm_readpgmrow(pgmfile, row, ncols, maxval, format); if (raw) // raw costmap from ROS { for (int jj(ncols - 1); jj >= 0; --jj) { int v = row[jj]; cmap[ii*ncols+jj] = v; if (v >= COST_OBS_ROS) otot++; if (v == 0) ftot++; } } else { ftot = ncols*nrows; for (int jj(ncols - 1); jj >= 0; --jj) { if (row[jj] < unknown_gray && ii < nrows-7 && ii > 7) { setcostobs(cmap,ii*ncols+jj,ncols); otot++; ftot--; } else if (row[jj] <= unknown_gray) { setcostunk(cmap,ii*ncols+jj,ncols); utot++; ftot--; } } } } printf("readPGM() Found %d obstacle cells, %d free cells, %d unknown cells\n", otot, ftot, utot); pgm_freerow(row); *width = ncols; *height = nrows; return cmap; }
int main(int argc, char** args) { int argchar; char* infn = NULL; char* outfn = NULL; unsigned int row; int bits; FILE* fid = stdin; FILE* fout = stdout; int loglvl = LOG_MSG; char* progname = args[0]; int bzero = 0; int outformat; qfits_header* hdr; unsigned int plane; off_t datastart; anbool onepass = FALSE; bl* pixcache = NULL; #if HAVE_NETPBM struct pam img; tuple * tuplerow; #else void* rowbuf; #endif int W, H, depth, maxval; while ((argchar = getopt (argc, args, OPTIONS)) != -1) switch (argchar) { case '?': case 'h': printHelp(progname); exit(0); case 'v': loglvl++; break; case 'q': loglvl--; break; case 'o': outfn = optarg; break; } log_init(loglvl); log_to(stderr); fits_use_error_system(); if (optind == argc) { // ok, stdin to stdout. } else if (optind == argc-1) { infn = args[optind]; } else if (optind == argc-2) { infn = args[optind]; outfn = args[optind+1]; } else { printHelp(progname); exit(-1); } if (infn && !streq(infn, "-")) { fid = fopen(infn, "rb"); if (!fid) { SYSERROR("Failed to open input file %s", infn); exit(-1); } } if (outfn) { fout = fopen(outfn, "wb"); if (!fid) { SYSERROR("Failed to open output file %s", outfn); exit(-1); } } else outfn = "stdout"; #if HAVE_NETPBM pm_init(args[0], 0); pnm_readpaminit(fid, &img, // PAM_STRUCT_SIZE isn't defined until Netpbm 10.23 (July 2004) #if defined(PAM_STRUCT_SIZE) PAM_STRUCT_SIZE(tuple_type) #else sizeof(struct pam) #endif ); W = img.width; H = img.height; depth = img.depth; maxval = img.maxval; tuplerow = pnm_allocpamrow(&img); bits = pm_maxvaltobits(img.maxval); bits = (bits <= 8) ? 8 : 16; #else // No NETPBM if (parse_pnm_header(fid, &W, &H, &depth, &maxval)) { ERROR("Failed to parse PNM header from file: %s\n", infn ? infn : "<stdin>"); exit(-1); } bits = 8 * maxval_to_bytes(maxval); rowbuf = malloc(W * depth * (bits/8)); #endif logmsg("Read file %s: %i x %i pixels x %i color(s); maxval %i\n", infn ? infn : "stdin", W, H, depth, maxval); if (bits == 8) outformat = BPP_8_UNSIGNED; else { outformat = BPP_16_SIGNED; if (maxval >= INT16_MAX) bzero = 0x8000; } logmsg("Using %i-bit output\n", bits); hdr = fits_get_header_for_image3(W, H, outformat, depth, NULL); if (bzero) fits_header_add_int(hdr, "BZERO", bzero, "Number that has been subtracted from pixel values"); if (qfits_header_dump(hdr, fout)) { ERROR("Failed to write FITS header to file %s", outfn); exit(-1); } qfits_header_destroy(hdr); datastart = ftello(fid); // Figure out if we can seek backward in this input file... if ((fid == stdin) || (fseeko(fid, 0, SEEK_SET) || fseeko(fid, datastart, SEEK_SET))) // Nope! onepass = TRUE; if (onepass && depth > 1) { logmsg("Reading in one pass\n"); pixcache = bl_new(16384, bits/8); } for (plane=0; plane<depth; plane++) { if (plane > 0) { if (fseeko(fid, datastart, SEEK_SET)) { SYSERROR("Failed to seek back to start of image data"); exit(-1); } } for (row = 0; row<H; row++) { unsigned int column; #if HAVE_NETPBM pnm_readpamrow(&img, tuplerow); #else read_pnm_row(fid, W, depth, maxval, rowbuf); #endif for (column = 0; column<W; column++) { int rtn; int pixval; #if HAVE_NETPBM pixval = tuplerow[column][plane]; #else pixval = (bits == 8 ? ((uint8_t *)rowbuf)[column*depth + plane] : ((uint16_t*)rowbuf)[column*depth + plane]); #endif if (outformat == BPP_8_UNSIGNED) rtn = fits_write_data_B(fout, pixval); else rtn = fits_write_data_I(fout, pixval-bzero, TRUE); if (rtn) { ERROR("Failed to write FITS pixel"); exit(-1); } } if (onepass && depth > 1) { for (column = 0; column<W; column++) { for (plane=1; plane<depth; plane++) { int pixval; #if HAVE_NETPBM pixval = tuplerow[column][plane]; #else pixval = (bits == 8 ? ((uint8_t *)rowbuf)[column*depth + plane] : ((uint16_t*)rowbuf)[column*depth + plane]); #endif if (outformat == BPP_8_UNSIGNED) { uint8_t pix = pixval; bl_append(pixcache, &pix); } else { int16_t pix = pixval - bzero; bl_append(pixcache, &pix); } } } } } } #if HAVE_NETPBM pnm_freepamrow(tuplerow); #else free(rowbuf); #endif if (pixcache) { int i, j; int step = (depth - 1); logverb("Writing %zu queued pixels\n", bl_size(pixcache)); for (plane=1; plane<depth; plane++) { j = (plane - 1); for (i=0; i<(W * H); i++) { int rtn; if (outformat == BPP_8_UNSIGNED) { uint8_t* pix = bl_access(pixcache, j); rtn = fits_write_data_B(fout, *pix); } else { int16_t* pix = bl_access(pixcache, j); rtn = fits_write_data_I(fout, *pix, TRUE); } if (rtn) { ERROR("Failed to write FITS pixel"); exit(-1); } j += step; } } bl_free(pixcache); } if (fid != stdin) fclose(fid); if (fits_pad_file(fout)) { ERROR("Failed to pad output file \"%s\"", outfn); return -1; } if (fout != stdout) if (fclose(fout)) { SYSERROR("Failed to close output file %s", outfn); exit(-1); } return 0; }
int main(void) { struct pm_context pm; float power; int ret; printf("Example program for libpm600x %s\n", pm_library_version()); printf("-----------------------------------\n\n"); // initialise the pm_context we want to use ret = pm_init(&pm); // find all power meter probes on the bus struct pm_list *list, *curdev; ret = pm_find_all(&pm, TYPE_PM_ALL, &list); if (!list) { printf("No powermeter probes found\n"); return -1; } // list all probes that we found for (curdev = list; curdev != NULL ;) { if (curdev->type == TYPE_PM_6006) printf("found PM 6006 with serial number %lu\n", curdev->serial); else if (curdev->type == TYPE_PM_6003) printf("found PM 6003 with serial number %lu\n", curdev->serial); curdev = curdev->next; } // open the first power meter that was found ret = pm_open(&pm, list->serial); if (ret < 0) { printf("Error %i, \"%s\"\n", ret, pm_get_error_string(&pm)); return -1; } // set frequency to 1 GHz ret = pm_set_frequency(&pm, 1000000000ULL); if (ret < 0) { printf("Error %i, \"%s\"\n", ret, pm_get_error_string(&pm)); return -1; } // set amount of averaging measurements to 255 ret = pm_set_averages(&pm, 255); if (ret < 0) { printf("Error %i, \"%s\"\n", ret, pm_get_error_string(&pm)); return -1; } // measure the power ret = pm_measure(&pm, &power); if (ret < 0) { printf("Error %i, \"%s\"\n", ret, pm_get_error_string(&pm)); return -1; } printf("Power: %.2f dBm\n", power); // close the device pm_close(&pm); // we do not need the device list anymore pm_list_free(&list); return 0; }
/* * Configure root file system. */ int rootconf(void) { int error; struct vfssw *vsw; extern void pm_init(void); BMDPRINTF(("rootconf: fstype %s\n", rootfs.bo_fstype)); BMDPRINTF(("rootconf: name %s\n", rootfs.bo_name)); BMDPRINTF(("rootconf: flags 0x%x\n", rootfs.bo_flags)); BMDPRINTF(("rootconf: obp_bootpath %s\n", obp_bootpath)); /* * Install cluster modules that were only loaded during * loadrootmodules(). */ if (error = clboot_rootconf()) return (error); if (root_is_svm) { (void) strncpy(rootfs.bo_name, obp_bootpath, BO_MAXOBJNAME); BMDPRINTF(("rootconf: svm: rootfs name %s\n", rootfs.bo_name)); BMDPRINTF(("rootconf: svm: svm name %s\n", svm_bootpath)); } /* * Run _init on the root filesystem (we already loaded it * but we've been waiting until now to _init it) which will * have the side-effect of running vsw_init() on this vfs. * Because all the nfs filesystems are lumped into one * module we need to special case it. */ if (strncmp(rootfs.bo_fstype, "nfs", 3) == 0) { if (modload("fs", "nfs") == -1) { cmn_err(CE_CONT, "Cannot initialize %s filesystem\n", rootfs.bo_fstype); return (ENXIO); } } else { if (modload("fs", rootfs.bo_fstype) == -1) { cmn_err(CE_CONT, "Cannot initialize %s filesystem\n", rootfs.bo_fstype); return (ENXIO); } } RLOCK_VFSSW(); vsw = vfs_getvfsswbyname(rootfs.bo_fstype); RUNLOCK_VFSSW(); VFS_INIT(rootvfs, &vsw->vsw_vfsops, (caddr_t)0); VFS_HOLD(rootvfs); if (root_is_svm) { rootvfs->vfs_flag |= VFS_RDONLY; } /* * This pm-releated call has to occur before root is mounted since we * need to power up all devices. It is placed after VFS_INIT() such * that opening a device via ddi_lyr_ interface just before root has * been mounted would work. */ pm_init(); if (netboot) { if ((error = strplumb()) != 0) { cmn_err(CE_CONT, "Cannot plumb network device\n"); return (error); } } /* * ufs_mountroot() ends up calling getrootdev() * (below) which actually triggers the _init, identify, * probe and attach of the drivers that make up root device * bush; these are also quietly waiting in memory. */ BMDPRINTF(("rootconf: calling VFS_MOUNTROOT %s\n", rootfs.bo_fstype)); error = VFS_MOUNTROOT(rootvfs, ROOT_INIT); vfs_unrefvfssw(vsw); rootdev = rootvfs->vfs_dev; if (error) cmn_err(CE_CONT, "Cannot mount root on %s fstype %s\n", rootfs.bo_name, rootfs.bo_fstype); else cmn_err(CE_CONT, "?root on %s fstype %s\n", rootfs.bo_name, rootfs.bo_fstype); return (error); }
/**@brief Function for handling Peer Manager events. * * @param[in] p_evt Peer Manager event. */ static void pm_evt_handler(pm_evt_t const * p_evt) { ret_code_t err_code; switch (p_evt->evt_id) { case PM_EVT_BONDED_PEER_CONNECTED: { NRF_LOG_DEBUG("Connected to previously bonded device\r\n"); m_peer_id = p_evt->peer_id; err_code = pm_peer_rank_highest(p_evt->peer_id); if (err_code != NRF_ERROR_BUSY) { APP_ERROR_CHECK(err_code); } }break;//PM_EVT_BONDED_PEER_CONNECTED case PM_EVT_CONN_SEC_START: break;//PM_EVT_CONN_SEC_START case PM_EVT_CONN_SEC_SUCCEEDED: { NRF_LOG_DEBUG("Link secured. Role: %d. conn_handle: %d, Procedure: %d\r\n", ble_conn_state_role(p_evt->conn_handle), p_evt->conn_handle, p_evt->params.conn_sec_succeeded.procedure); err_code = pm_peer_rank_highest(p_evt->peer_id); if (err_code != NRF_ERROR_BUSY) { APP_ERROR_CHECK(err_code); } if (p_evt->params.conn_sec_succeeded.procedure == PM_LINK_SECURED_PROCEDURE_BONDING) { NRF_LOG_DEBUG("New Bond, add the peer to the whitelist if possible\r\n"); NRF_LOG_DEBUG("\tm_whitelist_peer_cnt %d, MAX_PEERS_WLIST %d\r\n", m_whitelist_peer_cnt + 1, BLE_GAP_WHITELIST_ADDR_MAX_COUNT); if (m_whitelist_peer_cnt < BLE_GAP_WHITELIST_ADDR_MAX_COUNT) { //bonded to a new peer, add it to the whitelist. m_whitelist_peers[m_whitelist_peer_cnt++] = m_peer_id; m_is_wl_changed = true; } } }break;//PM_EVT_CONN_SEC_SUCCEEDED case PM_EVT_CONN_SEC_FAILED: { /** In some cases, when securing fails, it can be restarted directly. Sometimes it can * be restarted, but only after changing some Security Parameters. Sometimes, it cannot * be restarted until the link is disconnected and reconnected. Sometimes it is * impossible, to secure the link, or the peer device does not support it. How to * handle this error is highly application dependent. */ switch (p_evt->params.conn_sec_failed.error) { case PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING: // Rebond if one party has lost its keys. err_code = pm_conn_secure(p_evt->conn_handle, true); if (err_code != NRF_ERROR_INVALID_STATE) { APP_ERROR_CHECK(err_code); } break; default: break; } }break;//PM_EVT_CONN_SEC_FAILED case PM_EVT_CONN_SEC_CONFIG_REQ: { // Reject pairing request from an already bonded peer. pm_conn_sec_config_t conn_sec_config = {.allow_repairing = false}; pm_conn_sec_config_reply(p_evt->conn_handle, &conn_sec_config); }break;//PM_EVT_CONN_SEC_CONFIG_REQ case PM_EVT_STORAGE_FULL: // Run garbage collection on the flash. err_code = fds_gc(); if (err_code == FDS_ERR_BUSY || err_code == FDS_ERR_NO_SPACE_IN_QUEUES) { // Retry. } else { APP_ERROR_CHECK(err_code); } break;//PM_EVT_STORAGE_FULL case PM_EVT_ERROR_UNEXPECTED: // A likely fatal error occurred. Assert. APP_ERROR_CHECK(p_evt->params.error_unexpected.error); break;//PM_EVT_ERROR_UNEXPECTED case PM_EVT_PEER_DATA_UPDATE_SUCCEEDED: break;//PM_EVT_PEER_DATA_UPDATE_SUCCEEDED case PM_EVT_PEER_DATA_UPDATE_FAILED: APP_ERROR_CHECK(p_evt->params.peer_data_update_failed.error); break;//PM_EVT_PEER_DATA_UPDATE_FAILED case PM_EVT_PEER_DELETE_SUCCEEDED: break;//PM_EVT_PEER_DELETE_SUCCEEDED case PM_EVT_PEER_DELETE_FAILED: APP_ERROR_CHECK(p_evt->params.peer_delete_failed.error); break;//PM_EVT_PEER_DELETE_FAILED case PM_EVT_PEERS_DELETE_SUCCEEDED: break;//PM_EVT_PEERS_DELETE_SUCCEEDED case PM_EVT_PEERS_DELETE_FAILED: APP_ERROR_CHECK(p_evt->params.peers_delete_failed_evt.error); break;//PM_EVT_PEERS_DELETE_FAILED case PM_EVT_LOCAL_DB_CACHE_APPLIED: break;//PM_EVT_LOCAL_DB_CACHE_APPLIED case PM_EVT_LOCAL_DB_CACHE_APPLY_FAILED: // The local database has likely changed, send service changed indications. pm_local_database_has_changed(); break;//PM_EVT_LOCAL_DB_CACHE_APPLY_FAILED case PM_EVT_SERVICE_CHANGED_IND_SENT: break;//PM_EVT_SERVICE_CHANGED_IND_SENT case PM_EVT_SERVICE_CHANGED_IND_CONFIRMED: break;//PM_EVT_SERVICE_CHANGED_IND_CONFIRMED default: // No implementation needed. break; } } /**@brief Function for the Peer Manager initialization. * * @param[in] erase_bonds Indicates whether bonding information should be cleared from * persistent storage during initialization of the Peer Manager. */ static void peer_manager_init(bool erase_bonds) { ble_gap_sec_params_t sec_param; ret_code_t err_code; err_code = pm_init(); APP_ERROR_CHECK(err_code); if (erase_bonds) { err_code = pm_peers_delete(); APP_ERROR_CHECK(err_code); } memset(&sec_param, 0, sizeof(ble_gap_sec_params_t)); // Security parameters to be used for all security procedures. sec_param.bond = SEC_PARAM_BOND; sec_param.mitm = SEC_PARAM_MITM; sec_param.lesc = SEC_PARAM_LESC; sec_param.keypress = SEC_PARAM_KEYPRESS; sec_param.io_caps = SEC_PARAM_IO_CAPABILITIES; sec_param.oob = SEC_PARAM_OOB; sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE; sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE; sec_param.kdist_own.enc = 1; sec_param.kdist_own.id = 1; sec_param.kdist_peer.enc = 1; sec_param.kdist_peer.id = 1; err_code = pm_sec_params_set(&sec_param); APP_ERROR_CHECK(err_code); err_code = pm_register(pm_evt_handler); APP_ERROR_CHECK(err_code); }
void do_profiling(const int *sizes, const size_t count) { const int repetitions = 50; const int size_field_width = 5; const int result_field_width = 15; const plan_constructor_t plan_constructors[] = { interpolate_plan_3d_naive_interleaved, interpolate_plan_3d_padding_aware_interleaved, interpolate_plan_3d_phase_shift_interleaved, }; const papi_event_t counters[] = { PAPI_TOT_CYC, PAPI_L3_TCM, PAPI_DP_OPS }; const size_t num_plan_constructors = sizeof(plan_constructors)/sizeof(plan_constructors[0]); const size_t num_counters = sizeof(counters)/sizeof(counters[0]); printf("%*s", size_field_width, ""); for(size_t constructor_index = 0; constructor_index < num_plan_constructors; ++constructor_index) { interpolate_plan plan = plan_constructors[constructor_index](1, 1, 1, 0); assert(plan != NULL); printf("%*s", (int) (result_field_width * num_counters), interpolate_get_name(plan)); interpolate_destroy_plan(plan); } printf("\n"); printf("%*s", size_field_width, ""); for(size_t constructor_index = 0; constructor_index < num_plan_constructors; ++constructor_index) { char name[PAPI_MAX_STR_LEN]; for(size_t i=0; i < num_counters; ++i) { PAPI_CHECK(PAPI_event_code_to_name(counters[i], name)); printf("%*s", result_field_width, name); } } printf("\n"); for(size_t size_index = 0; size_index < count; ++size_index) { const int layout = INTERLEAVED; const size_t size = sizes[size_index]; const size_t block_size = size * size * size; storage_t coarse, fine; storage_allocate(&coarse, layout, block_size); storage_allocate(&fine, layout, 8 * block_size); printf("%5zd", size); for(size_t constructor_index = 0; constructor_index < num_plan_constructors; ++constructor_index) { interpolate_plan plan = plan_constructors[constructor_index](size, size, size, 0); assert(plan != NULL); papi_multiplex_t multiplex; PAPI_CHECK(pm_init(&multiplex)); for(size_t i=0; i < num_counters; ++i) PAPI_CHECK(pm_add_event(&multiplex, counters[i])); for(int repetition = 0; repetition < repetitions; ++repetition) { PAPI_CHECK(pm_start(&multiplex)); execute_interpolate(plan, &coarse, &fine); PAPI_CHECK(pm_stop(&multiplex)); } for(size_t i=0; i < num_counters; ++i) { long long value; PAPI_CHECK(pm_count(&multiplex, counters[i], &value)); printf("%15lld", value); } PAPI_CHECK(pm_destroy(&multiplex)); interpolate_destroy_plan(plan); } printf("\n"); storage_free(&coarse); storage_free(&fine); } }