<commit_before>#include <MicroManager.h>
#include <Regions.h>
#include <util.h>
#include <UnitsGroup.h>
#include "DefendChokeGoal.h"
#include "BorderManager.h"

using std::map;
using std::set;
using std::vector;
using std::list;
using namespace BWAPI;
using namespace BWTA;

MicroManager::MicroManager()
: BaseObject("MicroManager")
{
	this->defgroup = new UnitsGroup();

	this->arbitrator = NULL;
	this->regions = NULL;
}

MicroManager::~MicroManager()
{
	//Broodwar->printf("INOUT MicroManager::~MicroManager()");
}

void MicroManager::setDependencies(Arbitrator::Arbitrator<BWAPI::Unit*,double>* arb, Regions * reg){
	this->arbitrator = arb;
	this->regions = reg;

}

void MicroManager::onStart(){
	this->sendGroupToDefense(defgroup);

}
void MicroManager::update()
{
	//Suppress the list prompted to suppress
	for each (UnitsGroup * ug in this->promptedRemove){
		this->remove(ug);
		ug->idle();	//Set target of units to their position so that they are now idling
		ug->~UnitsGroup();
	}
	promptedRemove.clear();

	//Set bid on appropriate units (not workers and not building)
	std::set<BWAPI::Unit *> myUnits = BWAPI::Broodwar->self()->getUnits();

	for(std::set<BWAPI::Unit *>::iterator it = myUnits.begin(); it != myUnits.end(); ++it){
		if( !(*it)->getType().isBuilding() && !(*it)->getType().isWorker() ){
			this->arbitrator->setBid(this,(*it),40);
		}
	}

	checkDefense();

	//Update unitsgroup
	defgroup->update();
	if (unitsgroups.empty()) return;
	UnitsGroup* ug;
	for (std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it++)
	{
		 ug = *it;
		 ug->update();
	}

    sout << "LOL" << sendl;
    serr << "LOL" << sendl;
}

void MicroManager::onOffer(std::set<BWAPI::Unit*> units)
{

	for(std::set<BWAPI::Unit*>::iterator u = units.begin(); u != units.end(); u++)
	{
		if (!(*u)->getType().isWorker() && !(*u)->getType().isBuilding())
		{
			arbitrator->accept(this, *u);

			defgroup->takeControl(*u);
			//Broodwar->printf("New %s added to the micro manager", (*u)->getType().getName().c_str());
		}
		else
		{
			arbitrator->decline(this, *u, 0);
		}
	}
}

void MicroManager::onRevoke(BWAPI::Unit* unit, double bid)
{
	this->onUnitDestroy(unit);
}

std::string MicroManager::getName() const
{
	return "Micro Manager";
}

void MicroManager::onUnitCreate(BWAPI::Unit* unit)
{
	/*
	if (!unit->getType().isWorker() && unit->getPlayer()==Broodwar->self() && !unit->getType().isBuilding() && unit->getType().canAttack())
		arbitrator->setBid(this, unit, 100);
	*/
}

void MicroManager::onUnitDestroy(BWAPI::Unit* unit)
{
	for (std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end();)
	{
		(*it)->giveUpControl(unit);
		if( (*it)->emptyUnits())
		{
			UnitsGroup* ug = *it;
			it = unitsgroups.erase( it);
			delete ug;
		}
		else
			it++;
	}
}

void MicroManager::display()
{
	for( std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it++)
		(*it)->display();
}

void MicroManager::sendGroupToAttack( UnitsGroup* ug)
{
	// Get the nearest enemy position
	bool found = false;
	double minDist = 0xFFFF;
	Position nearestEnemyLocation;
	Unit* enemyUnit;
	for (map<Region*, RegionData>::const_iterator itRegions = regions->regionsData.begin(); itRegions != regions->regionsData.end(); itRegions++)
	{
		for (map<Player*, vector<RegionsUnitData> >::const_iterator itBuildings = itRegions->second.buildings.begin(); itBuildings != itRegions->second.buildings.end(); itBuildings++)
		{
			if (itBuildings->first->isEnemy(Broodwar->self()))
			{
				for (vector<RegionsUnitData>::const_iterator itBD = itBuildings->second.begin(); itBD != itBuildings->second.end(); ++itBD)
				{
					double distance = getGroundDistance( ug->getCenter(), itBD->position);
					if( distance < minDist)
					{
						minDist = distance;
						nearestEnemyLocation = itBD->position;
						enemyUnit = itBD->unit;
						found = true;
					}
				}
			}
		}
	}

	if (!found) return;
	//	ug->addGoal(pGoal(new AttackGoal(nearestEnemyLocation)));
	//Broodwar->printf( "Let's fight !!");
}

void MicroManager::sendGroupToDefense( UnitsGroup* ug)
{
	/*
	// Go to the nearest choke point.
	BaseLocation* startLoc = BWTA::getStartLocation(BWAPI::Broodwar->self());

	BWAPI::Position chokePoint;
	const std::set<Region*>& region = getRegions();
	const std::set<Chokepoint*>& chocke = getChokepoints();
	for( std::set<Region*>::const_iterator itRegion = region.begin(); itRegion != region.end(); itRegion++)
	{
		if( (*itRegion)->getPolygon().isInside(startLoc->getPosition()))
		{
			for( std::set<Chokepoint*>::const_iterator itChocke = chocke.begin(); itChocke != chocke.end(); itChocke++)
			{
				const std::pair<Region*,Region*>& border = (*itChocke)->getRegions();
				if( border.first == *itRegion || border.second == *itRegion )
				{
					chokePoint = (*itChocke)->getCenter();
				}
			}
		}
	}*/

	// Send the group defend the base
	pGoal g = pGoal(new DefendChokeGoal(ug,(*BorderManager::Instance().getMyBorder().begin())));
	ug->addGoal(g);
}

void MicroManager::checkDefense(){
	//Run through all our bases. Set defense in the main OR in the natural expo, and some defenses in all bases

}

bool MicroManager::remove(UnitsGroup* u){
	for(std::list<UnitsGroup *>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it ++){
		if( (*it) == u){
			unitsgroups.erase(it);
			return true;
		}
	}
	return false;
}

void MicroManager::promptRemove(UnitsGroup* ug){
	this->promptedRemove.push_back(ug);
}

std::set<Unit*> MicroManager::getEnemies()
{
    std::set<BWAPI::Player*>::iterator iter = Broodwar->getPlayers().begin();
    for(;iter != Broodwar->getPlayers().end() && !(*iter)->isEnemy(Broodwar->self());iter++);
    return (*iter)->getUnits();
}

#ifdef BW_QT_DEBUG
QWidget* MicroManager::createWidget(QWidget* parent) const
{
	return new QLabel(QString("createWidget and refreshWidget undefined for this component."), parent);
}

void MicroManager::refreshWidget(QWidget* widget) const
{
// TODO update your widget after having defined it in the previous method :)
}
#endif
<commit_msg>testing<commit_after>#include <MicroManager.h>
#include <Regions.h>
#include <util.h>
#include <UnitsGroup.h>
#include "DefendChokeGoal.h"
#include "BorderManager.h"

using std::map;
using std::set;
using std::vector;
using std::list;
using namespace BWAPI;
using namespace BWTA;

MicroManager::MicroManager()
: BaseObject("MicroManager")
{
	this->defgroup = new UnitsGroup();

	this->arbitrator = NULL;
	this->regions = NULL;
}

MicroManager::~MicroManager()
{
	//Broodwar->printf("INOUT MicroManager::~MicroManager()");
}

void MicroManager::setDependencies(Arbitrator::Arbitrator<BWAPI::Unit*,double>* arb, Regions * reg){
	this->arbitrator = arb;
	this->regions = reg;

}

void MicroManager::onStart(){
	this->sendGroupToDefense(defgroup);

}
void MicroManager::update()
{
	//Suppress the list prompted to suppress
	for each (UnitsGroup * ug in this->promptedRemove){
		this->remove(ug);
		ug->idle();	//Set target of units to their position so that they are now idling
		ug->~UnitsGroup();
	}
	promptedRemove.clear();

	//Set bid on appropriate units (not workers and not building)
	std::set<BWAPI::Unit *> myUnits = BWAPI::Broodwar->self()->getUnits();

	for(std::set<BWAPI::Unit *>::iterator it = myUnits.begin(); it != myUnits.end(); ++it){
		if( !(*it)->getType().isBuilding() && !(*it)->getType().isWorker() ){
			this->arbitrator->setBid(this,(*it),40);
		}
	}

	checkDefense();

	//Update unitsgroup
	defgroup->update();
	if (unitsgroups.empty()) return;
	UnitsGroup* ug;
	for (std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it++)
	{
		 ug = *it;
		 ug->update();
	}

    sout << "LOL" << sendl;
    serr << "LOL" << sendl;
}

void MicroManager::onOffer(std::set<BWAPI::Unit*> units)
{

	for(std::set<BWAPI::Unit*>::iterator u = units.begin(); u != units.end(); u++)
	{
		if (!(*u)->getType().isWorker() && !(*u)->getType().isBuilding())
		{
			arbitrator->accept(this, *u);

			defgroup->takeControl(*u);
			//Broodwar->printf("New %s added to the micro manager", (*u)->getType().getName().c_str());
		}
		else
		{
			arbitrator->decline(this, *u, 0);
		}
	}
}

void MicroManager::onRevoke(BWAPI::Unit* unit, double bid)
{
	this->onUnitDestroy(unit);
}

std::string MicroManager::getName() const
{
	return "Micro Manager";
}

void MicroManager::onUnitCreate(BWAPI::Unit* unit)
{
	/*
	if (!unit->getType().isWorker() && unit->getPlayer()==Broodwar->self() && !unit->getType().isBuilding() && unit->getType().canAttack())
		arbitrator->setBid(this, unit, 100);
	*/
}

void MicroManager::onUnitDestroy(BWAPI::Unit* unit)
{
	for (std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end();)
	{
		(*it)->giveUpControl(unit);
		if( (*it)->emptyUnits())
		{
			UnitsGroup* ug = *it;
			it = unitsgroups.erase( it);
			delete ug;
		}
		else
			it++;
	}
}

void MicroManager::display()
{
	for( std::list<UnitsGroup*>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it++)
		(*it)->display();
}

