repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
noahzhy/cpp_2018_fall
hw5-3/magic_square.h
<reponame>noahzhy/cpp_2018_fall<filename>hw5-3/magic_square.h<gh_stars>0 #pragma once #include <iostream> using namespace std; void magic_square(int **a, int size);
noahzhy/cpp_2018_fall
hw5-1/circle.h
#pragma once double getCirclePerimeter(double r); double getCircleArea(double r);
noahzhy/cpp_2018_fall
hw6-1/simple_account.h
<reponame>noahzhy/cpp_2018_fall<filename>hw6-1/simple_account.h #pragma once class simple_account{ public: int id; double balance; public: simple_account(); bool transfer(simple_account *from_id, simple_account *to_id, double amount); double get_balance(); bool deposit(double amount); bool withdraw(double amount); };
noahzhy/cpp_2018_fall
hw7-1/sorted_array.h
#ifndef __sorted_array__ #define __sorted_array__ #include <iostream> #include <vector> using namespace std; class SortedArray { public: SortedArray(); ~SortedArray(); void AddNumber(int num); vector<int> GetSortedAscending()const; vector<int> GetSortedDescending()const; int GetMax() const; int GetMin() const; private: std::vector<int> numbers_; }; #endif
noahzhy/cpp_2018_fall
hw11-1/string.h
#ifndef __String__ #define __String__ #include <iostream> using namespace std; class MyString { private: int len; char* a; public: //Constructor, Destructor MyString(); MyString(const char* str); ~MyString(); MyString operator+(const MyString& a); MyString operator*(const int a); MyString& operator=(const MyString& str); friend ostream& operator << (ostream& out, MyString& b); friend istream& operator >> (istream& in, MyString& b); }; #endif
noahzhy/cpp_2018_fall
hw10-1/shapes.h
#ifndef shape #define shape class Shape{ public: Shape(double width,double height); virtual double getArea() = 0; protected: double width; double height; }; class Rectangle:public Shape{ public: Rectangle(double width,double height); virtual double getArea(); }; class Triangle:public Shape{ public: Triangle(double width,double height); virtual double getArea(); }; #endif
noahzhy/cpp_2018_fall
hw6-3/minimal_fighter.h
<gh_stars>0 // minimal_fighter.h // Implement your minimal_fighter.cc #ifndef __hw03__minimal_fighter__ #define __hw03__minimal_fighter__ #include <iostream> using namespace std; enum EFighterStatus { Invalid = 0, Alive, Dead, }; typedef enum EFighterStatus FighterStatus; class MinimalFighter { private: int mHp; int mPower; FighterStatus mStatus; public: MinimalFighter(); MinimalFighter(int _hp, int _power); int hp() const; int power() const; FighterStatus status() const; void setHp(int _hp); void setStatus(); void hit(MinimalFighter *_enemy); void attack(MinimalFighter *_target); void fight(MinimalFighter *_enemy); }; #endif
noahzhy/cpp_2018_fall
hw12-2/my_shared_ptr.h
<gh_stars>0 #ifndef __my_shared_ptr__ #define __my_shared_ptr__ #include <iostream> using namespace std; template <class T> class My_shared_ptr { private: T* m_obj = NULL; int* count = NULL; public: My_shared_ptr(){ m_obj = NULL; count = NULL; } My_shared_ptr(T* obj){ m_obj = obj; count = new int; *count = 1; } My_shared_ptr(const My_shared_ptr& rhs){ m_obj = rhs.m_obj; count = rhs.m_count; *count += 1; } ~My_shared_ptr(){ *count -= 1; if (*count <= 0) { delete m_obj; delete count; } if(getCount() == 0) cout << "everything destroyed"<<endl; } My_shared_ptr<T>& operator=(const My_shared_ptr<T>& rhs){ if (m_obj == NULL || count == NULL) { delete m_obj; delete count; } else { *count -= 1; if (*count <= 0) { delete m_obj; delete count; } } m_obj = rhs.m_obj; count = rhs.count; *count += 1; return *this; } const T* get_m_obj(){ return m_obj;} int getCount(){ if (count) { return *count; } else { return 0; } } void increase(){ if (count) { *count += 1; } } void decrease(){ if (count) { *count -= 1; } } }; #endif
noahzhy/cpp_2018_fall
hw10-1/dynamic_cast.h
#ifndef __dynamic_cast__ #define __dynamic_cast__ #include <iostream> using namespace std; class B{ public: virtual ~B() {} }; class C : public B{ public: void test_C() { std::cout << "C::test_C()" << std::endl; } }; class D : public B{ public: void test_D() { std::cout << "D::test_D()" << std::endl; } }; #endif
noahzhy/cpp_2018_fall
hw9-2/draw_shape.h
#ifndef __draw_shape__ #define __draw_shape__ #include <iostream> #include <vector> using namespace std; class Canvas { public: Canvas(size_t row, size_t col); ~Canvas(); void Resize(size_t w, size_t h); bool DrawPixel(int x, int y, char brush); void Print(); void Clear(); private: size_t row_; size_t col_; char **p; }; class Shape { public: virtual ~Shape(); virtual void Draw(Canvas* canvas) {}; virtual void Dump(){}; protected: int x, y; int width, height; char brush; }; class Rectangle : public Shape { public: Rectangle(int x,int y,int w,int h,char brush); virtual void Draw(Canvas* canvas); virtual void Dump(); }; class UpTriangle : public Shape { public: UpTriangle(int x,int y,int h,char brush); virtual void Draw(Canvas* canvas); virtual void Dump(); }; class DownTriangle : public Shape { public: DownTriangle(int x,int y,int h,char brush); virtual void Draw(Canvas* canvas); virtual void Dump(); }; class Diamond : public Shape { public: Diamond(int x,int y,int h,char brush); virtual void Draw(Canvas* canvas); virtual void Dump(); }; #endif
noahzhy/cpp_2018_fall
hw10-2/clock_time.h
<filename>hw10-2/clock_time.h<gh_stars>0 #ifndef CLOCK_TIME_H #define CLOCK_TIME_H // Define a set of symbolic constants used to specify various values related // to time keeping. #define SECONDS_PER_MINUTE 60 #define MINUTES_PER_HOUR 60 #define HOURS_PER_DAY 24 class ClockTime // ClockTime is a concrete identity class used to keep track of current // time as it is moves forward. Note that time cannot be regressed. // // NOTE: Copying an instance of this class is bit-wise. { public: ClockTime (); ClockTime (int hour, int minute, int second, int secondsPerTick); ~ClockTime () { hour_ = minute_ = second_ = secondsPerTick_ = startTime_ = 0; } int const hour () const { return hour_; } int const minute () const { return minute_; } int const second () const { return second_; } int const secondsPerTick () const { return secondsPerTick_; } unsigned int startTime () const { return startTime_; } unsigned int deltaTime () const { return deltaTime_; } void setTime (ClockTime const& initialTime) { hour_ = initialTime.hour_; minute_ = initialTime.minute_; second_ = initialTime.second_; secondsPerTick_ = initialTime.secondsPerTick_; deltaTime_ = 0; } void setTime (int hour, int minute, int second, int secondsPerTick) { hour_ = hour; minute_ = minute; second_ = second; secondsPerTick_ = secondsPerTick; deltaTime_ = 0; } void reset (); void increment (); void display () const; private: int hour_; int minute_; int second_; int secondsPerTick_; unsigned int startTime_; unsigned int deltaTime_; void recordStartTime (); }; //0 class Clock{ protected: ClockTime _clockTime; double _driftPerSecond; double _totalDrift; public: Clock(int hour, int minute, int second, double driftPerSecond); void reset(); void tick(); virtual void displayTime() = 0; }; class NaturalClock : public Clock{ public: NaturalClock(int hour, int minute, int second, double driftPerSecond); virtual void displayTime() = 0; }; class MechanicalClock : public Clock{ public: MechanicalClock(int hour, int minute, int second, double driftPerSecond); virtual void displayTime() = 0; }; class DigitalClock : public Clock{ public: DigitalClock(int hour, int minute, int second, double driftPerSecond); virtual void displayTime() = 0; }; class QuantumClock : public Clock{ public: QuantumClock(int hour, int minute, int second, double driftPerSecond); virtual void displayTime() = 0; }; //second_level class SundialClock : public NaturalClock{ public: SundialClock(int hour, int minute, int second); virtual void displayTime(); }; class CuckooClock : public MechanicalClock{ public: CuckooClock(int hour, int minute, int second); virtual void displayTime(); }; class GrandFatherClock : public MechanicalClock{ public: GrandFatherClock(int hour, int minute, int second); virtual void displayTime(); }; class WristClock : public DigitalClock{ public: WristClock(int hour, int minute, int second); virtual void displayTime(); }; class AtomicClock : public QuantumClock{ public: AtomicClock(int hour, int minute, int second); virtual void displayTime(); }; #endif // CLOCK_TIME_H
noahzhy/cpp_2018_fall
hw9-1/classes.h
<filename>hw9-1/classes.h<gh_stars>0 #ifndef __classes__ #define __classes__ #include <iostream> using namespace std; class A{ public: virtual void test(); }; class B: public A{ public: virtual void test(); }; class C: public B{ public: virtual void test(); }; #endif
noahzhy/cpp_2018_fall
hw9-1/print_member.h
#ifndef __print_member__ #define __print_member__ #include <iostream> #include <string> using namespace std; class A { public: A(); A(int a); virtual ~A(); virtual void print(); private: int *memberA; }; class B: public A { public: B(); B(double b); virtual ~B(); virtual void print(); private: double *memberB; }; class C: public B { public: C(); C(string c); virtual ~C(); virtual void print(); private: string *memberC; }; #endif
noahzhy/cpp_2018_fall
hw10-1/class_function.h
<gh_stars>0 #ifndef __class_function__ #define __class_function__ //#include <iostream> //using namespace std; class A{ public: virtual void test1(); virtual void test2() = 0; }; class B : public A{ public: virtual void test2(); }; class C : public A{ public: void test1(); virtual void test2(); }; class BB : public B{ public: virtual void test1(); }; #endif
noahzhy/cpp_2018_fall
hw7-2/simple_int_set.h
#ifndef __simple_int_set__ #define __simple_int_set__ #include <iostream> #include <set> using namespace std; class SimpleIntSet{ public: SimpleIntSet(); ~SimpleIntSet(); bool InputSet(set<int>* s); set<int> SetIntersection(const set<int>& set0, const set<int>& set1); set<int> SetUnion(const set<int>& set0, const set<int>& set1); set<int> SetDifference(const set<int>& set0, const set<int>& set1); }; #endif
noahzhy/cpp_2018_fall
hw5-2/sort.h
#pragma once #include <iostream> void swap(int *a,int i,int j); void bubble_sort(int *a,int len);
noahzhy/cpp_2018_fall
hw12-1/Container.h
#ifndef __Container__ #define __Container__ #include "MyContainer.h" #include <iostream> using namespace std; int max(int a, int b) { if (a > b) { return a; } else { return b; } } template <typename T> class MyVector : public MyContainer<T> { public: MyVector() : MyContainer<T>() { capacity = 0; } MyVector(int n) : MyContainer<T>(n) { capacity = n; } MyVector(T* arr, size_t n) : MyContainer<T>(arr, n) { capacity = n; } bool empty() { if (MyContainer<T>::n_elements == 0) { return 1; } else { return 0; } } int size() { return MyContainer<T>::n_elements; } int max_size() { return capacity; } void reserve(int new_cap) { if (new_cap > capacity) { T* ptmp = new T[new_cap]; for (size_t i = 0; i < MyContainer<T>::n_elements; i++) { ptmp[i] = MyContainer<T>::obj_arr[i]; } MyContainer<T>::obj_arr = ptmp; capacity = new_cap; } } void push_back(T obj) { if (MyContainer<T>::n_elements >= capacity) { reserve(max(1, capacity * 2)); MyContainer<T>::obj_arr[MyContainer<T>::n_elements++] = obj; } } void pop_back() { if (MyContainer<T>::n_elements > 0) { MyContainer<T>::obj_arr[MyContainer<T>::n_elements--] = NULL; } } T& front() { return MyContainer<T>::obj_arr[0]; } T& back() { return MyContainer<T>::obj_arr[MyContainer<T>::n_elements - 1]; } T& at(int idx) { if (idx < MyContainer<T>::n_elements && idx>= 0) { return MyContainer<T>::obj_arr[idx]; } } T& operator[](const int &i) { return MyContainer<T>::obj_arr[i]; } MyVector operator+(const MyVector<T> &rhs) { int sum_elements = MyContainer<T>::n_elements + rhs.n_elements; MyVector tmp(sum_elements); for (size_t i = 0; i < MyContainer<T>::n_elements; i++) { tmp[i] = MyContainer<T>::obj_arr[i]; } for (size_t i = 0; i < rhs.n_elements; i++) { tmp[MyContainer<T>::n_elements + i] = rhs.obj_arr[i]; } return tmp; } private: int capacity; }; #endif
noahzhy/cpp_2018_fall
hw9-1/print_info.h
#ifndef __print_info__ #define __print_info__ #include <iostream> #include <string> using namespace std; class A { public: virtual string getTypeInfo(); }; class B: public A { public: virtual string getTypeInfo(); }; class C: public B { public: virtual string getTypeInfo(); }; #endif
donotturnoff/herbe
config.h
<filename>config.h static const char *background_color = "#222222"; static const char *border_color = "#005577"; static const char *font_color = "#eeeeee"; static const char *font_pattern = "Terminus:size=10:antialias=false:autohint=true"; static const unsigned line_spacing = 5; static const unsigned int padding = 15; static const unsigned int width = 210; static const unsigned int border_size = 1; static const unsigned int pos_x = 20; static const unsigned int pos_y = 38; enum corners { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT }; enum corners corner = TOP_RIGHT; static const unsigned int duration = 0; /* in seconds */ #define DISMISS_BUTTON Button1 #define ACTION_BUTTON Button3
SleepyLGod/Miscellaneous
Sudoku/SudokuQt/sudoku.h
#define SUDOKU_H /** * Suduku.h * 基于SAT的数独游戏求解程序 * * Created by 路昊东 on 2021/9/5 * Copyright ? 2021 路昊东. All rights reserved. **/ #ifndef Sudoku_h #define Sudoku_h #include <stdio.h> #include <stdlib.h> #include "dpll.h" #include "cnf.h" extern int sudoku_table[9][9]; //定义全局变量int类型二维数组存储数独盘 extern int users_sudoku[9][9]; //存储输出的含空格数独问题格局 status Sudoku(void); FILE * CreateSudokuFile(void); //创建数独问题转化为SAT问题后的cnf文件 status CreateSudoku(void); //创建新的随机9*9数独终盘 status DigHole(int num); //对已知数独终盘挖num个洞生成有唯一解的数独问题 status SudokuComplete(void); //完善数独终盘 status SudokuExchange(void); //基于cell元素交换原理增加一数独终盘的随机性 status CNFSudokuTableTransform(void); //数独对应SAT变元表转化为二维数组 status SudokuTablePrint(void); //输出数独盘 #endif /* Sudoku_h */
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version1/SITE.h
<filename>cpp_lab_2021/OtherVersions/lab5_2020/version1/SITE.h<gh_stars>1-10 #ifndef __Site_Imfo_H__ #define __Site_Imfo_H__ struct Site_Imfo{ char organization[2][100]={}; int location[2]={0,}; int organization_num=0; int organization_no[2]; // int accessible_location_num=0; // int accessible_location[10]={0,}; // double accessible_location_distance[10]={0,}; int accessible_site_num = 0; int accessible_site[10] ={0,}; double accessible_site_distance[25] = {0,}; }; #endif #ifndef __SITE_H__ #define __SITE_H__ class SITE{ public: const static int site_num = 25; Site_Imfo info[site_num]; SITE(); ~SITE(){}; }; #endif
SleepyLGod/Miscellaneous
cpp_lab_2021/HustMap/mapedge.h
#ifndef MAPEDGE_H #define MAPEDGE_H #include "mappoint.h" class MapPoint; class MapEdge { MapPoint* to_ = nullptr; MapEdge* next_ = nullptr; double edge_distance_ = 0.0; public: MapEdge(); // setters: void add_next_(MapPoint* to, double distance = 1.0); // getters: MapEdge*& get_next_(); MapPoint*& get_to_(); double& get_edge_distance_(); }; #endif // MAPEDGE_H
SleepyLGod/Miscellaneous
focusClimer/focusClimer 2.0/panel.h
<gh_stars>0 // 控制面板的设计 #ifndef PANEL_H #define PANEL_H #include <QWidget> #include <QMainWindow> #include <QtWidgets/QWidget> #include <QPainter> #include <algorithm> #include <complex> #include <QTimer> class panel : public QWidget { Q_OBJECT public: explicit panel(QWidget *parent = nullptr); void setTitle(const QString &title); protected: void paintEvent(QPaintEvent *); void drawCrown(QPainter *painter); void drawScale(QPainter *painter); void drawScaleNum(QPainter *painter); void drawTitle(QPainter *painter); void drawIndicator(QPainter *painter); void drawNumericalValue(QPainter *painter); void drawColorPie(QPainter *painter); void drawCoverCircle(QPainter *painter); private: void initVariables(); QColor m_background; QColor m_foreground; int m_maxValue; int m_minValue; int m_startAngle; int m_endAngle; int m_scaleMajor; // 表盘分度值 int m_scaleMinor; double m_value; int m_precision; QTimer *m_updateTimer; QTimer* singleTimer; QString m_units; QString m_title; // 单位 QColor pieColorStart; // 饼圆开始颜色 QColor pieColorMid; // 饼圆中间颜色 QColor pieColorEnd; // 饼圆结束颜色 QColor coverCircleColor; // 饼盘覆盖色 public slots: void setValue(qreal value); /* void setAnimating(bool enable) { m_bAnimating=enable; update(); } public: bool isAnimating() const { return m_bAnimating; } */ public Q_SLOTS: void UpdateAngle(); // 转动 }; #endif // PANEL_H
SleepyLGod/Miscellaneous
Sudoku/SudokuQt/cnf.h
#ifndef CNF_H #define CNF_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <qstring.h> #include <qdebug.h> #include <qtextcodec.h> #include <QTextCodec> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASTABLE -1 #define OVERFLOW -2 #define INCREASEMENT 100 #define SUDOKU_LENGTH 9 #define SUDOKU_BOX 729 typedef int status; /* 定义子句链表结点结构类型 */ typedef struct Clause { int literal; // 记录子句中的文字 int flag; // 标记该文字是否已被删除,未删除时值为0,否则值为使之删除的变元序号 struct Clause *nextl; // 指向该子句中下一文字的指针 struct Clause *litline; // 指向整个CNF公式邻接链表中下一个文字相同的子句结点 } Clause; /* 定义CNF范式链表结点(即子句链表头结点)结构类型 */ typedef struct Paradigm { int number; // 子句中显示的文字数 int flag; // 标记该子句是否已被删除,未删除时值为0,否则值为使之删除的变元序号 struct Paradigm *nextc; // 指向下一子句的头结点 struct Clause *sentence; // 子句头指针 } Paradigm; /* 定义CNF范式链表头结点类型,存储CNF范式信息 */ typedef struct Root { int litsize; // 存储文字数量 int parasize; // 存储子句数量 Paradigm *first; // 指向第一个子句 } Root; /* 定义指向子句链表头结点的指针链表结点结构类型 */ typedef struct Paraline { Paradigm *claline; // 指向子句链表头结点Paradigm struct Paraline *next; // 指向下一链表结点 } Paraline; /* 定义文字相关信息链表结构类型 */ typedef struct LitTrabverse { Paraline *Tra_cla; // 指向含有该正文字或负文字的子句头结点链表的头结点 Clause *Tra_lit; // 指向该正文字或负文字的文字结点 } LitTrabverse; /* 定义求解数独文件时所需的存储变元信息结构类型 */ typedef struct sudokusolver { int x; // 存储行信息 int y; // 存储列信息 int z; // 存储变元对应1~9数值信息 } sudokusolver; /* 定义存储变元信息的变元线性表结点结构类型 */ typedef struct ArgueValue { int Value; // 变元的真值 int IsInit; // 变元是否已赋值 int Occur_times; // 变元在所有子句中出现的总次数 LitTrabverse Pos; // 变元所有正文字的相关信息结构 LitTrabverse Neg; // 变元所有负文字的相关信息结构 sudokusolver xyz; // 求解数独文件时所需的变元信息 } ArgueValue; typedef struct { int number; // 变元在CNF范式中出现次数 int amount; // 出现次数为number的不同变元总数 } Frequent; typedef struct { int *amount; // 对不同的次数,出现次数相同的变元数量相同的数目 int totalvariety; // *amount不同的总数 } SameFre_AmountList; typedef struct { int argue; // 记录真值设为1的文字 int flag; // 记录是否已经测试过argue的反文字的真值 } mainstack; // 非递归式DPLL中记录每次设为1的文字的栈结构 status CreateParadigm(FILE **fp); // 创建CNF范式邻接链表及变元表 status CreateClause(FILE **fp,Clause **sentence,Paradigm *ClausHead,int first); // 创建子句链表及文字链表 status DestroyParadigm(Root *r); // 销毁所有链表及线性表结构 status HasUnitClause(Root *r); // 判断CNF范式中是否还含有单子句 Clause * HasUnitClause_Before(Root *r); // 判断CNF范式中是否还含有单子句(优化前版本) status isUnitClause(Paradigm *c); // 判断指针c指向的子句链表是否为单子句链表 /* 在整个CNF公式中取一个文字 */ status FindLiteral1(Root *r); // 取每次DPLL处理后公式中Occur_Times最大的文字 status FindLiteral2(Root *r); // 取原公式中Occur_Times最大的文字 status FindLiteral3(Root *r); // 取子句中第一个flag为0的文字 status FindLiteral4(Root *r); // 取ValueList正序第一个IsInit=0的变元正文字 Clause * FindLiteral_Before(Root *r); // 在整个CNF公式中取一个文字(优化前版本) status DeleteClause(Root *r,int l); // 删除出现了文字l的所有单子句 status AddClause(Root *r,int l); // 在CNF范式邻接链表表头添加只含有文字l的单子句链表 status RemoveHeadClaus(Root *r,int l); // 删除CNF范式邻接链表中从表头开始第一个只含有文字l的单子句链表 status DeleteLiteral(Root *r,int l); // 删除所有文字为-l的子句链表结点 status RecoverCNF(Root *r,int l); // 恢复认为文字l为真时对CNF范式邻接链表所作的操作 QString ParadigmTrabverse(Root *r); // 遍历CNF范式邻接链表 status SaveValue(ArgueValue *ValueList,int solut,int time,QString filenameInfo); // 保存CNF范式的解及求解时间信息 status OccurTimeCount(void); // 处理读取的文件中变元出现次数信息,决策DPLL过程中分裂策略的变元选取策略 #endif // CNF_H
SleepyLGod/Miscellaneous
cpp_lab_2021/HustMap/mappoint.h
#ifndef MAPPOINT_H #define MAPPOINT_H #include <iostream> #include <algorithm> #include <math.h> #include "mapedge.h" class MapEdge; class MapPoint { private: int point_x_ = 0; int point_y_ = 0; int point_index_ = 0; MapEdge* direct_edge_first_ = nullptr; MapEdge* every_edge_first_ = nullptr; public: MapPoint(); MapPoint(int point_x_, int point_y_, int point_index_) :point_x_(point_x_), point_y_(point_y_), point_index_(point_index_) {}; // getters: int get_point_index_(); MapEdge* get_direct_edge_first_(); MapEdge* get_every_edge_first_(); std::pair<int, int> get_point_pos(); // setters: void set_point_pos_(int x, int y); void set_point_index_(int index); void add_direct_Edge_(MapPoint* p, double distance); void add_every_edge_(MapPoint* p); }; double calculateDistance(MapPoint a, MapPoint b); #endif // MAPPOINT_H
SleepyLGod/Miscellaneous
Sudoku/Sudoku_cpp_linux/DPLL.h
/** * DPLL.h * 基于SAT的数独游戏求解程序 * * Created by 路昊东 on 2021/9/10 * Copyright ? 2021 路昊东. All rights reserved. */ #ifndef DPLL_h #define DPLL_h #include <stdlib.h> #include <stdio.h> #include <time.h> #include "cnf.h" status SAT(void); status DPLL1(int num,int op,int times); //采用第一种变元选取策略的递归算法DPLL函数 status DPLL2(int num,int op,int times); //采用第二种变元选取策略的递归算法DPLL函数 status DPLL3(int num,int op,int times); //采用第三种变元选取策略的递归算法DPLL函数 status DPLL4(int num,int op,int times); //采用第四种变元选取策略的递归算法DPLL函数 status DPLL (int num,int op,int times); //采用第一种变元选取策略的非递归算法DPLL函数 status DPLL_Before(Root *r,int op); //优化前版本DPLL void AnswerComplete(void); //完善SAT求解结果 status AnswerCheck(int solut); //检查SAT求解结果正确性 #endif /* DPLL_h */
SleepyLGod/Miscellaneous
Sudoku/SudokuQt/mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "dpll.h" #include "sudoku.h" #include <QList> #include <qvalidator.h> #include <QFileDialog> #include <QTextCodec> #include <qdebug.h> #include <iomanip> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); int satOrSudoku = 0; // SAT或者SUDOKU模块二选一解锁 int difficultyChoice = 0; // 随机数独难度选择 bool solveButtonIsOK = false; // SUDOKU已经解决 int satStepOption = 0; // SAT步骤(1:求解;2:检验正确性;3:保存文件 int optimizationChoice = 0; // 优化方案选择 int solut = 0; // solut记录CNF公式是否有解,有解为1,无解为0 float duration = 0.00; // 记录SAT求解时间 QString importFileName =""; // sudoku导入文件名称 QString importFileNameSAT = ""; // sat导入文件名称 int lockAll = 0; // 总解锁键 ~MainWindow(); // sudoku模块按钮 void initSudoku(); void submitSudoku(); void SolveSudoku(); void CheckSudoku(); void ClearBoard(); void ImportFile(); status SolveSudokuGame(void); private slots: void on_radioButton_clicked(); void on_radioButton_2_clicked(); void on_radioButton_3_clicked(); void on_toolButton_clicked(); void on_pushButton_11_clicked(); void on_pushButton_9_clicked(); void on_pushButton_8_clicked(); void on_radioButton_4_clicked(); void on_radioButton_5_clicked(); void on_radioButton_6_clicked(); void on_pushButton_6_clicked(); void on_pushButton_7_clicked(); void on_pushButton_12_clicked(); void on_pushButton_13_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
SleepyLGod/Miscellaneous
cpp_lab_2021/HustMap/mainwindow.h
<filename>cpp_lab_2021/HustMap/mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMouseEvent> #include <string> #include <QPoint> #include "BusMap.h" #include "mappoint.h" #include "mapedge.h" #include "busdialog.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT BusMap *bp_; bool is_cliked_; int start_point_index_ = 0; int end_point_index_ = 0; int* ans_; int timer_id_ = 0; // drawers about the line: QPoint start_pos_; QPoint end_pos_; public: void findPointByName(); MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_checkBox_nearest_stateChanged(int arg1); void on_checkBox_transfers_stateChanged(int arg1); private: Ui::MainWindow *ui; void paintEvent(QPaintEvent *); void mousePressEvent(QMouseEvent *event); void keyPressEvent(QKeyEvent *event); void timerEvent(QTimerEvent *event); }; #endif // MAINWINDOW_H
SleepyLGod/Miscellaneous
focusClimer/focusClimer 2.0/trajectory.h
#ifndef TRAJECTORY_H #define TRAJECTORY_H #include <QTransform> #include "lineentity.h" #include <QEntity> // 在我的Ubuntu20.04系统中的安装位置 //#include <eigen3/Eigen/Core> //#include <eigen3/Eigen/Geometry> // win10下的安装位置 #include <Eigen/Core> #include <Eigen/Geometry> class Trajectory : public LineEntity { private: Eigen::Vector3d lastPoint; public: Trajectory(const QColor &color, Qt3DCore::QNode *parent = nullptr):LineEntity(color, parent){}; void pointUpdate(Eigen::Vector3d lastPoint); // 更新起点 bool isOk(Eigen::Vector3d latestPoint); // 判断是否更新起点 void drawLine(Eigen::Vector3d lastPoint); // 画线 void clearTrajectory(); // 清空 }; #endif // TRAJECTORY_H
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version3/HustMap/HustMap.h
 // HustMap.h: HustMap 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含 'pch.h' 以生成 PCH" #endif #include "resource.h" // 主符号 // CHustMapApp: // 有关此类的实现,请参阅 HustMap.cpp // class CHustMapApp : public CWinAppEx { public: CHustMapApp() noexcept; // 重写 public: virtual BOOL InitInstance(); virtual int ExitInstance(); // 实现 UINT m_nAppLook; BOOL m_bHiColorIcons; virtual void PreLoadState(); virtual void LoadCustomState(); virtual void SaveCustomState(); afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() }; extern CHustMapApp theApp;
SleepyLGod/Miscellaneous
focusClimer/focusClimer 2.0/lineentity.h
#ifndef LINEENTITY_H #define LINEENTITY_H #include <Qt3DCore/QEntity> #include <Qt3DRender/QGeometry> #include <Qt3DRender/QBuffer> #include <Qt3DRender/QGeometryRenderer> #include <Qt3DExtras/QDiffuseSpecularMaterial> #include <Qt3DRender/QAttribute> #include <QVector3D> class LineEntity : public Qt3DCore::QEntity { public: LineEntity(Qt3DCore::QNode *parent = nullptr); LineEntity(const QColor &color, Qt3DCore::QNode *parent = nullptr); void setLineColor(const QColor &color); // 设置颜色 void addVertex(const QVector3D &vertex); // 画线 void clearVertices(); // 清空所有线 private: Qt3DRender::QGeometry *m_lineGeometry = nullptr; Qt3DRender::QBuffer *m_lineVertexPositionBuf = nullptr; Qt3DRender::QBuffer *m_lineVertexIndexBuf = nullptr; Qt3DRender::QGeometryRenderer *m_lineGeometryRenderer = nullptr; Qt3DExtras::QDiffuseSpecularMaterial *m_lineMaterial = nullptr; Qt3DRender::QAttribute *m_lineVertexPositionAttribute = nullptr; Qt3DRender::QAttribute *m_lineVertexIndexAttribute = nullptr; QByteArray m_lineVertexPositionByteArray; QByteArray m_lineVertexIndexByteArray; unsigned int m_count = 0; // 用于vertex数目计数 }; #endif // LINEENTITY_H
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version3/HustMap/ViewTree.h
 #pragma once ///////////////////////////////////////////////////////////////////////////// // CViewTree 窗口 class CViewTree : public CTreeCtrl { // 构造 public: CViewTree() noexcept; // 重写 protected: virtual BOOL OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult); // 实现 public: virtual ~CViewTree(); protected: DECLARE_MESSAGE_MAP() };
SleepyLGod/Miscellaneous
focusClimer/focusClimer 2.0/axesentity_robot.h
#ifndef AXESENTITY_ROBOT_H #define AXESENTITY_ROBOT_H #include "lineentity.h" // 自身系坐标轴 class AxesEntity_robot : public Qt3DCore::QEntity { public: AxesEntity_robot(Qt3DCore::QNode *parent = nullptr); AxesEntity_robot(unsigned int axisLen,/* unsigned int auxiliaryLen1,unsigned int auxiliaryLen2, */Qt3DCore::QNode *parent = nullptr); void setAxisLen(unsigned int axisLen); private: // 坐标轴对象 LineEntity *m_xAxisEntity = nullptr; LineEntity *m_yAxisEntity = nullptr; LineEntity *m_zAxisEntity = nullptr; void updateAxes(unsigned int axisLen); }; #endif // AXESENTITY_ROBOT_H
SleepyLGod/Miscellaneous
cpp_lab_2021/HustMap/busdialog.h
#ifndef BUSDIALOG_H #define BUSDIALOG_H #include <QDialog> #include <QPushButton> #include <QString> #include <QDebug> #include <iostream> namespace Ui { class BusDialog; } class BusDialog : public QDialog { Q_OBJECT public: QString point_name_; explicit BusDialog(QWidget *parent = nullptr); ~BusDialog(); private slots: void on_pushButton_clicked(); private: Ui::BusDialog *ui; }; #endif // BUSDIALOG_H
SleepyLGod/Miscellaneous
Sudoku/SudokuQt/dpll.h
#ifndef DPLL_H #define DPLL_H #include <stdlib.h> #include <stdio.h> #include <time.h> #include "cnf.h" #include "mainwindow.h" status DPLL1(int num,int op,int times); //采用第一种变元选取策略的递归算法DPLL函数 status DPLL2(int num,int op,int times); //采用第二种变元选取策略的递归算法DPLL函数 status DPLL3(int num,int op,int times); //采用第三种变元选取策略的递归算法DPLL函数 status DPLL4(int num,int op,int times); //采用第四种变元选取策略的递归算法DPLL函数 status DPLL (int num,int op,int times); //采用第一种变元选取策略的非递归算法DPLL函数 status DPLL_Before(Root *r,int op); //优化前版本DPLL void AnswerComplete(void); //完善SAT求解结果 status AnswerCheck(int solut); //检查SAT求解结果正确性 #endif // DPLL_H
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2021/version1/mainwindow.h
<gh_stars>1-10 #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "busMap.h" #include "dialog.h" #include <QMouseEvent> #include <string> #include <QPoint> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT busMap *bp; bool isClicked; int startPointIndex=0,endPointIndex=0; int* ans; int timerId=0; QPoint startPos,endPos; public: void findPointByName(); MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_checkBox_stateChanged(int arg1); void on_checkBox_2_stateChanged(int arg1); private: void paintEvent(QPaintEvent *); void mousePressEvent(QMouseEvent *event); void keyPressEvent(QKeyEvent *event); void timerEvent(QTimerEvent *event); Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
SleepyLGod/Miscellaneous
cpp_lab_2021/HustMap/BusMap.h
#ifndef BusMap_H #define BusMap_H #include <string> #include <fstream> #include <queue> #include "mappoint.h" using namespace std; class BusMap { private: int map_len_ = 0; int map_wid_ = 0; int bus_stop_cnt_ = 0; // 公交车站点数量 int bus_line_cnt_ = 0; // 公交车线路数量 int organizations_cnt_ = 0; // 机构或单位数量 string organization_names_[100]; // 机构或单位名称 pair<int,int> organization_pos_[100]; // 组织名 int* each_bus_line_num_ = nullptr; int** bus_lines_ = nullptr; MapPoint** bus_stops_ = nullptr; int* path_ = nullptr; public: // initialize: BusMap(string bus_stops_File, string bus_lines_File, string orgnizations_file); // getters: int get_bus_line_cnt_() { return bus_line_cnt_; } int** get_bus_lines_() { return bus_lines_; } int* get_each_bus_line_num_() { return each_bus_line_num_; } int get_bus_stop_cnt_() { return bus_stop_cnt_; } MapPoint** get_bus_stops_() { return bus_stops_; } int get_organizations_cnt_() { return organizations_cnt_; } string* get_organization_names_() { return organization_names_; } pair<int,int>* get_organization_pos_() { return organization_pos_; } void showStopsAndLines(); int* findDirectPath(int start_index, int end_index); int* findEveryPath(int start_index, int end_index); ~BusMap(); }; #endif // BusMap_H
SleepyLGod/Miscellaneous
focusClimer/focusClimer 2.0/axesentity.h
<gh_stars>1-10 #ifndef AXESENTITY_H #define AXESENTITY_H #include "lineentity.h" // 世界系坐标轴 class AxesEntity : public Qt3DCore::QEntity { public: AxesEntity(Qt3DCore::QNode *parent = nullptr); AxesEntity(unsigned int axisLen,Qt3DCore::QNode *parent = nullptr); void setAxisLen(unsigned int axisLen); private: // 坐标轴对象 LineEntity *m_xAxisEntity = nullptr; LineEntity *m_yAxisEntity = nullptr; LineEntity *m_zAxisEntity = nullptr; void updateAxes(unsigned int axisLen); }; #endif // AXESENTITY_H
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version3/HustMap/CMapModel.h
<gh_stars>1-10 #pragma once #include <afx.h> #include <vector> class CMapModel : public CObject { private: CString m_sMapFilePath = _T(""); CString m_sLocationFilePath = _T(""); CString m_sEdgeFilePath = _T(""); CString m_sOrgFilePath = _T(""); CString m_sLocOrgFilePath = _T(""); std::vector<CPoint>Location; double Edge[100][100]; public: DECLARE_SERIAL(CMapModel) CMapModel(); virtual ~CMapModel(); public: virtual void Serialize(CArchive& ar); public: std::vector<CString>Organization; std::vector<std::vector<int>>Locorg; int GetLocationNum() { return Location.size(); } CString GetMapFilePath(); CString GetLoacationFilePath(); CString GetEdgeFilePath(); CString GetOrgFilePath(); CString GetLocOrgFilePath(); CPoint GetLocation(int i); double GetEdge(int x, int y); void SetMapFilePath(CString path); void SetLocationFilePath(CString path); void SetEdgeFilePath(CString path); void SetOrgFilePath(CString path); void SetLocOrgFilePath(CString path); void PushLocation(CPoint point); void PushOrganization(CString name); void PushEdge(int a, int b,double edge); CPoint FindPositionByOrg(CString name); std::vector<CPoint> FindShortestPath(CPoint start, CPoint end); std::vector<CString>GetOrganizations(CPoint point); };
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version1/search.h
<gh_stars>1-10 #ifndef SEARCH_H #define SEARCH_H #include <QWidget> class search : public QWidget { Q_OBJECT public: explicit search(QWidget *parent = nullptr); signals: }; #endif // SEARCH_H
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version3/HustMap/CMapDialog.h
#pragma once #include<vector> // CMapDialog 对话框 class CMapDialog : public CDialogEx { DECLARE_DYNAMIC(CMapDialog) public: CMapDialog(CWnd* pParent = nullptr); // 标准构造函数 virtual ~CMapDialog(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_MAP_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: // 输入起点位置的下拉列表框对象 CComboBox m_ComboStart; // 输入终点位置的下拉列表框对象 CComboBox m_ComboEnd; std::vector<CString> StartDeletedString; std::vector<CString> EndDeletedString; virtual BOOL OnInitDialog(); afx_msg void OnBnClickedOk(); afx_msg void OnCbnEditchangeComboStart(); afx_msg void OnCbnEditchangeComboEnd(); afx_msg void OnCbnSetfocusComboStart(); afx_msg void OnCbnSetfocusComboEnd(); };
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version2/mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "mapwidget.h" //#include <QToolButton> #include <QGraphicsLineItem> #include <QGraphicsScene> #include <QGraphicsView> #include <QLabel> #include <QComboBox> #include <QTextEdit> #include <QVector> #include <QMouseEvent> #include <QDialog> #include <QPixmap> #include <QGridLayout> #include <QLineEdit> #include <QFileDialog> #include <QHBoxLayout> class QMyLabel; class ComboBox : public QComboBox { friend class MainWindow; Q_OBJECT public: explicit ComboBox(QWidget* parent = nullptr); protected: void keyReleaseEvent(QKeyEvent *e); signals: void keyEnterReleased(); }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); void createToolBar(); //创建顶层工具栏 void createAction(); //将ui和数据绑定 void setStart(int X, int Y); //线段起点 void setEnd(int X, int Y); //线段终点 void setNextPos (int index); //dj前置结点 void initScene(); //初始化背景 public slots: //void showfloatwindow(); //void hidefloatwindow(); void setStartStation(); //传输起始信号 void setEndStation(); //传输终点信号 void FindPath(); //dj void Clear(); //清屏 void callOtherMap(); //放大 void ShowDialog(); //展示路径 void addStartComboBox(); //输入起点框 void addEndComboBox(); //输入终止框 double similarity(const QString& s, const QVector<QString>&t); //返回字符串相似度 QVector<int>similarest(const QString& s, const QVector<QVector<QString>>v); //返回匹配字符串数组 private: MapWidget *mapWidget; //宽度 QLabel *startLabel; //开始小红点 QLabel *endLabel; //终点小红点 QComboBox *reviseComboBox; // QAction *findPathAction; //搜索路径按钮 QAction *clearAction; //清屏按钮 QAction *callMap; //放大 QGraphicsScene *scene;//背景 QGraphicsView *view;// int startX, startY, endX, endY;//开始xy,终点xy QVector<int> nextPath; //dj数组 /* * 图的实现,和最短路径算法声明 */ struct ArcCell{ //弧信息 int adj; //对无权图有1,0表示是否相邻,对带权图,则为权值类型 }; //内部类 static const int MAX_VERTEX_NUM = 50; static const int INF = 999999; struct MGraph{ QVector<int> vexs; //顶点集合 //临接矩阵 ArcCell arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; int vexnum; //顶点数 int arcnum; //边数 }; class DijkstraFindPath { public: DijkstraFindPath(); MGraph mgraph; void CreateGraph(); int prev[MAX_VERTEX_NUM]; //最短路上的前驱顶点 int d[MAX_VERTEX_NUM]; //表示边e = (u,v)的权值(不存在时为INF,不过d[i][i]=0) bool used[MAX_VERTEX_NUM]; //已经使用过的图 void dijkstra(int startPos); //求从起点startPos出发到各个顶点的最短距离 QVector<int> get_Path(int endPos);//到顶点endPos的最短路 QVector<QVector<int>>Location; //坐标 QVector<QVector<QString>>names; //名字 }; ComboBox *startComboBox; ComboBox *endComboBox; DijkstraFindPath *dj; //鼠标事件 protected: void mousePressEvent (QMouseEvent *e); private: QPixmap library; QPixmap canteen; QPixmap jxjBuilding; QPixmap westgate; QPixmap westground; QPixmap twoMarket; QString strPath; QLabel *label; QGraphicsSimpleTextItem *l; QGraphicsSimpleTextItem *r; int lv=-1; int rv=-1; }; #endif // MAINWINDOW_H
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version3/HustMap/HustMapView.h
 // HustMapView.h: CHustMapView 类的接口 // #pragma once class CHustMapView : public CView { protected: // 仅从序列化创建 CHustMapView() noexcept; DECLARE_DYNCREATE(CHustMapView) //起点,终点,拖拉状态 Add By Z protected: //CPoint m_LineStart;//鼠标点击画线起点 //CPoint m_LastLineEnd;//上次画线的终点 //boolean m_DraggingState = false;//按下鼠标左键的同时是否拖曳鼠标 //绘图时用,add by Z CPoint LastStart;//左右键设置起始点时上一次的起始点 CPoint LastEnd;//左右键设置终点时上一次的终点 bool HaveDrawLine = false;//记录屏幕上是否已经画过路径 //显示信息时用 boolean m_TrackingState = false; CToolTipCtrl m_Tooltip; public: void SetHaveDrawLine() { HaveDrawLine = true; };//HaveDrawLine的set方法(在Dialog内调用) // 特性 public: CHustMapDoc* GetDocument() const; // 操作 public: // 重写 public: virtual void OnDraw(CDC* pDC); // 重写以绘制该视图 virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 实现 public: virtual ~CHustMapView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: afx_msg void OnFilePrintPreview(); afx_msg void OnRButtonUp(UINT nFlags, CPoint point);//以修改为调出查询路径对话框 afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); DECLARE_MESSAGE_MAP() public: afx_msg void OnLButtonDown(UINT nFlags, CPoint point);//擦除上次路径,设置起点 void DrawCircle(CPoint center, LONG radius,int colors=0);//画点,colors为0时画红点,为1时画黄点 void DrawLine(CPoint start, CPoint end);//画线 afx_msg void OnLButtonUp(UINT nFlags, CPoint point);//功能已删除 afx_msg void OnMouseMove(UINT nFlags, CPoint point);//ToolTip显示地点信息 void DrawRubberLine(CPoint start, CPoint end);//功能已删除 afx_msg void OnMouseLeave();//ToolTip取消显示地点信息 virtual void OnInitialUpdate();//ToolTip显示地点信息 virtual BOOL PreTranslateMessage(MSG* pMsg);//ToolTip显示地点信息 afx_msg void OnRButtonDown(UINT nFlags, CPoint point);//设置终点信息 afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);//查询 }; #ifndef _DEBUG // HustMapView.cpp 中的调试版本 inline CHustMapDoc* CHustMapView::GetDocument() const { return reinterpret_cast<CHustMapDoc*>(m_pDocument); } #endif
SleepyLGod/Miscellaneous
focusClimer/focusClimer 2.0/auxiliatyentity.h
<filename>focusClimer/focusClimer 2.0/auxiliatyentity.h #ifndef AUXILIATYENTITY_H #define AUXILIATYENTITY_H #include "lineentity.h" // 三个平面上的辅助线 class AuxiliatyEntity: public Qt3DCore::QEntity { public: AuxiliatyEntity(Qt3DCore::QNode *parent = nullptr); AuxiliatyEntity(int auxiliaryLen1, int auxiliaryLen2, Qt3DCore::QNode *parent = nullptr); void set_xoy_AuxiliaryLen(int auxiliaryLen1,int auxiliaryLen2); void set_yoz_AuxiliaryLen(int auxiliaryLen1,int auxiliaryLen2); void set_xoz_AuxiliaryLen(int auxiliaryLen1,int auxiliaryLen2); private: // 辅助线对象 LineEntity *xoy_xAuxiliaryEntity = nullptr; LineEntity *xoy_yAuxiliaryEntity = nullptr; LineEntity *yoz_yAuxiliaryEntity = nullptr; LineEntity *yoz_zAuxiliaryEntity = nullptr; LineEntity *xoz_xAuxiliaryEntity = nullptr; LineEntity *xoz_zAuxiliaryEntity = nullptr; void xoy_updateAuxiliary(int auxiliaryLen1,int auxiliaryLen2); void yoz_updateAuxiliary(int auxiliaryLen1,int auxiliaryLen2); void xoz_updateAuxiliary(int auxiliaryLen1,int auxiliaryLen2); }; #endif // AUXILIATYENTITY_H
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2021/version1/myPoint.h
<reponame>SleepyLGod/Miscellaneous #pragma once #include <algorithm> #include <math.h> class myPoint; class myEdge { myPoint* to = nullptr; myEdge* next = nullptr; double distance = 0.0; public: void addNext(myPoint* to, double distance = 1.0); myEdge*& getNext(); myPoint*& getTo(); double& getDistance(); }; class myPoint { int x = 0, y = 0; int index = 0; myEdge* directEdgeFirst = nullptr, * everyEdgeFirst = nullptr; public: myPoint() {} myPoint(int x, int y, int index) :x(x), y(y), index(index) {} std::pair<int, int> getPosition(); int getIndex(); myEdge* getDirectEdgeFirst(); myEdge* getEveryEdgeFirst(); void setPosition(int x, int y); void setIndex(int index); void addDirectEdge(myPoint* p, double distance); void addEveryEdge(myPoint* p); }; double calculateDistance(myPoint a, myPoint b);
SleepyLGod/Miscellaneous
Sudoku/Sudoku_cpp_linux/Sudoku.h
/** * Suduku.h * 基于SAT的数独游戏求解程序 * * Created by 路昊东 on 2021/9/10 * Copyright ? 2021 路昊东. All rights reserved. */ #ifndef Sudoku_h #define Sudoku_h #include <stdio.h> #include <stdlib.h> #include "DPLL.h" #include "cnf.h" status Sudoku(void); FILE * CreateSudokuFile(void); // 创建数独问题转化为SAT问题后的cnf文件 status CreateSudoku(void); // 创建新的随机9*9数独终盘 status SolveSudoku(void); // 求解数独cnf文件并转化为数独终盘形式输出 status DigHole(int num); // 对已知数独终盘挖num个洞生成有唯一解的数独问题 status SudokuComplete(void); // 完善数独终盘 status SudokuExchange(void); // 基于cell元素交换原理增加一数独终盘的随机性 status CNFSudokuTableTransform(void); // 数独对应SAT变元表转化为二维数组 status SudokuTablePrint(void); // 输出数独盘 #endif /* Sudoku_h */
SleepyLGod/Miscellaneous
focusClimer/focusClimer 2.0/dobotmodel.h
<filename>focusClimer/focusClimer 2.0/dobotmodel.h #ifndef DOBOTMODEL_H #define DOBOTMODEL_H #include <Qt3DCore/QEntity> #include <QVector3D> #include <Qt3DCore/QTransform> #include <Qt3DExtras/QDiffuseSpecularMaterial> #include <Qt3DRender/QMesh> #include <iostream> #include "axesentity.h" // 本人Ubuntu20.04系统中的安装位置 // #include <eigen3/Eigen/Core> // #include <eigen3/Eigen/Geometry> // 本人win10下的安装位置 #include <Eigen/Core> #include <Eigen/Geometry> class DobotModel : public Qt3DCore::QEntity { public: DobotModel(Qt3DCore::QNode *parent = nullptr); void rotate_(float angle3); void rotate_quanternion(float x,float y,float z,float w); void move(float robot_x,float robot_y,float robot_z); void move_(float robot_x,float robot_y); private: QVector3D currentAngles; QVector3D currentPositions; QVector3D originalPositions; Qt3DCore::QTransform *BladeTransform; Qt3DCore::QTransform *robotTransform; Qt3DCore::QTransform *link1Transform; }; #endif // DOBOTMODEL_H
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version2/mapwidget.h
<filename>cpp_lab_2021/OtherVersions/lab5_2020/version2/mapwidget.h #ifndef MAPWIDGET_H #define MAPWIDGET_H #include <QGraphicsView> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QMouseEvent> class MapWidget : public QGraphicsView { Q_OBJECT public: MapWidget(); void readMap(); //读取地图信息 QPointF mapToMap(QPointF); //用于实现场景坐标系与地图坐标间的映射.以获得某点的经纬度 public slots: void slotZoom(int); //缩放信号 protected: //完成地图的显示功能 void drawBackground (QPainter *painter, const QRectF &rect); void mouseMoveEvent (QMouseEvent *event); private: QPixmap map; qreal zoom; QLabel *viewCoord; //视图目前坐标(以窗口左上为原点) QLabel *sceneCoord; //场景目前坐标(以场景中心为原点) QLabel *mapCoord; //地图目前坐标 double x1, y1; double x2, y2; }; #endif // MAPWIDGET_H
SleepyLGod/Miscellaneous
focusClimer/focusClimer 2.0/dataview.h
<reponame>SleepyLGod/Miscellaneous #ifndef DATAVIEW_H #define DATAVIEW_H #include <QMainWindow> #include <QWidget> #include <QtCharts> //必须这么设置 #include <QtDataVisualization> #include <QTimer> //using namespace QtDataVisualization; using QtDataVisualization::Q3DScatter; using QtDataVisualization::QScatter3DSeries; using QtDataVisualization::QScatterDataProxy; using QtDataVisualization::QAbstract3DSeries; using QtDataVisualization::QAbstract3DGraph; using QtDataVisualization::Q3DCamera; using QtDataVisualization::QScatterDataArray; using QtDataVisualization::Q3DTheme; //namespace Ui { //class dataview; //} class dataview : public QWidget { Q_OBJECT private: QWidget *graphContainer;// Q3DScatter *graph3D; //散点图 QScatter3DSeries *series; //散点序列 //初始化绘图 void iniScatterChart(); public: explicit dataview(QWidget *parent=nullptr); ~dataview(); private slots: void iniGraph3D(); void buildScatterChart(); private: // Ui::dataview *ui; QTimer* timer_t; qreal M; qreal S; qreal E; QScatterSeries *series0; QScatterSeries *series1; QScatterSeries *series2; QSplineSeries *seriesLine; QSplineSeries *seriesLine1; QSplineSeries *seriesLine2; QValueAxis *axisX ; QValueAxis *axisX1 ; QValueAxis *axisX2 ; QValueAxis *axisY; QValueAxis *axisY1; QValueAxis *axisY2; }; #endif // MAINWINDOW_H
SleepyLGod/Miscellaneous
focusClimer/focusClimer 2.0/filepath.h
// 获取JSON文件路径 #ifndef FILEPATH_H #define FILEPATH_H #define SettingFilePath "./setting.json" #define TrailFilePath "./optitrack_data.txt" #define fishEXE "F:\\ClimbotWizardProjOL20200526\\fish_show_finlish_EXE\\fish_submitted.exe" #endif // FILEPATH_H
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2021/version1/busMap.h
#pragma once #include <string> #include <fstream> #include <queue> #include "myPoint.h" using namespace std; class busMap { int mapLong = 0, mapWidth = 0, busStopsNumber = 0, busLinesNumber = 0, organizationsNumber = 0; int* eachBusLineNumber = nullptr; int** busLines = nullptr; myPoint** busStops = nullptr; string organizationNames[100]; pair<int,int> organizationPos[100]; int* path = nullptr; public: busMap(string busStopsFile, string busLinesFile, string orgnizationsFile); void showStopsAndLines(); int* findDirectPath(int startIndex, int endIndex); int* findEveryPath(int startIndex, int endIndex); int getBusLinesNumber() { return busLinesNumber; } int** getBusLines() { return busLines; } int* getEachBusLineNumber() { return eachBusLineNumber; } int getBusStopsNumber() { return busStopsNumber; } myPoint** getBusStops() { return busStops; } int getOrganizationsNumber() { return organizationsNumber; } string* getOrganizationNames() { return organizationNames; } pair<int,int>* getOrganizationPos() { return organizationPos; } ~busMap(); };
SleepyLGod/Miscellaneous
cpp_lab_2021/OtherVersions/lab5_2020/version1/ORGANIZATION.h
<gh_stars>1-10 #ifndef __Organization_Info_H__ #define __Organization_Info_H__ struct Organization_Info{ char name[100]; int site; int location[2]={0,}; int accessible_location_num=0; int accessible_location[10]={0,}; double accessible_location_distance[10]={0,}; }; #endif #ifndef __Organization_H__ #define __Organization_H__ class Organization{ public: const static int organization_num = 33; Organization_Info info[organization_num]; Organization(); ~Organization(){}; int which_site(int i); int which_site(char name[]); }; #endif
tonyhuang84/foxbms
embedded-software/mcu-primary/src/application/com/com.c
<filename>embedded-software/mcu-primary/src/application/com/com.c<gh_stars>0 /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file com.c * @author <NAME> * @date 28.08.2015 (date of creation) * @ingroup DRIVERS * @prefix COM * * @brief Driver for the COM module. * * Generic communication module which handles pre-defined user input and output. * In its current state it only uses UART/RS232 for communication * */ /*================== Includes =============================================*/ #include "com.h" #if BUILD_MODULE_ENABLE_COM == 1 #include "contactor.h" #include "mcu.h" #include "nvram_cfg.h" #include "os.h" #include "sox.h" #include <string.h> #include "rtc.h" #include "uart.h" #include "stdio.h" /*================== Macros and Definitions ===============================*/ #define TESTMODE_TIMEOUT 30000 #define com_receivedbyte uart_com_receivedbyte #define com_receive_slot uart_com_receive_slot /*================== Constant and Variable Definitions ====================*/ uint8_t printHelp = 0; static uint8_t com_testmode_enabled = 0; static uint32_t com_tickcount = 0; static RTC_Time_s com_Time; static RTC_Date_s com_Date; /*================== Function Prototypes ==================================*/ /*================== Function Implementations =============================*/ extern int _write(int fd, char *ptr, int len) { /* Write "len" of char from "ptr" * Return number of char written. * Check if file descriptor is in fact stdout * not neccessary but "good practice". */ if (fd == 1) { UART_uartWrite_intbuf((uint8_t*)ptr, len); } return len; } void COM_uartWrite(const uint8_t *source) { OS_TaskEnter_Critical(); UART_vWrite(source); OS_TaskExit_Critical(); } void UART_uartWrite_intbuf(const uint8_t *source, uint16_t length) { OS_TaskEnter_Critical(); UART_vWrite_intbuf(source, length); OS_TaskExit_Critical(); } void COM_printTimeAndDate(void) { /* Get time and date */ RTC_getTime(&com_Time); RTC_getDate(&com_Date); DEBUG_PRINTF(("Date and Time: 20%02d.%02d.%02d - %02d:%02d:%02d\r\n", com_Date.Year, com_Date.Month, com_Date.Date, com_Time.Hours, com_Time.Minutes, com_Time.Seconds)); } void COM_StartupInfo(void) { /* Get RCC Core Reset Register */ uint32_t tmp = main_state.CSR; DEBUG_PRINTF(("........................................\r\n")); DEBUG_PRINTF(("System starting...\r\n")); DEBUG_PRINTF(("RCC Core Reset Register: 0x%x\r\n", (unsigned int)tmp)); /* Print time and date */ COM_printTimeAndDate(); DEBUG_PRINTF(("Runtime: %02dh %02dm %02ds\r\n", os_timer.Timer_h, os_timer.Timer_min, os_timer.Timer_sec)); } void COM_printHelpCommand(void) { static uint8_t cnt = 0; if (printHelp == 0) return; switch (cnt) { case 0: DEBUG_PRINTF(("\r\nFollowing commands are available: :\r\n\r\n")); DEBUG_PRINTF(("==================== ========================================================================================================\r\n")); DEBUG_PRINTF(("Command Description\r\n")); DEBUG_PRINTF(("==================== ========================================================================================================\r\n")); break; case 1: DEBUG_PRINTF(("help get available command list\r\n")); DEBUG_PRINTF(("gettime get system time\r\n")); DEBUG_PRINTF(("getruntime get runtime since last reset\r\n")); DEBUG_PRINTF(("getoperatingtime get total operating time\r\n")); break; case 2: DEBUG_PRINTF(("printdiaginfo get diagnosis entries of DIAG module (entries can only be printed once)\r\n")); DEBUG_PRINTF(("printcontactorinfo get contactor information (number of switches/hard switches) (entries can only be printed once)\r\n")); DEBUG_PRINTF(("teston enable testmode, testmode will be disabled after a predefined timeout of 30s when no new command is sent\r\n")); break; case 3: DEBUG_PRINTF(("==================== ========================================================================================================\r\n")); DEBUG_PRINTF(("\r\nFollowing commands are only available during enabled testmode:\r\n\r\n")); DEBUG_PRINTF(("========================== ==========================================================================================\r\n")); break; case 4: DEBUG_PRINTF(("Command Description\r\n")); DEBUG_PRINTF(("========================== ==========================================================================================\r\n")); DEBUG_PRINTF(("testoff disable testmode\r\n")); break; case 5: DEBUG_PRINTF(("settime YY MM DD HH MM SS set mcu time and date (YY-year, MM-month, DD-date, HH-hours, MM-minutes, SS-seconds)\r\n")); DEBUG_PRINTF(("reset enforces complete software reset using HAL_NVIC_SystemReset()\r\n")); DEBUG_PRINTF(("watchdogtest performs watchdog test, watchdog timeout results in system reset (predefined 1s)\r\n")); break; case 6: DEBUG_PRINTF(("setsoc xxx.xxx set SOC value (000.000%% - 100.000%%)\r\n")); DEBUG_PRINTF(("ceX enables contactor number X (only possible if BMS is in no error state)\r\n")); DEBUG_PRINTF(("cdX disables contactor number X (only possible if BMS is in no error state)\r\n")); break; case 7: #if defined(ENABLE_THIRD_PARTY) COM_ThirdParty_printHelpCommand(&cnt); #else DEBUG_PRINTF(("========================== ==========================================================================================\r\n")); #endif break; default: break; } cnt++; if (cnt == 8) { printHelp = 0; cnt = 0; } } void COM_Decoder(void) { /* Command Received - Replace Carrier Return with null character */ if (com_receivedbyte[com_receive_slot - 1] == '\r') { com_receivedbyte[com_receive_slot - 1] = '\0'; /* ENABLE TESTMODE */ if (strcmp(com_receivedbyte, "teston") == 0) { /* Set timeout */ com_tickcount = OS_getOSSysTick(); if (!com_testmode_enabled) { /* Enable testmode */ com_testmode_enabled = 1; DEBUG_PRINTF(("Testmode enabled!\r\n")); } else { /* Testmode already enabled */ DEBUG_PRINTF(("Testmode already enabled!\r\n")); } /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); return; } /* PRINT help command */ if (strcmp(com_receivedbyte, "help") == 0) { /* Print contactor info */ printHelp = 1; /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); return; } /* PRINT CONTACTOR INFO */ if (strcmp(com_receivedbyte, "printcontactorinfo") == 0) { /* Print contactor info */ DIAG_PrintContactorInfo(); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); return; } /* PRINT DIAG INFO */ if (strcmp(com_receivedbyte, "printdiaginfo") == 0) { /* Print diag info */ DIAG_PrintErrors(); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); return; } /* GETTIME */ if (strcmp(com_receivedbyte, "gettime") == 0) { /* Print time and date */ COM_printTimeAndDate(); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); return; } /* Get runtime */ if (strcmp(com_receivedbyte, "getruntime") == 0) { /* Print runtime */ DEBUG_PRINTF(("Runtime: %02dh %02dm %02ds\r\n", os_timer.Timer_h, os_timer.Timer_min, os_timer.Timer_sec)); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); return; } /* Get operating time */ if (strcmp(com_receivedbyte, "getoperatingtime") == 0) { DEBUG_PRINTF(("Operating time: %03dd %02dh %02dm %02ds\r\n", bkpsram_op_hours.Timer_d, bkpsram_op_hours.Timer_h, bkpsram_op_hours.Timer_min, bkpsram_op_hours.Timer_sec)); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); return; } /* Command received and testmode enabled */ if (com_testmode_enabled) { /* DISABLE TESTMODE */ if (strcmp(com_receivedbyte, "testoff") == 0) { com_testmode_enabled = 0; DEBUG_PRINTF(("Testmode disabled on request!\r\n")); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; return; } /* SETTIME */ /* if (strcmp(com_receivedbyte, "settime") == 0) {*/ if (com_receivedbyte[0] == 's' && com_receivedbyte[1] == 'e' && com_receivedbyte[2] == 't' && com_receivedbyte[3] == 't' && com_receivedbyte[4] == 'i' && com_receivedbyte[5] == 'm' && com_receivedbyte[6] == 'e') { /* Command length = 24, +1 for \0, +1 cause index always one step ahead */ if (com_receive_slot == 26) { /* Set time and date only if command length is like expected */ uint8_t value, tmp10, tmp1, retVal = 0; /* Calculate year */ tmp10 = com_receivedbyte[8] - '0'; tmp1 = com_receivedbyte[9] - '0'; value = (tmp10 * 10) + tmp1; if (IS_RTC_YEAR(value)) /* Check if value is valid */ com_Date.Year = value; else retVal = 0xFF; /* Calculate month */ tmp10 = com_receivedbyte[11] - '0'; tmp1 = com_receivedbyte[12] - '0'; value = (tmp10 * 10) + tmp1; if (IS_RTC_MONTH(value)) /* Check if value is valid */ com_Date.Month = value; else retVal = 0xFF; /* Calculate day */ tmp10 = com_receivedbyte[14] - '0'; tmp1 = com_receivedbyte[15] - '0'; value = (tmp10 * 10) + tmp1; if (IS_RTC_DATE(value)) /* Check if value is valid */ com_Date.Date = value; else retVal = 0xFF; /* Calculate hours */ tmp10 = com_receivedbyte[17] - '0'; tmp1 = com_receivedbyte[18] - '0'; value = (tmp10 * 10) + tmp1; if (IS_RTC_HOUR24(value)) { /* Check if value is valid */ com_Time.Hours = value; } else { retVal = 0xFF; } /* Calculate minutes */ tmp10 = com_receivedbyte[20] - '0'; tmp1 = com_receivedbyte[21] - '0'; value = (tmp10 * 10) + tmp1; if (IS_RTC_MINUTES(value)) { /* Check if value is valid */ com_Time.Minutes = value; } else { retVal = 0xFF; } /* Calculate seconds */ tmp10 = com_receivedbyte[23] - '0'; tmp1 = com_receivedbyte[24] - '0'; value = (tmp10 * 10) + tmp1; if (IS_RTC_SECONDS(value)) { /* Check if value is valid */ com_Time.Seconds = value; } else { retVal = 0xFF; } if (retVal == 0) { /* Set time and date */ RTC_setTime(&com_Time); RTC_setDate(&com_Date); DEBUG_PRINTF(("Time and date set!\r\n")); } else { /* Print error message */ DEBUG_PRINTF(("Invalid parameter!\r\n%.25s\r\n", com_receivedbyte)); } } else { /* Print error message */ DEBUG_PRINTF(("Invalid parameter length!\r\n")); DEBUG_PRINTF(("%.*s\r\n", com_receive_slot, com_receivedbyte)); } /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); return; } /* RESET */ if (strcmp(com_receivedbyte, "reset") == 0) { DEBUG_PRINTF(("Software reset!\r\n")); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; HAL_NVIC_SystemReset(); return; } if (strcmp(com_receivedbyte, "watchdogtest") == 0) { DEBUG_PRINTF(("WDG")); /* DEBUG_PRINTF(("\r\n"); */ /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; OS_taskDelay(1); /* disable global interrupt, no saving of interrupt status because of follwing reset */ (void)MCU_DisableINT(); while (1) { /* stop system and wait for watchdog reset*/ } return; } /* Set soc */ if (com_receivedbyte[0] == 's' && com_receivedbyte[1] == 'e' && com_receivedbyte[2] == 't' && com_receivedbyte[3] == 's' && com_receivedbyte[4] == 'o' && com_receivedbyte[5] == 'c') { /* Set SOC */ /* Command length = 14, +1 for \0 and +1 cause index always one step ahead "setsoc xxx.xxx"*/ if (com_receive_slot == 15) { /* Set time and date only if command length is like expected */ uint8_t tmp100 = 0, tmp10 = 0, tmp1 = 0; float value = 0; /* Calculate year */ tmp100 = com_receivedbyte[7] - '0'; tmp10 = com_receivedbyte[8] - '0'; tmp1 = com_receivedbyte[9] - '0'; value = (tmp100 * 100) + (tmp10 * 10) + tmp1; tmp1 = com_receivedbyte[11] - '0'; tmp10 = com_receivedbyte[12] - '0'; tmp100 = com_receivedbyte[13] - '0'; value = value + (tmp1 * 0.1) + (tmp10 * 0.01) + (tmp100 * 0.001); if (0 <= value && value <= 100) SOC_SetValue(value, value, value); } } /* SWITCH CONTACTORS */ switch (com_receivedbyte[0]) { #if BUILD_MODULE_ENABLE_CONTACTOR == 1 case 'c': {} /* added to get rid of compile error */ /* Convert ascii number to int */ uint8_t contNumber; contNumber = com_receivedbyte[2] - '0'; /* Switch contactor */ if ((0 <= contNumber) && (contNumber <= BS_NR_OF_CONTACTORS)) { /* Close contactor */ if (com_receivedbyte[1] == 'e') { DEBUG_PRINTF(("Contactor %d", contNumber)); CONT_SetContactorState(contNumber, CONT_SWITCH_ON); DEBUG_PRINTF((" enabled\r\n")); } else if (com_receivedbyte[1] == 'd') { /* Open contactor */ DEBUG_PRINTF(("Contactor %d", contNumber)); CONT_SetContactorState(contNumber, CONT_SWITCH_OFF); DEBUG_PRINTF((" disabled\r\n")); } else { /* Invalid command */ DEBUG_PRINTF(("Invalid command!\r\n")); } } else { /* Invalid contactor number */ uint8_t a = BS_NR_OF_CONTACTORS; DEBUG_PRINTF(("Invalid contactor number! Only %d contactors are connected! \r\n", a)); } break; #endif default: DEBUG_PRINTF(("Invalid command!\r\n%s\r\n", com_receivedbyte)); break; } /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; return; } #if defined(ENABLE_THIRD_PARTY) if (COM_ThirdParty_Decoder(com_receivedbyte) == 0) { /* Reset timeout to TESTMODE_TIMEOUT */ com_tickcount = OS_getOSSysTick(); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; return; } #endif /* Invalid command */ DEBUG_PRINTF(("Invalid command!\r\n%s\r\n", com_receivedbyte)); /* Clear received command */ memset(com_receivedbyte, 0, sizeof(com_receivedbyte)); com_receive_slot = 0; } /* Timed out --> disable testmode */ if (com_tickcount + TESTMODE_TIMEOUT < OS_getOSSysTick() && com_testmode_enabled) { com_testmode_enabled = 0; DEBUG_PRINTF(("Testmode disabled on timeout!\r\n")); } } #endif /* BUILD_MODULE_ENABLE_COM */
tonyhuang84/foxbms
embedded-software/mcu-primary/src/module/config/cansignal_cfg.h
<filename>embedded-software/mcu-primary/src/module/config/cansignal_cfg.h /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file cansignal_cfg.h * @author foxBMS Team * @date 16.09.2015 (date of creation) * @ingroup DRIVERS_CONF * @prefix CANS * * @brief Headers for the configuration of the messages and signal settings for the CAN driver * */ #ifndef CANSIGNAL_CFG_H_ #define CANSIGNAL_CFG_H_ /*================== Includes =============================================*/ #include "general.h" #include "can_cfg.h" /*================== Macros and Definitions ===============================*/ /** * @ingroup CONFIG_CANSIGNAL * task timeslot where the CANS main function is called. Repetition time of periodic CAN messages must be multiple of this * \par Type: * select(3) * \par Default: * 1 */ /* #define CANS_TICK_MS 1 */ #define CANS_TICK_MS 10 /* #define CANS_TICK_MS 100 */ /** * Delay in ms after which it is considered the current sensor is not responding anymore. */ #define CANS_SENSOR_RESPONSE_TIMEOUT_MS 100 /** * symbolic names for TX CAN messages. Every used TX message needs to get an individual message name. */ typedef enum { /* Insert here symbolic names for CAN0 messages */ CAN0_MSG_SystemState_0, /*!< BMS general state 0 */ CAN0_MSG_SystemState_1, /*!< BMS general state 1 */ CAN0_MSG_SystemState_2, /*!< BMS general state 2 */ CAN0_MSG_SlaveState_0, /*!< Slave state 0 */ CAN0_MSG_SlaveState_1, /*!< Slave state 1 */ CAN0_MSG_RecOperatingCurrent, /*!< Max allowed charge/discharge current */ CAN0_MSG_SOP, /*!< SOP */ CAN0_MSG_SOC, /*!< SOC */ CAN0_MSG_SOH, /*!< SOH */ CAN0_MSG_SOE, /*!< SOE */ CAN0_MSG_MinMaxCellVolt, /*!< min/max/mean cell voltages */ CAN0_MSG_SOV, /*!< SOV */ CAN0_MSG_MinMaxCellTemp, /*!< min/max/mean cell temperatures */ CAN0_MSG_Tempering, /*!< Tempering */ CAN0_MSG_Insulation, /*!< Insulation */ CAN0_MSG_Power_0, /*!< Moving average power 1s 5s */ CAN0_MSG_Power_1, /*!< Moving average power 10s 30s */ CAN0_MSG_Power_2, /*!< Moving average power 60s configurable duration */ CAN0_MSG_Current_0, /*!< Moving average current 1s 5s */ CAN0_MSG_Current_1, /*!< Moving average current 10s 30s */ CAN0_MSG_Current_2, /*!< Moving average current 60s configurable duration */ CAN0_MSG_PackVoltage, /*!< Pack voltage */ CAN0_MSG_Mod0_Cellvolt_0, /*!< Module 0 Cell voltages 0-2 */ CAN0_MSG_Mod0_Cellvolt_1, /*!< Module 0 Cell voltages 3-5 */ CAN0_MSG_Mod0_Cellvolt_2, /*!< Module 0 Cell voltages 6-8 */ CAN0_MSG_Mod0_Cellvolt_3, /*!< Module 0 Cell voltages 9-11 */ CAN0_MSG_Mod0_Celltemp_0, /*!< Module 0 Cell temperatures 0-2 */ CAN0_MSG_Mod0_Celltemp_1, /*!< Module 0 Cell temperatures 3-5 */ CAN0_MSG_Mod0_Celltemp_2, /*!< Module 0 Cell temperatures 6-8 */ CAN0_MSG_Mod0_Celltemp_3, /*!< Module 0 Cell temperatures 9-11 */ CAN0_MSG_Mod1_Cellvolt_0, /*!< Module 1 Cell voltages 0-2 */ CAN0_MSG_Mod1_Cellvolt_1, /*!< Module 1 Cell voltages 3-5 */ CAN0_MSG_Mod1_Cellvolt_2, /*!< Module 1 Cell voltages 6-8 */ CAN0_MSG_Mod1_Cellvolt_3, /*!< Module 1 Cell voltages 9-11 */ CAN0_MSG_Mod1_Celltemp_0, /*!< Module 1 Cell temperatures 0-2 */ CAN0_MSG_Mod1_Celltemp_1, /*!< Module 1 Cell temperatures 3-5 */ CAN0_MSG_Mod1_Celltemp_2, /*!< Module 1 Cell temperatures 6-8 */ CAN0_MSG_Mod1_Celltemp_3, /*!< Module 1 Cell temperatures 9-11 */ CAN0_MSG_Mod2_Cellvolt_0, /*!< Module 2 Cell voltages 0-2 */ CAN0_MSG_Mod2_Cellvolt_1, /*!< Module 2 Cell voltages 3-5 */ CAN0_MSG_Mod2_Cellvolt_2, /*!< Module 2 Cell voltages 6-8 */ CAN0_MSG_Mod2_Cellvolt_3, /*!< Module 2 Cell voltages 9-11 */ CAN0_MSG_Mod2_Celltemp_0, /*!< Module 2 Cell temperatures 0-2 */ CAN0_MSG_Mod2_Celltemp_1, /*!< Module 2 Cell temperatures 3-5 */ CAN0_MSG_Mod2_Celltemp_2, /*!< Module 2 Cell temperatures 6-8 */ CAN0_MSG_Mod2_Celltemp_3, /*!< Module 2 Cell temperatures 9-11 */ CAN0_MSG_Mod3_Cellvolt_0, /*!< Module 3 Cell voltages 0-2 */ CAN0_MSG_Mod3_Cellvolt_1, /*!< Module 3 Cell voltages 3-5 */ CAN0_MSG_Mod3_Cellvolt_2, /*!< Module 3 Cell voltages 6-8 */ CAN0_MSG_Mod3_Cellvolt_3, /*!< Module 3 Cell voltages 9-11 */ CAN0_MSG_Mod3_Celltemp_0, /*!< Module 3 Cell temperatures 0-2 */ CAN0_MSG_Mod3_Celltemp_1, /*!< Module 3 Cell temperatures 3-5 */ CAN0_MSG_Mod3_Celltemp_2, /*!< Module 3 Cell temperatures 6-8 */ CAN0_MSG_Mod3_Celltemp_3, /*!< Module 3 Cell temperatures 9-11 */ CAN0_MSG_Mod4_Cellvolt_0, /*!< Module 4 Cell voltages 0-2 */ CAN0_MSG_Mod4_Cellvolt_1, /*!< Module 4 Cell voltages 3-5 */ CAN0_MSG_Mod4_Cellvolt_2, /*!< Module 4 Cell voltages 6-8 */ CAN0_MSG_Mod4_Cellvolt_3, /*!< Module 4 Cell voltages 9-11 */ CAN0_MSG_Mod4_Celltemp_0, /*!< Module 4 Cell temperatures 0-2 */ CAN0_MSG_Mod4_Celltemp_1, /*!< Module 4 Cell temperatures 3-5 */ CAN0_MSG_Mod4_Celltemp_2, /*!< Module 4 Cell temperatures 6-8 */ CAN0_MSG_Mod4_Celltemp_3, /*!< Module 4 Cell temperatures 9-11 */ CAN0_MSG_Mod5_Cellvolt_0, /*!< Module 5 Cell voltages 0-2 */ CAN0_MSG_Mod5_Cellvolt_1, /*!< Module 5 Cell voltages 3-5 */ CAN0_MSG_Mod5_Cellvolt_2, /*!< Module 5 Cell voltages 6-8 */ CAN0_MSG_Mod5_Cellvolt_3, /*!< Module 5 Cell voltages 9-11 */ CAN0_MSG_Mod5_Celltemp_0, /*!< Module 5 Cell temperatures 0-2 */ CAN0_MSG_Mod5_Celltemp_1, /*!< Module 5 Cell temperatures 3-5 */ CAN0_MSG_Mod5_Celltemp_2, /*!< Module 5 Cell temperatures 6-8 */ CAN0_MSG_Mod5_Celltemp_3, /*!< Module 5 Cell temperatures 9-11 */ CAN0_MSG_Mod6_Cellvolt_0, /*!< Module 6 Cell voltages 0-2 */ CAN0_MSG_Mod6_Cellvolt_1, /*!< Module 6 Cell voltages 3-5 */ CAN0_MSG_Mod6_Cellvolt_2, /*!< Module 6 Cell voltages 6-8 */ CAN0_MSG_Mod6_Cellvolt_3, /*!< Module 6 Cell voltages 9-11 */ CAN0_MSG_Mod6_Celltemp_0, /*!< Module 6 Cell temperatures 0-2 */ CAN0_MSG_Mod6_Celltemp_1, /*!< Module 6 Cell temperatures 3-5 */ CAN0_MSG_Mod6_Celltemp_2, /*!< Module 6 Cell temperatures 6-8 */ CAN0_MSG_Mod6_Celltemp_3, /*!< Module 6 Cell temperatures 9-11 */ CAN0_MSG_Mod7_Cellvolt_0, /*!< Module 7 Cell voltages 0-2 */ CAN0_MSG_Mod7_Cellvolt_1, /*!< Module 7 Cell voltages 3-5 */ CAN0_MSG_Mod7_Cellvolt_2, /*!< Module 7 Cell voltages 6-8 */ CAN0_MSG_Mod7_Cellvolt_3, /*!< Module 7 Cell voltages 9-11 */ CAN0_MSG_Mod7_Celltemp_0, /*!< Module 7 Cell temperatures 0-2 */ CAN0_MSG_Mod7_Celltemp_1, /*!< Module 7 Cell temperatures 3-5 */ CAN0_MSG_Mod7_Celltemp_2, /*!< Module 7 Cell temperatures 6-8 */ CAN0_MSG_Mod7_Celltemp_3, /*!< Module 7 Cell temperatures 9-11 */ #ifdef CAN_ISABELLENHUETTE_TRIGGERED CAN0_MSG_BMS_CurrentTrigger, /*!< Cell Voltages Max Min Average */ #endif #if defined(ITRI_MOD_5) CAN0_MSG_Mod8_Cellvolt_0, //!< Module 8 Cell voltages 0-2 CAN0_MSG_Mod8_Cellvolt_1, CAN0_MSG_Mod8_Cellvolt_2, CAN0_MSG_Mod8_Cellvolt_3, CAN0_MSG_Mod8_Celltemp_0, //!< Module 8 Cell temperatures 0-2 CAN0_MSG_Mod8_Celltemp_1, CAN0_MSG_Mod8_Celltemp_2, CAN0_MSG_Mod8_Celltemp_3, CAN0_MSG_Mod9_Cellvolt_0, //!< Module 9 Cell voltages 0-2 CAN0_MSG_Mod9_Cellvolt_1, CAN0_MSG_Mod9_Cellvolt_2, CAN0_MSG_Mod9_Cellvolt_3, CAN0_MSG_Mod9_Celltemp_0, //!< Module 9 Cell temperatures 0-2 CAN0_MSG_Mod9_Celltemp_1, CAN0_MSG_Mod9_Celltemp_2, CAN0_MSG_Mod9_Celltemp_3, CAN0_MSG_Mod10_Cellvolt_0, //!< Module 10 Cell voltages 0-2 CAN0_MSG_Mod10_Cellvolt_1, CAN0_MSG_Mod10_Cellvolt_2, CAN0_MSG_Mod10_Cellvolt_3, CAN0_MSG_Mod10_Celltemp_0, //!< Module 10 Cell temperatures 0-2 CAN0_MSG_Mod10_Celltemp_1, CAN0_MSG_Mod10_Celltemp_2, CAN0_MSG_Mod10_Celltemp_3, CAN0_MSG_Mod11_Cellvolt_0, //!< Module 11 Cell voltages 0-2 CAN0_MSG_Mod11_Cellvolt_1, CAN0_MSG_Mod11_Cellvolt_2, CAN0_MSG_Mod11_Cellvolt_3, CAN0_MSG_Mod11_Celltemp_0, //!< Module 11 Cell temperatures 0-2 CAN0_MSG_Mod11_Celltemp_1, CAN0_MSG_Mod11_Celltemp_2, CAN0_MSG_Mod11_Celltemp_3, CAN0_MSG_Mod12_Cellvolt_0, //!< Module 12 Cell voltages 0-2 CAN0_MSG_Mod12_Cellvolt_1, CAN0_MSG_Mod12_Cellvolt_2, CAN0_MSG_Mod12_Cellvolt_3, CAN0_MSG_Mod12_Celltemp_0, //!< Module 12 Cell temperatures 0-2 CAN0_MSG_Mod12_Celltemp_1, CAN0_MSG_Mod12_Celltemp_2, CAN0_MSG_Mod12_Celltemp_3, CAN0_MSG_Mod13_Cellvolt_0, //!< Module 13 Cell voltages 0-2 CAN0_MSG_Mod13_Cellvolt_1, CAN0_MSG_Mod13_Cellvolt_2, CAN0_MSG_Mod13_Cellvolt_3, CAN0_MSG_Mod13_Celltemp_0, //!< Module 13 Cell temperatures 0-2 CAN0_MSG_Mod13_Celltemp_1, CAN0_MSG_Mod13_Celltemp_2, CAN0_MSG_Mod13_Celltemp_3, CAN0_MSG_Mod14_Cellvolt_0, //!< Module 14 Cell voltages 0-2 CAN0_MSG_Mod14_Cellvolt_1, CAN0_MSG_Mod14_Cellvolt_2, CAN0_MSG_Mod14_Cellvolt_3, CAN0_MSG_Mod14_Celltemp_0, //!< Module 14 Cell temperatures 0-2 CAN0_MSG_Mod14_Celltemp_1, CAN0_MSG_Mod14_Celltemp_2, CAN0_MSG_Mod14_Celltemp_3, CAN0_MSG_Mod15_Cellvolt_0, //!< Module 15 Cell voltages 0-2 CAN0_MSG_Mod15_Cellvolt_1, CAN0_MSG_Mod15_Cellvolt_2, CAN0_MSG_Mod15_Cellvolt_3, CAN0_MSG_Mod15_Celltemp_0, //!< Module 15 Cell temperatures 0-2 CAN0_MSG_Mod15_Celltemp_1, CAN0_MSG_Mod15_Celltemp_2, CAN0_MSG_Mod15_Celltemp_3, CAN0_MSG_Mod16_Cellvolt_0, //!< Module 16 Cell voltages 0-2 CAN0_MSG_Mod16_Cellvolt_1, CAN0_MSG_Mod16_Cellvolt_2, CAN0_MSG_Mod16_Cellvolt_3, CAN0_MSG_Mod16_Celltemp_0, //!< Module 16 Cell temperatures 0-2 CAN0_MSG_Mod16_Celltemp_1, CAN0_MSG_Mod16_Celltemp_2, CAN0_MSG_Mod16_Celltemp_3, CAN0_MSG_Mod17_Cellvolt_0, //!< Module 17 Cell voltages 0-2 CAN0_MSG_Mod17_Cellvolt_1, CAN0_MSG_Mod17_Cellvolt_2, CAN0_MSG_Mod17_Cellvolt_3, CAN0_MSG_Mod17_Celltemp_0, //!< Module 17 Cell temperatures 0-2 CAN0_MSG_Mod17_Celltemp_1, CAN0_MSG_Mod17_Celltemp_2, CAN0_MSG_Mod17_Celltemp_3, CAN0_MSG_Mod18_Cellvolt_0, //!< Module 18 Cell voltages 0-2 CAN0_MSG_Mod18_Cellvolt_1, CAN0_MSG_Mod18_Cellvolt_2, CAN0_MSG_Mod18_Cellvolt_3, CAN0_MSG_Mod18_Celltemp_0, //!< Module 18 Cell temperatures 0-2 CAN0_MSG_Mod18_Celltemp_1, CAN0_MSG_Mod18_Celltemp_2, CAN0_MSG_Mod18_Celltemp_3, CAN0_MSG_Mod19_Cellvolt_0, //!< Module 19 Cell voltages 0-2 CAN0_MSG_Mod19_Cellvolt_1, CAN0_MSG_Mod19_Cellvolt_2, CAN0_MSG_Mod19_Cellvolt_3, CAN0_MSG_Mod19_Celltemp_0, //!< Module 19 Cell temperatures 0-2 CAN0_MSG_Mod19_Celltemp_1, CAN0_MSG_Mod19_Celltemp_2, CAN0_MSG_Mod19_Celltemp_3, CAN0_MSG_Mod20_Cellvolt_0, //!< Module 20 Cell voltages 0-2 CAN0_MSG_Mod20_Cellvolt_1, CAN0_MSG_Mod20_Cellvolt_2, CAN0_MSG_Mod20_Cellvolt_3, CAN0_MSG_Mod20_Celltemp_0, //!< Module 20 Cell temperatures 0-2 CAN0_MSG_Mod20_Celltemp_1, CAN0_MSG_Mod20_Celltemp_2, CAN0_MSG_Mod20_Celltemp_3, CAN0_MSG_Mod21_Cellvolt_0, //!< Module 21 Cell voltages 0-2 CAN0_MSG_Mod21_Cellvolt_1, CAN0_MSG_Mod21_Cellvolt_2, CAN0_MSG_Mod21_Cellvolt_3, CAN0_MSG_Mod21_Celltemp_0, //!< Module 21 Cell temperatures 0-2 CAN0_MSG_Mod21_Celltemp_1, CAN0_MSG_Mod21_Celltemp_2, CAN0_MSG_Mod21_Celltemp_3, CAN0_MSG_Mod22_Cellvolt_0, //!< Module 22 Cell voltages 0-2 CAN0_MSG_Mod22_Cellvolt_1, CAN0_MSG_Mod22_Cellvolt_2, CAN0_MSG_Mod22_Cellvolt_3, CAN0_MSG_Mod22_Celltemp_0, //!< Module 22 Cell temperatures 0-2 CAN0_MSG_Mod22_Celltemp_1, CAN0_MSG_Mod22_Celltemp_2, CAN0_MSG_Mod22_Celltemp_3, CAN0_MSG_Mod23_Cellvolt_0, //!< Module 23 Cell voltages 0-2 CAN0_MSG_Mod23_Cellvolt_1, CAN0_MSG_Mod23_Cellvolt_2, CAN0_MSG_Mod23_Cellvolt_3, CAN0_MSG_Mod23_Celltemp_0, //!< Module 23 Cell temperatures 0-2 CAN0_MSG_Mod23_Celltemp_1, CAN0_MSG_Mod23_Celltemp_2, CAN0_MSG_Mod23_Celltemp_3, CAN0_MSG_Mod24_Cellvolt_0, //!< Module 24 Cell voltages 0-2 CAN0_MSG_Mod24_Cellvolt_1, CAN0_MSG_Mod24_Cellvolt_2, CAN0_MSG_Mod24_Cellvolt_3, CAN0_MSG_Mod24_Celltemp_0, //!< Module 24 Cell temperatures 0-2 CAN0_MSG_Mod24_Celltemp_1, CAN0_MSG_Mod24_Celltemp_2, CAN0_MSG_Mod24_Celltemp_3, #endif // ITRI_MOD_5 /* Insert here symbolic names for CAN1 messages */ } CANS_messagesTx_e; /** * symbolic names for RX CAN messages */ typedef enum { /* Insert here symbolic names for CAN0 messages */ CAN0_MSG_StateRequest, /*!< state request */ CAN0_MSG_SW_RESET, /*!< can message for SW reset */ CAN0_MSG_IVT_Current, /*!< current sensing */ CAN0_MSG_IVT_Voltage_1, /*!< current sensor voltage 1 */ CAN0_MSG_IVT_Voltage_2, /*!< current sensor voltage 2 */ CAN0_MSG_IVT_Voltage_3, /*!< current sensor voltage 3 */ CAN0_MSG_IVT_Temperature, /*!< current sensor temperature */ CAN0_MSG_IVT_Power, /*!< current sensor power */ CAN0_MSG_IVT_CoulombCount, /*!< current sensor C-C */ CAN0_MSG_IVT_EnergyCount, /*!< current sensor E-C */ CAN0_MSG_DEBUG, /*!< debug messages */ CAN0_MSG_GetReleaseVersion, /*!< Get SW release version */ /* Insert here symbolic names for CAN1 messages */ } CANS_messagesRx_e; /** * symbolic names for CAN0 transmission signals */ typedef enum { CAN0_SIG_GS0_general_error, /* 0:good, 1:error */ CAN0_SIG_GS0_current_state, /* currently no used */ CAN0_SIG_GS0_error_overtemp_charge, /* 0:good, 1:error */ CAN0_SIG_GS0_error_undertemp_charge, /* 0:good, 1:error */ CAN0_SIG_GS0_error_overtemp_discharge, /* 0:good, 1:error */ CAN0_SIG_GS0_error_undertemp_discharge, /* 0:good, 1:error */ CAN0_SIG_GS0_error_overcurrent_charge, /* 0:good, 1:error */ CAN0_SIG_GS0_error_overcurrent_discharge, /* 0:good, 1:error */ CAN0_SIG_GS1_error_overvoltage, /* 0:good, 1:error */ CAN0_SIG_GS1_error_undervoltage, /* 0:good, 1:error */ CAN0_SIG_GS1_error_temperature_MCU0, /* 0:good, 1:error */ CAN0_SIG_GS1_error_contactor, /* 0:good, 1:error */ CAN0_SIG_GS1_error_selftest, /* 0:good, 1:error */ CAN0_SIG_GS1_error_cantiming, /* 0:good, 1:error */ CAN0_SIG_GS1_current_sensor, /* 0:good, 1:error */ CAN0_SIG_GS1_balancing_active, /* 0:off, 1:on */ CAN0_SIG_GS2_state_cont_interlock, /* bitfield 0:off, 1:on */ CAN0_SIG_GS2_error_insulation, /* 0: good, 1: error */ CAN0_SIG_GS2_fuse_state, /* 0: fuse intact, 1: fuse tripped */ CAN0_SIG_GS2_lowCoinCellVolt, /* 0: okay, else: low voltage */ CAN0_SIG_GS2_error_openWire, /* 0: okay, 1: open wire detected */ CAN0_SIG_GS2_daisyChain, /* 0: okay, else: error */ CAN0_SIG_SS0_states, /* 0: good, 1: error */ CAN0_SIG_SS1_states, /* 0: good, 1: error */ CAN0_SIG_RecChargeCurrent, CAN0_SIG_RecChargeCurrent_Peak, CAN0_SIG_RecDischargeCurrent, CAN0_SIG_RecDischargeCurrent_Peak, CAN0_SIG_MaxChargePower, CAN0_SIG_MaxChargePower_Peak, CAN0_SIG_MaxDischargePower, CAN0_SIG_MaxDischargePower_Peak, CAN0_SIG_SOC_mean, CAN0_SIG_SOC_min, CAN0_SIG_SOC_max, CAN0_SIG_SOH_mean, CAN0_SIG_SOH_min, CAN0_SIG_SOH_max, CAN0_SIG_SOE, CAN0_SIG_RemainingEnergy, CAN0_SIG_Cellvolt_mean, CAN0_SIG_Cellvolt_min, CAN0_SIG_Cellvolt_max, CAN0_SIG_ModNumber_volt_min, CAN0_SIG_ModNumber_volt_max, CAN0_SIG_SOV, CAN0_SIG_Celltemp_mean, CAN0_SIG_Celltemp_min, CAN0_SIG_Celltemp_max, CAN0_SIG_ModNumber_temp_min, CAN0_SIG_ModNumber_temp_max, CAN0_SIG_CoolingNeeded, CAN0_SIG_HeatingNeeded, CAN0_SIG_TemperingDemand, CAN0_SIG_InsulationStatus, CAN0_SIG_InsulationValue, CAN0_SIG_MovAverage_Power_1s, CAN0_SIG_MovAverage_Power_5s, CAN0_SIG_MovAverage_Power_10s, CAN0_SIG_MovAverage_Power_30s, CAN0_SIG_MovAverage_Power_60s, CAN0_SIG_MovAverage_Power_config, CAN0_SIG_MovAverage_Current_1s, CAN0_SIG_MovAverage_Current_5s, CAN0_SIG_MovAverage_Current_10s, CAN0_SIG_MovAverage_Current_30s, CAN0_SIG_MovAverage_Current_60s, CAN0_SIG_MovAverage_Current_config, CAN0_SIG_PackVolt_Battery, CAN0_SIG_PackVolt_PowerNet, CAN0_SIG_Mod0_volt_valid_0_2, CAN0_SIG_Mod0_volt_0, CAN0_SIG_Mod0_volt_1, CAN0_SIG_Mod0_volt_2, CAN0_SIG_Mod0_volt_valid_3_5, CAN0_SIG_Mod0_volt_3, CAN0_SIG_Mod0_volt_4, CAN0_SIG_Mod0_volt_5, CAN0_SIG_Mod0_volt_valid_6_8, CAN0_SIG_Mod0_volt_6, CAN0_SIG_Mod0_volt_7, CAN0_SIG_Mod0_volt_8, CAN0_SIG_Mod0_volt_valid_9_11, CAN0_SIG_Mod0_volt_9, CAN0_SIG_Mod0_volt_10, CAN0_SIG_Mod0_volt_11, CAN0_SIG_Mod0_temp_valid_0_2, CAN0_SIG_Mod0_temp_0, CAN0_SIG_Mod0_temp_1, CAN0_SIG_Mod0_temp_2, CAN0_SIG_Mod0_temp_valid_3_5, CAN0_SIG_Mod0_temp_3, CAN0_SIG_Mod0_temp_4, CAN0_SIG_Mod0_temp_5, CAN0_SIG_Mod0_temp_valid_6_8, CAN0_SIG_Mod0_temp_6, CAN0_SIG_Mod0_temp_7, CAN0_SIG_Mod0_temp_8, CAN0_SIG_Mod0_temp_valid_9_11, CAN0_SIG_Mod0_temp_9, CAN0_SIG_Mod0_temp_10, CAN0_SIG_Mod0_temp_11, CAN0_SIG_Mod1_volt_valid_0_2, CAN0_SIG_Mod1_volt_0, CAN0_SIG_Mod1_volt_1, CAN0_SIG_Mod1_volt_2, CAN0_SIG_Mod1_volt_valid_3_5, CAN0_SIG_Mod1_volt_3, CAN0_SIG_Mod1_volt_4, CAN0_SIG_Mod1_volt_5, CAN0_SIG_Mod1_volt_valid_6_8, CAN0_SIG_Mod1_volt_6, CAN0_SIG_Mod1_volt_7, CAN0_SIG_Mod1_volt_8, CAN0_SIG_Mod1_volt_valid_9_11, CAN0_SIG_Mod1_volt_9, CAN0_SIG_Mod1_volt_10, CAN0_SIG_Mod1_volt_11, CAN0_SIG_Mod1_temp_valid_0_2, CAN0_SIG_Mod1_temp_0, CAN0_SIG_Mod1_temp_1, CAN0_SIG_Mod1_temp_2, CAN0_SIG_Mod1_temp_valid_3_5, CAN0_SIG_Mod1_temp_3, CAN0_SIG_Mod1_temp_4, CAN0_SIG_Mod1_temp_5, CAN0_SIG_Mod1_temp_valid_6_8, CAN0_SIG_Mod1_temp_6, CAN0_SIG_Mod1_temp_7, CAN0_SIG_Mod1_temp_8, CAN0_SIG_Mod1_temp_valid_9_11, CAN0_SIG_Mod1_temp_9, CAN0_SIG_Mod1_temp_10, CAN0_SIG_Mod1_temp_11, CAN0_SIG_Mod2_volt_valid_0_2, CAN0_SIG_Mod2_volt_0, CAN0_SIG_Mod2_volt_1, CAN0_SIG_Mod2_volt_2, CAN0_SIG_Mod2_volt_valid_3_5, CAN0_SIG_Mod2_volt_3, CAN0_SIG_Mod2_volt_4, CAN0_SIG_Mod2_volt_5, CAN0_SIG_Mod2_volt_valid_6_8, CAN0_SIG_Mod2_volt_6, CAN0_SIG_Mod2_volt_7, CAN0_SIG_Mod2_volt_8, CAN0_SIG_Mod2_volt_valid_9_11, CAN0_SIG_Mod2_volt_9, CAN0_SIG_Mod2_volt_10, CAN0_SIG_Mod2_volt_11, CAN0_SIG_Mod2_temp_valid_0_2, CAN0_SIG_Mod2_temp_0, CAN0_SIG_Mod2_temp_1, CAN0_SIG_Mod2_temp_2, CAN0_SIG_Mod2_temp_valid_3_5, CAN0_SIG_Mod2_temp_3, CAN0_SIG_Mod2_temp_4, CAN0_SIG_Mod2_temp_5, CAN0_SIG_Mod2_temp_valid_6_8, CAN0_SIG_Mod2_temp_6, CAN0_SIG_Mod2_temp_7, CAN0_SIG_Mod2_temp_8, CAN0_SIG_Mod2_temp_valid_9_11, CAN0_SIG_Mod2_temp_9, CAN0_SIG_Mod2_temp_10, CAN0_SIG_Mod2_temp_11, CAN0_SIG_Mod3_volt_valid_0_2, CAN0_SIG_Mod3_volt_0, CAN0_SIG_Mod3_volt_1, CAN0_SIG_Mod3_volt_2, CAN0_SIG_Mod3_volt_valid_3_5, CAN0_SIG_Mod3_volt_3, CAN0_SIG_Mod3_volt_4, CAN0_SIG_Mod3_volt_5, CAN0_SIG_Mod3_volt_valid_6_8, CAN0_SIG_Mod3_volt_6, CAN0_SIG_Mod3_volt_7, CAN0_SIG_Mod3_volt_8, CAN0_SIG_Mod3_volt_valid_9_11, CAN0_SIG_Mod3_volt_9, CAN0_SIG_Mod3_volt_10, CAN0_SIG_Mod3_volt_11, CAN0_SIG_Mod3_temp_valid_0_2, CAN0_SIG_Mod3_temp_0, CAN0_SIG_Mod3_temp_1, CAN0_SIG_Mod3_temp_2, CAN0_SIG_Mod3_temp_valid_3_5, CAN0_SIG_Mod3_temp_3, CAN0_SIG_Mod3_temp_4, CAN0_SIG_Mod3_temp_5, CAN0_SIG_Mod3_temp_valid_6_8, CAN0_SIG_Mod3_temp_6, CAN0_SIG_Mod3_temp_7, CAN0_SIG_Mod3_temp_8, CAN0_SIG_Mod3_temp_valid_9_11, CAN0_SIG_Mod3_temp_9, CAN0_SIG_Mod3_temp_10, CAN0_SIG_Mod3_temp_11, CAN0_SIG_Mod4_volt_valid_0_2, CAN0_SIG_Mod4_volt_0, CAN0_SIG_Mod4_volt_1, CAN0_SIG_Mod4_volt_2, CAN0_SIG_Mod4_volt_valid_3_5, CAN0_SIG_Mod4_volt_3, CAN0_SIG_Mod4_volt_4, CAN0_SIG_Mod4_volt_5, CAN0_SIG_Mod4_volt_valid_6_8, CAN0_SIG_Mod4_volt_6, CAN0_SIG_Mod4_volt_7, CAN0_SIG_Mod4_volt_8, CAN0_SIG_Mod4_volt_valid_9_11, CAN0_SIG_Mod4_volt_9, CAN0_SIG_Mod4_volt_10, CAN0_SIG_Mod4_volt_11, CAN0_SIG_Mod4_temp_valid_0_2, CAN0_SIG_Mod4_temp_0, CAN0_SIG_Mod4_temp_1, CAN0_SIG_Mod4_temp_2, CAN0_SIG_Mod4_temp_valid_3_5, CAN0_SIG_Mod4_temp_3, CAN0_SIG_Mod4_temp_4, CAN0_SIG_Mod4_temp_5, CAN0_SIG_Mod4_temp_valid_6_8, CAN0_SIG_Mod4_temp_6, CAN0_SIG_Mod4_temp_7, CAN0_SIG_Mod4_temp_8, CAN0_SIG_Mod4_temp_valid_9_11, CAN0_SIG_Mod4_temp_9, CAN0_SIG_Mod4_temp_10, CAN0_SIG_Mod4_temp_11, CAN0_SIG_Mod5_volt_valid_0_2, CAN0_SIG_Mod5_volt_0, CAN0_SIG_Mod5_volt_1, CAN0_SIG_Mod5_volt_2, CAN0_SIG_Mod5_volt_valid_3_5, CAN0_SIG_Mod5_volt_3, CAN0_SIG_Mod5_volt_4, CAN0_SIG_Mod5_volt_5, CAN0_SIG_Mod5_volt_valid_6_8, CAN0_SIG_Mod5_volt_6, CAN0_SIG_Mod5_volt_7, CAN0_SIG_Mod5_volt_8, CAN0_SIG_Mod5_volt_valid_9_11, CAN0_SIG_Mod5_volt_9, CAN0_SIG_Mod5_volt_10, CAN0_SIG_Mod5_volt_11, CAN0_SIG_Mod5_temp_valid_0_2, CAN0_SIG_Mod5_temp_0, CAN0_SIG_Mod5_temp_1, CAN0_SIG_Mod5_temp_2, CAN0_SIG_Mod5_temp_valid_3_5, CAN0_SIG_Mod5_temp_3, CAN0_SIG_Mod5_temp_4, CAN0_SIG_Mod5_temp_5, CAN0_SIG_Mod5_temp_valid_6_8, CAN0_SIG_Mod5_temp_6, CAN0_SIG_Mod5_temp_7, CAN0_SIG_Mod5_temp_8, CAN0_SIG_Mod5_temp_valid_9_11, CAN0_SIG_Mod5_temp_9, CAN0_SIG_Mod5_temp_10, CAN0_SIG_Mod5_temp_11, CAN0_SIG_Mod6_volt_valid_0_2, CAN0_SIG_Mod6_volt_0, CAN0_SIG_Mod6_volt_1, CAN0_SIG_Mod6_volt_2, CAN0_SIG_Mod6_volt_valid_3_5, CAN0_SIG_Mod6_volt_3, CAN0_SIG_Mod6_volt_4, CAN0_SIG_Mod6_volt_5, CAN0_SIG_Mod6_volt_valid_6_8, CAN0_SIG_Mod6_volt_6, CAN0_SIG_Mod6_volt_7, CAN0_SIG_Mod6_volt_8, CAN0_SIG_Mod6_volt_valid_9_11, CAN0_SIG_Mod6_volt_9, CAN0_SIG_Mod6_volt_10, CAN0_SIG_Mod6_volt_11, CAN0_SIG_Mod6_temp_valid_0_2, CAN0_SIG_Mod6_temp_0, CAN0_SIG_Mod6_temp_1, CAN0_SIG_Mod6_temp_2, CAN0_SIG_Mod6_temp_valid_3_5, CAN0_SIG_Mod6_temp_3, CAN0_SIG_Mod6_temp_4, CAN0_SIG_Mod6_temp_5, CAN0_SIG_Mod6_temp_valid_6_8, CAN0_SIG_Mod6_temp_6, CAN0_SIG_Mod6_temp_7, CAN0_SIG_Mod6_temp_8, CAN0_SIG_Mod6_temp_valid_9_11, CAN0_SIG_Mod6_temp_9, CAN0_SIG_Mod6_temp_10, CAN0_SIG_Mod6_temp_11, CAN0_SIG_Mod7_volt_valid_0_2, CAN0_SIG_Mod7_volt_0, CAN0_SIG_Mod7_volt_1, CAN0_SIG_Mod7_volt_2, CAN0_SIG_Mod7_volt_valid_3_5, CAN0_SIG_Mod7_volt_3, CAN0_SIG_Mod7_volt_4, CAN0_SIG_Mod7_volt_5, CAN0_SIG_Mod7_volt_valid_6_8, CAN0_SIG_Mod7_volt_6, CAN0_SIG_Mod7_volt_7, CAN0_SIG_Mod7_volt_8, CAN0_SIG_Mod7_volt_valid_9_11, CAN0_SIG_Mod7_volt_9, CAN0_SIG_Mod7_volt_10, CAN0_SIG_Mod7_volt_11, CAN0_SIG_Mod7_temp_valid_0_2, CAN0_SIG_Mod7_temp_0, CAN0_SIG_Mod7_temp_1, CAN0_SIG_Mod7_temp_2, CAN0_SIG_Mod7_temp_valid_3_5, CAN0_SIG_Mod7_temp_3, CAN0_SIG_Mod7_temp_4, CAN0_SIG_Mod7_temp_5, CAN0_SIG_Mod7_temp_valid_6_8, CAN0_SIG_Mod7_temp_6, CAN0_SIG_Mod7_temp_7, CAN0_SIG_Mod7_temp_8, CAN0_SIG_Mod7_temp_valid_9_11, CAN0_SIG_Mod7_temp_9, CAN0_SIG_Mod7_temp_10, CAN0_SIG_Mod7_temp_11, #ifdef CAN_ISABELLENHUETTE_TRIGGERED CAN0_SIG_ISA_Trigger, #endif #if defined(ITRI_MOD_5) CAN0_SIG_Mod8_volt_valid_0_2, CAN0_SIG_Mod8_volt_0, CAN0_SIG_Mod8_volt_1, CAN0_SIG_Mod8_volt_2, CAN0_SIG_Mod8_volt_valid_3_5, CAN0_SIG_Mod8_volt_3, CAN0_SIG_Mod8_volt_4, CAN0_SIG_Mod8_volt_5, CAN0_SIG_Mod8_volt_valid_6_8, CAN0_SIG_Mod8_volt_6, CAN0_SIG_Mod8_volt_7, CAN0_SIG_Mod8_volt_8, CAN0_SIG_Mod8_volt_valid_9_11, CAN0_SIG_Mod8_volt_9, CAN0_SIG_Mod8_volt_10, CAN0_SIG_Mod8_volt_11, CAN0_SIG_Mod8_temp_valid_0_2, CAN0_SIG_Mod8_temp_0, CAN0_SIG_Mod8_temp_1, CAN0_SIG_Mod8_temp_2, CAN0_SIG_Mod8_temp_valid_3_5, CAN0_SIG_Mod8_temp_3, CAN0_SIG_Mod8_temp_4, CAN0_SIG_Mod8_temp_5, CAN0_SIG_Mod8_temp_valid_6_8, CAN0_SIG_Mod8_temp_6, CAN0_SIG_Mod8_temp_7, CAN0_SIG_Mod8_temp_8, CAN0_SIG_Mod8_temp_valid_9_11, CAN0_SIG_Mod8_temp_9, CAN0_SIG_Mod8_temp_10, CAN0_SIG_Mod8_temp_11, CAN0_SIG_Mod9_volt_valid_0_2, CAN0_SIG_Mod9_volt_0, CAN0_SIG_Mod9_volt_1, CAN0_SIG_Mod9_volt_2, CAN0_SIG_Mod9_volt_valid_3_5, CAN0_SIG_Mod9_volt_3, CAN0_SIG_Mod9_volt_4, CAN0_SIG_Mod9_volt_5, CAN0_SIG_Mod9_volt_valid_6_8, CAN0_SIG_Mod9_volt_6, CAN0_SIG_Mod9_volt_7, CAN0_SIG_Mod9_volt_8, CAN0_SIG_Mod9_volt_valid_9_11, CAN0_SIG_Mod9_volt_9, CAN0_SIG_Mod9_volt_10, CAN0_SIG_Mod9_volt_11, CAN0_SIG_Mod9_temp_valid_0_2, CAN0_SIG_Mod9_temp_0, CAN0_SIG_Mod9_temp_1, CAN0_SIG_Mod9_temp_2, CAN0_SIG_Mod9_temp_valid_3_5, CAN0_SIG_Mod9_temp_3, CAN0_SIG_Mod9_temp_4, CAN0_SIG_Mod9_temp_5, CAN0_SIG_Mod9_temp_valid_6_8, CAN0_SIG_Mod9_temp_6, CAN0_SIG_Mod9_temp_7, CAN0_SIG_Mod9_temp_8, CAN0_SIG_Mod9_temp_valid_9_11, CAN0_SIG_Mod9_temp_9, CAN0_SIG_Mod9_temp_10, CAN0_SIG_Mod9_temp_11, CAN0_SIG_Mod10_volt_valid_0_2, CAN0_SIG_Mod10_volt_0, CAN0_SIG_Mod10_volt_1, CAN0_SIG_Mod10_volt_2, CAN0_SIG_Mod10_volt_valid_3_5, CAN0_SIG_Mod10_volt_3, CAN0_SIG_Mod10_volt_4, CAN0_SIG_Mod10_volt_5, CAN0_SIG_Mod10_volt_valid_6_8, CAN0_SIG_Mod10_volt_6, CAN0_SIG_Mod10_volt_7, CAN0_SIG_Mod10_volt_8, CAN0_SIG_Mod10_volt_valid_9_11, CAN0_SIG_Mod10_volt_9, CAN0_SIG_Mod10_volt_10, CAN0_SIG_Mod10_volt_11, CAN0_SIG_Mod10_temp_valid_0_2, CAN0_SIG_Mod10_temp_0, CAN0_SIG_Mod10_temp_1, CAN0_SIG_Mod10_temp_2, CAN0_SIG_Mod10_temp_valid_3_5, CAN0_SIG_Mod10_temp_3, CAN0_SIG_Mod10_temp_4, CAN0_SIG_Mod10_temp_5, CAN0_SIG_Mod10_temp_valid_6_8, CAN0_SIG_Mod10_temp_6, CAN0_SIG_Mod10_temp_7, CAN0_SIG_Mod10_temp_8, CAN0_SIG_Mod10_temp_valid_9_11, CAN0_SIG_Mod10_temp_9, CAN0_SIG_Mod10_temp_10, CAN0_SIG_Mod10_temp_11, CAN0_SIG_Mod11_volt_valid_0_2, CAN0_SIG_Mod11_volt_0, CAN0_SIG_Mod11_volt_1, CAN0_SIG_Mod11_volt_2, CAN0_SIG_Mod11_volt_valid_3_5, CAN0_SIG_Mod11_volt_3, CAN0_SIG_Mod11_volt_4, CAN0_SIG_Mod11_volt_5, CAN0_SIG_Mod11_volt_valid_6_8, CAN0_SIG_Mod11_volt_6, CAN0_SIG_Mod11_volt_7, CAN0_SIG_Mod11_volt_8, CAN0_SIG_Mod11_volt_valid_9_11, CAN0_SIG_Mod11_volt_9, CAN0_SIG_Mod11_volt_10, CAN0_SIG_Mod11_volt_11, CAN0_SIG_Mod11_temp_valid_0_2, CAN0_SIG_Mod11_temp_0, CAN0_SIG_Mod11_temp_1, CAN0_SIG_Mod11_temp_2, CAN0_SIG_Mod11_temp_valid_3_5, CAN0_SIG_Mod11_temp_3, CAN0_SIG_Mod11_temp_4, CAN0_SIG_Mod11_temp_5, CAN0_SIG_Mod11_temp_valid_6_8, CAN0_SIG_Mod11_temp_6, CAN0_SIG_Mod11_temp_7, CAN0_SIG_Mod11_temp_8, CAN0_SIG_Mod11_temp_valid_9_11, CAN0_SIG_Mod11_temp_9, CAN0_SIG_Mod11_temp_10, CAN0_SIG_Mod11_temp_11, CAN0_SIG_Mod12_volt_valid_0_2, CAN0_SIG_Mod12_volt_0, CAN0_SIG_Mod12_volt_1, CAN0_SIG_Mod12_volt_2, CAN0_SIG_Mod12_volt_valid_3_5, CAN0_SIG_Mod12_volt_3, CAN0_SIG_Mod12_volt_4, CAN0_SIG_Mod12_volt_5, CAN0_SIG_Mod12_volt_valid_6_8, CAN0_SIG_Mod12_volt_6, CAN0_SIG_Mod12_volt_7, CAN0_SIG_Mod12_volt_8, CAN0_SIG_Mod12_volt_valid_9_11, CAN0_SIG_Mod12_volt_9, CAN0_SIG_Mod12_volt_10, CAN0_SIG_Mod12_volt_11, CAN0_SIG_Mod12_temp_valid_0_2, CAN0_SIG_Mod12_temp_0, CAN0_SIG_Mod12_temp_1, CAN0_SIG_Mod12_temp_2, CAN0_SIG_Mod12_temp_valid_3_5, CAN0_SIG_Mod12_temp_3, CAN0_SIG_Mod12_temp_4, CAN0_SIG_Mod12_temp_5, CAN0_SIG_Mod12_temp_valid_6_8, CAN0_SIG_Mod12_temp_6, CAN0_SIG_Mod12_temp_7, CAN0_SIG_Mod12_temp_8, CAN0_SIG_Mod12_temp_valid_9_11, CAN0_SIG_Mod12_temp_9, CAN0_SIG_Mod12_temp_10, CAN0_SIG_Mod12_temp_11, CAN0_SIG_Mod13_volt_valid_0_2, CAN0_SIG_Mod13_volt_0, CAN0_SIG_Mod13_volt_1, CAN0_SIG_Mod13_volt_2, CAN0_SIG_Mod13_volt_valid_3_5, CAN0_SIG_Mod13_volt_3, CAN0_SIG_Mod13_volt_4, CAN0_SIG_Mod13_volt_5, CAN0_SIG_Mod13_volt_valid_6_8, CAN0_SIG_Mod13_volt_6, CAN0_SIG_Mod13_volt_7, CAN0_SIG_Mod13_volt_8, CAN0_SIG_Mod13_volt_valid_9_11, CAN0_SIG_Mod13_volt_9, CAN0_SIG_Mod13_volt_10, CAN0_SIG_Mod13_volt_11, CAN0_SIG_Mod13_temp_valid_0_2, CAN0_SIG_Mod13_temp_0, CAN0_SIG_Mod13_temp_1, CAN0_SIG_Mod13_temp_2, CAN0_SIG_Mod13_temp_valid_3_5, CAN0_SIG_Mod13_temp_3, CAN0_SIG_Mod13_temp_4, CAN0_SIG_Mod13_temp_5, CAN0_SIG_Mod13_temp_valid_6_8, CAN0_SIG_Mod13_temp_6, CAN0_SIG_Mod13_temp_7, CAN0_SIG_Mod13_temp_8, CAN0_SIG_Mod13_temp_valid_9_11, CAN0_SIG_Mod13_temp_9, CAN0_SIG_Mod13_temp_10, CAN0_SIG_Mod13_temp_11, CAN0_SIG_Mod14_volt_valid_0_2, CAN0_SIG_Mod14_volt_0, CAN0_SIG_Mod14_volt_1, CAN0_SIG_Mod14_volt_2, CAN0_SIG_Mod14_volt_valid_3_5, CAN0_SIG_Mod14_volt_3, CAN0_SIG_Mod14_volt_4, CAN0_SIG_Mod14_volt_5, CAN0_SIG_Mod14_volt_valid_6_8, CAN0_SIG_Mod14_volt_6, CAN0_SIG_Mod14_volt_7, CAN0_SIG_Mod14_volt_8, CAN0_SIG_Mod14_volt_valid_9_11, CAN0_SIG_Mod14_volt_9, CAN0_SIG_Mod14_volt_10, CAN0_SIG_Mod14_volt_11, CAN0_SIG_Mod14_temp_valid_0_2, CAN0_SIG_Mod14_temp_0, CAN0_SIG_Mod14_temp_1, CAN0_SIG_Mod14_temp_2, CAN0_SIG_Mod14_temp_valid_3_5, CAN0_SIG_Mod14_temp_3, CAN0_SIG_Mod14_temp_4, CAN0_SIG_Mod14_temp_5, CAN0_SIG_Mod14_temp_valid_6_8, CAN0_SIG_Mod14_temp_6, CAN0_SIG_Mod14_temp_7, CAN0_SIG_Mod14_temp_8, CAN0_SIG_Mod14_temp_valid_9_11, CAN0_SIG_Mod14_temp_9, CAN0_SIG_Mod14_temp_10, CAN0_SIG_Mod14_temp_11, CAN0_SIG_Mod15_volt_valid_0_2, CAN0_SIG_Mod15_volt_0, CAN0_SIG_Mod15_volt_1, CAN0_SIG_Mod15_volt_2, CAN0_SIG_Mod15_volt_valid_3_5, CAN0_SIG_Mod15_volt_3, CAN0_SIG_Mod15_volt_4, CAN0_SIG_Mod15_volt_5, CAN0_SIG_Mod15_volt_valid_6_8, CAN0_SIG_Mod15_volt_6, CAN0_SIG_Mod15_volt_7, CAN0_SIG_Mod15_volt_8, CAN0_SIG_Mod15_volt_valid_9_11, CAN0_SIG_Mod15_volt_9, CAN0_SIG_Mod15_volt_10, CAN0_SIG_Mod15_volt_11, CAN0_SIG_Mod15_temp_valid_0_2, CAN0_SIG_Mod15_temp_0, CAN0_SIG_Mod15_temp_1, CAN0_SIG_Mod15_temp_2, CAN0_SIG_Mod15_temp_valid_3_5, CAN0_SIG_Mod15_temp_3, CAN0_SIG_Mod15_temp_4, CAN0_SIG_Mod15_temp_5, CAN0_SIG_Mod15_temp_valid_6_8, CAN0_SIG_Mod15_temp_6, CAN0_SIG_Mod15_temp_7, CAN0_SIG_Mod15_temp_8, CAN0_SIG_Mod15_temp_valid_9_11, CAN0_SIG_Mod15_temp_9, CAN0_SIG_Mod15_temp_10, CAN0_SIG_Mod15_temp_11, CAN0_SIG_Mod16_volt_valid_0_2, CAN0_SIG_Mod16_volt_0, CAN0_SIG_Mod16_volt_1, CAN0_SIG_Mod16_volt_2, CAN0_SIG_Mod16_volt_valid_3_5, CAN0_SIG_Mod16_volt_3, CAN0_SIG_Mod16_volt_4, CAN0_SIG_Mod16_volt_5, CAN0_SIG_Mod16_volt_valid_6_8, CAN0_SIG_Mod16_volt_6, CAN0_SIG_Mod16_volt_7, CAN0_SIG_Mod16_volt_8, CAN0_SIG_Mod16_volt_valid_9_11, CAN0_SIG_Mod16_volt_9, CAN0_SIG_Mod16_volt_10, CAN0_SIG_Mod16_volt_11, CAN0_SIG_Mod16_temp_valid_0_2, CAN0_SIG_Mod16_temp_0, CAN0_SIG_Mod16_temp_1, CAN0_SIG_Mod16_temp_2, CAN0_SIG_Mod16_temp_valid_3_5, CAN0_SIG_Mod16_temp_3, CAN0_SIG_Mod16_temp_4, CAN0_SIG_Mod16_temp_5, CAN0_SIG_Mod16_temp_valid_6_8, CAN0_SIG_Mod16_temp_6, CAN0_SIG_Mod16_temp_7, CAN0_SIG_Mod16_temp_8, CAN0_SIG_Mod16_temp_valid_9_11, CAN0_SIG_Mod16_temp_9, CAN0_SIG_Mod16_temp_10, CAN0_SIG_Mod16_temp_11, CAN0_SIG_Mod17_volt_valid_0_2, CAN0_SIG_Mod17_volt_0, CAN0_SIG_Mod17_volt_1, CAN0_SIG_Mod17_volt_2, CAN0_SIG_Mod17_volt_valid_3_5, CAN0_SIG_Mod17_volt_3, CAN0_SIG_Mod17_volt_4, CAN0_SIG_Mod17_volt_5, CAN0_SIG_Mod17_volt_valid_6_8, CAN0_SIG_Mod17_volt_6, CAN0_SIG_Mod17_volt_7, CAN0_SIG_Mod17_volt_8, CAN0_SIG_Mod17_volt_valid_9_11, CAN0_SIG_Mod17_volt_9, CAN0_SIG_Mod17_volt_10, CAN0_SIG_Mod17_volt_11, CAN0_SIG_Mod17_temp_valid_0_2, CAN0_SIG_Mod17_temp_0, CAN0_SIG_Mod17_temp_1, CAN0_SIG_Mod17_temp_2, CAN0_SIG_Mod17_temp_valid_3_5, CAN0_SIG_Mod17_temp_3, CAN0_SIG_Mod17_temp_4, CAN0_SIG_Mod17_temp_5, CAN0_SIG_Mod17_temp_valid_6_8, CAN0_SIG_Mod17_temp_6, CAN0_SIG_Mod17_temp_7, CAN0_SIG_Mod17_temp_8, CAN0_SIG_Mod17_temp_valid_9_11, CAN0_SIG_Mod17_temp_9, CAN0_SIG_Mod17_temp_10, CAN0_SIG_Mod17_temp_11, CAN0_SIG_Mod18_volt_valid_0_2, CAN0_SIG_Mod18_volt_0, CAN0_SIG_Mod18_volt_1, CAN0_SIG_Mod18_volt_2, CAN0_SIG_Mod18_volt_valid_3_5, CAN0_SIG_Mod18_volt_3, CAN0_SIG_Mod18_volt_4, CAN0_SIG_Mod18_volt_5, CAN0_SIG_Mod18_volt_valid_6_8, CAN0_SIG_Mod18_volt_6, CAN0_SIG_Mod18_volt_7, CAN0_SIG_Mod18_volt_8, CAN0_SIG_Mod18_volt_valid_9_11, CAN0_SIG_Mod18_volt_9, CAN0_SIG_Mod18_volt_10, CAN0_SIG_Mod18_volt_11, CAN0_SIG_Mod18_temp_valid_0_2, CAN0_SIG_Mod18_temp_0, CAN0_SIG_Mod18_temp_1, CAN0_SIG_Mod18_temp_2, CAN0_SIG_Mod18_temp_valid_3_5, CAN0_SIG_Mod18_temp_3, CAN0_SIG_Mod18_temp_4, CAN0_SIG_Mod18_temp_5, CAN0_SIG_Mod18_temp_valid_6_8, CAN0_SIG_Mod18_temp_6, CAN0_SIG_Mod18_temp_7, CAN0_SIG_Mod18_temp_8, CAN0_SIG_Mod18_temp_valid_9_11, CAN0_SIG_Mod18_temp_9, CAN0_SIG_Mod18_temp_10, CAN0_SIG_Mod18_temp_11, CAN0_SIG_Mod19_volt_valid_0_2, CAN0_SIG_Mod19_volt_0, CAN0_SIG_Mod19_volt_1, CAN0_SIG_Mod19_volt_2, CAN0_SIG_Mod19_volt_valid_3_5, CAN0_SIG_Mod19_volt_3, CAN0_SIG_Mod19_volt_4, CAN0_SIG_Mod19_volt_5, CAN0_SIG_Mod19_volt_valid_6_8, CAN0_SIG_Mod19_volt_6, CAN0_SIG_Mod19_volt_7, CAN0_SIG_Mod19_volt_8, CAN0_SIG_Mod19_volt_valid_9_11, CAN0_SIG_Mod19_volt_9, CAN0_SIG_Mod19_volt_10, CAN0_SIG_Mod19_volt_11, CAN0_SIG_Mod19_temp_valid_0_2, CAN0_SIG_Mod19_temp_0, CAN0_SIG_Mod19_temp_1, CAN0_SIG_Mod19_temp_2, CAN0_SIG_Mod19_temp_valid_3_5, CAN0_SIG_Mod19_temp_3, CAN0_SIG_Mod19_temp_4, CAN0_SIG_Mod19_temp_5, CAN0_SIG_Mod19_temp_valid_6_8, CAN0_SIG_Mod19_temp_6, CAN0_SIG_Mod19_temp_7, CAN0_SIG_Mod19_temp_8, CAN0_SIG_Mod19_temp_valid_9_11, CAN0_SIG_Mod19_temp_9, CAN0_SIG_Mod19_temp_10, CAN0_SIG_Mod19_temp_11, CAN0_SIG_Mod20_volt_valid_0_2, CAN0_SIG_Mod20_volt_0, CAN0_SIG_Mod20_volt_1, CAN0_SIG_Mod20_volt_2, CAN0_SIG_Mod20_volt_valid_3_5, CAN0_SIG_Mod20_volt_3, CAN0_SIG_Mod20_volt_4, CAN0_SIG_Mod20_volt_5, CAN0_SIG_Mod20_volt_valid_6_8, CAN0_SIG_Mod20_volt_6, CAN0_SIG_Mod20_volt_7, CAN0_SIG_Mod20_volt_8, CAN0_SIG_Mod20_volt_valid_9_11, CAN0_SIG_Mod20_volt_9, CAN0_SIG_Mod20_volt_10, CAN0_SIG_Mod20_volt_11, CAN0_SIG_Mod20_temp_valid_0_2, CAN0_SIG_Mod20_temp_0, CAN0_SIG_Mod20_temp_1, CAN0_SIG_Mod20_temp_2, CAN0_SIG_Mod20_temp_valid_3_5, CAN0_SIG_Mod20_temp_3, CAN0_SIG_Mod20_temp_4, CAN0_SIG_Mod20_temp_5, CAN0_SIG_Mod20_temp_valid_6_8, CAN0_SIG_Mod20_temp_6, CAN0_SIG_Mod20_temp_7, CAN0_SIG_Mod20_temp_8, CAN0_SIG_Mod20_temp_valid_9_11, CAN0_SIG_Mod20_temp_9, CAN0_SIG_Mod20_temp_10, CAN0_SIG_Mod20_temp_11, CAN0_SIG_Mod21_volt_valid_0_2, CAN0_SIG_Mod21_volt_0, CAN0_SIG_Mod21_volt_1, CAN0_SIG_Mod21_volt_2, CAN0_SIG_Mod21_volt_valid_3_5, CAN0_SIG_Mod21_volt_3, CAN0_SIG_Mod21_volt_4, CAN0_SIG_Mod21_volt_5, CAN0_SIG_Mod21_volt_valid_6_8, CAN0_SIG_Mod21_volt_6, CAN0_SIG_Mod21_volt_7, CAN0_SIG_Mod21_volt_8, CAN0_SIG_Mod21_volt_valid_9_11, CAN0_SIG_Mod21_volt_9, CAN0_SIG_Mod21_volt_10, CAN0_SIG_Mod21_volt_11, CAN0_SIG_Mod21_temp_valid_0_2, CAN0_SIG_Mod21_temp_0, CAN0_SIG_Mod21_temp_1, CAN0_SIG_Mod21_temp_2, CAN0_SIG_Mod21_temp_valid_3_5, CAN0_SIG_Mod21_temp_3, CAN0_SIG_Mod21_temp_4, CAN0_SIG_Mod21_temp_5, CAN0_SIG_Mod21_temp_valid_6_8, CAN0_SIG_Mod21_temp_6, CAN0_SIG_Mod21_temp_7, CAN0_SIG_Mod21_temp_8, CAN0_SIG_Mod21_temp_valid_9_11, CAN0_SIG_Mod21_temp_9, CAN0_SIG_Mod21_temp_10, CAN0_SIG_Mod21_temp_11, CAN0_SIG_Mod22_volt_valid_0_2, CAN0_SIG_Mod22_volt_0, CAN0_SIG_Mod22_volt_1, CAN0_SIG_Mod22_volt_2, CAN0_SIG_Mod22_volt_valid_3_5, CAN0_SIG_Mod22_volt_3, CAN0_SIG_Mod22_volt_4, CAN0_SIG_Mod22_volt_5, CAN0_SIG_Mod22_volt_valid_6_8, CAN0_SIG_Mod22_volt_6, CAN0_SIG_Mod22_volt_7, CAN0_SIG_Mod22_volt_8, CAN0_SIG_Mod22_volt_valid_9_11, CAN0_SIG_Mod22_volt_9, CAN0_SIG_Mod22_volt_10, CAN0_SIG_Mod22_volt_11, CAN0_SIG_Mod22_temp_valid_0_2, CAN0_SIG_Mod22_temp_0, CAN0_SIG_Mod22_temp_1, CAN0_SIG_Mod22_temp_2, CAN0_SIG_Mod22_temp_valid_3_5, CAN0_SIG_Mod22_temp_3, CAN0_SIG_Mod22_temp_4, CAN0_SIG_Mod22_temp_5, CAN0_SIG_Mod22_temp_valid_6_8, CAN0_SIG_Mod22_temp_6, CAN0_SIG_Mod22_temp_7, CAN0_SIG_Mod22_temp_8, CAN0_SIG_Mod22_temp_valid_9_11, CAN0_SIG_Mod22_temp_9, CAN0_SIG_Mod22_temp_10, CAN0_SIG_Mod22_temp_11, CAN0_SIG_Mod23_volt_valid_0_2, CAN0_SIG_Mod23_volt_0, CAN0_SIG_Mod23_volt_1, CAN0_SIG_Mod23_volt_2, CAN0_SIG_Mod23_volt_valid_3_5, CAN0_SIG_Mod23_volt_3, CAN0_SIG_Mod23_volt_4, CAN0_SIG_Mod23_volt_5, CAN0_SIG_Mod23_volt_valid_6_8, CAN0_SIG_Mod23_volt_6, CAN0_SIG_Mod23_volt_7, CAN0_SIG_Mod23_volt_8, CAN0_SIG_Mod23_volt_valid_9_11, CAN0_SIG_Mod23_volt_9, CAN0_SIG_Mod23_volt_10, CAN0_SIG_Mod23_volt_11, CAN0_SIG_Mod23_temp_valid_0_2, CAN0_SIG_Mod23_temp_0, CAN0_SIG_Mod23_temp_1, CAN0_SIG_Mod23_temp_2, CAN0_SIG_Mod23_temp_valid_3_5, CAN0_SIG_Mod23_temp_3, CAN0_SIG_Mod23_temp_4, CAN0_SIG_Mod23_temp_5, CAN0_SIG_Mod23_temp_valid_6_8, CAN0_SIG_Mod23_temp_6, CAN0_SIG_Mod23_temp_7, CAN0_SIG_Mod23_temp_8, CAN0_SIG_Mod23_temp_valid_9_11, CAN0_SIG_Mod23_temp_9, CAN0_SIG_Mod23_temp_10, CAN0_SIG_Mod23_temp_11, CAN0_SIG_Mod24_volt_valid_0_2, CAN0_SIG_Mod24_volt_0, CAN0_SIG_Mod24_volt_1, CAN0_SIG_Mod24_volt_2, CAN0_SIG_Mod24_volt_valid_3_5, CAN0_SIG_Mod24_volt_3, CAN0_SIG_Mod24_volt_4, CAN0_SIG_Mod24_volt_5, CAN0_SIG_Mod24_volt_valid_6_8, CAN0_SIG_Mod24_volt_6, CAN0_SIG_Mod24_volt_7, CAN0_SIG_Mod24_volt_8, CAN0_SIG_Mod24_volt_valid_9_11, CAN0_SIG_Mod24_volt_9, CAN0_SIG_Mod24_volt_10, CAN0_SIG_Mod24_volt_11, CAN0_SIG_Mod24_temp_valid_0_2, CAN0_SIG_Mod24_temp_0, CAN0_SIG_Mod24_temp_1, CAN0_SIG_Mod24_temp_2, CAN0_SIG_Mod24_temp_valid_3_5, CAN0_SIG_Mod24_temp_3, CAN0_SIG_Mod24_temp_4, CAN0_SIG_Mod24_temp_5, CAN0_SIG_Mod24_temp_valid_6_8, CAN0_SIG_Mod24_temp_6, CAN0_SIG_Mod24_temp_7, CAN0_SIG_Mod24_temp_8, CAN0_SIG_Mod24_temp_valid_9_11, CAN0_SIG_Mod24_temp_9, CAN0_SIG_Mod24_temp_10, CAN0_SIG_Mod24_temp_11, #endif // ITRI_MOD_5 CAN0_SIGNAL_NONE = 0xFFFF } CANS_CAN0_signalsTx_e; /** * symbolic names for CAN1 transmission signals */ typedef enum { CAN1_TX_SIGNAL_NONE = 0xFFFF, } CANS_CAN1_signalsTx_e; /** * symbolic names for CAN 0 receive signals */ typedef enum { CAN0_SIG_ReceiveStateRequest, /*!< current sensor counter */ CAN0_SIG_IVT_Current_MuxID, /*!< current sensor measurement type */ CAN0_SIG_IVT_Current_Status, /*!< current sensor counter */ CAN0_SIG_IVT_Current_Measurement, /*!< current sensor measurement I */ CAN0_SIG_IVT_Voltage_1_MuxID, /*!< current sensor measurement type */ CAN0_SIG_IVT_Voltage_1_Status, /*!< current sensor counter */ CAN0_SIG_IVT_Voltage_1_Measurement, /*!< current sensor measurement U1 */ CAN0_SIG_IVT_Voltage_2_MuxID, /*!< current sensor measurement type */ CAN0_SIG_IVT_Voltage_2_Status, /*!< current sensor counter */ CAN0_SIG_IVT_Voltage_2_Measurement, /*!< current sensor measurement U2 */ CAN0_SIG_IVT_Voltage_3_MuxID, /*!< current sensor measurement type */ CAN0_SIG_IVT_Voltage_3_Status, /*!< current sensor counter */ CAN0_SIG_IVT_Voltage_3_Measurement, /*!< current sensor measurement U3 */ CAN0_SIG_IVT_Temperature_MuxID, /*!< current sensor measurement type */ CAN0_SIG_IVT_Temperature_Status, /*!< current sensor counter */ CAN0_SIG_IVT_Temperature_Measurement, /*!< current sensor measurement T */ CAN0_SIG_IVT_Power_MuxID, /*!< current sensor measurement type */ CAN0_SIG_IVT_Power_Status, /*!< current sensor counter */ CAN0_SIG_IVT_Power_Measurement, /*!< current sensor measurement P */ CAN0_SIG_IVT_CC_MuxID, /*!< current sensor measurement type */ CAN0_SIG_IVT_CC_Status, /*!< current sensor counter */ CAN0_SIG_IVT_CC_Measurement, /*!< current sensor measurement C-C */ CAN0_SIG_IVT_EC_MuxID, /*!< current sensor measurement type */ CAN0_SIG_IVT_EC_Status, /*!< current sensor counter */ CAN0_SIG_IVT_EC_Measurement, /*!< current sensor measurement E-C */ CAN0_SIG_DEBUG_Data, /*!< Data of debug message */ CAN0_SIG_GetReleaseVersion } CANS_CAN0_signalsRx_e; /** * symbolic names for CAN 1 receive signals */ typedef enum { CAN1_RX_SIGNAL_NONE = 0xFFFF, } CANS_CAN1_signalsRx_e; typedef enum { CAN_RX_DIRECTION = 0, CAN_TX_DIRECTION = 1 } CANS_messageDirection_t; typedef union { CANS_messagesTx_e Tx; CANS_messagesRx_e Rx; } CANS_messages_t; typedef union { CANS_CAN0_signalsTx_e Tx; CANS_CAN0_signalsRx_e Rx; } CANS_signals_t; /** * type definition for structure of a CAN signal * * until now, multiplexed signal handling is hard coded * in the corresponding getters/setters. For use of multiplexed * signals refer to description in documentation. * * support for automatic scaling is planned, but not implemented yet, * so min, max, factor and offset are not relevant. */ typedef struct { CANS_messages_t msgIdx; uint8_t bit_position; uint8_t bit_length; float min; float max; float factor; float offset; can_callback_funcPtr setter; can_callback_funcPtr getter; } CANS_signal_s; /*================== Constant and Variable Definitions ====================*/ /** * array for transmission CAN0 signals definition */ extern const CANS_signal_s cans_CAN0_signals_tx[]; /** * array for transmission CAN1 signals definition */ extern const CANS_signal_s cans_CAN1_signals_tx[]; /** * array for received CAN0 signals definition */ extern const CANS_signal_s cans_CAN0_signals_rx[]; /** * array for received CAN1 signals definition */ extern const CANS_signal_s cans_CAN1_signals_rx[]; /** * length of the array for the CAN0 tx signals */ extern const uint16_t cans_CAN0_signals_tx_length; /** * length of the array for the CAN1 tx signals */ extern const uint16_t cans_CAN1_signals_tx_length; /** * length of the array for the CAN0 rx signals */ extern const uint16_t cans_CAN0_signals_rx_length; /** * length of the array for the CAN1 rx signals */ extern const uint16_t cans_CAN1_signals_rx_length; /*================== Function Prototypes ==================================*/ /*================== Function Implementations =============================*/ #endif /* CANSIGNAL_CFG_H_ */
tonyhuang84/foxbms
embedded-software/mcu-primary/src/module/contactor/contactor.h
<reponame>tonyhuang84/foxbms /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file contactor.h * @author f<NAME> * @date 23.09.2015 (date of creation) * @ingroup DRIVERS * @prefix CONT * * @brief Headers for the driver for the contactors. * */ #ifndef CONTACTOR_H_ #define CONTACTOR_H_ /*================== Includes =============================================*/ #include "contactor_cfg.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ /*================== Function Prototypes ==================================*/ /** * @brief Checks the configuration of the contactor-module * * @return retVal (type: STD_RETURN_TYPE_e) */ extern STD_RETURN_TYPE_e CONT_Init(void); /** * @brief Gets the latest value (TRUE, FALSE) the contactors were set to. * * @param contactor (type: CONT_NAMES_e) * * @return returns CONT_SWITCH_OFF or CONT_SWITCH_ON */ extern CONT_ELECTRICAL_STATE_TYPE_s CONT_GetContactorSetValue(CONT_NAMES_e contactor); /** * @brief Reads the feedback pin of every contactor and returns its current value * (CONT_SWITCH_OFF/CONT_SWITCH_ON). * * @details If the contactor has a feedback pin the measured feedback is returned. If the contactor * has no feedback pin, it is assumed that after a certain time the contactor has reached * the requested state. * * @param contactor (type: CONT_NAMES_e) * * @return measuredContactorState (type: CONT_ELECTRICAL_STATE_TYPE_s) */ extern CONT_ELECTRICAL_STATE_TYPE_s CONT_GetContactorFeedback(CONT_NAMES_e contactor); /** * @brief Reads the feedback pins of all contactors and updates the contactors_cfg[] array with * their current states. * * @return Returns E_OK if all feedbacks could be acquired (type: STD_RETURN_TYPE_e) */ extern STD_RETURN_TYPE_e CONT_AcquireContactorFeedbacks(void); /** * @brief Sets the contactor state to its requested state, if the contactor is at that time not * in the requested state. * * @details If the new state was already requested, but not reached (meaning the measured feedback * does not return the requested state), there are two states: it can be still ok (E_OK), * because the contactor has some time left to get physically in the requested state * (passed time since the request is lower than the limit) or it can be not ok (E_NOT_OK), * because there is timing violation, i.e. the contactor has surpassed the maximum time * for getting in the requested state. It returns E_OK if the requested state was * successfully set or if the contactor was at the requested state before. * * @param contactor (type: CONT_NAMES_e) * @param requestedContactorState (type: CONT_ELECTRICAL_STATE_TYPE_s) * * @return retVal (type: STD_RETURN_TYPE_e) */ extern STD_RETURN_TYPE_e CONT_SetContactorState(CONT_NAMES_e contactor, CONT_ELECTRICAL_STATE_TYPE_s requestedContactorState); /** * @brief Iterates over the contactor array and switches all contactors off * * @return E_OK if all contactors were opened, E_NOT_OK if not all contactors could be opened * (type: STD_RETURN_TYPE_e) */ extern STD_RETURN_TYPE_e CONT_SwitchAllContactorsOff(void); /*================== Function Implementations =============================*/ /*================== Constant and Variable Definitions ====================*/ /** * States of the CONT state machine */ typedef enum { /* Init-Sequence */ CONT_STATEMACH_UNINITIALIZED = 0, /*!< */ CONT_STATEMACH_INITIALIZATION = 1, /*!< */ CONT_STATEMACH_INITIALIZED = 2, /*!< */ CONT_STATEMACH_IDLE = 3, /*!< */ CONT_STATEMACH_STANDBY = 4, /*!< */ CONT_STATEMACH_PRECHARGE = 5, /*!< */ CONT_STATEMACH_NORMAL = 6, /*!< */ CONT_STATEMACH_CHARGE_PRECHARGE = 7, /*!< */ CONT_STATEMACH_CHARGE = 8, /*!< */ CONT_STATEMACH_UNDEFINED = 20, /*!< undefined state */ CONT_STATEMACH_RESERVED1 = 0x80, /*!< reserved state */ CONT_STATEMACH_ERROR = 0xF0, /*!< Error-State: */ } CONT_STATEMACH_e; /** * Substates of the CONT state machine */ typedef enum { CONT_ENTRY = 0, /*!< Substate entry state */ CONT_OPEN_FIRST_CONTACTOR = 1, /*!< Open-sequence: first contactor */ CONT_OPEN_SECOND_CONTACTOR_MINUS = 2, /*!< Open-sequence: second contactor */ CONT_OPEN_SECOND_CONTACTOR_PLUS = 3, /*!< Open-sequence: second contactor */ CONT_STANDBY = 4, /*!< Substate stanby */ CONT_PRECHARGE_CLOSE_MINUS = 5, /*!< Begin of precharge sequence: close main minus */ CONT_PRECHARGE_CLOSE_PRECHARGE = 6, /*!< Next step of precharge sequence: close precharge */ CONT_PRECHARGE_CLOSE_PLUS = 7, /*!< Next step of precharge sequence: close main plus */ CONT_PRECHARGE_CHECK_VOLTAGES = 8, /*!< Next step of precharge sequence: check if voltages OK */ CONT_PRECHARGE_OPEN_PRECHARGE = 9, /*!< Next step of precharge sequence: open precharge */ CONT_ERROR = 10, /*!< Error state */ } CONT_STATEMACH_SUB_e; /** * State requests for the CONT statemachine */ typedef enum { CONT_STATE_INIT_REQUEST = CONT_STATEMACH_INITIALIZATION, /*!< */ CONT_STATE_STANDBY_REQUEST = CONT_STATEMACH_STANDBY, /*!< */ CONT_STATE_NORMAL_REQUEST = CONT_STATEMACH_NORMAL, /*!< */ CONT_STATE_CHARGE_REQUEST = CONT_STATEMACH_CHARGE, /*!< */ CONT_STATE_ERROR_REQUEST = CONT_STATEMACH_ERROR, /*!< */ CONT_STATE_NO_REQUEST = CONT_STATEMACH_RESERVED1, /*!< */ } CONT_STATE_REQUEST_e; /** * Possible return values when state requests are made to the CONT statemachine */ typedef enum { CONT_OK = 0, /*!< CONT --> ok */ CONT_BUSY_OK = 1, /*!< CONT under load --> ok */ CONT_REQUEST_PENDING = 2, /*!< requested to be executed */ CONT_REQUEST_IMPOSSIBLE = 3, /*!< requested not possible */ CONT_ILLEGAL_REQUEST = 4, /*!< Request can not be executed */ CONT_INIT_ERROR = 5, /*!< Error state: Source: Initialization */ CONT_OK_FROM_ERROR = 6, /*!< Return from error --> ok */ CONT_ALREADY_INITIALIZED = 30, /*!< Initialization of LTC already finished */ CONT_ILLEGAL_TASK_TYPE = 99, /*!< Illegal */ } CONT_RETURN_TYPE_e; /** * This structure contains all the variables relevant for the CONT state machine. * The user can get the current state of the CONT state machine with this variable */ typedef struct { uint16_t timer; /*!< time in ms before the state machine processes the next state, e.g. in counts of 1ms */ CONT_STATE_REQUEST_e statereq; /*!< current state request made to the state machine */ CONT_STATEMACH_e state; /*!< state of Driver State Machine */ CONT_STATEMACH_SUB_e substate; /*!< current substate of the state machine */ CONT_STATEMACH_e laststate; /*!< previous state of the state machine */ CONT_STATEMACH_SUB_e lastsubstate; /*!< previous substate of the state machine */ uint32_t ErrRequestCounter; /*!< counts the number of illegal requests to the LTC state machine */ uint16_t OscillationCounter; /*!< timeout to prevent oscillation of contactors */ uint8_t PrechargeTryCounter; /*!< timeout to prevent oscillation of contactors */ uint16_t PrechargeTimeOut; /*!< time to wait when precharge has been closed for voltages to settle */ uint8_t triggerentry; /*!< counter for re-entrance protection (function running flag) */ uint8_t counter; /*!< general purpose counter */ } CONT_STATE_s; /*================== Function Prototypes ==================================*/ extern CONT_RETURN_TYPE_e CONT_SetStateRequest(CONT_STATE_REQUEST_e statereq); extern CONT_STATEMACH_e CONT_GetState(void); extern void CONT_Trigger(void); #endif /* CONTACTOR_H_ */
tonyhuang84/foxbms
embedded-software/mcu-primary/src/doxygen.h
<reponame>tonyhuang84/foxbms<filename>embedded-software/mcu-primary/src/doxygen.h /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file doxygen.h * @author foxBMS Team * @date 11.11.2015 (date of creation) * @ingroup none * @prefix none * * @brief Mainpage and Module-list for generating of documents with doxygen * */ #ifndef DOXYGEN_H_ #define DOXYGEN_H_ /** * @mainpage Primary MCU Source Code Documentation * * * This manual describes the functions and variables used in the foxBMS software. * Four sections can be found: * * - Common Interfaces * - Modules * - Data structures * - Files * * They can be browsed with the navigation bar on the left. * * <h2>Internal References</h2> * * <h3>Related Documentation References</h3> * <table> * <tr><th><b>Latest online available documentation</b> <th> <b>Version available if the documentation was locally build</b> * <tr><td>@warning The links to documentaions in this column always points to the latest realsed version on GitHub and your local changes can not be found in that online version. <td> @warning The links to documentaions in this column only exist after building the documentation locally. If this was not done, the link will not work. * <tr><td><a target="_blank" href="https://foxbms.readthedocs.io/"><b>Online</b> foxBMS General Documentation</a> <td> <a target="_blank" href="../../../documentation/index.html"><b>Local</b> foxBMS General Documentation</a> * <tr><td><a target="_blank" href="https://iisb-foxbms.iisb.fraunhofer.de/foxbms/documentation/primary/html/index.html"><b>Online</b> Primary MCU Source Code Documentation</a> <td> <a target="_blank" href="../../../primary/doxygen/html/index.html"><b>Local</b> Primary MCU Source Code Documentation</a> * <tr><td><a target="_blank" href="https://iisb-foxbms.iisb.fraunhofer.de/foxbms/documentation/secondary/html/index.html"><b>Online</b> Secondary MCU Source Code Documentation</a> <td> <a target="_blank" href="../../../secondary/doxygen/html/index.html"><b>Local</b> Secondary MCU Source Code Documentation</a> * </table> * * <h3>User Configurable Options</h3> * Direct access to the user configurable options: * - @ref CONFIG_PAGE * * <h3>Application Programming Interface</h3> * Direct access to the API: * - @ref API_PAGE * * Direct access to the source modules: * - @ref APPLICATION * - @ref APPLICATION_CONF * - @ref ENGINE * - @ref ENGINE_CONF * - @ref GENERAL * - @ref GENERAL_CONF * - @ref DRIVERS * - @ref DRIVERS_CONF * - @ref UTIL * - @ref UTIL_CONF * - @ref OS * * * @defgroup APPLICATION Applications * Contains low priority custom and user tasks * * @defgroup APPLICATION_CONF Application Configuration * Contains configuration for low priority custom and user tasks * * @defgroup ENGINE Engine * Contains high priority kernel and database handler * * @defgroup ENGINE_CONF Engine Configuration * Contains configuration for high priority kernel and database handler * * @defgroup GENERAL General * Contains the "main" function and interrupt declaration * * @defgroup GENERAL_CONF General Configuration * System related configuration * * @defgroup DRIVERS Drivers * Contains the drivers used by foxBMS * * @defgroup DRIVERS_CONF Driver Configuration * Contains the configuration for the drivers used by foxBMS * * @defgroup UTIL Utilities * Contains utilities used by foxBMS * * @defgroup UTIL_CONF Utility Configuration * Contains the configuration for the utilities used by foxBMS * * @defgroup OS Operating System * Contains functions related to the operating system * * */ /** * @page API_PAGE User Interfaces (API) * * foxBMS software provides the following user interfaces: * * Reference: * - @ref API_OS * - @ref API_DIAG * * @defgroup API_OS Operating System Interfaces * Contains the provided interfaces to FreeRTOS in the foxBMS software * * @defgroup API_DIAG Diagnosis Interfaces * Contains the provided interfaces to diagnostis module * * @defgroup API All Interfaces * Contains a list of all interfaces in the foxBMS software * */ /** * @page CONFIG_PAGE User configurable options * * A description of the configuration options available to the user can be found here: * * - @ref CONFIG_GENERAL * - @ref CONFIG_SOX * - @ref CONFIG_BMS * - @ref CONFIG_BATTERYCELL * - @ref CONFIG_BATTERYSYSTEM * - @ref CONFIG_BKPSRAM * - @ref CONFIG_CANSIGNAL * - @ref CONFIG_CAN * - @ref CONFIG_CONTACTOR * - @ref CONFIG_EEPR * - @ref CONFIG_INTERLOCK * - @ref CONFIG_IO * - @ref CONFIG_ISOGUARD * - @ref CONFIG_LTC * - @ref CONFIG_TIMER * - @ref CONFIG_IR155 * * @defgroup CONFIG_GENERAL General user configuration * * Contains the general software user configuration, e.g. what security features to include. * * @defgroup CONFIG_SOX SOX User configuration * * Contains the configuration settings for the SOX estimation, e.g. current, voltage and temperature limits. * * @defgroup CONFIG_BMS BMS User configuration * * Contains the configuration settings for the BMS system behaviour, e.g. time constants. * * @defgroup CONFIG_BATTERYCELL BATTERYCELL User configuration * * Contains the configuration settings of the battery cell, e.g. current, voltage and temperature limits. * * @defgroup CONFIG_BATTERYSYSTEM BATTERYSYSTEM User configuration * * Contains the configuration settings of the battery system, e.g. number of cells and modules or which monitoring chip is used. * * @defgroup CONFIG_BKPSRAM BKPSRAM User configuration * * Contains the configuration settings backup SRAM. * * @defgroup CONFIG_CANSIGNAL CANSIGNAL User configuration * * Contains the configuration of the CAN BUS signals used in the BMS. * * @defgroup CONFIG_CAN CAN User configuration * * Contains the configuration settings of the CAN BUS interface, e.g. baud rate. * * @defgroup CONFIG_CONTACTOR CONTACTOR User configuration * * Contains the configuration settings for the contactors, e.g. number of contactors and time constants. * * @defgroup CONFIG_EEPR EEPR User configuration * * Contains the configuration settings for the EEPROM. * * @defgroup CONFIG_INTERLOCK INTERLOCK User configuration * * Contains the configuration settings for the interlock. * * @defgroup CONFIG_IO IO User configuration * * Contains the configuration of the GPIO pins contained in the MCU. * * @defgroup CONFIG_ISOGUARD ISOGUARD User configuration * * Contains the configuration settings for isolation monitoring device. * * @defgroup CONFIG_LTC LTC User configuration * * Contains the configuration settings for LTC battery monitoring chip driver. * * @defgroup CONFIG_TIMER TIMER User configuration * * Contains the configuration settings for timer module. * * @defgroup CONFIG_IR155 IR155 User configuration * * Contains the configuration settings for IR155 isometer. * */ #endif /* DOXYGEN_H_ */
tonyhuang84/foxbms
embedded-software/mcu-secondary/src/general/config/batterycell_cfg.h
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file batterycell_cfg.h * @author <NAME> * @date 14.03.2017 (date of creation) * @ingroup BATTERY_CELL_CONF * @prefix BC * * @brief Configuration of the battery cell (e.g., minimum and maximum cell voltage) * * This files contains basic macros of the battery cell in order to derive needed inputs * in other parts of the software. These macros are all depended on the hardware. * */ #ifndef BATTERYCELL_CFG_H_ #define BATTERYCELL_CFG_H_ #if BUILD_MODULE_IMPORT_CELL_DATASHEET == 1 #include "LG_INR18650MJ1.h" #else /** * @ingroup CONFIG_BATTERYCELL * Maximum temperature limit during discharge. * When maximum safety limit (MSL) is violated, error state is requested and * contactors will open. When recommended safety limit (RSL) or maximum * operating limit (MOL) is violated, the respective flag will be set. * \par Type: * int * \par Unit: * &deg;C * \par Default: * 55 */ #define BC_TEMPMAX_DISCHARGE_MSL 55 /** * @ingroup CONFIG_BATTERYCELL * Minimum temperature limit during discharge. * When maximum safety limit (MSL) is violated, error state is requested and * contactors will open. When recommended safety limit (RSL) or maximum * operating limit (MOL) is violated, the respective flag will be set. * \par Type: * int * \par Unit: * &deg;C * \par Default: * -20 */ #define BC_TEMPMIN_DISCHARGE_MSL -20 /* &deg;C */ /** * @ingroup CONFIG_BATTERYCELL * Maximum temperature limit during charge. * When maximum safety limit (MSL) is violated, error state is requested and * contactors will open. When recommended safety limit (RSL) or maximum * operating limit (MOL) is violated, the respective flag will be set. * \par Type: * int * \par Unit: * &deg;C * \par Default: * 45 */ #define BC_TEMPMAX_CHARGE_MSL 45 /** * @ingroup CONFIG_BATTERYCELL * Minimum temperature limit during discharge. * When maximum safety limit (MSL) is violated, error state is requested and * contactors will open. When recommended safety limit (RSL) or maximum * operating limit (MOL) is violated, the respective flag will be set. * \par Type: * int * \par Unit: * &deg;C * \par Default: * 0 */ #define BC_TEMPMIN_CHARGE_MSL -20 /** * @ingroup CONFIG_BATTERYCELL * Maximum cell voltage limit. * When maximum safety limit (MSL) is violated, error state is requested and * contactors will open. When recommended safety limit (RSL) or maximum * operating limit (MOL) is violated, the respective flag will be set. * \par Type: * int * \par Unit: * mV * \par Default: * 2800 */ #define BC_VOLTMAX_MSL 2800 /** * @ingroup CONFIG_BATTERYCELL * nominal cell voltage according to datasheet * \par Type: * int * \par Unit: * mV * \par Default: * 2500 */ #define BC_VOLT_NOMINAL 2500 /** * @ingroup CONFIG_BATTERYCELL * Minimum cell voltage limit. * When maximum safety limit (MSL) is violated, error state is requested and * contactors will open. When recommended safety limit (RSL) or maximum * operating limit (MOL) is violated, the respective flag will be set. * \par Type: * int * \par Unit: * mV * \par Default: * 1700 */ #define BC_VOLTMIN_MSL 1700 /** * @ingroup CONFIG_BATTERYCELL * Maximum discharge current limit. * When maximum safety limit (MSL) is violated, error state is requested and * contactors will open. When recommended safety limit (RSL) or maximum * operating limit (MOL) is violated, the respective flag will be set. * \par Type: * int * \par Unit: * mA * \par Default: * 180000 */ #define BC_CURRENTMAX_DISCHARGE_MSL 180000 /** * @ingroup CONFIG_BATTERYCELL * Maximum charge current limit. * When maximum safety limit (MSL) is violated, error state is requested and * contactors will open. When recommended safety limit (RSL) or maximum * operating limit (MOL) is violated, the respective flag will be set. * \par Type: * int * \par Unit: * mA * \par Default: * 180000 */ #define BC_CURRENTMAX_CHARGE_MSL 180000 /* * the cell capacity used for SOC calculation, in this case Ah counting * @type int * @unit mAh * @default 3500 * @group */ #define BC_CAPACITY 3500 #endif #endif /* BATTERYCELL_CFG_H_ */
tonyhuang84/foxbms
embedded-software/mcu-primary/src/application/sox/sox.c
<filename>embedded-software/mcu-primary/src/application/sox/sox.c /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file sox.c * @author f<NAME> * @date 13.11.2015 (date of creation) * @ingroup APPLICATION * @prefix SOX * * @brief SOX module responsible for calculation of current derating and of SOC * */ /*================== Includes =============================================*/ #include "sox.h" #include "database.h" #include "batterycell_cfg.h" #include "batterysystem_cfg.h" #include "nvramhandler.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ static SOX_STATE_s sox_state = { .sensor_cc_used = 0, .cc_scaling = 0.0, .counter = 0, }; static DATA_BLOCK_CURRENT_SENSOR_s sox_current_tab; static DATA_BLOCK_MINMAX_s cellminmax; static DATA_BLOCK_SOX_s sox; static DATA_BLOCK_SOF_s sof; static DATA_BLOCK_CONTFEEDBACK_s contfeedbacktab; static uint32_t soc_previous_current_timestamp = 0; static uint32_t soc_previous_current_timestamp_cc = 0; /** @{ * module-local static Variables that are calculated at startup and used later to avoid divisions at runtime */ static SOF_curve_s sofCurveRecOperatingCurrent; static SOF_curve_s sofCurve_MOL; static SOF_curve_s sofCurve_RSL; static SOF_curve_s sofCurve_MSL; static SOX_SOF_s sof_recOperatingCurrent; static SOX_SOF_s sof_mol_Level; static SOX_SOF_s sof_rsl_Level; static SOX_SOF_s sof_msl_Level; /*================== Function Prototypes ==================================*/ static void SOF_CalculateCurves(const SOX_SOF_CONFIG_s *configLimitValues, SOF_curve_s* calcCurveValues); static void SOF_Calculate(int16_t maxtemp, int16_t mintemp, uint16_t maxvolt, uint16_t minvolt, uint16_t maxsoc, uint16_t minsoc); static void SOF_CalculateVoltageBased(float MinVoltage, float MaxVoltage, SOX_SOF_s *ResultValues, const SOX_SOF_CONFIG_s *configLimitValues, SOF_curve_s* calcCurveValues); static void SOF_CalculateSocBased(float MinSoc, float MaxSoc, SOX_SOF_s *ResultValues, const SOX_SOF_CONFIG_s *configLimitValues, SOF_curve_s* calcCurveValues); static void SOF_CalculateTemperatureBased(float MinTemp, float MaxTemp, SOX_SOF_s *ResultValues, const SOX_SOF_CONFIG_s *configLimitValues, SOF_curve_s* calcCurveValues); static void SOF_MinimumOfThreeSofValues(SOX_SOF_s Ubased, SOX_SOF_s Sbased, SOX_SOF_s Tbased, SOX_SOF_s *resultValues); static float SOF_MinimumOfThreeValues(float value1, float value2, float value3); static float SOC_GetFromVoltage(float voltage); /*================== Function Implementations =============================*/ void SOC_Init(uint8_t cc_present) { SOX_SOC_s soc = {50.0, 50.0, 50.0}; DATA_BLOCK_ERRORSTATE_s error_flags; DB_ReadBlock(&error_flags, DATA_BLOCK_ID_ERRORSTATE); DB_ReadBlock(&sox_current_tab, DATA_BLOCK_ID_CURRENT_SENSOR); NVM_getSOC(&soc); if (cc_present == TRUE) { soc_previous_current_timestamp_cc = sox_current_tab.timestamp_cc; error_flags.can_cc_used = 1; sox_state.sensor_cc_used = TRUE; if (POSITIVE_DISCHARGE_CURRENT == TRUE) { sox_state.cc_scaling = soc.mean + 100.0*sox_current_tab.current_counter/(3600.0*(SOX_CELL_CAPACITY/1000.0)); } else { sox_state.cc_scaling = soc.mean - 100.0*sox_current_tab.current_counter/(3600.0*(SOX_CELL_CAPACITY/1000.0)); } sox.soc_mean = soc.mean; sox.soc_min = soc.min; sox.soc_max = soc.max; if (sox.soc_mean > 100.0) { sox.soc_mean = 100.0; } if (sox.soc_mean < 0.0) { sox.soc_mean = 0.0; } if (sox.soc_min > 100.0) { sox.soc_min = 100.0; } if (sox.soc_min < 0.0) { sox.soc_min = 0.0; } if (sox.soc_max > 100.0) { sox.soc_max = 100.0; } if (sox.soc_max < 0.0) { sox.soc_max = 0.0; } /* Alternatively, SOC can be initialized with {V,SOC} lookup table if available */ /* with the function SOC_Init_Lookup_Table() */ sox.state = 0; sox.timestamp = 0; sox.previous_timestamp = 0; } else { soc_previous_current_timestamp = sox_current_tab.timestamp_cur; error_flags.can_cc_used = 0; sox_state.sensor_cc_used = FALSE; } DB_WriteBlock(&error_flags, DATA_BLOCK_ID_ERRORSTATE); DB_WriteBlock(&sox, DATA_BLOCK_ID_SOX); } void SOC_SetValue(float soc_value_min, float soc_value_max, float soc_value_mean) { SOX_SOC_s soc = {50.0, 50.0, 50.0}; if (soc_value_min < 0.0) { soc_value_min = 0.0; } if (soc_value_min > 100.0) { soc_value_min = 100.0; } if (soc_value_max < 0.0) { soc_value_max = 0.0; } if (soc_value_max > 100.0) { soc_value_max = 100.0; } if (soc_value_mean < 0.0) { soc_value_mean = 0.0; } if (soc_value_mean > 100.0) { soc_value_mean = 100.0; } if (sox_state.sensor_cc_used == FALSE) { soc.mean = soc_value_mean; soc.min = soc_value_min; soc.max = soc_value_max; NVM_setSOC(&soc); sox.soc_mean = soc.mean; sox.soc_min = soc.min; sox.soc_max = soc.max; sox.state = 0; sox.timestamp = 0; sox.previous_timestamp = 0; DB_WriteBlock(&sox, DATA_BLOCK_ID_SOX); } else { DB_ReadBlock(&sox_current_tab, DATA_BLOCK_ID_CURRENT_SENSOR); soc.mean = soc_value_mean; soc.min = soc_value_min; soc.max = soc_value_max; if (POSITIVE_DISCHARGE_CURRENT == TRUE) { sox_state.cc_scaling = soc.mean + 100.0*sox_current_tab.current_counter/(3600.0*(SOX_CELL_CAPACITY/1000.0)); } else { sox_state.cc_scaling = soc.mean - 100.0*sox_current_tab.current_counter/(3600.0*(SOX_CELL_CAPACITY/1000.0)); } sox.soc_mean = soc.mean; sox.soc_min = sox.soc_mean; sox.soc_max = sox.soc_mean; if (sox.soc_mean > 100.0) { sox.soc_mean = 100.0; } if (sox.soc_mean < 0.0) { sox.soc_mean = 0.0; } if (sox.soc_min > 100.0) { sox.soc_min = 100.0; } if (sox.soc_min < 0.0) { sox.soc_min = 0.0; } if (sox.soc_max > 100.0) { sox.soc_max = 100.0; } if (sox.soc_max < 0.0) { sox.soc_max = 0.0; } NVM_setSOC(&soc); DB_WriteBlock(&sox, DATA_BLOCK_ID_SOX); } } void SOC_Set_Lookup_Table(void) { float soc_min = 50.0; float soc_max = 50.0; float soc_mean = 50.0; DB_ReadBlock(&cellminmax, DATA_BLOCK_ID_MINMAX); DB_ReadBlock(&sox_current_tab, DATA_BLOCK_ID_CURRENT_SENSOR); soc_mean = SOC_GetFromVoltage((float)(cellminmax.voltage_mean)); soc_min = SOC_GetFromVoltage((float)(cellminmax.voltage_min)); soc_max = SOC_GetFromVoltage((float)(cellminmax.voltage_max)); SOC_SetValue(soc_min, soc_max, soc_mean); } void SOC_Calculation(void) { uint32_t timestamp = 0; uint32_t previous_timestamp = 0; uint32_t timestamp_cc = 0; uint32_t previous_timestamp_cc = 0; uint32_t timestep = 0; DATA_BLOCK_CURRENT_SENSOR_s cans_current_tab; SOX_SOC_s soc = {50.0, 50.0, 50.0}; float deltaSOC = 0.0; if (sox_state.sensor_cc_used == FALSE) { DB_ReadBlock(&sox_current_tab, DATA_BLOCK_ID_CURRENT_SENSOR); timestamp = sox_current_tab.timestamp_cur; previous_timestamp = sox_current_tab.previous_timestamp_cur; if (soc_previous_current_timestamp != timestamp) { /* check if current measurement has been updated */ timestep = timestamp - previous_timestamp; if (timestep > 0) { NVM_getSOC(&soc); /* Current in charge direction negative means SOC increasing --> BAT naming, not ROB */ /* soc_mean = soc_mean - (sox_current_tab.current *mA* /(float)SOX_CELL_CAPACITY (*mAh*)) * (float)(timestep) * (10.0/3600.0); */ /*milliseconds*/ if (POSITIVE_DISCHARGE_CURRENT == TRUE) { deltaSOC = (((sox_current_tab.current)*(float)(timestep)/10))/(3600.0*SOX_CELL_CAPACITY); /* ((mA *ms *(1s/1000ms)) / (3600(s/h) *mAh)) *100% */ } else { deltaSOC = -(((sox_current_tab.current)*(float)(timestep)/10))/(3600.0*SOX_CELL_CAPACITY); /* ((mA *ms *(1s/1000ms)) / (3600(s/h) *mAh)) *100% */ } soc.mean = soc.mean - deltaSOC; soc.min = soc.min - deltaSOC; soc.max = soc.max - deltaSOC; if (soc.mean > 100.0) { soc.mean = 100.0; } if (soc.mean < 0.0) { soc.mean = 0.0; } if (soc.min > 100.0) { soc.min = 100.0; } if (soc.min < 0.0) { soc.min = 0.0; } if (soc.max > 100.0) { soc.max = 100.0; } if (soc.max < 0.0) { soc.max = 0.0; } sox.soc_mean = soc.mean; sox.soc_min = soc.min; sox.soc_max = soc.max; NVM_setSOC(&soc); sox.state++; DB_WriteBlock(&sox, DATA_BLOCK_ID_SOX); } } /* end check if current measurement has been updated */ /* update the variable for the next check */ soc_previous_current_timestamp = sox_current_tab.timestamp; } else { DB_ReadBlock(&sox_current_tab, DATA_BLOCK_ID_CURRENT_SENSOR); timestamp_cc = sox_current_tab.timestamp_cc; previous_timestamp_cc = sox_current_tab.previous_timestamp_cc; if (previous_timestamp_cc != timestamp_cc) { /* check if cc measurement has been updated */ DB_ReadBlock(&cans_current_tab, DATA_BLOCK_ID_CURRENT_SENSOR); if (POSITIVE_DISCHARGE_CURRENT == TRUE) { sox.soc_mean = sox_state.cc_scaling - 100.0*cans_current_tab.current_counter/(3600.0*(SOX_CELL_CAPACITY/1000.0)); } else { sox.soc_mean = sox_state.cc_scaling + 100.0*cans_current_tab.current_counter/(3600.0*(SOX_CELL_CAPACITY/1000.0)); } sox.soc_min = sox.soc_mean; sox.soc_max = sox.soc_mean; soc.mean = sox.soc_mean; soc.min = sox.soc_min; soc.max = sox.soc_max; if (sox.soc_mean > 100.0) { sox.soc_mean = 100.0; } if (sox.soc_mean < 0.0) { sox.soc_mean = 0.0; } if (sox.soc_min > 100.0) { sox.soc_min = 100.0; } if (sox.soc_min < 0.0) { sox.soc_min = 0.0; } if (sox.soc_max > 100.0) { sox.soc_max = 100.0; } if (sox.soc_max < 0.0) { sox.soc_max = 0.0; } NVM_setSOC(&soc); sox.state++; DB_WriteBlock(&sox, DATA_BLOCK_ID_SOX); } soc_previous_current_timestamp_cc = sox_current_tab.timestamp_cc; } } void SOF_Init(void) { /* Calculating SOF curve for the recommended operating current */ SOF_CalculateCurves(&sox_sof_config_maxAllowedCurrent, &sofCurveRecOperatingCurrent); #if BMS_TEST_CELL_SOF_LIMITS == TRUE /* Calculating SOF curve for maximum operating limit */ SOF_CalculateCurves(&sox_sof_config_MOL, &sofCurve_MOL); /* Calculating SOF curve for recommended safety limit */ SOF_CalculateCurves(&sox_sof_config_RSL, &sofCurve_RSL); /* Calculating SOF curve for maximum safety limit */ SOF_CalculateCurves(&sox_sof_config_MSL, &sofCurve_MSL); #endif } static void SOF_CalculateCurves(const SOX_SOF_CONFIG_s *configLimitValues, SOF_curve_s* calcCurveValues) { /* Calculating SOF curve for the maximum allowed current for MOL/RSL/MSL */ calcCurveValues->Slope_TLowDischa = (configLimitValues->I_DischaMax_Cont - configLimitValues->I_Limphome) / (configLimitValues->Cutoff_TLow_Discha - configLimitValues->Limit_TLow_Discha); calcCurveValues->Offset_TLowDischa = configLimitValues->I_Limphome - (calcCurveValues->Slope_TLowDischa * configLimitValues->Limit_TLow_Discha); calcCurveValues->Slope_THighDischa = (0 - configLimitValues->I_DischaMax_Cont) / (configLimitValues->Limit_THigh_Discha - configLimitValues->Cutoff_THigh_Discha); calcCurveValues->Offset_THighDischa = 0 - calcCurveValues->Slope_THighDischa * configLimitValues->Limit_THigh_Discha; calcCurveValues->Slope_TLowCharge = (configLimitValues->I_ChargeMax_Cont - 0) / (configLimitValues->Cutoff_TLow_Charge - configLimitValues->Limit_TLow_Charge); calcCurveValues->Offset_TLowCharge = 0 - (calcCurveValues->Slope_TLowCharge * configLimitValues->Limit_TLow_Charge); calcCurveValues->Slope_THighCharge = (0 - configLimitValues->I_ChargeMax_Cont) / (configLimitValues->Limit_THigh_Charge - configLimitValues->Cutoff_THigh_Charge); calcCurveValues->Offset_THighCharge = 0 - calcCurveValues->Slope_THighCharge * configLimitValues->Limit_THigh_Charge; calcCurveValues->Slope_SocDischa = (configLimitValues->I_DischaMax_Cont - configLimitValues->I_Limphome) / (configLimitValues->Cutoff_Soc_Discha - configLimitValues->Limit_Soc_Discha); calcCurveValues->Offset_SocDischa = configLimitValues->I_Limphome - (calcCurveValues->Slope_SocDischa * configLimitValues->Limit_Soc_Discha); calcCurveValues->Slope_SocCharge = (configLimitValues->I_ChargeMax_Cont - 0.0) / (configLimitValues->Cutoff_Soc_Charge - configLimitValues->Limit_Soc_Charge); calcCurveValues->Offset_SocCharge = 0 - calcCurveValues->Slope_SocCharge * configLimitValues->Limit_Soc_Charge; calcCurveValues->Slope_VoltageDischa = (configLimitValues->I_DischaMax_Cont - 0) / (configLimitValues->Cutoff_Voltage_Discha - configLimitValues->Limit_Voltage_Discha); calcCurveValues->Offset_VoltageDischa = 0 - calcCurveValues->Slope_SocDischa * configLimitValues->Limit_Soc_Discha; calcCurveValues->Slope_VoltageCharge = (configLimitValues->I_ChargeMax_Cont - 0) / (configLimitValues->Cutoff_Voltage_Charge - configLimitValues->Limit_Voltage_Charge); calcCurveValues->Offset_VoltageCharge = 0 - calcCurveValues->Slope_VoltageCharge * configLimitValues->Limit_Soc_Discha; } void SOF_Calculation(void) { DB_ReadBlock(&cellminmax, DATA_BLOCK_ID_MINMAX); DB_ReadBlock(&sox, DATA_BLOCK_ID_SOX); DB_ReadBlock(&sof, DATA_BLOCK_ID_SOF); DB_ReadBlock(&contfeedbacktab, DATA_BLOCK_ID_CONTFEEDBACK); /* Calculate SOF limits */ SOF_Calculate(cellminmax.temperature_max, cellminmax.temperature_min, cellminmax.voltage_max, cellminmax.voltage_min, (uint16_t)(100.0*sox.soc_max), (uint16_t)(100.0*sox.soc_min)); /* Write MOL level */ sof.continuous_charge_MOL = sof_mol_Level.current_Charge_cont_max; sof.continuous_discharge_MOL = sof_mol_Level.current_Discha_cont_max; /* Write RSL level */ sof.continuous_charge_RSL = sof_rsl_Level.current_Charge_cont_max; sof.continuous_discharge_RSL = sof_rsl_Level.current_Discha_cont_max; /* Write MSL level */ sof.continuous_charge_MSL = sof_msl_Level.current_Charge_cont_max; sof.continuous_discharge_MSL = sof_msl_Level.current_Discha_cont_max; /* if Contactor MainPlus and MainMinus are not closed (when they are closed, state_feedback is 0x0C) */ #if BS_SEPARATE_POWERLINES == 1 if (!((contfeedbacktab.contactor_feedback & 0x3F) == 0x28 || (contfeedbacktab.contactor_feedback & 0x3F) == 0x05)) { #else if ((contfeedbacktab.contactor_feedback & 0x3F) != 0x05) { #endif /* BS_SEPARATE_POWERLINES == 1 */ sof.recommended_continuous_charge = 0.0; sof.recommended_continuous_discharge = 0.0; sof.recommended_peak_charge = 0.0; sof.recommended_peak_discharge = 0.0; } else { sof.recommended_continuous_charge = sof_recOperatingCurrent.current_Charge_cont_max; sof.recommended_continuous_discharge = sof_recOperatingCurrent.current_Discha_cont_max; sof.recommended_peak_charge = sof_recOperatingCurrent.current_Charge_peak_max; sof.recommended_peak_discharge = sof_recOperatingCurrent.current_Discha_peak_max; } DB_WriteBlock(&sof, DATA_BLOCK_ID_SOF); } /** * @brief look-up table for SOC initialization (mean, min and max). * * @param voltage: voltage of battery cell * * @return SOC value */ float SOC_GetFromVoltage(float voltage) { float SOC = 0.50; return SOC; } /** * @brief calculates State of function which means how much current can be delivered by battery to stay in safe operating area. * * @param maxtemp maximum temperature in system in �C * @param mintemp minimum temperature in system in �C * @param maxvolt maximum voltage in system in mV * @param minvolt minimum voltage in system in mV * @param maxsoc maximum soc in system with resolution 0.01% (0..10000) * @param minsoc minimum soc in system with resolution 0.01% (0..10000) */ static void SOF_Calculate(int16_t maxtemp, int16_t mintemp, uint16_t maxvolt, uint16_t minvolt, uint16_t maxsoc, uint16_t minsoc) { SOX_SOF_s UbasedSof = {0.0, 0.0, 0.0}; SOX_SOF_s SbasedSof = {0.0, 0.0, 0.0}; SOX_SOF_s TbasedSof = {0.0, 0.0, 0.0}; /* Calculate maximum allowed current depending on current values */ SOF_CalculateVoltageBased((float)minvolt, (float)maxvolt, &UbasedSof, &sox_sof_config_maxAllowedCurrent, &sofCurveRecOperatingCurrent); SOF_CalculateSocBased((float)minsoc, (float)maxsoc, &SbasedSof, &sox_sof_config_maxAllowedCurrent, &sofCurveRecOperatingCurrent); SOF_CalculateTemperatureBased((float)mintemp, (float)maxtemp, &TbasedSof, &sox_sof_config_maxAllowedCurrent, &sofCurveRecOperatingCurrent); SOF_MinimumOfThreeSofValues(UbasedSof, SbasedSof, TbasedSof, &sof_recOperatingCurrent); #if BMS_TEST_CELL_SOF_LIMITS == TRUE /* Calculate maximum allowed current MOL level */ SOF_CalculateVoltageBased((float)minvolt, (float)maxvolt, &UbasedSof, &sox_sof_config_MOL, &sofCurve_MOL); SOF_CalculateSocBased((float)minsoc, (float)maxsoc, &SbasedSof, &sox_sof_config_MOL, &sofCurve_MOL); SOF_CalculateTemperatureBased((float)mintemp, (float)maxtemp, &TbasedSof, &sox_sof_config_MOL, &sofCurve_MOL); SOF_MinimumOfThreeSofValues(UbasedSof, SbasedSof, TbasedSof, &sof_mol_Level); /* Calculate maximum allowed current RSL level */ SOF_CalculateVoltageBased((float)minvolt, (float)maxvolt, &UbasedSof, &sox_sof_config_RSL, &sofCurve_RSL); SOF_CalculateSocBased((float)minsoc, (float)maxsoc, &SbasedSof, &sox_sof_config_RSL, &sofCurve_RSL); SOF_CalculateTemperatureBased((float)mintemp, (float)maxtemp, &TbasedSof, &sox_sof_config_RSL, &sofCurve_RSL); SOF_MinimumOfThreeSofValues(UbasedSof, SbasedSof, TbasedSof, &sof_rsl_Level); /* Calculate maximum allowed current MSL level */ SOF_CalculateVoltageBased((float)minvolt, (float)maxvolt, &UbasedSof, &sox_sof_config_MSL, &sofCurve_MSL); SOF_CalculateSocBased((float)minsoc, (float)maxsoc, &SbasedSof, &sox_sof_config_MSL, &sofCurve_MSL); SOF_CalculateTemperatureBased((float)mintemp, (float)maxtemp, &TbasedSof, &sox_sof_config_MSL, &sofCurve_MSL); SOF_MinimumOfThreeSofValues(UbasedSof, SbasedSof, TbasedSof, &sof_msl_Level); #else sof_mol_Level.current_Charge_cont_max = BC_CURRENTMAX_CHARGE_MOL; sof_mol_Level.current_Discha_cont_max = BC_CURRENTMAX_DISCHARGE_MOL; sof_rsl_Level.current_Charge_cont_max = BC_CURRENTMAX_CHARGE_MOL; sof_rsl_Level.current_Discha_cont_max = BC_CURRENTMAX_DISCHARGE_MOL; sof_msl_Level.current_Charge_cont_max = BC_CURRENTMAX_CHARGE_MOL; sof_msl_Level.current_Discha_cont_max = BC_CURRENTMAX_DISCHARGE_MOL; #endif } /** * @brief calculates the SoF from voltage data (i.e., minimum and maximum voltage) * * @param MinVoltage minimum sell voltage * @param MaxVoltage maximum cell voltage * @param ResultValues Voltage-based SOF */ static void SOF_CalculateVoltageBased(float MinVoltage, float MaxVoltage, SOX_SOF_s *ResultValues, const SOX_SOF_CONFIG_s *configLimitValues, SOF_curve_s* calcCurveValues) { /* min voltage issues */ if (MinVoltage <= configLimitValues->Limit_Voltage_Discha) { ResultValues->current_Discha_cont_max = 0; ResultValues->current_Discha_peak_max = 0; } else { if (MinVoltage <= configLimitValues->Cutoff_Voltage_Discha) { ResultValues->current_Discha_cont_max = (calcCurveValues->Slope_VoltageDischa * (MinVoltage-configLimitValues->Limit_Voltage_Discha)); ResultValues->current_Discha_peak_max = ResultValues->current_Discha_cont_max; } else { ResultValues->current_Discha_cont_max = configLimitValues->I_DischaMax_Cont; ResultValues->current_Discha_peak_max = configLimitValues->I_DischaMax_Cont; } } /* max voltage issues */ if (MaxVoltage >= configLimitValues->Limit_Voltage_Charge) { ResultValues->current_Charge_cont_max = 0; ResultValues->current_Charge_peak_max = 0; } else { if (MaxVoltage >= configLimitValues->Cutoff_Voltage_Charge) { ResultValues->current_Charge_cont_max = (calcCurveValues->Slope_VoltageCharge * (MaxVoltage- configLimitValues->Limit_Voltage_Charge)); ResultValues->current_Charge_peak_max = ResultValues->current_Charge_cont_max; } else { ResultValues->current_Charge_cont_max = configLimitValues->I_ChargeMax_Cont; ResultValues->current_Charge_peak_max = configLimitValues->I_ChargeMax_Cont; } } } /** * @brief calculates the SoF from SoC data (i.e., minimum and maximum SoC of cells, both values are equal in case of Ah-counter) * * @param MinSoc minimum State of Charge * @param MaxSoc maximum State of Charge * @param ResultValues pointer where to store the results */ static void SOF_CalculateSocBased(float MinSoc, float MaxSoc, SOX_SOF_s *ResultValues, const SOX_SOF_CONFIG_s *configLimitValues, SOF_curve_s* calcCurveValues) { /* min voltage issues */ if (MinSoc <= configLimitValues->Limit_Soc_Discha) { ResultValues->current_Discha_cont_max = configLimitValues->I_Limphome; ResultValues->current_Discha_peak_max = configLimitValues->I_Limphome; } else { if (MinSoc <= configLimitValues->Cutoff_Soc_Discha) { ResultValues->current_Discha_cont_max = calcCurveValues->Slope_SocDischa * MinSoc + calcCurveValues->Offset_SocDischa; ResultValues->current_Discha_peak_max = ResultValues->current_Discha_cont_max; } else { ResultValues->current_Discha_cont_max = configLimitValues->I_DischaMax_Cont; ResultValues->current_Discha_peak_max = configLimitValues->I_DischaMax_Cont; } } /* max voltage issues */ if (MaxSoc >= configLimitValues->Limit_Soc_Charge) { ResultValues->current_Charge_cont_max = 0; ResultValues->current_Charge_peak_max = 0; } else { if (MaxSoc >= configLimitValues->Cutoff_Soc_Charge) { ResultValues->current_Charge_cont_max = calcCurveValues->Slope_SocCharge * MaxSoc + calcCurveValues->Offset_SocCharge; ResultValues->current_Charge_peak_max = ResultValues->current_Charge_cont_max; } else { ResultValues->current_Charge_cont_max = configLimitValues->I_ChargeMax_Cont; ResultValues->current_Charge_peak_max = configLimitValues->I_ChargeMax_Cont; } } } /** * @brief calculates the SoF from temperature data (i.e., minimum and maximum temperature of cells) * * @param MinTemp minimum temperature of cells * @param MaxTemp maximum temperature of cells * @param ResultValues pointer where to store the results */ static void SOF_CalculateTemperatureBased(float MinTemp, float MaxTemp, SOX_SOF_s *ResultValues, const SOX_SOF_CONFIG_s *configLimitValues, SOF_curve_s* calcCurveValues) { SOX_SOF_s dummyResultValues = {0.0, 0.0, 0.0}; /* Temperature low Discharge */ if (MinTemp <= configLimitValues->Limit_TLow_Discha) { ResultValues->current_Discha_cont_max = configLimitValues->I_Limphome; ResultValues->current_Discha_peak_max = configLimitValues->I_Limphome; } else { if (MinTemp <= configLimitValues->Cutoff_TLow_Discha) { ResultValues->current_Discha_cont_max = calcCurveValues->Slope_TLowDischa * MinTemp + calcCurveValues->Offset_TLowDischa; ResultValues->current_Discha_peak_max = ResultValues->current_Discha_cont_max; } else { ResultValues->current_Discha_cont_max = configLimitValues->I_DischaMax_Cont; ResultValues->current_Discha_peak_max = configLimitValues->I_DischaMax_Cont; } } /* Temperature low charge */ if (MinTemp <= configLimitValues->Limit_TLow_Charge) { ResultValues->current_Charge_cont_max = 0; ResultValues->current_Charge_peak_max = 0; } else { if (MinTemp <= configLimitValues->Cutoff_TLow_Charge) { ResultValues->current_Charge_cont_max = calcCurveValues->Slope_TLowCharge * MinTemp + calcCurveValues->Offset_TLowCharge; ResultValues->current_Charge_peak_max = ResultValues->current_Charge_cont_max; } else { ResultValues->current_Charge_cont_max = configLimitValues->I_ChargeMax_Cont; ResultValues->current_Charge_peak_max = configLimitValues->I_ChargeMax_Cont; } } /* Temperature high discharge */ if (MaxTemp >= configLimitValues->Limit_THigh_Discha) { ResultValues->current_Discha_cont_max = 0; ResultValues->current_Discha_peak_max = 0; dummyResultValues.current_Discha_cont_max = 0; dummyResultValues.current_Discha_peak_max = 0; } else { if (MaxTemp >= configLimitValues->Cutoff_THigh_Discha) { dummyResultValues.current_Discha_cont_max = (calcCurveValues->Slope_THighDischa * MaxTemp + calcCurveValues->Offset_THighDischa); dummyResultValues.current_Discha_peak_max = dummyResultValues.current_Discha_cont_max; } else { /* do nothing because this situation is handled with MinTemp */ dummyResultValues.current_Discha_cont_max = configLimitValues->I_DischaMax_Cont; dummyResultValues.current_Discha_peak_max = configLimitValues->I_DischaMax_Cont; } /* take the smaller current as limit */ if (dummyResultValues.current_Discha_cont_max < ResultValues->current_Discha_cont_max) ResultValues->current_Discha_cont_max = dummyResultValues.current_Discha_cont_max; if (dummyResultValues.current_Discha_peak_max < ResultValues->current_Discha_peak_max) ResultValues->current_Discha_peak_max = dummyResultValues.current_Discha_peak_max; } /* Temperature high Charge */ if (MaxTemp >= configLimitValues->Limit_THigh_Charge) { ResultValues->current_Charge_cont_max = 0; ResultValues->current_Charge_peak_max = 0; dummyResultValues.current_Charge_cont_max = 0; dummyResultValues.current_Charge_peak_max = 0; } else { if (MaxTemp >= configLimitValues->Cutoff_THigh_Charge) { dummyResultValues.current_Charge_cont_max = (calcCurveValues->Slope_THighCharge * MaxTemp + calcCurveValues->Offset_THighCharge); dummyResultValues.current_Charge_peak_max = dummyResultValues.current_Charge_cont_max; } else { /* do nothing because this situation is handled with MinTemp */ dummyResultValues.current_Charge_cont_max = configLimitValues->I_ChargeMax_Cont; dummyResultValues.current_Charge_peak_max = configLimitValues->I_ChargeMax_Cont; } /* take the smaller current as limit */ if (dummyResultValues.current_Charge_cont_max < ResultValues->current_Charge_cont_max) ResultValues->current_Charge_cont_max = dummyResultValues.current_Charge_cont_max; if (dummyResultValues.current_Charge_peak_max < ResultValues->current_Charge_peak_max) ResultValues->current_Charge_peak_max = dummyResultValues.current_Charge_peak_max; } } /** * @brief get the minimum current values of all variants of SoF calculation * * @param Ubased voltage constrained current derating values * @param Sbased SOC constrained current derating values * @param Tbased temperature constrained current derating values * @param resultValues minimum SoF current values */ static void SOF_MinimumOfThreeSofValues(SOX_SOF_s Ubased, SOX_SOF_s Sbased, SOX_SOF_s Tbased, SOX_SOF_s *resultValues) { resultValues->current_Charge_cont_max = SOF_MinimumOfThreeValues(Ubased.current_Charge_cont_max, Tbased.current_Charge_cont_max, Sbased.current_Charge_cont_max); resultValues->current_Charge_peak_max = SOF_MinimumOfThreeValues(Ubased.current_Charge_peak_max, Tbased.current_Charge_peak_max, Sbased.current_Charge_peak_max); resultValues->current_Discha_cont_max = SOF_MinimumOfThreeValues(Ubased.current_Discha_cont_max, Tbased.current_Discha_cont_max, Sbased.current_Discha_cont_max); resultValues->current_Discha_peak_max = SOF_MinimumOfThreeValues(Ubased.current_Discha_peak_max, Tbased.current_Discha_peak_max, Sbased.current_Discha_peak_max); } /** * @brief calculates minimum of three values * * @param value1 * @param value2 * @param value3 * * @return minimum of the 3 parameters */ static float SOF_MinimumOfThreeValues(float value1, float value2, float value3) { float result = 0.0; if (value1 <= value2) { if (value3 <= value1) { result = value3; } else { result = value1; } } else { if (value3 <= value2) { result = value3; } else { result = value2; } } return result; }
tonyhuang84/foxbms
embedded-software/mcu-common/src/driver/rtc/rtc.h
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file rtc.h * @author foxB<NAME> * @date 20.10.2015 (date of creation) * @ingroup DRIVERS * @prefix RTC * * @brief Headers for the driver for the real time clock. * */ #ifndef RTC_H_ #define RTC_H_ /*================== Includes =============================================*/ #include "rtc_cfg.h" /*================== Macros and Definitions ===============================*/ /** * Systemwide low level control, status Information of system */ typedef struct { RTC_Date_s date; /*!< RCC clock control & status register at startup */ RTC_Time_s time; /*!< state of Eeprom Driver State Machine */ /* uint32_t date; !< RCC clock control & status register at startup */ /* uint32_t time; !< state of Eeprom Driver State Machine */ uint32_t dummy[4]; /*!< */ } RTC_RESETSOURCE_s; /** * Systemwide low level control, status Information of system */ typedef struct { uint32_t CSR; /*!< RCC clock control & status register at startup */ RTC_Date_s boot_rtcdate; /*!< boot date */ RTC_Time_s boot_rtctime; /*!< boot time */ RTC_Date_s terminate_rtcdate; /*!< TODO */ RTC_Time_s terminate_rtctime; /*!< TODO */ uint32_t dummy[4]; /*!< */ RTC_RESETSOURCE_s resetsource[20]; /*!< in counts of 1ms */ } RTC_STATUS_s; /*================== Constant and Variable Definitions ====================*/ extern RTC_HandleTypeDef hrtc; extern RTC_STATUS_s main_state; /*================== Function Prototypes ==================================*/ /** * @brief initializes rtc module */ extern void RTC_Init(void); /** * @brief sets RTC time */ extern void RTC_setTime(RTC_TimeTypeDef* time); /** * @brief gets RTC time */ extern void RTC_getTime(RTC_TimeTypeDef* time); /** * @brief sets RTC date */ extern void RTC_setDate(RTC_DateTypeDef* date); /** * @brief gets RTC date */ extern void RTC_getDate(RTC_DateTypeDef* date); /* * @brief gets current unix time */ extern uint32_t RTC_getUnixTime(void); /* * @brief converts current RTC time into unix format */ extern uint32_t RTC_convertRTCtoUnixTime(RTC_TimeTypeDef* time, RTC_DateTypeDef* date); /*================== Function Implementations =============================*/ #endif /* RTC_H_ */
tonyhuang84/foxbms
embedded-software/mcu-secondary/src/engine/task/enginetask.h
<filename>embedded-software/mcu-secondary/src/engine/task/enginetask.h /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file enginetask.h * @author <NAME> * @date 27.08.2015 (date of creation) * @ingroup ENGINE * @prefix ENG * * @brief Header for external functions of the engine task * */ #ifndef ENGINETASK_H_ #define ENGINETASK_H_ /*================== Includes =============================================*/ #include "enginetask_cfg.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ /*================== Function Prototypes ==================================*/ /** * @brief creates cyclic tasks, called before scheduler start * */ extern void ENG_CreateTask(void); /** * @brief creates mutexes, called before scheduler start * */ extern void ENG_CreateMutex(void); /** * @brief creates events, called before scheduler start * */ extern void ENG_CreateEvent(void); /** * @brief creates queues, called before scheduler start * */ extern void ENG_CreateQueues(void); /** * @brief Cyclic 1ms-Task, preemptive with TSK_Cyclic_10ms() and * TSK_Cyclic_100ms(). * * @details The Task calls OsStartUp() in the very beginning, this is the first * active Task. Then the Task is delayed by a phase as defined in * eng_tskdef_cyclic_1ms.Phase (in milliseconds). After the phase * delay, the cyclic execution starts, the entry time is saved in * currentTime. After one cycle, the Task is set to sleep until entry * time + eng_tskdef_cyclic_1ms.CycleTime (in milliseconds). The Task * calls Job_1ms(), Job_2ms() and Job_5ms(). * */ extern void ENG_TSK_Cyclic_1ms(void); /** * @brief cyclic 10ms-Task, preemptive with TSK_Cyclic_1ms() and * TSK_Cyclic_100ms(). * * @details Task is delayed by a phase as defined in * eng_tskdef_cyclic_10ms.Phase (in milliseconds). After the phase * delay, the cyclic execution starts, the entry time is saved in * currentTime. After one cycle, the Task is set to sleep until entry * time + eng_tskdef_cyclic_10ms.CycleTime (in milliseconds). The task * calls Job_10ms() and Job_50ms(). * */ extern void ENG_TSK_Cyclic_10ms(void); /** * @brief cyclic 100ms-Task, preemptive with TSK_Cyclic_1ms() and * TSK_Cyclic_10ms(). * * @details Task is delayed by a phase as defined in * eng_tskdef_cyclic_100ms.Phase (in milliseconds). After the phase * delay, the cyclic execution starts, the entry time is saved in * currentTime. After one cycle, the Task is set to sleep until entry * time + eng_tskdef_cyclic_100ms.CycleTime (in milliseconds). The task * calls Job_100ms(), Job_500ms() and Job_1s(). * */ extern void ENG_TSK_Cyclic_100ms(void); /** * @brief cyclic and event driven handler. * * @details Task configurations (cycle and delay time) are specified by * eng_tskdef_eventhandler. * */ extern void ENG_TSK_EventHandler(void); /** * @brief cyclic diagnosis task. * * @details Task configurations (cycle and delay time) are specified by * eng_tskdef_diagnosis. * */ extern void ENG_TSK_Diagnosis(void); /*================== Function Implementations =============================*/ #endif /* ENGINETASK_H_ */
tonyhuang84/foxbms
embedded-software/mcu-primary/src/driver/config/io_cfg.c
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file io_cfg.c * @author <NAME> * @date 26.08.2015 (date of creation) * @ingroup DRIVERS_CONF * @prefix IO * * @brief Configuration for the driver for the I/O ports * * ============================================================================== * Detailed Configuration of the GPIOs * ============================================================================== * * The functionality of the signal defined in io_foxbms_mcu0_cfg.h is set in the array * io_cfg[], e.g. digital I/O or alternate functions like SPI, CAN, ... * * An incorrect definition of an signal may disturb one or more other * signal functional definitions of pins * * Every entry of the io_cfg[] array consists of * - name of the signal/pin (defined in io_foxbms_mcu0_cfg.h) * - mode of signal/pin (input, output, ...) * - push/pull * - pin speed * - alternate function (SPI, CAN, ...) * - locking of the pin configuration (has to enabled in io_cfg.h) * All available possibilities for each pin are found in the official<a href"http://www.st.com/st-web-ui/static/active/en/resource/technical/document/datasheet/DM00071990.pdf">datasheet</a>. * */ /*================== Includes =============================================*/ #include "io_cfg.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ const IO_PIN_CFG_s io_cfg[] = { /* * Trace */ {IO_PIN_MCU_0_TRACECLK, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_LOW, IO_ALTERNATE_AF0_TRACE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TRACED0, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_LOW, IO_ALTERNATE_AF0_TRACE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TRACED1, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_LOW, IO_ALTERNATE_AF0_TRACE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TRACED2, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_LOW, IO_ALTERNATE_AF0_TRACE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TRACED3, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_LOW, IO_ALTERNATE_AF0_TRACE, IO_PIN_LOCK_ENABLE}, /* * Data Storage SPI and Supply */ {IO_PIN_MCU_0_DATA_STORAGE_EEPROM_SPI_NSS, IO_MODE_OUTPUT_PP, IO_PIN_NOPULL, IO_SPEED_LOW, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE, IO_PIN_SET}, {IO_PIN_MCU_0_DATA_STORAGE_MEMORY_CARD_SPI_NSS, IO_MODE_OUTPUT_PP, IO_PIN_NOPULL, IO_SPEED_LOW, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE, IO_PIN_SET}, {IO_PIN_MCU_0_DATA_STORAGE_SPI_MISO, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI6, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_DATA_STORAGE_SPI_SCK, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI6, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_DATA_STORAGE_SPI_MOSI, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI6, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_MEMORY_CARD_SUPPLY_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, /* * Flexible Memory Controller */ {IO_PIN_MCU_0_FMC_RAM_A0, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A1, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A2, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A3, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A4, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A5, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A6, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A7, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A8, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A9, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A10, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_A11, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D0, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D1, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D2, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D3, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D4, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D5, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D6, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D7, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D8, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D9, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D10, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D11, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D12, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D13, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D14, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_D15, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_SDNWE, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_SDNRAS, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_SDNE1, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_SDCKE1, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_BA0, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_BA1, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_SDCLK, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_NBL0, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_SDNCAS, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FMC_RAM_NBL1, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF12_FMC, IO_PIN_LOCK_ENABLE}, /* * Debug LEDs */ {IO_PIN_MCU_0_DEBUG_LED_1, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_DEBUG_LED_0, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, /* * ADCs */ {IO_PIN_MCU_0_ADC_CH_0, IO_MODE_ANALOG, 0, 0, IO_ALTERNATE_NO_ALTERNATE, 0, }, {IO_PIN_MCU_0_ADC_CH_1, IO_MODE_ANALOG, 0, 0, IO_ALTERNATE_NO_ALTERNATE, 0, }, {IO_PIN_MCU_0_ADC_CH_2, IO_MODE_ANALOG, 0, 0, IO_ALTERNATE_NO_ALTERNATE, 0, }, {IO_PIN_MCU_0_ADC_CH_3, IO_MODE_ANALOG, 0, 0, IO_ALTERNATE_NO_ALTERNATE, 0, }, {IO_PIN_MCU_0_ADC_CH_4, IO_MODE_ANALOG, 0, 0, IO_ALTERNATE_NO_ALTERNATE, 0, }, /* * Bender */ {IO_PIN_MCU_0_BENDER_SUPPLY_ENABLE, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_BENDER_OK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_BENDER_PWM, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF3_TIM9, IO_PIN_LOCK_ENABLE}, /* * Contactors' Controll and Feedback Pins */ {IO_PIN_MCU_0_INTERLOCK_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_INTERLOCK_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_0_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_0_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_1_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_1_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_2_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_2_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_3_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_3_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_4_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_4_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_5_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_5_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_6_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_6_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_7_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_7_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_8_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CONTACTOR_8_FEEDBACK, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, /* * Interfaces */ {IO_PIN_MCU_0_BMS_INTERFACE_SPI_NSS, IO_MODE_OUTPUT_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE, IO_PIN_SET}, {IO_PIN_MCU_0_BMS_INTERFACE_SPI_SCK, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI1, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_BMS_INTERFACE_SPI_MISO, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI1, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_BMS_INTERFACE_SPI_MOSI, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI1, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TO_MCU_1_INTERFACE_SPI_NSS, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI1, IO_PIN_LOCK_ENABLE, IO_PIN_SET}, {IO_PIN_MCU_0_TO_MCU_1_INTERFACE_SPI_SCK, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI1, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TO_MCU_1_INTERFACE_SPI_MISO, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI1, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TO_MCU_1_INTERFACE_SPI_MOSI, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI1, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TO_FPGA_INTERFACE_SPI_NSS, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI5, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TO_FPGA_INTERFACE_SPI_SCK, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI5, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TO_FPGA_INTERFACE_SPI_MISO, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI5, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_TO_FPGA_INTERFACE_SPI_MOSI, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF5_SPI5, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_BMS_INTERFACE_0_GPIO_0, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_BMS_INTERFACE_0_GPIO_1, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_BMS_INTERFACE_0_GPIO_2, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, /* Pin high -> forward mode, Pin low -> reverse mode */ {IO_PIN_MCU_0_BMS_INTERFACE_ISOSPI_DIRECTION, IO_MODE_OUTPUT_PP, IO_PIN_NOPULL, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE, IO_PIN_SET}, {IO_PIN_MCU_0_CAN_0_TRANS_STANDBY_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CAN_0_TX, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF9_CAN0, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CAN_0_RX, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF9_CAN0, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CAN_1_TRANS_STANDBY_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CAN_1_TX, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF9_CAN1, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_CAN_1_RX, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF9_CAN1, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FTDI_TX, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF7_USART3, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_FTDI_RX, IO_MODE_AF_PP, IO_PIN_PULLUP, IO_SPEED_HIGH, IO_ALTERNATE_AF7_USART3, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_RS485_TX, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF7_USART2, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_RS485_RX, IO_MODE_AF_PP, IO_PIN_NOPULL, IO_SPEED_HIGH, IO_ALTERNATE_AF7_USART2, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_RS485_NRE, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE, IO_PIN_RESET}, {IO_PIN_MCU_0_RS485_DE, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE, IO_PIN_SET}, /* * Isolated In- and Outputs */ {IO_PIN_MCU_0_ISO_GPIO_IN_0, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISO_GPIO_OUT_0, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISO_GPIO_IN_1, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISO_GPIO_OUT_1, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISO_GPIO_IN_2, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISO_GPIO_OUT_2, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISO_GPIO_IN_3, IO_MODE_INPUT, IO_PIN_PULLDOWN, IO_SPEED_FAST, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISO_GPIO_OUT_3, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISONOC_0_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISONOC_1_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISONOC_2_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISONOC_3_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISONOC_4_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, {IO_PIN_MCU_0_ISONOC_5_CONTROL, IO_MODE_OUTPUT_PP, 0, 0, IO_ALTERNATE_NO_ALTERNATE, IO_PIN_LOCK_ENABLE}, }; const uint8_t io_cfg_length = sizeof(io_cfg)/sizeof(io_cfg[0]); /*================== Function Prototypes ==================================*/ /*================== Function Implementations =============================*/
tonyhuang84/foxbms
embedded-software/mcu-primary/src/general/third_party/ltc_itri.c
/* * ltc_itri.c * * Created on: 2019/5/21/ * Author: A50130 */ #include "general.h" #if defined(ITRI_MOD_2_b) #include "ltc_itri.h" extern LTC_EBM_CONFIG_s ltc_ebm_config[BS_NR_OF_MODULES]; extern LTC_EBM_CONFIG_s ltc_col_config[BS_NR_OF_COLUMNS]; extern LTC_EBM_CMD_s ltc_ebm_cmd; #endif // ITRI_MOD_2_b #if defined(ITRI_MOD_2) #include "database.h" extern void* LTC_ThirdParty_Get_static_var(char* varName); #if defined(ITRI_MOD_13) extern uint8_t LTC_ThirdParty_is_all_disabled(); #endif typedef uint32_t (*ltc_prop_funcPtr)(void* iParam1, void* iParam2, void* oParam1, void* oParam2); uint32_t get_BS_NR_OF_MODULES(void* iParam1, void* iParam2, void* oParam1, void* oParam2) { uint32_t* pOut = (uint32_t*)oParam1; *pOut = (uint32_t)BS_NR_OF_MODULES; return 0; } uint32_t get_BS_NR_OF_BAT_CELLS_PER_MODULE(void* iParam1, void* iParam2, void* oParam1, void* oParam2) { uint32_t* pOut = (uint32_t*)oParam1; *pOut = (uint32_t)BS_NR_OF_BAT_CELLS_PER_MODULE; return 0; } uint32_t get_LTC_CellVoltages(void* iParam1, void* iParam2, void* oParam1, void* oParam2) { uint32_t modIdx = *(uint32_t*)iParam1, i; char *com_out_buf = (char*)oParam1; DATA_BLOCK_CELLVOLTAGE_s* p_ltc_cellvoltage = (DATA_BLOCK_CELLVOLTAGE_s*)LTC_ThirdParty_Get_static_var("ltc_cellvoltage"); #if 1 sprintf(com_out_buf, "M[%02lu]", modIdx); for (i=0; i < BS_NR_OF_BAT_CELLS_PER_MODULE; i++) { sprintf(com_out_buf, "%s %u", com_out_buf, p_ltc_cellvoltage->voltage[modIdx * BS_NR_OF_BAT_CELLS_PER_MODULE + i]); } #else sprintf(com_out_buf, "M[%u] %u %u %u %u %u %u %u ", modIdx, p_ltc_cellvoltage->voltage[modIdx*(BS_NR_OF_BAT_CELLS_PER_MODULE)+0], p_ltc_cellvoltage->voltage[modIdx*(BS_NR_OF_BAT_CELLS_PER_MODULE)+1], p_ltc_cellvoltage->voltage[modIdx*(BS_NR_OF_BAT_CELLS_PER_MODULE)+2], p_ltc_cellvoltage->voltage[modIdx*(BS_NR_OF_BAT_CELLS_PER_MODULE)+3], p_ltc_cellvoltage->voltage[modIdx*(BS_NR_OF_BAT_CELLS_PER_MODULE)+4], p_ltc_cellvoltage->voltage[modIdx*(BS_NR_OF_BAT_CELLS_PER_MODULE)+5], p_ltc_cellvoltage->voltage[modIdx*(BS_NR_OF_BAT_CELLS_PER_MODULE)+6]); #endif //DEBUG_PRINTF(("%s\r\n", com_out_buf)); return 0; } uint32_t get_LTC_GPIOVoltages(void* iParam1, void* iParam2, void* oParam1, void* oParam2) { uint32_t modIdx = *(uint32_t*)iParam1, i; char *com_out_buf = (char*)oParam1; DATA_BLOCK_ALLGPIOVOLTAGE_s* p_ltc_allgpiovoltage = (DATA_BLOCK_ALLGPIOVOLTAGE_s*)LTC_ThirdParty_Get_static_var("ltc_allgpiovoltage"); sprintf(com_out_buf, "M[%02lu]", modIdx); for (i=0; i < BS_NR_OF_GPIOS_PER_MODULE; i++) { sprintf(com_out_buf, "%s %u", com_out_buf, p_ltc_allgpiovoltage->gpiovoltage[modIdx*BS_NR_OF_GPIOS_PER_MODULE+i]); } sprintf(com_out_buf, "%s %u", com_out_buf, p_ltc_allgpiovoltage->gpio_ref_vol[modIdx]); /* sprintf(com_out_buf, "M[%u] %u %u %u %u %u %u", modIdx, *((uint16_t *)(&LTC_allGPIOVoltages[modIdx*6 + 0])), *((uint16_t *)(&LTC_allGPIOVoltages[modIdx*6 + 1])), *((uint16_t *)(&LTC_allGPIOVoltages[modIdx*6 + 2])), *((uint16_t *)(&LTC_allGPIOVoltages[modIdx*6 + 3])), *((uint16_t *)(&LTC_allGPIOVoltages[modIdx*6 + 4])), *((uint16_t *)(&LTC_allGPIOVoltages[modIdx*6 + 5]))); */ return 0; } #if defined(ITRI_MOD_2_b) #include "..\..\..\..\mcu-common\src\module\ltc\ltc_defs.h" extern LTC_RETURN_TYPE_e LTC_SetStateRequest(LTC_STATE_REQUEST_e statereq); uint32_t set_ebm_eb_col_state(void* iParam1, void* iParam2, void* oParam1, void* oParam2) { uint8_t* pEBState = (uint8_t*)iParam1; uint8_t* pColState = (uint8_t*)iParam2; uint32_t i; if (ltc_ebm_cmd != LTC_EBM_NONE) return 0; for (i=0; i < BS_NR_OF_MODULES; i++) { ltc_ebm_config[i].eb_state = pEBState[i]; } for (i=0; i < BS_NR_OF_COLUMNS; i++) { ltc_col_config[i].eb_state = pColState != NULL ? pColState[i]:1; } if (LTC_SetStateRequest(LTC_STATE_EBMCONTROL_REQUEST) == LTC_OK) { ltc_ebm_cmd = LTC_EBM_EB_COL_CTRL; //DEBUG_PRINTF(("[%s:%d]done\r\n", __FILE__, __LINE__)); } else { DEBUG_PRINTF(("[%s:%d][ERR]set LTC_STATE_EBMCONTROL_REQUEST fail!!!\r\n", __func__, __LINE__)); } return 0; } #endif // ITRI_MOD_2_b #if defined(ITRI_MOD_6) uint32_t set_curr_cali(void* iParam1, void* iParam2, void* oParam1, void* oParam2) { if (ltc_ebm_cmd == LTC_EBM_NONE) { ltc_ebm_cmd = LTC_EBM_CURR_CALI; } return 0; } #endif // ITRI_MOD_6 #if defined(ITRI_MOD_13) uint32_t is_all_disabled(void* iParam1, void* iParam2, void* oParam1, void* oParam2) { uint8_t* pIsAllDisabled = (uint8_t*)oParam1; *pIsAllDisabled = LTC_ThirdParty_is_all_disabled(); return 0; } #endif typedef struct { char prop[48]; ltc_prop_funcPtr propFunc; } LTC_PROP_s; LTC_PROP_s ltc_props[] = { {"get_BS_NR_OF_MODULES", &get_BS_NR_OF_MODULES}, {"get_BS_NR_OF_BAT_CELLS_PER_MODULE", &get_BS_NR_OF_BAT_CELLS_PER_MODULE}, {"get_LTC_CellVoltages", &get_LTC_CellVoltages}, {"get_LTC_GPIOVoltages", &get_LTC_GPIOVoltages}, #if defined(ITRI_MOD_2_b) {"set_ebm_eb_col_state", &set_ebm_eb_col_state}, #endif #if defined(ITRI_MOD_6) {"set_curr_cali", &set_curr_cali}, #endif #if defined(ITRI_MOD_13) {"is_all_disabled", &is_all_disabled}, #endif }; uint32_t LTC_ThirdParty_Set_Get_Property(char* prop, void* iParam1, void* iParam2, void* oParam1, void* oParam2) { uint32_t i, ltc_props_len = sizeof(ltc_props) / sizeof(ltc_props[0]); if (prop == NULL) return 1; for (i=0; i < ltc_props_len; i++) { if (strcmp(prop, ltc_props[i].prop) == 0) { if (ltc_props[i].propFunc == NULL) break; return ltc_props[i].propFunc(iParam1, iParam2, oParam1, oParam2); } } DEBUG_PRINTF(("[%s:%d]unknown prop(%s)\r\n", __FILE__, __LINE__, prop)); return 0; } #endif // ITRI_MOD_2
tonyhuang84/foxbms
embedded-software/mcu-secondary/src/general/includes/std_types.h
<gh_stars>0 /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file std_types.h * @author <NAME> * @date 20.12.2015 (date of creation) * @ingroup GENERAL_CONF * @prefix STD * * @brief Definition of foxBMS standard types */ #ifndef STD_TYPES_H_ #define STD_TYPES_H_ /*================== Includes =============================================*/ #ifndef NOECLIPSE #include "gcc_builtin_macros.h" #endif /*================== Macros and Definitions ===============================*/ #define NULL_PTR (void*)(0) #define TRUE 1 #define FALSE 0 /*================== Constant and Variable Definitions ====================*/ typedef uint8_t boolean; typedef void (*VOID_FUNC_VOID_t)(); /** * enum for standard return type */ typedef enum { E_OK = 0, /*!< ok */ E_NOT_OK = 1 /*!< not ok */ } STD_RETURN_TYPE_e; /** * enum for error bits */ typedef enum { STD_ERR_BIT_0 = 0x00000001, STD_ERR_BIT_1 = 0x00000002, STD_ERR_BIT_2 = 0x00000004, STD_ERR_BIT_3 = 0x00000008, STD_ERR_BIT_4 = 0x00000010, STD_ERR_BIT_5 = 0x00000020, STD_ERR_BIT_6 = 0x00000040, STD_ERR_BIT_7 = 0x00000080, STD_ERR_BIT_8 = 0x00000100, STD_ERR_BIT_9 = 0x00000200, STD_ERR_BIT_10 = 0x00000400, STD_ERR_BIT_11 = 0x00000800, STD_ERR_BIT_12 = 0x00001000, STD_ERR_BIT_13 = 0x00002000, STD_ERR_BIT_14 = 0x00004000, STD_ERR_BIT_15 = 0x00008000, STD_ERR_BIT_16 = 0x00010000, STD_ERR_BIT_17 = 0x00020000, STD_ERR_BIT_18 = 0x00040000, STD_ERR_BIT_19 = 0x00080000, STD_ERR_BIT_20 = 0x00100000, STD_ERR_BIT_21 = 0x00200000, STD_ERR_BIT_22 = 0x00400000, STD_ERR_BIT_23 = 0x00800000, STD_ERR_BIT_24 = 0x01000000, STD_ERR_BIT_25 = 0x02000000, STD_ERR_BIT_26 = 0x04000000, STD_ERR_BIT_27 = 0x08000000, STD_ERR_BIT_28 = 0x10000000, STD_ERR_BIT_29 = 0x20000000, STD_ERR_BIT_30 = 0x40000000, STD_ERR_BIT_31 = 0x80000000, } STD_ERROR_BIT_e; /*================== Function Prototypes ==================================*/ /*================== Function Implementations =============================*/ #endif /* STD_TYPES_H_ */
tonyhuang84/foxbms
embedded-software/mcu-primary/src/general/third_party/com_itri.c
<reponame>tonyhuang84/foxbms #include "general.h" #if defined(ITRI_MOD_1) #include <stdio.h> #include <stdlib.h> #include <string.h> char* float_to_string(double v) { static char g_ftBuf[16] = {0, }; int decimalDigits = 4; int i = 1; int intPart, fractPart; for (;decimalDigits!=0; i*=10, decimalDigits--); intPart = (int)v; fractPart = (int)((v-(float)(int)v)*i); if(fractPart < 0) fractPart *= -1; sprintf(g_ftBuf, "%i.%i", intPart, fractPart); return g_ftBuf; } typedef uint32_t (*rb_cmd_funcPtr)(char* params); static char com_ltc_out_buf[128] = {0, }; uint32_t rb_cmd_test_func_1(char* params) { //DEBUG_PRINTF(("DEBUG_PRINTF_EX test, float(%s), int(%d), hex(0x%02X), str(%s)\r\n", float_to_string(1.234), 123, 16, "abc")); double timestamp = (double)24.0*3600.0*100.0 + (double)3600.0*23.0 + (double)60.0*59.0 + (double)59.0 + (double)0.1*9.0 + (double)0.01*9.0 + (double)0.001*9.0; DEBUG_PRINTF(("timestamp: %s\r\n", float_to_string(timestamp))); return 0; } #if defined(ITRI_MOD_2) extern uint32_t LTC_ThirdParty_Set_Get_Property(char* prop, void* iParam1, void* iParam2, void* oParam1, void* oParam2); uint32_t rb_cmd_get_BS_NR_OF_MODULES(char* params) { uint32_t numMod = 0; LTC_ThirdParty_Set_Get_Property("get_BS_NR_OF_MODULES", NULL, NULL, (void*)&numMod, NULL); DEBUG_PRINTF(("BS_NR_OF_MODULES=%lu\r\n", numMod)); return 0; } uint32_t rb_cmd_get_BS_NR_OF_BAT_CELLS_PER_MODULE(char* params) { uint32_t numMod = 0; LTC_ThirdParty_Set_Get_Property("get_BS_NR_OF_BAT_CELLS_PER_MODULE", NULL, NULL, (void*)&numMod, NULL); DEBUG_PRINTF(("BS_NR_OF_BAT_CELLS_PER_MODULE=%lu\r\n", numMod)); return 0; } uint32_t rb_cmd_get_LTC_CellVoltages(char* params) { //char* pCmd = strtok(params, " "); char* pParam = strtok(NULL, " "); uint32_t modIdx = (uint32_t)atoi(pParam); LTC_ThirdParty_Set_Get_Property("get_LTC_CellVoltages", (void*)&modIdx, NULL, com_ltc_out_buf, NULL); DEBUG_PRINTF(("%s\r\n", com_ltc_out_buf)); return 0; } uint32_t rb_cmd_get_LTC_GPIOVoltages(char* params) { //char* pCmd = strtok(params, " "); char* pParam = strtok(NULL, " "); uint32_t modIdx = (uint32_t)atoi(pParam); LTC_ThirdParty_Set_Get_Property("get_LTC_GPIOVoltages", (void*)&modIdx, NULL, com_ltc_out_buf, NULL); DEBUG_PRINTF(("%s\r\n", com_ltc_out_buf)); return 0; } #endif // ITRI_MOD_2 #if defined(ITRI_MOD_2_b) uint32_t rb_cmd_set_ebm_eb_col_state(char* params) { uint32_t i; uint8_t ebState[BS_NR_OF_MODULES]; uint8_t colState[BS_NR_OF_COLUMNS]; //char* pCmd = strtok(params, " "); char* pParam = NULL; for (i=0; i < BS_NR_OF_MODULES; i++) { pParam = strtok(NULL, " "); ebState[i] = (uint8_t)atoi(pParam); } for (i=0; i < BS_NR_OF_COLUMNS; i++) { pParam = strtok(NULL, " "); colState[i] = (uint8_t)atoi(pParam); } LTC_ThirdParty_Set_Get_Property("set_ebm_eb_col_state", (void*)ebState, (void*)colState, NULL, NULL); //DEBUG_PRINTF(("[%s:%d]rb_cmd_set_ebm_eb_col_state done\r\n", __FILE__, __LINE__)); return 0; } #endif // ITRI_MOD_2_b #if defined(ITRI_MOD_6) uint32_t rb_cmd_cur_cali(char* params) { LTC_ThirdParty_Set_Get_Property("set_curr_cali", NULL, NULL, NULL, NULL); return 0; } #endif #if defined(ITRI_MOD_11) extern void cans_send_heartbeat_pulse(); uint32_t rb_cmd_send_heartbeat_pulse(char* params) { cans_send_heartbeat_pulse(); return 0; } #endif #if defined(ITRI_MOD_13) extern uint8_t LTC_ThirdParty_is_all_disabled(); uint32_t rb_cmd_is_all_disabled(char* params) { uint8_t isAllDisabled = LTC_ThirdParty_is_all_disabled(); DEBUG_PRINTF(("is_all_disabled = %d\r\n", isAllDisabled)); return 0; } #endif typedef struct { char cmd[48]; char desc[64]; rb_cmd_funcPtr cmdFunc; } RB_CMD_s; RB_CMD_s rb_cmds[] = { {"test_func_1", "test func_1", &rb_cmd_test_func_1}, #if defined(ITRI_MOD_2) {"get_BS_NR_OF_MODULES", "number of modules", &rb_cmd_get_BS_NR_OF_MODULES}, {"get_BS_NR_OF_BAT_CELLS_PER_MODULE", "number of bat. cells per module", &rb_cmd_get_BS_NR_OF_BAT_CELLS_PER_MODULE}, {"get_LTC_CellVoltages", "cmd [module no.] ", &rb_cmd_get_LTC_CellVoltages}, {"get_LTC_GPIOVoltages", "cmd [module no.] ", &rb_cmd_get_LTC_GPIOVoltages}, #endif // ITRI_MOD_2 #if defined(ITRI_MOD_2_b) {"set_ebm_eb_col_state", "cmd [ebm ... spm ...", &rb_cmd_set_ebm_eb_col_state}, #endif #if defined(ITRI_MOD_6) {"set_cur_cali", "current calibration", &rb_cmd_cur_cali}, #endif #if defined(ITRI_MOD_11) {"send_heartbeat_pulse", "test heartbeat func.", &rb_cmd_send_heartbeat_pulse}, #endif #if defined(ITRI_MOD_13) {"is_all_disabled", "test is_all_disabled func.", &rb_cmd_is_all_disabled}, #endif }; void COM_ThirdParty_printHelpCommand(uint8_t* cnt) { static uint8_t rb_cmd_idx = 0; if (rb_cmd_idx == 0) { DEBUG_PRINTF(("========================== ==========================================================================================\r\n")); } DEBUG_PRINTF(("%-27s %s\r\n", rb_cmds[rb_cmd_idx].cmd, rb_cmds[rb_cmd_idx].desc)); rb_cmd_idx++; if (rb_cmd_idx < sizeof(rb_cmds)/sizeof(rb_cmds[0])) (*cnt)--; else rb_cmd_idx = 0; } // return: // 0: valid third-party command // 1: invalid command uint8_t COM_ThirdParty_Decoder(char* com_receivedbyte) { uint32_t i, cmd_len = sizeof(rb_cmds) / sizeof(rb_cmds[0]); char cmdStr[128]; char* pCmd = NULL; strcpy(cmdStr, com_receivedbyte); pCmd = strtok(cmdStr, " "); for (i=0; i < cmd_len; i++) { if (strcmp(pCmd, rb_cmds[i].cmd) == 0) { rb_cmds[i].cmdFunc(com_receivedbyte); return 0; } } return 1; } double COM_GetTimeStamp() { return (double)os_timer.Timer_d*24.0*3600.0 + (double)os_timer.Timer_h*3600.0 + (double)os_timer.Timer_min*60.0 + (double)os_timer.Timer_sec + (double)os_timer.Timer_100ms*0.1 + (double)os_timer.Timer_10ms*0.01 + (double)os_timer.Timer_1ms*0.001; } #endif // ITRI_MOD
tonyhuang84/foxbms
embedded-software/mcu-secondary/src/general/config/STM32F4xx/stm32f4xx_it.c
/** * @author STMicroelectronics * @date 2016 * @ingroup GENERAL_CONF * @brief HAL IT Module, definition of IRQ handlers for hardware units, * based on project examples Templates\Src\stm32f4xx_it.c * */ /** ****************************************************************************** * @file stm32f4xx_it.c * @author MCD Application Team * @version V1.0.3 * @date 06-May-2016 * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * 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. * 3. Neither the name of STMicroelectronics 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. * ****************************************************************************** */ /*================== Includes =============================================*/ #include "stm32f4xx_it.h" #include "os.h" #include "dma.h" #include "spi.h" #include "diag.h" #include "mcu.h" #include "io.h" #include "adc.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ /*================== Function Prototypes ==================================*/ /*================== Function Implementations =============================*/ /******************************************************************************/ /* Cortex-M4 Processor Interruption and Exception Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * * @retval void */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * * @retval void */ void HardFault_Handler(void) { uint32_t faultaddress; /* note: MSP Stack will be changed */ uint32_t lr_register; uint32_t sp_register; uint32_t caller_addr_at_stack; /* Go to infinite loop when Hard Fault exception occurs */ /* while (1) */ /* {*/ /* } */ #ifdef STM32F4 __ASM volatile ("mov %0, r14" : "=r" (lr_register)); /* VOID_FUNC_VOID fuptr; */ /* fuptr = (VOID_FUNC_VOID)(0xB0000020); */ /* fuptr(); */ /* Check EXC_RETURN at exception entry to identify the used stack (MSP or PSP) */ if (lr_register== 0xFFFFFFFD) /* Return to Thread mode, exception return uses non-floating-point state from */ { /* the PSP and execution uses PSP after return */ sp_register = __get_PSP(); } else if (lr_register== 0xFFFFFFF1) /* Return to Handler mode, exception return uses non-floating-point state from */ { /* MSP and execution uses MSP after return */ sp_register = __get_MSP() + 0x20; /* because of function local variables stack will be changed in MSP */ } diag_fc.Val0 = SCB->CFSR; /* Check if division by zero exception occured */ if (SCB->CFSR &= 0x02000000) /* FLAG: DIVBYZERO */ { caller_addr_at_stack = sp_register + 0x18; diag_fc.Val1 = *(uint32_t*)caller_addr_at_stack; /* report instruction address where division has occured */ DIAG_Handler(DIAG_CH_DIV_BY_ZERO_FAILURE,DIAG_EVENT_NOK,0, NULL); } else if (SCB->CFSR &= 0x00010000) /* FLAG: UNDEFINSTR */ { /* tested by undefined instruction in memory: "0xF7F0A000" */ caller_addr_at_stack = sp_register+0x18; diag_fc.Val1 = *(uint32_t*)caller_addr_at_stack; /* report instruction address with undefined instruction */ DIAG_Handler(DIAG_CH_UNDEF_INSTRUCTION_FAILURE,DIAG_EVENT_NOK,0, NULL); } /* Check if data bus error occured or data access violation */ else if (SCB->CFSR &= 0x00000202) /* FLAG: PRECIS ERR or DACC VIOL */ { /* tested by data pointer to address area 0x04000000, 0xb0000000... */ caller_addr_at_stack = sp_register+0x18; diag_fc.Val1 = *(uint32_t*)(caller_addr_at_stack); /* report instruction address where data bus error has occured */ faultaddress = SCB->BFAR; if (SCB->CFSR &= 0x00008000) /* check if BFAR (reported Bus Fault Address) is valid */ { diag_fc.Val2 = faultaddress; /* report bus address being accessed */ } DIAG_Handler(DIAG_CH_DATA_BUS_FAILURE,DIAG_EVENT_NOK,0, NULL); } /* Check if instruction bus error occured or instruction access violation */ else if (SCB->CFSR &= 0x00000101) /* FLAG: IBUS ERR or IACC VIOL */ { /* tested by using function pointer to address area 0x04000000, 0xb0000000... */ caller_addr_at_stack = (sp_register+0x18); diag_fc.Val1 = *(uint32_t*)(caller_addr_at_stack); /* report instruction address where instruction bus error has occured */ faultaddress = SCB->BFAR; if (SCB->CFSR &= 0x00008000) /* check if BFAR (reported Bus Fault Address) is valid */ { diag_fc.Val2 = faultaddress; /* report bus address being accessed */ } DIAG_Handler(DIAG_CH_INSTRUCTION_BUS_FAILURE,DIAG_EVENT_NOK, 0, NULL); } else { DIAG_Handler(DIAG_CH_HARDFAULT_NOTHANDLED, DIAG_EVENT_NOK, 0, NULL); } #endif while (1) { ; } } /** * @brief This function handles Memory Manage exception. * * @retval void */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * * @retval void * */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * * @retval void */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } #if 0 /* this function is implemented by FreeRTOS in port.c: macro vPortSVCHandler */ /** * @brief This function handles SVCall exception. * * @retval void */ void SVC_Handler(void) { } #endif /** * @brief This function handles Debug Monitor exception. * * @retval void */ void DebugMon_Handler(void) { } #if 0 /* this function is implemented by FreeRTOS in port.c: macro xPortPendSVHandler */ /** * @brief This function handles PendSVC exception. * * @retval void */ void PendSV_Handler(void) { } #endif /** * @brief This function handles SysTick Handler. * * @retval void */ void SysTick_Handler(void) { OS_SysTickHandler(); HAL_IncTick(); } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f4xx.s). */ /******************************************************************************/ /** * @brief This function handles PPP interrupt request. * * @retval void */ /*void PPP_IRQHandler(void) { }*/ #if 1 /* FIXME nötig? */ /** * @brief This function handles SPI6 global interrupt. */ void SPI6_IRQHandler(void) { /* USER CODE BEGIN SPI6_IRQn 0 */ /* USER CODE END SPI6_IRQn 0 */ HAL_NVIC_ClearPendingIRQ(SPI6_IRQn); HAL_SPI_IRQHandler(&spi_devices[1]); } #endif #if 0 /* FIXME kann gelöscht werden? */ /** * @brief This function handles SPI4 global interrupt. */ void SPI4_IRQHandler(void) { /* USER CODE BEGIN SPI4_IRQn 0 */ /* USER CODE END SPI4_IRQn 0 */ HAL_NVIC_ClearPendingIRQ(SPI4_IRQn); HAL_SPI_IRQHandler(&spi_devices[0]); /* USER CODE BEGIN SPI4_IRQn 1 */ /* USER CODE END SPI4_IRQn 1 */ } #endif /** * interrupt-handler for DMA2 * * @ingroup HAL */ void DMA2_Stream0_IRQHandler(void) { HAL_NVIC_ClearPendingIRQ(DMA2_Stream0_IRQn); HAL_DMA_IRQHandler(&dma_devices[0]); } /** * interrupt-handler for DMA2 * * @ingroup HAL */ void DMA2_Stream1_IRQHandler(void) { HAL_NVIC_ClearPendingIRQ(DMA2_Stream1_IRQn); HAL_DMA_IRQHandler(&dma_devices[1]); } /** * interrupt-handler for DMA2 * * @ingroup HAL */ void DMA2_Stream2_IRQHandler(void) { HAL_NVIC_ClearPendingIRQ(DMA2_Stream2_IRQn); HAL_DMA_IRQHandler(&dma_devices[0]); } /** * interrupt-handler for DMA2 * * @ingroup HAL */ void DMA2_Stream3_IRQHandler(void) { HAL_NVIC_ClearPendingIRQ(DMA2_Stream3_IRQn); HAL_DMA_IRQHandler(&dma_devices[1]); } /** * interrupt-handler for USART3 * * @ingroup HAL */ void USART3_IRQHandler(void) { } /** * interrupt-handler for USART2 * * @ingroup HAL */ void USART2_IRQHandler(void) { #if BUILD_MODULE_ENABLE_RS485 /* @todo akdere */ /* HAL_UART_CustomIRQHandler(&huart2); */ #endif } void ADC_IRQHandler(void) { HAL_NVIC_ClearPendingIRQ(ADC_IRQn); HAL_ADC_IRQHandler(&adc_devices[0]); } void TIM3_IRQHandler(void) { /* todo: do something here */ } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
tonyhuang84/foxbms
embedded-software/mcu-primary/src/application/bal/bal.c
<filename>embedded-software/mcu-primary/src/application/bal/bal.c /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file bal.c * @author foxBMS Team * @date 26.02.2016 (date of creation) * @ingroup DRIVERS * @prefix BAL * * @brief Driver for the Balancing module * */ /*================== Includes =============================================*/ #include "bal.h" #include "batterycell_cfg.h" #include "database.h" #include "FreeRTOS.h" #include "sox.h" #include "task.h" /*================== Macros and Definitions ===============================*/ /** * Saves the last state and the last substate */ #define BAL_SAVELASTSTATES() bal_state.laststate = bal_state.state; \ bal_state.lastsubstate = bal_state.substate /*================== Constant and Variable Definitions ====================*/ static DATA_BLOCK_MINMAX_s bal_minmax; static DATA_BLOCK_BALANCING_CONTROL_s bal_balancing; static DATA_BLOCK_CELLVOLTAGE_s bal_cellvoltage; DATA_BLOCK_STATEREQUEST_s bal_request; /** * contains the state of the contactor state machine * */ static BAL_STATE_s bal_state = { .timer = 0, .statereq = BAL_STATE_NO_REQUEST, .state = BAL_STATEMACH_UNINITIALIZED, .substate = BAL_ENTRY, .laststate = BAL_STATEMACH_UNINITIALIZED, .lastsubstate = 0, .triggerentry = 0, .ErrRequestCounter = 0, .active = FALSE, .resting = TRUE, .rest_timer = BAL_TIME_BEFORE_BALANCING_S*10, .balancing_threshold = BAL_THRESHOLD_MV + BAL_HYSTERESIS_MV, .balancing_allowed = TRUE, .balancing_global_allowed = FALSE, }; /*================== Function Prototypes ==================================*/ static BAL_RETURN_TYPE_e BAL_CheckStateRequest(BAL_STATE_REQUEST_e statereq); static BAL_STATE_REQUEST_e BAL_GetStateRequest(void); static BAL_STATE_REQUEST_e BAL_TransferStateRequest(void); static uint8_t BAL_CheckReEntrance(void); static void BAL_Init(void); static void BAL_Deactivate(void); #if BALANCING_VOLTAGE_BASED == TRUE static uint8_t BAL_Activate_Balancing_Voltage(void); #else static uint8_t BAL_Check_Imbalances(void); static void BAL_Compute_Imbalances(void); static void BAL_Activate_Balancing_History(void); #endif /*================== Function Implementations =============================*/ static void BAL_Init(void) { DB_ReadBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); bal_balancing.enable_balancing = 0; DB_WriteBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); } static void BAL_Deactivate(void) { uint16_t i; DB_ReadBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); for (i=0; i < BS_NR_OF_BAT_CELLS; i++) { bal_balancing.balancing_state[i] = 0; bal_balancing.delta_charge[i] = 0; } bal_balancing.enable_balancing = 0; bal_state.active = FALSE; bal_balancing.previous_timestamp = bal_balancing.timestamp; bal_balancing.timestamp = OS_getOSSysTick(); DB_WriteBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); } #if BALANCING_VOLTAGE_BASED == TRUE static uint8_t BAL_Activate_Balancing_Voltage(void) { uint32_t i = 0; uint16_t min = 0; uint8_t finished = TRUE; DB_ReadBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); DB_ReadBlock(&bal_cellvoltage, DATA_BLOCK_ID_CELLVOLTAGE); DB_ReadBlock(&bal_minmax, DATA_BLOCK_ID_MINMAX); min = bal_minmax.voltage_min; for (i=0; i < BS_NR_OF_BAT_CELLS; i++) { if (bal_cellvoltage.voltage[i] > min+bal_state.balancing_threshold) { bal_balancing.balancing_state[i] = 1; finished = FALSE; bal_state.balancing_threshold = BAL_THRESHOLD_MV; bal_state.active = TRUE; bal_balancing.enable_balancing = 1; } else { bal_balancing.balancing_state[i] = 0; } } bal_balancing.previous_timestamp = bal_balancing.timestamp; bal_balancing.timestamp = OS_getOSSysTick(); DB_WriteBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); return finished; } #else static uint8_t BAL_Check_Imbalances(void) { uint16_t i; uint8_t retVal = FALSE; DB_ReadBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); for (i=0; i < BS_NR_OF_BAT_CELLS; i++) { if (bal_balancing.delta_charge[i] > 0) { retVal = TRUE; } } return retVal; } static void BAL_Compute_Imbalances(void) { uint16_t i = 0; uint16_t voltageMin = 0; uint16_t minVoltageIndex = 0; float SOC = 0.0; uint32_t DOD = 0.0; uint32_t maxDOD = 0.0; DB_ReadBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); DB_ReadBlock(&bal_cellvoltage, DATA_BLOCK_ID_CELLVOLTAGE); voltageMin = bal_cellvoltage.voltage[0]; minVoltageIndex = 0; for (i=0; i < BS_NR_OF_BAT_CELLS; i++) { if (bal_cellvoltage.voltage[i] <= voltageMin) { voltageMin = bal_cellvoltage.voltage[i]; minVoltageIndex = i; } } SOC = SOC_GetFromVoltage(((float)(bal_cellvoltage.voltage[minVoltageIndex]))/1000.0); maxDOD = BC_CAPACITY * (uint32_t)((1.0 - SOC) * 3600.0); bal_balancing.delta_charge[minVoltageIndex] = 0; for (i=0; i < BS_NR_OF_BAT_CELLS; i++) { if (i != minVoltageIndex) { if (bal_cellvoltage.voltage[i] >= voltageMin + bal_state.balancing_threshold) { SOC = SOC_GetFromVoltage(((float)(bal_cellvoltage.voltage[i]))/1000.0); DOD = BC_CAPACITY * (uint32_t)((1.0 - SOC) * 3600.0); bal_balancing.delta_charge[i] = (maxDOD - DOD); } } } DB_WriteBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); } static void BAL_Activate_Balancing_History(void) { uint16_t i; float cellBalancingCurrent; uint32_t difference; DB_ReadBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); DB_ReadBlock(&bal_cellvoltage, DATA_BLOCK_ID_CELLVOLTAGE); for (i=0; i < BS_NR_OF_BAT_CELLS; i++) { if (bal_state.balancing_allowed == FALSE) { bal_balancing.balancing_state[i] = 0; } else { if (bal_balancing.delta_charge[i] > 0) { bal_balancing.balancing_state[i] = 1; cellBalancingCurrent = ((float)(bal_cellvoltage.voltage[i]))/BS_BALANCING_RESISTANCE_OHM; difference = (BAL_STATEMACH_BALANCINGTIME_100MS/10) * (uint32_t)(cellBalancingCurrent); bal_state.active = TRUE; bal_balancing.enable_balancing = 1; /* we are working with unsigned integers */ if (difference > bal_balancing.delta_charge[i]) { bal_balancing.delta_charge[i] = 0; } else { bal_balancing.delta_charge[i] -= difference; } } else { bal_balancing.balancing_state[i] = 0; } } } DB_WriteBlock(&bal_balancing, DATA_BLOCK_ID_BALANCING_CONTROL_VALUES); } #endif /** * @brief re-entrance check of BAL state machine trigger function * * This function is not re-entrant and should only be called time- or event-triggered. * It increments the triggerentry counter from the state variable bal_state. * It should never be called by two different processes, so if it is the case, triggerentry * should never be higher than 0 when this function is called. * * * @return retval 0 if no further instance of the function is active, 0xff else * */ static uint8_t BAL_CheckReEntrance(void) { uint8_t retval = 0; taskENTER_CRITICAL(); if (!bal_state.triggerentry) { bal_state.triggerentry++; } else { retval = 0xFF; /* multiple calls of function */ } taskEXIT_CRITICAL(); return (retval); } /** * @brief gets the current state request. * * This function is used in the functioning of the BAL state machine. * * @return retval current state request, taken from BAL_STATE_REQUEST_e */ static BAL_STATE_REQUEST_e BAL_GetStateRequest(void) { BAL_STATE_REQUEST_e retval = BAL_STATE_NO_REQUEST; taskENTER_CRITICAL(); retval = bal_state.statereq; taskEXIT_CRITICAL(); return (retval); } /** * @brief gets the current state. * * This function is used in the functioning of the BAL state machine. * * @return current state, taken from BAL_STATEMACH_e */ BAL_STATEMACH_e BAL_GetState(void) { return (bal_state.state); } /** * @brief transfers the current state request to the state machine. * * This function takes the current state request from bal_state and transfers it to the state machine. * It resets the value from bal_state to BAL_STATE_NO_REQUEST * * @return retVal current state request, taken from BAL_STATE_REQUEST_e * */ static BAL_STATE_REQUEST_e BAL_TransferStateRequest(void) { BAL_STATE_REQUEST_e retval = BAL_STATE_NO_REQUEST; taskENTER_CRITICAL(); retval = bal_state.statereq; bal_state.statereq = BAL_STATE_NO_REQUEST; taskEXIT_CRITICAL(); return (retval); } /** * @brief sets the current state request of the state variable bal_state. * * This function is used to make a state request to the state machine,e.g, start voltage measurement, * read result of voltage measurement, re-initialization * It calls BAL_CheckStateRequest() to check if the request is valid. * The state request is rejected if is not valid. * The result of the check is returned immediately, so that the requester can act in case * it made a non-valid state request. * * @param statereq state request to set * * @return retVal current state request, taken from BAL_STATE_REQUEST_e */ BAL_RETURN_TYPE_e BAL_SetStateRequest(BAL_STATE_REQUEST_e statereq) { BAL_RETURN_TYPE_e retVal = BAL_STATE_NO_REQUEST; taskENTER_CRITICAL(); retVal = BAL_CheckStateRequest(statereq); if (retVal == BAL_OK) { bal_state.statereq = statereq; } taskEXIT_CRITICAL(); return (retVal); } /** * @brief checks the state requests that are made. * * This function checks the validity of the state requests. * The resuls of the checked is returned immediately. * * @param statereq state request to be checked * * @return result of the state request that was made, taken from BAL_RETURN_TYPE_e */ static BAL_RETURN_TYPE_e BAL_CheckStateRequest(BAL_STATE_REQUEST_e statereq) { if (statereq == BAL_STATE_ERROR_REQUEST) { return BAL_OK; } if (statereq == BAL_STATE_GLOBAL_ENABLE_REQUEST) { bal_state.balancing_global_allowed = 1; return BAL_OK; } if (statereq == BAL_STATE_GLOBAL_DISABLE_REQUEST) { bal_state.balancing_global_allowed = 0; return BAL_OK; } if ((statereq == BAL_STATE_NOBALANCING_REQUEST) || (statereq == BAL_STATE_ALLOWBALANCING_REQUEST)) { return BAL_OK; } if (bal_state.statereq == BAL_STATE_NO_REQUEST) { /* init only allowed from the uninitialized state */ if (statereq == BAL_STATE_INIT_REQUEST) { if (bal_state.state == BAL_STATEMACH_UNINITIALIZED) { return BAL_OK; } else { return BAL_ALREADY_INITIALIZED; } /* request to forbid balancing */ } else { return BAL_ILLEGAL_REQUEST; } } else { return BAL_REQUEST_PENDING; } } /** * @brief trigger function for the BAL driver state machine. * * This function contains the sequence of events in the BAL state machine. * It must be called time-triggered, every 1ms. */ void BAL_Trigger(void) { BAL_STATE_REQUEST_e statereq = BAL_STATE_NO_REQUEST; uint8_t finished = FALSE; if (bal_state.rest_timer > 0) { bal_state.rest_timer--; } /* Check re-entrance of function */ if (BAL_CheckReEntrance()) { return; } if (bal_state.timer) { if (--bal_state.timer) { bal_state.triggerentry--; return; /* handle state machine only if timer has elapsed */ } } /* Check if battery is resting */ if (BS_CheckCurrent_Direction() == BS_CURRENT_NO_CURRENT) { if (bal_state.resting == FALSE) { bal_state.resting = TRUE; bal_state.rest_timer = BAL_TIME_BEFORE_BALANCING_S*10; } } else { bal_state.resting = FALSE; } switch (bal_state.state) { /****************************UNINITIALIZED***********************************/ case BAL_STATEMACH_UNINITIALIZED: /* waiting for Initialization Request */ statereq = BAL_TransferStateRequest(); if (statereq == BAL_STATE_INIT_REQUEST) { BAL_SAVELASTSTATES(); bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; bal_state.state = BAL_STATEMACH_INITIALIZATION; bal_state.substate = BAL_ENTRY; } else if (statereq == BAL_STATE_NO_REQUEST) { /* no actual request pending */ } else { bal_state.ErrRequestCounter++; /* illegal request pending */ } break; /****************************INITIALIZATION**********************************/ case BAL_STATEMACH_INITIALIZATION: BAL_SAVELASTSTATES(); BAL_Init(); bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; bal_state.state = BAL_STATEMACH_INITIALIZED; bal_state.substate = BAL_ENTRY; break; /****************************INITIALIZED*************************************/ case BAL_STATEMACH_INITIALIZED: BAL_SAVELASTSTATES(); bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; bal_state.state = BAL_STATEMACH_CHECK_BALANCING; bal_state.substate = BAL_ENTRY; break; #if BALANCING_VOLTAGE_BASED == FALSE /****************************CHECK_BALANCING*************************************/ case BAL_STATEMACH_CHECK_BALANCING: BAL_SAVELASTSTATES(); if (bal_state.substate == BAL_ENTRY) { if (bal_state.balancing_global_allowed == FALSE) { if (bal_state.active == TRUE) { BAL_Deactivate(); } bal_state.active = FALSE; bal_state.substate = BAL_ENTRY; } else { bal_state.substate = BAL_CHECK_IMBALANCES; } bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; break; } else if (bal_state.substate == BAL_CHECK_IMBALANCES) { if (bal_state.active == TRUE) { BAL_Deactivate(); } if (BAL_Check_Imbalances() == TRUE) { bal_state.state = BAL_STATEMACH_BALANCE; bal_state.substate = BAL_ENTRY; } else { bal_state.substate = BAL_COMPUTE_IMBALANCES; } bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; break; } else if (bal_state.substate == BAL_COMPUTE_IMBALANCES) { if (bal_state.rest_timer == 0) { BAL_Compute_Imbalances(); bal_state.state = BAL_STATEMACH_BALANCE; bal_state.substate = BAL_ENTRY; } else { bal_state.substate = BAL_CHECK_IMBALANCES; } bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; break; } break; /****************************BALANCE*************************************/ case BAL_STATEMACH_BALANCE: BAL_SAVELASTSTATES(); if (bal_state.substate == BAL_ENTRY) { if (bal_state.balancing_global_allowed == FALSE) { if (bal_state.active == TRUE) { BAL_Deactivate(); } bal_state.active = FALSE; bal_state.substate = BAL_STATEMACH_CHECK_BALANCING; } else { bal_state.substate = BAL_ACTIVATE_BALANCING; } bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; break; } else if (bal_state.substate == BAL_ACTIVATE_BALANCING) { DB_ReadBlock(&bal_minmax, DATA_BLOCK_ID_MINMAX); /* do not balance under a certain voltage level */ if (bal_minmax.voltage_min <= BAL_LOWER_VOLTAGE_LIMIT_MV || bal_minmax.temperature_max >= BAL_UPPER_TEMPERATURE_LIMIT_DEG || BAL_Check_Imbalances() == FALSE || bal_state.balancing_global_allowed == FALSE) { if (bal_state.active == TRUE) { BAL_Deactivate(); } bal_state.state = BAL_STATEMACH_CHECK_BALANCING; bal_state.substate = BAL_ENTRY; break; } else { BAL_Activate_Balancing_History(); bal_state.timer = BAL_STATEMACH_BALANCINGTIME_100MS; break; } } break; #else /* voltage-based balancing */ case BAL_STATEMACH_CHECK_BALANCING: BAL_SAVELASTSTATES(); statereq = BAL_TransferStateRequest(); if (statereq == BAL_STATE_NOBALANCING_REQUEST) { bal_state.balancing_allowed = FALSE; } if (statereq == BAL_STATE_ALLOWBALANCING_REQUEST) { bal_state.balancing_allowed = TRUE; } bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; if (bal_state.balancing_allowed == FALSE || bal_state.balancing_global_allowed == FALSE) { BAL_Deactivate(); bal_state.active = FALSE; } else { if (bal_state.rest_timer == 0) { bal_state.state = BAL_STATEMACH_BALANCE; bal_state.substate = BAL_ENTRY; } } break; /****************************BALANCE*************************************/ case BAL_STATEMACH_BALANCE: BAL_SAVELASTSTATES(); /* Check if balancing is still allowed */ statereq = BAL_TransferStateRequest(); if (statereq == BAL_STATE_NOBALANCING_REQUEST) { bal_state.balancing_allowed = FALSE; } if (statereq == BAL_STATE_ALLOWBALANCING_REQUEST) { bal_state.balancing_allowed = TRUE; } if (bal_state.balancing_global_allowed == FALSE) { if (bal_state.active == TRUE) { BAL_Deactivate(); } bal_state.active = FALSE; bal_state.state = BAL_STATEMACH_CHECK_BALANCING; bal_state.substate = BAL_ENTRY; bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; break; } if (bal_state.substate == BAL_ENTRY) { if (bal_state.balancing_allowed == FALSE) { if (bal_state.active == TRUE) { BAL_Deactivate(); } bal_state.active = FALSE; bal_state.state = BAL_STATEMACH_CHECK_BALANCING; bal_state.substate = BAL_ENTRY; } else { bal_state.substate = BAL_CHECK_LOWEST_VOLTAGE; } bal_state.timer = BAL_STATEMACH_SHORTTIME_100MS; break; } else if (bal_state.substate == BAL_CHECK_LOWEST_VOLTAGE) { DB_ReadBlock(&bal_minmax, DATA_BLOCK_ID_MINMAX); /* stop balacing if minimum voltage is below minimum threshold or maximum cell temperature breached upper temperature limit */ if (bal_minmax.voltage_min <= BAL_LOWER_VOLTAGE_LIMIT_MV || bal_minmax.temperature_max >= BAL_UPPER_TEMPERATURE_LIMIT_DEG) { if (bal_state.active == TRUE) { BAL_Deactivate(); } bal_state.state = BAL_STATEMACH_CHECK_BALANCING; bal_state.substate = BAL_ENTRY; } else { bal_state.substate = BAL_CHECK_CURRENT; } bal_state.timer = BAL_STATEMACH_BALANCINGTIME_100MS; break; } else if (bal_state.substate == BAL_CHECK_CURRENT) { if (bal_state.rest_timer == 0) { bal_state.substate = BAL_ACTIVATE_BALANCING; } else { if (bal_state.active == TRUE) { BAL_Deactivate(); } bal_state.state = BAL_STATEMACH_CHECK_BALANCING; bal_state.substate = BAL_ENTRY; } bal_state.timer = BAL_STATEMACH_BALANCINGTIME_100MS; break; } else if (bal_state.substate == BAL_ACTIVATE_BALANCING) { if (bal_state.balancing_allowed == FALSE) { if (bal_state.active == TRUE) { BAL_Deactivate(); } bal_state.active = FALSE; bal_state.state = BAL_STATEMACH_CHECK_BALANCING; bal_state.substate = BAL_ENTRY; } else { finished = BAL_Activate_Balancing_Voltage(); if (finished == TRUE) { bal_state.balancing_threshold = BAL_THRESHOLD_MV + BAL_HYSTERESIS_MV; bal_state.state = BAL_STATEMACH_CHECK_BALANCING; bal_state.substate = BAL_ENTRY; } else { bal_state.state = BAL_STATEMACH_BALANCE; bal_state.substate = BAL_ENTRY; } } bal_state.timer = BAL_STATEMACH_BALANCINGTIME_100MS; break; } break; #endif /* endif balancing type */ default: break; } /* end switch (bal_state.state) */ bal_state.triggerentry--; }
tonyhuang84/foxbms
embedded-software/mcu-common/src/module/cansignal/cansignal.h
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file cansignal.h * @author <NAME> * @date 01.10.2015 (date of creation) * @ingroup DRIVERS * @prefix CANS * * @brief Headers for the messages and signal settings for the CAN driver * * generic conversion module header of Can signals from CAN buffered reception to * DATA Manager and vice versa * */ #ifndef CANSIGNAL_H_ #define CANSIGNAL_H_ /*================== Includes =============================================*/ #include "cansignal_cfg.h" #include "can.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ /** * This structure contains variables relevant for the CAN signal module. */ typedef struct { uint8_t periodic_enable; /*!< defines if periodic transmit and receive should run */ uint8_t current_sensor_present; /*!< defines if a current sensor is detected */ uint8_t current_sensor_cc_present; /*!< defines if a CC info is being sent */ } CANS_STATE_s; /*================== Function Prototypes ==================================*/ /** * initializes local variables and module internals needed to use conversion of * can signals. Until now no initialization is needed and thus the function does * nothing. */ extern void CANS_Init(void); /** * handles the conversion of can signals from and to datamanager database or * other modules defined by the getter and setter configuration. */ extern void CANS_MainFunction(void); extern void CANS_Enable_Periodic(uint8_t command); extern uint8_t CANS_IsCurrentSensorPresent(void); extern uint8_t CANS_IsCurrentSensorCCPresent(void); /** * @brief Add message to transmit buffer, message will be transmitted shortly after. * * @param canNode: canNode on which the message shall be transmitted * @param msgID: ID of the message that will be transmitted * @param ptrMsgData: pointer to a uint8_t array that contains the message that will be transmitted * @param msgLength: length of the message that will be transmitted * This parameter can be a value of CAN_identifier_type. * @param RTR Specifies the type of frame for the message that will be transmitted. * This parameter can be a value of CAN_remote_transmission_request * * @retval E_OK if successful, E_NOT_OK if buffer is full or error occurred */ extern STD_RETURN_TYPE_e CANS_AddMessage(CAN_NodeTypeDef_e canNode, uint32_t msgID, uint8_t* ptrMsgData, uint32_t msgLength, uint32_t RTR); /** * @brief Transmits canNode transmit buffer * * @param canNode: canNode on which the message shall be transmitted * * @retval E_OK if transmission successful, otherwise E_NOT_OK */ extern STD_RETURN_TYPE_e CANS_TransmitBuffer(CAN_NodeTypeDef_e canNode); /** * @brief Transmits message directly on the CAN bus * * @param canNode: canNode on which the message shall be transmitted * @param msgID: ID of the message that will be transmitted * @param ptrMsgData: pointer to the data that shall be transmitted * @param msgLength: Specifies the data length * @param RTR: Specifies the type of frame for the message that will be transmitted. * * @retval E_OK if transmission successful, otherwise E_NOT_OK */ extern STD_RETURN_TYPE_e CANS_TransmitMessage(CAN_NodeTypeDef_e canNode, uint32_t msgID, uint8_t* ptrMsgData, uint32_t msgLength, uint32_t RTR); /*================== Function Implementations =============================*/ #endif /* CANSIGNAL_H_ */
tonyhuang84/foxbms
embedded-software/mcu-secondary/src/application/bms/bms.h
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file bms.h * @author <NAME> * @date 21.09.2015 (date of creation) * @ingroup ENGINE * @prefix BMS * * @brief bms driver header * * */ #ifndef BMS_H_ #define BMS_H_ /*================== Includes =============================================*/ #include "bms_cfg.h" /*================== Macros and Definitions ===============================*/ /** * Symbolic names for busyness of the syscontrol */ typedef enum { BMS_CHECK_OK = 0, /*!< syscontrol ok */ BMS_CHECK_BUSY = 1, /*!< syscontrol busy */ BMS_CHECK_NOT_OK = 2, /*!< syscontrol not ok */ } BMS_CHECK_e; typedef enum { BMS_MODE_STARTUP_EVENT = 0, /*!< syscontrol startup */ /* BMS_MODE_EVENT_INIT = 1, */ /*!< todo */ BMS_MODE_CYCLIC_EVENT = 2, /*!< for cyclic events */ BMS_MODE_TRIGGERED_EVENT = 3, /*!< for triggered events */ BMS_MODE_ABNORMAL_EVENT = 4, /*!< for abnormal (error etc.) events */ BMS_MODE_EVENT_RESERVED = 0xFF, /*!< do not use */ } BMS_TRIG_EVENT_e; /*================== Function Implementations =============================*/ /*================== Includes =============================================*/ /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ /*================== Function Prototypes ==================================*/ /*================== Function Implementations =============================*/ /*================== Constant and Variable Definitions ====================*/ /** * States of the SYS state machine */ typedef enum { /* Init-Sequence */ BMS_STATEMACH_UNINITIALIZED = 0, /*!< */ BMS_STATEMACH_INITIALIZATION = 1, /*!< */ BMS_STATEMACH_INITIALIZED = 2, /*!< */ BMS_STATEMACH_IDLE = 3, /*!< */ BMS_STATEMACH_STANDBY = 4, /*!< */ BMS_STATEMACH_PRECHARGE = 5, /*!< */ BMS_STATEMACH_NORMAL = 6, /*!< */ BMS_STATEMACH_CHARGE_PRECHARGE = 7, /*!< */ BMS_STATEMACH_CHARGE = 8, /*!< */ BMS_STATEMACH_UNDEFINED = 20, /*!< undefined state */ BMS_STATEMACH_RESERVED1 = 0x80, /*!< reserved state */ BMS_STATEMACH_ERROR = 0xF0, /*!< Error-State: */ } BMS_STATEMACH_e; /** * Substates of the SYS state machine */ typedef enum { BMS_ENTRY = 0, /*!< Substate entry state */ BMS_CHECK_ERROR_FLAGS_INTERLOCK = 1, /*!< Substate check measurements after interlock closed */ BMS_INTERLOCK_CHECKED = 2, /*!< Substate interlocked checked */ BMS_CHECK_STATE_REQUESTS = 3, /*!< Substate check if there is a state request */ BMS_CHECK_ERROR_FLAGS = 4, /*!< Substate check if any error flag set */ BMS_CHECK_CONTACTOR_NORMAL_STATE = 5, /*!< Substate in precharge, check if there contactors reached normal */ BMS_CHECK_CONTACTOR_CHARGE_STATE = 6, /*!< Substate in precharge, check if there contactors reached normal */ BMS_OPEN_INTERLOCK = 7, /*!< Substate in error to open interlock after contactors have been opened */ BMS_CHECK_INTERLOCK_CLOSE_AFTER_ERROR = 8, /*!< Substate in error to close interlock after all error flags were reset */ } BMS_STATEMACH_SUB_e; /** * State requests for the SYS statemachine */ typedef enum { BMS_STATE_INIT_REQUEST = BMS_STATEMACH_INITIALIZATION, /*!< */ BMS_STATE_ERROR_REQUEST = BMS_STATEMACH_ERROR, /*!< */ BMS_STATE_NO_REQUEST = BMS_STATEMACH_RESERVED1, /*!< */ } BMS_STATE_REQUEST_e; /** * Possible return values when state requests are made to the SYS statemachine */ typedef enum { BMS_OK = 0, /*!< CONT --> ok */ BMS_BUSY_OK = 1, /*!< CONT under load --> ok */ BMS_REQUEST_PENDING = 2, /*!< requested to be executed */ BMS_ILLEGAL_REQUEST = 3, /*!< Request can not be executed */ BMS_ALREADY_INITIALIZED = 30, /*!< Initialization of LTC already finished */ BMS_ILLEGAL_TASK_TYPE = 99, /*!< Illegal */ } BMS_RETURN_TYPE_e; /** * This structure contains all the variables relevant for the CONT state machine. * The user can get the current state of the CONT state machine with this variable */ typedef struct { uint16_t timer; /*!< time in ms before the state machine processes the next state, e.g. in counts of 1ms */ BMS_STATE_REQUEST_e statereq; /*!< current state request made to the state machine */ BMS_STATEMACH_e state; /*!< state of Driver State Machine */ BMS_STATEMACH_SUB_e substate; /*!< current substate of the state machine */ BMS_STATEMACH_e laststate; /*!< previous state of the state machine */ BMS_STATEMACH_SUB_e lastsubstate; /*!< previous substate of the state machine */ uint32_t ErrRequestCounter; /*!< counts the number of illegal requests to the LTC state machine */ uint8_t triggerentry; /*!< counter for re-entrance protection (function running flag) */ uint8_t counter; /*!< general purpose counter*/ } BMS_STATE_s; /*================== Function Prototypes ==================================*/ /** * @brief sets the current state request of the state variable bms_state. * * @details This function is used to make a state request to the state machine,e.g, start voltage * measurement, read result of voltage measurement, re-initialization. * It calls BMS_CheckStateRequest() to check if the request is valid. The state request is * rejected if is not valid. The result of the check is returned immediately, so that the * requester can act in case it made a non-valid state request. * * @param statereq state request to set * * @return current state request, taken from BMS_STATE_REQUEST_e */ extern BMS_RETURN_TYPE_e BMS_SetStateRequest(BMS_STATE_REQUEST_e statereq); /** * @brief Returns the current state. * * @details This function is used in the functioning of the SYS state machine. * * @return current state, taken from BMS_STATEMACH_e */ extern BMS_STATEMACH_e BMS_GetState(void); /** * @brief trigger function for the SYS driver state machine. * * @details This function contains the sequence of events in the SYS state machine. It must be * called time-triggered, every 1ms. */ extern void BMS_Trigger(void); #endif /* BMS_H_ */
tonyhuang84/foxbms
embedded-software/mcu-common/src/module/ltc/ltc_pec.h
<reponame>tonyhuang84/foxbms /************************************ REVISION HISTORY $Revision: 1000 $ $Date: 2013-07-15 Copyright (c) 2013, Linear Technology Corp.(LTC) 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 OWNER 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Linear Technology Corp. The Linear Technology Linduino is not affiliated with the official Arduino team. However, the Linduino is only possible because of the Arduino team's commitment to the open-source community. Please, visit http://www.arduino.cc and http://store.arduino.cc , and consider a purchase that will help fund their ongoing work. Copyright 2013 Linear Technology Corp. (LTC) ***********************************************************/ /* Pre computed crc15 table used for the LTC6804 PEC calculation The code used to generate the crc15 table is: void generate_crc15_table() { int remainder; for (int i = 0; i<256;i++) { remainder = i<< 7; for (int bit = 8; bit > 0; --bit) { if ((remainder & 0x4000) > 0) equivalent to remainder & 2^14 simply check for MSB { remainder = ((remainder << 1)) ; remainder = (remainder ^ 0x4599); } else { remainder = ((remainder << 1)); } } crc15Table[i] = remainder&0xFFFF; } } */ #ifndef LTC_PEC_H_ #define LTC_PEC_H_ /*================== Includes =============================================*/ #include "general.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ static const unsigned int crc15Table[256] = { /* precomputed CRC15 Table */ 0x0, 0xc599, 0xceab, 0xb32, 0xd8cf, 0x1d56, 0x1664, 0xd3fd, 0xf407, 0x319e, 0x3aac, 0xff35, 0x2cc8, 0xe951, 0xe263, 0x27fa, 0xad97, 0x680e, 0x633c, 0xa6a5, 0x7558, 0xb0c1, 0xbbf3, 0x7e6a, 0x5990, 0x9c09, 0x973b, 0x52a2, 0x815f, 0x44c6, 0x4ff4, 0x8a6d, 0x5b2e, 0x9eb7, 0x9585, 0x501c, 0x83e1, 0x4678, 0x4d4a, 0x88d3, 0xaf29, 0x6ab0, 0x6182, 0xa41b, 0x77e6, 0xb27f, 0xb94d, 0x7cd4, 0xf6b9, 0x3320, 0x3812, 0xfd8b, 0x2e76, 0xebef, 0xe0dd, 0x2544, 0x2be, 0xc727, 0xcc15, 0x98c, 0xda71, 0x1fe8, 0x14da, 0xd143, 0xf3c5, 0x365c, 0x3d6e, 0xf8f7, 0x2b0a, 0xee93, 0xe5a1, 0x2038, 0x7c2, 0xc25b, 0xc969, 0xcf0, 0xdf0d, 0x1a94, 0x11a6, 0xd43f, 0x5e52, 0x9bcb, 0x90f9, 0x5560, 0x869d, 0x4304, 0x4836, 0x8daf, 0xaa55, 0x6fcc, 0x64fe, 0xa167, 0x729a, 0xb703, 0xbc31, 0x79a8, 0xa8eb, 0x6d72, 0x6640, 0xa3d9, 0x7024, 0xb5bd, 0xbe8f, 0x7b16, 0x5cec, 0x9975, 0x9247, 0x57de, 0x8423, 0x41ba, 0x4a88, 0x8f11, 0x57c, 0xc0e5, 0xcbd7, 0xe4e, 0xddb3, 0x182a, 0x1318, 0xd681, 0xf17b, 0x34e2, 0x3fd0, 0xfa49, 0x29b4, 0xec2d, 0xe71f, 0x2286, 0xa213, 0x678a, 0x6cb8, 0xa921, 0x7adc, 0xbf45, 0xb477, 0x71ee, 0x5614, 0x938d, 0x98bf, 0x5d26, 0x8edb, 0x4b42, 0x4070, 0x85e9, 0xf84, 0xca1d, 0xc12f, 0x4b6, 0xd74b, 0x12d2, 0x19e0, 0xdc79, 0xfb83, 0x3e1a, 0x3528, 0xf0b1, 0x234c, 0xe6d5, 0xede7, 0x287e, 0xf93d, 0x3ca4, 0x3796, 0xf20f, 0x21f2, 0xe46b, 0xef59, 0x2ac0, 0xd3a, 0xc8a3, 0xc391, 0x608, 0xd5f5, 0x106c, 0x1b5e, 0xdec7, 0x54aa, 0x9133, 0x9a01, 0x5f98, 0x8c65, 0x49fc, 0x42ce, 0x8757, 0xa0ad, 0x6534, 0x6e06, 0xab9f, 0x7862, 0xbdfb, 0xb6c9, 0x7350, 0x51d6, 0x944f, 0x9f7d, 0x5ae4, 0x8919, 0x4c80, 0x47b2, 0x822b, 0xa5d1, 0x6048, 0x6b7a, 0xaee3, 0x7d1e, 0xb887, 0xb3b5, 0x762c, 0xfc41, 0x39d8, 0x32ea, 0xf773, 0x248e, 0xe117, 0xea25, 0x2fbc, 0x846, 0xcddf, 0xc6ed, 0x374, 0xd089, 0x1510, 0x1e22, 0xdbbb, 0xaf8, 0xcf61, 0xc453, 0x1ca, 0xd237, 0x17ae, 0x1c9c, 0xd905, 0xfeff, 0x3b66, 0x3054, 0xf5cd, 0x2630, 0xe3a9, 0xe89b, 0x2d02, 0xa76f, 0x62f6, 0x69c4, 0xac5d, 0x7fa0, 0xba39, 0xb10b, 0x7492, 0x5368, 0x96f1, 0x9dc3, 0x585a, 0x8ba7, 0x4e3e, 0x450c, 0x8095 }; /*================== Function Prototypes ==================================*/ /** * @brief calculates the PEC * * @param len Number of bytes that will be used to calculate a PEC * @param data Array of data that will be used to calculate a PEC * * @return retVal PEC */ uint16_t LTC_pec15_calc(uint8_t len, uint8_t *data); /*================== Function Implementations =============================*/ #endif /* LTC_PEC_H_ */
tonyhuang84/foxbms
embedded-software/mcu-primary/src/module/nvram/eepr.c
<gh_stars>0 /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file eepr.c * @author <NAME> * @date 07.10.2015 (date of creation) * @ingroup DRIVERS * @prefix EEPR * * @brief Driver for the storage in the EEPROM memory. * * driver for external EEPROM device AT25128 (16kByte) * /HOLD and /WP are permanently kept at Hi-Level, thus HW-Write-Protection (WP) is disabled. * SW-Protection(Block Write Protection) could be done by Sending Command EEPR_CMD_WREN if disabled before by EEPR_CMD_WRDI. * At startup the device is unprotected. Actual state will be provided by EEPR_CMD_RDSR (Read Status Register). * A Block Write Protection can be controlled by Status Register Bit BP1 and BP0 in different address ranges within * the whole range: Byte Address 0x0000..0x3FFF * \n * | Protected Address | BP1 | BP0 | * | :---- |:---- | :---- | * | None | 0 | 0 | * | 0x3000..0x3FFFF | 0 | 1 | * | 0x2000..0x3FFFF | 1 | 0 | * | 0x0000..0x3FFFF | 1 | 1 | */ /*================== Includes =============================================*/ #include "eepr.h" #include "diag.h" #include "io.h" #include "os.h" #include "rtc.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ uint8_t eepr_cmd_read[EEPR_TXBUF_LENGTH] = {EEPR_CMD_READ, 0, 0 }; uint8_t eepr_cmd_write[EEPR_TXBUF_LENGTH] = {EEPR_CMD_WRITE, 0, 0 }; uint8_t eepr_cmd_WREN[1] = {EEPR_CMD_WREN }; uint8_t eepr_cmdbuf[2]; /* buffer for sending commands via SPI */ uint8_t lastDirtyChannel; uint8_t lastReadChannel; uint16_t byte_len; uint8_t eepr_backupbuffer[EEPR_CH_MAXLENGTH]; EEPR_DATAHANDLING_ERROR_e EEPR_ch_dataerrors[EEPR_CHANNEL_MAX_NR]; uint8_t cnt; /* counter variable */ uint16_t timeout_cnt = 0; uint8_t tmpbuf[EEPR_TXBUF_LENGTH]; uint8_t protectionbuf[2]; EEPR_REQ_HW_PROTECTION_s protection_request = { .SR.u8 = 0xFF, }; /* EEPR_STATUSREGISTER_s epr_state; */ EEPR_STATUS_s eepr_state = { .RSR.u8 = 0xFF, .hwprotection = 0, .protectionstartadd = 1, .protectionendadd = 0, .state = EEPR_DISABLED, .stateend = EEPR_DISABLED, .statestart = EEPR_DISABLED, .statereq = EEPR_NO_REQUEST, .substate = 0, .triggerentry = 0, .repeat = 2, .timer = 0, .eepromaddress1 = 0, .eepromaddress2 = 0, .currentpagelength = 0, .nr_of_pages = 1, /* will be re-set at initialization to sizeof(struct_EEPR_CALIB_FRAME)+(EEPR_PageLength-1)/EEPR_PageLength */ .readtime = EEPR_READTIME_PER_PAGE, /* max. readtime of one page */ .writetime = EEPR_WRITETIME_PER_PAGE, /* max. writetime of one page */ .page_nr = 0, .write_len = EEPR_PageLength, .read_len = EEPR_PageLength, .ramaddress = 0, .currentchannel = EEPR_CH_HEADER, }; EEPR_DATA_HANDLING_s data_handler = { .dirtyChannel = 0xFF, .repeat = 2, .state = 0, .recovery_active = 0, }; /*================== Function Prototypes ==================================*/ static void EEPR_StateFailed(EEPR_STATE_e state); static void EEPR_ReEnterStateInit(void); static EEPR_STATE_e EEPR_CheckStateRequest(EEPR_STATE_e state_req, EEPR_CHANNEL_ID_TYPE_e channel); static void EEPR_TransferStateRequest(void); void EEPR_ClearErrorEvent(void); static void EEPR_delete_bkpsrambuffer(EEPR_CHANNEL_ID_TYPE_e eepr_channel); static EEPR_ERRORTYPES_e EEPR_BackupChannelData2Eepr(EEPR_CHANNEL_ID_TYPE_e eepr_channel); static EEPR_ERRORTYPES_e EEPR_ReadChannelData(EEPR_CHANNEL_ID_TYPE_e eepr_channel); static EEPR_ERRORTYPES_e EEPR_RefreshChannelData(EEPR_CHANNEL_ID_TYPE_e eepr_channel); STD_RETURN_TYPE_e EEPR_CheckDirtyFlags(); uint8_t EEPR_GetNextDirtyChannel(); /*================== Function Implementations =============================*/ /* FIXME if config changes (for example eepr_WR_RD_buffer) the main driver files have to be changed as well. Maintainability? */ /** * @brief initialization of external Serial EEPROM device (AT25128N) * * @return DIAG_EEPR_OK if initialization OK, otherwise DIAG_EEPR_ERROR */ EEPR_RETURNTYPE_e EEPR_StartInitialization(void) { EEPR_RETURNTYPE_e retVal = EEPR_ERROR; eepr_cmdbuf[0]=(EEPR_CMD_RDSR); /* first byte is command, second one is dummy (for data receive) */ if (EEPR_SendData(eepr_cmdbuf, 2, 1) == EEPR_OK) { /* send data, data length, receive data offset(leading dummy bytes) */ retVal = EEPR_OK; /* EEPROM Initialization: command sending process has been started */ } else { retVal = EEPR_ERROR; /* EEPROM Initialization failed due to communication error */ } return retVal; } uint16_t EEPR_GetChReadTime(EEPR_CHANNEL_ID_TYPE_e channel) { uint16_t number_of_pages; if (eepr_ch_cfg[channel].eepromaddress % EEPR_PageLength == 0) number_of_pages = (eepr_ch_cfg[channel].length+(EEPR_PageLength-1))/EEPR_PageLength; else number_of_pages = (((eepr_ch_cfg[channel].length - (eepr_ch_cfg[channel].eepromaddress % EEPR_PageLength))+(EEPR_PageLength-1))/EEPR_PageLength)+1; return number_of_pages * EEPR_READTIME_PER_PAGE; } uint16_t EEPR_GetChWriteTime(EEPR_CHANNEL_ID_TYPE_e channel) { uint16_t number_of_pages; if (eepr_ch_cfg[channel].eepromaddress % EEPR_PageLength == 0) number_of_pages = (eepr_ch_cfg[channel].length+(EEPR_PageLength-1))/EEPR_PageLength; else number_of_pages = (((eepr_ch_cfg[channel].length - (eepr_ch_cfg[channel].eepromaddress % EEPR_PageLength))+(EEPR_PageLength-1))/EEPR_PageLength)+1; return number_of_pages * EEPR_WRITETIME_PER_PAGE; } uint16_t EEPR_GetCurrentChReadTime(void) { return eepr_state.nr_of_pages * EEPR_READTIME_PER_PAGE; } uint16_t EEPR_GetCurrentChWriteTime(void) { return eepr_state.nr_of_pages * EEPR_WRITETIME_PER_PAGE; } uint16_t EEPR_GetRestReadTime(void) { return (eepr_state.nr_of_pages - eepr_state.page_nr) * EEPR_READTIME_PER_PAGE; } uint16_t EEPR_GetRestWriteTime(void) { return (eepr_state.nr_of_pages - eepr_state.page_nr) * EEPR_WRITETIME_PER_PAGE; } uint8_t EEPR_ReadMemory(uint32_t EeprAddr, uint16_t byte_len) { #ifdef EEPROM_VERSION_AT25128 eepr_cmd_read[1]=(uint8_t)(EeprAddr>>8); /* Highbyte of Address */ eepr_cmd_read[2]=(uint8_t)(EeprAddr); /* Lowbyte of Address */ #endif #ifdef EEPROM_VERSION_M95M02 eepr_cmd_read[1]=(uint8_t)(EeprAddr>>16); /* Highbyte of Address */ eepr_cmd_read[2]=(uint8_t)(EeprAddr>>8); /* Lowbyte of Address */ eepr_cmd_read[3]=(uint8_t)(EeprAddr); /* Lowbyte of Address */ #endif if (byte_len > EEPR_CH_MAXLENGTH) return 0xFE; if (EEPR_SendData(&eepr_cmd_read[0], byte_len+EEPR_CMDBUF_OFFSET, EEPR_CMDBUF_OFFSET) == 0) { /* Send Read Command has been started */ return 0; } else { return 0xFF; } } /** * @fn U8 EEPR_WriteMemory(U32 EeprAddr,U8 *srcptr ,U16 byte_len) * @brief writes "byte_len" of bytes from EEPROM memory starting at "address" and reading data from "srcptr" * * @param EeprAddr starting address of EEPROM where to write data * @param srcptr pointer where the data is stored * @param byte_len length of bytes that are to be written * @return 0 if writing successful, otherwise 0xFF */ uint8_t EEPR_WriteMemory(uint32_t EeprAddr, uint8_t *srcptr, uint16_t byte_len) { uint8_t cnt = 0; if (srcptr == NULL) return 0xFF; if (!byte_len) return 0xFF; else if (byte_len > EEPR_CH_MAXLENGTH) return 0xFE; #ifdef EEPROM_VERSION_AT25128 tmpbuf[0] = EEPR_CMD_WRITE; tmpbuf[1] = (uint8_t)(EeprAddr>>8); /* Highbyte of Address */ tmpbuf[2] = (uint8_t)(EeprAddr); /* Lowbyte of Address */ #endif #ifdef EEPROM_VERSION_M95M02 tmpbuf[0] = EEPR_CMD_WRITE; tmpbuf[1] = (uint8_t)(EeprAddr>>16); /* Highbyte of Address */ tmpbuf[2] = (uint8_t)(EeprAddr>>8); /* Lowbyte of Address */ tmpbuf[3] = (uint8_t)(EeprAddr); /* Lowbyte of Address */ #endif for (cnt = 0; cnt < byte_len; cnt++) { tmpbuf[EEPR_CMDBUF_OFFSET+cnt]=*srcptr++; } if (EEPR_SendData(&tmpbuf[0], byte_len+EEPR_CMDBUF_OFFSET, EEPR_CMDBUF_OFFSET) == EEPR_OK) { /* Send Write Command has been started */ return 0; } else { return 0xFF; } } /** * @brief writes the protection bytes BP0 and BP1 into EEPROM * * @return 0 if writing successful, otherwise 1 */ uint8_t EEPR_SetHwProtection(void) { protectionbuf[0] = EEPR_CMD_WRSR; protectionbuf[1] = (uint8_t)EEPR_HW_PROTECTION; if (EEPR_SendData(&protectionbuf[0], 2, 0) == EEPR_OK) { return 0; } else { return 1; } } /** * @brief sets the startaddress and the endaddress of the hardware-protected area */ void setProtectedAddresses(void) { if (eepr_state.hwprotection == 0x00) { /* no protection on, set values 1 and 0, so ne values are between start and end */ eepr_state.protectionstartadd = 0x4000; /* @FIXME: check and write some comments */ eepr_state.protectionendadd = 0x3FFF; } else if (eepr_state.hwprotection == 0x04) { eepr_state.protectionstartadd = 0x3000; eepr_state.protectionendadd = 0x3FFF; } else if (eepr_state.hwprotection == 0x08) { eepr_state.protectionstartadd = 0x2000; eepr_state.protectionendadd = 0x3FFF; } else if (eepr_state.hwprotection == 0x0C) { eepr_state.protectionstartadd = 0x0000; eepr_state.protectionendadd = 0x3FFF; } } /** * @fn EEPR_STATE_e EEPR_GetState(void) * @brief * @return returns the current state */ EEPR_STATE_e EEPR_GetState(void) { return (eepr_state.state); } uint8_t EEPR_IsInFinalState(void) { EEPR_STATE_e tempstate; tempstate = EEPR_GetState(); if (tempstate == EEPR_IDLE || (tempstate == EEPR_PROTECTION_FAILED && eepr_state.substate == 1) || (tempstate == EEPR_WRITEFAILED && eepr_state.substate == 1) || (tempstate == EEPR_READFAILED && eepr_state.substate == 1) || (tempstate == EEPR_INITFAILED && eepr_state.substate == 1) || tempstate == EEPR_DISABLED || (tempstate == EEPR_STATEREQFAILED && eepr_state.substate == 1) || tempstate == EEPR_WRITEPROTECTED) { /* eeprom is in a final state, where it doesn´t need SPI or any other resources, so return true. */ return 1; } else { return 0; } } /** * @fn EEPR_STATE_e EEPR_CheckStateRequest(EEPR_STATE_e state_req, EEPR_CHANNEL_ID_TYPE_e channel) * @brief checks if the transition from one state to another one is allowed * * @param state_req requested state * @param channel eepr_channel to be written or read from * @return the requested state if accepted or EEPR_STATEREQFAILED if denied */ EEPR_STATE_e EEPR_CheckStateRequest(EEPR_STATE_e state_req, EEPR_CHANNEL_ID_TYPE_e channel) { /* Checks if transition from current state to state_req is allowed */ EEPR_STATE_e retVal = EEPR_STATEREQFAILED; /* when in EEPR_IDLE, EEPR_READFAILED or in EEPR_WRITEFAILED */ /* only accept requests for: EEPR_WRITEMEMORY , EEPR_READMEMORY or EEPR_IDLE */ if (eepr_state.state == EEPR_IDLE || eepr_state.state == EEPR_READFAILED || eepr_state.state == EEPR_WRITEFAILED) { if (state_req == EEPR_READMEMORY || state_req == EEPR_IDLE) { retVal = state_req; } else if (state_req == EEPR_WRITEMEMORY) { if (eepr_ch_cfg[channel].writeprotection == 0) {/* check if software writeprotection is on */ /* check if channel is located in hardware write protected area */ if (((eepr_ch_cfg[channel].eepromaddress >= eepr_state.protectionstartadd) && (eepr_ch_cfg[channel].eepromaddress <= eepr_state.protectionendadd)) || (((eepr_ch_cfg[channel].eepromaddress + eepr_ch_cfg[channel].length) >= eepr_state.protectionstartadd) && ((eepr_ch_cfg[channel].eepromaddress + eepr_ch_cfg[channel].length) <= eepr_state.protectionendadd))) { /* channel is write protected, transition is not allowed */ retVal = EEPR_WRITEPROTECTED; } else { retVal = state_req; } } else { retVal = EEPR_WRITEPROTECTED; } } else { retVal = EEPR_STATEREQFAILED; } } else if (eepr_state.state == EEPR_UNINITIALIZED || eepr_state.state == EEPR_INITFAILED || eepr_state.state == EEPR_DISABLED) { /* when in EEPR_INITFAILED, UNINITIALIZED or DISABLED */ /* only accept requests for: EEPR_IDLE or EEPR_UNINITIALIZED */ if (state_req == EEPR_IDLE || state_req == EEPR_UNINITIALIZED) { retVal = EEPR_UNINITIALIZED; } else { retVal = EEPR_STATEREQFAILED; } } else { retVal = EEPR_STATEREQFAILED; } return retVal; } EEPR_RETURNTYPE_e EEPR_SetStateRequest(EEPR_STATE_e state_req, EEPR_CHANNEL_ID_TYPE_e channel, uint8_t* ramaddress) { EEPR_RETURNTYPE_e retVal = EEPR_OK; EEPR_STATE_e tempstate; OS_TaskEnter_Critical(); if (eepr_state.triggerentry) { retVal = EEPR_BUSY; /* return as "BUSY" because EEPR_Trigger() is actually running */ } else { if (eepr_state.statereq != EEPR_NO_REQUEST) { retVal = EEPR_REQUEST_PENDING; /* return as "REQUEST PENDING" because another request is waiting in Queue */ } } if (retVal == EEPR_OK) { tempstate = EEPR_CheckStateRequest(state_req, channel); if (tempstate == EEPR_STATEREQFAILED || tempstate == EEPR_WRITEPROTECTED) { /* Requested state declined */ if (tempstate == EEPR_WRITEPROTECTED) retVal = EEPR_WR_PROTECTED; else retVal = EEPR_ERROR; } else { /* transition is allowed */ eepr_state.statereq = tempstate; eepr_state.ramaddress = ramaddress; eepr_state.currentchannel = channel; if (state_req == EEPR_UNINITIALIZED) { eepr_state.stateend = EEPR_IDLE; /* statemachine will automatically go to Idle after Initialization */ } else { eepr_state.stateend = state_req; } } } OS_TaskExit_Critical(); return (retVal); } /** * @fn void EEPR_TransferStateRequest(void) * @brief updates the current state after checking once again if the transition is allowed and sets all the variables needed */ void EEPR_TransferStateRequest(void) { /* uses the request to update the current state, if allowed */ uint16_t i; uint16_t datalength; /* checks if transition is still allowed */ if ((EEPR_CheckStateRequest(eepr_state.statereq, eepr_state.currentchannel) != EEPR_STATEREQFAILED) && (EEPR_CheckStateRequest(eepr_state.statereq, eepr_state.currentchannel) != EEPR_WRITEPROTECTED)) { /* start transition */ EEPR_ClearErrorEvent(); /* clears error events */ eepr_state.statestart = eepr_state.state; /* save starting point */ eepr_state.state = eepr_state.statereq; eepr_state.statereq = EEPR_NO_REQUEST; if (eepr_state.stateend == EEPR_WRITEMEMORY) { OS_TaskEnter_Critical(); datalength = eepr_ch_cfg[eepr_state.currentchannel].length; for (i = 0; i < datalength; i++) { eepr_WR_RD_buffer[i] = *(eepr_state.ramaddress + i); } eepr_WR_RD_Chksum = *(uint32_t*)(eepr_state.ramaddress + (datalength -4)); if (EEPR_CalcChecksum(eepr_WR_RD_buffer, datalength-4) != eepr_WR_RD_Chksum) { /* the data in the WR_RD-Buffer aren´t valid, therefore don´t write them into eeprom. */ eepr_state.state = EEPR_WRITEFAILED; OS_TaskExit_Critical(); return; } OS_TaskExit_Critical(); } if (eepr_state.stateend == EEPR_WRITEMEMORY || eepr_state.stateend == EEPR_READMEMORY) { if (eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength == 0) { eepr_state.eepromaddress1 = eepr_ch_cfg[eepr_state.currentchannel].eepromaddress; eepr_state.eepromaddress2 = eepr_state.eepromaddress1 + EEPR_PageLength; eepr_state.nr_of_pages = (eepr_ch_cfg[eepr_state.currentchannel].length+(EEPR_PageLength-1))/EEPR_PageLength; /* will be used for EEPROM write in blocks of EEPR_PageLength Byte pages */ } else { eepr_state.eepromaddress1 = eepr_ch_cfg[eepr_state.currentchannel].eepromaddress; eepr_state.eepromaddress2 = eepr_state.eepromaddress1 + EEPR_PageLength - (eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength); eepr_state.nr_of_pages = (((eepr_ch_cfg[eepr_state.currentchannel].length - (EEPR_PageLength-(eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength)))+(EEPR_PageLength-1))/EEPR_PageLength)+1;/* will be used for EEPROM write in blocks of EEPR_PageLength Byte pages */ /* will be used for EEPROM write in blocks of EEPR_PageLength Byte pages */ /* calculation: first page is from startaddress to next multiple of EEPR_PageLength, following pages are always EEPR_PageLength bytes */ } eepr_state.readtime = (eepr_state.nr_of_pages) * EEPR_READTIME_PER_PAGE; /* max. EEPR_READTIME_PER_PAGE ms time for reading for each page (EEPR_PageLength Byte) */ eepr_state.writetime = (eepr_state.nr_of_pages) * EEPR_WRITETIME_PER_PAGE; /* max. EEPR_WRITETIME_PER_PAGE ms time for writing for each page */ eepr_state.page_nr = 0; eepr_state.read_len = eepr_ch_cfg[eepr_state.currentchannel].length; eepr_state.write_len = eepr_ch_cfg[eepr_state.currentchannel].length; } } else { eepr_state.statereq = EEPR_NO_REQUEST; /* delete Request if declined */ } } /** * @fn void EEPR_ClearErrorEvent(void) * @brief sends error message and clears the error event */ void EEPR_ClearErrorEvent(void) { switch (eepr_state.statereq) { case EEPR_WRITEMEMORY: (void)(DIAG_Handler(DIAG_CH_CALIB_EEPR_FAILURE, DIAG_EVENT_RESET, 0, NULL)); /* clear error event */ break; case EEPR_READMEMORY: (void)(DIAG_Handler(DIAG_CH_CALIB_EEPR_FAILURE, DIAG_EVENT_RESET, 1, NULL)); /* clear error event */ break; case EEPR_IDLE: if (eepr_state.state == EEPR_IDLE || eepr_state.state == EEPR_READFAILED || eepr_state.state == EEPR_WRITEFAILED) { (void)(DIAG_Handler(DIAG_CH_CALIB_EEPR_FAILURE, DIAG_EVENT_RESET, 2, NULL)); /* clear error event */ } else if (eepr_state.state == EEPR_UNINITIALIZED || eepr_state.state == EEPR_INITFAILED || eepr_state.state == EEPR_DISABLED) { (void)(DIAG_Handler(DIAG_CH_CALIB_EEPR_FAILURE, DIAG_EVENT_RESET, 3, NULL)); /* clear error event */ } break; case EEPR_UNINITIALIZED: (void)(DIAG_Handler(DIAG_CH_CALIB_EEPR_FAILURE, DIAG_EVENT_RESET, 4, NULL)); /* clear error event */ break; default: break; } } /** * @brief transition function for error states * * @param state error state */ static void EEPR_StateFailed(EEPR_STATE_e state) { eepr_state.state = state; eepr_state.substate = 0; eepr_state.repeat = 2; /* reset re-try-timer for next usage */ } /** * @brief EEPROM state is reset to state after initialization */ static void EEPR_ReEnterStateInit(void) { eepr_state.page_nr = 0; /* eepr_state.eepromaddress1 = EEPR_DATA_STARTADDR; */ eepr_state.repeat = 2; /* reset re-try-timer for next usage */ } void EEPR_Trigger(void) { uint16_t i; /* running variable for loop */ EEPR_RETURNTYPE_e ret_val; EEPR_STATUSREGISTER_s tmp_eepr_stat; uint16_t c_idx; uint32_t chksum; EEPR_STATE_e statereq; /* Check re-entrance of function */ taskENTER_CRITICAL(); if (!eepr_state.triggerentry) { eepr_state.triggerentry++; ret_val = EEPR_OK; } else { ret_val = EEPR_ERROR; /* multiple calls of function */ } statereq = eepr_state.statereq; taskEXIT_CRITICAL(); if (ret_val == EEPR_ERROR) return; if (eepr_state.timer) { --eepr_state.timer; eepr_state.triggerentry--; return; /* handle state machine only when timer has elapsed */ } if (statereq != EEPR_NO_REQUEST) EEPR_TransferStateRequest(); /* update current state when there is a request */ switch (eepr_state.state) { case EEPR_DISABLED: break; case EEPR_UNINITIALIZED: ret_val = EEPR_StartInitialization(); /* initialize EEPROM */ if (ret_val == EEPR_OK) { eepr_state.timer = 5; eepr_state.state = EEPR_INIT_INPROCESS; eepr_state.repeat = 2; /* reset repeat counter for next usage */ } else { if (--eepr_state.repeat) { eepr_state.timer = 5; /* retry in 5ms */ } else { eepr_state.state = EEPR_INITFAILED; eepr_state.repeat = 2; /* reset repeat counter for next usage */ } } break; case EEPR_INIT_INPROCESS: /* wait for response */ ret_val = EEPR_ReceiveData((uint8_t*)(&tmp_eepr_stat), 1); if (ret_val != EEPR_OK) { /* no data available */ if (--eepr_state.repeat) { eepr_state.timer = 2; /* retry Reading in 1ms */ } else { EEPR_StateFailed(EEPR_INITFAILED); } break; } else { eepr_state.repeat = 2; /* reset repeat counter for next usage */ } /* response received */ if (tmp_eepr_stat.B.nRDY) { /* /RDY-Flag is set -> EEPROM is busy (write cycle progress) */ if (--eepr_state.repeat) { eepr_state.timer = 10; /* restart initialization */ eepr_state.state = EEPR_UNINITIALIZED; } else { EEPR_StateFailed(EEPR_INITFAILED); } } else { /* nRDY = 0, device is ready */ eepr_state.RSR = tmp_eepr_stat; /* overtake status information */ /* initialization succeeded */ eepr_state.timer = 0; eepr_state.state = EEPR_IDLE; #if 0 /* check write protection */ protection_request.SR = (EEPR_STATUSREGISTER_s)(uint8_t)EEPR_HW_PROTECTION; if ((eepr_state.RSR.B.BP0 == protection_request.SR.B.BP0) && (eepr_state.RSR.B.BP1 == protection_request.SR.B.BP1)) { /* correct write protection is set, initialization successful */ eepr_state.hwprotection = EEPR_HW_PROTECTION; setProtectedAddresses(); eepr_state.state = EEPR_IDLE; } else { /* request and set protection */ eepr_state.state = EEPR_INIT_PROTECTION_CFG; } #endif } break; #if 0 case EEPR_INIT_PROTECTION_CFG: /* do first Write-Enable (WEN) */ if (EEPR_SendData(&eepr_cmd_WREN[0], 1, 0) == EEPR_OK) { /* send data, data length, receive data offset(leading dummy bytes) */ /* Sending Command has been started */ if (--eepr_state.repeat) { eepr_state.timer = 10; eepr_state.state = EEPR_ENABLE_PROTECTION_CFG; eepr_state.substate = 0; eepr_state.repeat = 2; } else { EEPR_StateFailed(EEPR_PROTECTION_FAILED); } } else { eepr_state.timer = 1; } break; case EEPR_ENABLE_PROTECTION_CFG: if (eepr_state.substate == 0) { ret_val = EEPR_ReceiveData((uint8_t*)(&tmp_eepr_stat), 1); if (ret_val != EEPR_OK) break; /*Write-Enable (WEN) has been send !*/ /*Now, verify status if WREN was accepted*/ eepr_cmdbuf[0]=(EEPR_CMD_RDSR); /* first byte is command, second one is dummy (for data receive) */ if (EEPR_SendData(eepr_cmdbuf, 2, 1) == EEPR_OK) { /* send data, data length, receive data offset(leading dummy bytes) */ if (--eepr_state.repeat) { eepr_state.timer = 1; eepr_state.substate = 1; eepr_state.repeat = 2; /* stay in state EEPR_WRITE_ENABLE_INPROCESS */ } else { EEPR_StateFailed(EEPR_PROTECTION_FAILED); } } else { eepr_state.timer = 1; /* retry Sending */ } } else if (eepr_state.substate == 1) { /* check Status Register of EEPROM (RSR) */ ret_val = EEPR_ReceiveData((uint8_t*)(&tmp_eepr_stat), 1); if (ret_val != EEPR_OK) { if (--eepr_state.repeat) { /* no data available */ eepr_state.timer = 1; /* retry Receiving */ } else { EEPR_StateFailed(EEPR_PROTECTION_FAILED); } break; } /* response received */ if (!tmp_eepr_stat.B.nRDY) { /* /RDY-Flag is cleared -> EEPROM is not busy (write cycle not in process) */ eepr_state.RSR = tmp_eepr_stat; /* overtake status information */ /* initialization succeeded */ if (eepr_state.RSR.B.WEN) { /* Write-Enable (WEN) has been accepted !*/ eepr_state.state = EEPR_PROTECTION_CFG_ENABLED; break; } } /* Write Not Enabled OR EEPROM is busy */ /* retry Write Enabling */ if (--eepr_state.repeat) { eepr_state.state = EEPR_INIT_PROTECTION_CFG; /* retry to enable the write statusregister process */ eepr_state.substate = 0; eepr_state.timer = 5; } else { EEPR_StateFailed(EEPR_PROTECTION_FAILED); } } break; case EEPR_PROTECTION_CFG_ENABLED: ret_val = EEPR_SetHwProtection(); if (ret_val != EEPR_OK) { if (--eepr_state.repeat) { eepr_state.timer = 2; /* retry Start Command of EEPROM SRWrite */ } else { EEPR_StateFailed(EEPR_PROTECTION_FAILED); } } else { eepr_state.timer = 5; eepr_state.substate = 0; eepr_state.state = EEPR_PROTECTION_CFG_INPROCESS; } break; case EEPR_PROTECTION_CFG_INPROCESS: ret_val = EEPR_ReceiveData(&protectionbuf[0], 2); if (ret_val != EEPR_OK) break; if (eepr_state.substate == 0) { eepr_cmdbuf[0]=(EEPR_CMD_RDSR); /* first byte is command, second one is dummy (for data receive) */ if (EEPR_SendData(eepr_cmdbuf, 2, 1) == EEPR_OK) { if (--eepr_state.repeat) { eepr_state.timer = 1; eepr_state.substate = 1; eepr_state.repeat = 2; /* stay in state EEPR_PROTECTION_CFG_INPROCESS */ } else { EEPR_StateFailed(EEPR_PROTECTION_FAILED); } } else { eepr_state.timer = 1; /* retry Sending */ } } else { ret_val = EEPR_ReceiveData(&protectionbuf[0], 1); if (ret_val == EEPR_OK) { if (--eepr_state.repeat) { eepr_state.RSR = (EEPR_STATUSREGISTER_s)protectionbuf[0]; if ((eepr_state.RSR.B.BP0 == protection_request.SR.B.BP0) && (eepr_state.RSR.B.BP1 == protection_request.SR.B.BP1)) { /* protection bits have been set, continue to Idle */ EEPR_ReEnterStateInit(); eepr_state.hwprotection = EEPR_HW_PROTECTION; setProtectedAddresses(); eepr_state.state = EEPR_IDLE; } else { EEPR_StateFailed(EEPR_PROTECTION_FAILED); } } else { EEPR_StateFailed(EEPR_PROTECTION_FAILED); } } } break; #endif case EEPR_READMEMORY: /* at first, set the new read_len by subtracting the number of bytes already read. */ if (eepr_state.page_nr == 1) eepr_state.read_len = eepr_state.read_len - (EEPR_PageLength - (eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength)); if (eepr_state.page_nr > 1) eepr_state.read_len = eepr_state.read_len - EEPR_PageLength; if (eepr_state.page_nr == 0) { if (eepr_state.read_len > (EEPR_PageLength - (eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength))) eepr_state.currentpagelength = EEPR_PageLength - (eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength); else eepr_state.currentpagelength = eepr_state.read_len; ret_val = EEPR_ReadMemory(eepr_state.eepromaddress1, eepr_state.currentpagelength); } else { if (eepr_state.read_len > EEPR_PageLength) eepr_state.currentpagelength = EEPR_PageLength; else eepr_state.currentpagelength = eepr_state.read_len; ret_val = EEPR_ReadMemory(eepr_state.eepromaddress2, eepr_state.currentpagelength); } if (ret_val != EEPR_OK) { if (--eepr_state.repeat) { eepr_state.timer = 2; /* retry Start of EEPROM Reading */ } else { EEPR_StateFailed(EEPR_READFAILED); } } else { eepr_state.timer = 2; eepr_state.state = EEPR_READMEMORY_INPROCESS; } break; case EEPR_READMEMORY_INPROCESS: ret_val = EEPR_ReceiveData(&eepr_WR_RD_buffer[eepr_ch_cfg[eepr_state.currentchannel].length - eepr_state.read_len], eepr_state.currentpagelength); if (ret_val == EEPR_OK) { if (++eepr_state.page_nr < eepr_state.nr_of_pages) { if (eepr_state.page_nr != 1) { eepr_state.eepromaddress2 += EEPR_PageLength; } eepr_state.state = EEPR_READMEMORY; /* read next page */ } else { eepr_state.state = EEPR_CHECK_DATA; } } else { if (--eepr_state.repeat) { eepr_state.timer = 2; /* retry receiving data */ } else { EEPR_StateFailed(EEPR_READFAILED); } } break; case EEPR_CHECK_DATA: c_idx = eepr_ch_cfg[eepr_state.currentchannel].length; chksum =* (uint32_t*)(&eepr_WR_RD_buffer[c_idx-4]); if (chksum != EEPR_CalcChecksum(eepr_WR_RD_buffer, c_idx - 4)) { /* Verify Checksum */ /* data corrupt */ if (--eepr_state.repeat) { /* @FIXME: there is no repetition implemented */ EEPR_StateFailed(EEPR_READFAILED); /* EEPR_ReEnterStateInit(); */ } else { EEPR_StateFailed(EEPR_READFAILED); /********************************************/ /* KEEP CALBRATION DATA at last valid NVRAM data (CALIB_eNVMDATA) * or at default CALIB_defaultDATA*/ /********************************************/ } } else { for (i = 0; i < eepr_ch_cfg[eepr_state.currentchannel].length; i++) *(eepr_state.ramaddress+i) = (uint8_t) eepr_WR_RD_buffer[i]; eepr_ch_cfg[eepr_state.currentchannel].errorflag = EEPR_NO_ERROR; eepr_state.state = EEPR_IDLE; EEPR_ReEnterStateInit(); } break; case EEPR_IDLE: /* wait for State Change Request */ EEPR_ReEnterStateInit(); break; case EEPR_WRITEMEMORY: /* do first Write-Enable (WEN) */ if (EEPR_SendData(&eepr_cmd_WREN[0], 1, 0) == EEPR_OK) { /* send data, data length, receive data offset(leading dummy bytes) */ /* Sending Command has been started */ eepr_state.timer = 10; eepr_state.state = EEPR_WRITE_ENABLE_INPROCESS; eepr_state.substate = 0; eepr_state.repeat = 2; } else { if (--eepr_state.repeat) { eepr_state.timer = 1; } else { EEPR_StateFailed(EEPR_WRITEFAILED); } } break; case EEPR_WRITE_ENABLE_INPROCESS: if (eepr_state.substate == 0) { ret_val = EEPR_ReceiveData((uint8_t*)(&tmp_eepr_stat), 1); if (ret_val != EEPR_OK) break; /*Write-Enable (WEN) has been send !*/ /*Now, verify status if WREN was accepted*/ eepr_cmdbuf[0]=(EEPR_CMD_RDSR); /* first byte is command, second one is dummy (for data receive) */ if (EEPR_SendData(eepr_cmdbuf, 2, 1) == EEPR_OK) { /* send data, data length, receive data offset(leading dummy bytes) */ eepr_state.timer = 1; eepr_state.substate = 1; eepr_state.repeat = 2; /* stay in state EEPR_WRITE_ENABLE_INPROCESS */ } else { if (--eepr_state.repeat) { eepr_state.timer = 1; /* retry Sending */ } else { EEPR_StateFailed(EEPR_WRITEFAILED); } break; } } else if (eepr_state.substate == 1) { /* check Status Register of EEPROM (RSR) */ ret_val = EEPR_ReceiveData((uint8_t*)(&tmp_eepr_stat), 1); if (ret_val != EEPR_OK) { if (--eepr_state.repeat) { /* no data available */ eepr_state.timer = 1; /* retry Receiving */ } else { EEPR_StateFailed(EEPR_WRITEFAILED); } break; } /* response received */ if (!tmp_eepr_stat.B.nRDY) { /* /RDY-Flag is cleared -> EEPROM is not busy (write cycle not in process) */ eepr_state.RSR = tmp_eepr_stat; /* overtake status information */ /* initialization succeeded */ if (eepr_state.RSR.B.WEN) { /* Write-Enable (WEN) has been accepted !*/ eepr_state.state = EEPR_WRITEMEMORY_ENABLED; break; } } /* Write Not Enabled OR EEPROM is busy */ /* retry Write Enabling */ if (--eepr_state.repeat) { eepr_state.state = EEPR_WRITEMEMORY; /* retry reading of EEPROM */ eepr_state.timer = 5; } else { EEPR_StateFailed(EEPR_WRITEFAILED); } } break; case EEPR_WRITEMEMORY_ENABLED: if (eepr_state.page_nr == 1) { eepr_state.write_len = eepr_state.write_len - (EEPR_PageLength - (eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength)); } if (eepr_state.page_nr > 1) { eepr_state.write_len = eepr_state.write_len - EEPR_PageLength; } if (eepr_state.page_nr == 0) { if (eepr_state.write_len > (EEPR_PageLength - (eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength))) { eepr_state.currentpagelength = EEPR_PageLength - (eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength); } else { eepr_state.currentpagelength = eepr_state.write_len; } ret_val = EEPR_WriteMemory(eepr_state.eepromaddress1, (uint8_t*)((uint32_t)(&eepr_WR_RD_buffer)+eepr_ch_cfg[eepr_state.currentchannel].length - eepr_state.write_len), eepr_state.currentpagelength); /* calculation of srcptr: startaddress+(totalwrtlngth - yet to read length) */ } else { if (eepr_state.write_len > EEPR_PageLength) { eepr_state.currentpagelength = EEPR_PageLength; } else { eepr_state.currentpagelength = eepr_state.write_len; } ret_val = EEPR_WriteMemory(eepr_state.eepromaddress2, (uint8_t*)((uint32_t)(&eepr_WR_RD_buffer) + eepr_ch_cfg[eepr_state.currentchannel].length - eepr_state.write_len), eepr_state.currentpagelength); /* calculation of srcptr: startaddress+(totalwrtlngth - yet to read length) */ } if (ret_val != EEPR_OK) { if (--eepr_state.repeat) { eepr_state.timer = 2; /* retry Start Command of EEPROM Write */ } else { EEPR_StateFailed(EEPR_WRITEFAILED); } } else { eepr_state.timer = 10; /* max time: 10ms/EEPR_PageLength-byte page todo: timer: unterschiedlich neu/alt */ eepr_state.state = EEPR_WRITEMEMORY_INPROCESS; } break; case EEPR_WRITEMEMORY_INPROCESS: ret_val = EEPR_ReceiveData(&eepr_WR_RD_buffer[eepr_ch_cfg[eepr_state.currentchannel].length - eepr_state.write_len], eepr_state.currentpagelength); if (ret_val == EEPR_OK) { if (++eepr_state.page_nr < eepr_state.nr_of_pages) { if (eepr_state.page_nr != 1) { eepr_state.eepromaddress2 += EEPR_PageLength; } eepr_state.state = EEPR_WRITEMEMORY; /* write next page */ eepr_state.repeat = 2; } else { eepr_state.eepromaddress2 = eepr_state.eepromaddress1 + EEPR_PageLength - (eepr_ch_cfg[eepr_state.currentchannel].eepromaddress % EEPR_PageLength); /*now, do verify*/ EEPR_ReEnterStateInit(); eepr_state.state = EEPR_READMEMORY; } } else { EEPR_StateFailed(EEPR_WRITEFAILED); } /* note: automatically write disable state at the completion of a write cycle ! */ /* make verify/checksum test ? */ break; case EEPR_INITFAILED: if (eepr_state.substate == 0) { (void)(DIAG_Handler(DIAG_CH_CALIB_EEPR_FAILURE, DIAG_EVENT_NOK, 2, NULL)); EEPR_ReEnterStateInit(); eepr_state.substate = 1; } break; case EEPR_READFAILED: if (eepr_state.substate == 0) { eepr_ch_cfg[eepr_state.currentchannel].errorflag = EEPR_ERR_RD; (void)(DIAG_Handler(DIAG_CH_CALIB_EEPR_FAILURE, DIAG_EVENT_NOK, 1, NULL)); IO_WritePin(IO_PIN_MCU_0_TO_FPGA_INTERFACE_SPI_NSS, IO_PIN_SET); EEPR_ReEnterStateInit(); eepr_state.substate = 1; } break; case EEPR_WRITEFAILED: if (eepr_state.substate == 0) { eepr_ch_cfg[eepr_state.currentchannel].errorflag = EEPR_ERR_WR; (void)(DIAG_Handler(DIAG_CH_CALIB_EEPR_FAILURE, DIAG_EVENT_NOK, 0, NULL)); EEPR_ReEnterStateInit(); eepr_state.substate = 1; } break; case EEPR_PROTECTION_FAILED: /* todo */ if (eepr_state.substate == 0) { EEPR_ReEnterStateInit(); } break; default: break; } eepr_state.triggerentry--; } /*==================INTERFACE FUNCTIONS===================*/ void EEPR_delete_bkpsrambuffer(EEPR_CHANNEL_ID_TYPE_e eepr_channel) { uint16_t counter; for (counter = 0; counter < eepr_ch_cfg[eepr_channel].length; counter++) { eepr_bkpsram_buffer[counter] = 0xFF; } } /** * @brief copys the data of one channel from bkpsram into the eeprom * * @param eepr_channel the channel that will be copied * @return 0 if everything worked correctly, error bit if something failed */ EEPR_ERRORTYPES_e EEPR_BackupChannelData2Eepr(EEPR_CHANNEL_ID_TYPE_e eepr_channel) { uint8_t*dataptr = eepr_ch_cfg[eepr_channel].bkpsramptr; EEPR_ERRORTYPES_e retval = EEPR_NO_ERROR; timeout_cnt = 0; uint16_t maxtime = EEPR_GetChWriteTime(eepr_channel); /* @FIXME check dataptr== NULL_PTR */ if (EEPR_SetStateRequest(EEPR_WRITEMEMORY, eepr_channel, dataptr) == EEPR_OK) { EEPR_Trigger(); while (EEPR_GetState() != EEPR_IDLE) { if (timeout_cnt > maxtime) { retval |= EEPR_ERR_WR; /* possible reasons: SPI busy, eeprom hardware in busy state or defect */ break; } timeout_cnt++; EEPR_Trigger(); OS_taskDelay(1); /* wait 1ms for next call of eeprom trigger */ } } else { retval = EEPR_ERR_WR; } if (retval == EEPR_NO_ERROR) { EEPR_RemoveChDirtyFlag(eepr_channel); } return retval; } /** * @brief copys the data of one channel from eeprom into the bkpsrams * * @param eepr_channel the channel that will be copied * @return 0 if everything worked correctly, error bit if something failed */ EEPR_ERRORTYPES_e EEPR_ReadChannelData(EEPR_CHANNEL_ID_TYPE_e eepr_channel) { timeout_cnt = 0; EEPR_ERRORTYPES_e retval = EEPR_NO_ERROR; uint8_t*dataptr = eepr_ch_cfg[eepr_channel].bkpsramptr; uint16_t maxtime = EEPR_GetChReadTime(eepr_channel); /* @FIXME check dataptr== NULL_PTR */ if (EEPR_SetStateRequest(EEPR_READMEMORY, eepr_channel, dataptr) == EEPR_OK) { EEPR_Trigger(); while (EEPR_GetState() != EEPR_IDLE) { if (timeout_cnt > maxtime) { retval = EEPR_ERR_RD; /* possible reasons: SPI busy, eeprom hardware in busy state or defect */ break; } timeout_cnt++; EEPR_Trigger(); OS_taskDelay(1); /* wait 1ms for next call of eeprom trigger */ } } else { retval = EEPR_ERR_RD; } if (retval == EEPR_NO_ERROR) { EEPR_RemoveChDirtyFlag(eepr_channel); } return retval; } /** * @brief handles the data exchange between eeprom and bkpsram * checks if the bkpsram data are valid. * If so, and a dirty flag is set, the function saves the data into eeprom * If not, the function recovers the BKPSRAM data backed up from the eeprom * * @param eepr_channel pointer where the channel data are stored * @return none */ EEPR_ERRORTYPES_e EEPR_RefreshChannelData(EEPR_CHANNEL_ID_TYPE_e eepr_channel) { EEPR_ERRORTYPES_e retval = 0; uint8_t*dataptr = eepr_ch_cfg[eepr_channel].bkpsramptr; uint16_t byte_len = eepr_ch_cfg[eepr_channel].length; /* if no RAM pointer defined in channel, use a temporary buffer */ if (dataptr == NULL_PTR) { dataptr = eepr_bkpsram_buffer; } /* verify the checksum of the RAM or Backup-SRAM instance */ if (EEPR_CalcChecksum(dataptr, byte_len - 4) == *((uint32_t*)(dataptr + byte_len - 4))) { /* checksum ok, if dirty flag is set actualize eeprom data (copy channel data RAM -> eeprom) */ if (eepr_ch_dirtyflag[eepr_channel] == 0) { retval = EEPR_BackupChannelData2Eepr(eepr_channel); } } else { /* checksum corrupt, recover RAM instance by eeprom data (copy channel data eeprom -> RAM or BKPSRAM) */ retval = EEPR_ReadChannelData(eepr_channel); } if (dataptr == eepr_bkpsram_buffer) { /* clear temporary buffer for next usage (invalidate checksum) */ EEPR_delete_bkpsrambuffer(eepr_channel); } return retval; } EEPR_ERRORTYPES_e EEPR_Init(void) { timeout_cnt = 0; EEPR_ERRORTYPES_e retval; retval = EEPR_NO_ERROR; uint16_t maxtime = EEPR_WRITETIME_PER_PAGE; if (EEPR_SetStateRequest(EEPR_IDLE, 0, 0) == EEPR_OK) { while (EEPR_GetState() != EEPR_IDLE) { if (timeout_cnt > maxtime) { /* timeout: 50ms (normal needed time: 5ms) */ /* eeprom not usable, no eeprom data available */ retval = EEPR_INIT_ERROR; /* possible reasons: SPI busy, eeprom hardware in busy state or defect */ break; } timeout_cnt++; EEPR_Trigger(); OS_taskDelay(1); /* wait 1ms for next call of eeprom trigger */ } } if (retval == EEPR_NO_ERROR) { /* initialization successful */ /* intialize flags */ for (cnt = 0; cnt < eepr_nr_of_channels; cnt++) { EEPR_RemoveChReadReqFlag(cnt); } retval = EEPR_InitChannelData(); /* do update channel data */ } else { EEPR_SetDefaultValue(EEPR_CH_HEADER); EEPR_SetDefaultValue(EEPR_CH_BOARD_INFO); } return retval; } EEPR_ERRORTYPES_e EEPR_InitChannelData(void) { EEPR_ERRORTYPES_e retval = EEPR_NO_ERROR; EEPR_ERRORTYPES_e errtype = EEPR_NO_ERROR; /* Read eeprom header check data format */ errtype = EEPR_ReadChannelData(EEPR_CH_HEADER); if (errtype == EEPR_NO_ERROR) { EEPR_FormatCheck(); /* handles data transfer (update) in case of new eeprom driver version with different data format */ } else { /* try to read a second time */ errtype = EEPR_ReadChannelData(EEPR_CH_HEADER); if (errtype == EEPR_NO_ERROR) { EEPR_FormatCheck(); /* handles data transfer (update) in case of new eeprom driver version with different data format */ } else { /* seems to be the very first time of eeprom initialization */ EEPR_SetDefaultValue(EEPR_CH_HEADER); errtype = EEPR_BackupChannelData2Eepr(EEPR_CH_HEADER); if (errtype != EEPR_NO_ERROR) { /* try to write a second time */ EEPR_SetDefaultValue(EEPR_CH_HEADER); errtype = EEPR_BackupChannelData2Eepr(EEPR_CH_HEADER); } return errtype; } } /* Read board and device info */ errtype = EEPR_ReadChannelData(EEPR_CH_BOARD_INFO); if (errtype != EEPR_NO_ERROR) { /* try to read a second time */ errtype = EEPR_ReadChannelData(EEPR_CH_BOARD_INFO); if (errtype != EEPR_NO_ERROR) { /* when reading of board info fails */ EEPR_SetDefaultValue(EEPR_CH_BOARD_INFO); #if 0 /* @FIXME do not overwrite board info forever if somehow reading fails one time !!! */ errtype = EEPR_BackupChannelData2Eepr(EEPR_CH_BOARD_INFO); if (errtype != EEPR_NO_ERROR) { /* try to write a second time */ EEPR_SetDefaultValue(EEPR_CH_BOARD_INFO); errtype = EEPR_BackupChannelData2Eepr(EEPR_CH_BOARD_INFO); } #endif } } /* Reset error because EEPR_Header is separate section in EEPROM */ errtype = EEPR_NO_ERROR; if (RTC_NVMRAM_DATAVALID_VARIABLE == 0) { /* NVM data corrupt, so set all the dirty flags and take backup (if valid) or default values */ uint8_t cnt; /* counter variable */ for (cnt = 0; cnt < eepr_nr_of_channels; cnt++) { EEPR_SetChDirtyFlag(cnt); } errtype |= EEPR_ReadChannelData(EEPR_CH_NVSOC); retval |= errtype; if (errtype != EEPR_NO_ERROR) { errtype = EEPR_NO_ERROR; EEPR_SetDefaultValue(EEPR_CH_NVSOC); } errtype |= EEPR_ReadChannelData(EEPR_CH_CONTACTOR); retval |= errtype; if (errtype != EEPR_NO_ERROR) { errtype = EEPR_NO_ERROR; EEPR_SetDefaultValue(EEPR_CH_CONTACTOR); } errtype |= EEPR_ReadChannelData(EEPR_CH_OPERATING_HOURS); retval |= errtype; if (errtype != EEPR_NO_ERROR) { errtype = EEPR_NO_ERROR; EEPR_SetDefaultValue(EEPR_CH_OPERATING_HOURS); } RTC_NVMRAM_DATAVALID_VARIABLE = 1; /* validate NVNRAM data */ } else { /* @FIXME do set dirty flags for not double buffered channel (not in bkpsram) unless the ram is not cleared (warm reset) */ errtype |= EEPR_RefreshChannelData(EEPR_CH_NVSOC); retval |= errtype; if (errtype == EEPR_ERR_RD || errtype == (EEPR_ERR_RD | EEPR_ERR_WR)) { /* read error can only occur if checksum of bkpsram channel is corrupt -> set default values */ /* ignore possible write error because we definitely want to try writing to EEPROM */ errtype = EEPR_NO_ERROR; EEPR_SetDefaultValue(EEPR_CH_NVSOC); } errtype |= EEPR_RefreshChannelData(EEPR_CH_CONTACTOR); retval |= errtype; if (errtype == EEPR_ERR_RD || errtype == (EEPR_ERR_RD | EEPR_ERR_WR)) { /* read error can only occur if checksum of bkpsram channel is corrupt -> set default values */ /* ignore possible write error because we definitely want to try writing to EEPROM */ errtype = EEPR_NO_ERROR; EEPR_SetDefaultValue(EEPR_CH_CONTACTOR); } errtype |= EEPR_RefreshChannelData(EEPR_CH_OPERATING_HOURS); retval |= errtype; if (errtype == EEPR_ERR_RD || errtype == (EEPR_ERR_RD | EEPR_ERR_WR)) { /* read error can only occur if checksum of bkpsram channel is corrupt -> set default values */ /* ignore possible write error because we definitely want to try writing to EEPROM */ errtype = EEPR_NO_ERROR; EEPR_SetDefaultValue(EEPR_CH_OPERATING_HOURS); } } return retval; } EEPR_RETURNTYPE_e EEPR_GetChannelData(EEPR_CHANNEL_ID_TYPE_e eepr_channel, uint8_t *dest_ptr) { EEPR_RETURNTYPE_e ret_val = EEPR_OK; uint8_t *dataptr; dataptr = dest_ptr; if (dataptr == NULL_PTR) { if (dest_ptr != NULL_PTR) { dataptr = eepr_ch_cfg[eepr_channel].bkpsramptr; } else { ret_val = EEPR_ERROR; } } if (ret_val == EEPR_OK) { ret_val = EEPR_SetStateRequest(EEPR_READMEMORY, eepr_channel, dataptr); } return ret_val; } EEPR_RETURNTYPE_e EEPR_SetChannelData(EEPR_CHANNEL_ID_TYPE_e eepr_channel, uint8_t *src_ptr) { EEPR_RETURNTYPE_e ret_val; uint8_t *dataptr; dataptr = src_ptr; uint16_t byte_len = eepr_ch_cfg[eepr_channel].length; if (dataptr == NULL_PTR) { dataptr = eepr_ch_cfg[eepr_channel].bkpsramptr; } /* checksumtest */ if (EEPR_CalcChecksum(dataptr, byte_len - 4) == *((uint32_t*)(dataptr + byte_len - 4))) { ret_val = EEPR_SetStateRequest(EEPR_WRITEMEMORY, eepr_channel, dataptr); } else { ret_val = EEPR_ERROR; } if (ret_val == EEPR_OK) { EEPR_RemoveChDirtyFlag(eepr_channel); } return ret_val; } STD_RETURN_TYPE_e EEPR_CheckDirtyFlags() { STD_RETURN_TYPE_e ret_val = 0; cnt = 0; for (cnt = 0; cnt < (eepr_nr_of_channels); cnt++) { if (eepr_ch_dirtyflag[cnt] == 0) { ret_val = 1; } } return ret_val; } uint8_t EEPR_GetNextReadReq() { uint8_t ret_val = 0xFF; uint8_t channel; cnt = 0; for (cnt = 0; cnt < (eepr_nr_of_channels + 1); cnt++) { channel = (cnt + lastReadChannel + 1)%eepr_nr_of_channels; if (eepr_ch_read_req_flag[channel] == 0) { lastReadChannel = channel; ret_val = channel; break; } } return ret_val; } uint8_t EEPR_GetNextDirtyChannel() { uint8_t ret_val = 0xFF; uint8_t channel; cnt = 0; for (cnt = 0; cnt < (eepr_nr_of_channels + 1); cnt++) { channel = (cnt + lastDirtyChannel + 1)%eepr_nr_of_channels; if (eepr_ch_dirtyflag[channel] == 0) { lastDirtyChannel = channel; ret_val = channel; break; } } return ret_val; } void EEPR_DataHandler() { uint16_t length = 0xFFFF; uint16_t chksum = 0xFFFF; uint16_t i = 0; /* check, if eeprom is busy */ if (!EEPR_IsInFinalState()) { return; } switch (data_handler.state) { case EEPR_STARTDIRTYCHECK: /* Read requests have priority */ data_handler.dirtyChannel = EEPR_GetNextReadReq(); if (data_handler.dirtyChannel == 0xFF) { /* nothing to read */ } else { /* there is at least one channel to update */ data_handler.repeat = 2; data_handler.state = EEPR_READREQUEST; EEPR_ch_dataerrors[data_handler.dirtyChannel] = EEPR_DAT_IDLE; eepr_ch_cfg[data_handler.dirtyChannel].accessprotection = EEPR_ACCESS_PROTECTED; return; } data_handler.dirtyChannel = EEPR_GetNextDirtyChannel(); if (data_handler.dirtyChannel == 0xFF) { /* nothing to update */ return; } else { /* there is at least one channel to update */ data_handler.repeat = 2; data_handler.state = EEPR_DATABACKUP; EEPR_ch_dataerrors[data_handler.dirtyChannel] = EEPR_DAT_IDLE; eepr_ch_cfg[data_handler.dirtyChannel].accessprotection = EEPR_ACCESS_PROTECTED; return; } break; case EEPR_DATABACKUP: /* first, delete old buffer */ for (i = 0; i < EEPR_CH_MAXLENGTH; i++) { eepr_backupbuffer[i] = 0xFF; } /* safe EEPROM-Data to Backupbuffer */ /* todo: check if request was accepted */ EEPR_GetChannelData(data_handler.dirtyChannel, (uint8_t*) &eepr_backupbuffer); data_handler.state = EEPR_CHECKBACKUP; break; case EEPR_CHECKBACKUP: /* check if safed eeprom data are valid */ length = eepr_ch_cfg[data_handler.dirtyChannel].length; chksum = *(uint16_t*)(&eepr_backupbuffer[length-4]); if (chksum != EEPR_CalcChecksum(eepr_backupbuffer, length - 4)) { /* checksum corrupt */ if (--data_handler.repeat != 0) { /* retry saving data */ data_handler.state = EEPR_DATABACKUP; } else { /* backup error */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_EEPROM_ERROR; data_handler.repeat = 2; data_handler.state = EEPR_WRITEEEPROM; } } else { data_handler.repeat = 2; data_handler.state = EEPR_WRITEEEPROM; } break; case EEPR_WRITEEEPROM: /* write new data into eeprom */ byte_len = eepr_ch_cfg[data_handler.dirtyChannel].length; if (EEPR_CalcChecksum(eepr_ch_cfg[data_handler.dirtyChannel].bkpsramptr, byte_len - 4) == *((uint32_t*)(eepr_ch_cfg[data_handler.dirtyChannel].bkpsramptr + byte_len - 4))) { /* checksum ok */ if (EEPR_SetChannelData(data_handler.dirtyChannel, NULL_PTR) != EEPR_OK) { /* eeprom is busy, try again or restart if already repeated. */ if (--data_handler.repeat == 0) { EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_EEPROM_ERROR; data_handler.repeat = 2; data_handler.state = EEPR_STARTDIRTYCHECK; } } else { data_handler.state = EEPR_CHECKEEPROM; } } else { /* Checksum of new data corrupt, use backup */ length = eepr_ch_cfg[data_handler.dirtyChannel].length; chksum = *(uint16_t*)(&eepr_backupbuffer[length-4]); if (chksum != EEPR_CalcChecksum(eepr_backupbuffer, length - 4)) { /* checksum of backed up data corrupt, try to read eeprom directly into ram */ EEPR_GetChannelData(data_handler.dirtyChannel, NULL_PTR); data_handler.repeat = 2; data_handler.state = EEPR_RECOVERYCHECK; } else { /* backed up data valid */ for (i = 0; i < eepr_ch_cfg[data_handler.dirtyChannel].length; i++) { *(eepr_ch_cfg[data_handler.dirtyChannel].bkpsramptr+i) = (uint8_t) eepr_backupbuffer[i]; } /* data are restored, handle next channel */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_RAM_ERROR; eepr_ch_cfg[data_handler.dirtyChannel].accessprotection = EEPR_ACCESS_UNPROTECTED; data_handler.repeat = 2; data_handler.state = EEPR_STARTDIRTYCHECK; } } break; case EEPR_CHECKEEPROM: if (eepr_ch_cfg[data_handler.dirtyChannel].errorflag == EEPR_ERR_WR || eepr_ch_cfg[data_handler.dirtyChannel].errorflag == EEPR_ERR_RD) { /* writing into eeprom unsuccessful */ length = eepr_ch_cfg[data_handler.dirtyChannel].length; chksum = *((uint32_t*)(eepr_ch_cfg[data_handler.dirtyChannel].bkpsramptr + length - 4)); if (chksum == EEPR_CalcChecksum(eepr_ch_cfg[data_handler.dirtyChannel].bkpsramptr, length - 4)) { /* new data are still valid */ if (--data_handler.repeat != 0) { /* eeprom error, retry writing into eeprom */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_EEPROM_ERROR; data_handler.state = EEPR_WRITEEEPROM; } else { /* eeprom error, ram data are valid. */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_EEPROM_ERROR; eepr_ch_cfg[data_handler.dirtyChannel].accessprotection = EEPR_ACCESS_UNPROTECTED; data_handler.repeat = 2; data_handler.state = EEPR_STARTDIRTYCHECK; } } else { /* new data and eeprom data are corrupt */ /* use backed up data to restore */ length = eepr_ch_cfg[data_handler.dirtyChannel].length; chksum = *(uint16_t*)(&eepr_backupbuffer[length-4]); if (chksum != EEPR_CalcChecksum(eepr_backupbuffer, length - 4)) { /* fatal error, all data are corrupt */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_FATAL_ERROR; eepr_ch_cfg[data_handler.dirtyChannel].accessprotection = EEPR_ACCESS_UNPROTECTED; data_handler.state = EEPR_STARTDIRTYCHECK; } else { /* backed up data are valid */ for (i = 0; i < eepr_ch_cfg[data_handler.dirtyChannel].length; i++) { *(eepr_ch_cfg[data_handler.dirtyChannel].bkpsramptr+i) = (uint8_t) eepr_backupbuffer[i]; } if (--data_handler.repeat != 0) { /* retry writing into eeprom */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_EEPROM_ERROR; data_handler.state = EEPR_WRITEEEPROM; } else { /* eeprom error */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_EEPROM_ERROR; eepr_ch_cfg[data_handler.dirtyChannel].accessprotection = EEPR_ACCESS_UNPROTECTED; data_handler.state = EEPR_STARTDIRTYCHECK; } } } } else { /* Idle, everything worked */ EEPR_ch_dataerrors[data_handler.dirtyChannel] = EEPR_DAT_SUCCESS; eepr_ch_cfg[data_handler.dirtyChannel].accessprotection = EEPR_ACCESS_UNPROTECTED; EEPR_RemoveChDirtyFlag(data_handler.dirtyChannel); data_handler.state = EEPR_STARTDIRTYCHECK; } break; case EEPR_RECOVERYCHECK: length = eepr_ch_cfg[data_handler.dirtyChannel].length; chksum = *(uint16_t*)((uint8_t*)eepr_ch_cfg[data_handler.dirtyChannel].bkpsramptr + length -4); if (chksum != EEPR_CalcChecksum(eepr_ch_cfg[data_handler.dirtyChannel].bkpsramptr, length - 4)) { /* recovery failed, fatal error */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_FATAL_ERROR; eepr_ch_cfg[data_handler.dirtyChannel].accessprotection = EEPR_ACCESS_UNPROTECTED; data_handler.state = EEPR_STARTDIRTYCHECK; } else { /* recovery successful */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_RAM_ERROR; EEPR_RemoveChDirtyFlag(data_handler.dirtyChannel); eepr_ch_cfg[data_handler.dirtyChannel].accessprotection = EEPR_ACCESS_UNPROTECTED; data_handler.state = EEPR_STARTDIRTYCHECK; } break; case EEPR_READREQUEST: if (EEPR_GetChannelData(data_handler.dirtyChannel, (uint8_t*) &eepr_backupbuffer) == EEPR_OK) { /* request was accepted */ data_handler.state = EEPR_READCHECK; } else { if (--data_handler.repeat != 0) { /* do nothing, try again */ } else { /* eeprom error */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_EEPROM_ERROR; data_handler.state = EEPR_STARTDIRTYCHECK; } } break; case EEPR_READCHECK: if (eepr_ch_cfg[data_handler.dirtyChannel].errorflag == EEPR_ERR_RD) { /* Reading was unsuccessful */ if (--data_handler.repeat != 0) { /* try to read again */ data_handler.state = EEPR_READREQUEST; } else { /* eeprom error */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_EEPROM_ERROR; data_handler.state = EEPR_STARTDIRTYCHECK; } } else { /* check if safed eeprom data are valid */ length = eepr_ch_cfg[data_handler.dirtyChannel].length; chksum = *(uint16_t*)(&eepr_backupbuffer[length-4]); if (chksum != EEPR_CalcChecksum(eepr_backupbuffer, length - 4)) { /* checksum corrupt */ if (--data_handler.repeat != 0) { /* retry reading data */ data_handler.state = EEPR_READREQUEST; } else { /* backup error */ EEPR_ch_dataerrors[data_handler.dirtyChannel] |= EEPR_DAT_EEPROM_ERROR; data_handler.repeat = 2; data_handler.state = EEPR_STARTDIRTYCHECK; } } else { /* reading was successful, overtake data and start cycle from beginning */ for (i = 0; i < eepr_ch_cfg[data_handler.dirtyChannel].length; i++) { *(eepr_ch_cfg[data_handler.dirtyChannel].bkpsramptr+i) = (uint8_t) eepr_backupbuffer[i]; } data_handler.repeat = 2; EEPR_ch_dataerrors[data_handler.dirtyChannel] = EEPR_DAT_SUCCESS; EEPR_RemoveChReadReqFlag(data_handler.dirtyChannel); data_handler.state = EEPR_STARTDIRTYCHECK; } } break; default: break; } return; }
tonyhuang84/foxbms
embedded-software/mcu-secondary/src/engine/config/enginetask_cfg.h
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file enginetask_cfg.h * @author foxB<NAME> * @date 26.08.2015 (date of creation) * @ingroup ENGINE_CONF * @prefix ENG * * @brief Engine task configuration header * */ #ifndef ENGINETASK_CFG_H_ #define ENGINETASK_CFG_H_ /*================== Includes =============================================*/ #include "general.h" #include "os.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ /** * @brief Task configuration of the 1ms engine task * * @details Predefined 1ms task for 1ms cyclic engine task * * @ingroup API_OS */ extern OS_Task_Definition_s eng_tskdef_cyclic_1ms; /** * @brief Task configuration of the 10ms engine task * * @details Predefined 10ms task for 10ms cyclic engine task * * @ingroup API_OS */ extern OS_Task_Definition_s eng_tskdef_cyclic_10ms; /** * @brief Task configuration of the 100ms engine task * * @details Predefined 100ms task for 100ms cyclic engine task * * @ingroup API_OS */ extern OS_Task_Definition_s eng_tskdef_cyclic_100ms; extern OS_Task_Definition_s eng_tskdef_eventhandler; extern OS_Task_Definition_s eng_tskdef_diagnosis; /*================== Function Prototypes ==================================*/ /** * @brief Initializes modules that were not initialized before scheduler * starts * * @details This function is called after the scheduler started but before any * cyclic task runs. Here modules get initialized that are not used * during the startup process. */ extern void ENG_Init(void); /** * @brief reads non-volatile memory and initializes the sys module * * Start up after scheduler start, called from 1ms-Task before the 1ms cyclic execution */ extern void ENG_PostOSInit(void); /** * @brief Cyclic 1ms task for the LTC measurement */ extern void ENG_Cyclic_1ms(void); /** * @brief Task for system- and bmscontrol and SOX algorithms * */ extern void ENG_Cyclic_10ms(void); /** * @brief Task for ADC control, balancing control and isolation * measurement * */ extern void ENG_Cyclic_100ms(void); /** * @brief OS_IdleTask, called by vApplicationIdleHook() */ extern void ENG_IdleTask(void); /** * @brief Engine Task for handling of events * */ extern void ENG_EventHandler(void); /** * @brief Engine Task for diagnosis * */ extern void ENG_Diagnosis(void); /** * @brief Database-Task * @details The task manages the data exchange with the database and must have a * higher task priority than any task using the database. * */ extern void ENG_TSK_Engine(void); /*================== Function Implementations =============================*/ #endif /* ENGINETASK_CFG_H_ */
tonyhuang84/foxbms
embedded-software/mcu-common/src/driver/adc/adc.h
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file adc.h * @author foxBMS Team * @date 26.08.2015 (date of creation) * @ingroup DRIVERS * @prefix ADC * * @brief Header for the driver for the analog to digital converter * * This adc module provides support for analog/digital conversion. * It must be initialized during startup. * */ #ifndef ADC_H_ #define ADC_H_ /*================== Includes =============================================*/ #include "adc_cfg.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ /*================== Function Prototypes ==================================*/ /** * @brief initializes the different ADC devices by enabling their * corresponding clocks. It is called during startup. * * @param AdcHandle: pointer to ADC hardware handle */ extern void ADC_Init(ADC_HandleTypeDef *AdcHandle); /** * starts the ADC conversion. * * @param AdcHandle: pointer to ADC hardware handle */ extern void ADC_Convert(ADC_HandleTypeDef *AdcHandle); /** * @brief determines which kind of measurements are made by the ADCs and stores result in database. * * It alternates between measurement of the voltage of the backup battery * and the voltage of the internal temperature sensor. * It starts the conversion with ADC_Convert(). * If the conversion is completed, the result is stored in the database. */ extern void ADC_Ctrl(void); /** * @brief callback function to the ADC conversion. * * It is called automatically when an ADC conversion is complete. * Before getting the converted value, it stops the ADC with HAL_ADC_Stop_IT(). * Then it gets the converted raw value with HAL_ADC_GetValue(). * The raw value is then scaled. * * @param AdcHandle: pointer to ADC hardware handle */ extern void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* AdcHandle); /** * @brief get coin cell battery voltage */ extern float ADC_GetVBAT_mV(void); /** * @brief get MCU temperature */ extern float ADC_GetMCUTemp_C(void); /** * @brief get voltage in mV */ extern uint16_t ADC_GetValue(uint32_t value); /*================== Function Implementations =============================*/ #endif /* ADC_H_ */
tonyhuang84/foxbms
embedded-software/mcu-primary/src/driver/timer/timer.h
<reponame>tonyhuang84/foxbms /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file timer.h * @author foxBMS Team * @date 30.09.2015 (date of creation) * @ingroup DRIVERS * @prefix TIM * * @brief Headers for the driver to enable/disable/change the peripheral timers * * Header file to enable/disable/change peripheral timers. */ #ifndef TIMER_H_ #define TIMER_H_ /*================== Includes =============================================*/ #include "timer_cfg.h" /*================== Macros and Definitions ===============================*/ /** * timer return types */ typedef enum { DIAG_TIM_OK = 0, /*!< error not occured or occured but threshold not reached */ DIAG_TIM_ERROR = 1, /*!< error occured */ DIAG_TIM_OVERFLOW = 2, /*!< timer overflow occured */ DIAG_TIM_NO_NEW_VAL = 3, /*!< no new value captured */ } TIM_RETURNTYPE_e; /** * struct to store PWM input capture data * struct is according to IsoGuard driver */ typedef struct { uint32_t ActiveTime; /*!< To store ActiveTime for GetDutyCycles API. */ uint32_t PeriodTime; /*!< To store PeriodTime for GetDutyCycles API. */ } TIM_DutyCycleType_s; /*================== Constant and Variable Definitions ====================*/ /*================== Function Prototypes ==================================*/ /** * @brief Interface function to enable the pwm output and pwm input caputure timers */ extern void TIM_Init(void); /** * @brief Initalizes the pwm output timer (timer4) */ extern void TIM_PWM_OUT_Init(void); /** * @brief Initalizes the pwm input capture timer (timer9) */ extern void TIM_PWM_IC_Init(void); /** * @brief Initializes cyclic timer interrupt */ extern void TIM_CyclicInterrupt_Init(void); /** * @brief Sets the pwm output timer frequency * * @param htim: pointer to timer handle struct * @param frequency: frequency in Hz */ extern void TIM_PWM_SetFrequency(TIM_HandleTypeDef *htim, uint32_t frequency); /** * @brief sets the timer output pwm dutycycle * * @param htim: pointer to timer handle struct * @param dutycycle: dutycycle in percentage (0-100) */ extern void TIM_PWM_SetDutycycle(TIM_HandleTypeDef *htim, uint8_t dutycycle); /** * @brief Interface function for start of input capture measurement */ extern void TIM_Start_PWM_IC_Measurement(TIM_HandleTypeDef *htim); /** * @brief Interface function for start of pwm output */ extern void TIM_Start_PWM_Out(TIM_HandleTypeDef *htim); /** * @brief Gets duty cycle data of PWM-measurement * Interface function for IsoGuard-Driver * * @param htim: handle pointer to timer * @param DutyCycleData: pointer where duty cycle data is stored * * @return E_OK if duty cycle data is valid, E_NOT_OK if duty cycle data is invalid */ extern TIM_RETURNTYPE_e TIM_GetDutycycle(TIM_HandleTypeDef *htim, TIM_DutyCycleType_s* DutyCycleData); /** * @brief Interrupt Handler for the timer interrupt */ extern void TIM_IRQHandler(void); /*================== Function Implementations =============================*/ #endif /* TIMER_H_ */
tonyhuang84/foxbms
embedded-software/mcu-common/src/driver/can/can.h
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file can.h * @author foxBMS Team * @date 12.07.2015 (date of creation) * @ingroup DRIVERS * @prefix CAN * * @brief Header for the driver for the CAN module * * Provides the interfaces for initialization, receive * and transmit handling * */ #ifndef CAN_H_ #define CAN_H_ /*================== Includes =============================================*/ #include "can_cfg.h" /*================== Macros and Definitions ===============================*/ #define CAN0_USE_TX_BUFFER CAN0_USE_TRANSMIT_BUFFER #define CAN0_USE_RX_BUFFER CAN0_USE_RECEIVE_BUFFER #define CAN0_TX_BUFFER_LENGTH CAN0_TRANSMIT_BUFFER_LENGTH #define CAN0_RX_BUFFER_LENGTH CAN0_RECEIVE_BUFFER_LENGTH #define CAN1_USE_TX_BUFFER CAN1_USE_TRANSMIT_BUFFER #define CAN1_USE_RX_BUFFER CAN1_USE_RECEIVE_BUFFER #define CAN1_TX_BUFFER_LENGTH CAN1_TRANSMIT_BUFFER_LENGTH #define CAN1_RX_BUFFER_LENGTH CAN1_RECEIVE_BUFFER_LENGTH typedef enum { CAN_ERROR_NONE = HAL_CAN_ERROR_NONE, /*!< No error */ CAN_ERROR_EWG = HAL_CAN_ERROR_EWG, /*!< EWG error */ CAN_ERROR_EPV = HAL_CAN_ERROR_EPV, /*!< EPV error */ CAN_ERROR_BOF = HAL_CAN_ERROR_BOF, /*!< BOF error */ CAN_ERROR_STF = HAL_CAN_ERROR_STF, /*!< Stuff error */ CAN_ERROR_FOR = HAL_CAN_ERROR_FOR, /*!< Form error */ CAN_ERROR_ACK = HAL_CAN_ERROR_ACK, /*!< Acknowledgment error */ CAN_ERROR_BR = HAL_CAN_ERROR_BR, /*!< Bit recessive */ CAN_ERROR_BD = HAL_CAN_ERROR_BD, /*!< LEC dominant */ CAN_ERROR_CRC = HAL_CAN_ERROR_CRC, /*!< LEC transfer error */ } CAN_ErrorTypeDef_e; typedef enum { CAN_NODE1 = 0, /* CAN1 */ CAN_NODE0 = 1, /* CAN0 */ } CAN_NodeTypeDef_e; typedef struct CAN_ERROR { CAN_ErrorTypeDef_e canError; uint16_t canErrorCounter[10 - 1]; /* One slot for every error from HAL_CAN_ErrorTypeDef; */ /* No space for NoError */ } CAN_ERROR_s; typedef struct CAN_RX_BUFFERELEMENT { uint32_t ID; uint8_t DLC; uint8_t RTR; uint8_t Data[8]; uint8_t newMsg; } CAN_RX_BUFFERELEMENT_s; typedef struct CAN_RX_BUFFER { uint8_t ptrRead; uint8_t ptrWrite; uint8_t length; CAN_RX_BUFFERELEMENT_s* buffer; } CAN_RX_BUFFER_s; typedef struct CAN_TX_BUFFERELEMENT { CanTxMsgTypeDef msg; uint8_t newMsg; } CAN_TX_BUFFERELEMENT_s; typedef struct CAN_TX_BUFFER { uint8_t ptrRead; uint8_t ptrWrite; uint8_t length; CAN_TX_BUFFERELEMENT_s* buffer; } CAN_TX_BUFFER_s; /*================== Constant and Variable Definitions ====================*/ /** * @brief CAN listen only transceiver mode of CAN node 0 */ extern uint8_t canNode0_listenonly_mode; /** * @brief CAN listen only transceiver mode of CAN node 1 */ extern uint8_t canNode1_listenonly_mode; /*================== Function Prototypes ==================================*/ /* Init */ /** * @brief Initializes CAN settings and message filtering * * @retval 0: if initialization successful, otherwise errorcode */ extern uint32_t CAN_Init(void); /* Interrupt handling */ /** * @brief Handles CAN TX interrupt request * @param ptrHcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * @retval none (void) */ extern void CAN_TX_IRQHandler(CAN_HandleTypeDef* ptrHcan); /** * @brief Handles CAN RX interrupt request * * @param canNode: canNode that received a message * @param ptrHcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * * @retval None */ extern void CAN_RX_IRQHandler(CAN_NodeTypeDef_e canNode, CAN_HandleTypeDef* ptrHcan); /** * @brief Handles CAN error interrupt request * * @param canNode: * @param ptrHcan: pointer to a CAN_HandleTypeDef structure that contains * the configuration information for the specified CAN. * * @retval None */ extern void CAN_Error_IRQHandler(CAN_NodeTypeDef_e canNode, CAN_HandleTypeDef* ptrHcan); /* Transmit Message */ /** * @brief Transmits message directly on the CAN bus * * @param canNode: canNode on which the message shall be transmitted * @param msgID: ID of the message that will be transmitted * @param ptrMsgData: pointer to the data that shall be transmitted * @param msgLength: Specifies the data length * @param RTR: Specifies the type of frame for the message that will be transmitted. * * @retval E_OK if transmission successful, otherwise E_NOT_OK */ extern STD_RETURN_TYPE_e CAN_TxMsg(CAN_NodeTypeDef_e canNode, uint32_t msgID, uint8_t* ptrMsgData, uint32_t msgLength, uint32_t RTR); /** * @brief Add message to transmit buffer, message will be transmitted shortly after. * * ------------------------ IMPORTANT!!!! -------------------------------- * Make sure that this function is not interrupted by the operating system * during its execution. * * @param canNode: canNode on which the message shall be transmitted * @param msgID: ID of the message that will be transmitted * @param ptrMsgData: pointer to a uint8_t array that contains the message that will be transmitted * @param msgLength: length of the message that will be transmitted * This parameter can be a value of CAN_identifier_type. * @param RTR Specifies the type of frame for the message that will be transmitted. * This parameter can be a value of CAN_remote_transmission_request * * @retval E_OK if successful, E_NOT_OK if buffer is full or error occurred */ extern STD_RETURN_TYPE_e CAN_Send(CAN_NodeTypeDef_e canNode, uint32_t msgID, uint8_t* ptrMsgData, uint32_t msgLength, uint32_t RTR); /** * @brief Transmits a can message from transmit buffer * * ------------------------ IMPORTANT!!!! -------------------------------- * Make sure that this function is not interrupted by the operating system * during its execution. * * @param canNode: canNode on which the message shall be transmitted * * @retval E_OK if transmission successful, otherwise E_NOT_OK */ extern STD_RETURN_TYPE_e CAN_TxMsgBuffer(CAN_NodeTypeDef_e canNode); /* Read Message */ /** * @brief Reads a can message from RxBuffer * * @param canNode canNode on which a message has been received * @param msg message that has been received * * @retval E_OK if reception successful, if buffer empty or invalid pointer E_NOT_OK */ extern STD_RETURN_TYPE_e CAN_ReceiveBuffer(CAN_NodeTypeDef_e canNode, Can_PduType* msg); /* Sleep mode */ /** * @brief Set CAN to sleep mode * * @param canNode canNode which shall be put to sleep mode * * @retval none (void) */ extern void CAN_SetSleepMode(CAN_NodeTypeDef_e canNode); /** * @brief Wake CAN up from sleep mode * * @param canNode canNode which shall be waken up from sleep mode * * @retval none. */ extern void CAN_WakeUp(CAN_NodeTypeDef_e canNode); /*================== Function Implementations =============================*/ /* *************************************** * CAN Fault Confinement ****************************************/ /* Fault confinement is a checking mechanism that makes it possible to distinguish between short disturbances (e.g. switching noise from a nearby power cable couples into the transmission media) and permanent failures (e.g. a node is malfunctioning and disturbs the bus). Manipulation of the error counters is asymmetric. On a successful transmission, or reception, of a message, the respective error counter is decremented if it had not been at zero. In the case of a transmit or receive error the counters are incremented, but by a value greater than the value they would be decrement by following a successful message transaction. If a node detects a local error condition (e.g. due to local conducted noise, application software, etc.), its resulting error flag (primary error flag) will subsequently cause all other nodes to respond with an error flag too (secondary error flags). It is important that a distinction is made between the nodes that detected an error first and the nodes which responded to the primary error flag. If a node transmits an active error frame, and it monitors a dominant bit after the sixth bit of its error flag, it considers itself as the node that has detected the error first. In the case where a node detects errors first too often, it is regarded as malfunctioning, and its impact to the network has to be limited. Therefore, a node can be in one of three possible error states: ERROR ACTIVE - Both of its error counters are less than 128. It takes part fully in bus communication and signals an error by transmission of an active error frame.This consists of sequence of 6 dominant bits followed by 8 recessive bits, all other nodes respond with the appropriate error flag, in response to the violation of the bit stuffing rule. ERROR PASSIVE - A node goes into error passive state if at least one of its error counters is greater than 127. It still takes part in bus activities, but it sends a passive error frame only, on errors. Furthermore, an error passive node has to wait an additional time (Suspend Transmission Field, 8 recessive bits after Intermission Field) after transmission of a message, before it can initiate a new data transfer. The primary passive error flag consists of 6 passive bits and thus is transparent on the bus and will not jam communications. BUS OFF - If the Transmit Error Counter of a CAN controller exceeds 255, it goes into the bus off state. It is disconnected from the bus (using internal logic) and does not take part in bus activities anymore. In order to reconnect the protocol controller, a so-called Bus Off recovery sequence has to be executed. This usually involves the re-initialization and configuration of the CAN controller by the host system, after which it will wait for 128 * 11 recessive bit times before it commences communication. */ /* *************************************** * CAN Error Confinement Rules ****************************************/ /* REC: Receive Error Counter, TEC: Transmit Error Counter */ /* - When a receiver detects an error, the REC will be increased by 1, except when the detected error was a Bit Error during the sending of an Active error Flag or an Overload Flag. - When a receiver detects a dominant bit as the first bit after sending an Error Flag, the REC will be increased by 8. - When a transmitter sends an Error Flag, the TEC is increased by 8. Exception 1: If the transmitter is Error Passive and detects an ACK Error because of not detecting a dominant ACK and does not detect a dominant bit while sending its Passive Error Flag. Exception 2: If the transmitter sends an Error Flag because a Stuff Error occurred during arbitration, and should have been recessive, and has been sent as recessive but monitored as dominant. - If the transmitter detects a Bit Error while sending an Active Error Flag or an Overload Frame, the TEC is increased by 8. - If a receiver detects a Bit Error while sending an Active Error Flag or an Overload Flag, the REC is increased by 8. - Any node tolerates up to 7 consecutive dominant bits after sending an Active Error Flag, Passive Error Flag or Overload Flag. After detecting the fourteenth consecutive dominant bit (in case of an Active Error Flag or an Overload Flag) or after detecting the eighth consecutive dominant bit following a Passive Error Flag, and after each sequence of additional eight consecutive dominant bits, ever y transmitter increases its TEC by 8 and every receiver increases its REC by 8. - After successful transmission of a frame (getting ACK and no error until EOF is finished), the TEC is decreased by 1 unless it was already 0. - After the successful reception of a frame (reception without error up to the ACK Slot and the successful sending of the ACK bit), the REC is decreased by 1, if it was between 1 and 127. If the REC was 0, it stays 0, and if it was greater than 127, then it will be set to a value between 119 and 127. - A node is Error Passive when the TEC equals or exceeds 128, or when the REC equals or exceeds 128. An error condition letting a node become Error Passive causes the node to send an Active Error Flag. - A node is Bus Off when the TEC is greater than or equal to 256. - An Error Passive node becomes Error Active again when both the TEC and the REC are less than or equal to 127. - A node which is Bus Off is permitted to become Error Active (no longer Bus Off) with its error counters both set to 0 after 128 occurrence of 11 consecutive recessive bits have been monitored on the bus. */ #endif /* CAN_H_ */
tonyhuang84/foxbms
embedded-software/mcu-common/src/driver/mcu/mcu.h
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file mcu.h * @author f<NAME> * @date 22.11.2015 (date of creation) * @ingroup DRIVERS * @prefix MCU * * @brief Headers for the functions for the MCU to manage time and interrupts * * Header file provides interfaces to set boot information, to disable/enable all interrupts, * to wait a designated time and and to get the a timestamp based on the os systick. * */ #ifndef MCU_H_ #define MCU_H_ /*================== Includes =============================================*/ #include "general.h" /*================== Macros and Definitions ===============================*/ typedef struct { uint32_t off0; uint32_t off32; uint32_t off64; uint32_t crc; } MCU_DeviceID_s; /*================== Constant and Variable Definitions ====================*/ extern MCU_DeviceID_s mcu_unique_deviceID; /*================== Function Prototypes ==================================*/ /** * @brief simple wait-loop to wait short periods of time * * @param time number of microseconds to wait, max. 1000us */ extern void MCU_Wait_us(uint32_t time); /** * @brief disables interrupts and returns prior state (enabled or disabled) * * this function is used for synchronization of real-time interrupts when bypassing FreeRTOS context and * could be used (called) from 'interrupt blocked' or 'interrupt unblocked' context * * @return current priority mask register, store this value and use it to enable interrupts again with CPU_RestoreINT() */ extern unsigned int MCU_DisableINT(void); /** * @brief restores interrupts to given state (enable or disable) * * this function is used for synchronization of real-time interrupts when bypassing FreeRTOS context * * @param primask_reg value for priority mask register, for use in case of nesting calling */ extern void MCU_RestoreINT(unsigned int primask_reg); /** * @brief Gets system reset status * * @return 0: no unexpected reset detected, otherwise unexpected reset detected */ extern uint32_t MCU_SystemResetStatus(uint32_t* regValue); /** * @brief gets systick value which is a 24-bit downcounter, auto refreshed with 71999 * * @return time current systick value */ extern uint32_t MCU_GetTimeBase(void); /** * @brief Get unique device ID */ extern void MCU_GetDeviceID(MCU_DeviceID_s * deviceID); /** * @brief Check if passed crc == unique device ID crc */ STD_RETURN_TYPE_e MCU_CheckCRCUniqueDeviceID(uint8_t *dataptr); /*================== Function Implementations =============================*/ #endif /* MCU_H_ */
tonyhuang84/foxbms
embedded-software/mcu-secondary/src/general/config/STM32F4xx/stm32f4xx_hal_msp.c
/** * @file stm32f4xx_hal_msp.c * @author STMicroelectronics * @date 2016 * @ingroup GENERAL_CONF * @brief HAL MSP Module, definition of initialization/de-initialization functions called when hardware units are activated/deactivated, * based on stm32f4xx_hal_msp_template.c * */ /** ****************************************************************************** * @file stm32f4xx_hal_msp.c * @author MCD Application Team * @version V1.5.0 * @date 06-May-2016 * @brief This file contains the HAL System and Peripheral (PPP) MSP initialization * and de-initialization functions. * It should be copied to the application folder and renamed into 'stm32f4xx_hal_msp.c'. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * 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. * 3. Neither the name of STMicroelectronics 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. * ****************************************************************************** */ /*================== Includes =============================================*/ #include "stm32f4xx_hal.h" #include "dma.h" /*================== Macros and Definitions ===============================*/ /*================== Function Prototypes ==================================*/ /*================== Function Implementations =============================*/ static uint8_t CAN_CLK1_enabled = 0; /** @defgroup HAL_MSP_Private_Functions HAL MSP Private Functions * @{ */ /** * @brief Initializes the Global MSP. * @note This function is called from HAL_Init() function to perform system * level initialization (GPIOs, clock, DMA, interrupt). * @retval None */ void HAL_MspInit(void) { } /** * @brief DeInitializes the Global MSP. * @note This functiona is called from HAL_DeInit() function to perform system * level de-initialization (GPIOs, clock, DMA, interrupt). * @retval None */ void HAL_MspDeInit(void) { } /** * @brief Initializes the PPP MSP. * @note This functiona is called from HAL_PPP_Init() function to perform * peripheral(PPP) system level initialization (GPIOs, clock, DMA, interrupt) * @retval None */ void HAL_PPP_MspInit(void) { } /** * @brief DeInitializes the PPP MSP. * @note This functiona is called from HAL_PPP_DeInit() function to perform * peripheral(PPP) system level de-initialization (GPIOs, clock, DMA, interrupt) * @retval None */ void HAL_PPP_MspDeInit(void) { } /** * Inizalizes the CAN modules, called by HAL_CAN_Init() * */ void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan) { if (hcan->Instance == CAN1) { CAN_CLK1_enabled++; if (CAN_CLK1_enabled == 1) { /* Enable CAN1 clock */ __HAL_RCC_CAN1_CLK_ENABLE(); } } if (hcan->Instance == CAN2) { CAN_CLK1_enabled++; if (CAN_CLK1_enabled == 1) { /* Enable CAN1 clock. CAN1 clock needs to run if CAN2 clock is enabled */ __HAL_RCC_CAN1_CLK_ENABLE(); } /* Enable CAN2 clock */ __HAL_RCC_CAN2_CLK_ENABLE(); } } /** * Deinitalizes the CAN modules * */ void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan) { if (hcan->Instance == CAN1) { if (CAN_CLK1_enabled > 0) { CAN_CLK1_enabled--; } if (CAN_CLK1_enabled == 0) { /* Enable CAN1 clock */ __HAL_RCC_CAN1_CLK_DISABLE(); } } if (hcan->Instance == CAN2) { /* Disable CAN2 clock */ __HAL_RCC_CAN2_CLK_DISABLE(); if (CAN_CLK1_enabled > 0) { CAN_CLK1_enabled--; } if (CAN_CLK1_enabled == 0) { /* Enable CAN1 clock. CAN1 clock needs to run if CAN2 clock is enabled */ __HAL_RCC_CAN1_CLK_DISABLE(); } } } /** * inits SPI 1-3 * configures SPI-Pins and SPI-Clocks * called by HAL_SPI_Init() * * @param hspi: pointer to SPI hardware handle */ void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi) { /* GPIO_InitTypeDef GPIO_InitStruct; */ /* USER CODE BEGIN SPI1_MspInit 0 */ /* USER CODE END SPI1_MspInit 0 */ /* GPIO_InitTypeDef GPIO_InitStruct; */ if (hspi->Instance == SPI6) { /* SPI4 peripheral clock enable */ __HAL_RCC_SPI6_CLK_ENABLE(); } } /** * de-inits SPI 1-3 * called by HAL-Functions * * @param hspi: pointer to SPI hardware handle * */ void HAL_SPI_MspDeInit(SPI_HandleTypeDef* hspi) { if (hspi->Instance == SPI4) { /* USER CODE BEGIN SPI4_MspDeInit 0 */ /* USER CODE END SPI4_MspDeInit 0 */ /* Peripheral clock disable */ /* __SPI1_CLK_DISABLE(); */ __SPI4_CLK_DISABLE(); HAL_GPIO_DeInit(GPIOE, GPIO_PIN_2|GPIO_PIN_3|GPIO_PIN_5|GPIO_PIN_6); /* USER CODE BEGIN SPI1_MspDeInit 1 */ /* USER CODE END SPI1_MspDeInit 1 */ } if (hspi->Instance == SPI6) { __SPI6_CLK_DISABLE(); } } void HAL_UART_MspInit(UART_HandleTypeDef* huart) { if (huart->Instance==USART3) { /* USER CODE BEGIN USART2_MspInit 0 */ /* USER CODE END USART2_MspInit 0 */ /* Peripheral clock enable */ __USART3_CLK_ENABLE(); // /**USART2 GPIO Configuration // PA2 ------> USART2_TX // PA3 ------> USART2_RX // */ /* GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3; */ /* GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; */ /* GPIO_InitStruct.Pull = GPIO_PULLUP; */ /* GPIO_InitStruct.Speed = GPIO_SPEED_LOW; */ /* GPIO_InitStruct.Alternate = GPIO_AF7_USART2; */ /* HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); */ /* USER CODE BEGIN USART2_MspInit 1 */ /* USER CODE END USART2_MspInit 1 */ } if (huart->Instance==USART2) { /* Peripheral clock enable */ __USART2_CLK_ENABLE(); } } #ifdef USE_FULL_ASSERT /** * runtime callback function of HAL Drivers parameter checking * called by HAL-Functions * * @param srcfile: pointer to filename * @param srcline: line number of source file * */ void assert_failed(uint8_t* srcfile, uint32_t srcline) { while (1) {; } } #endif /**@} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
tonyhuang84/foxbms
embedded-software/mcu-primary/src/driver/config/can_cfg.c
<gh_stars>0 /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file can_cfg.c * @author <NAME> * @date 12.07.2015 (date of creation) * @ingroup DRIVERS_CONF * @prefix CAN * * @brief Configuration for the CAN module * * The CAN bus settings and the received messages and their * reception handling are to be specified here. * */ /*================== Includes =============================================*/ #include "can_cfg.h" #include "rcc_cfg.h" #include "mcu.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ /*================== Function Prototypes ==================================*/ /*================== Function Implementations =============================*/ /* *************************************** * Set CAN settings here ****************************************/ CAN_HandleTypeDef hcan0 = { .Instance = CAN2, .Lock = HAL_UNLOCKED, .State = HAL_CAN_STATE_RESET, .ErrorCode = HAL_CAN_ERROR_NONE, #if (CAN0_BAUDRATE == 1000000) #if (RCC_APB1_CLOCK == 45000000) .Init.Prescaler = 3, /* CAN_CLOCK = APB1 = 45MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 45MHz/3/15 = 1.0MHz */ .Init.BS2 = CAN_BS2_8TQ, #elif(RCC_APB1_CLOCK == 42000000) .Init.Prescaler = 3, /* CAN_CLOCK = APB1 = 42MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 42MHz/3/14 = 1.0MHz */ .Init.BS2 = CAN_BS2_7TQ, #elif RCC_APB1_CLOCK == 32000000 .Init.Prescaler = 4, /* CAN_CLOCK = APB1 = 32MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_5TQ, /* --> CAN = 32MHz/4/8 = 1.0MHz */ .Init.BS2 = CAN_BS2_2TQ, #else #error "Please configure CAN Baudrate according to your clock configuration " #endif #elif(CAN0_BAUDRATE == 500000) #if (RCC_APB1_CLOCK == 45000000) .Init.Prescaler = 6, /* CAN_CLOCK = APB1 = 45MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 45MHz/6/15 = 0.5MHz */ .Init.BS2 = CAN_BS2_8TQ, #elif(RCC_APB1_CLOCK == 42000000) .Init.Prescaler = 6, /* CAN_CLOCK = APB1 = 42MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 42MHz/6/14 = 0.5MHz */ .Init.BS2 = CAN_BS2_7TQ, #elif RCC_APB1_CLOCK == 32000000 .Init.Prescaler = 8, /* CAN_CLOCK = APB1 = 32MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_5TQ, /* --> CAN = 32MHz/8/8 = 0.5MHz */ .Init.BS2 = CAN_BS2_2TQ, #else #error "Please configure CAN Baudrate according to your clock configuration " #endif #elif(CAN0_BAUDRATE == 250000) #if (RCC_APB1_CLOCK == 45000000) .Init.Prescaler = 12, /* CAN_CLOCK = APB1 = 45MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 45MHz/12/15 = 0.25MHz */ .Init.BS2 = CAN_BS2_8TQ, #elif(RCC_APB1_CLOCK == 42000000) .Init.Prescaler = 12, /* CAN_CLOCK = APB1 = 42MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 42MHz/12/14 = 0.25MHz */ .Init.BS2 = CAN_BS2_7TQ, #elif RCC_APB1_CLOCK == 32000000 .Init.Prescaler = 16, /* CAN_CLOCK = APB1 = 32MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_2TQ, /* --> CAN = 32MHz/16/8 = 0.25MHz */ .Init.BS2 = CAN_BS2_5TQ, #else #error "Please configure CAN Baudrate according to your clock configuration " #endif #elif(CAN0_BAUDRATE == 125000) #if (RCC_APB1_CLOCK == 45000000) .Init.Prescaler = 24, /* CAN_CLOCK = APB1 = 45MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 45MHz/12/14 = 0.125MHz */ .Init.BS2 = CAN_BS2_8TQ, #elif(RCC_APB1_CLOCK == 42000000) .Init.Prescaler = 24, /* CAN_CLOCK = APB1 = 42MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 42MHz/12/14 = 0.125MHz */ .Init.BS2 = CAN_BS2_7TQ, #elif RCC_APB1_CLOCK == 32000000 .Init.Prescaler = 32, /* CAN_CLOCK = APB1 = 32MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_2TQ, /* --> CAN = 32MHz/16/8 = 0.125MHz */ .Init.BS2 = CAN_BS2_5TQ, #else #error "Please configure CAN Baudrate according to your clock configuration " #endif #endif .Init.Mode = CAN_MODE_NORMAL, /* for test purpose, without connected can-bus use LOOPBACK mode */ .Init.SJW = CAN_SJW_1TQ, .Init.TTCM = DISABLE, /* time triggerd communication mode */ /* DISABLE: no influence */ /* ENABLE: saves timestamps for received and transmitted messages. See reference manual for more information. */ .Init.ABOM = ENABLE, /* automatic bus-off management */ /* DISABLE: Manually re-initialize CAN and wait for 128 * 11 recessive bits */ /* ENABLE: automatically leave bus-off mode after 128 * 11 recessive bits */ .Init.AWUM = ENABLE, /* automatic wake-up mode */ /* ENABLE: automatically leave sleep mode on message receiving */ /* DISABLE: SLEEP bit needs to be deleted by software */ .Init.NART = DISABLE, /* automatic retransition mode; */ /* DISABLE: retransmit the message until it has been successfully transmitted */ /* ENABLE: transmit only once, independently of transmission result */ .Init.RFLM = ENABLE, /* Receive FIFO locked against overrun. */ /* DISABLE: A new incoming message overwrites the last received message. */ /* ENABLE: Once a receive FIFO is full the next incoming message will be discarded. */ .Init.TXFP = DISABLE, /* Transmit FIFO priority */ /* DISABLE: driven by identifier of message. Lower identifier equals higher priority */ /* ENABLE: driven chronologically */ }; CAN_HandleTypeDef hcan1 = { .Instance = CAN1, .Lock = HAL_UNLOCKED, .State = HAL_CAN_STATE_RESET, .ErrorCode = HAL_CAN_ERROR_NONE, #if (CAN1_BAUDRATE == 1000000) #if (RCC_APB1_CLOCK == 45000000) .Init.Prescaler = 3, /* CAN_CLOCK = APB1 = 45MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 45MHz/3/15 = 1.0MHz */ .Init.BS2 = CAN_BS2_8TQ, #elif(RCC_APB1_CLOCK == 42000000) .Init.Prescaler = 3, /* CAN_CLOCK = APB1 = 42MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 42MHz/3/14 = 1.0MHz */ .Init.BS2 = CAN_BS2_7TQ, #elif RCC_APB1_CLOCK == 32000000 .Init.Prescaler = 4, /* CAN_CLOCK = APB1 = 32MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_5TQ, /* --> CAN = 32MHz/4/8 = 1.0MHz */ .Init.BS2 = CAN_BS2_2TQ, #else #error "Please configure CAN Baudrate according to your clock configuration " #endif #elif(CAN1_BAUDRATE == 500000) #if (RCC_APB1_CLOCK == 45000000) .Init.Prescaler = 6, /* CAN_CLOCK = APB1 = 45MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 45MHz/6/15 = 0.5MHz */ .Init.BS2 = CAN_BS2_8TQ, #elif(RCC_APB1_CLOCK == 42000000) .Init.Prescaler = 6, /* CAN_CLOCK = APB1 = 42MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 42MHz/6/14 = 0.5MHz */ .Init.BS2 = CAN_BS2_7TQ, #elif RCC_APB1_CLOCK == 32000000 .Init.Prescaler = 8, /* CAN_CLOCK = APB1 = 32MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_5TQ, /* --> CAN = 32MHz/8/8 = 0.5MHz */ .Init.BS2 = CAN_BS2_2TQ, #else #error "Please configure CAN Baudrate according to your clock configuration " #endif #elif(CAN1_BAUDRATE == 250000) #if (RCC_APB1_CLOCK == 45000000) .Init.Prescaler = 12, /* CAN_CLOCK = APB1 = 45MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 45MHz/12/15 = 0.25MHz */ .Init.BS2 = CAN_BS2_8TQ, #elif(RCC_APB1_CLOCK == 42000000) .Init.Prescaler = 12, /* CAN_CLOCK = APB1 = 42MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 42MHz/12/14 = 0.25MHz */ .Init.BS2 = CAN_BS2_7TQ, #elif RCC_APB1_CLOCK == 32000000 .Init.Prescaler = 16, /* CAN_CLOCK = APB1 = 32MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_5TQ, /* --> CAN = 32MHz/16/8 = 0.25MHz */ .Init.BS2 = CAN_BS2_2TQ, #else #error "Please configure CAN Baudrate according to your clock configuration " #endif #elif(CAN1_BAUDRATE == 125000) #if (RCC_APB1_CLOCK == 45000000) .Init.Prescaler = 24, /* CAN_CLOCK = APB1 = 45MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 45MHz/12/14 = 0.125MHz */ .Init.BS2 = CAN_BS2_8TQ, #elif(RCC_APB1_CLOCK == 42000000) .Init.Prescaler = 24, /* CAN_CLOCK = APB1 = 42MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_6TQ, /* --> CAN = 42MHz/12/14 = 0.125MHz */ .Init.BS2 = CAN_BS2_7TQ, #elif RCC_APB1_CLOCK == 32000000 .Init.Prescaler = 32, /* CAN_CLOCK = APB1 = 32MHz */ /* resulting CAN speed: APB1/prescaler/sumOfTimequants */ /* sum: 1tq for sync + BS1 + BS2 */ .Init.BS1 = CAN_BS1_5TQ, /* --> CAN = 32MHz/16/8 = 0.125MHz */ .Init.BS2 = CAN_BS2_2TQ, #else #error "Please configure CAN Baudrate according to your clock configuration " #endif #endif .Init.Mode = CAN_MODE_NORMAL, /* for test purpose, without connected can-bus use LOOPBACK mode */ .Init.SJW = CAN_SJW_1TQ, .Init.TTCM = DISABLE, /* time triggerd communication mode */ /* DISABLE: no influence */ /* ENABLE: saves timestamps for received and transmitted messages. See reference manual for more information. */ .Init.ABOM = ENABLE, /* automatic bus-off management */ /* DISABLE: Manually re-initialize CAN and wait for 128 * 11 recessive bits */ /* ENABLE: automatically leave bus-off mode after 128 * 11 recessive bits */ .Init.AWUM = ENABLE, /* automatic wake-up mode */ /* ENABLE: automatically leave sleep mode on message receiving */ /* DISABLE: SLEEP bit needs to be deleted by software */ .Init.NART = DISABLE, /* automatic retransition mode; */ /* DISABLE: retransmit the message until it has been successfully transmitted */ /* ENABLE: transmit only once, independently of transmission result */ .Init.RFLM = ENABLE, /* Receive FIFO locked against overrun. */ /* DISABLE: A new incoming message overwrites the last received message. */ /* ENABLE: Once a receive FIFO is full the next incoming message will be discarded. */ .Init.TXFP = DISABLE, /* Transmit FIFO priority */ /* DISABLE: driven by identifier of message. Lower identifier equals higher priority */ /* ENABLE: driven chronologically */ }; /* *************************************** * Configure TX messages here ****************************************/ #if defined(ITRI_MOD_5) #include "can_cfg_itri.h" #else const CAN_MSG_TX_TYPE_s can_CAN0_messages_tx[] = { { 0x110, 8, 100, 0, NULL_PTR }, /*!< BMS system state 0 */ { 0x111, 8, 100, 0, NULL_PTR }, /*!< BMS system state 1 */ { 0x112, 8, 100, 0, NULL_PTR }, /*!< BMS system state 2 */ { 0x115, 8, 100, 0, NULL_PTR }, /*!< BMS slave state 0 */ { 0x116, 8, 100, 0, NULL_PTR }, /*!< BMS slave state 1 */ { 0x130, 8, 100, 30, NULL_PTR }, /*!< Maximum allowed current */ { 0x131, 8, 100, 30, NULL_PTR }, /*!< SOP */ { 0x140, 8, 1000, 30, NULL_PTR }, /*!< SOC */ { 0x150, 8, 5000, 30, NULL_PTR }, /*!< SOH */ { 0x160, 8, 1000, 30, NULL_PTR }, /*!< SOE */ { 0x170, 8, 100, 30, NULL_PTR }, /*!< Cell voltages Min Max Average */ { 0x171, 8, 100, 30, NULL_PTR }, /*!< SOV */ { 0x180, 8, 100, 30, NULL_PTR }, /*!< Cell temperatures Min Max Average */ { 0x190, 8, 1000, 30, NULL_PTR }, /*!< Tempering */ { 0x1A0, 8, 1000, 30, NULL_PTR }, /*!< Insulation */ { 0x1D0, 8, 1000, 40, NULL_PTR }, /*!< Running average power 0 */ { 0x1D1, 8, 1000, 40, NULL_PTR }, /*!< Running average power 1 */ { 0x1D2, 8, 1000, 40, NULL_PTR }, /*!< Running average power 2 */ { 0x1E0, 8, 1000, 40, NULL_PTR }, /*!< Running average current 0 */ { 0x1E1, 8, 1000, 40, NULL_PTR }, /*!< Running average current 1 */ { 0x1E2, 8, 1000, 40, NULL_PTR }, /*!< Running average current 2 */ { 0x1F0, 8, 1000, 40, NULL_PTR }, /*!< Pack voltage */ { 0x200, 8, 200, 20, NULL_PTR }, /*!< Cell voltages module 0 cells 0 1 2 */ { 0x201, 8, 200, 20, NULL_PTR }, /*!< Cell voltages module 0 cells 3 4 5 */ { 0x202, 8, 200, 20, NULL_PTR }, /*!< Cell voltages module 0 cells 6 7 8 */ { 0x203, 8, 200, 20, NULL_PTR }, /*!< Cell voltages module 0 cells 9 10 11 */ { 0x210, 8, 200, 30, NULL_PTR }, /*!< Cell temperatures module 0 cells 0 1 2 */ { 0x211, 8, 200, 30, NULL_PTR }, /*!< Cell temperatures module 0 cells 3 4 5 */ { 0x212, 8, 200, 30, NULL_PTR }, /*!< Cell temperatures module 0 cells 6 7 8 */ { 0x213, 8, 200, 30, NULL_PTR }, /*!< Cell temperatures module 0 cells 9 10 11 */ { 0x220, 8, 200, 40, NULL_PTR }, /*!< Cell voltages module 1 cells 0 1 2 */ { 0x221, 8, 200, 40, NULL_PTR }, /*!< Cell voltages module 1 cells 3 4 5 */ { 0x222, 8, 200, 40, NULL_PTR }, /*!< Cell voltages module 1 cells 6 7 8 */ { 0x223, 8, 200, 40, NULL_PTR }, /*!< Cell voltages module 1 cells 9 10 11 */ { 0x230, 8, 200, 50, NULL_PTR }, /*!< Cell temperatures module 1 cells 0 1 2 */ { 0x231, 8, 200, 50, NULL_PTR }, /*!< Cell temperatures module 1 cells 3 4 5 */ { 0x232, 8, 200, 50, NULL_PTR }, /*!< Cell temperatures module 1 cells 6 7 8 */ { 0x233, 8, 200, 50, NULL_PTR }, /*!< Cell temperatures module 1 cells 9 10 11 */ { 0x240, 8, 200, 60, NULL_PTR }, /*!< Cell voltages module 2 cells 0 1 2 */ { 0x241, 8, 200, 60, NULL_PTR }, /*!< Cell voltages module 2 cells 3 4 5 */ { 0x242, 8, 200, 60, NULL_PTR }, /*!< Cell voltages module 2 cells 6 7 8 */ { 0x243, 8, 200, 60, NULL_PTR }, /*!< Cell voltages module 2 cells 9 10 11 */ { 0x250, 8, 200, 70, NULL_PTR }, /*!< Cell temperatures module 2 cells 0 1 2 */ { 0x251, 8, 200, 70, NULL_PTR }, /*!< Cell temperatures module 2 cells 3 4 5 */ { 0x252, 8, 200, 70, NULL_PTR }, /*!< Cell temperatures module 2 cells 6 7 8 */ { 0x253, 8, 200, 70, NULL_PTR }, /*!< Cell temperatures module 2 cells 9 10 11 */ { 0x260, 8, 200, 80, NULL_PTR }, /*!< Cell voltages module 3 cells 0 1 2 */ { 0x261, 8, 200, 80, NULL_PTR }, /*!< Cell voltages module 3 cells 3 4 5 */ { 0x262, 8, 200, 80, NULL_PTR }, /*!< Cell voltages module 3 cells 6 7 8 */ { 0x263, 8, 200, 80, NULL_PTR }, /*!< Cell voltages module 3 cells 9 10 11 */ { 0x270, 8, 200, 90, NULL_PTR }, /*!< Cell temperatures module 3 cells 0 1 2 */ { 0x271, 8, 200, 90, NULL_PTR }, /*!< Cell temperatures module 3 cells 3 4 5 */ { 0x272, 8, 200, 90, NULL_PTR }, /*!< Cell temperatures module 3 cells 6 7 8 */ { 0x273, 8, 200, 90, NULL_PTR }, /*!< Cell temperatures module 3 cells 9 10 11 */ { 0x280, 8, 200, 100, NULL_PTR }, /*!< Cell voltages module 4 cells 0 1 2 */ { 0x281, 8, 200, 100, NULL_PTR }, /*!< Cell voltages module 4 cells 3 4 5 */ { 0x282, 8, 200, 100, NULL_PTR }, /*!< Cell voltages module 4 cells 6 7 8 */ { 0x283, 8, 200, 100, NULL_PTR }, /*!< Cell voltages module 4 cells 9 10 11 */ { 0x290, 8, 200, 110, NULL_PTR }, /*!< Cell temperatures module 4 cells 0 1 2 */ { 0x291, 8, 200, 110, NULL_PTR }, /*!< Cell temperatures module 4 cells 3 4 5 */ { 0x292, 8, 200, 110, NULL_PTR }, /*!< Cell temperatures module 4 cells 6 7 8 */ { 0x293, 8, 200, 110, NULL_PTR }, /*!< Cell temperatures module 4 cells 9 10 11 */ { 0x2A0, 8, 200, 120, NULL_PTR }, /*!< Cell voltages module 5 cells 0 1 2 */ { 0x2A1, 8, 200, 120, NULL_PTR }, /*!< Cell voltages module 5 cells 3 4 5 */ { 0x2A2, 8, 200, 120, NULL_PTR }, /*!< Cell voltages module 5 cells 6 7 8 */ { 0x2A3, 8, 200, 120, NULL_PTR }, /*!< Cell voltages module 5 cells 9 10 11 */ { 0x2B0, 8, 200, 130, NULL_PTR }, /*!< Cell temperatures module 5 cells 0 1 2 */ { 0x2B1, 8, 200, 130, NULL_PTR }, /*!< Cell temperatures module 5 cells 3 4 5 */ { 0x2B2, 8, 200, 130, NULL_PTR }, /*!< Cell temperatures module 5 cells 6 7 8 */ { 0x2B3, 8, 200, 130, NULL_PTR }, /*!< Cell temperatures module 5 cells 9 10 11 */ { 0x2C0, 8, 200, 140, NULL_PTR }, /*!< Cell voltages module 6 cells 0 1 2 */ { 0x2C1, 8, 200, 140, NULL_PTR }, /*!< Cell voltages module 6 cells 3 4 5 */ { 0x2C2, 8, 200, 140, NULL_PTR }, /*!< Cell voltages module 6 cells 6 7 8 */ { 0x2C3, 8, 200, 140, NULL_PTR }, /*!< Cell voltages module 6 cells 9 10 11 */ { 0x2D0, 8, 200, 150, NULL_PTR }, /*!< Cell temperatures module 6 cells 0 1 2 */ { 0x2D1, 8, 200, 150, NULL_PTR }, /*!< Cell temperatures module 6 cells 3 4 5 */ { 0x2D2, 8, 200, 150, NULL_PTR }, /*!< Cell temperatures module 6 cells 6 7 8 */ { 0x2D3, 8, 200, 150, NULL_PTR }, /*!< Cell temperatures module 6 cells 9 10 11 */ { 0x2E0, 8, 200, 160, NULL_PTR }, /*!< Cell voltages module 7 cells 0 1 2 */ { 0x2E1, 8, 200, 160, NULL_PTR }, /*!< Cell voltages module 7 cells 3 4 5 */ { 0x2E2, 8, 200, 160, NULL_PTR }, /*!< Cell voltages module 7 cells 6 7 8 */ { 0x2E3, 8, 200, 160, NULL_PTR }, /*!< Cell voltages module 7 cells 9 10 11 */ { 0x2F0, 8, 200, 170, NULL_PTR }, /*!< Cell temperatures module 7 cells 0 1 2 */ { 0x2F1, 8, 200, 170, NULL_PTR }, /*!< Cell temperatures module 7 cells 3 4 5 */ { 0x2F2, 8, 200, 170, NULL_PTR }, /*!< Cell temperatures module 7 cells 6 7 8 */ { 0x2F3, 8, 200, 170, NULL_PTR }, /*!< Cell temperatures module 7 cells 9 10 11 */ #ifdef CAN_ISABELLENHUETTE_TRIGGERED , { 0x35B, 8, 100, 20, NULL_PTR } /*!< Current Sensor Trigger */ #endif }; #endif // ITRI_MOD_5 const CAN_MSG_TX_TYPE_s can_CAN1_messages_tx[] = { }; const uint8_t can_CAN0_tx_length = sizeof(can_CAN0_messages_tx)/sizeof(can_CAN0_messages_tx[0]); const uint8_t can_CAN1_tx_length = sizeof(can_CAN1_messages_tx)/sizeof(can_CAN1_messages_tx[0]); /* *************************************** * Configure RX messages here ****************************************/ /* Bypassed messages are --- ALSO --- to be configured here. See further down for bypass ID setting! */ CAN_MSG_RX_TYPE_s can0_RxMsgs[] = { { 0x120, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< state request */ { CAN_ID_SOFTWARE_RESET_MSG, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< software reset */ #ifdef CAN_ISABELLENHUETTE_TRIGGERED { 0x35C, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor I */ { 0x35D, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor U1 */ { 0x35E, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor U2 */ { 0x35F, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor U3 */ { 0x525, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor T in cyclic mode */ { 0x526, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor Power in cyclic mode */ { 0x527, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor C-C in cyclic mode */ { 0x528, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor E-C in cyclic mode */ #else { 0x521, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor I in cyclic mode */ { 0x522, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor U1 in cyclic mode */ { 0x523, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor U2 in cyclic mode */ { 0x524, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor U3 in cyclic mode */ { 0x525, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor T in cyclic mode */ { 0x526, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor Power in cyclic mode */ { 0x527, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor C-C in cyclic mode */ { 0x528, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< current sensor E-C in cyclic mode */ #endif { 0x100, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< debug message */ { 0x777, 0xFFFF, 8, 0, CAN_FIFO0, NULL }, /*!< request SW version */ }; CAN_MSG_RX_TYPE_s can1_RxMsgs[] = { }; const uint8_t can_CAN0_rx_length = sizeof(can0_RxMsgs)/sizeof(can0_RxMsgs[0]); const uint8_t can_CAN1_rx_length = sizeof(can1_RxMsgs)/sizeof(can1_RxMsgs[0]); /* *************************************** * Set bypass message IDs here ****************************************/ /* These IDs have to be included in the configuration for the filters in can_RxMsgs[]! */ uint32_t can0_bufferBypass_RxMsgs[CAN0_BUFFER_BYPASS_NUMBER_OF_IDs] = { CAN_ID_SOFTWARE_RESET_MSG }; uint32_t can1_bufferBypass_RxMsgs[CAN1_BUFFER_BYPASS_NUMBER_OF_IDs] = {};
tonyhuang84/foxbms
embedded-software/mcu-primary/src/module/nvram/eepr.h
<filename>embedded-software/mcu-primary/src/module/nvram/eepr.h /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file eepr.h * @author f<NAME> * @date 27.11.2012 (date of creation) * @ingroup DRIVERS * @prefix EEPR * * @brief Headers for the driver for the storage in the EEPROM memory * * Header file driver of external EEPROM device * */ #ifndef EEPR_H_ #define EEPR_H_ /*================== Includes =============================================*/ #include "eepr_cfg.h" /*================== Macros and Definitions ===============================*/ /** Instruction Set for Serial EEPROM AT25128 (16k x 8 Bit): <br> - REN */ #define EEPR_CMD_WREN 0x06 /** Instruction Set for Serial EEPROM AT25128 (16k x 8 Bit): <br> - RDI */ #define EEPR_CMD_WRDI 0x04 /** Instruction Set for Serial EEPROM AT25128 (16k x 8 Bit): <br> - DSR */ #define EEPR_CMD_RDSR 0x05 /** Instruction Set for Serial EEPROM AT25128 (16k x 8 Bit): <br> - RSR */ #define EEPR_CMD_WRSR 0x01 /** Instruction Set for Serial EEPROM AT25128 (16k x 8 Bit): <br> - Read */ #define EEPR_CMD_READ 0x03 /** Instruction Set for Serial EEPROM AT25128 (16k x 8 Bit): <br> - Write */ #define EEPR_CMD_WRITE 0x02 /** * Control and Status Information of EEPROM Driver * must be a multiple of a pagelength, e.g. multiple of 64 (AT25128) or 256 (M95M02) */ #define EEPR_DATA_STARTADDR 0x00 /** * Bitfield of EEPROM Status Register RSR */ typedef volatile union { struct { unsigned int nRDY : 1; /*!< RDY=0 indicates device is ready */ unsigned int WEN : 1; /*!< WEN=0 indicates device is not write enabled */ unsigned int BP0 : 1; /*!< BP0 Block Protection Bit 0 */ unsigned int BP1 : 1; /*!< BP1 Block Protection Bit 1 */ unsigned int : 3; /*!< dummy */ unsigned int WPEN : 1; /*!< WPEN */ } B; uint8_t u8; } EEPR_STATUSREGISTER_s; /** * structure to safe the requested hardware protection */ typedef struct { EEPR_STATUSREGISTER_s SR; } EEPR_REQ_HW_PROTECTION_s; /** * Control and Status Information of EEPROM Driver */ typedef struct { EEPR_STATUSREGISTER_s RSR; /*!< EEPROM status register */ uint8_t hwprotection; /*!< the selected writeprotection */ uint32_t protectionstartadd;/*!< the startaddress of the protected area */ uint32_t protectionendadd; /*!< the endaddress of the protected area */ EEPR_STATE_e state; /*!< state of EEPROM Driver State Machine */ EEPR_STATE_e statereq; /*!< current state request */ EEPR_STATE_e statestart; /*!< starting state of transition */ EEPR_STATE_e stateend; /*!< target state of transition */ uint8_t substate; /*!< sub-state of state */ uint8_t triggerentry; /*!< re-entrance protection (function running flag) */ uint8_t repeat; /*!< */ uint32_t timer; /*!< in counts of 1ms */ uint32_t eepromaddress1; /*!< actually accessed EEPROM address for first page */ uint32_t eepromaddress2; /*!< EEPROM address for other page(absolute, 64 Byte page aligned) */ uint16_t currentpagelength; /*!< length of the current page (maximum of 64 Bytes) */ uint8_t* ramaddress; /*!< source or destination */ EEPR_CHANNEL_ID_TYPE_e currentchannel; /*!< Channel to be written in or read from */ uint16_t nr_of_pages; /*!< (sizeof(EEPR_STATUS_s)+PageLength-/PageLength) */ uint16_t page_nr; /*!< actually accessed EEPROM page */ uint16_t readtime; /*!< time for read of all pages of struct_CALIB_FRAME */ uint16_t writetime; /*!< time for write of all pages of struct_CALIB_FRAME */ uint16_t write_len; /*!< write page in EEPROM < PageLength */ uint16_t read_len; /*!< depends only on SPI buffer */ } EEPR_STATUS_s; typedef struct { uint8_t repeat; uint8_t dirtyChannel; EEPR_DATAHANDLING_STATE_e state; uint8_t recovery_active; }EEPR_DATA_HANDLING_s; /*================== Constant and Variable Definitions ====================*/ /*================== Function Prototypes ==================================*/ /** * @brief returns 1 if the eeprom is in a final state in which it stays unless a staterequest is coming. * * @return uint8_t 1 if true 0 if false */ extern uint8_t EEPR_IsInFinalState(void); /** * @brief cyclic trigger of EEPROM State Machine, trigger cycle: 1ms * trigger timer in units of 1ms */ extern void EEPR_Trigger(void); /** * @brief Clears the error event and sends an errormessage * * @param state_req state request that caused the error * */ extern void EEPR_ClearErrorEvent(void); /* FIXME function not called, is it important? throw out? */ /** * @brief control of EEPROM Data management */ extern void EEPR_DataCtrl(void); /** * @brief reads "byte_len" of bytes from EEPROM memory starting at "address" and saving data in "eepr_spi_rxbuf" * * @param EeprAddr starting address of EEPROM where to read data * @param byte_len length of bytes that are to be read * @return 0 if reading successful, otherwise 0xFF */ extern uint8_t EEPR_ReadMemory(uint32_t EeprAddr, uint16_t byte_len); /** * @brief requests a state to be handled by the statetrigger * * @param state_req the requested state * @param channel channel to be written or read from * @param ramaddress sourceaddress for writing, targetaddress for reading * @return 0 if request was accepted, 1 if eeprom is busy, 2 if request was denied */ extern EEPR_RETURNTYPE_e EEPR_SetStateRequest(EEPR_STATE_e state_req, EEPR_CHANNEL_ID_TYPE_e channel, uint8_t* ramaddress); /* FIXME brief section is confusing */ /** * @brief max. time for reading of eeprom data of the current channel * * @return readtime in ms */ extern uint16_t EEPR_GetCurrentChReadTime(void); /* FIXME brief section is confusing */ /** * @brief max. time for writing of eeprom data of the current channel * * @return readtime in ms */ extern uint16_t EEPR_GetCurrentChWriteTime(void); /** * @brief calculates the maximum rest writetime for the current channel, by substracting the writetime taken to * read the current amount of pages * @return writetime in ms */ extern uint16_t EEPR_GetRestWriteTime(void); /** * @brief calculates the maximum rest readtime for the current channel, by substracting the readtime taken to * read the current amount of pages * * @return writetime in ms */ extern uint16_t EEPR_GetRestReadTime(void); /** * @brief calculates the maximum readtime for a specific channel * * @return writetime in ms */ extern uint16_t EEPR_GetChWriteTime(EEPR_CHANNEL_ID_TYPE_e channel); /** * @brief calculates the maximum writetime for a specific channel * * @return writetime in ms */ extern uint16_t EEPR_GetChReadTime(EEPR_CHANNEL_ID_TYPE_e channel); /** * @brief requests the initialization of the eeprom * and triggers the state machine until eeprom is in IDLE-Mode or timer has elapsed * * @return 0 if successful, error-bit if not */ EEPR_ERRORTYPES_e EEPR_Init(void); /** * @brief Updates the EEPROM data if bkpsram data are valid, otherwise uses the valid EEPROM data to update Bkpsram * If both data are invalid, writes default values into corrupt channels * * @return none */ extern EEPR_ERRORTYPES_e EEPR_InitChannelData(void); /** * @brief Reads the Data of one eeprom channel * function is usable as soon as the timer tasks have been initialized * * @param eepr_channel the channel to be read from * @param *dest_ptr pointer to the destination of the read data * @return state of epprom, returns EEPROM_OK if request was accepted, EEPR_BUSY, EEPR_ERROR or EEPR_REQUEST_PENDING if not */ extern EEPR_RETURNTYPE_e EEPR_GetChannelData(EEPR_CHANNEL_ID_TYPE_e eepr_channel, uint8_t *dest_ptr); /** * @brief Writes data into one eeprom channel * function is usable as soon as the timer tasks have been initialized * * @param eepr_channel the channel to be read from * @param *src_ptr ptr to the src of the data that should be written into the eeprom. Only necessary if no bkpsram channel is defined in eeprom channel config * @return state of epprom, returns EEPROM_OK if request was accepted, EEPR_BUSY, EEPR_ERROR or EEPR_REQUEST_PENDING if not */ extern EEPR_RETURNTYPE_e EEPR_SetChannelData(EEPR_CHANNEL_ID_TYPE_e eepr_channel, uint8_t *src_ptr); /** * @brief handles Data, checks validity, provides automatic backup in case of data corruption, dependent on dirtyflags * * The DataHandler provides an automatic read- and writeprocess if a dirtyflag is set in eepr_ch_dirtyflag[]. * If the dirtyflag is set, it checks the validity of the data. If they are invalid it recovers valid data from the eeprom. * If the data from the eeprom are also invalid, the default data are used. If the data are valid, they will be written into the eeprom */ extern void EEPR_DataHandler(); /*================== Function Implementations =============================*/ #endif /* EEPR_H_ */
tonyhuang84/foxbms
embedded-software/mcu-secondary/src/driver/config/rtc_cfg.h
<gh_stars>0 /** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file rtc_cfg.h * @author <NAME> * @date 02.10.2015 (date of creation) * @ingroup DRIVERS_CONF * @prefix RTC * * @brief Headers for the configuration for the real time clock * */ #ifndef RTC_CFG_H_ #define RTC_CFG_H_ /*================== Includes =============================================*/ #include "general.h" #include "cpu_cfg.h" /*================== Macros and Definitions ===============================*/ typedef RTC_InitTypeDef RTC_INIT_s; typedef RTC_TimeTypeDef RTC_Time_s; typedef RTC_DateTypeDef RTC_Date_s; /* backup size of the registers 80 Byte */ #define RTC_DATAVALID_VARIABLE (hrtc.Instance->BKP0R) /* rtc backup register valid */ #define RTC_BKPSRAM_DATAVALID_VARIABLE (hrtc.Instance->BKP1R) /* bkpsram data valid */ #define RTC_BKPDIAG_DATAVALID_VARIABLE (hrtc.Instance->BKP2R) /* bpksram diag data valid */ #define RTC_NVMRAM_DATAVALID_VARIABLE (hrtc.Instance->BKP3R) /* non-volatile data backups valid */ #define RTC_WDG_RESETCOUNTER (hrtc.Instance->BKP5R) /* wdg resetcounter */ /** * struct for the initialization and configuration of RTC */ typedef struct { RCC_OscInitTypeDef oscInitStruct; /*!< clock configuration of RTCs clock source */ RCC_PeriphCLKInitTypeDef clkInitStruct; /*!< clock source of RTC: RTCClk can be derived from HSE (ext. crystal), LSE (ext. crystal), LSI (internal RC oscillator) */ RTC_INIT_s initconfig; /*!< RTC configuration: hour format, prescaler,... */ uint8_t timeformat; /*!< date and time format configuration (binary or BCD) */ RTC_Time_s defaultTime; /*!< default time configuration */ RTC_Date_s defaultDate; /*!< default date configuration */ } RTC_CFG_s; typedef enum { BKPREGISTER_DATA_VALID = 0, BKPREGISTER_BKPSRAM_VALID = 1, BKPREGISTER_BKPSRAM_DIAG_VALID = 2, BKPREGISTER_NVRAM_VALID = 3, BKPREGISTER_WDG_RESETCOUNTER = 5, } RTC_BKPREGISTER_e; typedef enum { BKPREGISTER_NOT_VALID = 0, BKPREGISTER_VALID = 1, }RTC_BKPREGISTER_VALIDSTATE_e; /*================== Constant and Variable Definitions ====================*/ extern RTC_CFG_s rtc_cfg; extern RTC_HandleTypeDef hrtc; /*================== Function Prototypes ===================================*/ /** * @brief get backup register value */ uint32_t RTC_getRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber); /** * @brief set backup register value */ void RTC_setRegisterValueBKPSRAM(RTC_BKPREGISTER_e registerNumber, uint32_t value); /*================== Function Implementations ==============================*/ #endif /* RTC_CFG_H_ */
tonyhuang84/foxbms
embedded-software/mcu-primary/src/application/bal/bal.h
/** * * @copyright &copy; 2010 - 2019, Fraunhofer-Gesellschaft zur Foerderung der * angewandten Forschung e.V. All rights reserved. * * BSD 3-Clause License * 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. * 3. 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. * * We kindly request you to use one or more of the following phrases to refer * to foxBMS in your hardware, software, documentation or advertising * materials: * * &Prime;This product uses parts of foxBMS&reg;&Prime; * * &Prime;This product includes parts of foxBMS&reg;&Prime; * * &Prime;This product is derived from foxBMS&reg;&Prime; * */ /** * @file bal.h * @author foxBMS Team * @date 26.02.2016 (date of creation) * @ingroup DRIVERS * @prefix BAL * * @brief Header for the driver for balancing * */ #ifndef BAL_H_ #define BAL_H_ /*================== Includes =============================================*/ #include "bal_cfg.h" /*================== Macros and Definitions ===============================*/ /*================== Constant and Variable Definitions ====================*/ /*================== Function Prototypes ==================================*/ /*================== Function Implementations =============================*/ /*================== Constant and Variable Definitions ====================*/ /** * States of the BAL state machine */ typedef enum { /* Init-Sequence */ BAL_STATEMACH_UNINITIALIZED = 0, /*!< */ BAL_STATEMACH_INITIALIZATION = 1, /*!< */ BAL_STATEMACH_INITIALIZED = 2, /*!< */ BAL_STATEMACH_CHECK_BALANCING = 3, /*!< */ BAL_STATEMACH_BALANCE = 4, /*!< */ BAL_STATEMACH_NOBALANCING = 5, /*!< */ BAL_STATEMACH_ALLOWBALANCING = 6, /*!< */ BAL_STATEMACH_GLOBALDISABLE = 7, /*!< */ BAL_STATEMACH_GLOBALENABLE = 8, /*!< */ BAL_STATEMACH_UNDEFINED = 20, /*!< undefined state */ BAL_STATEMACH_RESERVED1 = 0x80, /*!< reserved state */ BAL_STATEMACH_ERROR = 0xF0, /*!< Error-State: */ } BAL_STATEMACH_e; /** * Substates of the BAL state machine */ typedef enum { BAL_ENTRY = 0, /*!< Substate entry state */ BAL_CHECK_IMBALANCES = 1, /*!< Check if balancing has been initialized */ BAL_COMPUTE_IMBALANCES = 2, /*!< Compute imbalances */ BAL_ACTIVATE_BALANCING = 3, /*!< Activated balancing resistors */ BAL_CHECK_LOWEST_VOLTAGE = 4, /*!< Check if lowest voltage is still above limit */ BAL_CHECK_CURRENT = 5, /*!< Check if current is still under limit */ } BAL_STATEMACH_SUB_e; /** * State requests for the BAL statemachine */ typedef enum { BAL_STATE_INIT_REQUEST = BAL_STATEMACH_INITIALIZATION, /*!< */ BAL_STATE_ERROR_REQUEST = BAL_STATEMACH_ERROR, /*!< */ BAL_STATE_NOBALANCING_REQUEST = BAL_STATEMACH_NOBALANCING, /*!< */ BAL_STATE_ALLOWBALANCING_REQUEST = BAL_STATEMACH_ALLOWBALANCING, /*!< */ BAL_STATE_GLOBAL_DISABLE_REQUEST = BAL_STATEMACH_GLOBALDISABLE, /*!< */ BAL_STATE_GLOBAL_ENABLE_REQUEST = BAL_STATEMACH_GLOBALENABLE, /*!< */ BAL_STATE_NO_REQUEST = BAL_STATEMACH_RESERVED1, /*!< */ } BAL_STATE_REQUEST_e; /** * Possible return values when state requests are made to the BAL statemachine */ typedef enum { BAL_OK = 0, /*!< CONT --> ok */ BAL_BUSY_OK = 1, /*!< CONT under load --> ok */ BAL_REQUEST_PENDING = 2, /*!< requested to be executed */ BAL_ILLEGAL_REQUEST = 3, /*!< Request can not be executed */ BAL_INIT_ERROR = 7, /*!< Error state: Source: Initialization */ BAL_OK_FROM_ERROR = 8, /*!< Return from error --> ok */ BAL_ERROR = 20, /*!< General error state */ BAL_ALREADY_INITIALIZED = 30, /*!< Initialization of LTC already finished */ BAL_ILLEGAL_TASK_TYPE = 99, /*!< Illegal */ } BAL_RETURN_TYPE_e; /** * This structure contains all the variables relevant for the BAL state machine. * The user can get the current state of the BAL state machine with this variable */ typedef struct { uint16_t timer; /*!< time in ms before the state machine processes the next state, e.g. in counts of 1ms */ BAL_STATE_REQUEST_e statereq; /*!< current state request made to the state machine */ BAL_STATEMACH_e state; /*!< state of Driver State Machine */ BAL_STATEMACH_SUB_e substate; /*!< current substate of the state machine */ BAL_STATEMACH_e laststate; /*!< previous state of the state machine */ uint8_t lastsubstate; /*!< previous substate of the state machine */ uint8_t triggerentry; /*!< counter for re-entrance protection (function running flag) */ uint32_t ErrRequestCounter; /*!< counts the number of illegal requests to the BAL state machine */ uint8_t active; /*!< indicate if balancing active or not */ uint8_t resting; /*!< indicate if current flowing through battery or not */ uint32_t rest_timer; /*!< counter since last timestamp with no current flowing */ uint32_t balancing_threshold; /*!< effective balancing threshod */ uint8_t balancing_allowed; /*!< flag to disable balancing */ uint8_t balancing_global_allowed; /*!< flag to globally disable balancing */ } BAL_STATE_s; /*================== Function Prototypes ==================================*/ extern BAL_RETURN_TYPE_e BAL_SetStateRequest(BAL_STATE_REQUEST_e statereq); extern BAL_STATEMACH_e BAL_GetState(void); extern void BAL_Trigger(void); #endif /* BAL_H_ */
1hAck-0/UE4-Cheat-Source-Code
Source/ImGui DirectX 11 Kiero Hook/menu/menu.h
#pragma once namespace Menu { void Render(); }
1hAck-0/UE4-Cheat-Source-Code
Source/ImGui DirectX 11 Kiero Hook/cheat/cheat.h
<reponame>1hAck-0/UE4-Cheat-Source-Code #pragma once #include "UnrealEngine/utils.h" namespace Cheat { bool Init(); void Uninit(); void DrawESP(); }
1hAck-0/UE4-Cheat-Source-Code
Source/ImGui DirectX 11 Kiero Hook/cheat/UnrealEngine/utils.h
<filename>Source/ImGui DirectX 11 Kiero Hook/cheat/UnrealEngine/utils.h #pragma once #include "UnrealClasses.h" #include <array> #include <vector> namespace mem { inline DWORD GNamesOffset = 0; inline uintptr_t TraceLineAddress = 0; template<typename T, typename U> constexpr size_t OffsetOf(U T::* member) { return (char*)&((T*)nullptr->*member) - (char*)nullptr; } extern __forceinline uintptr_t staticAddress(uintptr_t base, const std::vector<uintptr_t>& offsets); extern __forceinline uintptr_t GetPointerSafe(uintptr_t base, const std::vector<uintptr_t>& offsets); const char* GetGName(const int FNameIndex); uintptr_t GetModuleSize(const char* szModule); uintptr_t PatternScan(const bool usedIdaStyleMask, std::string idaSignature); DWORD GetStaticOffset(byte offsetToRead, byte extra, const bool usedIdaStyleMask, const char* pattern); } vec2 CalcAngle(const vec3& src, const vec3& dst, const vec2 currentAngles, float smoothness); vec3 GetVectorForward(const vec3& angles); template<const byte actorsToIgnoreCount = 0> __forceinline bool TraceLine(const vec3& src, const vec3& dst, FHitResult& hitinfo, const std::array<void*, actorsToIgnoreCount>& actorsToIgnore = {}, const int traceChannel = 0) { struct TTArray { uintptr_t* items = 0; int count = actorsToIgnoreCount; int max = actorsToIgnoreCount; }toIgnore; uintptr_t items_t[actorsToIgnoreCount]; toIgnore.items = items_t; for (byte i = 0; i < actorsToIgnoreCount; i++) toIgnore.items[i] = (uintptr_t)actorsToIgnore[i]; bool ret = reinterpret_cast<bool(*)( // function name: UKismetSystemLibrary::LineTraceSingle _UWorld * uWorld, const vec3 Start, const vec3 End, int TraceChannel, bool bTraceComplex, const TTArray & ActorsToIgnore, int DrawDebugType, FHitResult & hit, bool bIgnoreSelf, vec4 TraceColor, vec4 TraceHitColor, float DrawTime)> (mem::TraceLineAddress) (UWorld, src, dst, traceChannel, true, toIgnore, 0, hitinfo, true, {}, {}, 0.f); return ret; }
1hAck-0/UE4-Cheat-Source-Code
Source/ImGui DirectX 11 Kiero Hook/cheat/UnrealEngine/UnrealClasses.h
#pragma once #include "Classes.hpp" #include <string> #include <vector> namespace mem { uintptr_t GetPointerSafe(uintptr_t base, const std::vector<uintptr_t>& offsets); const char* GetGName(const int FNameIndex); } inline uintptr_t ModuleBase; inline uintptr_t ModuleBaseEnd; inline vec2 winSize; inline vec2 winCenter; struct UtilClass { #define DEFINE_MEMBER_N(type, name, offset) struct { char __pad__##name[offset]; type name; } #define DEFINE_MEMBER_N0(type, name) struct { type name; } template<typename T> T read(const USHORT& offset) { return *(T*)((uintptr_t)this + offset); } template<typename T> void write(const USHORT& offset, const T& value) { return *(T*)((uintptr_t)this + offset) = value; } }; template <typename T> struct TArray { inline T& operator[](const int i) { return items[i]; } inline const T& operator[](const int i) const { return items[i]; } __forceinline static TArray<T> Init(const std::vector<T>& items) { TArray<T> ret; ret.count = ret.max = items.size(); ret.items = new T[ret.count]; for (int i = 0; i < ret.count; i++) ret.items[i] = items[i]; return ret; } __forceinline void Uninit() { delete[] this->items; } T* items = nullptr; int count = 0; int max = 0; }; struct FString { inline wchar_t* GetWString() { return this->str; } inline char* GetString() { std::wstring buf(this->str); char ret[256]; strcpy_s(ret, std::string(buf.begin(), buf.end()).c_str()); return ret; } private: wchar_t* str; int count; int max; }; struct FTransform { vec4 Rotation; vec3 Translation; int _pad1; vec3 Scale; int _pad2; Matrix ToMatrixWithScale() const { Matrix m; m.m[3][0] = Translation.x; m.m[3][1] = Translation.y; m.m[3][2] = Translation.z; float x2 = Rotation.x + Rotation.x; float y2 = Rotation.y + Rotation.y; float z2 = Rotation.z + Rotation.z; float xx2 = Rotation.x * x2; float yy2 = Rotation.y * y2; float zz2 = Rotation.z * z2; m.m[0][0] = (1.0f - (yy2 + zz2)) * Scale.x; m.m[1][1] = (1.0f - (xx2 + zz2)) * Scale.y; m.m[2][2] = (1.0f - (xx2 + yy2)) * Scale.z; float yz2 = Rotation.y * z2; float wx2 = Rotation.w * x2; m.m[2][1] = (yz2 - wx2) * Scale.z; m.m[1][2] = (yz2 + wx2) * Scale.y; float xy2 = Rotation.x * y2; float wz2 = Rotation.w * z2; m.m[1][0] = (xy2 - wz2) * Scale.y; m.m[0][1] = (xy2 + wz2) * Scale.x; float xz2 = Rotation.x * z2; float wy2 = Rotation.w * y2; m.m[2][0] = (xz2 + wy2) * Scale.z; m.m[0][2] = (xz2 - wy2) * Scale.x; m.m[0][3] = 0.0f; m.m[1][3] = 0.0f; m.m[2][3] = 0.0f; m.m[3][3] = 1.0f; return m; } }; // size: 0x30 struct FName { union { struct { int32_t ComparisonIndex; //int32_t DisplayIndex; uint32_t Number; }; //uint64_t CompositeComparisonValue; }; }; struct TWeakObjectPtr { int ObjectIndex; int ObjectSerialNumber; }; struct FHitResult { uint32_t bBlockingHit : 1; uint32_t bStartPenetrating : 1; float Time; float Distance; vec3 Location; vec3 ImpactPoint; vec3 Normal; vec3 ImpactNormal; vec3 TraceStart; vec3 TraceEnd; float PenetrationDepth; int32_t Item; void* PhysMaterial; // TWeakObjectPtr<class UPhysicalMaterial> int ActorID; int ActorSerialNumber; void* Component; // TWeakObjectPtr<class UPrimitiveComponent> FName BoneName; int32_t FaceIndex; struct AEnemy* GetActor(); }; enum EStereoscopicPass { eSSP_FULL, eSSP_LEFT_EYE, eSSP_RIGHT_EYE, eSSP_MONOSCOPIC_EYE }; struct FMinimalViewInfo { vec3 Location; vec3 Rotation; float FOV; float OrthoWidth; float OrthoNearClipPlane; float OrthoFarClipPlane; float AspectRatio; uint32_t bConstrainAspectRatio : 1; uint32_t bUseFieldOfViewForLOD : 1; byte ProjectionMode; float PostProcessBlendWeight; //struct FPostProcessSettings PostProcessSettings; // FPostProcessSettings is a huge ass structure so I didn't bother remaking it //vec2 OffCenterProjectionOffset; }; struct UVTabel { inline uintptr_t operator[](const int index) { return items[index]; } inline uintptr_t offset(const int offset) { return *(uintptr_t*)((uintptr_t)this + offset); } uintptr_t items[256]; }; #define UObject_d \ DEFINE_MEMBER_N0(UVTabel*, VTable);\ DEFINE_MEMBER_N(int, ObjectIndex, 0xC);\ DEFINE_MEMBER_N(void*, Type, 0x10);\ DEFINE_MEMBER_N(int, FNameIndex, 0x18); struct UObject { union { UObject_d; }; }; struct USceneComponent { union { UObject_d; }; }; struct ACapsuleComponent { union { UObject_d; DEFINE_MEMBER_N(vec3, ModifiableLocation, 0x280); DEFINE_MEMBER_N(const vec3, RelativeLocation, 0x2C0); }; }; struct ARootComponent { union { UObject_d; DEFINE_MEMBER_N(vec3, Velocity, 0x338); }; }; struct ACharacterMovementComponent { enum EMovementMode : byte { MOVE_None, MOVE_Walking, MOVE_NavWalking, MOVE_Falling, MOVE_Swimming, MOVE_Flying, MOVE_Custom, MOVE_MAX }; union { UObject_d; DEFINE_MEMBER_N(float, GravityScale, 0x274); DEFINE_MEMBER_N(float, MaxJumpHeight, 0x278); DEFINE_MEMBER_N(float, JumpZVelocity, 0x27C); DEFINE_MEMBER_N(EMovementMode, MovementMode, 0x28C); DEFINE_MEMBER_N(byte, CustomMovementMode, 0x28D); DEFINE_MEMBER_N(float, MaxWalkSpeed, 0x2B4); DEFINE_MEMBER_N(float, MaxWalkSpeedCrouched, 0x2B8); DEFINE_MEMBER_N(float, MaxSwimSpeed, 0x2BC); DEFINE_MEMBER_N(float, MaxFlySpeed, 0x2C0); DEFINE_MEMBER_N(float, MaxCustomMovementSpeed, 0x2C4); DEFINE_MEMBER_N(float, MaxAcceleration, 0x2C8); DEFINE_MEMBER_N(float, Mass, 0x328); DEFINE_MEMBER_N(byte, bCheatFlying, 0x4A5); }; }; struct PlayerBP_C // local player class { union { UObject_d; DEFINE_MEMBER_N(byte, bActorEnableCollision, 0x86); DEFINE_MEMBER_N(struct ARootComponent*, RootComp, 0x168); DEFINE_MEMBER_N(struct ACharacterMovementComponent*, CharacterMovement, 0x3F0); DEFINE_MEMBER_N(struct ACapsuleComponent*, CapsuleComponent, 0x3F8); DEFINE_MEMBER_N(float, CrosshairExpand, 0x8CC); DEFINE_MEMBER_N(int, Ammo, 0x8D8); DEFINE_MEMBER_N(float, Health, 0x92C); DEFINE_MEMBER_N(byte, Crouched, 0x930); DEFINE_MEMBER_N(float, MaxMovementSpeed, 0x934); DEFINE_MEMBER_N(byte, Dead, 0x95C); }; vec3 GetVelocity() const; }; struct APlayerState { union { UObject_d; DEFINE_MEMBER_N(FString, PlayerName, 0x390); }; }; struct USkeletalMeshComponent { union { UObject_d; DEFINE_MEMBER_N(FTransform, CompToWorld, 0x270); DEFINE_MEMBER_N(TArray<FTransform>, CachedBoneArray, 0x920); }; vec3 GetBonePos(const byte& boneIndex) const { Matrix matrix = this->CachedBoneArray[boneIndex].ToMatrixWithScale() * this->CompToWorld.ToMatrixWithScale(); return { matrix.m[3][0], matrix.m[3][1], matrix.m[3][2] }; } }; struct AEnemy : UtilClass // actual class name: EnemyAI_BluePrintV2_C { union { UObject_d; DEFINE_MEMBER_N(struct ARootComponent*, RootComp, 0x168); DEFINE_MEMBER_N(struct USkeletalMeshComponent*, Mesh, 0x3E8); DEFINE_MEMBER_N(float, BulletRotation, 0x800); DEFINE_MEMBER_N(float, BulletDamage, 0x80C); DEFINE_MEMBER_N(byte, EnemyState, 0x839); DEFINE_MEMBER_N(byte, bCanSeePlayer, 0x892); DEFINE_MEMBER_N(byte, bInRange, 0x893); DEFINE_MEMBER_N(byte, CanSee, 0x9E8); DEFINE_MEMBER_N(vec3, Rotation, 0x41C); DEFINE_MEMBER_N(struct ULocalPlayer*, Player, 0x850); }; __forceinline vec3 GetBonePos(const byte& boneIndex) const { return this->Mesh->GetBonePos(boneIndex); } vec3 GetVelocity() const; bool HasValidId() const { return mem::GetPointerSafe((uintptr_t)this + 0x18, { 0x0 }); // 0x18 = offset of FNameIndex } bool IsDead() const { return !this->EnemyState; } bool IsPlayer() const { return this->HasValidId() && // is it a invalid pointer std::string(mem::GetGName(this->FNameIndex))._Starts_with("EnemyAI_BluePrint") && // is enemy type this->EnemyState; // is alive } bool IsVisible() const; }; struct APlayerCameraManager { union { UObject_d; DEFINE_MEMBER_N(vec3, Location, 0x410); DEFINE_MEMBER_N(vec3, Rotation, 0x41C); DEFINE_MEMBER_N(float, FOV, 0x428); }; bool WorldToScreen(const vec3& worldLoc, vec2& screenPos) const { Matrix tempMatrix = this->Rotation; vec3 vDelta = worldLoc - this->Location; vec3 vTransformed = { vDelta.Dot({ tempMatrix.m[1][0], tempMatrix.m[1][1], tempMatrix.m[1][2] }), vDelta.Dot({ tempMatrix.m[2][0], tempMatrix.m[2][1], tempMatrix.m[2][2] }), vDelta.Dot({ tempMatrix.m[0][0], tempMatrix.m[0][1], tempMatrix.m[0][2] }) }; if (vTransformed.z < 1.f) vTransformed.z = 1.f; screenPos.x = winCenter.x + vTransformed.x * (winCenter.x / tanf(this->FOV * M_PI / 360)) / vTransformed.z; screenPos.y = winCenter.y - vTransformed.y * (winCenter.x / tanf(this->FOV * M_PI / 360)) / vTransformed.z; if (screenPos.x > winSize.x || screenPos.x < 0.f || screenPos.y > winSize.y || screenPos.y < 0.f) return false; return true; } }; struct APlayerController { union { UObject_d; DEFINE_MEMBER_N(struct USceneComponent*, ActorComponent, 0x388); DEFINE_MEMBER_N(struct PlayerBP_C*, Character, 0x3A0); DEFINE_MEMBER_N(struct APlayerState*, PlayerState, 0x3A8); DEFINE_MEMBER_N(vec2, ControlRotation, 0x3B8); DEFINE_MEMBER_N(struct APlayerCameraManager*, CameraManager, 0x420); DEFINE_MEMBER_N(vec2, RotationVel, 0x588); }; }; struct ULocalPlayer { union { UObject_d; DEFINE_MEMBER_N(struct APlayerController*, PlayerController, 0x30); DEFINE_MEMBER_N(struct UGameViewportClient*, ViewportClient, 0x58); }; }; struct UGameInstance { union { UObject_d; DEFINE_MEMBER_N(TArray<struct ULocalPlayer*>, LocalPlayers, 0x38); }; }; struct ULevel { union { UObject_d; DEFINE_MEMBER_N(TArray<struct AEnemy*>, EntityList, 0xA0); }; }; struct _UWorld { union { UObject_d; DEFINE_MEMBER_N(TArray<struct ULevel*>, Levels, 0x110); DEFINE_MEMBER_N(struct ULevel*, PersistentLevel, 0x30); DEFINE_MEMBER_N(struct ULevel*, CurrentLevel, 0x138); DEFINE_MEMBER_N(struct UGameInstance*, GameInstance, 0x140); }; }; struct UGameViewportClient { union { UObject_d; DEFINE_MEMBER_N(struct _UWorld*, World, 0x80); DEFINE_MEMBER_N(struct UGameInstance*, GameInstance, 0x88); }; }; inline struct _UWorld* UWorld; inline struct ULocalPlayer* LocalPlayer; inline struct TArray<struct AEnemy*>* EntityList; inline struct APlayerCameraManager* CameraManager; #undef UObject_d #undef DEFINE_MEMBER_N
Beihic/Accumulation
AtCoder/BC212/Ccode.c
<reponame>Beihic/Accumulation<gh_stars>0 #include <stdio.h> void swap(int *a, int b, int c){ int tmp = a[b]; a[b] = a[c]; a[c] = tmp; } int part(int *a, int left, int right){ int tmp, k = (left+right)/2; swap(a, k, right); int i=left, j=right-1; while(i<=j){ while(a[i]<a[right]){i++;} while(j>=i && a[j]>=a[right]){j--;} if(i<j){swap(a, i, j);} } swap(a, i, right); return i; } void quicksort(int *a, int left, int right){ if(left<right){ int p=part(a, left, right); quicksort(a, left, p-1); quicksort(a, p+1, right); } } int main(void){ int N, M; int max = 200000; if(scanf("%d", &N)==EOF){ N=max; } if(scanf("%d", &M)==EOF){ M=max; } int A[N]; int B[M]; int i, j; for(i=0; i<N; i++){ if(scanf("%d", &A[i])==EOF){break;} } for(i=0; i<M; i++){ if(scanf("%d", &B[i])==EOF){break;} } quicksort(A, 0, N-1); quicksort(B, 0, M-1); int min=100000000; i=0; j=0; while(i<N && j<M){ if(A[i]>B[j]){ if(min>A[i]-B[j]){ min=A[i]-B[j]; } j++; }else if(A[i]<B[j]){ if(min>B[j]-A[i]){ min=B[j]-A[i]; } i++; } else{min=0; break;} } printf("%d", min); return 0; }
Beihic/Accumulation
MyCompiler/9cc.c
<filename>MyCompiler/9cc.c #include <ctype.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef enum{ TK_RESERVED, TK_NUM, TK_EOF, } TokenKind; typedef struct Token Token; struct Token{ TokenKind kind; Token *next; int val; char *str; }; char *user_input; Token *token; void error(char *fmt, ...){ va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); exit(1); } void error_at(char *loc, char *fmt, ...){ va_list ap; va_start(ap, fmt); int pos = loc - user_input; fprintf(stderr,"%s\n", user_input); fprintf(stderr,"%*s", pos, ""); fprintf(stderr,"^ "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); exit(1); } bool consume(char op){ if(token->kind != TK_RESERVED || token->str[0] != op) return false; token = token->next; return true; } void expect(char op){ if(token->kind != TK_RESERVED || token->str[0] != op) error_at(token->str, "expected '%c'", op); token = token->next; } int expect_number(){ if(token->kind != TK_NUM) error_at(token->str, "expected a number"); int val = token->val; token = token->next; return val; } bool at_eof(){ return token->kind == TK_EOF; } Token *new_token(TokenKind kind, Token *cur, char *str){ Token *tok = calloc(1, sizeof(Token)); tok->kind = kind; tok->str = str; cur->next = tok; return tok; } Token *tokenize(){ char *p = user_input; Token head; head.next = NULL; Token *cur = &head; while(*p){ if(isspace(*p)){ p++; continue; } if(strchr("+-*/()", *p)){ cur = new_token(TK_RESERVED, cur, p++); continue; } if(isdigit(*p)){ cur = new_token(TK_NUM, cur, p); cur->val = strtol(p, &p, 10); continue; } error_at(p, "invalid token"); } new_token(TK_EOF, cur, p); return head.next; } typedef enum{ ND_ADD, ND_SUB, ND_MUL, ND_DIV, ND_NUM, }NodeKind; typedef struct Node Node; struct Node{ NodeKind kind; Node *lhs; Node *rhs; int val; }; Node *new_node(NodeKind kind){ Node *node = calloc(1, sizeof(Node)); node->kind = kind; return node; } Node *new_binary(NodeKind kind, Node *lhs, Node *rhs){ Node *node = new_node(kind); node->lhs = lhs; node->rhs = rhs; return node; } Node *new_num(int val){ Node *node = new_node(ND_NUM); node->val = val; return node; } Node *expr(); Node *mul(); Node *unary(); Node *primary(); Node *expr(){ Node *node = mul(); for(;;){ if(consume('+')) node = new_binary(ND_ADD, node, mul()); else if(consume('-')) node = new_binary(ND_SUB, node, mul()); else return node; } } Node *mul(){ Node *node = unary(); for(;;){ if(consume('*')) node = new_binary(ND_MUL, node, unary()); else if(consume('/')) node = new_binary(ND_DIV, node, unary()); else return node; } } Node *unary(){ if(consume('+')) return unary(); if(consume('-')) return new_binary(ND_SUB, new_num(0), unary()); return primary(); } Node *primary(){ if(consume('(')){ Node *node = expr(); expect(')'); return node; } return new_num(expect_number()); } FILE *fp; void gen(Node *node){ if(node->kind == ND_NUM){ fprintf(fp, " push %d\n", node->val); return; } gen(node->lhs); gen(node->rhs); fprintf(fp, " pop rdi\n"); fprintf(fp, " pop rax\n"); switch(node->kind){ case ND_ADD: fprintf(fp, " add rax, rdi\n"); break; case ND_SUB: fprintf(fp, " sub rax, rdi\n"); break; case ND_MUL: fprintf(fp, " imul rax, rdi\n"); break; case ND_DIV: fprintf(fp, "cqo\n"); fprintf(fp, " idiv rdi\n"); break; } fprintf(fp, " push rax\n"); } int main(int argc, char **argv){ if(argc != 3) error("%s: invalid number of arguments", argv[0]); user_input = argv[1]; token = tokenize(); Node *node = expr(); fp = fopen(argv[2],"w"); fprintf(fp, ".intel_syntax noprefix\n"); fprintf(fp, ".global main\n"); fprintf(fp, "main:\n"); gen(node); fprintf(fp, " pop rax\n"); fprintf(fp, " ret\n"); fclose(fp); return 0; }
pariasm/bm4d-of
src/core/nldct.h
/* * Original work Copyright (c) 2013, <NAME> <<EMAIL>> * Modified work Copyright (c) 2014, <NAME> <<EMAIL>> * All rights reserved. * * This program is free software: you can use, modify and/or * redistribute it under the terms of the GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later * version. You should have received a copy of this license along * this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef VIDEO_NL_BAYES_H_INCLUDED #define VIDEO_NL_BAYES_H_INCLUDED #include "../utils/lib_videot.hpp" #include "../utils/utilities.h" /* Use VBM3D predictive search. */ //#define VBM3D_SEARCH /* Use VBM3D 3D transform. */ #define VBM3D_HAAR_TRANSFORM /* Emulate the full VBM3D algorithm (defines the previous VBM3D_* flags) */ //#define VBM3D namespace VideoNLB { enum ColorSpace {RGB, YUV}; enum Transform {dct, bior1_5}; /** * @brief Structures of parameters dedicated to NL-Bayes process * * @param sigma: value of noise; * @param sizePatch: size of patches (sizePatch x sizePatch); * @param nSimilarPatches: minimum number of similar patches wanted; * @param sizeSearchWindow: size of the search window around the reference patch; * @param boundary: must be > sizeSearchWindow. Boundary kept around sub-images when the image is * subdivided for parallelization; * @param offSet: step between two similar patches; * @param useHomogeneousArea: if true, use the homogeneous area trick; * @param gamma: threshold to detect homogeneous area; * @param beta: parameter used to estimate the covariance matrix; * @param tau: parameter used to determine similar patches; * @param isFirstStep: true if the first step of the algorithm is wanted; * @param doPasteBoost: if true, patches near denoised similar patches will not be used as reference * patches; * @param verbose: if true, print informations. **/ struct nlbParams { float sigma; unsigned sizePatch; // depends on sigma unsigned sizePatchTime; // user given unsigned nSimilarPatches; // depends on sigma, sizeSearchTimeRange (1 channel) or sizePatch (3 channels) unsigned sizeSearchWindow; // depends on nSimilarPatches unsigned sizeSearchTimeRangeFwd; // how many forward frames in search cube unsigned sizeSearchTimeRangeBwd; // how many backward frames in search cube unsigned boundary; // depends on sizeSearchWindow unsigned offSet; // depends on sizePatch unsigned offSetTime; // depends on sizePatchTime float beta; // noise correction factor float betaMean; // noise correction factor float tau; // depends on sizePatch bool orderInvariance; bool isFirstStep; bool doPasteBoost; bool verbose; ColorSpace colorSpace; Transform transform; // VBM3D: patch transform unsigned sizeSearchWindowPred; // VBM3D: search window for predictive search unsigned nSimilarPatchesPred; // VBM3D: number of sim patches for pred. search float dsub; // VBM3D: patch distance bias towards zero motion bool agg_window; // VBM3D: aggregation window (for the moment only Kaiser) }; /** * @brief Structure containing matrices used in the Bayesian estimation. * * @param groupTranspose: allocated memory. Used to contain the transpose of io_groupNoisy; * @param baricenter: allocated memory. Used to contain the baricenter of io_groupBasic; * @param covMat: allocated memory. Used to contain the covariance matrix of the 3D group; * @param covMatTmp: allocated memory. Used to process the Bayes estimate; * @param tmpMat: allocated memory. Used to process the Bayes estimate. **/ struct matWorkspace { std::vector<float> groupTranspose; std::vector<float> groupTransposeNoisy; std::vector<float> baricenter; std::vector<float> baricenterNoisy; std::vector<float> covMat; std::vector<float> covMatTmp; std::vector<float> tmpMat; // the following have been added for computing a low rank // approximation of the covariance matrix C // used if low-rank approximation is done via eigendecomp. of C std::vector<float> covEigVecs; std::vector<float> covEigVals; // used if low-rank approximation of C is done via SVD of data matrix X std::vector<float> svd_U; // left sing. vecs of X ~ eigen vecs of C std::vector<float> svd_V; // right sing. vecs of X std::vector<float> svd_VT; // right sing. vecs of X (transposed for LAPACKE) std::vector<float> svd_S; // sing. values of X ~ sqrt of eigen vecs of C std::vector<float> svd_work; std::vector<int > svd_iwork; // double matrix to compute svd using idd std::vector<double> svd_dU; // left sing. vecs of X ~ eigen vecs of C std::vector<double> svd_dV; // right sing. vecs of X std::vector<double> svd_dS; // sing. values of X ~ sqrt of eigen vecs of C std::vector<double> svd_ddata; // std::vector<double> svd_dwork; // store a fixed patch basis (eg. DCT) std::vector<float> patch_basis; std::vector<float> patch_basis_inv; // for non-orthogonal transforms // store a sepparable fixed patch basis (eg. DCT) std::vector<float> patch_basis_x; std::vector<float> patch_basis_y; std::vector<float> patch_basis_t; // aggregation window to minimize blocking artifacts std::vector<float> agg_window; }; /** * @brief Initialize Parameters of the NL-Bayes algorithm. * * @param params : will contain the nlbParams for the first step of the algorithm; * @param step : select first or second step; * @param sigma : standard deviation of the noise; * @param size : size of the video; * @param verbose : if true, print some informations. * * @return none. **/ void initializeNlbParameters( nlbParams &params , const unsigned step , const float sigma , const VideoSize &size , const bool verbose ); /** * @brief Sets size of spatial search window. It sets the border width accordingly, * and also ensures that the number of similar patches is not larger that the * total number of available patches. * * @param prms : nlbParams for first or second step of the algorithm; * @param sizeSearchWindow : size of search window; * * @return none. **/ void setSizeSearchWindow( nlbParams& prms , unsigned sizeSearchWindow ); /** * @brief Sets size of the patch. It sets the pixel offset as half the patch * size (this is BM3D speed-up). * * @param prms : nlbParams for first or second step of the algorithm; * @param sizePatch : size of the patch; * * @return none. **/ void setSizePatch( nlbParams& prms , const VideoSize &p_size , unsigned sizePatch ); /** * @brief Sets number of similar patches, ensuring that the number of similar * patches is not larger that the total number of available patches. * * @param prms : nlbParams for first or second step of the algorithm; * @param nSimilarPatches : number of similar patches; * * @return none. **/ void setNSimilarPatches( nlbParams& prms , unsigned nSimilarPatches ); /** * @brief Sets the distance threshold relative to the patch size. * * @param prms : nlbParams for first or second step of the algorithm; * @param tau : distance threshold; * * @return none. **/ void setTau( nlbParams& prms , const VideoSize &p_size , float tau ); /** * @brief Display parameters of the NL-Bayes algorithm. * * @param i_params : nlbParams for first or second step of the algorithm; * * @return none. **/ void printNlbParameters( const nlbParams &i_params ); /** * @brief Main function to process the whole NL-Bayes algorithm. * * @param i_imNoisy: contains the noisy video; * @param i_fflow : forward optical flow; * @param i_bflow : backward optical flow; * @param o_imBasic: will contain the basic estimate image after the first step; * @param o_imFinal: will contain the final denoised image after the second step; * @param p_params1 : parameters for first step * @param p_params1 : parameters for second step * * @return Percentage of processed groups over number of pixels. **/ std::vector<float> runNlBayes( Video<float> const& i_imNoisy , Video<float> const& i_fflow , Video<float> const& i_bflow , Video<float> &o_imBasic , Video<float> &o_imFinal , const nlbParams p_params1 , const nlbParams p_params2 ); /** * @brief Generic step of the NL-Bayes denoising (could be the first or the second). * * @param i_imNoisy: contains the noisy video; * @param io_imBasic: will contain the denoised image after the first step (basic estimation); * @param o_imFinal: will contain the denoised image after the second step; * @param p_params: parameters of the method, contains: * - sigma: standard deviation of the noise; * - sizePatch: size of patches (sizePatch x sizePatch); * - nSimilarPatches: number of similar patches; * - sizeSearchWindow: size of the neighbourhood searching window; * - useHomogeneousArea: if true, the trick of using homogeneous area will be used; * - gamma: parameter used to determine if we are in an homogeneous area; * - maxAvoid: parameter used to stop the paste trick; * - beta: parameter used during the estimate of the denoised patch; * - coefBaricenter: parameter to determine if the covariance matrix inversion is correct; * - isFirstStep: true if it's the first step of the algorithm which is needed; * - verbose: if true, print some informations, do nothing otherwise. * * @return Percentage of processed groups over number of pixels. **/ unsigned processNlBayes( Video<float> const& i_imNoisy , Video<float> const& i_fflow , Video<float> const& i_bflow , Video<float> &io_imBasic , Video<float> &o_imFinal , nlbParams const& p_params , VideoUtils::CropPosition p_crop = VideoUtils::CropPosition() ); /** * @brief Estimate the best similar patches to a reference one. * * @param i_im: contains the noisy video on which distances are processed; * @param o_group: will contain values of similar patches; * @param o_index: will contain index of similar patches; * @param p_ij: index of the reference patch; * @param p_params: see processStep1 for more explanation. * * @return number of similar patches kept. **/ unsigned estimateSimilarPatchesStep1( Video<float> const& i_im , Video<float> const& i_fflow , Video<float> const& i_bflow , std::vector<std::vector<float> > &o_group , std::vector<unsigned> &o_index , const unsigned p_ij , const nlbParams &p_params ); /** * @brief Keep from all near patches the similar ones to the reference patch for the second step. * * @param i_imNoisy: contains the original noisy video; * @param i_imBasic: contains the basic estimation; * @param o_groupNoisy: will contain similar patches for all channels of i_imNoisy; * @param o_groupBasic: will contain similar patches for all channels of i_imBasic; * @param o_index: will contain index of similar patches; * @param p_ij: index of the reference patch; * @param p_params: see processStep2 for more explanations. * * @return number of similar patches kept. **/ unsigned estimateSimilarPatchesStep2( Video<float> const& i_imNoisy , Video<float> const& i_imBasic , Video<float> const& i_fflow , Video<float> const& i_bflow , std::vector<float> &o_groupNoisy , std::vector<float> &o_groupBasic , std::vector<unsigned> &o_index , const unsigned p_ij , const nlbParams &p_params ); /** * @brief Detect if we are in an homogeneous area. In this case, compute the mean. * * @param io_group: contains for each channels values of similar patches. If an homogeneous area * is detected, will contain the average of all pixels in similar patches; * @param p_sP2: size of each patch (sP x sP); * @param p_nSimP: number of similar patches; * @param p_threshold: threshold below which an area is declared homogeneous; * @param p_imSize: size of the video. * * @return 1 if an homogeneous area is detected, 0 otherwise. **/ int computeHomogeneousAreaStep1( std::vector<std::vector<float> > &io_group , const unsigned p_sP , const unsigned p_nSimP , const float p_threshold , const VideoSize &p_imSize ); /** * @brief Detect if we are in an homogeneous area. In this case, compute the mean. * * @param io_groupNoisy: inputs values of similar patches for the noisy video; * if the area is classified as homogeneous, outputs the * average of all pixels in all patches. * @param i_groupBasic: contains values of similar patches for the basic video. * @param p_sP2: size of each patch (sP x sP); * @param p_nSimP: number of similar patches; * @param p_threshold: threshold below which an area is declared homogeneous; * @param p_imSize: size of the video. * * @return 1 if an homogeneous area is detected, 0 otherwise. **/ int computeHomogeneousAreaStep2( std::vector<float> & io_groupNoisy , std::vector<float> const &i_groupBasic , const unsigned p_sP , const unsigned p_nSimP , const float p_threshold , const VideoSize &p_imSize ); /** * @brief Compute the Bayes estimation assuming a low rank covariance matrix. * * @param io_group: contains all similar patches. Will contain estimates for all similar patches; * @param i_mat: contains : * - groupTranspose: allocated memory. Used to contain the transpose of io_groupNoisy; * - baricenter: allocated memory. Used to contain the baricenter of io_groupBasic; * - covMat: allocated memory. Used to contain the covariance matrix of the 3D group; * - covMatTmp: allocated memory. Used to process the Bayes estimate; * - tmpMat: allocated memory. Used to process the Bayes estimate; * @param io_nInverseFailed: update the number of failed matrix inversion; * @param p_params: see processStep1 for more explanation. * @param p_nSimP: number of similar patches. * @param aggreWeights: output aggregation weights. * * @return none. **/ float computeBayesEstimateStep1( std::vector<std::vector<float> > &io_group , matWorkspace &i_mat , unsigned &io_nInverseFailed , nlbParams const& p_params , const unsigned p_nSimP , std::vector<std::vector<float> > &aggreWeights ); /** * @brief Compute the Bayes estimation assuming a low rank covariance matrix. * * @param io_groupNoisy: inputs all similar patches in the noisy image, * outputs their denoised estimates. * @param i_groupBasic: contains all similar patches in the basic image. * @param i_mat: contains : * - groupTranspose: allocated memory. Used to contain the transpose of io_groupNoisy; * - baricenter: allocated memory. Used to contain the baricenter of io_groupBasic; * - covMat: allocated memory. Used to contain the covariance matrix of the 3D group; * - covMatTmp: allocated memory. Used to process the Bayes estimate; * - tmpMat: allocated memory. Used to process the Bayes estimate; * @param io_nInverseFailed: update the number of failed matrix inversion; * @param p_imSize: size of the image; * @param p_params: see processStep2 for more explanations; * @param p_nSimP: number of similar patches. * @param aggreWeights: output aggregation weights. * * @return none. **/ float computeBayesEstimateStep2( std::vector<float> &io_groupNoisy , std::vector<float> &i_groupBasic , matWorkspace &i_mat , unsigned &io_nInverseFailed , const VideoSize &p_imSize , nlbParams const& p_params , const unsigned p_nSimP , std::vector<float> &aggreWeights ); /** * @brief Aggregate estimates of all similar patches contained in the 3D group. * * @param io_im: update the video with estimate values; * @param io_weight: update corresponding weight, used later in the weighted aggregation; * @param io_mask: update values of mask: set to true the index of an used patch; * @param i_group: contains estimated values of all similar patches in the 3D group; * @param aggreWeights: input aggregation weights. * @param i_index: contains index of all similar patches contained in i_group; * @param p_params: see processStep1 for more explanation. * @param p_nSimP: number of similar patches. * * @return masked: number of processable pixels that were flaged non-processable. **/ int computeAggregationStep1( Video<float> &io_im , Video<float> &io_weight , Video<char> &io_mask , std::vector<std::vector<float> > const& i_group , std::vector<std::vector<float> > const& aggreWeights , std::vector<float> const& aggreWindow , std::vector<unsigned> const& i_index , const nlbParams& p_params , const unsigned p_nSimP ); /** * @brief Aggregate estimates of all similar patches contained in the 3D group. * * @param io_im: update the video with estimate values; * @param io_weight: update corresponding weight, used later in the weighted aggregation; * @param io_mask: update values of mask: set to true the index of an used patch; * @param i_group: contains estimated values of all similar patches in the 3D group; * @param aggreWeights: input aggregation weights. * @param i_index: contains index of all similar patches contained in i_group; * @param p_params: see processStep2 for more explanation; * @param p_nSimP: number of similar patches. * * @return masked: number of processable pixels that were flaged non-processable. * **/ int computeAggregationStep2( Video<float> &io_im , Video<float> &io_weight , Video<char> &io_mask , std::vector<float> const& i_group , std::vector<float> const& aggreWeights , std::vector<float> const& aggreWindow , Video<float> &variance , std::vector<unsigned> const& i_index , const nlbParams& p_params , const unsigned p_nSimP ); /** * @brief Aggregate estimates of all similar patches contained in the 3D * group. This version is for a test: in the original version, all patches * in the group are marked as processed, and cannot be origins of a patch * group. In this version we only mark as processed the patches of the * group which are nearby frames to the group origin. * * @param io_im: update the image with estimate values; * @param io_weight: update corresponding weight, used later in the weighted aggregation; * @param io_mask: update values of mask: set to true the index of an used patch; * @param i_group: contains estimated values of all similar patches in the 3D group; * @param i_index: contains index of all similar patches contained in i_group; * @param p_imSize: size of io_im; * @param p_params: see processStep1 for more explanation. * @param p_nSimP: number of similar patches. * * @return none. **/ void computeTemporalAggregationStep1( Video<float> &io_im , Video<float> &io_weight , Video<char> &io_mask , std::vector<std::vector<float> > const& i_group , std::vector<unsigned> const& i_index , const nlbParams &p_params , const unsigned p_nSimP ); /** * @brief Aggregate estimates of all similar patches contained in the 3D * group. This version is for a test: in the original version, all patches * in the group are marked as processed, and cannot be origins of a patch * group. In this version we only mark as processed the patches of the * group which are nearby frames to the group origin. * * @param io_im: update the image with estimate values; * @param io_weight: update corresponding weight, used later in the weighted aggregation; * @param io_mask: update values of mask: set to true the index of an used patch; * @param i_group: contains estimated values of all similar patches in the 3D group; * @param i_index: contains index of all similar patches contained in i_group; * @param p_imSize: size of io_im; * @param p_params: see processStep2 for more explanation; * @param p_nSimP: number of similar patches. * * @return none. **/ void computeTemporalAggregationStep2( Video<float> &io_im , Video<float> &io_weight , Video<char> &io_mask , std::vector<float> const& i_group , std::vector<unsigned> const& i_index , const nlbParams &p_params , const unsigned p_nSimP ); /** * @brief Compute the final weighted aggregation. * * i_imReference: video of reference, when the weight if null; * io_imResult: will contain the final video; * i_weight: associated weight for each estimate of pixels. * * @return none. **/ void computeWeightedAggregation( Video<float> const& i_im , Video<float> &io_im , Video<float> const& i_weight ); } // namespace #endif // VIDEO_NL_BAYES_H_INCLUDED
pariasm/bm4d-of
lib/tvl1flow/main_mesure.c
// This program is free software: you can use, modify and/or redistribute it // under the terms of the simplified BSD License. You should have received a // copy of this license along this program. If not, see // <http://www.opensource.org/licenses/bsd-license.html>. // // Copyright (C) 2011, <NAME> <<EMAIL>> // All rights reserved. #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #ifndef DISABLE_OMP #include <omp.h> #endif//DISABLE_OMP #include "iio.h" #include "tvl1flow_lib.c" #define PAR_DEFAULT_OUTFLOW "flow.flo" #define PAR_DEFAULT_NPROC 8 #define PAR_DEFAULT_TAU 0.25 #define PAR_DEFAULT_LAMBDA 0.15 #define PAR_DEFAULT_THETA 0.3 #define PAR_DEFAULT_NSCALES 100 #define PAR_DEFAULT_ZFACTOR 0.5 #define PAR_DEFAULT_NWARPS 5 #define PAR_DEFAULT_EPSILON 0.01 #define PAR_DEFAULT_VERBOSE 0 /** * * Function to read images using the iio library * It always returns an allocated the image. * */ static float **read_video(const char *filename, int *w, int *h, int f, int l) { float **output = xmalloc((l-f+1) * sizeof(*output)); for(int i = f,j = 0; i <= l; ++i,++j) { char gen_filename[1024]; sprintf(gen_filename, filename, i); float *f = iio_read_image_float(gen_filename, w, h); if (!f) fprintf(stderr, "ERROR: could not read image from file " "\"%s\"\n", gen_filename); output[j] = f; } return output; } static float **read_flow(const char *filename, int *w, int *h, int f, int l) { int c; float **output = xmalloc((l-f) * sizeof(*output)); for(int i = f,j = 0; i < l; ++i,++j) { char gen_filename[1024]; sprintf(gen_filename, filename, i); float *f = iio_read_image_float_split(gen_filename, w, h, &c); if (!f) fprintf(stderr, "ERROR: could not read flow from file " "\"%s\"\n", gen_filename); output[j] = f; } return output; } /** * * Main program: * This program reads the following parameters from the console and * then computes the optical flow: * -nprocs number of threads to use (OpenMP library) * -I0 first image * -I1 second image * -tau time step in the numerical scheme * -lambda data term weight parameter * -theta tightness parameter * -nscales number of scales in the pyramidal structure * -zfactor downsampling factor for creating the scales * -nwarps number of warps per scales * -epsilon stopping criterion threshold for the iterative process * -out name of the output flow field * -verbose switch on/off messages * */ int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s I0 I1 [out " // 0 1 2 3 "nproc tau lambda theta nscales zfactor nwarps epsilon " // 4 5 6 7 8 9 10 11 "verbose]\n", *argv); // 12 return EXIT_FAILURE; } //read the parameters int i = 1; char* vid_name = argv[i]; i++; int f = atoi(argv[i]); i++; int l = atoi(argv[i]); i++; char* of_name = argv[i]; i++; char* outpath = argv[i]; i++; float lambda = (argc>i)? atof(argv[i]): PAR_DEFAULT_LAMBDA; i++; int verbose = PAR_DEFAULT_VERBOSE; int nproc = PAR_DEFAULT_NPROC; //check parameters if (lambda <= 0) { lambda = PAR_DEFAULT_LAMBDA; if (verbose) fprintf(stderr, "warning: " "lambda changed to %g\n", lambda); } #ifndef DISABLE_OMP if (nproc > 0) omp_set_num_threads(nproc); #endif//DISABLE_OMP // read the input images int nx, ny; float **vid = read_video(vid_name, &nx, &ny, f, l); float **flow = read_flow(of_name, &nx, &ny, f, l); char gen_outpath[1024]; float error = 0.; //allocate memory for the diff float *diff = xmalloc(nx*ny * sizeof*diff); for(int i = 0, t=f; i < (l-f); ++i,++t) { sprintf(gen_outpath, outpath, t); //compute the optical flow error += energy_optic_flow( vid[i], vid[i+1], flow[i], flow[i]+(nx*ny), diff, nx, ny, lambda ); //save the difference iio_save_image_float(gen_outpath, diff, nx, ny); } error /= (l-f); printf("Energy error: %f\n", error); //delete allocated memory for(int t = 0; t < (l-f); ++t) { free(vid[t]); free(flow[t]); } free(vid[l-f]); free(vid); free(flow); free(diff); return EXIT_SUCCESS; }
pariasm/bm4d-of
src/core/matrix_funs.h
/* * Copyright (c) 2013, <NAME> <<EMAIL>> * All rights reserved. * * This program is free software: you can use, modify and/or * redistribute it under the terms of the GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later * version. You should have received a copy of this license along * this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIB_MATRIX_H_INCLUDED #define LIB_MATRIX_H_INCLUDED #include <vector> #include <string> /** * @brief Invert (in place) a symmetric real matrix, V -> Inv(V). * The input matrix V is symmetric (V[i,j] = V[j,i]). * * @param io_mat = array containing a symmetric input matrix. This is converted to the inverse matrix; * @param p_N = dimension of the system (dim(v)=n*n) * * @return EXIT_SUCCESS -> normal exit * EXIT_FAILURE -> input matrix not positive definite **/ int inverseMatrix( std::vector<float> &io_mat , const unsigned p_N ); /** * @brief Transpose a real square matrix in place io_mat -> io_mat~. * * @param io_mat : pointer to an array of p_N by p_N input matrix io_mat. This is overloaded by the transpose of io_mat; * @param p_N : dimension (dim(io_mat) = p_N * p_N). * * @return none. **/ void transposeMatrix( std::vector<float> &io_mat , const unsigned p_N ); /** * @brief Multiply two matrix A * B. It uses BLAS SGEMM. * * @param o_AB = array containing n by l product matrix at exit; * @param i_A = input array containing n by m matrix; * @param i_B = input array containing m by l matrix; * @param p_n, p_m, p_l = dimension parameters of arrays. * @param p_transA = true for transposing A. * @param p_transA = true for transposing B. * @param p_colMajor = true for if matrices should be read by columns. * * @return none. **/ void productMatrix( std::vector<float> &o_AB , std::vector<float> const& i_A , std::vector<float> const& i_B , const unsigned p_n , const unsigned p_m , const unsigned p_l , const bool p_transA , const bool p_transB , const bool p_colMajor = true , unsigned lda = 0 , unsigned ldb = 0 ); void printMatrix( std::vector<float> &matrix , unsigned rows , unsigned cols , std::string filename ); #endif // LIB_MATRIX_H_INCLUDED
pariasm/bm4d-of
src/utils/cmd_option.h
#ifndef __CMD_OPTION_H__ #define __CMD_OPTION_H__ #include <cstdarg> #include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; // // This is a copy paste of CImg option functions, so that they can be used // independently of CImg. To avoid name colisions, cimg_ prefixes have // been replaced by clo_. // // Define the program usage, and retrieve command line arguments. // #define clo_usage(usage) \ cmd_opt::option((char*)0,argc,argv,(char*)0,usage) #define clo_help(str) \ cmd_opt::option((char*)0,argc,argv,str,(char*)0) #define clo_option(name,defaut,usage) \ cmd_opt::option(name,argc,argv,defaut,usage) #define clo_argument(pos) \ cmd_opt::argument(pos,argc,argv) #define clo_argument1(pos,s0) \ cmd_opt::argument(pos,argc,argv,1,s0) #define clo_argument2(pos,s0,s1) \ cmd_opt::argument(pos,argc,argv,2,s0,s1) #define clo_argument3(pos,s0,s1,s2) \ cmd_opt::argument(pos,argc,argv,3,s0,s1,s2) #define clo_argument4(pos,s0,s1,s2,s3) \ cmd_opt::argument(pos,argc,argv,4,s0,s1,s2,s3) #define clo_argument5(pos,s0,s1,s2,s3,s4) \ cmd_opt::argument(pos,argc,argv,5,s0,s1,s2,s3,s4) #define clo_argument6(pos,s0,s1,s2,s3,s4,s5) \ cmd_opt::argument(pos,argc,argv,6,s0,s1,s2,s3,s4,s5) #define clo_argument7(pos,s0,s1,s2,s3,s4,s5,s6) \ cmd_opt::argument(pos,argc,argv,7,s0,s1,s2,s3,s4,s5,s6) #define clo_argument8(pos,s0,s1,s2,s3,s4,s5,s6,s7) \ cmd_opt::argument(pos,argc,argv,8,s0,s1,s2,s3,s4,s5,s6,s7) #define clo_argument9(pos,s0,s1,s2,s3,s4,s5,s6,s7,s8) \ cmd_opt::argument(pos,argc,argv,9,s0,s1,s2,s3,s4,s5,s6,s7,s8) namespace cmd_opt { const char t_normal[] = { 0x1b,'[','0',';','0',';','0','m','\0' }; const char t_red[] = { 0x1b,'[','4',';','3','1',';','5','9','m','\0' }; const char t_bold[] = { 0x1b,'[','1','m','\0' }; const char t_purple[] = { 0x1b,'[','0',';','3','5',';','5','9','m','\0' }; const char t_green[] = { 0x1b,'[','0',';','3','2',';','5','9','m','\0' }; //! Remove the 'case' of an ASCII character. inline char uncase(const char x) { return (char)((x<'A'||x>'Z')?x:x-'A'+'a'); } //! Remove the 'case' of a C string. /** Acts in-place. **/ inline void uncase(char *const string) { if (string) for (char *ptr = string; *ptr; ++ptr) *ptr = uncase(*ptr); } //! Read a float number from a C-string. /** \note This function is quite similar to <tt>std::atof()</tt>, but that it allows the retrieval of fractions as in "1/2". **/ inline float atof(const char *str) { float x = 0,y = 1; if (!str) return 0; else { sscanf(str,"%g/%g",&x,&y); return x/y; } } //! Compute the length of a C-string. /** \note This function is similar to <tt>std::strlen()</tt> and is here because some old compilers do not define the <tt>std::</tt> version. **/ inline int strlen(const char *s) { if (s) { int k; for (k = 0; s[k]; ++k) ; return k; } return -1; } //! Compare the first \p n characters of two C-strings. /** \note This function is similar to <tt>std::strncmp()</tt> and is here because some old compilers do not define the <tt>std::</tt> version. **/ inline int strncmp(const char *s1, const char *s2, const int l) { if (s1 && s2) { int n = 0; for (int k = 0; k<l; ++k) n+=abs(s1[k] - s2[k]); return n; } return 0; } //! Compare the first \p n characters of two C-strings, ignoring the case. /** \note This function is similar to <tt>std::strncasecmp()</tt> and is here because some old compilers do not define the <tt>std::</tt> version. **/ inline int strncasecmp(const char *s1, const char *s2, const int l) { if (s1 && s2) { int n = 0; for (int k = 0; k<l; ++k) n+=abs(uncase(s1[k])-uncase(s2[k])); return n; } return 0; } //! Compare two C-strings. /** \note This function is similar to <tt>std::strcmp()</tt> and is here because some old compilers do not define the <tt>std::</tt> version. **/ inline int strcmp(const char *s1, const char *s2) { const int l1 = strlen(s1), l2 = strlen(s2); return strncmp(s1,s2,1+(l1<l2?l1:l2)); } //! Compare two C-strings, ignoring the case. /** \note This function is similar to <tt>std::strcasecmp()</tt> and is here because some old compilers do not define the <tt>std::</tt> version. **/ inline int strcasecmp(const char *s1, const char *s2) { const int l1 = strlen(s1), l2 = strlen(s2); return strncasecmp(s1,s2,1+(l1<l2?l1:l2)); } //! Find a character in a C-string. inline int strfind(const char *s, const char c) { if (s) { int l; for (l=strlen(s); l>=0 && s[l]!=c; --l) ; return l; } return -1; } //! Compute the basename of a filename. inline const char* basename(const char *s) { return ("this is not windows")?(s?s+1+strfind(s,'/'):0):(s?s+1+strfind(s,'\\'):0); } inline const char* option(const char *const name, const int argc, char **argv, const char *defaut, const char *const usage=0) { static bool first = true, visu = false; const char *res = 0; if (first) { first=false; visu = (option("-h",argc,argv,(char*)0)!=0); visu |= (option("-help",argc,argv,(char*)0)!=0); visu |= (option("--help",argc,argv,(char*)0)!=0); } if (!name && visu) { if (usage) { fprintf(stderr,"\n %s%s%s", t_red,basename(argv[0]),t_normal); fprintf(stderr," : %s",usage); fprintf(stderr," (%s, %s)\n\n",__DATE__,__TIME__); } if (defaut) fprintf(stderr,"%s\n",defaut); } if (name) { if (argc>0) { int k = 0; while (k<argc && strcmp(argv[k],name)) ++k; res = (k++==argc?defaut:(k==argc?argv[--k]:argv[k])); } else res = defaut; if (visu && usage) fprintf(stderr," %s%-8s%s = %-12s : %s%s%s\n", t_bold,name,t_normal,res?res:"0",t_purple,usage,t_normal); } return res; } inline bool option(const char *const name, const int argc, char **argv, const bool defaut, const char *const usage=0) { const char *s = option(name,argc,argv,(char*)0); const bool res = s?(strcasecmp(s,"false") && strcasecmp(s,"off") && strcasecmp(s,"0")):defaut; option(name,0,0,res?"true":"false",usage); return res; } inline int option(const char *const name, const int argc, char **argv, const int defaut, const char *const usage=0) { const char *s = option(name,argc,argv,(char*)0); const int res = s?atoi(s):defaut; char tmp[256]; sprintf(tmp,"%d",res); option(name,0,0,tmp,usage); return res; } inline char option(const char *const name, const int argc, char **argv, const char defaut, const char *const usage=0) { const char *s = option(name,argc,argv,(char*)0); const char res = s?s[0]:defaut; char tmp[8]; tmp[0] = res; tmp[1] ='\0'; option(name,0,0,tmp,usage); return res; } inline float option(const char *const name, const int argc, char **argv, const float defaut, const char *const usage=0) { const char *s = option(name,argc,argv,(char*)0); const float res = s?atof(s):defaut; char tmp[256]; sprintf(tmp,"%g",res); option(name,0,0,tmp,usage); return res; } inline double option(const char *const name, const int argc, char **argv, const double defaut, const char *const usage=0) { const char *s = option(name,argc,argv,(char*)0); const double res = s?atof(s):defaut; char tmp[256]; sprintf(tmp,"%g",res); option(name,0,0,tmp,usage); return res; } inline const char* argument(const unsigned int nb, const int argc, char **argv, const unsigned int nb_singles=0, ...) { for (int k=1, pos=0; k<argc;) { const char *const item = argv[k]; bool option = (*item=='-'), single_option = false; if (option) { va_list ap; va_start(ap,nb_singles); for (unsigned int i=0; i<nb_singles; ++i) if (!strcasecmp(item,va_arg(ap,char*))) { single_option = true; break; } va_end(ap); } if (option) { ++k; if (!single_option) ++k; } else { if (pos++==(int)nb) return item; else ++k; } } return 0; } } //namespace cmd_opt #endif //__CLO_OPTION_H__
pariasm/bm4d-of
src/utils/lib_image.h
/* * Copyright (c) 2013, <NAME> <<EMAIL>> * All rights reserved. * * This program is free software: you can use, modify and/or * redistribute it under the terms of the GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later * version. You should have received a copy of this license along * this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIB_IMAGES_H_INCLUDED #define LIB_IMAGES_H_INCLUDED #include <vector> #include <string> #include <fftw3.h> /** * @brief Structure containing size informations of an image. * * @param width : width of the image; * @param height : height of the image; * @param nChannels : number of channels in the image; * @param wh : equal to width * height. Provided for convenience; * @param whc : equal to width * height * nChannels. Provided for convenience. **/ struct ImageSize { unsigned width; unsigned height; unsigned nChannels; unsigned wh; unsigned whc; }; /** * @brief Load image, check the number of channels. * * @param p_name : name of the image to read; * @param o_im : vector which will contain the image : R, G and B concatenated; * @param o_imSize : will contain the size of the image; * @param p_verbose : if true, print some informations. * * @return EXIT_SUCCESS if the image has been loaded, EXIT_FAILURE otherwise. **/ int loadImage( char* p_name , std::vector<float> &o_im , ImageSize &o_imSize , const bool p_verbose = false ); /** * @brief write image. * * @param p_name : path+name+extension of the image; * @param i_im : vector which contains the image; * @param p_imSize : size of the image; * @param p_min, p_max : range of data (usually [0, 255]). * * @return EXIT_SUCCESS if the image has been saved, EXIT_FAILURE otherwise **/ int saveImage( char* p_name , std::vector<float> const& i_im , const ImageSize &p_imSize , const float p_min , const float p_max ); /** * @brief add noise to img. * * @param i_im : original noise-free image; * @param o_imNoisy = im + noise; * @param p_sigma : standard deviation of the noise. * * @return none. **/ void addNoise( std::vector<float> const& i_im , std::vector<float> &o_imNoisy , const float p_sigma , const bool p_verbose ); /** * @brief Compute PSNR and RMSE between i_im1 and i_im2 * * @param i_im1 : pointer to an allocated array of pixels; * @param i_im2 : pointer to an allocated array of pixels; * @param o_psnr : will contain the PSNR; * @param o_rmse : will contain the RMSE; * @param p_imageName: name of the image; * @param p_verbose: if true, print values of PSNR and RMSE. * * @return EXIT_FAILURE if both images haven't the same size. **/ int computePsnr( std::vector<float> const& i_im1 , std::vector<float> const& i_im2 , float &o_psnr , float &o_rmse , const char* p_imageName , const bool p_verbose ); /** * @brief Compute a difference image between i_im1 and i_im2. * * @param i_im1: reference image; * @param i_im2: image to compare; * @param o_imDiff: will contain the difference; * @param p_sigma: standard deviation of the noise; * @param p_min, p_max : range of data (usually [0, 255]); * @param p_verbose : if true, print some informations. * * @return EXIT_FAILURE if i_im1 and i_im2 don't have the same size. **/ int computeDiff( std::vector<float> const& i_im1 , std::vector<float> const& i_im2 , std::vector<float> &o_imDiff , const float p_sigma , const float p_min , const float p_max , const bool p_verbose ); /** * @brief Add boundary by symetry. * * @param i_im : image to symetrize; * @param o_imSym : will contain i_img with symetrized boundaries; * @param p_imSize : size of i_im; * @param p_imSizeSym : size of o_imSym. * * @return none. **/ int addBoundary( std::vector<float> const& i_im , std::vector<float> &o_imSym , const ImageSize &p_imSize , const ImageSize &p_imSizeSym ); /** * @brief Remove boundaries added with addBoundary * * @param o_im : will contain the inner image; * @param i_imSym : contains i_im with symetrized boundaries; * @param p_imSize: size of o_im; * @param p_imSizeSym : size of i_imSym. * * @return none. **/ int removeBoundary( std::vector<float> &o_im , std::vector<float> const& i_imSym , const ImageSize &p_imSize , const ImageSize &p_imSizeSym ); /** * @brief Add boundaries by symetry * * @param io_im : original image; * @param io_imSym : contain io_im symetrized; * @param p_imSize : size of io_im; * @param p_borderSize : size of the boundary; * @param p_isForward: if true, build io_imSym, otherwise build io_im. * * @return none. **/ void symetrizeImage( std::vector<float> const& i_im1 , std::vector<float> &o_im2 , const ImageSize p_imSize , const unsigned p_borderSize , const bool p_isForward ); /** * @brief Transform the color space of an image, from RGB to YUV, or vice-versa. * * @param io_im: image on which the transform will be applied; * @param p_imSize: size of io_im; * @param p_isForward: if true, go from RGB to YUV, otherwise go from YUV to RGB. * * @return none. **/ void transformColorSpace( std::vector<float> &io_im , const ImageSize p_imSize , const bool p_isForward ); /** * @brief Subdivide an image into small sub-images * * @param i_im : image to subdivide; * @param o_imSub : will contain all sub-images; * @param p_imSize : size of i_im; * @param p_imSizeSub : size of sub-images; * @param p_N : boundary around sub-images; * @param p_nb : number of sub-images wanted. Need to be a power of 2. * * @return EXIT_FAILURE in case of problems. **/ int subDivide( std::vector<float> const& i_im , std::vector<std::vector<float> > &o_imSub , const ImageSize &p_imSize , ImageSize &p_imSizeSub , const unsigned p_N , const unsigned p_nb ); /** * @brief Reconstruct an image from its small sub-images * * @param o_im : image to reconstruct; * @param i_imSub : will contain all sub-images; * @param p_imSize : size of o_im; * @param p_imSizeSub : size of sub-images; * @param p_N : boundary around sub-images. * * @return EXIT_FAILURE in case of problems. **/ int subBuild( std::vector<float> &o_im , std::vector<std::vector<float> > const& i_imSub , const ImageSize &p_imSize , ImageSize &p_imSizeSub , const unsigned p_N ); #endif // LIB_IMAGES_H_INCLUDED
pariasm/bm4d-of
lib/tvl1flow/main.c
// This program is free software: you can use, modify and/or redistribute it // under the terms of the simplified BSD License. You should have received a // copy of this license along this program. If not, see // <http://www.opensource.org/licenses/bsd-license.html>. // // Copyright (C) 2011, <NAME> <<EMAIL>> // All rights reserved. #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #ifndef DISABLE_OMP #include <omp.h> #endif//DISABLE_OMP #include "iio.h" #include "tvl1flow_lib.c" #define PAR_DEFAULT_OUTFLOW "flow.flo" #define PAR_DEFAULT_NPROC 0 #define PAR_DEFAULT_TAU 0.25 #define PAR_DEFAULT_LAMBDA 0.15 #define PAR_DEFAULT_THETA 0.3 #define PAR_DEFAULT_NSCALES 100 #define PAR_DEFAULT_FSCALE 0 #define PAR_DEFAULT_ZFACTOR 0.5 #define PAR_DEFAULT_NWARPS 5 #define PAR_DEFAULT_EPSILON 0.01 #define PAR_DEFAULT_VERBOSE 0 /** * * Function to read images using the iio library * It always returns an allocated the image. * */ static float *read_image(const char *filename, int *w, int *h) { float *f = iio_read_image_float(filename, w, h); if (!f) fprintf(stderr, "ERROR: could not read image from file " "\"%s\"\n", filename); return f; } /** * * Main program: * This program reads the following parameters from the console and * then computes the optical flow: * -nprocs number of threads to use (OpenMP library) * -I0 first image * -I1 second image * -tau time step in the numerical scheme * -lambda data term weight parameter * -theta tightness parameter * -nscales number of scales in the pyramidal structure * -zfactor downsampling factor for creating the scales * -nwarps number of warps per scales * -epsilon stopping criterion threshold for the iterative process * -out name of the output flow field * -verbose switch on/off messages * */ int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s I0 I1 [out " // 0 1 2 3 "nproc tau lambda theta nscales fscale zfactor nwarps epsilon " // 4 5 6 7 8 9 10 11 12 "verbose]\n", *argv); // 13 return EXIT_FAILURE; } //read the parameters int i = 1; char* image1_name = argv[i]; i++; char* image2_name = argv[i]; i++; char* outfile = (argc>i)? argv[i]: PAR_DEFAULT_OUTFLOW; i++; int nproc = (argc>i)? atoi(argv[i]): PAR_DEFAULT_NPROC; i++; float tau = (argc>i)? atof(argv[i]): PAR_DEFAULT_TAU; i++; float lambda = (argc>i)? atof(argv[i]): PAR_DEFAULT_LAMBDA; i++; float theta = (argc>i)? atof(argv[i]): PAR_DEFAULT_THETA; i++; int nscales = (argc>i)? atoi(argv[i]): PAR_DEFAULT_NSCALES; i++; int fscale = (argc>i)? atoi(argv[i]): PAR_DEFAULT_FSCALE ; i++; float zfactor = (argc>i)? atof(argv[i]): PAR_DEFAULT_ZFACTOR; i++; int nwarps = (argc>i)? atoi(argv[i]): PAR_DEFAULT_NWARPS; i++; float epsilon = (argc>i)? atof(argv[i]): PAR_DEFAULT_EPSILON; i++; int verbose = (argc>i)? atoi(argv[i]): PAR_DEFAULT_VERBOSE; i++; //check parameters if (nproc < 0) { nproc = PAR_DEFAULT_NPROC; if (verbose) fprintf(stderr, "warning: " "nproc changed to %d\n", nproc); } if (tau <= 0 || tau > 0.25) { tau = PAR_DEFAULT_TAU; if (verbose) fprintf(stderr, "warning: " "tau changed to %g\n", tau); } if (lambda <= 0) { lambda = PAR_DEFAULT_LAMBDA; if (verbose) fprintf(stderr, "warning: " "lambda changed to %g\n", lambda); } if (theta <= 0) { theta = PAR_DEFAULT_THETA; if (verbose) fprintf(stderr, "warning: " "theta changed to %g\n", theta); } if (nscales <= 0) { nscales = PAR_DEFAULT_NSCALES; if (verbose) fprintf(stderr, "warning: " "nscales changed to %d\n", nscales); } if (zfactor <= 0 || zfactor >= 1) { zfactor = PAR_DEFAULT_ZFACTOR; if (verbose) fprintf(stderr, "warning: " "zfactor changed to %g\n", zfactor); } if (nwarps <= 0) { nwarps = PAR_DEFAULT_NWARPS; if (verbose) fprintf(stderr, "warning: " "nwarps changed to %d\n", nwarps); } if (epsilon <= 0) { epsilon = PAR_DEFAULT_EPSILON; if (verbose) fprintf(stderr, "warning: " "epsilon changed to %f\n", epsilon); } #ifndef DISABLE_OMP if (nproc > 0) omp_set_num_threads(nproc); #endif//DISABLE_OMP // read the input images int nx, ny, nx2, ny2; float *I0 = read_image(image1_name, &nx, &ny); float *I1 = read_image(image2_name, &nx2, &ny2); //read the images and compute the optical flow if (nx == nx2 && ny == ny2) { //Set the number of scales according to the size of the //images. The value N is computed to assure that the smaller //images of the pyramid don't have a size smaller than 16x16 const float N = 1 + log(hypot(nx, ny)/16.0) / log(1/zfactor); if (N < nscales) nscales = N; if (nscales < fscale) fscale = nscales; if (verbose) fprintf(stderr, "nproc=%d tau=%f lambda=%f theta=%f nscales=%d " "zfactor=%f nwarps=%d epsilon=%g\n", nproc, tau, lambda, theta, nscales, zfactor, nwarps, epsilon); //allocate memory for the flow float *u = xmalloc(2 * nx * ny * sizeof*u); float *v = u + nx*ny;; //compute the optical flow Dual_TVL1_optic_flow_multiscale( I0, I1, u, v, nx, ny, tau, lambda, theta, nscales, fscale, zfactor, nwarps, epsilon, verbose ); //save the optical flow iio_save_image_float_split(outfile, u, nx, ny, 2); //delete allocated memory free(I0); free(I1); free(u); } else { fprintf(stderr, "ERROR: input images size mismatch " "%dx%d != %dx%d\n", nx, ny, nx2, ny2); return EXIT_FAILURE; } return EXIT_SUCCESS; }
bonfireprocessor/gdb-proxy
debug_test.c
#include <stdio.h> #include "console.h" #include "riscv-gdb-stub.h" #define BAUDRATE 500000 void do_increment(volatile int *px) { (*px)++; } #define SIZE 10 uint64_t test[SIZE]; void initArray() { int i; for(i=0;i<SIZE;i++) test[i]=i*i; } void insertLastAt(int pos) // Inserts Last element of the array at pos { uint64_t *p; for(p=&test[SIZE-1];p>&test[pos];p--) { *p = *(p-1); } test[pos]=test[SIZE-1]; } void arrayTest() { int i; initArray(); for(i=0;i<SIZE;i++) printk("%4llu ",test[i]); insertLastAt(3); printk("\n"); for(i=0;i<SIZE;i++) printk("%4llu ",test[i]); } void main() { volatile int i=0; printk("Run with baudrate %d\n",BAUDRATE); gdb_setup_interface(BAUDRATE); gdb_initDebugger(1); gdb_breakpoint(); arrayTest(); gdb_breakpoint(); // while(1) { // do_increment(&i); // if ((i % 10000)==0 ) printk("*"); // } }
bonfireprocessor/gdb-proxy
trapframe.h
#ifndef __TRAPFRAME_H #define __TRAPFRAME_H #include <stdint.h> #ifdef __riscv64 #define TREG uint64_t #else #define TREG uint32_t #endif typedef struct { TREG gpr[32]; TREG status; TREG epc; TREG badvaddr; TREG cause; TREG insn; } trapframe_t; #endif
bonfireprocessor/gdb-proxy
riscv-gdb-stub.h
<gh_stars>0 #ifndef __RISCV_GDB_STUB_H__ #define __RISCV_GDB_STUB_H__ typedef trapframe_t* (*t_ptrapfuntion)(trapframe_t*); t_ptrapfuntion gdb_initDebugger(int set_mtvec); void gdb_setup_interface(int baudrate); trapframe_t* handle_exception (trapframe_t *ptf); /* This function will generate a breakpoint exception. It is used at the beginning of a program to sync up with a debugger and can be used otherwise as a quick means to stop program execution and "break" into the debugger. */ inline void gdb_breakpoint (void) { asm("sbreak"); } #endif
bonfireprocessor/gdb-proxy
trap.c
<filename>trap.c #include "trapframe.h" #include "riscv-gdb-stub.h" #include "encoding.h" trapframe_t* __attribute__((weak)) trap_handler(trapframe_t *ptf) { if (ptf->cause & 0x80000000) { // place interrupt handler here... return ptf; } else { return handle_exception(ptf); } } extern void __trap(); t_ptrapfuntion gdb_initDebugger(int set_mtvec) { if (set_mtvec) { write_csr(mtvec,__trap); } return handle_exception; }
bonfireprocessor/gdb-proxy
console.c
<gh_stars>0 // "Borrowed" from RISC-V proxy kernel // See LICENSE for license details. #include "bonfire.h" #include "console.h" #include <stdint.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #define UART_TX 0 #define UART_RECV 0 #define UART_STATUS 1 #define UART_CONTROL 1 static volatile uint32_t *uartadr=(uint32_t *)UART0_BASE; void writechar(char c) { while (!(uartadr[UART_STATUS] & 0x2)); // Wait while transmit buffer full uartadr[UART_TX]=(uint32_t)c; } void writestr(char *p) { while (*p) { writechar(*p); p++; } } // Like Writestr but expands \n to \n\r void write_console(char *p) { while (*p) { if (*p=='\n') writechar('\r'); writechar(*p); p++; } } static void vprintk(const char* s, va_list vl) { char out[4096]; vsnprintf(out, sizeof(out), s, vl); write_console(out); } void printk(const char* s, ...) { va_list vl; va_start(vl, s); vprintk(s, vl); va_end(vl); } void dump_tf(trapframe_t* tf) { static const char* regnames[] = { "z ", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "sa", "sb", "t3", "t4", "t5", "t6" }; printk("Trap %08lx\n",tf->cause); tf->gpr[0] = 0; for(int i = 0; i < 32; i+=4) { for(int j = 0; j < 4; j++) printk("%s %08lx%c",regnames[i+j],tf->gpr[i+j],j < 3 ? ' ' : '\n'); } printk("pc %08lx va %08lx op %08lx sr %08lx\n\n\n", tf->epc, tf->badvaddr, (uint32_t)tf->insn, tf->status); } void do_panic(const char* s, ...) { va_list vl; va_start(vl, s); vprintk(s, vl); while(1); // endless loop } void kassert_fail(const char* s) { register uintptr_t ra asm ("ra"); do_panic("assertion failed @ %p: %s\n", ra, s); } void hex_dump(void *mem,int numWords) { uint32_t *pmem = mem; int i; for(i=0;i<numWords;i++) { if ((i % 4)==0) { // Write Memory address for every four words printk("\n%08lx ",(uint32_t)&pmem[i]); } printk("%08lx ",pmem[i]); //writeHex(pmem[i]); } write_console("\n"); } long hstrtol(char *p, char **pp) { uint32_t v=0; char c; int digit; while(*p!='\0' ) { c=*p; if (c>='a' && c<='f') digit=c-'a'+10; else if (c>='A' && c<='F') digit=c-'A'+10; else if (c>='0' && c<='9') digit=c-'0'; else { // Invalid char *pp=p; // let pp point to it return v; } v= (v << 4 ) | digit; //printk("digit=%x v=%x\n",digit,v); p++; } *pp=p; return v; } bool parseNext(char *p,char **p1,uint32_t *pV) { if (p) { skipWhiteSpace(&p); if (*p=='\0') { *p1=p; return false; } *pV=hstrtol(p,p1); return p!=*p1; // true when chars are consumed } else return false; } void skipWhiteSpace(char **pc) { char *p; p=*pc; while((*p==' ' || *p=='\t') && *p!='\0') p++; // skip white space *pc=p; }
bonfireprocessor/gdb-proxy
riscv-tdep.h
<filename>riscv-tdep.h<gh_stars>1-10 /* Target-dependent header for the RISC-V architecture, for GDB, the GNU Debugger. Copyright (C) 2002-2015 Free Software Foundation, Inc. Contributed by <NAME>(<EMAIL>) at CMU and by <NAME>(<EMAIL>) at U.Wisconsin and by <NAME> <<EMAIL>> and by <NAME> <<EMAIL>>. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef RISCV_TDEP_H #define RISCV_TDEP_H struct gdbarch; /* All the official RISC-V ABIs. These mostly line up with mcpuid purely for convenience. */ #define RISCV_ABI_FLAG_RV32I (0x00000000) /* 32-bit Integer GPRs. */ #define RISCV_ABI_FLAG_RV64I (0x40000000) /* 64-bit Integer GPRs. */ #define RISCV_ABI_FLAG_D (1 << 3) /* Double-Precision Floating-Point. */ #define RISCV_ABI_FLAG_F (1 << 5) /* Single-Precision Floating-Point. */ #define IS_RV32I(x) (((x) & 0xF0000000) == RISCV_ABI_FLAG_RV32I) #define IS_RV64I(x) (((x) & 0xF0000000) == RISCV_ABI_FLAG_RV64I) #define HAS_FPU(x) ((x) & (RISCV_ABI_FLAG_D | RISCV_ABI_FLAG_F)) enum { RISCV_ZERO_REGNUM = 0, /* Read-only register, always 0. */ RISCV_RA_REGNUM = 1, /* Return Address. */ RISCV_SP_REGNUM = 2, /* Stack Pointer. */ RISCV_GP_REGNUM = 3, /* Global Pointer. */ RISCV_TP_REGNUM = 4, /* Thread Pointer. */ RISCV_FP_REGNUM = 8, /* Frame Pointer. */ RISCV_A0_REGNUM = 10, /* First argument. */ RISCV_A1_REGNUM = 11, /* Second argument. */ RISCV_PC_REGNUM = 32, /* Program Counter. */ RISCV_FIRST_FP_REGNUM = 33, /* First Floating Point Register */ RISCV_FA0_REGNUM = 49, RISCV_FA1_REGNUM = 50, RISCV_LAST_FP_REGNUM = 64, /* Last Floating Point Register */ RISCV_FIRST_CSR_REGNUM = 65, /* First CSR */ #define DECLARE_CSR(name, num) RISCV_ ## num ## _REGNUM = RISCV_LAST_FP_REGNUM + 1 + num, #include "opcode/riscv-opc.h" #undef DECLARE_CSR RISCV_LAST_CSR_REGNUM = 4160, RISCV_PRIV_REGNUM = 4161, /* Leave this as the last enum. */ RISCV_NUM_REGS }; #define RISCV_LAST_REGNUM (RISCV_NUM_REGS - 1) typedef enum { SUP_UNKNOWN, SUP_YES, SUP_NO } supported_t; /* RISC-V specific per-architecture information. */ struct gdbarch_tdep { int riscv_abi; supported_t supports_compressed_isa; }; static inline int riscv_isa_regsize (struct gdbarch *gdbarch) { int abi = gdbarch_tdep (gdbarch)->riscv_abi; switch (abi) { case RISCV_ABI_FLAG_RV32I: return 4; case RISCV_ABI_FLAG_RV64I: return 8; default: internal_error (__FILE__, __LINE__, _("unknown abi %i"), abi); return 4; } } #endif /* RISCV_TDEP_H */
nkennaA/Flixx
Flixx/DetailView.h
<gh_stars>0 // // DetailView.h // Flixx // // Created by <NAME> on 6/28/18. // Copyright © 2018 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface DetailView : UIViewController @property (weak, nonatomic) IBOutlet UIImageView *backdrop; @property (weak, nonatomic) IBOutlet UIImageView *poster2; @property (weak, nonatomic) IBOutlet UILabel *titlelabel; @property (weak, nonatomic) IBOutlet UIScrollView *scrollview; @property (weak, nonatomic) IBOutlet UILabel *sumlabel; @property NSDictionary *movie; @end
nkennaA/Flixx
Flixx/TrailerViewViewController.h
// // TrailerViewViewController.h // Flixx // // Created by <NAME> on 6/29/18. // Copyright © 2018 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface TrailerViewViewController : UIViewController @property (nonatomic) NSNumber *movieID; @end