repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
ThomasDuverney/Nachos_Project
code/test/PutChar_Exit_0.c
<reponame>ThomasDuverney/Nachos_Project #include "syscall.h" /* Ecriture d'un caractère sur la sortie standard. */ int main() { PutChar('c'); Exit(0); }
ThomasDuverney/Nachos_Project
code/test/MutexCondition_0.c
#include "syscall.h" #define NB 2 /* * */ Cond_t cond; Mutex_t mutex; int checkNumber; void g(void *arg) { MutexLock(mutex); while(checkNumber <= 0){ PutInt(checkNumber); checkNumber++; CondWait(cond,mutex); PutInt(666); } checkNumber = checkNumber+5; CondSignal(cond); MutexUnlock(mutex); PutInt(89); } int main(){ int tab[NB]; int i; int tid[NB]; cond = CondCreate(); mutex = MutexCreate(); checkNumber = 0; for(i=0; i<NB; i++){ tab[i] = i; tid[i] = UserThreadCreate(g,(void*) (tab+i)); } for(i=0; i<NB; i++){ UserThreadJoin(tid[i]); } CondDestroy(cond); return 0; }
ThomasDuverney/Nachos_Project
code/test/ForkExec_1.c
<gh_stars>0 #include "syscall.h" int main(){ PutString(" * Le processus ForkExec_1 lancé par de_forkexecmulti démarre*\n"); ForkExec("PutString_0"); PutString(" *Le processus ForkExec_1 lancé par de_forkexecmulti termine*\n"); Exit(0); }
ThomasDuverney/Nachos_Project
code/test/ForkExec_4.c
#include "syscall.h" #define NB 5 Mutex_t mutex; void g(void *arg) { int i = 0; MutexLock(mutex); for( i = 0; i<NB; i++){ PutInt(*(int *)arg); } MutexUnlock(mutex); UserThreadExit(); } int main(){ int tab[NB]; int i; int tid[NB]; mutex = MutexCreate(); PutString("MainDebut"); ForkExec("ForkExec_3"); for(i=0; i<NB; i++){ tab[i] = i+5; tid[i] = UserThreadCreate(g,(void*) (tab+i)); } for(i=0; i<NB; i++){ UserThreadJoin(tid[i]); } PutString("MainFin"); MutexDestroy(mutex); return(0); }
ThomasDuverney/Nachos_Project
code/test/PutInt_1.c
<filename>code/test/PutInt_1.c #include "syscall.h" /* Ecriture de deux entiers sur la sortie standart */ int main(){ PutInt(0); PutInt(1); return 0; }
ThomasDuverney/Nachos_Project
code/userprog/addrspace.h
<reponame>ThomasDuverney/Nachos_Project // addrspace.h // Data structures to keep track of executing user programs // (address spaces). // // For now, we don't keep any information about address spaces. // The user level CPU state is saved and restored in the thread // executing the user program (see thread.h). // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef ADDRSPACE_H #define ADDRSPACE_H #include "copyright.h" #include "filesys.h" #include "bitmap.h" #include <map> #include <list> #define UserStackSize 4096 // increase this as necessary! #define NumPagesPerStack 2 // Nombre de pages allouées aux piles des threads utilisateur #define MainGuardOffset 16 // Une garde pour empêcher la pile du main de démarer à l'adresse de fin de l'espace d'adressage. class Thread; class AddrSpace { public: AddrSpace (OpenFile * executable); // Create an address space, // initializing it with the program // stored in the file "executable" ~AddrSpace (); // De-allocate an address space void InitRegisters (); // Initialize user-level CPU registers, // before jumping to user code void SaveState (); // Save/restore address space-specific void RestoreState (); // info on a context switch BitMap *stackBitmap; std::map<int, std::list<Thread*>* > *joinMap; std::list<int> *threadList; TranslationEntry * getPageTable(); unsigned int getNumPages(); void printJoinMap(); void printThreadList(); int getNbThread(); private: TranslationEntry * pageTable; // Assume linear page table translation // for now! unsigned int numPages; // Number of pages in the virtual // address space }; #endif // ADDRSPACE_H
ThomasDuverney/Nachos_Project
code/test/test_putInt.c
#include "syscall.h" // test PutInt avec passage de variables dans une fonction void printInt(int test){ int i = 27; PutInt(i); PutChar('\n'); PutInt(test); PutChar('\n'); } int main(){ int i = 35; PutInt(10); PutChar('\n'); PutInt(202000); PutChar('\n'); PutInt(i); PutChar('\n'); printInt(200); printInt(i); return 0; }
ThomasDuverney/Nachos_Project
code/test/Forkexec_call.c
#include "syscall.h" int main(){ PutChar('2'); ForkExec("PutChar_0"); return(0); }
ThomasDuverney/Nachos_Project
code/test/MultiThreadGetString_0.c
<reponame>ThomasDuverney/Nachos_Project #include "syscall.h" #define NB 5 /* * Création de plusieurs threads exécutant getString puis PutString. * On vérifie le bon fonctionnement des structures de synchronisation par * l'utilisation concurrente de synchconsole */ void g(void *arg) { char s[10]; GetString(s,10); PutString(s); UserThreadExit(); } int main(){ int tab[NB]; int i; int tid[NB]; for(i=0; i<NB; i++){ tab[i] = i; tid[i] = UserThreadCreate(g,(void*) (tab+i)); } for(i=0; i<NB; i++){ UserThreadJoin(tid[i]); } return 0; }
ThomasDuverney/Nachos_Project
code/test/UserThreadCreate_2.c
#include "syscall.h" #define NB 10 /* * Programme de test créant un nombre de thread supérieur au nombre de thread possible. * Ici 7 Threads sont crées, puis au huitième thread, il n'y a plus assez de place pour placer la pile * de ce thread en mémoire. La bitMap est pleine, la création du thread renvoie -1. * Chaque thread affiche son identifiant. */ void g(void *arg) { int n = *(int*) arg; PutString("Je suis le thread num "); PutInt(n); PutChar('\n'); } int main(){ int tab[NB]; int i, tid; for(i=0; i<NB; i++){ tab[i] = i; tid = UserThreadCreate(g,(void*) (tab+i)); PutString("ID du thread : "); PutInt(tid); PutChar('\n'); } for(; i<8; i++){ tab[i] = i; tid = UserThreadCreate(g,(void*) (tab+i)); PutString("ID du thread : "); PutInt(tid); PutChar('\n'); } return 0; }
ThomasDuverney/Nachos_Project
code/test/ForkExec_Multithread_Mutex.c
#include "syscall.h" int main(){ PutString("Début Main\n"); ForkExec("MultiThreadPutChar_Mutex_0"); ForkExec("MultiThreadPutChar_Mutex_0"); PutString("Fin Main\n"); Exit(0); }
ThomasDuverney/Nachos_Project
code/test/PutString_0.c
#include "syscall.h" /* Affichage d'une chaine de caractères sur la sortie standart. */ int main() { PutString(" **Le programme PutString lancé par ForkExec_1 démare**\n"); PutString(" **ABCDEFGHIJKLMNOPQRSTUVWXYZ**\n"); PutString(" **Le programme PutString lancé par ForkExec_1 termine**\n"); return(0); }
ThomasDuverney/Nachos_Project
code/test/GetString_1.c
#include "syscall.h" /* Lecture d'une chaine de caractères de moins de 20 caractères depuis l'entrée standard. Affichage de la chaîne. */ int main(){ char s[20]; GetString(s, 20); PutString(s); PutString("\n"); return 0; }
ThomasDuverney/Nachos_Project
code/test/UserThreadJoin_3.c
#include "syscall.h" #define NB 5 /* * Création de plusieurs threads exécutant putInt. * On vérifie le bon fonctionnement de UserThreadjoin * Deux join du main sur chaque thread crée. */ void g(void *arg) { PutInt(*(int *)arg); UserThreadExit(); } int main(){ int tab[NB]; int i; int tid[NB]; for(i=0; i<NB; i++){ tab[i] = i; tid[i] = UserThreadCreate(g,(void*) (tab+i)); } for(i=0; i<NB; i++){ UserThreadJoin(tid[i]); UserThreadJoin(tid[i]); } PutInt(127); return 0; }
ThomasDuverney/Nachos_Project
code/test/putstring.c
#include "syscall.h" int main() { char s[] = {"ABCDEFGHIJKLMNOPQ"}; PutString(s); Halt(); }
ThomasDuverney/Nachos_Project
code/test/Factoriel.c
#include "syscall.h" int factorial(int n){ if (n == 1) { return 1; } else { int step = factorial(n-1); return (n * step); } } int main() { int res = factorial(5); PutString(" *Début du processus factorielle*\n"); PutString(" *"); PutInt(res); PutString("*"); PutChar('\n'); PutString(" *Fin du processus factorielle*\n"); return 0; }
ThomasDuverney/Nachos_Project
code/test/putchar.c
#include "syscall.h" void print(char c, int n) { int i; for (i = 0; i < n; i++) { PutChar(c+i); } PutChar('\n'); } int main() { print('a',4); PutChar('\n'); PutChar('a'); return(0); }
ThomasDuverney/Nachos_Project
code/test/de_forkexecthreads.c
#include "syscall.h" int main(){ PutString("Début du processus forkexecthreads\n"); ForkExec("MultiThreadPutInt_Mutex_0"); PutString("Fin du processus forkexecthreads\n"); return(0); }
ThomasDuverney/Nachos_Project
code/test/test_PutInt_Thread.c
<gh_stars>0 #include "syscall.h" // test PutInt avec passage de variables dans une fonction void printInt(void * test){ int i = 27; PutInt(i); UserThreadExit(); } int main(){ int i = 200; PutInt(i); PutChar('\n'); UserThreadCreate(printInt, (void *) i); return 0; }
goldim/unistats
unistats/category_states.h
<reponame>goldim/unistats #pragma once #include <string> #include <map> // Qt #include <QtQml> #include <QVariantMap> // unistatscore #include <unistatscore/Config.h> #include <unistatscore/System.h> class CategoryState { public: virtual Criterion *getCriterion() = 0; virtual ~CategoryState() = default; }; class TermState : public CategoryState { public: TermState() = default; virtual Criterion *getCriterion() { return new TermCriterion(); } virtual ~TermState(){} }; class YearState : public CategoryState { public: YearState() = default; virtual Criterion *getCriterion() { return new YearCriterion(); } virtual ~YearState(){} }; class SubjectState : public CategoryState { public: SubjectState() = default; virtual Criterion *getCriterion() { return new SubjectCriterion(); } virtual ~SubjectState(){} }; class TeacherState : public CategoryState { public: TeacherState() = default; virtual Criterion *getCriterion() { return new TeacherCriterion(); } virtual ~TeacherState(){} }; class GroupState : public CategoryState { public: GroupState() = default; virtual Criterion *getCriterion() { return new GroupCriterion(); } virtual ~GroupState(){} }; class KursState : public CategoryState { public: KursState() = default; virtual Criterion *getCriterion() { return new KursCriterion(); } virtual ~KursState(){} }; class FacultyState : public CategoryState { public: FacultyState() = default; virtual Criterion *getCriterion() { return new FacultyCriterion(); } virtual ~FacultyState(){} }; class SpecialtyState : public CategoryState { public: SpecialtyState() = default; virtual Criterion *getCriterion() { return new SpecialtyCriterion(); } virtual ~SpecialtyState(){} }; class SpecializationState : public CategoryState { public: SpecializationState() = default; virtual Criterion *getCriterion() { return new SpecializationCriterion(); } virtual ~SpecializationState(){} }; class YearStartState : public CategoryState { public: YearStartState() = default; virtual Criterion *getCriterion() { return new YearStartCriterion(); } virtual ~YearStartState(){} }; class ExamOrderGroupState : public CategoryState { public: ExamOrderGroupState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderGroupCriterion(_order); } virtual ~ExamOrderGroupState(){} private: int _order; }; class ExamOrderYearState : public CategoryState { public: ExamOrderYearState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderYearCriterion(_order); } virtual ~ExamOrderYearState(){} private: int _order; }; class ExamOrderTermState : public CategoryState { public: ExamOrderTermState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderTermCriterion(_order); } virtual ~ExamOrderTermState(){} private: int _order; }; class ExamOrderKursState : public CategoryState { public: ExamOrderKursState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderKursCriterion(_order); } virtual ~ExamOrderKursState(){} private: int _order; }; class ExamOrderFacultyState : public CategoryState { public: ExamOrderFacultyState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderFacultyCriterion(_order); } virtual ~ExamOrderFacultyState(){} private: int _order; }; class ExamOrderSpecialtyState : public CategoryState { public: ExamOrderSpecialtyState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderSpeacialtyCriterion(_order); } virtual ~ExamOrderSpecialtyState(){} private: int _order; }; class ExamOrderSpecializationState : public CategoryState { public: ExamOrderSpecializationState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderSpecializationCriterion(_order); } virtual ~ExamOrderSpecializationState(){} private: int _order; }; class ExamOrderYearStartState : public CategoryState { public: ExamOrderYearStartState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderYearStartCriterion(_order); } virtual ~ExamOrderYearStartState(){} private: int _order; }; class ExamOrderSubjectState : public CategoryState { public: ExamOrderSubjectState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderSubjectCriterion(_order); } virtual ~ExamOrderSubjectState(){} private: int _order; }; class ExamOrderTeacherState : public CategoryState { public: ExamOrderTeacherState(int order):_order(order){} virtual Criterion *getCriterion() { return new ExamOrderTeacherCriterion(_order); } virtual ~ExamOrderTeacherState(){} private: int _order; };
goldim/unistats
MathStats/point.h
<filename>MathStats/point.h #pragma once namespace stats { template<typename __X = double, typename __Y = double> struct Point { Point() = default; inline Point(__X _x, __Y _y){ x = _x; y = _y; } __X x; __Y y; }; }
goldim/unistats
unistatscore/defs.h
#pragma once #include <vector> #include <string> #include <map> struct IdValStruct { std::string id; // long long id; double value; }; //using idNameMap_t = std::map<long long, std::string>; using idNameMap_t = std::map<std::string, std::string>; using idValueMap_t = std::vector<IdValStruct>; using values_t = std::vector<double>; using ids_t = std::vector<std::string>; #include <memory> #include <cassert> #include <algorithm> template<typename __TY = int, typename __TVAL = double> class Grid { public: Grid(unsigned n, unsigned m): _rowNames(n), _columnNames(m) { _values = new __TVAL[n][m]; } void addRow(const std::string &y) { _rowNames.push_back(y); } void addColumn(const __TY &x) { _columnNames.push_back(x); } void setValue(unsigned y, unsigned x, const __TVAL &value) { _values[y][x] = value; } __TVAL getValue(const std::string &x, const __TY &y) const { } void setValue(const std::string &x, const __TY &y, const __TVAL &value) { if (!XExists(x)) _rowNames.push_back(x); if (!YExists(y)) _columnNames.push_back(y); } bool XExists(const std::string &x) const { return std::find(_columnNames.begin(), _columnNames.end(), x) != _columnNames.end(); } bool YExists(const __TY &y) const { return std::find(_rowNames.begin(), _rowNames.end(), y) != _rowNames.end(); } unsigned getRowCount(){ return _rowNames.size(); } unsigned getColumnCount(){ return _columnNames.size(); } protected: std::unique_ptr<__TVAL> _values; std::vector<std::string> _rowNames; std::vector<__TY> _columnNames; };
goldim/unistats
unistatscore/perfomance.h
<filename>unistatscore/perfomance.h #pragma once // STL #include <map> #include <string> #include <vector> #include <memory> #include "defs.h" #include <MathStats/correlation.h> #include <StorageStats/Config.h> #include <StorageStats/storage.h> class Perfomance { public: struct CorrelationInfo { std::map<std::string, stats::TimeSeries> _points; stats::MeanCorrelation::Matrix _mtx; }; struct Trends { std::map<std::string, std::array<double, 2>> y; int x0; int x1; }; Perfomance() = default; Perfomance(const Config &cfg); inline void setX(DomainFilter timeseries){ _conditions.timeseries = timeseries; _storage.set(_conditions); } inline void setY(DomainFilter category){ _conditions.category = category; _storage.set(_conditions); } inline void setGroupClass(int klass){ _conditions.klass = klass; _storage.set(_conditions); } inline void setExam(int order){ _conditions.exam = order; _storage.set(_conditions); } //general idNameMap_t getItems(); std::vector<int> getGroupClasses(); //statistics struct Statistics { std::string conclusion; stats::Sample sample; }; stats::Range getRange(const ids_t &ids) const; Statistics getStatistics(const ids_t &ids) const; idNameMap_t getSpecialties(const std::string &facName) const; //time series stats::TimeSeries getPerfomance(const ids_t &ids); stats::TimeSeries getPerfomanceFromStore(const ids_t &ids); Trends trends(const ids_t &ids); CorrelationInfo correlation(const ids_t &ids); double correlation2(const ids_t &ids); double autocorrelation(const ids_t &ids); std::string FTest2(const ids_t &ids); private: stats::Sample getCommonSampleInternal(const idValueMap_t &values) const; std::vector<stats::Sample> getSamplesById(const idValueMap_t &values) const; private: Conditions _conditions; Storage _storage; };
goldim/unistats
StorageStats/rdb_impl.h
<filename>StorageStats/rdb_impl.h #pragma once // STL #include <iostream> #include <memory> // Qt #include <QtSql> // local #include "rdb.h" class RDBValue : public IRDBValue { public: RDBValue() = default; RDBValue(const QVariant &val); virtual int toInt(); virtual long long toLongLong(); virtual double toDouble(); virtual std::string toStdString(); virtual ~RDBValue() = default; private: QVariant _val; }; class RDB : public IRDB { public: RDB(const std::string &filename); virtual void select(){} virtual void insert(){} virtual void update(){} virtual void del(){} virtual void request(const char *sql); virtual bool next(); virtual std::unique_ptr<IRDBValue> get(int column) const; virtual ~RDB(); private: QSqlDatabase _db; QSqlQuery _query; };
goldim/unistats
StorageStats/query.h
<reponame>goldim/unistats #pragma once #include "category_catalog.h" struct Conditions { DomainFilter category; DomainFilter timeseries = DomainFilter::dfYears; int klass = 0; int exam = 0; }; class Query { public: Query() = default; Query(const Conditions &conditions); std::string getSQL(const CategoryCatalog &ctlg); Conditions _conditions; protected: };
goldim/unistats
unistats/controller.h
#pragma once // Qt #include <QObject> #include <QString> #include <QVariantMap> #include <QtQml> // unistatscore #include <unistatscore/Config.h> #include <unistatscore/perfomance.h> class controller : public QObject { Q_OBJECT public: controller(const Config &cfg, QObject *parent = 0); private: Perfomance _perf; static std::map<QString, DomainFilter> _domains; signals: public slots: QVariantMap loadItems(); QVariantMap loadSpecialties(QString facName); QVariantMap getRangeChart(QVariantList chosenItems); QVariantMap getTimeChart(QVariantList chosenItems); QVariantMap getStats(QVariantList chosenItems); QVariantMap correlation(QVariantList chosenItems); QVariantMap trends(QVariantList chosenItems); QString getAnova2(QVariantList chosenItems); QVariantList getGroupClasses(); void setOrder(int order); void setCriterion(QString criterion); void setDomain(QString domain); void setGroupClass(QString klass); void save(QString text); };
goldim/unistats
StorageStats/rdbfactory_impl.h
<reponame>goldim/unistats #pragma once #include <memory> #include "rdbfactory.h" class RDBFactory : public IRDBFactory { public: RDBFactory() = default; RDBFactory(const std::string &filename); virtual std::unique_ptr<IRDB> createRDB(); virtual std::unique_ptr<IRDBValue> createRDBValue(); virtual ~RDBFactory() = default; private: std::string _filename; };
goldim/unistats
MathStats/sample_builder.h
#pragma once #include <map> #include "sample.h" namespace stats { class PerfomanceSampleBuilder { public: PerfomanceSampleBuilder() = default; void add(int name, unsigned m, unsigned n); std::map<int, PerfomanceSample> build(); private: std::map<int, PerfomanceSample> _samples; }; }// stats
goldim/unistats
StorageStats/domain_filter.h
<filename>StorageStats/domain_filter.h #pragma once enum class DomainFilter { dfNone, dfFaculties, dfSpecialties, dfSpecializations, dfStartYears, dfTeachers, dfSubjects, dfTerms, dfKurs, dfYears, dfGroups, dfExamOrder };
goldim/unistats
StorageStats/storage.h
#pragma once #include <vector> #include "defs.h" #include "rdb.h" #include "category_catalog.h" #include "query.h" class Storage { public: Storage(const Config &cfg); struct ID { std::string id; std::string name; }; struct Item { std::string id; int success; int all; }; inline void set(Conditions c){ _conditions = c; } std::vector<ID> getIDs(); std::vector<ID> getIDsByID(DomainFilter category, const std::string &id) const; std::vector<int> getKlasses(); std::vector<Item> getItems(const ids_t &ids, bool bTimeSeries = false) const; private: std::vector<Item> examTimeSeries() const; std::vector<Item> examPostProcess() const; private: std::shared_ptr<IRDB> _db; CategoryCatalog _catalog; Conditions _conditions; // Query _lastquery; };
goldim/unistats
StorageStats/rdb.h
#pragma once #include <memory> class IRDBValue { public: virtual int toInt() = 0; virtual long long toLongLong() = 0; virtual double toDouble() = 0; virtual std::string toStdString() = 0; virtual ~IRDBValue() = default; }; class IRDB { public: enum class Types{ INT, DOUBLE, TEXT, LONGLONG }; virtual void select() = 0; virtual void insert() = 0; virtual void update() = 0; virtual void del() = 0; virtual void request(const char *sql) = 0; virtual bool next() = 0; virtual std::unique_ptr<IRDBValue> get(int column) const = 0; virtual ~IRDB() = default; };
goldim/unistats
StorageStats/Config.h
<filename>StorageStats/Config.h /* * Config.h * * Created on: 07.01.2017 * Author: goldim */ #pragma once #include <boost/property_tree/ptree.hpp> #include <string> class ptree; class Config { public: Config(const std::string &path); ~Config() = default; std::string get(const std::string &key) const; std::string get(const std::string &key, const std::string &defVal) const; std::string get(const std::string &section, const std::string &key, const std::string &defVal) const; void set(const std::string &key, const std::string &value); private: std::string _Path; boost::property_tree::ptree _Tree; };
goldim/unistats
MathStats/range.h
<gh_stars>0 /* * RangeBuilder.h * * Created on: 08.01.2017 * Author: goldim */ #pragma once #include <vector> namespace stats { struct Range { struct Interval { double left; double right; long n = 0; }; double min = 0.0; double max = 0.0; double h = 0; long n = 0; std::vector<Interval> _Intervals; }; }// stats
goldim/unistats
MathStats/sample.h
<filename>MathStats/sample.h /* * Accumulator.h * * Created on: 10.01.2017 * Author: goldim */ #pragma once //local #include "range.h" //boost #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics.hpp> namespace stats { using values_t = std::vector<double>; class SampleBase { public: SampleBase() = default; inline values_t getElements() const { return _elements; } inline long long getCount() const { return _n; } inline void setName(const std::string &name) { _name = name; } inline std::string getName() { return _name; } protected: values_t _elements; long long _n = 0; std::string _name; }; class Sample : public SampleBase { public: Sample() = default; Sample(const std::initializer_list<double> &elements); void add(double value); Range buildRange(); void refresh(); Sample sqr(); inline double getMean() const { return _mean; } inline double getVariance() const { return _variance; } inline double getKurtosis() const { return _kurtosis; } inline double getSkewness() const { return _skewness; } inline double getVariation() const { return _variation; } inline double getDeviation() const { return _deviation; } Sample operator+(const Sample &sample); Sample operator*(const Sample &sample); private: double _mean = 0.0; double _variance = 0.0; double _deviation = 0.0; double _kurtosis = 0.0; double _skewness = 0.0; double _variation = 0.0; boost::accumulators::accumulator_set<double, boost::accumulators::features< boost::accumulators::tag::count, boost::accumulators::tag::mean,//среднее арифметическое boost::accumulators::tag::variance,//дисперсия boost::accumulators::tag::kurtosis,//экцесс boost::accumulators::tag::skewness>>//ассиметрия _acc; }; class PerfomanceSample : public SampleBase { public: PerfomanceSample() = default; void add(double successful, double all); inline double getPerfomance() const { return _perfomance; } private: double _perfomance = 0.0; double _successful = 0.0; double _all = 0.0; values_t _successfulElements; values_t _allElements; }; using Samples = std::vector<Sample>; }
goldim/unistats
StorageStats/category_catalog.h
<reponame>goldim/unistats<filename>StorageStats/category_catalog.h #pragma once #include <memory> #include <map> #include <vector> #include "domain_filter.h" #include "Config.h" #include <iostream> class Category { public: Category(const Config &cfg, const std::string &section): _idField(cfg.get(section, "id", "")), _nameField(cfg.get(section, "title", _idField)), _table(cfg.get(section, "table_name", "")), _sortFields(cfg.get(section, "sort", "1")) { } inline std::string getID() const { return _idField; } inline std::string getName() const { return _nameField; } inline std::string getTable() const { return _table; } inline std::string getSortFields() const { return _sortFields; } protected: std::string _idField; std::string _nameField; std::string _table; std::string _sortFields; }; class CategoryCatalog { public: CategoryCatalog() = default; CategoryCatalog(const Config &cfg){ for (const DomainSection &section: _sections) { _categories[section.filter] = std::make_shared<Category>(cfg, section.section); } } std::shared_ptr<Category> getCategory(DomainFilter filter) const { return _categories.at(filter); } private: struct DomainSection{ DomainFilter filter; std::string section; }; static std::vector<DomainSection> _sections; std::map<DomainFilter, std::shared_ptr<Category>> _categories; };
goldim/unistats
StorageStats/rdbfactory.h
#pragma once // STL #include <memory> // local #include "rdb.h" class IRDBFactory { public: IRDBFactory() = default; virtual std::unique_ptr<IRDB> createRDB() = 0; virtual std::unique_ptr<IRDBValue> createRDBValue() = 0; virtual ~IRDBFactory() = default; };
goldim/unistats
MathStats/ols.h
#pragma once #include <vector> #include <memory> #include "point.h" namespace stats { class OLS { public: OLS(const std::vector<Point<>> &points); inline double getB() const { return _B; } inline double getC() const { return _C; } Point<> getStartPoint() const; Point<> getEndPoint() const; void apply(); protected: int _N; std::vector<double> _xVec; std::vector<double> _yVec; double _B; double _C; }; class WOLS: public OLS { public: WOLS(const std::vector<Point<>> &points):OLS(points){} void apply(); }; }
goldim/unistats
unistatscore/analyser.h
#pragma once #include <string> #include <sstream> #include <MathStats/sample.h> #include <MathStats/anova.h> namespace stats { class Analyser { public: Analyser(); void addSample(const Sample &params); void addAnova(Anova &anova); void addAnova2(TwoFactorAnova &anova); std::string getConclusion() { return _output.str(); } private: std::stringstream _output; }; }// stats
goldim/unistats
MathStats/correlation.h
#pragma once #include <map> #include <limits> #include "sample.h" #include "timeseries.h" namespace stats { class TwoFactorCorrelation { public: TwoFactorCorrelation(const Sample &x, const Sample &y); double getRegression(); private: Sample _x; Sample _y; }; class MeanCorrelation { public: using Matrix = std::map<std::string, std::map<std::string, double>>; MeanCorrelation() = default; Matrix getRegressionMatrix(const std::map<std::string, Sample> &samplesMap); private: int _min = 0; int _max = std::numeric_limits<int>::max(); Matrix _result; }; }// stats
goldim/unistats
StorageStats/defs.h
<filename>StorageStats/defs.h #pragma once #include <string> #include <vector> using values_t = std::vector<double>; using ids_t = std::vector<std::string>;
goldim/unistats
MathStats/timeseries.h
<filename>MathStats/timeseries.h #pragma once #include <vector> #include "point.h" namespace stats { class TimeSeries: public std::iterator<std::input_iterator_tag, int> { public: using Points = std::vector<Point<int>>; TimeSeries() = default; std::vector<int> getMoments() const; std::vector<int> getValues() const; inline Points getPoints() const { return _points; } void add(Point<int> p); void add(int moment, double value); bool isExist(int moment) const; /*-----------------Iterator Part----------------------*/ int size() const { return _points.size(); } Points::iterator begin() { return _points.begin(); } Points::iterator end() { return _points.end(); } Points::const_iterator begin() const { return _points.begin(); } Points::const_iterator end() const { return _points.end(); } private: Points _points; }; }
goldim/unistats
MathStats/anova.h
#pragma once #include <map> #include "sample.h" namespace stats { class Anova { public: inline int getV1() const { return _v1; } inline int getV2() const { return _v2; } inline double getFTestRes() const { return _F; } double FTest(const Samples &samples); double FCriticalTest(double alpha) const; private: int _v1 = 0; int _v2 = 0; double _F; }; class TwoFactorAnova { public: struct Result { double FA; double FB; double FAB; }; inline int getVA() const { return _Va; } inline int getVB() const { return _Vb; } inline int getV2() const { return _V2; } double FCriticalTestA(double alpha) const; double FCriticalTestB(double alpha) const; double FCriticalTestAB(double alpha) const; inline Result getFTestRes() const { return _F; } Result FTest(const Samples &samples); protected: double FcriticalTest(double alpha, int v1, int v2) const; private: int _Va = 0; int _Vb = 0; int _V2 = 0; Result _F; }; }
zhihuidu/zhihuidu
src/c_helpers/help_h5ls.c
/** * External C functions for simulating h5ls and processing HDF5 API objects/data. * HDF5 API passes void* data objects in between calls which can't be processed * directly in chapel, so you need C functions to handle opaque data objects. */ #include "c_helpers/help_h5ls.h" /** * C function to retrieve the HDF5 object type for a given object name */ herr_t c_get_HDF5_obj_type(hid_t loc_id, const char *name, H5O_type_t *obj_type) { herr_t status; H5O_info_t info_t; status = H5Oget_info_by_name(loc_id, name, &info_t, H5P_DEFAULT); *obj_type = info_t.type; return status; } /** * C helper function to increment a counter passed via void* */ void c_incrementCounter(void *data) { int i = *(int *)data; i = i + 1; *(int *)data = i; } /** * C helper function to wrap `strlen` */ size_t c_strlen(char *s) { return strlen(s); } /** * C helper function to append HDF5 fieldnames to a char* passed as void* */ void c_append_HDF5_fieldname(void *data, const char *name) { char *d = (char *)data; // Turn void* data into char* if (strlen(d) > 0) { strcat(d, ","); } strcat(d, name); }
aklomp/libsmbclient-php
php_libsmbclient.h
<filename>php_libsmbclient.h /* ------------------------------------------------------------------ * This file is part of libsmbclient-php: Samba bindings for PHP. * Libsmbclient-php is licensed under the BSD 2-clause license: * ------------------------------------------------------------------ * * Copyright (c) 2003, <NAME> * 2009 - 2014, <NAME> * 2013 - 2015, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * ------------------------------------------------------------------ */ #ifndef PHP_LIBSMBCLIENT_H #define PHP_LIBSMBCLIENT_H extern zend_module_entry libsmbclient_module_entry; #define phpext_libsmbclient_ptr &libsmbclient_module_entry typedef struct { } php_libsmbclient_globals; PHP_MINIT_FUNCTION(smbclient); PHP_MSHUTDOWN_FUNCTION(smbclient); PHP_RINIT_FUNCTION(smbclient); PHP_MINFO_FUNCTION(smbclient); PHP_FUNCTION(smbclient_version); PHP_FUNCTION(smbclient_library_version); PHP_FUNCTION(smbclient_state_new); PHP_FUNCTION(smbclient_state_init); PHP_FUNCTION(smbclient_state_errno); PHP_FUNCTION(smbclient_state_free); PHP_FUNCTION(smbclient_option_get); PHP_FUNCTION(smbclient_option_set); PHP_FUNCTION(smbclient_opendir); PHP_FUNCTION(smbclient_readdir); PHP_FUNCTION(smbclient_closedir); PHP_FUNCTION(smbclient_rename); PHP_FUNCTION(smbclient_unlink); PHP_FUNCTION(smbclient_mkdir); PHP_FUNCTION(smbclient_rmdir); PHP_FUNCTION(smbclient_stat); PHP_FUNCTION(smbclient_fstat); PHP_FUNCTION(smbclient_open); PHP_FUNCTION(smbclient_creat); PHP_FUNCTION(smbclient_read); PHP_FUNCTION(smbclient_write); PHP_FUNCTION(smbclient_lseek); PHP_FUNCTION(smbclient_ftruncate); PHP_FUNCTION(smbclient_close); PHP_FUNCTION(smbclient_chmod); PHP_FUNCTION(smbclient_utimes); PHP_FUNCTION(smbclient_listxattr); PHP_FUNCTION(smbclient_getxattr); PHP_FUNCTION(smbclient_setxattr); PHP_FUNCTION(smbclient_removexattr); PHP_FUNCTION(smbclient_statvfs); PHP_FUNCTION(smbclient_fstatvfs); /* If Zend Thread Safety (ZTS) is defined, each thread gets its own private * php_libsmbclient_globals structure, the elements of which it can access * through the LIBSMBCLIENT() macro. Without ZTS, there is just one master * structure in which we access the members directly: */ #ifdef ZTS #define LIBSMBCLIENT(v) TSRMG(libsmbclient_globals_id, php_libsmbclient_globals *, v) #else #define LIBSMBCLIENT(v) (libsmbclient_globals.v) #endif #endif /* PHP_LIBSMBCLIENT_H */
congleetea/fuse
fuse_core/include/fuse_core/constraint.h
<filename>fuse_core/include/fuse_core/constraint.h<gh_stars>0 /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_CONSTRAINT_H #define FUSE_CORE_CONSTRAINT_H #include <fuse_core/macros.h> #include <fuse_core/serialization.h> #include <fuse_core/uuid.h> #include <boost/serialization/access.hpp> #include <boost/serialization/vector.hpp> #include <boost/type_index/stl_type_index.hpp> #include <ceres/cost_function.h> #include <ceres/loss_function.h> #include <initializer_list> #include <ostream> #include <string> #include <vector> /** * @brief Implementation of the clone() member function for derived classes * * Usage: * @code{.cpp} * class Derived : public Constraint * { * public: * FUSE_CONSTRAINT_CLONE_DEFINITION(Derived); * // The rest of the derived constraint implementation * } * @endcode */ #define FUSE_CONSTRAINT_CLONE_DEFINITION(...) \ fuse_core::Constraint::UniquePtr clone() const override \ { \ return __VA_ARGS__::make_unique(*this); \ } /** * @brief Implementation of the serialize() and deserialize() member functions for derived classes * * Usage: * @code{.cpp} * class Derived : public Constraint * { * public: * FUSE_CONSTRAINT_SERIALIZE_DEFINITION(Derived); * // The rest of the derived constraint implementation * } * @endcode */ #define FUSE_CONSTRAINT_SERIALIZE_DEFINITION(...) \ void serialize(fuse_core::BinaryOutputArchive& archive) const override \ { \ archive << *this; \ } /* NOLINT */ \ void serialize(fuse_core::TextOutputArchive& archive) const override \ { \ archive << *this; \ } /* NOLINT */ \ void deserialize(fuse_core::BinaryInputArchive& archive) override \ { \ archive >> *this; \ } /* NOLINT */ \ void deserialize(fuse_core::TextInputArchive& archive) override \ { \ archive >> *this; \ } /** * @brief Implements the type() member function using the suggested implementation * * Also creates a static detail::type() function that may be used without an object instance * * Usage: * @code{.cpp} * class Derived : public Constraint * { * public: * FUSE_CONSTRAINT_TYPE_DEFINITION(Derived); * // The rest of the derived constraint implementation * } * @endcode */ #define FUSE_CONSTRAINT_TYPE_DEFINITION(...) \ struct detail \ { \ static std::string type() \ { \ return boost::typeindex::stl_type_index::type_id<__VA_ARGS__>().pretty_name(); \ } /* NOLINT */ \ }; /* NOLINT */ \ std::string type() const override \ { \ return detail::type(); \ } /** * @brief Convenience function that creates the required pointer aliases, clone() method, and type() method * * Usage: * @code{.cpp} * class Derived : public Constraint * { * public: * FUSE_CONSTRAINT_DEFINITIONS(Derived); * // The rest of the derived constraint implementation * } * @endcode */ #define FUSE_CONSTRAINT_DEFINITIONS(...) \ SMART_PTR_DEFINITIONS(__VA_ARGS__) \ FUSE_CONSTRAINT_TYPE_DEFINITION(__VA_ARGS__) \ FUSE_CONSTRAINT_CLONE_DEFINITION(__VA_ARGS__) \ FUSE_CONSTRAINT_SERIALIZE_DEFINITION(__VA_ARGS__) /** * @brief Convenience function that creates the required pointer aliases, clone() method, and type() method * for derived Constraint classes that have fixed-sized Eigen member objects. * * Usage: * @code{.cpp} * class Derived : public Constraint * { * public: * FUSE_CONSTRAINT_DEFINITIONS_WTIH_EIGEN(Derived); * // The rest of the derived constraint implementation * } * @endcode */ #define FUSE_CONSTRAINT_DEFINITIONS_WITH_EIGEN(...) \ SMART_PTR_DEFINITIONS_WITH_EIGEN(__VA_ARGS__) \ FUSE_CONSTRAINT_TYPE_DEFINITION(__VA_ARGS__) \ FUSE_CONSTRAINT_CLONE_DEFINITION(__VA_ARGS__) \ FUSE_CONSTRAINT_SERIALIZE_DEFINITION(__VA_ARGS__) namespace fuse_core { /** * @brief The Constraint interface definition. * * A Constraint defines a cost function that is connected to one or more variables. This base class defines the * required interface of all Constraint objects, and holds the ordered list of involved variable UUIDs. All other * functionality is left to the derived classes to implement. * * Most importantly, the implementation of the cost function is left to the derived classes, allowing arbitrarily * complex sensor models to be implemented outside of the core fuse packages. The cost function must be a valid * ceres::CostFunction object. Ceres provides many nice features to make implementing the cost function easier, * including an automatic differentiation system. Please see the Ceres documentation for details on creating valid * ceres::CostFunction objects (http://ceres-solver.org/nnls_modeling.html). In addition to the cost function itself, * an optional loss function may be provided. Loss functions provide a mechanism for reducing the impact of outlier * measurements on the final optimization results. Again, see the Ceres documentation for details * (http://ceres-solver.org/nnls_modeling.html#lossfunction). */ class Constraint { public: SMART_PTR_ALIASES_ONLY(Constraint); /** * @brief Default constructor */ Constraint() = default; /** * @brief Constructor * * Accepts an arbitrary number of variable UUIDs directly. It can be called like: * @code{.cpp} * Constraint("source", {uuid1, uuid2, uuid3}); * @endcode * * @param[in] variable_uuid_list The list of involved variable UUIDs */ Constraint(const std::string& source, std::initializer_list<UUID> variable_uuid_list); /** * @brief Constructor * * Accepts an arbitrary number of variable UUIDs stored in a container using iterators. */ template<typename VariableUuidIterator> Constraint(const std::string& source, VariableUuidIterator first, VariableUuidIterator last); /** * @brief Destructor */ virtual ~Constraint() = default; /** * @brief Returns a unique name for this constraint type. * * The constraint type string must be unique for each class. As such, the fully-qualified class name is an excellent * choice for the type string. */ virtual std::string type() const = 0; /** * @brief Returns the UUID for this constraint. * * Each constraint will generate a unique, random UUID during construction. */ const UUID& uuid() const { return uuid_; } /** * @brief Returns the name of the sensor or motion model that generated this constraint */ const std::string& source() const { return source_; } /** * @brief Print a human-readable description of the constraint to the provided stream. * * @param stream The stream to write to. Defaults to stdout. */ virtual void print(std::ostream& stream = std::cout) const = 0; /** * @brief Create a new Ceres cost function and return a raw pointer to it. * * The Ceres interface requires a raw pointer. Ceres will take ownership of the pointer and promises to properly * delete the cost function when it is done. Additionally, fuse promises that the Constraint object will outlive any * generated cost functions (i.e. the Ceres objects will be destroyed before the Constraint objects). This guarantee * may allow optimizations for the creation of the cost function objects. * * @return A base pointer to an instance of a derived ceres::CostFunction. */ virtual ceres::CostFunction* costFunction() const = 0; /** * @brief Create a new Ceres loss function and return a raw pointer to it. * * See http://ceres-solver.org/nnls_modeling.html#lossfunction for a detailed description about loss functions. * Basically, a loss function defines the penalty associated with a specific amount error. By default, or if a NULL * pointer is provided as the loss function, the penalty will be quadratic. This is the loss function associated * with standard least-squares optimization. By providing a different loss function, the penalty for the constraint's * error can be altered. * * This is generally done to reduce the effect of outlier measurements that made it into the optimization problem. * It is always better to remove outliers before they make it into the optimization problem, but no method is perfect. * Using robust loss functions can significantly improve the results and stability of the solution in the presence * of outlier measurements. * * The Ceres interface requires a raw pointer. Ceres will take ownership of the pointer and promises to properly * delete the loss function when it is done. Additionally, Fuse promises that the Constraint object will outlive any * generated loss functions (i.e. the Ceres objects will be destroyed before the Constraint objects). This guarantee * may allow optimizations for the creation of the loss function objects. * * @return A base pointer to an instance of a derived ceres::LostFunction. */ virtual ceres::LossFunction* lossFunction() const { return nullptr; } /** * @brief Perform a deep copy of the Constraint and return a unique pointer to the copy * * This can/should be implemented as follows in all derived classes: * @code{.cpp} * return Derived::make_unique(*this); * @endcode * * @return A unique pointer to a new instance of the most-derived Constraint */ virtual Constraint::UniquePtr clone() const = 0; /** * @brief Read-only access to the ordered list of variable UUIDs involved in this constraint */ const std::vector<UUID>& variables() const { return variables_; } /** * @brief Serialize this Constraint into the provided binary archive * * This can/should be implemented as follows in all derived classes: * @code{.cpp} * archive << *this; * @endcode * * @param[out] archive - The archive to serialize this constraint into */ virtual void serialize(fuse_core::BinaryOutputArchive& /* archive */) const = 0; /** * @brief Serialize this Constraint into the provided text archive * * This can/should be implemented as follows in all derived classes: * @code{.cpp} * archive << *this; * @endcode * * @param[out] archive - The archive to serialize this constraint into */ virtual void serialize(fuse_core::TextOutputArchive& /* archive */) const = 0; /** * @brief Deserialize data from the provided binary archive into this Constraint * * This can/should be implemented as follows in all derived classes: * @code{.cpp} * archive >> *this; * @endcode * * @param[in] archive - The archive holding serialized Constraint data */ virtual void deserialize(fuse_core::BinaryInputArchive& /* archive */) = 0; /** * @brief Deserialize data from the provided text archive into this Constraint * * This can/should be implemented as follows in all derived classes: * @code{.cpp} * archive >> *this; * @endcode * * @param[in] archive - The archive holding serialized Constraint data */ virtual void deserialize(fuse_core::TextInputArchive& /* archive */) = 0; private: std::string source_; //!< The name of the sensor or motion model that generated this constraint UUID uuid_; //!< The unique ID associated with this constraint std::vector<UUID> variables_; //!< The ordered set of variables involved with this constraint // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * This method, or a combination of save() and load() methods, must be implemented by all derived classes. See * documentation on Boost Serialization for information on how to implement the serialize() method. * https://www.boost.org/doc/libs/1_70_0/libs/serialization/doc/ * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & source_; archive & uuid_; archive & variables_; } }; /** * Stream operator implementation used for all derived Constraint classes. */ std::ostream& operator <<(std::ostream& stream, const Constraint& constraint); template<typename VariableUuidIterator> Constraint::Constraint(const std::string& source, VariableUuidIterator first, VariableUuidIterator last) : source_(source), uuid_(uuid::generate()), variables_(first, last) { } } // namespace fuse_core #endif // FUSE_CORE_CONSTRAINT_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/uuid_ordering.h
<reponame>congleetea/fuse /* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_UUID_ORDERING_H #define FUSE_CONSTRAINTS_UUID_ORDERING_H #include <fuse_core/uuid.h> #include <boost/bimap/bimap.hpp> #include <boost/bimap/unordered_set_of.hpp> #include <boost/bimap/vector_of.hpp> namespace fuse_constraints { /** * @brief A class that represents a sequential ordering of UUIDs * * This is designed for use when marginalizing out variables, but it may have other uses. * * Specifically, this class maps a UUID to a sequential index. Bidirectional access is possible. * If you have a UUID, the index can be retrieved in constant time. And if you have the index, the UUID * may be retrieved in constant (and fast) time. Also, iterating through the UUIDs in sequence is an * efficient operation. * * The UuidOrdering is not designed to be highly dynamic. UUIDs can be added, but not removed. UUIDs are * assigned an index based on the order of insertion and cannot be modified. */ class UuidOrdering { public: /** * @brief Default constructor */ UuidOrdering() = default; /** * @brief Construct a UuidOrdering with the provided UUIDs * * Accepts an arbitrary number of UUIDs directly. It can be called like: * @code{.cpp} * UuidOrdering{uuid1, uuid2, uuid3}; * @endcode * * @param[in] uuid_list The list of involved UUIDs */ UuidOrdering(std::initializer_list<fuse_core::UUID> uuid_list); /** * @brief Construct a UuidOrdering with the UUIDs from the provided collection * * The \p UuidConstIterator class must meet the ForwardIterator requirements, and when dereferenced must * be compatible with a \p const fuse_core::UUID&. * * @param[in] first Iterator pointing to the first UUID to add to the ordering * @param[in] last Iterator pointing to one past the last UUID to add to the ordering */ template <typename UuidConstIterator> UuidOrdering(UuidConstIterator first, UuidConstIterator last); /** * @brief Returns true if there are no UUIDs in this ordering */ bool empty() const; /** * @brief Returns the number of UUIDs in this ordering * * This is always equal to "last index + 1" */ size_t size() const; /** * @brief Return true if the index exists in the ordering */ bool exists(const unsigned int index) const; /** * @brief Return true if the UUID exists in the ordering */ bool exists(const fuse_core::UUID& uuid) const; /** * @brief Add a new UUID to the back of the ordering * * If the UUID already exists, no change to the ordering will occur. * * @param[in] uuid The UUID to insert * @return True if the UUID was inserted, false if the UUID already existed */ bool push_back(const fuse_core::UUID& uuid); /** * @brief Access the UUID stored at the provided index * * Accessing an index that does not exist results in undefined behavior */ const fuse_core::UUID& operator[](const unsigned int index) const; /** * @brief Access the index associated with the provided UUID * * Accessing a UUID that does not exist results in the provided UUID being added to the ordering */ unsigned int operator[](const fuse_core::UUID& uuid); /** * @brief Access the UUID stored at the provided index * * If the requested index does not exist, an out_of_range exception will be thrown. */ const fuse_core::UUID& at(const unsigned int index) const; /** * @brief Access the index associated with the provided UUID * * If the requested UUID does not exist, an out_of_range exception will be thrown. */ unsigned int at(const fuse_core::UUID& uuid) const; private: using UuidOrderMapping = boost::bimaps::bimap<boost::bimaps::vector_of<unsigned int>, boost::bimaps::unordered_set_of<fuse_core::UUID>>; UuidOrderMapping order_; //!< Collection that contains the Index<-->UUID mapping }; template <typename UuidConstIterator> UuidOrdering::UuidOrdering(UuidConstIterator first, UuidConstIterator last) { for (; first != last; ++first) { order_.insert(order_.end(), UuidOrderMapping::value_type(order_.size(), *first)); } } } // namespace fuse_constraints #endif // FUSE_CONSTRAINTS_UUID_ORDERING_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/relative_constraint_impl.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_RELATIVE_CONSTRAINT_IMPL_H #define FUSE_CONSTRAINTS_RELATIVE_CONSTRAINT_IMPL_H #include <fuse_constraints/normal_delta.h> #include <fuse_constraints/normal_delta_orientation_2d.h> #include <Eigen/Dense> #include <string> #include <vector> namespace fuse_constraints { template<class Variable> RelativeConstraint<Variable>::RelativeConstraint( const std::string& source, const Variable& variable1, const Variable& variable2, const fuse_core::VectorXd& delta, const fuse_core::MatrixXd& covariance) : fuse_core::Constraint(source, {variable1.uuid(), variable2.uuid()}), // NOLINT(whitespace/braces) delta_(delta), sqrt_information_(covariance.inverse().llt().matrixU()) { assert(variable1.size() == variable2.size()); assert(delta.rows() == static_cast<int>(variable1.size())); assert(covariance.rows() == static_cast<int>(variable1.size())); assert(covariance.cols() == static_cast<int>(variable1.size())); } template<class Variable> RelativeConstraint<Variable>::RelativeConstraint( const std::string& source, const Variable& variable1, const Variable& variable2, const fuse_core::VectorXd& partial_delta, const fuse_core::MatrixXd& partial_covariance, const std::vector<size_t>& indices) : fuse_core::Constraint(source, {variable1.uuid(), variable2.uuid()}) // NOLINT(whitespace/braces) { assert(variable1.size() == variable2.size()); assert(partial_delta.rows() == static_cast<int>(indices.size())); assert(partial_covariance.rows() == static_cast<int>(indices.size())); assert(partial_covariance.cols() == static_cast<int>(indices.size())); // Compute the sqrt information of the provided cov matrix fuse_core::MatrixXd partial_sqrt_information = partial_covariance.inverse().llt().matrixU(); // Assemble a mean vector and sqrt information matrix from the provided values, but in proper Variable order // What are we doing here? // The constraint equation is defined as: cost(x) = ||A * (x1 - x0 - b)||^2 // If we are measuring a subset of dimensions, we only want to produce costs for the measured dimensions. // But the variable vectors will be full sized. We can make this all work out by creating a non-square A // matrix, where each row computes a cost for one measured dimensions, and the columns are in the order // defined by the variable. delta_ = fuse_core::VectorXd::Zero(variable1.size()); sqrt_information_ = fuse_core::MatrixXd::Zero(indices.size(), variable1.size()); for (size_t i = 0; i < indices.size(); ++i) { delta_(indices[i]) = partial_delta(i); sqrt_information_.col(indices[i]) = partial_sqrt_information.col(i); } } template<class Variable> fuse_core::MatrixXd RelativeConstraint<Variable>::covariance() const { // We want to compute: // cov = (sqrt_info' * sqrt_info)^-1 // With some linear algebra, we can swap the transpose and the inverse. // cov = (sqrt_info^-1) * (sqrt_info^-1)' // But sqrt_info _may_ not be square. So we need to compute the pseudoinverse instead. // Eigen doesn't have a pseudoinverse function (for probably very legitimate reasons). // So we set the right hand side to identity, then solve using one of Eigen's many decompositions. auto I = fuse_core::MatrixXd::Identity(sqrt_information_.rows(), sqrt_information_.cols()); fuse_core::MatrixXd pinv = sqrt_information_.colPivHouseholderQr().solve(I); return pinv * pinv.transpose(); } template<class Variable> void RelativeConstraint<Variable>::print(std::ostream& stream) const { stream << type() << "\n" << " source: " << source() << "\n" << " uuid: " << uuid() << "\n" << " variable1: " << variables().at(0) << "\n" << " variable2: " << variables().at(1) << "\n" << " delta: " << delta().transpose() << "\n" << " sqrt_info: " << sqrtInformation() << "\n"; } template<class Variable> ceres::CostFunction* RelativeConstraint<Variable>::costFunction() const { // Create a Gaussian/Normal Delta constraint return new fuse_constraints::NormalDelta(sqrt_information_, delta_); } // Specialization for Orientation2D template<> inline ceres::CostFunction* RelativeConstraint<fuse_variables::Orientation2DStamped>::costFunction() const { // Create a Gaussian/Normal Delta constraint return new NormalDeltaOrientation2D(sqrt_information_(0, 0), delta_(0)); } // Specialize the type() method to return the name that is registered with the plugins template<> inline std::string RelativeConstraint<fuse_variables::AccelerationAngular2DStamped>::type() const { return "fuse_constraints::RelativeAccelerationAngular2DStampedConstraint"; } template<> inline std::string RelativeConstraint<fuse_variables::AccelerationLinear2DStamped>::type() const { return "fuse_constraints::RelativeAccelerationLinear2DStampedConstraint"; } template<> inline std::string RelativeConstraint<fuse_variables::Orientation2DStamped>::type() const { return "fuse_constraints::RelativeOrientation2DStampedConstraint"; } template<> inline std::string RelativeConstraint<fuse_variables::Position2DStamped>::type() const { return "fuse_constraints::RelativePosition2DStampedConstraint"; } template<> inline std::string RelativeConstraint<fuse_variables::Position3DStamped>::type() const { return "fuse_constraints::RelativePosition3DStampedConstraint"; } template<> inline std::string RelativeConstraint<fuse_variables::VelocityAngular2DStamped>::type() const { return "fuse_constraints::RelativeVelocityAngular2DStampedConstraint"; } template<> inline std::string RelativeConstraint<fuse_variables::VelocityLinear2DStamped>::type() const { return "fuse_constraints::RelativeVelocityLinear2DStampedConstraint"; } } // namespace fuse_constraints #endif // FUSE_CONSTRAINTS_RELATIVE_CONSTRAINT_IMPL_H
congleetea/fuse
fuse_models/include/fuse_models/common/sensor_proc.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_COMMON_SENSOR_PROC_H #define FUSE_MODELS_COMMON_SENSOR_PROC_H #include <fuse_constraints/absolute_pose_2d_stamped_constraint.h> #include <fuse_constraints/relative_pose_2d_stamped_constraint.h> #include <fuse_constraints/absolute_constraint.h> #include <fuse_core/eigen.h> #include <fuse_core/transaction.h> #include <fuse_core/uuid.h> #include <fuse_variables/acceleration_linear_2d_stamped.h> #include <fuse_variables/orientation_2d_stamped.h> #include <fuse_variables/position_2d_stamped.h> #include <fuse_variables/velocity_linear_2d_stamped.h> #include <fuse_variables/velocity_angular_2d_stamped.h> #include <fuse_variables/stamped.h> #include <geometry_msgs/AccelWithCovarianceStamped.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <geometry_msgs/TransformStamped.h> #include <geometry_msgs/TwistWithCovarianceStamped.h> #include <ros/ros.h> #include <tf2/LinearMath/Transform.h> #include <tf2/LinearMath/Vector3.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2_ros/transform_listener.h> #include <tf2_2d/tf2_2d.h> #include <tf2_2d/transform.h> #include <boost/range/join.hpp> #include <algorithm> #include <functional> #include <stdexcept> #include <string> #include <vector> namespace tf2 { /** \brief Apply a geometry_msgs TransformStamped to a geometry_msgs TwistWithCovarianceStamped type. * This function is a specialization of the doTransform template defined in tf2/convert.h. * \param t_in The twist to transform, as a timestamped TwistWithCovarianceStamped message. * \param t_out The transformed twist, as a timestamped TwistWithCovarianceStamped message. * \param transform The timestamped transform to apply, as a TransformStamped message. */ template <> inline void doTransform(const geometry_msgs::TwistWithCovarianceStamped& t_in, geometry_msgs::TwistWithCovarianceStamped& t_out, const geometry_msgs::TransformStamped& transform) // NOLINT { tf2::Vector3 vl; fromMsg(t_in.twist.twist.linear, vl); tf2::Vector3 va; fromMsg(t_in.twist.twist.angular, va); tf2::Transform t; fromMsg(transform.transform, t); t_out.twist.twist.linear = tf2::toMsg(t.getBasis() * vl); t_out.twist.twist.angular = tf2::toMsg(t.getBasis() * va); t_out.header.stamp = transform.header.stamp; t_out.header.frame_id = transform.header.frame_id; t_out.twist.covariance = transformCovariance(t_in.twist.covariance, t); } /** \brief Apply a geometry_msgs TransformStamped to a geometry_msgs AccelWithCovarianceStamped type. * This function is a specialization of the doTransform template defined in tf2/convert.h. * \param t_in The acceleration to transform, as a timestamped AccelWithCovarianceStamped message. * \param t_out The transformed acceleration, as a timestamped AccelWithCovarianceStamped message. * \param transform The timestamped transform to apply, as a TransformStamped message. */ template <> inline void doTransform(const geometry_msgs::AccelWithCovarianceStamped& t_in, geometry_msgs::AccelWithCovarianceStamped& t_out, const geometry_msgs::TransformStamped& transform) // NOLINT { tf2::Vector3 al; fromMsg(t_in.accel.accel.linear, al); tf2::Vector3 aa; fromMsg(t_in.accel.accel.angular, aa); tf2::Transform t; fromMsg(transform.transform, t); t_out.accel.accel.linear = tf2::toMsg(t.getBasis() * al); t_out.accel.accel.angular = tf2::toMsg(t.getBasis() * aa); t_out.header.stamp = transform.header.stamp; t_out.header.frame_id = transform.header.frame_id; t_out.accel.covariance = transformCovariance(t_in.accel.covariance, t); } } // namespace tf2 namespace fuse_models { namespace common { /** * @brief Method to merge two vectors of indices adding an offset to the RHS one. * * @param[in] lhs_indices - LHS vector of indices * @param[in] rhs_indices - RHS vector of indices * @param[in] rhs_offset - RHS offset to be added to the RHS vector indices (defaults to 0) */ inline std::vector<size_t> mergeIndices( const std::vector<size_t>& lhs_indices, const std::vector<size_t>& rhs_indices, const size_t rhs_offset = 0u) { auto merged_indices = boost::copy_range<std::vector<size_t>>(boost::join(lhs_indices, rhs_indices)); const auto rhs_it = merged_indices.begin() + lhs_indices.size(); std::transform( rhs_it, merged_indices.end(), rhs_it, std::bind(std::plus<size_t>(), std::placeholders::_1, rhs_offset)); return merged_indices; } /** * @brief Method to create sub-measurements from full measurements and append them to existing partial measurements * * @param[in] mean_full - The full mean vector from which we will generate the sub-measurement * @param[in] covariance_full - The full covariance matrix from which we will generate the sub-measurement * @param[in] indices - The indices we want to include in the sub-measurement * @param[in,out] mean_partial - The partial measurement mean to which we want to append * @param[in,out] covariance_partial - The partial measurement covariance to which we want to append */ inline void populatePartialMeasurement( const fuse_core::VectorXd& mean_full, const fuse_core::MatrixXd& covariance_full, const std::vector<size_t>& indices, fuse_core::VectorXd& mean_partial, fuse_core::MatrixXd& covariance_partial) { for (size_t r = 0; r < indices.size(); ++r) { mean_partial(r) = mean_full(indices[r]); for (size_t c = 0; c < indices.size(); ++c) { covariance_partial(r, c) = covariance_full(indices[r], indices[c]); } } } /** * @brief Transforms a ROS geometry message from its frame to the frame of the output message * * @param[in] tf_buffer - The transform buffer with which we will lookup the required transform * @param[in] input - The message to transform. Source frame and stamp are dictated by its header. * @param[in,out] output - The transformed message. Target frame is dictated by its header. * @return true if the transform succeeded, false otherwise */ template <typename T> bool transformMessage(const tf2_ros::Buffer& tf_buffer, const T& input, T& output) { geometry_msgs::TransformStamped trans; bool have_transform = false; if (tf_buffer.canTransform(output.header.frame_id, input.header.frame_id, input.header.stamp)) { try { trans = tf_buffer.lookupTransform(output.header.frame_id, input.header.frame_id, input.header.stamp); have_transform = true; } catch (const tf2::TransformException& ex) { ROS_WARN_STREAM_THROTTLE(5.0, "Could not transform message from " << input.header.frame_id << " to " << output.header.frame_id << ". Error was " << ex.what() << " Will attempt to use latest transform instead."); } } if (!have_transform) { try { trans = tf_buffer.lookupTransform(output.header.frame_id, input.header.frame_id, ros::Time(0)); } catch (const tf2::TransformException& ex) { ROS_ERROR_STREAM_THROTTLE(5.0, "Could not transform message from " << input.header.frame_id << " to " << output.header.frame_id << ". Error was " << ex.what()); return false; } } tf2::doTransform(input, output, trans); return true; } /** * @brief Extracts 2D pose data from a PoseWithCovarianceStamped message and adds that data to a fuse Transaction * * This method effectively adds two variables (2D position and 2D orientation) and a 2D pose constraint to the given * \p transaction. The pose data is extracted from the \p pose message. Only 2D data is used. The data will be * automatically transformed into the \p target_frame before it is used. * * @param[in] source - The name of the sensor or motion model that generated this constraint * @param[in] device_id - The UUID of the machine * @param[in] pose - The PoseWithCovarianceStamped message from which we will extract the pose data * @param[in] target_frame - The frame ID into which the pose data will be transformed before it is used * @param[in] tf_buffer - The transform buffer with which we will lookup the required transform * @param[out] transaction - The generated variables and constraints are added to this transaction * @return true if any constraints were added, false otherwise */ inline bool processAbsolutePoseWithCovariance( const std::string& source, const fuse_core::UUID& device_id, const geometry_msgs::PoseWithCovarianceStamped& pose, const std::string& target_frame, const std::vector<size_t>& position_indices, const std::vector<size_t>& orientation_indices, const tf2_ros::Buffer& tf_buffer, fuse_core::Transaction& transaction) { if (position_indices.empty() && orientation_indices.empty()) { return false; } geometry_msgs::PoseWithCovarianceStamped transformed_message; transformed_message.header.frame_id = target_frame; if (!transformMessage(tf_buffer, pose, transformed_message)) { ROS_ERROR_STREAM("Cannot create constraint from pose message with stamp " << pose.header.stamp); return false; } // Convert the pose into tf2_2d transform tf2_2d::Transform absolute_pose_2d; tf2::fromMsg(transformed_message.pose.pose, absolute_pose_2d); // Create the pose variable auto position = fuse_variables::Position2DStamped::make_shared(transformed_message.header.stamp, device_id); auto orientation = fuse_variables::Orientation2DStamped::make_shared(transformed_message.header.stamp, device_id); position->x() = absolute_pose_2d.x(); position->y() = absolute_pose_2d.y(); orientation->yaw() = absolute_pose_2d.yaw(); // Create the pose for the constraint fuse_core::Vector3d pose_mean; pose_mean << absolute_pose_2d.x(), absolute_pose_2d.y(), absolute_pose_2d.yaw(); // Create the covariance for the constraint fuse_core::Matrix3d pose_covariance; pose_covariance << transformed_message.pose.covariance[0], transformed_message.pose.covariance[1], transformed_message.pose.covariance[5], transformed_message.pose.covariance[6], transformed_message.pose.covariance[7], transformed_message.pose.covariance[11], transformed_message.pose.covariance[30], transformed_message.pose.covariance[31], transformed_message.pose.covariance[35]; // Build the sub-vector and sub-matrices based on the requested indices fuse_core::VectorXd pose_mean_partial(position_indices.size() + orientation_indices.size()); fuse_core::MatrixXd pose_covariance_partial(pose_mean_partial.rows(), pose_mean_partial.rows()); const auto indices = mergeIndices(position_indices, orientation_indices, position->size()); populatePartialMeasurement(pose_mean, pose_covariance, indices, pose_mean_partial, pose_covariance_partial); // Create an absolute pose constraint auto constraint = fuse_constraints::AbsolutePose2DStampedConstraint::make_shared( source, *position, *orientation, pose_mean_partial, pose_covariance_partial, position_indices, orientation_indices); transaction.addVariable(position); transaction.addVariable(orientation); transaction.addConstraint(constraint); transaction.addInvolvedStamp(pose.header.stamp); return true; } /** * @brief Extracts relative 2D pose data from a PoseWithCovarianceStamped and adds that data to a fuse Transaction * * This method computes the delta between two poses and creates the required fuse variables and constraints, and then * adds them to the given \p transaction. Only 2D data is used. The pose delta is calculated as * * pose_relative = pose_absolute1^-1 * pose_absolute2 * * Additionally, the covariance of each pose message is rotated into the robot's base frame at the time of * pose_absolute1. They are then added in the constraint. This assumes independence between the pose measurements. * * @param[in] source - The name of the sensor or motion model that generated this constraint * @param[in] device_id - The UUID of the machine * @param[in] pose1 - The first (and temporally earlier) PoseWithCovarianceStamped message * @param[in] pose2 - The first (and temporally later) PoseWithCovarianceStamped message * @param[out] transaction - The generated variables and constraints are added to this transaction * @return true if any constraints were added, false otherwise */ inline bool processDifferentialPoseWithCovariance( const std::string& source, const fuse_core::UUID& device_id, const geometry_msgs::PoseWithCovarianceStamped& pose1, const geometry_msgs::PoseWithCovarianceStamped& pose2, const std::vector<size_t>& position_indices, const std::vector<size_t>& orientation_indices, fuse_core::Transaction& transaction) { if (position_indices.empty() && orientation_indices.empty()) { return false; } // Convert the poses into tf2_2d transforms tf2_2d::Transform pose1_2d; tf2::fromMsg(pose1.pose.pose, pose1_2d); tf2_2d::Transform pose2_2d; tf2::fromMsg(pose2.pose.pose, pose2_2d); // Create the pose variables auto position1 = fuse_variables::Position2DStamped::make_shared(pose1.header.stamp, device_id); auto orientation1 = fuse_variables::Orientation2DStamped::make_shared(pose1.header.stamp, device_id); position1->x() = pose1_2d.x(); position1->y() = pose1_2d.y(); orientation1->yaw() = pose1_2d.yaw(); auto position2 = fuse_variables::Position2DStamped::make_shared(pose2.header.stamp, device_id); auto orientation2 = fuse_variables::Orientation2DStamped::make_shared(pose2.header.stamp, device_id); position2->x() = pose2_2d.x(); position2->y() = pose2_2d.y(); orientation2->yaw() = pose2_2d.yaw(); // Create the delta for the constraint const double sy = ::sin(-pose1_2d.yaw()); const double cy = ::cos(-pose1_2d.yaw()); double x_diff = pose2_2d.x() - pose1_2d.x(); double y_diff = pose2_2d.y() - pose1_2d.y(); fuse_core::Vector3d pose_relative_mean; pose_relative_mean << cy * x_diff - sy * y_diff, sy * x_diff + cy * y_diff, (pose2_2d.rotation() - pose1_2d.rotation()).getAngle(); // Compute Jacobians so we can rotate the covariance fuse_core::Matrix3d j_pose1; j_pose1 << -cy, sy, sy * x_diff + cy * y_diff, -sy, -cy, -cy * x_diff + sy * y_diff, 0, 0, -1; fuse_core::Matrix3d j_pose2; j_pose2 << cy, -sy, 0, sy, cy, 0, 0, 0, 1; // Create the covariance components for the constraint fuse_core::Matrix3d cov1; cov1 << pose1.pose.covariance[0], pose1.pose.covariance[1], pose1.pose.covariance[5], pose1.pose.covariance[6], pose1.pose.covariance[7], pose1.pose.covariance[11], pose1.pose.covariance[30], pose1.pose.covariance[31], pose1.pose.covariance[35]; fuse_core::Matrix3d cov2; cov2 << pose2.pose.covariance[0], pose2.pose.covariance[1], pose2.pose.covariance[5], pose2.pose.covariance[6], pose2.pose.covariance[7], pose2.pose.covariance[11], pose2.pose.covariance[30], pose2.pose.covariance[31], pose2.pose.covariance[35]; auto pose_relative_covariance = j_pose1 * cov1 * j_pose1.transpose() + j_pose2 * cov2 * j_pose2.transpose(); // Build the sub-vector and sub-matrices based on the requested indices fuse_core::VectorXd pose_relative_mean_partial(position_indices.size() + orientation_indices.size()); fuse_core::MatrixXd pose_relative_covariance_partial(pose_relative_mean_partial.rows(), pose_relative_mean_partial.rows()); const auto indices = mergeIndices(position_indices, orientation_indices, position1->size()); populatePartialMeasurement( pose_relative_mean, pose_relative_covariance, indices, pose_relative_mean_partial, pose_relative_covariance_partial); // Create a relative pose constraint. We assume the pose measurements are independent. auto constraint = fuse_constraints::RelativePose2DStampedConstraint::make_shared( source, *position1, *orientation1, *position2, *orientation2, pose_relative_mean_partial, pose_relative_covariance_partial, position_indices, orientation_indices); transaction.addVariable(position1); transaction.addVariable(orientation1); transaction.addVariable(position2); transaction.addVariable(orientation2); transaction.addConstraint(constraint); transaction.addInvolvedStamp(pose1.header.stamp); transaction.addInvolvedStamp(pose2.header.stamp); return true; } /** * @brief Extracts velocity data from a TwistWithCovarianceStamped and adds that data to a fuse Transaction * * This method effectively adds two variables (2D linear velocity and 2D angular velocity) and their respective * constraints to the given \p transaction. The velocity data is extracted from the \p twist message. Only 2D data is * used. The data will be automatically transformed into the \p target_frame before it is used. * * @param[in] source - The name of the sensor or motion model that generated this constraint * @param[in] device_id - The UUID of the machine * @param[in] twist - The TwistWithCovarianceStamped message from which we will extract the twist data * @param[in] target_frame - The frame ID into which the twist data will be transformed before it is used * @param[in] tf_buffer - The transform buffer with which we will lookup the required transform * @param[out] transaction - The generated variables and constraints are added to this transaction * @return true if any constraints were added, false otherwise */ inline bool processTwistWithCovariance( const std::string& source, const fuse_core::UUID& device_id, const geometry_msgs::TwistWithCovarianceStamped& twist, const std::string& target_frame, const std::vector<size_t>& linear_indices, const std::vector<size_t>& angular_indices, const tf2_ros::Buffer& tf_buffer, fuse_core::Transaction& transaction) { // Make sure we actually have work to do if (linear_indices.empty() && angular_indices.empty()) { return false; } geometry_msgs::TwistWithCovarianceStamped transformed_message; transformed_message.header.frame_id = target_frame; if (!transformMessage(tf_buffer, twist, transformed_message)) { ROS_ERROR_STREAM("Cannot create constraint from pose message with stamp " << twist.header.stamp); return false; } bool constraints_added = false; // Create two absolute constraints if (!linear_indices.empty()) { auto velocity_linear = fuse_variables::VelocityLinear2DStamped::make_shared(transformed_message.header.stamp, device_id); velocity_linear->x() = transformed_message.twist.twist.linear.x; velocity_linear->y() = transformed_message.twist.twist.linear.y; // Create the mean twist vectors for the constraints fuse_core::Vector2d linear_vel_mean; linear_vel_mean << transformed_message.twist.twist.linear.x, transformed_message.twist.twist.linear.y; // Create the covariances for the constraints fuse_core::Matrix2d linear_vel_covariance; linear_vel_covariance << transformed_message.twist.covariance[0], transformed_message.twist.covariance[1], transformed_message.twist.covariance[6], transformed_message.twist.covariance[7]; // Build the sub-vector and sub-matrices based on the requested indices fuse_core::VectorXd linear_vel_mean_partial(linear_indices.size()); fuse_core::MatrixXd linear_vel_covariance_partial(linear_vel_mean_partial.rows(), linear_vel_mean_partial.rows()); populatePartialMeasurement( linear_vel_mean, linear_vel_covariance, linear_indices, linear_vel_mean_partial, linear_vel_covariance_partial); auto linear_vel_constraint = fuse_constraints::AbsoluteVelocityLinear2DStampedConstraint::make_shared( source, *velocity_linear, linear_vel_mean_partial, linear_vel_covariance_partial, linear_indices); transaction.addVariable(velocity_linear); transaction.addConstraint(linear_vel_constraint); constraints_added = true; } if (!angular_indices.empty()) { // Create the twist variables auto velocity_angular = fuse_variables::VelocityAngular2DStamped::make_shared(transformed_message.header.stamp, device_id); velocity_angular->yaw() = transformed_message.twist.twist.angular.z; fuse_core::Vector1d angular_vel_vector; angular_vel_vector << transformed_message.twist.twist.angular.z; fuse_core::Matrix1d angular_vel_covariance; angular_vel_covariance << transformed_message.twist.covariance[35]; auto angular_vel_constraint = fuse_constraints::AbsoluteVelocityAngular2DStampedConstraint::make_shared( source, *velocity_angular, angular_vel_vector, angular_vel_covariance, angular_indices); transaction.addVariable(velocity_angular); transaction.addConstraint(angular_vel_constraint); constraints_added = true; } if (constraints_added) { transaction.addInvolvedStamp(twist.header.stamp); } return constraints_added; } /** * @brief Extracts linear acceleration data from an AccelWithCovarianceStamped and adds that data to a fuse Transaction * * This method effectively adds a linear acceleration variable and constraint to the given to the given \p transaction. * The acceleration data is extracted from the \p acceleration message. Only 2D data is used. The data will be * automatically transformed into the \p target_frame before it is used. * * @param[in] source - The name of the sensor or motion model that generated this constraint * @param[in] device_id - The UUID of the machine * @param[in] acceleration - The AccelWithCovarianceStamped message from which we will extract the acceleration data * @param[in] target_frame - The frame ID into which the acceleration data will be transformed before it is used * @param[in] tf_buffer - The transform buffer with which we will lookup the required transform * @param[out] transaction - The generated variables and constraints are added to this transaction * @return true if any constraints were added, false otherwise */ inline bool processAccelWithCovariance( const std::string& source, const fuse_core::UUID& device_id, const geometry_msgs::AccelWithCovarianceStamped& acceleration, const std::string& target_frame, const std::vector<size_t>& indices, const tf2_ros::Buffer& tf_buffer, fuse_core::Transaction& transaction) { // Make sure we actually have work to do if (indices.empty()) { return false; } geometry_msgs::AccelWithCovarianceStamped transformed_message; transformed_message.header.frame_id = target_frame; if (!transformMessage(tf_buffer, acceleration, transformed_message)) { ROS_ERROR_STREAM("Cannot create constraint from pose message with stamp " << acceleration.header.stamp); return false; } // Create the acceleration variables auto acceleration_linear = fuse_variables::AccelerationLinear2DStamped::make_shared(transformed_message.header.stamp, device_id); acceleration_linear->x() = transformed_message.accel.accel.linear.x; acceleration_linear->y() = transformed_message.accel.accel.linear.y; // Create the full mean vector and covariance for the constraint fuse_core::Vector2d accel_mean; accel_mean << transformed_message.accel.accel.linear.x, transformed_message.accel.accel.linear.y; fuse_core::Matrix2d accel_covariance; accel_covariance << transformed_message.accel.covariance[0], transformed_message.accel.covariance[1], transformed_message.accel.covariance[6], transformed_message.accel.covariance[7]; // Build the sub-vector and sub-matrices based on the requested indices fuse_core::VectorXd accel_mean_partial(indices.size()); fuse_core::MatrixXd accel_covariance_partial(accel_mean_partial.rows(), accel_mean_partial.rows()); populatePartialMeasurement(accel_mean, accel_covariance, indices, accel_mean_partial, accel_covariance_partial); // Create the constraint auto linear_accel_constraint = fuse_constraints::AbsoluteAccelerationLinear2DStampedConstraint::make_shared( source, *acceleration_linear, accel_mean_partial, accel_covariance_partial, indices); transaction.addVariable(acceleration_linear); transaction.addConstraint(linear_accel_constraint); transaction.addInvolvedStamp(acceleration.header.stamp); return true; } } // namespace common } // namespace fuse_models #endif // FUSE_MODELS_COMMON_SENSOR_PROC_H
congleetea/fuse
fuse_graphs/test/covariance_constraint.h
<gh_stars>100-1000 /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_GRAPHS_TEST_COVARIANCE_CONSTRAINT_H // NOLINT{build/header_guard} #define FUSE_GRAPHS_TEST_COVARIANCE_CONSTRAINT_H // NOLINT{build/header_guard} #include <fuse_core/constraint.h> #include <fuse_core/macros.h> #include <fuse_core/serialization.h> #include <fuse_core/uuid.h> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> #include <ceres/cost_function.h> #include <algorithm> #include <string> /** * @brief Create a cost fuction that implements one of the Ceres unit tests * * UnaryCostFunctions are added to all three variables * - https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/covariance_test.cc#L423 * - https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/covariance_test.cc#L428 * - https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/covariance_test.cc#L433 * BinaryCostFunctions are added for (Y,X) and (Z,X) * - https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/covariance_test.cc#L441 * - https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/covariance_test.cc#L451 */ class CovarianceCostFunction : public ceres::CostFunction { public: CovarianceCostFunction() { set_num_residuals(8); mutable_parameter_block_sizes()->push_back(2); mutable_parameter_block_sizes()->push_back(3); mutable_parameter_block_sizes()->push_back(1); } bool Evaluate(double const* const* /*parameters*/, double* residuals, double** jacobians) const override { residuals[0] = 1; residuals[1] = 1; residuals[2] = 1; residuals[3] = 1; residuals[4] = 1; residuals[5] = 1; residuals[6] = 2; residuals[7] = 2; if (jacobians != NULL) { if (jacobians[0] != NULL) { static const double jacobian0[] = { 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -5.0, -6.0, 3.0, -2.0 }; std::copy(jacobian0, jacobian0 + 16, jacobians[0]); } if (jacobians[1] != NULL) { static const double jacobian1[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 0.0, 0.0, 0.0 }; std::copy(jacobian1, jacobian1 + 24, jacobians[1]); } if (jacobians[2] != NULL) { static const double jacobian2[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 2.0 }; std::copy(jacobian2, jacobian2 + 8, jacobians[2]); } } return true; } }; /** * @brief Constraint implementing the covariance cost function */ class CovarianceConstraint : public fuse_core::Constraint { public: FUSE_CONSTRAINT_DEFINITIONS(CovarianceConstraint); CovarianceConstraint() = default; CovarianceConstraint( const std::string& source, const fuse_core::UUID& variable1_uuid, const fuse_core::UUID& variable2_uuid, const fuse_core::UUID& variable3_uuid) : fuse_core::Constraint(source, {variable1_uuid, variable2_uuid, variable3_uuid}) { } void print(std::ostream& /*stream = std::cout*/) const override {} ceres::CostFunction* costFunction() const override { return new CovarianceCostFunction(); } private: // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & boost::serialization::base_object<fuse_core::Constraint>(*this); } }; BOOST_CLASS_EXPORT(CovarianceConstraint); #endif // FUSE_GRAPHS_TEST_COVARIANCE_CONSTRAINT_H // NOLINT{build/header_guard}
congleetea/fuse
fuse_core/include/fuse_core/callback_wrapper.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_CALLBACK_WRAPPER_H #define FUSE_CORE_CALLBACK_WRAPPER_H #include <ros/callback_queue_interface.h> #include <functional> #include <future> namespace fuse_core { /** * @brief Object that wraps a generic function call so that it may be inserted into a ROS callback queue. * * Once inserted, the function will be called from within the thread that services that callback queue. It will be * intermingled with any other standard ROS callbacks (message subscription callbacks, service callbacks, timer * callbacks, etc.), analogous to adding callbacks for an additional topic subscriber. * * boost::bind/std::bind can be used to provide input arguments. Note that bind() uses a pass-by-value mechanism. If * arguments should be passed by reference instead (i.e. copies are expensive or the function modifies the input in * place), wrap the input arguments with boost::ref() or std::ref(). * * The CallbackWrapper class uses the C++11 promise/future mechanism to provide the return data after the callback has * been executed in the callback queue's thread. This is done by getting a future<T> from the CallbackWrapper before it * is inserted into the callback queue. You can then block until the return value is ready by calling future.wait(), * and the value can be retrieved using future.get(). Even if the function returns void, it can still be useful to get * a copy of the CallbackWrapper's future. The future.wait() function is still valid for void types, thus allowing you * to block until the callback function has been executed. * * See C++11 documentation for more details on promises and futures: * - http://en.cppreference.com/w/cpp/thread/promise * - http://en.cppreference.com/w/cpp/thread/future * * Example usage: * @code{.cpp} * class MyClass * { * public: * double processData(const std::vector<double>& data) * { * return std::accumulate(data.begin(), data.end(), 0.0); * } * }; * * MyClass my_object; * std::vector<double> really_big_data(1000000); * auto callback = boost::make_shared<CallbackWrapper<double> >( * std::bind(&MyClass::processData, &my_object, std::ref(really_big_data))); * std::future<double> result = callback->getFuture(); * ros::getGlobalCallbackQueue()->addCallback(callback); * result.wait(); * ROS_INFO_STREAM("The result is: " << result.get()); * @endcode */ template <typename T> class CallbackWrapper : public ros::CallbackInterface { public: using CallbackFunction = std::function<T(void)>; /** * @brief Constructor * * @param[in] callback The function to be called from the callback queue */ explicit CallbackWrapper(CallbackFunction callback) : callback_(callback) { } /** * @brief Get a future<T> object that represents the function's return value */ std::future<T> getFuture() { return promise_.get_future(); } /** * @brief Call this function. This is used by the callback queue. */ CallResult call() override { promise_.set_value(callback_()); return Success; } private: CallbackFunction callback_; //!< The function to execute within the std::promise<T> promise_; //!< Promise/Future used to return data after the callback is executed }; // Specialization to handle 'void' return types // Specifically, promise_.set_value(callback_()) does not work if callback_() returns void. template <> inline ros::CallbackInterface::CallResult CallbackWrapper<void>::call() { callback_(); promise_.set_value(); return Success; } } // namespace fuse_core #endif // FUSE_CORE_CALLBACK_WRAPPER_H
congleetea/fuse
fuse_core/include/fuse_core/ceres_options.h
<gh_stars>0 /* * Software License Agreement (BSD License) * * Copyright (c) 2019 Clearpath Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_CERES_OPTIONS_H #define FUSE_CORE_CERES_OPTIONS_H #include <ros/console.h> #include <ros/node_handle.h> #include <ceres/covariance.h> #include <ceres/problem.h> #include <ceres/solver.h> #include <ceres/types.h> #include <string> /** * Defines ToString overloaded function to Ceres Options. * * For a given Ceres Solver Option <T>, the function ToString calls ceres::<T>ToString */ #define CERES_OPTION_TO_STRING_DEFINITION(Option) \ static inline const char* ToString(ceres::Option value) \ { \ return ceres::Option##ToString(value); \ } /** * Defines FromString overloaded function to Ceres Options. * * For a given Ceres Solver Option <T>, the function FromString calls ceres::StringTo<T> */ #define CERES_OPTION_FROM_STRING_DEFINITION(Option) \ static inline bool FromString(std::string string_value, ceres::Option* value) \ { \ return ceres::StringTo##Option(string_value, value); \ } /** * Defines ToString and FromString overloaded functions for Ceres Options. * * See CERES_OPTION_TO_STRING_DEFINITION and CERES_OPTION_FROM_STRING_DEFINITION. */ #define CERES_OPTION_STRING_DEFINITIONS(Option) \ CERES_OPTION_TO_STRING_DEFINITION(Option) \ CERES_OPTION_FROM_STRING_DEFINITION(Option) /** * Check for at least Ceres Solver version x.y.z, where: x = major, y = minor and z = revision. */ #define CERES_VERSION_AT_LEAST(x, y, z) (CERES_VERSION_MAJOR > x || (CERES_VERSION_MAJOR >= x && \ (CERES_VERSION_MINOR > y || (CERES_VERSION_MINOR >= y && \ CERES_VERSION_REVISION >= z)))) #if !CERES_VERSION_AT_LEAST(2, 0, 0) /** * Patch Ceres versions before 2.0.0 that miss the LoggingType and DumpFormatType ToString and StringTo functions. */ #include <algorithm> namespace ceres { #define CASESTR(x) case x: return #x #define STRENUM(x) if (value == #x) { *type = x; return true;} static void UpperCase(std::string* input) { // The NOLINT below it's because std::transform requires <algorithm>, which is included inside the #if above, but // roslint still complains std::transform(input->begin(), input->end(), input->begin(), ::toupper); // NOLINT(build/include_what_you_use) } inline const char* LoggingTypeToString(LoggingType type) { switch (type) { CASESTR(SILENT); CASESTR(PER_MINIMIZER_ITERATION); default: return "UNKNOWN"; } } inline bool StringToLoggingType(std::string value, LoggingType* type) { UpperCase(&value); STRENUM(SILENT); STRENUM(PER_MINIMIZER_ITERATION); return false; } inline const char* DumpFormatTypeToString(DumpFormatType type) { switch (type) { CASESTR(CONSOLE); CASESTR(TEXTFILE); default: return "UNKNOWN"; } } inline bool StringToDumpFormatType(std::string value, DumpFormatType* type) { UpperCase(&value); STRENUM(CONSOLE); STRENUM(TEXTFILE); return false; } #undef CASESTR #undef STRENUM } // namespace ceres #else /** * Patch Ceres version 2.0.0 that uses lower case for the LoggingType and DumpFormatType StringTo function. * See https://github.com/ceres-solver/ceres-solver/blob/master/include/ceres/types.h */ namespace ceres { bool StringToLoggingType(std::string value, LoggingType* type) { return StringtoLoggingType(value, type); } bool StringToDumpFormatType(std::string value, DumpFormatType* type) { return StringtoDumpFormatType(value, type); } } // namespace ceres #endif namespace fuse_core { /** * String definitions for all Ceres options. */ CERES_OPTION_STRING_DEFINITIONS(CovarianceAlgorithmType) CERES_OPTION_STRING_DEFINITIONS(DenseLinearAlgebraLibraryType) CERES_OPTION_STRING_DEFINITIONS(DoglegType) CERES_OPTION_STRING_DEFINITIONS(DumpFormatType) CERES_OPTION_STRING_DEFINITIONS(LinearSolverType) CERES_OPTION_STRING_DEFINITIONS(LineSearchDirectionType) CERES_OPTION_STRING_DEFINITIONS(LineSearchInterpolationType) CERES_OPTION_STRING_DEFINITIONS(LineSearchType) CERES_OPTION_STRING_DEFINITIONS(LoggingType) CERES_OPTION_STRING_DEFINITIONS(MinimizerType) CERES_OPTION_STRING_DEFINITIONS(NonlinearConjugateGradientType) CERES_OPTION_STRING_DEFINITIONS(PreconditionerType) CERES_OPTION_STRING_DEFINITIONS(SparseLinearAlgebraLibraryType) CERES_OPTION_STRING_DEFINITIONS(TrustRegionStrategyType) CERES_OPTION_STRING_DEFINITIONS(VisibilityClusteringType) /** * @brief Helper function that loads a Ceres Option (e.g. ceres::LinearSolverType) value from the parameter server * * @param[in] node_handle - The node handle used to load the parameter * @param[in] parameter_name - The parameter name to load * @param[in] default_value - A default value to use if the provided parameter name does not exist * @return The loaded (or default) value */ template <class T> T getParam(const ros::NodeHandle& node_handle, const std::string& parameter_name, const T& default_value) { const std::string default_string_value{ ToString(default_value) }; std::string string_value; node_handle.param(parameter_name, string_value, default_string_value); T value; if (!FromString(string_value, &value)) { ROS_WARN_STREAM("The requested " << parameter_name << " (" << string_value << ") is not supported. Using the default value (" << default_string_value << ") instead."); value = default_value; } return value; } /** * @brief Populate a ceres::Covariance::Options object with information from the parameter server * * @param[in] nh - A node handle in a namespace containing ceres::Covariance::Options settings * @param[out] covariance_options - The ceres::Covariance::Options object to update */ void loadCovarianceOptionsFromROS(const ros::NodeHandle& nh, ceres::Covariance::Options& covariance_options); /** * @brief Populate a ceres::Problem::Options object with information from the parameter server * * @param[in] nh - A node handle in a namespace containing ceres::Problem::Options settings * @param[out] problem_options - The ceres::Problem::Options object to update */ void loadProblemOptionsFromROS(const ros::NodeHandle& nh, ceres::Problem::Options& problem_options); /** * @brief Populate a ceres::Solver::Options object with information from the parameter server * * @param[in] nh - A node handle in a namespace containing ceres::Solver::Options settings * @param[out] solver_options - The ceres::Solver::Options object to update */ void loadSolverOptionsFromROS(const ros::NodeHandle& nh, ceres::Solver::Options& solver_options); } // namespace fuse_core #endif // FUSE_CORE_CERES_OPTIONS_H
congleetea/fuse
fuse_publishers/include/fuse_publishers/serialized_publisher.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_PUBLISHERS_SERIALIZED_PUBLISHER_H #define FUSE_PUBLISHERS_SERIALIZED_PUBLISHER_H #include <fuse_core/async_publisher.h> #include <fuse_core/graph.h> #include <fuse_core/macros.h> #include <fuse_core/transaction.h> #include <ros/ros.h> #include <string> namespace fuse_publishers { /** * @brief Publisher plugin that publishes the transaction and graph as serialized messages */ class SerializedPublisher : public fuse_core::AsyncPublisher { public: SMART_PTR_DEFINITIONS(SerializedPublisher); /** * @brief Constructor */ SerializedPublisher(); /** * @brief Destructor */ virtual ~SerializedPublisher() = default; /** * @brief Perform any required post-construction initialization, such as advertising publishers or reading from the * parameter server. */ void onInit() override; /** * @brief Notify the publisher about variables that have been added or removed * * @param[in] transaction A Transaction object, describing the set of variables that have been added and/or removed * @param[in] graph A read-only pointer to the graph object, allowing queries to be performed whenever needed */ void notifyCallback( fuse_core::Transaction::ConstSharedPtr transaction, fuse_core::Graph::ConstSharedPtr graph) override; protected: std::string frame_id_; //!< The name of the frame for this path ros::Publisher graph_publisher_; ros::Publisher transaction_publisher_; }; } // namespace fuse_publishers #endif // FUSE_PUBLISHERS_SERIALIZED_PUBLISHER_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/normal_prior_orientation_3d_euler_cost_functor.h
<gh_stars>100-1000 /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_NORMAL_PRIOR_ORIENTATION_3D_EULER_COST_FUNCTOR_H #define FUSE_CONSTRAINTS_NORMAL_PRIOR_ORIENTATION_3D_EULER_COST_FUNCTOR_H #include <fuse_core/eigen.h> #include <fuse_core/util.h> #include <fuse_variables/orientation_3d_stamped.h> #include <ceres/rotation.h> #include <Eigen/Core> #include <vector> namespace fuse_constraints { /** * @brief Create a prior cost function on a 3D orientation variable using Euler roll, pitch, and yaw measurements * * The functor can compute the cost of a subset of the axes, in the event that we are not interested in all the Euler * angles in the variable. * * So, for example, if * b_ = [ measured_yaw ] * [ meausred_roll ] * * then the cost function is of the form: * * cost(x) = || A * [ yaw(x) - b_(0) ] ||^2 * || [ roll(x) - b_(1) ] || * * where the matrix A and the vector b are fixed and (roll, pitch, yaw) are the components of the 3D orientation * variable. * * In case the user is interested in implementing a cost function of the form * * cost(X) = (X - mu)^T S^{-1} (X - mu) * * where, mu is a vector and S is a covariance matrix, then, A = S^{-1/2}, i.e the matrix A is the square root * information matrix (the inverse of the covariance). */ class NormalPriorOrientation3DEulerCostFunctor { public: using Euler = fuse_variables::Orientation3DStamped::Euler; /** * @brief Construct a cost function instance * * @param[in] A The residual weighting matrix, most likely the square root information matrix. Its order must match * the values in \p axes. * @param[in] b The orientation measurement or prior. Its order must match the values in \p axes. * @param[in] axes The Euler angle axes for which we want to compute errors. Defaults to all axes. */ NormalPriorOrientation3DEulerCostFunctor( const fuse_core::MatrixXd& A, const fuse_core::VectorXd& b, const std::vector<Euler> &axes = {Euler::ROLL, Euler::PITCH, Euler::YAW}) : //NOLINT A_(A), b_(b), axes_(axes) { } /** * @brief Evaluate the cost function. Used by the Ceres optimization engine. */ template <typename T> bool operator()(const T* const orientation, T* residuals) const { using fuse_variables::Orientation3DStamped; for (size_t i = 0; i < axes_.size(); ++i) { T angle; switch (axes_[i]) { case Euler::ROLL: { angle = fuse_core::getRoll(orientation[0], orientation[1], orientation[2], orientation[3]); break; } case Euler::PITCH: { angle = fuse_core::getPitch(orientation[0], orientation[1], orientation[2], orientation[3]); break; } case Euler::YAW: { angle = fuse_core::getYaw(orientation[0], orientation[1], orientation[2], orientation[3]); break; } default: { throw std::runtime_error("The provided axis specified is unknown. " "I should probably be more informative here"); } } residuals[i] = angle - T(b_[i]); } Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> residuals_map(residuals, A_.rows()); residuals_map.applyOnTheLeft(A_.template cast<T>()); return true; } private: fuse_core::MatrixXd A_; //!< The residual weighting matrix, most likely the square root information matrix fuse_core::VectorXd b_; //!< The measured 3D orientation (quaternion) value std::vector<Euler> axes_; //!< The Euler angle axes that we're measuring }; } // namespace fuse_constraints #endif // FUSE_CONSTRAINTS_NORMAL_PRIOR_ORIENTATION_3D_EULER_COST_FUNCTOR_H
congleetea/fuse
fuse_viz/include/fuse_viz/serialized_graph_display.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Clearpath Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_VIZ_SERIALIZED_GRAPH_DISPLAY_H #define FUSE_VIZ_SERIALIZED_GRAPH_DISPLAY_H #ifndef Q_MOC_RUN #include <fuse_core/graph_deserializer.h> #include <fuse_msgs/SerializedGraph.h> #include <rviz/message_filter_display.h> #endif // Q_MOC_RUN #include <vector> namespace Ogre { class SceneNode; } namespace rviz { class Object; class BoolProperty; class FloatProperty; /** * @brief An rviz dispaly for fuse_msgs::SerializedGraph messages. */ class SerializedGraphDisplay : public MessageFilterDisplay<fuse_msgs::SerializedGraph> { Q_OBJECT public: SerializedGraphDisplay(); ~SerializedGraphDisplay() override; void reset() override; protected: void onInitialize() override; void onEnable() override; void onDisable() override; private Q_SLOTS: void updateDrawVariablesAxesProperty(); void updateScaleProperty(); private: void clear(); void processMessage(const fuse_msgs::SerializedGraph::ConstPtr& msg) override; Ogre::SceneNode* root_node_; Ogre::SceneNode* variables_axes_node_; Ogre::SceneNode* variables_spheres_node_; std::vector<Object*> graph_shapes_; BoolProperty* draw_variables_axes_property_; FloatProperty* scale_property_; fuse_core::GraphDeserializer graph_deserializer_; }; } // namespace rviz #endif // FUSE_VIZ_SERIALIZED_GRAPH_DISPLAY_H
congleetea/fuse
fuse_core/include/fuse_core/transaction.h
<filename>fuse_core/include/fuse_core/transaction.h /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_TRANSACTION_H #define FUSE_CORE_TRANSACTION_H #include <fuse_core/constraint.h> #include <fuse_core/macros.h> #include <fuse_core/serialization.h> #include <fuse_core/uuid.h> #include <fuse_core/variable.h> #include <ros/time.h> #include <boost/range/any_range.hpp> #include <boost/serialization/access.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/vector.hpp> #include <ostream> #include <set> #include <vector> namespace fuse_core { /** * @brief A transaction is a group of variable and constraint additions and subtractions that should all be * processed at the same time. * * This arises most often with graph edits, when you want to remove an existing constraint and replace it with one * or more new constraints. You don't want the removal to happen independently of the additions. All graph operations * are contained within a Transaction object so that all operations are treated equally. */ class Transaction { public: SMART_PTR_DEFINITIONS(Transaction); /** * @brief A range of Constraint::SharedPtr objects * * An object representing a range defined by two iterators. It has begin() and end() methods (which means it can * be used in range-based for loops), an empty() method, and a front() method for directly accessing the first * member. When dereferenced, an iterator returns a const Constraint&. */ using const_constraint_range = boost::any_range<const Constraint, boost::forward_traversal_tag>; /** * @brief A range of ros::Time objects * * An object representing a range defined by two iterators. It has begin() and end() methods (which means it can * be used in range-based for loops), an empty() method, and a front() method for directly accessing the first * member. When dereferenced, an iterator returns a const ros::Time&. */ using const_stamp_range = boost::any_range<const ros::Time, boost::forward_traversal_tag>; /** * @brief A range of UUID objects * * An object representing a range defined by two iterators. It has begin() and end() methods (which means it can * be used in range-based for loops), an empty() method, and a front() method for directly accessing the first * member. When dereferenced, an iterator returns a const UUID&. */ using const_uuid_range = boost::any_range<const UUID, boost::forward_traversal_tag>; /** * @brief A range of Variable::SharedPtr objects * * An object representing a range defined by two iterators. It has begin() and end() methods (which means it can * be used in range-based for loops), an empty() method, and a front() method for directly accessing the first * member. When dereferenced, an iterator returns a const Variable&. */ using const_variable_range = boost::any_range<const Variable, boost::forward_traversal_tag>; /** * @brief Read-only access to this transaction's timestamp */ const ros::Time& stamp() const { return stamp_; } /** * @brief Write access to this transaction's timestamp */ void stamp(const ros::Time& stamp) { stamp_ = stamp; } /** * @brief Read-only access to the set of timestamps involved in this transaction * * @return An iterator range containing all involved timestamps, ordered oldest to newest */ const_stamp_range involvedStamps() const { return involved_stamps_; } /** * @brief Read-only access to the added constraints * * @return An iterator range containing all added constraints */ const_constraint_range addedConstraints() const; /** * @brief Read-only access to the removed constraints * * @return An iterator range containing all removed constraint UUIDs */ const_uuid_range removedConstraints() const { return removed_constraints_; } /** * @brief Read-only access to the added variables * * @return An iterator range containing all added variables */ const_variable_range addedVariables() const; /** * @brief Read-only access to the removed variables * * @return An iterator range containing all removed variable UUIDs */ const_uuid_range removedVariables() const { return removed_variables_; } /** * @brief Add a timestamp to the "involved stamps" collection * * Duplicate timestamps will be ignored, so adding a stamp multiple times will have no effect. * * @param[in] stamp The timestamp to be added */ void addInvolvedStamp(const ros::Time& stamp); /** * @brief Add a constraint to this transaction * * The transaction will shared ownership of the provided constraint. This function also performs several checks * to ensure the same constraint is not added twice, or added and removed. * * @param[in] constraint The constraint to be added * @param[in] overwrite Flag indicating the provided constraint should overwrite an existing constraint with * the same UUID */ void addConstraint(Constraint::SharedPtr constraint, bool overwrite = false); /** * @brief Remove a constraint from this transaction if it was previously added, or mark the constraint for removal * from the graph. * * The constraint UUID is marked to be removed by the receiver of this Transaction. This function also performs * several checks to ensure the same constraint is not removed twice, or added and removed. * * @param[in] constraint_uuid The UUID of the constraint to remove */ void removeConstraint(const UUID& constraint_uuid); /** * @brief Add a variable to this transaction * * The transaction will shared ownership of the provided variable. This function also performs several checks * to ensure the same variable is not added twice, or added and removed. * * @param[in] variable The variable to be added * @param[in] overwrite Flag indicating the provided variable should overwrite an existing variable with the * same UUID */ void addVariable(Variable::SharedPtr variable, bool overwrite = false); /** * @brief Remove the variable from this transaction if it was previously added, or mark the variable for removal * from the graph. * * The variable UUID is marked to be removed by the receiver of this Transaction. This function also performs * several checks to ensure the same variable is not removed twice, or added and removed. * * @param[in] variable_uuid The UUID of the variable to remove */ void removeVariable(const UUID& variable_uuid); /** * @brief Merge the contents of another transaction into this one. * * @param[in] other The transaction to merge in * @param[in] overwrite Flag indicating that variables and constraints in \p other should overwrite existing * variables and constraints with the UUIDs. */ void merge(const Transaction& other, bool overwrite = false); /** * @brief Print a human-readable description of the transaction to the provided stream. * * @param[out] stream The stream to write to. Defaults to stdout. */ void print(std::ostream& stream = std::cout) const; /** * @brief Perform a deep copy of the Transaction and return a unique pointer to the copy * * Unique pointers can be implicitly upgraded to shared pointers if needed. * * @return A unique pointer to a new instance of the most-derived Variable */ Transaction::UniquePtr clone() const; /** * @brief Serialize this Constraint into the provided binary archive * * @param[out] archive - The archive to serialize this constraint into */ void serialize(fuse_core::BinaryOutputArchive& /* archive */) const; /** * @brief Serialize this Constraint into the provided text archive * * @param[out] archive - The archive to serialize this constraint into */ void serialize(fuse_core::TextOutputArchive& /* archive */) const; /** * @brief Deserialize data from the provided binary archive into this Constraint * * @param[in] archive - The archive holding serialized Constraint data */ void deserialize(fuse_core::BinaryInputArchive& /* archive */); /** * @brief Deserialize data from the provided text archive into this Constraint * * @param[in] archive - The archive holding serialized Constraint data */ void deserialize(fuse_core::TextInputArchive& /* archive */); private: ros::Time stamp_; //!< The transaction message timestamp std::vector<Constraint::SharedPtr> added_constraints_; //!< The constraints to be added std::vector<Variable::SharedPtr> added_variables_; //!< The variables to be added std::set<ros::Time> involved_stamps_; //!< The set of timestamps involved in this transaction std::vector<UUID> removed_constraints_; //!< The constraint UUIDs to be removed std::vector<UUID> removed_variables_; //!< The variable UUIDs to be removed // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & stamp_; archive & added_constraints_; archive & added_variables_; archive & involved_stamps_; archive & removed_constraints_; archive & removed_variables_; } }; /** * Stream operator for printing Transaction objects. */ std::ostream& operator <<(std::ostream& stream, const Transaction& transaction); } // namespace fuse_core #endif // FUSE_CORE_TRANSACTION_H
congleetea/fuse
fuse_models/include/fuse_models/unicycle_2d_ignition.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_UNICYCLE_2D_IGNITION_H #define FUSE_MODELS_UNICYCLE_2D_IGNITION_H #include <fuse_core/async_sensor_model.h> #include <fuse_core/macros.h> #include <fuse_core/uuid.h> #include <fuse_models/parameters/unicycle_2d_ignition_params.h> #include <fuse_models/SetPose.h> #include <fuse_models/SetPoseDeprecated.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <ros/ros.h> #include <atomic> namespace fuse_models { /** * @brief A fuse_models ignition sensor designed to be used in conjunction with the unicycle 2D motion model. * * This class publishes a transaction that contains a prior on each state subvariable used in the unicycle 2D motion * model (x, y, yaw, x_vel, y_vel, yaw_vel, x_acc, and y_acc). When the sensor is first loaded, it publishes a single * transaction with the configured initial state and covariance. Additionally, whenever a pose is received, either * on the set_pose service or the topic, this ignition sensor resets the optimizer then publishes a new transaction * with a prior at the specified pose. Priors on (x_vel, y_vel, yaw_vel, x_acc, and y_acc) continue to use the values * configured on the parameter server. * * Parameters: * - ~device_id (uuid string, default: 00000000-0000-0000-0000-000000000000) The device/robot ID to publish * - ~device_name (string) Used to generate the device/robot ID if the device_id is not provided * - ~initial_sigma (vector of doubles) An 8-dimensional vector containing the standard deviations for the initial * state values. The covariance matrix is created placing the squared standard * deviations along the diagonal of an 8x8 matrix. Variable order is * (x, y, yaw, x_vel, y_vel, yaw_vel, x_acc, y_acc). * - ~initial_state (vector of doubles) An 8-dimensional vector containing the initial values for the state. * Variable order is (x, y, yaw, x_vel, y_vel, yaw_vel, x_acc, y_acc). * - ~queue_size (int, default: 10) The subscriber queue size for the pose messages * - ~reset_service (string, default: "~reset") The name of the reset service to call before sending a transaction * - ~set_pose_deprecated_service (string, default: "~set_pose_deprecated") The name of the set_pose_deprecated service * - ~set_pose_service (string, default: "~set_pose") The name of the set_pose service to advertise * - ~topic (string, default: "~set_pose") The topic name for received PoseWithCovarianceStamped messages */ class Unicycle2DIgnition : public fuse_core::AsyncSensorModel { public: SMART_PTR_DEFINITIONS(Unicycle2DIgnition); using ParameterType = parameters::Unicycle2DIgnitionParams; /** * @brief Default constructor * * All plugins are required to have a constructor that accepts no arguments */ Unicycle2DIgnition(); /** * @brief Destructor */ ~Unicycle2DIgnition() = default; /** * @brief Subscribe to the input topic to start sending transactions to the optimizer * * As a very special case, we are overriding the start() method instead of providing an onStart() implementation. * This is because the Unicycle2DIgnition sensor calls reset() on the optimizer, which in turn calls stop() and start(). If we * used the AsyncSensorModel implementations of start() and stop(), the system would hang inside of one callback * function while waiting for another callback to complete. */ void start() override; /** * @brief Unsubscribe from the input topic to stop sending transactions to the optimizer * * As a very special case, we are overriding the stop() method instead of providing an onStop() implementation. * This is because the Unicycle2DIgnition sensor calls reset() on the optimizer, which in turn calls stop() and start(). If we * used the AsyncSensorModel implementations of start() and stop(), the system would hang inside of one callback * function while waiting for another callback to complete. */ void stop() override; /** * @brief Triggers the publication of a new prior transaction at the supplied pose */ void subscriberCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg); /** * @brief Triggers the publication of a new prior transaction at the supplied pose */ bool setPoseServiceCallback(fuse_models::SetPose::Request& req, fuse_models::SetPose::Response& res); /** * @brief Triggers the publication of a new prior transaction at the supplied pose */ bool setPoseDeprecatedServiceCallback( fuse_models::SetPoseDeprecated::Request& req, fuse_models::SetPoseDeprecated::Response&); protected: /** * @brief Perform any required initialization for the kinematic ignition sensor */ void onInit() override; /** * @brief Process a received pose from one of the ROS comm channels * * This method validates the input pose, resets the optimizer, then constructs and sends the initial state * constraints (by calling sendPrior()). * * @param[in] pose - The pose and covariance to use for the prior constraints on (x, y, yaw) */ void process(const geometry_msgs::PoseWithCovarianceStamped& pose); /** * @brief Create and send a prior transaction based on the supplied pose * * The unicycle 2d state members not included in the pose message (x_vel, y_vel, yaw_vel, x_acc, y_acc) will use * the initial state values and standard deviations configured on the parameter server. * * @param[in] pose - The pose and covariance to use for the prior constraints on (x, y, yaw) */ void sendPrior(const geometry_msgs::PoseWithCovarianceStamped& pose); std::atomic_bool started_; //!< Flag indicating the sensor has been started bool initial_transaction_sent_; //!< Flag indicating an initial transaction has been sent already fuse_core::UUID device_id_; //!< The UUID of this device ParameterType params_; //!< Object containing all of the configuration parameters ros::ServiceClient reset_client_; //!< Service client used to call the "reset" service on the optimizer ros::ServiceServer set_pose_service_; //!< ROS service server that receives SetPose requests ros::ServiceServer set_pose_deprecated_service_; //!< ROS service server that receives SetPoseDeprecated requests ros::Subscriber subscriber_; //!< ROS subscriber that receives PoseWithCovarianceStamped messages }; } // namespace fuse_models #endif // FUSE_MODELS_UNICYCLE_2D_IGNITION_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/normal_delta_orientation_3d_cost_functor.h
<reponame>congleetea/fuse<filename>fuse_constraints/include/fuse_constraints/normal_delta_orientation_3d_cost_functor.h /* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_NORMAL_DELTA_ORIENTATION_3D_COST_FUNCTOR_H #define FUSE_CONSTRAINTS_NORMAL_DELTA_ORIENTATION_3D_COST_FUNCTOR_H #include <fuse_core/eigen.h> #include <fuse_core/macros.h> #include <fuse_core/util.h> #include <fuse_variables/orientation_3d_stamped.h> #include <ceres/rotation.h> #include <Eigen/Core> namespace fuse_constraints { /** * @brief Implements a cost function that models a difference between 3D orientation variables (quaternion) * * The cost function is of the form: * * || ||^2 * cost(x) = || A * AngleAxis(b^-1 * q1^-1 * q2) || * || || * * where the matrix A and the vector b are fixed, and q1 and q2 are the variables, represented as quaternions. * The AngleAxis function converts a quaternion into a 3-vector of the form theta*k, where k is the unit vector axis * of rotation and theta is the angle of rotation. The A matrix is applied to the angle-axis 3-vector. * * In case the user is interested in implementing a cost function of the form * * cost(X) = (X - mu)^T S^{-1} (X - mu) * * where, mu is a vector and S is a covariance matrix, then, A = S^{-1/2}, i.e the matrix A is the square root * information matrix (the inverse of the covariance). */ class NormalDeltaOrientation3DCostFunctor { public: FUSE_MAKE_ALIGNED_OPERATOR_NEW(); /** * @brief Construct a cost function instance * * @param[in] A The residual weighting matrix, most likely the square root information matrix in order (x, y, z) * @param[in] b The measured change between the two orientation variables */ NormalDeltaOrientation3DCostFunctor( const fuse_core::Matrix3d& A, const fuse_core::Vector4d& b) : A_(A), b_(b) { } /** * @brief Evaluate the cost function. Used by the Ceres optimization engine. */ template <typename T> bool operator()(const T* const orientation1, const T* const orientation2, T* residuals) const { using fuse_variables::Orientation3DStamped; T orientation1_inverse[4] = { orientation1[0], -orientation1[1], -orientation1[2], -orientation1[3] }; T observation_inverse[4] = { T(b_(0)), T(-b_(1)), T(-b_(2)), T(-b_(3)) }; T difference[4]; ceres::QuaternionProduct(orientation1_inverse, orientation2, difference); T error[4]; ceres::QuaternionProduct(observation_inverse, difference, error); ceres::QuaternionToAngleAxis(error, residuals); // Scale the residuals by the square root information matrix to account for the measurement uncertainty. Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> residuals_map(residuals, A_.rows()); residuals_map.applyOnTheLeft(A_.template cast<T>()); return true; } private: fuse_core::Matrix3d A_; //!< The residual weighting matrix, most likely the square root information matrix fuse_core::Vector4d b_; //!< The measured difference between orientation1 and orientation2 }; } // namespace fuse_constraints #endif // FUSE_CONSTRAINTS_NORMAL_DELTA_ORIENTATION_3D_COST_FUNCTOR_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/marginal_constraint.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_MARGINAL_CONSTRAINT_H #define FUSE_CONSTRAINTS_MARGINAL_CONSTRAINT_H #include <fuse_core/constraint.h> #include <fuse_core/eigen.h> #include <fuse_core/local_parameterization.h> #include <fuse_core/macros.h> #include <fuse_core/serialization.h> #include <fuse_core/variable.h> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/zip_iterator.hpp> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/vector.hpp> #include <boost/tuple/tuple.hpp> #include <ceres/cost_function.h> #include <algorithm> #include <cassert> #include <ostream> #include <string> #include <vector> namespace fuse_constraints { /** * @brief A constraint that represents remaining marginal information on a set of variables * * The marginal constraint cost function is of the form: * cost = A1 * (x1 - x1_bar) + A2 * (x2 - x2_bar) + ... + b * where x_bar is the linearization point of the variable taken from the variable value at the time of construction, * and the minus operator in implemented in the variable's local parameterization. */ class MarginalConstraint : public fuse_core::Constraint { public: FUSE_CONSTRAINT_DEFINITIONS(MarginalConstraint); /** * @brief Default constructor */ MarginalConstraint() = default; /** * @brief Create a linear/marginal constraint * * The variable iterators and matrix iterators must be the same size. Further, all A matrices and the b vector must * have the same number of rows, and the number of columns of each A matrix must match the \p localSize() of its * associated variable. * * @param[in] source The name of the sensor or motion model that generated this constraint * @param[in] first_variable Iterator pointing to the first involved variable for this constraint * @param[in] last_variable Iterator pointing to one past the last involved variable for this constraint * @param[in] first_A Iterator pointing to the first A matrix, associated with the first variable * @param[in] last_A Iterator pointing to one past the last A matrix * @param[in] b The b vector of the marginal cost (of the form A*(x - x_bar) + b) */ template<typename VariableIterator, typename MatrixIterator> MarginalConstraint( const std::string& source, VariableIterator first_variable, VariableIterator last_variable, MatrixIterator first_A, MatrixIterator last_A, const fuse_core::VectorXd& b); /** * @brief Destructor */ virtual ~MarginalConstraint() = default; /** * @brief Read-only access to the A matrices of the marginal constraint */ const std::vector<fuse_core::MatrixXd>& A() const { return A_; } /** * @brief Read-only access to the b vector of the marginal constraint */ const fuse_core::VectorXd& b() const { return b_; } /** * @brief Read-only access to the variable linearization points, x_bar */ const std::vector<fuse_core::VectorXd>& x_bar() const { return x_bar_; } /** * @brief Read-only access to the variable local parameterizations */ const std::vector<fuse_core::LocalParameterization::SharedPtr>& localParameterizations() const { return local_parameterizations_; } /** * @brief Print a human-readable description of the constraint to the provided stream. * * @param[out] stream The stream to write to. Defaults to stdout. */ void print(std::ostream& stream = std::cout) const override; /** * @brief Construct an instance of this constraint's cost function * * The function caller will own the new cost function instance. It is the responsibility of the caller to delete * the cost function object when it is no longer needed. If the pointer is provided to a Ceres::Problem object, the * Ceres::Problem object will take ownership of the pointer and delete it during destruction. * * @return A base pointer to an instance of a derived CostFunction. */ ceres::CostFunction* costFunction() const override; protected: std::vector<fuse_core::MatrixXd> A_; //!< The A matrices of the marginal constraint fuse_core::VectorXd b_; //!< The b vector of the marginal constraint std::vector<fuse_core::LocalParameterization::SharedPtr> local_parameterizations_; //!< The local parameterizations std::vector<fuse_core::VectorXd> x_bar_; //!< The linearization point of each involved variable private: // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & boost::serialization::base_object<fuse_core::Constraint>(*this); archive & A_; archive & b_; archive & local_parameterizations_; archive & x_bar_; } }; namespace detail { /** * @brief Return the UUID of the provided variable */ inline const fuse_core::UUID getUuid(const fuse_core::Variable& variable) { return variable.uuid(); } /** * @brief Return the current value of the provided variable */ inline const fuse_core::VectorXd getCurrentValue(const fuse_core::Variable& variable) { return Eigen::Map<const fuse_core::VectorXd>(variable.data(), variable.size()); } /** * @brief Return the local parameterization of the provided variable */ inline fuse_core::LocalParameterization::SharedPtr const getLocalParameterization(const fuse_core::Variable& variable) { return fuse_core::LocalParameterization::SharedPtr(variable.localParameterization()); } } // namespace detail template<typename VariableIterator, typename MatrixIterator> MarginalConstraint::MarginalConstraint( const std::string& source, VariableIterator first_variable, VariableIterator last_variable, MatrixIterator first_A, MatrixIterator last_A, const fuse_core::VectorXd& b) : Constraint(source, boost::make_transform_iterator(first_variable, &fuse_constraints::detail::getUuid), boost::make_transform_iterator(last_variable, &fuse_constraints::detail::getUuid)), A_(first_A, last_A), b_(b), local_parameterizations_(boost::make_transform_iterator(first_variable, &fuse_constraints::detail::getLocalParameterization), boost::make_transform_iterator(last_variable, &fuse_constraints::detail::getLocalParameterization)), x_bar_(boost::make_transform_iterator(first_variable, &fuse_constraints::detail::getCurrentValue), boost::make_transform_iterator(last_variable, &fuse_constraints::detail::getCurrentValue)) { assert(!A_.empty()); assert(A_.size() == x_bar_.size()); assert(A_.size() == local_parameterizations_.size()); assert(b_.rows() > 0); assert(std::all_of(A_.begin(), A_.end(), [this](const auto& A){ return A.rows() == this->b_.rows(); })); // NOLINT assert(std::all_of(boost::make_zip_iterator(boost::make_tuple(A_.begin(), first_variable)), boost::make_zip_iterator(boost::make_tuple(A_.end(), last_variable)), [](const boost::tuple<const fuse_core::MatrixXd&, const fuse_core::Variable&>& tuple) // NOLINT { return static_cast<size_t>(tuple.get<0>().cols()) == tuple.get<1>().localSize(); })); // NOLINT } } // namespace fuse_constraints BOOST_CLASS_EXPORT_KEY(fuse_constraints::MarginalConstraint); #endif // FUSE_CONSTRAINTS_MARGINAL_CONSTRAINT_H
congleetea/fuse
fuse_optimizers/include/fuse_optimizers/variable_stamp_index.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_OPTIMIZERS_VARIABLE_STAMP_INDEX_H #define FUSE_OPTIMIZERS_VARIABLE_STAMP_INDEX_H #include <fuse_core/macros.h> #include <fuse_core/transaction.h> #include <fuse_core/uuid.h> #include <ros/time.h> #include <unordered_map> #include <unordered_set> #include <vector> namespace fuse_optimizers { /** * @brief Object designed to track the timestamps associated with each variable * * If the variable is derived from a fuse_variables::Stamped type, then the variable's stamp is used. If a variable * is not derived from a fuse_variables::Stamped type, then the timestamp of the newest fuse_variables::Stamped * variable *directly connected* to the unstamped variable is used. If an unstamped variable is not directly connected * to any variable, then it is assigned a zero timestamp. */ class VariableStampIndex { public: SMART_PTR_DEFINITIONS(VariableStampIndex); /** * @brief Constructor */ VariableStampIndex() = default; /** * @brief Destructor */ virtual ~VariableStampIndex() = default; /** * @brief Return true if no variables exist in the index */ bool empty() const { return stamped_index_.empty() && unstamped_index_.empty(); } /** * @brief Returns the number of variables in the index */ size_t size() const { return stamped_index_.size() + unstamped_index_.size(); } /** * @brief Clear all tracked state */ void clear() { stamped_index_.clear(); unstamped_index_.clear(); } /** * @brief Returns the most recent timestamp associated with any variable */ ros::Time currentStamp() const; /** * @brief Access the timestamp associated with a specific variable * * If the requested variable does not exist, an out_of_range exception will be thrown */ ros::Time at(const fuse_core::UUID& variable) const; /** * @brief Update the index with the information from the added transactions * * @param[in] transaction The set of variables and constraints to add and remove */ void addNewTransaction(const fuse_core::Transaction& transaction); /** * @brief Update the index with the information from a marginal transaction * * Only a subset of information is used from the marginal transaction. We do not want to track the variable * connections induced by marginal factors. * * @param[in] transaction The set of variables and constraints to remove */ void addMarginalTransaction(const fuse_core::Transaction& transaction); /** * @brief Add all variables with a timestamp less than the provided stamp to the output container * * @param[in] stamp The reference timestamp. Only variables associated with timestamps less than this will be * added to the output container * @param[out] result An output iterator capable of receiving fuse_core::UUID objects */ template <typename OutputUuidIterator> void query(const ros::Time& stamp, OutputUuidIterator result) const { for (const auto& variable_stamp_pair : stamped_index_) { if (variable_stamp_pair.second < stamp) { *result = variable_stamp_pair.first; ++result; } } for (const auto& variable_constraints_pair : unstamped_index_) { auto max_stamp = getMaxConstraintStamp(variable_constraints_pair.second); if (max_stamp < stamp) { *result = variable_constraints_pair.first; ++result; } } } protected: using StampedMap = std::unordered_map<fuse_core::UUID, ros::Time, fuse_core::uuid::hash>; StampedMap stamped_index_; //!< Container that holds the UUID->Stamp mapping for fuse_variables::Stamped variables using ConstraintInfo = std::unordered_map<fuse_core::UUID, ros::Time, fuse_core::uuid::hash>; using UnstampedMap = std::unordered_map<fuse_core::UUID, ConstraintInfo, fuse_core::uuid::hash>; UnstampedMap unstamped_index_; //!< Container holding the UnstampedUUID->{Constraints} mapping /** * @brief Update this VariableStampIndex with the added constraints from the provided transaction */ void applyAddedConstraints(const fuse_core::Transaction& transaction); /** * @brief Update this VariableStampIndex with the added variables from the provided transaction */ void applyAddedVariables(const fuse_core::Transaction& transaction); /** * @brief Update this VariableStampIndex with the removed constraints from the provided transaction */ void applyRemovedConstraints(const fuse_core::Transaction& transaction); /** * @brief Update this VariableStampIndex with the removed variables from the provided transaction */ void applyRemovedVariables(const fuse_core::Transaction& transaction); /** * @brief Find the max stamp inside a ConstraintInfo object */ ros::Time getMaxConstraintStamp(const ConstraintInfo& constraints) const; }; } // namespace fuse_optimizers #endif // FUSE_OPTIMIZERS_VARIABLE_STAMP_INDEX_H
congleetea/fuse
fuse_models/include/fuse_models/parameters/odometry_2d_publisher_params.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_PARAMETERS_ODOMETRY_2D_PUBLISHER_PARAMS_H #define FUSE_MODELS_PARAMETERS_ODOMETRY_2D_PUBLISHER_PARAMS_H #include <fuse_models/parameters/parameter_base.h> #include <fuse_core/ceres_options.h> #include <ros/console.h> #include <ros/node_handle.h> #include <ceres/covariance.h> #include <cassert> #include <string> #include <vector> namespace fuse_models { namespace parameters { /** * @brief Defines the set of parameters required by the Odometry2DPublisher class */ struct Odometry2DPublisherParams : public ParameterBase { public: /** * @brief Method for loading parameter values from ROS. * * @param[in] nh - The ROS node handle with which to load parameters */ void loadFromROS(const ros::NodeHandle& nh) final { nh.getParam("publish_tf", publish_tf); nh.getParam("predict_to_current_time", predict_to_current_time); nh.getParam("tf_publish_frequency", tf_publish_frequency); double tf_cache_time_double = tf_cache_time.toSec(); nh.getParam("tf_cache_time", tf_cache_time_double); tf_cache_time.fromSec(tf_cache_time_double); double tf_timeout_double = tf_timeout.toSec(); nh.getParam("tf_timeout", tf_timeout_double); tf_timeout.fromSec(tf_timeout_double); nh.getParam("queue_size", queue_size); nh.getParam("map_frame_id", map_frame_id); nh.getParam("odom_frame_id", odom_frame_id); nh.getParam("base_link_frame_id", base_link_frame_id); nh.param("base_link_output_frame_id", base_link_output_frame_id, base_link_frame_id); nh.param("world_frame_id", world_frame_id, odom_frame_id); const bool frames_valid = map_frame_id != odom_frame_id && map_frame_id != base_link_frame_id && map_frame_id != base_link_output_frame_id && odom_frame_id != base_link_frame_id && odom_frame_id != base_link_output_frame_id && (world_frame_id == map_frame_id || world_frame_id == odom_frame_id); if (!frames_valid) { ROS_FATAL_STREAM("Invalid frame configuration! Please note:\n" << " - The values for map_frame_id, odom_frame_id, and base_link_frame_id must be unique\n" << " - The values for map_frame_id, odom_frame_id, and base_link_output_frame_id must be unique\n" << " - The world_frame_id must be the same as the map_frame_id or odom_frame_id\n"); assert(frames_valid); } nh.getParam("topic", topic); fuse_core::loadCovarianceOptionsFromROS(ros::NodeHandle(nh, "covariance_options"), covariance_options); } bool publish_tf { true }; bool predict_to_current_time { false }; double tf_publish_frequency { 10.0 }; ros::Duration tf_cache_time { 10.0 }; ros::Duration tf_timeout { 0.1 }; int queue_size { 1 }; std::string map_frame_id { "map" }; std::string odom_frame_id { "odom" }; std::string base_link_frame_id { "base_link" }; std::string base_link_output_frame_id { base_link_frame_id }; std::string world_frame_id { odom_frame_id }; std::string topic { "odometry/filtered" }; ceres::Covariance::Options covariance_options; }; } // namespace parameters } // namespace fuse_models #endif // FUSE_MODELS_PARAMETERS_ODOMETRY_2D_PUBLISHER_PARAMS_H
congleetea/fuse
fuse_models/include/fuse_models/common/sensor_config.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_COMMON_SENSOR_CONFIG_H #define FUSE_MODELS_COMMON_SENSOR_CONFIG_H #include <fuse_models/common/variable_traits.h> #include <boost/algorithm/string/case_conv.hpp> #include <fuse_variables/acceleration_linear_2d_stamped.h> #include <fuse_variables/orientation_2d_stamped.h> #include <fuse_variables/position_2d_stamped.h> #include <fuse_variables/velocity_angular_2d_stamped.h> #include <fuse_variables/velocity_linear_2d_stamped.h> #include <ros/console.h> #include <algorithm> #include <functional> #include <stdexcept> #include <string> #include <vector> namespace fuse_models { namespace common { /** * @brief Utility method for printing and throwing an error for invalid dimension specification * @param[in] dimension - The erroneous dimension name * @throws runtime_error */ inline void throwDimensionError(const std::string& dimension) { std::string error = "Dimension " + dimension + " is not valid for this type."; ROS_ERROR_STREAM(error); throw std::runtime_error(error); } /** * @brief Method that converts from 2D linear axis dimension names to index values * * This method is enabled only for variables that contain _only_ 2D linear quantities * * @param[in] dimension - The dimension name to convert * @return the index of the enumerated dimension for that type * @throws runtime_error if the dimension name is invalid */ template <typename T> typename std::enable_if<is_linear_2d<T>::value, size_t>::type toIndex(const std::string& dimension) { auto lower_dim = boost::algorithm::to_lower_copy(dimension); if (lower_dim == "x") return static_cast<size_t>(T::X); if (lower_dim == "y") return static_cast<size_t>(T::Y); throwDimensionError(dimension); return 0u; } /** * @brief Method that converts from 2D angular axis dimension names to index values * * This method is enabled only for variables that contain _only_ 2D angular quantities * * @param[in] dimension - The dimension name to convert * @return the index of the enumerated dimension for that type * @throws runtime_error if the dimension name is invalid */ template <typename T> typename std::enable_if<is_angular_2d<T>::value, size_t>::type toIndex(const std::string& dimension) { auto lower_dim = boost::algorithm::to_lower_copy(dimension); if (lower_dim == "yaw" || lower_dim == "z") return static_cast<size_t>(fuse_variables::Orientation2DStamped::YAW); throwDimensionError(dimension); return 0u; } /** * @brief Utility method to convert a vector of dimension names to a vector of dimension indices * * Note that the dimensions are sorted, and so the order in which the user specifies them will have no bearing when * the measurement vectors and covariances are actually built elsewhere. * * @param[in] dimension_names - The dimension names to convert * @return a vector of indices that are consistent with the enumerations for that variable type * @throws runtime_error if any dimension name is invalid */ template <typename T> std::vector<size_t> getDimensionIndices(const std::vector<std::string>& dimension_names) { std::vector<size_t> indices; indices.reserve(dimension_names.size()); std::transform( dimension_names.begin(), dimension_names.end(), std::back_inserter(indices), toIndex<T>); // Remove duplicates std::sort(indices.begin(), indices.end()); indices.erase(std::unique(indices.begin(), indices.end()), indices.end()); return indices; } } // namespace common } // namespace fuse_models #endif // FUSE_MODELS_COMMON_SENSOR_CONFIG_H
congleetea/fuse
fuse_core/include/fuse_core/graph_deserializer.h
<reponame>congleetea/fuse /* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_GRAPH_DESERIALIZER_H #define FUSE_CORE_GRAPH_DESERIALIZER_H #include <fuse_msgs/SerializedGraph.h> #include <fuse_core/constraint.h> #include <fuse_core/graph.h> #include <fuse_core/variable.h> #include <pluginlib/class_loader.h> namespace fuse_core { /** * @brief Serialize a graph into a message */ void serializeGraph(const fuse_core::Graph& graph, fuse_msgs::SerializedGraph& msg); /** * @brief Deserialize a graph * * The deserializer object loads all of the known Variable and Constraint libraries, allowing derived types contained * within the graph to be properly deserialized. The libraries will be unloaded on destruction. As a consequence, the * deserializer object must outlive any created graph instances. */ class GraphDeserializer { public: /** * @brief Constructor */ GraphDeserializer(); /** * @brief Deserialize a SerializedGraph message into a fuse Graph object. * * If no plugin is available for a contained Variable or Constraint, or an error occurs during deserialization, * an exception is thrown. * * @param[in] msg The SerializedGraph message to be deserialized * @return A unique_ptr to a derived Graph object */ fuse_core::Graph::UniquePtr deserialize(const fuse_msgs::SerializedGraph::ConstPtr& msg); /** * @brief Deserialize a SerializedGraph message into a fuse Graph object. * * If no plugin is available for a contained Variable or Constraint, or an error occurs during deserialization, * an exception is thrown. * * @param[in] msg The SerializedGraph message to be deserialized * @return A unique_ptr to a derived Graph object */ fuse_core::Graph::UniquePtr deserialize(const fuse_msgs::SerializedGraph& msg); private: pluginlib::ClassLoader<fuse_core::Variable> variable_loader_; //!< Pluginlib class loader for Variable types pluginlib::ClassLoader<fuse_core::Constraint> constraint_loader_; //!< Pluginlib class loader for Constraint types pluginlib::ClassLoader<fuse_core::Graph> graph_loader_; //!< Pluginlib class loader for Graph types }; } // namespace fuse_core #endif // FUSE_CORE_GRAPH_DESERIALIZER_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/normal_prior_pose_2d_cost_functor.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_NORMAL_PRIOR_POSE_2D_COST_FUNCTOR_H #define FUSE_CONSTRAINTS_NORMAL_PRIOR_POSE_2D_COST_FUNCTOR_H #include <fuse_core/eigen.h> #include <fuse_core/macros.h> #include <fuse_core/util.h> #include <Eigen/Core> namespace fuse_constraints { /** * @brief Create a prior cost function on both the position and orientation variables at once. * * The Ceres::NormalPrior cost function only supports a single variable. This is a convenience cost function that * applies a prior constraint on both the position and orientation variables at once. * * The cost function is of the form: * * || [ x - b(0)] ||^2 * cost(x) = ||A * [ y - b(1)] || * || [yaw - b(2)] || * * Here, the matrix A can be of variable size, thereby permitting the computation of errors for partial measurements. * The vector b is a fixed-size 3x1. In case the user is interested in implementing a cost function of the form: * * cost(X) = (X - mu)^T S^{-1} (X - mu) * * where, mu is a vector and S is a covariance matrix, then, A = S^{-1/2}, i.e the matrix A is the square root * information matrix (the inverse of the covariance). */ class NormalPriorPose2DCostFunctor { public: /** * @brief Construct a cost function instance * * The residual weighting matrix can vary in size, as this cost functor can be used to compute costs for partial * vectors. The number of rows of A will be the number of dimensions for which you want to compute the error, and the * number of columns in A will be fixed at 3. For example, if we just want to use the values of x and yaw, then \p A * will be of size 2x3. * * @param[in] A The residual weighting matrix, most likely the square root information matrix in order (x, y, yaw) * @param[in] b The pose measurement or prior in order (x, y, yaw) */ NormalPriorPose2DCostFunctor(const fuse_core::MatrixXd& A, const fuse_core::Vector3d& b); /** * @brief Evaluate the cost function. Used by the Ceres optimization engine. */ template <typename T> bool operator()(const T* const position, const T* const orientation, T* residual) const; private: fuse_core::MatrixXd A_; //!< The residual weighting matrix, most likely the square root information matrix fuse_core::Vector3d b_; //!< The measured 2D pose value }; NormalPriorPose2DCostFunctor::NormalPriorPose2DCostFunctor(const fuse_core::MatrixXd& A, const fuse_core::Vector3d& b) : A_(A), b_(b) { } template <typename T> bool NormalPriorPose2DCostFunctor::operator()(const T* const position, const T* const orientation, T* residual) const { Eigen::Matrix<T, 3, 1> full_residuals_vector; full_residuals_vector(0) = position[0] - T(b_(0)); full_residuals_vector(1) = position[1] - T(b_(1)); full_residuals_vector(2) = fuse_core::wrapAngle2D(orientation[0] - T(b_(2))); // Scale the residuals by the square root information matrix to account for // the measurement uncertainty. Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> residuals_vector(residual, A_.rows()); residuals_vector = A_.template cast<T>() * full_residuals_vector; return true; } } // namespace fuse_constraints #endif // FUSE_CONSTRAINTS_NORMAL_PRIOR_POSE_2D_COST_FUNCTOR_H
congleetea/fuse
fuse_models/include/fuse_models/unicycle_2d_predict.h
<reponame>congleetea/fuse /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_UNICYCLE_2D_PREDICT_H #define FUSE_MODELS_UNICYCLE_2D_PREDICT_H #include <ceres/jet.h> #include <fuse_core/util.h> #include <tf2_2d/tf2_2d.h> namespace fuse_models { /** * @brief Given a state and time delta, predicts a new state * @param[in] position1_x - First X position * @param[in] position1_y - First Y position * @param[in] yaw1 - First orientation * @param[in] vel_linear1_x - First X velocity * @param[in] vel_linear1_y - First Y velocity * @param[in] vel_yaw1 - First yaw velocity * @param[in] acc_linear1_x - First X acceleration * @param[in] acc_linear1_y - First Y acceleration * @param[in] dt - The time delta across which to predict the state * @param[in] position2_x - Second X position * @param[in] position2_y - Second Y position * @param[in] yaw2 - Second orientation * @param[in] vel_linear2_x - Second X velocity * @param[in] vel_linear2_y - Second Y velocity * @param[in] vel_yaw2 - Second yaw velocity * @param[in] acc_linear2_x - Second X acceleration * @param[in] acc_linear2_y - Second Y acceleration */ template<typename T> inline void predict( const T position1_x, const T position1_y, const T yaw1, const T vel_linear1_x, const T vel_linear1_y, const T vel_yaw1, const T acc_linear1_x, const T acc_linear1_y, const T dt, T& position2_x, T& position2_y, T& yaw2, T& vel_linear2_x, T& vel_linear2_y, T& vel_yaw2, T& acc_linear2_x, T& acc_linear2_y) { // There are better models for this projection, but this matches the one used by r_l. T sy = ceres::sin(yaw1); // Should probably be sin((yaw1 + yaw2) / 2), but r_l uses this model T cy = ceres::cos(yaw1); T delta_x = vel_linear1_x * dt + T(0.5) * acc_linear1_x * dt * dt; T delta_y = vel_linear1_y * dt + T(0.5) * acc_linear1_y * dt * dt; position2_x = position1_x + cy * delta_x - sy * delta_y; position2_y = position1_y + sy * delta_x + cy * delta_y; yaw2 = yaw1 + vel_yaw1 * dt; vel_linear2_x = vel_linear1_x + acc_linear1_x * dt; vel_linear2_y = vel_linear1_y + acc_linear1_y * dt; vel_yaw2 = vel_yaw1; acc_linear2_x = acc_linear1_x; acc_linear2_y = acc_linear1_y; fuse_core::wrapAngle2D(yaw2); } /** * @brief Given a state and time delta, predicts a new state * @param[in] position1 - First position (array with x at index 0, y at index 1) * @param[in] yaw1 - First orientation * @param[in] vel_linear1 - First velocity (array with x at index 0, y at index 1) * @param[in] vel_yaw1 - First yaw velocity * @param[in] acc_linear1 - First linear acceleration (array with x at index 0, y at index 1) * @param[in] dt - The time delta across which to predict the state * @param[out] position2 - Second position (array with x at index 0, y at index 1) * @param[out] yaw2 - Second orientation * @param[out] vel_linear2 - Second velocity (array with x at index 0, y at index 1) * @param[out] vel_yaw2 - Second yaw velocity * @param[out] acc_linear2 - Second linear acceleration (array with x at index 0, y at index 1) */ template<typename T> inline void predict( const T* const position1, const T* const yaw1, const T* const vel_linear1, const T* const vel_yaw1, const T* const acc_linear1, const T dt, T* const position2, T* const yaw2, T* const vel_linear2, T* const vel_yaw2, T* const acc_linear2) { predict( position1[0], position1[1], *yaw1, vel_linear1[0], vel_linear1[1], *vel_yaw1, acc_linear1[0], acc_linear1[1], dt, position2[0], position2[1], *yaw2, vel_linear2[0], vel_linear2[1], *vel_yaw2, acc_linear2[0], acc_linear2[1]); } /** * @brief Given a state and time delta, predicts a new state * @param[in] pose1 - The first 2D pose * @param[in] vel_linear_1 - The first linear velocity * @param[in] vel_yaw1 - The first yaw velocity * @param[in] acc_linear1 - The first linear acceleration * @param[in] dt - The time delta across which to predict the state * @param[in] pose2 - The second 2D pose * @param[in] vel_linear_2 - The second linear velocity * @param[in] vel_yaw2 - The second yaw velocity * @param[in] acc_linear2 - The second linear acceleration */ inline void predict( const tf2_2d::Transform& pose1, const tf2_2d::Vector2& vel_linear1, const double vel_yaw1, const tf2_2d::Vector2& acc_linear1, const double dt, tf2_2d::Transform& pose2, tf2_2d::Vector2& vel_linear2, double& vel_yaw2, tf2_2d::Vector2& acc_linear2) { double x_pred {}; double y_pred {}; double yaw_pred {}; double vel_linear_x_pred {}; double vel_linear_y_pred {}; double acc_linear_x_pred {}; double acc_linear_y_pred {}; predict( pose1.x(), pose1.y(), pose1.yaw(), vel_linear1.x(), vel_linear1.y(), vel_yaw1, acc_linear1.x(), acc_linear1.y(), dt, x_pred, y_pred, yaw_pred, vel_linear_x_pred, vel_linear_y_pred, vel_yaw2, acc_linear_x_pred, acc_linear_y_pred); pose2.setX(x_pred); pose2.setY(y_pred); pose2.setYaw(yaw_pred); vel_linear2.setX(vel_linear_x_pred); vel_linear2.setY(vel_linear_y_pred); acc_linear2.setX(acc_linear_x_pred); acc_linear2.setY(acc_linear_y_pred); } } // namespace fuse_models #endif // FUSE_MODELS_UNICYCLE_2D_PREDICT_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/normal_prior_pose_3d_cost_functor.h
<reponame>congleetea/fuse /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_NORMAL_PRIOR_POSE_3D_COST_FUNCTOR_H #define FUSE_CONSTRAINTS_NORMAL_PRIOR_POSE_3D_COST_FUNCTOR_H #include <fuse_constraints/normal_prior_orientation_3d_cost_functor.h> #include <fuse_core/eigen.h> #include <fuse_core/macros.h> #include <fuse_core/util.h> #include <Eigen/Core> namespace fuse_constraints { /** * @brief Create a prior cost function on both the 3D position and orientation variables at once. * * The Ceres::NormalPrior cost function only supports a single variable. This is a convenience cost function that * applies a prior constraint on both the 3D position and orientation variables at once. * * The cost function is of the form: * * cost(x) = || A * [ p - b(0:2) ] ||^2 * || [ AngleAxis(b(3:6)^-1 * q) ] || * * where, the matrix A and the vector b are fixed, p is the position variable, and q is the orientation variable. * Note that the covariance submatrix for the quaternion is 3x3, representing errors in the orientation local * parameterization tangent space. In case the user is interested in implementing a cost function of the form * * cost(X) = (X - mu)^T S^{-1} (X - mu) * * where, mu is a vector and S is a covariance matrix, then, A = S^{-1/2}, i.e the matrix A is the square root * information matrix (the inverse of the covariance). */ class NormalPriorPose3DCostFunctor { public: FUSE_MAKE_ALIGNED_OPERATOR_NEW(); /** * @brief Construct a cost function instance * * @param[in] A The residual weighting matrix, most likely the square root information matrix in order * (x, y, z, qx, qy, qz) * @param[in] b The 3D pose measurement or prior in order (x, y, z, qw, qx, qy, qz) */ NormalPriorPose3DCostFunctor(const fuse_core::Matrix6d& A, const fuse_core::Vector7d& b); /** * @brief Evaluate the cost function. Used by the Ceres optimization engine. */ template <typename T> bool operator()(const T* const position, const T* const orientation, T* residual) const; private: fuse_core::Matrix6d A_; fuse_core::Vector7d b_; NormalPriorOrientation3DCostFunctor orientation_functor_; }; NormalPriorPose3DCostFunctor::NormalPriorPose3DCostFunctor(const fuse_core::Matrix6d& A, const fuse_core::Vector7d& b) : A_(A), b_(b), orientation_functor_(fuse_core::Matrix3d::Identity(), b_.tail<4>()) // Delta will not be scaled { } template <typename T> bool NormalPriorPose3DCostFunctor::operator()(const T* const position, const T* const orientation, T* residual) const { // Compute the position error residual[0] = position[0] - T(b_(0)); residual[1] = position[1] - T(b_(1)); residual[2] = position[2] - T(b_(2)); // Use the 3D orientation cost functor to compute the orientation delta orientation_functor_(orientation, &residual[3]); // Scale the residuals by the square root information matrix to account for // the measurement uncertainty. Eigen::Map<Eigen::Matrix<T, 6, 1>> residual_map(residual); residual_map.applyOnTheLeft(A_.template cast<T>()); return true; } } // namespace fuse_constraints #endif // FUSE_CONSTRAINTS_NORMAL_PRIOR_POSE_3D_COST_FUNCTOR_H
congleetea/fuse
fuse_optimizers/include/fuse_optimizers/optimizer.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_OPTIMIZERS_OPTIMIZER_H #define FUSE_OPTIMIZERS_OPTIMIZER_H #include <fuse_core/graph.h> #include <fuse_core/macros.h> #include <fuse_core/motion_model.h> #include <fuse_core/publisher.h> #include <fuse_core/sensor_model.h> #include <fuse_core/transaction.h> #include <pluginlib/class_loader.h> #include <ros/ros.h> #include <string> #include <unordered_map> #include <vector> namespace fuse_optimizers { /** * @brief A base class that can be used to build fuse optimizer nodes * * An optimizer implements the basic fuse information flow contract: * - Sensors push information into the optimizer using the transaction callback * - The optimizer requests motion models be created between each sensor timestamp * - The optimizer computes the optimal variable values * - The optimizer provides access to the optimal variable values to the publishers * * Optimizer implementations are not required to use this base class; it is simply provided as a convenience * class that implements the mechanics of the information flow contract. Derived classes can then concentrate * on the details of when and what to optimize. * * This base class provides functions for: * - Loading the set of motion model plugins as configured on the parameter server * - Loading the set of publisher plugins as configured on the parameter server * - Loading the set of sensor plugins as configured on the parameter server * - Generating the correct motion model constraints for each received sensor transaction * - Sending updated variable information to the sensors, motion models, and publishers * * Parameter Server format: * @code{.yaml} * motion_models: * - name: string * type: string * - ... * sensor_models: * - name: string * type: string * motion_models: [name1, name2, ...] * - ... * publishers: * - name: string * type: string * - ... * @endcode */ class Optimizer { public: SMART_PTR_ALIASES_ONLY(Optimizer); /** * @brief Constructor * * @param[in] graph The derived graph object. This allows different graph implementations to be used * with the same optimizer code. * @param[in] node_handle A node handle in the global namespace * @param[in] private_node_handle A node handle in the node's private namespace */ Optimizer( fuse_core::Graph::UniquePtr graph, const ros::NodeHandle& node_handle = ros::NodeHandle(), const ros::NodeHandle& private_node_handle = ros::NodeHandle("~")); /** * @brief Destructor */ virtual ~Optimizer(); protected: // The unique ptrs returned by pluginlib have a custom deleter. This makes specifying the type rather annoying // as it is not equivalent to Class::UniquePtr using MotionModelUniquePtr = class_loader::ClassLoader::UniquePtr<fuse_core::MotionModel>; using MotionModels = std::unordered_map<std::string, MotionModelUniquePtr>; using PublisherUniquePtr = class_loader::ClassLoader::UniquePtr<fuse_core::Publisher>; using Publishers = std::unordered_map<std::string, PublisherUniquePtr>; using SensorModelUniquePtr = class_loader::ClassLoader::UniquePtr<fuse_core::SensorModel>; using SensorModels = std::unordered_map<std::string, SensorModelUniquePtr>; // Some internal book-keeping data structures using MotionModelGroup = std::vector<std::string>; //!< A set of motion model names using AssociatedMotionModels = std::unordered_map<std::string, MotionModelGroup>; //!< sensor -> motion models group AssociatedMotionModels associated_motion_models_; //!< Tracks what motion models should be used for each sensor fuse_core::Graph::UniquePtr graph_; //!< The graph object that holds all variables and constraints // Ordering ROS objects with callbacks last ros::NodeHandle node_handle_; //!< Node handle in the public namespace for subscribing and advertising ros::NodeHandle private_node_handle_; //!< Node handle in the private namespace for reading configuration settings pluginlib::ClassLoader<fuse_core::MotionModel> motion_model_loader_; //!< Pluginlib class loader for MotionModels MotionModels motion_models_; //!< The set of motion models, addressable by name pluginlib::ClassLoader<fuse_core::Publisher> publisher_loader_; //!< Pluginlib class loader for Publishers Publishers publishers_; //!< The set of publishers to execute after every graph optimization pluginlib::ClassLoader<fuse_core::SensorModel> sensor_model_loader_; //!< Pluginlib class loader for SensorModels SensorModels sensor_models_; //!< The set of sensor models, addressable by name /** * @brief Callback fired every time a SensorModel plugin creates a new transaction * * @param[in] sensor_name The name of the sensor that produced the Transaction * @param[in] stamps Any timestamps associated with the added variables. These are sent to the motion models * to generate connected constraints. * @param[in] transaction The populated Transaction object created by the loaded SensorModel plugin */ virtual void transactionCallback( const std::string& sensor_name, fuse_core::Transaction::SharedPtr transaction) = 0; /** * @brief Configure the motion model plugins specified on the parameter server * * Will throw if the parameter server configuration is invalid. */ void loadMotionModels(); /** * @brief Configure the publisher plugins specified on the parameter server * * Will throw if the parameter server configuration is invalid. */ void loadPublishers(); /** * @brief Configure the sensor model plugins specified on the parameter server * * Will throw if the parameter server configuration is invalid. */ void loadSensorModels(); /** * @brief Given a transaction and some timestamps, augment the transaction with constraints from all associated * motion models. * * If no timestamps are provided, or no motion models are associated with this sensor, the transaction is left * unmodified. If an associated motion model is unavailable, this will throw an exception. * * @param[in] name The name of the sensor that produced the Transaction * @param[in] timestamps Any timestamps associated with the added variables. These are sent to the motion models * to generate connected constraints. * @param[out] transaction The Transaction object will be augmented with constraints and variables from the motion * models * @return Flag indicating if all motion model constraints were successfully generated */ bool applyMotionModels( const std::string& sensor_name, fuse_core::Transaction& transaction) const; /** * @brief Send the sensors, motion models, and publishers updated graph information * * @param[in] transaction A read-only pointer to a transaction containing all recent additions and removals * @param[in] graph A read-only pointer to the graph object */ void notify( fuse_core::Transaction::ConstSharedPtr transaction, fuse_core::Graph::ConstSharedPtr graph); /** * @brief Inject a transaction callback function into the global callback queue * * @param[in] sensor_name The name of the sensor that produced the Transaction * @param[in] transaction The populated Transaction object created by the loaded SensorModel plugin */ void injectCallback( const std::string& sensor_name, fuse_core::Transaction::SharedPtr transaction); /** * @brief Clear all of the callbacks inserted into the callback queue by the injectCallback() method */ void clearCallbacks(); /** * @brief Start all configured plugins (motion models, publishers, and sensor models) */ void startPlugins(); /** * @brief Stop all configured plugins (motion models, publishers, and sensor models) */ void stopPlugins(); }; } // namespace fuse_optimizers #endif // FUSE_OPTIMIZERS_OPTIMIZER_H
congleetea/fuse
fuse_models/include/fuse_models/parameters/parameter_base.h
<reponame>congleetea/fuse /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_PARAMETERS_PARAMETER_BASE_H #define FUSE_MODELS_PARAMETERS_PARAMETER_BASE_H #include <fuse_models/common/sensor_config.h> #include <ros/node_handle.h> #include <stdexcept> #include <string> #include <vector> namespace fuse_models { namespace parameters { struct ParameterBase { ParameterBase() = default; virtual ~ParameterBase() = default; /** * @brief Method for loading parameter values from ROS. * * @param[in] nh - The ROS node handle with which to load parameters */ virtual void loadFromROS(const ros::NodeHandle& nh) = 0; }; /** * @brief Utility method for handling required ROS params * * @param[in] nh - The ROS node handle with which to load parameters * @param[in] key - The ROS parameter key for the required parameter * @param[out] value - The ROS parameter value for the \p key * @throws std::runtime_error if the parameter does not exist */ template <typename T> void getParamRequired(const ros::NodeHandle& nh, const std::string& key, T& value) { if (!nh.getParam(key, value)) { const std::string error = "Could not find required parameter " + key + " in namespace " + nh.getNamespace(); ROS_FATAL_STREAM(error); throw std::runtime_error(error); } } template <typename T> inline std::vector<size_t> loadSensorConfig(const ros::NodeHandle& nh, const std::string& name) { std::vector<std::string> dimensions; if (nh.getParam(name, dimensions)) { return common::getDimensionIndices<T>(dimensions); } return {}; } } // namespace parameters } // namespace fuse_models #endif // FUSE_MODELS_PARAMETERS_PARAMETER_BASE_H
congleetea/fuse
fuse_models/include/fuse_models/unicycle_2d_state_cost_functor.h
<gh_stars>0 /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_UNICYCLE_2D_STATE_COST_FUNCTOR_H #define FUSE_MODELS_UNICYCLE_2D_STATE_COST_FUNCTOR_H #include <fuse_models/unicycle_2d_predict.h> #include <fuse_core/eigen.h> #include <fuse_core/macros.h> #include <fuse_core/util.h> namespace fuse_models { /** * @brief Create a cost function for a 2D state vector * * The state vector includes the following quantities, given in this order: * x position * y position * yaw (rotation about the z axis) * x velocity * yaw velocity * x acceleration * y acceleration * * The Ceres::NormalPrior cost function only supports a single variable. This is a convenience cost function that * applies a prior constraint on both the entire state vector. * * The cost function is of the form: * * || [ x_t2 - proj(x_t1) ] ||^2 * cost(x) = || [ y_t2 - proj(y_t1) ] || * || [ yaw_t2 - proj(yaw_t1) ] || * ||A * [ x_vel_t2 - proj(x_vel_t1) ] || * || [ y_vel_t2 - proj(y_vel_t1) ] || * || [ yaw_vel_t2 - proj(yaw_vel_t1) ] || * || [ x_acc_t2 - proj(x_acc_t1) ] || * || [ y_acc_t2 - proj(y_acc_t1) ] || * * where, the matrix A is fixed, the state variables are provided at two discrete time steps, and proj is a function * that projects the state variables from time t1 to time t2. In case the user is interested in implementing a cost * function of the form * * cost(X) = (X - mu)^T S^{-1} (X - mu) * * where, mu is a vector and S is a covariance matrix, then, A = S^{-1/2}, i.e the matrix A is the square root * information matrix (the inverse of the covariance). */ class Unicycle2DStateCostFunctor { public: FUSE_MAKE_ALIGNED_OPERATOR_NEW(); /** * @brief Construct a cost function instance * * @param[in] dt The time delta across which to generate the kinematic model cost * @param[in] A The residual weighting matrix, most likely the square root information matrix in order * (x, y, yaw, x_vel, y_vel, yaw_vel, x_acc, y_acc) */ Unicycle2DStateCostFunctor(const double dt, const fuse_core::Matrix8d& A); /** * @brief Evaluate the cost function. Used by the Ceres optimization engine. * @param[in] position1 - First position (array with x at index 0, y at index 1) * @param[in] yaw1 - First yaw * @param[in] vel_linear1 - First linear velocity (array with x at index 0, y at index 1) * @param[in] vel_yaw1 - First yaw velocity * @param[in] acc_linear1 - First linear acceleration (array with x at index 0, y at index 1) * @param[in] position2 - Second position (array with x at index 0, y at index 1) * @param[in] yaw2 - Second yaw * @param[in] vel_linear2 - Second linear velocity (array with x at index 0, y at index 1) * @param[in] vel_yaw2 - Second yaw velocity * @param[in] acc_linear2 - Second linear acceleration (array with x at index 0, y at index 1) * @param[out] residual - The computed residual (error) */ template <typename T> bool operator()( const T* const position1, const T* const yaw1, const T* const vel_linear1, const T* const vel_yaw1, const T* const acc_linear1, const T* const position2, const T* const yaw2, const T* const vel_linear2, const T* const vel_yaw2, const T* const acc_linear2, T* residual) const; private: double dt_; fuse_core::Matrix8d A_; //!< The residual weighting matrix, most likely the square root information matrix }; Unicycle2DStateCostFunctor::Unicycle2DStateCostFunctor(const double dt, const fuse_core::Matrix8d& A) : dt_(dt), A_(A) { } template <typename T> bool Unicycle2DStateCostFunctor::operator()( const T* const position1, const T* const yaw1, const T* const vel_linear1, const T* const vel_yaw1, const T* const acc_linear1, const T* const position2, const T* const yaw2, const T* const vel_linear2, const T* const vel_yaw2, const T* const acc_linear2, T* residual) const { T position_pred[2]; T yaw_pred[1]; T vel_linear_pred[2]; T vel_yaw_pred[1]; T acc_linear_pred[2]; predict( position1, yaw1, vel_linear1, vel_yaw1, acc_linear1, T(dt_), position_pred, yaw_pred, vel_linear_pred, vel_yaw_pred, acc_linear_pred); Eigen::Map<Eigen::Matrix<T, 8, 1>> residuals_map(residual); residuals_map(0) = position2[0] - position_pred[0]; residuals_map(1) = position2[1] - position_pred[1]; residuals_map(2) = yaw2[0] - yaw_pred[0]; residuals_map(3) = vel_linear2[0] - vel_linear_pred[0]; residuals_map(4) = vel_linear2[1] - vel_linear_pred[1]; residuals_map(5) = vel_yaw2[0] - vel_yaw_pred[0]; residuals_map(6) = acc_linear2[0] - acc_linear_pred[0]; residuals_map(7) = acc_linear2[1] - acc_linear_pred[1]; fuse_core::wrapAngle2D(residuals_map(2)); // Scale the residuals by the square root information matrix to account for // the measurement uncertainty. residuals_map.applyOnTheLeft(A_.template cast<T>()); return true; } } // namespace fuse_models #endif // FUSE_MODELS_UNICYCLE_2D_STATE_COST_FUNCTOR_H
congleetea/fuse
fuse_models/include/fuse_models/twist_2d.h
<gh_stars>0 /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_TWIST_2D_H #define FUSE_MODELS_TWIST_2D_H #include <fuse_models/parameters/twist_2d_params.h> #include <fuse_core/async_sensor_model.h> #include <fuse_core/uuid.h> #include <geometry_msgs/TwistWithCovarianceStamped.h> #include <ros/ros.h> #include <tf2_ros/transform_listener.h> namespace fuse_models { /** * @brief An adapter-type sensor that produces absolute velocity constraints from information published by another node * * This sensor subscribes to a geometry_msgs::TwistWithCovarianceStamped topic and converts each received message * into two absolute velocity constraints (one for linear velocity, and one for angular). * * Parameters: * - device_id (uuid string, default: 00000000-0000-0000-0000-000000000000) The device/robot ID to publish * - device_name (string) Used to generate the device/robot ID if the device_id is not provided * - queue_size (int, default: 10) The subscriber queue size for the twist messages * - topic (string) The topic to which to subscribe for the twist messages * * Subscribes: * - \p topic (geometry_msgs::TwistWithCovarianceStamped) Absolute velocity information at a given timestamp */ class Twist2D : public fuse_core::AsyncSensorModel { public: SMART_PTR_DEFINITIONS(Twist2D); using ParameterType = parameters::Twist2DParams; /** * @brief Default constructor */ Twist2D(); /** * @brief Destructor */ virtual ~Twist2D() = default; /** * @brief Callback for twist messages * @param[in] msg - The twist message to process */ void process(const geometry_msgs::TwistWithCovarianceStamped::ConstPtr& msg); protected: fuse_core::UUID device_id_; //!< The UUID of this device /** * @brief Loads ROS parameters and subscribes to the parameterized topic */ void onInit() override; /** * @brief Subscribe to the input topic to start sending transactions to the optimizer */ void onStart() override; /** * @brief Unsubscribe from the input topic to stop sending transactions to the optimizer */ void onStop() override; ParameterType params_; tf2_ros::Buffer tf_buffer_; tf2_ros::TransformListener tf_listener_; ros::Subscriber subscriber_; }; } // namespace fuse_models #endif // FUSE_MODELS_TWIST_2D_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/relative_orientation_3d_stamped_constraint.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_RELATIVE_ORIENTATION_3D_STAMPED_CONSTRAINT_H #define FUSE_CONSTRAINTS_RELATIVE_ORIENTATION_3D_STAMPED_CONSTRAINT_H #include <fuse_core/constraint.h> #include <fuse_core/eigen.h> #include <fuse_core/macros.h> #include <fuse_core/serialization.h> #include <fuse_core/uuid.h> #include <fuse_variables/orientation_3d_stamped.h> #include <geometry_msgs/PoseWithCovariance.h> #include <geometry_msgs/Quaternion.h> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> #include <Eigen/Geometry> #include <array> #include <ostream> #include <string> namespace fuse_constraints { /** * @brief A constraint that represents a measurement on the difference between 3D orientation variables. * * This constraint holds the measured 3D orientation and the measurement uncertainty/covariance. */ class RelativeOrientation3DStampedConstraint : public fuse_core::Constraint { public: FUSE_CONSTRAINT_DEFINITIONS_WITH_EIGEN(RelativeOrientation3DStampedConstraint); /** * @brief Default constructor */ RelativeOrientation3DStampedConstraint() = default; /** * @brief Create a constraint using a measurement/prior of a 3D orientation * * @param[in] source The name of the sensor or motion model that generated this constraint * @param[in] orientation1 The variable representing the first orientation * @param[in] orientation2 The variable representing the second orientation * @param[in] delta The measured orientation change as a quaternion (4x1 vector: w, x, y, z) * @param[in] covariance The measurement covariance (3x3 matrix: qx, qy, qz) */ RelativeOrientation3DStampedConstraint( const std::string& source, const fuse_variables::Orientation3DStamped& orientation1, const fuse_variables::Orientation3DStamped& orientation2, const fuse_core::Vector4d& delta, const fuse_core::Matrix3d& covariance); /** * @brief Create a constraint using a measurement/prior of a 3D orientation * * @param[in] source The name of the sensor or motion model that generated this constraint * @param[in] orientation1 The variable representing the first orientation * @param[in] orientation2 The variable representing the second orientation * @param[in] delta The measured orientation change as an Eigen quaternion * @param[in] covariance The measurement covariance (3x3 matrix: qx, qy, qz) */ RelativeOrientation3DStampedConstraint( const std::string& source, const fuse_variables::Orientation3DStamped& orientation1, const fuse_variables::Orientation3DStamped& orientation2, const Eigen::Quaterniond& delta, const fuse_core::Matrix3d& covariance); /** * @brief Create a constraint using a measurement/prior of a 3D orientation * * @param[in] source The name of the sensor or motion model that generated this constraint * @param[in] orientation1 The variable representing the first orientation * @param[in] orientation2 The variable representing the second orientation * @param[in] delta The measured orientation change as a ROS quaternion message * @param[in] covariance The measurement covariance (3x3 matrix: qx, qy, qz) */ RelativeOrientation3DStampedConstraint( const std::string& source, const fuse_variables::Orientation3DStamped& orientation1, const fuse_variables::Orientation3DStamped& orientation2, const geometry_msgs::Quaternion& delta, const std::array<double, 9>& covariance); /** * @brief Destructor */ virtual ~RelativeOrientation3DStampedConstraint() = default; /** * @brief Read-only access to the measured change between variables. * * Order is (w, x, y, z) */ const fuse_core::Vector4d& delta() const { return delta_; } /** * @brief Read-only access to the square root information matrix. * * Order is (x, y, z) */ const fuse_core::Matrix3d& sqrtInformation() const { return sqrt_information_; } /** * @brief Compute the measurement covariance matrix. * * Order is (x, y, z) */ fuse_core::Matrix3d covariance() const; /** * @brief Print a human-readable description of the constraint to the provided stream. * * @param[out] stream The stream to write to. Defaults to stdout. */ void print(std::ostream& stream = std::cout) const override; /** * @brief Construct an instance of this constraint's cost function * * The function caller will own the new cost function instance. It is the responsibility of the caller to delete * the cost function object when it is no longer needed. If the pointer is provided to a Ceres::Problem object, the * Ceres::Problem object will takes ownership of the pointer and delete it during destruction. * * @return A base pointer to an instance of a derived CostFunction. */ ceres::CostFunction* costFunction() const override; protected: /** * @brief Utility method to convert an Eigen quaternion to an Eigen Vector4d * * @param[in] quaternion The input Eigen quaternion * @return The \p quaternion, converted to an Eigen Vector4d */ static fuse_core::Vector4d toEigen(const Eigen::Quaterniond& quaternion); /** * @brief Utility method to convert an ROS quaternion message to an Eigen Vector4d * * @param[in] quaternion The input ROS quaternion message * @return The \p quaternion, converted to an Eigen Vector4d */ static fuse_core::Vector4d toEigen(const geometry_msgs::Quaternion& quaternion); /** * @brief Utility method to convert a flat 1D array to a 3x3 Eigen matrix * * @param[in] covariance The input covariance array * @return The \p covariance, converted to an Eigen Matrix3d */ static fuse_core::Matrix3d toEigen(const std::array<double, 9>& covariance); fuse_core::Vector4d delta_; //!< The measured/prior mean vector for this variable fuse_core::Matrix3d sqrt_information_; //!< The square root information matrix private: // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & boost::serialization::base_object<fuse_core::Constraint>(*this); archive & delta_; archive & sqrt_information_; } }; } // namespace fuse_constraints BOOST_CLASS_EXPORT_KEY(fuse_constraints::RelativeOrientation3DStampedConstraint); #endif // FUSE_CONSTRAINTS_RELATIVE_ORIENTATION_3D_STAMPED_CONSTRAINT_H
congleetea/fuse
fuse_core/include/fuse_core/motion_model.h
<reponame>congleetea/fuse /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_MOTION_MODEL_H #define FUSE_CORE_MOTION_MODEL_H #include <fuse_core/graph.h> #include <fuse_core/macros.h> #include <fuse_core/transaction.h> #include <string> namespace fuse_core { /** * @brief The interface definition for motion model plugins in the fuse ecosystem. * * A model model plugin is responsible for generating constraints that link together timestamps introduced by other * sensors in the system. */ class MotionModel { public: SMART_PTR_ALIASES_ONLY(MotionModel); /** * @brief Destructor */ virtual ~MotionModel() = default; /** * @brief Augment a transaction object such that all involved timestamps are connected by motion model constraints. * * This function will be called by the optimizer (in the Optimizer's thread) for each received transaction. * * @param[in,out] transaction The transaction object that should be augmented with motion model constraints * @return True if the motion models were generated successfully, false otherwise */ virtual bool apply(Transaction& transaction) = 0; /** * @brief Function to be executed whenever the optimizer has completed a Graph update * * This method will be called by the optimizer, in the optimizer's thread, after each Graph update is complete. This * generally means that new variables have been inserted into the Graph, and new optimized values are available. * To simplify synchronization between the motion models and other consumers of Graph data, the provided Graph * object will never be updated by anyone. Thus, only read access to the Graph is provided. Information may be * accessed or computed, but it cannot be changed. The optimizer provides the motion models with Graph updates by * sending a new Graph object, not by modifying this Graph object. * * @param[in] graph A read-only pointer to the graph object, allowing queries to be performed whenever needed. */ virtual void graphCallback(Graph::ConstSharedPtr /*graph*/) {} /** * @brief Perform any required post-construction initialization, such as subscribing to topics or reading from the * parameter server. * * This will be called on each plugin after construction, and after the ros node has been initialized. Plugins are * encouraged to subnamespace any of their parameters to prevent conflicts and allow the same plugin to be used * multiple times with different settings and topics. * * @param[in] name A unique name to give this plugin instance */ virtual void initialize(const std::string& name) = 0; /** * @brief Get the unique name of this motion model */ virtual const std::string& name() const = 0; /** * @brief Function to be executed whenever the optimizer is ready to receive transactions * * This method will be called by the optimizer, in the optimizer's thread, once the optimizer has been initialized * and is ready to receive transactions. It may also be called as part of a stop-start cycle when the optimizer * has been requested to reset itself. This allows the motion model to reset any internal state before the * optimizer begins processing after a reset. No calls to apply() will happen before the optimizer calls start(). */ virtual void start() {} /** * @brief Function to be executed whenever the optimizer is no longer ready to receive transactions * * This method will be called by the optimizer, in the optimizer's thread, before the optimizer shutdowns. It may * also be called as part of a stop-start cycle when the optimizer has been requested to reset itself. This allows * the motion model to reset any internal state before the optimizer begins processing after a reset. No calls * to apply() will happen until start() has been called again. */ virtual void stop() {} protected: /** * @brief Default Constructor */ MotionModel() = default; }; } // namespace fuse_core #endif // FUSE_CORE_MOTION_MODEL_H
congleetea/fuse
fuse_core/include/fuse_core/eigen_gtest.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_EIGEN_GTEST_H #define FUSE_CORE_EIGEN_GTEST_H #include <Eigen/Core> #include <gtest/gtest.h> /** * @file eigen_gtest.h * * @brief Provides ASSERT_MATRIX_EQ()/EXPECT_MATRIX_EQ() and ASSERT_MATRIX_NEAR()/EXPECT_MATRIX_NEAR() * gtest macros */ namespace testing { /** * @brief Internal helper function for implementing {EXPECT|ASSERT}_MATRIX_EQ. * * Don't use this in your code. * * @param[in] e1 Expected matrix name * @param[in] e2 Actual matrix name * @param[in] v1 Expected matrix * @param[in] v2 Actual matrix * @return AssertionSuccess or AssertionFailure */ template <typename Derived1, typename Derived2> AssertionResult AssertMatrixEqualHelper( const char* e1, const char* e2, const Eigen::MatrixBase<Derived1>& v1, const Eigen::MatrixBase<Derived2>& v2) { if (v1 == v2) { return AssertionSuccess(); } Eigen::IOFormat clean(4, 0, ", ", "\n", "[", "]"); return AssertionFailure() << e1 << " is:\n" << v1.format(clean) << "\n" << e2 << " is:\n" << v2.format(clean) << "\n" << "Difference is:\n" << (v1 - v2).format(clean) << "\n"; } /** * @brief Internal helper function for implementing {EXPECT|ASSERT}_MATRIX_NEAR. * * Don't use this in your code. * * @param[in] e1 Expected matrix name * @param[in] e2 Actual matrix name * @param[in] v1 Expected matrix * @param[in] v2 Actual matrix * @param[in] tol Tolerance * @return AssertionSuccess or AssertionFailure */ template <typename Derived1, typename Derived2> AssertionResult AssertMatrixNearHelper( const char* e1, const char* e2, const Eigen::MatrixBase<Derived1>& v1, const Eigen::MatrixBase<Derived2>& v2, double tol) { if ((v1 - v2).cwiseAbs().maxCoeff() < tol) { return AssertionSuccess(); } Eigen::IOFormat clean(4, 0, ", ", "\n", "[", "]"); return AssertionFailure() << e1 << " is:\n" << v1.format(clean) << "\n" << e2 << " is:\n" << v2.format(clean) << "\n" << "Difference is:\n" << (v1 - v2).format(clean) << "\n"; } // Internal macro for implementing {EXPECT|ASSERT}_MATRIX_EQ. // Don't use this in your code. #define GTEST_MATRIX_EQUAL_(v1, v2, on_failure) \ GTEST_ASSERT_(::testing::AssertMatrixEqualHelper(#v1, \ #v2, \ v1, \ v2), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_MATRIX_NEAR. // Don't use this in your code. #define GTEST_MATRIX_NEAR_(v1, v2, tol, on_failure) \ GTEST_ASSERT_(::testing::AssertMatrixNearHelper(#v1, \ #v2, \ v1, \ v2, \ tol), on_failure) // Define gtest macros for use with Eigen /** * @brief Non-fatal check for exact equality of two Eigen matrix-like objects. * * This should probably be used only for integer-based matrix types * * @param[in] v1 The expected matrix * @param[in] v2 The actual matrix */ #define EXPECT_MATRIX_EQ(v1, v2) \ GTEST_MATRIX_EQUAL_(v1, v2, GTEST_NONFATAL_FAILURE_) /** * @brief Fatal check for exact equality of two Eigen matrix-like objects. * * This should probably be used only for integer-based matrix types * * @param[in] v1 The expected matrix * @param[in] v2 The actual matrix */ #define ASSERT_MATRIX_EQ(v1, v2) \ GTEST_MATRIX_EQUAL_(v1, v2, GTEST_FATAL_FAILURE_) /** * @brief Non-fatal check for approximate equality of two Eigen matrix-like objects. * * This version return success if abs(v1[i] - v2[i]) < tol for every element i in the matrix. * * @param[in] v1 The expected matrix * @param[in] v2 The actual matrix * @param[in] tol The allowed tolerance between any entries in v1 and v2 */ #define EXPECT_MATRIX_NEAR(v1, v2, tol) \ GTEST_MATRIX_NEAR_(v1, v2, tol, GTEST_NONFATAL_FAILURE_) /** * @brief Fatal check for approximate equality of two Eigen matrix-like objects. * * This version return success if abs(v1[i] - v2[i]) < tol for every element i in the matrix. * * @param[in] v1 The expected matrix * @param[in] v2 The actual matrix * @param[in] tol The allowed tolerance between any entries in v1 and v2 */ #define ASSERT_MATRIX_NEAR(v1, v2, tol) \ GTEST_MATRIX_NEAR_(v1, v2, tol, GTEST_FATAL_FAILURE_) } // namespace testing #endif // FUSE_CORE_EIGEN_GTEST_H
congleetea/fuse
fuse_models/include/fuse_models/parameters/imu_2d_params.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_PARAMETERS_IMU_2D_PARAMS_H #define FUSE_MODELS_PARAMETERS_IMU_2D_PARAMS_H #include <fuse_models/parameters/parameter_base.h> #include <fuse_variables/acceleration_linear_2d_stamped.h> #include <fuse_variables/orientation_2d_stamped.h> #include <fuse_variables/velocity_angular_2d_stamped.h> #include <ros/node_handle.h> #include <string> #include <vector> namespace fuse_models { namespace parameters { /** * @brief Defines the set of parameters required by the Imu2D class */ struct Imu2DParams : public ParameterBase { public: /** * @brief Method for loading parameter values from ROS. * * @param[in] nh - The ROS node handle with which to load parameters */ void loadFromROS(const ros::NodeHandle& nh) final { angular_velocity_indices = loadSensorConfig<fuse_variables::VelocityAngular2DStamped>(nh, "angular_velocity_dimensions"); linear_acceleration_indices = loadSensorConfig<fuse_variables::AccelerationLinear2DStamped>(nh, "linear_acceleration_dimensions"); orientation_indices = loadSensorConfig<fuse_variables::Orientation2DStamped>(nh, "orientation_dimensions"); nh.getParam("differential", differential); nh.getParam("queue_size", queue_size); nh.getParam("remove_gravitational_acceleration", remove_gravitational_acceleration); nh.getParam("gravitational_acceleration", gravitational_acceleration); getParamRequired(nh, "topic", topic); if (!linear_acceleration_indices.empty()) { getParamRequired(nh, "acceleration_target_frame", acceleration_target_frame); } if (!orientation_indices.empty()) { getParamRequired(nh, "orientation_target_frame", orientation_target_frame); } if (!angular_velocity_indices.empty()) { getParamRequired(nh, "twist_target_frame", twist_target_frame); } } bool differential { false }; bool remove_gravitational_acceleration { false }; int queue_size { 10 }; double gravitational_acceleration { 9.80665 }; std::string acceleration_target_frame {}; std::string orientation_target_frame {}; std::string topic {}; std::string twist_target_frame {}; std::vector<size_t> angular_velocity_indices; std::vector<size_t> linear_acceleration_indices; std::vector<size_t> orientation_indices; }; } // namespace parameters } // namespace fuse_models #endif // FUSE_MODELS_PARAMETERS_IMU_2D_PARAMS_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/relative_pose_2d_stamped_constraint.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_RELATIVE_POSE_2D_STAMPED_CONSTRAINT_H #define FUSE_CONSTRAINTS_RELATIVE_POSE_2D_STAMPED_CONSTRAINT_H #include <fuse_core/constraint.h> #include <fuse_core/eigen.h> #include <fuse_core/macros.h> #include <fuse_core/serialization.h> #include <fuse_core/uuid.h> #include <fuse_variables/orientation_2d_stamped.h> #include <fuse_variables/position_2d_stamped.h> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> #include <Eigen/Dense> #include <ostream> #include <string> #include <vector> namespace fuse_constraints { /** * @brief A constraint that represents a measurement on the difference between two poses. * * This type of constraint arises in many situations. Many types of incremental odometry measurements (wheel encoders, * inertial strap-down, visual odometry) measure the change in the pose, not the pose directly. This constraint * holds the measured 2D pose change and the measurement uncertainty/covariance. It also permits measurement of a * subset of the relative pose provided in the position and orientation varables. */ class RelativePose2DStampedConstraint : public fuse_core::Constraint { public: FUSE_CONSTRAINT_DEFINITIONS(RelativePose2DStampedConstraint); /** * @brief Default constructor */ RelativePose2DStampedConstraint() = default; /** * @brief Constructor * * Note that, when measuring subset of dimensions, empty axis vectors are permitted. This signifies that you * don't want to measure any of the quantities in that variable. * * The mean is given as a vector. The first components (if any) will be dictated, both in content and in ordering, by * the value of the \p linear_indices. The final component (if any) is dictated by the \p angular_indices. The * covariance matrix follows the same ordering. * * @param[in] source The name of the sensor or motion model that generated this constraint * @param[in] position1 The variable representing the position components of the first pose * @param[in] orientation1 The variable representing the orientation components of the first pose * @param[in] position2 The variable representing the position components of the second pose * @param[in] orientation2 The variable representing the orientation components of the second pose * @param[in] partial_delta The measured change in the pose (max 3x1 vector, components are dictated by * \p linear_indices and \p angular_indices) * @param[in] partial_covariance The measurement covariance (max 3x3 matrix, components are dictated by * \p linear_indices and \p angular_indices) * @param[in] linear_indices The set of indices corresponding to the measured position dimensions * e.g., "{fuse_variables::Position2DStamped::X, fuse_variables::Position2DStamped::Y}" * @param[in] angular_indices The set of indices corresponding to the measured orientation dimensions * e.g., "{fuse_variables::Orientation2DStamped::Yaw}" */ RelativePose2DStampedConstraint( const std::string& source, const fuse_variables::Position2DStamped& position1, const fuse_variables::Orientation2DStamped& orientation1, const fuse_variables::Position2DStamped& position2, const fuse_variables::Orientation2DStamped& orientation2, const fuse_core::VectorXd& partial_delta, const fuse_core::MatrixXd& partial_covariance, const std::vector<size_t>& linear_indices = {fuse_variables::Position2DStamped::X, fuse_variables::Position2DStamped::Y}, // NOLINT const std::vector<size_t>& angular_indices = {fuse_variables::Orientation2DStamped::YAW}); // NOLINT /** * @brief Destructor */ virtual ~RelativePose2DStampedConstraint() = default; /** * @brief Read-only access to the measured pose change. * * Order is (dx, dy, dyaw). Note that the returned vector will be full sized (3x1) and in the stated order. */ const fuse_core::Vector3d& delta() const { return delta_; } /** * @brief Read-only access to the square root information matrix. * * If only a partial covariance matrix was provided in the constructor, this covariance matrix will not be square. */ const fuse_core::MatrixXd& sqrtInformation() const { return sqrt_information_; } /** * @brief Compute the measurement covariance matrix. * * Order is (dx, dy, dyaw). Note that the returned covariance matrix will be full sized (3x3) and in the stated * order. If only a partial covariance matrix was provided in the constructor, this covariance matrix may be a * different size and in a different order than the constructor input. */ fuse_core::Matrix3d covariance() const; /** * @brief Print a human-readable description of the constraint to the provided stream. * * @param[out] stream The stream to write to. Defaults to stdout. */ void print(std::ostream& stream = std::cout) const override; /** * @brief Access the cost function for this constraint * * The function caller will own the new cost function instance. It is the responsibility of the caller to delete * the cost function object when it is no longer needed. If the pointer is provided to a Ceres::Problem object, the * Ceres::Problem object will takes ownership of the pointer and delete it during destruction. * * @return A base pointer to an instance of a derived CostFunction. */ ceres::CostFunction* costFunction() const override; protected: fuse_core::Vector3d delta_; //!< The measured pose change (dx, dy, dyaw) fuse_core::MatrixXd sqrt_information_; //!< The square root information matrix (derived from the covariance matrix) private: // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & boost::serialization::base_object<fuse_core::Constraint>(*this); archive & delta_; archive & sqrt_information_; } }; } // namespace fuse_constraints BOOST_CLASS_EXPORT_KEY(fuse_constraints::RelativePose2DStampedConstraint); #endif // FUSE_CONSTRAINTS_RELATIVE_POSE_2D_STAMPED_CONSTRAINT_H
congleetea/fuse
fuse_core/include/fuse_core/local_parameterization.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_LOCAL_PARAMETERIZATION_H #define FUSE_CORE_LOCAL_PARAMETERIZATION_H #include <fuse_core/macros.h> #include <fuse_core/serialization.h> #include <boost/serialization/access.hpp> #include <ceres/local_parameterization.h> namespace fuse_core { /** * @brief The LocalParameterization interface definition. * * This class extends the Ceres LocalParameterization class, adding the additional requirement of a * \p Minus() method, the conceptual inverse of the already required \p Plus() method. * * If Plus(x1, delta) -> x2, then Minus(x1, x2) -> delta * * See the Ceres documentation for more details. http://ceres-solver.org/nnls_modeling.html#localparameterization */ class LocalParameterization : public ceres::LocalParameterization { public: SMART_PTR_ALIASES_ONLY(LocalParameterization); /** * @brief Generalization of the subtraction operation * * Minus(x1, x2) -> delta * * with the conditions that: * - Minus(x, x) -> 0 * - if Plus(x1, delta) -> x2, then Minus(x1, x2) -> delta * * @param[in] x1 The value of the first variable, of size \p GlobalSize() * @param[in] x2 The value of the second variable, of size \p GlobalSize() * @param[out] delta The difference between the second variable and the first, of size \p LocalSize() * @return True if successful, false otherwise */ virtual bool Minus( const double* x1, const double* x2, double* delta) const = 0; /** * @brief The jacobian of Minus(x1, x2) w.r.t x2 at x1 == x2 == x * * @param[in] x The value used to evaluate the Jacobian, of size \p GlobalSize() * @param[out] jacobian The first-order derivative in row-major order, of size \p LocalSize() x \p GlobalSize() * @return True if successful, false otherwise */ virtual bool ComputeMinusJacobian( const double* x, double* jacobian) const = 0; private: // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& /* archive */, const unsigned int /* version */) { } }; } // namespace fuse_core #endif // FUSE_CORE_LOCAL_PARAMETERIZATION_H
congleetea/fuse
fuse_publishers/include/fuse_publishers/pose_2d_publisher.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_PUBLISHERS_POSE_2D_PUBLISHER_H #define FUSE_PUBLISHERS_POSE_2D_PUBLISHER_H #include <fuse_publishers/stamped_variable_synchronizer.h> #include <fuse_core/async_publisher.h> #include <fuse_core/graph.h> #include <fuse_core/macros.h> #include <fuse_core/transaction.h> #include <fuse_core/uuid.h> #include <fuse_variables/orientation_2d_stamped.h> #include <fuse_variables/position_2d_stamped.h> #include <ros/ros.h> #include <tf2_ros/transform_broadcaster.h> #include <tf2_ros/transform_listener.h> #include <memory> #include <string> namespace fuse_publishers { /** * @brief Publisher plugin that publishes the latest 2D pose (combination of Position2DStamped and Orientation2DStamped) * * There are several options: the latest pose can be sent to the tf topic, just the pose can be published, or the pose * and the covariance can be published. * * The tf operation is not straight forward. The standard ROS frame conventions are map->odom->base_link. The * odom->base_link frame is generally published by a separate odometry system (robot driver node, robot_localization * node, robot_pose_ekf node, etc.). If this node published a map->base_link transform, the tf system would no longer * form a tree (the base_link node would have multiple parents), which breaks the tf system. Instead, we want to * publish the map->odom transform. If the map->base_link transform is desired, the odom frame may be set to an empty * string. Additionally, the tf system requires transforms to be available both before and after a requested timestamp * before it will compute a transform. If this plugin only published transforms after each successful cycle of the * optimizer, the map->odom transform will become old or stale as the optimization time increases. To prevent this, * the map->odom transform is published in response to an independent timer, and the timestamp of the transform is * updated to the current publication time. Although this is "wrong", it keeps the tf tree populated with recent * transform data so that other nodes can execute tf queries. * * Parameters: * - base_frame (string, default: base_link) Name for the robot's base frame * - device_id (uuid string, default: 00000000-0000-0000-0000-000000000000) The device/robot ID to publish * - device_name (string) Used to generate the device/robot ID if the device_id is not provided * - map_frame (string, default: map) Name for the robot's map frame * - odom_frame (string, default: odom) Name for the robot's odom frame (or {empty} if the frame map->base should be * published to tf instead of map->odom) * - publish_to_tf (bool, default: false) Flag indicating that the optimized pose should be published to tf * - tf_cache_time (seconds, default: 10.0) How long to keep a history of transforms (for map->odom lookup) * - tf_publish_frequency (Hz, default: 10.0) How often the latest pose should be published to tf * - tf_timeout (seconds, default: 0.1) The maximum amount of time to wait for a transform to become available * * Publishes: * - pose (geometry_msgs::PoseStamped) The most recent optimized robot pose (i.e. the map->base transform) * - pose_with_covariance (geometry_msgs::PoseWithCovarianceStamped) The most recent optimized robot pose and * covariance (i.e. the map->base transform) * - tf (tf2_msgs::TFMessage) The most recent map->odom transform (or map->base if the odom_frame is empty) * * Subscribes: * - tf, tf_static (tf2_msgs::TFMessage) Used to lookup the current odom->base frame, if needed */ class Pose2DPublisher : public fuse_core::AsyncPublisher { public: SMART_PTR_DEFINITIONS(Pose2DPublisher); /** * @brief Constructor */ Pose2DPublisher(); /** * @brief Destructor */ virtual ~Pose2DPublisher() = default; /** * @brief Perform any required post-construction initialization, such as advertising publishers or reading from the * parameter server. */ void onInit() override; /** * @brief Perform any required operations before the first call to notify() occurs */ void onStart() override; /** * @brief Perform any required operations to stop publications */ void onStop() override; /** * @brief Notify the publisher about variables that have been added or removed * * This publisher publishes only the most recent pose. By analyzing the added and removed variables, the most * recent pose UUID can be maintained without performing an exhaustive search through the entire Graph during * the Publisher::publish() call. * * @param[in] transaction A Transaction object, describing the set of variables that have been added and/or removed * @param[in] graph A read-only pointer to the graph object, allowing queries to be performed whenever needed */ void notifyCallback( fuse_core::Transaction::ConstSharedPtr transaction, fuse_core::Graph::ConstSharedPtr graph) override; /** * @brief Timer-based callback that publishes the latest map->odom transform * * The transform is published with the current timestamp, not the timestamp of the data used to generate the * transform. Although this is "wrong", it keeps the tf tree populated with recent transforms so that other nodes * can execute tf queries. */ void tfPublishTimerCallback(const ros::TimerEvent& event); protected: using Synchronizer = StampedVariableSynchronizer<fuse_variables::Orientation2DStamped, fuse_variables::Position2DStamped>; std::string base_frame_; //!< The name of the robot's base_link frame fuse_core::UUID device_id_; //!< The UUID of the device to be published std::string map_frame_; //!< The name of the robot's map frame std::string odom_frame_; //!< The name of the odom frame for this pose (or empty if the odom is not used) ros::Publisher pose_publisher_; //!< Publish the pose as a geometry_msgs::PoseStamped ros::Publisher pose_with_covariance_publisher_; //!< Publish the pose as a geometry_msgs::PoseWithCovarianceStamped bool publish_to_tf_; //!< Flag indicating the pose should be sent to the tf system as well as the pose topics Synchronizer::UniquePtr synchronizer_; //!< Object that tracks the latest common timestamp of multiple variables std::unique_ptr<tf2_ros::Buffer> tf_buffer_; //!< TF2 object that supports querying transforms by time and frame id std::unique_ptr<tf2_ros::TransformListener> tf_listener_; //!< TF2 object that subscribes to the tf topics and //!< inserts the received transforms into the tf buffer tf2_ros::TransformBroadcaster tf_publisher_; //!< Publish the map->odom or map->base transform to the tf system ros::Timer tf_publish_timer_; //!< Timer that publishes tf messages to ensure the tf transform doesn't get stale ros::Duration tf_timeout_; //!< The max time to wait for a tf transform to become available geometry_msgs::TransformStamped tf_transform_; //!< The transform to be published to tf bool use_tf_lookup_; //!< Internal flag indicating that a tf frame lookup is required }; } // namespace fuse_publishers #endif // FUSE_PUBLISHERS_POSE_2D_PUBLISHER_H
congleetea/fuse
fuse_core/include/fuse_core/autodiff_local_parameterization.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_AUTODIFF_LOCAL_PARAMETERIZATION_H #define FUSE_CORE_AUTODIFF_LOCAL_PARAMETERIZATION_H #include <fuse_core/local_parameterization.h> #include <fuse_core/macros.h> #include <ceres/internal/autodiff.h> #include <memory> namespace fuse_core { /** * @brief Create a local parameterization with the Jacobians computed via automatic differentiation. * * To get an auto differentiated local parameterization, you must define two classes with a templated operator() * (a.k.a. a functor). * * The first functor should compute: * * Plus(x, delta) -> x_plus_delta * * And the second functor should compute the inverse operation: * * Minus(x1, x2) -> delta * * Minus() should be defined such that if Plus(x1, delta) -> x2, then Minus(x1, x2) -> delta * * The autodiff framework substitutes appropriate "Jet" objects for the template parameter T in order to compute * the derivative when necessary, but this is hidden, and you should write the function as if T were a scalar type * (e.g. a double-precision floating point number). * * Additionally the GlobalSize and LocalSize must be specified as template parameters. * - GlobalSize is the size of the variables x1 and x2. If this is a quaternion, the GloblaSize would be 4. * - LocalSize is the size of delta, and may be different from GlobalSize. For quaternions, there are only 3 degrees * of freedom, so the LocalSize is 3. * * For more information on local parameterizations, see fuse_core::LocalParameterization */ template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> class AutoDiffLocalParameterization : public LocalParameterization { public: SMART_PTR_DEFINITIONS(AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>); /** * @brief Constructs new PlusFunctor and MinusFunctor instances */ AutoDiffLocalParameterization(); /** * @brief Takes ownership of the provided PlusFunctor and MinusFunctor instances */ AutoDiffLocalParameterization(PlusFunctor* plus_functor, MinusFunctor* minus_functor); /** * @brief Generalization of the addition operation, implemented by the provided PlusFunctor * * @param[in] x The starting variable value, of size \p GlobalSize() * @param[in] delta The variable increment to apply, of size \p LocalSize() * @param[out] x_plus_delta The final variable value, of size \p GlobalSize() * @return True if successful, false otherwise */ bool Plus( const double* x, const double* delta, double* x_plus_delta) const override; /** * @brief The Jacobian of Plus(x, delta) w.r.t delta at delta = 0, computed using automatic differentiation * * @param[in] x The value used to evaluate the Jacobian, of size GloblaSize() * @param[out] jacobian The Jacobian in row-major order, of size \p GlobalSize() x \p LocalSize() * @return True is successful, false otherwise */ bool ComputeJacobian( const double* x, double* jacobian) const override; /** * @brief Generalization of the subtraction operation, implemented by the provided MinusFunctor * * @param[in] x1 The value of the first variable, of size \p GlobalSize() * @param[in] x2 The value of the second variable, of size \p GlobalSize() * @param[out] delta The difference between the second variable and the first, of size \p LocalSize() * @return True if successful, false otherwise */ bool Minus( const double* x1, const double* x2, double* delta) const override; /** * @brief The Jacobian of Minus(x1, x2) w.r.t x2 evaluated at x1 = x2 = x, computed using automatic differentiation * @param[in] x The value used to evaluate the Jacobian, of size \p GlobalSize() * @param[out] jacobian The Jacobian in row-major order, of size \p LocalSize() x \p GlobalSize() * @return True is successful, false otherwise */ bool ComputeMinusJacobian( const double* x, double* jacobian) const override; /** * @brief The size of the variable parameterization in the nonlinear manifold */ int GlobalSize() const override { return kGlobalSize; } /** * @brief The size of a delta vector in the linear tangent space to the nonlinear manifold */ int LocalSize() const override { return kLocalSize; } private: std::unique_ptr<PlusFunctor> plus_functor_; std::unique_ptr<MinusFunctor> minus_functor_; }; template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::AutoDiffLocalParameterization() : plus_functor_(new PlusFunctor()), minus_functor_(new MinusFunctor()) { } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::AutoDiffLocalParameterization( PlusFunctor* plus_functor, MinusFunctor* minus_functor) : plus_functor_(plus_functor), minus_functor_(minus_functor) { } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> bool AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::Plus( const double* x, const double* delta, double* x_plus_delta) const { return (*plus_functor_)(x, delta, x_plus_delta); } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> bool AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::ComputeJacobian( const double* x, double* jacobian) const { double zero_delta[kLocalSize] = {}; // zero-initialize double x_plus_delta[kGlobalSize]; const double* parameter_ptrs[2] = {x, zero_delta}; double* jacobian_ptrs[2] = {NULL, jacobian}; return ceres::internal::AutoDiff<PlusFunctor, double, kGlobalSize, kLocalSize> ::Differentiate(*plus_functor_, parameter_ptrs, kGlobalSize, x_plus_delta, jacobian_ptrs); } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> bool AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::Minus( const double* x1, const double* x2, double* delta) const { return (*minus_functor_)(x1, x2, delta); } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> bool AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::ComputeMinusJacobian( const double* x, double* jacobian) const { double delta[kLocalSize] = {}; // zero-initialize const double* parameter_ptrs[2] = {x, x}; double* jacobian_ptrs[2] = {NULL, jacobian}; return ceres::internal::AutoDiff<MinusFunctor, double, kGlobalSize, kGlobalSize> ::Differentiate(*minus_functor_, parameter_ptrs, kLocalSize, delta, jacobian_ptrs); } } // namespace fuse_core #endif // FUSE_CORE_AUTODIFF_LOCAL_PARAMETERIZATION_H
congleetea/fuse
fuse_models/include/fuse_models/unicycle_2d_state_kinematic_constraint.h
<reponame>congleetea/fuse<filename>fuse_models/include/fuse_models/unicycle_2d_state_kinematic_constraint.h<gh_stars>100-1000 /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_UNICYCLE_2D_STATE_KINEMATIC_CONSTRAINT_H #define FUSE_MODELS_UNICYCLE_2D_STATE_KINEMATIC_CONSTRAINT_H #include <fuse_core/constraint.h> #include <fuse_core/eigen.h> #include <fuse_core/macros.h> #include <fuse_core/serialization.h> #include <fuse_core/uuid.h> #include <fuse_variables/acceleration_linear_2d_stamped.h> #include <fuse_variables/orientation_2d_stamped.h> #include <fuse_variables/position_2d_stamped.h> #include <fuse_variables/velocity_angular_2d_stamped.h> #include <fuse_variables/velocity_linear_2d_stamped.h> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> #include <ostream> #include <string> #include <vector> namespace fuse_models { /** * @brief A class that represents a kinematic constraint between 2D states at two different times * * The fuse_models 2D state is a combination of 2D position, 2D orientation, 2D linear velocity, 2D angular velocity, * and 2D linear acceleration. */ class Unicycle2DStateKinematicConstraint : public fuse_core::Constraint { public: FUSE_CONSTRAINT_DEFINITIONS_WITH_EIGEN(Unicycle2DStateKinematicConstraint); /** * @brief Default constructor */ Unicycle2DStateKinematicConstraint() = default; /** * @brief Create a constraint using a time delta and a kinematic model cost functor * * The constraint is created between two states. The state is broken up into multiple fuse variable types. * * @param[in] source The name of the sensor or motion model that generated this constraint * @param[in] position1 Position component variable of the fist state * @param[in] yaw1 Yaw component variable of the first state * @param[in] linear_velocity1 Linear velocity component variable of the first state * @param[in] yaw_velocity1 Yaw velocity component variable of the first state * @param[in] linear_acceleration1 Linear acceleration component variable of the first state * @param[in] position2 Position component variable of the second state * @param[in] yaw2 Yaw component variable of the second state * @param[in] linear_velocity2 Linear velocity component variable of the second state * @param[in] yaw_velocity2 Yaw velocity component variable of the second state * @param[in] linear_acceleration2 Linear acceleration component variable of the second state * @param[in] covariance - The covariance matrix used to weight the constraint. Order is * (x, y, yaw, x_vel, y_vel, yaw_vel, x_acc, y_acc) */ Unicycle2DStateKinematicConstraint( const std::string& source, const fuse_variables::Position2DStamped& position1, const fuse_variables::Orientation2DStamped& yaw1, const fuse_variables::VelocityLinear2DStamped& linear_velocity1, const fuse_variables::VelocityAngular2DStamped& yaw_velocity1, const fuse_variables::AccelerationLinear2DStamped& linear_acceleration1, const fuse_variables::Position2DStamped& position2, const fuse_variables::Orientation2DStamped& yaw2, const fuse_variables::VelocityLinear2DStamped& linear_velocity2, const fuse_variables::VelocityAngular2DStamped& yaw_velocity2, const fuse_variables::AccelerationLinear2DStamped& linear_acceleration2, const fuse_core::Matrix8d& covariance); /** * @brief Destructor */ virtual ~Unicycle2DStateKinematicConstraint() = default; /** * @brief Read-only access to the time delta between the first and second state (really, between the position1 and position2 variables in the constructor) */ double dt() const { return dt_; } /** * @brief Read-only access to the square root information matrix. * * Order is (x, y, yaw, x_vel, y_vel, yaw_vel, x_acc, y_acc) */ const fuse_core::Matrix8d& sqrtInformation() const { return sqrt_information_; } /** * @brief Compute the measurement covariance matrix. * * Order is (x, y, yaw, x_vel, y_vel, yaw_vel, x_acc, y_acc) */ fuse_core::Matrix8d covariance() const { return (sqrt_information_.transpose() * sqrt_information_).inverse(); } /** * @brief Print a human-readable description of the constraint to the provided stream. * * @param[out] stream The stream to write to. Defaults to stdout. */ void print(std::ostream& stream = std::cout) const override; /** * @brief Construct an instance of this constraint's cost function * * The function caller will own the new cost function instance. It is the responsibility of the caller to delete * the cost function object when it is no longer needed. If the pointer is provided to a Ceres::Problem object, the * Ceres::Problem object will takes ownership of the pointer and delete it during destruction. * * @return A base pointer to an instance of a derived CostFunction. */ ceres::CostFunction* costFunction() const override; protected: double dt_; //!< The time delta for the constraint fuse_core::Matrix8d sqrt_information_; //!< The square root information matrix private: // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & boost::serialization::base_object<fuse_core::Constraint>(*this); archive & dt_; archive & sqrt_information_; } }; } // namespace fuse_models BOOST_CLASS_EXPORT_KEY(fuse_models::Unicycle2DStateKinematicConstraint); #endif // FUSE_MODELS_UNICYCLE_2D_STATE_KINEMATIC_CONSTRAINT_H
congleetea/fuse
fuse_core/include/fuse_core/eigen.h
<filename>fuse_core/include/fuse_core/eigen.h /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_EIGEN_H #define FUSE_CORE_EIGEN_H #include <Eigen/Core> namespace fuse_core { // Define some Eigen Typedefs that use Row-Major order using VectorXd = Eigen::Matrix<double, Eigen::Dynamic, 1>; using Vector1d = Eigen::Matrix<double, 1, 1>; using Vector2d = Eigen::Matrix<double, 2, 1>; using Vector3d = Eigen::Matrix<double, 3, 1>; using Vector4d = Eigen::Matrix<double, 4, 1>; using Vector5d = Eigen::Matrix<double, 5, 1>; using Vector6d = Eigen::Matrix<double, 6, 1>; using Vector7d = Eigen::Matrix<double, 7, 1>; using Vector8d = Eigen::Matrix<double, 8, 1>; using Vector9d = Eigen::Matrix<double, 9, 1>; using MatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; using Matrix1d = Eigen::Matrix<double, 1, 1, Eigen::RowMajor>; using Matrix2d = Eigen::Matrix<double, 2, 2, Eigen::RowMajor>; using Matrix3d = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>; using Matrix4d = Eigen::Matrix<double, 4, 4, Eigen::RowMajor>; using Matrix5d = Eigen::Matrix<double, 5, 5, Eigen::RowMajor>; using Matrix6d = Eigen::Matrix<double, 6, 6, Eigen::RowMajor>; using Matrix7d = Eigen::Matrix<double, 7, 7, Eigen::RowMajor>; using Matrix8d = Eigen::Matrix<double, 8, 8, Eigen::RowMajor>; using Matrix9d = Eigen::Matrix<double, 9, 9, Eigen::RowMajor>; } // namespace fuse_core #endif // FUSE_CORE_EIGEN_H
congleetea/fuse
fuse_core/include/fuse_core/publisher.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_PUBLISHER_H #define FUSE_CORE_PUBLISHER_H #include <fuse_core/graph.h> #include <fuse_core/macros.h> #include <fuse_core/transaction.h> #include <string> namespace fuse_core { /** * @brief The interface class for publisher plugins in the fuse ecosystem. * * A publisher plugin is responsible for querying the latest variable value from the optimized Graph, converting the * variable values into ROS messages, and publishing the messages on their desired topics. Publisher plugins will be * loaded by the optimizer at run/configure time. The optimizer will notify the plugins after the graph has been * optimized. This class defines the supported interface between the optimizer and publisher. If you are deriving a * new publisher class, consider using fuse_core::AsyncPublisher as the base class instead. It offers additional * features making it act similar to a standard node or nodelet. */ class Publisher { public: SMART_PTR_ALIASES_ONLY(Publisher); /** * @brief Constructor * * All ROS plugins must provide a default constructor for use with the plugin loader. */ Publisher() = default; /** * @brief Destructor */ virtual ~Publisher() = default; /** * @brief Perform any required post-construction initialization, such as advertising publishers or reading from the * parameter server. * * This will be called on each plugin after construction, and after the ros node has been initialized. Plugins are * encouraged to subnamespace any of their parameters to prevent conflicts and allow the same plugin to be used * multiple times with different settings and topics. * * @param[in] name A unique name to give this plugin instance */ virtual void initialize(const std::string& name) = 0; /** * @brief Get the unique name of this publisher */ virtual const std::string& name() const = 0; /** * @brief Notify the publisher that an optimization cycle is complete, and about changes to the Graph. * * Most publishers will only publish new data whenever the Graph values have been updated. The Publisher::notify() * method will be called by the optimizer (and in the optimizer's thread) after every optimization cycle is * complete. Additionally, the set of added and removed variables and constraints since the last optimization cycle * will be provided to the publisher. In many cases this should prevent the plugins from searching through the * entire graph, looking for the variables of interest. * * @param[in] transaction A Transaction object, describing the set of variables that have been added and/or removed * @param[in] graph A read-only pointer to the graph object, allowing queries to be performed whenever needed */ virtual void notify(Transaction::ConstSharedPtr transaction, Graph::ConstSharedPtr graph) = 0; /** * @brief Function to be executed whenever the optimizer is ready to receive transactions * * This method will be called by the optimizer, in the optimizer's thread, once the optimizer has been initialized * and is ready to receive transactions. It may also be called as part of a stop-start cycle when the optimizer * has been requested to reset itself. This allows the publisher to reset any internal state before the * optimizer begins processing after a reset. No calls to notify() will happen before the optimizer calls start(). */ virtual void start() {} /** * @brief Function to be executed whenever the optimizer is no longer ready to receive transactions * * This method will be called by the optimizer, in the optimizer's thread, before the optimizer shutdowns. It may * also be called as part of a stop-start cycle when the optimizer has been requested to reset itself. This allows * the publisher to reset any internal state before the optimizer begins processing after a reset. No calls * to notify() will happen until start() has been called again. */ virtual void stop() {} }; } // namespace fuse_core #endif // FUSE_CORE_PUBLISHER_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/absolute_constraint.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_ABSOLUTE_CONSTRAINT_H #define FUSE_CONSTRAINTS_ABSOLUTE_CONSTRAINT_H #include <fuse_core/constraint.h> #include <fuse_core/eigen.h> #include <fuse_core/macros.h> #include <fuse_core/serialization.h> #include <fuse_core/uuid.h> #include <fuse_variables/acceleration_angular_2d_stamped.h> #include <fuse_variables/acceleration_linear_2d_stamped.h> #include <fuse_variables/orientation_2d_stamped.h> #include <fuse_variables/position_2d_stamped.h> #include <fuse_variables/position_3d_stamped.h> #include <fuse_variables/velocity_angular_2d_stamped.h> #include <fuse_variables/velocity_linear_2d_stamped.h> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/export.hpp> #include <ceres/cost_function.h> #include <ostream> #include <string> #include <vector> namespace fuse_constraints { /** * @brief A constraint that represents prior information about a variable or a direct measurement of the variable. * * This type of constraint arises in many situations. In mapping it is common to define the very first pose as the * origin. Some sensors, such as an IMU, provide direct measurements of certain state variables (e.g. linear * acceleration). And localization systems often match laserscans to a prior map (scan-to-map measurements). * This constraint holds the measured variable value and the measurement uncertainty/covariance. */ template<class Variable> class AbsoluteConstraint : public fuse_core::Constraint { public: FUSE_CONSTRAINT_DEFINITIONS(AbsoluteConstraint<Variable>); /** * @brief Default constructor */ AbsoluteConstraint() = default; /** * @brief Create a constraint using a measurement/prior of all dimensions of the target variable * * @param[in] source The name of the sensor or motion model that generated this constraint * @param[in] variable An object derived from fuse_core::Variable. * @param[in] mean The measured/prior value of all variable dimensions * @param[in] covariance The measurement/prior uncertainty of all variable dimensions */ AbsoluteConstraint( const std::string& source, const Variable& variable, const fuse_core::VectorXd& mean, const fuse_core::MatrixXd& covariance); /** * @brief Create a constraint using a measurement/prior of only a partial set of dimensions of the target variable * * @param[in] source The name of the sensor or motion model that generated this constraint * @param[in] variable An object derived from fuse_core::Variable. * @param[in] partial_mean The measured value of the subset of dimensions in the order defined by \p indices * @param[in] partial_covariance The uncertainty of the subset of dimensions in the order defined by \p indices. * @param[in] indices The set of indices corresponding to the measured dimensions */ AbsoluteConstraint( const std::string& source, const Variable& variable, const fuse_core::VectorXd& partial_mean, const fuse_core::MatrixXd& partial_covariance, const std::vector<size_t>& indices); /** * @brief Destructor */ virtual ~AbsoluteConstraint() = default; /** * @brief Read-only access to the measured/prior vector of mean values. * * All dimensions are present, even if only a partial set of dimensions were measured. Dimensions are in the order * defined by the variable, not the order defined by the \p indices parameter. All unmeasured variable dimensions * are set to zero. */ const fuse_core::VectorXd& mean() const { return mean_; } /** * @brief Read-only access to the square root information matrix. * * Dimensions are in the order defined by the variable, not the order defined by the \p indices parameter. The * square root information matrix will have size measured_dimensions X variable_dimensions. If only a partial set * of dimensions are measured, then this matrix will not be square. */ const fuse_core::MatrixXd& sqrtInformation() const { return sqrt_information_; } /** * @brief Compute the measurement covariance matrix. * * Dimensions are in the order defined by the variable, not the order defined by the \p indices parameter. The * covariance matrix will always be square, with size variable_dimensions X variable_dimensions. If only a * subset of dimensions are measured, then some rows/columns will be zero. This will result in a rank-deficient * covariance matrix. You have been warned. */ fuse_core::MatrixXd covariance() const; /** * @brief Print a human-readable description of the constraint to the provided stream. * * @param[out] stream The stream to write to. Defaults to stdout. */ void print(std::ostream& stream = std::cout) const override; /** * @brief Construct an instance of this constraint's cost function * * The function caller will own the new cost function instance. It is the responsibility of the caller to delete * the cost function object when it is no longer needed. If the pointer is provided to a Ceres::Problem object, the * Ceres::Problem object will takes ownership of the pointer and delete it during destruction. * * @return A base pointer to an instance of a derived CostFunction. */ ceres::CostFunction* costFunction() const override; protected: fuse_core::VectorXd mean_; //!< The measured/prior mean vector for this variable fuse_core::MatrixXd sqrt_information_; //!< The square root information matrix private: // Allow Boost Serialization access to private methods friend class boost::serialization::access; /** * @brief The Boost Serialize method that serializes all of the data members in to/out of the archive * * @param[in/out] archive - The archive object that holds the serialized class members * @param[in] version - The version of the archive being read/written. Generally unused. */ template<class Archive> void serialize(Archive& archive, const unsigned int /* version */) { archive & boost::serialization::base_object<fuse_core::Constraint>(*this); archive & mean_; archive & sqrt_information_; } }; // Define unique names for the different variations of the absolute constraint using AbsoluteAccelerationAngular2DStampedConstraint = AbsoluteConstraint<fuse_variables::AccelerationAngular2DStamped>; using AbsoluteAccelerationLinear2DStampedConstraint = AbsoluteConstraint<fuse_variables::AccelerationLinear2DStamped>; using AbsoluteOrientation2DStampedConstraint = AbsoluteConstraint<fuse_variables::Orientation2DStamped>; using AbsolutePosition2DStampedConstraint = AbsoluteConstraint<fuse_variables::Position2DStamped>; using AbsolutePosition3DStampedConstraint = AbsoluteConstraint<fuse_variables::Position3DStamped>; using AbsoluteVelocityAngular2DStampedConstraint = AbsoluteConstraint<fuse_variables::VelocityAngular2DStamped>; using AbsoluteVelocityLinear2DStampedConstraint = AbsoluteConstraint<fuse_variables::VelocityLinear2DStamped>; } // namespace fuse_constraints // Include the template implementation #include <fuse_constraints/absolute_constraint_impl.h> BOOST_CLASS_EXPORT_KEY(fuse_constraints::AbsoluteAccelerationAngular2DStampedConstraint); BOOST_CLASS_EXPORT_KEY(fuse_constraints::AbsoluteAccelerationLinear2DStampedConstraint); BOOST_CLASS_EXPORT_KEY(fuse_constraints::AbsoluteOrientation2DStampedConstraint); BOOST_CLASS_EXPORT_KEY(fuse_constraints::AbsolutePosition2DStampedConstraint); BOOST_CLASS_EXPORT_KEY(fuse_constraints::AbsolutePosition3DStampedConstraint); BOOST_CLASS_EXPORT_KEY(fuse_constraints::AbsoluteVelocityAngular2DStampedConstraint); BOOST_CLASS_EXPORT_KEY(fuse_constraints::AbsoluteVelocityLinear2DStampedConstraint); #endif // FUSE_CONSTRAINTS_ABSOLUTE_CONSTRAINT_H
congleetea/fuse
fuse_models/include/fuse_models/parameters/acceleration_2d_params.h
<reponame>congleetea/fuse<filename>fuse_models/include/fuse_models/parameters/acceleration_2d_params.h<gh_stars>0 /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_MODELS_PARAMETERS_ACCELERATION_2D_PARAMS_H #define FUSE_MODELS_PARAMETERS_ACCELERATION_2D_PARAMS_H #include <fuse_variables/acceleration_linear_2d_stamped.h> #include <fuse_models/parameters/parameter_base.h> #include <ros/node_handle.h> #include <string> #include <vector> namespace fuse_models { namespace parameters { /** * @brief Defines the set of parameters required by the Acceleration2D class */ struct Acceleration2DParams : public ParameterBase { public: /** * @brief Method for loading parameter values from ROS. * * @param[in] nh - The ROS node handle with which to load parameters */ void loadFromROS(const ros::NodeHandle& nh) final { indices = loadSensorConfig<fuse_variables::AccelerationLinear2DStamped>(nh, "dimensions"); nh.getParam("queue_size", queue_size); getParamRequired(nh, "topic", topic); getParamRequired(nh, "target_frame", target_frame); } int queue_size { 10 }; std::string topic {}; std::string target_frame {}; std::vector<size_t> indices; }; } // namespace parameters } // namespace fuse_models #endif // FUSE_MODELS_PARAMETERS_ACCELERATION_2D_PARAMS_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/marginal_cost_function.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_MARGINAL_COST_FUNCTION_H #define FUSE_CONSTRAINTS_MARGINAL_COST_FUNCTION_H #include <fuse_core/eigen.h> #include <fuse_core/local_parameterization.h> #include <ceres/cost_function.h> #include <vector> namespace fuse_constraints { /** * @brief Implements a cost function designed for precomputed marginal distributions * * The cost function is of the form: * * || ||^2 * cost(x) = || A1 * (x1 - x1_bar) + A2 * (x2 - x2_bar) + ... + An * (xn - xn_bar) + b || * || || * * where, the A matrices and the b vector are fixed, x_bar is the linearization point used when calculating the A * matrices and b vector, and the minus operator in (x - x_bar) is provided by the variable's local parameterization. * * The A matrices can have any number of rows, but they must all be the same. The number of columns of each A matrix * must match the associated variable's local parameterization size, and the number of rows of each x_bar must match * the associated variable's global size. The cost function will have the same number of residuals as the rows of A. */ class MarginalCostFunction : public ceres::CostFunction { public: /** * @brief Construct a cost function instance * * @param[in] A The A matrix of the marginal cost (of the form A*(x - x_bar) + b) * @param[in] b The b vector of the marginal cost (of the form A*(x - x_bar) + b) * @param[in] x_bar The linearization point of the involved variables * @param[in] local_parameterizations The local parameterization associated with the variable */ MarginalCostFunction( const std::vector<fuse_core::MatrixXd>& A, const fuse_core::VectorXd& b, const std::vector<fuse_core::VectorXd>& x_bar, const std::vector<fuse_core::LocalParameterization::SharedPtr>& local_parameterizations); /** * @brief Destructor */ virtual ~MarginalCostFunction() = default; /** * @brief Compute the cost values/residuals, and optionally the Jacobians, using the provided variable/parameter * values */ bool Evaluate( double const* const* parameters, double* residuals, double** jacobians) const override; private: const std::vector<fuse_core::MatrixXd>& A_; //!< The A matrices of the marginal cost const fuse_core::VectorXd& b_; //!< The b vector of the marginal cost const std::vector<fuse_core::LocalParameterization::SharedPtr>& local_parameterizations_; //!< Parameterizations const std::vector<fuse_core::VectorXd>& x_bar_; //!< The linearization point of each variable }; } // namespace fuse_constraints #endif // FUSE_CONSTRAINTS_MARGINAL_COST_FUNCTION_H
congleetea/fuse
fuse_constraints/include/fuse_constraints/normal_prior_orientation_2d.h
<reponame>congleetea/fuse /* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CONSTRAINTS_NORMAL_PRIOR_ORIENTATION_2D_H #define FUSE_CONSTRAINTS_NORMAL_PRIOR_ORIENTATION_2D_H #include <ceres/sized_cost_function.h> namespace fuse_constraints { /** * @brief Implements a cost function that models a direct measurement or prior on a 2D orientation variable * * The cost function is of the form: * * cost(x) = ||A(x - b)||^2 * * where, the matrix A and the vector b are fixed and x is the 2D orientation variable. * In case the user is interested in implementing a cost function of the form * * cost(x) = (x - mu)^T S^{-1} (x - mu) * * where, mu is a vector and S is a covariance matrix, then, A = S^{-1/2}, i.e the matrix A is the square root * information matrix (the inverse of the covariance). This is a specialization of the generic "normal prior" provided * by the Ceres library that handles the 2*pi roll-over that occurs with rotations. */ class NormalPriorOrientation2D : public ceres::SizedCostFunction<1, 1> { public: /** * @brief Constructor * * The number of rows in vector b must be the same as the number of columns of matrix A. * * @param[in] A The residual weighting matrix, most likely the square root information matrix * @param[in] b The measured difference between variable x0 and variable x1. It is assumed that these are the same * type of variable. At a minimum, they must have the same dimensions and the per-element subtraction * operator must be valid. */ NormalPriorOrientation2D(const double A, const double b); /** * @brief Destructor */ virtual ~NormalPriorOrientation2D() = default; /** * @brief Compute the cost values/residuals, and optionally the Jacobians, using the provided variable/parameter * values */ virtual bool Evaluate( double const* const* parameters, double* residuals, double** jacobians) const; private: double A_; //!< The residual weighting matrix, most likely the square root information matrix double b_; //!< The measured value of the 2D orientation }; } // namespace fuse_constraints #endif // FUSE_CONSTRAINTS_NORMAL_PRIOR_ORIENTATION_2D_H
congleetea/fuse
fuse_core/include/fuse_core/sensor_model.h
/* * Software License Agreement (BSD License) * * Copyright (c) 2018, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_SENSOR_MODEL_H #define FUSE_CORE_SENSOR_MODEL_H #include <fuse_core/graph.h> #include <fuse_core/macros.h> #include <fuse_core/transaction.h> #include <functional> #include <string> namespace fuse_core { /** * @brief The signature of the callback function that will be executed for every generated transaction object. */ using TransactionCallback = std::function<void(Transaction::SharedPtr transaction)>; /** * @brief The interface definition for sensor model plugins in the fuse ecosystem. * * A sensor model plugin is responsible for generating new constraints and passing them along to the optimizer, where * the actual sensor fusion takes place. This class defines the basic interface between the sensor model and the * optimizer. If you are developing your own sensor model, look at the AsyncSensorModel class, as this provides * additional features that make the sensor model act similar to a ROS node or nodelet. * * During the initialize() call, the optimizer will provide a transaction callback. This function serves the same * basic purpose as publishing a Transaction using a standard ROS publisher. Derived classes should call this function * whenever they are ready to send a fuse_core::Transaction object to the optimizer. This function will be called in * the SensorModel's thread. The optimizer implementation should ensure that this callback is safe to execute in this * thread. The optimizer should also ensure the callback executes quickly so that it will not block execution in the * SensorModel. */ class SensorModel { public: SMART_PTR_ALIASES_ONLY(SensorModel); /** * @brief Destructor */ virtual ~SensorModel() = default; /** * @brief Function to be executed whenever the optimizer has completed a Graph update * * This method will be called by the optimizer, in the optimizer's thread, after each Graph update is complete. This * generally means that new variables have been inserted into the Graph, and new optimized values are available. * To simplify synchronization between the sensor models and other consumers of Graph data, the provided Graph * object will never be updated by anyone. Thus, only read access to the Graph is provided. Information may be * accessed or computed, but it cannot be changed. The optimizer provides the sensors with Graph updates by * sending a new Graph object, not by modifying this Graph object. * * @param[in] graph A read-only pointer to the graph object, allowing queries to be performed whenever needed. */ virtual void graphCallback(Graph::ConstSharedPtr /*graph*/) {} /** * @brief Perform any required post-construction initialization, such as subscribing to topics or reading from the * parameter server. * * This will be called on each plugin after construction, and after the ROS node has been initialized. Plugins are * encouraged to subnamespace any of their parameters to prevent conflicts and allow the same plugin to be used * multiple times with different settings and topics. * * @param[in] name A unique name to give this plugin instance * @param[in] transaction_callback The function to call every time a transaction is published */ virtual void initialize( const std::string& name, TransactionCallback transaction_callback) = 0; /** * @brief Get the unique name of this sensor */ virtual const std::string& name() const = 0; /** * @brief Function to be executed whenever the optimizer is ready to receive transactions * * This method will be called by the optimizer, in the optimizer's thread, once the optimizer has been initialized * and is ready to receive transactions. It may also be called as part of a stop-start cycle when the optimizer * has been requested to reset itself. This allows the sensor model to reset any internal state before the * optimizer begins processing after a reset. * * The sensor model must not send any transactions to the optimizer before start() is called. */ virtual void start() {} /** * @brief Function to be executed whenever the optimizer is no longer ready to receive transactions * * This method will be called by the optimizer, in the optimizer's thread, before the optimizer shutdowns. It may * also be called as part of a stop-start cycle when the optimizer has been requested to reset itself. This allows * the sensor model to reset any internal state before the optimizer begins processing after a reset. * * The sensor model must not send any transactions to the optimizer after stop() is called. */ virtual void stop() {} protected: /** * @brief Default Constructor */ SensorModel() = default; }; } // namespace fuse_core #endif // FUSE_CORE_SENSOR_MODEL_H
psyeugenic/monarch
c_src/libmonarch.c
<reponame>psyeugenic/monarch<gh_stars>0 /* * Copyright (C) 2014 <NAME> * * File: libmonarch.c * Author: <NAME> * Created: 2014-09-11 */ #include <stdio.h> #include <string.h> #include <sys/types.h> #ifdef __linux__ #include <sys/sysinfo.h> #include <unistd.h> #endif #include <sys/time.h> #include <sys/sysctl.h> #ifdef __APPLE__ #include <mach/mach.h> #include <mach/host_info.h> #include <mach/mach_host.h> #include <mach/task_info.h> #include <mach/task.h> #endif /* getpwuid */ #include <pwd.h> #ifdef __APPLE__ #include <uuid/uuid.h> #endif /* getfsstat */ #ifdef __APPLE__ #include <sys/param.h> #include <sys/mount.h> #include <sys/ucred.h> #endif #ifdef __linux__ #include <mntent.h> #include <sys/statvfs.h> #endif #include "erl_nif.h" #ifdef __APPLE__ #define MIB_ENTRIES (12) #define MIB_STRING (0) #define MIB_INTEGER (1) #define MIB_TIMEVAL (2) #define MIB_TYPE_SZ (2) /* #bits required for types */ #define MIB_CLASS_SZ (15) /* #bits required for MIB TIER 1 */ /* mask val before oring .. */ #define MIB_ENC(C,M,TYPE) (((((M) << MIB_CLASS_SZ) | (C)) << MIB_TYPE_SZ) | (TYPE)) #define MIB_DEC_CLASS(C) (((C) >> (MIB_TYPE_SZ)) & ((1 << (MIB_CLASS_SZ)) - 1)) #define MIB_DEC_CODE(C) ((C) >> (MIB_CLASS_SZ + MIB_TYPE_SZ)) #define MIB_DEC_TYPE(C) ((C) & ((1 << MIB_TYPE_SZ) - 1)) #endif #define monarch_alloc(Sz) (malloc((Sz))) #define monarch_free(Ptr) (free((Ptr))) /* useful atoms */ static ERL_NIF_TERM am_error; static ERL_NIF_TERM am_ok; static ERL_NIF_TERM am_undefined; /* getfsstat */ static ERL_NIF_TERM am_mountpoint; static ERL_NIF_TERM am_blocks; static ERL_NIF_TERM am_bfree; static ERL_NIF_TERM am_bsize; static ERL_NIF_TERM am_device; /* vm_stat */ static ERL_NIF_TERM am_total; static ERL_NIF_TERM am_wired; static ERL_NIF_TERM am_active; static ERL_NIF_TERM am_inactive; static ERL_NIF_TERM am_free; #if defined (__APPLE__) /* sysctl */ static ERL_NIF_TERM mib_atom[MIB_ENTRIES]; static unsigned int mib_code[MIB_ENTRIES]; #elif defined (__linux__) static ERL_NIF_TERM am_pagesize; static ERL_NIF_TERM am_ncpu; #endif /* loadavg */ static ERL_NIF_TERM loadavg_key[3]; /* util */ static ERL_NIF_TERM am_cpu_id; /*static ERL_NIF_TERM am_user;*/ static ERL_NIF_TERM am_nice_user; static ERL_NIF_TERM am_kernel; static ERL_NIF_TERM am_io_wait; static ERL_NIF_TERM am_idle; static ERL_NIF_TERM am_hard_irq; static ERL_NIF_TERM am_soft_irq; static ERL_NIF_TERM am_steal; /* processes */ static ERL_NIF_TERM am_uid; static ERL_NIF_TERM am_pid; static ERL_NIF_TERM am_ppid; static ERL_NIF_TERM am_pgid; static ERL_NIF_TERM am_user; static ERL_NIF_TERM am_name; static ERL_NIF_TERM am_starttime; static ERL_NIF_TERM am_load; static ERL_NIF_TERM am_mem_res; static ERL_NIF_TERM am_mem_map; static ERL_NIF_TERM am_state; static ERL_NIF_TERM process_state[8]; /* machine * return: * #{ 'machine' => binary(), * 'model' => binary(), * 'ncpu' => integer(), * 'memsize' => integer(), * 'pagesize' => integer() }. * * The idea is to only return *static* data known at boot time. * * From CTL_HW: * * HW_MACHINE string no * HW_MODEL string no * HW_NCPU integer no (deprecated) * HW_BYTEORDER integer no * HW_MEMSIZE integer no * HW_PHYSMEM integer no (deprecated) * HW_PAGESIZE integer no * * hw.physicalcpu * hw.physicalcpu_max * hw.logicalcpu * hw.logicalcpu_max * * From CTL_KERN * * KERN_BOOTTIME struct timeval no * KERN_HOSTNAME string yes * KERN_OSRELDATE integer no * KERN_OSRELEASE string no * KERN_OSREV integer no * KERN_OSTYPE string no * KERN_VERSION string no * * KERN_ARGMAX integer no * KERN_BOOTFILE string yes * KERN_CLOCKRATE struct clockinfo no * KERN_FILE struct file no * KERN_HOSTID integer yes * KERN_JOB_CONTROL integer no * KERN_MAXFILES integer yes * KERN_MAXFILESPERPROC integer yes * KERN_MAXPROC integer no * KERN_MAXPROCPERUID integer yes * KERN_MAXVNODES integer yes * KERN_NGROUPS integer no * KERN_NISDOMAINNAME string yes * KERN_POSIX1 integer no * KERN_PROC struct kinfo_proc no * KERN_PROF node not applicable * KERN_QUANTUM integer yes * KERN_SAVED_IDS integer no * KERN_SECURELVL integer raise only * KERN_UPDATEINTERVAL integer no * KERN_VNODE struct vnode no * */ static ERL_NIF_TERM monarch_machine(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM map = enif_make_new_map(env); #if defined (__APPLE__) int ix,mib[2]; long val; size_t sz; for (ix=0; ix < MIB_ENTRIES; ix++) { mib[0] = MIB_DEC_CLASS(mib_code[ix]); mib[1] = MIB_DEC_CODE(mib_code[ix]); switch MIB_DEC_TYPE(mib_code[ix]) { case MIB_INTEGER: sz = sizeof(val); val = 0; sysctl(mib, 2, &val, &sz, NULL, 0); enif_make_map_put(env, map, mib_atom[ix], enif_make_long(env,val), &map); break; case MIB_STRING: { /* string .. null terminated ..*/ ErlNifBinary obin; char tmp[256]; sysctl(mib, 2, NULL, &sz, NULL, 0); if (sz < 2 || sz > 255) { return enif_make_badarg(env); } sysctl(mib, 2, tmp, &sz, NULL, 0); sz--; /* don't include \0 */ if (!enif_alloc_binary(sz,&obin)) { return enif_make_badarg(env); } memcpy(obin.data,tmp,sz); enif_make_map_put(env, map, mib_atom[ix], enif_make_binary(env,&obin), &map); } break; case MIB_TIMEVAL: { struct timeval tv; sz = sizeof(tv); sysctl(mib, 2, &tv, &sz, NULL, 0); enif_make_map_put(env, map, mib_atom[ix], enif_make_long(env,tv.tv_sec), &map); } break; } } #elif defined (__linux__) enif_make_map_put(env, map, am_pagesize, enif_make_long(env,sysconf(_SC_PAGESIZE)), &map); enif_make_map_put(env, map, am_ncpu, enif_make_long(env,sysconf(_SC_NPROCESSORS_CONF)), &map); #endif return map; } /* monarch_memory * return: * #{ 'total' => Bytes :: integer(), * 'wired' => Bytes :: integer(), * 'active' => Bytes :: integer(), * 'inactive' => Bytes :: integer(), * 'free' => Bytes :: integer() } */ static ERL_NIF_TERM monarch_memory(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { unsigned long total,wired,active,inactive,free; ERL_NIF_TERM map = enif_make_new_map(env); #if defined (__APPLE__) mach_msg_type_number_t count = HOST_VM_INFO_COUNT; vm_statistics_data_t vmstat; int pagesize = 0; size_t sz; int mib[] = { CTL_HW, HW_PAGESIZE }; if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t) &vmstat, &count) != KERN_SUCCESS) { return enif_make_badarg(env); } sz = sizeof(pagesize); sysctl(mib, 2, &pagesize, &sz, NULL, 0); /* natural_t is machine depedent unsigned int */ total = vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count; total = total * pagesize; wired = vmstat.wire_count * pagesize; active = vmstat.active_count * pagesize; inactive = vmstat.inactive_count * pagesize; free = vmstat.free_count * pagesize; #elif defined(__linux__) struct sysinfo meminfo; // struct sysinfo { // long uptime; /* Seconds since boot */ // unsigned long loads[3]; /* 1, 5, and 15 minute load averages */ // unsigned long totalram; /* Total usable main memory size */ // unsigned long freeram; /* Available memory size */ // unsigned long sharedram; /* Amount of shared memory */ // unsigned long bufferram; /* Memory used by buffers */ // unsigned long totalswap; /* Total swap space size */ // unsigned long freeswap; /* swap space still available */ // unsigned short procs; /* Number of current processes */ // char _f[22]; /* Pads structure to 64 bytes */ // }; sysinfo(&meminfo); total = meminfo.totalram; free = meminfo.freeram; active = 0; inactive = 0; wired = 0; #endif enif_make_map_put(env, map, am_total, enif_make_ulong(env,total), &map); enif_make_map_put(env, map, am_wired, enif_make_ulong(env,wired), &map); enif_make_map_put(env, map, am_active, enif_make_ulong(env,active), &map); enif_make_map_put(env, map, am_inactive, enif_make_ulong(env,inactive), &map); enif_make_map_put(env, map, am_free, enif_make_ulong(env,free), &map); return map; } /* monarch_loadavg * return: * #{ 1 => Load :: float(), * 5 => Load :: float(), * 15 => Load :: float() } */ static ERL_NIF_TERM monarch_loadavg(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM map = enif_make_new_map(env); int i, n; #if defined (__APPLE__) #define monarch_load_array(Ix) ((double) loadinfo.ldavg[(Ix)] / loadinfo.fscale) struct loadavg loadinfo; size_t sz; int mib[] = {CTL_VM, VM_LOADAVG}; sz = sizeof(loadinfo); if (sysctl(mib, 2, &loadinfo, &sz, NULL, 0) < 0) return enif_make_badarg(env); n = sizeof(loadinfo.ldavg) / sizeof(fixpt_t); #elif defined (__linux__) #define monarch_load_array(Ix) ((double) (meminfo.loads[(Ix)] / (float)(1 << SI_LOAD_SHIFT))) struct sysinfo meminfo; sysinfo(&meminfo); n = sizeof(meminfo.loads) / sizeof(meminfo.loads[0]); #endif for (i = 0; i < n; i++) { enif_make_map_put(env, map, loadavg_key[i], enif_make_double(env, monarch_load_array(i)), &map); } return map; } /* monarch_disks * return: * [#{bfree => Free :: integer(), * blocks => Blocks :: integer(), * mountpoint => Path :: binary() % ex. <<"/home">> * }]. */ static ERL_NIF_TERM monarch_disks(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM res = enif_make_list(env, 0); /* NIL */ ERL_NIF_TERM map; #if defined (__APPLE__) int i,fsn; size_t sz; struct statfs buf[125]; ErlNifBinary obin; fsn = getfsstat(NULL, 0, MNT_NOWAIT); getfsstat(buf, fsn * sizeof(struct statfs), MNT_NOWAIT); for (i = 0; i < fsn; ++i) { map = enif_make_new_map(env); sz = strlen(buf[i].f_mntonname); if (!enif_alloc_binary(sz,&obin)) { return enif_make_badarg(env); } memcpy(obin.data,buf[i].f_mntonname,sz); enif_make_map_put(env, map, am_mountpoint, enif_make_binary(env,&obin), &map); enif_make_map_put(env, map, am_blocks, enif_make_ulong(env,buf[i].f_blocks), &map); enif_make_map_put(env, map, am_bfree, enif_make_ulong(env,buf[i].f_bfree), &map); res = enif_make_list_cell(env, map, res); } #elif defined (__linux__) struct mntent *ent; struct statvfs vfs; FILE *mounts = setmntent("/etc/mtab", "r"); // struct mntent { // char *mnt_fsname; /* name of mounted filesystem */ // char *mnt_dir; /* filesystem path prefix */ // char *mnt_type; /* mount type (see mntent.h) */ // char *mnt_opts; /* mount options (see mntent.h) */ // int mnt_freq; /* dump frequency in days */ // int mnt_passno; /* pass number on parallel fsck */ // }; size_t sz; ErlNifBinary obin; // struct statvfs { // unsigned long f_bsize; /* filesystem block size */ // unsigned long f_frsize; /* fragment size */ // fsblkcnt_t f_blocks; /* size of fs in f_frsize units */ // fsblkcnt_t f_bfree; /* # free blocks */ // fsblkcnt_t f_bavail; /* # free blocks for unprivileged users */ // fsfilcnt_t f_files; /* # inodes */ // fsfilcnt_t f_ffree; /* # free inodes */ // fsfilcnt_t f_favail; /* # free inodes for unprivileged users */ // unsigned long f_fsid; /* filesystem ID */ // unsigned long f_flag; /* mount flags */ // unsigned long f_namemax; /* maximum filename length */ // }; while ((ent = getmntent(mounts)) != NULL) { statvfs(ent->mnt_dir, &vfs); map = enif_make_new_map(env); sz = strlen(ent->mnt_dir); if (!enif_alloc_binary(sz,&obin)) { return enif_make_badarg(env); } memcpy(obin.data,ent->mnt_dir,sz); enif_make_map_put(env, map, am_mountpoint, enif_make_binary(env, &obin), &map); sz = strlen(ent->mnt_fsname); if (!enif_alloc_binary(sz,&obin)) { return enif_make_badarg(env); } memcpy(obin.data,ent->mnt_fsname,sz); enif_make_map_put(env, map, am_device, enif_make_binary(env, &obin), &map); enif_make_map_put(env, map, am_blocks, enif_make_ulong(env,vfs.f_blocks), &map); enif_make_map_put(env, map, am_bfree, enif_make_ulong(env,vfs.f_bfree), &map); enif_make_map_put(env, map, am_bsize, enif_make_ulong(env,vfs.f_bsize), &map); res = enif_make_list_cell(env, map, res); } endmntent(mounts); #endif return res; } /* monarch_processes * * struct eproc { * struct proc *e_paddr; // address of proc * struct session *e_sess; // session pointer * struct pcred e_pcred; // process credentials * struct ucred e_ucred; // current credentials * struct vmspace e_vm; // address space * pid_t e_ppid; // parent process id * pid_t e_pgid; // process group id * short e_jobc; // job control counter * dev_t e_tdev; // controlling tty dev * pid_t e_tpgid; // tty process group id * struct session *e_tsess; // tty session pointer * #define WMESGLEN 7 * char e_wmesg[WMESGLEN+1]; // wchan message * segsz_t e_xsize; // text size * short e_xrssize; // text rss * short e_xccount; // text references * short e_xswrss; * long e_flag; * #define EPROC_CTTY 0x01 // controlling tty vnode active * #define EPROC_SLEADER 0x02 // session leader * char e_login[MAXLOGNAME]; // setlogin() name * long e_spare[4]; * } kp_eproc; * * * int procFlag = (int)(kp->kp_proc.p_flag); * char procStat = (char)(kp->kp_proc.p_stat); * pid_t procPid = (pid_t)(kp->kp_proc.p_pid); * u_char procPriority = (u_char)(kp->kp_proc.p_priority); * char procNice = (kp->kp_proc.p_nice); * NSString *procName = nameForProcessWithPID( kp->kp_proc.p_pid ); * pid_t procParentPid = (pid_t)(kp->kp_eproc.e_ppid); * time_t procStartTime = (kp->kp_proc.p_starttime.tv_sec); * uid_t userId = (kp->kp_eproc.e_ucred.cr_uid); * NSDate *theDate = [NSDate dateWithTimeIntervalSince1970:procStartTime]; * struct passwd *pw; */ #ifdef __APPLE__ static ERL_NIF_TERM monarch_get_process_name(ErlNifEnv *env, pid_t pid) { int mib[4], maxarg = 0, numArgs = 0; size_t sz = 0; char *args = NULL, *name = NULL, *string = NULL; ERL_NIF_TERM res = am_undefined; ErlNifBinary obin; mib[0] = CTL_KERN; mib[1] = KERN_ARGMAX; sz = sizeof(maxarg); if (sysctl(mib, 2, &maxarg, &sz, NULL, 0) == -1) { return am_undefined; } if ((args = (char *)monarch_alloc(maxarg)) == NULL) { return am_undefined; } mib[0] = CTL_KERN; mib[1] = KERN_PROCARGS2; mib[2] = pid; sz = (size_t) maxarg; if (sysctl(mib, 3, args, &sz, NULL, 0) == -1) { monarch_free(args); return am_undefined; } memcpy(&numArgs, args, sizeof(numArgs)); string = args + sizeof(numArgs); if ((name = strrchr(string, '/')) != NULL) { name++; } else { name = string; } sz = strlen(name); if (!enif_alloc_binary(sz,&obin)) { monarch_free(args); return am_undefined; } memcpy(obin.data,name,sz); res = enif_make_binary(env,&obin); monarch_free(args); return res; } #endif #ifdef __APPLE__ static ERL_NIF_TERM monarch_process(ErlNifEnv *env, struct kinfo_proc *proc) { uid_t uid = proc->kp_eproc.e_ucred.cr_uid; char *username = NULL; struct passwd *user = getpwuid(uid); ERL_NIF_TERM map; ErlNifBinary obin; size_t sz; username = user ? user->pw_name : "undefined"; map = enif_make_new_map(env); sz = strlen(username); /* int procFlag = (int)(kp->kp_proc.p_flag); * char procStat = (char)(kp->kp_proc.p_stat); * u_char procPriority = (u_char)(kp->kp_proc.p_priority); * char procNice = (kp->kp_proc.p_nice); */ if (!enif_alloc_binary(sz,&obin)) { return enif_make_badarg(env); } memcpy(obin.data,username,sz); /* user name */ enif_make_map_put(env, map, am_user, enif_make_binary(env,&obin), &map); /* user id */ enif_make_map_put(env, map, am_uid, enif_make_ulong(env,(unsigned long)uid), &map); /* process name, if any otherwise 'undefined' */ enif_make_map_put(env, map, am_name, monarch_get_process_name(env, proc->kp_proc.p_pid), &map); /* process id */ enif_make_map_put(env, map, am_pid, enif_make_ulong(env,(unsigned long)proc->kp_proc.p_pid), &map); /* parent process id */ enif_make_map_put(env, map, am_ppid, enif_make_ulong(env,(unsigned long)proc->kp_eproc.e_ppid), &map); /* process group id */ enif_make_map_put(env, map, am_pgid, enif_make_ulong(env,(unsigned long)proc->kp_eproc.e_pgid), &map); /* process start time in seconds */ enif_make_map_put(env, map, am_starttime, enif_make_long(env,(long)proc->kp_proc.p_starttime.tv_sec), &map); /* process state */ enif_make_map_put(env, map, am_state, enif_make_int(env,(int)proc->kp_proc.p_stat), &map); /* process memory mapped */ /* darn mac sz = (proc_list[i].kp_eproc.e_vm.vm_tsize + proc_list[i].kp_eproc.e_vm.vm_dsize + proc_list[i].kp_eproc.e_vm.vm_ssize);// * getpagesize(); enif_make_map_put(env, map, am_mem_map, enif_make_ulong(env,(unsigned long)sz), &map); */ /* process memory resident */ /* darn mac sz = proc_list[i].kp_eproc.e_vm.vm_rssize; // * getpagesize(); enif_make_map_put(env, map, am_mem_res, enif_make_ulong(env,(unsigned long)sz), &map); */ /* process memory load */ enif_make_map_put(env, map, am_load, enif_make_double(env,((double)proc->kp_proc.p_pctcpu / FSCALE)), &map); return map; } #endif /* monarch_processes * [#{load => Load :: float(), ex 0.0, * name => Name :: binary() | 'undefined', * pgid => Pgid :: integer(), * pid => Pid :: integer(), * ppid => Ppid :: integer(), * starttime => Secs :: integer(), 1428494470, * state => 2, * uid => 0, * user => <<"root">>}]. */ static ERL_NIF_TERM monarch_processes(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM res = enif_make_list(env, 0); /* NIL */ #ifdef __APPLE__ ERL_NIF_TERM map = am_undefined; struct kinfo_proc *proc_list = NULL; size_t sz = 0; int i, n, mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL }; /* XXX: Race condition? */ sysctl(mib, 3, NULL, &sz, NULL, 0); proc_list = monarch_alloc(sz); sysctl(mib, 3, proc_list, &sz, NULL, 0); n = sz / sizeof(struct kinfo_proc); for (i = 0; i < n; i++) { map = monarch_process(env, &(proc_list[i])); res = enif_make_list_cell(env, map, res); } monarch_free(proc_list); #endif return res; } static ERL_NIF_TERM monarch_cpu_util(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM res = enif_make_list(env, 0); /* NIL */ ERL_NIF_TERM map; #if defined (__APPLE__) int i; natural_t no_of_cpus; processor_info_array_t info_array; mach_msg_type_number_t info_count; mach_port_t host_port; kern_return_t error; processor_cpu_load_info_data_t *cpu_load_info = NULL; host_port = mach_host_self(); error = host_processor_info(host_port, PROCESSOR_CPU_LOAD_INFO, &no_of_cpus, &info_array, &info_count); if (error != KERN_SUCCESS) return enif_make_badarg(env); mach_port_deallocate(mach_task_self(), host_port); cpu_load_info = (processor_cpu_load_info_data_t *) info_array; for (i = 0; i < no_of_cpus; ++i) { map = enif_make_new_map(env); enif_make_map_put(env, map, am_cpu_id, enif_make_int(env,i), &map); enif_make_map_put(env, map, am_user, enif_make_ulong(env,cpu_load_info[i].cpu_ticks[CPU_STATE_USER]), &map); enif_make_map_put(env, map, am_nice_user, enif_make_ulong(env,cpu_load_info[i].cpu_ticks[CPU_STATE_NICE]), &map); enif_make_map_put(env, map, am_kernel, enif_make_ulong(env,cpu_load_info[i].cpu_ticks[CPU_STATE_SYSTEM]), &map); enif_make_map_put(env, map, am_idle, enif_make_ulong(env,cpu_load_info[i].cpu_ticks[CPU_STATE_IDLE]), &map); res = enif_make_list_cell(env, map, res); } error = vm_deallocate(mach_task_self(), (vm_address_t)info_array, info_count * sizeof(int)); if (error != KERN_SUCCESS) return enif_make_badarg(env); #endif return res; } /* boilerplate */ #ifdef __APPLE__ #define init_mib_code(Class,Code,Type,Ix,Name) \ do { \ mib_atom[Ix] = enif_make_atom(env,Name); \ mib_code[Ix] = MIB_ENC(Class,Code,Type); \ } while(0) #endif static void init(ErlNifEnv *env) { am_undefined = enif_make_atom(env,"undefined"); am_error = enif_make_atom(env,"error"); am_ok = enif_make_atom(env,"ok"); /* vm_stat */ am_total = enif_make_atom(env,"total"); am_wired = enif_make_atom(env,"wired"); am_active = enif_make_atom(env,"active"); am_inactive = enif_make_atom(env,"inactive"); am_free = enif_make_atom(env,"free"); /* vm_stat and statvfs*/ am_mountpoint = enif_make_atom(env,"mountpoint"); am_blocks = enif_make_atom(env,"blocks"); am_bfree = enif_make_atom(env,"bfree"); am_bsize = enif_make_atom(env,"bsize"); am_device = enif_make_atom(env,"device"); /* util */ am_cpu_id = enif_make_atom(env,"cpu_id"); /*am_user = enif_make_atom(env,"user");*/ am_nice_user = enif_make_atom(env,"nice_user"); am_kernel = enif_make_atom(env,"kernel"); am_io_wait = enif_make_atom(env,"io_wait"); am_idle = enif_make_atom(env,"idle"); am_hard_irq = enif_make_atom(env,"hard_irq"); am_soft_irq = enif_make_atom(env,"soft_irq"); am_steal = enif_make_atom(env,"steal"); /* loadavg */ loadavg_key[0] = enif_make_int(env,1); loadavg_key[1] = enif_make_int(env,5); loadavg_key[2] = enif_make_int(env,15); /* processes */ am_uid = enif_make_atom(env,"uid"); am_pid = enif_make_atom(env,"pid"); am_ppid = enif_make_atom(env,"ppid"); am_pgid = enif_make_atom(env,"pgid"); am_user = enif_make_atom(env,"user"); am_name = enif_make_atom(env,"name"); am_load = enif_make_atom(env,"load"); am_mem_res = enif_make_atom(env,"mem_res"); am_mem_map = enif_make_atom(env,"mem_map"); am_starttime = enif_make_atom(env,"starttime"); /* process states */ //char p_stat[]="?iRSTZ"; am_state = enif_make_atom(env,"state"); process_state[0] = enif_make_atom(env,"zombie"); process_state[1] = enif_make_atom(env,"running"); process_state[2] = enif_make_atom(env,"stuck"); process_state[3] = enif_make_atom(env,"sleeping"); process_state[4] = enif_make_atom(env,"idle"); process_state[5] = enif_make_atom(env,"stopped"); process_state[6] = enif_make_atom(env,"halted"); process_state[7] = enif_make_atom(env,"unknown"); /* sysctl */ #if defined (__APPLE__) init_mib_code(CTL_HW, HW_MACHINE, MIB_STRING, 0, "machine"); init_mib_code(CTL_HW, HW_MODEL, MIB_STRING, 1, "model"); init_mib_code(CTL_HW, HW_NCPU, MIB_INTEGER, 2, "ncpu"); init_mib_code(CTL_HW, HW_MEMSIZE, MIB_INTEGER, 3, "memsize"); init_mib_code(CTL_HW, HW_PAGESIZE, MIB_INTEGER, 4, "pagesize"); init_mib_code(CTL_KERN, KERN_HOSTNAME, MIB_STRING, 5, "hostname"); init_mib_code(CTL_KERN, KERN_OSRELDATE, MIB_INTEGER, 6, "osreldate"); init_mib_code(CTL_KERN, KERN_OSREV, MIB_INTEGER, 7, "osrev"); init_mib_code(CTL_KERN, KERN_OSRELEASE, MIB_STRING, 8, "osrelease"); init_mib_code(CTL_KERN, KERN_OSTYPE, MIB_STRING, 9, "ostype"); init_mib_code(CTL_KERN, KERN_VERSION, MIB_STRING, 10, "kernel_version"); init_mib_code(CTL_KERN, KERN_BOOTTIME, MIB_TIMEVAL, 11, "boottime"); #elif defined (__linux__) am_pagesize = enif_make_atom(env,"pagesize"); am_ncpu = enif_make_atom(env,"ncpu"); #endif } #undef init_mib_code static ErlNifFunc nif_functions[] = { {"loadavg", 0, monarch_loadavg}, {"memory", 0, monarch_memory}, {"processes", 0, monarch_processes}, {"disks", 0, monarch_disks}, {"cpu_util", 0, monarch_cpu_util}, {"machine", 0, monarch_machine} }; static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) { init(env); *priv_data = NULL; return 0; } ERL_NIF_INIT(monarch_lib, nif_functions, load, NULL, NULL, NULL)
tj1432423/Rectangle_Overlap_Judgement
Rectangle.h
<reponame>tj1432423/Rectangle_Overlap_Judgement #ifndef RECTANGLE_H #define RECTANGLE_H #include <math.h> #include "opencv2/core.hpp" using namespace cv; class Rectangle{ public: Rectangle(double _center_x,double _center_y,double _center_phi,double _length,double _width); bool Overlap(const Rectangle& obj); double length; double width; double head; Mat center_point; //[center_x,center_y] Mat unit_axis_vector; // [first_axis_vector;second_axis_vector] //副轴与主轴垂直,且符合右手定则 Mat vertex; // 4个顶点,逆时针 private: bool Atleft(const Mat& _p_start_point,const Mat& _p_end_point,const Mat& _point); }; #endif // RECTANGLE_OVERLAP_H
wangchunjie1993/test
test.c
<filename>test.c<gh_stars>0 #include<stdio.h> #include<unistd.h> int main() { pid_t pid; if((pid=fork())>0){ printf("I'm father.pid=%d,child's pid=%d\n",getpid(),pid); }else if(pid==0){ printf("I'm child.pid=%d,father's pid=%d\n",getpid(),getppid()); exit(0); }else{ printf("fork() failed\n"); exit(0); } system("echo hello > /dev/console"); sleep(1); exit(0); }
wangchunjie1993/test
serial.c
<filename>serial.c #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main(){ int len; char buffer[30]; int fd = open("/dev/tq2440_serial0",O_RDWR); if(fd<0){ printf("open file failed\n"); exit(-1); } printf("sizeof(buffer)=%d\n",sizeof(buffer)); while(1){ len=read(fd,buffer,sizeof(buffer)-1); if(len>0){ buffer[len]=0; printf("%s",buffer); } } close(fd); return 0; }
wangchunjie1993/test
beepApp.c
#include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main(){ int fd = open("/dev/PWM-Test",O_RDWR); if(fd<0){ printf("open file failed\n"); exit(-1); } ioctl(fd,1,2000); getchar(); ioctl(fd,0,1); close(fd); return 0; }
coolshou/hostap
wpa_supplicant/wpa_gui-qt4/userdatarequest.h
<gh_stars>0 /* * wpa_gui - UserDataRequest class * Copyright (c) 2005-2006, <NAME> <<EMAIL>> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef USERDATAREQUEST_H #define USERDATAREQUEST_H #include <QObject> #include <QtGlobal> #include "ui_userdatarequest.h" class WpaGui; class UserDataRequest : public QDialog, public Ui::UserDataRequest { Q_OBJECT public: #if QT_VERSION >= 0x050000 UserDataRequest(QWidget *parent = 0, const char *name = 0, bool modal = false, Qt::WindowFlags fl = 0); #else UserDataRequest(QWidget *parent = 0, const char *name = 0, bool modal = false, Qt::WFlags fl = 0); #endif ~UserDataRequest(); int setParams(WpaGui *_wpagui, const char *reqMsg); public slots: virtual void sendReply(); protected slots: virtual void languageChange(); private: WpaGui *wpagui; int networkid; QString field; }; #endif /* USERDATAREQUEST_H */
coolshou/hostap
src/crypto/tls_gnutls.c
<filename>src/crypto/tls_gnutls.c /* * SSL/TLS interface functions for GnuTLS * Copyright (c) 2004-2017, <NAME> <<EMAIL>> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "includes.h" #include <gnutls/gnutls.h> #include <gnutls/x509.h> #ifdef PKCS12_FUNCS #include <gnutls/pkcs12.h> #endif /* PKCS12_FUNCS */ #if GNUTLS_VERSION_NUMBER >= 0x030103 #include <gnutls/ocsp.h> #endif /* 3.1.3 */ #include "common.h" #include "crypto/crypto.h" #include "tls.h" static int tls_gnutls_ref_count = 0; struct tls_global { /* Data for session resumption */ void *session_data; size_t session_data_size; int server; int params_set; gnutls_certificate_credentials_t xcred; void (*event_cb)(void *ctx, enum tls_event ev, union tls_event_data *data); void *cb_ctx; int cert_in_cb; char *ocsp_stapling_response; }; struct tls_connection { struct tls_global *global; gnutls_session_t session; int read_alerts, write_alerts, failed; u8 *pre_shared_secret; size_t pre_shared_secret_len; int established; int verify_peer; unsigned int disable_time_checks:1; struct wpabuf *push_buf; struct wpabuf *pull_buf; const u8 *pull_buf_offset; int params_set; gnutls_certificate_credentials_t xcred; char *suffix_match; char *domain_match; unsigned int flags; }; static int tls_connection_verify_peer(gnutls_session_t session); static void tls_log_func(int level, const char *msg) { char *s, *pos; if (level == 6 || level == 7) { /* These levels seem to be mostly I/O debug and msg dumps */ return; } s = os_strdup(msg); if (s == NULL) return; pos = s; while (*pos != '\0') { if (*pos == '\n') { *pos = '\0'; break; } pos++; } wpa_printf(level > 3 ? MSG_MSGDUMP : MSG_DEBUG, "gnutls<%d> %s", level, s); os_free(s); } void * tls_init(const struct tls_config *conf) { struct tls_global *global; if (tls_gnutls_ref_count == 0) { wpa_printf(MSG_DEBUG, "GnuTLS: Library version %s (runtime) - %s (build)", gnutls_check_version(NULL), GNUTLS_VERSION); } global = os_zalloc(sizeof(*global)); if (global == NULL) return NULL; if (tls_gnutls_ref_count == 0 && gnutls_global_init() < 0) { os_free(global); return NULL; } tls_gnutls_ref_count++; gnutls_global_set_log_function(tls_log_func); if (wpa_debug_show_keys) gnutls_global_set_log_level(11); if (conf) { global->event_cb = conf->event_cb; global->cb_ctx = conf->cb_ctx; global->cert_in_cb = conf->cert_in_cb; } return global; } void tls_deinit(void *ssl_ctx) { struct tls_global *global = ssl_ctx; if (global) { if (global->params_set) gnutls_certificate_free_credentials(global->xcred); os_free(global->session_data); os_free(global->ocsp_stapling_response); os_free(global); } tls_gnutls_ref_count--; if (tls_gnutls_ref_count == 0) gnutls_global_deinit(); } int tls_get_errors(void *ssl_ctx) { return 0; } static ssize_t tls_pull_func(gnutls_transport_ptr_t ptr, void *buf, size_t len) { struct tls_connection *conn = (struct tls_connection *) ptr; const u8 *end; if (conn->pull_buf == NULL) { errno = EWOULDBLOCK; return -1; } end = wpabuf_head_u8(conn->pull_buf) + wpabuf_len(conn->pull_buf); if ((size_t) (end - conn->pull_buf_offset) < len) len = end - conn->pull_buf_offset; os_memcpy(buf, conn->pull_buf_offset, len); conn->pull_buf_offset += len; if (conn->pull_buf_offset == end) { wpa_printf(MSG_DEBUG, "%s - pull_buf consumed", __func__); wpabuf_free(conn->pull_buf); conn->pull_buf = NULL; conn->pull_buf_offset = NULL; } else { wpa_printf(MSG_DEBUG, "%s - %lu bytes remaining in pull_buf", __func__, (unsigned long) (end - conn->pull_buf_offset)); } return len; } static ssize_t tls_push_func(gnutls_transport_ptr_t ptr, const void *buf, size_t len) { struct tls_connection *conn = (struct tls_connection *) ptr; if (wpabuf_resize(&conn->push_buf, len) < 0) { errno = ENOMEM; return -1; } wpabuf_put_data(conn->push_buf, buf, len); return len; } static int tls_gnutls_init_session(struct tls_global *global, struct tls_connection *conn) { const char *err; int ret; ret = gnutls_init(&conn->session, global->server ? GNUTLS_SERVER : GNUTLS_CLIENT); if (ret < 0) { wpa_printf(MSG_INFO, "TLS: Failed to initialize new TLS " "connection: %s", gnutls_strerror(ret)); return -1; } ret = gnutls_set_default_priority(conn->session); if (ret < 0) goto fail; ret = gnutls_priority_set_direct(conn->session, "NORMAL:-VERS-SSL3.0", &err); if (ret < 0) { wpa_printf(MSG_ERROR, "GnuTLS: Priority string failure at " "'%s'", err); goto fail; } gnutls_transport_set_pull_function(conn->session, tls_pull_func); gnutls_transport_set_push_function(conn->session, tls_push_func); gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr_t) conn); gnutls_session_set_ptr(conn->session, conn); return 0; fail: wpa_printf(MSG_INFO, "TLS: Failed to setup new TLS connection: %s", gnutls_strerror(ret)); gnutls_deinit(conn->session); return -1; } struct tls_connection * tls_connection_init(void *ssl_ctx) { struct tls_global *global = ssl_ctx; struct tls_connection *conn; int ret; conn = os_zalloc(sizeof(*conn)); if (conn == NULL) return NULL; conn->global = global; if (tls_gnutls_init_session(global, conn)) { os_free(conn); return NULL; } if (global->params_set) { ret = gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, global->xcred); if (ret < 0) { wpa_printf(MSG_INFO, "Failed to configure " "credentials: %s", gnutls_strerror(ret)); os_free(conn); return NULL; } } if (gnutls_certificate_allocate_credentials(&conn->xcred)) { os_free(conn); return NULL; } return conn; } void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn) { if (conn == NULL) return; gnutls_certificate_free_credentials(conn->xcred); gnutls_deinit(conn->session); os_free(conn->pre_shared_secret); wpabuf_free(conn->push_buf); wpabuf_free(conn->pull_buf); os_free(conn->suffix_match); os_free(conn->domain_match); os_free(conn); } int tls_connection_established(void *ssl_ctx, struct tls_connection *conn) { return conn ? conn->established : 0; } char * tls_connection_peer_serial_num(void *tls_ctx, struct tls_connection *conn) { /* TODO */ return NULL; } int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn) { struct tls_global *global = ssl_ctx; int ret; if (conn == NULL) return -1; /* Shutdown previous TLS connection without notifying the peer * because the connection was already terminated in practice * and "close notify" shutdown alert would confuse AS. */ gnutls_bye(conn->session, GNUTLS_SHUT_RDWR); wpabuf_free(conn->push_buf); conn->push_buf = NULL; conn->established = 0; gnutls_deinit(conn->session); if (tls_gnutls_init_session(global, conn)) { wpa_printf(MSG_INFO, "GnuTLS: Failed to preparare new session " "for session resumption use"); return -1; } ret = gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, conn->params_set ? conn->xcred : global->xcred); if (ret < 0) { wpa_printf(MSG_INFO, "GnuTLS: Failed to configure credentials " "for session resumption: %s", gnutls_strerror(ret)); return -1; } if (global->session_data) { ret = gnutls_session_set_data(conn->session, global->session_data, global->session_data_size); if (ret < 0) { wpa_printf(MSG_INFO, "GnuTLS: Failed to set session " "data: %s", gnutls_strerror(ret)); return -1; } } return 0; } int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn, const struct tls_connection_params *params) { int ret; const char *err; char prio_buf[100]; const char *prio = NULL; if (conn == NULL || params == NULL) return -1; if (params->flags & TLS_CONN_REQUIRE_OCSP_ALL) { wpa_printf(MSG_INFO, "GnuTLS: ocsp=3 not supported"); return -1; } if (params->flags & TLS_CONN_EXT_CERT_CHECK) { wpa_printf(MSG_INFO, "GnuTLS: tls_ext_cert_check=1 not supported"); return -1; } if (params->subject_match) { wpa_printf(MSG_INFO, "GnuTLS: subject_match not supported"); return -1; } if (params->altsubject_match) { wpa_printf(MSG_INFO, "GnuTLS: altsubject_match not supported"); return -1; } os_free(conn->suffix_match); conn->suffix_match = NULL; if (params->suffix_match) { conn->suffix_match = os_strdup(params->suffix_match); if (conn->suffix_match == NULL) return -1; } #if GNUTLS_VERSION_NUMBER >= 0x030300 os_free(conn->domain_match); conn->domain_match = NULL; if (params->domain_match) { conn->domain_match = os_strdup(params->domain_match); if (conn->domain_match == NULL) return -1; } #else /* < 3.3.0 */ if (params->domain_match) { wpa_printf(MSG_INFO, "GnuTLS: domain_match not supported"); return -1; } #endif /* >= 3.3.0 */ conn->flags = params->flags; if (params->flags & (TLS_CONN_DISABLE_TLSv1_0 | TLS_CONN_DISABLE_TLSv1_1 | TLS_CONN_DISABLE_TLSv1_2)) { os_snprintf(prio_buf, sizeof(prio_buf), "NORMAL:-VERS-SSL3.0%s%s%s", params->flags & TLS_CONN_DISABLE_TLSv1_0 ? ":-VERS-TLS1.0" : "", params->flags & TLS_CONN_DISABLE_TLSv1_1 ? ":-VERS-TLS1.1" : "", params->flags & TLS_CONN_DISABLE_TLSv1_2 ? ":-VERS-TLS1.2" : ""); prio = prio_buf; } if (params->openssl_ciphers) { if (os_strcmp(params->openssl_ciphers, "SUITEB128") == 0) { prio = "SUITEB128"; } else if (os_strcmp(params->openssl_ciphers, "SUITEB192") == 0) { prio = "SUITEB192"; } else if ((params->flags & TLS_CONN_SUITEB) && os_strcmp(params->openssl_ciphers, "ECDHE-RSA-AES256-GCM-SHA384") == 0) { prio = "NONE:+VERS-TLS1.2:+AEAD:+ECDHE-RSA:+AES-256-GCM:+SIGN-RSA-SHA384:+CURVE-SECP384R1:+COMP-NULL"; } else if (os_strcmp(params->openssl_ciphers, "ECDHE-RSA-AES256-GCM-SHA384") == 0) { prio = "NONE:+VERS-TLS1.2:+AEAD:+ECDHE-RSA:+AES-256-GCM:+SIGN-RSA-SHA384:+CURVE-SECP384R1:+COMP-NULL"; } else if (os_strcmp(params->openssl_ciphers, "DHE-RSA-AES256-GCM-SHA384") == 0) { prio = "NONE:+VERS-TLS1.2:+AEAD:+DHE-RSA:+AES-256-GCM:+SIGN-RSA-SHA384:+CURVE-SECP384R1:+COMP-NULL:%PROFILE_HIGH"; } else if (os_strcmp(params->openssl_ciphers, "ECDHE-ECDSA-AES256-GCM-SHA384") == 0) { prio = "NONE:+VERS-TLS1.2:+AEAD:+ECDHE-ECDSA:+AES-256-GCM:+SIGN-RSA-SHA384:+CURVE-SECP384R1:+COMP-NULL"; } else { wpa_printf(MSG_INFO, "GnuTLS: openssl_ciphers not supported"); return -1; } } else if (params->flags & TLS_CONN_SUITEB) { prio = "NONE:+VERS-TLS1.2:+AEAD:+ECDHE-ECDSA:+ECDHE-RSA:+DHE-RSA:+AES-256-GCM:+SIGN-RSA-SHA384:+CURVE-SECP384R1:+COMP-NULL:%PROFILE_HIGH"; } if (prio) { wpa_printf(MSG_DEBUG, "GnuTLS: Set priority string: %s", prio); ret = gnutls_priority_set_direct(conn->session, prio, &err); if (ret < 0) { wpa_printf(MSG_ERROR, "GnuTLS: Priority string failure at '%s'", err); return -1; } } /* TODO: gnutls_certificate_set_verify_flags(xcred, flags); * to force peer validation(?) */ if (params->ca_cert) { wpa_printf(MSG_DEBUG, "GnuTLS: Try to parse %s in DER format", params->ca_cert); ret = gnutls_certificate_set_x509_trust_file( conn->xcred, params->ca_cert, GNUTLS_X509_FMT_DER); if (ret < 0) { wpa_printf(MSG_DEBUG, "GnuTLS: Failed to read CA cert '%s' in DER format (%s) - try in PEM format", params->ca_cert, gnutls_strerror(ret)); ret = gnutls_certificate_set_x509_trust_file( conn->xcred, params->ca_cert, GNUTLS_X509_FMT_PEM); if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to read CA cert '%s' in PEM format: %s", params->ca_cert, gnutls_strerror(ret)); return -1; } wpa_printf(MSG_DEBUG, "GnuTLS: Successfully read CA cert '%s' in PEM format", params->ca_cert); } else { wpa_printf(MSG_DEBUG, "GnuTLS: Successfully read CA cert '%s' in DER format", params->ca_cert); } } else if (params->ca_cert_blob) { gnutls_datum_t ca; ca.data = (unsigned char *) params->ca_cert_blob; ca.size = params->ca_cert_blob_len; ret = gnutls_certificate_set_x509_trust_mem( conn->xcred, &ca, GNUTLS_X509_FMT_DER); if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to parse CA cert in DER format: %s", gnutls_strerror(ret)); ret = gnutls_certificate_set_x509_trust_mem( conn->xcred, &ca, GNUTLS_X509_FMT_PEM); if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to parse CA cert in PEM format: %s", gnutls_strerror(ret)); return -1; } } } else if (params->ca_path) { wpa_printf(MSG_INFO, "GnuTLS: ca_path not supported"); return -1; } conn->disable_time_checks = 0; if (params->ca_cert || params->ca_cert_blob) { conn->verify_peer = 1; gnutls_certificate_set_verify_function( conn->xcred, tls_connection_verify_peer); if (params->flags & TLS_CONN_ALLOW_SIGN_RSA_MD5) { gnutls_certificate_set_verify_flags( conn->xcred, GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5); } if (params->flags & TLS_CONN_DISABLE_TIME_CHECKS) { conn->disable_time_checks = 1; gnutls_certificate_set_verify_flags( conn->xcred, GNUTLS_VERIFY_DISABLE_TIME_CHECKS); } } if (params->client_cert && params->private_key) { wpa_printf(MSG_DEBUG, "GnuTLS: Try to parse client cert '%s' and key '%s' in DER format", params->client_cert, params->private_key); #if GNUTLS_VERSION_NUMBER >= 0x03010b ret = gnutls_certificate_set_x509_key_file2( conn->xcred, params->client_cert, params->private_key, GNUTLS_X509_FMT_DER, params->private_key_passwd, 0); #else /* private_key_passwd not (easily) supported here */ ret = gnutls_certificate_set_x509_key_file( conn->xcred, params->client_cert, params->private_key, GNUTLS_X509_FMT_DER); #endif if (ret < 0) { wpa_printf(MSG_DEBUG, "GnuTLS: Failed to read client cert/key in DER format (%s) - try in PEM format", gnutls_strerror(ret)); #if GNUTLS_VERSION_NUMBER >= 0x03010b ret = gnutls_certificate_set_x509_key_file2( conn->xcred, params->client_cert, params->private_key, GNUTLS_X509_FMT_PEM, params->private_key_passwd, 0); #else ret = gnutls_certificate_set_x509_key_file( conn->xcred, params->client_cert, params->private_key, GNUTLS_X509_FMT_PEM); #endif if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to read client " "cert/key in PEM format: %s", gnutls_strerror(ret)); return ret; } wpa_printf(MSG_DEBUG, "GnuTLS: Successfully read client cert/key in PEM format"); } else { wpa_printf(MSG_DEBUG, "GnuTLS: Successfully read client cert/key in DER format"); } } else if (params->private_key) { int pkcs12_ok = 0; #ifdef PKCS12_FUNCS /* Try to load in PKCS#12 format */ wpa_printf(MSG_DEBUG, "GnuTLS: Try to parse client cert/key '%s'in PKCS#12 DER format", params->private_key); ret = gnutls_certificate_set_x509_simple_pkcs12_file( conn->xcred, params->private_key, GNUTLS_X509_FMT_DER, params->private_key_passwd); if (ret != 0) { wpa_printf(MSG_DEBUG, "Failed to load private_key in " "PKCS#12 format: %s", gnutls_strerror(ret)); return -1; } else pkcs12_ok = 1; #endif /* PKCS12_FUNCS */ if (!pkcs12_ok) { wpa_printf(MSG_DEBUG, "GnuTLS: PKCS#12 support not " "included"); return -1; } } else if (params->client_cert_blob && params->private_key_blob) { gnutls_datum_t cert, key; cert.data = (unsigned char *) params->client_cert_blob; cert.size = params->client_cert_blob_len; key.data = (unsigned char *) params->private_key_blob; key.size = params->private_key_blob_len; #if GNUTLS_VERSION_NUMBER >= 0x03010b ret = gnutls_certificate_set_x509_key_mem2( conn->xcred, &cert, &key, GNUTLS_X509_FMT_DER, params->private_key_passwd, 0); #else /* private_key_passwd not (easily) supported here */ ret = gnutls_certificate_set_x509_key_mem( conn->xcred, &cert, &key, GNUTLS_X509_FMT_DER); #endif if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to read client cert/key " "in DER format: %s", gnutls_strerror(ret)); #if GNUTLS_VERSION_NUMBER >= 0x03010b ret = gnutls_certificate_set_x509_key_mem2( conn->xcred, &cert, &key, GNUTLS_X509_FMT_PEM, params->private_key_passwd, 0); #else /* private_key_passwd not (easily) supported here */ ret = gnutls_certificate_set_x509_key_mem( conn->xcred, &cert, &key, GNUTLS_X509_FMT_PEM); #endif if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to read client " "cert/key in PEM format: %s", gnutls_strerror(ret)); return ret; } } } else if (params->private_key_blob) { #ifdef PKCS12_FUNCS gnutls_datum_t key; key.data = (unsigned char *) params->private_key_blob; key.size = params->private_key_blob_len; /* Try to load in PKCS#12 format */ ret = gnutls_certificate_set_x509_simple_pkcs12_mem( conn->xcred, &key, GNUTLS_X509_FMT_DER, params->private_key_passwd); if (ret != 0) { wpa_printf(MSG_DEBUG, "Failed to load private_key in " "PKCS#12 format: %s", gnutls_strerror(ret)); return -1; } #else /* PKCS12_FUNCS */ wpa_printf(MSG_DEBUG, "GnuTLS: PKCS#12 support not included"); return -1; #endif /* PKCS12_FUNCS */ } #if GNUTLS_VERSION_NUMBER >= 0x030103 if (params->flags & (TLS_CONN_REQUEST_OCSP | TLS_CONN_REQUIRE_OCSP)) { ret = gnutls_ocsp_status_request_enable_client(conn->session, NULL, 0, NULL); if (ret != GNUTLS_E_SUCCESS) { wpa_printf(MSG_INFO, "GnuTLS: Failed to enable OCSP client"); return -1; } } #else /* 3.1.3 */ if (params->flags & TLS_CONN_REQUIRE_OCSP) { wpa_printf(MSG_INFO, "GnuTLS: OCSP not supported by this version of GnuTLS"); return -1; } #endif /* 3.1.3 */ conn->params_set = 1; ret = gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, conn->xcred); if (ret < 0) { wpa_printf(MSG_INFO, "Failed to configure credentials: %s", gnutls_strerror(ret)); } return ret; } #if GNUTLS_VERSION_NUMBER >= 0x030103 static int server_ocsp_status_req(gnutls_session_t session, void *ptr, gnutls_datum_t *resp) { struct tls_global *global = ptr; char *cached; size_t len; if (!global->ocsp_stapling_response) { wpa_printf(MSG_DEBUG, "GnuTLS: OCSP status callback - no response configured"); return GNUTLS_E_NO_CERTIFICATE_STATUS; } cached = os_readfile(global->ocsp_stapling_response, &len); if (!cached) { wpa_printf(MSG_DEBUG, "GnuTLS: OCSP status callback - could not read response file (%s)", global->ocsp_stapling_response); return GNUTLS_E_NO_CERTIFICATE_STATUS; } wpa_printf(MSG_DEBUG, "GnuTLS: OCSP status callback - send cached response"); resp->data = gnutls_malloc(len); if (!resp->data) { os_free(resp); return GNUTLS_E_MEMORY_ERROR; } os_memcpy(resp->data, cached, len); resp->size = len; os_free(cached); return GNUTLS_E_SUCCESS; } #endif /* 3.1.3 */ int tls_global_set_params(void *tls_ctx, const struct tls_connection_params *params) { struct tls_global *global = tls_ctx; int ret; /* Currently, global parameters are only set when running in server * mode. */ global->server = 1; if (global->params_set) { gnutls_certificate_free_credentials(global->xcred); global->params_set = 0; } ret = gnutls_certificate_allocate_credentials(&global->xcred); if (ret) { wpa_printf(MSG_DEBUG, "Failed to allocate global credentials " "%s", gnutls_strerror(ret)); return -1; } if (params->ca_cert) { ret = gnutls_certificate_set_x509_trust_file( global->xcred, params->ca_cert, GNUTLS_X509_FMT_DER); if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to read CA cert '%s' " "in DER format: %s", params->ca_cert, gnutls_strerror(ret)); ret = gnutls_certificate_set_x509_trust_file( global->xcred, params->ca_cert, GNUTLS_X509_FMT_PEM); if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to read CA cert " "'%s' in PEM format: %s", params->ca_cert, gnutls_strerror(ret)); goto fail; } } if (params->flags & TLS_CONN_ALLOW_SIGN_RSA_MD5) { gnutls_certificate_set_verify_flags( global->xcred, GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5); } if (params->flags & TLS_CONN_DISABLE_TIME_CHECKS) { gnutls_certificate_set_verify_flags( global->xcred, GNUTLS_VERIFY_DISABLE_TIME_CHECKS); } } if (params->client_cert && params->private_key) { /* TODO: private_key_passwd? */ ret = gnutls_certificate_set_x509_key_file( global->xcred, params->client_cert, params->private_key, GNUTLS_X509_FMT_DER); if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to read client cert/key " "in DER format: %s", gnutls_strerror(ret)); ret = gnutls_certificate_set_x509_key_file( global->xcred, params->client_cert, params->private_key, GNUTLS_X509_FMT_PEM); if (ret < 0) { wpa_printf(MSG_DEBUG, "Failed to read client " "cert/key in PEM format: %s", gnutls_strerror(ret)); goto fail; } } } else if (params->private_key) { int pkcs12_ok = 0; #ifdef PKCS12_FUNCS /* Try to load in PKCS#12 format */ ret = gnutls_certificate_set_x509_simple_pkcs12_file( global->xcred, params->private_key, GNUTLS_X509_FMT_DER, params->private_key_passwd); if (ret != 0) { wpa_printf(MSG_DEBUG, "Failed to load private_key in " "PKCS#12 format: %s", gnutls_strerror(ret)); goto fail; } else pkcs12_ok = 1; #endif /* PKCS12_FUNCS */ if (!pkcs12_ok) { wpa_printf(MSG_DEBUG, "GnuTLS: PKCS#12 support not " "included"); goto fail; } } #if GNUTLS_VERSION_NUMBER >= 0x030103 os_free(global->ocsp_stapling_response); if (params->ocsp_stapling_response) global->ocsp_stapling_response = os_strdup(params->ocsp_stapling_response); else global->ocsp_stapling_response = NULL; gnutls_certificate_set_ocsp_status_request_function( global->xcred, server_ocsp_status_req, global); #endif /* 3.1.3 */ global->params_set = 1; return 0; fail: gnutls_certificate_free_credentials(global->xcred); return -1; } int tls_global_set_verify(void *ssl_ctx, int check_crl) { /* TODO */ return 0; } int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn, int verify_peer, unsigned int flags, const u8 *session_ctx, size_t session_ctx_len) { if (conn == NULL || conn->session == NULL) return -1; conn->verify_peer = verify_peer; gnutls_certificate_server_set_request(conn->session, verify_peer ? GNUTLS_CERT_REQUIRE : GNUTLS_CERT_REQUEST); return 0; } int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn, struct tls_random *keys) { #if GNUTLS_VERSION_NUMBER >= 0x030012 gnutls_datum_t client, server; if (conn == NULL || conn->session == NULL || keys == NULL) return -1; os_memset(keys, 0, sizeof(*keys)); gnutls_session_get_random(conn->session, &client, &server); keys->client_random = client.data; keys->server_random = server.data; keys->client_random_len = client.size; keys->server_random_len = client.size; return 0; #else /* 3.0.18 */ return -1; #endif /* 3.0.18 */ } int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn, const char *label, u8 *out, size_t out_len) { if (conn == NULL || conn->session == NULL) return -1; return gnutls_prf(conn->session, os_strlen(label), label, 0 /* client_random first */, 0, NULL, out_len, (char *) out); } int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn, u8 *out, size_t out_len) { return -1; } static void gnutls_tls_fail_event(struct tls_connection *conn, const gnutls_datum_t *cert, int depth, const char *subject, const char *err_str, enum tls_fail_reason reason) { union tls_event_data ev; struct tls_global *global = conn->global; struct wpabuf *cert_buf = NULL; if (global->event_cb == NULL) return; os_memset(&ev, 0, sizeof(ev)); ev.cert_fail.depth = depth; ev.cert_fail.subject = subject ? subject : ""; ev.cert_fail.reason = reason; ev.cert_fail.reason_txt = err_str; if (cert) { cert_buf = wpabuf_alloc_copy(cert->data, cert->size); ev.cert_fail.cert = cert_buf; } global->event_cb(global->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev); wpabuf_free(cert_buf); } #if GNUTLS_VERSION_NUMBER < 0x030300 static int server_eku_purpose(gnutls_x509_crt_t cert) { unsigned int i; for (i = 0; ; i++) { char oid[128]; size_t oid_size = sizeof(oid); int res; res = gnutls_x509_crt_get_key_purpose_oid(cert, i, oid, &oid_size, NULL); if (res == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) { if (i == 0) { /* No EKU - assume any use allowed */ return 1; } break; } if (res < 0) { wpa_printf(MSG_INFO, "GnuTLS: Failed to get EKU"); return 0; } wpa_printf(MSG_DEBUG, "GnuTLS: Certificate purpose: %s", oid); if (os_strcmp(oid, GNUTLS_KP_TLS_WWW_SERVER) == 0 || os_strcmp(oid, GNUTLS_KP_ANY) == 0) return 1; } return 0; } #endif /* < 3.3.0 */ static int check_ocsp(struct tls_connection *conn, gnutls_session_t session, gnutls_alert_description_t *err) { #if GNUTLS_VERSION_NUMBER >= 0x030103 gnutls_datum_t response, buf; gnutls_ocsp_resp_t resp; unsigned int cert_status; int res; if (!(conn->flags & (TLS_CONN_REQUEST_OCSP | TLS_CONN_REQUIRE_OCSP))) return 0; if (!gnutls_ocsp_status_request_is_checked(session, 0)) { if (conn->flags & TLS_CONN_REQUIRE_OCSP) { wpa_printf(MSG_INFO, "GnuTLS: No valid OCSP response received"); goto ocsp_error; } wpa_printf(MSG_DEBUG, "GnuTLS: Valid OCSP response was not received - continue since OCSP was not required"); return 0; } /* * GnuTLS has already verified the OCSP response in * check_ocsp_response() and rejected handshake if the certificate was * found to be revoked. However, if the response indicates that the * status is unknown, handshake continues and reaches here. We need to * re-import the OCSP response to check for unknown certificate status, * but we do not need to repeat gnutls_ocsp_resp_check_crt() and * gnutls_ocsp_resp_verify_direct() calls. */ res = gnutls_ocsp_status_request_get(session, &response); if (res != GNUTLS_E_SUCCESS) { wpa_printf(MSG_INFO, "GnuTLS: OCSP response was received, but it was not valid"); goto ocsp_error; } if (gnutls_ocsp_resp_init(&resp) != GNUTLS_E_SUCCESS) goto ocsp_error; res = gnutls_ocsp_resp_import(resp, &response); if (res != GNUTLS_E_SUCCESS) { wpa_printf(MSG_INFO, "GnuTLS: Could not parse received OCSP response: %s", gnutls_strerror(res)); gnutls_ocsp_resp_deinit(resp); goto ocsp_error; } res = gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &buf); if (res == GNUTLS_E_SUCCESS) { wpa_printf(MSG_DEBUG, "GnuTLS: %s", buf.data); gnutls_free(buf.data); } res = gnutls_ocsp_resp_get_single(resp, 0, NULL, NULL, NULL, NULL, &cert_status, NULL, NULL, NULL, NULL); gnutls_ocsp_resp_deinit(resp); if (res != GNUTLS_E_SUCCESS) { wpa_printf(MSG_INFO, "GnuTLS: Failed to extract OCSP information: %s", gnutls_strerror(res)); goto ocsp_error; } if (cert_status == GNUTLS_OCSP_CERT_GOOD) { wpa_printf(MSG_DEBUG, "GnuTLS: OCSP cert status: good"); } else if (cert_status == GNUTLS_OCSP_CERT_REVOKED) { wpa_printf(MSG_DEBUG, "GnuTLS: OCSP cert status: revoked"); goto ocsp_error; } else { wpa_printf(MSG_DEBUG, "GnuTLS: OCSP cert status: unknown"); if (conn->flags & TLS_CONN_REQUIRE_OCSP) goto ocsp_error; wpa_printf(MSG_DEBUG, "GnuTLS: OCSP was not required, so allow connection to continue"); } return 0; ocsp_error: gnutls_tls_fail_event(conn, NULL, 0, NULL, "bad certificate status response", TLS_FAIL_REVOKED); *err = GNUTLS_A_CERTIFICATE_REVOKED; return -1; #else /* GnuTLS 3.1.3 or newer */ return 0; #endif /* GnuTLS 3.1.3 or newer */ } static int tls_connection_verify_peer(gnutls_session_t session) { struct tls_connection *conn; unsigned int status, num_certs, i; struct os_time now; const gnutls_datum_t *certs; gnutls_x509_crt_t cert; gnutls_alert_description_t err; int res; conn = gnutls_session_get_ptr(session); if (!conn->verify_peer) { wpa_printf(MSG_DEBUG, "GnuTLS: No peer certificate verification enabled"); return 0; } wpa_printf(MSG_DEBUG, "GnuTSL: Verifying peer certificate"); #if GNUTLS_VERSION_NUMBER >= 0x030300 { gnutls_typed_vdata_st data[1]; unsigned int elements = 0; os_memset(data, 0, sizeof(data)); if (!conn->global->server) { data[elements].type = GNUTLS_DT_KEY_PURPOSE_OID; data[elements].data = (void *) GNUTLS_KP_TLS_WWW_SERVER; elements++; } res = gnutls_certificate_verify_peers(session, data, 1, &status); } #else /* < 3.3.0 */ res = gnutls_certificate_verify_peers2(session, &status); #endif if (res < 0) { wpa_printf(MSG_INFO, "TLS: Failed to verify peer " "certificate chain"); err = GNUTLS_A_INTERNAL_ERROR; goto out; } #if GNUTLS_VERSION_NUMBER >= 0x030104 { gnutls_datum_t info; int ret, type; type = gnutls_certificate_type_get(session); ret = gnutls_certificate_verification_status_print(status, type, &info, 0); if (ret < 0) { wpa_printf(MSG_DEBUG, "GnuTLS: Failed to print verification status"); err = GNUTLS_A_INTERNAL_ERROR; goto out; } wpa_printf(MSG_DEBUG, "GnuTLS: %s", info.data); gnutls_free(info.data); } #endif /* GnuTLS 3.1.4 or newer */ certs = gnutls_certificate_get_peers(session, &num_certs); if (certs == NULL || num_certs == 0) { wpa_printf(MSG_INFO, "TLS: No peer certificate chain received"); err = GNUTLS_A_UNKNOWN_CA; goto out; } if (conn->verify_peer && (status & GNUTLS_CERT_INVALID)) { wpa_printf(MSG_INFO, "TLS: Peer certificate not trusted"); if (status & GNUTLS_CERT_INSECURE_ALGORITHM) { wpa_printf(MSG_INFO, "TLS: Certificate uses insecure " "algorithm"); gnutls_tls_fail_event(conn, NULL, 0, NULL, "certificate uses insecure algorithm", TLS_FAIL_BAD_CERTIFICATE); err = GNUTLS_A_INSUFFICIENT_SECURITY; goto out; } if (status & GNUTLS_CERT_NOT_ACTIVATED) { wpa_printf(MSG_INFO, "TLS: Certificate not yet " "activated"); gnutls_tls_fail_event(conn, NULL, 0, NULL, "certificate not yet valid", TLS_FAIL_NOT_YET_VALID); err = GNUTLS_A_CERTIFICATE_EXPIRED; goto out; } if (status & GNUTLS_CERT_EXPIRED) { wpa_printf(MSG_INFO, "TLS: Certificate expired"); gnutls_tls_fail_event(conn, NULL, 0, NULL, "certificate has expired", TLS_FAIL_EXPIRED); err = GNUTLS_A_CERTIFICATE_EXPIRED; goto out; } gnutls_tls_fail_event(conn, NULL, 0, NULL, "untrusted certificate", TLS_FAIL_UNTRUSTED); err = GNUTLS_A_INTERNAL_ERROR; goto out; } if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) { wpa_printf(MSG_INFO, "TLS: Peer certificate does not have a " "known issuer"); gnutls_tls_fail_event(conn, NULL, 0, NULL, "signed not found", TLS_FAIL_UNTRUSTED); err = GNUTLS_A_UNKNOWN_CA; goto out; } if (status & GNUTLS_CERT_REVOKED) { wpa_printf(MSG_INFO, "TLS: Peer certificate has been revoked"); gnutls_tls_fail_event(conn, NULL, 0, NULL, "certificate revoked", TLS_FAIL_REVOKED); err = GNUTLS_A_CERTIFICATE_REVOKED; goto out; } if (status != 0) { wpa_printf(MSG_INFO, "TLS: Unknown verification status: %d", status); err = GNUTLS_A_INTERNAL_ERROR; goto out; } if (check_ocsp(conn, session, &err)) goto out; os_get_time(&now); for (i = 0; i < num_certs; i++) { char *buf; size_t len; if (gnutls_x509_crt_init(&cert) < 0) { wpa_printf(MSG_INFO, "TLS: Certificate initialization " "failed"); err = GNUTLS_A_BAD_CERTIFICATE; goto out; } if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) { wpa_printf(MSG_INFO, "TLS: Could not parse peer " "certificate %d/%d", i + 1, num_certs); gnutls_x509_crt_deinit(cert); err = GNUTLS_A_BAD_CERTIFICATE; goto out; } gnutls_x509_crt_get_dn(cert, NULL, &len); len++; buf = os_malloc(len + 1); if (buf) { buf[0] = buf[len] = '\0'; gnutls_x509_crt_get_dn(cert, buf, &len); } wpa_printf(MSG_DEBUG, "TLS: Peer cert chain %d/%d: %s", i + 1, num_certs, buf); if (conn->global->event_cb) { struct wpabuf *cert_buf = NULL; union tls_event_data ev; #ifdef CONFIG_SHA256 u8 hash[32]; const u8 *_addr[1]; size_t _len[1]; #endif /* CONFIG_SHA256 */ os_memset(&ev, 0, sizeof(ev)); if (conn->global->cert_in_cb) { cert_buf = wpabuf_alloc_copy(certs[i].data, certs[i].size); ev.peer_cert.cert = cert_buf; } #ifdef CONFIG_SHA256 _addr[0] = certs[i].data; _len[0] = certs[i].size; if (sha256_vector(1, _addr, _len, hash) == 0) { ev.peer_cert.hash = hash; ev.peer_cert.hash_len = sizeof(hash); } #endif /* CONFIG_SHA256 */ ev.peer_cert.depth = i; ev.peer_cert.subject = buf; conn->global->event_cb(conn->global->cb_ctx, TLS_PEER_CERTIFICATE, &ev); wpabuf_free(cert_buf); } if (i == 0) { if (conn->suffix_match && !gnutls_x509_crt_check_hostname( cert, conn->suffix_match)) { wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found", conn->suffix_match); gnutls_tls_fail_event( conn, &certs[i], i, buf, "Domain suffix mismatch", TLS_FAIL_DOMAIN_SUFFIX_MISMATCH); err = GNUTLS_A_BAD_CERTIFICATE; gnutls_x509_crt_deinit(cert); os_free(buf); goto out; } #if GNUTLS_VERSION_NUMBER >= 0x030300 if (conn->domain_match && !gnutls_x509_crt_check_hostname2( cert, conn->domain_match, GNUTLS_VERIFY_DO_NOT_ALLOW_WILDCARDS)) { wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found", conn->domain_match); gnutls_tls_fail_event( conn, &certs[i], i, buf, "Domain mismatch", TLS_FAIL_DOMAIN_MISMATCH); err = GNUTLS_A_BAD_CERTIFICATE; gnutls_x509_crt_deinit(cert); os_free(buf); goto out; } #endif /* >= 3.3.0 */ /* TODO: validate altsubject_match. * For now, any such configuration is rejected in * tls_connection_set_params() */ #if GNUTLS_VERSION_NUMBER < 0x030300 /* * gnutls_certificate_verify_peers() not available, so * need to check EKU separately. */ if (!conn->global->server && !server_eku_purpose(cert)) { wpa_printf(MSG_WARNING, "GnuTLS: No server EKU"); gnutls_tls_fail_event( conn, &certs[i], i, buf, "No server EKU", TLS_FAIL_BAD_CERTIFICATE); err = GNUTLS_A_BAD_CERTIFICATE; gnutls_x509_crt_deinit(cert); os_free(buf); goto out; } #endif /* < 3.3.0 */ } if (!conn->disable_time_checks && (gnutls_x509_crt_get_expiration_time(cert) < now.sec || gnutls_x509_crt_get_activation_time(cert) > now.sec)) { wpa_printf(MSG_INFO, "TLS: Peer certificate %d/%d is " "not valid at this time", i + 1, num_certs); gnutls_tls_fail_event( conn, &certs[i], i, buf, "Certificate is not valid at this time", TLS_FAIL_EXPIRED); gnutls_x509_crt_deinit(cert); os_free(buf); err = GNUTLS_A_CERTIFICATE_EXPIRED; goto out; } os_free(buf); gnutls_x509_crt_deinit(cert); } if (conn->global->event_cb != NULL) conn->global->event_cb(conn->global->cb_ctx, TLS_CERT_CHAIN_SUCCESS, NULL); return 0; out: conn->failed++; gnutls_alert_send(session, GNUTLS_AL_FATAL, err); return GNUTLS_E_CERTIFICATE_ERROR; } static struct wpabuf * gnutls_get_appl_data(struct tls_connection *conn) { int res; struct wpabuf *ad; wpa_printf(MSG_DEBUG, "GnuTLS: Check for possible Application Data"); ad = wpabuf_alloc((wpabuf_len(conn->pull_buf) + 500) * 3); if (ad == NULL) return NULL; res = gnutls_record_recv(conn->session, wpabuf_mhead(ad), wpabuf_size(ad)); wpa_printf(MSG_DEBUG, "GnuTLS: gnutls_record_recv: %d", res); if (res < 0) { wpa_printf(MSG_DEBUG, "%s - gnutls_record_recv failed: %d " "(%s)", __func__, (int) res, gnutls_strerror(res)); wpabuf_free(ad); return NULL; } wpabuf_put(ad, res); wpa_printf(MSG_DEBUG, "GnuTLS: Received %d bytes of Application Data", res); return ad; } struct wpabuf * tls_connection_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data) { struct tls_global *global = tls_ctx; struct wpabuf *out_data; int ret; if (appl_data) *appl_data = NULL; if (in_data && wpabuf_len(in_data) > 0) { if (conn->pull_buf) { wpa_printf(MSG_DEBUG, "%s - %lu bytes remaining in " "pull_buf", __func__, (unsigned long) wpabuf_len(conn->pull_buf)); wpabuf_free(conn->pull_buf); } conn->pull_buf = wpabuf_dup(in_data); if (conn->pull_buf == NULL) return NULL; conn->pull_buf_offset = wpabuf_head(conn->pull_buf); } ret = gnutls_handshake(conn->session); if (ret < 0) { gnutls_alert_description_t alert; union tls_event_data ev; switch (ret) { case GNUTLS_E_AGAIN: if (global->server && conn->established && conn->push_buf == NULL) { /* Need to return something to trigger * completion of EAP-TLS. */ conn->push_buf = wpabuf_alloc(0); } break; case GNUTLS_E_DH_PRIME_UNACCEPTABLE: wpa_printf(MSG_DEBUG, "GnuTLS: Unacceptable DH prime"); if (conn->global->event_cb) { os_memset(&ev, 0, sizeof(ev)); ev.alert.is_local = 1; ev.alert.type = "fatal"; ev.alert.description = "insufficient security"; conn->global->event_cb(conn->global->cb_ctx, TLS_ALERT, &ev); } /* * Could send a TLS Alert to the server, but for now, * simply terminate handshake. */ conn->failed++; conn->write_alerts++; break; case GNUTLS_E_FATAL_ALERT_RECEIVED: alert = gnutls_alert_get(conn->session); wpa_printf(MSG_DEBUG, "%s - received fatal '%s' alert", __func__, gnutls_alert_get_name(alert)); conn->read_alerts++; if (conn->global->event_cb != NULL) { os_memset(&ev, 0, sizeof(ev)); ev.alert.is_local = 0; ev.alert.type = gnutls_alert_get_name(alert); ev.alert.description = ev.alert.type; conn->global->event_cb(conn->global->cb_ctx, TLS_ALERT, &ev); } /* continue */ default: wpa_printf(MSG_DEBUG, "%s - gnutls_handshake failed " "-> %s", __func__, gnutls_strerror(ret)); conn->failed++; } } else { size_t size; wpa_printf(MSG_DEBUG, "TLS: Handshake completed successfully"); #if GNUTLS_VERSION_NUMBER >= 0x03010a { char *desc; desc = gnutls_session_get_desc(conn->session); if (desc) { wpa_printf(MSG_DEBUG, "GnuTLS: %s", desc); gnutls_free(desc); } } #endif /* GnuTLS 3.1.10 or newer */ conn->established = 1; if (conn->push_buf == NULL) { /* Need to return something to get final TLS ACK. */ conn->push_buf = wpabuf_alloc(0); } gnutls_session_get_data(conn->session, NULL, &size); if (global->session_data == NULL || global->session_data_size < size) { os_free(global->session_data); global->session_data = os_malloc(size); } if (global->session_data) { global->session_data_size = size; gnutls_session_get_data(conn->session, global->session_data, &global->session_data_size); } if (conn->pull_buf && appl_data) *appl_data = gnutls_get_appl_data(conn); } out_data = conn->push_buf; conn->push_buf = NULL; return out_data; } struct wpabuf * tls_connection_server_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data) { return tls_connection_handshake(tls_ctx, conn, in_data, appl_data); } struct wpabuf * tls_connection_encrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data) { ssize_t res; struct wpabuf *buf; res = gnutls_record_send(conn->session, wpabuf_head(in_data), wpabuf_len(in_data)); if (res < 0) { wpa_printf(MSG_INFO, "%s: Encryption failed: %s", __func__, gnutls_strerror(res)); return NULL; } buf = conn->push_buf; conn->push_buf = NULL; return buf; } struct wpabuf * tls_connection_decrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data) { ssize_t res; struct wpabuf *out; if (conn->pull_buf) { wpa_printf(MSG_DEBUG, "%s - %lu bytes remaining in " "pull_buf", __func__, (unsigned long) wpabuf_len(conn->pull_buf)); wpabuf_free(conn->pull_buf); } conn->pull_buf = wpabuf_dup(in_data); if (conn->pull_buf == NULL) return NULL; conn->pull_buf_offset = wpabuf_head(conn->pull_buf); /* * Even though we try to disable TLS compression, it is possible that * this cannot be done with all TLS libraries. Add extra buffer space * to handle the possibility of the decrypted data being longer than * input data. */ out = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3); if (out == NULL) return NULL; res = gnutls_record_recv(conn->session, wpabuf_mhead(out), wpabuf_size(out)); if (res < 0) { wpa_printf(MSG_DEBUG, "%s - gnutls_record_recv failed: %d " "(%s)", __func__, (int) res, gnutls_strerror(res)); wpabuf_free(out); return NULL; } wpabuf_put(out, res); return out; } int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn) { if (conn == NULL) return 0; return gnutls_session_is_resumed(conn->session); } int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn, u8 *ciphers) { /* TODO */ return -1; } int tls_get_version(void *ssl_ctx, struct tls_connection *conn, char *buf, size_t buflen) { gnutls_protocol_t ver; ver = gnutls_protocol_get_version(conn->session); if (ver == GNUTLS_TLS1_0) os_strlcpy(buf, "TLSv1", buflen); else if (ver == GNUTLS_TLS1_1) os_strlcpy(buf, "TLSv1.1", buflen); else if (ver == GNUTLS_TLS1_2) os_strlcpy(buf, "TLSv1.2", buflen); else return -1; return 0; } int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn, char *buf, size_t buflen) { gnutls_cipher_algorithm_t cipher; gnutls_kx_algorithm_t kx; gnutls_mac_algorithm_t mac; const char *kx_str, *cipher_str, *mac_str; int res; cipher = gnutls_cipher_get(conn->session); cipher_str = gnutls_cipher_get_name(cipher); if (!cipher_str) cipher_str = ""; kx = gnutls_kx_get(conn->session); kx_str = gnutls_kx_get_name(kx); if (!kx_str) kx_str = ""; mac = gnutls_mac_get(conn->session); mac_str = gnutls_mac_get_name(mac); if (!mac_str) mac_str = ""; if (kx == GNUTLS_KX_RSA) res = os_snprintf(buf, buflen, "%s-%s", cipher_str, mac_str); else res = os_snprintf(buf, buflen, "%s-%s-%s", kx_str, cipher_str, mac_str); if (os_snprintf_error(buflen, res)) return -1; return 0; } int tls_connection_enable_workaround(void *ssl_ctx, struct tls_connection *conn) { gnutls_record_disable_padding(conn->session); return 0; } int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn, int ext_type, const u8 *data, size_t data_len) { /* TODO */ return -1; } int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn) { if (conn == NULL) return -1; return conn->failed; } int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn) { if (conn == NULL) return -1; return conn->read_alerts; } int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn) { if (conn == NULL) return -1; return conn->write_alerts; } int tls_connection_set_session_ticket_cb(void *tls_ctx, struct tls_connection *conn, tls_session_ticket_cb cb, void *ctx) { return -1; } int tls_get_library_version(char *buf, size_t buf_len) { return os_snprintf(buf, buf_len, "GnuTLS build=%s run=%s", GNUTLS_VERSION, gnutls_check_version(NULL)); } void tls_connection_set_success_data(struct tls_connection *conn, struct wpabuf *data) { } void tls_connection_set_success_data_resumed(struct tls_connection *conn) { } const struct wpabuf * tls_connection_get_success_data(struct tls_connection *conn) { return NULL; } void tls_connection_remove_session(struct tls_connection *conn) { }
coolshou/hostap
src/crypto/tls_internal.c
<gh_stars>1-10 /* * TLS interface functions and an internal TLS implementation * Copyright (c) 2004-2011, <NAME> <<EMAIL>> * * This software may be distributed under the terms of the BSD license. * See README for more details. * * This file interface functions for hostapd/wpa_supplicant to use the * integrated TLSv1 implementation. */ #include "includes.h" #include "common.h" #include "tls.h" #include "tls/tlsv1_client.h" #include "tls/tlsv1_server.h" static int tls_ref_count = 0; struct tls_global { int server; struct tlsv1_credentials *server_cred; int check_crl; void (*event_cb)(void *ctx, enum tls_event ev, union tls_event_data *data); void *cb_ctx; int cert_in_cb; }; struct tls_connection { struct tlsv1_client *client; struct tlsv1_server *server; struct tls_global *global; }; void * tls_init(const struct tls_config *conf) { struct tls_global *global; if (tls_ref_count == 0) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (tlsv1_client_global_init()) return NULL; #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (tlsv1_server_global_init()) return NULL; #endif /* CONFIG_TLS_INTERNAL_SERVER */ } tls_ref_count++; global = os_zalloc(sizeof(*global)); if (global == NULL) return NULL; if (conf) { global->event_cb = conf->event_cb; global->cb_ctx = conf->cb_ctx; global->cert_in_cb = conf->cert_in_cb; } return global; } void tls_deinit(void *ssl_ctx) { struct tls_global *global = ssl_ctx; tls_ref_count--; if (tls_ref_count == 0) { #ifdef CONFIG_TLS_INTERNAL_CLIENT tlsv1_client_global_deinit(); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER tlsv1_server_global_deinit(); #endif /* CONFIG_TLS_INTERNAL_SERVER */ } #ifdef CONFIG_TLS_INTERNAL_SERVER tlsv1_cred_free(global->server_cred); #endif /* CONFIG_TLS_INTERNAL_SERVER */ os_free(global); } int tls_get_errors(void *tls_ctx) { return 0; } struct tls_connection * tls_connection_init(void *tls_ctx) { struct tls_connection *conn; struct tls_global *global = tls_ctx; conn = os_zalloc(sizeof(*conn)); if (conn == NULL) return NULL; conn->global = global; #ifdef CONFIG_TLS_INTERNAL_CLIENT if (!global->server) { conn->client = tlsv1_client_init(); if (conn->client == NULL) { os_free(conn); return NULL; } tlsv1_client_set_cb(conn->client, global->event_cb, global->cb_ctx, global->cert_in_cb); } #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (global->server) { conn->server = tlsv1_server_init(global->server_cred); if (conn->server == NULL) { os_free(conn); return NULL; } } #endif /* CONFIG_TLS_INTERNAL_SERVER */ return conn; } #ifdef CONFIG_TESTING_OPTIONS #ifdef CONFIG_TLS_INTERNAL_SERVER void tls_connection_set_test_flags(struct tls_connection *conn, u32 flags) { if (conn->server) tlsv1_server_set_test_flags(conn->server, flags); } #endif /* CONFIG_TLS_INTERNAL_SERVER */ #endif /* CONFIG_TESTING_OPTIONS */ void tls_connection_set_log_cb(struct tls_connection *conn, void (*log_cb)(void *ctx, const char *msg), void *ctx) { #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) tlsv1_server_set_log_cb(conn->server, log_cb, ctx); #endif /* CONFIG_TLS_INTERNAL_SERVER */ } void tls_connection_deinit(void *tls_ctx, struct tls_connection *conn) { if (conn == NULL) return; #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) tlsv1_client_deinit(conn->client); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) tlsv1_server_deinit(conn->server); #endif /* CONFIG_TLS_INTERNAL_SERVER */ os_free(conn); } int tls_connection_established(void *tls_ctx, struct tls_connection *conn) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) return tlsv1_client_established(conn->client); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) return tlsv1_server_established(conn->server); #endif /* CONFIG_TLS_INTERNAL_SERVER */ return 0; } char * tls_connection_peer_serial_num(void *tls_ctx, struct tls_connection *conn) { /* TODO */ return NULL; } int tls_connection_shutdown(void *tls_ctx, struct tls_connection *conn) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) return tlsv1_client_shutdown(conn->client); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) return tlsv1_server_shutdown(conn->server); #endif /* CONFIG_TLS_INTERNAL_SERVER */ return -1; } int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn, const struct tls_connection_params *params) { #ifdef CONFIG_TLS_INTERNAL_CLIENT struct tlsv1_credentials *cred; if (conn->client == NULL) return -1; if (params->flags & TLS_CONN_EXT_CERT_CHECK) { wpa_printf(MSG_INFO, "TLS: tls_ext_cert_check=1 not supported"); return -1; } cred = tlsv1_cred_alloc(); if (cred == NULL) return -1; if (params->subject_match) { wpa_printf(MSG_INFO, "TLS: subject_match not supported"); tlsv1_cred_free(cred); return -1; } if (params->altsubject_match) { wpa_printf(MSG_INFO, "TLS: altsubject_match not supported"); tlsv1_cred_free(cred); return -1; } if (params->suffix_match) { wpa_printf(MSG_INFO, "TLS: suffix_match not supported"); tlsv1_cred_free(cred); return -1; } if (params->domain_match) { wpa_printf(MSG_INFO, "TLS: domain_match not supported"); tlsv1_cred_free(cred); return -1; } if (params->openssl_ciphers) { wpa_printf(MSG_INFO, "TLS: openssl_ciphers not supported"); tlsv1_cred_free(cred); return -1; } if (tlsv1_set_ca_cert(cred, params->ca_cert, params->ca_cert_blob, params->ca_cert_blob_len, params->ca_path)) { wpa_printf(MSG_INFO, "TLS: Failed to configure trusted CA " "certificates"); tlsv1_cred_free(cred); return -1; } if (tlsv1_set_cert(cred, params->client_cert, params->client_cert_blob, params->client_cert_blob_len)) { wpa_printf(MSG_INFO, "TLS: Failed to configure client " "certificate"); tlsv1_cred_free(cred); return -1; } if (tlsv1_set_private_key(cred, params->private_key, params->private_key_passwd, params->private_key_blob, params->private_key_blob_len)) { wpa_printf(MSG_INFO, "TLS: Failed to load private key"); tlsv1_cred_free(cred); return -1; } if (tlsv1_set_dhparams(cred, params->dh_file, params->dh_blob, params->dh_blob_len)) { wpa_printf(MSG_INFO, "TLS: Failed to load DH parameters"); tlsv1_cred_free(cred); return -1; } if (tlsv1_client_set_cred(conn->client, cred) < 0) { tlsv1_cred_free(cred); return -1; } tlsv1_client_set_flags(conn->client, params->flags); return 0; #else /* CONFIG_TLS_INTERNAL_CLIENT */ return -1; #endif /* CONFIG_TLS_INTERNAL_CLIENT */ } int tls_global_set_params(void *tls_ctx, const struct tls_connection_params *params) { #ifdef CONFIG_TLS_INTERNAL_SERVER struct tls_global *global = tls_ctx; struct tlsv1_credentials *cred; /* Currently, global parameters are only set when running in server * mode. */ global->server = 1; tlsv1_cred_free(global->server_cred); global->server_cred = cred = tlsv1_cred_alloc(); if (cred == NULL) return -1; if (tlsv1_set_ca_cert(cred, params->ca_cert, params->ca_cert_blob, params->ca_cert_blob_len, params->ca_path)) { wpa_printf(MSG_INFO, "TLS: Failed to configure trusted CA " "certificates"); return -1; } if (tlsv1_set_cert(cred, params->client_cert, params->client_cert_blob, params->client_cert_blob_len)) { wpa_printf(MSG_INFO, "TLS: Failed to configure server " "certificate"); return -1; } if (tlsv1_set_private_key(cred, params->private_key, params->private_key_passwd, params->private_key_blob, params->private_key_blob_len)) { wpa_printf(MSG_INFO, "TLS: Failed to load private key"); return -1; } if (tlsv1_set_dhparams(cred, params->dh_file, params->dh_blob, params->dh_blob_len)) { wpa_printf(MSG_INFO, "TLS: Failed to load DH parameters"); return -1; } if (params->ocsp_stapling_response) cred->ocsp_stapling_response = os_strdup(params->ocsp_stapling_response); if (params->ocsp_stapling_response_multi) cred->ocsp_stapling_response_multi = os_strdup(params->ocsp_stapling_response_multi); return 0; #else /* CONFIG_TLS_INTERNAL_SERVER */ return -1; #endif /* CONFIG_TLS_INTERNAL_SERVER */ } int tls_global_set_verify(void *tls_ctx, int check_crl) { struct tls_global *global = tls_ctx; global->check_crl = check_crl; return 0; } int tls_connection_set_verify(void *tls_ctx, struct tls_connection *conn, int verify_peer, unsigned int flags, const u8 *session_ctx, size_t session_ctx_len) { #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) return tlsv1_server_set_verify(conn->server, verify_peer); #endif /* CONFIG_TLS_INTERNAL_SERVER */ return -1; } int tls_connection_get_random(void *tls_ctx, struct tls_connection *conn, struct tls_random *data) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) return tlsv1_client_get_random(conn->client, data); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) return tlsv1_server_get_random(conn->server, data); #endif /* CONFIG_TLS_INTERNAL_SERVER */ return -1; } static int tls_get_keyblock_size(struct tls_connection *conn) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) return tlsv1_client_get_keyblock_size(conn->client); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) return tlsv1_server_get_keyblock_size(conn->server); #endif /* CONFIG_TLS_INTERNAL_SERVER */ return -1; } static int tls_connection_prf(void *tls_ctx, struct tls_connection *conn, const char *label, int server_random_first, int skip_keyblock, u8 *out, size_t out_len) { int ret = -1, skip = 0; u8 *tmp_out = NULL; u8 *_out = out; if (skip_keyblock) { skip = tls_get_keyblock_size(conn); if (skip < 0) return -1; tmp_out = os_malloc(skip + out_len); if (!tmp_out) return -1; _out = tmp_out; } #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) { ret = tlsv1_client_prf(conn->client, label, server_random_first, _out, skip + out_len); } #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) { ret = tlsv1_server_prf(conn->server, label, server_random_first, _out, skip + out_len); } #endif /* CONFIG_TLS_INTERNAL_SERVER */ if (ret == 0 && skip_keyblock) os_memcpy(out, _out + skip, out_len); bin_clear_free(tmp_out, skip); return ret; } int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn, const char *label, u8 *out, size_t out_len) { return tls_connection_prf(tls_ctx, conn, label, 0, 0, out, out_len); } int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn, u8 *out, size_t out_len) { return tls_connection_prf(tls_ctx, conn, "key expansion", 1, 1, out, out_len); } struct wpabuf * tls_connection_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data) { return tls_connection_handshake2(tls_ctx, conn, in_data, appl_data, NULL); } struct wpabuf * tls_connection_handshake2(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data, int *need_more_data) { #ifdef CONFIG_TLS_INTERNAL_CLIENT u8 *res, *ad; size_t res_len, ad_len; struct wpabuf *out; if (conn->client == NULL) return NULL; ad = NULL; res = tlsv1_client_handshake(conn->client, in_data ? wpabuf_head(in_data) : NULL, in_data ? wpabuf_len(in_data) : 0, &res_len, &ad, &ad_len, need_more_data); if (res == NULL) return NULL; out = wpabuf_alloc_ext_data(res, res_len); if (out == NULL) { os_free(res); os_free(ad); return NULL; } if (appl_data) { if (ad) { *appl_data = wpabuf_alloc_ext_data(ad, ad_len); if (*appl_data == NULL) os_free(ad); } else *appl_data = NULL; } else os_free(ad); return out; #else /* CONFIG_TLS_INTERNAL_CLIENT */ return NULL; #endif /* CONFIG_TLS_INTERNAL_CLIENT */ } struct wpabuf * tls_connection_server_handshake(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, struct wpabuf **appl_data) { #ifdef CONFIG_TLS_INTERNAL_SERVER u8 *res; size_t res_len; struct wpabuf *out; if (conn->server == NULL) return NULL; if (appl_data) *appl_data = NULL; res = tlsv1_server_handshake(conn->server, wpabuf_head(in_data), wpabuf_len(in_data), &res_len); if (res == NULL && tlsv1_server_established(conn->server)) return wpabuf_alloc(0); if (res == NULL) return NULL; out = wpabuf_alloc_ext_data(res, res_len); if (out == NULL) { os_free(res); return NULL; } return out; #else /* CONFIG_TLS_INTERNAL_SERVER */ return NULL; #endif /* CONFIG_TLS_INTERNAL_SERVER */ } struct wpabuf * tls_connection_encrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) { struct wpabuf *buf; int res; buf = wpabuf_alloc(wpabuf_len(in_data) + 300); if (buf == NULL) return NULL; res = tlsv1_client_encrypt(conn->client, wpabuf_head(in_data), wpabuf_len(in_data), wpabuf_mhead(buf), wpabuf_size(buf)); if (res < 0) { wpabuf_free(buf); return NULL; } wpabuf_put(buf, res); return buf; } #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) { struct wpabuf *buf; int res; buf = wpabuf_alloc(wpabuf_len(in_data) + 300); if (buf == NULL) return NULL; res = tlsv1_server_encrypt(conn->server, wpabuf_head(in_data), wpabuf_len(in_data), wpabuf_mhead(buf), wpabuf_size(buf)); if (res < 0) { wpabuf_free(buf); return NULL; } wpabuf_put(buf, res); return buf; } #endif /* CONFIG_TLS_INTERNAL_SERVER */ return NULL; } struct wpabuf * tls_connection_decrypt(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data) { return tls_connection_decrypt2(tls_ctx, conn, in_data, NULL); } struct wpabuf * tls_connection_decrypt2(void *tls_ctx, struct tls_connection *conn, const struct wpabuf *in_data, int *need_more_data) { if (need_more_data) *need_more_data = 0; #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) { return tlsv1_client_decrypt(conn->client, wpabuf_head(in_data), wpabuf_len(in_data), need_more_data); } #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) { struct wpabuf *buf; int res; buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3); if (buf == NULL) return NULL; res = tlsv1_server_decrypt(conn->server, wpabuf_head(in_data), wpabuf_len(in_data), wpabuf_mhead(buf), wpabuf_size(buf)); if (res < 0) { wpabuf_free(buf); return NULL; } wpabuf_put(buf, res); return buf; } #endif /* CONFIG_TLS_INTERNAL_SERVER */ return NULL; } int tls_connection_resumed(void *tls_ctx, struct tls_connection *conn) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) return tlsv1_client_resumed(conn->client); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) return tlsv1_server_resumed(conn->server); #endif /* CONFIG_TLS_INTERNAL_SERVER */ return -1; } int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn, u8 *ciphers) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) return tlsv1_client_set_cipher_list(conn->client, ciphers); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) return tlsv1_server_set_cipher_list(conn->server, ciphers); #endif /* CONFIG_TLS_INTERNAL_SERVER */ return -1; } int tls_get_version(void *ssl_ctx, struct tls_connection *conn, char *buf, size_t buflen) { if (conn == NULL) return -1; #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) return tlsv1_client_get_version(conn->client, buf, buflen); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ return -1; } int tls_get_cipher(void *tls_ctx, struct tls_connection *conn, char *buf, size_t buflen) { if (conn == NULL) return -1; #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) return tlsv1_client_get_cipher(conn->client, buf, buflen); #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) return tlsv1_server_get_cipher(conn->server, buf, buflen); #endif /* CONFIG_TLS_INTERNAL_SERVER */ return -1; } int tls_connection_enable_workaround(void *tls_ctx, struct tls_connection *conn) { return -1; } int tls_connection_client_hello_ext(void *tls_ctx, struct tls_connection *conn, int ext_type, const u8 *data, size_t data_len) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) { return tlsv1_client_hello_ext(conn->client, ext_type, data, data_len); } #endif /* CONFIG_TLS_INTERNAL_CLIENT */ return -1; } int tls_connection_get_failed(void *tls_ctx, struct tls_connection *conn) { return 0; } int tls_connection_get_read_alerts(void *tls_ctx, struct tls_connection *conn) { return 0; } int tls_connection_get_write_alerts(void *tls_ctx, struct tls_connection *conn) { return 0; } int tls_connection_set_session_ticket_cb(void *tls_ctx, struct tls_connection *conn, tls_session_ticket_cb cb, void *ctx) { #ifdef CONFIG_TLS_INTERNAL_CLIENT if (conn->client) { tlsv1_client_set_session_ticket_cb(conn->client, cb, ctx); return 0; } #endif /* CONFIG_TLS_INTERNAL_CLIENT */ #ifdef CONFIG_TLS_INTERNAL_SERVER if (conn->server) { tlsv1_server_set_session_ticket_cb(conn->server, cb, ctx); return 0; } #endif /* CONFIG_TLS_INTERNAL_SERVER */ return -1; } int tls_get_library_version(char *buf, size_t buf_len) { return os_snprintf(buf, buf_len, "internal"); } void tls_connection_set_success_data(struct tls_connection *conn, struct wpabuf *data) { } void tls_connection_set_success_data_resumed(struct tls_connection *conn) { } const struct wpabuf * tls_connection_get_success_data(struct tls_connection *conn) { return NULL; } void tls_connection_remove_session(struct tls_connection *conn) { }
ibarisic05/CHRTextFieldFormatter
CHRTextFieldFormatter/CHRUSPhoneNumberMask.h
// // CHRUSPhoneNumberMask.h // CHRTextFieldFormatterTest // // Created by <NAME> on 30/09/2016. // Copyright © 2016 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "CHRTextMask.h" @interface CHRUSPhoneNumberMask : NSObject <CHRTextMask> /** Specifies not editable phone number prefix. Phone number prefix will be separated by a whitespace from the actual phone number. */ @property (nonatomic, copy) NSString *prefix; @end
ibarisic05/CHRTextFieldFormatter
Example/Pods/Headers/Public/CHRTextFieldFormatter/CHRTextMask.h
// // CHRTextMask.h // // Created by <NAME> on 12/05/15. // Copyright (c) 2015 e-legion. All rights reserved. // #import <Foundation/Foundation.h> @protocol CHRTextMask <NSObject, NSCopying> - (BOOL)shouldChangeText:(NSString *)text withReplacementString:(NSString *)string inRange:(NSRange)range; - (NSString *)filteredStringFromString:(NSString *)string cursorPosition:(NSUInteger *)cursorPosition; - (NSString *)formattedStringFromString:(NSString *)string cursorPosition:(NSUInteger *)cursorPosition; @end
ibarisic05/CHRTextFieldFormatter
Example/Pods/Headers/Public/CHRTextFieldFormatter/CHRTextFieldFormatter.h
// // CHRTextFieldFormatter.h // // Created by <NAME> on 12/05/15. // Copyright (c) 2015 e-legion. All rights reserved. // #import <UIKit/UIKit.h> #import "CHRTextMask.h" NS_ASSUME_NONNULL_BEGIN /** UITextField formatter that applies a mask to the input text. @see http://stackoverflow.com/a/19161529/318790 */ @interface CHRTextFieldFormatter : NSFormatter @property (nonatomic, copy, readonly) id<CHRTextMask> mask; /** Initializes the formatter for UITextField with specified mask. Retain's stong reference to passed UITextField and adds target/action for EditingChanged event. */ - (instancetype)initWithTextField:(nullable UITextField *)textField mask:(nullable id<CHRTextMask>)mask NS_DESIGNATED_INITIALIZER; /** Proxy method to be called from the UITextField's delegate callback. @param textField Must be the same text field which was passed as initializer argument. */ - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; - (NSString *)maskedStringFromString:(NSString *)string; - (NSString *)unmaskedStringFromString:(NSString *)string; @end NS_ASSUME_NONNULL_END
ibarisic05/CHRTextFieldFormatter
CHRTextFieldFormatter/CHRBusinessEINNumberMask.h
<filename>CHRTextFieldFormatter/CHRBusinessEINNumberMask.h // // CHRBusinessEINNumberMask.h // CHRTextFieldFormatterTest // // Created by <NAME> on 30/09/2016. // Copyright © 2016 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "CHRTextMask.h" NS_ASSUME_NONNULL_BEGIN @interface CHRBusinessEINNumberMask : NSObject <CHRTextMask> @end NS_ASSUME_NONNULL_END
Pako2/esp-rfid
src/rfid125kHz.h
/* RFID reader. Based on the "rfid_reader" library (https://github.com/travisfarmer) from <NAME>. Author: <NAME> Hardware: RDM6300 or RF125-PS Uses 125KHz RFID tags. */ #ifndef rfid125kHz_h #define rfid125kHz_h #include "Arduino.h" class RFID_Read { public: void rfidSerial(char x); bool Available(); String GetHexID(); String GetDecID(); private: char *ulltostr(unsigned long long value, char *ptr, int base); void parse(); uint8_t char2int(char c); uint8_t get_checksum(unsigned long long data); static const char asciiNum_diff = 48; static const char asciiUpp_diff = 7; bool data_available = false; unsigned long long new_ID = 0ULL; unsigned long long last_ID = 0ULL; unsigned long LastRFID = 0UL; char msg[15]; uint8_t msgLen; byte ix = 0; byte StartByte = 0x02; byte EndByte = 0x03; }; #endif
vladcc/tme
tme/tme.c
<reponame>vladcc/tme<filename>tme/tme.c<gh_stars>0 /* Executable name : tme.exe * Version : v1.0 * Created Date : 14.04.2016 * Last Update : 15.04.2016 * Author : <NAME> * Description : A countdown timer program. It exists because I always forget my coffe on the stove. * The time is given in minutes as decimal numbers (e.g. 2.3 = 2 minutes and 18 seconds). * A timer is set with the line * tme <time in minutes> "Your message" * The message needs to be enclosed in quotes if it contains more than one word. * By default the message is displayed in a message box and repeated vi the Windows speech syntesizer until * the message box is closed. /m after "Your message" will disable the voice, and only show you the message box. * /list /l -list and -l can be used to list active timers. * /stop /s -stop -s can be used to stop an active timer identified by it's number as listed by the list option. * In the function descriptions all calls to the standard C library are omitted for brevity. * * Built with : TDM GCC (tdm64-1) version 5.1.0 * IDE used : Geany 1.26 * Build line : gcc -Wall -o "%e.exe" "%f" -s -m32 -lole32 -lWbemuuid -lOleAut32 -municode */ #include "tme.h" //------------------------------------------------------------------------- // main starts here //------------------------------------------------------------------------- int _tmain(int argc, _TCHAR * argv[]) { /* Name : _tmain() * Updated : 15.04.2016 * In : The cmd line arguments. * Returns : An int to the OS. * Modifies : Nothing. * Calls : Check_Arguments(), Set_Timer(), Start_Timer(), List_Timers(), Stop_Timer(), Print_Help(), Print_Options() * Description : The main function is used to direct program flow depending on the cmd line arguments. */ bool msgonly = false; bool printable_msg = false; int timer_number, i; DWORD ttk_pid = 0; switch (Check_Arguments(argc, argv)) { case SET_MSG_ONLY: /* If the message only option is set toggle msgonly * and fall through to the SET procedure. */ msgonly = true; case SET: // Go through message and see if contains any printable characters. for (i = 0; '\0' != argv[2][i]; ++i) if (_istgraph(argv[2][i])) { printable_msg = true; break; } // If it doesn't show error and exit. if (!printable_msg) { _putts(_T("Not a valid message.")); return -1; } // Set the timer in a new background process. Set_Timer(argc, argv, msgonly); break; case START: /* 4th character of the 3rd argument will be either the 'm' * in /setm, or the '\0' in /set. */ if ('m' == argv[3][4]) Start_Timer(_tstof(argv[1]), argv[2], false); else Start_Timer(_tstof(argv[1]), argv[2], true); break; case LIST: // List active timers if availabe. List_Timers(argv, false, 0, NULL); break; case STOP: // Stop a timer. if ( (timer_number = _ttoi(argv[2])) <= 0 ) _tprintf(_T("Second argument has to be a valid timer number.\n")); else { List_Timers(argv, true, timer_number, &ttk_pid); Stop_Timer(ttk_pid, timer_number); } break; case ARG_ERR: _tprintf(_T("Invalid arguments.\n")); break; case HELP: Print_Help(argv); break; case OPTIONS: Print_Options(argv); break; default: break; } return 0; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- char Check_Arguments(int argc, _TCHAR * argv[]) { /* Name : Check_Arguments() * Updated : 15.04.2016 * In : The cmd line arguments. * Returns : A numerical value stored in a char. * Modifies : Nothing. * Calls : Nothing. * Description : Examines the cmd line arguments and returns a control code to _tmain(). */ // Print help if no additional arguments are present. if (1 == argc) return HELP; /* If we have 2 additional arguments, and the first one is a digit * set the timer. */ if ( (3 == argc) && (('0' <= argv[1][0]) && ('9' >= argv[1][0])) ) return SET; /* If we have 3 additional arguments and a time, check for the * no message flag. */ if ( (4 == argc) && (('0' <= argv[1][0]) && ('9' >= argv[1][0])) && (0 == _tcscmp(ARG_MSG_ONLY, argv[3])) ) return SET_MSG_ONLY; /* If we have 3 additional arguments, and the last one is a /set * option, start the timer. */ if ( (4 == argc) && ((0 == _tcscmp(ARG_SET, argv[3])) || (0 == _tcscmp(ARG_SET_MSG_ONLY, argv[3]))) ) return START; /* If the first character of the first additional argument is a * '/' or a '-', check what's the argument. */ if ( (SLASH == argv[1][0]) || (DASH == argv[1][0]) ) { if ( 0 == _tcscmp(ARG_OPTIONS, argv[1]) ) return OPTIONS; int i; for (i = 0; i < LIST_ARGS_COUNT; ++i) { if ( 0 == _tcscmp(argv[1], ARGS_LIST[i]) ) return LIST; if ( 0 == _tcscmp(argv[1], ARGS_STOP[i]) ) return STOP; } } // If none of the above, return argument error code. return ARG_ERR; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- void Set_Timer(int argc, _TCHAR * argv[], bool msgonly) { /* Name : Set_Timer() * Updated : 15.04.2016 * In : The cmd line arguments, and a boolean value indicating if the message will be spoken or not. * Returns : Nothing. * Modifies : Nothing. * Calls : Create_Timer() * Description : Creates the command line for the new process(which will work as the actual countdown timer) * and prints a message for the user. */ int i, arglen, minutes; float time, seconds; time = _tstof(argv[1]); // Check if first argument is a valid time. if (time <= 0 || time > (float)MAX_MINUTES) { _tprintf(TIME_ERROR_MSG, (int)MAX_MINUTES); return; } // Create the command line string for the new process: // Find out the lengths of all arguments. for (i = 0, arglen = 0; i < argc; ++i) arglen += _tcslen(argv[i]); /* We add the number of arguments + 2 + 4 in order to make sure * that we have space for the spaces(' '), quotes('"'), the /set or /setm option, * and the '\0' at the end, when we form the command line for the new process. */ arglen += argc + 2 + 4; TCHAR cmdline[arglen]; // Concatenate the new command line string. _tcscpy(cmdline, argv[0]); // Executable name _tcscat(cmdline, _T(" ")); _tcscat(cmdline, argv[1]); // Time in minutes _tcscat(cmdline, _T(" ")); _tcscat(cmdline, _T("\"")); _tcscat(cmdline, argv[2]); // Message _tcscat(cmdline, _T("\"")); _tcscat(cmdline, _T(" ")); // Add appropriate /set flag. if (msgonly) _tcscat(cmdline, ARG_SET_MSG_ONLY); else _tcscat(cmdline, ARG_SET); // Create the new process. if ( Create_Timer(cmdline) ) { // Calculate time values. time *= 60; minutes = (int)time / 60; seconds = (minutes > 0) ? (time - minutes * 60) : time; // Print "timer is set for..." message. _tprintf(_T("Timer is set for %d %s and %.*f %s from now.\n"), minutes, _T("min"), (seconds - (float)((int)seconds) >= 0.05) ? 1 : 0, seconds, _T("sec")); _tprintf(_T("Timer message is \"%s\".\n"), argv[2]); } else // Print error if Create_Timer() failed. _tprintf(_T("Timer could not be started.\n")); return; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- bool Create_Timer(TCHAR cmdline[]) { /* Name : Create_Timer() * Updated : 15.04.2016 * In : The command line for the new process. * Returns : Success of failure. * Modifies : Nothing. * Calls : WIN API ZeroMemory(), CreateProcess(), CloseHandle() * Description : Creates a new process, passing it the command line composed in Set_Timer() * The new process will be the actual countdown timer and will work indepedently in the background. */ STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); // Start the child process. if( !CreateProcess( NULL, // No module name (use command line) cmdline, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW | DETACHED_PROCESS, // Creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { _tprintf(_T("New process could not be created.\n")); return false; } // Close process and thread handles. CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return true; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- void Start_Timer(float time, TCHAR msg[], bool include_voice) { /* Name : Start_Timer() * Updated : 15.04.2016 * In : A float value of the time in minutes, a pointer to the message string, and a boolean value * indicating if the message will be spoken or not. * Returns : Nothing. * Modifies : Nothing. * Calls : WIN API Sleep(), CoInitialize(), MessageBox(), CoCreateInstance(), CreateThread(), CloseHandle(), CoUninitialize() * Description : Checks if the time value is valid, converts it to milliseconds and sleeps for that long. After that it checks * if the timer message should be spoken, and if not it only displays a message box. If it is supposed to be * spoken it initializes a Windows speech synthesizer COM object, creates a separate thread for the message box(since * MessageBox() blocks the thread it runs on), and repeats the message until the message box is closed. */ /* Another time check in case someone passes * /set or /setm manually. */ if (time <= 0 || time > (float)MAX_MINUTES) { _tprintf(TIME_ERROR_MSG, (int)MAX_MINUTES); return; } // time * 60 * 1000 gives us the sleep time in seconds. Sleep(time * 60 * 1000); if (!include_voice) { // Display only a message box if the /m option is used. MessageBox(NULL, msg, TITLE, MB_ICONINFORMATION | MB_SYSTEMMODAL); return; } HRESULT hr = 0; // Initialize a Windows voice synthesizer COM object. hr = CoInitialize(NULL); if (FAILED(hr)) { MessageBox(NULL, _T("Speech COM initialization failed.\n"), TITLE, MB_ICONERROR | MB_SYSTEMMODAL); CoUninitialize(); return; } struct ISpVoice* pVoice = NULL; hr = CoCreateInstance(&CLSID_SpVoice, NULL, CLSCTX_ALL, &IID_ISpVoice, (void**)&pVoice); if (FAILED(hr)) { MessageBox(NULL, _T("Speech COM CoCreateInstance failed.\n"), TITLE, MB_ICONERROR | MB_SYSTEMMODAL); CoUninitialize(); return; } /* Covert msg to wide string. * Add for ANSI only int requiredSize = mbstowcs(NULL, msg, 0); WCHAR wmsg[requiredSize + 1]; mbstowcs(wmsg, msg, requiredSize + 1); */ // Create thread struct. THREAD_MSG thrdmsg = { msg, true }; HANDLE thread; // Run the message box thread. thread = CreateThread(NULL, 0, Show_Message, &thrdmsg, 0, NULL); // Loop while the message box is on the screen. while (thrdmsg.thread_running) { pVoice->lpVtbl->Speak(pVoice, msg, 0, NULL); Sleep(SPEAK_PAUSE); } CloseHandle(thread); pVoice->lpVtbl->Release(pVoice); /* MSDN documentation says that even if CoInitalize fails, * CoUnitialize must be called. */ CoUninitialize(); return; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- DWORD WINAPI Show_Message(LPVOID lpParam) { /* Name : Show_Message() * Updated : 15.04.2016 * In : A void pointer later converted to a pointer to a THREAD_MSG struct. * Returns : 32 bit unsigned int. * Modifies : The thread_running member of the THREAD_MSG struct. * Calls : WIN API MessageBox() * Description : Shows the timer message in a message box and notifies the voice loop in Start_Timer() * when the message box is closed. */ THREAD_MSG *tmsg = (THREAD_MSG*)lpParam; // Show the message box. MessageBox(NULL, tmsg->msg, TITLE, MB_ICONINFORMATION | MB_SYSTEMMODAL); /* After MessageBox returns, toggle thread_running * in order to exit the loop in Start_Timer(). */ tmsg->thread_running = false; return 0; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- bool List_Timers(_TCHAR * argv[], bool kill, char timer_to_kill, DWORD * ttk_pid) { /* Name : List_Timers() * Updated : 15.04.2016 * In : The cmd line arguments, a boolean value indicating if the functions will be used to stop a timer, * a char holding the ID of the timer to be stopped, and a pointer to it's PID. * Returns : Success or failure. * Modifies : The value at &ttk_pid if the kill option is set. * Calls : Get_Image_Name(), Print_Timer_Info() * WIN API GetCurrentProcessId(), CoInitializeEx(), CoInitializeSecurity(), CoCreateInstance(), CoUninitialize() * Description : Enumerates the current running timers, and either calls Print_Timer_Info() or puts the PID of the timer * to be killed at &ttk_pid. */ HRESULT hr = 0; IWbemLocator *WbemLocator = NULL; IWbemServices *WbemServices = NULL; IEnumWbemClassObject *EnumWbem = NULL; TCHAR image_name[MAX_PATH]; DWORD current_pid; bool are_there_timers = false; // Get image name. if( !Get_Image_Name(image_name) ) { _tprintf(_T("Error: Could not get image name.\n")); return false; } current_pid = GetCurrentProcessId(); // Initializate the Windows security. hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hr)) { _tprintf(_T("CoInitializeEx failed.\n")); CoUninitialize(); return false; } hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); if (FAILED(hr)) { _tprintf(_T("CoInitializeSecurity failed.\n")); CoUninitialize(); return false; } hr = CoCreateInstance(&CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, &IID_IWbemLocator, (LPVOID *) &WbemLocator); if (FAILED(hr)) { _tprintf(_T("CoCreateInstance failed.\n")); CoUninitialize(); return false; } // Connect to the WMI. hr = WbemLocator->lpVtbl->ConnectServer(WbemLocator, _T("ROOT\\CIMV2"), NULL, NULL, NULL, 0, NULL, NULL, &WbemServices); if (FAILED(hr)) { _tprintf(_T("Could not connect to server.\n")); WbemLocator->lpVtbl->Release(WbemLocator); CoUninitialize(); return false; } // Run the WQL Query. hr = WbemServices->lpVtbl->ExecQuery(WbemServices, _T("WQL"), _T("SELECT ProcessId, Name, CommandLine FROM Win32_Process"), WBEM_FLAG_FORWARD_ONLY, NULL, &EnumWbem); if (FAILED(hr)) { _tprintf(_T("Could not execute query.\n")); WbemServices->lpVtbl->Release(WbemServices); WbemLocator->lpVtbl->Release(WbemLocator); CoUninitialize(); return false; } // Iterate over the enumerator. if (EnumWbem != NULL) { IWbemClassObject *result = NULL; ULONG returnedCount = 0; int timer_number = 0; while((hr = EnumWbem->lpVtbl->Next(EnumWbem, WBEM_INFINITE, 1, &result, &returnedCount)) == S_OK) { VARIANT ProcessId; VARIANT CommandLine; VARIANT Name; // Access the properties. hr = result->lpVtbl->Get(result, _T("ProcessId"), 0, &ProcessId, 0, 0); hr = result->lpVtbl->Get(result, _T("CommandLine"), 0, &CommandLine, 0, 0); hr = result->lpVtbl->Get(result, _T("Name"), 0, &Name, 0, 0); if ( !(CommandLine.vt == VT_NULL) && (0 == _tcscmp(Name.bstrVal, image_name)) && (ProcessId.uintVal != current_pid) ) { ++timer_number; if (false == kill) { Print_Timer_Info(CommandLine.bstrVal, timer_number, ProcessId.uintVal); are_there_timers = true; } else { are_there_timers = true; if (timer_number == timer_to_kill) *ttk_pid = ProcessId.uintVal; } } result->lpVtbl->Release(result); } } if (!are_there_timers) _tprintf(_T("No timers available.\n")); // Release the resources. EnumWbem->lpVtbl->Release(EnumWbem); WbemServices->lpVtbl->Release(WbemServices); WbemLocator->lpVtbl->Release(WbemLocator); CoUninitialize(); return true; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- void Print_Timer_Info(BSTR timer_cmd_line, int timer_number, DWORD pid) { /* Name : Print_Timer_Info() * Updated : 15.04.2016 * In : The cmd line of the enumerated from List_Timers() timer, it's number, and it's pid. * Returns : Nothing. * Modifies : Nothing. * Calls : Calculate_Time_Left() * Description : Examines the command line arguments of the enumerated from List_Timers() timer * and prints a frame buffer containing timer information. */ int i, j, k, l, set_minutes, set_seconds, left_minutes, left_seconds; float time_in_min, calc_time; bool msg_speak = true; TCHAR szSetTimeInMinutes[10] = {_T(' ')}; // Significant time value can be at most 9 characters. TCHAR szMessage[256] = {_T(' ')}; // Cmd message. TCHAR szFrameBuff[512] = {_T(' ')}; // Frame buffer. // Get the start of the seconds argument, which is the time. for (i = 0; ' ' != timer_cmd_line[i]; ++i) continue; // Put it in the time buffer. for (++i, j = 0; ' ' != timer_cmd_line[i]; ++i, ++j) szSetTimeInMinutes[j] = timer_cmd_line[i]; time_in_min = _tstof(szSetTimeInMinutes); // Print time in format mm:ss as well. set_minutes = (int)time_in_min; set_seconds = (int)(time_in_min * 60) % 60; // Get the start index of the message. for (i = 0; '"' != timer_cmd_line[i]; ++i) continue; // Put the message in the message buffer. ++i; k = 0; l = sizeof(szMessage) - 2; do { szMessage[k] = timer_cmd_line[i]; ++k; ++i; } while ('"' != timer_cmd_line[i] && k < l); // Put a null at the end to terminate the string. szMessage[k] = _T('\0'); // Get time left. calc_time = Calculate_Time_Left(pid, time_in_min); if (-1 == calc_time) _tprintf(_T("\nError in calculating the time left.")); // Get left time in format mm:ss as well. left_minutes = ((int)calc_time * 60) / 60; left_seconds = (int)(calc_time * 60) % 60; // See if the message has been set with the message only flag. if ('m' == timer_cmd_line[_tcslen(timer_cmd_line) - 1]) msg_speak = false; // Fill the frame buffer. _sntprintf(szFrameBuff, sizeof(szFrameBuff), _T("\n%d.\n%-11s %.2f min or %02d:%02d min\n%-11s %.2f min or %02d:%02d min\n%-11s %s \n%-11s %s\n"), timer_number, _T("Set for:"), time_in_min, set_minutes, set_seconds, _T("Time left:"), calc_time, left_minutes, left_seconds, _T("Message:"), szMessage, _T("Voice:"), (msg_speak) ? _T("yes") : _T("no")); // Print it. _tprintf(_T("%s"), szFrameBuff); return; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- float Calculate_Time_Left(DWORD pid, float time_in_min) { /* Name : Calculate_Time_Left() * Updated : 15.04.2016 * In : The PID of a timer and it's set time in minutes. * Returns : A float value of the remaining time in minutes. * Modifies : Nothing. * Calls : WIN API GetSystemTime(), OpenProcess(), GetProcessTimes(), SystemTimeToFileTime(), CloseHandle() * Description : Calculates the time left by substracting the process creation time from the current system time * and subsctracting the result from that from the amount of time the timer has been originally set. */ FILETIME ftSys, ftCreationTime, ftExitTime, ftKernelTime, ftUserTime; ULARGE_INTEGER uliSys, uliProc; SYSTEMTIME st; HANDLE p; BOOL chk; float time_in_seconds; GetSystemTime(&st); p = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid); if (!p) { _tprintf(_T("Could not open process.\n")); return -1; } chk = GetProcessTimes(p, &ftCreationTime, &ftExitTime, &ftKernelTime, &ftUserTime); if (!chk) { _tprintf(_T("Could not get process time.\n")); return -1; } // Convert system time to file time so we can perform arithmetic. chk = SystemTimeToFileTime(&st, &ftSys); if (!chk) { _tprintf(_T("Could not convert system time.\n")); return -1; } // Place both file times in a ULARGE_INTEGER as per Microsoft documentation. uliSys.LowPart = ftSys.dwLowDateTime; uliSys.HighPart = ftSys.dwHighDateTime; uliProc.LowPart = ftCreationTime.dwLowDateTime; uliProc.HighPart = ftCreationTime.dwHighDateTime; /* Get the difference in seconds. Filetime holds the amount of times 100 nanoseconds have passed * since January 1, 1601 (UTC), hence the divison by 10 000 000 */ time_in_seconds = (uliSys.QuadPart - uliProc.QuadPart) / 10000000; CloseHandle(p); // Return the time left. return time_in_min - (time_in_seconds / 60); } //------------------------------------------------------------------------- //------------------------------------------------------------------------- bool Get_Image_Name(TCHAR * image_name) { /* Name : Get_Image_Name() * Updated : 15.04.2016 * In : A pointer to the address where the image's name will be stored. * Returns : Success or failure. * Modifies : The value at &image_name. * Calls : WIN API GetModuleFileName() * Description : Gets the full path and image name, extracts only the image name, and writes it at &image_name. */ TCHAR szImgFullName[MAX_PATH]; // Get full module path and name. if( !GetModuleFileName(NULL, szImgFullName, MAX_PATH) ) { _tprintf(_T("GetModuleFileName failed.\n")); return false; } // Get length of the string. int path_size, img_name_start; path_size = _tcslen(szImgFullName); /* szImgFullName[2] would be the delimiting character in the path * string (e.g. the '\' in "C:\..\.."), so here we parse the * szImgFullName starting from the end and look for the first * delimiter. */ for (img_name_start = path_size; szImgFullName[img_name_start] != szImgFullName[2]; --img_name_start) continue; /* After ++img_name_start we have the index of the first letter of * the image name. */ ++img_name_start; int i; for (i = 0; img_name_start <= path_size; ++i, ++img_name_start) image_name[i] = szImgFullName[img_name_start]; return true; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- void Stop_Timer(DWORD pid, char tmr_num) { /* Name : Stop_Timer() * Updated : 15.04.2016 * In : A PID and the timer's number. * Returns : Nothing. * Modifies : Nothing. * Calls : WIN API OpenProcess(), TerminateProcess(), CloseHandle() * Description : Kills the process identified by the PID. */ if (0 == pid) { _tprintf(_T("There is no timer %d.\n"), tmr_num); return; } HANDLE p; BOOL chk; p = OpenProcess(PROCESS_TERMINATE, false, pid); if (!p) { _tprintf(_T("Could not open process.\n")); return; } chk = TerminateProcess(p, 0); if (!chk) { _tprintf(_T("Could not terminate process.\n")); return; } _tprintf(_T("Timer %d has been stopped.\n"), tmr_num); CloseHandle(p); return; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- void Print_Help(_TCHAR * argv[]) { /* Name : Print_Help() * Updated : 15.04.2016 * In : The cmd line arguments. * Returns : Nothing. * Modifies : Nothing. * Calls : Nothing. * Description : Prints help info when the program is called with no arguments. */ _tprintf(_T("%-15s %s\n"), _T("Name:"), NAME); _tprintf(_T("%-14s %s\n"), _T("Version:"), VERSION); _tprintf(_T("%-15s Sets a countdown timer and notifies you when the time is up.\n"), _T("Description:")); _tprintf(_T("%-15s %s <time in minutes> <your message> \n"), _T("Use:"), argv[0]); _tprintf(_T("%-15s %s 5 \"Your coffee is ready.\"\n"), _T("Example:"), argv[0]); _tprintf(_T("%-15s %s %s\n"), _T("For options:"), argv[0], ARG_OPTIONS); _tprintf(_T("%-15s For times less than a minute use a decimal number\n%-15s e.g. 0.5 for 30 seconds.\n"), _T("Remarks:"), _T(" ")); _tprintf(_T("%-15s Messages are spoken by default.\n"), _T(" ")); return; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- void Print_Options(_TCHAR * argv[]) { /* Name : Print_Options() * Updated : 15.04.2016 * In : The cmd line arguments. * Returns : Nothing. * Modifies : Nothing. * Calls : Nothing. * Description : Prints the available options when the program is called with the /? argument. */ const TCHAR example[] = _T("Example:"); _tprintf(_T("To list running timers use %s, %s, %s, or %s\n"), ARGS_LIST[0], ARGS_LIST[1], ARGS_LIST[2], ARGS_LIST[3]); _tprintf(_T("%s %s /l\n"), example, argv[0]); _tprintf(_T("To stop a running timer use %s, %s, %s, or %s\n"), ARGS_STOP[0], ARGS_STOP[1], ARGS_STOP[2], ARGS_STOP[3]); _tprintf(_T("%s %s /s <timer number>\n"), example, argv[0]); _tprintf(_T("To disable speech and only display the message box use %s\n"), ARG_MSG_ONLY); _tprintf(_T("%s %s 5 \"Coffee is ready.\" %s\n"), example, argv[0], ARG_MSG_ONLY); return; }
vladcc/tme
tme/tme.h
// #define UNICODE /* defined automatically by the -municode flag in gcc */ #define _UNICODE #define _WIN32_WINNT 0x0400 #define _WIN32_DCOM #include <initguid.h> #include <windows.h> #include <sapi.h> #include <ole2.h> #include <oleauto.h> #include <wbemidl.h> #include <tchar.h> #include <Tlhelp32.h> #include <stdbool.h> #define NAME _T("TimeMe") #define VERSION _T(" v1.0") #define TITLE NAME VERSION #define LIST_ARGS_COUNT 4 #define STOP_ARGS_COUNT 4 #define ARG_SET _T("/set") #define ARG_SET_MSG_ONLY _T("/setm") #define ARG_MSG_ONLY _T("/m") #define ARG_OPTIONS _T("/?") #define SLASH _T('/') #define DASH _T('-') #define SPEAK_PAUSE 250 #define MAX_MINUTES 525960 // Average number of minutes in a year. #define HELP 0 #define SET 1 #define SET_MSG_ONLY 2 #define START 3 #define LIST 4 #define STOP 5 #define OPTIONS 6 #define ARG_ERR 7 const TCHAR TIME_ERROR_MSG[] = _T("Time has to be between 0 and %d.\n"); const TCHAR *ARGS_LIST[LIST_ARGS_COUNT] = { _T("/list"), _T("/l"), _T("-list"), _T("-l") }; const TCHAR *ARGS_STOP[STOP_ARGS_COUNT] = { _T("/stop"), _T("/s"), _T("-stop"), _T("-s") }; struct THREAD_MSG { TCHAR * msg; bool thread_running; }; typedef struct THREAD_MSG THREAD_MSG; char Check_Arguments(int argc, _TCHAR * argv[]); void Set_Timer(int argc, _TCHAR * argv[], bool msgonly); bool Create_Timer(TCHAR cmdline[]); void Start_Timer(float time, TCHAR msg[], bool include_voice); DWORD WINAPI Show_Message(LPVOID lpParam); bool List_Timers(_TCHAR * argv[], bool kill, char timer_to_kill, DWORD * ttk_pid); bool Get_Image_Name(TCHAR * image_name); void Print_Timer_Info(BSTR timer_cmd_line, int timer_number, DWORD pid); float Calculate_Time_Left(DWORD pid, float time_in_min); void Stop_Timer(DWORD pid, char tmr_num); void Print_Help(_TCHAR * argv[]); void Print_Options(_TCHAR * argv[]); /* Caller table: * ------------------------------------------- * Function: Caller: * * ------------------------------------------- * Check_Arguments() main() * Set_Timer() main() * Create_Timer() Set_Timer() * Start_Timer() main() * Show_Message() Start_Timer() * List_Timers() main() * Get_Image_Name() List_Timers() * Print_Timer_Info() List_Timers() * Calculate_Time_Left() Print_Timer_Info() * Stop_Timer() main() * Print_Help() main() * Print_Options() main() */