void MicroManager::sendGroupToAttack( UnitsGroup* ug)
{
	// Get the nearest enemy position
	bool found = false;
	double minDist = 0xFFFF;
	Position nearestEnemyLocation;
	Unit* enemyUnit;
	for (map<Region*, RegionData>::const_iterator itRegions = regions->regionsData.begin(); itRegions != regions->regionsData.end(); itRegions++)
	{
		for (map<Player*, vector<RegionsUnitData> >::const_iterator itBuildings = itRegions->second.buildings.begin(); itBuildings != itRegions->second.buildings.end(); itBuildings++)
		{
			if (itBuildings->first->isEnemy(Broodwar->self()))
			{
				for (vector<RegionsUnitData>::const_iterator itBD = itBuildings->second.begin(); itBD != itBuildings->second.end(); ++itBD)
				{
					double distance = getGroundDistance( ug->getCenter(), itBD->position);
					if( distance < minDist)
					{
						minDist = distance;
						nearestEnemyLocation = itBD->position;
						enemyUnit = itBD->unit;
						found = true;
					}
				}
			}
		}
	}

	if (!found) return;
	//	ug->addGoal(pGoal(new AttackGoal(nearestEnemyLocation)));
	//Broodwar->printf( "Let's fight !!");
}

void MicroManager::sendGroupToDefense( UnitsGroup* ug)
{
	/*
	// Go to the nearest choke point.
	BaseLocation* startLoc = BWTA::getStartLocation(BWAPI::Broodwar->self());

	BWAPI::Position chokePoint;
	const std::set<Region*>& region = getRegions();
	const std::set<Chokepoint*>& chocke = getChokepoints();
	for( std::set<Region*>::const_iterator itRegion = region.begin(); itRegion != region.end(); itRegion++)
	{
		if( (*itRegion)->getPolygon().isInside(startLoc->getPosition()))
		{
			for( std::set<Chokepoint*>::const_iterator itChocke = chocke.begin(); itChocke != chocke.end(); itChocke++)
			{
				const std::pair<Region*,Region*>& border = (*itChocke)->getRegions();
				if( border.first == *itRegion || border.second == *itRegion )
				{
					chokePoint = (*itChocke)->getCenter();
				}
			}
		}
	}*/

	// Send the group defend the base
	pGoal g = pGoal(new DefendChokeGoal(ug,(*BorderManager::Instance().getMyBorder().begin())));
	ug->addGoal(g);
}

void MicroManager::checkDefense(){
	//Run through all our bases. Set defense in the main OR in the natural expo, and some defenses in all bases

}

bool MicroManager::remove(UnitsGroup* u){
	for(std::list<UnitsGroup *>::iterator it = unitsgroups.begin(); it != unitsgroups.end(); it ++){
		if( (*it) == u){
			unitsgroups.erase(it);
			return true;
		}
	}
	return false;
}

void MicroManager::promptRemove(UnitsGroup* ug){
	this->promptedRemove.push_back(ug);
}

std::set<Unit*> MicroManager::getEnemies()
{
    std::set<BWAPI::Player*>::iterator iter = Broodwar->getPlayers().begin();
    for(;iter != Broodwar->getPlayers().end() && !(*iter)->isEnemy(Broodwar->self());iter++);
    return (*iter)->getUnits();
}

#ifdef BW_QT_DEBUG
QWidget* MicroManager::createWidget(QWidget* parent) const
{
	return new QLabel(QString("createWidget and refreshWidget undefined for this component."), parent);
}

void MicroManager::refreshWidget(QWidget* widget) const
{
// TODO update your widget after having defined it in the previous method :)
}
#endif
<|endoftext|>


<commit_before>#pragma once

#include "vector.hpp"

struct entity_t{
	typedef vector3_t<float> position_t, velocity_t;
	position_t position;
	velocity_t velocity;
	void move(position_t offset);
	void accelerate(velocity_t ammount);
	void update(); //std::chrono?
};
<commit_msg>Delete entity.hpp<commit_after><|endoftext|>


<commit_before>/**
 * @file ModeledReferencePR.hpp
 * Class to compute modeled pseudoranges using a reference station
 */

#ifndef GPSTK_MODELEDREFERENCEPR_HPP
#define GPSTK_MODELEDREFERENCEPR_HPP

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Dagoberto Salazar - gAGE. 2006
//
//============================================================================

#include "ModeledPseudorangeBase.hpp"
#include "DayTime.hpp"
#include "EngEphemeris.hpp"
#include "EphemerisStore.hpp"
#include "EphemerisRange.hpp"
#include "TropModel.hpp"
#include "IonoModel.hpp"
#include "IonoModelStore.hpp"
#include "Geodetic.hpp"
#include "Position.hpp"
#include "icd_200_constants.hpp"
#include "TypeID.hpp"

namespace gpstk
{
      /** @addtogroup GPSsolutions */
      //@{

      /**
       * This class compute modeled pseudoranges from satellites to a reference station.
       *
       * @sa ModeledPseudorangeBase.hpp for base class.
       *
       */
   class ModeledReferencePR : public ModeledPseudorangeBase
   {
    public:

        /// Implicit constructor
        ModeledReferencePR() throw(Exception) {
            InitializeValues();
        };

        /** Explicit constructor taking as input reference station coordinates.
         *
         * Those coordinates may be Cartesian (X, Y, Z in meters) or Geodetic
         * (Latitude, Longitude, Altitude), but defaults to Cartesian.
         *
         * Also, a pointer to GeoidModel may be specified, but default is NULL
         * (in which case WGS84 values will be used).
         *
         * @param aRx   first coordinate [ X(m), or latitude (degrees N) ]
         * @param bRx   second coordinate [ Y(m), or longitude (degrees E) ]
         * @param cRx   third coordinate [ Z, height above ellipsoid or radius, in m ]
         * @param s     coordinate system (default is Cartesian, may be set to Geodetic).
         * @param geoid pointer to GeoidModel (default is null, implies WGS84)
         */
        ModeledReferencePR(double aRx, double bRx, double cRx,
            Position::CoordinateSystem s = Position::Cartesian,
            GeoidModel *geoid = NULL) throw(Exception)
        {
            InitializeValues();
            setInitialRxPosition(aRx, bRx, cRx, s, geoid);
        };

        /// Explicit constructor, taking as input a Position object containing reference station coordinates.
        ModeledReferencePR(Position RxCoordinates) throw(Exception) {
            InitializeValues();
            setInitialRxPosition(RxCoordinates);
        };

        /** Explicit constructor, taking as input reference station coordinates, default
         * ionospheric and tropospheric models, and default observable.

         * This constructor is meant to be used when working with GNSS data structures in
         * order to set the basic parameters from the beginning.
         *
         * @param RxCoordinates Reference station coordinates.
         * @param dIonoModel    Ionospheric model to be used by default.
         * @param dTropoModel   Tropospheric model to be used by default.
         * @param dObservable   Observable type to be used by default.
         * @param dEphemeris    EphemerisStore object to be used by default.
         * @param usetgd        Whether TGD will be used by default or not.
         *
         * @sa DataStructures.hpp.
         */
        ModeledReferencePR(Position RxCoordinates, IonoModelStore& dIonoModel, TropModel& dTropoModel, EphemerisStore& dEphemeris, TypeID& dObservable, bool usetgd = true) throw(Exception) {
            InitializeValues();
            setInitialRxPosition(RxCoordinates);
            setDefaultIonoModel(dIonoModel);
            setDefaultTropoModel(dTropoModel);
            setDefaultObservable(dObservable);
            setDefaultEphemeris(dEphemeris);
            useTGD = usetgd;
        };

