repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
turesnake/tprPixelGames
src/Engine/camera/ViewingBox.h
<gh_stars>100-1000 /* * ========================= ViewingBox.h ========================== * -- tpr -- * CREATE -- 2019.01.22 * MODIFY -- * ---------------------------------------------------------- * camera.viewingBox * ---------------------------- */ #ifndef TPR_VIEWING_BOX_H #define TPR_VIEWING_BOX_H #include "pch.h" //-------------------- Engine --------------------// #include "RenderLayerType.h" class ViewingBox{ public: //--- MUST before OpenGL init --- static void init(); static double get_renderLayerZOff( RenderLayerType type_ )noexcept{ switch(type_){ case RenderLayerType::Ground: return ground_zOff; case RenderLayerType::GroundGo: return groundGo_zOff; case RenderLayerType::Floor: return floor_zOff; case RenderLayerType::BioSoup: return bioSoup_zOff; case RenderLayerType::GoShadows: return goShadows_zOff; case RenderLayerType::Debug: return debug_zOff; case RenderLayerType::MajorGoes: return majorGoes_zOff; case RenderLayerType::AboveMajorGoes: return aboveMajorGoes_zOff; //----- case RenderLayerType::UIs: return UIs_zOff; //----- default: tprAssert(0); return 0.0; //- never reach } } //======= statix =======// static IntVec2 windowSZ; //- 屏幕尺寸(像素)(在mac屏中,实际窗口尺寸可能为此值的2倍) static IntVec2 gameSZ; //- 游戏像素尺寸 static bool isFullScreen; //- 是否开启全屏模式 // 尚未完工,此值必须确保为 false //----- 取景盒 深度size ----- static constexpr double z { VIEWING_BOX_Z_DEEP<double> }; static constexpr double halfZ { 0.5 * ViewingBox::z }; //-- distance from zFar(to zNear) -- // camera.zFar 是个动态值,此处只能保存一个 相对偏移 static constexpr double ground_zOff { 10.0 }; // 整个游戏最 “深” 的图层,a canvas,往往涂上一个单一的底色 static constexpr double groundGo_zOff { 20.0 }; static constexpr double floor_zOff { 30.0 }; // under biosoup // 地表 图层。 放置 地衣,苔藓 等没有碰撞的 纯装饰性 go static constexpr double bioSoup_zOff { 3000.0 }; static constexpr double boxCenter_2_bioSoup { -2000.0 }; // 异世界生物汤,独占一整段 深度区间,目前深度为 (4000) // bioSoup_zOff 是这段深度区间的中点 static constexpr double goShadows_zOff { 5000.0 }; // go阴影 图层。 static constexpr double debug_zOff { 5010.0 }; // tprDebug 专用 图层 static constexpr double majorGoes_zOff { 7000.0 }; static constexpr double boxCenter_2_majorGoes { 2000.0 }; // 主体世界 表层go, 独占一整段 深度区间 目前深度为 (4000) // majorGoes_zOff 是这段深度区间的中点 //... static constexpr double aboveMajorGoes_zOff { 9890.0 }; // 在 MajorGoes 上方的一层 // 目前放置 playerGoCircle 的一部分 static constexpr double UIs_zOff { 9900.0 }; // UIs 专用 图层 }; #endif
turesnake/tprPixelGames
src/Script/gameObjs/majorGos/rocks/BreakStone.h
/* * ======================= BreakStone.h ========================== * -- tpr -- * CREATE -- 2019.12.31 * MODIFY -- * ---------------------------------------------------------- */ #ifndef TPR_GO_BREAK_STONE_H #define TPR_GO_BREAK_STONE_H //-------------------- Engine --------------------// #include "GameObj.h" #include "DyParam.h" namespace gameObjs{//------------- namespace gameObjs ---------------- class BreakStone{ public: static void init(GameObj &goRef_,const DyParam &dyParams_ ); private: static void bind( GameObj &goRef_ ); static void rebind( GameObj &goRef_ ); //--- callback ---// static void OnRenderUpdate( GameObj &goRef_ ); static void OnLogicUpdate( GameObj &goRef_ ); static void OnActionSwitch( GameObj &goRef_, ActionSwitchType type_ ); }; }//------------- namespace gameObjs: end ---------------- #endif
turesnake/tprPixelGames
src/Engine/collision/signInMapEnts/SignInMapEnts_Square_Type.h
/* * ====================== SignInMapEnts_Square_Type.h ========================== * -- tpr -- * CREATE -- 2020.02.19 * MODIFY -- * ---------------------------------------------------------- */ #ifndef TPR_SIGN_IN_MAP_ENTS_SQUARE_TYPE_H #define TPR_SIGN_IN_MAP_ENTS_SQUARE_TYPE_H //--------------- CPP ------------------// #include <string> // 一个 mp-go,自身所在的 mapent 为 rootMP, // 同时还允许占据数个 weakMP enum class SignInMapEnts_Square_Type{ T_1m1, // only have rootMapEnt //--- T_1m2, T_2m1, T_2m2, T_3m3, T_4m4, //... }; std::string signInMapEnts_square_type_2_str( SignInMapEnts_Square_Type t_ )noexcept; SignInMapEnts_Square_Type str_2_signInMapEnts_square_type( const std::string &str_ )noexcept; #endif
turesnake/tprPixelGames
src/Engine/ecoSys/EcoObj_ReadOnly.h
<gh_stars>100-1000 /* * ========================== EcoObj_ReadOnly.h ======================= * -- tpr -- * CREATE -- 2019.04.27 * MODIFY -- * ---------------------------------------------------------- */ #ifndef TPR_ECO_OBJ_READ_ONLY_H #define TPR_ECO_OBJ_READ_ONLY_H //-------------------- Engine --------------------// #include "EcoObj.h" #include "EcoObjBorder.h" //-- 仅用于 atom 函数 值传递 -- class EcoObj_ReadOnly{ public: sectionKey_t sectionKey {}; colorTableId_t colorTableId {}; double densitySeaLvlOff {}; //double uWeight {}; const std::vector<double> *densityDivideValsPtr {}; const EcoObjBorder *ecoObjBorderPtr {nullptr}; }; #endif
turesnake/tprPixelGames
src/Script/uiGos/Button_SceneBegin_Pointer.h
/* * ================ Button_SceneBegin_Pointer.h ========================== * -- tpr -- * CREATE -- 2019.08.25 * MODIFY -- * ---------------------------------------------------------- */ #ifndef TPR_UI_BUTTON_SCENE_BEGIN_POINTER_2_H #define TPR_UI_BUTTON_SCENE_BEGIN_POINTER_2_H //-------------------- Engine --------------------// #include "GameObj.h" #include "dyParams.h" namespace uiGos{//------------- namespace uiGos ---------------- class Button_SceneBegin_Pointer{ public: static void init( GameObj &goRef_, const DyParam &dyParams_ ); private: //--- callback ---// static void OnRenderUpdate( GameObj &goRef_ ); static void OnActionSwitch( GameObj &goRef_, ActionSwitchType type_ ); }; }//------------- namespace uiGos: end ---------------- #endif
turesnake/tprPixelGames
src/Engine/blueprint/YardBlueprint.h
/* * ======================= YardBlueprint.h ======================= * -- tpr -- * CREATE -- 2019.12.02 * MODIFY -- * ---------------------------------------------------------- */ #ifndef TPR_YARD_BLUE_PRINT_H #define TPR_YARD_BLUE_PRINT_H #include "pch.h" //-------------------- Engine --------------------// #include "BlueprintVarType.h" #include "GameObjType.h" #include "NineDirection.h" #include "BrokenLvl.h" #include "fieldKey.h" #include "FloorGoType.h" #include "PlotBlueprint.h" #include "blueprint_oth.h" #include "ID_Manager.h" namespace blueprint {//------------------ namespace: blueprint start ---------------------// using varTypeDatas_Yard_MajorGoId_t = uint32_t; class VarTypeDatas_Yard_MajorGo{ public: VarTypeDatas_Yard_MajorGo()=default; //----- set -----// inline void set_isAllInstanceUseSamePlan( bool b_ )noexcept{ this->isAllInstanceUseSamePlan = b_; } inline void set_isPlotBlueprint( bool b_ )noexcept{ this->isPlotBlueprint = b_; } inline void insert_2_goSpecPool( std::unique_ptr<GoSpec> uptr_, size_t num_ )noexcept{ varTypeDatas_Yard_MajorGoId_t id = VarTypeDatas_Yard_MajorGo::id_manager.apply_a_u32_id();// 盲目分配id auto [insertIt, insertBool] = this->goSpecPool.emplace( id, std::move( uptr_ ) ); tprAssert( insertBool ); //--- this->goSpecRandPool.insert( this->goSpecRandPool.end(), num_, id ); } inline void insert_2_plotIds( plotBlueprintId_t id_, size_t num_ )noexcept{ this->plotIds.insert( this->plotIds.end(), num_, id_ ); } void init_check()noexcept; //----- get -----// inline bool get_isPlotBlueprint()const noexcept{ return this->isPlotBlueprint; } inline bool get_isAllInstanceUseSamePlan()const noexcept{ return this->isAllInstanceUseSamePlan; } inline const GoSpec &apply_rand_goSpec( size_t uWeight_ )const noexcept{ varTypeDatas_Yard_MajorGoId_t id = this->goSpecRandPool.at( (uWeight_ + 7106177) % this->goSpecRandPool.size() ); return *(this->goSpecPool.at(id)); } inline const std::vector<plotBlueprintId_t> &get_plotIds()const noexcept{ return this->plotIds; } private: //-- 以下 2组容器,只有一个被使用,要么是 goSpecs,要么是 plots std::vector<varTypeDatas_Yard_MajorGoId_t> goSpecRandPool {}; std::unordered_map<varTypeDatas_Yard_MajorGoId_t, std::unique_ptr<GoSpec>> goSpecPool {}; //--- std::vector<plotBlueprintId_t> plotIds {}; // 随机抽取池 bool isAllInstanceUseSamePlan {}; // 是否 本类型的所有个体,共用一个 实例化对象 bool isPlotBlueprint {}; // 本变量是否为一个 plot //======== static ========// static ID_Manager id_manager; }; using varTypeDatas_Yard_FloorGoId_t = uint32_t; class VarTypeDatas_Yard_FloorGo{ public: VarTypeDatas_Yard_FloorGo()=default; //----- set -----// inline void set_isAllInstanceUseSamePlan( bool b_ )noexcept{ this->isAllInstanceUseSamePlan = b_; } inline void set_floorGoSize( FloorGoSize size_ )noexcept{ this->floorGoSize = size_; } inline void insert_2_goSpecPool( std::unique_ptr<GoSpec> uptr_, size_t num_ )noexcept{ varTypeDatas_Yard_FloorGoId_t id = VarTypeDatas_Yard_FloorGo::id_manager.apply_a_u32_id();// 盲目分配id auto [insertIt, insertBool] = this->goSpecPool.emplace( id, std::move(uptr_) ); tprAssert( insertBool ); //--- this->goSpecRandPool.insert( this->goSpecRandPool.end(), num_, id ); } void init_check()noexcept; //----- get -----// inline bool get_isAllInstanceUseSamePlan()const noexcept{ return this->isAllInstanceUseSamePlan; } inline FloorGoSize get_floorGoSize()const noexcept{ return this->floorGoSize; } inline const GoSpec &apply_rand_goSpec( size_t uWeight_ )const noexcept{ varTypeDatas_Yard_FloorGoId_t id = this->goSpecRandPool.at( (uWeight_ + 1076177) % this->goSpecRandPool.size() ); return *(this->goSpecPool.at(id)); } private: std::vector<varTypeDatas_Yard_FloorGoId_t> goSpecRandPool {}; std::unordered_map<varTypeDatas_Yard_FloorGoId_t, std::unique_ptr<GoSpec>> goSpecPool {}; bool isAllInstanceUseSamePlan {}; // 是否 本类型的所有个体,共用一个 实例化对象 FloorGoSize floorGoSize {}; //======== static ========// static ID_Manager id_manager; }; // 院子级蓝图。中间级别的蓝图,有数 fields 大 class YardBlueprint{ public: using mapDataId_t = uint32_t; //--- inline void insert_2_majorGo_varTypeDatas( VariableTypeIdx typeIdx_, std::shared_ptr<VarTypeDatas_Yard_MajorGo> sptr_ )noexcept{ auto [insertIt1, insertBool1] = this->majorGo_varTypeDatas.insert({ typeIdx_, std::move(sptr_) }); tprAssert( insertBool1 ); auto [insertIt2, insertBool2] = this->majorGo_varTypes.insert( typeIdx_ ); tprAssert( insertBool2 ); } inline void insert_2_floorGo_varTypeDatas( VariableTypeIdx typeIdx_, std::shared_ptr<VarTypeDatas_Yard_FloorGo> sptr_ )noexcept{ auto [insertIt1, insertBool1] = this->floorGo_varTypeDatas.insert({ typeIdx_, std::move(sptr_) }); tprAssert( insertBool1 ); auto [insertIt2, insertBool2] = this->floorGo_varTypes.insert( typeIdx_ ); tprAssert( insertBool2 ); } inline void set_isHaveMajorGos( bool b_ )noexcept{ this->isHaveMajorGos = b_; } inline void set_isHaveFloorGos( bool b_ )noexcept{ this->isHaveFloorGos = b_; } inline void set_sizeByField( IntVec2 sizeByMapEnt_ )noexcept{ this->sizeByFild = sizeByMapEnt_2_yardSize( sizeByMapEnt_ ); } void init_check()noexcept; inline YardSize get_yardSize()const noexcept{ return this->sizeByFild; } //- 仅用于 读取 json数据 时 - inline bool get_isHaveMajorGos()const noexcept{ return this->isHaveMajorGos; } inline bool get_isHaveFloorGos()const noexcept{ return this->isHaveFloorGos; } inline std::pair<mapDataId_t, MapData*> create_new_majorGo_mapData( size_t num_=1 )noexcept{ mapDataId_t id = YardBlueprint::mapDataId_manager.apply_a_u32_id(); this->majorGo_mapDataIds.insert( this->majorGo_mapDataIds.end(), num_, id ); //--- auto [insertIt, insertBool] = this->majorGo_mapDatas.emplace( id, MapData{} ); tprAssert( insertBool ); return { id, &(insertIt->second) }; } inline std::pair<mapDataId_t, MapData*> create_new_floorGo_mapData( size_t num_=1 )noexcept{ mapDataId_t id = YardBlueprint::mapDataId_manager.apply_a_u32_id(); this->floorGo_mapDataIds.insert( this->floorGo_mapDataIds.end(), num_, id ); //--- auto [insertIt, insertBool] = this->floorGo_mapDatas.emplace( id, MapData{} ); tprAssert( insertBool ); return { id, &(insertIt->second) }; } inline void bind_floorId_2_majorId( mapDataId_t majorId_, mapDataId_t floorId_ )noexcept{ tprAssert( this->isHaveMajorGos && this->isHaveFloorGos ); auto [insertIt, insertBool] = this->majorDataId_2_floorDataIds.emplace( majorId_, floorId_ ); tprAssert( insertBool ); // Must } inline std::pair<mapDataId_t, const MapData*> get_binded_floorData( mapDataId_t majorId_ )const noexcept{ tprAssert( this->majorDataId_2_floorDataIds.find(majorId_) != this->majorDataId_2_floorDataIds.end() ); mapDataId_t id = this->majorDataId_2_floorDataIds.at( majorId_ ); tprAssert( this->floorGo_mapDatas.find(id) != this->floorGo_mapDatas.end() ); return { id, &this->floorGo_mapDatas.at(id) }; } inline const std::set<VariableTypeIdx> &get_majorGo_varTypes()const noexcept{ return this->majorGo_varTypes; } inline const std::set<VariableTypeIdx> &get_floorGo_varTypes()const noexcept{ return this->floorGo_varTypes; } inline std::pair<mapDataId_t, const MapData*> apply_a_random_majorGo_mapData( size_t uWeight_ )const noexcept{ mapDataId_t id = this->majorGo_mapDataIds.at( (uWeight_+86887311) % this->majorGo_mapDataIds.size() ); return { id, &this->majorGo_mapDatas.at(id) }; } inline std::pair<mapDataId_t, const MapData*> apply_a_random_floorGo_mapData( size_t uWeight_ )const noexcept{ mapDataId_t id = this->floorGo_mapDataIds.at( (uWeight_ + 906117317) % this->floorGo_mapDataIds.size() ); return { id, &this->floorGo_mapDatas.at(id) }; } inline const VarTypeDatas_Yard_MajorGo *get_majorGo_varTypeDataPtr_Yard( VariableTypeIdx type_ )const noexcept{ tprAssert( this->majorGo_varTypeDatas.find(type_) != this->majorGo_varTypeDatas.end() ); return this->majorGo_varTypeDatas.at(type_).get(); } inline const VarTypeDatas_Yard_FloorGo *get_floorGo_varTypeDataPtr_Yard( VariableTypeIdx type_ )const noexcept{ tprAssert( this->floorGo_varTypeDatas.find(type_) != this->floorGo_varTypeDatas.end() ); return this->floorGo_varTypeDatas.at(type_).get(); } static inline std::unique_ptr<YardBlueprint> create_new_uptr()noexcept{ std::unique_ptr<YardBlueprint> uptr ( new YardBlueprint() ); // can't use std::make_unique return uptr; } private: YardBlueprint()=default; YardSize sizeByFild {}; // yard 尺寸,以 field 为单位 // major-gos std::vector<mapDataId_t> majorGo_mapDataIds {}; // 实际分配池。元素个数可能大于 帧数 std::unordered_map<mapDataId_t, MapData>majorGo_mapDatas {}; // 若干帧,每一帧数据 就是一份 分配方案 std::set<VariableTypeIdx> majorGo_varTypes {}; std::unordered_map<VariableTypeIdx, std::shared_ptr<VarTypeDatas_Yard_MajorGo>> majorGo_varTypeDatas {}; // floor-gos std::vector<mapDataId_t> floorGo_mapDataIds {}; // 实际分配池。元素个数可能大于 帧数 std::unordered_map<mapDataId_t, MapData>floorGo_mapDatas {}; // 若干帧,每一帧数据 就是一份 分配方案 std::set<VariableTypeIdx> floorGo_varTypes {}; std::unordered_map<VariableTypeIdx, std::shared_ptr<VarTypeDatas_Yard_FloorGo>> floorGo_varTypeDatas {}; //- 当同时拥有 majorGo/floorGo 数据时,两两元素是强关联的 // 此时就可以用本容器,根据 majorDataId 来寻找 floorDataId std::unordered_map<mapDataId_t, mapDataId_t> majorDataId_2_floorDataIds {}; // {majorId, floorId} //- 至少有一个为 true bool isHaveMajorGos {}; bool isHaveFloorGos {}; //======= static =======// static ID_Manager mapDataId_manager; // majorGo_mapDatas / floorGo_mapDatas 共用 }; /* "yardName" 索引到一个 set 实例 * 再根据 label/labelId 索引到一个 yardId * --- * "yardLabel" 一种简陋的 type数据 * 可以用 "" / "default" / "Default" / "DEFAULT" 来表示一种 默认类型 (它们指向同一份数据) */ class YardBlueprintSet{ using yardLabelId_t = size_t; // std::hash using yardBlueprintSetId_t = size_t; // std::hash public: using F_getYardId = std::function< std::optional<yardBlueprintId_t>(NineDirection)>; //===== static =====// static void init_for_static()noexcept;// MUST CALL IN MAIN !!! static yardBlueprintId_t init_new_yard( const std::string &yardName_, const std::string &yardLabel_, NineDirection yardDir_ ); static YardBlueprint &get_yardBlueprintRef( yardBlueprintId_t id_ )noexcept; // 仅用于 json_ecoSysPlan.cpp inline static yardBlueprintId_t get_yardBlueprintId(const std::string &yardName_, const std::string &yardLabel_, NineDirection yardDir_ )noexcept{ auto &innUMap = YardBlueprintSet::get_dir_2_yardId_umap( yardName_, yardLabel_ ); tprAssert( innUMap.find(yardDir_) != innUMap.end() ); return innUMap.at(yardDir_); } // 返回一个 函数指针,存储在 village 实例中,为了可以用它,配合 具体的 dir,来获取 yardId static F_getYardId getFunctor_getYardId(const std::string &yardName_, const std::string &yardLabel_ )noexcept{ return [ yardName_l=yardName_, yardLabel_l=yardLabel_ ]( NineDirection dir_ )->std::optional<yardBlueprintId_t>{ auto &innUMap = YardBlueprintSet::get_dir_2_yardId_umap( yardName_l, yardLabel_l ); return ( innUMap.find(dir_) == innUMap.end() ) ? std::nullopt : std::optional<yardBlueprintId_t>{ innUMap.at(dir_) }; }; } inline static bool is_find_name( const std::string &yardName_, const std::string &yardLabel_ )noexcept{ //--- yardName ---// yardBlueprintSetId_t setId = std::hash<std::string>{}( yardName_ ); if( YardBlueprintSet::setUPtrs.find(setId) == YardBlueprintSet::setUPtrs.end() ){ return false; } YardBlueprintSet &setRef = *(YardBlueprintSet::setUPtrs.at(setId)); //--- yardLabel ---// std::string yardLabel = check_and_unify_default_labels(yardLabel_); // "_DEFAULT_" yardLabelId_t yardLabelId = std::hash<std::string>{}( yardLabel ); return (setRef.yardIDs.find(yardLabelId) != setRef.yardIDs.end()); } private: YardBlueprintSet()=default; inline static std::unordered_map<NineDirection, yardBlueprintId_t> & get_dir_2_yardId_umap( const std::string &yardName_, const std::string &yardLabel_ )noexcept{ //--- yardName ---// yardBlueprintSetId_t setId = std::hash<std::string>{}( yardName_ ); tprAssert( YardBlueprintSet::setUPtrs.find(setId) != YardBlueprintSet::setUPtrs.end() ); YardBlueprintSet &setRef = *(YardBlueprintSet::setUPtrs.at(setId)); //--- yardLabel ---// std::string yardLabel = check_and_unify_default_labels(yardLabel_); // "_DEFAULT_" yardLabelId_t yardLabelId = std::hash<std::string>{}( yardLabel ); tprAssert( setRef.yardIDs.find(yardLabelId) != setRef.yardIDs.end() ); // Must existed return setRef.yardIDs.at( yardLabelId ); } // 两层索引: yardLabel, dir std::unordered_map<yardLabelId_t, std::unordered_map<NineDirection, yardBlueprintId_t>> yardIDs; //===== static =====// static ID_Manager yardId_manager; // apply yardBlueprint id static std::unordered_map<yardBlueprintSetId_t, std::unique_ptr<YardBlueprintSet>> setUPtrs; // 真实资源 static std::unordered_map<yardBlueprintId_t, std::unique_ptr<YardBlueprint>> yardUPtrs; // 真实资源 }; void parse_yardJsonFiles(); void calc_yard_fieldKeys( std::unordered_set<fieldKey_t> &outContainer_, IntVec2 yardMPos_, YardSize sizeByFild_ )noexcept; }//--------------------- namespace: blueprint end ------------------------// #endif
comfortablynick/ctodo
include/common.h
#include <fmt/format.h> #include <iostream> #include <memory> #include <stddef.h> #include <string> #include <vector> /// @brief Data structure to hold common program options struct options { std::string cmd, verbosity; bool quiet, getline; }; std::ostream& operator<<(std::ostream&, std::shared_ptr<options>); /// Data structure for terminal cols and lines struct termsize { unsigned cols, lines; }; std::shared_ptr<termsize> getTermSize(); /// Output a text representation of vector to stream. /// For pretty output, use prettify() to get string first. /// @param `out` Stream to print to /// @param `vec` Vector to print template <class T> std::ostream& operator<<(std::ostream& out, const std::vector<T>& vec) { out << '['; for (size_t i = 0; i < vec.size(); ++i) { if (i != 0) out << ", "; out << vec[i]; } out << ']'; return out; } /// Pretty print representation of vector. /// For simple debug print, use << operator on vector directly. /// @param `vec` Vector of <T> type template <class T> std::string prettify(const std::vector<T>& vec) { fmt::memory_buffer out; fmt::format_to(out, "[\n"); for (size_t i = 0; i < vec.size(); ++i) { if (i != 0) fmt::format_to(out, ",\n"); fmt::format_to(out, "{:4}: {}", i, vec[i]); } fmt::format_to(out, "\n]"); return fmt::to_string(out); } std::string prettify(int, char**); namespace Ansi { /// Value on the Ansi 256 color spectrum enum class Color : unsigned int { // std colors black = 0, blue = 12, green = 2, cyan = 37, red = 124, yellow = 142, lime = 154, lightorange = 215, gray = 245, // bright colors brcyan = 51, brred = 196, bryellow = 226, }; const std::string setFg(Ansi::Color); const std::string setFg(unsigned int); const std::string setBg(Ansi::Color); const std::string reset(); } // namespace Ansi
clayne/clib-1
test/package/package-new.c
<reponame>clayne/clib-1<filename>test/package/package-new.c #include "clib-cache.h" #include "clib-package.h" #include "describe/describe.h" #include "rimraf/rimraf.h" int main() { clib_cache_init(100); rimraf(clib_cache_dir()); describe("clib_package_new") { char json[] = "{" " \"name\": \"foo\"," " \"version\": \"1.0.0\"," " \"repo\": \"foobar/foo\"," " \"license\": \"mit\"," " \"description\": \"lots of foo\"," " \"src\": [" " \"foo.h\"," " \"foo.c\"" " ]," " \"dependencies\": {" " \"blah/blah\": \"1.2.3\"," " \"bar\": \"*\"," " \"abc/def\": \"master\"" " }" "}"; it("should return NULL when given broken json") { assert(NULL == clib_package_new("{", 0)); } it("should return NULL when given a bad string") { assert(NULL == clib_package_new(NULL, 0)); } it("should return a clib_package when given valid json") { clib_package_t *pkg = clib_package_new(json, 0); assert(pkg); assert_str_equal(json, pkg->json); assert_str_equal("foo", pkg->name); assert_str_equal("foobar", pkg->author); assert_str_equal("1.0.0", pkg->version); assert_str_equal("foobar/foo", pkg->repo); assert_str_equal("mit", pkg->license); assert_str_equal("lots of foo", pkg->description); assert(NULL == pkg->install); assert(2 == pkg->src->len); assert_str_equal("foo.h", list_at(pkg->src, 0)->val); assert_str_equal("foo.c", list_at(pkg->src, 1)->val); assert(3 == pkg->dependencies->len); clib_package_dependency_t *dep0 = list_at(pkg->dependencies, 0)->val; assert_str_equal("blah", dep0->name); assert_str_equal("1.2.3", dep0->version); clib_package_dependency_t *dep1 = list_at(pkg->dependencies, 1)->val; assert_str_equal("bar", dep1->name); assert_str_equal("master", dep1->version); clib_package_dependency_t *dep2 = list_at(pkg->dependencies, 2)->val; assert_str_equal("def", dep2->name); assert_str_equal("master", dep2->version); clib_package_free(pkg); } it("should support missing src") { char json[] = "{" " \"name\": \"foo\"," " \"version\": \"1.0.0\"," " \"repo\": \"foobar/foo\"," " \"license\": \"mit\"," " \"description\": \"lots of foo\"" "}"; clib_package_t *pkg = clib_package_new(json, 0); assert(pkg); clib_package_free(pkg); } } return assert_failures(); }
clayne/clib-1
test/package/package-parse-version.c
#include "clib-cache.h" #include "clib-package.h" #include "describe/describe.h" #include "rimraf/rimraf.h" int main() { clib_cache_init(100); rimraf(clib_cache_dir()); describe("clib_package_parse_version") { char *version = NULL; it("should return NULL when given a bad slug") { assert(NULL == clib_package_parse_version(NULL)); assert(NULL == clib_package_parse_version("")); } it("should default to \"master\"") { version = clib_package_parse_version("foo"); assert_str_equal("master", version); free(version); version = clib_package_parse_version("foo/bar"); assert_str_equal("master", version); free(version); } it("should transform \"*\" to \"master\"") { version = clib_package_parse_version("*"); assert_str_equal("master", version); free(version); version = clib_package_parse_version("foo@*"); assert_str_equal("master", version); free(version); version = clib_package_parse_version("foo/bar@*"); assert_str_equal("master", version); free(version); } it("should support \"name\"-style slugs") { version = clib_package_parse_version("foo"); assert_str_equal("master", version); free(version); } it("should support \"name@version\"-style slugs") { version = clib_package_parse_version("foo@bar"); assert_str_equal("bar", version); free(version); version = clib_package_parse_version("foo@*"); assert_str_equal("master", version); free(version); version = clib_package_parse_version("foo@1.2.3"); assert_str_equal("1.2.3", version); free(version); } it("should support \"author/name@version\"-style slugs") { version = clib_package_parse_version("foo/bar@baz"); assert_str_equal("baz", version); free(version); version = clib_package_parse_version("foo/bar@*"); assert_str_equal("master", version); free(version); version = clib_package_parse_version("foo/bar@1.2.3"); assert_str_equal("1.2.3", version); free(version); } // this was a bug in parse-repo.c... it("should not be affected after the slug is freed") { char *slug = malloc(48); assert(slug); strcpy(slug, "author/name@version"); version = clib_package_parse_version(slug); assert_str_equal("version", version); free(slug); assert_str_equal("version", version); free(version); } } return assert_failures(); }
clayne/clib-1
test/package/package-url.c
#include "clib-cache.h" #include "clib-package.h" #include "describe/describe.h" #include "rimraf/rimraf.h" int main() { clib_cache_init(100); rimraf(clib_cache_dir()); describe("clib_package_url") { it("should return NULL when given a bad author") { assert(NULL == clib_package_url(NULL, "name", "version")); } it("should return NULL when given a bad name") { assert(NULL == clib_package_url("author", NULL, "version")); } it("should return NULL when given a bad version") { assert(NULL == clib_package_url("author", "name", NULL)); } it("should build a GitHub url") { char *url = clib_package_url("author", "name", "version"); assert_str_equal("https://raw.githubusercontent.com/author/name/version", url); free(url); } } return assert_failures(); }
clayne/clib-1
test/package/package-parse-author.c
#include "clib-cache.h" #include "clib-package.h" #include "describe/describe.h" #include <string.h> #include "rimraf/rimraf.h" int main() { clib_cache_init(100); rimraf(clib_cache_dir()); describe("clib_package_parse_author") { char *author = NULL; it("should return NULL when given a bad slug") { assert(NULL == clib_package_parse_author(NULL)); } it("should return NULL when unable to parse an author") { assert(NULL == clib_package_parse_author("/")); assert(NULL == clib_package_parse_author("/name")); assert(NULL == clib_package_parse_author("/name@version")); } it("should default to \"clibs\"") { author = clib_package_parse_author("foo"); assert_str_equal("clibs", author); free(author); } it("should support \"author/name\"-style slugs") { author = clib_package_parse_author("author/name"); assert_str_equal("author", author); free(author); } it("should support \"author/name@version\"-slugs slugs") { author = clib_package_parse_author("author/name@master"); assert_str_equal("author", author); free(author); author = clib_package_parse_author("author/name@*"); assert_str_equal("author", author); free(author); } // this was a bug in parse-repo.c... it("should not be affected after the slug is freed") { char *slug = malloc(48); assert(slug); strcpy(slug, "author/name@version"); author = clib_package_parse_author(slug); assert_str_equal("author", author); free(slug); assert_str_equal("author", author); free(author); } } return assert_failures(); }
clayne/clib-1
test/package/package-load-from-manifest.c
#include "clib-cache.h" #include "clib-package.h" #include "describe/describe.h" #include "rimraf/rimraf.h" int main() { clib_cache_init(100); rimraf(clib_cache_dir()); describe("clib_package_load_from_manifest") { it("should load a package from a file if available") { int verbose = 0; clib_package_t *pkg = clib_package_load_from_manifest("./clib.json", verbose); assert(NULL != pkg); if (pkg) { clib_package_free(pkg); } } } return assert_failures(); }
lliunix/rt-thread
bsp/raspberry-pico/libcpu/cpuport_smp.c
<filename>bsp/raspberry-pico/libcpu/cpuport_smp.c #include <rthw.h> #include <rtthread.h> #ifdef RT_USING_SMP #include "hardware/structs/sio.h" #include "hardware/irq.h" #include "hardware/sync.h" #include "pico/multicore.h" #include "board.h" #include "hardware/structs/systick.h" int rt_hw_cpu_id(void) { return sio_hw->cpuid; } void rt_hw_spin_lock_init(rt_hw_spinlock_t *lock) { static int spin_num = 0; if ( spin_num < 32 ) { lock->slock = (rt_uint32_t)spin_lock_instance(spin_num); spin_num = spin_num + 1; } } void rt_hw_spin_lock(rt_hw_spinlock_t *lock) { spin_lock_unsafe_blocking((spin_lock_t *)lock->slock); } void rt_hw_spin_unlock(rt_hw_spinlock_t *lock) { spin_unlock_unsafe((spin_lock_t *)lock->slock); } void secondary_cpu_c_start(void) { irq_set_enabled(SIO_IRQ_PROC1,RT_TRUE); systick_config(frequency_count_khz(CLOCKS_FC0_SRC_VALUE_ROSC_CLKSRC)*10000/RT_TICK_PER_SECOND); rt_hw_spin_lock(&_cpus_lock); rt_system_scheduler_start(); } void rt_hw_secondary_cpu_up(void) { multicore_launch_core1(secondary_cpu_c_start); irq_set_enabled(SIO_IRQ_PROC0,RT_TRUE); } void rt_hw_secondary_cpu_idle_exec(void) { asm volatile ("wfi"); } #define IPI_MAGIC 0x5a5a void rt_hw_ipi_send(int ipi_vector, unsigned int cpu_mask) { sio_hw->fifo_wr = IPI_MAGIC; } void rt_hw_ipi_handler(void) { uint32_t status = sio_hw->fifo_st; if ( status & (SIO_FIFO_ST_ROE_BITS | SIO_FIFO_ST_WOF_BITS) ) { sio_hw->fifo_st = 0; } if ( status & SIO_FIFO_ST_VLD_BITS ) { if ( sio_hw->fifo_rd == IPI_MAGIC ) { rt_schedule(); } } } void isr_irq15(void) { rt_hw_ipi_handler(); } void isr_irq16(void) { rt_hw_ipi_handler(); } /*======================================================================================*/ struct __thread_switch_status { uint32_t from; uint32_t to; uint32_t flag; }_thread_switch_array[2]; extern void rt_cpus_lock_status_restore(struct rt_thread *thread); void thread_switch_status_store(uint32_t from, uint32_t to, rt_thread_t thread) { int cpu_id = sio_hw->cpuid; if ( _thread_switch_array[cpu_id].flag == 0) { _thread_switch_array[cpu_id].from = from; _thread_switch_array[cpu_id].flag = 1; } _thread_switch_array[cpu_id].to = to; if ( from != 0 ) { rt_thread_t currrent_cpu_thread = rt_thread_self(); thread->cpus_lock_nest = currrent_cpu_thread->cpus_lock_nest; thread->scheduler_lock_nest = currrent_cpu_thread->scheduler_lock_nest; thread->critical_lock_nest = currrent_cpu_thread->critical_lock_nest; } rt_cpus_lock_status_restore(thread); } uint32_t thread_switch_status_check(void) { int cpu_id = sio_hw->cpuid; if ( _thread_switch_array[cpu_id].flag == 0) { return 0; } _thread_switch_array[cpu_id].flag = 0; return (uint32_t)(&_thread_switch_array[cpu_id]); } #endif /*RT_USING_SMP*/
amdprophet/WS2812FX
WS2812FX.h
<gh_stars>1-10 /* WS2812FX.h - Library for WS2812 LED effects. <NAME> - 2016 www.aldick.org FEATURES * A lot of blinken modes and counting * WS2812FX can be used as drop-in replacement for Adafruit NeoPixel Library NOTES * Uses the Adafruit NeoPixel library. Get it here: https://github.com/adafruit/Adafruit_NeoPixel LICENSE The MIT License (MIT) Copyright (c) 2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. CHANGELOG 2016-05-28 Initial beta release 2016-06-03 Code cleanup, minor improvements, new modes 2016-06-04 2 new fx, fixed setColor (now also resets _mode_color) 2017-02-02 added external trigger functionality (e.g. for sound-to-light) */ #ifndef WS2812FX_h #define WS2812FX_h #include <Adafruit_NeoPixel.h> #define DEFAULT_BRIGHTNESS 50 #define DEFAULT_MODE 0 #define DEFAULT_SPEED 1000 #define DEFAULT_COLOR 0xFF0000 #define SPEED_MIN 10 #define SPEED_MAX 65535 #define BRIGHTNESS_MIN 0 #define BRIGHTNESS_MAX 255 /* each segment uses 36 bytes of SRAM memory, so if you're application fails because of insufficient memory, decreasing MAX_NUM_SEGMENTS may help */ #define MAX_NUM_SEGMENTS 10 #define NUM_COLORS 3 /* number of colors per segment */ #define SEGMENT _segments[_segment_index] #define SEGMENT_RUNTIME _segment_runtimes[_segment_index] #define SEGMENT_LENGTH (SEGMENT.stop - SEGMENT.start + 1) #define RESET_RUNTIME memset(_segment_runtimes, 0, sizeof(_segment_runtimes)) // some common colors #define RED 0xFF0000 #define GREEN 0x00FF00 #define BLUE 0x0000FF #define WHITE 0xFFFFFF #define BLACK 0x000000 #define YELLOW 0xFFFF00 #define CYAN 0x00FFFF #define MAGENTA 0xFF00FF #define PURPLE 0x400080 #define ORANGE 0xFF3000 #define ULTRAWHITE 0xFFFFFFFF #define MODE_COUNT 57 #define FX_MODE_STATIC 0 #define FX_MODE_BLINK 1 #define FX_MODE_BREATH 2 #define FX_MODE_COLOR_WIPE 3 #define FX_MODE_COLOR_WIPE_INV 4 #define FX_MODE_COLOR_WIPE_REV 5 #define FX_MODE_COLOR_WIPE_REV_INV 6 #define FX_MODE_COLOR_WIPE_RANDOM 7 #define FX_MODE_RANDOM_COLOR 8 #define FX_MODE_SINGLE_DYNAMIC 9 #define FX_MODE_MULTI_DYNAMIC 10 #define FX_MODE_RAINBOW 11 #define FX_MODE_RAINBOW_CYCLE 12 #define FX_MODE_SCAN 13 #define FX_MODE_DUAL_SCAN 14 #define FX_MODE_FADE 15 #define FX_MODE_THEATER_CHASE 16 #define FX_MODE_THEATER_CHASE_RAINBOW 17 #define FX_MODE_RUNNING_LIGHTS 18 #define FX_MODE_TWINKLE 19 #define FX_MODE_TWINKLE_RANDOM 20 #define FX_MODE_TWINKLE_FADE 21 #define FX_MODE_TWINKLE_FADE_RANDOM 22 #define FX_MODE_SPARKLE 23 #define FX_MODE_FLASH_SPARKLE 24 #define FX_MODE_HYPER_SPARKLE 25 #define FX_MODE_STROBE 26 #define FX_MODE_STROBE_RAINBOW 27 #define FX_MODE_MULTI_STROBE 28 #define FX_MODE_BLINK_RAINBOW 29 #define FX_MODE_CHASE_WHITE 30 #define FX_MODE_CHASE_COLOR 31 #define FX_MODE_CHASE_RANDOM 32 #define FX_MODE_CHASE_RAINBOW 33 #define FX_MODE_CHASE_FLASH 34 #define FX_MODE_CHASE_FLASH_RANDOM 35 #define FX_MODE_CHASE_RAINBOW_WHITE 36 #define FX_MODE_CHASE_BLACKOUT 37 #define FX_MODE_CHASE_BLACKOUT_RAINBOW 38 #define FX_MODE_COLOR_SWEEP_RANDOM 39 #define FX_MODE_RUNNING_COLOR 40 #define FX_MODE_RUNNING_RED_BLUE 41 #define FX_MODE_RUNNING_RANDOM 42 #define FX_MODE_LARSON_SCANNER 43 #define FX_MODE_COMET 44 #define FX_MODE_FIREWORKS 45 #define FX_MODE_FIREWORKS_RANDOM 46 #define FX_MODE_MERRY_CHRISTMAS 47 #define FX_MODE_FIRE_FLICKER 48 #define FX_MODE_FIRE_FLICKER_SOFT 49 #define FX_MODE_FIRE_FLICKER_INTENSE 50 #define FX_MODE_CIRCUS_COMBUSTUS 51 #define FX_MODE_HALLOWEEN 52 #define FX_MODE_BICOLOR_CHASE 53 #define FX_MODE_TRICOLOR_CHASE 54 #define FX_MODE_ICU 55 #define FX_MODE_CUSTOM 56 class WS2812FX : public Adafruit_NeoPixel { typedef uint16_t (WS2812FX::*mode_ptr)(void); // segment parameters public: typedef struct Segment { // 20 bytes uint16_t start; uint16_t stop; uint16_t speed; uint8_t mode; bool reverse; uint32_t colors[NUM_COLORS]; } segment; // segment runtime parameters public: typedef struct Segment_runtime { // 16 bytes unsigned long next_time; uint32_t counter_mode_step; uint32_t counter_mode_call; uint16_t aux_param; uint16_t aux_param2; } segment_runtime; public: WS2812FX(uint16_t n, uint8_t p, neoPixelType t) : Adafruit_NeoPixel(n, p, t) { _mode[FX_MODE_STATIC] = &WS2812FX::mode_static; _mode[FX_MODE_BLINK] = &WS2812FX::mode_blink; _mode[FX_MODE_COLOR_WIPE] = &WS2812FX::mode_color_wipe; _mode[FX_MODE_COLOR_WIPE_INV] = &WS2812FX::mode_color_wipe_inv; _mode[FX_MODE_COLOR_WIPE_REV] = &WS2812FX::mode_color_wipe_rev; _mode[FX_MODE_COLOR_WIPE_REV_INV] = &WS2812FX::mode_color_wipe_rev_inv; _mode[FX_MODE_COLOR_WIPE_RANDOM] = &WS2812FX::mode_color_wipe_random; _mode[FX_MODE_RANDOM_COLOR] = &WS2812FX::mode_random_color; _mode[FX_MODE_SINGLE_DYNAMIC] = &WS2812FX::mode_single_dynamic; _mode[FX_MODE_MULTI_DYNAMIC] = &WS2812FX::mode_multi_dynamic; _mode[FX_MODE_RAINBOW] = &WS2812FX::mode_rainbow; _mode[FX_MODE_RAINBOW_CYCLE] = &WS2812FX::mode_rainbow_cycle; _mode[FX_MODE_SCAN] = &WS2812FX::mode_scan; _mode[FX_MODE_DUAL_SCAN] = &WS2812FX::mode_dual_scan; _mode[FX_MODE_FADE] = &WS2812FX::mode_fade; _mode[FX_MODE_THEATER_CHASE] = &WS2812FX::mode_theater_chase; _mode[FX_MODE_THEATER_CHASE_RAINBOW] = &WS2812FX::mode_theater_chase_rainbow; _mode[FX_MODE_TWINKLE] = &WS2812FX::mode_twinkle; _mode[FX_MODE_TWINKLE_RANDOM] = &WS2812FX::mode_twinkle_random; _mode[FX_MODE_TWINKLE_FADE] = &WS2812FX::mode_twinkle_fade; _mode[FX_MODE_TWINKLE_FADE_RANDOM] = &WS2812FX::mode_twinkle_fade_random; _mode[FX_MODE_SPARKLE] = &WS2812FX::mode_sparkle; _mode[FX_MODE_FLASH_SPARKLE] = &WS2812FX::mode_flash_sparkle; _mode[FX_MODE_HYPER_SPARKLE] = &WS2812FX::mode_hyper_sparkle; _mode[FX_MODE_STROBE] = &WS2812FX::mode_strobe; _mode[FX_MODE_STROBE_RAINBOW] = &WS2812FX::mode_strobe_rainbow; _mode[FX_MODE_MULTI_STROBE] = &WS2812FX::mode_multi_strobe; _mode[FX_MODE_BLINK_RAINBOW] = &WS2812FX::mode_blink_rainbow; _mode[FX_MODE_CHASE_WHITE] = &WS2812FX::mode_chase_white; _mode[FX_MODE_CHASE_COLOR] = &WS2812FX::mode_chase_color; _mode[FX_MODE_CHASE_RANDOM] = &WS2812FX::mode_chase_random; _mode[FX_MODE_CHASE_RAINBOW] = &WS2812FX::mode_chase_rainbow; _mode[FX_MODE_CHASE_FLASH] = &WS2812FX::mode_chase_flash; _mode[FX_MODE_CHASE_FLASH_RANDOM] = &WS2812FX::mode_chase_flash_random; _mode[FX_MODE_CHASE_RAINBOW_WHITE] = &WS2812FX::mode_chase_rainbow_white; _mode[FX_MODE_CHASE_BLACKOUT] = &WS2812FX::mode_chase_blackout; _mode[FX_MODE_CHASE_BLACKOUT_RAINBOW] = &WS2812FX::mode_chase_blackout_rainbow; _mode[FX_MODE_COLOR_SWEEP_RANDOM] = &WS2812FX::mode_color_sweep_random; _mode[FX_MODE_RUNNING_COLOR] = &WS2812FX::mode_running_color; _mode[FX_MODE_RUNNING_RED_BLUE] = &WS2812FX::mode_running_red_blue; _mode[FX_MODE_RUNNING_RANDOM] = &WS2812FX::mode_running_random; _mode[FX_MODE_LARSON_SCANNER] = &WS2812FX::mode_larson_scanner; _mode[FX_MODE_COMET] = &WS2812FX::mode_comet; _mode[FX_MODE_FIREWORKS] = &WS2812FX::mode_fireworks; _mode[FX_MODE_FIREWORKS_RANDOM] = &WS2812FX::mode_fireworks_random; _mode[FX_MODE_MERRY_CHRISTMAS] = &WS2812FX::mode_merry_christmas; _mode[FX_MODE_HALLOWEEN] = &WS2812FX::mode_halloween; _mode[FX_MODE_FIRE_FLICKER] = &WS2812FX::mode_fire_flicker; _mode[FX_MODE_FIRE_FLICKER_SOFT] = &WS2812FX::mode_fire_flicker_soft; _mode[FX_MODE_FIRE_FLICKER_INTENSE] = &WS2812FX::mode_fire_flicker_intense; _mode[FX_MODE_CIRCUS_COMBUSTUS] = &WS2812FX::mode_circus_combustus; _mode[FX_MODE_BICOLOR_CHASE] = &WS2812FX::mode_bicolor_chase; _mode[FX_MODE_TRICOLOR_CHASE] = &WS2812FX::mode_tricolor_chase; // if flash memory is constrained (I'm looking at you Arduino Nano), replace modes // that use a lot of flash with mode_static (reduces flash footprint by about 3600 bytes) #ifdef REDUCED_MODES _mode[FX_MODE_BREATH] = &WS2812FX::mode_static; _mode[FX_MODE_RUNNING_LIGHTS] = &WS2812FX::mode_static; _mode[FX_MODE_ICU] = &WS2812FX::mode_static; #else _mode[FX_MODE_BREATH] = &WS2812FX::mode_breath; _mode[FX_MODE_RUNNING_LIGHTS] = &WS2812FX::mode_running_lights; _mode[FX_MODE_ICU] = &WS2812FX::mode_icu; #endif _mode[FX_MODE_CUSTOM] = &WS2812FX::mode_custom; _name[FX_MODE_STATIC] = F("Static"); _name[FX_MODE_BLINK] = F("Blink"); _name[FX_MODE_BREATH] = F("Breath"); _name[FX_MODE_COLOR_WIPE] = F("Color Wipe"); _name[FX_MODE_COLOR_WIPE_INV ] = F("Color Wipe Inverse"); _name[FX_MODE_COLOR_WIPE_REV] = F("Color Wipe Reverse"); _name[FX_MODE_COLOR_WIPE_REV_INV] = F("Color Wipe Reverse Inverse"); _name[FX_MODE_COLOR_WIPE_RANDOM] = F("Color Wipe Random"); _name[FX_MODE_RANDOM_COLOR] = F("Random Color"); _name[FX_MODE_SINGLE_DYNAMIC] = F("Single Dynamic"); _name[FX_MODE_MULTI_DYNAMIC] = F("Multi Dynamic"); _name[FX_MODE_RAINBOW] = F("Rainbow"); _name[FX_MODE_RAINBOW_CYCLE] = F("Rainbow Cycle"); _name[FX_MODE_SCAN] = F("Scan"); _name[FX_MODE_DUAL_SCAN] = F("Dual Scan"); _name[FX_MODE_FADE] = F("Fade"); _name[FX_MODE_THEATER_CHASE] = F("Theater Chase"); _name[FX_MODE_THEATER_CHASE_RAINBOW] = F("Theater Chase Rainbow"); _name[FX_MODE_RUNNING_LIGHTS] = F("Running Lights"); _name[FX_MODE_TWINKLE] = F("Twinkle"); _name[FX_MODE_TWINKLE_RANDOM] = F("Twinkle Random"); _name[FX_MODE_TWINKLE_FADE] = F("Twinkle Fade"); _name[FX_MODE_TWINKLE_FADE_RANDOM] = F("Twinkle Fade Random"); _name[FX_MODE_SPARKLE] = F("Sparkle"); _name[FX_MODE_FLASH_SPARKLE] = F("Flash Sparkle"); _name[FX_MODE_HYPER_SPARKLE] = F("Hyper Sparkle"); _name[FX_MODE_STROBE] = F("Strobe"); _name[FX_MODE_STROBE_RAINBOW] = F("Strobe Rainbow"); _name[FX_MODE_MULTI_STROBE] = F("Multi Strobe"); _name[FX_MODE_BLINK_RAINBOW] = F("Blink Rainbow"); _name[FX_MODE_CHASE_WHITE] = F("Chase White"); _name[FX_MODE_CHASE_COLOR] = F("Chase Color"); _name[FX_MODE_CHASE_RANDOM] = F("Chase Random"); _name[FX_MODE_CHASE_RAINBOW] = F("Chase Rainbow"); _name[FX_MODE_CHASE_FLASH] = F("Chase Flash"); _name[FX_MODE_CHASE_FLASH_RANDOM] = F("Chase Flash Random"); _name[FX_MODE_CHASE_RAINBOW_WHITE] = F("Chase Rainbow White"); _name[FX_MODE_CHASE_BLACKOUT] = F("Chase Blackout"); _name[FX_MODE_CHASE_BLACKOUT_RAINBOW] = F("Chase Blackout Rainbow"); _name[FX_MODE_COLOR_SWEEP_RANDOM] = F("Color Sweep Random"); _name[FX_MODE_RUNNING_COLOR] = F("Running Color"); _name[FX_MODE_RUNNING_RED_BLUE] = F("Running Red Blue"); _name[FX_MODE_RUNNING_RANDOM] = F("Running Random"); _name[FX_MODE_LARSON_SCANNER] = F("Larson Scanner"); _name[FX_MODE_COMET] = F("Comet"); _name[FX_MODE_FIREWORKS] = F("Fireworks"); _name[FX_MODE_FIREWORKS_RANDOM] = F("Fireworks Random"); _name[FX_MODE_MERRY_CHRISTMAS] = F("Merry Christmas"); _name[FX_MODE_HALLOWEEN] = F("Halloween"); _name[FX_MODE_FIRE_FLICKER] = F("Fire Flicker"); _name[FX_MODE_FIRE_FLICKER_SOFT] = F("Fire Flicker (soft)"); _name[FX_MODE_FIRE_FLICKER_INTENSE] = F("Fire Flicker (intense)"); _name[FX_MODE_CIRCUS_COMBUSTUS] = F("Circus Combustus"); _name[FX_MODE_BICOLOR_CHASE] = F("Bicolor Chase"); _name[FX_MODE_TRICOLOR_CHASE] = F("Tricolor Chase"); _name[FX_MODE_ICU] = F("ICU"); _name[FX_MODE_CUSTOM] = F("Custom"); _brightness = DEFAULT_BRIGHTNESS; _running = false; _num_segments = 1; _segments[0].mode = DEFAULT_MODE; _segments[0].colors[0] = DEFAULT_COLOR; _segments[0].start = 0; _segments[0].stop = n - 1; _segments[0].speed = DEFAULT_SPEED; RESET_RUNTIME; } void init(void), service(void), start(void), stop(void), setMode(uint8_t m), setCustomMode(uint16_t (*p)()), setSpeed(uint16_t s), increaseSpeed(uint8_t s), decreaseSpeed(uint8_t s), setColor(uint8_t r, uint8_t g, uint8_t b), setColor(uint32_t c), setBrightness(uint8_t b), increaseBrightness(uint8_t s), decreaseBrightness(uint8_t s), setLength(uint16_t b), increaseLength(uint16_t s), decreaseLength(uint16_t s), trigger(void), setNumSegments(uint8_t n), setSegment(uint8_t n, uint16_t start, uint16_t stop, uint8_t mode, uint32_t color, uint16_t speed, bool reverse), setSegment(uint8_t n, uint16_t start, uint16_t stop, uint8_t mode, const uint32_t colors[], uint16_t speed, bool reverse), resetSegments(); boolean isRunning(void); uint8_t getMode(void), getBrightness(void), getModeCount(void), getNumSegments(void); uint16_t getSpeed(void), getLength(void); uint32_t color_wheel(uint8_t), getColor(void); const __FlashStringHelper* getModeName(uint8_t m); WS2812FX::Segment getSegment(void); WS2812FX::Segment_runtime getSegmentRuntime(void); WS2812FX::Segment* getSegments(void); private: void strip_off(void), fade_out(void); uint16_t mode_static(void), blink(uint32_t, uint32_t, bool strobe), mode_blink(void), mode_blink_rainbow(void), mode_strobe(void), mode_strobe_rainbow(void), color_wipe(uint32_t, uint32_t, bool), mode_color_wipe(void), mode_color_wipe_inv(void), mode_color_wipe_rev(void), mode_color_wipe_rev_inv(void), mode_color_wipe_random(void), mode_color_sweep_random(void), mode_random_color(void), mode_single_dynamic(void), mode_multi_dynamic(void), mode_breath(void), mode_fade(void), mode_scan(void), mode_dual_scan(void), theater_chase(uint32_t, uint32_t), mode_theater_chase(void), mode_theater_chase_rainbow(void), mode_rainbow(void), mode_rainbow_cycle(void), mode_running_lights(void), twinkle(uint32_t), mode_twinkle(void), mode_twinkle_random(void), twinkle_fade(uint32_t), mode_twinkle_fade(void), mode_twinkle_fade_random(void), mode_sparkle(void), mode_flash_sparkle(void), mode_hyper_sparkle(void), mode_multi_strobe(void), chase(uint32_t, uint32_t, uint32_t), mode_chase_white(void), mode_chase_color(void), mode_chase_random(void), mode_chase_rainbow(void), mode_chase_flash(void), mode_chase_flash_random(void), mode_chase_rainbow_white(void), mode_chase_blackout(void), mode_chase_blackout_rainbow(void), running(uint32_t, uint32_t), mode_running_color(void), mode_running_red_blue(void), mode_running_random(void), mode_larson_scanner(void), mode_comet(void), fireworks(uint32_t), mode_fireworks(void), mode_fireworks_random(void), mode_merry_christmas(void), mode_halloween(void), mode_fire_flicker(void), mode_fire_flicker_soft(void), mode_fire_flicker_intense(void), fire_flicker(int), mode_circus_combustus(void), tricolor_chase(uint32_t, uint32_t, uint32_t), mode_bicolor_chase(void), mode_tricolor_chase(void), mode_icu(void), mode_custom(void); boolean _running, _triggered; uint8_t get_random_wheel_index(uint8_t), _brightness; const __FlashStringHelper* _name[MODE_COUNT]; // SRAM footprint: 2 bytes per element mode_ptr _mode[MODE_COUNT]; // SRAM footprint: 4 bytes per element uint8_t _segment_index = 0; uint8_t _num_segments = 1; segment _segments[MAX_NUM_SEGMENTS] = { // SRAM footprint: 20 bytes per element // start, stop, speed, mode, reverse, color[] { 0, 7, DEFAULT_SPEED, FX_MODE_STATIC, false, {DEFAULT_COLOR}} }; segment_runtime _segment_runtimes[MAX_NUM_SEGMENTS]; // SRAM footprint: 16 bytes per element }; #endif
legokit/LEGONavigationController
LEGONavigationController/Classes/LEGONavigationView+StausBarClick.h
// // LEGONavigationView+StausBarClick.h // FilmCamera // // Created by 杨庆人 on 2019/6/1. // Copyright © 2019年 The last stand. All rights reserved. // #import "LEGONavigationView.h" typedef void(^stausbarClickCallback)(void); NS_ASSUME_NONNULL_BEGIN @interface LEGONavigationView (StausBarClick) - (void)addStausBarClickCallback:(stausbarClickCallback)callback; @end NS_ASSUME_NONNULL_END
legokit/LEGONavigationController
LEGONavigationController/Classes/LEGONavigationController.h
// // LEGONavigationController.h // FilmCamera // // Created by 杨庆人 on 2019/5/31. // Copyright © 2019年 The last stand. All rights reserved. // #import <UIKit/UIKit.h> #import "LEGONavigation.h" NS_ASSUME_NONNULL_BEGIN @interface LEGONavigationController : UINavigationController @end NS_ASSUME_NONNULL_END
legokit/LEGONavigationController
Example/Pods/Target Support Files/LEGONavigationController/LEGONavigationController-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "LEGONavigation.h" #import "LEGONavigationController.h" #import "LEGONavigationUtils.h" #import "LEGONavigationView+NavigationItem.h" #import "LEGONavigationView+StausBarClick.h" #import "LEGONavigationView.h" #import "UIView+LEGONavigationExt.h" #import "UIViewController+LEGONavigationView.h" FOUNDATION_EXPORT double LEGONavigationControllerVersionNumber; FOUNDATION_EXPORT const unsigned char LEGONavigationControllerVersionString[];
legokit/LEGONavigationController
LEGONavigationController/Classes/LEGONavigation.h
<reponame>legokit/LEGONavigationController<gh_stars>0 // // LEGONavigation.h // FilmCamera // // Created by 杨庆人 on 2019/5/31. // Copyright © 2019年 The last stand. All rights reserved. // #ifndef LEGONavigation_h #define LEGONavigation_h #import "LEGONavigationUtils.h" #import "LEGONavigationController.h" #import "LEGONavigationView.h" #import "UIViewController+LEGONavigationView.h" #import "LEGONavigationView+NavigationItem.h" #import "LEGONavigationView+StausBarClick.h" #import "UIView+LEGONavigationExt.h" #endif /* LEGONavigation_h */
legokit/LEGONavigationController
LEGONavigationController/Classes/LEGONavigationView+NavigationItem.h
<reponame>legokit/LEGONavigationController<filename>LEGONavigationController/Classes/LEGONavigationView+NavigationItem.h<gh_stars>0 // // LEGONavigationView+NavigationItem.h // FilmCamera // // Created by 杨庆人 on 2019/6/1. // Copyright © 2019年 The last stand. All rights reserved. // #import "LEGONavigationView.h" @interface LEGONavigationView (NavigationItem) /** 添加自定义view,不更改布局信息 */ - (UIView *)addCustomView:(__kindof UIView *)customView clickCallBack:(itemCallback)callback; /** 添加titleView,内部自动适配 iPhone X */ - (void)addTitleView:(UIView *)titleView; /** 添加左部按钮 */ - (LEGONavigationButton *)addLeftButtonWithTitle:(NSString *)title clickCallBack:(itemCallback)callback; - (LEGONavigationButton *)addLeftButtonWithTitle:(NSString *)title image:(UIImage *)image clickCallBack:(itemCallback)callback; - (LEGONavigationButton *)addLeftButtonWithImage:(UIImage *)image clickCallBack:(itemCallback)callback; /** 添加右部按钮 */ - (LEGONavigationButton *)addRightButtonWithTitle:(NSString *)title clickCallBack:(itemCallback)callback; - (LEGONavigationButton *)addRightButtonWithTitle:(NSString *)title image:(UIImage *)image clickCallBack:(itemCallback)callback; - (LEGONavigationButton *)addRightButtonWithImage:(UIImage *)image clickCallBack:(itemCallback)callback; @end
legokit/LEGONavigationController
LEGONavigationController/Classes/LEGONavigationUtils.h
<gh_stars>0 // // LEGONavigationUtils.h // FilmCamera // // Created by 杨庆人 on 2019/5/31. // Copyright © 2019年 The last stand. All rights reserved. // #ifndef LEGONavigationUtils_h #define LEGONavigationUtils_h #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #define IS_IPHONE_X \ ({BOOL isPhoneX = NO;\ if (@available(iOS 11.0, *)) {\ isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\ }\ (isPhoneX);}) #define NavigationMargan (IS_IPHONE_X ? 40.0 : 0) #define NavigationHeightWithoutMargan (IS_IPHONE_X ? 70 : 64) #define NavigationHeight (NavigationMargan + NavigationHeightWithoutMargan) #endif /* LEGONavigationUtils_h */
legokit/LEGONavigationController
LEGONavigationController/Classes/UIViewController+LEGONavigationView.h
// // UIViewController+LBNavigationView.h // FilmCamera // // Created by 杨庆人 on 2019/5/31. // Copyright © 2019年 The last stand. All rights reserved. // #import <UIKit/UIKit.h> #import "LEGONavigation.h" NS_ASSUME_NONNULL_BEGIN @interface UIViewController (LBNavigationView) /** * 当前的导航条(首次调用该 getter 方法则添加到当前 ViewController) */ @property (nonatomic, strong) LEGONavigationView *navigationView; /** * 当前控制器 是否 禁止侧滑返回 */ @property (nonatomic, assign) BOOL disableSlidingBackGesture; @end NS_ASSUME_NONNULL_END
legokit/LEGONavigationController
LEGONavigationController/Classes/LEGONavigationView.h
<reponame>legokit/LEGONavigationController<filename>LEGONavigationController/Classes/LEGONavigationView.h<gh_stars>0 // // LEGONavigationView.h // FilmCamera // // Created by 杨庆人 on 2019/6/1. // Copyright © 2019年 The last stand. All rights reserved. // #import <UIKit/UIKit.h> @class LEGONavigationButton; typedef void(^itemCallback)(__kindof UIView * _Nullable view); NS_ASSUME_NONNULL_BEGIN @interface LEGONavigationView : UIView @property (nonatomic, strong) UILabel *titleLabel; @property (nonatomic, strong) UIView *titleView; @property (nonatomic, strong) LEGONavigationButton *leftButton; @property (nonatomic, strong) LEGONavigationButton *rightButton; - (void)setTitle:(NSString *)title; - (void)setAttributedTitle:(NSAttributedString *)attributedTitle; @end @interface LEGONavigationButton : UIButton @property (nonatomic, copy) itemCallback callback; + (instancetype)buttonWithTitle:(NSString *)title image:(UIImage *)image; @end NS_ASSUME_NONNULL_END
roatis2/IoT
demos/st/stm32l475_discovery/common/application_code/sensor_data.c
<filename>demos/st/stm32l475_discovery/common/application_code/sensor_data.c /** ****************************************************************************** * @file sensor_data.c * @author MCD Application Team * @version V1.0.0 * @date 13-Feb-2019 * @brief A simple example demonstration how to publish sensor data to AWS. * * It creates an MQTT client that publishes sensor data to the MQTT topic * at regular intervals. * * The user can subscribe to "freertos/demos/sensors/<thing_name>" topic * from the AWS IoT Console to see the sensor reports as they arrive. * * The demo uses a single task. The task implemented by * prvMQTTConnectAndPublishTask() creates the MQTT client, subscribes to * the broker specified by the clientcredentialMQTT_BROKER_ENDPOINT * constant, performs the publish operations, and cleans up all the used * resources after a minute of operation. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution 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 other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS 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. * ****************************************************************************** */ /* Standard includes. */ #include "string.h" #include "stdio.h" /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" /* MQTT includes. */ #include "aws_mqtt_agent.h" /* Credentials includes. */ #include "aws_clientcredential.h" /* Demo includes. */ #include "aws_demo_config.h" #include "stm32l475e_iot01_accelero.h" #include "stm32l475e_iot01_psensor.h" #include "stm32l475e_iot01_gyro.h" #include "stm32l475e_iot01_hsensor.h" #include "stm32l475e_iot01_tsensor.h" #include "stm32l475e_iot01_magneto.h" /** * @brief MQTT client ID. * * It must be unique per MQTT broker. */ #define pubCLIENT_ID ( ( const uint8_t * ) clientcredentialIOT_THING_NAME ) /** * @brief The topic that the MQTT client both subscribes and publishes to. */ #define pubTOPIC_NAME ( ( const uint8_t * ) "freertos/demos/sensors/" clientcredentialIOT_THING_NAME) /** * @brief Dimension of the character array buffers used to hold data (strings in * this case) that is published to and received from the MQTT broker (in the cloud). */ #define pubMAX_DATA_LENGTH 256 /* MQTT publish task parameters. */ #define democonfigMQTT_PUB_TASK_STACK_SIZE ( 512 ) /* Stack size in words */ #define democonfigMQTT_PUB_TASK_PRIORITY ( tskIDLE_PRIORITY ) #define democonfigSAMPLING_DELAY_SECONDS ( 5 ) #define democonfigITERATE_FOREVER ( 1 ) /* Set to zero to iterate for one minute only */ /* Timeout used when establishing a connection, which required TLS * negotiation. */ #define democonfigMQTT_PUB_TLS_NEGOTIATION_TIMEOUT pdMS_TO_TICKS( 12000 ) /* Timeout used when performing MQTT operations that do not need extra time * to perform a TLS negotiation. */ #define democonfigMQTT_TIMEOUT pdMS_TO_TICKS( 2500 ) /*-----------------------------------------------------------*/ /** * @brief Implements the task that connects to and then publishes messages to the * MQTT broker. * * Messages are published every five seconds for a minute. * * @param[in] pvParameters Parameters passed while creating the task. Unused in our * case. */ static void prvMQTTConnectAndPublishTask( void * pvParameters ); /** * @brief Creates an MQTT client and then connects to the MQTT broker. * * The MQTT broker end point is set by clientcredentialMQTT_BROKER_ENDPOINT. * * @return pdPASS if everything is successful, pdFAIL otherwise. */ static BaseType_t prvCreateClientAndConnectToBroker( void ); /** * @brief Publishes the next message to the pubTOPIC_NAME topic. * * This is called every five seconds to publish the next message. * */ static void prvPublishNextMessage( void ); /*-----------------------------------------------------------*/ /** * @ brief The handle of the MQTT client object */ static MQTTAgentHandle_t xMQTTHandle = NULL; /*-----------------------------------------------------------*/ static BaseType_t prvCreateClientAndConnectToBroker( void ) { MQTTAgentReturnCode_t xReturned; BaseType_t xReturn = pdFAIL; MQTTAgentConnectParams_t xConnectParameters = { clientcredentialMQTT_BROKER_ENDPOINT, /* The URL of the MQTT broker to connect to. */ democonfigMQTT_AGENT_CONNECT_FLAGS, /* Connection flags. */ pdFALSE, /* Deprecated. */ clientcredentialMQTT_BROKER_PORT, /* Port number on which the MQTT broker is listening. */ pubCLIENT_ID, /* Client Identifier of the MQTT client. It should be unique per broker. */ 0, /* The length of the client Id, filled in later as not const. */ pdFALSE, /* Deprecated. */ NULL, /* User data supplied to the callback. Can be NULL. */ NULL, /* Callback used to report various events. Can be NULL. */ NULL, /* Certificate used for secure connection. Can be NULL. */ 0 /* Size of certificate used for secure connection. */ }; /* Check this function has not already been executed. */ configASSERT( xMQTTHandle == NULL ); /* The MQTT client object must be created before it can be used. The * maximum number of MQTT client objects that can exist simultaneously * is set by mqttconfigMAX_BROKERS. */ xReturned = MQTT_AGENT_Create( &xMQTTHandle ); if( xReturned == eMQTTAgentSuccess ) { /* Fill in the MQTTAgentConnectParams_t member that is not const, * and therefore could not be set in the initializer (where * xConnectParameters is declared in this function). */ xConnectParameters.usClientIdLength = ( uint16_t ) strlen( ( const char * ) pubCLIENT_ID ); /* Connect to the broker. */ configPRINTF( ( "MQTT attempting to connect to %s.\r\n", clientcredentialMQTT_BROKER_ENDPOINT ) ); xReturned = MQTT_AGENT_Connect( xMQTTHandle, &xConnectParameters, democonfigMQTT_PUB_TLS_NEGOTIATION_TIMEOUT ); if( xReturned != eMQTTAgentSuccess ) { /* Could not connect, so delete the MQTT client. */ ( void ) MQTT_AGENT_Delete( xMQTTHandle ); configPRINTF( ( "ERROR: MQTT failed to connect with error %d.\r\n", xReturned ) ); } else { configPRINTF( ( "MQTT connected.\r\n" ) ); xReturn = pdPASS; } } return xReturn; } /*-----------------------------------------------------------*/ /** * @brief fill the buffer with the sensor values * @param none * @param Buffer is the char pointer for the buffer to be filled * @param Size size of the above buffer * @retval 0 in case of success * -1 in case of failure */ int PrepareSensorsData(char * Buffer, int Size, char * deviceID) { float TEMPERATURE_Value; float HUMIDITY_Value; float PRESSURE_Value; int16_t ACC_Value[3]; float GYR_Value[3]; int16_t MAG_Value[3]; char * Buff = Buffer; int BuffSize = Size; int snprintfreturn = 0; TEMPERATURE_Value = BSP_TSENSOR_ReadTemp(); HUMIDITY_Value = BSP_HSENSOR_ReadHumidity(); PRESSURE_Value = BSP_PSENSOR_ReadPressure(); BSP_ACCELERO_AccGetXYZ(ACC_Value); BSP_GYRO_GetXYZ(GYR_Value); BSP_MAGNETO_GetXYZ(MAG_Value); if (deviceID != NULL) { /* Format data for transmission to AWS */ snprintfreturn = snprintf( Buff, BuffSize, "{\"Board_id\":\"%s\"," "\"Temp\": %d, \"Hum\": %d, \"Press\": %d, " "\"Accel_X\": %d, \"Accel_Y\": %d, \"Accel_Z\": %d, " "\"Gyro_X\": %d, \"Gyro_Y\": %d, \"Gyro_Z\": %d, " "\"Magn_X\": %d, \"Magn_Y\": %d, \"Magn_Z\": %d" "}", deviceID, (int)TEMPERATURE_Value, (int)HUMIDITY_Value, (int)PRESSURE_Value, ACC_Value[0], ACC_Value[1], ACC_Value[2], (int)GYR_Value[0], (int)GYR_Value[1], (int)GYR_Value[2], MAG_Value[0], MAG_Value[1], MAG_Value[2] ); } /* Check total size to be less than buffer size * if the return is >=0 and <n, then * the entire string was successfully formatted; if the return is * >=n, the string was truncated (but there is still a null char * at the end of what was written); if the return is <0, there was * an error. */ if (snprintfreturn >= 0 && snprintfreturn < Size) { return 0; } else if(snprintfreturn >= Size) { configPRINT_STRING("Data Pack truncated\n"); return 0; } else { configPRINT_STRING("Data Pack Error\n"); return -1; } } /*-----------------------------------------------------------*/ static void prvPublishNextMessage( void ) { MQTTAgentPublishParams_t xPublishParameters; MQTTAgentReturnCode_t xReturned; char cDataBuffer[ pubMAX_DATA_LENGTH ]; /* Check this function is not being called before the MQTT client object has * been created. */ configASSERT( xMQTTHandle != NULL ); /* create desired message */ if (PrepareSensorsData(cDataBuffer, sizeof(cDataBuffer), (char *) clientcredentialIOT_THING_NAME) != 0) { configPRINTF( ( "Error obtaining sensor data\r\n" ) ); return; } /* Setup the publish parameters. */ memset( &( xPublishParameters ), 0x00, sizeof( xPublishParameters ) ); xPublishParameters.pucTopic = pubTOPIC_NAME; xPublishParameters.pvData = cDataBuffer; xPublishParameters.usTopicLength = ( uint16_t ) strlen( ( const char * ) pubTOPIC_NAME ); xPublishParameters.ulDataLength = ( uint32_t ) strlen( cDataBuffer ); xPublishParameters.xQoS = eMQTTQoS1; /* Publish the message. */ xReturned = MQTT_AGENT_Publish( xMQTTHandle, &( xPublishParameters ), democonfigMQTT_TIMEOUT ); if( xReturned == eMQTTAgentSuccess ) { configPRINTF( ( "MQTT successfully published '%s'\r\n", cDataBuffer ) ); } else { configPRINTF( ( "ERROR: MQTT failed to publish '%s'\r\n", cDataBuffer ) ); } /* Remove compiler warnings in case configPRINTF() is not defined. */ ( void ) xReturned; } /*-----------------------------------------------------------*/ static void prvMQTTConnectAndPublishTask( void * pvParameters ) { BaseType_t xIterationCount; BaseType_t xReturned; const TickType_t xDelay = pdMS_TO_TICKS( democonfigSAMPLING_DELAY_SECONDS * 1000UL ); const BaseType_t xIterationsInAMinute = 60 / 5; /* Avoid compiler warnings about unused parameters. */ ( void ) pvParameters; /* Create the MQTT client object and connect it to the MQTT broker. */ xReturned = prvCreateClientAndConnectToBroker(); if( xReturned == pdPASS ) { configPRINTF( ( "MQTT: successfully connected to broker.\r\n" ) ); /* MQTT client is now connected to a broker. Publish a message * every five seconds until a minute has elapsed. */ for( xIterationCount = 0; ( democonfigITERATE_FOREVER || ( xIterationCount < xIterationsInAMinute ) ); xIterationCount++ ) { prvPublishNextMessage(); /* Five seconds delay between publishes. */ vTaskDelay( xDelay ); } } else { configPRINTF( ( "MQTT: could not connect to broker.\r\n" ) ); } /* Disconnect the client. */ ( void ) MQTT_AGENT_Disconnect( xMQTTHandle, democonfigMQTT_TIMEOUT ); /* End the demo by deleting all created resources. */ configPRINTF( ( "Sensor demo finished.\r\n" ) ); vTaskDelete( NULL ); /* Delete this task. */ } /*-----------------------------------------------------------*/ void vRunSensorDemo( void ) { configPRINTF( ( "Creating MQTT Publishing Task...\r\n" ) ); /* Create the task that publishes messages to the MQTT broker periodically. */ ( void ) xTaskCreate( prvMQTTConnectAndPublishTask, /* The function that implements the demo task. */ "SensorPub", /* The name to assign to the task being created. */ democonfigMQTT_PUB_TASK_STACK_SIZE, /* The size, in WORDS (not bytes), of the stack to allocate for the task being created. */ NULL, /* The task parameter is not being used. */ democonfigMQTT_PUB_TASK_PRIORITY, /* The priority at which the task being created will run. */ NULL ); /* Not storing the task's handle. */ } /*-----------------------------------------------------------*/
BiscayRobin/brainIt
src/arguments.h
#ifndef __ARGUMENTS_H #define __ARGUMENTS_H #include <stdbool.h> typedef struct { char *in_file; char *out_file; bool isCompiled; } args_t; int argument_parse(int argc, char **argv, args_t *args_result); #endif // __ARGUMENTS_H
BiscayRobin/brainIt
src/bf_runtime.h
#ifndef __BF_RUNTIME_H #define __BF_RUNTIME_H #include <stdlib.h> #define BF_STDOUT_ERROR 2 #define BF_STDIN_ERROR 1 #define BF_SUCCESS 0 typedef struct { char tape[30000]; size_t head_idx; } bf_runtime_t; int bf_run(char *source, size_t source_length); #endif // __BF_RUNTIME_H
BiscayRobin/brainIt
src/utils.h
<filename>src/utils.h #ifndef __UTILS_H #define __UTILS_H #include <stdio.h> size_t file_to_buffer(char *stream, char **buffer_addr); #endif // __UTILS_H
BiscayRobin/brainIt
src/arguments.c
<filename>src/arguments.c #include "arguments.h" #include <stdio.h> #include <stdlib.h> #include <argp.h> error_t parse_opt(int key, char *arg, struct argp_state *state) { args_t *arguments = state->input; switch (key) { case 'o': arguments->out_file = arg; break; case 'c': arguments->isCompiled = true; break; case ARGP_KEY_ARG: if (state->arg_num >= 1) argp_usage(state); arguments->in_file = arg; break; case ARGP_KEY_END: if (state->arg_num < 1) argp_usage(state); break; default: return ARGP_ERR_UNKNOWN; } return 0; } const char *argp_program_version = "brainIt v0.1"; static char doc[] = "brainIt -- An intepreter for brainfuck."; static char args_doc[] = "INPUT"; static struct argp_option options[] = { {.name = "output", .key = 'o', .doc = "Print program outputs to a file.", .group = 0}, {.name = "compilation-target", .key = 'c', .doc = "supported architectures are: x86_64", .group = 1}, {0}}; static struct argp argp = {options, parse_opt, args_doc, doc, NULL, NULL, NULL}; int argument_parse(int argc, char **argv, args_t *args_result) { return argp_parse(&argp, argc, argv, 0, 0, args_result); }
BiscayRobin/brainIt
src/bf_runtime.c
#include <stdio.h> #include "bf_runtime.h" int bf_run(char *source, size_t source_length) { bf_runtime_t bf_runtime = {0}; size_t source_idx = 0; while (source_idx < source_length) { char curr_op = source[source_idx]; size_t loop_depth = 0; switch (curr_op) { case '+': bf_runtime.tape[bf_runtime.head_idx]++; break; case '-': bf_runtime.tape[bf_runtime.head_idx]--; break; case '>': bf_runtime.head_idx++; break; case '<': bf_runtime.head_idx--; break; case '.': if (putchar(bf_runtime.tape[bf_runtime.head_idx]) == EOF) { return BF_STDOUT_ERROR; } break; case ',': bf_runtime.tape[bf_runtime.head_idx] = getchar(); if (ferror(stdin)) { return BF_STDIN_ERROR; } break; case '[': if (source[source_idx + 1] == '-' && source[source_idx + 2] == ']') { bf_runtime.tape[bf_runtime.head_idx] = 0; source_idx += 1; } if (!bf_runtime.tape[bf_runtime.head_idx]) { source_idx++; while (source[source_idx] != ']' || loop_depth != 0) { if (source[source_idx] == '[') loop_depth++; else if (source[source_idx] == ']') loop_depth--; source_idx++; } } break; case ']': if (bf_runtime.tape[bf_runtime.head_idx]) { source_idx--; while (source[source_idx] != '[' || loop_depth != 0) { if (source[source_idx] == ']') loop_depth++; else if (source[source_idx] == '[') loop_depth--; source_idx--; } } break; default: // ignore all unknown operations break; } source_idx++; } return BF_SUCCESS; }
BiscayRobin/brainIt
src/utils.c
#include "utils.h" #include <stdlib.h> #include <errno.h> #include <string.h> size_t file_to_buffer(char *file_path, char **buffer_addr) { FILE *file_stream = fopen(file_path, "rb"); if (!file_stream) { fprintf(stderr, "%s: %s\n", file_path, strerror(errno)); exit(EXIT_FAILURE); } size_t source_length; fseek(file_stream, 0, SEEK_END); source_length = ftell(file_stream); fseek(file_stream, 0, SEEK_SET); if (!(*buffer_addr = malloc(source_length))) { fclose(file_stream); fprintf(stderr, "Fatal: Could not allocate %zu bytes\n", source_length); exit(EXIT_FAILURE); } fread(*buffer_addr, 1, source_length, file_stream); int error_code; if ((error_code = ferror(file_stream))) { fclose(file_stream); fprintf(stderr, "%s: %s\n", file_path, strerror(error_code)); exit(EXIT_FAILURE); } fclose(file_stream); return source_length; }
BiscayRobin/brainIt
src/main.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "bf_runtime.h" #include "arguments.h" #include "utils.h" int main(int argc, char **argv) { int error_code = 0; args_t arguments = {0}; argument_parse(argc, argv, &arguments); char *source_code; size_t source_length = file_to_buffer(arguments.in_file, &source_code); if ((error_code = bf_run(source_code, source_length))) { char *error_message; switch (error_code) { case BF_STDIN_ERROR: error_message = "could not read from stdin"; break; case BF_STDOUT_ERROR: error_message = "could not write to stdout"; break; default: error_message = "unknown error"; break; } fprintf(stderr, "Error(%d): %s", error_code, error_message); return EXIT_FAILURE; } return EXIT_SUCCESS; }
hdaikoku/hadoop
hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfspp/examples/c/connect_cancel/connect_cancel.c
<gh_stars>1-10 /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Attempt to connect to a cluster and use Control-C to bail out if it takes a while. Valid config must be in environment variable $HADOOP_CONF_DIR */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include "hdfspp/hdfs_ext.h" #include "common/util_c.h" #include "x-platform/c_api.h" #define ERROR_BUFFER_SIZE 1024 // Global so signal handler can get at it hdfsFS fs = NULL; const char *catch_enter = "In signal handler, going to try and cancel.\n"; const char *catch_cancel = "hdfsCancelPendingConnect has been canceled in the signal handler.\n"; const char *catch_exit = "Exiting the signal handler.\n"; // Print to stdout without calling malloc or otherwise indirectly modify userspace state. // Write calls to stdout may still interleave with stuff coming from elsewhere. static void sighandler_direct_stdout(const char *msg) { if(!msg) { return; } x_platform_syscall_write_to_stdout(msg); } static void sig_catch(int val) { // Beware of calling things that aren't reentrant e.g. malloc while in a signal handler. sighandler_direct_stdout(catch_enter); if(fs) { hdfsCancelPendingConnection(fs); sighandler_direct_stdout(catch_cancel); } sighandler_direct_stdout(catch_exit); } int main(int argc, char** argv) { hdfsSetLoggingLevel(HDFSPP_LOG_LEVEL_INFO); signal(SIGINT, sig_catch); char error_text[ERROR_BUFFER_SIZE]; if (argc != 1) { fprintf(stderr, "usage: ./connect_cancel_c\n"); ShutdownProtobufLibrary_C(); exit(EXIT_FAILURE); } const char *hdfsconfdir = getenv("HADOOP_CONF_DIR"); if(!hdfsconfdir) { fprintf(stderr, "$HADOOP_CONF_DIR must be set\n"); ShutdownProtobufLibrary_C(); exit(EXIT_FAILURE); } struct hdfsBuilder* builder = hdfsNewBuilderFromDirectory(hdfsconfdir); fs = hdfsAllocateFileSystem(builder); if (fs == NULL) { hdfsGetLastError(error_text, ERROR_BUFFER_SIZE); fprintf(stderr, "hdfsAllocateFileSystem returned null.\n%s\n", error_text); hdfsFreeBuilder(builder); ShutdownProtobufLibrary_C(); exit(EXIT_FAILURE); } int connected = hdfsConnectAllocated(fs, builder); if (connected != 0) { hdfsGetLastError(error_text, ERROR_BUFFER_SIZE); fprintf(stderr, "hdfsConnectAllocated errored.\n%s\n", error_text); hdfsFreeBuilder(builder); ShutdownProtobufLibrary_C(); exit(EXIT_FAILURE); } hdfsDisconnect(fs); hdfsFreeBuilder(builder); // Clean up static data and prevent valgrind memory leaks ShutdownProtobufLibrary_C(); return 0; }
awesomemachinelearning/flashlight
flashlight/common/CudaUtils.h
/** * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <af/cuda.h> /// usage: `FL_CUDA_CHECK(cudaError_t err[, const char* prefix])` #define FL_CUDA_CHECK(...) \ ::fl::cuda::detail::check(__VA_ARGS__, __FILE__, __LINE__) namespace fl { namespace cuda { /** * Gets the Arrayfire CUDA stream. Gets the stream * for the device it's called on (with that device id) */ cudaStream_t getActiveStream(); /** * Synchronizes (blocks) a CUDA stream on another. That is, records a snapshot * of any operations currently enqueued on CUDA stream blockOn using a CUDA * Event, and forces blockee to wait on those events to complete before * beginning any future-enqueued operations. Does so without blocking the host * CPU thread. * * @param[in] blockee the CUDA stream to be blocked * @param[in] blockOn the CUDA stream to block on, whose events will be waited * on to complete before the blockee starts execution of its enqueued events * @param[in] event an existing CUDA event to use to record events on blockOn * CUDA stream */ void synchronizeStreams( cudaStream_t blockee, cudaStream_t blockOn, cudaEvent_t event); namespace detail { // Flags for CUDA Event creation. Timing creates overhead, so disable. constexpr unsigned int kCudaEventDefaultFlags = cudaEventDefault | cudaEventDisableTiming; void check(cudaError_t err, const char* file, int line); void check(cudaError_t err, const char* prefix, const char* file, int line); } // namespace detail } // namespace cuda } // namespace fl
RenanBasilio/ArgsParser
include/argsparser/typed_input_container.h
/** * typed_input_container.h * * This file contains the definition of the template container class * TypedInputContainer, used to process argument values when the argument type * can be specified. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <argsparser/input_container.h> #include <argsparser/typed_value_wrapper.h> namespace ArgsParser { /** * This class is a InputContainer with an assigned type. It is to be * used when a specific return type is desired from an option, if said * type is known. * A converter function must be provided that transforms a string into the * desired type. * This class is used by positionals and input parameters. */ template <typename T> class TypedInputContainer : public InputContainer { public: /** * This method gets the converted value of the user input. * * @return {T} The result of the conversion of the user input stored in this parser. */ TypedValueWrapper<T> getConvertedValue() const; /** * This is the constructor for the typed user input container. * * @param {ArgType} type The type of argument stored in this container. * @param {string} name The name of the argument stored in this container. * @param {vector<string>} identifiers The identifiers associated with the argument stored in this container. * @param {string} description The description of the argument stored in this container. * @param {string} placeholder_text The placeholder text of the argument stored in this container. * @param {size_t} max_values The maximum number of inputs this container can hold. * @param {Validator} validator A function to use for input validation. * @param {Converter<T>} converter A function to use for input conversion. * @param {ErrorHandler} error_callback A function to call if validation fails. * @param {Callback} callback A function to call if validation succeeds. */ TypedInputContainer( const ArgType type, const std::string& name, const std::vector<std::string>& identifiers, const std::string& description = "", const std::string& placeholder_text = "", const size_t max_values = 1, const Converter<T>& converter = nullptr, const Validator<T>& validator = nullptr, const ErrorHandler& error_callback = nullptr, const Callback& callback = nullptr ); /** * Cloning method. * * @return {Container*} A pointer to a new TypedInputContainer object cloned from this object. */ virtual TypedInputContainer<T>* clone() const; /** * This is the destructor for the typed user input container. */ virtual ~TypedInputContainer() {}; private: std::vector<T> converted_value_; const Converter<T> converter_; const Validator<T> validator_; friend class Parser; /** * This method executes all post-processing logic associated with * this container. * * This method will call the converter on each input, and upon * successful conversion will call the validator. If every * validation succeeds the callback function will be called. If even * a single validation or conversion fails the error callback will * be called instead. * * It is virtual, as the derived classes use different post-processing * logic to account for other features. */ virtual void postProcess(); }; /////////////////////// Template Method Definitions /////////////////////// template <typename T> TypedValueWrapper<T> TypedInputContainer<T>::getConvertedValue() const { return TypedValueWrapper<T>(active_, converted_value_); }; template <typename T> TypedInputContainer<T>::TypedInputContainer( const ArgType type, const std::string& name, const std::vector<std::string>& identifiers, const std::string& description, const std::string& placeholder_text, const size_t max_values, const Converter<T>& converter, const Validator<T>& validator, const ErrorHandler& error_callback, const Callback& callback ) : InputContainer( type, name, identifiers, description, placeholder_text, max_values, nullptr, error_callback, callback ), converter_(converter), validator_(validator) {}; template <typename T> TypedInputContainer<T>* TypedInputContainer<T>::clone() const { TypedInputContainer<T>* copy = new TypedInputContainer<T>( type_, name_, identifiers_, description_, placeholder_text_, max_values_, converter_, validator_, error_callback_, callback_ ); copy->user_input_ = user_input_; copy->validation_ = validation_; copy->validation_failure_reason_ = validation_failure_reason_; copy->converted_value_ = converted_value_; return copy; }; template <typename T> void TypedInputContainer<T>::postProcess() { if (converter_ != nullptr) { for (size_t i = 0; i < user_input_.size(); i++) { try { T input = converter_(user_input_[i]); if (validator_ != nullptr) { bool valid = validator_(input); if (!valid) throw std::runtime_error("Unspecified validation error."); } converted_value_.push_back(input); } catch (std::exception& e) { validation_ = false; validation_failure_reason_ = e.what(); if(error_callback_ != nullptr) error_callback_(e); return; } } } if (callback_ != nullptr) callback_(); }; }
RenanBasilio/ArgsParser
include/argsparser/value_wrapper.h
/** * value_wrapper.h * * This file contains the declaration of the ValueWrapper struct, a utility * class that is implicitly convertible to bool or string for returning * argument values. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <argsparser/common.h> namespace ArgsParser { struct ValueWrapper { const std::vector<std::string> user_input; const bool active; // Implicit conversion to bool. operator bool() const noexcept; // Implicit conversion to string. operator std::string() const noexcept; // Implicit conversion to vector of strings. operator std::vector<std::string>() const noexcept; // Accessor operator. std::string operator[](size_t position) const noexcept; // Number of values in this wrapper. size_t size() const noexcept; // Explicit conversion to string. std::string to_string() const noexcept; }; }
RenanBasilio/ArgsParser
include/argsparser/token.h
/** * token.h * * This file contains the declaration of the Token class and related global * defines. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <argsparser/common.h> namespace ArgsParser { /** * This struct is the type of the id tokens returned by registration methods * in the parser. These can be used to more quickly retrieve registered items * by skipping the hashing and lookup processes associated with stl maps. * * Objects of the token class are implicitly convertible to bool. Furthermore, * the logical equality and comparison operators are implemented to compare * objects of this type. */ struct Token { ArgType type; unsigned short position; operator bool() const noexcept; bool operator==(const Token& other) const noexcept; Token operator||(const Token& other) const noexcept; }; const Token NULL_TOKEN = {ArgType::Null, 0}; }
RenanBasilio/ArgsParser
include/argsparser/typed_value_wrapper.h
<filename>include/argsparser/typed_value_wrapper.h /** * typed_value_wrapper.h * * This file contains the declaration of the TypedValueWrapper struct, a template * utility that is implicitly convertible to bool or a user defined type used for * returning typed argument values. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <argsparser/common.h> namespace ArgsParser { template <typename T> struct TypedValueWrapper { const std::vector<T> typed_input_; const bool active_; operator bool() const noexcept; operator T() const noexcept; operator std::vector<T>() const noexcept; T operator[](size_t position) const noexcept; size_t size() const noexcept; TypedValueWrapper(); TypedValueWrapper(bool active, std::vector<T> typed_input); }; /////////////////////// Template Method Definitions /////////////////////// template <typename T> TypedValueWrapper<T>::operator bool() const noexcept { return active_; }; template <typename T> TypedValueWrapper<T>::operator T() const noexcept { if (typed_input_.size() > 0) return typed_input_[0]; else return T(); }; template <typename T> TypedValueWrapper<T>::operator std::vector<T>() const noexcept { return typed_input_; }; template <typename T> T TypedValueWrapper<T>::operator[](size_t position) const noexcept { // Return the requested value if the position specified is valid if (position < typed_input_.size()) return typed_input_[position]; // Return the last value if the position specified is after the end of the vector. else if (typed_input_.size() != 0) return typed_input_[typed_input_.size()-1]; // Return an empty object of type T otherwise. else return T(); }; template <typename T> size_t TypedValueWrapper<T>::size() const noexcept { return typed_input_.size(); }; template <typename T> TypedValueWrapper<T>::TypedValueWrapper(): active_(false), typed_input_(std::vector<T>()) {}; template <typename T> TypedValueWrapper<T>::TypedValueWrapper( bool active, std::vector<T> typed_input): active_(active), typed_input_(typed_input) {}; }
RenanBasilio/ArgsParser
include/argsparser/common.h
/** * common.h * * This file contains common definitions and declarations used throughout the library. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <memory> #include <string> #include <vector> #include <exception> #include <functional> #include <iostream> namespace ArgsParser { /** * This enumeration is used internally to define the possible types of * options and store them for use by the parser. */ enum ArgType { Null, Positional = 1, Switch, Option }; /** * This is the declaration of a validator function. * * Validator functions must always take a string (the input that will be * fed into it) and return a boolean of whether the validation succeeded * or not. * * The result of the validation process can be retrieved by calling * getValidation() on the container or through the equivalent interface * on the parser itself. * * Optionally, validator functions may throw an exception with the error * that caused validation to fail. The exception will be handled internally * and the error message made available if validation failures are not to * be considered critical. Otherwise it will be rethrown. * * Some sample validator methods are defined in samples/validators.h */ template <typename T> using Validator = std::function<bool(const T&)>; /** * This is the declaration of a callback function. * * Callback methods do not take any arguments and must not return anything. * They are called after validation but do not require the value to validate * successfully. This type of method is recommended to be called as an entry * point for a positional argument or switch. * * Some sample callback methods are defined in samples/callbacks.h */ using Callback = std::function<void()>; /** * This is the declaration of an error handler function. * * Error handlers are called alternatively to callback methods in case of an * error. They are provided the error code and description string related to * the error that occurred. */ using ErrorHandler = std::function<void(const std::exception&)>; /** * This is the declaration of a converter function. * * Converter functions are used to convert input from user submitted strings * to another type. As such, they must always take a string and a pointer. * The string will be the user input string, and the pointer will be an * argument of the template instantiated type to contain the result. */ template <typename T> using Converter = std::function<T(const std::string&)>; }
RenanBasilio/ArgsParser
include/argsparser/autohelp.h
/** * autohelp.h * * This file contains the declaration of methods used to automatically * generate usage help text. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <iostream> #include <argsparser/parser.h> namespace ArgsParser { /** * This method outputs usage help text to the provided stream (which is * the standard output stream "std::cout" by default) in the following * form: * usage: ${program_name} [<positional>] ... [<args>] * -s, --switch ${switch_description} * ... * * options * -o, --option ${option_description} * -p, --value-option <placeholder> ${value_option_description} * ... */ void autohelper(const Parser& parser, std::ostream& stream = std::cout); }
RenanBasilio/ArgsParser
include/argsparser/parser.h
<reponame>RenanBasilio/ArgsParser /** * parser.h * * This file contains the class declaration for the base Parser class. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <unordered_map> #include <limits> #include <token.h> #include <argsparser/typed_input_container.h> #include <argsparser/util.h> namespace ArgsParser { /** * This is the base Parser class. It provides basic parsing and auto-help * without additional features such as parameter validation. */ class Parser{ struct ParserImpl; std::unique_ptr<ParserImpl> parser_impl; // Whether errors should throw unhandled exceptions. const bool no_except_; // A method to call if an error occurs. ErrorHandler error_callback_; public: Parser(); Parser(bool no_except, ErrorHandler error_callback = ArgsTools::print_error); Parser(const Parser& other); // Copy constructor. Parser(Parser&& other); // Move constructor. Parser& operator=(Parser other); // Assignment operator ~Parser(); friend void swap(Parser& first, Parser& second); ValueWrapper getValue(const std::string& name) const noexcept; ValueWrapper getValue(const Token& token) const noexcept; template <typename T> const TypedValueWrapper<T> getValue(const std::string& name) const noexcept; template <typename T> const TypedValueWrapper<T> getValue(const Token& token) const noexcept; const unsigned short& error_code; const std::string& error_description; /** * This method returns whether a name or identifier is registered to * the parser. * @param {std::string} symbol The symbol to search for. * @return {bool} True if symbol is registered. False otherwise. */ Token isRegistered(const std::string& symbol) const noexcept; /** * This method returns whether a name is registered to the parser. * @param {std::string} name The name to search for. * @return {bool} True if name is registered. False otherwise. */ Token isNameRegistered(const std::string& name) const noexcept; /** * This method returns whether an identifier is registered to the * parser. * @param {std::string} identifier The identifier to search for. * @return {bool} True if the identifier is registered. False otherwise. */ Token isIdentifierRegistered(const std::string& identifier) const noexcept; /** * This method register a positional argument to the parser. Usage example: * ArgsParser.register_positional( * "file", "filename", file_exists, show_error, callback); * * The above line will enable parsing the following lines: * myapp example.txt * The parser will then call file_exists(example.txt) and if true then callback(), * otherwise show_error(). * * It will generate the following help text: * usage: myapp [<filename>] * * Positionals are parsed in the order they are registered. * * The method returns true if the option was registered successfully. Otherwise * it returns false and sets the "error_description" variable to a description of the * error. * * @param {std::string} name The name of the positional. * @param {std::string} placeholder_text The text to show in a help message to describe the positional. * @param {Validator} validator The method to use to validate the user input string. * @param {Converter} converter The converter method to use for converting string input to type T. * @param {Callback} error_callback A method to call in case validation fails. * @param {Callback} callback A method to call in case validation succeeds. * @return {Token} The token to retrieve the argument value by Id. * @except {std::runtime_error} Registration failure. */ template <typename T> Token registerPositional( const std::string& name, const std::string& placeholder_text, const Callback& callback = nullptr, const Converter<T>& converter = nullptr, const Validator<T>& validator = nullptr, const ErrorHandler& error_callback = nullptr ); Token registerPositional( const std::string& name, const std::string& placeholder_text, const Callback& callback = nullptr, const Validator<std::string>& validator = nullptr, const ErrorHandler& error_callback = nullptr ); /** * This method registers a switch to the parser. Usage example: * Parser.register_switch( * "help", {"h", "help"}, "Outputs help text to the command line.", autohelp); * * The above line will enable parsing the following lines: * myapp -h * myapp --help * Upon reading either switch, the parser will call it's callback method. * * Autohelp will generate the following help text: * -h, --help Outputs help text to the command line. * * The method returns true if the option was registered successfully. * Otherwise it returns false and sets the "error_description" * variable to a description of the error. * * @param {std::string} name The name of the option. * @param {std::vector<std::string>} identifiers The identifiers to register with this option. * @param {std::string} description The description of the option to use for help text. * @param {Callback} callback A function to call upon encountering this switch. * @return {Token} The token to retrieve the argument value by Id. * @except {std::runtime_error} Registration failure. */ Token registerSwitch( const std::string& name, const std::vector<std::string>& identifiers, const std::string& description = "Description not given.", const Callback& callback = nullptr ); /** * This method registers an input value option to the parser. Usage example: * Parser.register_option( * "file", {"f", "file"}, "filename", "The file to open", file_exists show_error, callback); * * The above line will enable parsing the following lines: * myapp -f example.txt * myapp --file example.txt * The parser will then call file_exists(example.txt) and if true then callback(), otherwise * then show_error(). * * And generate the following help text: * -f, --file <filename> The file to open. * * The method returns true if the option was registered successfully. Otherwise * it returns false and sets the "error_description" variable to a description of the * error. * * @param {std::string} name The name of the option. * @param {std::vector<std::string>} identifiers The identifiers to register for this option * @param {std::string} placeholder_text The text that will be displayed within <> in the help text. * @param {std::string} description The description of the option that will be displayed in the help text. * @param {Validator} validator A function to check if the parameter provided with the option is valid. * @param {Converter} converter The converter method to use for converting string input to type T. * @param {Callback} error_callback A function to call if validation fails. * @param {Callback} callback A function to be called if validation succeeds. * @return {Token} The token to retrieve the argument value by Id. * @except {std::runtime_error} Registration failure. */ template <typename T> Token registerOption( const std::string& name, const std::vector<std::string>& identifiers, const std::string& placeholder_text = "value", const std::string& description = "Description not given.", const size_t max_values = 1, const Callback& callback = nullptr, const Converter<T>& converter = nullptr, const Validator<T>& validator = nullptr, const ErrorHandler& error_callback = nullptr ); Token registerOption( const std::string& name, const std::vector<std::string>& identifiers, const std::string& placeholder_text = "value", const std::string& description = "Description not given.", const size_t max_values = 1, const Callback& callback = nullptr, const Validator<std::string>& validator = nullptr, const ErrorHandler& error_callback = nullptr ); /** * This method returns a vector of all tokens that have been * registered to the parser. * @return {std::vector<Token>} The list of registered tokens. */ std::vector<Token> getRegisteredTokens() const; /** * This method returns a vector of all names that have been * registered to the parser. * @return {std::vector<std::string>} The list of registered names. */ std::vector<std::string> getRegisteredNames() const; /** * This method gets a registered container by it's token. * @param {Token} The registration token. * @return {Container*} The container. */ const Container* getContainer(const std::string& name) const noexcept; const Container* getContainer(const Token& token) const noexcept; /** * This method gets the program name (either as provided by the user * or parsed by the application). * @return {std::string} The name of the program. */ std::string getProgramName() const noexcept; /** * This method sets the program name. If a name is set it will override * one parsed from the command line. */ void setProgramName(const std::string& name); /** * Calling this method will register the 'h' and 'help' switches under 'help'. * * This method will return true if the switches registered successfully. Otherwise, * if one or both have already been registered, it will return false. * * Alternatively, if you wish to register your own help provider, register a * switch with the method you wish to use as the callback function. * * @return {bool} Whether autohelp was enabled successfully. */ bool enableAutohelp(); /** * This method parses argv. * @param {int} argc The argument count. * @param {char**} argv The argument vector. */ void parse(int argc, char* argv[]); private: // The following private methods are used to interface with the // implementation class. /** * This method registers a container of a specified type and returns * its id token. * * @param {ArgType} type The type of option in the container. * @param {Container*} container The container being registered. */ Token registerContainer(ArgType type, Container* container); /** * This method sets the error description to the message provided. * * @param {std::string} message The error message. */ void setError(const std::string& message); /** * This method sets the container represented by a token to active and * optionally assigns it a user input parameter. * * @param {Token} token The token that identifies the option. * @param {std::string} user_input The user input data. */ void setActive(const Token token, const std::string& user_input = nullptr); }; ////////////////////// Definition of Template Methods ////////////////////////////// template <typename T> const TypedValueWrapper<T> Parser::getValue(const std::string& name) const noexcept { return getValue<T>(isRegistered(name)); }; template <typename T> const TypedValueWrapper<T> Parser::getValue(const Token& token) const noexcept { try { const TypedInputContainer<T>* container = dynamic_cast<const TypedInputContainer<T>*>(getContainer(token)); if (container == nullptr) throw std::invalid_argument( std::string("Identifier does not refer to a registered container of type ") + typeid(T).name()); return container->getConvertedValue(); } catch (const std::exception&) { return TypedValueWrapper<T>(); } }; template <typename T> Token Parser::registerPositional( const std::string& name, const std::string& placeholder_text, const Callback& callback, const Converter<T>& converter, const Validator<T>& validator, const ErrorHandler& error_callback ){ try{ // First check if name is already registered. if(isNameRegistered(name)) throw std::runtime_error("Name \"" + name + "\" is already registered."); TypedInputContainer<T>* container = new TypedInputContainer<T>( ArgType::Positional, name, std::vector<std::string>(), "", placeholder_text, 1, converter, validator, error_callback, callback ); Token id = registerContainer(ArgType::Positional, container); return id; } catch (const std::exception& e){ std::string error_string = std::string("Registration Error: ") + e.what(); if(!no_except_) throw std::runtime_error(error_string); else setError(error_string); return NULL_TOKEN; } }; template <typename T> Token Parser::registerOption( const std::string& name, const std::vector<std::string>& identifiers, const std::string& placeholder_text, const std::string& description, const size_t max_values, const Callback& callback, const Converter<T>& converter, const Validator<T>& validator, const ErrorHandler& error_callback ){ try{ // First check if all identifiers are open to be registered. if(isNameRegistered(name)) throw std::runtime_error( "Name \"" + name + "\" is already registered." ); std::vector<std::string> identifiers_(identifiers.size()); for(size_t i = 0; i < identifiers.size(); i++) { identifiers_[i] = ArgsTools::make_identifier(identifiers[i]); if(isIdentifierRegistered(identifiers_[i])) throw std::runtime_error( "Identifier \"" + identifiers_[i] + "\" is already registered." ); } // If check was successful, create a new container object. TypedInputContainer<T>* container = new TypedInputContainer<T>( ArgType::Option, name, identifiers_, description, placeholder_text, max_values, converter, validator, error_callback, callback ); // And push the container to the array of registered options. Token id = registerContainer(ArgType::Option, container); return id; } catch (const std::exception& e) { std::string error_string = std::string("Registration Error: ") + e.what(); if(!no_except_) throw std::runtime_error(error_string); else setError(error_string); return NULL_TOKEN; } }; }
RenanBasilio/ArgsParser
include/argsparser/util.h
<gh_stars>1-10 /** * util.h * * This file contains the declaration of utility methods in the ArgsParser * namespace. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <string> #include <iostream> #include <stdexcept> #include <exception> namespace ArgsTools { /** * This method checks if an identifier is valid. That is, if the identifier * is prefixed by the correct amount of dashes and does not contain any * invalid characters. Valid characters are: * "-AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz" * * @param {std::string} identifier The identifier to check. * @return {bool} Whether the string is a valid identifier. */ bool check_identifier(const std::string& identifier); /** * This method makes a valid identifier from a string. This is done by * prefixing a single '-' character to the string if it is only one * character long and '--' if it contains multiple character. * * This method throws an exception if the string contains invalid * characters. * * @param {std::string} string The string to make a valid identifier from. * @return {std::string} A valid identifier string. * @except {std::runtime_error} String contains invalid characters. */ std::string make_identifier(const std::string& string); /** * This method is an error handler that simply prints the e.what() of an * exception object. * * @param {std::exception&} e The exception to print. */ void print_error(const std::exception& e); }
RenanBasilio/ArgsParser
include/argsparser/container.h
/** * container.h * * This file contains the public interface of the container class used to store * data. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <algorithm> #include <argsparser/value_wrapper.h> #include <argsparser/common.h> namespace ArgsParser { /** * This template base class is used to store basic information about an * argument type to be parsed. * This class is used when a switch is registered, as it has a smaller * memory footprint. */ class Container{ public: /** * This method retrieves the name assigned to this container. * * @return {string} The name of the argument stored in this container. */ std::string getName() const noexcept; /** * This method retrieves the type of this container. * * @return {ArgType} The type of the argument stored in this container. */ ArgType getType() const noexcept; /** * This method retrieves the description assigned to this container. * * @return {string} The description of the argument stored in this container. */ std::string getDescription() const noexcept; /** * This method retrives the list of identifiers registered to this * container. * * @return {vector<string>} The list of identifiers associated with this container. */ std::vector<std::string> getIdentifiers() const noexcept; /** * This method retrieves whether this container is active. This is * always false before parsing, and will be set if this container * refers to an option called by the user. * * @return {bool} Whether the parser found this container in the command line. */ bool isActive() const noexcept; /** * Constructor of the container class. * * @param {ArgType} type The type of the argument. * @param {string} name The name of the argument. * @param {vector<string>} identifiers The list of identifiers associated with the argument. * @param {string} description The description of the argument. * @param {Callback} callback The method to call during post processing if this argument is found by the parser. */ Container( const ArgType type, const std::string& name, const std::vector<std::string>& identifiers, const std::string& description, const Callback& callback ); /** * Destructor of the container class. */ virtual ~Container(); /** * Cloning method. * * @return {Container*} A pointer to a new Container object cloned from this object. */ virtual Container* clone() const; protected: const std::string name_; const std::string description_; const std::vector<std::string> identifiers_; const Callback callback_; const ArgType type_; bool active_; friend class Parser; /** * This method sets the container to active. * It is private, and can only be called by the parser. It will be * called if the parser finds this argument in the command line. */ void setActive(); /** * This method executes all post-processing logic associated with * this container. * It is virtual, as the derived classes use different post-processing * logic to account for features such as validation or conversion. */ virtual void postProcess(); }; }
RenanBasilio/ArgsParser
include/argsparser/parserImpl.h
/** * parserImpl.h * * This file contains the declarations of the internals of the Parser class. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #include <argsparser/parser.h> namespace ArgsParser { struct Parser::ParserImpl{ // This string stores the parsed name of the program. std::string program_name; // This short stores the code of the last non-critical error. unsigned short error_code; // This string stores the description of the last non-critical error. std::string error_description; /** * These maps stores name and symbol information respectively. The name * map maps user entered names (such as "help") to the respective type * of argument and identifier so it may be quickly accessed from the * corresponding vector, while the symbol maps map command line symbols * (such as "-h") for access when parsing the command line. */ std::unordered_map<std::string, Token> names; std::unordered_map<std::string, Token> identifiers; /** * These vectors contain pointers to the actual containers storing each * argument type. * Positionals are read in the order they are declared, so this vector * can be used to retrieve their containers faster than a map lookup. */ std::vector<Container*> registered_positionals; std::vector<Container*> registered_switches; std::vector<Container*> registered_options; ParserImpl(); ~ParserImpl(); /** * This method gets a registered container by it's token. * @param {Token} The registration token. * @return {Container*} The container. */ Container* getContainer(const Token& token); }; }
RenanBasilio/ArgsParser
include/argsparser/input_container.h
<filename>include/argsparser/input_container.h /** * input_container.h * * This file contains the declaration of the InputContainer class, used to * process arguments where the input does not have a user-specified type and * is therefore treated as a string. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <argsparser/container.h> namespace ArgsParser { /** * This class is used to parse for user inputted strings. It is based on * the basic container class with additional methods to store and retrieve * input parameters. */ class InputContainer : public Container{ public: /** * This method retrieves the placeholder text assigned to this * container. The placeholder text is used for generating help * text. * * @return {string} The placeholder text associated with this input argument. */ virtual std::string getPlaceholderText() const noexcept; /** * This method retrieves user input how it was parsed from the * command line. Only string conversion is performed. * * @return {vector<string>} The list of user inputs parsed to this container. */ std::vector<std::string> getUserInput() const noexcept; /** * This method returns the number of independent inputs parsed to this * container. * * @return {size_t} The size of the list of user inputs parsed to this container. */ size_t getInputSize() const noexcept; /** * This method returns the maximum number of independent inputs that this * container can hold. * * @return {size_t} The maximum number of inputs that this container can hold. */ size_t getMaxInputs() const noexcept; /** * This method returns the wrapped value of this container. * * @return {ValueWrapper} The wrapped state and input stored in this container. */ ValueWrapper getValue() const noexcept; /** * This method returns the validation state of the user input as a * pair, with the first element being whether the validation was * successful and the second being the error string generated. * * @return {pair<bool, string>} The validation state and error message (if failure). */ std::pair<bool, std::string> getValidation() const noexcept; /** * This is the constructor for the user input container. * * @param {ArgType} type The type of argument stored in this container. * @param {string} name The name of the argument stored in this container. * @param {vector<string>} identifiers The identifiers associated with the argument stored in this container. * @param {string} description The description of the argument stored in this container. * @param {string} placeholder_text The placeholder text of the argument stored in this container. * @param {size_t} max_values The maximum number of inputs this container can hold. * @param {Validator} validator A function to use for input validation. * @param {ErrorHandler} error_callback A function to call if validation fails. * @param {Callback} callback A function to call if validation succeeds. */ InputContainer( const ArgType type, const std::string& name, const std::vector<std::string>& identifiers, const std::string& description = "", const std::string& placeholder_text = "", const size_t max_values = 1, const Validator<std::string>& validator = nullptr, const ErrorHandler& error_callback = nullptr, const Callback& callback = nullptr ); /** * This is the destructor for the user input container. */ virtual ~InputContainer(); /** * Cloning method. * * @return {Container*} A pointer to a new InputContainer object cloned from this object. */ virtual InputContainer* clone() const; protected: const size_t max_values_; std::string placeholder_text_; std::vector<std::string> user_input_; const Validator<std::string> validator_; const ErrorHandler error_callback_; bool validation_; std::string validation_failure_reason_; friend class Parser; /** * This method sets the container state to active and appends the * input string to the list of user inputs. It will be called when * a value passed to the identifiers associated with this container * is found by the parser. * * @param {string} user_input The input to associate with this container. */ void setActive(const std::string& user_input); /** * This method executes all post-processing logic associated with * this container. * * This method will call the validator on each input, and if every * validation succeeds the callback function will be called. If even * a single validation fails the error callback will be called instead. * * It is virtual, as the derived classes use different post-processing * logic to account for features such conversion. */ virtual void postProcess(); }; }
RenanBasilio/ArgsParser
include/argsparser.h
/** * argsparser.h * * This file includes all headers from the argsparser library. * * Copyright (C) 2018 <NAME>. All rights reserved. */ #pragma once #include <argsparser/autohelp.h> #include <argsparser/common.h> #include <argsparser/container.h> #include <argsparser/input_container.h> #include <argsparser/parser.h> #include <argsparser/typed_input_container.h> #include <argsparser/value_wrapper.h> #include <argsparser/version.hpp> #include <argsparser/util.h>
GCZhang/Profugus
packages/Utils/rng/sprng/makeseed.c
#include <time.h> #include <Utils/config.h> #if __STDC__ int make_new_seed() #else int make_new_seed() #endif { time_t tp; struct tm *temp; unsigned int temp2, temp3; static unsigned int temp4 = 0xe0e1; time(&tp); temp = localtime(&tp); temp2 = (temp->tm_sec<<26)+(temp->tm_min<<20)+(temp->tm_hour<<15)+ (temp->tm_mday<<10)+(temp->tm_mon<<6); temp3 = (temp->tm_year<<13)+(temp->tm_wday<<10)+(temp->tm_yday<<1)+ temp->tm_isdst; temp2 ^= clock()^temp3; temp4 = (temp4*0xeeee)%0xffff; temp2 ^= temp4<<16; temp4 = (temp4*0xaeee)%0xffff; temp2 ^= temp4; temp2 &= 0x7fffffff; return temp2; } #if 0 main() { printf("%u\n", make_new_seed()); } #endif
GCZhang/Profugus
packages/Utils/rng/sprng/fwrap.h
#ifndef Utils_rng_sprng_fwrap_h #define Utils_rng_sprng_fwrap_h #include <mc/config.h> /************************************************************************/ /************************************************************************/ /* Inter-language Naming Convention Problem Solution */ /* */ /* Note that with different compilers you may find that */ /* the linker fails to find certain modules due to the naming */ /* conventions implicit in particular compilers. Here the */ /* solution was to look at the object code produced by the FORTRAN */ /* compiler and modify this wrapper code so that the C routines */ /* compiled with the same routine names as produced in the FORTRAN */ /* program. */ /* */ /* We hope to have a comprehensive version that based on the */ /* compiler information automatically produces the appropriate */ /* wrapper code (need more work). */ /* */ /************************************************************************/ /************************************************************************/ /* Turn funcName (which must be all lower-case) into something callable from FORTRAN, typically by appending one or more underscores. */ #if defined(Add__) #define FORTRAN_CALLABLE(funcName) funcName ## __ #elif defined(NoChange) #define FORTRAN_CALLABLE(funcName) funcName #elif defined(Add_) #define FORTRAN_CALLABLE(funcName) funcName ## _ #endif #ifdef UpCase #define FNAMEOF_finit_rng FINIT_RNG #define FNAMEOF_fspawn_rng FSPAWN_RNG #define FNAMEOF_fget_rn_int FGET_RN_INT #define FNAMEOF_fget_rn_flt FGET_RN_FLT #define FNAMEOF_fget_rn_dbl FGET_RN_DBL #define FNAMEOF_fmake_new_seed FMAKE_NEW_SEED #define FNAMEOF_fseed_mpi FSEED_MPI #define FNAMEOF_ffree_rng FFREE_RNG #define FNAMEOF_fget_seed_rng FGET_SEED_RNG #define FNAMEOF_fpack_rng FPACK_RNG #define FNAMEOF_funpack_rng FUNPACK_RNG #define FNAMEOF_fprint_rng FPRINT_RNG #define FNAMEOF_finit_rng_sim FINIT_RNG_SIM #define FNAMEOF_fget_rn_int_sim FGET_RN_INT_SIM #define FNAMEOF_fget_rn_flt_sim FGET_RN_FLT_SIM #define FNAMEOF_fget_rn_dbl_sim FGET_RN_DBL_SIM #define FNAMEOF_finit_rng_simmpi FINIT_RNG_SIMMPI #define FNAMEOF_fget_rn_int_simmpi FGET_RN_INT_SIMMPI #define FNAMEOF_fget_rn_flt_simmpi FGET_RN_FLT_SIMMPI #define FNAMEOF_fget_rn_dbl_simmpi FGET_RN_DBL_SIMMPI #define FNAMEOF_fpack_rng_simple FPACK_RNG_SIMPLE #define FNAMEOF_funpack_rng_simple FUNPACK_RNG_SIMPLE #define FNAMEOF_fprint_rng_simple FPRINT_RNG_SIMPLE #define FNAMEOF_finit_rng_ptr FINIT_RNG_PTR #define FNAMEOF_fget_rn_int_ptr FGET_RN_INT_PTR #define FNAMEOF_fget_rn_flt_ptr FGET_RN_FLT_PTR #define FNAMEOF_fget_rn_dbl_ptr FGET_RN_DBL_PTR #define FNAMEOF_fpack_rng_ptr FPACK_RNG_PTR #define FNAMEOF_funpack_rng_ptr FUNPACK_RNG_PTR #define FNAMEOF_fprint_rng_ptr FPRINT_RNG_PTR #define FNAMEOF_ffree_rng_ptr FFREE_RNG_PTR #define FNAMEOF_fspawn_rng_ptr FSPAWN_RNG_PTR #define FNAMEOF_fcpu_t FCPU_T #else #define FNAMEOF_ffree_rng FORTRAN_CALLABLE(ffree_rng) #define FNAMEOF_fmake_new_seed FORTRAN_CALLABLE(fmake_new_seed) #define FNAMEOF_fseed_mpi FORTRAN_CALLABLE(fseed_mpi) #define FNAMEOF_finit_rng FORTRAN_CALLABLE(finit_rng) #define FNAMEOF_fspawn_rng FORTRAN_CALLABLE(fspawn_rng) #define FNAMEOF_fget_rn_int FORTRAN_CALLABLE(fget_rn_int) #define FNAMEOF_fget_rn_flt FORTRAN_CALLABLE(fget_rn_flt) #define FNAMEOF_fget_rn_dbl FORTRAN_CALLABLE(fget_rn_dbl) #define FNAMEOF_fget_seed_rng FORTRAN_CALLABLE(fget_seed_rng) #define FNAMEOF_fpack_rng FORTRAN_CALLABLE(fpack_rng) #define FNAMEOF_funpack_rng FORTRAN_CALLABLE(funpack_rng) #define FNAMEOF_fprint_rng FORTRAN_CALLABLE(fprint_rng) #define FNAMEOF_finit_rng_sim FORTRAN_CALLABLE(finit_rng_sim) #define FNAMEOF_fget_rn_int_sim FORTRAN_CALLABLE(fget_rn_int_sim) #define FNAMEOF_fget_rn_flt_sim FORTRAN_CALLABLE(fget_rn_flt_sim) #define FNAMEOF_fget_rn_dbl_sim FORTRAN_CALLABLE(fget_rn_dbl_sim) #define FNAMEOF_finit_rng_simmpi FORTRAN_CALLABLE(finit_rng_simmpi) #define FNAMEOF_fget_rn_int_simmpi FORTRAN_CALLABLE(fget_rn_int_simmpi) #define FNAMEOF_fget_rn_flt_simmpi FORTRAN_CALLABLE(fget_rn_flt_simmpi) #define FNAMEOF_fget_rn_dbl_simmpi FORTRAN_CALLABLE(fget_rn_dbl_simmpi) #define FNAMEOF_fpack_rng_simple FORTRAN_CALLABLE(fpack_rng_simple) #define FNAMEOF_funpack_rng_simple FORTRAN_CALLABLE(funpack_rng_simple) #define FNAMEOF_fprint_rng_simple FORTRAN_CALLABLE(fprint_rng_simple) #define FNAMEOF_finit_rng_ptr FORTRAN_CALLABLE(finit_rng_ptr) #define FNAMEOF_fget_rn_int_ptr FORTRAN_CALLABLE(fget_rn_int_ptr) #define FNAMEOF_fget_rn_flt_ptr FORTRAN_CALLABLE(fget_rn_flt_ptr) #define FNAMEOF_fget_rn_dbl_ptr FORTRAN_CALLABLE(fget_rn_dbl_ptr) #define FNAMEOF_fpack_rng_ptr FORTRAN_CALLABLE(fpack_rng_ptr) #define FNAMEOF_funpack_rng_ptr FORTRAN_CALLABLE(funpack_rng_ptr) #define FNAMEOF_fprint_rng_ptr FORTRAN_CALLABLE(fprint_rng_ptr) #define FNAMEOF_ffree_rng_ptr FORTRAN_CALLABLE(ffree_rng_ptr) #define FNAMEOF_fspawn_rng_ptr FORTRAN_CALLABLE(fspawn_rng_ptr) #define FNAMEOF_fcpu_t FORTRAN_CALLABLE(fcpu_t) #endif #endif
GCZhang/Profugus
packages/Utils/rng/sprng/fwrap_.h
#include <mc/config.h> #include "fwrap.h" /************************************************************************/ /************************************************************************/ /* */ /* This package of C wrappers is intended to be called from a */ /* FORTRAN program. The main purpose of the package is to mediate */ /* between the call-by-address and call-by-value conventions in */ /* the two languages. In most cases, the arguments of the C */ /* routines and the wrappers are the same. There are two */ /* exceptions to this. The trivial exception is that the C number */ /* scheme of 0 thru N-1 is automatically converted to the FORTRAN */ /* scheme of 1 thru N, so when referring to a particular generator */ /* the FORTRAN user should number as is natural to that language. */ /* */ /* */ /* The wrappers should be treated as FORTRAN function calls. */ /* */ /************************************************************************/ /************************************************************************/ #if __STDC__ int FNAMEOF_fget_seed_rng(int **genptr) #else int FNAMEOF_fget_seed_rng(genptr) int **genptr; #endif { return get_seed_rng(*genptr); } #if __STDC__ int FNAMEOF_ffree_rng_ptr(int **genptr) #else int FNAMEOF_ffree_rng_ptr(genptr) int **genptr; #endif { if (deleteID(*genptr) == NULL) return -1; return free_rng(*genptr); } #if __STDC__ int FNAMEOF_ffree_rng(int **genptr) #else int FNAMEOF_ffree_rng(genptr) int **genptr; #endif { return free_rng(*genptr); } #if __STDC__ int FNAMEOF_fmake_new_seed(void) #else int FNAMEOF_fmake_new_seed() #endif { return make_new_seed(); } #if __STDC__ int * FNAMEOF_finit_rng_sim( int *seed, int *mult) #else int * FNAMEOF_finit_rng_sim(seed,mult) int *mult,*seed; #endif { return init_rng_simple(*seed, *mult); } #if __STDC__ int * FNAMEOF_finit_rng( int *gennum, int *total_gen, int *seed, int *length) #else int * FNAMEOF_finit_rng(gennum, total_gen, seed, length) int *gennum, *length, *seed, *total_gen; #endif { return init_rng(*gennum-1, *total_gen, *seed, *length); } #if __STDC__ int * FNAMEOF_finit_rng_ptr( int *gennum, int *total_gen, int *seed, int *length) #else int * FNAMEOF_finit_rng_ptr(gennum, total_gen, seed, length) int *gennum, *length, *seed, *total_gen; #endif { int *tmpGen; tmpGen = init_rng(*gennum-1, *total_gen, *seed, *length); addID(tmpGen); return tmpGen; } #if __STDC__ int FNAMEOF_fspawn_rng(int **genptr, int *nspawned, int **newGen, int checkid) #else int FNAMEOF_fspawn_rng(genptr, nspawned, newGen, checkid) int **genptr, *nspawned, **newGen, checkid; #endif { int i, **tmpGen, n; n = spawn_rng(*genptr, *nspawned, &tmpGen, checkid); for (i=0; i< n; i++) newGen[i] = tmpGen[i]; if(n != 0) free( tmpGen); return n; } #if __STDC__ int FNAMEOF_fspawn_rng_ptr(int **genptr, int *nspawned, int **newGen, int checkid) #else int FNAMEOF_fspawn_rng_ptr(genptr, nspawned, newGen, checkid) int **genptr, *nspawned, **newGen, checkid; #endif { int i, **tmpGen, n; if (checkID(*genptr) == NULL) return 0; n = spawn_rng(*genptr, *nspawned, &tmpGen, checkid); for (i=0; i< n; i++) newGen[i] = tmpGen[i]; if(n != 0) free( tmpGen); return n; } #if __STDC__ int FNAMEOF_fget_rn_int_sim(void) #else int FNAMEOF_fget_rn_int_sim() #endif { return get_rn_int_simple(); } #if __STDC__ int FNAMEOF_fget_rn_int(int **genptr) #else int FNAMEOF_fget_rn_int(genptr) int **genptr; #endif { return get_rn_int(*genptr); } #if __STDC__ int FNAMEOF_fget_rn_int_ptr(int **genptr) #else int FNAMEOF_fget_rn_int_ptr(genptr) int **genptr; #endif { if (checkID(*genptr)==NULL) return -1; return get_rn_int(*genptr); } #if __STDC__ float FNAMEOF_fget_rn_flt_sim(void) #else float FNAMEOF_fget_rn_flt_sim() #endif { return get_rn_flt_simple(); } #if __STDC__ float FNAMEOF_fget_rn_flt(int **genptr) #else float FNAMEOF_fget_rn_flt(genptr) int **genptr; #endif { return get_rn_flt(*genptr); } #if __STDC__ float FNAMEOF_fget_rn_flt_ptr(int **genptr) #else float FNAMEOF_fget_rn_flt_ptr(genptr) int **genptr; #endif { if (checkID(*genptr)==NULL) return -1.0; return get_rn_flt(*genptr); } #if __STDC__ double FNAMEOF_fget_rn_dbl_sim(void) #else double FNAMEOF_fget_rn_dbl_sim() #endif { return get_rn_dbl_simple(); } #if __STDC__ double FNAMEOF_fget_rn_dbl(int **genptr) #else double FNAMEOF_fget_rn_dbl(genptr) int **genptr; #endif { return get_rn_dbl(*genptr); } #if __STDC__ double FNAMEOF_fget_rn_dbl_ptr(int **genptr) #else double FNAMEOF_fget_rn_dbl_ptr(genptr) int **genptr; #endif { if ( checkID(*genptr)==NULL) return -1.0; return get_rn_dbl(*genptr); } #if __STDC__ int FNAMEOF_fpack_rng( int **genptr, char *buffer) #else int FNAMEOF_fpack_rng(genptr, buffer) int **genptr; char *buffer; #endif { int size; char *temp; size = pack_rng(*genptr, &temp); if(temp != NULL) { memcpy(buffer,temp,size); free(temp); } return size; } #if __STDC__ int FNAMEOF_fpack_rng_ptr( int **genptr, char *buffer) #else int FNAMEOF_fpack_rng_ptr(genptr, buffer) int **genptr; char *buffer; #endif { int size; char *temp; if( checkID(*genptr)==NULL) return 0; size = pack_rng(*genptr, &temp); if(temp != NULL) { memcpy(buffer,temp,size); free(temp); } return size; } #if __STDC__ int FNAMEOF_fpack_rng_simple(char *buffer) #else int FNAMEOF_fpack_rng_simple(buffer) char *buffer; #endif { int size; char *temp; size = pack_rng_simple(&temp); if(temp != NULL) { memcpy(buffer,temp,size); free(temp); } return size; } #if __STDC__ int * FNAMEOF_funpack_rng( char *buffer) #else int * FNAMEOF_funpack_rng(buffer) char *buffer; #endif { return unpack_rng(buffer); } #if __STDC__ int * FNAMEOF_funpack_rng_ptr( char *buffer) #else int * FNAMEOF_funpack_rng_ptr(buffer) char *buffer; #endif { int *tmpGen; tmpGen = unpack_rng(buffer); addID(tmpGen); return tmpGen; } #if __STDC__ int * FNAMEOF_funpack_rng_simple( char *buffer) #else int * FNAMEOF_funpack_rng_simple(buffer) char *buffer; #endif { return unpack_rng_simple(buffer); } /* 11/15/96 J.J.: split into two cases: general print_rng, and print_rng_ptr #if __STDC__ int FNAMEOF_fprint_rng( int **genptr,int checkid) #else int FNAMEOF_fprint_rng(genptr, checkid) int **genptr, checkid; #endif { if(checkid != 0) if(checkID(*genptr) == NULL) return 0; return print_rng(*genptr); } */ #if __STDC__ int FNAMEOF_fprint_rng( int **genptr) #else int FNAMEOF_fprint_rng(genptr) int **genptr; #endif { return print_rng(*genptr); } #if __STDC__ int FNAMEOF_fprint_rng_simple(void) #else int FNAMEOF_fprint_rng_simple() #endif { return print_rng_simple(); } #if __STDC__ int FNAMEOF_fprint_rng_ptr( int **genptr) #else int FNAMEOF_fprint_rng_ptr(genptr) int **genptr; #endif { if(checkID(*genptr) == NULL) return 0; return print_rng(*genptr); }
GCZhang/Profugus
packages/Utils/rng/sprng/lfg.c
<gh_stars>10-100 /*CRCrem: 1571591324 This is an optional comment */ /*************************************************************************/ /*************************************************************************/ /* A MULTI-PROCESSOR LAGGED-FIBONACCI RANDOM NUMBER GENERATION SYSTEM */ /* */ /* Authors: <NAME> and <NAME>, */ /* IDA/Center for Computing Sciences (CCS) */ /* E-Mail: <EMAIL> <EMAIL> */ /* */ /* Copyright 1996 September 3, United States Government as Represented */ /* by the Director, National Security Agency. All rights reserved. */ /* */ /* Disclaimer: CCS expressly disclaims any and all warranties, expressed */ /* or implied, concerning the enclosed software. This software was */ /* developed at CCS for use in internal research. The intent in sharing */ /* this software is to promote the productive interchange of ideas */ /* throughout the research community. All software is furnished on an */ /* "as is" basis. No further updates to this software should be */ /* expected. Although this may occur, no commitment exists. The authors */ /* certainly invite your comments as well as the reporting of any bugs. */ /* CCS cannot commit that any or all bugs will be fixed. */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* This version has been modified to use two integer-based additive */ /* lagged-Fibonacci generators to produce integer, float and double */ /* values. The lagged-Fibonacci generators each have 31 bits of */ /* precision (after the bit fixed by the canonical form of the */ /* generator is removed), 31-bit values are generated by XORing */ /* the values after one has been shifted left one bit. The floating */ /* point value is formed by dividing the integer by 1.e+32 (the */ /* lsb's will be dropped from the mantissa to make room for the */ /* exponent), and two of these integer values in sequence are used */ /* to get the necessary precision for the double value. */ /* */ /* This method has the advantage that the generators pass fairly */ /* strict randomness tests, including the Birthday Spacings test */ /* that additive lagged-Fibonacci generators are well known to */ /* fail. The disadvantage is the additional time needed to do the */ /* division explicitly, which was avoided in previous versions. */ /* (As the division is by powers of 2, the user might well consider */ /* making machine-specific versions of this code to insert the bits */ /* into the appropriate places and avoid the problem entirely.) */ /*************************************************************************/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <math.h> #include <assert.h> #include "interface.h" #include "memory.h" /*#define PRINT_GEN*/ /* BITS_IN_INT_GEN is the log_2 of the modulus of the generator */ /* for portability this is set to 32, but can be modified; */ /* if modified, make sure INT_MOD_MASK can still be calculated */ #define BITS_IN_INT_GEN 32 /* INT_MOD_MASK is used to perform modular arithmetic - specifying */ /* this value compensates for different sized words on */ /* different architectures */ /* FLT_MULT is used in converting to float and double values; the */ /* odd form is due to a compiler glitch on our CM-5, which */ /* caused (0.5/(unsigned)(1<<31)) to be negative. */ #if (BITS_IN_INT_GEN==32) #define INT_MOD_MASK 0xffffffff #define INT_MOD_MASK2 0xfffffffe #define FLT_MULT (0.25f/(unsigned)((1u<<30) + (1u << 7))) #define DBL_MULT (0.25/(unsigned)(1<<30)) #else #define INT_MOD_MASK ((unsigned)(1<<BITS_IN_INT_GEN)-1) #define FLT_MULT (1.0f/(1<<BITS_IN_INT_GEN)) #define DBL_MULT (1.0/(1<<BITS_IN_INT_GEN)) #endif /* INT_MASK is used to mask out the part of the generator which */ /* is not in the canonical form; it should be */ /* 2^{BITS_IN_INT_GEN-1}-1 */ #define INT_MASK ((unsigned)INT_MOD_MASK>>1) /* MAX_BIT_INT is the largest bit position allowed in the index */ /* of the node - it equals BITS_IN_INT_GEN - 2 */ #define MAX_BIT_INT (BITS_IN_INT_GEN-2) /* INTX2_MASK is used in calculation of the node numbers */ #define INTX2_MASK ((1<<MAX_BIT_INT)-1) /* RUNUP keeps certain generators from looking too similar in the */ /* first few words output */ #define RUNUP (2*BITS_IN_INT_GEN) /* GS0 gives a more "random" distribution of generators when the */ /* user uses small integers as seeds */ #define GS0 0x372f05ac #define TOOMANY "generator has branched maximum number of times;\nindependence of generators no longer guaranteed" /*************************************************************************/ /*************************************************************************/ /* STRUCTURES AND GLOBAL DATA */ /*************************************************************************/ /*************************************************************************/ struct lfgen { unsigned *si; /* sets next branch seed */ unsigned *r0; /* pointer to the even generator */ unsigned *r1; /* pointer to the odd generator */ int hptr; /* integer pointer into fill */ int seed; int init_seed; int lval, kval; int param; }; int MAX_STREAMS=0x7fffffff; struct vstruct { int L; int K; int LSBS; /* number of least significant bits that are 1 */ int first; /* the first seed whose LSB is 1 */ }; const struct vstruct valid[] = { {1279,861,1,233}, {17,5,1,10}, {31,6,1,2}, {55,24,1,11}, {63,31,1,14}, {127,97,1,21}, {521,353,1,100}, {521,168,1,83}, {607,334,1,166}, {607,273,1,105}, {1279,418,1,208} }; #define NPARAMS 11 int gseed=0,lval=0,kval=0; int NGENS = 0; /*************************************************************************/ /*************************************************************************/ /* ERROR PRINTING FUNCTION */ /*************************************************************************/ /*************************************************************************/ #if __STDC__ static void errprint(char *level, char *routine, char *error) #else static int errprint(level, routine, error) char *level,*routine,*error; #endif { fprintf(stderr,"%s from %s: %s\n",level,routine,error); } /*************************************************************************/ /*************************************************************************/ /* ROUTINES USED TO CREATE GENERATOR FILLS */ /*************************************************************************/ /*************************************************************************/ /* The number of bits set in the binary representation of the integers 0-255 */ static const unsigned bitcount[256] = { 0, /* 0 */ 1, /* 1 */ 1, /* 2 */ 2, /* 3 */ 1, /* 4 */ 2, /* 5 */ 2, /* 6 */ 3, /* 7 */ 1, /* 8 */ 2, /* 9 */ 2, /* 10 */ 3, /* 11 */ 2, /* 12 */ 3, /* 13 */ 3, /* 14 */ 4, /* 15 */ 1, /* 16 */ 2, /* 17 */ 2, /* 18 */ 3, /* 19 */ 2, /* 20 */ 3, /* 21 */ 3, /* 22 */ 4, /* 23 */ 2, /* 24 */ 3, /* 25 */ 3, /* 26 */ 4, /* 27 */ 3, /* 28 */ 4, /* 29 */ 4, /* 30 */ 5, /* 31 */ 1, /* 32 */ 2, /* 33 */ 2, /* 34 */ 3, /* 35 */ 2, /* 36 */ 3, /* 37 */ 3, /* 38 */ 4, /* 39 */ 2, /* 40 */ 3, /* 41 */ 3, /* 42 */ 4, /* 43 */ 3, /* 44 */ 4, /* 45 */ 4, /* 46 */ 5, /* 47 */ 2, /* 48 */ 3, /* 49 */ 3, /* 50 */ 4, /* 51 */ 3, /* 52 */ 4, /* 53 */ 4, /* 54 */ 5, /* 55 */ 3, /* 56 */ 4, /* 57 */ 4, /* 58 */ 5, /* 59 */ 4, /* 60 */ 5, /* 61 */ 5, /* 62 */ 6, /* 63 */ 1, /* 64 */ 2, /* 65 */ 2, /* 66 */ 3, /* 67 */ 2, /* 68 */ 3, /* 69 */ 3, /* 70 */ 4, /* 71 */ 2, /* 72 */ 3, /* 73 */ 3, /* 74 */ 4, /* 75 */ 3, /* 76 */ 4, /* 77 */ 4, /* 78 */ 5, /* 79 */ 2, /* 80 */ 3, /* 81 */ 3, /* 82 */ 4, /* 83 */ 3, /* 84 */ 4, /* 85 */ 4, /* 86 */ 5, /* 87 */ 3, /* 88 */ 4, /* 89 */ 4, /* 90 */ 5, /* 91 */ 4, /* 92 */ 5, /* 93 */ 5, /* 94 */ 6, /* 95 */ 2, /* 96 */ 3, /* 97 */ 3, /* 98 */ 4, /* 99 */ 3, /* 100 */ 4, /* 101 */ 4, /* 102 */ 5, /* 103 */ 3, /* 104 */ 4, /* 105 */ 4, /* 106 */ 5, /* 107 */ 4, /* 108 */ 5, /* 109 */ 5, /* 110 */ 6, /* 111 */ 3, /* 112 */ 4, /* 113 */ 4, /* 114 */ 5, /* 115 */ 4, /* 116 */ 5, /* 117 */ 5, /* 118 */ 6, /* 119 */ 4, /* 120 */ 5, /* 121 */ 5, /* 122 */ 6, /* 123 */ 5, /* 124 */ 6, /* 125 */ 6, /* 126 */ 7, /* 127 */ 1, /* 128 */ 2, /* 129 */ 2, /* 130 */ 3, /* 131 */ 2, /* 132 */ 3, /* 133 */ 3, /* 134 */ 4, /* 135 */ 2, /* 136 */ 3, /* 137 */ 3, /* 138 */ 4, /* 139 */ 3, /* 140 */ 4, /* 141 */ 4, /* 142 */ 5, /* 143 */ 2, /* 144 */ 3, /* 145 */ 3, /* 146 */ 4, /* 147 */ 3, /* 148 */ 4, /* 149 */ 4, /* 150 */ 5, /* 151 */ 3, /* 152 */ 4, /* 153 */ 4, /* 154 */ 5, /* 155 */ 4, /* 156 */ 5, /* 157 */ 5, /* 158 */ 6, /* 159 */ 2, /* 160 */ 3, /* 161 */ 3, /* 162 */ 4, /* 163 */ 3, /* 164 */ 4, /* 165 */ 4, /* 166 */ 5, /* 167 */ 3, /* 168 */ 4, /* 169 */ 4, /* 170 */ 5, /* 171 */ 4, /* 172 */ 5, /* 173 */ 5, /* 174 */ 6, /* 175 */ 3, /* 176 */ 4, /* 177 */ 4, /* 178 */ 5, /* 179 */ 4, /* 180 */ 5, /* 181 */ 5, /* 182 */ 6, /* 183 */ 4, /* 184 */ 5, /* 185 */ 5, /* 186 */ 6, /* 187 */ 5, /* 188 */ 6, /* 189 */ 6, /* 190 */ 7, /* 191 */ 2, /* 192 */ 3, /* 193 */ 3, /* 194 */ 4, /* 195 */ 3, /* 196 */ 4, /* 197 */ 4, /* 198 */ 5, /* 199 */ 3, /* 200 */ 4, /* 201 */ 4, /* 202 */ 5, /* 203 */ 4, /* 204 */ 5, /* 205 */ 5, /* 206 */ 6, /* 207 */ 3, /* 208 */ 4, /* 209 */ 4, /* 210 */ 5, /* 211 */ 4, /* 212 */ 5, /* 213 */ 5, /* 214 */ 6, /* 215 */ 4, /* 216 */ 5, /* 217 */ 5, /* 218 */ 6, /* 219 */ 5, /* 220 */ 6, /* 221 */ 6, /* 222 */ 7, /* 223 */ 3, /* 224 */ 4, /* 225 */ 4, /* 226 */ 5, /* 227 */ 4, /* 228 */ 5, /* 229 */ 5, /* 230 */ 6, /* 231 */ 4, /* 232 */ 5, /* 233 */ 5, /* 234 */ 6, /* 235 */ 5, /* 236 */ 6, /* 237 */ 6, /* 238 */ 7, /* 239 */ 4, /* 240 */ 5, /* 241 */ 5, /* 242 */ 6, /* 243 */ 5, /* 244 */ 6, /* 245 */ 6, /* 246 */ 7, /* 247 */ 5, /* 248 */ 6, /* 249 */ 6, /* 250 */ 7, /* 251 */ 6, /* 252 */ 7, /* 253 */ 7, /* 254 */ 8 /* 255 */ }; /* Given the code snippet: const unsigned mask = 0x1b; unsigned new_fill = 0; for (i=0; i < 4; ++i) new_fill |= (1&bitcount[(val >> i)&mask]) << i; the following array precomputes values of new_fill for val=0..255 */ static const unsigned mask_gen[256] = { 0, /* 0 */ 1, /* 1 */ 3, /* 2 */ 2, /* 3 */ 6, /* 4 */ 7, /* 5 */ 5, /* 6 */ 4, /* 7 */ 13, /* 8 */ 12, /* 9 */ 14, /* 10 */ 15, /* 11 */ 11, /* 12 */ 10, /* 13 */ 8, /* 14 */ 9, /* 15 */ 11, /* 16 */ 10, /* 17 */ 8, /* 18 */ 9, /* 19 */ 13, /* 20 */ 12, /* 21 */ 14, /* 22 */ 15, /* 23 */ 6, /* 24 */ 7, /* 25 */ 5, /* 26 */ 4, /* 27 */ 0, /* 28 */ 1, /* 29 */ 3, /* 30 */ 2, /* 31 */ 6, /* 32 */ 7, /* 33 */ 5, /* 34 */ 4, /* 35 */ 0, /* 36 */ 1, /* 37 */ 3, /* 38 */ 2, /* 39 */ 11, /* 40 */ 10, /* 41 */ 8, /* 42 */ 9, /* 43 */ 13, /* 44 */ 12, /* 45 */ 14, /* 46 */ 15, /* 47 */ 13, /* 48 */ 12, /* 49 */ 14, /* 50 */ 15, /* 51 */ 11, /* 52 */ 10, /* 53 */ 8, /* 54 */ 9, /* 55 */ 0, /* 56 */ 1, /* 57 */ 3, /* 58 */ 2, /* 59 */ 6, /* 60 */ 7, /* 61 */ 5, /* 62 */ 4, /* 63 */ 12, /* 64 */ 13, /* 65 */ 15, /* 66 */ 14, /* 67 */ 10, /* 68 */ 11, /* 69 */ 9, /* 70 */ 8, /* 71 */ 1, /* 72 */ 0, /* 73 */ 2, /* 74 */ 3, /* 75 */ 7, /* 76 */ 6, /* 77 */ 4, /* 78 */ 5, /* 79 */ 7, /* 80 */ 6, /* 81 */ 4, /* 82 */ 5, /* 83 */ 1, /* 84 */ 0, /* 85 */ 2, /* 86 */ 3, /* 87 */ 10, /* 88 */ 11, /* 89 */ 9, /* 90 */ 8, /* 91 */ 12, /* 92 */ 13, /* 93 */ 15, /* 94 */ 14, /* 95 */ 10, /* 96 */ 11, /* 97 */ 9, /* 98 */ 8, /* 99 */ 12, /* 100 */ 13, /* 101 */ 15, /* 102 */ 14, /* 103 */ 7, /* 104 */ 6, /* 105 */ 4, /* 106 */ 5, /* 107 */ 1, /* 108 */ 0, /* 109 */ 2, /* 110 */ 3, /* 111 */ 1, /* 112 */ 0, /* 113 */ 2, /* 114 */ 3, /* 115 */ 7, /* 116 */ 6, /* 117 */ 4, /* 118 */ 5, /* 119 */ 12, /* 120 */ 13, /* 121 */ 15, /* 122 */ 14, /* 123 */ 10, /* 124 */ 11, /* 125 */ 9, /* 126 */ 8, /* 127 */ 8, /* 128 */ 9, /* 129 */ 11, /* 130 */ 10, /* 131 */ 14, /* 132 */ 15, /* 133 */ 13, /* 134 */ 12, /* 135 */ 5, /* 136 */ 4, /* 137 */ 6, /* 138 */ 7, /* 139 */ 3, /* 140 */ 2, /* 141 */ 0, /* 142 */ 1, /* 143 */ 3, /* 144 */ 2, /* 145 */ 0, /* 146 */ 1, /* 147 */ 5, /* 148 */ 4, /* 149 */ 6, /* 150 */ 7, /* 151 */ 14, /* 152 */ 15, /* 153 */ 13, /* 154 */ 12, /* 155 */ 8, /* 156 */ 9, /* 157 */ 11, /* 158 */ 10, /* 159 */ 14, /* 160 */ 15, /* 161 */ 13, /* 162 */ 12, /* 163 */ 8, /* 164 */ 9, /* 165 */ 11, /* 166 */ 10, /* 167 */ 3, /* 168 */ 2, /* 169 */ 0, /* 170 */ 1, /* 171 */ 5, /* 172 */ 4, /* 173 */ 6, /* 174 */ 7, /* 175 */ 5, /* 176 */ 4, /* 177 */ 6, /* 178 */ 7, /* 179 */ 3, /* 180 */ 2, /* 181 */ 0, /* 182 */ 1, /* 183 */ 8, /* 184 */ 9, /* 185 */ 11, /* 186 */ 10, /* 187 */ 14, /* 188 */ 15, /* 189 */ 13, /* 190 */ 12, /* 191 */ 4, /* 192 */ 5, /* 193 */ 7, /* 194 */ 6, /* 195 */ 2, /* 196 */ 3, /* 197 */ 1, /* 198 */ 0, /* 199 */ 9, /* 200 */ 8, /* 201 */ 10, /* 202 */ 11, /* 203 */ 15, /* 204 */ 14, /* 205 */ 12, /* 206 */ 13, /* 207 */ 15, /* 208 */ 14, /* 209 */ 12, /* 210 */ 13, /* 211 */ 9, /* 212 */ 8, /* 213 */ 10, /* 214 */ 11, /* 215 */ 2, /* 216 */ 3, /* 217 */ 1, /* 218 */ 0, /* 219 */ 4, /* 220 */ 5, /* 221 */ 7, /* 222 */ 6, /* 223 */ 2, /* 224 */ 3, /* 225 */ 1, /* 226 */ 0, /* 227 */ 4, /* 228 */ 5, /* 229 */ 7, /* 230 */ 6, /* 231 */ 15, /* 232 */ 14, /* 233 */ 12, /* 234 */ 13, /* 235 */ 9, /* 236 */ 8, /* 237 */ 10, /* 238 */ 11, /* 239 */ 9, /* 240 */ 8, /* 241 */ 10, /* 242 */ 11, /* 243 */ 15, /* 244 */ 14, /* 245 */ 12, /* 246 */ 13, /* 247 */ 4, /* 248 */ 5, /* 249 */ 7, /* 250 */ 6, /* 251 */ 2, /* 252 */ 3, /* 253 */ 1, /* 254 */ 0 /* 255 */ }; /**************************/ /* function advance_reg: */ /**************************/ #if __STDC__ static void advance_reg(int *reg_fill) #else static void advance_reg(reg_fill) int *reg_fill; #endif { /* the register steps according to the primitive polynomial */ /* (64,4,3,1,0); each call steps register 64 times */ /* we use two words to represent the register to allow for integer */ /* size of 32 bits */ /* NOTE: if this changes from 0x1b, the contents of the mask_gen array need to be recomputed! */ const unsigned int mask = 0x1b; int i; unsigned new_fill0 = 0; unsigned new_fill1 = 0; unsigned temp; const unsigned urf0 = (unsigned)reg_fill[0]; const unsigned urf1 = (unsigned)reg_fill[1]; const unsigned urf0_sr_24 = urf0 >> 24; /* Commenting out to avoid unused variable warning - TME const unsigned adv_64[4][2] = { {0xb0000000, 0x1b}, {0x60000000, 0x2d}, {0xc0000000, 0x5a}, {0x80000000, 0xaf} }; */ for (i=0; i < 28; i+=4) { new_fill0 |= mask_gen[(urf0 >> i)&255] << i; new_fill1 |= mask_gen[(urf1 >> i)&255] << i; } /* i = 28 */ temp = bitcount[(urf0 >> 28)&mask]; temp ^= bitcount[urf1&(mask>>4)]; new_fill0 |= (1&temp)<<28; temp = bitcount[urf0_sr_24 & 0xb0]; temp ^= bitcount[urf1 & 0x1b]; new_fill1 |= (1&temp)<<28; /* i = 29 */ temp = bitcount[(urf0 >> 29)&mask]; temp ^= bitcount[urf1&(mask>>3)]; new_fill0 |= (1&temp)<<29; temp = bitcount[urf0_sr_24 & 0x60]; temp ^= bitcount[urf1 & 0x2d]; new_fill1 |= (1&temp)<<29; /* i = 30 */ temp = bitcount[(urf0 >> 30)&mask]; temp ^= bitcount[urf1&(mask>>2)]; new_fill0 |= (1&temp)<<30; temp = bitcount[urf0_sr_24 & 0xc0]; temp ^= bitcount[urf1 & 0x5a]; new_fill1 |= (1&temp)<<30; /* i = 31 */ temp = bitcount[(urf0 >> 31)&mask]; temp ^= bitcount[urf1&(mask>>1)]; new_fill0 |= (1&temp)<<31; temp = bitcount[urf0_sr_24 & 0x80]; temp ^= bitcount[urf1 & 0xaf]; new_fill1 |= (1&temp)<<31; reg_fill[0] = new_fill0; reg_fill[1] = new_fill1; } /**************************/ /* function get_fill: */ /**************************/ #if __STDC__ static int get_fill( unsigned *n, unsigned *r, int param, unsigned seed) #else static int get_fill(n,r, param, seed) unsigned *n, *r, seed; int param; #endif { int i,j,k,temp[2]; const int length = valid[param].L; /* initialize the shift register with the node number XORed with */ /* the global seed */ /* fill the shift register with two copies of this number */ /* except when equal to zero */ temp[1] = temp[0] = n[0]^seed; if (!temp[0]) temp[0] = GS0; /* advance the shift register some */ advance_reg(temp); advance_reg(temp); /* the first word in the generator is defined by the 31 LSBs of the */ /* node number */ r[0] = (INT_MASK&n[0])<<1; /* the generator is filled with the lower 31 bits of the shift */ /* register at each time, shifted up to make room for the bits */ /* defining the canonical form; the node number is XORed into */ /* the fill to make the generators unique */ for (i=1;i<length-1;i++) { advance_reg(temp); r[i] = (INT_MASK&(temp[0]^n[i]))<<1; } r[length-1] = 0; /* the canonical form for the LSB is instituted here */ k = valid[param].first + valid[param].LSBS; for (j=valid[param].first;j<k;j++) r[j] |= 1; return(0); } /*************************************************************************/ /*************************************************************************/ /* SI_DOUBLE: updates index for next spawning */ /*************************************************************************/ /*************************************************************************/ #if __STDC__ static void si_double(unsigned *a, unsigned *b, int length) #else static void si_double(a,b, length) unsigned *a,*b; int length; #endif { int i; if (b[length-2]&(1<<MAX_BIT_INT)) errprint("WARNING","si_double",TOOMANY); a[length-2] = (INTX2_MASK&b[length-2])<<1; for (i=length-3;i>=0;i--) { if (b[i]&(1<<MAX_BIT_INT)) a[i+1]++; a[i] = (INTX2_MASK&b[i])<<1; } } /*************************************************************************/ /*************************************************************************/ /* GET_RN: returns generated random number */ /*************************************************************************/ /*************************************************************************/ #if __STDC__ int get_rn_int(int *genptr) #else int get_rn_int(genptr) int *genptr; #endif /* returns value put into new position */ { unsigned new_val,*r0,*r1; int hptr,lptr,*hp = &((struct lfgen *)genptr)->hptr; int lval, kval; lval = ((struct lfgen *)genptr)->lval; kval = ((struct lfgen *)genptr)->kval; r0 = ((struct lfgen *)genptr)->r0; r1 = ((struct lfgen *)genptr)->r1; hptr = *hp; lptr = hptr + kval; if (lptr>=lval) lptr -= lval; /* INT_MOD_MASK causes arithmetic to be modular when integer size is */ /* different from generator modulus */ r0[hptr] = INT_MOD_MASK&(r0[hptr] + r0[lptr]); r1[hptr] = INT_MOD_MASK&(r1[hptr] + r1[lptr]); new_val = (r1[hptr]&(~1)) ^ (r0[hptr]>>1); if (--hptr < 0) hptr = lval - 1; /* skip an element in the sequence */ if (--lptr < 0) lptr = lval - 1; r0[hptr] = INT_MOD_MASK&(r0[hptr] + r0[lptr]); r1[hptr] = INT_MOD_MASK&(r1[hptr] + r1[lptr]); *hp = (--hptr < 0) ? lval-1 : hptr; return (new_val>>1); } #if __STDC__ float get_rn_flt(int *genptr) #else float get_rn_flt(genptr) int *genptr; #endif /* returns value put into new position */ { unsigned long new_val; /* this cannot be unsigned int due to a bug in the SGI compiler */ unsigned *r0,*r1; int hptr,lptr,*hp = &((struct lfgen *)genptr)->hptr; int lval, kval; lval = ((struct lfgen *)genptr)->lval; kval = ((struct lfgen *)genptr)->kval; r0 = ((struct lfgen *)genptr)->r0; r1 = ((struct lfgen *)genptr)->r1; hptr = *hp; lptr = hptr + kval; if (lptr>=lval) lptr -= lval; /* INT_MOD_MASK causes arithmetic to be modular when integer size is */ /* different from generator modulus */ r0[hptr] = INT_MOD_MASK & (r0[hptr] + r0[lptr]); r1[hptr] = INT_MOD_MASK & (r1[hptr] + r1[lptr]); new_val = (r1[hptr]&(~1)) ^ (r0[hptr]>>1); if (--hptr < 0) hptr = lval - 1; /* skip an element in the sequence */ if (--lptr < 0) lptr = lval - 1; r0[hptr] = INT_MOD_MASK&(r0[hptr] + r0[lptr]); r1[hptr] = INT_MOD_MASK&(r1[hptr] + r1[lptr]); *hp = (--hptr<0) ? lval-1 : hptr; return (new_val*FLT_MULT); } #if __STDC__ double get_rn_dbl(int *genptr) #else double get_rn_dbl(genptr) int *genptr; #endif /* returns value put into new position */ { unsigned *r0,*r1; unsigned long temp1,temp2; /* Due to a bug in the SGI compiler, this should not be unsigned int */ int hptr,lptr,*hp = &((struct lfgen *)genptr)->hptr; double new_val; int lval, kval; lval = ((struct lfgen *)genptr)->lval; kval = ((struct lfgen *)genptr)->kval; r0 = ((struct lfgen *)genptr)->r0; r1 = ((struct lfgen *)genptr)->r1; hptr = *hp; lptr = hptr + kval; if (lptr>=lval) lptr -= lval; /* INT_MOD_MASK causes arithmetic to be modular when integer size is */ /* different from generator modulus */ r0[hptr] = INT_MOD_MASK&(r0[hptr] + r0[lptr]); r1[hptr] = INT_MOD_MASK&(r1[hptr] + r1[lptr]); temp1 = (r1[hptr]&(~1)) ^ (r0[hptr]>>1); if (--hptr < 0) hptr = lval - 1; if (--lptr < 0) lptr = lval - 1; r0[hptr] = INT_MOD_MASK&(r0[hptr] + r0[lptr]); r1[hptr] = INT_MOD_MASK&(r1[hptr] + r1[lptr]); temp2 = (r1[hptr]&(~1)) ^ (r0[hptr]>>1); *hp = (--hptr < 0) ? lval-1 : hptr; new_val = ((unsigned int)temp2 * (double)DBL_MULT + (unsigned int)temp1) * DBL_MULT; return (new_val); } /*************************************************************************/ /*************************************************************************/ /* INITIALIZE: starts the whole thing going */ /*************************************************************************/ /*************************************************************************/ #define OLD 0 static int *order = 0; static int order_size = 0; static int **initialize(int ngen, int param, unsigned seed, unsigned *nstart, unsigned initseed) { int i,j,k,l; struct lfgen **q; unsigned *nindex; const int length = valid[param].L; const unsigned desired_order_size = ngen * sizeof(int); const unsigned desired_malloc = (3*length-1)*sizeof(unsigned); /* allocate memory for node number and fill of each generator */ if(desired_order_size > order_size) { if(order) free(order); order = (int *) mymalloc(desired_order_size); order_size = desired_order_size; } q = (struct lfgen **) mymalloc(ngen*sizeof(struct lfgen *)); if (q == NULL || order == NULL) return NULL; for (i=0;i<ngen;i++) { q[i] = (struct lfgen *) mymalloc(sizeof(struct lfgen)); if (q[i] == NULL) return NULL; q[i]->hptr = length - 1; #if OLD q[i]->si = (unsigned *) mymalloc((length-1)*sizeof(unsigned)); q[i]->r0 = (unsigned *) mymalloc(length*sizeof(unsigned)); q[i]->r1 = (unsigned *) mymalloc(length*sizeof(unsigned)); #else q[i]->si = (unsigned *) mymalloc(desired_malloc); q[i]->r0 = (unsigned *) (q[i]->si + length - 1); q[i]->r1 = (unsigned *) (q[i]->r0 + length); #endif q[i]->lval = length; q[i]->kval = valid[param].K; q[i]->param = param; q[i]->seed = seed; q[i]->init_seed = initseed; #if OLD if (q[i]->r1 == NULL || q[i]->r0 == NULL || q[i]->si == NULL) return NULL; #else if (q[i]->si == NULL) return NULL; #endif } /* specify register fills and node number arrays */ /* do fills in tree fashion so that all fills branch from index */ /* contained in nstart array */ si_double(q[0]->si,nstart,length); get_fill(q[0]->si,q[0]->r0,param,seed); q[0]->si[0]++; get_fill(q[0]->si,q[0]->r1,param,seed); i = 1; order[0] = 0; if (ngen>1) while (1) { l = i; for (k=0;k<l;k++) { nindex = q[order[k]]->si; si_double(nindex,nindex, length); for (j=0;j<length-1;j++) q[i]->si[j] = nindex[j]; get_fill(q[i]->si,q[i]->r0,param,seed); q[i]->si[0]++; get_fill(q[i]->si,q[i]->r1,param,seed); if (ngen == ++i) break; } if (ngen == i) break; for (k=l-1;k>0;k--) { order[2*k+1] = l+k; order[2*k] = order[k]; } order[1] = l; } for (i=ngen-1;i>=0;i--) { k = 0; for (j=1;j<lval-1 && !k;j++) k = (q[i]->si[j] != 0); if (!k) break; for (j=0;j<length*RUNUP;j++) get_rn_int((int *)(q[i])); } k = length<<2; while (!(i<0)) { for (j = 0; j < k; ++j) get_rn_int((int *)(q[i])); --i; } return((int **)q); } /*************************************************************************/ /*************************************************************************/ /* INIT_RNG's: user interface to start things off */ /*************************************************************************/ /*************************************************************************/ #if __STDC__ int *init_rng( int gennum, int total_gen, int seed, int param) #else int *init_rng(gennum,total_gen,seed,param) int gennum,param,seed,total_gen; #endif { int doexit=0,i,k, length; int **p=NULL, *rng; unsigned *nstart=NULL,*si; /* gives back one generator (node gennum) with updated spawning */ /* info; should be called total_gen times, with different value */ /* of gennum in [0,total_gen) each call */ /* check values of gennum and total_gen */ if (total_gen <= 0) /* check if total_gen is valid */ { total_gen = 1; errprint("WARNING","init_rng","Total_gen <= 0. Default value of 1 used for total_gen"); } if (gennum >= MAX_STREAMS) /* check if gen_num is valid */ fprintf(stderr,"WARNING - init_rng: gennum: %d > maximum number of independent streams: %d\n\tIndependence of streams cannot be guranteed.\n", gennum, MAX_STREAMS); if (gennum < 0 || gennum >= total_gen) /* check if gen_num is valid */ { errprint("ERROR","init_rng","gennum out of range. "); return (int *) NULL; } seed &= 0x7fffffff; /* Only 32 LSB of seed considered */ if (param < 0 || param >= NPARAMS) { errprint("WARNING","init_rng","Parameter not valid. Using Default param"); param = 0; } /* check whether generators have previously been defined */ /* guard against access while defining generator parameters for */ /* the 1st time */ length = valid[param].L; /* determine parameters */ k = valid[param].K; if (!lval) { lval = length; /* determine parameters */ kval = k; gseed = seed^GS0; } else { if (lval != length) doexit++; if( seed != (gseed^GS0) ) doexit += 2; if (doexit) { if (doexit&1) errprint("WARNING","init_rng","changing global L value! Independence of streams is not guaranteed"); if (doexit&2) errprint("WARNING","init_rng","changing global seed value! Independence of streams is not guaranteed"); } } /* define the starting vector for the initial node */ nstart = (unsigned *) mymalloc((length-1)*sizeof(unsigned)); if (nstart == NULL) return NULL; nstart[0] = gennum; for (i=1;i<length-1;i++) nstart[i] = 0; p = initialize(1,param,seed^GS0,nstart,seed); /* create a generator */ if (p==NULL) return NULL; /* update si array to allow for future spawning of generators */ si = ((struct lfgen *)(p[0]))->si; while (si[0] < total_gen && !si[1]) si_double(si,si,length); NGENS++; free(nstart); rng = p[0]; free(p); return rng; } /*************************************************************************/ /*************************************************************************/ /* SPAWN_RNG: spawns new generators */ /*************************************************************************/ /*************************************************************************/ #if __STDC__ int spawn_rng(int *genptr, int nspawned, int ***newgens, int checkid) #else int spawn_rng(genptr,nspawned,newgens, checkid) int *genptr,nspawned, ***newgens, checkid; #endif { int **q=NULL, i; unsigned *p; struct lfgen *temp; if (nspawned <= 0) /* check if nspawned is valid */ { nspawned = 1; errprint("WARNING","spawn_rng","Nspawned <= 0. Default value of 1 used for nspawned"); } temp = (struct lfgen *) genptr; p = temp->si; q = initialize(nspawned,temp->param,temp->seed,p,temp->init_seed); if (q == NULL) { *newgens = NULL; return 0; } si_double(p,p,temp->lval); NGENS += nspawned; *newgens = (int **) q; if(checkid != 0) for(i=0; i<nspawned; i++) if(addID((*newgens)[i]) == NULL) return i; return nspawned; } /*************************************************************************/ /*************************************************************************/ /* UTILITY ROUTINES */ /*************************************************************************/ /*************************************************************************/ /* These functions aren't called anywhere, so comment them out - TME #if __STDC__ static int get_llag_rng(void) #else static int get_llag_rng() #endif { return(lval); } #if __STDC__ static int get_klag_rng(void) #else static int get_klag_rng() #endif { return(kval); } #if __STDC__ static int get_hptr_rng( int *genptr) #else static int get_hptr_rng(genptr) int *genptr; #endif { return (((struct lfgen *)genptr)->hptr); } #if __STDC__ static int *get_fill_rng( int *genptr) #else static int *get_fill_rng(genptr) int *genptr; #endif { int i,*p; unsigned *pp; struct lfgen *temp; temp = (struct lfgen *) genptr; p = (int *) mymalloc(2*(temp->lval)*sizeof(int)); if(p == NULL) return NULL; pp = ((struct lfgen *)genptr)->r0; for (i=0;i<lval;i++) p[i] = pp[i]; pp = ((struct lfgen *)genptr)->r1; for (i=0;i<temp->lval;i++) p[temp->lval+i] = pp[i]; return(p); } #if __STDC__ static int *get_node_index_rng( int *genptr) #else static int *get_node_index_rng(genptr) int *genptr; #endif { int *p, length; length = ( (struct lfgen *) genptr)->lval; p = get_next_index_rng(genptr); if(p == NULL) return NULL; while (!(p[0]&1)) si_halve(p,length); si_halve(p, length); return(p); } #if __STDC__ int get_seed_rng(int *gen) #else int get_seed_rng(gen) int *gen; #endif { return(GS0^gseed); } #if __STDC__ static int *get_next_index_rng( int *genptr) #else static int *get_next_index_rng(genptr) int *genptr; #endif { int i,*p, lval; unsigned *pp; lval = ((struct lfgen *) genptr)->lval; pp = ((struct lfgen *)genptr)->si; p = (int *) mymalloc((lval-1)*sizeof(int)); if(p == NULL) return NULL; for (i=0;i<lval-1;i++) p[i] = pp[i]; return(p); } #if __STDC__ static void si_halve(int *a, int length) #else static void si_halve(a, length) int *a, length; #endif { int i; for (i=0;i<length-2;i++) { a[i] >>= 1; if (a[i+1]&1) a[i] ^= (1<<MAX_BIT_INT); } a[length-2] >>= 1; } */ #if __STDC__ int get_seed_rng(int *gen) #else int get_seed_rng(gen) int *gen; #endif { return(GS0^gseed); } /*************************************************************************/ /*************************************************************************/ /* MESSAGE PASSING ROUTINES */ /*************************************************************************/ /*************************************************************************/ #if __STDC__ int pack_rng( int *genptr, char **buffer) #else int pack_rng(genptr,buffer) int *genptr; char **buffer; #endif { int i,*p, size; struct lfgen *q; q = (struct lfgen *)genptr; size = (3*(q->lval)+4)*sizeof(int); p = (int *) mymalloc(size); if (p == NULL) return 0; p[0] = q->lval; p[1] = q->kval; p[2] = q->seed; p[3] = q->init_seed; for (i=0;i<q->lval-1;i++) p[i+4] = q->si[i]; for (i=0;i<q->lval;i++) p[q->lval+i+3] = q->r0[i]; for (i=0;i<q->lval;i++) p[2*q->lval+i+3] = q->r1[i]; p[3*q->lval+3] = q->hptr; *buffer = (char *) p; return size; } #if __STDC__ int *unpack_rng( char *p) #else int *unpack_rng(p) char *p; #endif { int doexit=0,i, found, length, k, *packed, param; struct lfgen *q; unsigned seed; int desired_malloc; packed = (int *) p; /* check values of parameters for consistency */ if (!lval) { for(i=found=0; i<NPARAMS; i++) if(packed[0]==valid[i].L && packed[1]==valid[i].K) { found = 1; break; } if(found == 0) { fprintf(stderr,"ERROR: Unpacked parameters are not acceptable.\n"); return NULL; } param = i; length = lval = valid[i].L; k = kval = valid[i].K; seed = gseed = packed[2]; } else { if (packed[0]!=lval) doexit++; if (packed[1]!=kval) doexit += 2; if (packed[2]!=gseed) doexit += 4; if (doexit) { if (doexit&1) errprint("WARNING","unpack_rng","different global L value!"); if (doexit&2) errprint("WARNING","unpack_rng","different global K value!"); if (doexit&4) errprint("WARNING","unpack_rng","different global seed value!"); fprintf(stderr,"\t Independence of streams is not guaranteed\n"); } for(i=found=0; i<NPARAMS; i++) if(packed[0]==valid[i].L && packed[1]==valid[i].K) { found = 1; break; } if(found == 0) { fprintf(stderr,"ERROR: Unpacked parameters are not acceptable. \n"); return NULL; } param = i; length = valid[i].L; k = valid[i].K; seed = packed[2]; } q = (struct lfgen *) mymalloc(sizeof(struct lfgen)); if(q == NULL) return NULL; #if OLD q->si = (unsigned *) mymalloc((length-1)*sizeof(unsigned)); q->r0 = (unsigned *) mymalloc(length*sizeof(unsigned)); q->r1 = (unsigned *) mymalloc(length*sizeof(unsigned)); #else desired_malloc = (length*3-1)*sizeof(unsigned); q->si = (unsigned *) mymalloc(desired_malloc); q->r0 = (unsigned *) (q->si + length - 1); q->r1 = (unsigned *) (q->r0 + length); #endif q->lval = length; q->kval = k; q->seed = seed; q->param = param; q->init_seed = packed[3]; if (q->r1 == NULL || q->si == NULL || q->r0 == NULL) return NULL; for (i=0;i<length-1;i++) q->si[i] = packed[i+4]; for (i=0;i<length;i++) q->r0[i] = packed[length+i+3]; for (i=0;i<length;i++) q->r1[i] = packed[2*length+i+3]; q->hptr = packed[3*length+3]; NGENS++; return (int *) q; } /*************************************************************************/ /*************************************************************************/ /* FREE_RNG: remove memory for a generator */ /*************************************************************************/ /*************************************************************************/ #if __STDC__ int free_rng(int *genptr) #else int free_rng(genptr) int *genptr; #endif { struct lfgen *q; q = (struct lfgen *)genptr; free(q->si); #if OLD free(q->r0); free(q->r1); #endif free(q); NGENS--; if(!NGENS && order_size) { free(order); order = 0; order_size = 0; } return NGENS; } #if __STDC__ int print_rng( int *igen) #else int print_rng(igen) int *igen; #endif { struct lfgen *gen; printf("\nLagged Fibonacci Generator:\n"); gen = (struct lfgen *) igen; printf("\n \tseed = %u, lags = (%d,%d)\n\n", gen->init_seed,gen->lval, gen->kval); return 1; } #include "simple_.h" /* Manually turning off FORTRAN wrappers - TME */ /* #include "fwrap_.h" */
thearchitector/experiments
fizzbuzz/fizzbuzz.c
#include <stdio.h> #include <stdint.h> int main(int argc, char* argv[]) { uint_fast8_t flag = 0; // run for numbers 1-100 for(int i = 1; i <= 100; ++i) { // special print conditions (Fizz, Buzz, FizzBuzz) if(i % 3 == 0 && (flag = 1)) printf("Fizz"); if(i % 5 == 0 && (flag = 1)) printf("Buzz"); // default case (print the number) if(!flag) printf("%d", i); printf("\n"); flag = 0; } }
liuanlin-mx/net_log
net_log.h
<reponame>liuanlin-mx/net_log /***************************************************************************** * * * Copyright (C) 2021, <NAME>. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *****************************************************************************/ #ifndef __NET_LOG_H__ #define __NET_LOG_H__ #include <stdio.h> #include <string.h> #if (defined(_WIN32) || defined(_WIN64) || defined(__MINGW32__) || defined(__MINGW64__)) #define NET_LOG_OS_WINDOWS #ifdef __GNUC__ #define net_log_filename(x) strrchr(x,'/')?strrchr(x,'/')+1:x #else #define net_log_filename(x) strrchr(x,'\\')?strrchr(x,'\\')+1:x #endif #else #define NET_LOG_OS_LINUX #define net_log_filename(x) strrchr(x,'/')?strrchr(x,'/')+1:x #endif #ifdef NET_LOG_OS_LINUX #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <net/if.h> typedef int net_log_socket_t; typedef socklen_t net_log_socklen_t; #define NET_LOG_INVALID_SOCKET (-1) static inline void net_log_close_socket(net_log_socket_t s) { shutdown(s, 2); close(s); } #else #include <windows.h> typedef int net_log_socklen_t; typedef SOCKET net_log_socket_t; #define NET_LOG_INVALID_SOCKET INVALID_SOCKET static inline void net_log_close_socket(net_log_socket_t s) { shutdown(s, 2); closesocket(s); } #endif #ifndef NET_LOG_SERVER_IP #define NET_LOG_SERVER_IP "127.0.0.1" #endif #ifndef NET_LOG_FLAG #define NET_LOG_FLAG "" #endif #define NET_LOG_PORT (18598) #ifdef __GNUC__ #endif #ifdef NET_LOG_DISABLE #define NET_LOG_DISABLE_DEBUG #define NET_LOG_DISABLE_INFO #define NET_LOG_DISABLE_ERR #define NET_LOG_DISABLE_WARN #endif static inline void net_log_sendto(const char *log, int len) { net_log_socket_t sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock == NET_LOG_INVALID_SOCKET) { return; } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(NET_LOG_PORT); addr.sin_addr.s_addr = inet_addr(NET_LOG_SERVER_IP); sendto(sock, log, len, 0, (struct sockaddr *)&addr, sizeof(addr)); net_log_close_socket(sock); } #ifndef NET_LOG_DISABLE_DEBUG #define net_log_debug(...) do { \ static char __net_log_buf[8192]; \ int __net_log_len = snprintf(__net_log_buf, sizeof(__net_log_buf), "D " NET_LOG_FLAG "%s:%s:%d ", net_log_filename(__FILE__), __FUNCTION__, __LINE__); \ if (__net_log_len > 0) { \ int __net_log_r = snprintf(__net_log_buf + __net_log_len, sizeof(__net_log_buf) - __net_log_len, ##__VA_ARGS__); \ if (__net_log_r > 0) { \ net_log_sendto(__net_log_buf, __net_log_len + __net_log_r); \ printf("%s", __net_log_buf); \ } \ } \ } while (0) #else #define net_log_debug(...) #endif #ifndef NET_LOG_DISABLE_INFO #define net_log_info(...) do { \ static char __net_log_buf[8192]; \ int __net_log_len = snprintf(__net_log_buf, sizeof(__net_log_buf), "I " NET_LOG_FLAG "%s:%s:%d ", net_log_filename(__FILE__), __FUNCTION__, __LINE__); \ if (__net_log_len > 0) { \ int __net_log_r = snprintf(__net_log_buf + __net_log_len, sizeof(__net_log_buf) - __net_log_len, ##__VA_ARGS__); \ if (__net_log_r > 0) { \ net_log_sendto(__net_log_buf, __net_log_len + __net_log_r); \ printf("%s", __net_log_buf); \ } \ } \ } while (0) #else #define net_log_info(...) #endif #ifndef NET_LOG_DISABLE_ERR #define net_log_err(...) do { \ static char __net_log_buf[8192]; \ int __net_log_len = snprintf(__net_log_buf, sizeof(__net_log_buf), "E " NET_LOG_FLAG "%s:%s:%d ", net_log_filename(__FILE__), __FUNCTION__, __LINE__); \ if (__net_log_len > 0) { \ int __net_log_r = snprintf(__net_log_buf + __net_log_len, sizeof(__net_log_buf) - __net_log_len, ##__VA_ARGS__); \ if (__net_log_r > 0) { \ net_log_sendto(__net_log_buf, __net_log_len + __net_log_r); \ printf("%s", __net_log_buf); \ } \ } \ } while (0) #else #define net_log_err(...) #endif #ifndef NET_LOG_DISABLE_WARN #define net_log_warn(...) do { \ static char __net_log_buf[8192]; \ int __net_log_len = snprintf(__net_log_buf, sizeof(__net_log_buf), "W " NET_LOG_FLAG "%s:%s:%d ", net_log_filename(__FILE__), __FUNCTION__, __LINE__); \ if (__net_log_len > 0) { \ int __net_log_r = snprintf(__net_log_buf + __net_log_len, sizeof(__net_log_buf) - __net_log_len, ##__VA_ARGS__); \ if (__net_log_r > 0) { \ net_log_sendto(__net_log_buf, __net_log_len + __net_log_r); \ printf("%s", __net_log_buf); \ } \ } \ } while (0) #else #define net_log_warn(...) #endif #endif
pjamison1/PiWiFi
PiWiFiService/src/appsettings.h
/* Copyright (c) 2013 BlackBerry Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef APPSETTINGS_H_ #define APPSETTINGS_H_ #include <QObject> #include <QVariantMap> #include <QUrl> #include <QString> /** * AppSettings Description * * This class handles application wide settings that persist between runs. */ class AppSettings: public QObject { Q_OBJECT /** * The gravity property stores the setting for if the starship gravity should be on or off. */ Q_PROPERTY(bool gravity READ gravity WRITE setGravity NOTIFY gravityChanged FINAL) /** * The powerDivert property tells where to divert power to (hyperdrive = 0 and sauna = 1). */ Q_PROPERTY(int powerDivert READ powerDivert WRITE setPowerDivert NOTIFY powerDivertChanged FINAL) /** * The uranuscanner property used to store if scanning for Uranus or not. */ Q_PROPERTY(bool uranuscanner READ uranuscanner WRITE setUranuscanner NOTIFY uranuscannerChanged FINAL) /** * This property contain the current setting of the warp drive. */ Q_PROPERTY(float warpDriveSpeedScanner READ warpDriveSpeedScanner WRITE setWarpDriveSpeedScanner NOTIFY warpDriveSpeedScannerChanged) /** * The gravity property stores the setting for if the starship gravity should be on or off. */ Q_PROPERTY(QString msg READ msg WRITE setMsg NOTIFY msgChanged FINAL) /** * The uuid property stores the setting. */ Q_PROPERTY(QString uuid READ uuid WRITE setUuid NOTIFY uuidChanged FINAL) public: AppSettings(QObject *parent = 0); /** * The gravity setting in the starship. * * @return True if gravity is on otherwise False */ bool gravity() const; QString msg() const; QString uuid() const; /** * The warp drive scanner setting. * @return A float representing the current setting of the warp engine. */ int powerDivert() const; /** * The Uranus scanner. * @return True if the scanner is on otherwise False */ bool uranuscanner() const; /** * The warp drive scanner setting. * @return A float representing the current setting of the warp engine. */ float warpDriveSpeedScanner() const; public slots: /** * Sets the gravity setting to on or off. * @param gravity The new value of the gravity setting. */ void setGravity(bool gravity); /** * Sets where to divert power, and index that is interpreted by the application. * @param powerDivert The new value of the powerDivert. */ void setPowerDivert(int powerDivert); /** * Sets the scanner to be on or off. * @param uranuscanner The new value of the scanner. */ void setUranuscanner(bool uranuscanner); /** * Sets the current warp speed. * @param warpDriveSpeedScanner The current speed ranging from 0-1 */ void setWarpDriveSpeedScanner(float warpDriveSpeedScanner); void setMsg(QString msg); void setUuid(QString uuid); signals: /** * @brief Signal emitted when the value where to divert power to changes. * @param powerDivert The new value of the powerDivert. */ void powerDivertChanged(int powerDivert); /** * @brief Signal emitted when the gravity setting changes. * @param gravity The new value of the gravity setting. */ void gravityChanged(bool gravity); /** * @brief Signal emitted when the scanner is turned on and off. * @param uranuscanner The new value of the scanner setting. */ void uranuscannerChanged(bool uranuscanner); /** * @brief Signal emitted when the speed is altered. * @param warpDriveSpeedScanner The new speed. */ void warpDriveSpeedScannerChanged(float warpDriveSpeedScanner); void msgChanged(QString msg); void uuidChanged(QString uuid); private: /** * Default values for properties */ static const bool mDefaultGravity; static const int mDefaultPowerDivert; static const bool mDefaultUranusscanner; static const float mDefaultWarpDriveSpeedScanner; static const QString mDefaultMsg; static const QString mDefaultUuid; /** * The keys where the properties are stored in the QSettings object. */ static const QString STARSHIP_GRAVITY_KEY; static const QString STARSHIP_POWERDIVERT_KEY; static const QString STARSHIP_URANUSSCANNER_KEY; static const QString STARSHIP_WARPDRIVESPEEDSCANNER_KEY; static const QString WIFI_KEY; static const QString WIFI_UUID; /** * The property variables. */ bool mGravity; int mPowerDivert; bool mUranuscanner; float mWarpDriveSpeedScanner; QString mMsg; QString mUuid; }; #endif /* APPSETTINGS_H_ */
hugo3132/EmlaLockSafe
software/src/emlalock/EmlaLockApi.h
<reponame>hugo3132/EmlaLockSafe /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../configuration/Configuration.h" #define ARDUINOJSON_USE_LONG_LONG 1 #define ARDUINOJSON_DECODE_UNICODE 1 #include <Arduino.h> #include <ArduinoJson.h> #include <HTTPClient.h> #include <Thread.h> #include <WiFiClientSecure.h> #include <chrono> #include <condition_variable> #include <limits> #include <mutex> namespace emlalock { /** * @brief Class interfacing Arduino to the EmlaLock API * @see https://www.emlalock.com/apidoc/ */ class EmlaLockApi { protected: /** * @brief The base address to the API */ const String host = "api.emlalock.com"; protected: /** * @brief JSON parser */ StaticJsonDocument<10000> jsonDocument; protected: /** * @brief Mutex used to ensure thread safety of the API */ std::mutex mtx; protected: /** * @brief Condition variable to which can be triggered to immediately request * the status of the EmlaLock Session */ std::condition_variable condVar; protected: /** * @brief Helper variable to detect spurious wakeups of thread. */ bool triggered; protected: /** * @brief If true the thread requesting data from emlalock won't be started. */ bool offlineMode; public: /** * @brief Get the singleton instance of the API handler * * @param offlineMode if true the thread requesting data from emlalock won't * be started. */ static EmlaLockApi& getSingleton(bool offlineMode = false) { static EmlaLockApi* instance = nullptr; if (!instance) { instance = new EmlaLockApi(offlineMode); } return *instance; } protected: /** * @brief Construct a new EmlaLock Api Object. Use the singleton EmlaLock or * getInstance() instead of creating new objects. * * @param offlineMode if true the thread requesting data from emlalock won't * be started. */ EmlaLockApi(bool offlineMode) : triggered(true) , offlineMode(offlineMode) { if (offlineMode) { Serial.println("Starting EmlaLock API in offline mode.."); } else { Serial.println("Starting EmlaLock API in online mode.."); esp32::Thread::create("ElmaApiThread", 8192, 1, 1, *this, &EmlaLockApi::threadFunction); } } public: /** * @brief Triggers the client to reload the current state from the EmlaLock * server */ void triggerRefresh() { std::unique_lock<std::mutex> lock(mtx); if (offlineMode) { LockState::setLastUpdateTime(time(NULL)); } else { triggered = true; lock.unlock(); condVar.notify_all(); } } protected: /** * @brief The thread functions which is communicating asynchronously with the * Emlalock API */ void threadFunction() { // This thread runs forever std::unique_lock<std::mutex> lock(mtx); while (true) { // wait until the thread will be triggered or every ten minutes... condVar.wait_for(lock, std::chrono::seconds(600), [this]() -> bool { return triggered; }); // use lambda to avoid spurious wakeups triggered = false; // ensure we are not in the manual mode! if ((LockState::getEndDate() > time(NULL)) && (LockState::getMode() == LockState::Mode::manual)) { continue; } else { LockState::setMode(LockState::Mode::emlalock); } if (requestUrl("/info/?userid=" + configuration::Configuration::getSingleton().getUserId() + "&apikey=" + configuration::Configuration::getSingleton().getApiKey())) { uint32_t numberOfFailedSessionOld = LockState::getNumberOfFailedSessions(); uint32_t numberOfFailedSessionNew = jsonDocument["user"]["failedsessions"].as<uint32_t>(); if (numberOfFailedSessionOld != numberOfFailedSessionNew) { LockState::setNumberOfFailedSessions(numberOfFailedSessionNew); // Check if a session with an known end date was aborted: if ((LockState::getMode() == LockState::Mode::emlalock) && (LockState::getEndDate() != 0) && (configuration::Configuration::getSingleton().getDisableFailedSession())) { // that's not allowed if this happened during an active // emlalock-session! Switch to manual mode with the last known end-time Serial.println("Abort rejected"); LockState::setMode(LockState::Mode::manual); return; } } if (jsonDocument["chastitysession"].size() != 0) { LockState::setDisplayTimePassed( (LockState::DisplayTimePassed)jsonDocument["chastitysession"]["displaymode"]["timepassed"].as<int>()); LockState::setDisplayTimeLeft( (LockState::DisplayTimeLeft)jsonDocument["chastitysession"]["displaymode"]["timeleft"].as<int>()); if (LockState::getDisplayTimePassed() == LockState::DisplayTimePassed::yes) { LockState::setStartDate(jsonDocument["chastitysession"]["startdate"].as<time_t>()); } else { LockState::setStartDate(0); } if (LockState::getDisplayTimeLeft() == LockState::DisplayTimeLeft::yes) { LockState::setEndDate(jsonDocument["chastitysession"]["enddate"].as<time_t>()); char buf[21]; tm tmBuf; strftime(buf, 21, "%d.%m.%Y %T", localtime_r(&LockState::getEndDate(), &tmBuf)); Serial.printf("End-date: %s\n", buf); } else { if (LockState::getDisplayTimeLeft() == LockState::DisplayTimeLeft::temperature) { String s = jsonDocument["chastitysession"]["enddate"].as<String>(); s.replace("{{localization.", ""); s.replace("}}", ""); LockState::setTemperatureString(s); } LockState::setEndDate(std::numeric_limits<time_t>::max()); } if (jsonDocument["chastitysession"]["incleaning"].as<int>() != 0) { LockState::setCleaningEndDate(jsonDocument["chastitysession"]["cleaningstarted"].as<time_t>() + jsonDocument["chastitysession"]["timeforcleaning"].as<time_t>()); } else { LockState::setCleaningEndDate(0); } } else { // Session was closed on server ---> reset if the enddate was not // displayed... LockState::setEndDate(0); } } else { Serial.println("Connection failed."); } LockState::setLastUpdateTime(time(NULL)); } } protected: /** * @brief Loads the requested url and parses the json result * * @param url the URL to be loaded * @return true if no error occurred. */ bool requestUrl(String& url) { WiFiClientSecure client; client.setInsecure(); url = String("https://") + host + url; Serial.println(url); // Your Domain name with URL path or IP address with path HTTPClient http; http.useHTTP10(true); http.begin(client, url); // Send HTTP GET request int httpResponseCode = http.GET(); String data; if (httpResponseCode > 0) { DeserializationError error = deserializeJson(jsonDocument, http.getStream()); http.end(); if (error) { Serial.print(F("deserializeJson() failed: ")); Serial.println(error.c_str()); return false; } } else { Serial.print("Error code: "); Serial.println(httpResponseCode); // Free resources http.end(); return false; } return true; } }; } // namespace emlalock
hugo3132/EmlaLockSafe
software/src/views/UnlockedMainMenu.h
/** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../Tools.h" #include "ViewStore.h" #include <Esp.h> #include <MenuView.h> namespace views { /** * @brief Main menu as long as there is no active session */ class UnlockedMainMenu : public lcd::MenuView { public: /** * @brief Construct a new main menu object * * @param display pointer to the display instance * @param encoder pointer to the encoder instance * @param numberOfColumns number of display-columns * @param numberOfRows number of display-rows */ UnlockedMainMenu(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder, const int& numberOfColumns, const int& numberOfRows) : lcd::MenuView(display, "UnlockedMainMenu", encoder, "Unlocked Main Menu", numberOfColumns, numberOfRows) {} public: /** * @brief Copy constructor - not available */ UnlockedMainMenu(const UnlockedMainMenu& other) = delete; public: /** * @brief Move constructor - not available otherwise we get problems with the * callbacks. */ UnlockedMainMenu(UnlockedMainMenu&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { // is this the first time activate is called? if (menuItems.empty()) { // create menu items createMenuItem("Open Safe", [](MenuItem*) { const auto& timeRestictions = configuration::Configuration::getSingleton().getTimeRestrictions(); if (!timeRestictions.restrictUnlockTimes || timeRestictions.checkTime()) { ViewStore::activateView(ViewStore::UnlockSafeView); } else { ViewStore::activateView(ViewStore::TimeRestrictedView); } }); createMenuItem("Set Custom Timer", [](MenuItem*) { ViewStore::activateView(ViewStore::SetTimerView); }); createMenuItem("Emlalock Unlock Key", [](MenuItem*) { ViewStore::activateView(ViewStore::EmlalockUnlockKeyMenu); }); createMenuItem("Preferences", [](MenuItem*) { ViewStore::activateView(ViewStore::PreferencesMenu); }); createMenuItem("Hardware Test View", [](MenuItem*) { ViewStore::activateView(ViewStore::HardwareTestView); }); createMenuItem("Reboot", [](MenuItem*) { ESP.restart(); }); } lcd::MenuView::activate(); } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { // updated the view of the menu lcd::MenuView::tick(forceRedraw); // update the signal strength symbol Tools::tickWifiSymbol(display, forceRedraw); } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/SelectDisplayTimeLeft.h
<reponame>hugo3132/EmlaLockSafe<gh_stars>1-10 /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../LockState.h" #include "ViewStore.h" #include <MenuView.h> #include <time.h> namespace views { /** * @brief selection menu if the time passed should be displayed or not */ class SelectDisplayTimeLeft : public lcd::MenuView { public: /** * @brief Construct a new menu object * * @param display pointer to the display instance * @param encoder pointer to the encoder instance * @param numberOfColumns number of display-columns * @param numberOfRows number of display-rows */ SelectDisplayTimeLeft(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder, const int& numberOfColumns, const int& numberOfRows) : lcd::MenuView(display, "SelectDisplayTimeLeft", encoder, "Display time left?", numberOfColumns, numberOfRows) {} public: /** * @brief Copy constructor - not available */ SelectDisplayTimeLeft(const SelectDisplayTimeLeft& other) = delete; public: /** * @brief Move constructor - not available otherwise we get problems with the callbacks. */ SelectDisplayTimeLeft(SelectDisplayTimeLeft&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { // is this the first time activate is called? if (menuItems.empty()) { // create menu items createMenuItem("Yes", [this](MenuItem*) { LockState::setDisplayTimeLeft(LockState::DisplayTimeLeft::yes); LockState::setStartDate(time(NULL)); LockState::setTemperatureString(""); LockState::setMode(LockState::Mode::manual); LockState::setEndDate(LockState::getCachedEndDate()); }); createMenuItem("No", [this](MenuItem*) { LockState::setDisplayTimeLeft(LockState::DisplayTimeLeft::no); LockState::setStartDate(time(NULL)); LockState::setTemperatureString(""); LockState::setMode(LockState::Mode::manual); LockState::setEndDate(LockState::getCachedEndDate()); }); createMenuItem("Temperature", [this](MenuItem*) { LockState::setDisplayTimeLeft(LockState::DisplayTimeLeft::temperature); LockState::setStartDate(time(NULL)); LockState::setTemperatureString(""); // Automatically generated! LockState::setMode(LockState::Mode::manual); LockState::setEndDate(LockState::getCachedEndDate()); }); createMenuItem("Cancel", [this](MenuItem*) { views::ViewStore::activateView(views::ViewStore::UnlockedMainMenu); }); } lcd::MenuView::activate(); } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/EmergencyEnterMenuView.h
/** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include <ViewBase.h> namespace views { /** * @brief A view which is displayed for a view seconds when the button is * pressed during boot. */ class EmergencyEnterMenuView : public lcd::ViewBase { public: /** * @brief Construct a vie object * * @param display pointer to the LCD instance */ EmergencyEnterMenuView(LiquidCrystal_PCF8574* display) : lcd::ViewBase(display, "EmergencyEnterMenuView") {} public: /** * @brief Copy constructor - not available */ EmergencyEnterMenuView(const EmergencyEnterMenuView& other) = delete; public: /** * @brief Move constructor - not available */ EmergencyEnterMenuView(EmergencyEnterMenuView&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { display->clear(); display->setCursor(0, 0); display->print("Keep button pressed"); display->setCursor(0, 1); display->print("to enter emergency"); display->setCursor(0, 2); display->print("menu."); display->setCursor(0, 3); } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { display->print('*'); } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/RealTimeClock.h
<reponame>hugo3132/EmlaLockSafe /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include <ds3231.h> #include <stdlib.h> #include <sys/time.h> /** * @brief Helper syncinc the SystemClock with the RTC running in UTC. */ class RealTimeClock { public: /** * @brief Sets the system clock based on the RTC */ static void loadTimeFromRtc() { char currentTimezone[100]; char* envTimezone = getenv("TZ"); // was the timezone set? create a copy if (envTimezone) { strcpy(currentTimezone, envTimezone); } // The DS3231 runs in UTC. Temporarily change the system to UTC as well setenv("TZ", "UTC0", 1); tzset(); // Initialize clock DS3231_init(DS3231_CONTROL_INTCN); // Get current time struct ts rtcTime; DS3231_get(&rtcTime); // convert the ts to a tm struc tm timeBuf; memset(&timeBuf, 0, sizeof(tm)); timeBuf.tm_year = rtcTime.year - 1900; timeBuf.tm_mon = rtcTime.mon - 1; timeBuf.tm_mday = rtcTime.mday; timeBuf.tm_hour = rtcTime.hour; timeBuf.tm_min = rtcTime.min; timeBuf.tm_sec = rtcTime.sec; timeBuf.tm_isdst = -1; // negative value means no daylightsaving time as required for UTC0 // convert to timeval struct timeval tv; tv.tv_sec = mktime(&timeBuf); tv.tv_usec = 0; // set system-clock settimeofday(&tv, NULL); // was the timezone set before? Restore the original timezone if (envTimezone) { setenv("TZ", currentTimezone, 1); tzset(); } } /** * @brief Sets the RTC time to the value of the system clock */ static void saveTimeToRtc() { tm timeBuf; struct ts rtcTime; // convert current time to tm structure time_t tNow; time(&tNow); // convert to UTC time gmtime_r(&tNow, &timeBuf); // convert tm structure to RTC structure rtcTime.year = timeBuf.tm_year + 1900; rtcTime.mon = timeBuf.tm_mon + 1; rtcTime.mday = timeBuf.tm_mday; rtcTime.hour = timeBuf.tm_hour; rtcTime.min = timeBuf.tm_min; rtcTime.sec = timeBuf.tm_sec; // Initialize clock DS3231_init(DS3231_CONTROL_INTCN); // Set current time DS3231_set(rtcTime); } };
hugo3132/EmlaLockSafe
software/src/configuration/WifiConfigurationServer.h
<filename>software/src/configuration/WifiConfigurationServer.h /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "Configuration.h" #include "ConfigurationServerBase.h" #include <Arduino.h> #include <DNSServer.h> #include <Esp.h> #include <LiquidCrystal_PCF8574.h> #include <WiFi.h> #include <list> #include <mutex> /** * @brief Name of the the temporary WiFi for the configuration */ #define CONFIGURATION_SSID "SafeSetup" namespace configuration { /** * @brief Class implementing the configuration of the WiFi */ class WifiConfigurationServer : ConfigurationServerBase { #pragma region Singelton protected: /** * @brief Function providing the instance for the singleton */ inline static WifiConfigurationServer** getInstance() { static WifiConfigurationServer* instance = nullptr; return &instance; } public: /** * @brief Get the Singleton object */ inline static WifiConfigurationServer* getSingletonPointer() { return *getInstance(); } /** * @brief Create a new Configuration server * * @param display * @return ConfigurationServer& */ inline static void begin(LiquidCrystal_PCF8574& display) { if (!*getInstance()) { *getInstance() = new WifiConfigurationServer(display); } } #pragma endregion #pragma region Members protected: /** * @brief Instance of the DNS server in access point mode */ DNSServer dnsServer; protected: /** * @brief Reference to the display */ LiquidCrystal_PCF8574& display; protected: /** * @brief mutex for the protection of the data */ std::mutex mtx; protected: /** * @brief List with all found ssids */ std::list<String> ssids; protected: /** * @brief IP address in Access Point mode */ IPAddress IP; protected: /** * @brief Network mask in Access Point mode */ IPAddress netMsk; #pragma endregion private: /** * @brief Construct a new Configuration Server object * * @param display Reference to the LCD to display some status information */ WifiConfigurationServer(LiquidCrystal_PCF8574& display) : ConfigurationServerBase() , display(display) , IP(10, 0, 0, 1) , netMsk(255, 255, 255, 0) { createAp(); configureWebserver(); server.begin(); // Web server start initialLcdMessage(); } public: /** * @brief Forward of the Arduino loop function */ void loop() { dnsServer.processNextRequest(); // DNS scanWiFi(); } protected: /** * @brief Create and configures the WiFi in AP mode */ void createAp() { // open access point WiFi.setAutoReconnect(false); WiFi.persistent(false); WiFi.disconnect(); WiFi.setHostname("EmlalockSafe"); // Setup Access Point display.clear(); display.setCursor(0, 0); display.print("Setting up WiFi"); Serial.println("Setting up WiFi"); if (!WiFi.softAP(CONFIGURATION_SSID)) { display.clear(); display.setCursor(0, 0); display.print("Error starting"); display.setCursor(0, 1); display.print("Access Point "); display.setCursor(0, 2); display.print(CONFIGURATION_SSID); Serial.print("Error starting Access Point "); Serial.println(CONFIGURATION_SSID); return; } delay(2000); // Without delay I've seen the IP address blank WiFi.softAPConfig(IP, IP, netMsk); dnsServer.setErrorReplyCode(DNSReplyCode::NoError); dnsServer.start(53, "*", IP); } protected: /** * @brief adds the handlers for the different webpages */ void configureWebserver() { // Setup Webserver display.clear(); display.setCursor(0, 0); display.print("Setting up Webserver"); Serial.println("Setting up Webserver"); delay(500); addSpiffsFileToServer("/", "text/html", "/indexWifi.html"); // Captive Portal forwards addSpiffsFileToServer("/generate_204", "text/html", "/indexWifi.html"); addSpiffsFileToServer("/favicon.ico", "text/html", "/indexWifi.html"); addSpiffsFileToServer("/fwlink", "text/html", "/indexWifi.html"); // Add file to webserver listing all visible SSIDs server.on("/ssids", HTTP_GET, [this](AsyncWebServerRequest* request) { std::unique_lock<std::mutex> lock(mtx); String resp = ""; for (const auto& ssid : ssids) { resp += ssid + "\r\n"; } request->send(200, "text/plain", resp); }); // Callback for if the modifications should be saved server.on("/saveData", HTTP_GET, [this](AsyncWebServerRequest* request) { Configuration::getSingleton().setWifiSettings(request->getParam("ssid")->value(), request->getParam("pwd")->value()); request->send(200, "text/plain", "Configuration Updated. Rebooting..."); delay(100); ESP.restart(); }); // Callback if the a site is requested which does not exist server.onNotFound([](AsyncWebServerRequest* request) { // just always forward to the main page AsyncWebServerResponse* response = request->beginResponse(302, "text/plain", ""); response->addHeader("Location", String("http://") + WiFi.softAPIP().toString()); request->send(response); }); } protected: /** * @brief shows the ssid of the AP and the address to which the user should connect */ void initialLcdMessage() { // Update the LCD display.clear(); display.setCursor(0, 0); display.print("Connect to WiFi:"); display.setCursor(0, 1); display.print(CONFIGURATION_SSID); display.setCursor(0, 2); display.print("Open in Browser:"); display.setCursor(0, 3); display.print("http://"); display.print(IP); Serial.println("\n"); Serial.println("Display: Connect to WiFi:"); Serial.print("Display: "); Serial.println(CONFIGURATION_SSID); Serial.println("Display: Open in Browser:"); Serial.print("Display: http://"); Serial.print(IP); } protected: /** * @brief scans the visible wifis and saves them into @ref ssids. Should be continuously called during @ref loop. */ void scanWiFi() { // check the state scanning for wifis int16_t scanState = WiFi.scanComplete(); if (scanState == -2) { // not started yet, start a new scan WiFi.scanNetworks(true); } else if (scanState >= 0) { // scan completed std::unique_lock<std::mutex> lock(mtx); ssids.clear(); for (int i = 0; i < scanState; i++) { ssids.push_back(WiFi.SSID(i)); } WiFi.scanNetworks(true); } } }; } // namespace configuration
hugo3132/EmlaLockSafe
software/src/LockState.h
/** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "Tools.h" #include "UsedInterrupts.h" #include <SPIFFS.h> #include <mutex> #include <time.h> /** * @brief Singleton class managing the current lock state. The class also * automatically saves the lock state to flash so we know what's going on after * a reboot even if there is no wifi. * * For more details see \ref secLockstate * * Access to this class is thread-safe */ class LockState { #pragma region Enums public: /** * @brief Enum basetype used for saving to the flash */ using enumBaseType = uint8_t; public: /** * @brief Current mode of the safe */ enum class Mode : enumBaseType { emlalock = 0, manual = 1 }; public: /** * @brief States for the selection how the passed time should be displayed */ enum class DisplayTimePassed : enumBaseType { no = 0, yes = 1 }; public: /** * @brief States for the selection how the time left should be displayed */ enum class DisplayTimeLeft : enumBaseType { no = 0, yes = 1, temperature = 2, timeWithPenalty = 3, timeWithRandomPenalty = 4 }; #pragma endregion protected: /** * @brief mutex used to synchronize the data access */ std::mutex mtx; #pragma region Members stored on Flash protected: /** * @brief The mode */ Mode mode; protected: /** * @brief how the passed time should be displayed */ DisplayTimePassed displayTimePassed; protected: /** * @brief how the passed time should be displayed */ DisplayTimeLeft displayTimeLeft; protected: /** * @brief start date of the current session */ time_t startDate; protected: /** * @brief end date of the current session */ time_t endDate; protected: /** * @brief temperature string */ String temperatureString; protected: /** * @brief The number of failed session */ uint32_t numberOfFailedSessions; #pragma endregion protected: /** * @brief chache for the end date of the session which is currently * configured. This value won't be saved to the flash! */ time_t cachedEndDate; protected: /** * @brief end date of the current cleaning opening or 0 if not opened for * cleaning. This value won't be saved to the flash! */ time_t cleaningEndDate; protected: /** * @brief time of the last update */ time_t lastUpdateTime; #pragma region singleton protected: /** * @brief Constructs the lock state by trying to reading the state from flash */ LockState() : mode(Mode::emlalock) , displayTimePassed(DisplayTimePassed::yes) , displayTimeLeft(DisplayTimeLeft::yes) , startDate(0) , endDate(0) , numberOfFailedSessions(0) , cachedEndDate(0) , cleaningEndDate(0) , lastUpdateTime(0) { loadData(); } protected: /** * @brief Get the singleton instance */ static LockState& getSingleton() { static LockState lockState; return lockState; } #pragma endregion #pragma region Flash Access Functions protected: /** * @brief Loads the current state of the object to the flash */ void loadData() { Serial.println("Loading lockState"); constexpr auto numberOfBytes = sizeof(Mode) + sizeof(DisplayTimePassed) + sizeof(DisplayTimeLeft) + 2 * sizeof(time_t) + sizeof(uint32_t); char buf[numberOfBytes]; bool readOk; // load the data from the file system if available UsedInterrupts::executeWithoutInterrupts([this, &readOk, &buf]() { File file = SPIFFS.open("/lockSt.bin", "r"); if (!file) { Serial.println("Loading lockState failed"); return; } // read everything to a buffer readOk = file.readBytes(buf, numberOfBytes) == numberOfBytes; if (readOk) { temperatureString = file.readString(); } file.close(); }); if (readOk) { // copy the data from the buffer to the actual variables char* src = buf; memcpy(&mode, src, sizeof(Mode)); src += sizeof(Mode); memcpy(&displayTimePassed, src, sizeof(DisplayTimePassed)); src += sizeof(DisplayTimePassed); memcpy(&displayTimeLeft, src, sizeof(DisplayTimeLeft)); src += sizeof(DisplayTimeLeft); memcpy(&startDate, src, sizeof(time_t)); src += sizeof(time_t); memcpy(&endDate, src, sizeof(time_t)); src += sizeof(time_t); memcpy(&numberOfFailedSessions, src, sizeof(uint32_t)); src += sizeof(uint32_t); } } protected: /** * @brief Saves the current state of the object to the flash */ void saveData() { Serial.println("Saving lockState"); UsedInterrupts::executeWithoutInterrupts([this]() { File file = SPIFFS.open("/lockSt.bin", "w"); if (!file) { return; } file.write((uint8_t*)&mode, sizeof(DisplayTimePassed)); file.write((uint8_t*)&displayTimePassed, sizeof(DisplayTimePassed)); file.write((uint8_t*)&displayTimeLeft, sizeof(DisplayTimeLeft)); file.write((uint8_t*)&startDate, sizeof(time_t)); file.write((uint8_t*)&endDate, sizeof(time_t)); file.write((uint8_t*)&numberOfFailedSessions, sizeof(uint32_t)); file.write((uint8_t*)temperatureString.c_str(), temperatureString.length()); file.close(); }); Serial.println("Saved lockState"); } #pragma endregion #pragma region getter / setter #pragma region mode public: /** * @brief Get the mode */ static const Mode& getMode() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().mode; } public: /** * @brief Set the mode */ static void setMode(const Mode& mode) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().mode != mode) { getSingleton().mode = mode; getSingleton().saveData(); } } #pragma endregion #pragma region displayTimePassed public: /** * @brief Get how the time passed should be displayed */ static const DisplayTimePassed& getDisplayTimePassed() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().displayTimePassed; } public: /** * @brief Set how the time passed should be displayed */ static void setDisplayTimePassed(const DisplayTimePassed& displayTimePassed) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().displayTimePassed != displayTimePassed) { getSingleton().displayTimePassed = displayTimePassed; getSingleton().saveData(); } } #pragma endregion #pragma region displayTimeLeft public: /** * @brief Get how the time left should be displayed */ static const DisplayTimeLeft& getDisplayTimeLeft() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().displayTimeLeft; } public: /** * @brief Set how the time left should be displayed */ static void setDisplayTimeLeft(const DisplayTimeLeft& displayTimeLeft) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().displayTimeLeft != displayTimeLeft) { getSingleton().displayTimeLeft = displayTimeLeft; getSingleton().saveData(); } } #pragma endregion #pragma region startDate public: /** * @brief Get the Start Date */ static const time_t& getStartDate() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().startDate; } public: /** * @brief Set the Start Date */ static void setStartDate(const time_t& startDate) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().startDate != startDate) { getSingleton().startDate = startDate; getSingleton().saveData(); } } #pragma endregion #pragma region endDate public: /** * @brief Get the End Date */ static const time_t& getEndDate() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().endDate; } public: /** * @brief Set the End Date */ static void setEndDate(const time_t& endDate) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().endDate != endDate) { getSingleton().endDate = endDate; getSingleton().saveData(); } } #pragma endregion #pragma region numberOfFailedSessions public: /** * @brief Get the number of failed sessions */ static const uint32_t& getNumberOfFailedSessions() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().numberOfFailedSessions; } public: /** * @brief Set the number of failed sessions */ static void setNumberOfFailedSessions(const uint32_t& numberOfFailedSessions) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().numberOfFailedSessions != numberOfFailedSessions) { getSingleton().numberOfFailedSessions = numberOfFailedSessions; getSingleton().saveData(); } } #pragma endregion #pragma region temperatureString public: /** * @brief Get the temperature string */ static const String& getTemperatureString() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().temperatureString; } public: /** * @brief Set the temperature string */ static void setTemperatureString(const String& temperatureString) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().temperatureString != temperatureString) { getSingleton().temperatureString = temperatureString; getSingleton().saveData(); } } #pragma endregion #pragma region cachedEndDate public: /** * @brief Get the Cached End Date */ static const time_t& getCachedEndDate() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().cachedEndDate; } public: /** * @brief Set the Cached End Date */ static void setCachedEndDate(const time_t& cachedEndDate) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().cachedEndDate != cachedEndDate) { getSingleton().cachedEndDate = cachedEndDate; } } #pragma endregion #pragma region cleaningEndDate public: /** * @brief Get the End Date of the current cleaning opening (or 0) */ static const time_t& getCleaningEndDate() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().cleaningEndDate; } public: /** * @brief Set the End Date of the current cleaning opening */ static void setCleaningEndDate(const time_t& cleaningEndDate) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().cleaningEndDate != cleaningEndDate) { getSingleton().cleaningEndDate = cleaningEndDate; } } #pragma endregion #pragma region lastUpdateTime public: /** * @brief Get the time of the last update over the emlalock api */ static const time_t& getLastUpdateTime() { std::unique_lock<std::mutex> lock(getSingleton().mtx); return getSingleton().lastUpdateTime; } public: /** * @brief Set the time of the last update over the emlalock api */ static void setLastUpdateTime(const time_t& lastUpdateTime) { std::unique_lock<std::mutex> lock(getSingleton().mtx); if (getSingleton().lastUpdateTime != lastUpdateTime) { getSingleton().lastUpdateTime = lastUpdateTime; } } #pragma endregion #pragma endregion };
hugo3132/EmlaLockSafe
software/src/configuration/ConfigurationServerBase.h
<filename>software/src/configuration/ConfigurationServerBase.h /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../UsedInterrupts.h" #include <ESPAsyncWebServer.h> #include <SPIFFS.h> namespace configuration { /** * @brief Base class for configuring the controller over WiFi */ class ConfigurationServerBase { protected: /** * @brief The used asynchronous webserver */ AsyncWebServer server; protected: /** * @brief Construct a new Configuration Server object */ ConfigurationServerBase() : server(80) { // Add files to webserver which are loaded from the file system addSpiffsFileToServer("/jquery-3.6.0.min.js", "text/javascript"); addSpiffsFileToServer("/main.css", "text/css"); } protected: /** * @brief Adds the file from the SPIFFS with the filename to the webserver * under the given path. * * @param path path under which the file should be reachable * @param contentType type of the data * @param filename optional, path on the SPIFFS. Must only be set if different to path */ void addSpiffsFileToServer(const char* path, String contentType, const char* filename = nullptr) { if (!filename) { filename = path; } server.on(path, HTTP_GET, [contentType, filename](AsyncWebServerRequest* request) { UsedInterrupts::executeWithoutInterrupts([request, contentType, filename]() { request->send(SPIFFS, filename, contentType); }); }); } }; } // namespace configuration
hugo3132/EmlaLockSafe
software/src/views/ConfigurationServerView.h
<reponame>hugo3132/EmlaLockSafe<filename>software/src/views/ConfigurationServerView.h /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../Tools.h" #include <MenuView.h> namespace views { /** * @brief preferences menu */ class ConfigurationServerView : public lcd::MenuView { public: /** * @brief Construct a new menu object * * @param display pointer to the display instance * @param encoder pointer to the encoder instance * @param numberOfColumns number of display-columns * @param numberOfRows number of display-rows */ ConfigurationServerView(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder, const int& numberOfColumns, const int& numberOfRows) : lcd::MenuView(display, "ConfigurationServerView", encoder, "Open in Browser:", numberOfColumns, numberOfRows) {} public: /** * @brief Copy constructor - not available */ ConfigurationServerView(const ConfigurationServerView& other) = delete; public: /** * @brief Move constructor - not available otherwise we get problems with the callbacks. */ ConfigurationServerView(ConfigurationServerView&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { // is this the first time activate is called? if (menuItems.empty()) { // create menu items createMenuItem("http://" + WiFi.localIP().toString(), [this](MenuItem*) {}); createMenuItem("Change Wifi Settings", [this](MenuItem*) { configuration::Configuration::getSingleton().setWifiSettings("", ""); ESP.restart(); }); createMenuItem("Back", [this](MenuItem*) { activatePreviousView(); }); } lcd::MenuView::activate(); } public: /** * @brief Overload Tick * * This is necessary directly after a reboot, localIP returns 0.0.0.0 */ virtual void tick(const bool& forceRedraw) { static unsigned long nextCheck = millis(); if (nextCheck < millis()) { static String ip = ""; String tmpIp = WiFi.localIP().toString(); if (ip != tmpIp) { ip = tmpIp; menuItems.front().setText("http://" + tmpIp); } nextCheck = millis() + 100; } lcd::MenuView::tick(forceRedraw); } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/HardwareTestView.h
/** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../Tools.h" #include <RotaryEncoder.h> #include <ViewBase.h> #include <ds3231.h> namespace views { /** * @brief Main view testing all connected hardware */ class HardwareTestView : public lcd::ViewBase { protected: /** * @brief pointer to the encoder instance */ RotaryEncoder* encoder; public: /** * @brief Construct a vie object * * @param display pointer to the LCD instance */ HardwareTestView(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder) : lcd::ViewBase(display, "HardwareTestView") , encoder(encoder) {} public: /** * @brief Copy constructor - not available */ HardwareTestView(const HardwareTestView& other) = delete; public: /** * @brief Move constructor */ HardwareTestView(HardwareTestView&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { display->clear(); display->setCursor(0, 0); display->print("Encoder Test"); } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { auto direction = encoder->getDirection(); auto click = encoder->getNewClick(); // Display the state of the encoder if (click) { display->setCursor(0, 1); display->print("Clicked"); delay(500); display->setCursor(0, 1); display->print(" "); } if (direction == RotaryEncoder::Direction::CLOCKWISE) { display->setCursor(0, 1); display->print("CLOCKWISE"); delay(500); display->setCursor(0, 1); display->print(" "); } if (direction == RotaryEncoder::Direction::COUNTERCLOCKWISE) { display->setCursor(0, 1); display->print("COUNTERCLOCKWISE"); delay(500); display->setCursor(0, 1); display->print(" "); } // Get current time struct ts rtcTime; DS3231_get(&rtcTime); // convert RTC structure to tm structure tm timeBuf; char buf[21]; timeBuf.tm_year = rtcTime.year - 1900; timeBuf.tm_mon = rtcTime.mon - 1; timeBuf.tm_mday = rtcTime.mday; timeBuf.tm_hour = rtcTime.hour; timeBuf.tm_min = rtcTime.min; timeBuf.tm_sec = rtcTime.sec; strftime(buf, 21, "R %d.%m.%y %T", &timeBuf); display->setCursor(0, 2); display->print(buf); static time_t lastTime = 0; time_t now = time(NULL); if (now != lastTime) { strftime(buf, 21, "S %d.%m.%y %T", localtime_r(&now, &timeBuf)); display->setCursor(0, 3); display->print(buf); lastTime = now; digitalWrite(COIL_PIN, now % 2); } Tools::tickWifiSymbol(display, forceRedraw); } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/EmergencyEnterKeyView.h
<filename>software/src/views/EmergencyEnterKeyView.h /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../LockState.h" #include "../configuration/Configuration.h" #include "ViewStore.h" #include <RotaryEncoder.h> #include <ViewBase.h> namespace views { /** * @brief View which allows to enter a key to unlock without WiFi */ class EmergencyEnterKeyView : public lcd::ViewBase { protected: /** * @brief pointer to the encoder instance */ RotaryEncoder* encoder; protected: /** * @brief Cache of the entered key */ char enteredKey[7]; protected: /** * @brief Position of the key cache which is currently edited */ int editIndex; public: /** * @brief Construct the view object * * @param display pointer to the LCD instance */ EmergencyEnterKeyView(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder) : lcd::ViewBase(display, "EmergencyEnterKeyView") , encoder(encoder) {} public: /** * @brief Copy constructor - not available */ EmergencyEnterKeyView(const EmergencyEnterKeyView& other) = delete; public: /** * @brief Move constructor */ EmergencyEnterKeyView(EmergencyEnterKeyView&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { strcpy(enteredKey, "AAAAAA"); editIndex = 0; display->clear(); display->setCursor(0, 0); display->print("Enter emergency key:"); tick(true); } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { auto direction = encoder->getDirection(); bool redraw = forceRedraw; if (direction == RotaryEncoder::Direction::CLOCKWISE) { if (enteredKey[editIndex] == 'Z') { enteredKey[editIndex] = '0'; } else if (enteredKey[editIndex] == '9') { enteredKey[editIndex] = 'A'; } else { enteredKey[editIndex]++; } redraw = true; } else if (direction == RotaryEncoder::Direction::COUNTERCLOCKWISE) { if (enteredKey[editIndex] == 'A') { enteredKey[editIndex] = '9'; } else if (enteredKey[editIndex] == '0') { enteredKey[editIndex] = 'Z'; } else { enteredKey[editIndex]--; } redraw = true; } if (encoder->getNewClick()) { editIndex++; if (editIndex == 6) { editIndex = 0; display->setCursor(0, 1); if (strcmp(enteredKey, configuration::Configuration::getSingleton().getEmergencyKey().c_str()) == 0) { const auto& timeRestictions = configuration::Configuration::getSingleton().getTimeRestrictions(); if (!timeRestictions.restrictEmergencyKeyTimes || timeRestictions.checkTime()) { // Correct key was entered... LockState::setEndDate(0); // set to unlock LockState::setLastUpdateTime(time(NULL) + 10); ViewStore::activateView(ViewStore::UnlockSafeView); return; } else { ViewStore::activateView(ViewStore::TimeRestrictedView); return; } } else { display->print("Invalid Key"); } } redraw = true; } if (redraw) { for (int i = 0; i < 6; i++) { display->setCursor(2 * i + 3, 3); display->print(' '); display->print(enteredKey[i]); } display->print(' '); display->setCursor(editIndex * 2 + 3, 3); display->print('>'); display->setCursor(editIndex * 2 + 5, 3); display->print('<'); } } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/configuration/ConfigurationServer.h
<reponame>hugo3132/EmlaLockSafe /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../UsedInterrupts.h" #include "../views/ViewStore.h" #include "ConfigurationServerBase.h" #include <Arduino.h> #include <ESPAsyncWebServer.h> #include <LiquidCrystal_PCF8574.h> #include <RotaryEncoder.h> #include <SPIFFS.h> #include <WiFi.h> #include <list> #include <mutex> #include <stdlib.h> namespace configuration { /** * @brief Class implementing all functions to configure the Controller */ class ConfigurationServer : public ConfigurationServerBase { #pragma region Singelton protected: /** * @brief Function providing the instance for the singleton */ inline static ConfigurationServer** getInstance() { static ConfigurationServer* instance = nullptr; return &instance; } public: /** * @brief Get the Singleton object */ inline static ConfigurationServer& getSingleton() { return **getInstance(); } public: /** * @brief Create a new Configuration server * * @param display Reference to the display * @param encoder Reference to the encoder */ inline static ConfigurationServer& begin(LiquidCrystal_PCF8574& display, RotaryEncoder& encoder) { if (!*getInstance()) { *getInstance() = new ConfigurationServer(display, encoder); } return **getInstance(); } #pragma endregion protected: /** * @brief Websocket to remote control the display */ AsyncWebSocket remoteControlWebSocket; protected: /** * @brief Reference to the display */ LiquidCrystal_PCF8574& display; protected: /** * @brief Refernce to the encoder */ RotaryEncoder& encoder; private: /** * @brief Construct a new Configuration Server object * * @param display Reference to the display * @param encoder Reference to the encoder */ ConfigurationServer(LiquidCrystal_PCF8574& display, RotaryEncoder& encoder) : ConfigurationServerBase() , remoteControlWebSocket("/ws") , display(display) , encoder(encoder) { // Add files to webserver which are loaded from the file system server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { UsedInterrupts::executeWithoutInterrupts([request]() { if (isConfigurationAllowed()) { request->send(SPIFFS, "/indexConfig.html", "text/html"); } else { request->send(SPIFFS, "/indexRemote.html", "text/html"); } }); }); addSpiffsFileToServer("/zones.json", "text/json"); addSpiffsFileToServer("/moment.js", "text/javascript"); addSpiffsFileToServer("/dotmatrix.js", "text/javascript"); addSpiffsFileToServer("/remoteLcd.js", "text/javascript"); addSpiffsFileToServer("/rotate.svg", "image/svg+xml"); // Add file to webserver returning the current settings server.on("/lastValues", HTTP_GET, [this](AsyncWebServerRequest* request) { onGetLastValues(request); }); // Handler to save the configuration server.on("/saveData", HTTP_GET, [this](AsyncWebServerRequest* request) { onSaveData(request); }); // Handler to generate a new emergency key server.on("/generateNewKey", HTTP_GET, [this](AsyncWebServerRequest* request) { onGenerateNewKey(request); }); // Handler of the websocket for the remote control of the safe remoteControlWebSocket.onEvent( [this](AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len) { onRemoteControlWebSocketEvent(client, type, arg, data, len); }); server.addHandler(&remoteControlWebSocket); // Start Webserver server.begin(); } protected: /** * @brief Extract a passed parameter value from a HTTP GET request */ static String getParam(AsyncWebServerRequest* request, const String& paramName) { auto param = request->getParam(paramName); if (param == nullptr) { Serial.println("Error getting parameter: " + paramName); return ""; } else { Serial.println("Getting parameter: " + paramName + " = \"" + param->value() + "\""); return param->value(); } } protected: /** * @brief Quick check if the ConfigurationServerView is active --> changing the configuration is allowed */ static inline bool isConfigurationAllowed() { return views::ViewStore::getView(views::ViewStore::ConfigurationServerView) == lcd::ViewBase::getCurrentView(); } protected: /** * @brief Event handler called if the current configuration should be sent to the browser * * @param request the request received from the browser */ void onGetLastValues(AsyncWebServerRequest* request) { if (isConfigurationAllowed()) { String response = ""; response += Configuration::getSingleton().getUserId(); response += "\r\n"; response += Configuration::getSingleton().getApiKey(); response += "\r\n"; response += Configuration::getSingleton().getEmergencyKey(); response += "\r\n"; response += Configuration::getSingleton().getDisableFailedSession() ? "true" : "false"; response += "\r\n"; response += Configuration::getSingleton().getTimezoneName(); response += "\r\n"; response += Configuration::getSingleton().getBacklightTimeOut(); response += "\r\n"; response += Configuration::getSingleton().getAutoLockHygieneOpeningTimeout() ? "true" : "false"; response += "\r\n"; response += Configuration::getSingleton().getTimeRestrictions().startTime; response += "\r\n"; response += Configuration::getSingleton().getTimeRestrictions().endTime; response += "\r\n"; response += Configuration::getSingleton().getTimeRestrictions().restrictUnlockTimes ? "true" : "false"; response += "\r\n"; response += Configuration::getSingleton().getTimeRestrictions().restrictHygieneOpeningTimes ? "true" : "false"; response += "\r\n"; response += Configuration::getSingleton().getTimeRestrictions().restrictEmergencyKeyTimes ? "true" : "false"; response += "\r\n"; response += Configuration::getSingleton().getTimeRestrictions().restrictConfigurationServer ? "true" : "false"; response += "\r\n"; request->send(200, "text/plain", response); } else { request->send(404, "text/plain", "Not Found!"); } } protected: /** * @brief Event handler called if new configuration data should be saved * * @param request the request received from the browser */ void onSaveData(AsyncWebServerRequest* request) { if (isConfigurationAllowed()) { Configuration::TimeRestrictions restrictions; restrictions.startTime = strtoul(getParam(request, "timeRestrictionsStartTime").c_str(), NULL, 0); restrictions.endTime = strtoul(getParam(request, "timeRestrictionsEndTime").c_str(), NULL, 0); restrictions.restrictUnlockTimes = getParam(request, "timeRestrictionsRestrictUnlockTimes") == "true"; restrictions.restrictHygieneOpeningTimes = getParam(request, "timeRestrictionsRestrictHygieneOpeningTimes") == "true"; restrictions.restrictEmergencyKeyTimes = getParam(request, "timeRestrictionsRestrictEmergencyKeyTimes") == "true"; restrictions.restrictConfigurationServer = getParam(request, "timeRestrictionsRestrictConfigurationServer") == "true"; Configuration::getSingleton().setConfigurationSettings(getParam(request, "userId"), getParam(request, "apiKey"), getParam(request, "disableFailedSession") == "true", getParam(request, "timezoneName"), getParam(request, "timezone"), strtoul(getParam(request, "backlightTimeOut").c_str(), NULL, 0), getParam(request, "autoLockHygieneOpeningTimeout") == "true", restrictions); request->send(200, "text/plain", "Configuration updated"); } else { request->send(404, "text/plain", "Not Found!"); } } protected: /** * @brief Event handler called if a new emergency key should be generated * * @param request the request received from the browser */ void onGenerateNewKey(AsyncWebServerRequest* request) { if (isConfigurationAllowed()) { request->send(200, "text/plain", Configuration::getSingleton().generateNewEmergencyKey()); } else { request->send(404, "text/plain", "Not Found!"); } } protected: /** * @brief Event handler for the WebSocket connection which is used to remote control the safe * * @param client the client which triggered the event * @param type the event type * @param arg the information about received data * @param data the received data * @param len the length of the received data */ void onRemoteControlWebSocketEvent(AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len) { if (type == WS_EVT_CONNECT) { Serial.println("Websocket client connection received"); } else if (type == WS_EVT_DATA) { AwsFrameInfo* info = (AwsFrameInfo*)arg; if ((info->opcode == WS_TEXT) && (len == 1)) { if (data[0] == 'L') { String response = display.getCompleteContent(); response += isConfigurationAllowed() ? "true\n" : "false\n"; response += lcd::ViewBase::isBacklightOn() ? "true\n" : "false\n"; client->text(response); } else if (data[0] == 'A') { encoder.injectClockwiseRotation(); } else if (data[0] == 'B') { encoder.injectClick(); } else if (data[0] == 'C') { encoder.injectCounterClockwiseRotation(); } } } else if (type == WS_EVT_DISCONNECT) { Serial.println("Client disconnected"); } else { Serial.println("else"); } } }; } // namespace configuration
hugo3132/EmlaLockSafe
software/src/views/EmergencyMenu.h
/** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "ViewStore.h" #include <MenuView.h> namespace views { /** * @brief Emergency menu */ class EmergencyMenu : public lcd::MenuView { public: /** * @brief Construct a new main menu object * * @param display pointer to the display instance * @param encoder pointer to the encoder instance * @param numberOfColumns number of display-columns * @param numberOfRows number of display-rows */ EmergencyMenu(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder, const int& numberOfColumns, const int& numberOfRows) : lcd::MenuView(display, "EmergencyMenu", encoder, "Emergency Menu", numberOfColumns, numberOfRows) {} public: /** * @brief Copy constructor - not available */ EmergencyMenu(const EmergencyMenu& other) = delete; public: /** * @brief Move constructor - not available otherwise we get problems with the callbacks. */ EmergencyMenu(EmergencyMenu&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { // is this the first time activate is called? if (menuItems.empty()) { // create menu items createMenuItem("Unlock with key", [this](MenuItem*) { ViewStore::activateView(ViewStore::EmergencyEnterKeyView); }); createMenuItem("Start Wifi", [this](MenuItem*) { ViewStore::activateView(ViewStore::WifiConnectingView); }); createMenuItem("Offline Mode", [this](MenuItem*) { if (LockState::getEndDate() > time(NULL)) { views::ViewStore::activateView(views::ViewStore::LockedView); } else { views::ViewStore::activateView(views::ViewStore::UnlockedMainMenu); } }); } lcd::MenuView::activate(); } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/configuration/HardwareConfiguration.h
<gh_stars>1-10 /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once /** * @brief GPIO the coil of the safe is connected to */ #define COIL_PIN 15 /** * @brief Value of the COIL_PIN if the coil should be locked */ #define SAFE_COIL_LOCKED LOW /** * @brief Value of the COIL_PIN if the coil should be unlocked */ #define SAFE_COIL_UNLOCKED HIGH /** * @brief GPIO of the ky-040 clk pin */ #define ENCODER_PIN_CLK 27 /** * @brief GPIO of the ky-040 dt pin */ #define ENCODER_PIN_DT 26 /** * @brief GPIO of the ky-040 sw pin */ #define ENCODER_SWITCH 25 /** * @brief I2C address of the LCD */ #define LCD_ADDR 0x27 /** * @brief number of columns of the lcd */ #define LCD_NUMBER_OF_COLS 20 /** * @brief number of rows of the lcd */ #define LCD_NUMBER_OF_ROWS 4
hugo3132/EmlaLockSafe
software/src/views/PreferencesMenu.h
<filename>software/src/views/PreferencesMenu.h /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../Tools.h" #include "../UsedInterrupts.h" #include "../configuration/Configuration.h" #include <DialogYesNo.h> #include <ESP.h> #include <MenuView.h> #include <SPIFFS.h> namespace views { /** * @brief preferences menu */ class PreferencesMenu : public lcd::MenuView { public: /** * @brief Construct a new menu object * * @param display pointer to the display instance * @param encoder pointer to the encoder instance * @param numberOfColumns number of display-columns * @param numberOfRows number of display-rows */ PreferencesMenu(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder, const int& numberOfColumns, const int& numberOfRows) : lcd::MenuView(display, "PreferencesMenu", encoder, "Preferences", numberOfColumns, numberOfRows) {} public: /** * @brief Copy constructor - not available */ PreferencesMenu(const PreferencesMenu& other) = delete; public: /** * @brief Move constructor - not available otherwise we get problems with the callbacks. */ PreferencesMenu(PreferencesMenu&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { // is this the first time activate is called? if (menuItems.empty()) { createMenuItem("Change Wifi Settings", [this](MenuItem*) { configuration::Configuration::getSingleton().setWifiSettings("", ""); ESP.restart(); }); createMenuItem("Start Configuration Server", [this](MenuItem*) { const auto& timeRestictions = configuration::Configuration::getSingleton().getTimeRestrictions(); if (!timeRestictions.restrictConfigurationServer || timeRestictions.checkTime()) { ViewStore::activateView(ViewStore::ConfigurationServerView); } else { ViewStore::activateView(ViewStore::TimeRestrictedView); } }); createMenuItem("Restore Factory Defaults", [this](MenuItem*) { if (lcd::DialogYesNo(display, encoder, "Are you sure to\ndelete everything?", numberOfColumns, numberOfRows) .showModal(false)) { configuration::Configuration::getSingleton().restoreFactoryDefaults(); display->clear(); display->setCursor(0, 0); display->print("The controller is"); display->setCursor(0, 1); display->print("gooing to reboot..."); delay(2000); ESP.restart(); } }); createMenuItem("Back", [this](MenuItem*) { activatePreviousView(); }); } lcd::MenuView::activate(); } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/UpdateCertificatesView.h
/** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../configuration/HardwareConfiguration.h" #include <ESP8266WiFi.h> #include <LittleFS.h> #include <ViewBase.h> namespace views { /** * @brief View displayed while updating the certificates */ class UpdateCertificatesView : public lcd::ViewBase { protected: /** * @brief Reference of the ssl client used for the communication */ WiFiClientSecure& sslClient; protected: /** * @brief Reference of the certificate store */ BearSSL::CertStore certStore; String lastErrorMessage; protected: int numberOfLoadedCertificates; public: /** * @brief Construct a vie object * * @param display pointer to the LCD instance * @param sslClient reference of the ssl client used for the communication * @param certStore reference of the certificate store */ UpdateCertificatesView(LiquidCrystal_PCF8574* display, WiFiClientSecure& sslClient, BearSSL::CertStore& certStore) : lcd::ViewBase(display) , sslClient(sslClient) , certStore(certStore) {} public: /** * @brief Copy constructor - not available */ UpdateCertificatesView(const UpdateCertificatesView& other) = delete; public: /** * @brief Move constructor - not available */ UpdateCertificatesView(UpdateCertificatesView&& other) noexcept = delete; public: int begin() { numberOfLoadedCertificates = certStore.initCertStore(LittleFS, PSTR("/certs.idx"), PSTR("/certs.ar")); if (numberOfLoadedCertificates == 0) { // no SSL certificates available Serial.println("No SSL Certificates found in Flash."); sslClient.setInsecure(); } else { Serial.print(numberOfLoadedCertificates); Serial.println(" SSL Certificates found in Flash."); sslClient.setCertStore(&certStore); } return numberOfLoadedCertificates; } protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { begin(); display->clear(); display->setCursor(0, 0); display->print("Updating SSL Certs"); // download the csv file to the file-system if (!downloadCertificatesAsCsv()) { Serial.println(lastErrorMessage); return; } sslClient.stopAll(); Serial.print("Free Heap: "); Serial.print(ESP.getFreeHeap()); Serial.print(" Free Stack: "); Serial.println(ESP.getFreeContStack()); // First iteration through csv file: Count certificates /////////////////////////////////////////////////////////////////////////// File certsCsv = LittleFS.open("/certs.csv", "r"); int numberOfCertificates = 0; while (true) { // jump to the start of the next certificate if (!goToStartOfNextCertificate(certsCsv)) { break; } numberOfCertificates++; } // check if it makes sense to regenerate the archive if (numberOfCertificates == 0) { lastErrorMessage = "No certificates found in downloaded CSV file"; return; } Serial.print("Free Heap: "); Serial.print(ESP.getFreeHeap()); Serial.print(" Free Stack: "); Serial.println(ESP.getFreeContStack()); // go to the beginning of the CSV file to start parsing certsCsv.seek(0); // Second iteration through csv file: Convert to DER and save as archive /////////////////////////////////////////////////////////////////////////// display->clear(); display->setCursor(0, 0); display->print("Updating SSL Certs"); display->setCursor(0, 1); display->print("Converting:"); display->setCursor(0, 2); display->print("Certificate 0/"); display->print(numberOfCertificates); File certsAr = LittleFS.open("/certs.tmp", "w"); certsAr.write("!<arch>\n"); for (int certificateCounter = 1; certificateCounter <= numberOfCertificates; certificateCounter++) { display->setCursor(12, 2); display->print(certificateCounter); display->print("/"); display->print(numberOfCertificates); if (!goToStartOfNextCertificate(certsCsv)) { break; } if (!convertCertificate(certsCsv, certsAr)) { break; } yield(); } certsAr.close(); certsCsv.close(); Serial.print("Free Heap: "); Serial.print(ESP.getFreeHeap()); Serial.print(" Free Stack: "); Serial.println(ESP.getFreeContStack()); display->clear(); display->setCursor(0, 0); display->print("Updating SSL Certs"); display->setCursor(0, 1); display->print("Verifying..."); Serial.print("Free Heap: "); Serial.print(ESP.getFreeHeap()); Serial.print(" Free Stack: "); Serial.println(ESP.getFreeContStack()); auto numberOfLoadedCertificates = certStore.initCertStore(LittleFS, PSTR("/certst.idx"), PSTR("/certs.tmp")); if (numberOfLoadedCertificates != 0) { if (LittleFS.exists("/certs.ar")) { LittleFS.remove("/certs.ar"); } if (LittleFS.exists("/certs.idx")) { LittleFS.remove("/certs.idx"); } if (LittleFS.exists("/certst.idx")) { LittleFS.remove("/certst.idx"); } LittleFS.rename("/certs.tmp", "/certs.ar"); } display->setCursor(0, 2); display->print("OK. Going to Reboot"); delay(2000); ESP.restart(); } protected: /** * @brief Shows the animation while waiting until the callback returns false * * @param stillActive callback function checking if the animation should be * shown */ void waitAnimation(std::function<bool()> stillActive) { while (stillActive()) { for (int i = 0; (i < 20) && stillActive(); i++) { if (i == 0) { display->setCursor(19, 3); display->print(' '); display->setCursor(i, 3); display->print('*'); } else { display->setCursor(i - 1, 3); display->print(" *"); } delay(100); } } } protected: bool initializeConnection(const String& host, const String& url) { // try to connect to the server if (!sslClient.connect(host, 443)) { lastErrorMessage = "Connection to https://" + host + "/" + url + " failed."; return false; } yield(); // send get request sslClient.print("GET /" + url + " HTTP/1.1\r\n" "Host: " + host + "\r\n" "User-Agent: ESP8266\r\n" "Connection: Keep-Alive\r\n\r\n"); yield(); // wait until the header is received. String result = "Invalid Header received."; while (sslClient.connected()) { String line = sslClient.readStringUntil('\n'); if ((line.length() > 8) && (line.substring(0, 8) == "HTTP/1.1")) { result = line.substring(9); } if (line == "\r") { break; } } yield(); // check result result.trim(); if (result != "200 OK") { lastErrorMessage = "Error Getting https://" + host + "/" + url + ": " + result; sslClient.stopAll(); } yield(); return true; } bool downloadCertificatesAsCsv() { Serial.print("Free Heap: "); Serial.print(ESP.getFreeHeap()); Serial.print(" Free Stack: "); Serial.println(ESP.getFreeContStack()); display->setCursor(0, 1); display->print("Connecting..."); if (!initializeConnection("ccadb-public.secure.force.com", "mozilla/IncludedCACertificateReportPEMCSV")) { return false; } Serial.print("Free Heap: "); Serial.print(ESP.getFreeHeap()); Serial.print(" Free Stack: "); Serial.println(ESP.getFreeContStack()); File certsCsv = LittleFS.open("/certs.csv", "w"); char buf[100]; int blockCounter = 0; display->setCursor(0, 1); display->print("Downloading 0kb "); while (true) { size_t numBytesRead = sslClient.readBytes(buf, 100); if (numBytesRead == 0) { break; } certsCsv.write(buf, numBytesRead); blockCounter++; if (blockCounter % 100 == 0) { display->setCursor(12, 1); display->print(blockCounter / 10); display->print("kb"); } yield(); } display->setCursor(0, 1); display->print("CSV downloaded. "); display->setCursor(0, 2); display->print("Saving file."); certsCsv.close(); Serial.print("Free Heap: "); Serial.print(ESP.getFreeHeap()); Serial.print(" Free Stack: "); Serial.println(ESP.getFreeContStack()); // cleanup client sslClient.stopAll(); Serial.print("Free Heap: "); Serial.print(ESP.getFreeHeap()); Serial.print(" Free Stack: "); Serial.println(ESP.getFreeContStack()); return true; } protected: bool goToStartOfNextCertificate(File& certsCsv) { const char* searchString = "-----BEGIN CERTIFICATE-----"; const char* searchChar = searchString; while (searchChar != searchString + strlen(searchString)) { uint8_t chr; if (certsCsv.read(&chr, 1) != 1) { return false; } // check if it is part of the search string if (chr == *searchChar) { searchChar++; } else { searchChar = searchString; } } return true; } protected: uint16_t certificateCounter = 0; bool convertCertificate(File& certsCsv, File& certsAr) { static const uint8_t base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; uint8_t chr; // write header of file char headerBuf[17]; strcpy(headerBuf, "ca_000.der/ "); headerBuf[3] = (certificateCounter / 100) % 10 + 48; headerBuf[4] = (certificateCounter / 10) % 10 + 48; headerBuf[5] = certificateCounter % 10 + 48; certificateCounter++; certsAr.write(headerBuf, 16); // file modification date certsAr.write("1596291962 ", 12); // owner id certsAr.write("0 ", 6); // group ID certsAr.write("0 ", 6); // File mode (type and permission) certsAr.write("100666 ", 8); auto sizeStart = certsAr.position(); // File size in bytes certsAr.write(" ", 10); // Ending characters headerBuf[0] = 0x60; headerBuf[1] = 0x0A; certsAr.write(headerBuf, 2); // Parse, Convert and Write the actual certificate uint16_t fileSize = 0; while (true) { // buffer for the converted bytes uint8_t buf[3] = {0, 0, 0}; uint8_t parserInCounter = 0; uint8_t parserOutCounter = 0; // Try to get 4 base64 characters which convert into 3 binary characters while (parserInCounter != 4) { // read next character if (certsCsv.read(&chr, 1) != 1) { return false; } // check if this is part of the end certificate string if (chr == '-') { break; } // Is it a alignment character? if (chr == '=') { parserInCounter++; continue; } // First part of conversion uint8_t i; for (i = 0; i < 64 && chr != base64[i]; i++) { } // Shift the bits of the conversion to the correct position if (i != 64) { switch (parserInCounter) { case 0: buf[0] = i << 2; parserOutCounter = 1; break; case 1: buf[0] += i >> 4; buf[1] = i << 4; if (buf[1] != 0) { parserOutCounter = 2; } break; case 2: buf[1] += i >> 2; buf[2] = i << 6; parserOutCounter = 2; if (buf[2] != 0) { parserOutCounter = 3; } break; case 3: buf[2] += i; parserOutCounter = 3; break; } parserInCounter++; } } // output the generated data certsAr.write(buf, parserOutCounter); fileSize += parserOutCounter; // Check if the certificate was fully read. if (chr == '-') { break; } } // check if the number of bytes is odd: if (fileSize % 2 != 0) { headerBuf[0] = 0x0A; certsAr.write(headerBuf, 1); } // Save the file Size certsAr.seek(sizeStart); certsAr.print(fileSize); certsAr.seek(0, fs::SeekEnd); return true; } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) {} }; // namespace views } // namespace views
hugo3132/EmlaLockSafe
software/src/views/UnlockSafeView.h
/** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../LockState.h" #include "../Tools.h" #include "../configuration/Configuration.h" #include "ViewStore.h" #include <DialogOK.h> #include <MenuView.h> #include <RotaryEncoder.h> #include <ViewBase.h> #include <time.h> namespace views { /** * @brief View used to unlock the safe */ class UnlockSafeView : public lcd::ViewBase { protected: /** * @brief pointer to the encoder instance */ RotaryEncoder* encoder; protected: /** * @brief Number of display-columns */ const int numberOfColumns; protected: /** * @brief Number of display-rows */ const int numberOfRows; protected: /** * @brief Time when this view was activated */ time_t activationTime; public: /** * @brief Construct the vie * * @param display pointer to the LCD instance * @param encoder pointer to the encoder instance * @param numberOfColumns number of display-columns * @param numberOfRows number of display-rows */ UnlockSafeView(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder, const int& numberOfColumns, const int& numberOfRows) : lcd::ViewBase(display, "UnlockSafeView") , encoder(encoder) , numberOfColumns(numberOfColumns) , numberOfRows(numberOfRows) {} public: /** * @brief Copy constructor - not available */ UnlockSafeView(const UnlockSafeView& other) = delete; public: /** * @brief Move constructor - not available */ UnlockSafeView(UnlockSafeView&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { display->clear(); display->setCursor(0, 0); display->print("Verifying Emlalock"); activationTime = time(NULL); // only update trigger the api if the last update time is not in the future. // The time will be in the future if an emergency key was entered. if (LockState::getLastUpdateTime() < time(NULL)) { emlalock::EmlaLockApi::getSingleton().triggerRefresh(); } // since tick is blocking we should never call it directly from here... } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { // Show the wait animation Tools::waitAnimation(display, [this]() -> bool { return (LockState::getLastUpdateTime() < activationTime) && (time(NULL) - activationTime < 15); }); // Did we run in a 15s timeout? if (LockState::getLastUpdateTime() < activationTime) { digitalWrite(COIL_PIN, SAFE_COIL_LOCKED); lcd::DialogOk(display, encoder, "The Emlalock API\ndid not answer\nwithin 15s.", numberOfColumns, numberOfRows).showModal(); activatePreviousView(); return; } // Should the safe be locked configuration::Configuration& config = configuration::Configuration::getSingleton(); if ((LockState::getEndDate() > time(NULL)) && ((LockState::getCleaningEndDate() == 0) || (config.getAutoLockHygieneOpeningTimeout() && (LockState::getCleaningEndDate() < time(NULL))))) { digitalWrite(COIL_PIN, SAFE_COIL_LOCKED); activatePreviousView(); return; } // Activate the coil if necessary static unsigned long coilActivationTime = 0; if (!digitalRead(COIL_PIN)) { display->clear(); display->setCursor(0, 0); display->print("Safe unlocked"); coilActivationTime = millis(); digitalWrite(COIL_PIN, SAFE_COIL_UNLOCKED); } // show a animation showing how many time is lest until the coil is released // again display->setCursor(0, 1); for (int i = 0; i < (millis() - coilActivationTime) / 500; i++) { display->write('='); } // Check if the coil should be released after 10 seconds if ((millis() - coilActivationTime > 10000) || (encoder->getNewClick())) { digitalWrite(COIL_PIN, SAFE_COIL_LOCKED); activatePreviousView(); } } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/TimeRestrictedView.h
/** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../configuration/Configuration.h" #include <ViewBase.h> namespace views { /** * @brief View used when the safe should be opened but the time is not within the allowed range */ class TimeRestrictedView : public lcd::ViewBase { protected: /** * @brief Time when the view was activated */ long activationMillis; public: /** * @brief Construct the view * * @param display pointer to the LCD instance */ TimeRestrictedView(LiquidCrystal_PCF8574* display) : lcd::ViewBase(display, "TimeRestrictedView") {} public: /** * @brief Copy constructor - not available */ TimeRestrictedView(const TimeRestrictedView& other) = delete; public: /** * @brief Move constructor */ TimeRestrictedView(TimeRestrictedView&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { getBacklightTimeoutManager().delayTimeout(); activationMillis = millis(); tick(true); } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { getBacklightTimeoutManager().delayTimeout(); if (activationMillis + 10000 < millis()) { activatePreviousView(); } // Stuff which never changes if (forceRedraw) { const auto& restrictions = configuration::Configuration::getSingleton().getTimeRestrictions(); display->clear(); display->setCursor(0, 0); display->print("Open Time Restricted"); display->setCursor(0, 1); int h = restrictions.startTime / 3600; int m = (restrictions.startTime / 60) % 60; display->printf("Start Time: %02d:%02d", h, m); display->setCursor(0, 2); h = restrictions.endTime / 3600; m = (restrictions.startTime / 60) % 60; display->printf("End Time: %02d:%02d", h, m); display->setCursor(0, 3); display->print("Current Time: 00:00"); } // current time static time_t lastDisplayedCurrentTime = 0; time_t currentTime = time(NULL); if (forceRedraw || (lastDisplayedCurrentTime / 60 != currentTime / 60)) { char buf[21]; tm tmBuf; lastDisplayedCurrentTime = currentTime; strftime(buf, 6, "%R", localtime_r(&currentTime, &tmBuf)); display->setCursor(15, 3); display->print(buf); } } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/HygieneOpeningMenu.h
<gh_stars>1-10 /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../LockState.h" #include "ViewStore.h" #include <MenuView.h> namespace views { /** * @brief View used when the safe is unlocked for a hygiene opening */ class HygieneOpeningMenu : public lcd::MenuView { public: /** * @brief Construct a new hygiene opening menu object * * @param display pointer to the display instance * @param encoder pointer to the encoder instance * @param numberOfColumns number of display-columns * @param numberOfRows number of display-rows */ HygieneOpeningMenu(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder, const int& numberOfColumns, const int& numberOfRows) : lcd::MenuView(display, "HygieneOpeningMenu", encoder, "Hygiene Opening", numberOfColumns, numberOfRows) {} public: /** * @brief Copy constructor - not available */ HygieneOpeningMenu(const HygieneOpeningMenu& other) = delete; public: /** * @brief Move constructor */ HygieneOpeningMenu(HygieneOpeningMenu&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { // is this the first time activate is called? if (menuItems.empty()) { // create menu items createMenuItem("Open Safe", [](MenuItem*) { const auto& timeRestictions = configuration::Configuration::getSingleton().getTimeRestrictions(); if (!timeRestictions.restrictHygieneOpeningTimes || timeRestictions.checkTime()) { ViewStore::activateView(ViewStore::UnlockSafeView); } else { ViewStore::activateView(ViewStore::TimeRestrictedView); } }); createMenuItem("Emlalock Unlock Key", [](MenuItem*) { ViewStore::activateView(ViewStore::EmlalockUnlockKeyMenu); }); createMenuItem("Time Left: 00:00:00", [](MenuItem*) {}); } lcd::MenuView::activate(); } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { // updated the view of the menu lcd::MenuView::tick(forceRedraw); auto direction = encoder->getDirection(); auto click = encoder->getNewClick(); char buf[21]; if (click || (direction != RotaryEncoder::Direction::NOROTATION)) { if (!getBacklightTimeoutManager().delayTimeout()) { return; } } getBacklightTimeoutManager().tick(display); // should the time left be displayed? If yes, how static time_t lastDisplayedTime = 0; time_t timeLeft = 0; if (LockState::getCleaningEndDate() > time(NULL)) { timeLeft = LockState::getCleaningEndDate() - time(NULL); } // redraw required? if (forceRedraw || (lastDisplayedTime != timeLeft)) { lastDisplayedTime = timeLeft; int sec = timeLeft % 60; timeLeft = timeLeft / 60; int min = timeLeft % 60; timeLeft = timeLeft / 60; int hour = timeLeft; sprintf(buf, "Time Left: %02d:%02d:%02d", hour, min, sec); menuItems.back().setText(buf); } } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/SetTimerView.h
<reponame>hugo3132/EmlaLockSafe /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "LockState.h" #include "ViewStore.h" #include <DialogYesNoBack.h> #include <MenuView.h> #include <RotaryEncoder.h> #include <ViewBase.h> namespace views { /** * @brief View used to set a manual timer without EmlaLock in the background */ class SetTimerView : public lcd::ViewBase { protected: /** * @brief pointer to the encoder instance */ RotaryEncoder* encoder; protected: /** * @brief Number of display-columns */ const int numberOfColumns; protected: /** * @brief Number of display-rows */ const int numberOfRows; protected: /** * @brief current selection of the number of days */ uint8_t numberOfDays; protected: /** * @brief current selection of the number of hours */ uint8_t numberOfHours; protected: /** * @brief current selection of the number of minutes */ uint8_t numberOfMinutes; protected: /** * @brief selection what field can be changed: * * 0: number of days * 1: number of hours * 2: number of minutes */ uint8_t editIndex; public: /** * @brief Construct the new set timer view * * @param display pointer to the LCD instance * @param encoder pointer to the encoder instance * @param numberOfColumns number of display-columns * @param numberOfRows number of display-rows */ SetTimerView(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder, const int& numberOfColumns, const int& numberOfRows) : lcd::ViewBase(display, "SetTimerView") , encoder(encoder) , numberOfColumns(numberOfColumns) , numberOfRows(numberOfRows) {} public: /** * @brief Copy constructor - not available */ SetTimerView(const SetTimerView& other) = delete; public: /** * @brief Move constructor - not available */ SetTimerView(SetTimerView&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { display->clear(); // reset the values numberOfDays = 0; numberOfHours = 0; numberOfMinutes = 0; editIndex = 0; // redraw everything tick(true); } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { bool redraw = forceRedraw; // handle the encoder handleEncoderRotation(redraw); if (!handleEncoderClick(redraw)) { return; } // redraw the timer settings if (redraw) { display->setCursor(0, 0); display->print("Set Lock Timer:"); display->setCursor(0, 1); display->printf("%s%d%cdays ", (editIndex == 0 ? ">" : ""), numberOfDays, (editIndex == 0 ? '<' : ' ')); display->setCursor(0, 2); char buf[25]; sprintf(buf, "%s%d%chours %s%d%cminutes ", (editIndex == 1 ? ">" : ""), numberOfHours, (editIndex == 1 ? '<' : ' '), (editIndex == 2 ? ">" : ""), numberOfMinutes, (editIndex == 2 ? '<' : ' ')); buf[20] = '\0'; display->print(buf); } // redraw end-time time_t setTime = time(NULL) + ((((time_t)numberOfDays) * 24 + ((time_t)numberOfHours)) * 60 + ((time_t)numberOfMinutes)) * 60; static time_t lastDisplayedTime = 0; if (redraw || (setTime != lastDisplayedTime)) { tm tmBuf; char buf[21]; strftime(buf, 20, "(%d.%m.%Y %R)", localtime_r(&setTime, &tmBuf)); display->setCursor(0, 3); display->print(buf); lastDisplayedTime = setTime; } } protected: /** * @brief handles if the encoder was rotated * * @param[in, out] redraw true if the content of the display must be redraw */ void handleEncoderRotation(bool& redraw) { // read the state of the encoder auto direction = encoder->getDirection(); // increase the selected value? if (direction == RotaryEncoder::Direction::CLOCKWISE) { switch (editIndex) { case 0: numberOfDays++; break; case 1: numberOfHours++; if (numberOfHours == 24) { numberOfHours = 0; } break; case 2: numberOfMinutes++; if (numberOfMinutes == 60) { numberOfMinutes = 0; } break; } redraw = true; // redraw required } // decrease the selected value? if (direction == RotaryEncoder::Direction::COUNTERCLOCKWISE) { switch (editIndex) { case 0: numberOfDays--; break; case 1: if (numberOfHours == 0) { numberOfHours = 24; } numberOfHours--; break; case 2: if (numberOfMinutes == 0) { numberOfMinutes = 60; } numberOfMinutes--; break; } redraw = true; // redraw required } } protected: /** * @brief handles if the encoder was rotated * * @param[in, out] redraw true if the content of the display must be redraw * * @return false if the current tick should be immediately skipped */ bool handleEncoderClick(bool& redraw) { // was the button pressed? if (encoder->getNewClick()) { // select the next value editIndex++; redraw = true; // redraw required // check if all 3 values were updated if (editIndex == 3) { // generate the dialog message for the are you sure question: time_t endDate = time(NULL) + ((((time_t)numberOfDays) * 24 + ((time_t)numberOfHours)) * 60 + ((time_t)numberOfMinutes)) * 60; tm tmBuf; char buf[61]; strftime(buf, 61, "Are you sure to lock\nuntil\n%d.%m.%Y %R?", localtime_r(&endDate, &tmBuf)); // display dialog switch (lcd::DialogYesNoBack(display, encoder, buf, numberOfColumns, numberOfRows) .showModal(lcd::DialogYesNoBack::DialogResult::no)) { case lcd::DialogYesNoBack::DialogResult::yes: LockState::setCachedEndDate(endDate); views::ViewStore::activateView(views::ViewStore::SelectDisplayTimePassed); return false; // immediately skip tick case lcd::DialogYesNoBack::DialogResult::no: return true; case lcd::DialogYesNoBack::DialogResult::back: // go back to menu activatePreviousView(); return false; } } } return true; } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/EmlalockUnlockKeyMenu.h
<filename>software/src/views/EmlalockUnlockKeyMenu.h /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../configuration/Configuration.h" #include <DialogYesNo.h> #include <MenuView.h> namespace views { /** * @brief Menu for showing / changing the unlock key */ class EmlalockUnlockKeyMenu : public lcd::MenuView { public: /** * @brief Construct a new menu object * * @param display pointer to the display instance * @param encoder pointer to the encoder instance * @param numberOfColumns number of display-columns * @param numberOfRows number of display-rows */ EmlalockUnlockKeyMenu(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder, const int& numberOfColumns, const int& numberOfRows) : lcd::MenuView(display, "EmlalockUnlockKeyMenu", encoder, "Emlalock Unlock Key", numberOfColumns, numberOfRows) {} public: /** * @brief Copy constructor - not available */ EmlalockUnlockKeyMenu(const EmlalockUnlockKeyMenu& other) = delete; public: /** * @brief Move constructor - not available otherwise we get problems with the callbacks. */ EmlalockUnlockKeyMenu(EmlalockUnlockKeyMenu&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { // is this the first time activate is called? if (menuItems.empty()) { // Menu item just showing the current key String keyItemText = "Current Key: " + configuration::Configuration::getSingleton().getEmergencyKey(); createMenuItem(keyItemText, [this](MenuItem*) {}); // Menu item which allows to generate a new key createMenuItem("Generate new key", [this](MenuItem*) { if (lcd::DialogYesNo(display, encoder, "Are you sure?\nThe old key wont't\nbe valid anymore.", numberOfColumns, numberOfRows) .showModal(false)) { // update the menu item String keyItemText = "Current key: " + configuration::Configuration::getSingleton().generateNewEmergencyKey(); menuItems.front().setText(keyItemText); } }); // Item for going back to the previous menu. createMenuItem("Back", [this](MenuItem*) { activatePreviousView(); }); } lcd::MenuView::activate(); } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/views/WifiConnectingView.h
<gh_stars>1-10 /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../Tools.h" #include "../configuration/Configuration.h" #include <MenuView.h> #include <ViewBase.h> #include <WiFi.h> #include <time.h> namespace views { /** * @brief View displayed while connection to the access point */ class WifiConnectingView : public lcd::ViewBase { public: /** * @brief Construct the view object * * @param display pointer to the LCD instance */ WifiConnectingView(LiquidCrystal_PCF8574* display) : lcd::ViewBase(display, "WifiConnectingView") {} public: /** * @brief Copy constructor - not available */ WifiConnectingView(const WifiConnectingView& other) = delete; public: /** * @brief Move constructor - not available */ WifiConnectingView(WifiConnectingView&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { display->clear(); display->setCursor(0, 0); display->print("Connecting to wifi:"); display->setCursor(0, 1); display->print(configuration::Configuration::getSingleton().getSsid()); // Start connecting WiFi.disconnect(); WiFi.setHostname("EmlalockSafe"); WiFi.mode(WIFI_STA); WiFi.begin(configuration::Configuration::getSingleton().getSsid().c_str(), configuration::Configuration::getSingleton().getPwd().c_str()); WiFi.setAutoReconnect(true); // Play an animation while the connection is established int counter = 0; Tools::waitAnimation(display, [&counter]() -> bool { counter++; if (counter % 25 == 0) { // if we've waited for over 2.5s (25 loops), restart wifi.... // this is required because of an bug in the ESP32 arduino core. WiFi.disconnect(); WiFi.setHostname("EmlalockSafe"); WiFi.mode(WIFI_STA); WiFi.begin(configuration::Configuration::getSingleton().getSsid().c_str(), configuration::Configuration::getSingleton().getPwd().c_str()); WiFi.setAutoReconnect(true); } return WiFi.status() != WL_CONNECTED; }); display->clear(); display->setCursor(0, 0); display->print("Setting Timezone:"); // configure NTP configTzTime(configuration::Configuration::getSingleton().getTimezone().c_str(), "pool.ntp.org", "time.nist.gov", "time.google.com"); // go back to previous view activatePreviousView(); } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { // not used since activate blocks and immediately returns to the previous // view } }; // namespace views } // namespace views
hugo3132/EmlaLockSafe
software/src/configuration/Configuration.h
<reponame>hugo3132/EmlaLockSafe /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "..\UsedInterrupts.h" #include <Arduino.h> #include <SPIFFS.h> #include <ViewBase.h> #include <algorithm> #include <stdlib.h> #include <time.h> namespace configuration { /** * @brief Static class accessing the configuration */ class Configuration { public: /** * @brief Container to restrict the time when the safe can be opened. * * The safe can only be opened between start and endTime */ class TimeRestrictions { friend class Configuration; public: /** * @brief The number of seconds after midnight after which the safe can be opened */ uint32_t startTime; public: /** * @brief The number of seconds after midnight until which the safe can be opened */ uint32_t endTime; public: /** * @brief If set, the safe can only be opened during the specified time using the normal unlock function */ bool restrictUnlockTimes; public: /** * @brief If set, the time for hygiene openings is restricted */ bool restrictHygieneOpeningTimes; public: /** * @brief If set, the time when the emergency key is accepted is restricted */ bool restrictEmergencyKeyTimes; public: /** * @brief If set, the time when the configuration server can be started is restricted */ bool restrictConfigurationServer; public: /** * @brief Construct a new Time Restrictions object */ TimeRestrictions() : startTime(0) , endTime(86400) , restrictUnlockTimes(false) , restrictHygieneOpeningTimes(false) , restrictEmergencyKeyTimes(false) , restrictConfigurationServer(false) {} public: /** * @brief check if the current time is valid for opening the safe */ bool checkTime() const { // compute the number of seconds of this day time_t currentTime = time(NULL); tm tmBuf; localtime_r(&currentTime, &tmBuf); uint32_t currentSeconds = tmBuf.tm_hour * 3600 + tmBuf.tm_min * 60 + tmBuf.tm_sec; if (startTime == endTime) { return true; } else if (endTime > startTime) { return (currentSeconds >= startTime) && (currentSeconds <= endTime); } else { // Midnight overflow return (currentSeconds >= endTime) && (currentSeconds <= startTime); } } protected: /** * @brief Reads the content of this class from the configuration file stream * * @param file file stream at the position where the data should be located */ void readFromFile(File& file) { String start = file.readStringUntil('\n'); String end = file.readStringUntil('\n'); String restrictions = file.readStringUntil('\n'); start.trim(); end.trim(); restrictions.end(); if (start.isEmpty() || end.isEmpty() || restrictions.isEmpty()) { startTime = 0; endTime = 86400; restrictUnlockTimes = false; restrictHygieneOpeningTimes = false; restrictEmergencyKeyTimes = false; restrictConfigurationServer = false; } else { startTime = strtoul(start.c_str(), NULL, 0); endTime = strtoul(end.c_str(), NULL, 0); unsigned long l = strtoul(restrictions.c_str(), NULL, 0); restrictUnlockTimes = l & (1 << 0); restrictHygieneOpeningTimes = l & (1 << 1); restrictEmergencyKeyTimes = l & (1 << 2); restrictConfigurationServer = l & (1 << 3); } } protected: /** * @brief Writes all configuration items of this class to the file at the current stream position * * @param file file stream at the position where the data should be located */ void writeToFile(File& file) { file.println(startTime); file.println(endTime); file.println((restrictUnlockTimes << 0) | (restrictHygieneOpeningTimes << 1) | (restrictEmergencyKeyTimes << 2) | (restrictConfigurationServer << 3)); } }; #pragma region Singelton protected: /** * @brief Function providing the instance for the singleton */ inline static Configuration** getInstance() { static Configuration* instance = nullptr; return &instance; } public: /** * @brief Get the Singleton object */ inline static Configuration& getSingleton() { return **getInstance(); } public: /** * @brief initialize the configuration object and load the configuration file */ inline static Configuration& begin() { if (!*getInstance()) { *getInstance() = new Configuration(); } return **getInstance(); } #pragma endregion #pragma region WiFi Settings protected: /** * @brief The SSID(name) of your wifi */ String ssid; protected: /** * @brief The password of your wifi. */ String pwd; #pragma endregion #pragma region Emlalock settings protected: /** * @brief The User ID extracted from the webpage settings > API */ String userId; protected: /** * @brief The API Key extracted from the webpage settings > API */ String apiKey; protected: /** * @brief The emergency key */ String emergencyKey; protected: /** * @brief Disable support of failed session. <b>Note: </b>If selected, the safe will be locked until the last known end date before * a session was ended and marked as failed. Hygiene openings can no longer be triggered since the session is no longer valid! */ bool disableFailedSession; #pragma endregion #pragma region Miscellaneous Settings protected: /** * @brief The timezone-string (e.g. "CET-1CEST,M3.5.0,M10.5.0/3") see also * https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv */ String timezone; protected: /** * @brief The name to the timezone-string (e.g. "Europe/Berlin") */ String timezoneName; protected: /** * @brief Timeout of display backlight in seconds */ unsigned long backlightTimeOut; protected: /** * @brief Automatically lock after the time for hygiene opening is over. If not set, the safe stays unlocked until the hygiene * opening is ended on the website. */ bool autoLockHygieneOpeningTimeout; protected: /** * @brief Container to restrict the time when the safe can be opened */ TimeRestrictions timeRestrictions; #pragma endregion public: Configuration() { readConfiguration(); } #pragma region Getter #pragma region WiFi Settings public: /** * @brief get the SSID(name) of your wifi */ const String& getSsid() const { return ssid; } public: /** * @brief get the password of your wifi. */ const String& getPwd() const { return pwd; } #pragma endregion #pragma region Emlalock settings public: /** * @brief get the User ID extracted from the webpage settings > API */ const String& getUserId() const { return userId; } public: /** * @brief get the API Key extracted from the webpage settings > API */ const String& getApiKey() const { return apiKey; } public: /** * @brief get the emergency key of the safe */ const String& getEmergencyKey() const { return emergencyKey; } public: /** * @brief get disable support of failed session. <b>Note: </b>If selected, the safe will be locked until the last known end date before * a session was ended and marked as failed. Hygiene openings can no longer be triggered since the session is no longer valid! */ const bool& getDisableFailedSession() const { return disableFailedSession; } #pragma endregion #pragma region Miscellaneous Settings public: /** * @brief get the timezone-string (e.g. "CET-1CEST,M3.5.0,M10.5.0/3") see also * https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv */ const String& getTimezone() const { return timezone; } public: /** * @brief get the name to the timezone-string (e.g. "Europe/Berlin") */ const String& getTimezoneName() const { return timezoneName; } public: /** * @brief get the timeout of display backlight in seconds */ const unsigned long& getBacklightTimeOut() const { return backlightTimeOut; } public: /** * @brief return if the safe should automatically lock after the time for hygiene opening is over. If not set, the safe stays * unlocked until the hygiene opening is ended on the website. */ const bool& getAutoLockHygieneOpeningTimeout() const { return autoLockHygieneOpeningTimeout; } public: /** * @brief get the timeout of display backlight in seconds */ const TimeRestrictions& getTimeRestrictions() const { return timeRestrictions; } #pragma endregion #pragma endregion #pragma region Setter public: /** * @brief Set the Wifi Settings * * @param ssid new ssid * @param pwd <PASSWORD> */ void setWifiSettings(const String& ssid, const String& pwd) { this->ssid = ssid; this->pwd = <PASSWORD>; writeConfiguration(); } /** * @brief Set the Configuration Settings * * @param userId new Emlalock API user id * @param apiKey new Emlalock API key * @param disableFailedSession disable support of failed session. <b>Note: </b>If selected, the safe will be locked until the last known end date before * a session was ended and marked as failed. Hygiene openings can no longer be triggered since the session is no longer valid! * @param timezoneName new name of timezone * @param timezone new timezone string * @param backlightTimeOut new timeout of display backlight in seconds * @param autoLockHygieneOpeningTimeout Automatically lock after the time for hygiene opening is over. If not set, the safe * stays unlocked until the hygiene opening is ended on the website. * @param timeRestrictions the new time restrictions */ void setConfigurationSettings(const String& userId, const String& apiKey, const bool& disableFailedSession, const String& timezoneName, const String& timezone, const long& backlightTimeOut, const bool& autoLockHygieneOpeningTimeout, const TimeRestrictions& timeRestrictions) { this->userId = userId; this->apiKey = apiKey; this->disableFailedSession = disableFailedSession; this->timezoneName = timezoneName; this->timezone = timezone; setenv("TZ", timezone.c_str(), 1); tzset(); this->backlightTimeOut = backlightTimeOut; lcd::ViewBase::setBacklightTimeout(backlightTimeOut * 1000); this->autoLockHygieneOpeningTimeout = autoLockHygieneOpeningTimeout; this->timeRestrictions = timeRestrictions; this->timeRestrictions.startTime = std::min(this->timeRestrictions.startTime, (uint32_t)86400); this->timeRestrictions.endTime = std::min(this->timeRestrictions.endTime, (uint32_t)86400); writeConfiguration(); } /** * @brief Generates a new key and stores it to the file system. */ const String& generateNewEmergencyKey() { std::srand((unsigned int)micros()); for (int i = 0; i < 6; i++) { emergencyKey[i] = getRandomChar(); } writeConfiguration(); return emergencyKey; } #pragma endregion public: /** * @brief Reset all values to the default values and write configuration */ void restoreFactoryDefaults() { ssid = ""; pwd = ""; userId = ""; apiKey = ""; emergencyKey = "AAAAAA"; disableFailedSession = false; timezone = "CET-1CEST,M3.5.0,M10.5.0/3"; timezoneName = "Europe/Berlin"; backlightTimeOut = 15; autoLockHygieneOpeningTimeout = false; timeRestrictions = TimeRestrictions(); writeConfiguration(); } protected: /** * @brief Read all configuration data from file */ void readConfiguration() { // load everything from the SPIFFS UsedInterrupts::executeWithoutInterrupts([this]() { File file = SPIFFS.open("/configuration.txt", "r"); if (!file) { Serial.println("Loading configuration.txt failed"); return; } ssid = file.readStringUntil('\n'); ssid.trim(); pwd = file.readStringUntil('\n'); pwd.trim(); userId = file.readStringUntil('\n'); userId.trim(); apiKey = file.readStringUntil('\n'); apiKey.trim(); emergencyKey = file.readStringUntil('\n'); emergencyKey.trim(); if (emergencyKey.length() != 6) { emergencyKey = "AAAAAA"; } disableFailedSession = strtol(file.readStringUntil('\n').c_str(), NULL, 0) == 1; timezone = file.readStringUntil('\n'); timezone.trim(); timezoneName = file.readStringUntil('\n'); timezoneName.trim(); backlightTimeOut = strtoul(file.readStringUntil('\n').c_str(), NULL, 0); autoLockHygieneOpeningTimeout = strtol(file.readStringUntil('\n').c_str(), NULL, 0) == 1; timeRestrictions.readFromFile(file); file.close(); file = SPIFFS.open("/configuration.txt", "r"); Serial.printf("configuration.txt: \n\"%s\"\n", file.readString().c_str()); }); } protected: /** * @brief writes all configuration values to the SPIFFS */ void writeConfiguration() { // load everything from the SPIFFS UsedInterrupts::executeWithoutInterrupts([this]() { File file = SPIFFS.open("/configuration.txt", "w"); if (!file) { Serial.println("Loading configuration.txt failed"); return; } file.println(ssid); file.println(pwd); file.println(userId); file.println(apiKey); file.println(emergencyKey); file.println((disableFailedSession) ? "1" : "0"); file.println(timezone); file.println(timezoneName); file.println(backlightTimeOut); file.println((autoLockHygieneOpeningTimeout) ? "1" : "0"); timeRestrictions.writeToFile(file); }); } protected: /** * @brief Get a random character (A-Z, 0-9) */ static char getRandomChar() { int x = 36; while (x > 35) { // according to example of // https://en.cppreference.com/w/cpp/numeric/random/rand we need this to // have no bias.... x = std::rand() / ((RAND_MAX + 1u) / 35); } if (x < 26) { return (char)x + 'A'; } return (char)x - 26 + '0'; } }; } // namespace configuration
hugo3132/EmlaLockSafe
software/src/views/ViewStore.h
/** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include <ViewBase.h> #include <map> namespace views { /** * @brief Class managing which holds static references to all views which can be * accessed over the ViewId without including any views. This ensures that no * include loops are necessary. * * To activate a view use * views::ViewStore::activateView(views::ViewStore::HardwareTestView); */ class ViewStore { public: /** * @brief IDs of the different views */ enum ViewId { ConfigurationServerView, EmergencyEnterKeyView, EmergencyEnterMenuView, EmergencyMenu, EmlalockUnlockKeyMenu, HardwareTestView, HygieneOpeningMenu, LockedView, PreferencesMenu, SelectDisplayTimeLeft, SelectDisplayTimePassed, SetTimerView, TimeRestrictedView, UnlockedMainMenu, UnlockSafeView, WifiConnectingView, }; protected: /** * @brief Map linking the IDs */ std::map<ViewId, lcd::ViewBase*> views; protected: /** * @brief protected, use the static functions instead */ ViewStore() {}; protected: /** * @brief Get the Singleton object if the ViewStore */ static ViewStore& getSingleton() { static ViewStore instance; return instance; } public: /** * @brief Returns the pointer to the view registered by the given id * * @param id @ref ViewId of the view which should be returned * @return pointer to the requested view or nullptr if the view was not * registered (yet) */ static lcd::ViewBase* getView(const ViewId& id) { auto it = getSingleton().views.find(id); if (it == getSingleton().views.end()) { return nullptr; } return it->second; } public: /** * @brief registers a new view * * @param id @ref ViewId of the view which should be registered * @param view pointer to the view which should be accessible using the * @ref ViewId */ static void addView(const ViewId& id, lcd::ViewBase& view) { getSingleton().views[id] = &view; } public: /** * @brief activates the view described by the id * * @param id @ref ViewId of the view which should be activated * @return true if the view was known */ static bool activateView(const ViewId& id) { auto it = getSingleton().views.find(id); if (it == getSingleton().views.end()) { lcd::ViewBase::activateView(nullptr); return false; } lcd::ViewBase::activateView(it->second); return true; } }; } // namespace views
hugo3132/EmlaLockSafe
software/src/Tools.h
<filename>software/src/Tools.h /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "configuration/HardwareConfiguration.h" #include <ViewBase.h> #include <WiFi.h> /** * @brief class providing some static functions */ class Tools { public: /** * @brief tick routine updating the wifi signal strength icon * * @param display pointer to the display * @param forceRedraw if true the icon is redrawn */ static void tickWifiSymbol(LiquidCrystal_PCF8574* display, bool forceRedraw) { static uint8_t lastDrawnSymbol = 0; if (forceRedraw) { lastDrawnSymbol = 0; } // get signal strength long rssi = WiFi.RSSI(); if ((rssi < -80) || (rssi >= 0)) { if (lastDrawnSymbol != lcd::ViewBase::scWifiSignal0) { display->setCursor(19, 0); display->write(lcd::ViewBase::scWifiSignal0); lastDrawnSymbol = lcd::ViewBase::scWifiSignal0; } } else if (rssi < -70) { if (lastDrawnSymbol != lcd::ViewBase::scWifiSignal1) { display->setCursor(19, 0); display->write(lcd::ViewBase::scWifiSignal1); lastDrawnSymbol = lcd::ViewBase::scWifiSignal1; } } else if (rssi < -67) { if (lastDrawnSymbol != lcd::ViewBase::scWifiSignal2) { display->setCursor(19, 0); display->write(lcd::ViewBase::scWifiSignal2); lastDrawnSymbol = lcd::ViewBase::scWifiSignal2; } } else if (rssi < -30) { if (lastDrawnSymbol != lcd::ViewBase::scWifiSignal3) { display->setCursor(19, 0); display->write(lcd::ViewBase::scWifiSignal3); lastDrawnSymbol = lcd::ViewBase::scWifiSignal3; } } } public: /** * @brief Shows the animation while waiting until the callback returns false * * @param stillActive callback function checking if the animation should be * shown */ static void waitAnimation(LiquidCrystal_PCF8574* display, std::function<bool()> stillActive) { while (stillActive()) { for (int i = 0; (i < 20) && stillActive(); i++) { if (i == 0) { display->setCursor(19, 3); display->print(' '); display->setCursor(i, 3); display->print('*'); } else { display->setCursor(i - 1, 3); display->print(" *"); } delay(100); } } } };
hugo3132/EmlaLockSafe
software/src/UsedInterrupts.h
<gh_stars>1-10 /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "configuration/HardwareConfiguration.h" #include <Arduino.h> #include <functional> void ICACHE_RAM_ATTR encoderInterrupt(void); /** * @brief Class used to globally disable enable interrupts. * * The interrupts must e.g. disabled when accessing the SPI Filesystem */ class UsedInterrupts { private: /** * @brief true if at attach() was called at least once */ static bool interruptsAttached; public: /** * @brief attach the encoder pins to a interrupt */ static void attach() { if (!interruptsAttached) { attachInterrupt(digitalPinToInterrupt(ENCODER_PIN_CLK), encoderInterrupt, CHANGE); attachInterrupt(digitalPinToInterrupt(ENCODER_PIN_DT), encoderInterrupt, CHANGE); attachInterrupt(digitalPinToInterrupt(ENCODER_SWITCH), encoderInterrupt, CHANGE); interruptsAttached = true; } } public: /** * @brief detach the interrupts */ static void detach() { if (interruptsAttached) { detachInterrupt(digitalPinToInterrupt(ENCODER_PIN_CLK)); detachInterrupt(digitalPinToInterrupt(ENCODER_PIN_DT)); detachInterrupt(digitalPinToInterrupt(ENCODER_SWITCH)); interruptsAttached = false; } } public: /** * @brief Execute the passed function without interrupts * * @param f function / lambda which should be executed */ static void executeWithoutInterrupts(std::function<void(void)> f) { if (interruptsAttached) { detach(); try { f(); } catch (...) { attach(); throw; } attach(); } else { f(); } } };
hugo3132/EmlaLockSafe
software/src/views/LockedView.h
<gh_stars>1-10 /** * @author Hugo3132 * @copyright 2-clause BSD license */ #pragma once #include "../Tools.h" #include "../emlalock/EmlaLockApi.h" #include <RotaryEncoder.h> #include <ViewBase.h> namespace views { /** * @brief View used when the safe is locked. */ class LockedView : public lcd::ViewBase { protected: /** * @brief pointer to the encoder instance */ RotaryEncoder* encoder; protected: /** * @brief temperature strings if they are not provided by the emlalock API */ String temperatureStrings[6]; public: /** * @brief Construct the locked view * * @param display pointer to the LCD instance * @param encoder pointer to the encoder instance */ LockedView(LiquidCrystal_PCF8574* display, RotaryEncoder* encoder) : lcd::ViewBase(display, "LockedView") , encoder(encoder) { temperatureStrings[0] = "very cold"; temperatureStrings[1] = "cold"; temperatureStrings[2] = "warm"; temperatureStrings[3] = "very warm"; temperatureStrings[4] = "hot"; temperatureStrings[5] = "very hot"; } public: /** * @brief Copy constructor - not available */ LockedView(const LockedView& other) = delete; public: /** * @brief Move constructor */ LockedView(LockedView&& other) noexcept = delete; protected: /** * @brief called as soon as the view becomes active */ virtual void activate() { initializeSpecialCharacters(); tick(true); } public: /** * @brief called during the loop function * * @param forceRedraw if true everything should be redrawn */ virtual void tick(const bool& forceRedraw) { auto direction = encoder->getDirection(); auto click = encoder->getNewClick(); char buf[21]; tm tmBuf; if (click || (direction != RotaryEncoder::Direction::NOROTATION)) { if (!getBacklightTimeoutManager().delayTimeout()) { return; } } getBacklightTimeoutManager().tick(display); // click reloads the data from emlalock if (click) { emlalock::EmlaLockApi::getSingleton().triggerRefresh(); } // just to be sure... digitalWrite(COIL_PIN, SAFE_COIL_LOCKED); // Stuff which never changes if (forceRedraw) { display->clear(); display->setCursor(0, 0); display->print("Safe Locked"); display->setCursor(0, 1); display->print("Passed: ***:**:**:**"); display->setCursor(0, 2); display->print("Left: ***:**:**:**"); if (LockState::getDisplayTimeLeft() == LockState::DisplayTimeLeft::yes) { strftime(buf, 21, " %d.%m.%Y %T", localtime_r(&LockState::getEndDate(), &tmBuf)); display->setCursor(0, 3); display->print(buf); } } // current time static time_t lastDisplayedCurrentTime = 0; time_t currentTime = time(NULL); if (forceRedraw || (lastDisplayedCurrentTime / 60 != currentTime / 60)) { lastDisplayedCurrentTime = currentTime; strftime(buf, 6, "%R", localtime_r(&currentTime, &tmBuf)); display->setCursor(13, 0); display->print(buf); } // draw wifi signal strength Tools::tickWifiSymbol(display, forceRedraw); // should the passed time be displayed? if (LockState::getDisplayTimePassed() == LockState::DisplayTimePassed::yes) { static time_t lastDisplayedTime = 0; time_t timePassed = time(NULL) - LockState::getStartDate(); // redraw required if (forceRedraw || (lastDisplayedTime != timePassed)) { lastDisplayedTime = timePassed; int sec = timePassed % 60; timePassed = timePassed / 60; int min = timePassed % 60; timePassed = timePassed / 60; int hour = timePassed % 24; int day = std::min((int)timePassed / 24, 999); sprintf(buf, "Passed: %03d:%02d:%02d:%02d", day, hour, min, sec); display->setCursor(0, 1); display->print(buf); } } // should the time left be displayed? If yes, how switch (LockState::getDisplayTimeLeft()) { case LockState::DisplayTimeLeft::yes: { static time_t lastDisplayedTime = 0; time_t timeLeft = LockState::getEndDate() - time(NULL); // redraw required? if (forceRedraw || (lastDisplayedTime != timeLeft)) { lastDisplayedTime = timeLeft; int sec = timeLeft % 60; timeLeft = timeLeft / 60; int min = timeLeft % 60; timeLeft = timeLeft / 60; int hour = timeLeft % 24; int day = std::min((int)timeLeft / 24, 999); sprintf(buf, "Left: %03d:%02d:%02d:%02d", day, hour, min, sec); display->setCursor(0, 2); display->print(buf); } break; } case LockState::DisplayTimeLeft::temperature: { static String lastString = ""; String s = LockState::getTemperatureString(); // The string does not come from the Emlalock API. Just generate it if (s.isEmpty()) { int idx = std::min( (int)(((time(NULL) - LockState::getStartDate()) * 6) / (LockState::getEndDate() - LockState::getStartDate())), 5); s = temperatureStrings[idx]; } // redraw required? if (forceRedraw || (s != lastString)) { display->setCursor(0, 2); display->print("Left: "); display->setCursor(6, 2); display->print(s); lastString = s; } break; } default: break; } } }; } // namespace views
dra27/ocaml-jit
lib/jit_stubs.c
/* Copyright (c) 2021 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #define CAML_INTERNALS #include "caml/mlvalues.h" #include "caml/memory.h" #include "caml/stack.h" #include "caml/callback.h" #include "caml/alloc.h" #include "caml/osdeps.h" #include "caml/codefrag.h" #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/mman.h> #include <unistd.h> CAMLprim value jit_get_page_size(value unit) { CAMLparam1(unit); CAMLlocal1(result); result = Val_long(getpagesize()); CAMLreturn(result); } CAMLprim value jit_dlsym(value symbol) { CAMLparam1(symbol); CAMLlocal1(result); void *addr; addr = caml_globalsym(String_val(symbol)); if(!addr) { result = Val_int(0); } else { result = caml_alloc(1, 0); Store_field(result, 0, caml_copy_nativeint((intnat) addr)); } CAMLreturn (result); } CAMLprim value jit_memalign(value section_size) { CAMLparam1 (section_size); CAMLlocal1 (result); void *addr = NULL; long res, size; size = Long_val(section_size); res = posix_memalign(&addr, getpagesize(), size); if (res) { result = caml_alloc(1, 1); Store_field(result, 0, caml_copy_string(strerror(res))); } else { result = caml_alloc(1, 0); Store_field(result, 0, caml_copy_nativeint((intnat) addr)); }; CAMLreturn(result); } CAMLprim value jit_load_section(value addr, value section, value section_size) { CAMLparam3 (addr, section, section_size); int size = Int_val(section_size); const char *src = String_val(section); void *dest = (intnat*) Nativeint_val(addr); memcpy(dest, src, size); CAMLreturn(Val_unit); } CAMLprim value jit_mprotect_ro(value caml_addr, value caml_size) { CAMLparam2 (caml_addr, caml_size); CAMLlocal1 (result); void *addr; int size; size = Int_val(caml_size); addr = (intnat*) Nativeint_val(caml_addr); if (mprotect(addr, size, PROT_READ)) { result = caml_alloc(1, 1); Store_field(result, 0, Val_int(errno)); } else { result = caml_alloc(1, 0); Store_field(result, 0, Val_unit); }; CAMLreturn(result); } CAMLprim value jit_mprotect_rx(value caml_addr, value caml_size) { CAMLparam2 (caml_addr, caml_size); CAMLlocal1 (result); void *addr; int size; size = Int_val(caml_size); addr = (intnat*) Nativeint_val(caml_addr); if (mprotect(addr, size, PROT_READ | PROT_EXEC)) { result = caml_alloc(1, 1); Store_field(result, 0, Val_int(errno)); } else { result = caml_alloc(1, 0); Store_field(result, 0, Val_unit); }; CAMLreturn(result); } static void *addr_from_caml_option(value option) { void *sym = NULL; if (Is_block(option)) { sym = (intnat*) Nativeint_val(Field(option,0)); } return sym; } CAMLprim value jit_run(value symbols_addresses) { CAMLparam1 (symbols_addresses); CAMLlocal1 (result); void *sym,*sym2; void (*entrypoint)(void); //sym = optsym("__frametable"); sym = addr_from_caml_option(Field(symbols_addresses, 0)); if (NULL != sym) caml_register_frametable(sym); //sym = optsym("__gc_roots"); sym = addr_from_caml_option(Field(symbols_addresses, 1)); if (NULL != sym) caml_register_dyn_global(sym); //sym = optsym("__data_begin"); //sym2 = optsym("__data_end"); sym = addr_from_caml_option(Field(symbols_addresses, 2)); sym2 = addr_from_caml_option(Field(symbols_addresses, 3)); if (NULL != sym && NULL != sym2) caml_page_table_add(In_static_data, sym, sym2); //sym = optsym("__code_begin"); //sym2 = optsym("__code_end"); sym = addr_from_caml_option(Field(symbols_addresses, 4)); sym2 = addr_from_caml_option(Field(symbols_addresses, 5)); if (NULL != sym && NULL != sym2) { caml_page_table_add(In_code_area, sym, sym2); caml_register_code_fragment((char *) sym, (char *) sym2, DIGEST_LATER, NULL); } //entrypoint = optsym("__entry"); entrypoint = (void*) Nativeint_val(Field(symbols_addresses, 6)); result = caml_callback((value)(&entrypoint), 0); CAMLreturn (result); } CAMLprim value jit_run_toplevel(value symbols_addresses) { CAMLparam1 (symbols_addresses); CAMLlocal2 (res, v); res = caml_alloc(1,0); v = jit_run(symbols_addresses); Store_field(res, 0, v); CAMLreturn(res); } CAMLprim value jit_addr_to_obj(value address) { CAMLparam1 (address); CAMLlocal1 (obj); obj = (value) ((intnat*) Nativeint_val(address)); CAMLreturn(obj); }
DieracDelta/cbat_tools
wp/resources/sample_binaries/nested_ifs/main.c
<gh_stars>0 #include <assert.h> #include <stdlib.h> #define STRING_MAX 10 void gotoExample() { char *string1, *string2, *string3, *string4, *string5; if ( !(string1 = (char*) calloc(STRING_MAX, sizeof(char))) ) goto gotoExample_string1; if ( !(string2 = (char*) calloc(STRING_MAX, sizeof(char))) ) goto gotoExample_string2; if ( !(string3 = (char*) calloc(STRING_MAX, sizeof(char))) ) goto gotoExample_string3; if ( !(string4 = (char*) calloc(STRING_MAX, sizeof(char))) ) goto gotoExample_string4; if ( !(string5 = (char*) calloc(STRING_MAX, sizeof(char))) ) goto gotoExample_string5; //important code goes here assert(string1 && string2 && string3 && string4 && string5); gotoExample_string5: free(string5); gotoExample_string4: free(string4); gotoExample_string3: free(string3); gotoExample_string2: free(string2); gotoExample_string1: free(string1); } void nestedIfExample() { char *string1, *string2, *string3, *string4, *string5; if (string1 = (char*) calloc(STRING_MAX, sizeof(char))) { if (string2 = (char*) calloc(STRING_MAX, sizeof(char))) { if (string3 = (char*) calloc(STRING_MAX, sizeof(char))) { if (string4 = (char*) calloc(STRING_MAX, sizeof(char))) { if (string5 = (char*) calloc(STRING_MAX, sizeof(char))) { //important code here assert(string1 && string2 && string3 && string4 && string5); free(string5); } free(string4); } free(string3); } free(string2); } free(string1); } } int main(int argc, char* argv[]) { nestedIfExample(); gotoExample(); return 0; }
DieracDelta/cbat_tools
wp/resources/sample_binaries/equiv_null_check/main_2.c
<reponame>DieracDelta/cbat_tools<gh_stars>0 #include<stdlib.h> #include<assert.h> int main(void) { char * p = malloc(10); if( p == NULL ) assert(0); * (p + 3) = 0; return * (p + 3); }
krevony/wordcount
wordcount.c
#include <stdio.h> int main(int argc, const char * srgv[]) { char c = '\0'; char firstletter; int wordnum; int word_in; while(1) { wordnum = 0; word_in = 1; firstletter = '\0'; printf("문자열을 입력하세요: "); while(1) { c = getchar(); if(c == '\n') { if(word_in) wordnum++; break; } firstletter = c; if(c == ' ' || c == '.') { if(word_in) { wordnum++ word_in = 0; } } else word_in = 1; } if(firstletter == '\0') break; printf("단어수: %d\n", wordnum); } return 0; }
pedromig/COMP-Project
tests/meta3/input/duplicateParamNames.c
double f1(short a, double b, int b); double f2(short a, double b, int b); double f2(short a, double b, int b){} double f3(short a, double b, int b){} double f4(short a, double b, int b){} double f3(short a, double b){}
pedromig/COMP-Project
tests/meta4/input/logical_funcs.c
<reponame>pedromig/COMP-Project char nand(char x, char y){ return !(x && y); } char nor(char x, char y){ return !(x || y); } int main(void){ putchar(nand(0, 0) + 'A'); putchar(nor(0, 0) + 'A'); return 0; }
pedromig/COMP-Project
tests/meta4/input/fibonacci.c
<filename>tests/meta4/input/fibonacci.c<gh_stars>1-10 int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } int fibonacci_seq(int n) { int n1 = 0, n2 = 1, n3 = 0; int i = 2; while (i < n) { n3 = n1 + n2; putchar(' '); putchar(n3); n1 = n2; n2 = n3; i = i + 1; } return 0; } int main(void) { int a = 20; putchar(fibonacci_seq(a)); putchar('\n'); putchar(fibonacci_seq(a)); return 0; }
pedromig/COMP-Project
tests/meta3/input/globalVarTest.c
int a = 2; int a(int v1); int main(void){ a=3; } int f1(void){ a=3; int a; a=4; }
pedromig/COMP-Project
src/structures.h
<gh_stars>1-10 /** * Licenciatura em Engenharia Informática | Faculdade de Ciências e Tecnologia da Universidade de Coimbra * Projeto de Compiladores 2020/2021 * * 2018288117 <NAME> * 2018283166 <NAME> * */ #ifndef __STRUCTURES_H #define __STRUCTURES_H #include <stdbool.h> typedef const char *type_t; typedef struct Parameter param_t; struct Parameter { type_t type; param_t *next; }; typedef struct Annotation annotation_t; struct Annotation { type_t type; param_t *parameters; }; typedef struct Token { char *value; int line; int column; } token_t; typedef struct ASTNode ast_node_t; struct ASTNode { const char *id; token_t token; annotation_t annotation; ast_node_t *first_child; ast_node_t *next_sibling; }; typedef struct Symbol sym_t; struct Symbol { const char *id; int llvm_var; bool is_param; bool is_defined; type_t type; param_t *parameters; sym_t *next; }; typedef struct SymbolTable symtab_t; struct SymbolTable { const char *id; bool is_defined; sym_t *symlist; symtab_t *next; }; #endif // __STRUCTURES_H
pedromig/COMP-Project
tests/meta3/input/mooshak1.c
int a, A1, A5, A4; char blah(int r); char c1; char localvars( int A0, char A1, short A2, double A3, int A4, char C0) { char c0, c1, c2, c3, c4; int a0, a1, a2, a3, a4; double b1, b2, b3, b4; int blah, localvars; } char C1, C2, C3, C4; char localvars( int A0, char A1, short A2, double A3, int A4, char C0); char blah(int q) { int blah, localvars, f; char p, b; int i, j, k; short v; } char C1, C2, C3, C4; int zf23(int x); void f(void) { char c0, c1, c2, c3, c4; int a0, a1, a2, a3, a4; double b1, b2, b3, b4; short d1, d2, d3, d4; }
pedromig/COMP-Project
tests/meta4/input/nested_whiles.c
<gh_stars>1-10 void print_number(int n) { int u = 1; while (n / u) u = u * 10; while (u > 1) { putchar('0' + n / (u / 10) - n / u * 10); u = u / 10; } } int sum_range_inverse(int min, int max) { int sum = 0; int i = max; while (i >= min) { while (i >= min) { while (i >= min) { sum = sum + i; i = i - 1; } while (i >= min) { sum = sum + i; i = i - 1; } sum = sum + i; i = i - 1; } sum = sum + i; i = i - 1; } return sum; } int sum_range(int min, int max) { int sum = 0; int i = min; while (i < max) { sum = sum + i; i = i + 1; } return sum; } int sum_range2(int min, int max) { int sum = 0; int i = min; while (i < max) { sum = sum + i; i = i + 1; } return sum; } int sum_range3(int min, int max) { int sum = 0; int i = min; while (i < max) { sum = sum + i; i = i + 1; } return sum; } int sum_range4(int min, int max) { int sum = 0; int i = min; while (i < max) { sum = sum + i; i = i + 1; } return sum; } int sum_range5(int min, int max) { int sum = 0; int i = min; while (i < max) { sum = sum + i; i = i + 1; } return sum_range_inverse(max, sum); } int main(void) { int min = 100, max = 105; int i = min; while (i < max) { print_number(sum_range(min, i + 1)); print_number(sum_range2(min, i + 1)); print_number(sum_range3(min, i + 1)); print_number(sum_range4(min, i + 1)); print_number(sum_range5(min, i + 1)); print_number(sum_range_inverse(min, i + 1)); putchar('\n'); i = i + 1; } int a = 2; putchar('A' + (a && a && a)); putchar('A'); 0 && putchar('F'); return 0; return 0; }
pedromig/COMP-Project
tests/meta3/input/alreadyDefinedTest.c
double f1(double a){} int f1(int a, int p){} int f1(void, void){}
pedromig/COMP-Project
tests/meta4/input/hello.c
int main(void) { char a = 'H'; char b = 'e'; putchar(a); putchar(b); putchar('l'); putchar('l'); putchar('o'); char c = ' '; char d = 'W'; putchar(c); putchar(d); char e = 'o'; putchar(e); putchar('r'); putchar('l'); putchar('d'); char f = '\n'; putchar(f); }
pedromig/COMP-Project
tests/meta4/input/returns.c
char aa(char a) { return a; } short bb(short b) { return b; } int cc(int c) { return c; } double dd(double d) { return d; } int ee(char a) { return aa(a); } int ff(short a) { return bb(a); } char gg(int a) { return cc(a); } short hh(char a) { return aa(a); } double ii(double x) { return dd(x); } double jj(char a) { return aa(a); } double kk(int a) { return cc(a); } void ll(int a) { return; } int main(void) { return 0; }
pedromig/COMP-Project
tests/meta3/input/duplicateParamWithVoid.c
<reponame>pedromig/COMP-Project<filename>tests/meta3/input/duplicateParamWithVoid.c int func1(short a, double b, void b); int func2(short a, void b, void b); double f7(short a, double b, int b);
pedromig/COMP-Project
src/ast.c
/** * Licenciatura em Engenharia Informática | Faculdade de Ciências e Tecnologia da Universidade de Coimbra * Projeto de Compiladores 2020/2021 * * 2018288117 <NAME> * 2018283166 <NAME> * */ #include "ast.h" #include "y.tab.h" extern bool syntax_error; int alloc_types[] = { ID, INTLIT, REALLIT, CHRLIT, }; token_t token(char *value, int line, int column, int type) { token_t token = {.value = NULL, .line = line, .column = column}; for (int i = 0; i < (sizeof(alloc_types) / sizeof(alloc_types[0])); ++i) { if (type == alloc_types[i]) { token.value = (char *)strdup(value); } } return token; } ast_node_t *ast_node(const char *id, token_t token) { ast_node_t *node = (ast_node_t *)malloc(sizeof(ast_node_t)); assert(node != NULL); node->id = id; node->token = token; node->annotation.type = NULL; node->annotation.parameters = NULL; node->first_child = NULL; node->next_sibling = NULL; return node; } void add_children(ast_node_t *parent, int argc, ...) { va_list args; ast_node_t *child = NULL; va_start(args, argc); assert(parent != NULL); child = va_arg(args, ast_node_t *); parent->first_child = child; ast_node_t *current = parent->first_child; for (int i = 0; i < argc - 1; ++i) { child = va_arg(args, ast_node_t *); for (ast_node_t *c = child; c; c = c->next_sibling) { current->next_sibling = c; current = current->next_sibling; } } va_end(args); } void add_siblings(ast_node_t *node, int argc, ...) { va_list args; va_start(args, argc); ast_node_t *sibling; assert(node != NULL); ast_node_t *current = node; while (current->next_sibling != NULL) { current = current->next_sibling; } for (int i = 0; i < argc; ++i) { sibling = va_arg(args, ast_node_t *); if (!sibling) continue; current->next_sibling = sibling; current = current->next_sibling; } va_end(args); } void free_ast(ast_node_t *node) { if (node) { if (node->token.value) { free(node->token.value); } free_ast(node->first_child); free_ast(node->next_sibling); free(node); } } void print_node(const char *id, token_t token, annotation_t annotation, int indent_level) { for (int i = 0; i < indent_level; ++i) printf(".."); printf("%s", id); if (token.value) printf("(%s)", token.value); if (annotation.type) { printf(" - %s", annotation.type); if (annotation.parameters) { print_parameter_list(annotation.parameters); } } printf("\n"); } void __print_ast(ast_node_t *node, int indent_level) { print_node(node->id, node->token, node->annotation, indent_level); if (node->first_child != NULL) __print_ast(node->first_child, indent_level + 1); if (node->next_sibling != NULL) __print_ast(node->next_sibling, indent_level); } void print_ast(ast_node_t *program) { if (!syntax_error) __print_ast(program, 0); } void add_typespec(ast_node_t *type, ast_node_t *give_me_type) { ast_node_t *new_type_node = NULL; for (ast_node_t *current = give_me_type; current; current = current->next_sibling) { new_type_node = ast_node(type->id, NULL_TOKEN); new_type_node->next_sibling = current->first_child; current->first_child = new_type_node; } } ast_node_t *statement_list(ast_node_t *stat_list) { ast_node_t *list = stat_list; if (list && list->next_sibling) { list = ast_node("StatList", NULL_TOKEN); list->first_child = stat_list; } return list; } ast_node_t *null_check(ast_node_t *node) { return node ? node : ast_node("Null", NULL_TOKEN); }
pedromig/COMP-Project
tests/meta4/input/factorials.c
int factorial(int number) { int answer = 1; while (number != 0) { answer = answer * number; number = number - 1; } return answer; } int recursive_factorial(int number) { if (number == 0) { return 1; } return number * recursive_factorial(number - 1); } int tail_recursive_factorial(int number, int k) { if (number == 0) { return 1; } return tail_recursive_factorial(number - 1, k * number); } void i_have_no_life_xD(void) { putchar('#'); putchar('#'); putchar('\t'); putchar('F'); putchar('A'); putchar('C'); putchar('T'); putchar('O'); putchar('R'); putchar('I'); putchar('A'); putchar('L'); putchar('S'); putchar('\t'); putchar('#'); putchar('#'); putchar('\n'); } int main(void) { i_have_no_life_xD(); int i = 5; putchar(recursive_factorial(i)); putchar('\n'); putchar(tail_recursive_factorial(i, 1)); putchar('\n'); putchar(factorial(i)); return 0; }
pedromig/COMP-Project
tests/meta4/input/functions.c
<reponame>pedromig/COMP-Project int getint(void) { int read = 0, sign = 1; char c = '4'; if (c == '-') sign = -1; while (c != '\n') { if (c != '-') read = read * 10 + c - '0'; c = '\n'; } return sign * read; } void putint(int n) { if (n < 0) { putchar('-'); n = -n; } if (n / 10) { putint(n / 10); } putchar(n % 10 + '0'); } int main(void) { int i = 1; while (i != 0) { i = getint(); putint(i); putchar('\n'); i = 0; } }
pedromig/COMP-Project
tests/meta4/input/simple_if.c
int main(void) { int a = 1; if(1); if (a) { putchar('a'); } if (1) { if (0) { putchar('a'); } else { if (2 < 0) { putchar('b'); } putchar('b'); } } if (1 + 2) { putchar('a'); } if (0) { putchar('a'); } else { putchar('b'); } }
pedromig/COMP-Project
tests/meta4/input/primes.c
<reponame>pedromig/COMP-Project<gh_stars>1-10 void primes(int low, int high) { int i, flag, stop; while (low < high) { flag = 0; if (low <= 1) { low = low + 1; } else { i = 2; stop = 0; while (i <= low / 2 && !stop) { if (low % i == 0) { flag = 1; stop = 1; } i = i + 1; } if (flag == 0) { putchar('0' + low); } low = low + 1; } } return; } int main(void) { primes(1, 50); -5.5; }
pedromig/COMP-Project
tests/meta4/input/essential.c
<filename>tests/meta4/input/essential.c char global_char = '\000'; char global_char1 = '\1'; char global_char2 = '\4'; char global_char3 = '\44'; char global_char4 = '\24'; char global_a = 'A'; short global_b = 'B'; int global_c = 'C'; double global_d = 4.0; int main(void) { // Printing, variable declaration, assignment, unary minus. char a = 'D'; short b = 'E'; int c = 'F'; double d = 4.0; int temp; temp = -(-2147483648); temp = -2147483648; // A temp = a; a = global_a; putchar(-(-(-(-a)))); a = temp; // B temp = b; b = global_b; putchar(b); b = temp; // C temp = c; c = global_c; putchar(-(-c)); c = temp; // D E F putchar(a); putchar(b); putchar(c); // D B B D a = a; b = -'B'; c = -a; putchar(a); putchar(-b); putchar(-(-(-(-(-(-'B')))))); putchar(-(-(-(-'B')))); // putchar(-(-(-(-'B')))); putchar(-(-(-(-(-(-(-c))))))); putchar('\n'); return -(-(-c)); }
pedromig/COMP-Project
src/utils.c
#include "utils.h" #define MAX(A, B) (A > B) ? (A) : (B) // Low(char) -> High(double) static const char *types[] = { "char", "short", "int", "double", }; // Arithmetic Operators static const char *arithmetic[] = { "Add", "Sub", "Mul", "Div", "Mod", }; // Unary Operators static const char *unary[] = { "Plus", "Minus", "Not", }; // Relational Operators static const char *relational[] = { "Le", "Ge", "Lt", "Gt", "Eq", "Ne", }; // Bitwise Operators static const char *bitwise[] = { "BitWiseAnd", "BitWiseOr", "BitWiseXor", }; // Logical Operators static const char *logical[] = { "And", "Or", }; // Statement Identifiers static const char *statement_ids[] = { "If", "While", }; bool has_parameters_omitted(ast_node_t *parameter_list) { for (ast_node_t *aux = parameter_list->first_child; aux; aux = aux->next_sibling) { if (strcmp(aux->first_child->id, "Void") && !aux->first_child->next_sibling) { parameter_name_omitted(aux->first_child->token.line, aux->first_child->token.column); return true; } } return false; } bool invalid_assign(type_t lhs, type_t rhs) { int l = -1, r = -1; if (!strcmp(rhs, "void") || !strcmp(rhs, "undef")) return true; for (int i = 0; i < sizeof(types) / sizeof(types[0]); ++i) { if (!strcmp(lhs, types[i])) l = i; if (!strcmp(rhs, types[i])) r = i; } if ((!l && (r == 1 || r == 2)) || (l == 1 && r == 2)) return false; return l < r; } const char *implicit_conversion(type_t left_operand, type_t right_operand) { int lop = -1, rop = -1; for (int i = 0; i < sizeof(types) / sizeof(types[0]); ++i) { if (!strcmp(left_operand, types[i])) lop = i; if (!strcmp(right_operand, types[i])) rop = i; } return types[MAX(lop, rop)]; } bool find_operator(const char **array, int n, const char *operator) { for (int i = 0; i < n; ++i) { if (!strcmp(array[i], operator)) { return true; } } return false; } inline bool is_unary_operator(const char *operator) { return find_operator(unary, sizeof(unary) / sizeof(unary[0]), operator); } inline bool is_arithmetic_operator(const char *operator) { return find_operator(arithmetic, sizeof(arithmetic) / sizeof(arithmetic[0]), operator); } inline bool is_relational_operator(const char *operator) { return find_operator(relational, sizeof(relational) / sizeof(relational[0]), operator); } inline bool is_bitwise_operator(const char *operator) { return find_operator(bitwise, sizeof(bitwise) / sizeof(bitwise[0]), operator); } inline bool is_logical_operator(const char *operator) { return find_operator(logical, sizeof(logical) / sizeof(logical[0]), operator); } inline bool is_statement_id(const char *operator) { return find_operator(statement_ids, sizeof(statement_ids) / sizeof(statement_ids[0]), operator); } const char * decapitalize(const char *string) { if (!strcmp(string, "Int")) return "int"; else if (!strcmp(string, "Double")) return "double"; else if (!strcmp(string, "Char")) return "char"; else if (!strcmp(string, "Void")) return "void"; else if (!strcmp(string, "Short")) return "short"; return "unkown"; } const char *select_operator(const char *string) { if (!strcmp(string, "Store")) return "="; else if (!strcmp(string, "Comma")) return ","; else if (!strcmp(string, "Add") || !strcmp(string, "Plus")) return "+"; else if (!strcmp(string, "Sub") || !strcmp(string, "Minus")) return "-"; else if (!strcmp(string, "Mul")) return "*"; else if (!strcmp(string, "Div")) return "/"; else if (!strcmp(string, "Mod")) return "%"; else if (!strcmp(string, "Or")) return "||"; else if (!strcmp(string, "And")) return "&&"; else if (!strcmp(string, "BitWiseAnd")) return "&"; else if (!strcmp(string, "BitWiseOr")) return "|"; else if (!strcmp(string, "BitWiseXor")) return "^"; else if (!strcmp(string, "Eq")) return "=="; else if (!strcmp(string, "Ne")) return "!="; else if (!strcmp(string, "Le")) return "<="; else if (!strcmp(string, "Ge")) return ">="; else if (!strcmp(string, "Lt")) return "<"; else if (!strcmp(string, "Gt")) return ">"; else if (!strcmp(string, "Not")) return "!"; return "unknown"; } // * LLVM Util Functions // Return Ascii value for a one-character const char * int ord(const char *str) { int ans = str[1]; if (str[1] == '\\') { switch (str[2]) { case 'n': ans = 0x0a; break; case 't': ans = 0x09; break; case '\\': ans = 0x5c; break; case '\'': ans = 0x27; break; case '"': ans = 0x22; break; default: ans = 0; for (int i = 4, octal = 1; i >= 2; --i) { if (isdigit(str[i])) { ans += ((str[i] - '0') * octal); octal *= 8; } } break; } } return ans; } int intlit_to_int(const char *str) { int ans; if (str[0] == '0') { sscanf(str, "%o", &ans); } else { ans = strtol(str, NULL, 10); } return ans; } const char *type_to_llvm(const char *type) { return (!strcmp(type, "Double") || !strcmp(type, "double")) ? "double" : (!strcmp(type, "Void")) ? "void" : "i32"; } int insert_default_return(const char *llvm_type, bool has_return_keyword) { if (!has_return_keyword) { return !strcmp(llvm_type, "double") ? printf("\tret %s %e\n", llvm_type, 0.0f) : !strcmp(llvm_type, "void") ? printf("\tret void\n") : printf("\tret %s %d\n", llvm_type, 0); } return 0; }