예제 #1
0
void *TPZParFrontStructMatrix<front>::ElementAssemble(void *t){
    
    
	TPZParFrontStructMatrix<front> *parfront = (TPZParFrontStructMatrix<front> *) t;
	
	TPZAdmChunkVector<TPZCompEl *> &elementvec = parfront->fMesh->ElementVec();
	
	
	while(parfront->fCurrentElement < parfront->fNElements) {
		
		/**
		 *Lock mutex and search for an avilable element
		 *A global variable to be updated whenever a element is processed
		 */
		
		//Lock a mutex and get an element number
		
		PZ_PTHREAD_MUTEX_LOCK(&mutex_element_assemble, "TPZParFrontStructMatrix<front>::ElementAssemble()");
		
		//Stack is full and process must wait here!
		if(parfront->felnum.NElements()==parfront->fMaxStackSize)
        {
			/*          cout << "    Stack full" << endl;
			 cout << "    Waiting" << endl;
			 cout.flush();*/
			//cout << "Mutex unlocked on Condwait" << endl;
#ifdef LOG4CXX
            if (logger->isDebugEnabled())
			{
				std::stringstream sout;
				sout << "Entering cond_wait because of stack overflow ";
				LOGPZ_DEBUG(logger,sout.str())
			}
#endif
			PZ_PTHREAD_COND_WAIT(&stackfull,&mutex_element_assemble,"TPZParFrontStructMatrix<front>::ElementAssemble()");
			//cout << "Mutex LOCKED leaving Condwait" << endl;
			
        }
		
		//cout << "Locking mutex_element_assemble" << endl;
		//cout.flush();
		int64_t local_element = parfront->fCurrentElement;
		if(local_element==parfront->fNElements)
        {
            PZ_PTHREAD_MUTEX_UNLOCK(&mutex_element_assemble, "TPZParFrontStructMatrix<front>::ElementAssemble()");
            return 0;
        }
		/*          cout << "All element matrices assembled" << endl;
		 return 0;
		 }
		 */
#ifdef LOG4CXX
        if (logger->isDebugEnabled())
		{
			std::stringstream sout;
			sout << "Computing element " << local_element;
			LOGPZ_DEBUG(logger,sout.str())
		}
예제 #2
0
파일: pzhdivfull.cpp 프로젝트: labmec/neopz
TPZCompElHDivFull<TSHAPE>::TPZCompElHDivFull(TPZCompMesh &mesh, TPZGeoEl *gel, int64_t &index) :
TPZRegisterClassId(&TPZCompElHDivFull::ClassId),
TPZCompElHDiv<TSHAPE>(mesh,gel,index) {
	
	int i;
	int nconflux= TPZCompElHDiv<TSHAPE>::NConnects();
    this->fConnectIndexes.Resize(nconflux);
	gel->SetReference(this);
	
	for(i=0;i< nconflux;i++)
	{
        int sideaux= i + TSHAPE::NCornerNodes;
		this->fConnectIndexes[i] = this->CreateMidSideConnect(sideaux);
#ifdef LOG4CXX
        if (logger->isDebugEnabled())
        {
            std::stringstream sout;
            sout << "After creating last flux connect " << i << std::endl;
            //	this->Print(sout);
            LOGPZ_DEBUG(logger,sout.str())
        }
#endif
        
		mesh.ConnectVec()[this->fConnectIndexes[i]].IncrementElConnected();
		this->IdentifySideOrder(sideaux);
    }	
예제 #3
0
파일: main.cpp 프로젝트: labmec/neopz
void ErrorH1(TPZCompMesh *l2mesh, std::ostream &out)
{
    int64_t nel = l2mesh->NElements();
    int dim = l2mesh->Dimension();
    TPZManVector<STATE,10> globerrors(10,0.);
    for (int64_t el=0; el<nel; el++) {
        TPZCompEl *cel = l2mesh->ElementVec()[el];
        if (!cel) {
            continue;
        }
        TPZGeoEl *gel = cel->Reference();
        if (!gel || gel->Dimension() != dim) {
            continue;
        }
        TPZManVector<STATE,10> elerror(10,0.);
        elerror.Fill(0.);
        cel->EvaluateError(SolSuave, elerror, NULL);
        
        int nerr = elerror.size();
        //globerrors.resize(nerr);
#ifdef LOG4CXX
        if (logger->isDebugEnabled()) {
            std::stringstream sout;
            sout << "L2 Error sq of element " << el << elerror[0]*elerror[0];
            LOGPZ_DEBUG(logger, sout.str())
        }
#endif
        for (int i=0; i<nerr; i++) {
            globerrors[i] += elerror[i]*elerror[i];
        }
    }
예제 #4
0
TPZMatrix<STATE> * TPZSpStructMatrix::Create(){
    int64_t neq = fEquationFilter.NActiveEquations();
	/*    if(fMesh->FatherMesh()) {
	 TPZSubCompMesh *smesh = (TPZSubCompMesh *) fMesh;
	 neq = smesh->NumInternalEquations();
	 }*/
    TPZFYsmpMatrix<STATE> * mat = new TPZFYsmpMatrix<STATE>(neq,neq);
	
    /**
     *Longhin implementation
	 */
    TPZStack<int64_t> elgraph;
    TPZVec<int64_t> elgraphindex;
    //    int nnodes = 0;
    fMesh->ComputeElGraph(elgraph,elgraphindex);
    /**Creates a element graph*/
    TPZMetis metis;
    metis.SetElementsNodes(elgraphindex.NElements() -1 ,fMesh->NIndependentConnects());
    metis.SetElementGraph(elgraph,elgraphindex);
	
    TPZManVector<int64_t> nodegraph;
    TPZManVector<int64_t> nodegraphindex;
    /**
     *converts an element graph structure into a node graph structure
     *those vectors have size ZERO !!!
     */
    metis.ConvertGraph(elgraph,elgraphindex,nodegraph,nodegraphindex);
    
#ifdef LOG4CXX2
    if(logger->isDebugEnabled()){
        std::stringstream sout;
        sout << "Node graph \n";
        metis.TPZRenumbering::Print(nodegraph, nodegraphindex);
        LOGPZ_DEBUG(logger, sout.str())
    }
예제 #5
0
void ScanAllSkinnyMessages(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, TcpHeaderStruct* tcpHeader, u_char* ipPacketEnd)
{
	u_char* startTcpPayload = (u_char*)tcpHeader + (tcpHeader->off * 4);
	SkinnyHeaderStruct* skinnyHeader = (SkinnyHeaderStruct*)(startTcpPayload);

	// Scan all skinny messages in this TCP packet
	while(	ipPacketEnd > (u_char*)skinnyHeader &&
			(u_char*)skinnyHeader>=startTcpPayload &&
			(ipPacketEnd - (u_char*)skinnyHeader) > SKINNY_MIN_MESSAGE_SIZE	&&
			skinnyHeader->len > 1 && skinnyHeader->len < 2048 &&
			skinnyHeader->messageType >= 0x0 && skinnyHeader->messageType <= 0x200 )	// Last known skinny message by ethereal is 0x13F, but seen higher message ids in the field.
	{
		if(s_skinnyParsersLog->isDebugEnabled())
		{
			CStdString dbg;
			unsigned int offset = (u_char*)skinnyHeader - startTcpPayload;
			dbg.Format("Offset:%x Len:%u Type:%x %s", offset, skinnyHeader->len, skinnyHeader->messageType, SkinnyMessageToString(skinnyHeader->messageType));
			LOG4CXX_DEBUG(s_skinnyParsersLog, dbg);
		}

		HandleSkinnyMessage(skinnyHeader, ipHeader, ipPacketEnd, tcpHeader);

		// Point to next skinny message within this TCP packet
		skinnyHeader = (SkinnyHeaderStruct*)((u_char*)skinnyHeader + SKINNY_HEADER_LENGTH + skinnyHeader->len);
	}
}
예제 #6
0
파일: Iax2Parsers.cpp 프로젝트: HiPiH/Oreka
bool TryIax2FullVoiceFrame(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader,
                UdpHeaderStruct* udpHeader, u_char* udpPayload)
{
        struct Iax2FullHeader *fh = (struct Iax2FullHeader *)udpPayload;
        int data_len = 0, codec = 0, pt = 0, udp_act_payload_len = 0;
	Iax2PacketInfoRef info(new Iax2PacketInfo());

        if(!DLLCONFIG.m_iax2Support)
                return false;

        udp_act_payload_len = (ntohs(udpHeader->len)-sizeof(UdpHeaderStruct));
        if(udp_act_payload_len < (int)sizeof(*fh))
                return false; /* Frame too small */

        if(!(ntohs(fh->scallno) & 0x8000))
                return false; /* Not a full frame */

        if(fh->type != IAX2_FRAME_VOICE)
                return false; /* Frame type must be VOICE */

	codec = get_uncompressed_subclass(fh->c_sub);
	if((pt = iax2_codec_to_rtp_payloadtype(codec)) < 0) {
		CStdString logmsg;

		logmsg.Format("Invalid payload type %d received for "
				"IAX_FRAME_VOICE, IAX2 codec %d", pt, codec);
		LOG4CXX_INFO(s_iax2parsersLog, logmsg);
		return false; /* Invalid codec type received */
	}

	data_len = ((u_char*)ipHeader+ntohs(ipHeader->ip_len))-(udpPayload+sizeof(*fh));
	if(data_len == 0)
		return false; /* Empty packet? */

        /* We have a full VOICE frame */

	info->m_sourceIp = ipHeader->ip_src;
	info->m_destIp = ipHeader->ip_dest;
	info->m_sourcecallno = (ntohs(fh->scallno) & ~0x8000);
	info->m_destcallno = (ntohs(fh->dcallno) & ~0x8000);
	info->m_payloadSize = data_len;
	info->m_payload = udpPayload+sizeof(*fh);
	info->m_payloadType = pt;
	info->m_timestamp = ntohl(fh->ts);
	info->m_arrivalTimestamp = time(NULL);
	info->m_frame_type = IAX2_FRAME_FULL;

	Iax2SessionsSingleton::instance()->ReportIax2Packet(info);

	CStdString logmsg, packetInfo;
	info->ToString(packetInfo);
	logmsg.Format("Processed IAX2 FULL VOICE frame pt:%d", pt);
        LOG4CXX_INFO(s_iax2parsersLog, logmsg);
	if(s_iax2parsersLog->isDebugEnabled())
	{
		LOG4CXX_DEBUG(s_iax2parsersLog, packetInfo);
	}

	return true;
}
예제 #7
0
void TPZSkylParMatrix<TVar>::ColumnToWork(int64_t &lcol) {
	int64_t neq = this->Dim();
	int64_t lcolentry = lcol;
#ifdef PZDEBUG
	if(lcolentry < 0 || lcolentry >= neq)
	{
		LOGPZ_ERROR(logger,"ColumnToWork called with wrong lcol argument")
		DebugStop();
	}
#endif
	lcol++;
	lcol = lcol%neq;
	while(lcol != lcolentry)
    {
		if(fColUsed.find(lcol) != fColUsed.end() || fDec[lcol] == lcol) 
		{
			lcol++;
			lcol = lcol%neq;
			continue;
		}
		int decomposeduntil = fDec[lcol]+1;
		if(fDec[decomposeduntil] == decomposeduntil)
		{
#ifdef LOG4CXX
            if (logger->isDebugEnabled()) {
                std::stringstream sout;
                sout << "Will work column " << lcol;
                LOGPZ_DEBUG(logger,sout.str())
            }
#endif
			return;
		}
		lcol++;
		if(lcol == neq) lcol = 0;
    }
예제 #8
0
파일: pzmatred.cpp 프로젝트: labmec/neopz
void TPZMatRed<TVar,TSideMatrix>::SetF(const TPZFMatrix<TVar> & F)
{
	
	int64_t FCols=F.Cols(),c,r,r1;
	
	fF0.Redim(fDim0,FCols);
	fF1.Redim(fDim1,FCols);
	
	for(c=0; c<FCols; c++){
		r1=0;
		for(r=0; r<fDim0; r++){
			fF0.PutVal( r,c,F.GetVal(r,c) ) ;
		}
		//aqui r=fDim0
		for( ;r<fDim0+fDim1; r++){
			fF1.PutVal( r1++,c,F.GetVal(r,c) );
		}
	}
#ifdef LOG4CXX
    if (logger->isDebugEnabled()) {
        std::stringstream sout;
        F.Print("F Input",sout);
        fF0.Print("fF0 Initialized",sout);
        fF1.Print("fF1 Initialized",sout);
        LOGPZ_DEBUG(logger, sout.str())
    }
예제 #9
0
파일: Main.cpp 프로젝트: labmec/neopz
void IterativeProcess(TPZAnalysis *an, std::ostream &out, int numiter)
{
    int iter = 0;
    REAL error = 1.e10, NormResLambdaLast = 1.e10;;
    const REAL tol = 1.e-5;
    
    int numeq = an->Mesh()->NEquations();
    
    TPZFMatrix<STATE> Uatk0(an->Solution());
    TPZFMatrix<STATE> Uatk(Uatk0),DeltaU(Uatk0);
    if(Uatk0.Rows() != numeq) Uatk0.Redim(numeq,1);
    
    an->Assemble();
    an->Rhs() *= -1.0; //- [R(U0)];
    
    TPZAutoPointer< TPZMatrix<STATE> > matK; // getting X(Uatn)
    
    bool converged = false;
    while(!converged && iter < numiter) {
        
#ifdef LOG4CXX
        if(logger->isDebugEnabled())
        {
            std::stringstream sout;
            matK=an->Solver().Matrix();
            matK->Print("matK = ", sout,EMathematicaInput);
            an->Rhs().Print("Rhs = ", sout, EMathematicaInput);
            LOGPZ_DEBUG(logger,sout.str())
        }
#endif
        
        // Computing Uatk = Uatn + DeltaU;
        an->Solve();
        DeltaU= an->Solution();
        Uatk = Uatk0 + DeltaU;
        
        //Computing ||DeltaU||
        REAL NormOfDeltaU = Norm(DeltaU);
        
#ifdef LOG4CXX
        if(logger->isDebugEnabled())
        {
            std::stringstream sout;
            DeltaU.Print("DeltaU = ", sout,EMathematicaInput);
            Uatk.Print("Uatk = ", sout,EMathematicaInput);
            LOGPZ_DEBUG(logger,sout.str())
        }
예제 #10
0
TPZMatrix<STATE> * TPZSpStructMatrix::CreateAssemble(TPZFMatrix<STATE> &rhs,
                                              TPZAutoPointer<TPZGuiInterface> guiInterface){

#ifdef LOG4CXX
    if(logger->isDebugEnabled())
    {
        LOGPZ_DEBUG(logger,"TPZSpStructMatrix::CreateAssemble starting")
    }
#endif
	
    int64_t neq = fMesh->NEquations();
    if(fMesh->FatherMesh()) {
		cout << "TPZSpStructMatrix should not be called with CreateAssemble for a substructure mesh\n";
		return new TPZFYsmpMatrix<STATE>(0,0);
    }
    TPZMatrix<STATE> *stiff = Create();//new TPZFYsmpMatrix(neq,neq);
    TPZFYsmpMatrix<STATE> *mat = dynamic_cast<TPZFYsmpMatrix<STATE> *> (stiff);
    rhs.Redim(neq,1);
    //stiff->Print("Stiffness TPZFYsmpMatrix :: CreateAssemble()");
    TPZTimer before("Assembly of a sparse matrix");
    before.start();
#ifdef LOG4CXX
    if (logger->isDebugEnabled())
    {
        LOGPZ_DEBUG(logger,"TPZSpStructMatrix::CreateAssemble calling Assemble()");
    }
#endif
    Assemble(*stiff,rhs,guiInterface);
    before.stop();
    std::cout << __PRETTY_FUNCTION__ << " " << before << std::endl;
//    mat->ComputeDiagonal();
    //    mat->ComputeDiagonal();
    //stiff->Print("Stiffness TPZFYsmpMatrix :: CreateAssemble()");
#ifdef LOG4CXX
    if(logger->isDebugEnabled()) LOGPZ_DEBUG(logger,"TPZSpStructMatrix::CreateAssemble exiting");
#endif
    return stiff;
}
예제 #11
0
void TPZDarcyAnalysis::PrintLS(TPZAnalysis *an)
{
    TPZAutoPointer< TPZMatrix<REAL> > KGlobal;
    TPZFMatrix<STATE> FGlobal;
    KGlobal =   an->Solver().Matrix();
    FGlobal =   an->Rhs();
    
#ifdef PZDEBUG
    #ifdef LOG4CXX
        if(logger->isDebugEnabled())
        {
            std::stringstream sout;
            KGlobal->Print("KGlobal = ", sout,EMathematicaInput);
            FGlobal.Print("FGlobal = ", sout,EMathematicaInput);
            LOGPZ_DEBUG(logger,sout.str())
        }
예제 #12
0
파일: HDiv.cpp 프로젝트: labmec/neopz
int main()
{
	
#ifdef LOG4CXX
    if (logger->isDebugEnabled())
	{
		InitializePZLOG();
		std::stringstream sout;
		sout<< "Problema de Steklov"<<endl;
		LOGPZ_DEBUG(logger, sout.str());
	}
#endif
	
	for (int porder= 1; porder<2; porder++) {
		
		for(int h=1;h<2;h++){
			
			
			TPZGeoMesh *gmesh2 = MalhaGeo(h);//malha geometrica
			
			
			TPZCompMeshReferred *cmesh = CreateMesh2d(*gmesh2,porder+1);//malha computacional
			
            /*
            TPZCompEl *cel = cmesh->ElementVec()[0];
            TPZManVector<int,5> subindex(4,-1);
            int index;
            cel->Divide(index , subindex);
            cmesh->AdjustBoundaryElements();
            cmesh->ExpandSolution();
            cmesh->CleanUpUnconnectedNodes();
            
            TPZCreateApproximationSpace::MakeRaviartTomas(*cmesh);
            TPZCompEl *cel = cmesh->ElementVec()[0];
            TPZElementMatrix ek(cmesh,TPZElementMatrix::EK),ef(cmesh,TPZElementMatrix::EF);
            cel->CalcStiff(ek, ef);
            ek.ApplyConstraints();
            */
//#ifdef LOG4CXX
//            if (logger->isDebugEnabled())
//            {
//                std::stringstream sout;
//                cmesh->Print(sout);
//                LOGPZ_DEBUG(logger, sout.str())
//            }
//#endif
			int submeshindex = -1;
			TPZSubCompMesh *submesh = 0;
			// Aq faz a condensacao estatica			
			if(h >=0)
				if(-1)
				{
					submeshindex = SubStructure(cmesh,1);//monto a submalha com os elementos q serao condesados (externos) e retorna o numero de elementos computacionais da malha
					submesh = dynamic_cast<TPZSubCompMesh *> (cmesh->ElementVec()[submeshindex]);//converte os elementos computacionais para um objeto do tipo TPZSubCompMesh
                    submesh->SetNumberRigidBodyModes(1);//aq defino o numero de pivos nulos que podera ter o sistema?
					cmesh->ExpandSolution();//ajusta o vetor de solucao
					int numThreads=0;
                    TPZAutoPointer<TPZRenumbering> renumber = new TPZCutHillMcKee;
					submesh->SetAnalysisSkyline(numThreads,1, renumber);
                    cmesh->SetName("Malha depois de SubStructure-----");
#ifdef LOG4CXX
                    if(logger->isDebugEnabled())
						{
								std::stringstream sout;
								cmesh->Print(sout);
								LOGPZ_DEBUG(logger,sout.str())
						}
#endif
				}
			

			
			
			cmesh->LoadReferences();//mapeia para a malha geometrica lo
			
			TPZAdmChunkVector<TPZCompEl *> elvec = cmesh->ElementVec();
			
			TPZAnalysis analysis(cmesh);
			//SaddlePermute(cmesh);
				
		cmesh->SetName("Malha depois de Analysis-----");
#ifdef LOG4CXX
            if (logger->isDebugEnabled())
			{
				std::stringstream sout;
				cmesh->Print(sout);
			//	submesh->Block().Print("Block",sout);
				LOGPZ_DEBUG(logger,sout.str())
			}
예제 #13
0
void TPZYCCamClayPV::ProjectToSurface(const TPZVec<REAL> &sigma_trial_pv, const REAL aPrev, TPZVec<REAL> &sigma_pv, REAL &aProj, const REAL tol) const {
    REAL theta = 0.;
    REAL theta_distance = std::numeric_limits<REAL>::max();
    TPZManVector<REAL> sigma_cyl;
    TPZHWTools::FromPrincipalToHWCyl(sigma_trial_pv, sigma_cyl);
    REAL beta = sigma_cyl[2];
    {
        const REAL initial_theta_guess = 0; // initial_xi_guess = fPt*sqrt3; // multiplying by sqrt converts from p to xi coordinates
        const REAL final_theta_guess = M_PI; // final_xi_guess (fPt - (1 + fGamma * fA)) * sqrt3;
        const unsigned int n_steps_theta = 40;
        const REAL theta_interval = (final_theta_guess - initial_theta_guess) / n_steps_theta;
        for (unsigned int i = 0; i < n_steps_theta; ++i) {
            REAL theta_guess = initial_theta_guess + i*theta_interval;
            REAL distance = DistanceToSurface(sigma_trial_pv, theta_guess, beta, aPrev);
            if (fabs(distance) < fabs(theta_distance)) {
                theta = theta_guess;
                theta_distance = distance;
            }
        }
    }

    REAL residual_norm = std::numeric_limits<REAL>::max();
    TPZFNMatrix<3, STATE> xn(3, 1, 0.), sol(3, 1, 0.);
    TPZManVector<STATE> fxn(3);
    xn(0, 0) = theta;
    xn(1, 0) = beta;
    xn(2, 0) = aPrev;
    for (unsigned int i = 0; i < 30; ++i) {
        TPZFNMatrix<9, STATE> jac(3, 3);
        D2DistanceToSurface(sigma_trial_pv, xn(0), xn(1), xn(2), jac);
        DDistanceToSurface(sigma_trial_pv, xn(0), xn(1), xn(2), aPrev, fxn);
        for (unsigned int k = 0; k < 3; ++k) {
            sol(k, 0) = fxn[k];
        }
        residual_norm = Norm(sol);

#ifdef LOG4CXX
        if (loggerConvTest->isDebugEnabled()) {
            std::stringstream outfile; //("convergencF1.txt");
            outfile << i << " " << log(residual_norm) << endl;
            //jac.Print(outfile);
            //outfile<< "\n xn " << " "<<fxnvec <<endl;
            //outfile<< "\n res " << " "<<fxnvec <<endl;
            LOGPZ_DEBUG(loggerConvTest, outfile.str());
        }
#endif

        jac.Solve_LU(&sol);
        xn = xn - sol;
        if (residual_norm < tol) break;
    }

    STATE thetasol, betasol, asol;

    thetasol = xn(0);
    betasol = xn(1);
    asol = xn(2);
    aProj = asol;

    TPZManVector<STATE, 3> surfaceCyl(3);
    SurfaceInCyl(thetasol, betasol, asol, surfaceCyl);
    TPZHWTools::FromHWCylToPrincipal(surfaceCyl, sigma_pv);
}
예제 #14
0
TPZMultiphysicsInterfaceElement * TPZMultiphysicsElement::CreateInterface(int side)
{
	//  LOGPZ_INFO(logger, "Entering CreateInterface");
	TPZMultiphysicsInterfaceElement * newcreatedinterface = NULL;
	
	TPZGeoEl *ref = Reference();
	if(!ref) {
		LOGPZ_WARN(logger, "Exiting CreateInterface Null reference reached - NULL interface returned");
		return newcreatedinterface;
	}
	
	TPZCompElSide thisside(this,side);
	TPZStack<TPZCompElSide> list;
	list.Resize(0);
	thisside.EqualLevelElementList(list,0,0);//retorna distinto ao atual ou nulo
	int64_t size = list.NElements();
	//espera-se ter os elementos computacionais esquerdo e direito
	//ja criados antes de criar o elemento interface
    // try to create an interface element between myself and an equal sized neighbour
    for (int64_t is=0; is<size; is++)
    {
		//Interface has the same material of the neighbour with lesser dimension.
		//It makes the interface have the same material of boundary conditions (TPZCompElDisc with interface dimension)
		int matid;
		int thisdim = this->Dimension();
		int neighbourdim = list[is].Element()->Dimension();
        
        if(thisdim != neighbourdim)
        {
            if (thisdim < neighbourdim)
            {
                // return the material id of boundary condition IF the associated material is derived from bndcond
                TPZMaterial *mat = this->Material();
                TPZBndCond *bnd = dynamic_cast<TPZBndCond *>(mat);
                if(bnd)
                {
                    matid = this->Material()->Id();
                }
                else
                {
                    matid = this->Mesh()->Reference()->InterfaceMaterial(this->Reference()->MaterialId(),list[0].Element()->Reference()->MaterialId());
                    continue;
                }
            }
			else
            {
                TPZMaterial *mat = list[is].Element()->Material();
                TPZBndCond *bnd = dynamic_cast<TPZBndCond *>(mat);
                if (bnd) {
                    matid = bnd->Id();
                }
                else {
                    matid = this->Mesh()->Reference()->InterfaceMaterial(this->Reference()->MaterialId(), list[0].Element()->Reference()->MaterialId());
                    continue;
                }
            }
        }else
        {
            matid = this->Mesh()->Reference()->InterfaceMaterial(this->Reference()->MaterialId(), list[0].Element()->Reference()->MaterialId());
            if(matid == GMESHNOMATERIAL)
            {
                continue;
            }
        }
		
		int64_t index;
		
		
		TPZGeoEl *gel = ref->CreateBCGeoEl(side,matid); //isto acertou as vizinhanas da interface geometrica com o atual
		if(!gel){
			DebugStop();
#ifdef LOG4CXX
            if (logger->isDebugEnabled())
			{
				std::stringstream sout;
				sout << "CreateBCGeoEl devolveu zero!@@@@";
				LOGPZ_DEBUG(logger,sout.str());
			}
#endif
		}
        bool withmem = fMesh->ApproxSpace().NeedsMemory();
		if(Dimension() > list[is].Reference().Dimension()) {
			//o de volume eh o direito caso um deles seja BC
			//a normal aponta para fora do contorno
			TPZCompElSide thiscompelside(this, thisside.Side());
			TPZCompElSide neighcompelside(list[is]);
            if (!withmem) {
                newcreatedinterface = new TPZMultiphysicsInterfaceElement(*fMesh,gel,index,thiscompelside,neighcompelside);
            }
            else
            {
                newcreatedinterface = new TPZCompElWithMem<TPZMultiphysicsInterfaceElement>(*fMesh,gel,index,thiscompelside,neighcompelside);
            }
		} else {
			//caso contrario ou caso ambos sejam de volume
			TPZCompElSide thiscompelside(this, thisside.Side());
			TPZCompElSide neighcompelside(list[is]);
            if (!withmem) {
                newcreatedinterface = new TPZMultiphysicsInterfaceElement(*fMesh,gel,index,neighcompelside,thiscompelside);
            }
            else
            {
                newcreatedinterface = new TPZCompElWithMem<TPZMultiphysicsInterfaceElement>(*fMesh,gel,index,neighcompelside,thiscompelside);
            }
		}
		
		
		
		return newcreatedinterface;
	}
	
	//If there is no equal or lower level element, we try the lower elements.
	//Higher elements will not be considered by this method. In that case the interface must be created by the neighbour.
	TPZCompElSide lower = thisside.LowerLevelElementList(0);
	if(lower.Exists()){
		//Interface has the same material of the neighbour with lesser dimension.
		//It makes the interface has the same material of boundary conditions (TPZCompElDisc with interface dimension)
		int matid = GMESHNOMATERIAL;
		int thisdim = this->Dimension();
		int neighbourdim = lower.Element()->Dimension();
        matid = this->Mesh()->Reference()->InterfaceMaterial(this->Material()->Id(), lower.Element()->Material()->Id() );
		
		if (matid == GMESHNOMATERIAL && thisdim == neighbourdim){
			//      matid = this->Material()->Id();
            //break;
        }
        else if(matid == GMESHNOMATERIAL && thisdim != neighbourdim)
        {
			if (thisdim < neighbourdim) 
            {
                // return the material id of boundary condition IF the associated material is derived from bndcond
                TPZMaterial *mat = this->Material();
                TPZBndCond *bnd = dynamic_cast<TPZBndCond *>(mat);
                if(bnd)
                {
                    matid = this->Material()->Id();
                }
                else {
                    //continue;
                }
            }
			else 
            {
                TPZMaterial *mat = lower.Element()->Material();
                TPZBndCond *bnd = dynamic_cast<TPZBndCond *>(mat);
                if (bnd) {
                    matid = bnd->Id();
                }
                else {
                    //continue;
                }
            }
		}
		
        // return zero
        if(matid == GMESHNOMATERIAL)
        {
            return newcreatedinterface;
        }
		
		TPZCompEl *lowcel = lower.Element();
		//int lowside = lower.Side();
		//existem esquerdo e direito: this e lower
		TPZGeoEl *gel = ref->CreateBCGeoEl(side,matid);
		int64_t index;
		
        bool withmem = fMesh->ApproxSpace().NeedsMemory();
        
		if(Dimension() > lowcel->Dimension()){
			//para que o elemento esquerdo seja de volume
			TPZCompElSide thiscompelside(this, thisside.Side());
			TPZCompElSide lowcelcompelside(lower);
            if (!withmem) {
                newcreatedinterface = new TPZMultiphysicsInterfaceElement(*fMesh,gel,index,thiscompelside,lowcelcompelside);
            }
            else
            {
                newcreatedinterface = new TPZCompElWithMem<TPZMultiphysicsInterfaceElement>(*fMesh,gel,index,thiscompelside,lowcelcompelside);
            }
		} else {
			TPZCompElSide thiscompelside(this, thisside.Side());
			TPZCompElSide lowcelcompelside(lower);
#ifdef LOG4CXX_KEEP
            if (logger->isDebugEnabled())
			{
				std::stringstream sout;
				sout << __PRETTY_FUNCTION__ << " left element";
				sout << lowcelcompelside << thiscompelside;
				sout << "Left Element ";
				lowcelcompelside.Element()->Print(sout);
				sout << "Right Element ";
				thiscompelside.Element()->Print(sout);
				LOGPZ_DEBUG(logger,sout.str())
			}
#endif
            if (!withmem)
            {
                newcreatedinterface = new TPZMultiphysicsInterfaceElement(*fMesh,gel,index,lowcelcompelside,thiscompelside);
            }
            else
            {
                newcreatedinterface = new TPZCompElWithMem<TPZMultiphysicsInterfaceElement>(*fMesh,gel,index,lowcelcompelside,thiscompelside);
            }
		}
예제 #15
0
파일: main.cpp 프로젝트: labmec/neopz
TPZGeoMesh *GMesh(bool triang_elements, REAL Lx, REAL Ly){
    
    int Qnodes = 4;
	
	TPZGeoMesh * gmesh = new TPZGeoMesh;
	gmesh->SetMaxNodeId(Qnodes-1);
	gmesh->NodeVec().Resize(Qnodes);
	TPZVec<TPZGeoNode> Node(Qnodes);
	
	TPZVec <int64_t> TopolQuad(4);
    TPZVec <int64_t> TopolTriang(3);
	TPZVec <int64_t> TopolLine(2);
    TPZVec <int64_t> TopolPoint(1);
	
	//indice dos nos
	int64_t id = 0;
	REAL valx;
	for(int xi = 0; xi < Qnodes/2; xi++)
	{
		valx = xi*Lx;
		Node[id].SetNodeId(id);
		Node[id].SetCoord(0 ,valx );//coord X
		Node[id].SetCoord(1 ,0. );//coord Y
		gmesh->NodeVec()[id] = Node[id];
		id++;
	}
	
	for(int xi = 0; xi < Qnodes/2; xi++)
	{
		valx = Lx - xi*Lx;
		Node[id].SetNodeId(id);
		Node[id].SetCoord(0 ,valx );//coord X
		Node[id].SetCoord(1 ,Ly);//coord Y
		gmesh->NodeVec()[id] = Node[id];
		id++;
	}
	
	//indice dos elementos
	id = 0;
    
    if(triang_elements==true)
    {
        TopolTriang[0] = 0;
        TopolTriang[1] = 1;
        TopolTriang[2] = 3;
        new TPZGeoElRefPattern< pzgeom::TPZGeoTriangle > (id,TopolTriang,matId,*gmesh);
        id++;
        
        TopolTriang[0] = 2;
        TopolTriang[1] = 1;
        TopolTriang[2] = 3;
        new TPZGeoElRefPattern< pzgeom::TPZGeoTriangle> (id,TopolTriang,matId,*gmesh);
        id++;
        
        TopolLine[0] = 0;
        TopolLine[1] = 1;
        new TPZGeoElRefPattern< pzgeom::TPZGeoLinear > (id,TopolLine,bc0,*gmesh);
        id++;
        
        TopolLine[0] = 2;
        TopolLine[1] = 1;
        new TPZGeoElRefPattern< pzgeom::TPZGeoLinear > (id,TopolLine,bc1,*gmesh);
        id++;
        
        TopolLine[0] = 3;
        TopolLine[1] = 2;
        new TPZGeoElRefPattern< pzgeom::TPZGeoLinear > (id,TopolLine,bc2,*gmesh);
        id++;
        
        TopolLine[0] = 3;
        TopolLine[1] = 0;
        new TPZGeoElRefPattern< pzgeom::TPZGeoLinear > (id,TopolLine,bc3,*gmesh);
    }
    else{
        TopolQuad[0] = 0;
        TopolQuad[1] = 1;
        TopolQuad[2] = 2;
        TopolQuad[3] = 3;
        new TPZGeoElRefPattern< pzgeom::TPZGeoQuad> (id,TopolQuad,matId,*gmesh);
        id++;
        
        TopolLine[0] = 0;
        TopolLine[1] = 1;
        new TPZGeoElRefPattern< pzgeom::TPZGeoLinear > (id,TopolLine,bc0,*gmesh);
        id++;
        
        TopolLine[0] = 1;
        TopolLine[1] = 2;
        new TPZGeoElRefPattern< pzgeom::TPZGeoLinear > (id,TopolLine,bc1,*gmesh);
        id++;
        
        TopolLine[0] = 2;
        TopolLine[1] = 3;
        new TPZGeoElRefPattern< pzgeom::TPZGeoLinear > (id,TopolLine,bc2,*gmesh);
        id++;
        
        TopolLine[0] = 3;
        TopolLine[1] = 0;
        new TPZGeoElRefPattern< pzgeom::TPZGeoLinear > (id,TopolLine,bc3,*gmesh);
    }
    
	gmesh->BuildConnectivity();
    
    #ifdef LOG4CXX
    	if(logger->isDebugEnabled())
    	{
            std::stringstream sout;
            sout<<"\n\n Malha Geometrica Inicial\n ";
            gmesh->Print(sout);
          LOGPZ_DEBUG(logger,sout.str())
    	}
예제 #16
0
bool TrySipInvite(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd)
{
	CStdString logMsg;
	bool result = false;
	bool drop = false;
	CStdString sipMethod;

	int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct);
	char* sipEnd = (char*)udpPayload + sipLength;

	if (DLLCONFIG.m_ipFragmentsReassemble == false && sipEnd > (char*)packetEnd && ipHeader->offset() == 0) {
		FLOG_DEBUG(s_sipExtractionLog, "Will try to process incomplete first fragment with id:%u",ipHeader->packetId());
		sipEnd = (char*)packetEnd;
	}

	if(sipLength < 3 || sipEnd > (char*)packetEnd)
	{
		drop = true;	// packet too short
	}
	else if(memcmp(SIP_METHOD_INVITE, (void*)udpPayload, SIP_METHOD_INVITE_SIZE) == 0)
	{
		sipMethod = SIP_METHOD_INVITE;
	}
	else if(memcmp(SIP_METHOD_ACK, (void*)udpPayload, SIP_METHOD_ACK_SIZE) == 0)
	{
		sipMethod = SIP_METHOD_ACK;
	}
	else if((DLLCONFIG.m_sipTreat200OkAsInvite == true) && (memcmp(SIP_RESPONSE_200_OK, (void*)udpPayload, SIP_RESPONSE_200_OK_SIZE) == 0))
	{
		sipMethod = SIP_METHOD_200_OK;
		LOG4CXX_DEBUG(s_sipExtractionLog, "TrySipInvite: packet matches 200 OK and SipTreat200OkAsInvite is enabled");
	}
	else if((DLLCONFIG.m_sipDetectSessionProgress == true) && (memcmp(SIP_RESPONSE_SESSION_PROGRESS, (void*)udpPayload, SIP_RESPONSE_SESSION_PROGRESS_SIZE) == 0))
	{
		sipMethod = SIP_RESPONSE_SESSION_PROGRESS;
	}
	else
	{
		drop = true;
	}

	if (drop == false)
	{
		result = true;

		SipInviteInfoRef info(new SipInviteInfo());
		info->m_sipMethod = sipMethod;
		char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd);
		if(!fromField)
		{
			fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd);
		}
		char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd);
		if(!toField)
		{
			toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd);
		}
		char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd);
		if(!callIdField)
		{
			callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd);
		}

		char* replacesField = memFindAfter("Replaces:", (char*)udpPayload, sipEnd);
		if(!replacesField)
		{
			replacesField = memFindAfter("\nr:", (char*)udpPayload, sipEnd);
		}

		char * dialedNumber = NULL;
		if(!(DLLCONFIG.m_sipDialedNumberFieldName.length()==0) )
		{
			dialedNumber = memFindAfter(DLLCONFIG.m_sipDialedNumberFieldName + ":", (char*)udpPayload,sipEnd);
		}

		char * sipRemoteParty = NULL;
		if(!(DLLCONFIG.m_sipRemotePartyFieldName.length()==0) )
		{
			sipRemoteParty = memFindAfter(DLLCONFIG.m_sipRemotePartyFieldName + ":", (char*)udpPayload,sipEnd);
		}

		char* contactField = memFindAfter("Contact:", (char*)udpPayload, sipEnd);
		if(!contactField)
		{
			contactField = memFindAfter("\nc:", (char*)udpPayload, sipEnd);
		}

                char * audioSdpStart = (char*) udpPayload;;
                char * audioSdpEnd   = (char*) sipEnd;;

                char* audioStart = memFindAfter("m=audio", (char*)udpPayload, sipEnd);
                char* videoStart = memFindAfter("m=video", (char*)udpPayload, sipEnd);

                if (audioStart < videoStart) {
                    audioSdpEnd = videoStart;
                }

                if (audioStart > videoStart) {
                    audioSdpStart = audioStart;
                }

		char* localExtensionField = memFindAfter(DLLCONFIG.m_sipLocalPartyFieldName, (char*)udpPayload, sipEnd);
		char* audioField = NULL;
		char* connectionAddressField = NULL;
		char* attribSendonly = memFindAfter("a=sendonly", (char*)audioSdpStart, audioSdpEnd);
		char* attribInactive = memFindAfter("a=inactive", (char*)audioSdpStart, audioSdpEnd);
		char* rtpmapAttribute = memFindAfter("\na=rtpmap:", (char*)audioSdpStart, audioSdpEnd);
		char* userAgentField = memFindAfter("\nUser-Agent:", (char*)udpPayload, sipEnd);

		if(DLLCONFIG.m_sipRequestUriAsLocalParty == true)
		{
			char* sipUriAttribute = memFindAfter("INVITE ", (char*)udpPayload, sipEnd);

			if(sipUriAttribute)
			{
				if(s_sipExtractionLog->isDebugEnabled())
				{
					CStdString uri;
					GrabLine(sipUriAttribute, sipEnd, uri);
					LOG4CXX_DEBUG(s_sipExtractionLog, "uri: " + uri);
				}

				char* sipUriAttributeEnd = memFindEOL(sipUriAttribute, sipEnd);
				char* sipUser = memFindAfter("sip:", sipUriAttribute, sipUriAttributeEnd);

				if(sipUser)
				{
					if(DLLCONFIG.m_sipReportFullAddress)
					{
						GrabSipUserAddress(sipUser, sipUriAttributeEnd, info->m_requestUri);
					}
					else
					{
						GrabSipUriUser(sipUser, sipUriAttributeEnd, info->m_requestUri);
					}
				}
				else
				{
					if(DLLCONFIG.m_sipReportFullAddress)
					{
						GrabSipUserAddress(sipUriAttribute, sipUriAttributeEnd, info->m_requestUri);
					}
					else
					{
						GrabSipUriUser(sipUriAttribute, sipUriAttributeEnd, info->m_requestUri);
					}
				}

				if(s_sipExtractionLog->isDebugEnabled())
				{
					LOG4CXX_DEBUG(s_sipExtractionLog, "extracted uri: " + info->m_requestUri);
				}
			}
		}

		if(fromField)
		{
			if(s_sipExtractionLog->isDebugEnabled())
			{
				CStdString from;
				GrabLine(fromField, sipEnd, from);
				LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from);
			}

			char* fromFieldEnd = memFindEOL(fromField, sipEnd);

			GrabSipName(fromField, fromFieldEnd, info->m_fromName);

			char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, fromFieldEnd, info->m_from);
				}
				else
				{
					GrabSipUriUser(sipUser, fromFieldEnd, info->m_from);
				}
				GrabSipUriDomain(sipUser, fromFieldEnd, info->m_fromDomain);
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(fromField, fromFieldEnd, info->m_from);
				}
				else
				{
					GrabSipUriUser(fromField, fromFieldEnd, info->m_from);
				}
				GrabSipUriDomain(fromField, fromFieldEnd, info->m_fromDomain);
			}
		}
		if(toField)
		{
			CStdString to;
			char* toFieldEnd = GrabLine(toField, sipEnd, to);
			LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to);

			GrabSipName(toField, toFieldEnd, info->m_toName);

			char* sipUser = memFindAfter("sip:", toField, toFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, toFieldEnd, info->m_to);
				}
				else
				{
					GrabSipUriUser(sipUser, toFieldEnd, info->m_to);
				}
				GrabSipUriDomain(sipUser, toFieldEnd, info->m_toDomain);
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(toField, toFieldEnd, info->m_to);
				}
				else
				{
					GrabSipUriUser(toField, toFieldEnd, info->m_to);
				}
				GrabSipUriDomain(toField, toFieldEnd, info->m_toDomain);
			}
			if(DLLCONFIG.m_sipGroupPickUpPattern == info->m_to)
			{
				info->m_SipGroupPickUpPatternDetected = true;
			}
		}
		if(dialedNumber)
		{
			CStdString token;
			GrabTokenSkipLeadingWhitespaces(dialedNumber, sipEnd, token);
			info->m_sipDialedNumber = token;
		}
		if(sipRemoteParty)
		{
			CStdString token;

			char* sip = memFindAfter("sip:", sipRemoteParty, sipEnd);
			if(sip)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sip, sipEnd, token);
				}
				else
				{
					GrabSipUriUser(sip, sipEnd, token);
				}
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipRemoteParty, sipEnd, token);
				}
				else
				{
					GrabSipUriUser(sipRemoteParty, sipEnd, token);
				}
			}
			info->m_sipRemoteParty = token;
		}
		if(callIdField)
		{
			GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId);
			audioField = memFindAfter("m=audio ", callIdField, sipEnd);
			connectionAddressField = memFindAfter("c=IN IP4 ", callIdField, sipEnd);
		}
		if(replacesField)
		{
			CStdString fieldContent;
			GrabTokenSkipLeadingWhitespaces(replacesField, sipEnd, fieldContent);
			int firstsemicoma;
			firstsemicoma = fieldContent.Find(';');
			if(firstsemicoma != -1)
			{
				info->m_replacesId = fieldContent.substr(0, firstsemicoma);
			}

			LOG4CXX_DEBUG(s_sipExtractionLog, "replaces CallId:" + info->m_replacesId);
		}
		if(localExtensionField)
		{
			CStdString localExtension;
			GrabTokenSkipLeadingWhitespaces(localExtensionField, sipEnd, localExtension);
			if(localExtension.size() > 0)
			{
				info->m_from = localExtension;
			}
		}
		if(userAgentField)
		{
			GrabTokenSkipLeadingWhitespaces(userAgentField, sipEnd, info->m_userAgent);
		}
		if(audioField)
		{
			GrabToken(audioField, sipEnd, info->m_fromRtpPort);
		}
		if(attribSendonly || attribInactive)
		{
			info->m_attrSendonly = true;
		}
		if(connectionAddressField)
		{
			CStdString connectionAddress;
			GrabToken(connectionAddressField, sipEnd, connectionAddress);
			struct in_addr fromIp;
			if(connectionAddress.size())
			{
				if(ACE_OS::inet_aton((PCSTR)connectionAddress, &fromIp))
				{
					info->m_fromRtpIp = fromIp;

					if (DLLCONFIG.m_sipDropIndirectInvite)
					{
						if((unsigned int)fromIp.s_addr != (unsigned int)ipHeader->ip_src.s_addr)
						{
							// SIP invite SDP connection address does not match with SIP packet origin
							drop =true;
						}
					}
				}
			}
		}
		if(contactField && sipMethod == SIP_METHOD_INVITE)
		{
			CStdString contact;
			char* contactFieldEnd = GrabLine(contactField, sipEnd, contact);
			LOG4CXX_DEBUG(s_sipExtractionLog, "contact: " + contact);

			GrabSipName(contactField, contactFieldEnd, info->m_contactName);

			char* sipUser = memFindAfter("sip:", contactField, contactFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, contactFieldEnd, info->m_contact);
				}
				else
				{
					GrabSipUriUser(sipUser, contactFieldEnd, info->m_contact);
				}
				GrabSipUriDomain(sipUser, contactFieldEnd, info->m_contactDomain);
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(contactField, contactFieldEnd, info->m_contact);
				}
				else
				{
					GrabSipUriUser(contactField, contactFieldEnd, info->m_contact);
				}
				GrabSipUriDomain(contactField, contactFieldEnd, info->m_contactDomain);
			}
		}
		// SIP fields extraction
		for(std::list<CStdString>::iterator it = DLLCONFIG.m_sipExtractFields.begin(); it != DLLCONFIG.m_sipExtractFields.end(); it++)
		{
			CStdString fieldName = *it + ":";
			char* szField = memFindAfter((PSTR)(PCSTR)fieldName, (char*)udpPayload, sipEnd);
			if(szField)
			{
				CStdString field;

				// XXX
				// The line below was replaced because I experienced
				// cases where we would have a leading whitespace in the
				// tag which has been extracted.  However, since we are
				// dealing with SIP, RFC 3261, section 7.3.1 illustrates
				// that any leading whitespaces after the colon is not
				// in fact part of the header value.  Therefore, I
				// created the GrabLineSkipLeadingWhitespace() function
				// which I use in this particular case.
				//
				// Hope this is ok.
				//
				// --Gerald
				//
				//GrabLine(szField, sipEnd, field);

				GrabLineSkipLeadingWhitespace(szField, sipEnd, field);
				info->m_extractedFields.insert(std::make_pair(*it, field));
			}
		}

		if(DLLCONFIG.m_rtpReportDtmf)
		{
			if(rtpmapAttribute)
			{
				CStdString rtpPayloadType, nextToken;
				char *nextStep = NULL;

				while(rtpmapAttribute && rtpmapAttribute < sipEnd)
				{
					rtpPayloadType = "";
					GrabTokenSkipLeadingWhitespaces(rtpmapAttribute, audioSdpEnd, rtpPayloadType);
					nextToken.Format("%s ", rtpPayloadType);
					nextStep = memFindAfter((char*)nextToken.c_str(), rtpmapAttribute, audioSdpEnd);

					/* We need our "nextStep" to contain at least the length
					 * of the string "telephone-event", 15 characters */
					if(nextStep && ((sipEnd - nextStep) >= 15))
					{
						if(ACE_OS::strncasecmp(nextStep, "telephone-event", 15) == 0)
						{
							/* Our DTMF packets are indicated using
							 * the payload type rtpPayloadType */
							info->m_telephoneEventPayloadType = rtpPayloadType;
							info->m_telephoneEventPtDefined = true;
							break;
						}
					}

					rtpmapAttribute = memFindAfter("\na=rtpmap:", rtpmapAttribute, audioSdpEnd);
				}
			}
		}

		//Determine the being used codec: should be the first rtpmap
		if(sipMethod == SIP_METHOD_200_OK || sipMethod == SIP_RESPONSE_SESSION_PROGRESS)
		{
			rtpmapAttribute = memFindAfter("\na=rtpmap:", (char*)audioSdpStart, audioSdpEnd);
			if(rtpmapAttribute)
			{
				CStdString line;
				GrabLineSkipLeadingWhitespace(rtpmapAttribute, sipEnd, line);
				info->m_orekaRtpPayloadType = GetOrekaRtpPayloadTypeForSdpRtpMap(line);
			}
		}

		if((unsigned int)info->m_fromRtpIp.s_addr == 0)
		{
			// In case connection address could not be extracted, use SIP invite sender IP address
			if(DLLCONFIG.m_dahdiIntercept == true)
			{
				info->m_fromRtpIp = ipHeader->ip_dest;
			}
			else
			{
				info->m_fromRtpIp = ipHeader->ip_src;
			}
		}
		if(sipMethod == SIP_METHOD_200_OK)
		{
			info->m_senderIp = ipHeader->ip_dest;
			info->m_receiverIp = ipHeader->ip_src;
		}
		else
		{
			info->m_senderIp = ipHeader->ip_src;
			info->m_receiverIp = ipHeader->ip_dest;
		}
		info->m_originalSenderIp = ipHeader->ip_src;
		info->m_recvTime = time(NULL);
		memcpy(info->m_senderMac, ethernetHeader->sourceMac, sizeof(info->m_senderMac));
		memcpy(info->m_receiverMac, ethernetHeader->destinationMac, sizeof(info->m_receiverMac));

		if(sipMethod.Equals(SIP_METHOD_INVITE) || info->m_fromRtpPort.size())
		{
			// Only log SIP non-INVITE messages that contain SDP (i.e. with a valid RTP port)
			info->ToString(logMsg);
			logMsg = sipMethod + ": " + logMsg;
			LOG4CXX_INFO(s_sipPacketLog, logMsg);
		}

		//Sip INVITE without sdp will be reported, but other methods without sdp will not be
		if(drop == false && sipMethod == SIP_METHOD_INVITE && info->m_from.size() && info->m_to.size() && info->m_callId.size())
		{
			VoIpSessionsSingleton::instance()->ReportSipInvite(info);
		}
		else if(drop == false && info->m_fromRtpPort.size() && info->m_from.size() && info->m_to.size() && info->m_callId.size())
		{
			VoIpSessionsSingleton::instance()->ReportSipInvite(info);
		}
	}
	return result;
}
예제 #17
0
bool TrySipRefer(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd)
{
	bool result = false;

	int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct);
	char* sipEnd = (char*)udpPayload + sipLength;
	if(sipLength < SIP_METHOD_REFER_SIZE || sipEnd > (char*)packetEnd)
	{
		;	// packet too short
	}
	else if(memcmp(SIP_METHOD_REFER, (void*)udpPayload, SIP_METHOD_REFER_SIZE) == 0)
	{
		result = true;

		SipReferRef info(new SipRefer());
		info->m_timestamp = time(NULL);
		char* referToField = memFindAfter("Refer-To:", (char*)udpPayload, sipEnd);
		char* referredByField = memFindAfter("Referred-By:", (char*)udpPayload, sipEnd);
		char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd);
		if(!callIdField)
		{
			callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd);
		}
		char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd);
		if(!fromField)
		{
			fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd);
		}
		char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd);
		if(!toField)
		{
			toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd);
		}

		if(callIdField)
		{
			GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId);
		}

		if(fromField)
		{
			if(s_sipExtractionLog->isDebugEnabled())
			{
				CStdString from;
				GrabLine(fromField, sipEnd, from);
				LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from);
			}
			char* fromFieldEnd = memFindEOL(fromField, sipEnd);
			GrabSipName(fromField, fromFieldEnd, info->m_fromName);
			char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd);
			if(sipUser)
			{
				GrabSipUriUser(sipUser, fromFieldEnd, info->m_from);
				GrabSipUriDomain(sipUser, fromFieldEnd, info->m_fromDomain);
			}
			else
			{
				GrabSipUriUser(fromField, fromFieldEnd, info->m_from);
				GrabSipUriDomain(fromField, fromFieldEnd, info->m_fromDomain);
			}
		}
		if(toField)
		{
			CStdString to;
			char* toFieldEnd = GrabLine(toField, sipEnd, to);
			LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to);
			GrabSipName(toField, toFieldEnd, info->m_toName);
			char* sipUser = memFindAfter("sip:", toField, toFieldEnd);
			if(sipUser)
			{
				GrabSipUriUser(sipUser, toFieldEnd, info->m_to);
				GrabSipUriDomain(sipUser, toFieldEnd, info->m_toDomain);
			}
			else
			{
				GrabSipUriUser(toField, toFieldEnd, info->m_to);
				GrabSipUriDomain(toField, toFieldEnd, info->m_toDomain);
			}
		}

		if(referToField)
		{
			char* referToFieldEnd = memFindEOL(referToField, sipEnd);
			char* sipUser = memFindAfter("sip:", referToField, referToFieldEnd);
			if(sipUser)
			{
				GrabSipUriUser(sipUser, referToFieldEnd, info->m_referToParty);

			}
		}
		if(referredByField)
		{
			char* referredByFieldEnd = memFindEOL(referredByField, sipEnd);
			char* sipUser = memFindAfter("sip:", referredByField, referredByFieldEnd);
			if(sipUser)
			{
				GrabSipUriUser(sipUser, referredByFieldEnd, info->m_referredByParty);

			}
		}
		if((!(info->m_to.length()==0)) && (info->m_to.CompareNoCase(info->m_referToParty) != 0) && (info->m_to.CompareNoCase(info->m_referredByParty) != 0))
		{
			info->m_referredParty = info->m_to;
		}
		if((!(info->m_from.length()==0)) && (info->m_from.CompareNoCase(info->m_referToParty) != 0) && (info->m_from.CompareNoCase(info->m_referredByParty) != 0))
		{
			info->m_referredParty = info->m_from;
		}
		info->m_senderIp = ipHeader->ip_src;
		info->m_receiverIp = ipHeader->ip_dest;

		CStdString logMsg;

		info->ToString(logMsg);
		logMsg = "REFER: " + logMsg;
		LOG4CXX_INFO(s_sipPacketLog, logMsg);

		VoIpSessionsSingleton::instance()->ReportSipRefer(info);
	}
	return result;
}
예제 #18
0
bool TrySipBye(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd)
{
	bool result = false;

	int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct);
	char* sipEnd = (char*)udpPayload + sipLength;
	if(sipLength < (int)sizeof(SIP_METHOD_BYE) || sipEnd > (char*)packetEnd)
	{
		return false;
	}

	if (memcmp(SIP_METHOD_BYE, (void*)udpPayload, SIP_METHOD_BYE_SIZE) == 0)
	{
		result = true;
		SipByeInfoRef info(new SipByeInfo());

		char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd);
		if(!fromField)
		{
			fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd);
		}
		char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd);
		if(!toField)
		{
			toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd);
		}

		char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd);
		if(!callIdField)
		{
			callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd);
		}
		if(callIdField)
		{
			GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId);
		}

		if(fromField)
		{
			if(s_sipExtractionLog->isDebugEnabled())
			{
				CStdString from;
				GrabLine(fromField, sipEnd, from);
				LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from);
			}

			char* fromFieldEnd = memFindEOL(fromField, sipEnd);

			GrabSipName(fromField, fromFieldEnd, info->m_fromName);

			char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, fromFieldEnd, info->m_from);
				}
				else
				{
					GrabSipUriUser(sipUser, fromFieldEnd, info->m_from);
				}
				GrabSipUriDomain(sipUser, fromFieldEnd, info->m_fromDomain);
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(fromField, fromFieldEnd, info->m_from);
				}
				else
				{
					GrabSipUriUser(fromField, fromFieldEnd, info->m_from);
				}
				GrabSipUriDomain(fromField, fromFieldEnd, info->m_fromDomain);
			}
		}
		if(toField)
		{
			CStdString to;
			char* toFieldEnd = GrabLine(toField, sipEnd, to);
			LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to);

			GrabSipName(toField, toFieldEnd, info->m_toName);

			char* sipUser = memFindAfter("sip:", toField, toFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, toFieldEnd, info->m_to);
				}
				else
				{
					GrabSipUriUser(sipUser, toFieldEnd, info->m_to);
				}
				GrabSipUriDomain(sipUser, toFieldEnd, info->m_toDomain);
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(toField, toFieldEnd, info->m_to);
				}
				else
				{
					GrabSipUriUser(toField, toFieldEnd, info->m_to);
				}
				GrabSipUriDomain(toField, toFieldEnd, info->m_toDomain);
			}
		}

		info->m_senderIp = ipHeader->ip_src;
		info->m_receiverIp = ipHeader->ip_dest;

		CStdString logMsg;
		info->ToString(logMsg);
		LOG4CXX_INFO(s_sipPacketLog, "BYE: " + logMsg);
		if(callIdField && DLLCONFIG.m_sipIgnoreBye == false)
		{
			VoIpSessionsSingleton::instance()->ReportSipBye(info);
		}
	}
	return result;
}
예제 #19
0
void HandleSkinnyMessage(SkinnyHeaderStruct* skinnyHeader, IpHeaderStruct* ipHeader, u_char* packetEnd, TcpHeaderStruct* tcpHeader)
{
	bool useful = true;
	CStdString logMsg;

	SkStartMediaTransmissionStruct* startMedia;
	SkStartMediaTransmissionStruct smtmp;
	SkStopMediaTransmissionStruct* stopMedia;
	SkCallInfoStruct* callInfo;
	SkCallStateMessageStruct* callStateMessage;
	SkOpenReceiveChannelAckStruct* openReceiveAck;
	SkOpenReceiveChannelAckStruct orcatmp;
	SkLineStatStruct* lineStat;
	SkCcm5CallInfoStruct* ccm5CallInfo;
	SkSoftKeyEventMessageStruct* softKeyEvent;
	SkSoftKeySetDescriptionStruct* softKeySetDescription;

	char szEndpointIp[16];
	char szCmIp[16];
	struct in_addr endpointIp = ipHeader->ip_dest;	// most of the interesting skinny messages are CCM -> phone
	struct in_addr cmIp = ipHeader->ip_src;
	unsigned short endpointTcpPort = ntohs(tcpHeader->dest);
	unsigned short cmTcpPort = ntohs(tcpHeader->source);


	memset(&smtmp, 0, sizeof(smtmp));
	memset(&orcatmp, 0, sizeof(orcatmp));

	switch(skinnyHeader->messageType)
	{
	case SkStartMediaTransmission:

		startMedia = (SkStartMediaTransmissionStruct*)skinnyHeader;
		SkCcm7_1StartMediaTransmissionStruct *ccm7_1sm;
		ccm7_1sm = (SkCcm7_1StartMediaTransmissionStruct*)skinnyHeader;

		if(SkinnyValidateStartMediaTransmission(startMedia, packetEnd))
		{
			if(s_skinnyParsersLog->isInfoEnabled())
			{
				char szRemoteIp[16];
				ACE_OS::inet_ntop(AF_INET, (void*)&startMedia->remoteIpAddr, szRemoteIp, sizeof(szRemoteIp));
				logMsg.Format(" CallId:%u PassThru:%u media address:%s,%u", startMedia->conferenceId, startMedia->passThruPartyId, szRemoteIp, startMedia->remoteTcpPort);
			}
			VoIpSessionsSingleton::instance()->ReportSkinnyStartMediaTransmission(startMedia, ipHeader, tcpHeader);
		}
		else if(SkinnyValidateCcm7_1StartMediaTransmission(ccm7_1sm, packetEnd))
		{
			startMedia = &smtmp;

			memcpy(&startMedia->header, &ccm7_1sm->header, sizeof(startMedia->header));
			startMedia->conferenceId = ccm7_1sm->conferenceId;
			startMedia->passThruPartyId = ccm7_1sm->passThruPartyId;
			memcpy(&startMedia->remoteIpAddr, &ccm7_1sm->remoteIpAddr, sizeof(startMedia->remoteIpAddr));
			startMedia->remoteTcpPort = ccm7_1sm->remoteTcpPort;

			if(s_skinnyParsersLog->isInfoEnabled())
			{
				char szRemoteIp[16];
				ACE_OS::inet_ntop(AF_INET, (void*)&startMedia->remoteIpAddr, szRemoteIp, sizeof(szRemoteIp));
				logMsg.Format(" (CCM 7.1) CallId:%u PassThru:%u media address:%s,%u", startMedia->conferenceId, startMedia->passThruPartyId, szRemoteIp, startMedia->remoteTcpPort);
			}

			VoIpSessionsSingleton::instance()->ReportSkinnyStartMediaTransmission(startMedia, ipHeader, tcpHeader);
		}
		else
		{
			useful = false;
			LOG4CXX_WARN(s_skinnyParsersLog, "Invalid StartMediaTransmission.");
		}
		break;
	case SkStopMediaTransmission:
	case SkCloseReceiveChannel:
		// StopMediaTransmission and CloseReceiveChannel have the same definition, treat them the same for now.
		stopMedia = (SkStopMediaTransmissionStruct*)skinnyHeader;
		if(SkinnyValidateStopMediaTransmission(stopMedia, packetEnd))
		{
			if(s_skinnyParsersLog->isInfoEnabled())
			{
				logMsg.Format(" ConferenceId:%u PassThruPartyId:%u", stopMedia->conferenceId, stopMedia->passThruPartyId);
			}
			VoIpSessionsSingleton::instance()->ReportSkinnyStopMediaTransmission(stopMedia, ipHeader, tcpHeader);
		}
		else
		{
			useful = false;
			LOG4CXX_WARN(s_skinnyParsersLog, "Invalid StopMediaTransmission or CloseReceiveChannel.");
		}
		break;
	case SkCallInfoMessage:
		callInfo = (SkCallInfoStruct*)skinnyHeader;
		if(SkinnyValidateCallInfo(callInfo, packetEnd))
		{
			if(s_skinnyParsersLog->isInfoEnabled())
			{
				ConvertWin1251ToUtf8(callInfo->callingPartyName, utf);
				ConvertWin1251ToUtf8(callInfo->calledPartyName, utf);
				logMsg.Format(" CallId:%u calling:%s called:%s callingname:%s calledname:%s line:%d callType:%d",
								callInfo->callId, callInfo->callingParty, callInfo->calledParty,
								callInfo->callingPartyName, callInfo->calledPartyName, callInfo->lineInstance, callInfo->callType);

			}
			VoIpSessionsSingleton::instance()->ReportSkinnyCallInfo(callInfo, ipHeader, tcpHeader);
		}
		else
		{
			useful = false;
			LOG4CXX_WARN(s_skinnyParsersLog, "Invalid CallInfoMessage.");
		}
		break;
	case SkCallStateMessage:
		callStateMessage = (SkCallStateMessageStruct*)skinnyHeader;
		if(SkinyValidateCallStateMessage(callStateMessage, packetEnd))
		{
			VoIpSessionsSingleton::instance()->ReportSkinnyCallStateMessage(callStateMessage, ipHeader, tcpHeader);
		}
	case SkCcm5CallInfoMessage:
		ccm5CallInfo = (SkCcm5CallInfoStruct*)skinnyHeader;
		if(SkinnyValidateCcm5CallInfo(ccm5CallInfo, packetEnd))
		{
			// Extract Calling and Called number.
			char* parties = (char*)(&ccm5CallInfo->parties);
			char* partiesPtr = parties;
			long partiesLen = (long)packetEnd - (long)ccm5CallInfo - sizeof(SkCcm5CallInfoStruct);

			CStdString callingParty;
			CStdString calledParty;
			CStdString callingPartyName;
			CStdString calledPartyName;

			// Tokens separated by a single null char. Multiple sequential null chars result in empty tokens.
			// There are 12 tokens:
			// calling general number, called long num, called long num, called long num
			// calling extension (1), called ext num, called ext num, called ext num
			// calling name, called name (2), called name, called name
			//(1) not always available, in this case, use calling general number
			//(2) not always available
			int tokenNr = 0;
			while(tokenNr < 10 && partiesPtr < parties+partiesLen)
			{
				CStdString party;
				GrabTokenAcceptSpace(partiesPtr, parties+partiesLen, party);
				if(s_skinnyParsersLog->isDebugEnabled())
				{
					logMsg = logMsg + party + ", ";
				}
				partiesPtr += party.size() + 1;
				tokenNr += 1;

				switch(tokenNr)
				{
				case 1:
					// Token 1 can be the general office number for outbound
					// TODO, report this as local entry point
					callingParty = party;
					break;
				case 2:
					calledParty = party;
					break;
				case 3:
					if(DLLCONFIG.m_cucm7_1Mode == true)
					{
						// In CCM 7.1, it appears that each party is
						// named twice
						calledParty = party;
					}
					break;
				case 5:
					if(DLLCONFIG.m_cucm7_1Mode == false)
					{
						// Token 5 is the calling extension, use this if outbound for callingParty instead of general number
						// With CCM 7.1, this appears not to be the case
						if(party.size()>0 && ccm5CallInfo->callType == SKINNY_CALL_TYPE_OUTBOUND)
						{
							callingParty = party;
						}
					}
					break;
				case 6:
					// This is the called party extension, not used for now
					break;
				case 9:
					callingPartyName = party;
					break;
				case 10:
					calledPartyName = party;
					break;
				}
			}
			LOG4CXX_DEBUG(s_skinnyParsersLog, "parties tokens:" + logMsg);

			// Emulate a regular CCM CallInfo message
			SkCallInfoStruct callInfo;
			strcpy(callInfo.calledParty, (PCSTR)calledParty);
			strcpy(callInfo.callingParty, (PCSTR)callingParty);
			callInfo.callId = ccm5CallInfo->callId;
			callInfo.callType = ccm5CallInfo->callType;
			callInfo.lineInstance = 0;
			if(calledPartyName.size())
			{
				strncpy(callInfo.calledPartyName, (PCSTR)calledPartyName, sizeof(callInfo.calledPartyName));
			}
			else
			{
				callInfo.calledPartyName[0] = '\0';
			}
			if(callingPartyName.size())
			{
				strncpy(callInfo.callingPartyName, (PCSTR)callingPartyName, sizeof(callInfo.callingPartyName));
			}
			else
			{
				callInfo.callingPartyName[0] = '\0';
			}

			if(s_skinnyParsersLog->isInfoEnabled())
			{
				logMsg.Format(" CallId:%u calling:%s called:%s callingname:%s calledname:%s callType:%d", callInfo.callId,
								callInfo.callingParty, callInfo.calledParty, callInfo.callingPartyName, callInfo.calledPartyName, callInfo.callType);
			}
			VoIpSessionsSingleton::instance()->ReportSkinnyCallInfo(&callInfo, ipHeader, tcpHeader);
		}
		break;
	case SkOpenReceiveChannelAck:

		openReceiveAck = (SkOpenReceiveChannelAckStruct*)skinnyHeader;
		SkCcm7_1SkOpenReceiveChannelAckStruct *orca;
		orca = (SkCcm7_1SkOpenReceiveChannelAckStruct*)skinnyHeader;

		if(SkinnyValidateOpenReceiveChannelAck(openReceiveAck, packetEnd))
		{
			if(s_skinnyParsersLog->isInfoEnabled())
			{
				char szMediaIp[16];
				ACE_OS::inet_ntop(AF_INET, (void*)&openReceiveAck->endpointIpAddr, szMediaIp, sizeof(szMediaIp));
				logMsg.Format(" PassThru:%u media address:%s,%u", openReceiveAck->passThruPartyId, szMediaIp, openReceiveAck->endpointTcpPort);
			}
			endpointIp = ipHeader->ip_src;	// this skinny message is phone -> CCM
			cmIp = ipHeader->ip_dest;
			endpointTcpPort = ntohs(tcpHeader->source);
			cmTcpPort = ntohs(tcpHeader->dest);
			VoIpSessionsSingleton::instance()->ReportSkinnyOpenReceiveChannelAck(openReceiveAck, ipHeader, tcpHeader);
		}
		else if(SkinnyValidateCcm7_1SkOpenReceiveChannelAckStruct(orca, packetEnd))
		{
			openReceiveAck = &orcatmp;

			memcpy(&openReceiveAck->header, &orca->header, sizeof(openReceiveAck->header));
			openReceiveAck->openReceiveChannelStatus = orca->openReceiveChannelStatus;
			memcpy(&openReceiveAck->endpointIpAddr, &orca->endpointIpAddr, sizeof(openReceiveAck->endpointIpAddr));
			openReceiveAck->endpointTcpPort = orca->endpointTcpPort;
			openReceiveAck->passThruPartyId = orca->passThruPartyId;

			if(s_skinnyParsersLog->isInfoEnabled())
			{
				char szMediaIp[16];
				ACE_OS::inet_ntop(AF_INET, (void*)&openReceiveAck->endpointIpAddr, szMediaIp, sizeof(szMediaIp));
				logMsg.Format(" (CCM 7.1) PassThru:%u media address:%s,%u", openReceiveAck->passThruPartyId, szMediaIp, openReceiveAck->endpointTcpPort);
			}
			endpointIp = ipHeader->ip_src;	// this skinny message is phone -> CCM
			cmIp = ipHeader->ip_dest;
			endpointTcpPort = ntohs(tcpHeader->source);
			cmTcpPort = ntohs(tcpHeader->dest);
			VoIpSessionsSingleton::instance()->ReportSkinnyOpenReceiveChannelAck(openReceiveAck, ipHeader, tcpHeader);
		}

		else
		{
			useful = false;
			LOG4CXX_WARN(s_skinnyParsersLog, "Invalid OpenReceiveChannelAck.");
		}
		break;
	case SkLineStatMessage:
		lineStat = (SkLineStatStruct*)skinnyHeader;
		if(SkinnyValidateLineStat(lineStat, packetEnd))
		{
			if(s_skinnyParsersLog->isInfoEnabled())
			{
				logMsg.Format(" line:%u extension:%s display name:%s", lineStat->lineNumber, lineStat->lineDirNumber, lineStat->displayName);
			}
			endpointIp = ipHeader->ip_dest;	// this skinny message is CCM -> phone
			VoIpSessionsSingleton::instance()->ReportSkinnyLineStat(lineStat, ipHeader, tcpHeader);
		}
		else
		{
			useful = false;
			LOG4CXX_WARN(s_skinnyParsersLog, "Invalid LineStatMessage.");
		}

		break;
	case SkSoftKeyEventMessage:
		softKeyEvent = (SkSoftKeyEventMessageStruct*)skinnyHeader;
		if(SkinnyValidateSoftKeyEvent(softKeyEvent, packetEnd))
		{
			useful = true;
			logMsg.Format(" eventString:%s eventNum:%d line:%lu callId:%lu",
					SoftKeyEvent::SoftKeyEventToString(softKeyEvent->softKeyEvent),
					softKeyEvent->softKeyEvent,
					softKeyEvent->lineInstance,
					softKeyEvent->callIdentifier);

			endpointIp = ipHeader->ip_src;  // this skinny message is phone -> CCM
			cmIp = ipHeader->ip_dest;
			endpointTcpPort = ntohs(tcpHeader->source);
			cmTcpPort = ntohs(tcpHeader->dest);

			switch(softKeyEvent->softKeyEvent)
			{
			case SoftKeyEvent::SkSoftKeyHold:
				VoIpSessionsSingleton::instance()->ReportSkinnySoftKeyHold(softKeyEvent, ipHeader, tcpHeader);
				break;
			case SoftKeyEvent::SkSoftKeyResume:
				VoIpSessionsSingleton::instance()->ReportSkinnySoftKeyResume(softKeyEvent, ipHeader, tcpHeader);
				break;
			case SoftKeyEvent::SkSoftKeyConfrn:
				if (DLLCONFIG.m_SkinnyTrackConferencesTransfers == true)
				{
					VoIpSessionsSingleton::instance()->ReportSkinnySoftKeyConfPressed(endpointIp, tcpHeader);
				}
				break;
			default:
				CStdString logSoftKey;

				logSoftKey.Format("Ignoring unsupported event %s (%d)",
					SoftKeyEvent::SoftKeyEventToString(softKeyEvent->softKeyEvent),
					softKeyEvent->softKeyEvent);
				LOG4CXX_INFO(s_skinnyParsersLog, logSoftKey);
				break;
			}
		}
		else
		{
			useful = false;
			LOG4CXX_WARN(s_skinnyParsersLog, "Invalid SoftKeyEventMessage.");
		}
		break;
	case SkSoftKeySetDescription:
		softKeySetDescription = (SkSoftKeySetDescriptionStruct*)skinnyHeader;
		if(SkinnyValidateSoftKeySetDescription(softKeySetDescription, packetEnd))
		{
			useful = true;
			logMsg.Format(" eventString:%s eventNum:%d line:%lu callId:%lu",
					SoftKeySetDescription::SoftKeySetDescriptionToString(softKeySetDescription->softKeySetDescription),
					softKeySetDescription->softKeySetDescription,
					softKeySetDescription->lineInstance,
					softKeySetDescription->callIdentifier);

			endpointIp = ipHeader->ip_dest;
			switch(softKeySetDescription->softKeySetDescription)
			{
				case SoftKeySetDescription::SkSoftKeySetConference:
					if (DLLCONFIG.m_SkinnyTrackConferencesTransfers == true)
					{
						VoIpSessionsSingleton::instance()->ReportSkinnySoftKeySetConfConnected(endpointIp, tcpHeader);
					}
					break;
				case SoftKeySetDescription::SkSoftKeySetTransfer:
					VoIpSessionsSingleton::instance()->ReportSkinnySoftKeySetTransfConnected(softKeySetDescription, ipHeader, tcpHeader);
					break;
			}
		}
		else
		{
			useful = false;
			LOG4CXX_WARN(s_skinnyParsersLog, "Invalid SoftKeySetDescription.");
		}
		break;
	default:
		useful = false;
	}
	if(useful && s_skinnyParsersLog->isInfoEnabled())
	{
		CStdString msg = SkinnyMessageToString(skinnyHeader->messageType);
		ACE_OS::inet_ntop(AF_INET, (void*)&endpointIp, szEndpointIp, sizeof(szEndpointIp));
		ACE_OS::inet_ntop(AF_INET, (void*)&cmIp, szCmIp, sizeof(szCmIp));
		logMsg.Format("processed %s%s endpoint:%s,%u cm:%s,%u", msg, logMsg, szEndpointIp, endpointTcpPort, szCmIp, cmTcpPort);
		LOG4CXX_INFO(s_skinnyParsersLog, logMsg);
	}
}
예제 #20
0
bool TrySip200Ok(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd)
{
	bool result = false;

	if(DLLCONFIG.m_sipTreat200OkAsInvite == true)
	{
		return false;
	}

	int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct);
	char* sipEnd = (char*)udpPayload + sipLength;
	if(sipLength < SIP_RESPONSE_200_OK_SIZE || sipEnd > (char*)packetEnd)
	{
		;	// packet too short
	}
	else if (memcmp(SIP_RESPONSE_200_OK, (void*)udpPayload, SIP_RESPONSE_200_OK_SIZE) == 0)
	{
		result = true;

		Sip200OkInfoRef info(new Sip200OkInfo());

		char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd);
		if(!fromField)
		{
			fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd);
		}
		char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd);
		if(!toField)
		{
			toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd);
		}

		char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd);
		if(!callIdField)
		{
			callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd);
		}

		char* audioField = NULL;
		char* connectionAddressField = NULL;

		if(callIdField)
		{
			GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId);
			audioField = memFindAfter("m=audio ", callIdField, sipEnd);
			connectionAddressField = memFindAfter("c=IN IP4 ", callIdField, sipEnd);
		}
		if(audioField && connectionAddressField)
		{
			info->m_hasSdp = true;

			GrabToken(audioField, sipEnd, info->m_mediaPort);

			CStdString connectionAddress;
			GrabToken(connectionAddressField, sipEnd, connectionAddress);
			struct in_addr mediaIp;
			if(connectionAddress.size())
			{
				if(ACE_OS::inet_aton((PCSTR)connectionAddress, &mediaIp))
				{
					info->m_mediaIp = mediaIp;
				}
			}
		}

		if(fromField)
		{
			if(s_sipExtractionLog->isDebugEnabled())
			{
				CStdString from;
				GrabLine(fromField, sipEnd, from);
				LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from);
			}

			char* fromFieldEnd = memFindEOL(fromField, sipEnd);

			char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, fromFieldEnd, info->m_from);
				}
				else
				{
					GrabSipUriUser(sipUser, fromFieldEnd, info->m_from);
				}
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(fromField, fromFieldEnd, info->m_from);
				}
				else
				{
					GrabSipUriUser(fromField, fromFieldEnd, info->m_from);
				}
			}
		}
		if(toField)
		{
			CStdString to;
			char* toFieldEnd = GrabLine(toField, sipEnd, to);
			LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to);

			char* sipUser = memFindAfter("sip:", toField, toFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, toFieldEnd, info->m_to);
				}
				else
				{
					GrabSipUriUser(sipUser, toFieldEnd, info->m_to);
				}
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(toField, toFieldEnd, info->m_to);
				}
				else
				{
					GrabSipUriUser(toField, toFieldEnd, info->m_to);
				}
			}
		}
		info->m_senderIp = ipHeader->ip_src;
		info->m_receiverIp = ipHeader->ip_dest;

		CStdString logMsg;

		info->ToString(logMsg);
		logMsg = "200 OK: " + logMsg;
		if(info->m_hasSdp)
		{
			LOG4CXX_INFO(s_sipPacketLog, logMsg);
		}
		else
		{
			LOG4CXX_DEBUG(s_sipPacketLog, logMsg);
		}

		VoIpSessionsSingleton::instance()->ReportSip200Ok(info);
	}
	return result;
}
예제 #21
0
bool TrySip302MovedTemporarily(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader, UdpHeaderStruct* udpHeader, u_char* udpPayload, u_char* packetEnd)
{
	bool result = false;
	bool drop = false;

	if(DLLCONFIG.m_sip302MovedTemporarilySupport == false)
	{
		return false;
	}

	int sipLength = ntohs(udpHeader->len) - sizeof(UdpHeaderStruct);
	char* sipEnd = (char*)udpPayload + sipLength;
	CStdString sipMethod = "302 Moved Temporarily";

	if(sipLength < SIP_RESPONSE_302_MOVED_TEMPORARILY_SIZE || sipEnd > (char*)packetEnd)
	{
		drop = true;	// packet too short
	}
	else if(memcmp(SIP_RESPONSE_302_MOVED_TEMPORARILY, (void*)udpPayload, SIP_RESPONSE_302_MOVED_TEMPORARILY_SIZE) != 0)
	{
		drop = true;
	}

	if(drop == false)
	{
		result = true;

		Sip302MovedTemporarilyInfoRef info(new Sip302MovedTemporarilyInfo());

		char* fromField = memFindAfter("From:", (char*)udpPayload, sipEnd);
		if(!fromField)
		{
			fromField = memFindAfter("\nf:", (char*)udpPayload, sipEnd);
		}
		char* toField = memFindAfter("To:", (char*)udpPayload, sipEnd);
		if(!toField)
		{
			toField = memFindAfter("\nt:", (char*)udpPayload, sipEnd);
		}
		char* callIdField = memFindAfter("Call-ID:", (char*)udpPayload, sipEnd);
		if(!callIdField)
		{
			callIdField = memFindAfter("\ni:", (char*)udpPayload, sipEnd);
		}
		char* contactField = memFindAfter("Contact:", (char*)udpPayload, sipEnd);
		if(!contactField)
		{
			contactField = memFindAfter("\nc:", (char*)udpPayload, sipEnd);
		}

		if(fromField)
		{
			if(s_sipExtractionLog->isDebugEnabled())
			{
				CStdString from;
				GrabLine(fromField, sipEnd, from);
				LOG4CXX_DEBUG(s_sipExtractionLog, "from: " + from);
			}

			char* fromFieldEnd = memFindEOL(fromField, sipEnd);

			GrabSipName(fromField, fromFieldEnd, info->m_fromName);

			char* sipUser = memFindAfter("sip:", fromField, fromFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, fromFieldEnd, info->m_from);
				}
				else
				{
					GrabSipUriUser(sipUser, fromFieldEnd, info->m_from);
				}
				GrabSipUriDomain(sipUser, fromFieldEnd, info->m_fromDomain);
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(fromField, fromFieldEnd, info->m_from);
				}
				else
				{
					GrabSipUriUser(fromField, fromFieldEnd, info->m_from);
				}
				GrabSipUriDomain(fromField, fromFieldEnd, info->m_fromDomain);
			}
		}
		if(toField)
		{
			CStdString to;
			char* toFieldEnd = GrabLine(toField, sipEnd, to);
			LOG4CXX_DEBUG(s_sipExtractionLog, "to: " + to);

			GrabSipName(toField, toFieldEnd, info->m_toName);

			char* sipUser = memFindAfter("sip:", toField, toFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, toFieldEnd, info->m_to);
				}
				else
				{
					GrabSipUriUser(sipUser, toFieldEnd, info->m_to);
				}
				GrabSipUriDomain(sipUser, toFieldEnd, info->m_toDomain);
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(toField, toFieldEnd, info->m_to);
				}
				else
				{
					GrabSipUriUser(toField, toFieldEnd, info->m_to);
				}
				GrabSipUriDomain(toField, toFieldEnd, info->m_toDomain);
			}
		}
		if(contactField)
		{
			CStdString contact;
			char* contactFieldEnd = GrabLine(contactField, sipEnd, contact);
			LOG4CXX_DEBUG(s_sipExtractionLog, "contact: " + contact);

			GrabSipName(contactField, contactFieldEnd, info->m_contactName);

			char* sipUser = memFindAfter("sip:", contactField, contactFieldEnd);
			if(sipUser)
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(sipUser, contactFieldEnd, info->m_contact);
				}
				else
				{
					GrabSipUriUser(sipUser, contactFieldEnd, info->m_contact);
				}
				GrabSipUriDomain(sipUser, contactFieldEnd, info->m_contactDomain);
			}
			else
			{
				if(DLLCONFIG.m_sipReportFullAddress)
				{
					GrabSipUserAddress(contactField, contactFieldEnd, info->m_contact);
				}
				else
				{
					GrabSipUriUser(contactField, contactFieldEnd, info->m_contact);
				}
				GrabSipUriDomain(contactField, contactFieldEnd, info->m_contactDomain);
			}

		}
		if(callIdField)
		{
			GrabTokenSkipLeadingWhitespaces(callIdField, sipEnd, info->m_callId);
		}

		info->m_senderIp = ipHeader->ip_src;
		info->m_receiverIp = ipHeader->ip_dest;

		if(!info->m_callId.size())
		{
			drop = true;
		}
		if(!info->m_contact)
		{
			drop = true;
		}

		CStdString logMsg;
		info->ToString(logMsg);
		logMsg = sipMethod + ": " + logMsg;
		LOG4CXX_INFO(s_sipPacketLog, logMsg);

		if(drop == false)
		{
			VoIpSessionsSingleton::instance()->ReportSip302MovedTemporarily(info);
		}
		else
		{
			CStdString packetInfo;

			info->ToString(packetInfo);
			logMsg.Format("Dropped this %s: %s", sipMethod, packetInfo);
			LOG4CXX_INFO(s_sipPacketLog, logMsg);
		}
	}

	return result;
}
예제 #22
0
/// Compute the contribution at an integration point to the stiffness matrix of the HDiv formulation
void TPZMatPoisson3d::ContributeHDiv(TPZMaterialData &data,REAL weight,TPZFMatrix<STATE> &ek,TPZFMatrix<STATE> &ef)
{
	/** monta a matriz
	 |A B^T |  = |0 |
	 |B 0   |    |f |
	 
	 **/
    
    //TPZVec<REAL>  &x = data.x;
	STATE fXfLoc = fXf;
	if(fForcingFunction) {                           // phi(in, 0) = phi_in
		TPZManVector<STATE> res(1);
		fForcingFunction->Execute(data.x,res);       // dphi(i,j) = dphi_j/dxi
		fXfLoc = res[0];
	}
	int numvec = data.fVecShapeIndex.NElements();
	int numdual = data.numberdualfunctions;
	int numprimalshape = data.phi.Rows()-numdual;
	
	int i,j;
    REAL kreal = 0.;
#ifdef STATE_COMPLEX
    kreal = fK.real();
#else
    kreal = fK;
#endif
    REAL ratiok = 1./kreal;
	for(i=0; i<numvec; i++)
	{
		int ivecind = data.fVecShapeIndex[i].first;
		int ishapeind = data.fVecShapeIndex[i].second;
		for (j=0; j<numvec; j++) {
			int jvecind = data.fVecShapeIndex[j].first;
			int jshapeind = data.fVecShapeIndex[j].second;
			REAL prod = data.fNormalVec(0,ivecind)*data.fNormalVec(0,jvecind)+
			data.fNormalVec(1,ivecind)*data.fNormalVec(1,jvecind)+
			data.fNormalVec(2,ivecind)*data.fNormalVec(2,jvecind);//faz o produto escalar entre u e v--> Matriz A
			ek(i,j) += weight*ratiok*data.phi(ishapeind,0)*data.phi(jshapeind,0)*prod;
			
			
			
		}
		TPZFNMatrix<3> ivec(3,1);
		ivec(0,0) = data.fNormalVec(0,ivecind);
		ivec(1,0) = data.fNormalVec(1,ivecind);
		ivec(2,0) = data.fNormalVec(2,ivecind);
		TPZFNMatrix<3> axesvec(3,1);
		data.axes.Multiply(ivec,axesvec);
		int iloc;
		REAL divwq = 0.;
		for(iloc=0; iloc<fDim; iloc++)
		{
			divwq += axesvec(iloc,0)*data.dphix(iloc,ishapeind);
		}
		for (j=0; j<numdual; j++) {
			REAL fact = (-1.)*weight*data.phi(numprimalshape+j,0)*divwq;//calcula o termo da matriz B^T  e B
			ek(i,numvec+j) += fact;
			ek(numvec+j,i) += fact;//-div
		}
	}
	for(i=0; i<numdual; i++)
	{
		ef(numvec+i,0) += (STATE)((-1.)*weight*data.phi(numprimalshape+i,0))*fXfLoc;//calcula o termo da matriz f
        
#ifdef LOG4CXX
        if (logger->isDebugEnabled()) 
		{
            std::stringstream sout;
            sout<< "Verificando termo fonte\n";
            sout << "  pto  " <<data.x << std::endl;
            sout<< " fpto " <<fXfLoc <<std::endl;
            LOGPZ_DEBUG(logger,sout.str())
		}
#endif
	}
예제 #23
0
//.........................................................................................................................................
void TPZRefPatternDataBase::InitializeUniformRefPattern(MElementType elType)
{
	switch (elType)
	{
		case 0://EPoint
		{
			break;
		}
		case 1://EOned
		{
			std::cout << "\n\tinserting uniform refpattern: line\n";
			char buf[] =
			"3     3  "
			"-50       UnifLin	"
			"-1.     0.     0. "
			" 1.     0.     0. "
			" 0.     0.     0. "
			" 1     2     0     1 "
			" 1     2     0     2 "
			" 1     2     2     1 ";
			std::istringstream str(buf);
			TPZAutoPointer<TPZRefPattern> refpat = new TPZRefPattern(str);
			TPZAutoPointer<TPZRefPattern> refpatFound = FindRefPattern(refpat);
			if(!refpatFound)
			{
				InsertRefPattern(refpat);
			}
			else
			{
				refpatFound->SetName(refpat->Name());
			}
			refpat->InsertPermuted();
			
			break;
		}
		case 2://ETriangle
		{
			std::cout << "\n\tinserting uniform refpattern: triangle\n";
			char buf[] =
			"6     5  "
			"-50       UnifTri	"
			"0.     0.     0. "
			"1.     0.     0. "
			"0.     1.     0. "
			"0.5    0.     0. "
			"0.5    0.5    0. "
			"0.     0.5     0. "
			"2     3     0     1     2 "
			"2     3     0     3     5 "
			"2     3     3     1     4 "
			"2     3     5     4     2 "
			"2     3     4     5     3 ";
			std::istringstream str(buf);
			TPZAutoPointer<TPZRefPattern> refpat = new TPZRefPattern(str);
			TPZAutoPointer<TPZRefPattern> refpatFound = FindRefPattern(refpat);
			if(!refpatFound)
			{
				InsertRefPattern(refpat);
			}
			else
			{
				refpatFound->SetName(refpat->Name());
			}
			refpat->InsertPermuted();
			
			break;
		}
		case 3://EQuadrilateral
		{
			std::cout << "\n\tinserting uniform refpattern: quadrilateral\n";
			char buf[] =
			"9     5  "
			"-50       UnifQua	"
			"-1.    -1.     0. "
			" 1.    -1.     0. "
			" 1.     1.     0. "
			"-1.     1.     0.	"
			" 0.    -1.     0. "
			" 1.     0.     0. "
			" 0.     1.     0. "
			"-1.     0.     0. "
			" 0.     0.     0. "
			" 3     4     0     1     2     3 "
			" 3     4     0     4     8     7 "
			" 3     4     4     1     5     8 "
			" 3     4     8     5     2     6 "
			" 3     4     7     8     6     3 ";
			std::istringstream str(buf);
			TPZAutoPointer<TPZRefPattern> refpat = new TPZRefPattern(str);
			TPZAutoPointer<TPZRefPattern> refpatFound = FindRefPattern(refpat);
			if(!refpatFound)
			{
				InsertRefPattern(refpat);
			}
			else
			{
				refpatFound->SetName(refpat->Name());
			}
			refpat->InsertPermuted();
#ifdef LOG4CXX
            if (logger->isDebugEnabled()) {
                std::stringstream sout;
                refpat->PrintMore(sout);
                LOGPZ_DEBUG(logger, sout.str())
            }
#endif
			
			break;
		}
		case 4://ETetraedro
		{
			std::cout << "\n\tinserting uniform refpattern: tetrahedra\n";
			char buf[] =
			"10     7"
			"-50       UnifTet	"
			"0.     0.     0. "
			"1.     0.     0. "
			"0.     1.     0. "
			"0.     0.     1. "
			"0.5    0.     0. "
			"0.5    0.5    0. "
			"0.     0.5    0. "
			"0.     0.     0.5 "
			"0.5    0.     0.5 "
			"0.     0.5    0.5 "
			"4     4     0     1     2     3 "
			"4     4     0     4     6     7 "
			"4     4     4     1     5     8 "
			"4     4     6     5     2     9 "
			"4     4     7     8     9     3 "
			"5     5     4     8     9     6     7 "
			"5     5     8     4     6     9     5 ";
			std::istringstream str(buf);
			TPZAutoPointer<TPZRefPattern> refpat = new TPZRefPattern(str);
			TPZAutoPointer<TPZRefPattern> refpatFound = FindRefPattern(refpat);
			if(!refpatFound)
			{
				InsertRefPattern(refpat);
			}
			else
			{
				refpatFound->SetName(refpat->Name());
			}
			refpat->InsertPermuted();
			
			break;
		}
		case 5://EPiramide
		{
			std::cout << "\n\tinserting uniform refpattern: pyramid\n";
			char buf[] =
			"14     11	"
			"-50       UnifPyr	"
			"-1.    -1.     0. "
			" 1.    -1.     0. "
			" 1.     1.     0. "
			"-1.     1.     0. "
			" 0.     0.     1. "
			" 0.    -1.     0. "
			" 1.     0.     0. "
			" 0.     1.     0. "
			"-1.     0.     0. "
			"-0.5   -0.5    0.5 "
			" 0.5   -0.5    0.5 "
			" 0.5    0.5    0.5 "
			"-0.5    0.5    0.5 "
			" 0.     0.     0. "
			" 5     5     0     1     2     3     4 "
			" 5     5     0     5    13     8     9	"
			" 5     5     5     1     6    13    10	"
			" 5     5    13     6     2     7    11	"
			" 5     5     8    13     7     3    12	"
			" 5     5     9    10    11    12     4	"
			" 5     5     9    12    11    10    13	"
			" 4     4     9     5    13    10	"
			" 4     4    10     6    13    11	"
			" 4     4    11     7    12    13	"
			" 4     4     8    13    12     9	";
			std::istringstream str(buf);
			TPZAutoPointer<TPZRefPattern> refpat = new TPZRefPattern(str);
			TPZAutoPointer<TPZRefPattern> refpatFound = FindRefPattern(refpat);
			if(!refpatFound)
			{
				InsertRefPattern(refpat);
			}
			else
			{
				refpatFound->SetName(refpat->Name());
			}
			refpat->InsertPermuted();
			
			break;
		}
		case 6://EPrisma
		{
			std::cout << "\n\tinserting uniform refpattern: prism\n";
			char buf[] =
			"18     9  "
			"-50       UnifPri 	"
			" 0.     0.    -1.	"
			" 1.     0.    -1.	"
			" 0.     1.    -1.	"
			" 0.     0.     1.	"
			" 1.     0.     1.	"
			" 0.     1.     1.	"
			" 0.5    0.    -1.	"
			" 0.5    0.5   -1.	"
			" 0.     0.5   -1.	"
			" 0.     0.     0.	"
			" 1.     0.     0.	"
			" 0.     1.     0.	"
			" 0.5    0.     1.	"
			" 0.5    0.5    1.	"
			" 0.     0.5    1.	"
			" 0.5    0.     0.	"
			" 0.5    0.5    0.	"
			" 0.     0.5    0.	"
			" 6     6     0     1     2     3     4     5	"
			" 6     6     0     6     8     9    15    17	"
			" 6     6     6     1     7    15    10    16	"
			" 6     6     8     7     2    17    16    11	"
			" 6     6    17    16    15     8     7     6	"
			" 6     6     9    15    17     3    12    14	"
			" 6     6    15    10    16    12     4    13	"
			" 6     6    17    16    11    14    13     5	"
			" 6     6    14    13    12    17    16    15	";
			std::istringstream str(buf);
			TPZAutoPointer<TPZRefPattern> refpat = new TPZRefPattern(str);
			TPZAutoPointer<TPZRefPattern> refpatFound = FindRefPattern(refpat);
			if(!refpatFound)
			{
				InsertRefPattern(refpat);
			}
			else
			{
				refpatFound->SetName(refpat->Name());
			}
			refpat->InsertPermuted();
			
			break;
		}
		case 7://ECube
		{
			std::cout << "\n\tinserting uniform refpattern: hexahedre\n";
			char buf[] =
			"27     9  "
			"-50     UnifHex  "
			"-1.    -1.    -1.  "
			" 1.    -1.    -1.  "
			" 1.     1.    -1.  "
			"-1.     1.    -1.  "
			"-1.    -1.     1.  "
			" 1.    -1.     1.  "
			" 1.     1.     1.  "
			"-1.     1.     1.  "
			" 0.    -1.    -1.  "
			" 1.     0.    -1.  "
			" 0.     1.    -1.  "
			"-1.     0.    -1.  "
			"-1.    -1.     0.  "
			" 1.    -1.     0.  "
			" 1.     1.     0.  "
			"-1.     1.     0.  "
			" 0.    -1.     1.  "
			" 1.     0.     1.  "
			" 0.     1.     1.  "
			"-1.     0.     1.  "
			" 0.     0.    -1.  "
			" 0.    -1.     0.  "
			" 1.     0.     0.  "
			" 0.     1.     0.  "
			"-1.     0.     0.  "
			" 0.     0.     1.  "
			" 0.     0.     0.  "
			"7     8     0     1     2     3     4     5     6     7  "
			"7     8     0     8    20    11    12    21    26    24  "
			"7     8     8     1     9    20    21    13    22    26  "
			"7     8    20     9     2    10    26    22    14    23  "
			"7     8    11    20    10     3    24    26    23    15  "
			"7     8    12    21    26    24     4    16    25    19  "
			"7     8    21    13    22    26    16     5    17    25  "
			"7     8    26    22    14    23    25    17     6    18  "
			"7     8    24    26    23    15    19    25    18     7  ";
			std::istringstream str(buf);
			TPZAutoPointer<TPZRefPattern> refpat = new TPZRefPattern(str);
			TPZAutoPointer<TPZRefPattern> refpatFound = FindRefPattern(refpat);
			if(!refpatFound)
			{
				InsertRefPattern(refpat);
			}
			else
			{
				refpatFound->SetName(refpat->Name());
			}
			refpat->InsertPermuted();
			
			break;
		}
		default:
		{
			cout << "Cant generate uniform refpattern because MElementType was not found on " << __PRETTY_FUNCTION__ << endl;
			DebugStop();
		}
	}
예제 #24
0
파일: LinearWave.cpp 프로젝트: labmec/neopz
void SolveSystemTransient(REAL deltaT,REAL maxTime, TPZAnalysis *NonLinearAn, TPZCompMesh* CMesh)
{
    
    TPZFMatrix<STATE> Patn;
    TPZFMatrix<STATE> PatnMinusOne;    
//  {
//      TPZBFileStream load;
//      load.OpenRead("MultiphaseSaturationSol.bin");
//      SolutiontoLoad.Read(load,0);
//      meshvec[2]->LoadSolution(SolutiontoLoad);
//      TPZBuildMultiphysicsMesh::TransferFromMeshes(meshvec, mphysics);        
//  }

  
    std::string OutPutFile = "WaveSolution";
    TPZMaterial *mat1 = CMesh->FindMaterial(1);    
    
    TPZLinearWave * material1 = dynamic_cast<TPZLinearWave *>(mat1);  
    //    TPZMultiphase * material2 = dynamic_cast<TPZMultiphase *>(mat2);      
    material1->SetTimeStep(deltaT);
    
    //  Starting Newton Iterations
    TPZFMatrix<STATE> DeltaX = CMesh->Solution();
    TPZFMatrix<STATE> Uatn = CMesh->Solution();
    TPZFMatrix<STATE> Uatk = CMesh->Solution();      
    
    
    REAL TimeValue = 0.0;
    REAL Tolerance = 1.0e-7;
    int cent = 0;
    int MaxIterations = 50;
    TimeValue = cent*deltaT;
    REAL NormValue =1.0;
    bool StopCriteria = false;
    TPZFMatrix<STATE> RhsAtnMinusOne, RhsAtn, RhsAtnPlusOne, Residual;

    
    std::string outputfile;
    outputfile = OutPutFile;
    std::stringstream outputfiletemp;
    outputfiletemp << outputfile << ".vtk";
    std::string plotfile = outputfiletemp.str();
    PosProcess(material1->Dimension(),*NonLinearAn,outputfile,2);      

    std::cout << " Starting the time computations. " << std::endl;  
    while (TimeValue < maxTime)
    {
        
        material1->SetMinusOneState();
        CMesh->LoadSolution(PatnMinusOne);
        NonLinearAn->AssembleResidual();
        RhsAtnMinusOne = NonLinearAn->Rhs();

        material1->SetNState();
        CMesh->LoadSolution(Patn);        
        NonLinearAn->AssembleResidual();
        RhsAtn = NonLinearAn->Rhs();        
        
        material1->SetPlusOneState();
        CMesh->LoadSolution(Patn);        
        NonLinearAn->Assemble();
        RhsAtnPlusOne = NonLinearAn->Rhs();
        
        Residual= RhsAtnMinusOne + RhsAtn + RhsAtnPlusOne;       
        NormValue = Norm(Residual);
        


        
        int iterations= 0;      
        while (NormValue > Tolerance)
        {       
            
            Residual*=-1.0;
            NonLinearAn->Rhs()=Residual;
            NonLinearAn->Solve();           
            DeltaX = NonLinearAn->Solution();
            Uatk = (Uatn + DeltaX);
            
            
            CMesh->LoadSolution(Uatn + DeltaX);          
            
#ifdef LOG4CXX
            if(logdata->isDebugEnabled())
            {
                std::stringstream sout;
                sout.precision(20);
                Residual.Print(sout);
                Uatk.Print(sout);       
                LOGPZ_DEBUG(logdata,sout.str());
            }
#endif          


            material1->SetPlusOneState();
            NonLinearAn->Assemble();
            RhsAtnPlusOne = NonLinearAn->Rhs();
            Residual= RhsAtnMinusOne + RhsAtn + RhsAtnPlusOne;
            NormValue = Norm(Residual); 
                
            
#ifdef LOG4CXX
            if(logdata->isDebugEnabled())
            {
                std::stringstream sout;
                sout.precision(15);             
                Uatk.Print(sout);
                Residual.Print("Res = ",sout,EMathematicaInput);
                LOGPZ_DEBUG(logdata,sout.str());
            }
#endif      

            
        
            
            iterations++;
            std::cout << " Newton's Iteration = : " << iterations  << "     L2 norm = : " << NormValue <<  std::endl;
            if (iterations == MaxIterations) 
            {
                StopCriteria = true;
                std::cout << " Time Step number = : " << iterations  << "\n Exceed max iterations numbers = : " << MaxIterations <<  std::endl;                 
                break;
            }

                
            Uatn = Uatk;
            
        }   

        outputfile = OutPutFile;
        std::stringstream outputfiletemp;
        outputfiletemp << outputfile << ".vtk";
        std::string plotfile = outputfiletemp.str();
        PosProcess(material1->Dimension(),*NonLinearAn,outputfile,2);      
        
        if (StopCriteria) {
            std::cout << " Newton's Iteration = : " << iterations  << "     L2 norm = : " << NormValue <<  std::endl;       
            break;
        }
        
        cent++;
        TimeValue = cent*deltaT;
        
        std::cout << " Time Step :  " << cent  << "  Time :  " << TimeValue <<  std::endl; 
        
        PatnMinusOne = Patn;
        Patn = Uatk;
        
    }
   
}