        /** Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
         * @param Tr            Measured time of reception of the data.
         * @param Satellite     Vector of satellites; on successful return, satellites that
         *                      were excluded by the algorithm are marked by a negative
         *                      Satellite[i].prn
         * @param Pseudorange   Vector of raw pseudoranges (parallel to satellite), in meters.
         * @param Eph           EphemerisStore to be used.
         * @param pTropModel    Pointer to tropospheric model to be used. By default points to NULL.
         * @param pIonoModel    Pointer to ionospheric model to be used. By default points to NULL.
         * @param extraBiases   Vector of extra biases to be added to the model.
         *
         * @return
         *  Number of satellites with valid data
         *
         * @sa TropModel.hpp, IonoModelStore.hpp.
         */
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, const Vector<double>& extraBiases, TropModel
            *pTropModel=NULL, IonoModelStore *pIonoModel=NULL) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, TropModel *pTropModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, const Vector<double>& extraBiases, IonoModelStore
            *pIonoModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, IonoModelStore *pIonoModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, TropModel *pTropModel, IonoModelStore *pIonoModel)
            throw(Exception);

        /** Compute just one modeled pseudorange, given satellite ID's, pseudorange and other data
         * @param Tr            Measured time of reception of the data.
         * @param Satellite     ID's of satellite
         * @param Pseudorange   Pseudorange (parallel to satellite), in meters.
         * @param Eph           EphemerisStore to be used.
         * @param pTropModel    Pointer to tropospheric model to be used. By default points to NULL.
         * @param pIonoModel    Pointer to ionospheric model to be used. By default points to NULL.
         * @param extraBiases   Extra bias to be added to the model.
         *
         * @return
         *  1 if satellite has valid data
         *
         * @sa TropModel.hpp, IonoModelStore.hpp.
         */
        int Compute(const DayTime& Tr, SatID& Satellite, double& Pseudorange,
            const EphemerisStore& Eph, const double& extraBiases, TropModel *pTropModel=NULL,
            IonoModelStore *pIonoModel=NULL) throw(Exception);

        /// Boolean variable indicating if SV instrumental delays (TGD) will be included  in results. It is true by default.
        bool useTGD;

        /// Method to get satellite elevation cut-off angle. By default, it is set to 10 degrees.
        double getMinElev()
        {
           return minElev;
        };

        /// Method to set satellite elevation cut-off angle. By default, it is set to 10 degrees.
        void setMinElev(double newElevation)
        {
           minElev = newElevation;
        };

        /** Method to set the default ionospheric model.
         * @param dIonoModel    Ionospheric model to be used by default.
         */
        void setDefaultIonoModel(IonoModelStore& dIonoModel)
        {
           pDefaultIonoModel = &dIonoModel;
        };

        /** Method to set the default tropospheric model.
         * @param dTropoModel    Tropospheric model to be used by default.
         */
        void setDefaultTropoModel(TropModel& dTropoModel)
        {
           pDefaultTropoModel = &dTropoModel;
        };

        /** Method to set the default extra biases.
         * @param eBiases    Vector with the default extra biases
         */
        void setDefaultExtraBiases(Vector<double>& eBiases)
        {
           extraBiases = eBiases;
        };

        /** Method to set the default observable to be used when fed with GNSS data structures.
         * @param type      TypeID object to be used by default
         */
        virtual void setDefaultObservable(TypeID& type)
        {
           defaultObservable = type;
        };

        /// Method to get the default observable being used with GNSS data structures.
        virtual TypeID getDefaultObservable()
        {
           return defaultObservable;
        };

        /** Method to set the default EphemerisStore to be used with GNSS data structures.
         * @param ephem     EphemerisStore object to be used by default
         */
        virtual void setDefaultEphemeris(EphemerisStore& ephem)
        {
           pDefaultEphemeris = &ephem;
        };

        /// Destructor.
        virtual ~ModeledReferencePR() throw() {};

    protected:

        /// Pointer to default ionospheric model.
        IonoModelStore *pDefaultIonoModel;

        /// Pointer to default tropospheric model.
        TropModel *pDefaultTropoModel;

        /// Default observable to be used when fed with GNSS data structures.
        TypeID defaultObservable;

        /// Pointer to default EphemerisStore object when working with GNSS data structures.
        EphemerisStore* pDefaultEphemeris;

        /// Initialization method
        void InitializeValues() throw(Exception) {
            setInitialRxPosition();
            geometricRho(0);
            svClockBiases(0);
            svXvt(0);
            svTGD(0);
            svRelativity(0);
            ionoCorrections(0);
            tropoCorrections(0);
            modeledPseudoranges(0);
            prefitResiduals(0);
            extraBiases(0);
            availableSV(0);
            rejectedSV(0);
            useTGD = true;
            minElev = 10.0;  // By default, cut-off elevation is set to 10 degrees
            pDefaultIonoModel = NULL;
            pDefaultTropoModel = NULL;
            defaultObservable = TypeID::C1;     // By default, process C1 code
            pDefaultEphemeris = NULL;
        };

        /** Method to set the initial (a priori) position of receiver.
         * @return
         *  0 if OK
         *  -1 if problems arose
         */
        int setInitialRxPosition(double aRx, double bRx, double cRx,
            Position::CoordinateSystem s=Position::Cartesian,
            GeoidModel *geoid=NULL) throw(GeometryException)
        {
            try {
                Position rxpos(aRx, bRx, cRx, s, geoid);
                setInitialRxPosition(rxpos);
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to set the initial (a priori) position of receiver.
        int setInitialRxPosition(Position RxCoordinates) throw(GeometryException)
        {
            try {
                rxPos = RxCoordinates;
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to set the initial (a priori) position of receiver.
        int setInitialRxPosition() throw(GeometryException)
        {
            try {
                rxPos.setECEF(0.0, 0.0, 0.0);
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to get the tropospheric corrections.
        double getTropoCorrections(TropModel *pTropModel, double elevation) throw()
        {
            double tropoCorr = 0.0;
            try {
                tropoCorr = pTropModel->correction(elevation);
                // Check validity
                if(!(pTropModel->isValid())) tropoCorr = 0.0;
            }
            catch(TropModel::InvalidTropModel& e) {
                tropoCorr = 0.0;
            }
            return tropoCorr;
        };

        /// Method to get the ionospheric corrections.
        double getIonoCorrections(IonoModelStore *pIonoModel, DayTime Tr, Geodetic rxGeo, double elevation, double azimuth) throw()
        {
            double ionoCorr = 0.0;
            try {
                ionoCorr = pIonoModel->getCorrection(Tr, rxGeo, elevation, azimuth);
            }
            catch(IonoModelStore::NoIonoModelFound& e) {
                ionoCorr = 0.0;
            }
            return ionoCorr;
        };

        /// Method to get TGD corrections.
        double getTGDCorrections(DayTime Tr, const EphemerisStore& Eph, SatID sat) throw()
        {

            double TGDCorr = 0.0;

            try {
                TGDCorr = (Eph.getTGD(sat, Tr));
            }
            catch(EphemerisStore::NoTGDFound& e) {
                TGDCorr = 0.0;
            }
            return TGDCorr;
        };

   }; // class ModeledReferencePR

   //@}

} // namespace

#endif
<commit_msg>Added method getDefaultEphemeris().<commit_after>/**
 * @file ModeledReferencePR.hpp
 * Class to compute modeled pseudoranges using a reference station
 */

#ifndef GPSTK_MODELEDREFERENCEPR_HPP
#define GPSTK_MODELEDREFERENCEPR_HPP

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Dagoberto Salazar - gAGE. 2006
//
//============================================================================

#include "ModeledPseudorangeBase.hpp"
#include "DayTime.hpp"
#include "EngEphemeris.hpp"
#include "EphemerisStore.hpp"
#include "EphemerisRange.hpp"
#include "TropModel.hpp"
#include "IonoModel.hpp"
#include "IonoModelStore.hpp"
#include "Geodetic.hpp"
#include "Position.hpp"
#include "icd_200_constants.hpp"
#include "TypeID.hpp"

namespace gpstk
{
      /** @addtogroup GPSsolutions */
      //@{

      /**
       * This class compute modeled pseudoranges from satellites to a reference station.
       *
       * @sa ModeledPseudorangeBase.hpp for base class.
       *
       */
   class ModeledReferencePR : public ModeledPseudorangeBase
   {
    public:

        /// Implicit constructor
        ModeledReferencePR() throw(Exception) {
            InitializeValues();
        };

        /** Explicit constructor taking as input reference station coordinates.
         *
         * Those coordinates may be Cartesian (X, Y, Z in meters) or Geodetic
         * (Latitude, Longitude, Altitude), but defaults to Cartesian.
         *
         * Also, a pointer to GeoidModel may be specified, but default is NULL
         * (in which case WGS84 values will be used).
         *
         * @param aRx   first coordinate [ X(m), or latitude (degrees N) ]
         * @param bRx   second coordinate [ Y(m), or longitude (degrees E) ]
         * @param cRx   third coordinate [ Z, height above ellipsoid or radius, in m ]
         * @param s     coordinate system (default is Cartesian, may be set to Geodetic).
         * @param geoid pointer to GeoidModel (default is null, implies WGS84)
         */
        ModeledReferencePR(double aRx, double bRx, double cRx,
            Position::CoordinateSystem s = Position::Cartesian,
            GeoidModel *geoid = NULL) throw(Exception)
        {
            InitializeValues();
            setInitialRxPosition(aRx, bRx, cRx, s, geoid);
        };

        /// Explicit constructor, taking as input a Position object containing reference station coordinates.
        ModeledReferencePR(Position RxCoordinates) throw(Exception) {
            InitializeValues();
            setInitialRxPosition(RxCoordinates);
        };

        /** Explicit constructor, taking as input reference station coordinates, default
         * ionospheric and tropospheric models, and default observable.

         * This constructor is meant to be used when working with GNSS data structures in
         * order to set the basic parameters from the beginning.
         *
         * @param RxCoordinates Reference station coordinates.
         * @param dIonoModel    Ionospheric model to be used by default.
         * @param dTropoModel   Tropospheric model to be used by default.
         * @param dObservable   Observable type to be used by default.
         * @param dEphemeris    EphemerisStore object to be used by default.
         * @param usetgd        Whether TGD will be used by default or not.
         *
         * @sa DataStructures.hpp.
         */
        ModeledReferencePR(Position RxCoordinates, IonoModelStore& dIonoModel, TropModel& dTropoModel, EphemerisStore& dEphemeris, TypeID& dObservable, bool usetgd = true) throw(Exception) {
            InitializeValues();
            setInitialRxPosition(RxCoordinates);
            setDefaultIonoModel(dIonoModel);
            setDefaultTropoModel(dTropoModel);
            setDefaultObservable(dObservable);
            setDefaultEphemeris(dEphemeris);
            useTGD = usetgd;
        };

        /** Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
         * @param Tr            Measured time of reception of the data.
         * @param Satellite     Vector of satellites; on successful return, satellites that
         *                      were excluded by the algorithm are marked by a negative
         *                      Satellite[i].prn
         * @param Pseudorange   Vector of raw pseudoranges (parallel to satellite), in meters.
         * @param Eph           EphemerisStore to be used.
         * @param pTropModel    Pointer to tropospheric model to be used. By default points to NULL.
         * @param pIonoModel    Pointer to ionospheric model to be used. By default points to NULL.
         * @param extraBiases   Vector of extra biases to be added to the model.
         *
         * @return
         *  Number of satellites with valid data
         *
         * @sa TropModel.hpp, IonoModelStore.hpp.
         */
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, const Vector<double>& extraBiases, TropModel
            *pTropModel=NULL, IonoModelStore *pIonoModel=NULL) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, TropModel *pTropModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, const Vector<double>& extraBiases, IonoModelStore
            *pIonoModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, IonoModelStore *pIonoModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, TropModel *pTropModel, IonoModelStore *pIonoModel)
            throw(Exception);

        /** Compute just one modeled pseudorange, given satellite ID's, pseudorange and other data
         * @param Tr            Measured time of reception of the data.
         * @param Satellite     ID's of satellite
         * @param Pseudorange   Pseudorange (parallel to satellite), in meters.
         * @param Eph           EphemerisStore to be used.
         * @param pTropModel    Pointer to tropospheric model to be used. By default points to NULL.
         * @param pIonoModel    Pointer to ionospheric model to be used. By default points to NULL.
         * @param extraBiases   Extra bias to be added to the model.
         *
         * @return
         *  1 if satellite has valid data
         *
         * @sa TropModel.hpp, IonoModelStore.hpp.
         */
        int Compute(const DayTime& Tr, SatID& Satellite, double& Pseudorange,
            const EphemerisStore& Eph, const double& extraBiases, TropModel *pTropModel=NULL,
            IonoModelStore *pIonoModel=NULL) throw(Exception);

        /// Boolean variable indicating if SV instrumental delays (TGD) will be included  in results. It is true by default.
        bool useTGD;

        /// Method to get satellite elevation cut-off angle. By default, it is set to 10 degrees.
        double getMinElev()
        {
           return minElev;
        };

        /// Method to set satellite elevation cut-off angle. By default, it is set to 10 degrees.
        void setMinElev(double newElevation)
        {
           minElev = newElevation;
        };

        /** Method to set the default ionospheric model.
         * @param dIonoModel    Ionospheric model to be used by default.
         */
        void setDefaultIonoModel(IonoModelStore& dIonoModel)
        {
           pDefaultIonoModel = &dIonoModel;
        };

        /** Method to set the default tropospheric model.
         * @param dTropoModel    Tropospheric model to be used by default.
         */
        void setDefaultTropoModel(TropModel& dTropoModel)
        {
           pDefaultTropoModel = &dTropoModel;
        };

        /** Method to set the default extra biases.
         * @param eBiases    Vector with the default extra biases
         */
        void setDefaultExtraBiases(Vector<double>& eBiases)
        {
           extraBiases = eBiases;
        };

        /** Method to set the default observable to be used when fed with GNSS data structures.
         * @param type      TypeID object to be used by default
         */
        virtual void setDefaultObservable(TypeID& type)
        {
           defaultObservable = type;
        };

        /// Method to get the default observable being used with GNSS data structures.
        virtual TypeID getDefaultObservable()
        {
           return defaultObservable;
        };

        /** Method to set the default EphemerisStore to be used with GNSS data structures.
         * @param ephem     EphemerisStore object to be used by default
         */
        virtual void setDefaultEphemeris(EphemerisStore& ephem)
        {
           pDefaultEphemeris = &ephem;
        };

        /** Method to get a pointer to the default EphemerisStore to be used with GNSS data structures.
         */
        virtual EphemerisStore* getDefaultEphemeris()
        {
           return pDefaultEphemeris;
        };

        /// Destructor.
        virtual ~ModeledReferencePR() throw() {};

    protected:

        /// Pointer to default ionospheric model.
        IonoModelStore *pDefaultIonoModel;

        /// Pointer to default tropospheric model.
        TropModel *pDefaultTropoModel;

        /// Default observable to be used when fed with GNSS data structures.
        TypeID defaultObservable;

        /// Pointer to default EphemerisStore object when working with GNSS data structures.
        EphemerisStore* pDefaultEphemeris;

        /// Initialization method
        void InitializeValues() throw(Exception) {
            setInitialRxPosition();
            geometricRho(0);
            svClockBiases(0);
            svXvt(0);
            svTGD(0);
            svRelativity(0);
            ionoCorrections(0);
            tropoCorrections(0);
            modeledPseudoranges(0);
            prefitResiduals(0);
            extraBiases(0);
            availableSV(0);
            rejectedSV(0);
            useTGD = true;
            minElev = 10.0;  // By default, cut-off elevation is set to 10 degrees
            pDefaultIonoModel = NULL;
            pDefaultTropoModel = NULL;
            defaultObservable = TypeID::C1;     // By default, process C1 code
            pDefaultEphemeris = NULL;
        };

        /** Method to set the initial (a priori) position of receiver.
         * @return
         *  0 if OK
         *  -1 if problems arose
         */
        int setInitialRxPosition(double aRx, double bRx, double cRx,
            Position::CoordinateSystem s=Position::Cartesian,
            GeoidModel *geoid=NULL) throw(GeometryException)
        {
            try {
                Position rxpos(aRx, bRx, cRx, s, geoid);
                setInitialRxPosition(rxpos);
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to set the initial (a priori) position of receiver.
        int setInitialRxPosition(Position RxCoordinates) throw(GeometryException)
        {
            try {
                rxPos = RxCoordinates;
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to set the initial (a priori) position of receiver.
        int setInitialRxPosition() throw(GeometryException)
        {
            try {
                rxPos.setECEF(0.0, 0.0, 0.0);
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to get the tropospheric corrections.
        double getTropoCorrections(TropModel *pTropModel, double elevation) throw()
        {
            double tropoCorr = 0.0;
            try {
                tropoCorr = pTropModel->correction(elevation);
                // Check validity
                if(!(pTropModel->isValid())) tropoCorr = 0.0;
            }
            catch(TropModel::InvalidTropModel& e) {
                tropoCorr = 0.0;
            }
            return tropoCorr;
        };

        /// Method to get the ionospheric corrections.
        double getIonoCorrections(IonoModelStore *pIonoModel, DayTime Tr, Geodetic rxGeo, double elevation, double azimuth) throw()
        {
            double ionoCorr = 0.0;
            try {
                ionoCorr = pIonoModel->getCorrection(Tr, rxGeo, elevation, azimuth);
            }
            catch(IonoModelStore::NoIonoModelFound& e) {
                ionoCorr = 0.0;
            }
            return ionoCorr;
        };

        /// Method to get TGD corrections.
        double getTGDCorrections(DayTime Tr, const EphemerisStore& Eph, SatID sat) throw()
        {

            double TGDCorr = 0.0;

            try {
                TGDCorr = (Eph.getTGD(sat, Tr));
            }
            catch(EphemerisStore::NoTGDFound& e) {
                TGDCorr = 0.0;
            }
            return TGDCorr;
        };

   }; // class ModeledReferencePR

   //@}

} // namespace

#endif
<|endoftext|>


<commit_before>#include "RestClient.h"

#ifdef HTTP_DEBUG
#define HTTP_DEBUG_PRINT(string) (Serial.print(string))
#endif

#ifndef HTTP_DEBUG
#define HTTP_DEBUG_PRINT(string)
#endif

RestClient::RestClient(const char* _host){
    host = _host;
    port = 80;
    ssl = 0;
    fingerprint = NULL;
    num_headers = 0;
        if (contentType != NULL) {
            contentType = "application/x-www-form-urlencoded";  // default
	}
}

RestClient::RestClient(const char* _host, int _port){
    host = _host;
    port = _port;
    ssl = 0;
    fingerprint = NULL;
    num_headers = 0;
        if (contentType != NULL) {
            contentType = "application/x-www-form-urlencoded";  // default
        }
}

bool RestClient::dhcp(){
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  if (begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    return false;
  }

  //give it time to initialize
  delay(1000);
  return true;
}

RestClient::RestClient(const char* _host, int _port, const char* _fingerprint){
    host = _host;
    port = _port;
    ssl = 1;
    fingerprint = _fingerprint;
    num_headers = 0;
        if (contentType != NULL) {
            contentType = "application/x-www-form-urlencoded";  // default
        }
}

RestClient::RestClient(const char* _host, int _port, int _ssl) {
    host = _host;
    port = _port;
    ssl = (_ssl) ? 1 : 0;
    fingerprint = NULL;
    num_headers = 0;
        if (contentType != NULL) {
            contentType = "application/x-www-form-urlencoded";  // default
        }
}

// GET path
int RestClient::get(const char* path){
    return request("GET", path, NULL, NULL);
}

//GET path with response
int RestClient::get(const char* path, String* response){
    return request("GET", path, NULL, response);
}

// POST path and body
int RestClient::post(const char* path, const char* body){
    return request("POST", path, body, NULL);
}

// POST path and body with response
int RestClient::post(const char* path, const char* body, String* response){
    return request("POST", path, body, response);
}

// PATCH path and body
int RestClient::patch(const char* path, const char* body){
    return request("PATCH", path, body, NULL);
}

// PATCH path and body with response
int RestClient::patch(const char* path, const char* body, String* response){
    return request("PATCH", path, body, response);
}

// PUT path and body
int RestClient::put(const char* path, const char* body){
    return request("PUT", path, body, NULL);
}

// PUT path and body with response
int RestClient::put(const char* path, const char* body, String* response){
    return request("PUT", path, body, response);
}

// DELETE path
int RestClient::del(const char* path){
    return request("DELETE", path, NULL, NULL);
}

// DELETE path and response
int RestClient::del(const char* path, String* response){
    return request("DELETE", path, NULL, response);
}

// DELETE path and body
int RestClient::del(const char* path, const char* body ){
    return request("DELETE", path, body, NULL);
}

// DELETE path and body with response
int RestClient::del(const char* path, const char* body, String* response){
    return request("DELETE", path, body, response);
}

void RestClient::write(const char* string){

    if(ssl) {
        HTTP_DEBUG_PRINT("\nSSL Print: ");
        HTTP_DEBUG_PRINT(string);
        sslClient.print(string);
    } else {
        HTTP_DEBUG_PRINT("\nHTTP Print: ");
        HTTP_DEBUG_PRINT(string);
        client.print(string);
    }
}

void RestClient::setHeader(const char* header){
    headers[num_headers] = header;
    num_headers++;
}

void RestClient::setContentType(const char* contentTypeValue){
    contentType = contentTypeValue;
}

void RestClient::setSSL(int _ssl){
    ssl = (_ssl) ? 1 : 0;
}

// The mother- generic request method.
//
int RestClient::request(const char* method, const char* path,
                        const char* body, String* response){

    HTTP_DEBUG_PRINT("HTTP: connect\n");

    if (ssl) {
        if(!sslClient.connect(host, port)){
            HTTP_DEBUG_PRINT("HTTPS Connection failed\n");
            return 0;
        }
        if (fingerprint) {
            HTTP_DEBUG_PRINT("Verifiying SSL certificate\n");
            if (sslClient.verify(fingerprint, host)) {
                HTTP_DEBUG_PRINT("SSL certificate matches\n");
            } else {
                HTTP_DEBUG_PRINT("SSL certificate does not match\n");
                return 0;
            }
        }
    } else {
        if(!client.connect(host, port)){
            HTTP_DEBUG_PRINT("HTTP Connection failed\n");
            return 0;
        }
    }

    HTTP_DEBUG_PRINT("HTTP: connected\n");
    HTTP_DEBUG_PRINT("REQUEST: \n");

    String request = String(method) + " " + String(path) + " HTTP/1.1\r\n";
    for(int i=0; i<num_headers; i++){
        request += String(headers[i]) + "\r\n";
    }
    request += "Host: " + String(host) +  ":" + String(port) + "\r\n";
    request += "Connection: close\r\n";
    if(body != NULL){
        char contentLength[30];
        sprintf(contentLength, "Content-Length: %d\r\n", strlen(body));
        request += String(contentLength);

        request += "Content-Type: " + String(contentType) + "\r\n";
    }
    if(method == "GET"){
        request += "\r\n";
    }

    if(body != NULL){
        request += String(body);
        request += "\r\n\r\n";
    }

    write(request.c_str());

    HTTP_DEBUG_PRINT("\nEND REQUEST\n");
    //make sure you write all those bytes.
    //delay(1000);

    HTTP_DEBUG_PRINT("HTTP: call readResponse\n");
    int statusCode = readResponse(response);
    HTTP_DEBUG_PRINT("HTTP: return readResponse\n");

    //cleanup
    HTTP_DEBUG_PRINT("HTTP: stop client\n");
    num_headers = 0;
    if(ssl){
        sslClient.stop();
    } else {
        client.stop();
    }
    delay(50);
    HTTP_DEBUG_PRINT("HTTP: client stopped\n");

    return statusCode;

}

int RestClient::readResponse(String* response) {

    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    boolean httpBody = false;
    boolean inStatus = false;

    char statusCode[4];
    int i = 0;
    int code = 0;

    if(response == NULL){
        HTTP_DEBUG_PRINT("HTTP: NULL RESPONSE POINTER: \n");
    }else{
        HTTP_DEBUG_PRINT("HTTP: NON-NULL RESPONSE POINTER: \n");
    }

    HTTP_DEBUG_PRINT("HTTP: RESPONSE: \n");
    void* http_client;
    if(ssl) {
        HTTP_DEBUG_PRINT("HTTP: Connect: " + String(sslClient.connected()) + " Available: " + String(sslClient.available()) + "\n");
        while (sslClient.connected()) {
            HTTP_DEBUG_PRINT(".");

            if (sslClient.available()) {
                HTTP_DEBUG_PRINT(",");

                char c = sslClient.read();
                HTTP_DEBUG_PRINT(c);

                if(c == ' ' && !inStatus){
                    inStatus = true;
                }

                if(inStatus && i < 3 && c != ' '){
                    statusCode[i] = c;
                    i++;
                }
                if(i == 3){
                    statusCode[i] = '\0';
                    code = atoi(statusCode);
                }

                if(httpBody){
                    //only write response if its not null
                    if(response != NULL) response->concat(c);
                }
                else
                {
                    if (c == '\n' && currentLineIsBlank) {
                        httpBody = true;
                    }

                    if (c == '\n') {
                        // you're starting a new line
                        currentLineIsBlank = true;
                    }
                    else if (c != '\r') {
                        // you've gotten a character on the current line
                        currentLineIsBlank = false;
                    }
                }
            }
        }
        HTTP_DEBUG_PRINT("HTTPS client closed \n");
    }else {
        while (client.connected()) {
            HTTP_DEBUG_PRINT(".");

            if (client.available()) {
                HTTP_DEBUG_PRINT(",");

                char c = client.read();
                HTTP_DEBUG_PRINT(c);

                if(c == ' ' && !inStatus){
                    inStatus = true;
                }

                if(inStatus && i < 3 && c != ' '){
                    statusCode[i] = c;
                    i++;
                }
                if(i == 3){
                    statusCode[i] = '\0';
                    code = atoi(statusCode);
                }

                if(httpBody){
                    //only write response if its not null
                    if(response != NULL) response->concat(c);
                }
                else
                {
                    if (c == '\n' && currentLineIsBlank) {
                        httpBody = true;
                    }

                    if (c == '\n') {
                        // you're starting a new line
                        currentLineIsBlank = true;
                    }
                    else if (c != '\r') {
                        // you've gotten a character on the current line
                        currentLineIsBlank = false;
                    }
                }
            }
        }
    }

    HTTP_DEBUG_PRINT("HTTP: return readResponse3\n");
    return code;
}
<commit_msg>Revert bug in overwriting Content-Type headers<commit_after>#include "RestClient.h"

#ifdef HTTP_DEBUG
#define HTTP_DEBUG_PRINT(string) (Serial.print(string))
#endif

#ifndef HTTP_DEBUG
#define HTTP_DEBUG_PRINT(string)
#endif

RestClient::RestClient(const char* _host){
    host = _host;
    port = 80;
    ssl = 0;
    fingerprint = NULL;
    num_headers = 0;
        if (contentType == NULL) {
            contentType = "application/x-www-form-urlencoded";  // default
	}
}

RestClient::RestClient(const char* _host, int _port){
    host = _host;
    port = _port;
    ssl = 0;
    fingerprint = NULL;
    num_headers = 0;
        if (contentType == NULL) {
            contentType = "application/x-www-form-urlencoded";  // default
        }
}

bool RestClient::dhcp(){
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  if (begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    return false;
  }

  //give it time to initialize
  delay(1000);
  return true;
}

RestClient::RestClient(const char* _host, int _port, const char* _fingerprint){
    host = _host;
    port = _port;
    ssl = 1;
    fingerprint = _fingerprint;
    num_headers = 0;
        if (contentType == NULL) {
            contentType = "application/x-www-form-urlencoded";  // default
        }
}

RestClient::RestClient(const char* _host, int _port, int _ssl) {
    host = _host;
    port = _port;
    ssl = (_ssl) ? 1 : 0;
    fingerprint = NULL;
    num_headers = 0;
        if (contentType == NULL) {
            contentType = "application/x-www-form-urlencoded";  // default
        }
}

// GET path
int RestClient::get(const char* path){
    return request("GET", path, NULL, NULL);
}

//GET path with response
int RestClient::get(const char* path, String* response){
    return request("GET", path, NULL, response);
}

// POST path and body
int RestClient::post(const char* path, const char* body){
    return request("POST", path, body, NULL);
}

// POST path and body with response
int RestClient::post(const char* path, const char* body, String* response){
    return request("POST", path, body, response);
}

// PATCH path and body
int RestClient::patch(const char* path, const char* body){
    return request("PATCH", path, body, NULL);
}

// PATCH path and body with response
int RestClient::patch(const char* path, const char* body, String* response){
    return request("PATCH", path, body, response);
}

// PUT path and body
int RestClient::put(const char* path, const char* body){
    return request("PUT", path, body, NULL);
}

// PUT path and body with response
int RestClient::put(const char* path, const char* body, String* response){
    return request("PUT", path, body, response);
}

// DELETE path
int RestClient::del(const char* path){
    return request("DELETE", path, NULL, NULL);
}

// DELETE path and response
int RestClient::del(const char* path, String* response){
    return request("DELETE", path, NULL, response);
}

// DELETE path and body
int RestClient::del(const char* path, const char* body ){
    return request("DELETE", path, body, NULL);
}

// DELETE path and body with response
int RestClient::del(const char* path, const char* body, String* response){
    return request("DELETE", path, body, response);
}

void RestClient::write(const char* string){

    if(ssl) {
        HTTP_DEBUG_PRINT("\nSSL Print: ");
        HTTP_DEBUG_PRINT(string);
        sslClient.print(string);
    } else {
        HTTP_DEBUG_PRINT("\nHTTP Print: ");
        HTTP_DEBUG_PRINT(string);
        client.print(string);
    }
}

void RestClient::setHeader(const char* header){
    headers[num_headers] = header;
    num_headers++;
}

void RestClient::setContentType(const char* contentTypeValue){
    contentType = contentTypeValue;
}

void RestClient::setSSL(int _ssl){
    ssl = (_ssl) ? 1 : 0;
}

// The mother- generic request method.
//
int RestClient::request(const char* method, const char* path,
                        const char* body, String* response){

    HTTP_DEBUG_PRINT("HTTP: connect\n");

    if (ssl) {
        if(!sslClient.connect(host, port)){
            HTTP_DEBUG_PRINT("HTTPS Connection failed\n");
            return 0;
        }
        if (fingerprint) {
            HTTP_DEBUG_PRINT("Verifiying SSL certificate\n");
            if (sslClient.verify(fingerprint, host)) {
                HTTP_DEBUG_PRINT("SSL certificate matches\n");
            } else {
                HTTP_DEBUG_PRINT("SSL certificate does not match\n");
                return 0;
            }
        }
    } else {
        if(!client.connect(host, port)){
            HTTP_DEBUG_PRINT("HTTP Connection failed\n");
            return 0;
        }
    }

    HTTP_DEBUG_PRINT("HTTP: connected\n");
    HTTP_DEBUG_PRINT("REQUEST: \n");

    String request = String(method) + " " + String(path) + " HTTP/1.1\r\n";
    for(int i=0; i<num_headers; i++){
        request += String(headers[i]) + "\r\n";
    }
    request += "Host: " + String(host) +  ":" + String(port) + "\r\n";
    request += "Connection: close\r\n";
    if(body != NULL){
        char contentLength[30];
        sprintf(contentLength, "Content-Length: %d\r\n", strlen(body));
        request += String(contentLength);

        request += "Content-Type: " + String(contentType) + "\r\n";
    }
    if(method == "GET"){
        request += "\r\n";
    }

    if(body != NULL){
        request += String(body);
        request += "\r\n\r\n";
    }

    write(request.c_str());

    HTTP_DEBUG_PRINT("\nEND REQUEST\n");
    //make sure you write all those bytes.
    //delay(1000);

    HTTP_DEBUG_PRINT("HTTP: call readResponse\n");
    int statusCode = readResponse(response);
    HTTP_DEBUG_PRINT("HTTP: return readResponse\n");

    //cleanup
    HTTP_DEBUG_PRINT("HTTP: stop client\n");
    num_headers = 0;
    if(ssl){
        sslClient.stop();
    } else {
        client.stop();
    }
    delay(50);
    HTTP_DEBUG_PRINT("HTTP: client stopped\n");

    return statusCode;

}

int RestClient::readResponse(String* response) {

    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    boolean httpBody = false;
    boolean inStatus = false;

    char statusCode[4];
    int i = 0;
    int code = 0;

    if(response == NULL){
        HTTP_DEBUG_PRINT("HTTP: NULL RESPONSE POINTER: \n");
    }else{
        HTTP_DEBUG_PRINT("HTTP: NON-NULL RESPONSE POINTER: \n");
    }

    HTTP_DEBUG_PRINT("HTTP: RESPONSE: \n");
    void* http_client;
    if(ssl) {
        HTTP_DEBUG_PRINT("HTTP: Connect: " + String(sslClient.connected()) + " Available: " + String(sslClient.available()) + "\n");
        while (sslClient.connected()) {
            HTTP_DEBUG_PRINT(".");

            if (sslClient.available()) {
                HTTP_DEBUG_PRINT(",");

                char c = sslClient.read();
                HTTP_DEBUG_PRINT(c);

                if(c == ' ' && !inStatus){
                    inStatus = true;
                }

                if(inStatus && i < 3 && c != ' '){
                    statusCode[i] = c;
                    i++;
                }
                if(i == 3){
                    statusCode[i] = '\0';
                    code = atoi(statusCode);
                }

                if(httpBody){
                    //only write response if its not null
                    if(response != NULL) response->concat(c);
                }
                else
                {
                    if (c == '\n' && currentLineIsBlank) {
                        httpBody = true;
                    }

                    if (c == '\n') {
                        // you're starting a new line
                        currentLineIsBlank = true;
                    }
                    else if (c != '\r') {
                        // you've gotten a character on the current line
                        currentLineIsBlank = false;
                    }
                }
            }
        }
        HTTP_DEBUG_PRINT("HTTPS client closed \n");
    }else {
        while (client.connected()) {
            HTTP_DEBUG_PRINT(".");

            if (client.available()) {
                HTTP_DEBUG_PRINT(",");

                char c = client.read();
                HTTP_DEBUG_PRINT(c);

                if(c == ' ' && !inStatus){
                    inStatus = true;
                }

                if(inStatus && i < 3 && c != ' '){
                    statusCode[i] = c;
                    i++;
                }
                if(i == 3){
                    statusCode[i] = '\0';
                    code = atoi(statusCode);
                }

                if(httpBody){
                    //only write response if its not null
                    if(response != NULL) response->concat(c);
                }
                else
                {
                    if (c == '\n' && currentLineIsBlank) {
                        httpBody = true;
                    }

                    if (c == '\n') {
                        // you're starting a new line
                        currentLineIsBlank = true;
                    }
                    else if (c != '\r') {
                        // you've gotten a character on the current line
                        currentLineIsBlank = false;
                    }
                }
            }
        }
    }

    HTTP_DEBUG_PRINT("HTTP: return readResponse3\n");
    return code;
}
<|endoftext|>


<commit_before>/**
 * @file ModeledReferencePR.hpp
 * Class to compute modeled pseudoranges using a reference station
 */

#ifndef GPSTK_MODELEDREFERENCEPR_HPP
#define GPSTK_MODELEDREFERENCEPR_HPP

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Dagoberto Salazar - gAGE. 2006
//
//============================================================================

#include "ModeledPseudorangeBase.hpp"
#include "DayTime.hpp"
#include "EngEphemeris.hpp"
#include "EphemerisStore.hpp"
#include "EphemerisRange.hpp"
#include "TropModel.hpp"
#include "IonoModel.hpp"
#include "IonoModelStore.hpp"
#include "Geodetic.hpp"
#include "Position.hpp"
#include "icd_200_constants.hpp"

namespace gpstk
{
      /** @addtogroup GPSsolutions */
      //@{

      /**
       * This class compute modeled pseudoranges from satellites to a reference station.
       *
       * @sa ModeledPseudorangeBase.hpp for base class.
       *
       */
   class ModeledReferencePR : public ModeledPseudorangeBase
   {
    public:

        /// Implicit constructor
        ModeledReferencePR() throw(Exception) {
            InitializeValues();
        };

        /** Explicit constructor taking as input reference station coordinates.
         *
         * Those coordinates may be Cartesian (X, Y, Z in meters) or Geodetic
         * (Latitude, Longitude, Altitude), but defaults to Cartesian.
         *
         * Also, a pointer to GeoidModel may be specified, but default is NULL
         * (in which case WGS84 values will be used).
         *
         * @param aRx   first coordinate [ X(m), or latitude (degrees N) ]
         * @param bRx   second coordinate [ Y(m), or longitude (degrees E) ]
         * @param cRx   third coordinate [ Z, height above ellipsoid or radius, in m ]
         * @param s     coordinate system (default is Cartesian, may be set to Geodetic).
         * @param geoid pointer to GeoidModel (default is null, implies WGS84)
         */
        ModeledReferencePR(double aRx, double bRx, double cRx,
            Position::CoordinateSystem s = Position::Cartesian,
            GeoidModel *geoid = NULL) throw(Exception)
        {
            InitializeValues();
            setInitialRxPosition(aRx, bRx, cRx, s, geoid);
        };

        /// Explicit constructor, taking as input a Position object containing reference station coordinates.
        ModeledReferencePR(Position RxCoordinates) throw(Exception) {
            InitializeValues();
            setInitialRxPosition(RxCoordinates);
        };

        /** Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
         * @param Tr            Measured time of reception of the data.
         * @param Satellite     Vector of satellites; on successful return, satellites that
         *                      were excluded by the algorithm are marked by a negative
         *                      Satellite[i].prn
         * @param Pseudorange   Vector of raw pseudoranges (parallel to satellite), in meters.
         * @param Eph           EphemerisStore to be used.
         * @param pTropModel    Pointer to tropospheric model to be used. By default points to NULL.
         * @param pIonoModel    Pointer to ionospheric model to be used. By default points to NULL.
         * @param extraBiases   Vector of extra biases to be added to the model.
         *
         * @return
         *  Number of satellites with valid data
         *
         * @sa TropModel.hpp, IonoModelStore.hpp.
         */
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, const Vector<double>& extraBiases, TropModel
            *pTropModel=NULL, IonoModelStore *pIonoModel=NULL) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, TropModel *pTropModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, const Vector<double>& extraBiases, IonoModelStore
            *pIonoModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, IonoModelStore *pIonoModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, TropModel *pTropModel, IonoModelStore *pIonoModel)
            throw(Exception);

        /** Compute just one modeled pseudorange, given satellite ID's, pseudorange and other data
         * @param Tr            Measured time of reception of the data.
         * @param Satellite     ID's of satellite
         * @param Pseudorange   Pseudorange (parallel to satellite), in meters.
         * @param Eph           EphemerisStore to be used.
         * @param pTropModel    Pointer to tropospheric model to be used. By default points to NULL.
         * @param pIonoModel    Pointer to ionospheric model to be used. By default points to NULL.
         * @param extraBiases   Extra bias to be added to the model.
         *
         * @return
         *  1 if satellite has valid data
         *
         * @sa TropModel.hpp, IonoModelStore.hpp.
         */
        int Compute(const DayTime& Tr, SatID& Satellite, double& Pseudorange,
            const EphemerisStore& Eph, const double& extraBiases, TropModel *pTropModel=NULL,
            IonoModelStore *pIonoModel=NULL) throw(Exception);

        /// Boolean variable indicating if SV instrumental delays (TGD) will be included  in results. It is true by default.
        bool useTGD;

        /// Destructor.
        virtual ~ModeledReferencePR() throw() {};

    protected:

        /// Initialization method
        void InitializeValues() throw(Exception) {
            setInitialRxPosition();
            geometricRho(0);
            svClockBiases(0);
            svXvt(0);
            svTGD(0);
            svRelativity(0);
            ionoCorrections(0);
            tropoCorrections(0);
            modeledPseudoranges(0);
            prefitResiduals(0);
            extraBiases(0);
            availableSV(0);
            rejectedSV(0);
            useTGD = true;
            minElev = 10.0;  // By default, cut-off elevation is set to 10 degrees
        };

        /** Method to set the initial (a priori) position of receiver.
         * @return
         *  0 if OK
         *  -1 if problems arose
         */
        int setInitialRxPosition(double aRx, double bRx, double cRx,
            Position::CoordinateSystem s=Position::Cartesian,
            GeoidModel *geoid=NULL) throw(GeometryException)
        {
            try {
                Position rxpos(aRx, bRx, cRx, s, geoid);
                setInitialRxPosition(rxpos);
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to set the initial (a priori) position of receiver.
        int setInitialRxPosition(Position RxCoordinates) throw(GeometryException)
        {
            try {
                rxPos = RxCoordinates;
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to set the initial (a priori) position of receiver.
        int setInitialRxPosition() throw(GeometryException)
        {
            try {
                rxPos.setECEF(0.0, 0.0, 0.0);
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to get the tropospheric corrections.
        double getTropoCorrections(TropModel *pTropModel, double elevation) throw()
        {
            double tropoCorr = 0.0;
            try {
                tropoCorr = pTropModel->correction(elevation);
                // Check validity
                if(!(pTropModel->isValid())) tropoCorr = 0.0;
            }
            catch(TropModel::InvalidTropModel& e) {
                tropoCorr = 0.0;
            }
            return tropoCorr;
        };

        /// Method to get the ionospheric corrections.
        double getIonoCorrections(IonoModelStore *pIonoModel, DayTime Tr, Geodetic rxGeo, double elevation, double azimuth) throw()
        {
            double ionoCorr = 0.0;
            try {
                ionoCorr = pIonoModel->getCorrection(Tr, rxGeo, elevation, azimuth);
            }
            catch(IonoModelStore::NoIonoModelFound& e) {
                ionoCorr = 0.0;
            }
            return ionoCorr;
        };

        /// Method to get TGD corrections.
        double getTGDCorrections(DayTime Tr, const EphemerisStore& Eph, SatID sat) throw()
        {

            double TGDCorr = 0.0;

            try {
                TGDCorr = (Eph.getTGD(sat, Tr));
            }
            catch(EphemerisStore::NoTGDFound& e) {
                TGDCorr = 0.0;
            }
            return TGDCorr;
        };

        /// Method to get satellite elevation cut-off angle. By default, it is set to 10 degrees.
        double getMinElev()
        {
           return minElev;
        };

        /// Method to set satellite elevation cut-off angle. By default, it is set to 10 degrees.
        void setMinElev(double newElevation)
        {
           minElev = newElevation;
        };

   }; // class ModeledReferencePR

   //@}

} // namespace

#endif
<commit_msg>Added new constructor, members and methods to ModeledReferencePR in order to adapt it to GNSS data structures.<commit_after>/**
 * @file ModeledReferencePR.hpp
 * Class to compute modeled pseudoranges using a reference station
 */

#ifndef GPSTK_MODELEDREFERENCEPR_HPP
#define GPSTK_MODELEDREFERENCEPR_HPP

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published
//  by the Free Software Foundation; either version 2.1 of the License, or
//  any later version.
//
//  The GPSTk is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Dagoberto Salazar - gAGE. 2006
//
//============================================================================

#include "ModeledPseudorangeBase.hpp"
#include "DayTime.hpp"
#include "EngEphemeris.hpp"
#include "EphemerisStore.hpp"
#include "EphemerisRange.hpp"
#include "TropModel.hpp"
#include "IonoModel.hpp"
#include "IonoModelStore.hpp"
#include "Geodetic.hpp"
#include "Position.hpp"
#include "icd_200_constants.hpp"

namespace gpstk
{
      /** @addtogroup GPSsolutions */
      //@{

      /**
       * This class compute modeled pseudoranges from satellites to a reference station.
       *
       * @sa ModeledPseudorangeBase.hpp for base class.
       *
       */
   class ModeledReferencePR : public ModeledPseudorangeBase
   {
    public:

        /// Implicit constructor
        ModeledReferencePR() throw(Exception) {
            InitializeValues();
        };

        /** Explicit constructor taking as input reference station coordinates.
         *
         * Those coordinates may be Cartesian (X, Y, Z in meters) or Geodetic
         * (Latitude, Longitude, Altitude), but defaults to Cartesian.
         *
         * Also, a pointer to GeoidModel may be specified, but default is NULL
         * (in which case WGS84 values will be used).
         *
         * @param aRx   first coordinate [ X(m), or latitude (degrees N) ]
         * @param bRx   second coordinate [ Y(m), or longitude (degrees E) ]
         * @param cRx   third coordinate [ Z, height above ellipsoid or radius, in m ]
         * @param s     coordinate system (default is Cartesian, may be set to Geodetic).
         * @param geoid pointer to GeoidModel (default is null, implies WGS84)
         */
        ModeledReferencePR(double aRx, double bRx, double cRx,
            Position::CoordinateSystem s = Position::Cartesian,
            GeoidModel *geoid = NULL) throw(Exception)
        {
            InitializeValues();
            setInitialRxPosition(aRx, bRx, cRx, s, geoid);
        };

        /// Explicit constructor, taking as input a Position object containing reference station coordinates.
        ModeledReferencePR(Position RxCoordinates) throw(Exception) {
            InitializeValues();
            setInitialRxPosition(RxCoordinates);
        };

        /** Explicit constructor, taking as input a Position object containing reference
         * station coordinates.
         * @param dIonoModel    Ionospheric model to be used by default.
         * @param dTropoModel   Tropospheric model to be used by default.
         */
        ModeledReferencePR(Position RxCoordinates, IonoModelStore& dIonoModel, TropModel& dTropoModel) throw(Exception) {
            InitializeValues();
            setInitialRxPosition(RxCoordinates);
            setDefaultIonoModel(dIonoModel);
            setDefaultTropoModel(dTropoModel);
        };

        /** Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
         * @param Tr            Measured time of reception of the data.
         * @param Satellite     Vector of satellites; on successful return, satellites that
         *                      were excluded by the algorithm are marked by a negative
         *                      Satellite[i].prn
         * @param Pseudorange   Vector of raw pseudoranges (parallel to satellite), in meters.
         * @param Eph           EphemerisStore to be used.
         * @param pTropModel    Pointer to tropospheric model to be used. By default points to NULL.
         * @param pIonoModel    Pointer to ionospheric model to be used. By default points to NULL.
         * @param extraBiases   Vector of extra biases to be added to the model.
         *
         * @return
         *  Number of satellites with valid data
         *
         * @sa TropModel.hpp, IonoModelStore.hpp.
         */
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, const Vector<double>& extraBiases, TropModel
            *pTropModel=NULL, IonoModelStore *pIonoModel=NULL) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, TropModel *pTropModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, const Vector<double>& extraBiases, IonoModelStore
            *pIonoModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, IonoModelStore *pIonoModel) throw(Exception);

        /// Compute the modeled pseudoranges, given satellite ID's, pseudoranges and other data
        int Compute(const DayTime& Tr, Vector<SatID>& Satellite, Vector<double>& Pseudorange,
            const EphemerisStore& Eph, TropModel *pTropModel, IonoModelStore *pIonoModel)
            throw(Exception);

        /** Compute just one modeled pseudorange, given satellite ID's, pseudorange and other data
         * @param Tr            Measured time of reception of the data.
         * @param Satellite     ID's of satellite
         * @param Pseudorange   Pseudorange (parallel to satellite), in meters.
         * @param Eph           EphemerisStore to be used.
         * @param pTropModel    Pointer to tropospheric model to be used. By default points to NULL.
         * @param pIonoModel    Pointer to ionospheric model to be used. By default points to NULL.
         * @param extraBiases   Extra bias to be added to the model.
         *
         * @return
         *  1 if satellite has valid data
         *
         * @sa TropModel.hpp, IonoModelStore.hpp.
         */
        int Compute(const DayTime& Tr, SatID& Satellite, double& Pseudorange,
            const EphemerisStore& Eph, const double& extraBiases, TropModel *pTropModel=NULL,
            IonoModelStore *pIonoModel=NULL) throw(Exception);

        /// Boolean variable indicating if SV instrumental delays (TGD) will be included  in results. It is true by default.
        bool useTGD;

        /// Destructor.
        virtual ~ModeledReferencePR() throw() {};

    protected:

        /// Pointer to default ionospheric model
        IonoModelStore *pDefaultIonoModel;

        /// Pointer to default tropospheric model
        TropModel *pDefaultTropoModel;

        /// Initialization method
        void InitializeValues() throw(Exception) {
            setInitialRxPosition();
            geometricRho(0);
            svClockBiases(0);
            svXvt(0);
            svTGD(0);
            svRelativity(0);
            ionoCorrections(0);
            tropoCorrections(0);
            modeledPseudoranges(0);
            prefitResiduals(0);
            extraBiases(0);
            availableSV(0);
            rejectedSV(0);
            useTGD = true;
            minElev = 10.0;  // By default, cut-off elevation is set to 10 degrees
            pDefaultIonoModel = NULL;
            pDefaultTropoModel = NULL;
        };

        /** Method to set the initial (a priori) position of receiver.
         * @return
         *  0 if OK
         *  -1 if problems arose
         */
        int setInitialRxPosition(double aRx, double bRx, double cRx,
            Position::CoordinateSystem s=Position::Cartesian,
            GeoidModel *geoid=NULL) throw(GeometryException)
        {
            try {
                Position rxpos(aRx, bRx, cRx, s, geoid);
                setInitialRxPosition(rxpos);
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to set the initial (a priori) position of receiver.
        int setInitialRxPosition(Position RxCoordinates) throw(GeometryException)
        {
            try {
                rxPos = RxCoordinates;
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to set the initial (a priori) position of receiver.
        int setInitialRxPosition() throw(GeometryException)
        {
            try {
                rxPos.setECEF(0.0, 0.0, 0.0);
                return 0;
            }
            catch(GeometryException& e) {
                return -1;
            }
        };

        /// Method to get the tropospheric corrections.
        double getTropoCorrections(TropModel *pTropModel, double elevation) throw()
        {
            double tropoCorr = 0.0;
            try {
                tropoCorr = pTropModel->correction(elevation);
                // Check validity
                if(!(pTropModel->isValid())) tropoCorr = 0.0;
            }
            catch(TropModel::InvalidTropModel& e) {
                tropoCorr = 0.0;
            }
            return tropoCorr;
        };

        /// Method to get the ionospheric corrections.
        double getIonoCorrections(IonoModelStore *pIonoModel, DayTime Tr, Geodetic rxGeo, double elevation, double azimuth) throw()
        {
            double ionoCorr = 0.0;
            try {
                ionoCorr = pIonoModel->getCorrection(Tr, rxGeo, elevation, azimuth);
            }
            catch(IonoModelStore::NoIonoModelFound& e) {
                ionoCorr = 0.0;
            }
            return ionoCorr;
        };

        /// Method to get TGD corrections.
        double getTGDCorrections(DayTime Tr, const EphemerisStore& Eph, SatID sat) throw()
        {

            double TGDCorr = 0.0;

            try {
                TGDCorr = (Eph.getTGD(sat, Tr));
            }
            catch(EphemerisStore::NoTGDFound& e) {
                TGDCorr = 0.0;
            }
            return TGDCorr;
        };

        /// Method to get satellite elevation cut-off angle. By default, it is set to 10 degrees.
        double getMinElev()
        {
           return minElev;
        };

        /// Method to set satellite elevation cut-off angle. By default, it is set to 10 degrees.
        void setMinElev(double newElevation)
        {
           minElev = newElevation;
        };

        /** Method to set the default ionospheric model.
         * @param dIonoModel    Ionospheric model to be used by default.
         */
        void setDefaultIonoModel(IonoModelStore& dIonoModel)
        {
           pDefaultIonoModel = &dIonoModel;
        };

        /** Method to set the default tropospheric model.
         * @param dTropoModel    Tropospheric model to be used by default.
         */
        void setDefaultTropoModel(TropModel& dTropoModel)
        {
           pDefaultTropoModel = &dTropoModel;
        };

        /** Method to set the default extra biases.
         * @param eBiases    Vector with the default extra biases
         */
        void setDefaultExtraBiases(Vector<double>& eBiases)
        {
           extraBiases = eBiases;
        };

   }; // class ModeledReferencePR

   //@}

} // namespace

#endif
<|endoftext|>


<commit_before>#include "internal.hpp"
#include "external.hpp"
#include "message.hpp"
#include "macros.hpp"

namespace CaDiCaL {

// The extension stack allows to reconstruct an assignment for the original
// formula after removing eliminated clauses.  This was pioneered by Niklas
// Soerensson in MiniSAT and for instance is described in our inprocessing
// paper, published at IJCAR'12.  This first function adds a clause to this
// stack.  First the blocking or eliminated literal is added, and then the
// rest of the clause.

void External::push_on_extension_stack (Clause * c, int pivot) {
  extension.push_back (0);
  const const_literal_iterator end = c->end ();
  const_literal_iterator l;
  extension.push_back (pivot);
  for (l = c->begin (); l != end; l++)
    if (*l != pivot) extension.push_back (*l);
}

// This is the actual extension process. It goes backward over the clauses
// on the extension stack and flips the assignment of the last literal found
// in a clause if the clause is falsified.

void External::extend () {
  START (extend);
  long flipped = 0;
  VRB ("extend",
    "mapping internal %d assignments to %d assignments",
    internal->max_var, max_var);
  for (int i = 1; i <= max_var; i++)
    vals[i] = internal->val (internalize (i));
  VRB ("extend",
    "extending through extension stack of size %ld",
    (long) extension.size ());
  const const_int_iterator begin = extension.begin ();
  const_int_iterator i = extension.end ();
  while (i != begin) {
    bool satisfied = false;
    int lit, last = 0;
    assert (i != begin);
    while ((lit = *--i)) {
      if (satisfied) continue;
      if (val (lit) > 0) satisfied = true;
      assert (i != begin);
      last = lit;
    }
    if (satisfied) continue;
    flipped++;
    assert (last);
    LOG ("flipping blocking literal %d", last);
    const int idx = vidx (last);
    const int tmp = sign (last);
    vals[idx] = tmp;
    vals[-idx] = -tmp;
  }
  VRB ("extend", "flipped %ld literals during extension", flipped);
  STOP (extend);
}

};
<commit_msg>fuzzing bugs gone too<commit_after>#include "internal.hpp"
#include "external.hpp"
#include "message.hpp"
#include "macros.hpp"

namespace CaDiCaL {

// The extension stack allows to reconstruct an assignment for the original
// formula after removing eliminated clauses.  This was pioneered by Niklas
// Soerensson in MiniSAT and for instance is described in our inprocessing
// paper, published at IJCAR'12.  This first function adds a clause to this
// stack.  First the blocking or eliminated literal is added, and then the
// rest of the clause.

void External::push_on_extension_stack (Clause * c, int pivot) {
  extension.push_back (0);
  const const_literal_iterator end = c->end ();
  const_literal_iterator l;
  extension.push_back (pivot);
  for (l = c->begin (); l != end; l++)
    if (*l != pivot) extension.push_back (*l);
}

// This is the actual extension process. It goes backward over the clauses
// on the extension stack and flips the assignment of the last literal found
// in a clause if the clause is falsified.

void External::extend () {
  START (extend);
  long flipped = 0;
  VRB ("extend",
    "mapping internal %d assignments to %d assignments",
    internal->max_var, max_var);
  for (int i = 1; i <= max_var; i++)
    vals[i] = internal->val (internalize (i));
  VRB ("extend",
    "extending through extension stack of size %ld",
    (long) extension.size ());
  const const_int_iterator begin = extension.begin ();
  const_int_iterator i = extension.end ();
  while (i != begin) {
    bool satisfied = false;
    int lit, last = 0;
    assert (i != begin);
    while ((lit = *--i)) {
      if (satisfied) continue;
      if (val (lit) > 0) satisfied = true;
      assert (i != begin);
      last = lit;
    }
    if (satisfied) continue;
    assert (last);
    LOG ("flipping blocking literal %d", last);
    vals[vidx (last)] = sign (last);
    flipped++;
  }
  VRB ("extend", "flipped %ld literals during extension", flipped);
  STOP (extend);
}

};
<|endoftext|>


<commit_before>/*
 *  SDLBackend.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Sun Oct 24 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#include "SDLBackend.h"
#include "SDL_gfxPrimitives.h"
#include "openc2e.h"
#include "Agent.h"

SDLBackend *g_backend;

void SoundSlot::play() {
	soundchannel = Mix_PlayChannel(-1, sound, 0);
}

void SoundSlot::playLooped() {
	soundchannel = Mix_PlayChannel(-1, sound, -1);
}

void SoundSlot::adjustPanning(int angle, int distance) {
	Mix_SetPosition(soundchannel, angle, distance);
}

void SoundSlot::fadeOut() {
	Mix_FadeOutChannel(soundchannel, 500); // TODO: is 500 a good value?
}

void SoundSlot::stop() {
	Mix_HaltChannel(soundchannel);
	sound = 0;
}

void SDLBackend::resizeNotify(int _w, int _h) {
	width = _w;
	height = _h;
	screen = SDL_SetVideoMode(width, height, 0, SDL_RESIZABLE);
	assert(screen != 0);
}

void SDLBackend::init(bool enable_sound) {
	int init = SDL_INIT_VIDEO;
	if (enable_sound) init |= SDL_INIT_AUDIO;

	if (SDL_Init(init) < 0) {
		std::cerr << "SDL init failed: " << SDL_GetError() << std::endl;
		assert(false);
	}

	if (!enable_sound) {
		std::cerr << "Sound disabled per user request." << std::endl;
		soundenabled = false;
	} else if (Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 4096) < 0) {
		std::cerr << "SDL_mixer init failed, disabling sound: " << Mix_GetError() << std::endl;
		soundenabled = false;
	} else soundenabled = true;

	resizeNotify(800, 600);

	SDL_WM_SetCaption("openc2e - Creatures 3 (development build)", "openc2e");
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
	SDL_ShowCursor(false);
}

SoundSlot *SDLBackend::getAudioSlot(std::string filename) {
	if (!soundenabled) return 0;

	unsigned int i = 0;

	while (i < nosounds) {
		if (sounddata[i].sound == 0) break;
		if (!Mix_Playing(sounddata[i].soundchannel)) {
			sounddata[i].sound = 0;
			if (sounddata[i].agent)
				sounddata[i].agent->soundslot = 0;
			break;
		}
		i++;
	}

	if (i == nosounds) return 0; // no free slots, so return

	sounddata[i].agent = 0;

	std::map<std::string, Mix_Chunk *>::iterator it = soundcache.find(filename);
	if (it != soundcache.end()) {
		sounddata[i].sound = (*it).second;
	} else {
		std::string fname = datapath + "/Sounds/" + filename + ".wav"; // TODO: case sensitivity stuff
		//std::cout << "trying to load " << fname << std::endl;
		sounddata[i].sound = Mix_LoadWAV(fname.c_str());
		if (!sounddata[i].sound) return 0; // TODO: spout error
		soundcache[filename] = sounddata[i].sound;
	}

	return &sounddata[i];
}

void SDLBackend::renderLine(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int colour) {
	aalineColor(screen, x1, y1, x2, y2, colour);
}

void SDLBackend::render(creaturesImage *image, unsigned int frame, unsigned int x, unsigned int y, bool trans, unsigned char transparency) {
	SDL_Surface *surf = SDL_CreateRGBSurfaceFrom(image->data(frame),
												 image->width(frame),
												 image->height(frame),
												 16, // depth
												 image->width(frame) * 2, // pitch
												 0xF800, 0x07E0, 0x001F, 0); // RGBA mask
	SDL_SetColorKey(surf, SDL_SRCCOLORKEY, 0);
	if (trans) SDL_SetAlpha(surf, SDL_SRCALPHA, 255 - transparency);
	SDL_Rect destrect;
	destrect.x = x; destrect.y = y;
	SDL_BlitSurface(surf, 0, screen, &destrect);
	SDL_FreeSurface(surf);
}

<commit_msg>remove Creatures 3 from the window title<commit_after>/*
 *  SDLBackend.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Sun Oct 24 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#include "SDLBackend.h"
#include "SDL_gfxPrimitives.h"
#include "openc2e.h"
#include "Agent.h"

SDLBackend *g_backend;

void SoundSlot::play() {
	soundchannel = Mix_PlayChannel(-1, sound, 0);
}

void SoundSlot::playLooped() {
	soundchannel = Mix_PlayChannel(-1, sound, -1);
}

void SoundSlot::adjustPanning(int angle, int distance) {
	Mix_SetPosition(soundchannel, angle, distance);
}

void SoundSlot::fadeOut() {
	Mix_FadeOutChannel(soundchannel, 500); // TODO: is 500 a good value?
}

void SoundSlot::stop() {
	Mix_HaltChannel(soundchannel);
	sound = 0;
}

void SDLBackend::resizeNotify(int _w, int _h) {
	width = _w;
	height = _h;
	screen = SDL_SetVideoMode(width, height, 0, SDL_RESIZABLE);
	assert(screen != 0);
}

void SDLBackend::init(bool enable_sound) {
	int init = SDL_INIT_VIDEO;
	if (enable_sound) init |= SDL_INIT_AUDIO;

	if (SDL_Init(init) < 0) {
		std::cerr << "SDL init failed: " << SDL_GetError() << std::endl;
		assert(false);
	}

	if (!enable_sound) {
		std::cerr << "Sound disabled per user request." << std::endl;
		soundenabled = false;
	} else if (Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 4096) < 0) {
		std::cerr << "SDL_mixer init failed, disabling sound: " << Mix_GetError() << std::endl;
		soundenabled = false;
	} else soundenabled = true;

	resizeNotify(800, 600);

	SDL_WM_SetCaption("openc2e (development build " __DATE__ ")", "openc2e");
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
	SDL_ShowCursor(false);
}

SoundSlot *SDLBackend::getAudioSlot(std::string filename) {
	if (!soundenabled) return 0;

	unsigned int i = 0;

	while (i < nosounds) {
		if (sounddata[i].sound == 0) break;
		if (!Mix_Playing(sounddata[i].soundchannel)) {
			sounddata[i].sound = 0;
			if (sounddata[i].agent)
				sounddata[i].agent->soundslot = 0;
			break;
		}
		i++;
	}

	if (i == nosounds) return 0; // no free slots, so return

	sounddata[i].agent = 0;

	std::map<std::string, Mix_Chunk *>::iterator it = soundcache.find(filename);
	if (it != soundcache.end()) {
		sounddata[i].sound = (*it).second;
	} else {
		std::string fname = datapath + "/Sounds/" + filename + ".wav"; // TODO: case sensitivity stuff
		//std::cout << "trying to load " << fname << std::endl;
		sounddata[i].sound = Mix_LoadWAV(fname.c_str());
		if (!sounddata[i].sound) return 0; // TODO: spout error
		soundcache[filename] = sounddata[i].sound;
	}

	return &sounddata[i];
}

void SDLBackend::renderLine(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int colour) {
	aalineColor(screen, x1, y1, x2, y2, colour);
}

void SDLBackend::render(creaturesImage *image, unsigned int frame, unsigned int x, unsigned int y, bool trans, unsigned char transparency) {
	SDL_Surface *surf = SDL_CreateRGBSurfaceFrom(image->data(frame),
												 image->width(frame),
												 image->height(frame),
												 16, // depth
												 image->width(frame) * 2, // pitch
												 0xF800, 0x07E0, 0x001F, 0); // RGBA mask
	SDL_SetColorKey(surf, SDL_SRCCOLORKEY, 0);
	if (trans) SDL_SetAlpha(surf, SDL_SRCALPHA, 255 - transparency);
	SDL_Rect destrect;
	destrect.x = x; destrect.y = y;
	SDL_BlitSurface(surf, 0, screen, &destrect);
	SDL_FreeSurface(surf);
}

<|endoftext|>