示例#1
0
bool
EstAssort_registNewTag( ZnkVarpAry post_vars, ZnkStr tag_editor_msg, ZnkStr tagid )
{
	bool result = false;
	ZnkVarp varp = NULL;
	if( IS_OK( varp = ZnkVarpAry_find_byName_literal( post_vars, "EstCM_new_tag", false ) )){
		if( ZnkS_empty( ZnkVar_cstr( varp ) ) ){
			ZnkStr_addf( tag_editor_msg, "無効なタグです.\n" );
		} else {
			ZnkStr unesc_new_tag = ZnkStr_new( "" );
			ZnkHtpURL_unescape_toStr( unesc_new_tag, ZnkVar_cstr(varp), ZnkVar_str_leng(varp) );
			if( IS_OK( varp = ZnkVarpAry_find_byName_literal( post_vars, "EstCM_select_group", false ) )){
				ZnkMyf tags_myf = EstConfig_tags_myf();
				const char* EstCM_select_group = ZnkVar_cstr( varp );
				if( EstTag_registNew( tags_myf, ZnkStr_cstr(unesc_new_tag), tagid, tag_editor_msg, EstCM_select_group ) ){
					EstConfig_saveTagsMyf();
					result = true;
				}
			}
			ZnkStr_delete( unesc_new_tag );
		}
	} else {
		ZnkStr_addf( tag_editor_msg, "EstCM_new_tag doesn't exist.\n" );
	}
	return result;
}
示例#2
0
bool SansgridRadio::setDestAddr(uint64_t addr) {
	uint8_t at_response[12];
	char cmd[80];
	memset(at_response,'\0',12);
	//set upper destination address
	sprintf(cmd,"ATDH %x", (addr >> 32)); 
	atCmd(at_response, (const char *)cmd);
	if (at_response[0] == '\0') {
		return 0;
	}
	else if(!IS_OK(at_response)) {
		Radio->println("AT cmd Failed with");
		//delete at_response;
		return 0;
	}
	
	// set lower destination address
	memset(at_response,'\0',12);
	sprintf(cmd,"ATDL %x", (addr & 0x00000000FFFFFFFF)); 
	atCmd(at_response, (const char *)cmd);
	if (at_response == '\0') {
		return 0;
	}
	else if(!IS_OK(at_response)) {
		return 0;
	}
	
	return 1;
}
示例#3
0
tResult cDriverModule::LoadManeuverList()
{
    m_sectorList.clear();
    // create dom from string received from pin
    cDOM oDOM;       
    oDOM.FromString(m_strManeuverFileString);
    cDOMElementRefList oSectorElems;
    cDOMElementRefList oManeuverElems;

    //read first Sector Elem
    if(IS_OK(oDOM.FindNodes("AADC-Maneuver-List/AADC-Sector", oSectorElems)))
    {                
        //iterate through sectors
        for (cDOMElementRefList::iterator itSectorElem = oSectorElems.begin(); itSectorElem != oSectorElems.end(); ++itSectorElem)
        {
            //if sector found
            tSector sector;
            sector.id = (*itSectorElem)->GetAttributeUInt32("id");

            if(IS_OK((*itSectorElem)->FindNodes("AADC-Maneuver", oManeuverElems)))
            {
                //iterate through maneuvers
                for(cDOMElementRefList::iterator itManeuverElem = oManeuverElems.begin(); itManeuverElem != oManeuverElems.end(); ++itManeuverElem)
                {
                    tAADC_Maneuver man;
                    man.id = (*itManeuverElem)->GetAttributeUInt32("id");
                    man.action = (*itManeuverElem)->GetAttribute("action");
                    sector.maneuverList.push_back(man);
                }
            }

            m_sectorList.push_back(sector);
        }
    }
    if (oSectorElems.size() > 0)
    {
        LOG_INFO("DriverFilter: Loaded Maneuver file successfully.");
        m_pWidget->EnableManeuverGroupBox(true);
    }
    else
    {
        LOG_ERROR("DriverFilter: no valid Maneuver Data found!");
        m_pWidget->EnableManeuverGroupBox(false);
        RETURN_ERROR(ERR_INVALID_FILE);
    }

    // update the ui
    m_pWidget->SetManeuverList(m_sectorList);
    m_pWidget->ShowManeuverList();
    m_pWidget->FillComboBox();
    

    RETURN_NOERROR;
}
示例#4
0
tResult cSensorAnalyzer::LoadConfigurationData(cString filename)
{
    //Get path of configuration file
    //EDS macro is resolved automatically because it is a file property
    m_fileConfig = filename;//GetPropertyStr("Filename for Sensorpresets");

    if (m_fileConfig.IsEmpty())
        LOG_WARNING("Configuration file not found for Analyzer");    

    ADTF_GET_CONFIG_FILENAME(m_fileConfig);
    m_fileConfig = m_fileConfig.CreateAbsolutePath(".");

    if (cFileSystem::Exists(m_fileConfig))
    {
        cDOM oDOM;
        oDOM.Load(m_fileConfig);
        cDOMElementRefList oElems;
        if(IS_OK(oDOM.FindNodes("presets/sensorPreset", oElems)))
        {                
            for (cDOMElementRefList::iterator itElem = oElems.begin(); itElem != oElems.end(); ++itElem)
            {
                cDOMElement* pConfigElement;
                tSensorPreset newSensorPreset;
                if (IS_OK((*itElem)->FindNode("sensor", pConfigElement)))
                {
                    newSensorPreset.sensorName = cString(pConfigElement->GetData());
                    if (IS_OK((*itElem)->FindNode("nominalValue", pConfigElement)))
                        newSensorPreset.nominalValue = static_cast<tFloat32>(cString(pConfigElement->GetData()).AsFloat64());
                    if (IS_OK((*itElem)->FindNode("maxPosDeviation", pConfigElement)))
                        newSensorPreset.maxPosDeviation = static_cast<tFloat32>(cString(pConfigElement->GetData()).AsFloat64());
                    if (IS_OK((*itElem)->FindNode("maxNegDeviation", pConfigElement)))
                        newSensorPreset.maxNegDeviation = static_cast<tFloat32>(cString(pConfigElement->GetData()).AsFloat64());
                }          
                /*LOG_INFO(cString::Format("Name %s, Nominal: %f, NegDev: %f, PosDev: %f",
                newSensorPreset.sensorName.GetPtr(),
                newSensorPreset.nominalValue,
                newSensorPreset.maxNegDeviation,
                newSensorPreset.maxPosDeviation
                ));*/
                addParsedElement(newSensorPreset);
            }        
        }
        else
        {
            LOG_WARNING("Configured configuration file does not contain valid xml scheme");
        }
    }
    else
    {
        LOG_WARNING("Configured configuration file not found (yet).Will appear after extracting the extended data");
    }

    RETURN_NOERROR;
}
示例#5
0
DD_TEST(load_i16_loads_correct_value, load_i16_iter, FixnumLoadData, load) {
    uint8_t dest = load->dest;
    NFixnum value = load->value;
    NFixnum result;

    n_encode_op_load_i16(CODE, dest, value);
    n_evaluator_step(&EVAL, &ERR);
    ASSERT(IS_OK(ERR));

    result = n_unwrap_fixnum(n_evaluator_get_local(&EVAL, dest, &ERR));
    ASSERT(IS_OK(ERR));

    ASSERT(EQ_INT(result, value));
}
示例#6
0
DD_TEST(jump_adds_offset_to_pc, jump_iter, int16_t, offset) {
    EVAL.pc = 32;
    n_encode_op_jump(CODE +32, *offset);
    n_evaluator_step(&EVAL, &ERR);
    ASSERT(IS_OK(ERR));
    ASSERT(EQ_INT(EVAL.pc, 32 + *offset));
}
示例#7
0
文件: giop.c 项目: MaxGekk/ZigZag
void    event_handler( event_type_t event_type, unidata_t   unidata )
{
    if( event_type == GIOP_INTERRUPT ) {
        /* Изменилось состояние входов */
#if defined(BLINK_ON)
        port_t  ledpin;
        port_read( LED_PORT, LED1, &ledpin );
        ledpin ^= LED1; 
        port_write( LED_PORT, LED1, ledpin );
#endif
#if defined(INVERT_ATTR)
        unidata = ~unidata;
#endif        
        attr_write( INPUT, &unidata );
    } else if( event_type == EV_AWRITTEN ){
        if( unidata == OUTPUT ) {
            /* Изменён атрибут цифровых выходов */
            port_t  out;
            result_t res = attr_read( OUTPUT, &out );
            if( IS_OK(res) ) {
                /* Записываем в порт новое значение атрибута */
                port_write( OPORT, OPINS, out );
            }
#if defined(BLINK_ON)
            port_t  ledpin;
            port_read( LED_PORT, LED2, &ledpin );
            ledpin ^= LED2; 
            port_write( LED_PORT, LED2, ledpin );
#endif
        }
    }
    return;
}
示例#8
0
void DisplayWidget::SetDirectory(QString filename)
{
	QDir dir(filename);

	if(!dir.isAbsolute())
		LOG_WARNING(cString::Format("Path is not absolute. Force absolute path!"));

	QStringList fileList = dir.entryList(QDir::Files);
	QStringList files;
	
	for(QStringList::iterator it = fileList.begin(); it != fileList.end(); it++)
	{
		if(it->endsWith(".xml"))
		{
			cDOM oDOM;
			QString qString = dir.absoluteFilePath(".") + "/" + *it;
			LOG_INFO(cString::Format("path %s", qString.toStdString().c_str()));
			oDOM.Load(qString.toStdString().c_str());
			cDOMElementRefList oElems;
			if(IS_OK(oDOM.FindNodes("presets/sensorPreset", oElems)))
				files.push_back(*it);
		}
	}

	m_dropDownFileChooser->addItems(files);
}
void StateControllerNew::LoadManeuverList(cString maneuverString)
{
    sectorList.clear();
    cDOM oDOM;
    oDOM.FromString(maneuverString);
    cDOMElementRefList oSectorElems;
    cDOMElementRefList oManeuverElems;

    if (IS_OK(oDOM.FindNodes("AADC-Maneuver-List/AADC-Sector", oSectorElems)))
    {
        for (cDOMElementRefList::iterator itSectorElem = oSectorElems.begin(); itSectorElem != oSectorElems.end(); ++itSectorElem)
        {
            //if sector found
            tSector sector;
            sector.id = (*itSectorElem)->GetAttributeUInt32("id");

            if (IS_OK((*itSectorElem)->FindNodes("AADC-Maneuver", oManeuverElems)))
            {
                //iterate through maneuvers
                for (cDOMElementRefList::iterator itManeuverElem = oManeuverElems.begin();
                     itManeuverElem != oManeuverElems.end(); ++itManeuverElem)
                {
                    tAADC_Maneuver man;
                    man.id = (*itManeuverElem)->GetAttributeUInt32("id");
                    man.action = (*itManeuverElem)->GetAttribute("action");
                    sector.maneuverList.push_back(man);
                    logger.Log(cString::Format("id = %d action = %s", man.id, man.action.GetPtr()).GetPtr());
                }
            }

            sectorList.push_back(sector);
        }
    }

    if (oSectorElems.size() > 0)
    {
        logger.Log("Loaded Maneuver file successfully.");
        sectionListIndex = 0;
        maneuverListIndex = 0;
    }
    else
    {
        logger.Log("No valid Maneuver Data found!");
        sectionListIndex = -1;
        maneuverListIndex = -1;
    }
}
示例#10
0
DD_TEST(jump_unless_adds_offset_to_pc, jump_unless_iter, int16_t, offset) {
    EVAL.pc = 32;
    n_evaluator_set_local(&EVAL, 3, N_TRUE, &ERR);
    n_encode_op_jump_unless(CODE +32, 3, *offset);
    n_evaluator_step(&EVAL, &ERR);
    ASSERT(IS_OK(ERR));
    ASSERT(EQ_INT(EVAL.pc, 32 + *offset));
}
示例#11
0
文件: nsEscape.cpp 项目: isleon/Jaxer
//----------------------------------------------------------------------------------------
static char* nsEscapeCount(
    const char * str,
    PRInt32 len,
    nsEscapeMask flags,
    PRInt32* out_len)
//----------------------------------------------------------------------------------------
{
	if (!str)
		return 0;

    int i, extra = 0;
    static const char hexChars[] = "0123456789ABCDEF";

	register const unsigned char* src = (const unsigned char *) str;
    for (i = 0; i < len; i++)
	{
        if (!IS_OK(*src++))
            extra += 2; /* the escape, plus an extra byte for each nibble */
	}

	char* result = (char *)nsMemory::Alloc(len + extra + 1);
    if (!result)
        return 0;

    register unsigned char* dst = (unsigned char *) result;
	src = (const unsigned char *) str;
	if (flags == url_XPAlphas)
	{
	    for (i = 0; i < len; i++)
		{
			unsigned char c = *src++;
			if (IS_OK(c))
				*dst++ = c;
			else if (c == ' ')
				*dst++ = '+'; /* convert spaces to pluses */
			else 
			{
				*dst++ = HEX_ESCAPE;
				*dst++ = hexChars[c >> 4];	/* high nibble */
				*dst++ = hexChars[c & 0x0f];	/* low nibble */
			}
		}
	}
	else
	{
	    for (i = 0; i < len; i++)
示例#12
0
result_t compress_directory(struct pak_file* pak, struct paki_args* args, const char* subdir)
{
    result_t r;
    char directory[DH_PATH_MAX];
    char filepath[DH_PATH_MAX];
    char fullfilepath[DH_PATH_MAX];

    strcpy(directory, args->path);
    if (subdir[0] != 0)     {
        path_join(directory, directory, subdir, NULL);
    }

    WIN32_FIND_DATA fdata;
    char filter[DH_PATH_MAX];
    path_join(filter, directory, "*", NULL);
    HANDLE find_hdl = FindFirstFile(filter, &fdata);
    if (find_hdl == INVALID_HANDLE_VALUE)    {
        printf(TERM_BOLDRED "Creating pak failed: directory '%s' does not exist.\n" TERM_RESET,
               directory);
        return RET_FAIL;
    }

    /* read directory recuresively, and compress files into pak */
    BOOL fr = TRUE;
    while (fr)     {
        if (!str_isequal(fdata.cFileName, ".") && !str_isequal(fdata.cFileName, ".."))    {
            filepath[0] = 0;
            if (subdir[0] != 0)     {
                strcpy(filepath, subdir);
            }

            if (!BIT_CHECK(fdata.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY))  {
                /* put the file into the archive */
                path_join(filepath, filepath, fdata.cFileName, NULL);
                path_join(fullfilepath, directory, fdata.cFileName, NULL);

                r = archive_put(pak, args, fullfilepath, filepath);
                if (IS_OK(r) && BIT_CHECK(args->usage, PAKI_USAGE_VERBOSE))     {
                    puts(filepath);
                }   else if (IS_FAIL(r))  {
                    err_sendtolog(FALSE);
                    args->err_cnt ++;
                }
                args->file_cnt ++;
            }   else    {
                /* it's a directory, recurse */
                path_join(filepath, filepath, fdata.cFileName, NULL);
                compress_directory(pak, args, filepath);
            }
        }
        fr = FindNextFile(find_hdl, &fdata);
    }

    FindClose(find_hdl);
    return RET_OK;
}
示例#13
0
result_t compress_directory(struct pak_file* pak, struct paki_args* args, const char* subdir)
{
    result_t r;
    char directory[DH_PATH_MAX];
    char filepath[DH_PATH_MAX];
    char fullfilepath[DH_PATH_MAX];

    strcpy(directory, args->path);
    if (subdir[0] != 0)     {
        path_join(directory, path_norm(directory, directory), subdir, NULL);
    }

    DIR* dir = opendir(directory);
    if (dir == NULL)    {
        printf(TERM_BOLDRED "Creating pak failed: directory '%s' does not exist.\n" TERM_RESET,
               directory);
        return RET_FAIL;
    }

    /* read directory recuresively, and compress files into pak */
    struct dirent* ent = readdir(dir);
    while (ent != NULL)     {
        if (!str_isequal(ent->d_name, ".") && !str_isequal(ent->d_name, ".."))    {
            filepath[0] = 0;
            if (subdir[0] != 0)
                strcpy(filepath, subdir);

            if (ent->d_type != DT_DIR)  {
                // put the file into the archive
                path_join(filepath, filepath, ent->d_name, NULL);
                path_join(fullfilepath, directory, ent->d_name, NULL);
                r = archive_put(pak, args, fullfilepath, filepath);
                if (IS_OK(r) && BIT_CHECK(args->usage, PAKI_USAGE_VERBOSE))     {
                    puts(filepath);
                }   else if (IS_FAIL(r))  {
                    err_sendtolog(FALSE);
                    args->err_cnt ++;
                }
                args->file_cnt ++;
            }   else    {
                // it's a directory, recurse
                path_join(filepath, filepath, ent->d_name, NULL);
                compress_directory(pak, args, filepath);
            }
        }
        ent = readdir(dir);
    }

    closedir(dir);
    return RET_OK;
}
示例#14
0
void
EstAssort_addPostVars_ifNewTagRegisted( ZnkVarpAry post_vars, ZnkStr tag_editor_msg )
{
	ZnkStr tagid = ZnkStr_new( "" );
	if( EstAssort_registNewTag( post_vars, tag_editor_msg, tagid ) ){
		ZnkVarp new_tag = NULL;
		ZnkVarp new_var = ZnkVarp_create( ZnkStr_cstr(tagid), "", 0, ZnkPrim_e_Str, NULL );
		if( IS_OK( new_tag = ZnkVarpAry_find_byName_literal( post_vars, "EstCM_new_tag", false ) )){
			ZnkVar_set_val_Str( new_var, ZnkVar_cstr( new_tag ), ZnkVar_str_leng( new_tag ) );
		}
		ZnkVarpAry_push_bk( post_vars, new_var );
	}
	ZnkStr_delete( tagid );
}
示例#15
0
文件: mbtx.c 项目: MaxGekk/ZigZag
void    event_handler( event_type_t event_type, unidata_t   unidata )
{
    if( EV_MBREQ_DONE == event_type ) {
        result_t    res;
        res = mb_master_request( slave_addr[cur_slave],
                100, 0,0, &ans_fcode,ans_dptr,&ans_dsize );
        if( IS_OK(res) ) {
            cur_slave++;
            if( cur_slave >= SLAVE_TOTAL )
                cur_slave = 0;
            return;
        }
        event_emit( PRIORITY_HIGH, EV_MBREQ_DONE, (unidata_t)ENOERR );
    }
}
tResult ImageCutter::transmitVideoOutput(Mat &image, cVideoPin &pin)
{
	if (!pin.IsConnected())
	{
		RETURN_NOERROR;
	}
	
	// Create new IMediaSample
	cObjectPtr<IMediaSample> sample;

	if (IS_OK(AllocMediaSample(&sample)))
	{
		tTimeStamp time = _clock ? _clock->GetStreamTime() : cHighResTimer::GetTime();
		RETURN_IF_FAILED(sample->Update(time, image.data, this->videoOutputInfo.nSize, 0));
		RETURN_IF_FAILED(pin.Transmit(sample));
	}

	RETURN_NOERROR;
}
示例#17
0
tResult cQrPlayer::ProcessVideo(adtf::IMediaSample* pISample)
{
	RETURN_IF_POINTER_NULL(pISample);
//  creating new temporary variables
	adtf_util::cImage oImage;	
	const tVoid* l_pSrcBuffer;

//  receiving data from inputsample, and saving to oImage
	if (IS_OK(pISample->Lock(&l_pSrcBuffer)))
	{
			oImage.SetBits((tUInt8*) l_pSrcBuffer, &m_sInputFormat);
			
			pISample->Unlock(l_pSrcBuffer);
	}

//  convert adtf-image to greyscaled image which is used by zbar
	RETURN_IF_FAILED(oImage.Convert(&m_sProcessFormat));	

//  creates image which is used by the QR Scanner   
	Image image(m_sInputFormat.nWidth, m_sInputFormat.nHeight, "Y800", (unsigned char*)oImage.GetBitmap(), m_sInputFormat.nWidth * m_sInputFormat.nHeight);

//  scan image for codes and check for errors		
	int n =  m_qrScanner.scan(image);
	if (n== -1) LOG_ERROR(cString::Format("QR Player: Error in QRScanner"));	
	
//  extract results to console
    for(Image::SymbolIterator symbol = image.symbol_begin();
        symbol != image.symbol_end();
        ++symbol) {
        //print only new results
        if (m_lastQRCode!=symbol->get_data())
            {
            m_lastQRCode=symbol->get_data();            
            }
        ProcessCommand(cString(symbol->get_data().c_str()));
    }
    
    // clean up
    image.set_data(NULL, 0);		

	RETURN_NOERROR;
}
tResult ImageCutter::processImage(IMediaSample *mediaSample)
{
	const tVoid *buffer;

	if (IS_OK(mediaSample->Lock(&buffer)))
	{
		//Receive the image
		Mat image(Size(this->videoInputInfo.nWidth, this->videoInputInfo.nHeight), CV_8UC3, (char*)buffer);
		
		mediaSample->Unlock(buffer);

		static Mat cuttedImage;
		//Extract region of interest
		cuttedImage = image(Range(240, this->videoInputInfo.nHeight), Range(0, this->videoInputInfo.nWidth)).clone();
		// extractROI(image);
		
		//Send it to the output pin
		transmitVideoOutput(cuttedImage, this->cuttedVideoOutputPin);
	}
	
	RETURN_NOERROR;
}
示例#19
0
/* bind animation to object, by evaluating object's model component
 * - obj->model_cmp is invalid: wait to model to update (will be called from cmp_model)
 * - obj->model_cmp is skinned: bind skeleton, find first geometry that is skinned, bind to that
 * - obj->model_cmp is not skinned: bind hierarchal animation
 */
result_t cmp_anim_bind(struct cmp_obj* obj, void* data, struct allocator* alloc,
    struct allocator* tmp_alloc, reshandle_t hdl)
{
    struct cmp_anim* a = (struct cmp_anim*)data;

     if (obj->model_cmp == INVALID_HANDLE)
        return RET_OK;

    struct cmp_model* m = (struct cmp_model*)cmp_getinstancedata(obj->model_cmp);
    if (m->model_hdl == INVALID_HANDLE)
        return RET_OK;

    /* choose between skinned geometry and hierarchal */
    struct gfx_model* gmodel = rs_get_model(m->model_hdl);
    if (gmodel == NULL)
        return RET_OK;

    uint geo_idx = INVALID_INDEX;
    for (uint i = 0; i < gmodel->geo_cnt; i++)    {
        if (gmodel->geos[i].skeleton != NULL)   {
            geo_idx = i;
            break;
        }
    }

    result_t r = RET_FAIL;
    cmp_anim_destroybind(a);
    if (geo_idx != INVALID_INDEX)   {
        r = cmp_anim_createskeleton(a, m, gmodel, geo_idx);
    }    else   {
        r = cmp_anim_createhierarchy(a, m, gmodel);
    }

    if (IS_OK(r))   {
        cmp_anim_play(hdl);
    }

    return r;
}
示例#20
0
/* Обработка уведомления об отправке ответа новому дочернему узлу */
void    znet_pjoin_done( zcall_t    *zc )
{
    neighbor_t  *child_ptr;
    zargs_passoc_t  *arg = (zargs_passoc_t *)(zc->args);
    if( arg->status == SUCCESS ) {
        /* Ответ успешно отправлен */
        if( nwkMaxChildren <= child_count() ) {
            /* Достигнут порог для числа детей. Обновим информацию в нашем кадре-маяке */
            bcn_all_cap_off();
        }
        /* Уведомляем вышележащий уровень о новом дочернем узле. */
        ZCALL_INIT( zc, ZCALL_NLME_JOIN_INDICATION, 0 );
        if( IS_OK(zcall_invoke(zc)) )
            return;
    }
    /* Произошла какая-то ошибка. Ищем запись узла в таблице соседей и удаляем её.  */
    child_ptr = child_by_eaddr( arg->dev_addr );
    if( IN_TABLE( child_ptr ) )
        child_ptr->busy = 0;
    zcall_del(zc);
    return;
}
tResult CurveDetector::transmitVideoOutput(Mat &image, cVideoPin &pin)
{
    if (!pin.IsConnected())
    {
        RETURN_NOERROR;
    }

    if (image.type() != CV_8UC3)
    {
        cvtColor(image, image, CV_GRAY2RGB);
    }

    cObjectPtr<IMediaSample> sample;

    if (IS_OK(AllocMediaSample(&sample)))
    {
        tTimeStamp time = _clock ? _clock->GetStreamTime() : cHighResTimer::GetTime();
        RETURN_IF_FAILED(sample->Update(time, image.data, this->videoInputInfo.nSize, 0));
        RETURN_IF_FAILED(pin.Transmit(sample));
    }

    RETURN_NOERROR;
}
tResult CurveDetector::processImage(IMediaSample *mediaSample)
{
    const tVoid *buffer;

    if (IS_OK(mediaSample->Lock(&buffer)))
    {
        Mat image(Size(this->videoInputInfo.nWidth, this->videoInputInfo.nHeight), CV_8UC3, (char*)buffer);
        mediaSample->Unlock(buffer);

        Mat result = image.clone();
        prepareImage(result);

        list<SD_Point> left, right;
        searchLines(result, left, right);

        drawPointsInImage(result, left, Scalar(0, 0, 255));
        drawPointsInImage(result, right, Scalar(0, 0, 255));

        transmitVideoOutput(result, this->rgbOutput);
    }

    RETURN_NOERROR;
}
示例#23
0
u_result MainWindow::captureAndDisplay()
{
    u_result ans;

    rplidar_response_measurement_node_t nodes[360*2];
    size_t count = _countof(nodes);

    printf("waiting for data...\n");

    // fetech extactly one 0-360 degrees' scan
    ans = mDrv->grabScanData(nodes, count);
    if (IS_OK(ans) || ans == RESULT_OPERATION_TIMEOUT)
    {
        mDrv->ascendScanData(nodes, count);
        plotHistogram(nodes, count);
/*
        printf("Do you want to see all the data? (y/n) ");
        int key = getchar();
        if (key == 'Y' || key == 'y')
        {
            for (int pos = 0; pos < (int)count ; ++pos)
            {
                printf("%s theta: %03.2f Dist: %08.2f \n",
                    (nodes[pos].sync_quality & RPLIDAR_RESP_MEASUREMENT_SYNCBIT) ?"S ":"  ",
                    (nodes[pos].angle_q6_checkbit >> RPLIDAR_RESP_MEASUREMENT_ANGLE_SHIFT)/64.0f,
                    nodes[pos].distance_q2/4.0f);
            }
        }
*/
    }
    else
    {
        printf("error code: %x\n", ans);
    }

    return ans;
}
示例#24
0
// -------------------------------------------------------------------------------------------------
tResult LaneFilter::processImage(IMediaSample* image_sample) {
// -------------------------------------------------------------------------------------------------
  const tVoid* source_buffer;
  
  bool enable_lights = false;
  
  if (IS_OK(image_sample->Lock(&source_buffer))) {
    int source_width = input_format_.nWidth;
    int source_height = input_format_.nHeight;
    
    Mat current_image(source_height, source_width, CV_8UC3, (uchar*)source_buffer);
    
    enable_lights = calculateImageLuminosity(current_image) < GetPropertyFloat("lum_threshold");
    
    // Detect the edges of the image by using a Canny Algo
    Mat preprocessed;
    lane_preprocessor_.set_gaussian_blur(Size(15,15), 2);
    lane_preprocessor_.preprocess_image(current_image, preprocessed);
    
    std::vector<Vector2> mapped_points;
    Mat mapping_image;
    lane_detector_.detect_lanes(preprocessed, mapping_image, mapped_points);
    image_sample->Unlock(source_buffer);
    
    transmitLanePoints(mapped_points);
  }
  
  if (GetPropertyBool("headlights_enabled")) {
    if(enable_lights != headlights_on_) {
      transmitHeadLight(enable_lights);
      headlights_on_ = enable_lights;
    }
  }
  
  RETURN_NOERROR;
}
示例#25
0
文件: attr.c 项目: MaxGekk/ZigZag
/* Обработка сообщений установки и запроса атрибутов */
size_t  _msg_attr_recv( uint16_t obj_offset, msg_t  imsg_id )
{
    size_t  imsg_size   =   0;      /* Размер обрабатываемого входящего сообщения */
    uint8_t itype;                  /* Тип входящего сообщения */
    uint8_t *ibody_begin;           /* Указатель на начала тела входящего сообщения */
    net_addr_t  dst_addr;           /* Адрес назначения для исходящего сообщения */
    app_port_t  dst_port;           /* Порт для исходящего сообщения */
    uint8_t *ibody_ptr;             /* Указатель тела входящего сообщения */
    uint8_t attr_total;             /* Общее число запрашиваемых или устанавливаемых атрибутов */
    uint8_t ombody_size;            /* Размер тела исходящего сообщения */
    msg_t   omsg_id;                /* Идентификатор исходящего сообщения */
    uint8_t *obody_ptr;             /* Указатель тела исходящего сообщения */

    {struct msginfo     iminfo;
     if( IS_ERROR( _msg_info( obj_offset, imsg_id, &iminfo ) ) )
         goto   destroy_imessage;
     itype = iminfo.msg_type;
     ibody_ptr = ibody_begin = (uint8_t *)iminfo.body_ptr;
     dst_addr = iminfo.src_addr, dst_port = iminfo.src_port;   
    }
    switch( itype ) {
        case  MSG_ATTR_GET: case MSG_ATTR_SET:
            attr_total = 1;
            break;
        case MSG_MULTI_ATTR_GET: case MSG_MULTI_ATTR_SET:
            attr_total = *ibody_ptr++;    /* Первый байт тела сообщения содержит общее число атрибутов */
            if( 0 == attr_total ) {
                imsg_size = MSG_HEADER_SIZE;
                goto    destroy_imessage;
            }
            break;
        default: goto destroy_imessage;
    }

    ombody_size = 9;    /* Атрибуты будем возвращать в сообщении типа MSG_MULTI_ATTR_RET, 
                           первое поле -- метка времени (8 байт)
                           второе поле -- количество передаваемых атрибутов (1 байт) */

    {uint8_t    attr_size, i;
     for( i = 0; i < attr_total; i++ )   {
        if( ( MSG_ATTR_SET == itype )||( MSG_MULTI_ATTR_SET == itype ) ) {
            attr_size = _attr_set( obj_offset, *ibody_ptr, ibody_ptr + 1 );
            ibody_ptr += 1 + attr_size;
        } else {
            attr_size = _attr_size( obj_offset, *ibody_ptr );
            ++ibody_ptr;
        }
        if( 0 == attr_size )      
            goto    destroy_imessage;
        ombody_size += 1 + attr_size;
     }
    }
    DBG("new msg");
    omsg_id = _msg_new( obj_offset, dst_addr, dst_port, offset2port( obj_offset),
            MSG_MULTI_ATTR_RET, ombody_size, _MFLAG_NO_CONFIRM );
    if( IS_ERROR( omsg_id ) )
        goto    destroy_imessage;
    {struct msginfo     ominfo;
     if( IS_ERROR( _msg_info( obj_offset, omsg_id, &ominfo ) ) )   
         goto   destroy_omessage;
     obody_ptr = (uint8_t *)ominfo.body_ptr;
    }

    serialize(obody_ptr, 8, "8:", (uint64_t)_sys_time());
    obody_ptr += 8;

    // запись кол-ва атрибутов
    *obody_ptr++ = attr_total;

    ibody_ptr = ibody_begin;
    if( ( MSG_MULTI_ATTR_GET == itype )||( MSG_MULTI_ATTR_SET == itype ) )
        ibody_ptr++;
    {uint8_t    attr_size, i;
     for( i = 0; i< attr_total; i++ ) {
         *obody_ptr = *ibody_ptr;   /* Копируем номер атрибута */
         attr_size = _attr_get( obj_offset, *obody_ptr, obody_ptr + 1 );
         obody_ptr += 1 + attr_size;
         ibody_ptr++;
         if( ( MSG_ATTR_SET == itype )||( MSG_MULTI_ATTR_SET == itype ) )
             ibody_ptr += attr_size;
     }
    }
    imsg_size = MSG_HEADER_SIZE + ( ibody_ptr - ibody_begin );
    if( IS_OK( _msg_send( obj_offset, omsg_id ) ) )
        goto    destroy_imessage;
destroy_omessage:
    _msg_destroy( obj_offset, omsg_id );
destroy_imessage:
    _msg_destroy( obj_offset, imsg_id );

    return imsg_size;
}
tResult cJuryTransmitter::loadManeuverList()
{

    m_maneuverListFile = GetPropertyStr("ManeuverFile");
    
    if (m_maneuverListFile.IsEmpty())
    {
        LOG_ERROR("Jury Module: Maneuver file not found");
        RETURN_ERROR(ERR_INVALID_FILE);
    }
    
    ADTF_GET_CONFIG_FILENAME(m_maneuverListFile);
    
    m_maneuverListFile = m_maneuverListFile.CreateAbsolutePath(".");

    //Load file, parse configuration, print the data

    if (cFileSystem::Exists(m_maneuverListFile))
    {
        cDOM oDOM;
        oDOM.Load(m_maneuverListFile);
        cDOMElementRefList oSectorElems;
        cDOMElementRefList oManeuverElems;

        //read first Sector Elem
        if(IS_OK(oDOM.FindNodes("AADC-Maneuver-List/AADC-Sector", oSectorElems)))
        {
            //iterate through sectors
            for (cDOMElementRefList::iterator itSectorElem = oSectorElems.begin(); itSectorElem != oSectorElems.end(); ++itSectorElem)
            {
                //if sector found
                tSector sector;
                sector.id = (*itSectorElem)->GetAttributeUInt32("id");
                
                if(IS_OK((*itSectorElem)->FindNodes("AADC-Maneuver", oManeuverElems)))
                {
                    //iterate through maneuvers
                    for(cDOMElementRefList::iterator itManeuverElem = oManeuverElems.begin(); itManeuverElem != oManeuverElems.end(); ++itManeuverElem)
                    {
                        tAADC_Maneuver man;
                        man.id = (*itManeuverElem)->GetAttributeUInt32("id");
                        man.action = (*itManeuverElem)->GetAttribute("action");
                        sector.maneuverList.push_back(man);
                    }
                }

                m_sectorList.push_back(sector);
            }
        }
        if (oSectorElems.size() > 0)
        {
            LOG_INFO("Jury Module: Loaded Maneuver file successfully.");
        }
        else
        {
            LOG_ERROR("Jury Moduler: no valid Maneuver Data found!");
            RETURN_ERROR(ERR_INVALID_FILE);
        }
    }
    else
    {
        LOG_ERROR("Jury Module: no valid Maneuver File found!");
        RETURN_ERROR(ERR_INVALID_FILE);
    }

    //OUTPUT DATA TO LOG
    //for(int i = 0; i < m_sectorList.size(); i++)
    //{
    //    LOG_INFO(cString::Format("Driver Module: Sector ID %d",m_sectorList[i].id));
    //    for(int j = 0; j < m_sectorList[i].maneuverList.size(); j++)
    //    {
    //        LOG_INFO(cString::Format("\tManeuver ID: %d", m_sectorList[i].maneuverList.at(j).id));
    //        LOG_INFO(cString::Format("\tManeuver action: %s", m_sectorList[i].maneuverList.at(j).action.GetPtr()));
    //    }
    //}

    RETURN_NOERROR;
}
tResult StateControlManagementSlim::LoadSCMStructureData()
{
	// Get path of structure file
	m_strStructureFileName = GetPropertyStr("Configuration File For StateControlManagement");

    // check if file exits
    if (m_strStructureFileName.IsEmpty())
    {
		#ifdef WRITE_DEBUG_OUTPUT_TO_FILE
    	scm_logfile << std::endl << "### --- " << std::endl << "SCM ERROR: XML-File for structural configuration not found, please check property!" << std::endl;
		#endif
        RETURN_AND_LOG_ERROR_STR(ERR_INVALID_FILE,cString::Format("SCM: XML-File for structural configuration not found, please check property!"));
    }

    // create absolute path
    ADTF_GET_CONFIG_FILENAME(m_strStructureFileName);
    m_strStructureFileName = m_strStructureFileName.CreateAbsolutePath(".");

    //Load file, parse configuration, print the data

    if (cFileSystem::Exists(m_strStructureFileName))
    {
        cDOM oDOM;
        oDOM.Load(m_strStructureFileName);

        m_SCMstructureList.clear();

		cDOMElementRefList oScManeuverElems;
		cDOMElementRefList oScStepElems;
		cDOMElement*  oScLevelActiveElem;
		cDOMElement*  oScLevelPassiveElem;
		cDOMElementRefList oScFilterIDActiveElems;
		cDOMElementRefList oScFilterIDPassiveElems;
		cDOMElement*  oScActionElem;
		cDOMElementRefList  oScRequestElems;
		/* counters for checking if structural configuration file of StateControlManagement was correctly implemented by user, which means
		 * that both maneuvers and steps start at id=0 and are implemented in ascending order in the xml-file, with NO gaps existing between ids! */
		tUInt32 manCounter = 0;
		tUInt32 stepCounter = 0;

		//read first scManeuver Element
		if(IS_OK(oDOM.FindNodes("SCM-Structure-List/SCM-Maneuver", oScManeuverElems)))
		{
			//iterate through scManeuvers
			for (cDOMElementRefList::iterator itScManeuverElem = oScManeuverElems.begin(); itScManeuverElem != oScManeuverElems.end(); ++itScManeuverElem)
			{
				//if scManeuver found
				sc_Maneuver scManeuver; 	// declare object of scManeuver for saving purpose
				scManeuver.id = (*itScManeuverElem)->GetAttributeUInt32("id");
				if(manCounter != scManeuver.id){
					#ifdef WRITE_DEBUG_OUTPUT_TO_FILE
					scm_logfile << std::endl << "### --- " << std::endl << "SCM ERROR: Invalid structure of xml-file at maneuver " << scManeuver.id << ". Maneuvers must have ascending order and start at ID = 0. No gaps allowed. Check file!" << std::endl;
					#endif
					RETURN_AND_LOG_ERROR_STR(ERR_INVALID_FILE,cString::Format("SCM: Invalid structure of xml-file at maneuver %d. Maneuvers must have ascending order and start at ID = 0. No gaps allowed. Check file!",scManeuver.id));
				}

				if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: Maneuver %d ;",scManeuver.id));

				if(IS_OK((*itScManeuverElem)->FindNodes("SCM-Step", oScStepElems)))
				{
					stepCounter = 0;
					//iterate through scSteps
					for(cDOMElementRefList::iterator itScStepsElem = oScStepElems.begin(); itScStepsElem != oScStepElems.end(); ++itScStepsElem)
					{
						//if scStep found
						sc_Step scStep;
						scStep.id = (*itScStepsElem)->GetAttributeUInt32("id");
						if(stepCounter != scStep.id){
							#ifdef WRITE_DEBUG_OUTPUT_TO_FILE
							scm_logfile << std::endl << "### --- " << std::endl << "SCM ERROR: Invalid structure of xml-file in maneuver " << scManeuver.id << ", step " << scStep.id << ". Maneuvers must have ascending order and start at ID = 0. No gaps allowed. Check file!" << std::endl;
							#endif
							RETURN_AND_LOG_ERROR_STR(ERR_INVALID_FILE,cString::Format("SCM: Invalid structure of xml-file in maneuver %d, step %d. Steps must have ascending order and start at ID = 0. No gaps allowed. Check file!",scManeuver.id,scStep.id));
						}
						if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: ---> Step %d ;",scStep.id));

						// PATH FOR ACTIVITYLEVEL: ACTIVE
						if(IS_OK((*itScStepsElem)->FindNode("SCM-ActivityLevel/SCM-Active", oScLevelActiveElem)))
						{
							if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: -----> ACTIVE:"));
							//if scActivityLevel_ACTIVE found
							if(IS_OK(oScLevelActiveElem->FindNodes("SCM-FilterID", oScFilterIDActiveElems)))
							{
								//iterate through scFilterID_Active
								for(cDOMElementRefList::iterator itScFilterIDActiveElem = oScFilterIDActiveElems.begin(); itScFilterIDActiveElem != oScFilterIDActiveElems.end(); ++itScFilterIDActiveElem)
								{
									//if ScFilterID_Active found, Element of List FilterList active
									sc_Filter_active scFilterActive;
									scFilterActive.filterID= (*itScFilterIDActiveElem)->GetAttributeUInt32("id");
									if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: -------> FilterID %d ;",scFilterActive.filterID));

									// inside ID, there is only SCM-Action, so only search for specific node
									if(IS_OK((*itScFilterIDActiveElem)->FindNode("SCM-Action", oScActionElem)))
										{
												scFilterActive.action.enabled = oScActionElem->GetAttributeBool("enable");
												if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: ---------> enable %d ;",scFilterActive.action.enabled));
												scFilterActive.action.started = oScActionElem->GetAttributeBool("start");
												if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: ---------> start %d ;",scFilterActive.action.started));
												scFilterActive.action.command = oScActionElem->GetAttributeUInt32("command");
												if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: ---------> command %d ;",scFilterActive.action.command));
										}
									// Push found FilterActive Commands into Filter-Active-list for current step
									scStep.activityLvl.active.FilterList.push_back(scFilterActive);

								}
							}

						}

						// PATH FOR ACTIVITYLEVEL: PASSIVE
						if(IS_OK((*itScStepsElem)->FindNode("SCM-ActivityLevel/SCM-Passive", oScLevelPassiveElem)))
						{
							if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: -----> PASSIVE:"));
							//if scActivityLevel_PASSIVE found
							if(IS_OK(oScLevelPassiveElem->FindNodes("SCM-FilterID", oScFilterIDPassiveElems)))
							{
								//iterate through scFilterID_Passive
								for(cDOMElementRefList::iterator itScFilterIDPassiveElem = oScFilterIDPassiveElems.begin(); itScFilterIDPassiveElem != oScFilterIDPassiveElems.end(); ++itScFilterIDPassiveElem)
								{
									//if ScFilterID_Passive found, Element of List FilterList passive
									sc_Filter_passive scFilterPassive;
									scFilterPassive.filterID= (*itScFilterIDPassiveElem)->GetAttributeUInt32("id");
									if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: -------> FilterID %d ;",scFilterPassive.filterID));

									// inside ID, there can be several SCM-Requests
									if(IS_OK((*itScFilterIDPassiveElem)->FindNodes("SCM-Request", oScRequestElems)))
										{
										//iterate through scFilterID_Passive
											for(cDOMElementRefList::iterator itScReqeustElems = oScRequestElems.begin(); itScReqeustElems != oScRequestElems.end(); ++itScReqeustElems)
											{
												//if sc_Request found, Element of List Request
												sc_Request scRequest;
												scRequest.request = (*itScReqeustElems)->GetAttributeUInt32("status");
												scRequest.command = (*itScReqeustElems)->GetAttributeUInt32("command");

												scFilterPassive.Requests.push_back(scRequest);
												if(m_bPrintStrucModeEnabled) LOG_WARNING(cString::Format("SCM: ---------> status %d, command %d ;",scRequest.request,scRequest.command));
											}

										}
									// Push found FilterPassive Commands into Filter-Passive-list for current step
									scStep.activityLvl.passive.FilterList.push_back(scFilterPassive);

								}
							}

						}
						// Push found steps into step-list
						scManeuver.Steps.push_back(scStep);
						stepCounter++; // increase step counter
					}
				}

				m_SCMstructureList.push_back(scManeuver);
				manCounter++; // increase maneuver counter
			}
		}

		if (oScManeuverElems.size() > 0)
		{
			if(m_bDebugModeEnabled) LOG_WARNING(cString::Format("SCM: Loaded Structural Configuration file successfully."));
			#ifdef WRITE_DEBUG_OUTPUT_TO_FILE
			scm_logfile << "SCM: Loaded Structural Configuration file successfully." << std::endl;
			#endif
		}
		else
		{
			#ifdef WRITE_DEBUG_OUTPUT_TO_FILE
			scm_logfile << std::endl << "### --- " << std::endl << "SCM ERROR: no valid Configuration Data found in file!" << std::endl;
			#endif
			RETURN_AND_LOG_ERROR_STR(ERR_INVALID_FILE, cString::Format("SCM: no valid Configuration Data found in file!"));
		}
    }
    else
	{
		#ifdef WRITE_DEBUG_OUTPUT_TO_FILE
		scm_logfile << std::endl << "### --- " << std::endl << "SCM ERROR: Structural configuration file not found!" << std::endl;
		#endif
		RETURN_AND_LOG_ERROR_STR(ERR_INVALID_FILE,cString::Format("SCM: Structural configuration file not found!"));
	}


    RETURN_NOERROR;
}
示例#28
0
tResult cDriverModule::OnPinEvent(IPin* pSource, tInt nEventCode, tInt nParam1, tInt nParam2, IMediaSample* pMediaSample)
{

    RETURN_IF_POINTER_NULL(pMediaSample);
    RETURN_IF_POINTER_NULL(pSource);



    if (nEventCode == IPinEventSink::PE_MediaSampleReceived  )
    {      

        if (pSource == &m_JuryStructInputPin && m_pDescJuryStruct != NULL) 
        {
            tInt8 i8ActionID = -2;
            tInt16 i16entry = -1;

            {   // focus for sample read lock
                __adtf_sample_read_lock_mediadescription(m_pDescJuryStruct,pMediaSample,pCoder);
                // get the IDs for the items in the media sample 
                if(!m_bIDsJuryStructSet)
                {
                    pCoder->GetID("i8ActionID", m_szIDJuryStructI8ActionID);
                    pCoder->GetID("i16ManeuverEntry", m_szIDJuryStructI16ManeuverEntry);
                    m_bIDsJuryStructSet = tTrue;
                }      

                pCoder->Get(m_szIDJuryStructI8ActionID, (tVoid*)&i8ActionID);
                pCoder->Get(m_szIDJuryStructI16ManeuverEntry, (tVoid*)&i16entry);              
            }

            switch (juryActions(i8ActionID))
            {
            case action_GETREADY:
                if(m_bDebugModeEnabled)  LOG_INFO(cString::Format("Driver Module: Received Request Ready with maneuver ID %d",i16entry));
                emit SendRequestReady((int)i16entry);
                break;
            case action_START:
                if(m_bDebugModeEnabled)  LOG_INFO(cString::Format("Driver Module: Received Run with maneuver ID %d",i16entry));
                emit SendRun((int)i16entry);
                break;
            case action_STOP:
                if(m_bDebugModeEnabled)  LOG_INFO(cString::Format("Driver Module: Received Stop with maneuver ID %d",i16entry));
                emit SendStop((int)i16entry);
                break;
            }

        }
        else if (pSource == &m_ManeuverListInputPin && m_pDescManeuverList != NULL)
        {

            {   // focus for sample read lock
                __adtf_sample_read_lock_mediadescription(m_pDescManeuverList,pMediaSample,pCoder);

                
                std::vector<tSize> vecDynamicIDs;
               
                // retrieve number of elements by providing NULL as first paramter
                tSize szBufferSize = 0;
                if(IS_OK(pCoder->GetDynamicBufferIDs(NULL, szBufferSize)))
                {
                    // create a buffer depending on the size element
                    tChar* pcBuffer = new tChar[szBufferSize];
                    vecDynamicIDs.resize(szBufferSize);
                    // get the dynamic ids (we already got the first "static" size element)
                    if (IS_OK(pCoder->GetDynamicBufferIDs(&(vecDynamicIDs.front()), szBufferSize)))
                    {
                        // iterate over all elements
                        for (tUInt32 nIdx = 0; nIdx < vecDynamicIDs.size(); ++nIdx)
                        {
                            // get the value and put it into the buffer
                            pCoder->Get(vecDynamicIDs[nIdx], (tVoid*)&pcBuffer[nIdx]);
                        }

                        // set the resulting char buffer to the string object
                        m_strManeuverFileString = (const tChar*) pcBuffer;
                    }

                    // cleanup the buffer
                    delete pcBuffer;
                }
        
            }

            // trigger loading maneuver list and update the ui
            TriggerLoadManeuverList();
        }
    }
    RETURN_NOERROR;

}
示例#29
0
//----------------------------------------------------------------------------------------
static char* nsEscapeCount(
    const char * str,
    nsEscapeMask flags,
    size_t* out_len)
//----------------------------------------------------------------------------------------
{
	if (!str)
		return 0;

    size_t i, len = 0, charsToEscape = 0;
    static const char hexChars[] = "0123456789ABCDEF";

	register const unsigned char* src = (const unsigned char *) str;
    while (*src)
	{
        len++;
        if (!IS_OK(*src++))
            charsToEscape++;
	}

    // calculate how much memory should be allocated
    // original length + 2 bytes for each escaped character + terminating '\0'
    // do the sum in steps to check for overflow
    size_t dstSize = len + 1 + charsToEscape;
    if (dstSize <= len)
	return 0;
    dstSize += charsToEscape;
    if (dstSize < len)
	return 0;

    // fail if we need more than 4GB
    // size_t is likely to be long unsigned int but nsMemory::Alloc(size_t)
    // calls NS_Alloc_P(size_t) which calls PR_Malloc(PRUint32), so there is
    // no chance to allocate more than 4GB using nsMemory::Alloc()
    if (dstSize > PR_UINT32_MAX)
        return 0;

	char* result = (char *)nsMemory::Alloc(dstSize);
    if (!result)
        return 0;

    register unsigned char* dst = (unsigned char *) result;
	src = (const unsigned char *) str;
	if (flags == url_XPAlphas)
	{
	    for (i = 0; i < len; i++)
		{
			unsigned char c = *src++;
			if (IS_OK(c))
				*dst++ = c;
			else if (c == ' ')
				*dst++ = '+'; /* convert spaces to pluses */
			else 
			{
				*dst++ = HEX_ESCAPE;
				*dst++ = hexChars[c >> 4];	/* high nibble */
				*dst++ = hexChars[c & 0x0f];	/* low nibble */
			}
		}
	}
	else
	{
	    for (i = 0; i < len; i++)
示例#30
0
/* Окончено активное сканирование каналов */
void    znet_form_start( zcall_t    *mc )
{
    zcall_t     *zc = mc->assoc_call;
    zargs_nform_t   *narg = (zargs_nform_t *)(zc->args);
    zargs_ascan_t   *arg = (zargs_ascan_t *)(mc->args);

    if( arg->status == SUCCESS ) {
        /* Активное сканирование успешно проведено */
        uint32_t  channels = arg->channels & narg->channels;  /* Битовая маска просканированных каналов */
        if( channels ) {    /* Есть каналы, который удалось просканировать */
            uint16_t    i;
            neighbor_t    *nbr_ptr;
            /* Определяем канал с наименьшим числом узлов */
            uint8_t  node_count[ TOTAL_CHANNELS ];  /* Массив числа узлов на каждом канале */
            uint8_t  opt_channel = INVALID_CHANNEL;
            uint8_t  min_node = INVALID_NODE_COUNT;
            /* Инициализация счётчиков узлов на каналах */
            for( i=0; i<TOTAL_CHANNELS; i++, channels >>= 1 )
                node_count[i] = (channels & 1)?0:INVALID_NODE_COUNT;
            /* Подсчёт числа узлов на каждом канале */
            nbr_ptr = nbr_next(0);
            while( IN_TABLE(nbr_ptr) ) {
                if( node_count[nbr_ptr->channel]!=INVALID_NODE_COUNT )
                    node_count[ nbr_ptr->channel ] += 1;
                nbr_ptr = nbr_next( nbr_ptr );
            }
            /* Поиск канала с наименьшим числом узлов */
            for( i=0; i<TOTAL_CHANNELS; i++ )            
                if( (node_count[i] != INVALID_NODE_COUNT)&&(node_count[i]<min_node) ) {
                    min_node = node_count[i];
                    opt_channel = i;
                }
            if( opt_channel != INVALID_CHANNEL ) {
                /* Найден канал с наименьшим числом узлов */
                zargs_mstart_t  *start_arg = (zargs_mstart_t *)(mc->args);
                /* Ищем не используемый на выбранном канале короткий идентификатор сети */
                start_arg->panid = znet_unused_spanid( opt_channel );
                if( start_arg->panid < 0xFFFF ) {
                    /* Найден неиспользуемый идентификатор сети. */
                    { /* Обновляем beacon payload */
                      uint8_t bcn_payload[Z_BCN_PAYLOAD_SIZE];
                      SET_PROTOCOL_ID(bcn_payload, 0);
                      SET_STACK_PROFILE(bcn_payload, nwkStackProfile );
                      SET_PROTOCOL_VERSION(bcn_payload, nwkProtocolVersion );
                      SET_ROUT_CAPACITY(bcn_payload, 1 );
                      SET_DEPTH(bcn_payload, 0 );
                      SET_END_CAPACITY(bcn_payload, 1 );
                      SET_EPANID( bcn_payload, &nwkExtendedPANID);
                      { uint32_t _txoffset=0; SET_TX_OFFSET( bcn_payload, &_txoffset); }
                      bcn_payload_set( bcn_payload );
                    }
                    /* Готовим аргументы для вызова MLME_START.request */
                    start_arg->channel = opt_channel;
                    start_arg->pan_coord = 1;
                    start_arg->batt_life_ext = narg->batt_life_ext;
                    start_arg->realignment = 0;
                    start_arg->beacon_order = narg->beacon_order;
                    start_arg->sf_order = narg->sf_order;
                    macPANID = start_arg->panid;
                    macShortAddress = 0x0000;
                    if( nwkExtendedPANID == 0 ) nwkExtendedPANID = aExtendedAddress;
                    ZCALL_INIT( mc, ZCALL_MAC_START, znet_form_done );
                    if( IS_OK(zcall_invoke(mc)) )
                        return;
                }
            }
        }
        narg->status = NWK_STARTUP_FAILURE;
    } else narg->status = arg->status;