repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
BryceStandley/TNAH
core/src/TNAH/Events/KeyEvent.h
<reponame>BryceStandley/TNAH<gh_stars>1-10 #pragma once #include <sstream> #include "TNAH/Events/Event.h" #include "TNAH/Core/KeyCodes.h" namespace tnah { /** * @class KeyEvent * * @brief A key event class that inherits from the base class event * * @author <NAME> * @date 10/09/2021 */ class KeyEvent : public Event { public: /** * @fn KeyCode KeyEvent::GetKeyCode() const * * @brief Gets key code * * @author <NAME> * @date 10/09/2021 * * @returns The key code. */ KeyCode GetKeyCode() const { return m_KeyCode; } EVENT_CLASS_CATEGORY(EventCategoryKeyboard | EventCategoryInput) protected: /** * @fn tnah::KeyEvent::KeyEvent(const KeyCode keycode) * * @brief Constructor * * @author <NAME> * @date 10/09/2021 * * @param keycode The keycode. */ KeyEvent(const KeyCode keycode) : m_KeyCode(keycode) {} KeyCode m_KeyCode; }; /** * @class KeyPressedEvent * * @brief A key pressed event class that inherits from KeyEvent class * * @author <NAME> * @date 10/09/2021 */ class KeyPressedEvent : public KeyEvent { public: /** * @fn KeyPressedEvent::KeyPressedEvent(const KeyCode keycode, const uint16_t repeatCount) * * @brief Constructor * * @author <NAME> * @date 10/09/2021 * * @param keycode The keycode. * @param repeatCount Number of repeats. */ KeyPressedEvent(const KeyCode keycode, const uint16_t repeatCount) : KeyEvent(keycode), m_RepeatCount(repeatCount) {} /** * @fn uint16_t KeyPressedEvent::GetRepeatCount() const * * @brief Gets repeat count * * @author <NAME> * @date 10/09/2021 * * @returns The repeat count. */ uint16_t GetRepeatCount() const { return m_RepeatCount; } /** * @fn std::string KeyPressedEvent::ToString() const override * * @brief Convert the keycode and repeat count into a string format * * @author <NAME> * @date 10/09/2021 * * @returns A std::string that represents this object. */ std::string ToString() const override { std::stringstream ss; ss << "KeyPressedEvent: " << m_KeyCode << " (" << m_RepeatCount << " repeats)"; return ss.str(); } EVENT_CLASS_TYPE(KeyPressed) private: /** @brief Number of repeats */ uint16_t m_RepeatCount; }; /** * @class KeyReleasedEvent * * @brief A key released event that inherits from the KeyEvent class * * @author <NAME> * @date 10/09/2021 */ class KeyReleasedEvent : public KeyEvent { public: /** * @fn KeyReleasedEvent::KeyReleasedEvent(const KeyCode keycode) * * @brief Constructor * * @author <NAME> * @date 10/09/2021 * * @param keycode The keycode. */ KeyReleasedEvent(const KeyCode keycode) : KeyEvent(keycode) {} /** * @fn std::string KeyReleasedEvent::ToString() const override * * @brief Convert the keyCode of the KeyReleasedEvent to a string format * * @author <NAME> * @date 10/09/2021 * * @returns A std::string that represents this object. */ std::string ToString() const override { std::stringstream ss; ss << "KeyReleasedEvent: " << m_KeyCode; return ss.str(); } EVENT_CLASS_TYPE(KeyReleased) }; /** * @class KeyTypedEvent * * @brief A key typed event that inherits from the KeyEvent class * * @author <NAME> * @date 10/09/2021 */ class KeyTypedEvent : public KeyEvent { public: /** * @fn KeyTypedEvent::KeyTypedEvent(const KeyCode keycode) * * @brief Constructor * * @author <NAME> * @date 10/09/2021 * * @param keycode The keycode. */ KeyTypedEvent(const KeyCode keycode) : KeyEvent(keycode) {} /** * @fn std::string KeyTypedEvent::ToString() const override * * @brief Convert this keycode into into a string representation * * @author <NAME> * @date 10/09/2021 * * @returns A std::string that represents this object. */ std::string ToString() const override { std::stringstream ss; ss << "KeyTypedEvent: " << m_KeyCode; return ss.str(); } EVENT_CLASS_TYPE(KeyTyped) }; }
BryceStandley/TNAH
core/src/TNAH/Core/FileManager.h
<gh_stars>1-10 #pragma once #include <string> namespace tnah { /** * @enum FileError * * @brief Values that represent file errors */ enum class FileError { None, UserClosed, PathInvalid }; /** * @struct ActiveFile * * @brief An active file. * * @author <NAME> * @date 7/09/2021 */ struct ActiveFile { /** @brief Filename of the file */ std::string FileName; /** @brief Full pathname of the file */ std::string FilePath; /** @brief True if file is valid, false if not */ bool IsValid = false; /** @brief The file open error */ FileError FileOpenError; /** * @fn ActiveFile() :FileName(""), FilePath(""), FileOpenError(FileError::None) * * @brief Default constructor * * @author <NAME> * @date 7/09/2021 */ ActiveFile() :FileName(""), FilePath(""), FileOpenError(FileError::None) {} }; /** * @class FileManager * * @brief Manager for files. * * @author <NAME> * @date 7/09/2021 */ class FileManager { public: /** * @fn static bool FileManager::NewScene(); * * @brief Creates a new scene * * @author <NAME> * @date 7/09/2021 * * @returns True if it succeeds, false if it fails. */ static bool NewScene(); /** * @fn static bool FileManager::OpenScene(); * * @brief Opens the scene * * @author <NAME> * @date 7/09/2021 * * @returns True if it succeeds, false if it fails. */ static bool OpenScene(); /** * @fn static bool FileManager::OpenAudio(); * * @brief Opens the audio * * @author <NAME> * @date 7/09/2021 * * @returns True if it succeeds, false if it fails. */ static bool OpenAudio(); /** * @fn static bool FileManager::OpenMesh(); * * @brief Opens the mesh * * @author <NAME> * @date 7/09/2021 * * @returns True if it succeeds, false if it fails. */ static bool OpenMesh(); /** * @fn static bool FileManager::SaveScene(); * * @brief Saves the scene * * @author <NAME> * @date 7/09/2021 * * @returns True if it succeeds, false if it fails. */ static bool SaveScene(); /** * @fn static bool FileManager::SaveSceneAs(); * * @brief Saves the scene as * * @author <NAME> * @date 7/09/2021 * * @returns True if it succeeds, false if it fails. */ static bool SaveSceneAs(); /** * @fn static ActiveFile* FileManager::GetActiveFile(); * * @brief Gets active file * * @author <NAME> * @date 7/09/2021 * * @returns Null if it fails, else the active file. */ static ActiveFile* GetActiveFile(); private: /** * @fn static bool FileManager::CheckValidFile(const std::string& filePath); * * @brief Check valid file * * @author <NAME> * @date 7/09/2021 * * @param filePath Full pathname of the file. * * @returns True if it succeeds, false if it fails. */ static bool CheckValidFile(const std::string& filePath); private: /** @brief The active file */ static ActiveFile* s_ActiveFile; }; }
BryceStandley/TNAH
core/src/TNAH/Scene/Components/TerrainComponent.h
<reponame>BryceStandley/TNAH<gh_stars>1-10 #pragma once #include "TNAH/Core/Core.h" #include <glm/glm.hpp> #include "ComponentIdentification.h" #include "Platform/OpenGL/OpenGLVertexArray.h" #include "Platform/OpenGL/OpenGLBuffer.h" #include "Platform/OpenGL/OpenGLShader.h" #include "Platform/OpenGL/OpenGLTexture.h" #include "TNAH/Renderer/Material.h" namespace tnah { class Terrain { public: /**********************************************************************************************//** * @fn Terrain::Terrain() = default; * * @brief Defaulted constructor, will construct a 100 square terrain with a min of 40 and a max of * 100 units. * * @author <NAME> * @date 23/07/2021 **************************************************************************************************/ Terrain(); /**********************************************************************************************//** * @fn Terrain::Terrain(const int width, const int maxHeight, const int minHeight); * * @brief Constructor * * @author <NAME> * @date 10/09/2021 * * @param width The width. * @param maxHeight The maximum height. * @param minHeight The minimum height. **************************************************************************************************/ Terrain(const int width, const int maxHeight, const int minHeight); /**********************************************************************************************//** * @fn Terrain::Terrain(const std::string& heightmapFilePath); * * @brief Constructor * * @author <NAME> * @date 10/09/2021 * * @param heightmapFilePath Full pathname of the heightmap file. **************************************************************************************************/ Terrain(const std::string& heightmapFilePath); /**********************************************************************************************//** * @fn Terrain::~Terrain(); * * @brief Destructor * * @author <NAME> * @date 10/09/2021 **************************************************************************************************/ ~Terrain(); /**********************************************************************************************//** * @fn inline const glm::vec3 Terrain::GetMaxHeight() * * @brief Gets maximum height * * @author <NAME> * @date 10/09/2021 * * @returns The maximum height. **************************************************************************************************/ inline const glm::vec3 GetMaxHeight() { return m_HighestPoint; } /**********************************************************************************************//** * @fn inline const glm::vec3 Terrain::GetMinHeight() * * @brief Gets minimum height * * @author <NAME> * @date 10/09/2021 * * @returns The minimum height. **************************************************************************************************/ inline const glm::vec3 GetMinHeight() { return m_LowestPoint; } /**********************************************************************************************//** * @fn inline const std::vector<glm::vec3> Terrain::GetVertexPositions() * * @brief Gets vertex positions * * @author <NAME> * @date 10/09/2021 * * @returns The vertex positions. **************************************************************************************************/ inline const std::vector<glm::vec3> GetVertexPositions() { return m_TerrainInfo.position; } /**********************************************************************************************//** * @fn inline float* Terrain::GetTotalData() * * @brief Gets total data * * @author <NAME> * @date 10/09/2021 * * @returns Null if it fails, else the total data. **************************************************************************************************/ inline float* GetTotalData() { return &m_VBOData[0].x; } /**********************************************************************************************//** * @fn inline uint32_t* Terrain::GetIndicesData() * * @brief Gets indices data * * @author <NAME> * @date 10/09/2021 * * @returns Null if it fails, else the indices data. **************************************************************************************************/ inline uint32_t* GetIndicesData() { return &m_IndicesData[0]; } /**********************************************************************************************//** * @fn inline const glm::vec2 Terrain::GetSize() * * @brief Gets the size * * @author <NAME> * @date 10/09/2021 * * @returns The size. **************************************************************************************************/ inline const glm::vec2 GetSize() { return m_Size; } /**********************************************************************************************//** * @fn inline const float Terrain::GetHeight(int x, int z); * * @brief Gets a height * * @author <NAME> * @date 10/09/2021 * * @param x The x coordinate. * @param z The z coordinate. * * @returns The height. **************************************************************************************************/ inline const float GetHeight(int x, int z); /**********************************************************************************************//** * @fn inline const float Terrain::GetHeightColor(int x, int z); * * @brief Gets height color * * @author <NAME> * @date 10/09/2021 * * @param x The x coordinate. * @param z The z coordinate. * * @returns The height color. **************************************************************************************************/ inline const float GetHeightColor(int x, int z); /**********************************************************************************************//** * @fn inline const float Terrain::GetVertexHeight(int x, int z); * * @brief Gets vertex height * * @author <NAME> * @date 10/09/2021 * * @param x The x coordinate. * @param z The z coordinate. * * @returns The vertex height. **************************************************************************************************/ inline const float GetVertexHeight(int x, int z); /**********************************************************************************************//** * @fn inline const uint32_t Terrain::GetTotalDataSize() * * @brief Gets total data size * * @author <NAME> * @date 10/09/2021 * * @returns The total data size. **************************************************************************************************/ inline const uint32_t GetTotalDataSize() { return m_VBOSize; } /**********************************************************************************************//** * @fn inline const uint32_t Terrain::GetIndicesSize() * * @brief Gets indices size * * @author <NAME> * @date 10/09/2021 * * @returns The indices size. **************************************************************************************************/ inline const uint32_t GetIndicesSize() { return m_IBOSize; } /**********************************************************************************************//** * @fn inline const BufferLayout Terrain::GetBufferLayout() * * @brief Gets buffer layout * * @author <NAME> * @date 10/09/2021 * * @returns The buffer layout. **************************************************************************************************/ inline const VertexBufferLayout GetBufferLayout() { return m_BufferLayout; } /**********************************************************************************************//** * @fn inline Ref<VertexArray> Terrain::GetVertexArray() * * @brief Gets vertex array * * @author <NAME> * @date 10/09/2021 * * @returns The vertex array. **************************************************************************************************/ inline Ref<VertexArray> GetVertexArray() { return m_VAO; } /**********************************************************************************************//** * @fn inline Ref<VertexBuffer> Terrain::GetVertexBuffer() * * @brief Gets vertex buffer * * @author <NAME> * @date 10/09/2021 * * @returns The vertex buffer. **************************************************************************************************/ inline Ref<VertexBuffer> GetVertexBuffer() { return m_VBO; } /**********************************************************************************************//** * @fn inline Ref<IndexBuffer> Terrain::GetIndexBuffer() * * @brief Gets index buffer * * @author <NAME> * @date 10/09/2021 * * @returns The index buffer. **************************************************************************************************/ inline Ref<IndexBuffer> GetIndexBuffer() { return m_IBO; } /**********************************************************************************************//** * @fn inline Ref<Material> Terrain::GetMaterial() * * @brief Gets the material * * @author <NAME> * @date 10/09/2021 * * @returns The material. **************************************************************************************************/ inline Ref<Material> GetMaterial() { return m_Material; } private: /**********************************************************************************************//** * @struct TerrainInformation * * @brief Information used to construct the terrain with textures and colours * * @author <NAME> * @date 23/07/2021 **************************************************************************************************/ struct TerrainInformation { /** @brief The position */ std::vector<glm::vec3> position; /** @brief The color */ std::vector<glm::vec3> color; /** @brief The texture */ std::vector<glm::vec3> texture; /** @brief The normal */ std::vector<glm::vec3> normal; }; /**********************************************************************************************//** * @fn void Terrain::Create(); * * @brief Creates this object * * @author <NAME> * @date 10/09/2021 **************************************************************************************************/ void Create(); /**********************************************************************************************//** * @fn void Terrain::GenerateHeightmap(const int width, const int maxHeight, const int minHeight); * * @brief Generates a heightmap * * @author <NAME> * @date 10/09/2021 * * @param width The width. * @param maxHeight The maximum height. * @param minHeight The minimum height. **************************************************************************************************/ void GenerateHeightmap(const int width, const int maxHeight, const int minHeight); /**********************************************************************************************//** * @fn bool Terrain::LoadHeightField(const std::string& fileName); * * @brief Loads height field * * @author <NAME> * @date 10/09/2021 * * @param fileName Filename of the file. * * @returns True if it succeeds, false if it fails. **************************************************************************************************/ bool LoadHeightField(const std::string& fileName); /**********************************************************************************************//** * @fn bool Terrain::InBounds(int x, int z); * * @brief In bounds * * @author <NAME> * @date 10/09/2021 * * @param x The x coordinate. * @param z The z coordinate. * * @returns True if it succeeds, false if it fails. **************************************************************************************************/ bool InBounds(int x, int z); /**********************************************************************************************//** * @fn void Terrain::SetVertexHeight(int x, int z, const float newHeight); * * @brief Sets vertex height * * @author <NAME> * @date 10/09/2021 * * @param x The x coordinate. * @param z The z coordinate. * @param newHeight Height of the new. **************************************************************************************************/ void SetVertexHeight(int x, int z, const float newHeight); /**********************************************************************************************//** * @fn void Terrain::GenerateVertexPositions(TerrainInformation& terrainInformation); * * @brief Generates a vertex positions * * @author <NAME> * @date 10/09/2021 * * @param [in,out] terrainInformation Information describing the terrain. **************************************************************************************************/ void GenerateVertexPositions(TerrainInformation& terrainInformation); /**********************************************************************************************//** * @fn void Terrain::GenerateVertexIndices(); * * @brief Generates a vertex indices * * @author <NAME> * @date 10/09/2021 **************************************************************************************************/ void GenerateVertexIndices(); /**********************************************************************************************//** * @fn void Terrain::GenerateVertexColors(TerrainInformation& terrainInformaion); * * @brief Generates a vertex colors * * @author <NAME> * @date 10/09/2021 * * @param [in,out] terrainInformaion The terrain informaion. **************************************************************************************************/ void GenerateVertexColors(TerrainInformation& terrainInformaion); /**********************************************************************************************//** * @fn void Terrain::GenerateVertexTextureCoords(TerrainInformation& terrainInformation); * * @brief Generates a vertex texture coordinates * * @author <NAME> * @date 10/09/2021 * * @param [in,out] terrainInformation Information describing the terrain. **************************************************************************************************/ void GenerateVertexTextureCoords(TerrainInformation& terrainInformation); /**********************************************************************************************//** * @fn void Terrain::GenerateVertexNormals(TerrainInformation& terrainInformation); * * @brief Generates a vertex normals * * @author <NAME> * @date 10/09/2021 * * @param [in,out] terrainInformation Information describing the terrain. **************************************************************************************************/ void GenerateVertexNormals(TerrainInformation& terrainInformation); /**********************************************************************************************//** * @fn void Terrain::SmoothTerrain(TerrainInformation& terrainInformation); * * @brief Smooth terrain * * @author <NAME> * @date 10/09/2021 * * @param [in,out] terrainInformation Information describing the terrain. **************************************************************************************************/ void SmoothTerrain(TerrainInformation& terrainInformation); private: /** @brief Full pathname of the heightmap file */ std::string m_HeightmapPath = ""; /** @brief The minimum heightmap height */ float m_MinHeightmapHeight = 40.0f; /** @brief The maximum heightmap height */ float m_MaxHeightmapHeight = 100.0f; /** @brief The size */ glm::vec2 m_Size = glm::vec2(0.0f); /** @brief List of heights of the terrains */ std::vector<float> m_TerrainHeights; /** @brief The minimum height */ float m_MinHeight = 0.0f; /** @brief The maximum height */ float m_MaxHeight = 0.0f; /** @brief Information describing the terrain */ TerrainInformation m_TerrainInfo; /** @brief Terrain information combined into a single vector for use in the vertex buffer*/ std::vector<glm::vec3> m_VBOData; /** @brief Information describing the indices */ std::vector<uint32_t> m_IndicesData; /** @brief Size of the vbo */ uint32_t m_VBOSize; /** @brief Size of the ibo */ uint32_t m_IBOSize; /** @brief The buffer layout */ VertexBufferLayout m_BufferLayout; /** @brief The vao */ Ref<VertexArray> m_VAO; /** @brief The vbo */ Ref<VertexBuffer> m_VBO; /** @brief The ibo */ Ref<IndexBuffer> m_IBO; /** @brief The material */ Ref<Material> m_Material; /** @brief List of names of the texture files */ std::vector<std::string> m_TextureFileNames; /** @brief The highest point */ glm::vec3 m_HighestPoint = glm::vec3(0.0f); /** @brief The lowest point */ glm::vec3 m_LowestPoint = glm::vec3(0.0f); /**********************************************************************************************//** * @class EditorUI * * @brief An editor user interface. * * @author <NAME> * @date 10/09/2021 **************************************************************************************************/ friend class EditorUI; friend class Serializer; }; /**********************************************************************************************//** * @class TerrainComponent * * @brief A terrain component. * * @author <NAME> * @date 10/09/2021 **************************************************************************************************/ class TerrainComponent { public: /** @brief The scene terrain */ Terrain* SceneTerrain; /**********************************************************************************************//** * @fn TerrainComponent::TerrainComponent() = default; * * @brief Defaulted constructor * * @author <NAME> * @date 10/09/2021 **************************************************************************************************/ TerrainComponent() = default; /**********************************************************************************************//** * @fn TerrainComponent::TerrainComponent(const TerrainComponent& other) = default; * * @brief Defaulted copy constructor * * @author <NAME> * @date 10/09/2021 * * @param other The other. **************************************************************************************************/ TerrainComponent(const TerrainComponent& other) = default; /**********************************************************************************************//** * @fn TerrainComponent::TerrainComponent(const std::string& heightMapFilePath) * * @brief Constructor * * @author <NAME> * @date 10/09/2021 * * @param heightMapFilePath Full pathname of the height map file. **************************************************************************************************/ TerrainComponent(const std::string& heightMapFilePath) { SceneTerrain = new Terrain(heightMapFilePath); } /**********************************************************************************************//** * @fn TerrainComponent::TerrainComponent(const int width, const int maxHeight, const int minHeight) * * @brief Constructor * * @author <NAME> * @date 10/09/2021 * * @param width The width. * @param maxHeight The maximum height. * @param minHeight The minimum height. **************************************************************************************************/ TerrainComponent(const int width, const int maxHeight, const int minHeight) { SceneTerrain = new Terrain(width, maxHeight, minHeight); } private: friend class EditorUI; inline static std::string s_SearchString = "terrain component"; inline static ComponentTypes s_Types = { {ComponentVariations::Terrain}, {{ComponentCategory::Objects, ComponentCategory::Environment, ComponentCategory::Objects}} }; }; }
BryceStandley/TNAH
core/src/TNAH/Renderer/Mesh.h
#pragma once #define MAX_BONE_INFLUENCE 4 #include "TNAH/Core/Core.h" #include "TNAH/Core/Timestep.h" #include "TNAH/Renderer/VertexArray.h" #include "TNAH/Renderer/RenderingBuffers.h" #include "TNAH/Renderer/Shader.h" #include "TNAH/Renderer/Material.h" #include "Animation.h" #include "BoneInfo.h" #pragma warning(push, 0) #include <Assimp/Importer.hpp> #include <Assimp/scene.h> #include <Assimp/postprocess.h> #include <vector> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include<glm/gtx/matrix_decompose.hpp> #pragma warning(pop) namespace tnah { /** * @struct Vertex * * @brief A vertex. * * @author <NAME> * @date 12/09/2021 */ struct Vertex { /** @brief The position */ glm::vec3 Position; /** @brief The normal */ glm::vec3 Normal; /** @brief The tangent */ glm::vec3 Tangent; /** @brief The bitangents */ glm::vec3 Bitangents; /** @brief The texcoord */ glm::vec2 Texcoord; /** @brief bone IDs */ uint32_t IDs[MAX_BONE_INFLUENCE]; /** @brief The weights of bones */ float Weights[MAX_BONE_INFLUENCE]; /** * @fn void AddBoneData(uint32_t BoneID, float Weight) * * @brief Adds bone data * * @author <NAME> * @date 12/09/2021 * * @param BoneID Identifier for the bone. * @param Weight The weight. */ void AddBoneData(uint32_t BoneID, float Weight) { for (size_t i = 0; i < 4; i++) { if (Weights[i] == 0.0) { IDs[i] = BoneID; Weights[i] = Weight; return; } } // TODO: Keep top weights TNAH_CORE_WARN("Vertex has more than four bones/weights affecting it, extra data will be discarded (BoneID={0}, Weight={1})", BoneID, Weight); } }; /** * @struct MeshTexture * * @brief A mesh texture * * @author <NAME> * @date 12/09/2021 */ struct MeshTexture { /** @brief The texture */ Ref<Texture2D> Texture; /** @brief Full pathname of the texture file */ std::string TexturePath; /** * @fn MeshTexture(Ref<Texture2D> texture, const std::string& path) * * @brief Constructor * * @author <NAME> * @date 12/09/2021 * * @param texture The texture. * @param path Full pathname of the file. */ MeshTexture(Ref<Texture2D> texture, const std::string& path) :Texture(texture), TexturePath(path) {} }; /** * @struct MeshShader * * @brief A mesh shader. * * @author <NAME> * @date 12/09/2021 */ struct MeshShader { /** @brief The shader */ Ref<Shader> Shader; /** @brief Full pathname of the vertex shader file */ std::string VertexShaderPath; /** @brief Full pathname of the fragment shader file */ std::string FragmentShaderPath; /** * @fn MeshShader(Ref<tnah::Shader> shader, const std::string& vertex, const std::string& fragment) * * @brief Constructor * * @author <NAME> * @date 12/09/2021 * * @param shader The shader. * @param vertex The vertex. * @param fragment The fragment. */ MeshShader(Ref<tnah::Shader> shader, const std::string& vertex, const std::string& fragment) :Shader(shader), VertexShaderPath(vertex), FragmentShaderPath(fragment) {} }; /** * @class Mesh * * @brief A mesh class responsible for handling the meshes of models * * @author <NAME> * @date 12/09/2021 */ class Mesh { public: /** * @fn Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<Ref<Texture2D>> textures, bool animated); * * @brief Constructor * * @author <NAME> * @date 12/09/2021 * * @param vertices The vertices. * @param indices The indices. * @param textures The textures. * @param animated True if animated. */ Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<Ref<Texture2D>> textures, bool animated); /** * @fn Ref<VertexArray> Mesh::GetMeshVertexArray() const * * @brief Gets mesh vertex array * * @author <NAME> * @date 12/09/2021 * * @returns The mesh vertex array. */ Ref<VertexArray> GetMeshVertexArray() const {return m_Vao;} /** * @fn Ref<VertexBuffer> Mesh::GetMeshVertexBuffer() const * * @brief Gets mesh vertex buffer * * @author <NAME> * @date 12/09/2021 * * @returns The mesh vertex buffer. */ Ref<VertexBuffer> GetMeshVertexBuffer() const {return m_Vbo;} /** * @fn Ref<IndexBuffer> Mesh::GetMeshIndexBuffer() const * * @brief Gets mesh index buffer * * @author <NAME> * @date 12/09/2021 * * @returns The mesh index buffer. */ Ref<IndexBuffer> GetMeshIndexBuffer() const {return m_Ibo;} /** * @fn Ref<Material> Mesh::GetMeshMaterial() const * * @brief Gets mesh material * * @author <NAME> * @date 12/09/2021 * * @returns The mesh material. */ Ref<Material> GetMeshMaterial() const {return m_Material;} /** * @fn std::vector<glm::vec3> Mesh::GetVertexPositions() const; * * @brief Gets vertex positions * * @author <NAME> * @date 12/09/2021 * * @returns The vertex positions. */ std::vector<glm::vec3> GetVertexPositions() const; /** * @fn std::vector<uint32_t> Mesh::GetIndices() const * * @brief Gets the indices * * @author <NAME> * @date 12/09/2021 * * @returns The indices. */ std::vector<uint32_t> GetIndices() const { return m_Indices; } private: /** @brief The vertices */ std::vector<Vertex> m_Vertices; /** @brief The indices */ std::vector<uint32_t> m_Indices; /** @brief True if animated */ bool m_Animated; /** @brief The vao */ Ref<VertexArray> m_Vao; /** @brief The vbo */ Ref<VertexBuffer> m_Vbo; /** @brief The ibo */ Ref<IndexBuffer> m_Ibo; /** @brief The VertexBufferLayout */ VertexBufferLayout m_BufferLayout; /** @brief The material */ Ref<Material> m_Material; friend class EditorUI; }; /** * @class Model * * @brief A model class that inherits from the refCounted class, which allows model to use the Ref *. Responsible for the loading and handling of models * * @author <NAME> * @date 12/09/2021 */ class Model : public RefCounted { public: /** * @fn static Ref<Model> Model::Create(const std::string& filePath); * * @brief Creates a new model * * @author <NAME> * @date 12/09/2021 * * @param filePath Full pathname of the file. * * @returns A model */ static Ref<Model> Create(const std::string& filePath); /** * @fn Model::Model(); * * @brief Default constructor * * @author <NAME> * @date 12/09/2021 */ Model(); /** * @fn Model::Model(const std::string& filePath); * * @brief Constructor * * @author <NAME> * @date 12/09/2021 * * @param filePath Full pathname of the file. */ Model(const std::string& filePath); /** * @fn auto& Model::GetAnimation() * * @brief Gets the animation * * @author <NAME> * @date 12/09/2021 * * @returns The animation. */ auto& GetAnimation() { return m_Animation; } /** * @fn std::vector<Mesh> Model::GetMeshes() const * * @brief Gets the meshes * * @author <NAME> * @date 12/09/2021 * * @returns The meshes. */ std::vector<Mesh> GetMeshes() const { return m_Meshes; } /** * @fn uint32_t Model::GetNumberOfMeshes() const * * @brief Gets number of meshes * * @author <NAME> * @date 12/09/2021 * * @returns The number of meshes. */ uint32_t GetNumberOfMeshes() const { return static_cast<uint32_t>(m_Meshes.size()); } /** * @fn auto& Model::GetBoneInfoMap() * * @brief Gets bone information map * * @author <NAME> * @date 12/09/2021 * * @returns The bone information map. */ auto& GetBoneInfoMap() { return m_BoneInfoMap; } /** * @fn int& Model::GetBoneCount() * * @brief Gets bone count * * @author <NAME> * @date 12/09/2021 * * @returns The bone count. */ int& GetBoneCount() { return m_BoneCounter; } const Resource& GetResource() const { return m_Resource; } private: /** @brief The meshes */ std::vector<Mesh> m_Meshes; Resource m_Resource; /** @brief The animation */ Animation m_Animation; /** @brief The bone information map */ std::map<std::string, BoneInfo> m_BoneInfoMap; /** @brief The bone counter */ int m_BoneCounter = 0; /** @brief True if is animated, false if not */ bool m_IsAnimated = false; /** * @fn glm::mat4 Model::AiToGLM(aiMatrix4x4t<float> m); * * @brief Converts aiMatrix to glm::mat4 * * @author <NAME> * @date 12/09/2021 * * @param m An aiMatrix4x4t to process. * * @returns A glm::mat4. */ glm::mat4 AiToGLM(aiMatrix4x4t<float> m); /** * @fn glm::vec3 Model::AiToGLM(aiVector3t<float> v); * * @brief Converts aiVector to glm::vec3 * * @author <NAME> * @date 12/09/2021 * * @param v An aiVector3t to process. * * @returns A glm::vec3. */ glm::vec3 AiToGLM(aiVector3t<float> v); /** * @fn glm::quat Model::AiToGLM(aiQuaterniont<float> q); * * @brief Converts aiQuaterniont to glm::quat * * @author <NAME> * @date 12/09/2021 * * @param q An aiQuaterniont to process. * * @returns A glm::quat. */ glm::quat AiToGLM(aiQuaterniont<float> q); /** * @fn void Model::SetVertexBoneDataToDefault(Vertex& vertex); * * @brief Sets vertex bone data to default * * @author <NAME> * @date 12/09/2021 * * @param [in,out] vertex The vertex. */ void SetVertexBoneDataToDefault(Vertex& vertex); /** * @fn void Model::SetVertexBoneData(Vertex& vertex, int boneID, float weight); * * @brief Sets vertex bone data * * @author <NAME> * @date 12/09/2021 * * @param [in,out] vertex The vertex. * @param boneID Identifier for the bone. * @param weight The weight. */ void SetVertexBoneData(Vertex& vertex, int boneID, float weight); /** * @fn void Model::ExtractBoneWeightForVertices(std::vector<Vertex>& vertices, aiMesh* mesh, const aiScene* scene); * * @brief Extracts the bone weight for vertices * * @author <NAME> * @date 12/09/2021 * * @param [in,out] vertices The vertices. * @param [in,out] mesh If non-null, the mesh. * @param scene The scene. */ void ExtractBoneWeightForVertices(std::vector<Vertex>& vertices, aiMesh* mesh, const aiScene* scene); /** * @fn void Model::LoadModel(const std::string& filePath); * * @brief Loads a model * * @author <NAME> * @date 12/09/2021 * * @param filePath Full pathname of the file. */ void LoadModel(const std::string& filePath); /** * @fn void Model::ProcessNode(aiNode* node, const aiScene* scene); * * @brief Process the node * * @author <NAME> * @date 12/09/2021 * * @param [in,out] node If non-null, the node. * @param scene The scene. */ void ProcessNode(aiNode* node, const aiScene* scene); /** * @fn Mesh Model::ProcessMesh(aiMesh* mesh, const aiScene* scene, bool animated); * * @brief Process the mesh * * @author <NAME> * @date 12/09/2021 * * @param [in,out] mesh If non-null, the mesh. * @param scene The scene. * @param animated True if animated. * * @returns A Mesh. */ Mesh ProcessMesh(aiMesh* mesh, const aiScene* scene, bool animated); /** * @fn std::vector<Ref<Texture2D>> Model::LoadMaterialTextures(const aiScene* scene, aiMaterial* material, aiTextureType type, const std::string& typeName); * * @brief Loads material textures * * @author <NAME> * @date 12/09/2021 * * @param scene The scene. * @param [in,out] material If non-null, the material. * @param type The type. * @param typeName Name of the type. * * @returns The material textures. */ std::vector<Ref<Texture2D>> LoadMaterialTextures(const aiScene* scene, aiMaterial* material, aiTextureType type, const std::string& typeName); friend class EditorUI; friend class Serializer; }; }
BryceStandley/TNAH
core/src/TNAH/Scene/Scene.h
#pragma once #include <TNAH/Core/Core.h> #include "TNAH/Core/UUID.h" #include <vector> #include "SceneCamera.h" #include "Components/Components.h" #include "TNAH/Core/Timestep.h" #include "TNAH/Core/Math.h" #include "TNAH/Core/Ref.h" #include "TNAH/Physics/PhysicsTimestep.h" #pragma warning(push, 0) #include <entt/entt.hpp> #include <reactphysics3d/reactphysics3d.h> #pragma warning(pop) namespace tnah { /** * @class Light * * @brief A light object forward declaration. * * @author <NAME> * @date 7/09/2021 */ class Light; /** * @class GameObject * * @brief A game object forward declaration. * * @author <NAME> * @date 7/09/2021 */ class GameObject; /**********************************************************************************************//** * @class Scene * * @brief A scene * * @author <NAME> * @date 7/09/2021 **************************************************************************************************/ class Scene : public RefCounted { friend class GameObject; public: /**********************************************************************************************//** * @struct ActiveScene * * @brief The current active scene reference * * @author Chris * @date 10/09/2021 **************************************************************************************************/ struct ActiveScene { Ref<Scene> Scene; }; /**********************************************************************************************//** * @fn Scene::Scene(bool editor = false); * * @brief Constructor * * @author Chris * @date 10/09/2021 * * @param editor (Optional) True to create a scene for the editor. **************************************************************************************************/ Scene(bool editor = false); /**********************************************************************************************//** * @fn Scene::~Scene(); * * @brief Destructor * * @author Chris * @date 10/09/2021 **************************************************************************************************/ ~Scene(); /**********************************************************************************************//** * @fn static void Scene::ClearActiveScene(); * * @brief Clears the active scene * * @author Chris * @date 10/09/2021 **************************************************************************************************/ static void ClearActiveScene(); /**********************************************************************************************//** * @fn static Ref<Scene> Scene::CreateEmptyScene(); * * @brief Creates empty scene * * @author Chris * @date 10/09/2021 * * @returns The new empty scene. **************************************************************************************************/ static Ref<Scene> CreateEmptyScene(); /**********************************************************************************************//** * @fn void Scene::OnUpdate(Timestep deltaTime); * * @brief Creates game object and adds a default transform component to it * * @author <NAME> * @date 18/07/2021 * * @param deltaTime The delta time. * * ### returns The new game object. **************************************************************************************************/ void OnUpdate(Timestep deltaTime); /**********************************************************************************************//** * @fn void Scene::OnFixedUpdate(PhysicsTimestep deltaTime); * * @brief Executes the 'fixed update' action * * @author Chris * @date 10/09/2021 * * @param deltaTime The delta time. **************************************************************************************************/ void OnFixedUpdate(Timestep deltaTime, PhysicsTimestep physicsDeltaTime); /**********************************************************************************************//** * @fn glm::mat4 Scene::GetTransformRelativeToParent(GameObject gameObject); * * @brief Gets the parent of this item * * @author Chris * @date 10/09/2021 * * @param gameObject The game object. * * @returns The transform relative to parent. **************************************************************************************************/ glm::mat4 GetTransformRelativeToParent(GameObject gameObject); /**********************************************************************************************//** * @fn GameObject& Scene::CreateGameObject(const std::string& name); * * @brief Creates game object * * @author Chris * @date 10/09/2021 * * @param name The name. * * @returns The new game object. **************************************************************************************************/ GameObject& CreateGameObject(const std::string& name); /**********************************************************************************************//** * @fn GameObject Scene::CreateGameObject(); * * @brief Creates game object * * @author Chris * @date 10/09/2021 * * @returns The new game object. **************************************************************************************************/ GameObject CreateGameObject(); /**********************************************************************************************//** * @fn GameObject Scene::FindEntityByTag(const std::string& tag); * * @brief Searches for the first entity by tag * * @author Chris * @date 10/09/2021 * * @param tag The tag. * * @returns The found entity by tag. **************************************************************************************************/ GameObject FindEntityByTag(const std::string& tag); /**********************************************************************************************//** * @fn GameObject Scene::FindEntityByUUID(UUID id); * * @brief Searches for the first entity by uuid * * @author Chris * @date 10/09/2021 * * @param id The identifier. * * @returns The found entity by uuid. **************************************************************************************************/ GameObject FindEntityByUUID(UUID id); /**********************************************************************************************//** * @fn GameObject& Scene::FindGameObjectByID(const entt::entity& id); * * @brief Searches for the first game object by identifier * * @author Chris * @date 10/09/2021 * * @param id The identifier. * * @returns The found game object by identifier. **************************************************************************************************/ GameObject& FindGameObjectByID(const entt::entity& id); /**********************************************************************************************//** * @fn void Scene::DestroyGameObject(GameObject gameObject); * * @brief Destroys the game object described by gameObject * * @author Chris * @date 10/09/2021 * * @param gameObject The game object. **************************************************************************************************/ void DestroyGameObject(GameObject gameObject); /**********************************************************************************************//** * @fn GameObject& Scene::GetSceneCamera(); * * @brief Gets scene camera * * @author Chris * @date 10/09/2021 * * @returns The scene camera. **************************************************************************************************/ GameObject& GetSceneCamera(); /**********************************************************************************************//** * @fn GameObject& Scene::GetSceneLight(); * * @brief Gets scene light * * @author Chris * @date 10/09/2021 * * @returns The scene light. **************************************************************************************************/ GameObject& GetSceneLight(); /**********************************************************************************************//** * @fn std::map<UUID, GameObject>& Scene::GetGameObjectsInScene(); * * @brief Gets game objects in scene * * @author Chris * @date 10/09/2021 * * @returns The game objects in scene in a map. **************************************************************************************************/ std::map<UUID, GameObject>& GetGameObjectsInScene(); PhysicsTimestep m_PhysicsTime; bool GetPlayerInteraction() { return mPlayerInteractions; } std::string GetTargetString() const { return mTargetString; }private: /**********************************************************************************************//** * @fn GameObject Scene::CreateEditorCamera(); * * @brief Creates editor camera * * @author Chris * @date 10/09/2021 * * @returns The new editor camera. **************************************************************************************************/ GameObject CreateEditorCamera(); /**********************************************************************************************//** * @fn void Scene::Destroy(); * * @brief Destroys this object * * @author Chris * @date 10/09/2021 **************************************************************************************************/ void Destroy(); /**********************************************************************************************//** * @fn static Ref<Scene> Scene::CreateNewEditorScene(); * * @brief Creates a new editor scene * * @author Chris * @date 10/09/2021 * * @returns The new new editor scene. **************************************************************************************************/ static Ref<Scene> CreateNewEditorScene(); /**********************************************************************************************//** * @fn GameObject& Scene::GetEditorCamera(); * * @brief Gets editor camera * * @author Chris * @date 10/09/2021 * * @returns The editor camera. **************************************************************************************************/ GameObject& GetEditorCamera(); /**********************************************************************************************//** * @fn Ref<Framebuffer> Scene::GetEditorSceneFramebuffer() * * @brief Gets editor scene framebuffer * * @author Chris * @date 10/09/2021 * * @returns The editor scene framebuffer. **************************************************************************************************/ Ref<Framebuffer> GetEditorSceneFramebuffer() { return m_EditorSceneFramebuffer; } /**********************************************************************************************//** * @fn Ref<Framebuffer> Scene::GetEditorGameFramebuffer() * * @brief Gets editor game framebuffer * * @author Chris * @date 10/09/2021 * * @returns The editor game framebuffer. **************************************************************************************************/ Ref<Framebuffer> GetEditorGameFramebuffer() { return m_EditorGameFramebuffer; } /**********************************************************************************************//** * @fn entt::registry& Scene::GetRegistry() * * @brief Gets the registry * * @author Chris * @date 10/09/2021 * * @returns The registry. **************************************************************************************************/ entt::registry& GetRegistry() { return m_Registry; } /**********************************************************************************************//** * @fn GameObject* Scene::GetRefGameObject(const UUID& id); * * @brief Gets reference game object * * @author Chris * @date 10/09/2021 * * @param id The identifier. * * @returns Null if it fails, else the reference game object. **************************************************************************************************/ GameObject* GetRefGameObject(const UUID& id); private: /** @brief A active scene reference */ static ActiveScene s_ActiveScene; /** @brief The component registry */ entt::registry m_Registry; /** @brief The game objects in scene */ std::map<UUID, GameObject> m_GameObjectsInScene; /** @brief The active camera */ UUID m_ActiveCamera; /** @brief The scene light */ UUID m_SceneLight; /** @brief The editor camera */ UUID m_EditorCamera; /** @brief The editor scene framebuffer */ Ref<Framebuffer> m_EditorSceneFramebuffer; /** @brief The editor game framebuffer */ Ref<Framebuffer> m_EditorGameFramebuffer; /** @brief True if is editor scene, false if not */ bool m_IsEditorScene = false; /** @brief The render passes for scene rendering */ uint32_t m_RenderPasses = 0; /** @brief The scene entity */ entt::entity m_SceneEntity; /** @brief Identifier for the scene */ UUID m_SceneID; /** @brief The listener */ rp3d::EventListener * listener; bool mPlayerInteractions; std::string mTargetString = ""; friend class EditorLayer; friend class Editor; friend class Serializer; }; }
BryceStandley/TNAH
core/src/TNAH/Renderer/Animation.h
<reponame>BryceStandley/TNAH<filename>core/src/TNAH/Renderer/Animation.h #pragma once #include "AssimpGLMHelpers.h" #include "TNAH/Core/Core.h" #include <Assimp/scene.h> #include "Bone.h" #include "BoneInfo.h" namespace tnah { /** * @struct AssimpNodeData * * @brief A struct containing the Assimp node data * * @author <NAME> * @date 12/09/2021 */ struct AssimpNodeData { AssimpNodeData() { children.reserve(1); } /** @brief The transformation */ glm::mat4 transformation = glm::mat4(1.0f); /** @brief The name */ std::string name = ""; /** @brief Number of childrens */ int childrenCount = 0; /** @brief The children */ std::vector<AssimpNodeData> children; }; /** * @class Animation * * @brief An animation class responsible for the skeletal animation * * @author <NAME> * @date 12/09/2021 */ class Animation { public: /** * @fn Animation::Animation() = default; * * @brief Defaulted constructor * * @author <NAME> * @date 12/09/2021 */ Animation() = default; /** * @fn Animation::Animation(const aiScene* scene) * * @brief Constructor * * @author <NAME> * @date 12/09/2021 * * @param scene The scene. */ Animation(const aiScene* scene) { m_Animation = scene->mAnimations[0]; m_Duration = m_Animation->mDuration; m_TicksPerSecond = m_Animation->mTicksPerSecond; ReadHeirarchyData(m_RootNode, scene->mRootNode); } /** * @fn Animation::~Animation() * * @brief Destructor * * @author <NAME> * @date 12/09/2021 */ ~Animation() {} /** * @fn Bone* Animation::FindBone(const std::string& name) * * @brief Searches for the first bone * * @author <NAME> * @date 12/09/2021 * * @param name The name. * * @returns Null if it fails, else the found bone. */ Bone* FindBone(const std::string& name) { auto iter = std::find_if(m_Bones.begin(), m_Bones.end(), [&](const Bone& Bone) { return Bone.GetBoneName() == name; } ); if (iter == m_Bones.end()) return nullptr; else return &(*iter); } /** * @fn inline float Animation::GetTicksPerSecond() * * @brief Gets ticks per second * * @author <NAME> * @date 12/09/2021 * * @returns The ticks per second. */ inline float GetTicksPerSecond() { return m_TicksPerSecond; } /** * @fn inline float Animation::GetDuration() * * @brief Gets the duration * * @author <NAME> * @date 12/09/2021 * * @returns The duration. */ inline float GetDuration() { return m_Duration; } /** * @fn inline const AssimpNodeData& Animation::GetRootNode() * * @brief Gets root node * * @author <NAME> * @date 12/09/2021 * * @returns The root node. */ inline const AssimpNodeData& GetRootNode() { return m_RootNode; } /** * @fn inline const std::map<std::string, BoneInfo>& Animation::GetBoneIDMap() * * @brief Gets bone identifier map * * @author <NAME> * @date 12/09/2021 * * @returns The bone identifier map. */ inline const std::map<std::string, BoneInfo>& GetBoneIDMap() { return m_BoneInfoMap; } /** * @fn void Animation::ReadMissingBones(std::map<std::string, BoneInfo>& boneInfoMap, int& boneCount) * * @brief Reads missing bones * * @author <NAME> * @date 12/09/2021 * * @param [in,out] boneInfoMap The bone information map. * @param [in,out] boneCount Number of bones. */ void ReadMissingBones(std::map<std::string, BoneInfo>& boneInfoMap, int& boneCount) { int size = m_Animation->mNumChannels; //reading channels (bone engaged in an animation and their keyframes) for (int i = 0; i < size; i++) { auto channel = m_Animation->mChannels[i]; std::string boneName = channel->mNodeName.data; if (boneInfoMap.find(boneName) == boneInfoMap.end()) { boneInfoMap[boneName].id = boneCount; boneCount++; } m_Bones.push_back(Bone(channel->mNodeName.data, boneInfoMap[channel->mNodeName.data].id, channel)); } m_BoneInfoMap = boneInfoMap; } private: /** * @fn void Animation::ReadHeirarchyData(AssimpNodeData& dest, const aiNode* src) * * @brief Reads heirarchy data * * @author <NAME> * @date 12/09/2021 * * @param [in,out] dest Destination for the. * @param src Source for the. */ void ReadHeirarchyData(AssimpNodeData& dest, const aiNode* src) { assert(src); dest.name = src->mName.data; dest.transformation = AssimpGLMHelpers::ConvertMatrixToGLMFormat(src->mTransformation); dest.childrenCount = src->mNumChildren; for (int i = 0; i < src->mNumChildren; i++) { AssimpNodeData newData; ReadHeirarchyData(newData, src->mChildren[i]); dest.children.push_back(newData); } } /** @brief The duration of the animation */ float m_Duration = 0.0f; /** @brief The ticks per second, which notes how fast interpolation between frames should be */ int m_TicksPerSecond = 0.0f; /** @brief The bones required for the animation */ std::vector<Bone> m_Bones; /** @brief The root node */ AssimpNodeData m_RootNode; /** @brief The bone information map */ std::map<std::string, BoneInfo> m_BoneInfoMap; /** @brief The animation */ aiAnimation* m_Animation; }; }
BryceStandley/TNAH
core/src/TNAH/Renderer/BoneInfo.h
#pragma once /** * @struct BoneInfo * * @brief Information about the bone. * * @author <NAME> * @date 12/09/2021 */ struct BoneInfo { /** @brief The identifier */ int id; /** @brief Transform vertex from model space to bone space. */ glm::mat4 offset; };
BryceStandley/TNAH
core/src/Platform/MiniAudio/MiniAudio.h
#pragma once #include "TNAH/Audio/AudioAPI.h" namespace tnah { //TODO Actually set up mini audio class MiniAudio : public AudioAPI { public: bool SetListener(TransformComponent &transforms) const override; bool AddAudioSource(AudioSourceComponent &sound) override; bool UpdateAudioSource(AudioSourceComponent &sound) override; void OnUpdate() override; void UpdateSound(AudioSourceComponent& sound, TransformComponent &transforms) override; bool Active() const override; void Clear() override; }; }
BryceStandley/TNAH
core/src/TNAH/Physics/PhysicsStructures.h
#pragma once #pragma warning(push, 0) #include <reactphysics3d/reactphysics3d.h> #pragma warning(pop) namespace tnah { namespace Physics{ /** * @brief Type of a RigidBody * @author <NAME> * @date 06-11-2021 */ enum class BodyType { Dynamic, Static, Kinematic }; /** * @brief Structure of LinearVelocity * @author <NAME> * @date 06-11-2021 */ struct LinearVelocity { glm::vec3 Velocity = {}; operator glm::vec3 () { return Velocity; } operator glm::vec3 () const { return Velocity; } glm::vec3 operator = (const glm::vec3& value) { Velocity = value; return Velocity; } glm::vec3 operator * (const float& value) { Velocity *= value; return Velocity; } glm::vec3 operator *= (const float& value) { Velocity *= value; return Velocity; } glm::vec3 operator / (const float& value) { Velocity /= value; return Velocity; } glm::vec3 operator + (const glm::vec3& value) { Velocity += value; return Velocity; } glm::vec3 operator - (const glm::vec3& value) { Velocity -= value; return Velocity; } }; /** * @brief Structure of Force * @author <NAME> * @date 06-11-2021 */ struct Force { glm::vec3 Forces = {}; glm::vec3 operator = (const glm::vec3& value) { Forces = value; return Forces; } glm::vec3 operator += (const glm::vec3 value) { Forces += value; return value; } }; /** * @brief Structure of Linear Dampening * @author <NAME> * @date 06-11-2021 */ struct LinearDampening { float Dampening = 0.0f; float operator = (const float& value) { Dampening = value; return Dampening; } operator float () const { return Dampening; } }; /** * @brief Structure of Mass * @author <NAME> * @date 06-11-2021 */ struct BodyMass { /** * @brief Construct a new Body Mass object * @author <NAME> * @date 06-11-2021 */ BodyMass() { SetMass(); } /** * @fn void BodyMass::SetMass(float mass = 1.0f); * * @brief Sets the mass and updates the inverse mass. */ void SetMass(float mass = 1.0f) { Mass = mass; InverseMass = 1.0f / (Mass > 0.0f ? Mass : 1.0f); // cant invert mass if its 0 } glm::vec3 LocalCentreOfMass = {0,0,0}; glm::vec3 WorldCentreOfMass = {0,0,0}; float Mass = 1.0f; float InverseMass = 1.0f; }; /** * @brief Structure of Angular Velocity * @author <NAME> * @date 06-11-2021 */ struct AngularVelocity { glm::vec3 Velocity = {}; operator glm::vec3 () { return Velocity; } operator glm::vec3 () const { return Velocity; } glm::vec3 operator = (const glm::vec3& value) { Velocity = value; return Velocity; } glm::vec3 operator * (const float& value) { Velocity *= value; return Velocity; } glm::vec3 operator *= (const float& value) { Velocity *= value; return Velocity; } glm::vec3 operator / (const float& value) { Velocity /= value; return Velocity; } glm::vec3 operator + (const glm::vec3& value) { Velocity += value; return Velocity; } glm::vec3 operator - (const glm::vec3& value) { Velocity -= value; return Velocity; } }; /** * @brief Structure of Angular Dampening * @author <NAME> * @date 06-11-2021 */ struct AngularDampening { float Dampening = 0.2f; float operator = (const float& value) { Dampening = value; return Dampening; } operator float () const { return Dampening; } }; /** * @brief Structure of Torque * @author <NAME> * @date 06-11-2021 */ struct Torque { glm::vec3 Torques = {}; glm::vec3 operator = (const glm::vec3& value) { Torques = value; return Torques; } glm::vec3 operator += (const glm::vec3 value) { Torques += value; return value; } }; /** * @brief Structure of Inertia Tensors (resistance to rotation) * @author <NAME> * @date 06-11-2021 */ struct InertiaTensor { glm::mat3 WorldInertiaTensor = glm::mat3(1.0f); glm::mat3 WorldInverseInertiaTensor = glm::inverse(glm::mat3(1.0f)); glm::vec3 LocalInertiaTensor = {1,1,1}; glm::vec3 LocalInverseInertiaTensor = {1,1,1}; glm::vec3 SetLocalInertiaTensor(const glm::vec3 localTensor) { LocalInertiaTensor = localTensor; LocalInverseInertiaTensor = glm::vec3(localTensor.x != 0.0f ? 1.0f / localTensor.x : 0.0f, localTensor.y != 0.0f ? 1.0f / localTensor.y : 0.0f, localTensor.z != 0.0f ? 1.0f / localTensor.z : 0.0f); return LocalInertiaTensor; } glm::mat3 SetWorldInertiaTensor(const glm::mat3& worldTensor) { WorldInertiaTensor = worldTensor; WorldInverseInertiaTensor = glm::inverse(worldTensor); return WorldInertiaTensor; } }; } }
BryceStandley/TNAH
core/src/TNAH/Core/Utility.h
<filename>core/src/TNAH/Core/Utility.h #pragma once #include <string> #include <filesystem> #include <map> #include <set> #include <sstream> #include <glm/detail/type_quat.hpp> namespace tnah { /** * @namespace tnah::Utility {} * * @brief Utility sub-namespace */ namespace Utility { /** * @fn static std::pair<std::string, std::string> tnah::Utility::SplitDirectoryAndFilePath(const std::string& filePath) * * @brief Splits directory and file path * * @author <NAME> * @date 7/09/2021 * * @param filePath Full pathname of the file. * * @returns A std::pair&lt;std::string,std::string&gt; */ static std::pair<std::string, std::string> SplitDirectoryAndFilePath(const std::string& filePath) { std::pair<std::string, std::string> split; auto lastSlash = filePath.find_last_of("/\\"); lastSlash = lastSlash == std::string::npos ? 0 : lastSlash; split.first = filePath.substr(0, lastSlash + 1); auto count = filePath.size() - 1; split.second = filePath.substr(lastSlash + 1, count); return split; } /** * @fn static std::string FindFileNameFromPath(const std::string& filePath) * * @brief Searches for the first file name from path * * @author <NAME> * @date 7/09/2021 * * @param filePath Full pathname of the file. * * @returns The found file name from path. */ static std::string FindFileNameFromPath(const std::string& filePath) { auto lastSlash = filePath.find_last_of("/\\"); lastSlash = lastSlash == std::string::npos ? 0 : lastSlash + 1; auto lastDot = filePath.rfind('.'); auto count = lastDot == std::string::npos ? filePath.size() - lastSlash : lastDot - lastSlash; return filePath.substr(lastSlash, count); } /** * @fn static std::pair<std::string, std::string> SplitFileNameAndExtension(const std::string& fileName) * * @brief Splits file name and extension * * @author <NAME> * @date 7/09/2021 * * @param fileName Filename of the file. * * @returns A std::pair&lt;std::string,std::string&gt; */ static std::pair<std::string, std::string> SplitFileNameAndExtension(const std::string& fileName) { auto dot = fileName.find_first_of("."); std::pair<std::string, std::string> split; split.first = fileName.substr(0,dot); auto count = fileName.size() - 1; auto start = dot + 1; split.second = fileName.substr(start, count); return split; } /** * @fn static std::string RelativePathFromAbsolute(const std::string& absolutePath) * * @brief Relative path from absolute * * @author <NAME> * @date 7/09/2021 * * @param absolutePath Full pathname of the absolute file. * * @returns A std::string. */ static std::string RelativePathFromAbsolute(const std::string& absolutePath) { auto wd = std::filesystem::current_path(); auto relative = absolutePath.find(wd.string()); if(relative != std::string::npos) { return std::string(absolutePath.substr(relative, wd.string().length())); } return "null"; } /** * @fn static std::string AbsolutePathFromRelative(const std::string& relativePath) * * @brief Absolute path from relative * * @author <NAME> * @date 7/09/2021 * * @param relativePath Full pathname of the relative file. * * @returns A std::string. */ static std::string AbsolutePathFromRelative(const std::string& relativePath) { auto wd = std::filesystem::current_path(); std::string out = wd.string() + "/" + relativePath; return out; } /** * @fn template<typename T> static bool Contains(const std::list<T>& list, const T& searchItem) * * @brief Query if the search item is contained within the given list * *@author <NAME> * * @tparam T Generic type parameter. * @param list The list. * @param searchItem The search item. * * @returns True if the object is in this list, false if not. */ template<typename T> static bool Contains(const std::list<T>& list, const T& searchItem) { return (std::find(list.begin(), list.end(), searchItem) != list.end()); } /** * @fn template<typename T, typename S> static bool Contains(const std::list<T>& list, const S& searchItem) * * @brief Query if the search item of a given type is contained within the given list. Used for sub-searches. * *@author <NAME> * * @tparam T Generic type parameter. * @tparam S Generic type parameter. * @param list The list. * @param searchItem The search item. * * @returns True if the object is in this list, false if not. */ template<typename T, typename S> static bool Contains(const std::list<T>& list, const S& searchItem) { return (std::find(list.begin(), list.end(), searchItem) != list.end()); } /** * @fn template<typename T> static bool Contains(const std::vector<T>& vector, const T& searchItem) * * @brief Query if the search item is contained within the given vector * * @tparam T Generic type parameter. * @param vector The vector. * @param searchItem The search item. * * @returns True if the object is in this collection, false if not. */ template<typename T> static bool Contains(const std::vector<T>& vector, const T& searchItem) { return (std::find(vector.begin(), vector.end(), searchItem) != vector.end()); } /** * @fn template<typename T> static bool Contains(const std::set<T>& set, const T& searchItem) * * @brief Query if the search item is contained within the given set * * @tparam T Generic type parameter. * @param set The set. * @param searchItem The search item. * * @returns True if the object is in this collection, false if not. */ template<typename T> static bool Contains(const std::set<T>& set, const T& searchItem) { return (std::find(set.begin(), set.end(), searchItem) != set.end()); } /** * @fn template<typename T, typename J> static bool Contains(const std::map<T, J>& map, const T& searchItem) * * @brief Query if the searchItem is contained within the given map * * @tparam T Generic type parameter. * @tparam J Generic type parameter. * @param map The map. * @param searchItem The search item. * * @returns True if the object is in this collection, false if not. */ template<typename T, typename J> static bool Contains(const std::map<T, J>& map, const T& searchItem) { return (std::find(map.begin(), map.end(), searchItem) != map.end()); } /** * @fn std::string VecToString(const glm::vec2& value); * * @brief Converts a glm vec to string * * @author <NAME> * @date 6/11/2021 * * @param value * @return * */ static std::string VecToString(const glm::vec2& value) { auto x = std::to_string(value.x); auto y = std::to_string(value.y); std::stringstream ss; ss << "X: " + x + " Y: " + y; return {ss.str()}; } /** * @fn std::string VecToString(const glm::vec3& value); * * @brief Converts a glm vec to string * * @author <NAME> * @date 6/11/2021 * * @param value * @return * */ static std::string VecToString(const glm::vec3& value) { auto x = std::to_string(value.x); auto y = std::to_string(value.y); auto z = std::to_string(value.z); std::stringstream ss; ss << "X: " + x + " Y: " + y + " Z: " + z; return {ss.str()}; } /** * @fn std::string VecToString(const glm::vec4& value); * * @brief Converts a glm vec to string * * @author <NAME> * @date 6/11/2021 * * @param value * @return * */ static std::string VecToString(const glm::vec4& value) { auto x = std::to_string(value.x); auto y = std::to_string(value.y); auto z = std::to_string(value.z); auto w = std::to_string(value.w); std::stringstream ss; ss << "X: " + x + " Y: " + y + " Z: " + z + " W: " + w; return {ss.str()}; } /** * @fn std::string QuatToString(const glm::quat& value); * * @brief Converts a quaternion to string * * @author <NAME> * @date 6/11/2021 * * @param value * @return * */ static std::string QuatToString(const glm::quat& value) { auto x = std::to_string(value.x); auto y = std::to_string(value.y); auto z = std::to_string(value.z); auto w = std::to_string(value.w); std::stringstream ss; ss << "X: " + x + " Y: " + y + " Z: " + z + " W: " + w; return {ss.str()}; } /** * @fn std::string MatToString(const glm::mat2& value); * * @brief Converts a glm mat to string * * @author <NAME> * @date 6/11/2021 * * @param value * @return * */ static std::string MatToString(const glm::mat2& value) { /* * 0,0: v | 0,1: v \n * 1,0: v | 1,1: v \n */ std::stringstream ss; ss << "0,0: " + std::to_string(value[0][0]) + " | 0,1: " +std::to_string(value[0][1]) + " | "; ss << "1,0: " + std::to_string(value[1][0]) + " | 1,1: " +std::to_string(value[1][1]); return ss.str(); } /** * @fn std::string MatToString(const glm::mat3& value); * * @brief Converts a glm mat to string * * @author <NAME> * @date 6/11/2021 * * @param value * @return * */ static std::string MatToString(const glm::mat3& value) { /* * 0,0: v | 0,1: v \n * 1,0: v | 1,1: v \n */ std::stringstream ss; ss << "0,0: " + std::to_string(value[0][0]) + " | 0,1: " +std::to_string(value[0][1]) + " | 0,2: " + std::to_string(value[0][2]) + " | "; ss << "1,0: " + std::to_string(value[1][0]) + " | 1,1: " +std::to_string(value[1][1]) + " | 1,2: " + std::to_string(value[1][2]) + " | "; ss << "2,0: " + std::to_string(value[2][0]) + " | 2,1: " +std::to_string(value[2][1]) + " | 2,2: " + std::to_string(value[2][2]); return ss.str(); } /** * @fn std::string MatToString(const glm::mat4& value); * * @brief Converts a glm mat to string * * @author <NAME> * @date 6/11/2021 * * @param value * @return * */ static std::string MatToString(const glm::mat4& value) { /* * 0,0: v | 0,1: v \n * 1,0: v | 1,1: v \n */ std::stringstream ss; ss << "0,0: " + std::to_string(value[0][0]) + " | 0,1: " +std::to_string(value[0][1]) + " | 0,2: " + std::to_string(value[0][2]) + " | 0,3: " + std::to_string(value[0][3]) + " | "; ss << "1,0: " + std::to_string(value[1][0]) + " | 1,1: " +std::to_string(value[1][1]) + " | 1,2: " + std::to_string(value[1][2]) + " | 1,3: " + std::to_string(value[1][3]) + " | "; ss << "2,0: " + std::to_string(value[2][0]) + " | 2,1: " +std::to_string(value[2][1]) + " | 2,2: " + std::to_string(value[2][2]) + " | 2,3: " + std::to_string(value[2][3]) + " | "; ss << "3,0: " + std::to_string(value[3][0]) + " | 3,1: " +std::to_string(value[3][1]) + " | 3,2: " + std::to_string(value[3][2]) + " | 3,3: " + std::to_string(value[3][3]); return ss.str(); } } }
BryceStandley/TNAH
core/src/Platform/OpenGL/OpenGLRendererAPI.h
#pragma once #include "TNAH/Renderer/RendererAPI.h" namespace tnah { /** * @class OpenGLRendererAPI * * @brief An OpenGLRendererAPI class that inherits from the RendererAPI base class * * @author <NAME> * @date 7/09/2021 */ class OpenGLRendererAPI : public RendererAPI { public: /** * @fn void OpenGLRendererAPI::Init() override; * * @brief Initializes this object * * @author <NAME> * @date 7/09/2021 */ void Init() override; /** * @fn void OpenGLRendererAPI::SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height) override; * * @brief Sets the glViewport * * @author <NAME> * @date 7/09/2021 * * @param x An uint32_t to process. * @param y An uint32_t to process. * @param width The width. * @param height The height. */ void SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height) override; /** * @fn void OpenGLRendererAPI::SetClearColor(const glm::vec4& color) override; * * @brief Sets clear color * * @author <NAME> * @date 7/09/2021 * * @param color The color provided in a vec4. */ void SetClearColor(const glm::vec4& color) override; /** * @fn void OpenGLRendererAPI::Clear() override; * * @brief Clears this object to its blank/initial state * * @author <NAME> * @date 7/09/2021 */ void Clear() override; /** * @fn void OpenGLRendererAPI::Disable(const APIEnum& value) override; * * @brief Disables the given value * * @author <NAME> * @date 7/09/2021 * * @param value The value. */ void Disable(const APIEnum& value) override; /** * @fn void OpenGLRendererAPI::Enable(const APIEnum& value) override; * * @brief Enables the given value * * @author <NAME> * @date 7/09/2021 * * @param value The value. */ void Enable(const APIEnum& value) override; /** * @fn void OpenGLRendererAPI::DrawIndexed(const Ref<VertexArray>& vertexArray) override; * * @brief Draw indexed using glDrawElements * * @author <NAME> * @date 7/09/2021 * * @param vertexArray Array of vertices. * @param mode Drawing Mode * @param indicesStart Pointer to the first element of the indices array. Void pointer to be any type */ void DrawIndexed(const Ref<VertexArray>& vertexArray, const DrawMode& mode = DrawMode::Triangles, void* indicesStart = nullptr) override; /** * @fn void OpenGLRendererAPI::DrawArray(const Ref<VertexArray>& vertexArray) override; * * @brief Draws an array using glDrawArrays * * @author <NAME> * @date 7/09/2021 * * @param vertexArray Array of vertices. */ void DrawArray(const Ref<VertexArray>& vertexArray, const DrawMode& mode) override; /** * @fn void OpenGLRendererAPI::SetWireframe(const bool& enable) override; * * @brief Sets a wireframe * * @author <NAME> * @date 7/09/2021 * * @param enable True to enable wireframe, false to disable. */ void SetWireframe(const bool& enable) override; /** * @fn bool OpenGLRendererAPI::CheckFullScreen(const int& width, const int& height) override; * * @brief Check full screen * * @author <NAME> * @date 7/09/2021 * * @param width The width. * @param height The height. * * @returns True if it succeeds, false if it fails. */ bool CheckFullScreen(const int& width, const int& height) override; /** * @fn void OpenGLRendererAPI::SetCullMode(const CullMode& mode) override; * * @brief Sets cull mode * * @author <NAME> * @date 7/09/2021 * * @param mode The mode. */ void SetCullMode(const CullMode& mode) override; /** * @fn void OpenGLRendererAPI::SetDepthMask(const bool& enabled) override; * * @brief Sets depth mask * * @author <NAME> * @date 7/09/2021 * * @param enabled True to enable, false to disable. */ void SetDepthMask(const bool& enabled) override; /** * @fn void OpenGLRendererAPI::SetDepthFunc(const DepthFunc& func) override; * * @brief Sets depth function * * @author <NAME> * @date 7/09/2021 * * @param func The function. */ void SetDepthFunc(const DepthFunc& func) override; protected: /** * @fn void OpenGLRendererAPI::ModeFromDrawMode(const DrawMode& mode) override; * * @brief Gets a API specific value based on provided Enum Mode. * * @note This is a protected function as it is intended to be implemented per API but not accessed externally. * * @author <NAME> * @date 7/09/2021 * * @param mode The mode enum. * @return The API specific enum int value. */ int ModeFromDrawMode(const DrawMode& mode) override; }; }
jjpolaczek/QuickestFlow
src/GraphPerf.h
<filename>src/GraphPerf.h #pragma once #include "Generator.h" #include "QFSolver.h" #include <ctime> #include <vector> //! Performance Monitor Class /*! Class for measuring the Quickest flow algorithm performance */ class PerformanceMonitor { public: PerformanceMonitor() {} //! Measure /*! Measure time needed for solving a sampleCount quickest flow problems in a flow network with graphSize ammount of nodes and average the time needed */ double Measure(int graphSize, int sampleCount); };
jjpolaczek/QuickestFlow
src/QFSolver.h
<reponame>jjpolaczek/QuickestFlow<filename>src/QFSolver.h #pragma once #include <lemon\concepts\graph.h> #include <lemon\concepts\maps.h> #include <lemon\list_graph.h> #include <lemon\edmonds_karp.h> #include <iostream> #include <fstream> //! Quickest Flow Solver class /*! Class for solving the quickest flow problem. Typical workflow consists of calling LoadGraph() on a graph file followed by Solve() and SaveResults() */ class QFSolver { public: QFSolver() : baseGraph_(nullptr), speedMap_(nullptr), capacityMap_(nullptr), teGraph_(nullptr), teMap_(nullptr), flowMap_(nullptr), initialized_(false), horizon_(0), sourceID_(-1), targetID_(-1), flowValue_(0), maxCapacity_(0), maxDelay_(0) { } ~QFSolver() { if (baseGraph_ != nullptr) delete baseGraph_; if (speedMap_ != nullptr) delete speedMap_; if (capacityMap_ != nullptr) delete capacityMap_; if (teGraph_ != nullptr) delete teGraph_; if (teMap_ != nullptr) delete teMap_; if (flowMap_ != nullptr) delete flowMap_; } //! LoadGraph /*! Method loads flow network into class structure from file containing flow network definition named filepath */ void LoadGraph(std::string filepath); //! Solve /*! Method solves Quickest flow problem for previously loaded graph. Throws exception if called without geometry */ void Solve(); //! SaveResults /*! Method saves calculation results in a file specified with filename. */ void SaveResults(std::string filename); private: //! ExpandGrapg /*! Create a time expanded graph for max flow calculation */ void ExpandGraph(unsigned int horizon); //! MaxFlow /*! Calculate Max flow on base flow network loaded from file, Calls ExpandGraph internally */ int MaxFlow(unsigned int horizon); //! MaxFlowMap /*! Variation of MaxFlow, saves the flow map into class structure ( it is dedstroyed in the alternative) */ void MaxFlowMap(unsigned int horizon); lemon::ListDigraph *baseGraph_; lemon::ListDigraph::ArcMap<int> *capacityMap_; lemon::ListDigraph::ArcMap<int> *speedMap_; lemon::ListDigraph *teGraph_; lemon::ListDigraph::ArcMap<int> *teMap_; lemon::ListDigraph::ArcMap<int> *flowMap_; bool initialized_; int horizon_; int sourceID_; int targetID_; int flowValue_; int maxCapacity_; int maxDelay_; int unitsSent_; int timeUsed_; };
jjpolaczek/QuickestFlow
LEMON/include/lemon/config.h
<reponame>jjpolaczek/QuickestFlow #define LEMON_VERSION "1.3.1" #define LEMON_HAVE_LONG_LONG 1 #define LEMON_HAVE_LP 1 #define LEMON_HAVE_MIP 1 #define LEMON_HAVE_GLPK 1 /* #undef LEMON_HAVE_CPLEX */ /* #undef LEMON_HAVE_SOPLEX */ /* #undef LEMON_HAVE_CLP */ /* #undef LEMON_HAVE_CBC */ #define _LEMON_CPLEX 1 #define _LEMON_CLP 2 #define _LEMON_GLPK 3 #define _LEMON_SOPLEX 4 #define _LEMON_CBC 5 #define LEMON_DEFAULT_LP _LEMON_GLPK #define LEMON_DEFAULT_MIP _LEMON_GLPK /* #undef LEMON_USE_PTHREAD */ #define LEMON_USE_WIN32_THREADS 1
jjpolaczek/QuickestFlow
src/Generator.h
#pragma once #include <lemon\concepts\graph.h> #include <lemon\concepts\maps.h> #include <lemon\list_graph.h> #include <lemon\euler.h> #include <iostream> #include <fstream> #include <random> //! Flow network generator /*! Class encapsulating flow network generation method */ class GraphGenerator { public: GraphGenerator() { } //! Generate /*! Crates and saves a file named filename containing random graph with nodeCount ammount of nodes */ void Generate(std::string filename, int NodeCount); };
google/cpp-from-the-sky-down
meta_struct_20/cppcon_version/meta_struct.h
#pragma once #include <algorithm> #include <cstddef> #include <optional> #include <string_view> #include <type_traits> namespace ftsd { namespace internal_meta_struct { struct no_init_fixed_string {}; template <std::size_t N> struct fixed_string { constexpr fixed_string(const char (&foo)[N + 1]) { std::copy_n(foo, N + 1, data); } constexpr static auto from_string_view(std::string_view s) { fixed_string<N> fs{no_init_fixed_string{}}; std::copy(s.begin(), s.end(), fs.data); return fs; } constexpr std::string_view sv() const { return std::string_view(data); } auto operator<=>(const fixed_string&) const = default; char data[N + 1] = {}; constexpr fixed_string(no_init_fixed_string) : data{} {}; constexpr std::size_t size()const { return N; } }; template <std::size_t N> fixed_string(const char (&str)[N]) -> fixed_string<N - 1>; template <fixed_string Tag, typename T> struct tag_and_value { T value; }; template <typename... Members> struct meta_struct_impl; template <typename... Members> struct meta_struct; template <typename... Members> meta_struct(Members...) -> meta_struct<Members...>; template <> struct meta_struct_impl<> {}; template <> struct meta_struct<>:meta_struct_impl<> {}; struct no_conversion {}; template <typename... TagsAndValues> struct parms : TagsAndValues... { constexpr operator no_conversion() const { return no_conversion{}; } }; template <typename... TagsAndValues> parms(TagsAndValues...) -> parms<TagsAndValues...>; template <typename T> struct default_init { constexpr default_init() = default; auto operator<=>(const default_init&) const = default; constexpr auto operator()() const { if constexpr (std::is_default_constructible_v<T>) { return T{}; } } }; template <fixed_string Tag,typename T, typename Self, typename F> constexpr auto call_init(Self&, F& f) requires(requires { { f() } -> std::convertible_to<T>; }) { return f(); } template <fixed_string Tag,typename T, typename Self, typename F> constexpr auto call_init(Self& self, F& f) requires(requires { { f(self) } -> std::convertible_to<T>; }) { return f(self); } template <fixed_string Tag,typename T, typename Self, typename F> constexpr auto call_init(Self& self, F& f) requires(requires { { f() } -> std::same_as<void>; }) { static_assert(!std::is_same_v<decltype(f()), void>, "Required argument not specified"); } inline constexpr auto required = [] {}; template <fixed_string Tag, typename T, auto Init = default_init<T>(), meta_struct Attributes = {}> struct member { constexpr static auto tag() { return Tag; } constexpr static auto init() { return Init; } constexpr static auto attributes() { return Attributes; } using element_type = T; T value; template <typename Self, typename OtherT> constexpr member(Self&, tag_and_value<Tag, OtherT> tv) : value(std::move(tv.value)) {} template <typename Self> constexpr member(Self& self, no_conversion) : value(call_init<Tag,T>(self, Init)) {} template <typename Self> constexpr member(Self& self, tag_and_value<Tag, std::optional<std::remove_reference_t<T>>> tv_or) requires(!std::is_reference_v<T>) : value(tv_or.value.has_value() ? std::move(*tv_or.value) : call_init<Tag,T>(self, Init)) {} template <typename Self, typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member( Self&, const member<Tag, OtherT, OtherInit, OtherAttributes>& other) : value(other.value) {} template <typename Self, typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member( Self&, member<Tag, OtherT, OtherInit, OtherAttributes>&& other) : value(std::move(other.value)) {} template <typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member& operator=( const member<Tag, OtherT, OtherInit, OtherAttributes>& other) { value = other.value; return *this; } template <typename OtherT, auto OtherInit, auto OtherAttributes> requires(std::is_convertible_v<OtherT, T>) constexpr member& operator=( member<Tag, OtherT, OtherInit, OtherAttributes>&& other) { value = std::move(other.value); return *this; } constexpr member(member&&) = default; constexpr member(const member&) = default; constexpr member& operator=(member&&) = default; constexpr member& operator=(const member&) = default; auto operator<=>(const member&) const = default; }; template <typename... Members> struct meta_struct_impl<Members...> : Members... { template <typename... Args> constexpr meta_struct_impl(parms<Args...> p) : Members(*this, std::move(p))... {} constexpr meta_struct_impl() : Members(*this, no_conversion{})... {} constexpr meta_struct_impl(meta_struct_impl&&) = default; constexpr meta_struct_impl(const meta_struct_impl&) = default; constexpr meta_struct_impl& operator=(meta_struct_impl&&) = default; constexpr meta_struct_impl& operator=(const meta_struct_impl&) = default; template <typename... OtherMembers> constexpr meta_struct_impl(meta_struct_impl<OtherMembers...>&& other) : Members(*this, std::move(other))... {}; template <typename... OtherMembers> constexpr meta_struct_impl(const meta_struct_impl<OtherMembers...>& other) : Members(*this, other)... {}; template <typename... OtherMembers> constexpr meta_struct_impl& operator=( meta_struct_impl<OtherMembers...>&& other) { ((static_cast<Members&>(*this) = std::move(other)), ...); return *this; }; template <typename... OtherMembers> constexpr meta_struct_impl& operator=( const meta_struct_impl<OtherMembers...>& other) { ((static_cast<Members&>(*this) = other), ...); return *this; }; constexpr operator no_conversion() const { return no_conversion{}; } auto operator<=>(const meta_struct_impl&) const = default; }; template <typename... Members> struct meta_struct : meta_struct_impl<Members...> { using super = meta_struct_impl<Members...>; template <typename... TagsAndValues> constexpr meta_struct(TagsAndValues... tags_and_values) : super(parms(std::move(tags_and_values)...)) {} constexpr meta_struct() = default; constexpr meta_struct(meta_struct&&) = default; constexpr meta_struct(const meta_struct&) = default; constexpr meta_struct& operator=(meta_struct&&) = default; constexpr meta_struct& operator=(const meta_struct&) = default; template <typename... OtherMembers> constexpr meta_struct(meta_struct<OtherMembers...>&& other) : super(std::move(other)) {} template <typename... OtherMembers> constexpr meta_struct(const meta_struct<OtherMembers...>& other) : super(other) {} template <typename... OtherMembers> constexpr meta_struct& operator=(meta_struct<OtherMembers...>&& other) { static_cast<super&>(*this) = std::move(other); return *this; } template <typename... OtherMembers> constexpr meta_struct& operator=(const meta_struct<OtherMembers...>& other) { static_cast<super&>(*this) = other; return *this; } auto operator<=>(const meta_struct&) const = default; }; template <fixed_string Tag> struct arg_type { template <typename T> constexpr auto operator=(T t) const { return member<Tag, T>(*this, tag_and_value<Tag, T>(std::move(t))); } }; template <fixed_string Tag> inline constexpr auto arg = arg_type<Tag>{}; template <typename F, typename... Members> constexpr decltype(auto) meta_struct_apply(F&& f, meta_struct_impl<Members...>& m) { return std::forward<F>(f)(static_cast<Members&>(m)...); } template <typename F, typename... Members> constexpr decltype(auto) meta_struct_apply( F&& f, const meta_struct_impl<Members...>& m) { return std::forward<F>(f)(static_cast<const Members&>(m)...); } template <typename F, typename... Members> constexpr decltype(auto) meta_struct_apply(F&& f, meta_struct_impl<Members...>&& m) { return std::forward<F>(f)(static_cast<Members&&>(m)...); } template <typename MetaStructImpl> struct apply_static_impl; template <typename... Members> struct apply_static_impl<meta_struct_impl<Members...>> { template <typename F> constexpr static decltype(auto) apply(F&& f) { return f(static_cast<Members*>(nullptr)...); } }; template <typename MetaStruct, typename F> constexpr auto meta_struct_apply(F&& f) { return apply_static_impl<typename MetaStruct::super>::apply( std::forward<F>(f)); } template <typename MetaStruct, typename F> constexpr void meta_struct_for_each(F&& f,MetaStruct&& ms) { meta_struct_apply( [&](auto&... m) mutable { (std::forward<F>(f)(m), ...); }, std::forward<MetaStruct>(ms)); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr decltype(auto) get_impl(member<tag, T, Init, Attributes>& m) { return (m.value); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr decltype(auto) get_impl(const member<tag, T, Init, Attributes>& m) { return (m.value); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr decltype(auto) get_impl(member<tag, T, Init, Attributes>&& m) { return std::move(m.value); } template <fixed_string tag, typename MetaStruct> constexpr decltype(auto) get(MetaStruct&& s) { return get_impl<tag>(std::forward<MetaStruct>(s)); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr member<tag, T, Init, Attributes> get_member_impl( const member<tag, T, Init, Attributes>& m); template <fixed_string Tag, typename MetaStruct> constexpr auto get_attributes(MetaStruct&& s) { return decltype(get_member_impl(s))::attributes(); } template <fixed_string Tag, typename MetaStruct> constexpr auto get_attributes() { return decltype(get_member_impl<Tag>( std::declval<MetaStruct&>()))::attributes(); } template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr std::true_type has_impl(const member<tag, T, Init, Attributes>&); template <fixed_string tag, typename T, auto Init, auto Attributes> constexpr std::false_type has_impl(no_conversion); template <fixed_string tag, typename MetaStruct> constexpr bool has(MetaStruct&& s) { return decltype(has_impl<tag>(s))::value; } template <fixed_string tag, typename MetaStruct> constexpr bool has() { return decltype(has_impl<tag>(std::declval<MetaStruct&>()))::value; } template <typename... Members> constexpr std::size_t meta_struct_size_impl(const meta_struct<Members...>*) { return sizeof...(Members); } template <typename... Members> constexpr std::size_t meta_struct_size(const meta_struct<Members...>&) { return sizeof...(Members); } template <typename MetaStruct> constexpr std::size_t meta_struct_size() { return meta_struct_size_impl(static_cast<const MetaStruct*>(nullptr)); } } // namespace internal_meta_struct using internal_meta_struct::arg; using internal_meta_struct::fixed_string; using internal_meta_struct::get; using internal_meta_struct::get_attributes; using internal_meta_struct::has; using internal_meta_struct::member; using internal_meta_struct::meta_struct; using internal_meta_struct::meta_struct_apply; using internal_meta_struct::meta_struct_size; using internal_meta_struct::required; using internal_meta_struct::default_init; } // namespace ftsd
google/cpp-from-the-sky-down
cpp20_tagged_tuple/tagged_tuple.h
<filename>cpp20_tagged_tuple/tagged_tuple.h #pragma once #include <algorithm> #include <array> #include <cstdint> #include <optional> #include <string_view> #include <tuple> #include <utility> namespace ftsd { namespace internal_tagged_tuple { template <std::size_t N> struct fixed_string { constexpr fixed_string(const char (&foo)[N + 1]) { std::copy_n(foo, N + 1, data); } constexpr fixed_string(std::string_view s) { std::copy_n(s.data(), N, data); }; auto operator<=>(const fixed_string&) const = default; char data[N + 1] = {}; constexpr std::string_view sv() const { return std::string_view(&data[0], N); } constexpr std::size_t size() const { return N; } constexpr auto operator[](std::size_t i) const { return data[i]; } }; template <std::size_t N> fixed_string(const char (&str)[N]) -> fixed_string<N - 1>; template <std::size_t N> fixed_string(fixed_string<N>) -> fixed_string<N>; template <typename Member> constexpr auto member_tag() { return Member::fs.sv(); } template <typename T> struct type_to_type { using type = T; }; template <typename... Members> struct tagged_tuple; template <typename S, typename M> struct chop_to_helper; template <typename... Members, typename M> struct chop_to_helper<tagged_tuple<Members...>, M> { template <fixed_string fs> static constexpr std::size_t find_index() { std::array<std::string_view, sizeof...(Members)> ar{ member_tag<Members>()...}; for (std::size_t i = 0; i < ar.size(); ++i) { if (ar[i] == fs.sv()) return i; } } static constexpr std::size_t index = find_index<M::fs>(); decltype(std::make_index_sequence<index>()) sequence; using member_tuple = std::tuple<Members...>; template <std::size_t... I> static constexpr auto chop(std::index_sequence<I...>) { return type_to_type< tagged_tuple<std::tuple_element_t<I, member_tuple>...>>{}; } using type = typename decltype(chop(sequence))::type; }; template <typename S, typename M> using chopped = typename chop_to_helper<S, M>::type; template <typename T> struct default_init_impl { static constexpr auto init() { if constexpr (std::is_default_constructible_v<T>) return T{}; } }; template <typename T> struct default_init_impl<T&> { static constexpr void init() {} }; template <typename T> constexpr auto default_init = []() { return default_init_impl<T>::init(); }; struct dummy_conversion {}; struct no_conversion { no_conversion() = delete; no_conversion(const no_conversion&) = delete; no_conversion& operator=(const no_conversion&) = delete; }; template <typename T> struct optional_no_ref { using type = std::optional<T>; }; template <typename T> struct optional_no_ref<T&> { using type = no_conversion; }; template <typename T> using optional_no_ref_t = typename optional_no_ref<T>::type; template <typename Tag, typename T, auto Init = default_init<T>> struct member_impl { static constexpr decltype(Init) init = Init; T value_; template <typename Self> constexpr member_impl(Self& self, dummy_conversion) requires requires { { Init() } -> std::convertible_to<T>; } : value_(Init()) { } static constexpr bool has_default_init() requires requires { { Init() } -> std::same_as<void>; } { return false; } static constexpr bool has_default_init() { return true; } using optional_type = optional_no_ref_t<T>; template <typename Self, typename U> constexpr member_impl(Self& self, U value_or) requires std::same_as<U, optional_type> && requires { { Init() } -> std::convertible_to<T>; } : value_(value_or.has_value() ? std::move(*value_or) : Init()) { } template <typename Self> constexpr member_impl(Self& self, dummy_conversion) requires requires { { Init() } -> std::same_as<void>; } { static_assert(!std::is_same_v<decltype(Init()), void>, "Missing required argument."); } template <typename Self> constexpr member_impl(Self& self, dummy_conversion) requires requires { { Init(self) } -> std::convertible_to<T>; } : value_(Init(self)) { } template <typename Self, typename U> constexpr member_impl(Self& self, U value_or) requires std::same_as<U, optional_type> && requires { { Init(self) } -> std::convertible_to<T>; } : value_(value_or.has_value() ? std::move(*value_or) : Init(self)) { } constexpr member_impl(T value) requires(!std::is_reference_v<T>) : value_(std::move(value)) {} constexpr member_impl(T value) requires(std::is_reference_v<T>) : value_(value) {} template <typename Self> constexpr member_impl(Self&, T value) requires(!std::is_reference_v<T>) : value_(std::move(value)) {} template <typename Self> constexpr member_impl(Self&, T value) requires(std::is_reference_v<T>) : value_(value) {} constexpr member_impl() requires requires { { Init() } -> std::convertible_to<T>; } : value_(Init()) { } template <typename Self> constexpr member_impl(Self& self) requires requires { { Init(self) } -> std::convertible_to<T>; } : value_(Init(self)) { } constexpr member_impl(const member_impl&) = default; constexpr member_impl& operator=(const member_impl&) = default; constexpr member_impl(member_impl&&) = default; constexpr member_impl& operator=(member_impl&&) = default; template <typename Self, typename OtherT, auto OtherInit> constexpr member_impl(Self& self, const member_impl<Tag, OtherT, OtherInit>& other) : member_impl(self, other.value_) {} template <typename Self, typename OtherT, auto OtherInit> constexpr member_impl(Self& self, member_impl<Tag, OtherT, OtherInit>& other) : member_impl(self, other.value_) {} template <typename Self, typename OtherT, auto OtherInit> constexpr member_impl(Self& self, member_impl<Tag, OtherT, OtherInit>&& other) : member_impl(self, std::move(other.value_)){}; template <typename OtherT, auto OtherInit> constexpr member_impl& operator=( const member_impl<Tag, OtherT, OtherInit>& other) { value_ = other.value_; return *this; } template <typename OtherT, auto OtherInit> constexpr member_impl& operator=( member_impl<Tag, OtherT, OtherInit>&& other) { value_ = std::move(other.value_); return *this; }; constexpr auto operator<=>(const member_impl&) const = default; using tag_type = Tag; using value_type = T; static constexpr std::string_view key() { return Tag::value.sv(); } static constexpr auto fixed_key() { return Tag::value; } constexpr value_type& value() & { return value_; } constexpr value_type&& value() && { return std::move(value_); } constexpr const value_type& value() const& { return value_; } constexpr const value_type&& value() const&& { return std::move(value_); } }; template <fixed_string fs> struct tuple_tag { static constexpr decltype(fs) value = fs; static constexpr bool ftsd_is_tuple_tag_type = true; template <typename T> constexpr auto operator=(T t) const { return member_impl<tuple_tag<fixed_string<fs.size()>(fs)>, T>{std::move(t)}; } template <typename T> constexpr decltype(auto) operator()(T&& t) const { return get<fs>(std::forward<T>(t)); } }; template <typename T> struct is_tuple_tag : std::false_type {}; template <typename T> requires requires { {T::ftsd_is_tuple_tag_type}; } struct is_tuple_tag<T> : std::true_type {}; template <typename T> constexpr bool is_tuple_tag_v = is_tuple_tag<T>::value; struct auto_; template <typename Self, typename T, auto Init> struct t_or_auto { using type = T; }; template <typename Self, auto Init> requires requires { {Init()}; } struct t_or_auto<Self, auto_, Init> { using type = decltype(Init()); }; template <typename Self, typename T, auto Init> requires requires { { Init(std::declval<Self&>()) } -> std::convertible_to<T>; } struct t_or_auto<Self, T, Init> { using type = decltype(Init(std::declval<Self&>())); }; template <typename Self, auto Init> requires requires { {Init(std::declval<Self&>())}; } struct t_or_auto<Self, auto_, Init> { using type = decltype(Init(std::declval<Self&>())); }; template <typename Self, typename T, auto Init> using t_or_auto_t = typename t_or_auto<Self, T, Init>::type; template <fixed_string Fs, typename T, auto Init = default_init<T>> struct member { using type = T; using fs_type = decltype(Fs); static constexpr fs_type fs = Fs; static constexpr decltype(Init) init = Init; }; template <typename Self, typename Member> struct member_to_impl { using type = member_impl<tuple_tag<fixed_string<Member::fs.size()>(Member::fs)>, typename t_or_auto<chopped<Self, Member>, typename Member::type, Member::init>::type, Member::init>; }; template <typename Self, typename Member> using member_to_impl_t = typename member_to_impl<Self, Member>::type; template <typename Tag, typename T> constexpr auto make_member_impl(T t) { return member_impl<Tag, T>{std::move(t)}; } template <typename... Members> struct parameters : Members... { constexpr operator dummy_conversion() { return {}; } }; template <typename... Members> parameters(Members&&...) -> parameters<std::decay_t<Members>...>; template <typename Self, typename... Members> struct tagged_tuple_base : member_to_impl_t<Self, Members>... { template <typename... Args> constexpr tagged_tuple_base(Self& self, parameters<Args...> p) : member_to_impl_t<Self, Members>{self, p}... {} template <typename OtherSelf, typename... OtherMembers> constexpr tagged_tuple_base( tagged_tuple_base<OtherSelf, OtherMembers...>& other) : member_to_impl_t<Self, Members>{ other, static_cast<member_to_impl_t<OtherSelf, OtherMembers>&>( other)}... {} template <typename OtherSelf, typename... OtherMembers> constexpr tagged_tuple_base( const tagged_tuple_base<OtherSelf, OtherMembers...>& other) : member_to_impl_t<Self, Members>{ other, static_cast<const member_to_impl_t<OtherSelf, OtherMembers>&>( other)}... {} constexpr tagged_tuple_base(const tagged_tuple_base&) = default; constexpr tagged_tuple_base& operator=(const tagged_tuple_base&) = default; constexpr tagged_tuple_base(tagged_tuple_base&&) = default; constexpr tagged_tuple_base& operator=(tagged_tuple_base&&) = default; constexpr auto operator<=>(const tagged_tuple_base&) const = default; template <typename F> constexpr static auto apply_static(F&& f) { return f(static_cast<member_to_impl_t<Self, Members>*>(nullptr)...); } template <typename F> constexpr auto apply(F&& f) & { return f(static_cast<member_to_impl_t<Self, Members>&>(*this)...); } template <typename F> constexpr auto apply(F&& f) const& { return f(static_cast<const member_to_impl_t<Self, Members>&>(*this)...); } template <typename F> constexpr auto apply(F&& f) && { return f(static_cast<member_to_impl_t<Self, Members>&&>(*this)...); } template <typename F> constexpr void for_each(F&& f) & { auto functor = [&](auto&&... a) mutable { (f(std::forward<decltype(a)>(a)), ...); }; apply(functor); } template <typename F> constexpr void for_each(F&& f) const& { auto functor = [&](auto&&... a) mutable { (f(std::forward<decltype(a)>(a)), ...); }; apply(functor); } template <typename F> constexpr void for_each(F&& f) && { auto functor = [&f](auto&&... a) mutable { (f(std::forward<decltype(a)>(a)), ...); }; apply(functor); } static constexpr auto size() { return sizeof...(Members); } }; template <typename Tag, typename T, auto Init> constexpr decltype(auto) get_impl(member_impl<Tag, T, Init>& m) { return (m.value()); } template <typename Tag, typename T, auto Init> constexpr decltype(auto) get_impl(const member_impl<Tag, T, Init>& m) { return (m.value()); } template <typename Tag, typename T, auto Init> constexpr decltype(auto) get_impl(member_impl<Tag, T, Init>&& m) { return std::move(m.value()); } template <typename Tag, typename T, auto Init> constexpr decltype(auto) get_impl(const member_impl<Tag, T, Init>&& m) { return std::move(m.value()); } template <fixed_string fs, typename S> constexpr decltype(auto) get(S&& s) { return get_impl<tuple_tag<fixed_string<fs.size()>(fs)>>(std::forward<S>(s)); } template <typename... Members> struct tagged_tuple : tagged_tuple_base<tagged_tuple<Members...>, Members...> { using super = tagged_tuple_base<tagged_tuple, Members...>; template <typename... Tag, typename... T, auto... Init> constexpr tagged_tuple(member_impl<Tag, T, Init>... args) : super(*this, parameters{std::move(args)...}) {} constexpr tagged_tuple() : super(*this, parameters{}) {} template <typename... OtherMembers> constexpr tagged_tuple(tagged_tuple<OtherMembers...>& other) : super(other) {} template <typename... OtherMembers> constexpr tagged_tuple(const tagged_tuple<OtherMembers...>& other) : super(other) {} constexpr tagged_tuple(const tagged_tuple& other) = default; constexpr tagged_tuple& operator=(const tagged_tuple&) = default; constexpr tagged_tuple(tagged_tuple&&) = default; constexpr tagged_tuple& operator=(tagged_tuple&& other) = default; template <typename Tag> constexpr auto& operator[](Tag) { return get<Tag::value>(*this); } template <typename Tag> constexpr auto& operator[](Tag) const { return get<Tag::value>(*this); } }; template <typename Tag, typename T, auto Init> T tagged_tuple_value_type_impl(member_impl<Tag, T, Init>&); // A lambda passed to a template must be stateless and default constructible // anyway. template <typename Tag, typename T, auto Init> decltype(Init) tagged_tuple_init_impl(member_impl<Tag, T, Init>&); template <fixed_string fs, typename Tuple> using tagged_tuple_value_type_t = decltype(tagged_tuple_value_type_impl<tuple_tag<fs>> (std::declval<Tuple&>())); template <fixed_string fs, typename Tuple> inline constexpr auto tagged_tuple_init_v = decltype(tagged_tuple_init_impl<tuple_tag<fs>>(std::declval<Tuple&>())){}; template <typename Member> struct member_impl_to_member { using tag_t = typename Member::tag_type; static constexpr decltype(Member::init) init = Member::init; static constexpr fixed_string<tag_t::value.size()> fs{tag_t::value.sv()}; using type = member<fs, typename Member::value_type, init>; }; template <typename T> using member_impl_to_member_t = typename member_impl_to_member<T>::type; template <typename... Tag, typename... T, auto... Init> tagged_tuple(member_impl<Tag, T, Init>...) -> tagged_tuple<member_impl_to_member_t<member_impl<Tag, T, Init>>...>; template <typename TaggedTuple> struct tagged_tuple_ref; template <auto... Tags, typename... T, auto... Init> struct tagged_tuple_ref<tagged_tuple<member<Tags, T, Init>...>> { using Self = tagged_tuple<member<Tags, T, Init>...>; using type = tagged_tuple<member< Tags, std::add_lvalue_reference_t<typename t_or_auto<Self, T, Init>::type>, Init>...>; }; template <auto... Tags, typename... T, auto... Init> struct tagged_tuple_ref<const tagged_tuple<member<Tags, T, Init>...>> { using Self = tagged_tuple<member<Tags, T, Init>...>; using type = tagged_tuple<member<Tags, std::add_lvalue_reference_t<std::add_const_t< typename t_or_auto<Self, T, Init>::type>>, Init>...>; }; template <typename TaggedTuple> using tagged_tuple_ref_t = typename tagged_tuple_ref<TaggedTuple>::type; template <fixed_string fs> inline constexpr auto tag = tuple_tag<fixed_string<fs.size()>(fs)>{}; enum class tag_comparison { eq, ne, lt, gt, le, ge }; template <typename TagOrValue1, typename TagOrValue2, tag_comparison comparison> struct tag_comparator_predicate { template <typename Value, typename TS> constexpr static const auto& get_value_for_comparison(const Value& value, const TS&) { return value; } template <typename Tag, typename TS> requires is_tuple_tag_v<Tag> constexpr static const auto& get_value_for_comparison(const Tag& tag, const TS& ts) { return tag(ts); } TagOrValue1 tag_or_value1; TagOrValue2 tag_or_value2; template <typename TS> bool operator()(const TS& ts) const { const auto& a = get_value_for_comparison(tag_or_value1, ts); const auto& b = get_value_for_comparison(tag_or_value2, ts); if constexpr (comparison == tag_comparison::eq) { return a == b; } if constexpr (comparison == tag_comparison::ne) { return a != b; } if constexpr (comparison == tag_comparison::lt) { return a < b; } if constexpr (comparison == tag_comparison::gt) { return a > b; } if constexpr (comparison == tag_comparison::le) { return a <= b; } if constexpr (comparison == tag_comparison::ge) { return a >= b; } } }; template <tag_comparison comparison, typename T1, typename T2> constexpr auto make_tag_comparator_predicate(T1 a, T2 b) { return tag_comparator_predicate<T1, T2, comparison>{std::move(a), std::move(b)}; } namespace tag_relops { // Compare two tags template <typename A, typename B> requires is_tuple_tag_v<A> || is_tuple_tag_v<B> constexpr auto operator==(A a, B b) { return make_tag_comparator_predicate<tag_comparison::eq>(a, b); } template <typename A, typename B> requires is_tuple_tag_v<A> || is_tuple_tag_v<B> constexpr auto operator!=(A a, B b) { return make_tag_comparator_predicate<tag_comparison::ne>(a, b); } template <typename A, typename B> requires is_tuple_tag_v<A> || is_tuple_tag_v<B> constexpr auto operator<=(A a, B b) { return make_tag_comparator_predicate<tag_comparison::le>(a, b); } template <typename A, typename B> requires is_tuple_tag_v<A> || is_tuple_tag_v<B> constexpr auto operator>=(A a, B b) { return make_tag_comparator_predicate<tag_comparison::ge>(a, b); } template <typename A, typename B> requires is_tuple_tag_v<A> || is_tuple_tag_v<B> constexpr auto operator<(A a, B b) { return make_tag_comparator_predicate<tag_comparison::lt>(a, b); } template <typename A, typename B> requires is_tuple_tag_v<A> || is_tuple_tag_v<B> constexpr auto operator>(A a, B b) { return make_tag_comparator_predicate<tag_comparison::gt>(a, b); } } // namespace tag_relops } // namespace internal_tagged_tuple using internal_tagged_tuple::auto_; using internal_tagged_tuple::get; using internal_tagged_tuple::member; using internal_tagged_tuple::tag; using internal_tagged_tuple::tagged_tuple; using internal_tagged_tuple::tagged_tuple_init_v; using internal_tagged_tuple::tagged_tuple_ref_t; using internal_tagged_tuple::tagged_tuple_value_type_t; namespace tag_relops = internal_tagged_tuple::tag_relops; namespace literals { template < internal_tagged_tuple::fixed_string fs> // placeholder type for deduction constexpr auto operator""_tag() { return tag<fs>; } } // namespace literals } // namespace ftsd
google/cpp-from-the-sky-down
tagged_tuple/tagged_tuple.h
<reponame>google/cpp-from-the-sky-down // Copyright 2019 Google LLC // // 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 // // https://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. #pragma once #include <initializer_list> #include <ostream> #include <type_traits> #include <utility> #include "../simple_type_name/simple_type_name.h" namespace skydown { template <typename Tag, typename T> struct member { T value; static constexpr std::string_view tag_name = skydown::short_type_name<Tag>; using tag_type = Tag; using value_type = T; }; template <typename Tag, typename T> auto make_member(T t) { return member<Tag, T>{std::move(t)}; } template <typename... Members> struct tagged_tuple : Members... {}; template <typename... Members> tagged_tuple(Members...) -> tagged_tuple<Members...>; namespace detail { template <typename Tag, typename T> T element_type_helper(member<Tag, T> m); } template <typename Tag, typename TTuple> using element_type_t = decltype(detail::element_type_helper<Tag>(std::declval<TTuple>())); template <typename Tag, typename T> decltype(auto) get(member<Tag, T> &m) { return (m.value); } template <typename Tag, typename T> decltype(auto) get(const member<Tag, T> &m) { return (m.value); } template <typename Tag, typename T> decltype(auto) get(member<Tag, T> &&m) { return std::move(m.value); } template <typename Tag, typename T> decltype(auto) get(const member<Tag, T> &&m) { return std::move(m.value); } namespace skydown_tagged_tuple_internal { template <typename Tag> struct tag_function_type { template <typename T> decltype(auto) operator()(T &&t) const { return get<Tag>(std::forward<T>(t)); } template <typename V> auto operator=(V &&v) const { return make_member<Tag>(std::forward<V>(v)); } }; template<typename T> struct tuple_size_helper; template<typename... Members> struct tuple_size_helper<tagged_tuple<Members...>>:public std::integral_constant<int,sizeof...(Members)>{}; } // namespace skydown_tagged_tuple_internal template <typename Tag> inline constexpr skydown_tagged_tuple_internal::tag_function_type<Tag> tag = {}; template <typename... Members> constexpr auto tuple_size(const tagged_tuple<Members...> &) { return sizeof...(Members); } template<typename T> inline constexpr auto tuple_size_v = skydown_tagged_tuple_internal::tuple_size_helper<std::decay_t<T>>::value; template <typename... Members, typename... OtherMembers> auto append(tagged_tuple<Members...> t, OtherMembers... m) { return tagged_tuple<Members..., OtherMembers...>{ std::move(static_cast<Members &>(t))..., std::move(m)...}; } template <typename... Members, typename... OtherMembers> auto operator|(tagged_tuple<Members...> t, tagged_tuple<OtherMembers...> m) { return tagged_tuple<Members..., OtherMembers...>{ static_cast<Members &&>(t)..., static_cast<OtherMembers &&>(m)...}; } template <typename... Members, typename F> void for_each(const tagged_tuple<Members...> &m, F f) { (f(static_cast<const Members &>(m)), ...); } template <typename... Members, typename F> void for_each(tagged_tuple<Members...> &m, F f) { (f(static_cast<Members &>(m)), ...); } template <typename... Members, typename F> decltype(auto) apply(const tagged_tuple<Members...> &m, F f) { return (f(static_cast<const Members &>(m)...)); } template <typename... Members, typename F> decltype(auto) apply(tagged_tuple<Members...> &m, F f) { return (f(static_cast<Members &>(m)...)); } namespace detail { template <typename Tag, typename T> std::true_type test_has_tag(const member<Tag, T> &); template <typename Tag> std::false_type test_has_tag(...); struct remove_member_tag {}; } // namespace detail template <typename Tag, typename Tuple> constexpr bool has_tag = decltype(detail::test_has_tag<Tag>(std::declval<Tuple>()))::value; template <typename Tag> inline constexpr auto remove_tag = member<Tag,detail::remove_member_tag>{}; template <typename T1, typename T2> auto merge(const T1 &, T2 t2) { return t2; } namespace skydown_merge_detail { template <typename T> struct empty {}; template <typename... Types> struct typelist : empty<Types>... {}; template <typename T> std::true_type typelist_has_impl(empty<T>); template <typename T> std::false_type typelist_has_impl(...); template <typename List, typename T> constexpr bool typelist_has = decltype(typelist_has_impl<T>(List{}))::value; template <typename List, typename T, bool has> struct append_maybe { using type = List; }; template <typename... Types, typename T> struct append_maybe<typelist<Types...>, T, false> { using type = typelist<Types..., T>; }; template <typename List, typename T> using append_maybe_t = typename append_maybe<List, T, typelist_has<List, T>>::type; template <typename List, typename... T> struct append_helper; template <typename List, typename First, typename... Rest> struct append_helper<List, First, Rest...> { using type = typename append_helper<append_maybe_t<List, First>, Rest...>::type; }; template <typename List> struct append_helper<List> { using type = List; }; template <typename List, typename... T> using append_helper_t = typename append_helper<List, T...>::type; template <typename List1, typename List2> struct typelist_union; template <typename... Types1, typename... Types2> struct typelist_union<typelist<Types1...>, typelist<Types2...>> { using type = append_helper_t<typelist<>, Types1..., Types2...>; }; template <typename List1, typename List2> using typelist_union_t = typename typelist_union<List1, List2>::type; template <typename M> using tag_t = typename M::tag_type; template <typename TTuple> struct tagged_tuple_to_typelist; template <typename... M> struct tagged_tuple_to_typelist<tagged_tuple<M...>> { using type = typelist<tag_t<M>...>; }; template <typename TT> using tagged_tuple_to_typelist_t = typename tagged_tuple_to_typelist<TT>::type; template <typename Tag, typename TT1, typename TT2> auto get_element(const TT1 &a, const TT2 &b) { using tl1 = tagged_tuple_to_typelist_t<TT1>; using tl2 = tagged_tuple_to_typelist_t<TT2>; static_assert(typelist_has<tl1, Tag> || typelist_has<tl2, Tag>); if constexpr (typelist_has<tl1, Tag> && typelist_has<tl2, Tag>) { if constexpr (std::is_same_v<std::decay_t<decltype(get<Tag>(b))>, detail::remove_member_tag>) { return tagged_tuple{}; } else { return tagged_tuple{make_member<Tag>(merge(get<Tag>(a), get<Tag>(b)))}; } } else if constexpr (typelist_has<tl1, Tag>) { return tagged_tuple{make_member<Tag>(get<Tag>(a))}; } else if constexpr (typelist_has<tl2, Tag>) { return tagged_tuple{make_member<Tag>(get<Tag>(b))}; } } template <typename TT1, typename TT2, typename... Tags> auto merge_helper(const TT1 &a, const TT2 &b, typelist<Tags...>) { return (get_element<Tags>(a, b)|...);; } template <typename TT1, typename TT2> auto merge_helper(const TT1 &a, const TT2 &b) { using tl1 = tagged_tuple_to_typelist_t<TT1>; using tl2 = tagged_tuple_to_typelist_t<TT2>; return merge_helper(a, b, typelist_union_t<tl1, tl2>{}); } } // namespace skydown_merge_detail template <typename... M1, typename... M2> auto merge(tagged_tuple<M1...> t1, tagged_tuple<M2...> t2) { return skydown_merge_detail::merge_helper(t1, t2); } namespace detail { template <typename V> auto has_ostream_op(V &v) -> decltype(std::declval<std::ostream &>() << v); void has_ostream_op(...); } // namespace detail template <typename... Members> std::ostream &operator<<(std::ostream &os, const tagged_tuple<Members...> &t) { os << "{\n"; auto output = [&](auto &v) mutable { if constexpr (!std::is_same_v<void, decltype(detail::has_ostream_op(v.value))>) { os << v.tag_name << " : " << v.value << "\n"; } else { os << v.tag_name << " : " << skydown::short_type_name<decltype(v.value)> << "\n"; } }; for_each(t, output); os << "}\n"; return os; } } // namespace skydown
google/cpp-from-the-sky-down
tagged_sqlite/tagged_sqlite.h
// Copyright 2020 Google LLC // // 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 // // https://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. #pragma once #include <assert.h> #include <sqlite3.h> #include <array> #include <cstdint> #include <iostream> #include <optional> #include <string> #include <string_view> #include <type_traits> #include <utility> #include <exception> #include <memory> namespace skydown { namespace sqlite_experimental { template <typename T, typename... GoodValues> void check_sqlite_return(T r, GoodValues... good_values) { bool success = false; if constexpr (sizeof...(good_values) == 0) { success = (r == SQLITE_OK); } else { success = ((r == good_values) || ...); } if (!success) { std::string err_msg = sqlite3_errstr(r); assert(success); std::cerr << "SQLITE ERROR " << r << " " << err_msg; throw std::runtime_error("sqlite error: " + err_msg); } } inline bool read_row_into(sqlite3_stmt *stmt, int index, std::optional<std::int64_t> &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_INTEGER) { v = sqlite3_column_int64(stmt, index); return true; } else if (type == SQLITE_NULL) { v = std::nullopt; return true; } else { return false; } } inline bool read_row_into(sqlite3_stmt *stmt, int index, std::int64_t &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_INTEGER) { v = sqlite3_column_int64(stmt, index); return true; } else if (type == SQLITE_NULL) { return false; } else { return false; } } inline bool read_row_into(sqlite3_stmt *stmt, int index, std::optional<double> &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_FLOAT) { v = sqlite3_column_double(stmt, index); return true; } else if (type == SQLITE_NULL) { v = std::nullopt; return true; } else { return false; } } inline bool read_row_into(sqlite3_stmt *stmt, int index, double &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_FLOAT) { v = sqlite3_column_double(stmt, index); return true; } else if (type == SQLITE_NULL) { return false; } else { return false; } } inline bool read_row_into(sqlite3_stmt *stmt, int index, std::optional<std::string_view> &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_TEXT) { const char *ptr = reinterpret_cast<const char *>(sqlite3_column_text(stmt, index)); auto size = sqlite3_column_bytes(stmt, index); v = std::string_view(ptr, ptr ? size : 0); return true; } else if (type == SQLITE_NULL) { v = std::nullopt; return true; } else { return false; } } inline bool read_row_into(sqlite3_stmt *stmt, int index, std::string_view &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_TEXT) { const char *ptr = reinterpret_cast<const char *>(sqlite3_column_text(stmt, index)); auto size = sqlite3_column_bytes(stmt, index); v = std::string_view(ptr, ptr ? size : 0); return true; } else if (type == SQLITE_NULL) { return false; } else { return false; } } template <typename RowType> auto read_row(sqlite3_stmt *stmt) { RowType row = {}; std::size_t count = sqlite3_column_count(stmt); auto size = tuple_size(row); assert(size == count); if (size != count) { throw std::runtime_error( "sqlite error: mismatch between read_row and sql columns"); } int index = 0; for_each(row, [&](auto &m) mutable { read_row_into(stmt, index, m.value); ++index; }); return row; } template <typename RowType> struct row_range { RowType row; int last_result = 0; sqlite3_stmt *stmt; row_range(sqlite3_stmt *stmt) : stmt(stmt) { next(); } struct end_type {}; end_type end() { return {}; } void next() { last_result = sqlite3_step(stmt); check_sqlite_return(last_result, SQLITE_DONE, SQLITE_ROW); } struct row_iterator { row_range *p; row_iterator &operator++() { p->next(); return *this; } bool operator!=(end_type) { return p->last_result == SQLITE_ROW; } RowType &operator*() { p->row = read_row<RowType>(p->stmt); return p->row; } }; bool has_error() const { return last_result != SQLITE_ROW && last_result != SQLITE_DONE; } row_iterator begin() { return {this}; } }; inline bool bind_impl(sqlite3_stmt *stmt, int index, double v) { auto r = sqlite3_bind_double(stmt, index, v); return r == SQLITE_OK; } inline bool bind_impl(sqlite3_stmt *stmt, int index, std::int64_t v) { auto r = sqlite3_bind_int64(stmt, index, v); return r == SQLITE_OK; } inline bool bind_impl(sqlite3_stmt *stmt, int index, std::string_view v) { auto r = sqlite3_bind_text(stmt, index, v.data(), static_cast<int>(v.size()), SQLITE_TRANSIENT); return r == SQLITE_OK; } template <typename Tag, typename T> struct member { T value; using tag_type = Tag; using value_type = T; }; template <typename Tag, typename T> auto make_member(T t) { return member<Tag, T>{std::move(t)}; } template <typename... Members> struct tagged_tuple : Members... {}; template <typename... Members> tagged_tuple(Members &&...) -> tagged_tuple<std::decay_t<Members>...>; template <typename... Members> constexpr auto tuple_size(const tagged_tuple<Members...> &) { return sizeof...(Members); } template <typename... Members, typename F> void for_each(const tagged_tuple<Members...> &m, F f) { (f(static_cast<const Members &>(m)), ...); } template <typename... Members, typename F> void for_each(tagged_tuple<Members...> &m, F f) { (f(static_cast<Members &>(m)), ...); } template <typename Tag, typename T> decltype(auto) get(member<Tag, T> &m) { return (m.value); } template <typename Tag, typename T> decltype(auto) get(const member<Tag, T> &m) { return (m.value); } template <typename Tag, typename T> decltype(auto) get(member<Tag, T> &&m) { return std::move(m.value); } template <typename Tag, typename T> decltype(auto) get(const member<Tag, T> &&m) { return std::move(m.value); } template <char... c> struct compile_string {}; template <auto &sv, std::size_t... I> auto to_compile_string_helper(std::index_sequence<I...>) { constexpr auto svp = sv; return compile_string<svp[I]...>{}; } template <auto &sv> constexpr auto to_compile_string() { constexpr auto svp = sv; return to_compile_string_helper<sv>(std::make_index_sequence<svp.size()>()); } template <auto &sv> using compile_string_sv = decltype(to_compile_string<sv>()); template <bool make_optional, typename Tag, typename T> auto maybe_make_optional(member<Tag, T> m) { if constexpr (make_optional) { return member<Tag, std::optional<T>>{}; } else { return m; } } template <typename T> struct string_to_type; template <> struct string_to_type<compile_string<'i', 'n', 't'>> { using type = std::int64_t; }; template <> struct string_to_type<compile_string<'s', 't', 'r', 'i', 'n', 'g'>> { using type = std::string_view; }; template <> struct string_to_type<compile_string<'d', 'o', 'u', 'b', 'l', 'e'>> { using type = double; }; template <typename T> using string_to_type_t = typename string_to_type<T>::type; constexpr std::string_view start_group = "{{"; constexpr std::string_view end_group = "}}"; template <const std::string_view &parm, bool is_parms> constexpr auto get_type_spec_count(std::string_view start_group, std::string_view end_group) { constexpr auto sv = parm; std::size_t count = 0; for (std::size_t i = sv.find(start_group); i != std::string_view::npos;) { if (is_parms == (sv[i + start_group.size()] == '?')) { ++count; } i = sv.find(start_group, i + 1); } return count; } struct type_spec { std::string_view name; std::string_view type; bool optional; constexpr type_spec(std::string_view n, std::string_view t, bool o) : name(n), type(t), optional(o) {} constexpr type_spec() : name(), type(), optional(false) {} }; constexpr type_spec parse_type_spec(std::string_view sv) { auto colon = sv.find(":"); auto name = sv.substr(0, colon); bool optional = sv[sv.size() - 1] == '?' ? true : false; auto last_colon = sv.find_last_of(':'); auto size = sv.size(); auto new_size = size - (optional ? 2 : 1); std::string_view type_str = sv.substr(last_colon + 1, new_size - last_colon); return {name, type_str, optional}; } template <const std::string_view &parm, bool is_parms> constexpr auto parse_type_specs() { constexpr auto sv = parm; constexpr auto size = get_type_spec_count<parm, is_parms>(start_group, end_group); std::array<type_spec, size> ar = {}; std::size_t count = 0; for (std::size_t i = sv.find(start_group); i != std::string_view::npos;) { auto end = sv.find(end_group, i); auto start = i + start_group.size(); if (is_parms == (sv[start] == '?')) { if (is_parms) ++start; ar[count] = parse_type_spec(sv.substr(start, end - start)); ++count; } i = sv.find(start_group, i + 1); } return ar; } template <const std::string_view &parm, bool is_parms> inline constexpr auto parse_type_specs_v = parse_type_specs<parm,is_parms>(); template <const auto &parm,std::size_t I> inline constexpr auto parse_type_specs_i_v = parm[I]; template <const auto &parm> struct make_member_ts_helper { constexpr static auto ts = parm; constexpr static auto name = ts.name; constexpr static auto type = ts.type; constexpr static auto optional = ts.optional; using name_t = compile_string_sv<name>; using type_str_t = compile_string_sv<type>; }; template <const auto &parm> constexpr auto make_member_ts() { using helper = make_member_ts_helper<parm>; return maybe_make_optional<helper::optional>( make_member<typename helper::name_t>(string_to_type_t<typename helper::type_str_t>{})); } template <const auto &parm, typename S> struct make_members_struct; template <const auto &parm, std::size_t... I> struct make_members_struct<parm, std::index_sequence<I...>> { constexpr static auto ar = parm; template <std::size_t i> struct helper_struct { constexpr static std::decay_t<decltype(ar[i])> a = ar[i]; }; template <std::size_t i> constexpr static auto helper(){ constexpr auto& ts =parse_type_specs_i_v<parm,i>; return make_member_ts<ts>(); } constexpr static auto make_members_ts() { return tagged_tuple{helper<I>()...}; } }; template <const std::string_view &parm> constexpr auto make_members() { constexpr auto& ar = parse_type_specs_v<parm, false>; constexpr auto size = ar.size(); using sequence = std::make_index_sequence<size>; using mms = make_members_struct<ar, sequence>; return mms::make_members_ts(); } template <const std::string_view &parm> constexpr auto make_parameters() { constexpr auto sv = parm; constexpr auto& ar = parse_type_specs_v<parm, true>; constexpr auto size = ar.size(); using sequence = std::make_index_sequence<size>; using mms = make_members_struct<ar, sequence>; return mms::make_members_ts(); } // todo make constexpr inline std::string get_sql_string(std::string_view sv, std::string_view start_group, std::string_view end_group) { std::string ret; ret.reserve(sv.size()); std::size_t prev_i = 0; for (std::size_t i = sv.find(start_group); i != std::string_view::npos;) { ret += std::string(sv.substr(prev_i, i - prev_i)); auto end = sv.find(end_group, i); ret += " "; auto ts_str = sv.substr(i + start_group.size(), end - (i + start_group.size()) - 1); auto ts = parse_type_spec(ts_str); if (ts.name.front() != '?') { ret += std::string(ts.name); } else { ret += '?'; } ret += " "; prev_i = end + end_group.size(); i = sv.find(start_group, i + 1); } ret += std::string(sv.substr(prev_i)); return ret; } template <typename PTuple, typename ATuple> void do_binding(sqlite3_stmt *stmt, PTuple p_tuple, ATuple a_tuple) { int index = 1; skydown::sqlite_experimental::for_each(p_tuple, [&](auto &m) mutable { using m_t = std::decay_t<decltype(m)>; using tag = typename m_t::tag_type; m.value = std::move(get<tag>(a_tuple)); auto r = bind_impl(stmt, index, m.value); check_sqlite_return<bool>(r, true); ++index; }); } struct stmt_closer { void operator()(sqlite3_stmt *s) { if (s) sqlite3_finalize(s); } }; using unique_stmt = std::unique_ptr<sqlite3_stmt, stmt_closer>; template <typename RowType, typename PTuple> struct prepared_statement { unique_stmt stmt; void reset_stmt() { auto r = sqlite3_reset(stmt.get()); check_sqlite_return(r); r = sqlite3_clear_bindings(stmt.get()); check_sqlite_return(r); } template <typename... Args> row_range<RowType> execute_rows(Args &&... args) { reset_stmt(); PTuple p_tuple = {}; tagged_tuple a_tuple{std::forward<Args>(args)...}; do_binding(stmt.get(), p_tuple, a_tuple); return row_range<RowType>(stmt.get()); } template <typename... Args> void execute(Args &&... args) { reset_stmt(); PTuple p_tuple = {}; tagged_tuple a_tuple{std::forward<Args>(args)...}; do_binding(stmt.get(), p_tuple, a_tuple); auto r = sqlite3_step(stmt.get()); check_sqlite_return(r, SQLITE_DONE); } }; template <const std::string_view &parm> auto prepare(sqlite3 *sqldb) { using row_type = decltype(make_members<parm>()); auto sv = parm; sqlite3_stmt *stmt; auto query_string = get_sql_string(sv, start_group, end_group); auto rc = sqlite3_prepare_v2(sqldb, query_string.c_str(), static_cast<int>(query_string.size()), &stmt, 0); check_sqlite_return(rc); using p_tuple_type = decltype(make_parameters<parm>()); return prepared_statement<row_type, p_tuple_type>{unique_stmt(stmt)}; } template <const std::string_view &tag1, const std::string_view &tag2> constexpr auto concatenate_tags() { constexpr auto tag_str1 = tag1; constexpr auto tag_str2 = tag2; std::array<char, tag_str1.size() + tag_str2.size() + 1> ar = {}; std::size_t i = 0; for (auto c : tag_str1) { ar[i] = c; ++i; } ar[i] = '.'; ++i; for (auto c : tag_str2) { ar[i] = c; ++i; } return ar; } inline constexpr std::string_view no_tag = ""; template <const std::string_view &tag1, const std::string_view &tag2 = no_tag, typename T> decltype(auto) field(T &&t) { constexpr auto str2 = tag2; if constexpr (str2.empty()) { return skydown::sqlite_experimental::get<compile_string_sv<tag1>>( std::forward<T>(t)); } else { static constexpr auto ar = concatenate_tags<tag1, tag2>(); return skydown::sqlite_experimental::get<compile_string_sv<ar>>( std::forward<T>(t)); } } template <const std::string_view &sv, typename T> auto bind(T &&t) { return make_member<compile_string_sv<sv>>(std::forward<T>(t)); } } // namespace sqlite_experimental using sqlite_experimental::bind; using sqlite_experimental::field; using sqlite_experimental::prepare; } // namespace skydown
google/cpp-from-the-sky-down
cpp20_tagged_tuple/soa_vector.h
#pragma once #include <boost/stl_interfaces/iterator_interface.hpp> #include <span> #include <vector> #include "tagged_tuple.h" namespace ftsd { template <typename TaggedTuple> class soa_vector; template <auto... Tags, typename... Ts, auto... Inits> class soa_vector<tagged_tuple<member<Tags, Ts, Inits>...>> { using TaggedTuple = tagged_tuple<member<Tags, Ts, Inits>...>; tagged_tuple<member< Tags, std::vector<tagged_tuple_value_type_t<Tags, TaggedTuple>>>...> vectors_; template <auto Tag, auto...> decltype(auto) first_helper() { return get<Tag>(vectors_); } template <auto Tag, auto...> decltype(auto) first_helper() const { return get<Tag>(vectors_); } decltype(auto) first() { return first_helper<Tags...>(); } decltype(auto) first() const { return first_helper<Tags...>(); } public: soa_vector() = default; decltype(auto) vectors() { return (vectors_); } decltype(auto) vectors() const { return (vectors_); } void push_back(TaggedTuple t) { (ftsd::get<Tags>(vectors_).push_back(get<Tags>(t)), ...); } void pop_back() { (get<Tags>(vectors_).pop_back(), ...); } void clear() { (get<Tags>(vectors_).clear(), ...); } std::size_t size() const { return first().size(); } bool empty() const { return first().empty(); } auto operator[](std::size_t i) { return tagged_tuple_ref_t<TaggedTuple>( (ftsd::tag<Tags> = std::ref(ftsd::get<Tags>(vectors_)[i]))...); } auto operator[](std::size_t i) const { return tagged_tuple_ref_t<TaggedTuple>( (ftsd::tag<Tags> = std::ref(ftsd::get<Tags>(vectors_)[i]))...); } auto front() { return (*this)[0]; } auto back() { return (*this)[size() - 1]; } }; template <typename Tag, typename TaggedTuple> decltype(auto) get_impl(soa_vector<TaggedTuple>& s) { return std::span{ftsd::get<Tag::value>(s.vectors())}; } template <typename Tag, typename TaggedTuple> auto get_impl(const soa_vector<TaggedTuple>& s) { return std::span{ftsd::get<Tag::value>(s.vectors())}; } template <typename Tag, typename TaggedTuple> auto get_impl(soa_vector<TaggedTuple>&& s) { return std::span{ftsd::get<Tag::value>(std::move(s.vectors()))}; } } // namespace ftsd
google/cpp-from-the-sky-down
simple_type_name/simple_type_name.h
<reponame>google/cpp-from-the-sky-down // Copyright 2019 Google LLC // // 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 // // https://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. #pragma once #include <cstdint> #include <string_view> namespace skydown { namespace detail { #if !defined(__clang__) && !defined(__GNUC__) && defined(_MSC_VER) #define SIMPLE_TYPE_NAME_PRETTY_FUNCTION __FUNCSIG__ #else #define SIMPLE_TYPE_NAME_PRETTY_FUNCTION __PRETTY_FUNCTION__ #endif template <typename T> constexpr std::string_view type_to_string_raw() { return SIMPLE_TYPE_NAME_PRETTY_FUNCTION; } constexpr std::string_view long_double_raw_string = type_to_string_raw<long double>(); constexpr std::string_view long_double_string = "long double"; constexpr std::size_t begin_type_name = long_double_raw_string.find(long_double_string); static_assert(begin_type_name != std::string_view::npos); constexpr std::size_t end_type_name = begin_type_name + long_double_string.size(); static_assert(begin_type_name != std::string_view::npos); constexpr std::size_t suffix_type_name_size = long_double_raw_string.size() - end_type_name; template <typename T> constexpr std::string_view long_name() { std::string_view raw_name = type_to_string_raw<T>(); auto size = raw_name.size(); raw_name.remove_prefix(begin_type_name); raw_name.remove_suffix(suffix_type_name_size); std::string_view struct_name("struct "); std::string_view class_name("class "); if (raw_name.substr(0, struct_name.size()) == struct_name) raw_name.remove_prefix(struct_name.size()); if (raw_name.substr(0, class_name.size()) == class_name) raw_name.remove_prefix(class_name.size()); while (!raw_name.empty() && raw_name.back() == ' ') { raw_name.remove_suffix(1); } return raw_name; } #undef SIMPLE_TYPE_NAME_PRETTY_FUNCTION template <typename T> constexpr std::string_view short_name() { auto raw_str = long_name<T>(); int last = -1; int count = 0; for (std::size_t pos = 0; pos < raw_str.size(); ++pos) { auto& c = raw_str[pos]; if (c == '<') ++count; if (c == '>') --count; if (c == ':' && count == 0) last = pos; } if (last != -1) { raw_str.remove_prefix(last + 1); } return raw_str; } } // namespace detail template <typename T> inline constexpr std::string_view short_type_name = detail::short_name<T>(); template <typename T> inline constexpr std::string_view long_type_name = detail::long_name<T>(); namespace simple_type_name_testing { static_assert(long_type_name<long double> == detail::long_double_string); static_assert(short_type_name<long double> == detail::long_double_string); struct MyClass; template <typename T> class TemplateTester; static_assert(skydown::short_type_name<int> == "int"); static_assert(skydown::short_type_name<TemplateTester<int>> == "TemplateTester<int>"); static_assert(skydown::short_type_name<MyClass> == "MyClass"); } // namespace simple_type_name_testing } // namespace skydown
google/cpp-from-the-sky-down
cpp20_sql/tagged_sqlite.h
<filename>cpp20_sql/tagged_sqlite.h // Copyright 2020 Google LLC // // 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 // // https://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. #pragma once #include <assert.h> #include <sqlite3.h> #include <array> #include <cstdint> #include <exception> #include <iostream> #include <memory> #include <optional> #include <string> #include <string_view> #include <type_traits> #include <utility> #include "../cpp20_tagged_tuple/tagged_tuple.h" namespace ftsd { namespace sqlite_experimental { template <typename T, typename... GoodValues> void check_sqlite_return(T r, GoodValues... good_values) { bool success = false; if constexpr (sizeof...(good_values) == 0) { success = (r == SQLITE_OK); } else { success = ((r == good_values) || ...); } if (!success) { std::string err_msg = sqlite3_errstr(r); assert(success); std::cerr << "SQLITE ERROR " << r << " " << err_msg; throw std::runtime_error("sqlite error: " + err_msg); } } inline bool read_row_into(sqlite3_stmt *stmt, int index, std::int64_t &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_INTEGER) { v = sqlite3_column_int64(stmt, index); return true; } else if (type == SQLITE_NULL) { return false; } else { return false; } } inline bool read_row_into(sqlite3_stmt *stmt, int index, double &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_FLOAT) { v = sqlite3_column_double(stmt, index); return true; } else if (type == SQLITE_NULL) { return false; } else { return false; } } inline bool read_row_into(sqlite3_stmt *stmt, int index, std::string_view &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_TEXT) { const char *ptr = reinterpret_cast<const char *>(sqlite3_column_text(stmt, index)); auto size = sqlite3_column_bytes(stmt, index); v = std::string_view(ptr, ptr ? size : 0); return true; } else if (type == SQLITE_NULL) { return false; } else { return false; } } template <typename T> inline bool read_row_into(sqlite3_stmt *stmt, int index, std::optional<T> &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_NULL) { v = std::nullopt; return true; } else { v.emplace(); return read_row_into(stmt, index, *v); } } template <typename RowType> auto read_row(sqlite3_stmt *stmt) { RowType row = {}; std::size_t count = sqlite3_column_count(stmt); auto size = row.size(); assert(size == count); if (size != count) { throw std::runtime_error( "sqlite error: mismatch between read_row and sql columns"); } int index = 0; row.for_each([&](auto &m) mutable { read_row_into(stmt, index, m.value()); ++index; }); return row; } template <typename RowType> struct row_range { RowType row; int last_result = 0; sqlite3_stmt *stmt; row_range(sqlite3_stmt *stmt) : stmt(stmt) { next(); } struct end_type {}; end_type end() { return {}; } void next() { last_result = sqlite3_step(stmt); check_sqlite_return(last_result, SQLITE_DONE, SQLITE_ROW); } struct row_iterator { row_range *p; row_iterator &operator++() { p->next(); return *this; } bool operator!=(end_type) { return p->last_result == SQLITE_ROW; } bool operator==(end_type) { return p->last_result != SQLITE_ROW; } RowType &operator*() { p->row = read_row<RowType>(p->stmt); return p->row; } }; bool has_error() const { return last_result != SQLITE_ROW && last_result != SQLITE_DONE; } row_iterator begin() { return {this}; } }; inline bool bind_impl(sqlite3_stmt *stmt, int index, double v) { auto r = sqlite3_bind_double(stmt, index, v); return r == SQLITE_OK; } inline bool bind_impl(sqlite3_stmt *stmt, int index, std::int64_t v) { auto r = sqlite3_bind_int64(stmt, index, v); return r == SQLITE_OK; } inline bool bind_impl(sqlite3_stmt *stmt, int index, std::string_view v) { auto r = sqlite3_bind_text(stmt, index, v.data(), static_cast<int>(v.size()), SQLITE_TRANSIENT); return r == SQLITE_OK; } template <typename T> bool bind_impl(sqlite3_stmt *stmt, int index, const std::optional<T> &v) { if (v.has_value()) { return bind_impl(stmt, index, *v); } else { auto r = sqlite3_bind_null(stmt, index); return r == SQLITE_OK; } } auto to_concrete(const std::string_view &v) { return std::string(v); } auto to_concrete(std::int64_t i) { return i; } auto to_concrete(double d) { return d; } template <typename T> auto to_concrete(const std::optional<T> &o) -> std::optional<decltype(to_concrete(std::declval<T>()))> { if (!o) { return std::nullopt; } else { return to_concrete(*o); } } template <typename T> auto to_concrete(std::optional<T> &&o) -> std::optional<decltype(to_concrete(std::declval<T>()))> { if (!o) { return std::nullopt; } else { return to_concrete(std::move(*o)); } } template <auto... Tags, typename... Ts, auto... Init> auto to_concrete( const tagged_tuple<ftsd::member<Tags, Ts, Init>...> &t) { return tagged_tuple{(tag<Tags> = to_concrete(get<Tags>(t)))...}; } template <auto... Tags, typename... Ts, auto... Init> auto to_concrete( tagged_tuple<ftsd::member<Tags, Ts, Init>...> &&t) { return tagged_tuple{(tag<Tags> = to_concrete(get<Tags>(std::move(t))))...}; } using ftsd::internal_tagged_tuple::fixed_string; template <fixed_string fs> struct compile_string {}; template <bool make_optional, typename Tag, typename T, auto Init> auto maybe_make_optional( ftsd::internal_tagged_tuple::member_impl<Tag, T, Init> m) { if constexpr (make_optional) { return ftsd::internal_tagged_tuple::member_impl<Tag, std::optional<T>, Init>{std::nullopt}; } else { return m; } } template <typename> struct string_to_type; template <> struct string_to_type<compile_string<"integer">> { using type = std::int64_t; }; template <> struct string_to_type<compile_string<"text">> { using type = std::string_view; }; template <> struct string_to_type<compile_string<"real">> { using type = double; }; template <typename T> using string_to_type_t = typename string_to_type<T>::type; constexpr std::string_view start_group = "{{"; constexpr std::string_view end_group = "}}"; constexpr std::string_view delimiters = ", ();"; constexpr std::string_view quotes = "\"\'"; struct type_specs_count { std::size_t fields; std::size_t params; auto operator<=>(const type_specs_count &) const = default; }; inline constexpr std::string_view start_comment = "/*:"; inline constexpr std::string_view end_comment = "*/"; template <fixed_string query_string> constexpr auto get_type_spec_count() { constexpr auto sv = query_string.sv(); type_specs_count count{0, 0}; std::string_view str = sv; while (!str.empty()) { auto pos = str.find(start_comment); if (pos == str.npos) break; pos += start_comment.size(); str = str.substr(pos); pos = str.find(end_comment); if (pos == str.npos) { break; } auto comment = str.substr(0, pos); if (comment.find(":") == comment.npos) { ++count.fields; } else { ++count.params; } } return count; } template <typename First, typename Second> struct pair { First first; Second second; constexpr auto operator<=>(const pair &other) const = default; }; struct type_spec { pair<std::size_t, std::size_t> name; pair<std::size_t, std::size_t> type; bool optional; constexpr auto operator<=>(const type_spec &other) const = default; }; template <std::size_t N> struct type_specs { auto operator<=>(const type_specs &) const = default; type_spec data[N]; static constexpr std::size_t size() { return N; } constexpr auto &operator[](std::size_t i) const { return data[i]; } constexpr auto &operator[](std::size_t i) { return data[i]; } }; template <std::size_t Fields, std::size_t Params> struct combined_type_specs { type_specs<Fields> fields; type_specs<Params> params; auto operator<=>(const combined_type_specs &) const = default; }; template <> struct type_specs<0> { auto operator<=>(const type_specs &) const = default; static constexpr std::size_t size() { return 0; } }; template <fixed_string query_string> constexpr auto parse_type_specs() { constexpr auto sv = query_string.sv(); constexpr auto ret_counts = get_type_spec_count<query_string>(); combined_type_specs<ret_counts.fields, ret_counts.params> ret = {}; type_specs_count counts{0, 0}; auto in_range_inclusive = [](char c, char b, char e) { return b <= c && c <= e; }; auto is_name = [in_range_inclusive](char c) { return in_range_inclusive(c, 'A', 'Z') || in_range_inclusive(c, 'a', 'z') || in_range_inclusive(c, '0', '9') || c == '_' || c == '.'; }; auto is_space = [](char c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; const std::string_view str = sv; std::size_t offset = 0; while (offset != str.npos && offset < str.size()) { auto pos = str.find(start_comment, offset); offset = pos + start_comment.size(); if (pos == str.npos) break; auto end_pos = str.find(end_comment, offset); auto comment_begin = pos + start_comment.size(); auto comment_end = end_pos; auto comment = str.substr(comment_begin, comment_end - comment_begin); auto colon_pos = comment.find(":"); if constexpr (ret_counts.fields > 0) { if (colon_pos == comment.npos) { int prev_name_end = static_cast<int>(pos + 1); int prev_name_begin = 0; for (int rpos = static_cast<int>(pos - 1); rpos > -1; --rpos) { char c = str[rpos]; if (is_name(c)) { if (prev_name_end == pos + 1) { prev_name_end = rpos + 1; } } else { if (prev_name_end == pos + 1) continue; prev_name_begin = rpos + 1; break; } } type_spec &spec = ret.fields[counts.fields]; spec.name.first = prev_name_begin; spec.name.second = prev_name_end - prev_name_begin; spec.type.first = comment_begin; spec.type.second = comment_end - comment_begin; bool optional = false; auto type = str.substr(comment_begin, comment_end - comment_begin); if (!type.empty() && type.ends_with("?")) { optional = true; --spec.type.second; } spec.optional = optional; auto name = str.substr(spec.name.first, spec.name.second - spec.name.first); ++counts.fields; } } if constexpr (ret_counts.params > 0) { if (colon_pos != comment.npos) { auto name = comment.substr(0, colon_pos); auto type = comment.substr(colon_pos + 1); bool optional = false; if (!type.empty() && type.ends_with("?")) { optional = true; type.remove_suffix(1); } type_spec &spec = ret.params[counts.params]; spec.name.first = comment_begin; spec.name.second = name.size(); spec.type.first = comment_begin + colon_pos + 1; spec.type.second = type.size(); spec.optional = optional; ++counts.params; } } } return ret; } template <fixed_string query_string, type_spec ts> constexpr auto make_member_ts() { constexpr auto sv = query_string.sv(); constexpr fixed_string<ts.name.second> name{ sv.substr(ts.name.first, ts.name.second)}; constexpr fixed_string<ts.type.second> type = sv.substr(ts.type.first, ts.type.second); return maybe_make_optional<ts.optional>( tag<name> = (string_to_type_t<compile_string<type>>{})); } template <fixed_string query_string, type_specs ts, std::size_t... I> constexpr auto make_members_helper(std::index_sequence<I...>) { return tagged_tuple{make_member_ts<query_string, ts[I]>()...}; } template <fixed_string query_string> constexpr auto make_members() { constexpr auto ts = parse_type_specs<query_string>(); constexpr auto fields = ts.fields; if constexpr (fields.size() == 0) { return tagged_tuple<>{}; } else { return make_members_helper<query_string, fields>( std::make_index_sequence<fields.size()>()); } } template <fixed_string query_string> constexpr auto make_parameters() { constexpr auto ts = parse_type_specs<query_string>(); return make_members_helper<query_string, ts.params>( std::make_index_sequence<ts.params.size()>()); } template <typename T> std::true_type is_optional(const std::optional<T> &); std::false_type is_optional(...); template <typename PTuple> void do_binding(sqlite3_stmt *stmt, PTuple p_tuple) { int index = 1; p_tuple.for_each([&](auto &m) mutable { using m_t = std::decay_t<decltype(m)>; using tag = typename m_t::tag_type; auto r = bind_impl(stmt, index, m.value()); check_sqlite_return<bool>(r, true); ++index; }); } struct stmt_closer { void operator()(sqlite3_stmt *s) { if (s) sqlite3_finalize(s); } }; using unique_stmt = std::unique_ptr<sqlite3_stmt, stmt_closer>; template <fixed_string Query> class prepared_statement { using RowType = decltype(make_members<Query>()); using PTuple = decltype(make_parameters<Query>()); unique_stmt stmt_; void reset_stmt() { auto r = sqlite3_reset(stmt_.get()); check_sqlite_return(r); r = sqlite3_clear_bindings(stmt_.get()); check_sqlite_return(r); } public: prepared_statement(sqlite3 *sqldb) { auto sv = Query.sv(); sqlite3_stmt *stmt; auto specs = parse_type_specs<Query>(); auto rc = sqlite3_prepare_v2(sqldb, sv.data(), static_cast<int>(sv.size()), &stmt, 0); check_sqlite_return(rc); stmt_.reset(stmt); } row_range<RowType> execute_rows() requires(PTuple::size() == 0) { reset_stmt(); return row_range<RowType>(stmt_.get()); } row_range<RowType> execute_rows(PTuple p_tuple) { reset_stmt(); do_binding(stmt_.get(), std::move(p_tuple)); return row_range<RowType>(stmt_.get()); } std::optional<decltype(to_concrete(std::declval<RowType>()))> execute_single_row(PTuple p_tuple) { auto rng = execute_rows(std::move(p_tuple)); auto begin = rng.begin(); if (begin != rng.end()) { return to_concrete(*begin); } else { return std::nullopt; } } std::optional<decltype(to_concrete(std::declval<RowType>()))> execute_single_row() requires(PTuple::size() == 0) { auto rng = execute_rows(); auto begin = rng.begin(); if (begin != rng.end()) { return to_concrete(*begin); } else { return std::nullopt; } } void execute(PTuple p_tuple) { reset_stmt(); do_binding(stmt_.get(), std::move(p_tuple)); auto r = sqlite3_step(stmt_.get()); check_sqlite_return(r, SQLITE_DONE); } void execute() requires(PTuple::size() == 0) { reset_stmt(); auto r = sqlite3_step(stmt_.get()); check_sqlite_return(r, SQLITE_DONE); } }; template <fixed_string S, typename T> decltype(auto) field(T &&t) { return ftsd::get<S>(std::forward<T>(t)); } template <fixed_string fs, typename T> auto bind(T &&t) { return tag<fs> = std::forward<T>(t); } template <typename Tag> struct param_helper { template <typename T> auto operator=(T t) { return make_member<Tag, T>(std::move(t)); } }; } // namespace sqlite_experimental using sqlite_experimental::bind; using sqlite_experimental::field; using sqlite_experimental::prepared_statement; using sqlite_experimental::to_concrete; } // namespace ftsd
google/cpp-from-the-sky-down
cpp20_tagged_tuple/to_from_nlohmann_json.h
<reponame>google/cpp-from-the-sky-down #pragma once #include <nlohmann/json.hpp> #include "tagged_tuple.h" namespace nlohmann { template <typename... Members> struct adl_serializer<ftsd::tagged_tuple<Members...>> { using TTuple = ftsd::tagged_tuple<Members...>; template <typename Member> static auto get_from_json(const json& j) { using ftsd::tag; if constexpr (!Member::has_default_init()) { return tag<Member::fixed_key()> = j.at(Member::key().data()).get<typename Member::value_type>(); } else { if (j.contains(Member::key().data())) { return tag<Member::fixed_key()> = std::optional<typename Member::value_type>( j.at(Member::key().data()).get<typename Member::value_type>()); } else { return tag<Member::tag_type::value> = std::optional<typename Member::value_type>(); } } } static TTuple from_json(const json& j) { return TTuple::apply_static([&]<typename... M>(M * ...) { return TTuple(get_from_json<M>(j)...); }); } static void to_json(json& j, const TTuple& t) { t.for_each([&](auto& member) { j[member.key().data()] = member.value(); }); } }; } // namespace nlohmann
google/cpp-from-the-sky-down
metaprogrammed_polymorphism/benchmark_imp.h
<gh_stars>100-1000 #include <memory> #include <functional> #include "polymorphic.hpp" struct Dummy {}; class draw {}; int poly_extend(draw, Dummy&); struct Base { virtual int draw() = 0; virtual ~Base() {} }; struct NonVirtual { int draw(); }; std::function<int()> GetFunction(); std::unique_ptr<Base> MakeBase(); std::function<int()> GetFunctionRand(int r); std::unique_ptr<Base> MakeBaseRand(int r); polymorphic::object<int(draw)> GetObjectRand(int r);
google/cpp-from-the-sky-down
meta_struct_20/cppcon_version/meta_struct_sqlite.h
<filename>meta_struct_20/cppcon_version/meta_struct_sqlite.h // Copyright 2020 Google LLC // // 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 // // https://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. #pragma once #include <assert.h> #include <sqlite3.h> #include <array> #include <cstdint> #include <exception> #include <iostream> #include <memory> #include <optional> #include <string> #include <string_view> #include <type_traits> #include <utility> #include "meta_struct.h" namespace ftsd { namespace sqlite_experimental { template <typename T, typename... GoodValues> void check_sqlite_return(T r, GoodValues... good_values) { bool success = false; if constexpr (sizeof...(good_values) == 0) { success = (r == SQLITE_OK); } else { success = ((r == good_values) || ...); } if (!success) { std::string err_msg = sqlite3_errstr(r); assert(success); std::cerr << "SQLITE ERROR " << r << " " << err_msg; throw std::runtime_error("sqlite error: " + err_msg); } } inline bool read_row_into(sqlite3_stmt *stmt, int index, std::int64_t &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_INTEGER) { v = sqlite3_column_int64(stmt, index); return true; } else if (type == SQLITE_NULL) { return false; } else { return false; } } inline bool read_row_into(sqlite3_stmt *stmt, int index, double &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_FLOAT) { v = sqlite3_column_double(stmt, index); return true; } else if (type == SQLITE_NULL) { return false; } else { return false; } } inline bool read_row_into(sqlite3_stmt *stmt, int index, std::string_view &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_TEXT) { const char *ptr = reinterpret_cast<const char *>(sqlite3_column_text(stmt, index)); auto size = sqlite3_column_bytes(stmt, index); v = std::string_view(ptr, ptr ? size : 0); return true; } else if (type == SQLITE_NULL) { return false; } else { return false; } } template <typename T> inline bool read_row_into(sqlite3_stmt *stmt, int index, std::optional<T> &v) { auto type = sqlite3_column_type(stmt, index); if (type == SQLITE_NULL) { v = std::nullopt; return true; } else { v.emplace(); return read_row_into(stmt, index, *v); } } template <typename RowType> auto read_row(sqlite3_stmt *stmt) { RowType row = {}; std::size_t count = sqlite3_column_count(stmt); auto size = meta_struct_size(row); assert(size == count); if (size != count) { throw std::runtime_error( "sqlite error: mismatch between read_row and sql columns"); } int index = 0; meta_struct_for_each( [&](auto &m) mutable { read_row_into(stmt, index, m.value); ++index; }, row); return row; } template <typename RowType> struct row_range { RowType row; int last_result = 0; sqlite3_stmt *stmt; row_range(sqlite3_stmt *stmt) : stmt(stmt) { next(); } struct end_type {}; end_type end() { return {}; } void next() { last_result = sqlite3_step(stmt); check_sqlite_return(last_result, SQLITE_DONE, SQLITE_ROW); } struct row_iterator { row_range *p; row_iterator &operator++() { p->next(); return *this; } bool operator!=(end_type) { return p->last_result == SQLITE_ROW; } bool operator==(end_type) { return p->last_result != SQLITE_ROW; } RowType &operator*() { p->row = read_row<RowType>(p->stmt); return p->row; } }; bool has_error() const { return last_result != SQLITE_ROW && last_result != SQLITE_DONE; } row_iterator begin() { return {this}; } }; inline bool bind_impl(sqlite3_stmt *stmt, int index, double v) { auto r = sqlite3_bind_double(stmt, index, v); return r == SQLITE_OK; } inline bool bind_impl(sqlite3_stmt *stmt, int index, std::int64_t v) { auto r = sqlite3_bind_int64(stmt, index, v); return r == SQLITE_OK; } inline bool bind_impl(sqlite3_stmt *stmt, int index, std::string_view v) { auto r = sqlite3_bind_text(stmt, index, v.data(), static_cast<int>(v.size()), SQLITE_TRANSIENT); return r == SQLITE_OK; } template <typename T> bool bind_impl(sqlite3_stmt *stmt, int index, const std::optional<T> &v) { if (v.has_value()) { return bind_impl(stmt, index, *v); } else { auto r = sqlite3_bind_null(stmt, index); return r == SQLITE_OK; } } auto to_concrete(const std::string_view &v) { return std::string(v); } auto to_concrete(std::int64_t i) { return i; } auto to_concrete(double d) { return d; } template <typename T> auto to_concrete(const std::optional<T> &o) -> std::optional<decltype(to_concrete(std::declval<T>()))> { if (!o) { return std::nullopt; } else { return to_concrete(*o); } } template <typename T> auto to_concrete(std::optional<T> &&o) -> std::optional<decltype(to_concrete(std::declval<T>()))> { if (!o) { return std::nullopt; } else { return to_concrete(std::move(*o)); } } template <auto... Tags, typename... Ts, auto... Init, auto... Attributes> auto to_concrete(const meta_struct<member<Tags, Ts, Init, Attributes>...> &t) { return meta_struct_apply( [](auto &...m) { return meta_struct{(arg<m.tag()> = m.value)...}; }, t); } template <auto... Tags, typename... Ts, auto... Init, auto... Attributes> auto to_concrete(meta_struct<ftsd::member<Tags, Ts, Init, Attributes>...> &&t) { return meta_struct{(arg<Tags> = to_concrete(get<Tags>(std::move(t))))...}; } template <fixed_string Tag> struct string_to_type; template <> struct string_to_type<"integer"> { using type = std::int64_t; }; template <> struct string_to_type<"text"> { using type = std::string_view; }; template <> struct string_to_type<"real"> { using type = double; }; template <fixed_string Tag> using string_to_type_t = typename string_to_type<Tag>::type; struct type_specs_count { std::size_t fields; std::size_t params; }; inline constexpr std::string_view start_comment = "/*:"; inline constexpr std::string_view end_comment = "*/"; template <fixed_string query_string> constexpr auto get_type_spec_count() { constexpr auto sv = query_string.sv(); type_specs_count count{0, 0}; std::string_view str = sv; while (!str.empty()) { auto pos = str.find(start_comment); if (pos == str.npos) break; pos += start_comment.size(); str = str.substr(pos); pos = str.find(end_comment); if (pos == str.npos) { break; } auto comment = str.substr(0, pos); if (comment.find(":") == comment.npos) { ++count.fields; } else { ++count.params; } } return count; } struct query_substring { std::size_t offset; std::size_t count; constexpr auto operator<=>(const query_substring &other) const = default; }; struct type_spec { query_substring name; query_substring type; bool optional; constexpr auto operator<=>(const type_spec &other) const = default; }; template <std::size_t N> struct type_specs { auto operator<=>(const type_specs &) const = default; type_spec data[N]; static constexpr std::size_t size() { return N; } constexpr auto &operator[](std::size_t i) const { return data[i]; } constexpr auto &operator[](std::size_t i) { return data[i]; } }; template <std::size_t Fields, std::size_t Params> struct combined_type_specs { type_specs<Fields> fields; type_specs<Params> params; auto operator<=>(const combined_type_specs &) const = default; }; template <> struct type_specs<0> { auto operator<=>(const type_specs &) const = default; static constexpr std::size_t size() { return 0; } }; template <fixed_string query_string> constexpr auto parse_type_specs() { constexpr auto sv = query_string.sv(); constexpr auto ret_counts = get_type_spec_count<query_string>(); combined_type_specs<ret_counts.fields, ret_counts.params> ret = {}; type_specs_count counts{0, 0}; auto in_range_inclusive = [](char c, char b, char e) { return b <= c && c <= e; }; auto is_name = [in_range_inclusive](char c) { return in_range_inclusive(c, 'A', 'Z') || in_range_inclusive(c, 'a', 'z') || in_range_inclusive(c, '0', '9') || c == '_' || c == '.'; }; auto is_space = [](char c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; const std::string_view str = sv; std::size_t offset = 0; while (offset != str.npos && offset < str.size()) { auto pos = str.find(start_comment, offset); offset = pos + start_comment.size(); if (pos == str.npos) break; auto end_pos = str.find(end_comment, offset); auto comment_begin = pos + start_comment.size(); auto comment_end = end_pos; auto comment = str.substr(comment_begin, comment_end - comment_begin); auto colon_pos = comment.find(":"); if constexpr (ret_counts.fields > 0) { if (colon_pos == comment.npos) { int prev_name_end = static_cast<int>(pos + 1); int prev_name_begin = 0; for (int rpos = static_cast<int>(pos - 1); rpos > -1; --rpos) { char c = str[rpos]; if (is_name(c)) { if (prev_name_end == pos + 1) { prev_name_end = rpos + 1; } } else { if (prev_name_end == pos + 1) continue; prev_name_begin = rpos + 1; break; } } type_spec &spec = ret.fields[counts.fields]; spec.name.offset = prev_name_begin; spec.name.count = prev_name_end - prev_name_begin; spec.type.offset = comment_begin; spec.type.count = comment_end - comment_begin; bool optional = false; auto type = str.substr(comment_begin, comment_end - comment_begin); if (!type.empty() && type.ends_with("?")) { optional = true; --spec.type.count; } spec.optional = optional; auto name = str.substr(spec.name.offset, spec.name.count - spec.name.offset); ++counts.fields; } } if constexpr (ret_counts.params > 0) { if (colon_pos != comment.npos) { auto name = comment.substr(0, colon_pos); auto type = comment.substr(colon_pos + 1); bool optional = false; if (!type.empty() && type.ends_with("?")) { optional = true; type.remove_suffix(1); } type_spec &spec = ret.params[counts.params]; spec.name.offset = comment_begin; spec.name.count = name.size(); spec.type.offset = comment_begin + colon_pos + 1; spec.type.count = type.size(); spec.optional = optional; ++counts.params; } } } return ret; } template <fixed_string query_string, type_spec ts, bool required> struct member_from_type_spec { static constexpr auto sv = query_string.sv(); static constexpr auto name_str = fixed_string<ts.name.count>::from_string_view( sv.substr(ts.name.offset, ts.name.count)); static constexpr auto type_str = fixed_string<ts.type.count>::from_string_view( sv.substr(ts.type.offset, ts.type.count)); using type_from_string = string_to_type_t<type_str>; using value_type = std::conditional_t<ts.optional, std::optional<type_from_string>, type_from_string>; using type = ftsd::member<name_str, value_type, []() { if constexpr (required && !ts.optional) return ftsd::required; else return ftsd::default_init<value_type>(); }()>; }; template <fixed_string query_string, type_specs ts, bool required, typename Sequence> struct meta_struct_from_type_specs; template <fixed_string query_string, type_specs ts, bool required, std::size_t... I> struct meta_struct_from_type_specs<query_string, ts, required, std::index_sequence<I...>> { using type = typename meta_struct< typename member_from_type_spec<query_string, ts[I], required>::type...>; }; template <fixed_string query_string> struct meta_structs_from_query { static constexpr auto ts = parse_type_specs<query_string>(); using fields_type = typename meta_struct_from_type_specs< query_string, ts.fields, false, std::make_index_sequence<ts.fields.size()>>::type; using parameters_type = typename meta_struct_from_type_specs< query_string, ts.params, true, std::make_index_sequence<ts.params.size()>>::type; }; template <typename T> std::true_type is_optional(const std::optional<T> &); std::false_type is_optional(...); template <typename ParametersMetaStruct> void bind_parameters(sqlite3_stmt *stmt, ParametersMetaStruct parameters) { int index = 1; meta_struct_for_each( [&](auto &m) mutable { auto r = bind_impl(stmt, index, m.value); check_sqlite_return<bool>(r, true); ++index; }, parameters); } struct stmt_closer { void operator()(sqlite3_stmt *s) { if (s) sqlite3_finalize(s); } }; using unique_stmt = std::unique_ptr<sqlite3_stmt, stmt_closer>; template <fixed_string Query> class prepared_statement { using RowTypeAndParametersMetaStruct = typename meta_structs_from_query<Query>; using RowType = typename RowTypeAndParametersMetaStruct::fields_type; using ParametersMetaStruct = typename RowTypeAndParametersMetaStruct::parameters_type; unique_stmt stmt_; void reset_stmt() { auto r = sqlite3_reset(stmt_.get()); check_sqlite_return(r); r = sqlite3_clear_bindings(stmt_.get()); check_sqlite_return(r); } public: prepared_statement(sqlite3 *sqldb) { auto sv = Query.sv(); sqlite3_stmt *stmt; auto rc = sqlite3_prepare_v2(sqldb, sv.data(), static_cast<int>(sv.size()), &stmt, 0); check_sqlite_return(rc); stmt_.reset(stmt); } row_range<RowType> execute_rows(ParametersMetaStruct parameters = {}) { reset_stmt(); bind_parameters(stmt_.get(), std::move(parameters)); return row_range<RowType>(stmt_.get()); } std::optional<decltype(to_concrete(std::declval<RowType>()))> execute_single_row(ParametersMetaStruct parameters = {}) { auto rng = execute_rows(std::move(parameters)); auto begin = rng.begin(); if (begin != rng.end()) { return to_concrete(*begin); } else { return std::nullopt; } } void execute(ParametersMetaStruct parameters = {}) { reset_stmt(); bind_parameters(stmt_.get(), std::move(parameters)); auto r = sqlite3_step(stmt_.get()); check_sqlite_return(r, SQLITE_DONE); } }; template <fixed_string S, typename T> decltype(auto) field(T &&t) { return ftsd::get<S>(std::forward<T>(t)); } template <fixed_string fs, typename T> auto bind(T &&t) { return arg<fs> = std::forward<T>(t); } template <typename Tag> struct param_helper { template <typename T> auto operator=(T t) { return make_member<Tag, T>(std::move(t)); } }; } // namespace sqlite_experimental using sqlite_experimental::prepared_statement; using sqlite_experimental::to_concrete; } // namespace ftsd
caja-matematica/chimera-embedding
examples/solve_biclique.c
<reponame>caja-matematica/chimera-embedding<filename>examples/solve_biclique.c /* Copyright 2016 D-Wave Systems Inc. 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. */ #include "dwave_sapi.h" #include "stdio.h" #include "stdlib.h" #include "math.h" #include "string.h" /* I make this with gcc solve_biclique.c -o solve_biclique libdwave_sapi.so -lm */ void handle_error(sapi_Code error, const char *function, const char *more_error) { if(error == SAPI_OK) { return; } printf("Error encountered at (%s) calling dwave_sapi function: ", function); switch( (int)error ) { case SAPI_ERR_INVALID_PARAMETER: printf("invalid parameter"); break; case SAPI_ERR_SOLVE_FAILED: printf("solve failed"); break; case SAPI_ERR_AUTHENTICATION: printf("authentication error"); break; case SAPI_ERR_NETWORK: printf("network error"); break; case SAPI_ERR_COMMUNICATION: printf("communication error"); break; case SAPI_ERR_ASYNC_NOT_DONE: printf("async not done"); break; case SAPI_ERR_PROBLEM_CANCELLED: printf("problem cancelled"); break; case SAPI_ERR_NO_INIT: printf("not initialized"); break; case SAPI_ERR_OUT_OF_MEMORY: printf("out of memory"); break; default: printf("unknown error, %d", (int) error); } printf("\n"); if(more_error != NULL) { printf("%s\n", more_error); } } int main() { int i,j; /* always initialize first */ sapi_Code retval; retval = sapi_globalInit(); if (retval != SAPI_OK) { handle_error(retval, "globalInit", NULL); goto CLEANUP0; } /* grab a local connection */ sapi_Connection *connection = sapi_localConnection(); /* or, connect to a remote solver. You'll need to put in your authentication information */ /* char *sapi_url = NULL; char *sapi_token = NULL; char *proxy_url = NULL; code = sapi_remoteConnection(sapi_url, sapi_token, proxy_url, &connection, err_msg); if (code != SAPI_OK) { printf("%s\n", err_msg); goto CLEANUP0; } */ /* connect to a local solver... you probably want to change this to use the hardware */ char *solver_name = "c4-sw_sample"; sapi_Solver *solver = sapi_getSolver(connection, solver_name); if (solver == NULL) { printf("Could not get the solver named '%s'.\n", solver_name); retval = -1; goto CLEANUP1; } /* grab the properties for this solver */ const sapi_SolverProperties *solver_properties = sapi_getSolverProperties(solver); /* fetch the hardware adjaceny */ sapi_Problem *hardware_adj; retval = sapi_getHardwareAdjacency(solver, &hardware_adj); if(retval != SAPI_OK) { handle_error(retval, "getHardwareAdjacency", NULL); goto CLEANUP2; } /* now let's load in the embedding from file. first, we initialize the embedding object */ sapi_Embeddings embedding; int N_q = embedding.len = solver_properties->quantum_solver->num_qubits; embedding.elements = (int *)malloc(N_q * sizeof(int)); for(i=0;i<embedding.len;i++) { /* qubits labeled -1 aren't used in the embedding, some of these will be overwritten */ embedding.elements[i] = -1; } /* now read in the file */ FILE *embedding_file = fopen("embedded_biclique_largest","r"); int qubit = -1; int n1 = 0; while(!feof(embedding_file) && fscanf(embedding_file, "%d", &qubit) && qubit != -1) { embedding.elements[qubit] = n1; if(feof(embedding_file) || fgetc(embedding_file) != ' ') { n1 ++; } qubit = -1; } int n2 = 0; while(!feof(embedding_file) && fscanf(embedding_file, "%d", &qubit) && qubit != -1) { embedding.elements[qubit] = n1+n2; if(feof(embedding_file) || fgetc(embedding_file) != ' ') { n2 ++; } qubit = -1; } fclose(embedding_file); /* generate the problem, start by initializing the problem object */ sapi_Problem random_problem; random_problem.len = n1*n2 + n1+n2; random_problem.elements = (sapi_ProblemEntry *) malloc(random_problem.len * sizeof(sapi_ProblemEntry)); /* set some random h biases */ sapi_ProblemEntry *entry; for(i = 0; i < (n1+n2); i++) { entry = random_problem.elements + i; entry->i = entry->j = i; entry->value = 1 - (rand() * 2.0 / RAND_MAX); } /* set the J_{i,j} couplings */ int offset = n1+n2; for(i = 0; i < n1; i++) { for(j=0; j < n2; j++) { entry = random_problem.elements + offset; entry->i = i; entry->j = n1+j; entry->value = 1 - (rand() * 2.0 / RAND_MAX); offset ++; } } /* now we've got the pieces in place to embed our problem */ sapi_EmbedProblemResult *pre_embedded_problem; char err_msg[SAPI_ERROR_MESSAGE_MAX_SIZE]; retval = sapi_embedProblem(&random_problem, &embedding, hardware_adj, 0,0,NULL, &pre_embedded_problem, err_msg); if(retval != SAPI_OK) { handle_error(retval, "embedProblem", err_msg); goto CLEANUP3; } /* in the python examples, we showcase using a couple of chain strengths. we'll just go with .25 here with hopes that we get some boken chains. */ double chain_strength = .25; /* sqrt(n); */ sapi_Problem embedded_problem; embedded_problem.len = pre_embedded_problem->problem.len + pre_embedded_problem->jc.len; embedded_problem.elements = (sapi_ProblemEntry *) malloc(embedded_problem.len * sizeof(sapi_ProblemEntry)); memcpy(embedded_problem.elements, pre_embedded_problem->problem.elements, pre_embedded_problem->problem.len * sizeof(sapi_ProblemEntry)); offset = pre_embedded_problem->problem.len; for(i=0;i < pre_embedded_problem->jc.len; i++) { entry = embedded_problem.elements + offset + i; entry->i = pre_embedded_problem->jc.elements[i].i; entry->j = pre_embedded_problem->jc.elements[i].j; entry->value = -chain_strength; } /* now we've actually got the embedded problem! let's solve it! */ /* NOTE: if you're using a solver other than "c4-sw_sample" then you'll need to use a type other than sapi_SwSampleSolverParameters. Please consult the documentation for sapi_solveIsing. */ sapi_SwSampleSolverParameters params = SAPI_SW_SAMPLE_SOLVER_DEFAULT_PARAMETERS; params.num_reads = 1; /* this is an inefficient way to use the hardware! */ sapi_IsingResult *samples; sapi_solveIsing(solver, &embedded_problem, (sapi_SolverParameters*)&params, &samples, err_msg); /* we expect the above to contain some broken chains, so let's patch that up. */ /* there are a few strategies, the MINIMIZE_ENERGY strategy requires the most input from us (specifically, the original problem) so we show how to do that here. */ /* first, make space to store the new solutions */ int *new_solutions = (int *)malloc(samples->num_solutions * (n1+n2) * sizeof(int)); size_t num_new_solutions; retval = sapi_unembedAnswer(samples->solutions, samples->solution_len, samples->num_solutions, &embedding, SAPI_BROKEN_CHAINS_MINIMIZE_ENERGY, &random_problem, new_solutions, &num_new_solutions, err_msg); if(retval != SAPI_OK) { handle_error(retval, "unembedSolution", err_msg); goto CLEANUP4; } /* Now, let's see what we got */ printf("spin | chain spins:\n"); for(i=0;i<(n1+n2);i++) { fflush(stdout); switch(new_solutions[i]) { case 1: printf(" + | "); break; case -1: printf(" - | "); break; default: printf(" ? | "); break; /* this shouldn't happen */ } for(j=0;j<N_q;j++) { if (embedding.elements[j] == i) { switch(samples->solutions[j]) { case 1: printf("+"); break; case -1: printf("-"); break; default: printf("?"); break; /* this shouldn't happen */ } } } printf("\n"); } CLEANUP4: free(embedded_problem.elements); free(new_solutions); sapi_freeIsingResult(samples); CLEANUP3: free(embedding.elements); free(random_problem.elements); sapi_freeEmbedProblemResult(pre_embedded_problem); CLEANUP2: sapi_freeProblem(hardware_adj); CLEANUP1: sapi_freeSolver(solver); sapi_freeConnection(connection); CLEANUP0: sapi_globalCleanup(); return retval; }
jozhalaj/gateway
src/iqrf/DPAProtocol.h
<filename>src/iqrf/DPAProtocol.h #pragma once #include <list> #include <string> #include <vector> #include <Poco/SharedPtr.h> #include "iqrf/DPAMessage.h" #include "iqrf/DPARequest.h" #include "model/ModuleType.h" #include "model/SensorData.h" namespace BeeeOn { /** * @brief The class provides interface for obtaining of measured * data, for detecting of supported modules that can be specific * for general or some own protocol. */ class DPAProtocol { public: typedef Poco::SharedPtr<DPAProtocol> Ptr; /** * @brief Vendor and product name for each paired device. It can be * filled from IQRF repository or statically from code. */ struct ProductInfo { const std::string vendorName; const std::string productName; }; virtual ~DPAProtocol(); /** * @brief DPA request for detecting that specific device communicates * using the same protocols as implemented protocol. * * @returns DPARequest that can be used as a ping message. */ virtual DPARequest::Ptr pingRequest( DPAMessage::NetworkAddress address) const = 0; /** * @returns DPA request for detecting of product info about specific * device (vendor name and product name). */ virtual DPARequest::Ptr dpaProductInfoRequest( DPAMessage::NetworkAddress address) const = 0; /** * @brief Obtaining of information from received response on the * dpaProductInfoRequest(). * * @returns product information as encoded in the given message */ virtual ProductInfo extractProductInfo( const std::vector<uint8_t> &msg, uint16_t hwPID) const = 0; /** * @returns DPA request to detect available modules on the * specific device. */ virtual DPARequest::Ptr dpaModulesRequest( DPAMessage::NetworkAddress node) const = 0; /** * @returns list of module types encoded in the given message */ virtual std::list<ModuleType> extractModules( const std::vector<uint8_t> &message) const = 0; /** * @returns DPA request to obtain measured values from a specific * IQRF node. */ virtual DPARequest::Ptr dpaValueRequest( DPAMessage::NetworkAddress node, const std::list<ModuleType> &type) const = 0; /** * @brief Obtains measured values from the given byte message. * The contents of the message must conform with the list of * module types. * * @returns measured values encoded in the given message */ virtual SensorData parseValue( const std::list<ModuleType> &modules, const std::vector<uint8_t> &msg) const = 0; }; }
jozhalaj/gateway
src/zwave/OZWNetwork.h
<filename>src/zwave/OZWNetwork.h #pragma once #include <list> #include <map> #include <set> #include <string> #include <Poco/AtomicCounter.h> #include <Poco/Mutex.h> #include <Poco/Path.h> #include <Poco/Timespan.h> #include "hotplug/HotplugListener.h" #include "loop/StoppableLoop.h" #include "util/EventSource.h" #include "util/PeriodicRunner.h" #include "zwave/AbstractZWaveNetwork.h" #include "zwave/OZWCommand.h" #include "zwave/ZWaveListener.h" #include "zwave/ZWaveNode.h" namespace OpenZWave { class Notification; class ValueID; } namespace BeeeOn { /** * @brief OZWNetwork manages the Z-Wave network by using the OpenZWave library (OZW). * Its purpose is to handle OZW notifications and initiate OZW commands if needed. * * The OZW library has multiple configuration options. Some are set internally to * some sane values (unimportant for the BeeeOn gateway), others can be changed by * OZWNetwork properties. * * To initialize, the OZWNetwork::configure() is to be used. The method is called * automatically by DI. The deinitialization is implemented via OZWNetwork::cleanup() * (also called by DI). * * The OZWNetwork is able to handle multiple Z-Wave dongles (according to OZW). It * assigns dongles via the hotplug mechanism. It recognizes dongles with property * tty.BEEEON_DONGLE == "zwave". Currently, only dongles connected via tty are supported. * * Everytime when a Z-Wave dongle is detected via OZWNetwork::onAdd(), the OZW library * is notified and starts a thread for the driver. Drivers are removed on hot-unplug * via OZWNetwork::onRemove() or when the OZWNetwork::cleanup() is called. * * The OZWNetwork utilizes AsyncExecutor for performing asynchronous tasks that must * not be performed from the OZW notification handler function. */ class OZWNetwork : public HotplugListener, public AbstractZWaveNetwork { friend class OZWCommand; public: OZWNetwork(); ~OZWNetwork(); /** * @brief Set OZW configPath (contains definitions, XML files, etc.). * The directory should exist prior to calling OZWNetwork::configure(). * * @see OZWNetwork::checkDirectory() */ void setConfigPath(const std::string &path); /** * @brief Set OZW userPath (cache of device definitions). This directory * would be created if it does not exist. * * @see OZWNetwork::prepareDirectory() */ void setUserPath(const std::string &path); /** * @brief Set OZW PollInterval option. */ void setPollInterval(const Poco::Timespan &interval); /** * @brief Set OZW IntervalBetweenPolls option. */ void setIntervalBetweenPolls(bool enable); /** * @brief Set OZW RetryTimeout option. */ void setRetryTimeout(const Poco::Timespan &timeout); /** * @brief Set OZW AssumeAwake option. */ void setAssumeAwake(bool awake); /** * @brief Set OZW DriverMaxAttempts option. */ void setDriverMaxAttempts(int attempts); /** * @brief Set OZW NetworkKey option. The key is expected to * be 16 bytes long. */ void setNetworkKey(const std::list<std::string> &bytes); /** * @brief Set the interval of reporting OZW statistics. */ void setStatisticsInterval(const Poco::Timespan &interval); /** * @brief Set controllers (list of home IDs) to be reset * upon their first appearance in the network. */ void setControllersToReset(const std::list<std::string> &homes); /** * @brief Set asynchronous executor used for asynchronous tasks * and events reporting. */ void setExecutor(AsyncExecutor::Ptr executor); /** * @brief Register a ZWaveListener that would be receiving events. */ void registerListener(ZWaveListener::Ptr listener); /** * @brief Handle incoming OZW notifications in the context * of the OZWNetwork instance. */ void onNotification(const OpenZWave::Notification *n); /** * @brief If the event represents a compatible Z-Wave dongle, * an appropriate driver is added into the OZW runtime. */ void onAdd(const HotplugEvent &event) override; /** * @brief If the event represents a compatible Z-Wave dongle, * the appropriate driver is removed from the OZW runtime. */ void onRemove(const HotplugEvent &event) override; /** * @brief Initialize OZW library, set options and register self * as a watcher for handling notifications. The statistics reporter * is started. */ void configure(); /** * @brief Deinitialize OZW library. Stop the statistics reporter. */ void cleanup(); protected: /** * @brief OZWNode wraps the ZWaveNode to be able to hold specific * data related to the OpenZWave library. */ class OZWNode : public ZWaveNode { public: OZWNode(const Identity &id, bool controller = false); /** * @brief Register the command class together with ValueID * representation as provided by the OpenZWave library. * Calls ZWaveNode::add() internally. */ void add(const CommandClass &cc, const OpenZWave::ValueID &id); /** * @brief Return the appropriate ValueID for the given command class. * @throws Poco::NotFoundException */ OpenZWave::ValueID operator[](const CommandClass &cc) const; private: std::map<CommandClass, OpenZWave::ValueID> m_valueIDs; }; /** * @brief Check that the given directory exists and is readable. * @throws FileAccessDeniedException if the directory is not readable */ void checkDirectory(const Poco::Path &path); /** * @brief Create the directory represented by the given path. * If it already exists, it must be writable and readable. */ void prepareDirectory(const Poco::Path &path); /** * @brief Fire Z-Wave statistics. This is called periodically by the * m_statisticsRunner. * * @see OZWNetwork::setExecutor() * @see OZWNetwork::registerListener() * @see OZWNetwork::setStatisticsInterval() */ void fireStatistics(); /** * @brief Determine hotplugged devices compatible with the OZWNetwork. * The property tty.BEEEON_DONGLE is tested to equal to "zwave". */ static bool matchEvent(const HotplugEvent &event); /** * The OpenZWave library uses a notification loop to provide information * about the Z-Wave network. A notification represents e.g. detection of a * new device, change of a value, Z-Wave dongle initialization, etc. */ static void ozwNotification( OpenZWave::Notification const *n, void *context); /** * @brief Certain notifications coming from OZW are to be ignored because * they are uninteresting or known to screw up certain things. This call * filters all such notifications. */ bool ignoreNotification(const OpenZWave::Notification *n) const; /** * @brief Initiate asynchronous reset of controller associated * with the given home ID. * * The controller reset is invoked via the m_executor instance. * During the reset procedure, the driverRemoved() would be called * for the given home ID. */ void resetController(const uint32_t home); /** * @brief Called when the OZW driver becomes ready to work * for the given home ID. The OZWNetwork installs the home * ID and if configured, it performs reset of the associated * controller. */ void driverReady(const OpenZWave::Notification *n); /** * @brief Called when OZW driver fails to become ready. * The associated home ID is uninstalled. */ void driverFailed(const OpenZWave::Notification *n); /** * @brief Called when OZW driver is removed from the system. * * This happens usually when a Z-Wave dongle is removed or * its controller is being reset. */ void driverRemoved(const OpenZWave::Notification *n); /** * @brief Find out whether the given node ID represents a controller * of the given home. */ bool checkNodeIsController(const uint32_t home, const uint8_t node) const; /** * @brief Called when the OZW discovered a new Z-Wave node. */ void nodeNew(const OpenZWave::Notification *n); /** * @brief Called when the OZW added a Z-Wave node to its list. * * An instance of ZWaveNode is maintained for every such node. * At this stage we might have not enough information about * that node. */ void nodeAdded(const OpenZWave::Notification *n); /** * @brief Called when OZW resolves more details about a Z-Wave node. * * At this stage, we know identification details about the Z-Wave * node. Such information are maintained in the associated ZWaveNode * instance. * * @see ZWaveNode::setProductId() * @see ZWaveNode::setProduct() * @see ZWaveNode::setProductType() * @see ZWaveNode::setVendorId() * @see ZWaveNode::setVendor() */ void nodeNaming(const OpenZWave::Notification *n); /** * @brief Called when OZW resolves properties of a Z-Wave node. * * After this call, the associated ZWaveNode instance would have * information about the features supported by that Z-Wave node. * * @see ZWaveNode::setSupport() */ void nodeProtocolInfo(const OpenZWave::Notification *n); /** * @brief Called when OZW believes that the given Z-Wave node * is ready for standard operations. * * The event EVENT_NEW_NODE will be delivered to upper layers having * information about a new available node for further work. * * Note that, the Z-Wave node might not be discovered fully at this * stage. However, ig the node is already known by the upper layers, * the node can be directly used without waiting for more details * which might take quite a long time. * * @see ZWaveNetwork::pollEvent() * @see PollEvent::EVENT_NEW_NODE */ void nodeReady(const OpenZWave::Notification *n); /** * @brief Called when OZW assumes that a Z-Wave node was removed * from the network and thus is unreachable. * * The event EVENT_REMOVE_NODE will be delivered to upper layers * with information the node removal. * * The OZW persistent configuration cache is written here. * * @see ZWaveNetwork::pollEvent() * @see PollEvent::EVENT_REMOVE_NODE */ void nodeRemoved(const OpenZWave::Notification *n); /** * @brief Called when OZW discoveres a new value associated with a * certain Z-Wave node. * * The value is checked and a proper CommandClass * instance created and added to the appropriate ZWaveNode instance. * * @see buildCommandClass() */ void valueAdded(const OpenZWave::Notification *n); /** * @brief Called when OZW received data associated with a Z-Wave * node's value. Such data are processed by the upper layers. * * The event EVENT_VALUE will be delivered to upper layers having * the new data. * * @see ZWaveNetwork::pollEvent() * @see PollEvent::EVENT_VALUE */ void valueChanged(const OpenZWave::Notification *n); /** * @brief Called when OZW finishes discovering of a Z-Wave node. * At this moment, we are sure to know all dynamic information about * the node (including values definitions). * * The event EVENT_UPDATE_NODE will be delivered to upper layers having * updated information about a node. The associated ZWaveNode instance * is marked to be queried by this call. * * The OZW persistent configuration cache is written here. * * @see ZWaveNode::setQueried() * @see ZWaveNetwork::pollEvent() * @see PollEvent::EVENT_UPDATE_NODE */ void nodeQueried(const OpenZWave::Notification *n); /** * @brief Called when OZW believes that all awaken node have been queried * fully. Here we analyze some stats about nodes (queried, failed, total, * etc.). * * All nodes of the associated home ID are checked whether they are awake. * The awake nodes marked as not-queried are updated and the event * EVENT_UPDATE_NODE is emitted to upper layers. * * Finally, the EVENT_READY will be delivered to upper layers. * * @see ZWaveNode::setQueried() * @see ZWaveNetwork::pollEvent() * @see PollEvent::EVENT_UPDATE_NODE * @see PollEvent::EVENT_READY */ void awakeNodesQueried(const OpenZWave::Notification *n); /** * @brief Called when OZW believes that all nodes have been queried fully. * This call is similar to awakeNodesQueried(). We perform some statistics * collection and update certain nodes if needed. * * All nodes marked as non-queried that are not failing are updated and * the event EVENT_UPDATE_NODE is emitted to upper layers. * * Finally, the EVENT_READY will be delivered to upper layers. * * @see ZWaveNode::setQueried() * @see ZWaveNetwork::pollEvent() * @see PollEvent::EVENT_UPDATE_NODE * @see PollEvent::EVENT_READY */ void allNodesQueried(const OpenZWave::Notification *n); /** * @brief Helper method to print the home ID. */ static std::string homeAsString(uint32_t home); /** * @brief Helper method to build a CommandClass instance directly * from the OZW ValueID instance. */ static ZWaveNode::CommandClass buildCommandClass( const OpenZWave::ValueID &id); /** * @brief Start the inclusion mode on the primary controller(s). * @see OZWCommand::request() */ void startInclusion() override; /** * @brief Cancel the inclusion mode if active. * @see OZWCommand::cancelIf() */ void cancelInclusion() override; /** * @brief Start the removal mode on the primary controller(s). * @see OZWCommand::request() */ void startRemoveNode() override; /** * @brief Cancel the removal mode if active. * @see OZWCommand::cancelIf() */ void cancelRemoveNode() override; /** * @brief Cancel the current OZW command and interrupt an active * pollEvent() call. */ void interrupt() override; /** * @brief Post the given value into the Z-Wave network. The call is non-blocking * and there is no direct feedback about a successful progress. It is possible * to check successful change by watching polling for events. * * @throws Poco::NotFoundException - when home or node are not registered * @throws Poco::NotFoundException - when the command class is not * registered with the node * @throws Poco::InvalidArgumentException - when value cannot be set or is invalid * @throws Poco::NotImplementedException - for unsupported value types */ void postValue(const ZWaveNode::Value &value) override; /** * @returns label of list item for the given ValueID and a value of the list. */ std::string valueForList(const OpenZWave::ValueID &valueID, const int value); private: Poco::Path m_configPath; Poco::Path m_userPath; Poco::Timespan m_pollInterval; bool m_intervalBetweenPolls; Poco::Timespan m_retryTimeout; bool m_assumeAwake; unsigned int m_driverMaxAttempts; std::set<uint32_t> m_controllersToReset; std::vector<uint8_t> m_networkKey; /** * Homes and nodes maintained by the OZWNetwork instance. */ std::map<uint32_t, std::map<uint8_t, OZWNode>> m_homes; /** * Set after the OZWNetwork::configure() finishes successfuly. * The OZWNetwork::cleanup() does nothing, if the m_configured * is false to not segfault when configure() fails. */ Poco::AtomicCounter m_configured; /** * Lock access to the global OpenZWave::Manager instance. */ mutable Poco::FastMutex m_managerLock; /** * Lock access to the members of OZWNetwork. */ mutable Poco::FastMutex m_lock; /** * Initiate and maintain commands sent to the Z-Wave controller * via the OpenZWave library. */ OZWCommand m_command; EventSource<ZWaveListener> m_eventSource; AsyncExecutor::Ptr m_executor; PeriodicRunner m_statisticsRunner; }; }
jozhalaj/gateway
src/bluetooth/BeeWiSmartDoor.h
<reponame>jozhalaj/gateway<filename>src/bluetooth/BeeWiSmartDoor.h #pragma once #include <Poco/SharedPtr.h> #include "bluetooth/BeeWiDevice.h" #include "bluetooth/HciConnection.h" namespace BeeeOn { /** * @brief The class represents BeeWi door sensor. It allows * to parse recieved data from the device. Its modules are * open/close and battery level. */ class BeeWiSmartDoor : public BeeWiDevice { public: typedef Poco::SharedPtr<BeeWiSmartDoor> Ptr; static const std::string NAME; protected: /** * The intention of this constructor is only for testing. */ BeeWiSmartDoor( const MACAddress& address, const Poco::Timespan& timeout, const RefreshTime& refresh, const HciInterface::Ptr hci); public: BeeWiSmartDoor( const MACAddress& address, const Poco::Timespan& timeout, const RefreshTime& refresh, const HciInterface::Ptr hci, HciConnection::Ptr conn); ~BeeWiSmartDoor(); /** * <pre> * | ID (1 B) | 1 B | open/close (1 B) | 1 B | battery (1 B) | * </pre> */ SensorData parseAdvertisingData( const std::vector<unsigned char>& data) const override; static bool match(const std::string& modelID); }; }
jozhalaj/gateway
src/conrad/ConradDevice.h
<filename>src/conrad/ConradDevice.h #pragma once #include <list> #include <string> #include <Poco/SharedPtr.h> #include <Poco/JSON/Object.h> #include "model/DeviceID.h" #include "model/ModuleType.h" #include "model/RefreshTime.h" #include "model/SensorData.h" #include "util/Loggable.h" namespace BeeeOn { /** * @brief Abstract class representing generic Conrad device. */ class ConradDevice : protected Loggable { public: typedef Poco::SharedPtr<ConradDevice> Ptr; static const std::string VENDOR_NAME; ConradDevice( const DeviceID& id, const RefreshTime &refresh, const std::string& productName, const std::list<ModuleType>& moduleTypes); virtual ~ConradDevice(); DeviceID id() const; RefreshTime refreshTime() const; std::list<ModuleType> moduleTypes() const; std::string vendor() const; std::string productName() const; /** * @brief Transforms received ZMQ message to SensorData. */ virtual SensorData parseMessage(const Poco::JSON::Object::Ptr message) = 0; protected: /** * @brief Returns true or false depending if the string is number or not. */ bool isNumber(const std::string& s); protected: const DeviceID m_deviceId; RefreshTime m_refresh; std::string m_productName; std::list<ModuleType> m_moduleTypes; }; }
jozhalaj/gateway
src/net/SOAPMessage.h
<gh_stars>1-10 #pragma once #include <string> #include <sstream> #include <Poco/Net/HTTPRequest.h> #include <Poco/XML/XMLWriter.h> namespace BeeeOn { class SOAPMessage { public: SOAPMessage(); ~SOAPMessage(); void setAction(const std::string& action); Poco::XML::XMLWriter& bodyWriter(); void prepare(Poco::Net::HTTPRequest& request); std::string toString() const; private: std::string m_action; std::stringstream m_stream; Poco::XML::XMLWriter m_writer; bool m_writerDone; }; }
jozhalaj/gateway
src/net/UPnP.h
#pragma once #include <list> #include <string> #include <Poco/Net/SocketAddress.h> #include <Poco/Timespan.h> #include "util/Loggable.h" // Documentation for UPnP protocol // http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf // Section 1 Discovery #define UPNP_MULTICAST_IP "192.168.3.11" #define UPNP_PORT 1900 namespace BeeeOn { class UPnP : protected Loggable { public: UPnP(const Poco::Net::SocketAddress& address = Poco::Net::SocketAddress(UPNP_MULTICAST_IP, UPNP_PORT)); std::list<Poco::Net::SocketAddress> discover(const Poco::Timespan& timeout, const std::string& deviceType); private: Poco::Net::SocketAddress m_multicastAddress; }; }
jozhalaj/gateway
src/core/QueuingExporter.h
<gh_stars>1-10 #pragma once #include <deque> #include <Poco/Event.h> #include <Poco/Mutex.h> #include <Poco/SharedPtr.h> #include "core/Exporter.h" #include "exporters/QueuingStrategy.h" #include "model/SensorData.h" #include "util/Loggable.h" namespace BeeeOn { /** * @class QueuingExporter * @brief Implements Exporter interface and provides SensorData prevents * SensorData loss. * * QueuingExporter serves as interface for any particular exporter. It prevents * SensorData loss by buffering them and cooperating with a QueuingStrategy. By * inheritance of this class, the particular exporter can work with the data via * acquire(), ack() and reset() methods. * * As long as this class implements the Exporter interface, it can be used with * any particular class which implements the Distributor interface. Despite * the particular Distributor could provide its own data buffering, it is not * needed for any particular Exporter that inherits from QueuingExporter. * QueuingExporter always reports successful export and provides both * the persistent and via the QueuingStrategy also non-persistent buffering. * * QueuingExporter has its own buffer, which serves as a temporary SensorData * backup. When a situation that could lead to significant loss of the data occurs, * or when the data loss is probable, the data from buffer are pushed * to the QueuingStrategy. * * - The data loss is considered probable when the particular exporter does not * report successful export by calling the method ack() for the time longer * than the set threshold * * - The possible data loss is considered significant when the buffer contains * more data than the set threshold. */ class QueuingExporter : public Exporter, protected Loggable { public: typedef Poco::SharedPtr<QueuingExporter> Ptr; QueuingExporter(); ~QueuingExporter() override; /** * @param data SensorData to be enqueued * @return always true */ bool ship(const SensorData &data) override; void setStrategy(const QueuingStrategy::Ptr strategy); /** * When the number of enqueued SensorData is greater than or equal to * saveThreshold, the data are pushed to the QueuingStrategy. * * If the push to the QueuingStrategy is not successful, the oldest data * in the buffer, that are not acquired, are erased. After this erase, * the amount of data in the buffer is equal to saveThreshold - 1. * * @param dataCount */ void setSaveThreshold(const int dataCount); /** * When the given timeout is elapsed since the last successful export, * enqueued data are pushed to the QueuingStrategy. * * @param timeout */ void setSaveTimeout(const Poco::Timespan &timeout); /** * Provided SensorData are mix from the queue and the QueuingStrategy. * The strategyPriority gives the ratio of the provided data between * the enqueued data and the data from the QueuingStrategy. * * @param percent */ void setStrategyPriority(const int percent); protected: /** * Acquires the data from the queue and from the QueuingStrategy. * * @param data Vector to be filled with the acquired data. This method does * not clear the vector, but just adds the data to the end of it. * @param count The count of data to be acquired. This number gives * the maximum count, if there are less data available, * the vector is filled just by them (if no data are available, * the vector stays as it was given). * @param timeout If there are no data available, this method waits for the * new data income, but for a maximum of this timeout. */ void acquire( std::vector<SensorData> &data, size_t count, const Poco::Timespan &timeout); /** * When this method is called, all the previously acquired data are * permanently deleted. */ void ack(); /** * After calling this method, no data are longer considered as acquired. */ void reset(); /** * @return True if the queue is empty. */ bool empty() const; private: bool shouldSave() const; size_t queueSize() const; bool waitNotEmpty(const Poco::Timespan &timeout); /** * This method serves to fill the vector by the appropriate SensorData from * the buffer and the QueuingStrategy. If both the buffer and * the QueuingStrategy are empty, given vector stays as given, else the data * are added to the end of the vector. * * The count of the data to be required from the QueuingStrategy depends * on the set backupPriority and the required data count. For example if * the required data count is 10 and the backupPriority is 20%, 2 SensorData * will be required from the QueuingStrategy. * * However, the result of this calculation could be a decimal number. * In this case, the number is rounded down and the remainder is stored. * The stored remainder is added to the result in the next call of this method. * This eliminates the risk of unwanted suspension of the QueuingStrategy * as the data source, as it is possible that the calculation result would * always be less than 1. * * To avoid inconsistency in the case of calling this method multiple times * without a successful export in between, two remainders are stored, * one actual and one previous. If the successful export was not acknowledged * since the last time this method was called the previous remainder is used * in the calculation, to ensure that behaviour of the method will be equal * to its last call. * * If the QueuingStrategy does not provide the required * count of data, both remainders are reset to 0. * * The count of the data required from buffer is calculated as the difference * of the required data count and the number of data loaded from strategy. * * A situation can also occur, when the sum of the SensorData in the buffer * and the SensorData in the QueuingStrategy is greater than or equal to * the required amount, but one of the sources has less data than is required * from it based on its priority. In this case, all the data from that source * are used to fill the vector, and the appropriate amount of data from another * source is added, to provide the total required amount. * * @param data Vector to be filled * @param count Required amount of SensorData * @param acquired The count of data in the added to vector from the buffer * is returned via this parameter * @param peeked The count of data in the added to vector from * the QueuingStrategy is returned via this parameter */ void mix( std::vector<SensorData> &data, size_t count, size_t &acquired, size_t &peeked); size_t mixFromBackup( size_t requiredCount, size_t queueDataCount, size_t backupPriority, double remainder); void updateRemaindersAfterPeek( size_t peeked, size_t requiredToPeek, double potentialRemainder); size_t mixFromQueue(size_t toAcquire, size_t queueDataCount); void saveQueue(size_t skipFirst); void doSaveQueue(size_t skipFirst); private: mutable Poco::Mutex m_queueMutex; QueuingStrategy::Ptr m_strategy; Poco::Event m_notEmpty; uint32_t m_backupPriority; size_t m_saveThreshold; Poco::Timespan m_saveTimeout; size_t m_acquiredDataCount; size_t m_peekedDataCount; Poco::Timestamp m_lastExport; std::deque<SensorData> m_queue; bool m_acked; double m_mixRemainder; double m_previousMixRemainder; }; }
jozhalaj/gateway
src/belkin/BelkinWemoBulb.h
#pragma once #include <list> #include <string> #include <Poco/Mutex.h> #include <Poco/SharedPtr.h> #include "belkin/BelkinWemoDevice.h" #include "belkin/BelkinWemoLink.h" #include "model/ModuleID.h" #include "model/ModuleType.h" #include "model/SensorData.h" namespace BeeeOn { /** * @brief The class represents Belkin WeMo Led Light Bulb. It works with * Belkin WeMo Link it uses his methods to turn off, turn on and * the brightness control of bulb. */ class BelkinWemoBulb : public BelkinWemoDevice { public: typedef Poco::SharedPtr<BelkinWemoBulb> Ptr; /** * @brief The DeviceID is created based on a bulb's 64-bit identifier, * where DevicePrefix is given on 8th byte. */ BelkinWemoBulb( const BelkinWemoLink::BulbID bulbId, const BelkinWemoLink::Ptr link, const RefreshTime &refresh); ~BelkinWemoBulb(); bool requestModifyState(const ModuleID& moduleID, const double value) override; SensorData requestState() override; std::list<ModuleType> moduleTypes() const override; std::string name() const override; Poco::FastMutex& lock() override; BelkinWemoLink::Ptr link() const; private: static DeviceID buildDeviceID(const BelkinWemoLink::BulbID &id); int dimToPercentage(const double value); int dimFromPercentage(const double percents); private: BelkinWemoLink::BulbID m_bulbId; BelkinWemoLink::Ptr m_link; }; }
jozhalaj/gateway
src/credentials/FileCredentialsStorage.h
<gh_stars>1-10 #pragma once #include <Poco/Timer.h> #include <Poco/AtomicCounter.h> #include <Poco/Timespan.h> #include "credentials/CredentialsStorage.h" namespace BeeeOn{ /** * FileCredentialsStorage is subclass of CredentialsStorage which includes * methods for saving credentials to file and loading them from it. * To load from file, it is necessary to setFile and optionally * to setConfigRoot, then call load. */ class FileCredentialsStorage : public CredentialsStorage { public: FileCredentialsStorage(); ~FileCredentialsStorage(); void setFile(const std::string &path); /** * Credentials are saved in configuration in this form: * <configRoot>.<DeviceID>.<attribute> = <value>. * Default configRoot is "credentials". */ void setConfigRoot(const std::string &root); /** * If a change occurs in Credentials (inserting, updating, or removing), * FileCredentialsStorage will be automaticly saved after SaveDelayTime * (from the first change). * Default SaveDelayTime is 30min. * Passing negative number to this funcion causes disabling of autosave (if * autosave timer is already running, storage is saved). */ void setSaveDelay(const Poco::Timespan &delay); void load(); void save(); void insertOrUpdate( const DeviceID &device, const Poco::SharedPtr<Credentials> credentials) override; void remove(const DeviceID &device) override; void clear() override; protected: /** * This method must be always called while holding the write-lock. */ void saveLater(); void onSaveLater(Poco::Timer &); void saveUnlocked() const; private: std::string m_file; std::string m_confRoot; Poco::Timer m_timer; Poco::TimerCallback<FileCredentialsStorage> m_callback; Poco::AtomicCounter m_timerRunning; Poco::Timespan m_saveDelayTime; }; }
jozhalaj/gateway
src/zwave/GenericZWaveMapperRegistry.h
<filename>src/zwave/GenericZWaveMapperRegistry.h #pragma once #include <iosfwd> #include <map> #include "model/ModuleID.h" #include "model/ModuleType.h" #include "util/Loggable.h" #include "zwave/ZWaveMapperRegistry.h" namespace BeeeOn { /** * @brief Certain Z-Wave nodes can be mapped to the BeeeOn system generically. * This allows to support any node type without knowing it in advance. The * GenericZWaveMapperRegistry implements this approach. * * Devices resolved by the GenericZWaveMapperRegistry would have mangled device * ID with 0xff in the top bits of the ident part. * * Reported devices resolved by the GenericZWaveMapperRegistry would have a * product name with appended string " (generic)". Thus, such devices can be * distinguished easily from specific implementations that might have different * module types. */ class GenericZWaveMapperRegistry : public ZWaveMapperRegistry, Loggable { public: class GenericMapper : public ZWaveMapperRegistry::Mapper { public: typedef Poco::SharedPtr<GenericMapper> Ptr; /** * @brief Mangle bits to be injected into device ID of Z-Wave * devices that are using the GenericMapper. */ static uint8_t ID_MANGLE_BITS; GenericMapper(const ZWaveNode::Identity &id, const std::string &product); /** * @returns device ID for the given Z-Wave identity mangled by * the ID_MANGLE_BITS (0xff). */ DeviceID buildID() const override; /** * @returns product name of the ZWaveNode with appended " (generic)" * string to be easily distinguishable. */ std::string product() const override; /** * @returns resolved module types */ std::list<ModuleType> types() const override; SensorValue convert(const ZWaveNode::Value &value) const override; ZWaveNode::Value convert(const ModuleID &id, double value) const override; /** * @brief Record the given association between the given Z-Wave * command class and BeeeOn ModuleType. When calling this method * mutiple times, the order corresponds to an increasing ModuleID. */ void mapType( const ZWaveNode::CommandClass &cc, const ModuleType &type); protected: /** * @brief Throw an exception when the given value cannot be converted * into the BeeeOn representation. */ void cannotConvert(const ZWaveNode::Value &value) const; private: std::map<ZWaveNode::CommandClass, ModuleID> m_mapping; std::map<ModuleID, ModuleType> m_modules; }; GenericZWaveMapperRegistry(); /** * @brief Load XML file with the types mapping between Z-Wave and BeeeOn. */ void loadTypesMapping(const std::string &file); void loadTypesMapping(std::istream &in); /** * @breif Map the given ZWaveNode instance on-fly to the BeeeOn system * by using the GenericMapper. */ Mapper::Ptr resolve(const ZWaveNode &node) override; private: /** * The m_typesMapping maps Z-Wave command classes to BeeeOn types. */ std::map<std::pair<uint8_t, uint8_t>, ModuleType> m_typesMapping; /** * The m_typesOrder maintains backwards compatibility of the m_typesMapping and GenericMapper. * If a new data type is added, it MUST be appended to the end of the m_typesOrder and its * value must be incremented by 1 from the last one. * * The values as discovered from Z-Wave nodes must be always in the same order to * have a stable mapping to BeeeOn modules of a device. When all values are reported * for a Z-Wave device, they are sorted according to the m_typesOrder. */ std::map<std::pair<uint8_t, uint8_t>, unsigned int> m_typesOrder; }; }
jozhalaj/gateway
src/net/VPTHTTPScanner.h
<reponame>jozhalaj/gateway<gh_stars>1-10 #pragma once #include <Poco/Net/IPAddress.h> #include <Poco/Net/SocketAddress.h> #include "net/AbstractHTTPScanner.h" namespace BeeeOn { class VPTHTTPScanner : public AbstractHTTPScanner { public: VPTHTTPScanner(); VPTHTTPScanner(const std::string& path, uint16_t port, const Poco::Net::IPAddress& minNetMask); ~VPTHTTPScanner(); protected: void prepareRequest(Poco::Net::HTTPRequest& request) override; bool isValidResponse(const std::string& response) override; }; }
jozhalaj/gateway
src/util/SensorDataParser.h
<gh_stars>1-10 #pragma once #include <string> #include <Poco/SharedPtr.h> #include "model/SensorData.h" namespace BeeeOn { class SensorDataParser { public: typedef Poco::SharedPtr<SensorDataParser> Ptr; virtual ~SensorDataParser(); /** * Convert string representation of SensorData to SensorData object. */ virtual SensorData parse(const std::string &data) const = 0; }; }
jozhalaj/gateway
src/core/TestingCenter.h
<gh_stars>1-10 #pragma once #include <functional> #include <list> #include <map> #include <vector> #include <Poco/AtomicCounter.h> #include <Poco/SharedPtr.h> #include "core/CommandHandler.h" #include "core/CommandSender.h" #include "credentials/FileCredentialsStorage.h" #include "io/Console.h" #include "loop/StoppableRunnable.h" #include "model/DeviceID.h" #include "model/DeviceDescription.h" #include "model/ModuleID.h" #include "util/CryptoConfig.h" #include "util/Loggable.h" namespace BeeeOn { class TestingCenter : public CommandSender, public CommandHandler, public StoppableRunnable, protected Loggable { public: typedef std::map<ModuleID, double> DeviceData; struct ActionContext { ConsoleSession &console; std::map<DeviceID, DeviceData> &devices; Poco::Mutex &mutex; CommandSender &sender; const std::vector<std::string> args; Poco::SharedPtr<FileCredentialsStorage> credentialsStorage; Poco::SharedPtr<CryptoConfig> cryptoConfig; std::list<DeviceID> &newDevices; std::set<DeviceID> &acceptedDevices; std::map<DeviceID, DeviceDescription> &seenDevices; }; /** * Action to be executed when processing console input. */ typedef std::function<void(ActionContext &context)> Action; struct ActionRecord { std::string description; Action action; }; TestingCenter(); bool accept(const Command::Ptr cmd) override; void handle(Command::Ptr cmd, Answer::Ptr answer) override; void run() override; void stop() override; void setConsole(Poco::SharedPtr<Console> console); void setPairedDevices(const std::list<std::string> &ids); Poco::SharedPtr<Console> console() const; void setCredentialsStorage(Poco::SharedPtr<FileCredentialsStorage> storage); void setCryptoConfig(Poco::SharedPtr<CryptoConfig> config); protected: void registerAction( const std::string &name, const Action action, const std::string &description); void printHelp(ConsoleSession &session); void processLine(ConsoleSession &session, const std::string &line); private: Poco::SharedPtr<Console> m_console; std::list<DeviceID> m_newDevices; Poco::AtomicCounter m_stop; std::map<std::string, ActionRecord> m_action; std::map<DeviceID, DeviceData> m_devices; Poco::Mutex m_mutex; Poco::SharedPtr<FileCredentialsStorage> m_credentialsStorage; Poco::SharedPtr<CryptoConfig> m_cryptoConfig; std::map<DeviceID, DeviceDescription> m_seenDevices; std::set<DeviceID> m_acceptedDevices; }; }
jozhalaj/gateway
src/vektiva/VektivaSmarwiStatus.h
#pragma once #include <Poco/Net/IPAddress.h> namespace BeeeOn { /** * @brief The class represents the status of the Smarwi device. * The status information is obtained by MQTT client in the status message. */ class VektivaSmarwiStatus { public: VektivaSmarwiStatus( int status, int error, int ok, int ro, bool pos, int fix, Poco::Net::IPAddress ipAddress, int rssi); /** * @brief Status is a number according to representing SmarWi state. * There are several status codes such as: * 200 - near frame opening * 210 - opening * 212 - closing but will open * 220 - closing * 230 - near frame closing * 232 - closing from closed state, open a little bit * 234 - closing from closed state, closing * 250 - no action * -1 - not calibrated not ready * 130 - closing window, finishing calibration * 10 - error * 0 - Smarwi connected to the network */ int status() const; /** * @brief In case any error occurs, it can be detected in this * property. If correct state, 0 is sent or other number if any other * error occurs. To be able to communicate with SmarWi when error occurs, * "stop" command must be sent. * Error codes: * 0 - no error * 10 - window seems locked * 20 - movement timeout */ int error() const; /** * @brief Shows whether Smarwi is in correct state. * Values: * 0 - error state * 1 - available state */ int ok() const; /** * @brief Signalizes whether the ridge is inside of the Smarwi or not. * Values: * 0 - ridge is outside of SmarWi * 1 - ridge is inside of SmarWi */ int ro() const; /** * @brief Shows in which position Smarwi is. * Values: * true - Smarwi is in open position * false - Smarwi is in closed position */ bool pos() const; /** * @brief Shows whether window is fixed by Smarwi or not. That means * whether window can be moved easily without Smarwi trying to lock the * window or Smarwi is holding the window. * Values: * 0 - unfixed * 1 - fixed */ int fix() const; /** * @brief Returns an IP address of the Smarwi. */ Poco::Net::IPAddress ipAddress() const; /** * @brief Shows a current Wi-Fi signal strength. */ int rssi() const; private: int m_status; int m_error; int m_ok; int m_ro; bool m_pos; int m_fix; Poco::Net::IPAddress m_ipAddress; int m_rssi; }; }
jozhalaj/gateway
src/philips/PhilipsHueBridgeInfo.h
<reponame>jozhalaj/gateway<filename>src/philips/PhilipsHueBridgeInfo.h<gh_stars>1-10 #pragma once #include <string> #include "net/MACAddress.h" namespace BeeeOn { /** * Provides information about Philips Hue bridge. */ class PhilipsHueBridgeInfo { public: PhilipsHueBridgeInfo(); std::string name() const; std::string dataStoreVersion() const; std::string swVersion() const; std::string apiVersion() const; MACAddress mac() const; std::string bridgeId() const; bool factoryNew() const; std::string modelId() const; static PhilipsHueBridgeInfo buildBridgeInfo( const std::string& response); private: std::string m_name; std::string m_dataStoreVersion; std::string m_swVersion; std::string m_apiVersion; MACAddress m_mac; std::string m_bridgeId; bool m_factoryNew; std::string m_modelId; }; }
jozhalaj/gateway
src/conrad/PowerMeterSwitch.h
<reponame>jozhalaj/gateway #pragma once #include <Poco/SharedPtr.h> #include "model/SensorData.h" #include "conrad/ConradDevice.h" namespace BeeeOn { /** * @brief The class represents a standalone device Conrad Power meter switch. * It allows to communicate with the device via Conrad interface. */ class PowerMeterSwitch : public ConradDevice { public: typedef Poco::SharedPtr<PowerMeterSwitch> Ptr; static const std::string PRODUCT_NAME; PowerMeterSwitch(const DeviceID& id, const RefreshTime &refresh); ~PowerMeterSwitch(); /** * @brief Parses the message from Conrad interface and creates * from it SensorData. */ SensorData parseMessage(const Poco::JSON::Object::Ptr message) override; }; }
jozhalaj/gateway
src/core/Exporter.h
<gh_stars>1-10 #pragma once namespace BeeeOn { class SensorData; /** * Interface for Exporter * Exports data in best effort (or better) */ class Exporter { public: Exporter(); virtual ~Exporter(); /** * Ensures export data in best effort to target destination * @return true when successfully shipped (this is kind of a guarantee that the caller doesn't have to care about the data anymore). * @return false when the Exporter cannot ship data temporarily (e.g. full output buffers). * @throws Poco::IOException when a serious issue caused the Exporter to deny its service. */ virtual bool ship(const SensorData &data) = 0; }; }
jozhalaj/gateway
src/sonoff/SonoffDeviceManager.h
#pragma once #include <map> #include <Poco/Mutex.h> #include <Poco/Timespan.h> #include "core/DeviceManager.h" #include "model/DeviceID.h" #include "net/MqttClient.h" #include "sonoff/SonoffDevice.h" namespace BeeeOn { /** * @brief The class implements the work with Sonoff devices. Allows us * to process and execute the commands from server and gather * data from the devices. */ class SonoffDeviceManager : public DeviceManager { public: SonoffDeviceManager(); void run() override; void stop() override; void setMqttClient(MqttClient::Ptr mqttClient); void setMaxLastSeen(const Poco::Timespan &timeout); protected: AsyncWork<>::Ptr startDiscovery(const Poco::Timespan &timeout) override; AsyncWork<std::set<DeviceID>>::Ptr startUnpair( const DeviceID &id, const Poco::Timespan &) override; void handleAccept(const DeviceAcceptCommand::Ptr cmd) override; /** * @brief Processes the incoming MQTT message, which means creating * a new device or sending the gathered data to the server. */ void processMQTTMessage(const MqttMessage &message); /** * @brief Retrieves device information from JSON message received from MQTT broker. * @return Pair of device id and device name. */ std::pair<DeviceID, std::string> retrieveDeviceInfo(const std::string &message) const; /** * @brief Creates instance of sonoff device according to device name and * appends it into m_devices. */ void createNewDevice(const std::pair<DeviceID, std::string>& deviceInfo); private: Poco::FastMutex m_devicesMutex; std::map<DeviceID, SonoffDevice::Ptr> m_devices; MqttClient::Ptr m_mqttClient; Poco::Timespan m_maxLastSeen; }; }
jozhalaj/gateway
src/conrad/RadiatorThermostat.h
<reponame>jozhalaj/gateway #pragma once #include <Poco/SharedPtr.h> #include "conrad/ConradDevice.h" #include "model/SensorData.h" namespace BeeeOn { /** * @brief The class represents a standalone device Conrad Radiator thermostat. * It allows to communicate with the device via Conrad interface. */ class RadiatorThermostat : public ConradDevice { public: typedef Poco::SharedPtr<RadiatorThermostat> Ptr; static const std::string PRODUCT_NAME; RadiatorThermostat(const DeviceID& id, const RefreshTime &refresh); ~RadiatorThermostat(); /** * @brief Parses the message from Conrad interface and creates * from it SensorData. */ SensorData parseMessage(const Poco::JSON::Object::Ptr message) override; }; }
jozhalaj/gateway
src/server/GWSPriorityAssigner.h
#pragma once #include <Poco/SharedPtr.h> #include "gwmessage/GWMessage.h" namespace BeeeOn { /** * @brief Implementation of GWSPriorityAssigner interface provides a method * for assigning of sending priority to GWMessage instances. The priorities * are used for better control flow of output traffic. * * The highest priority is 0 (the most urgent messages). Priorities greater * then 0 are lower (less urgent). */ class GWSPriorityAssigner { public: typedef Poco::SharedPtr<GWSPriorityAssigner> Ptr; virtual ~GWSPriorityAssigner(); /** * @returns priority for the given message (smaller is better). */ virtual size_t assignPriority(const GWMessage::Ptr message) = 0; }; }
jozhalaj/gateway
src/zwave/AbstractZWaveNetwork.h
#pragma once #include <deque> #include <Poco/Event.h> #include <Poco/Mutex.h> #include "util/Loggable.h" #include "zwave/ZWaveNetwork.h" namespace BeeeOn { /** * @brief Abstract implementation of the ZWaveNetwork class. It provides * a pre-implemented polling mechanism. It is assumed that exactly one * thread calls the method pollEvent() periodically to read the events * (using multiple threads might be an issue because we use Poco::Event). */ class AbstractZWaveNetwork : public ZWaveNetwork, protected virtual Loggable { public: AbstractZWaveNetwork(); /** * Implements the pollEvent() operation generically. It just * waits on the m_event and reads events from the m_eventsQueue. */ PollEvent pollEvent( const Poco::Timespan &timeout) override; /** * Interrupt the pollEvent() operation to return regardless of * the state of the m_eventsQueue. */ void interrupt() override; protected: /** * This method enqueues the given event in the m_eventsQueue and * wake ups the pollEvent() operation. */ void notifyEvent(const PollEvent &event); private: std::deque<PollEvent> m_eventsQueue; Poco::Event m_event; mutable Poco::FastMutex m_lock; }; }
jozhalaj/gateway
src/bluetooth/BeeWiSmartWatt.h
#pragma once #include <Poco/SharedPtr.h> #include <Poco/UUID.h> #include "bluetooth/BeeWiDevice.h" #include "bluetooth/HciConnection.h" namespace BeeeOn { /** * @brief The class represents BeeWi smart switch. It allows * to gather and to control all its modules. */ class BeeWiSmartWatt : public BeeWiDevice { public: typedef Poco::SharedPtr<BeeWiSmartWatt> Ptr; static const std::string NAME; private: /** * UUID of characteristics containing actual values of all sensor modules. */ static const Poco::UUID ACTUAL_VALUES; /** * UUID of characteristics to switch on/off the switch. */ static const Poco::UUID ON_OFF; /** * UUID of characteristics to switch on/off the light on the switch. */ static const Poco::UUID LIGHT_ON_OFF; protected: /** * The intention of this constructor is only for testing. */ BeeWiSmartWatt( const MACAddress& address, const Poco::Timespan& timeout, const RefreshTime& refersh, const HciInterface::Ptr hci); public: BeeWiSmartWatt( const MACAddress& address, const Poco::Timespan& timeout, const RefreshTime& refersh, const HciInterface::Ptr hci, HciConnection::Ptr conn); ~BeeWiSmartWatt(); bool pollable() const override; void poll(Distributor::Ptr distributor) override; void requestModifyState( const ModuleID& moduleID, const double value) override; /** * <pre> * | ID (1 B) | 1 B | on/off (1 B) | 3 B | power (2 B) | 5 B | * </pre> */ SensorData parseAdvertisingData( const std::vector<unsigned char>& data) const override; static bool match(const std::string& modelID); protected: /** * <pre> * | on/off (1 B) | power (2 B) | voltage (1 B) | current (2 B) | frequency (1 B) | * </pre> */ SensorData parseValues(std::vector<unsigned char>& values) const; }; }
jozhalaj/gateway
src/philips/PhilipsHueDeviceManager.h
#pragma once #include <map> #include <vector> #include <Poco/Mutex.h> #include <Poco/Timespan.h> #include "core/AbstractSeeker.h" #include "core/DeviceManager.h" #include "core/PollingKeeper.h" #include "credentials/FileCredentialsStorage.h" #include "loop/StopControl.h" #include "model/DeviceID.h" #include "model/RefreshTime.h" #include "net/MACAddress.h" #include "philips/PhilipsHueBridge.h" #include "philips/PhilipsHueBulb.h" #include "philips/PhilipsHueListener.h" #include "util/AsyncWork.h" #include "util/CryptoConfig.h" #include "util/EventSource.h" namespace BeeeOn { /** * @brief The class implements the work with Philips Hue bulbs. Allows us * to process and execute the commands from server. It means modify state * of proper bulb. */ class PhilipsHueDeviceManager : public DeviceManager { public: /** * @brief Provides searching philips devices on network * in own thread. */ class PhilipsHueSeeker : public AbstractSeeker { public: typedef Poco::SharedPtr<PhilipsHueSeeker> Ptr; PhilipsHueSeeker(PhilipsHueDeviceManager& parent, const Poco::Timespan& duration); protected: void seekLoop(StopControl &control) override; private: PhilipsHueDeviceManager& m_parent; }; static const Poco::Timespan SEARCH_DELAY; PhilipsHueDeviceManager(); void run() override; void stop() override; void setDevicePoller(DevicePoller::Ptr poller); void setUPnPTimeout(const Poco::Timespan &timeout); void setHTTPTimeout(const Poco::Timespan &timeout); void setRefresh(const Poco::Timespan &refresh); void setCredentialsStorage(Poco::SharedPtr<FileCredentialsStorage> storage); void setCryptoConfig(Poco::SharedPtr<CryptoConfig> config); void setEventsExecutor(AsyncExecutor::Ptr executor); void registerListener(PhilipsHueListener::Ptr listener); protected: void handleAccept(const DeviceAcceptCommand::Ptr cmd) override; AsyncWork<>::Ptr startDiscovery(const Poco::Timespan &timeout) override; AsyncWork<std::set<DeviceID>>::Ptr startUnpair( const DeviceID &id, const Poco::Timespan &timeout) override; AsyncWork<double>::Ptr startSetValue( const DeviceID &id, const ModuleID &module, const double value, const Poco::Timespan &timeout) override; void searchPairedDevices(); /** * @brief Erases the bridges which don't care any bulb. */ void eraseUnusedBridges(); std::vector<PhilipsHueBulb::Ptr> seekBulbs(const StopControl& stop); void authorizationOfBridge(PhilipsHueBridge::Ptr bridge); void processNewDevice(PhilipsHueBulb::Ptr newDevice); void fireBridgeStatistics(PhilipsHueBridge::Ptr bridge); void fireBulbStatistics(PhilipsHueBulb::Ptr bulb); private: Poco::FastMutex m_bridgesMutex; Poco::FastMutex m_pairedMutex; std::map<MACAddress, PhilipsHueBridge::Ptr> m_bridges; std::map<DeviceID, PhilipsHueBulb::Ptr> m_devices; PollingKeeper m_pollingKeeper; RefreshTime m_refresh; Poco::Timespan m_httpTimeout; Poco::Timespan m_upnpTimeout; Poco::SharedPtr<FileCredentialsStorage> m_credentialsStorage; Poco::SharedPtr<CryptoConfig> m_cryptoConfig; EventSource<PhilipsHueListener> m_eventSource; }; }
jozhalaj/gateway
src/bluetooth/HciInfoReporter.h
<gh_stars>1-10 #pragma once #include <set> #include <string> #include <Poco/Mutex.h> #include <Poco/Timespan.h> #include "bluetooth/HciListener.h" #include "bluetooth/HciInterface.h" #include "hotplug/HotplugListener.h" #include "loop/StoppableLoop.h" #include "util/EventSource.h" #include "util/Loggable.h" #include "util/PeriodicRunner.h" namespace BeeeOn { /** * @brief HciInfoReporter periodically collects and reports statistics * information about HCI interfaces in the system. Reporting is done * via the HciListener interface. * * The HciInfoReporter depends on the hotplug system. It can serve any * bluetooth controller notified via the onAdd() event. Information about * multiple compatible HCI devices can be collected this way. * * Compatible HCI devices is recognized by method HciUtil::hotplugMatch(). */ class HciInfoReporter : public StoppableLoop, public HotplugListener, Loggable { public: HciInfoReporter(); /** * Set interval of periodic bluetooth statistics generation. */ void setStatisticsInterval(const Poco::Timespan &interval); /** * Set HciInterfaceManager implementation. */ void setHciManager(HciInterfaceManager::Ptr manager); /** * Set executor for delivering events. */ void setEventsExecutor(AsyncExecutor::Ptr executor); /** * Register listener of bluetooth events. */ void registerListener(HciListener::Ptr listener); /** * @brief Check the given event whether it is a bluetooth controller. * Every matching controller is added to the list and statistics for * it are reported periodically. * * @see HciUtil::hotplugMatch() */ void onAdd(const HotplugEvent &event) override; /** * @brief Check the given event whether it is a bluetooth controller. * The method allows to unplug a device and stop reporting for it. * * @see HciUtil::hotplugMatch() */ void onRemove(const HotplugEvent &event) override; /** * @brief Start the periodic reporting loop. */ void start() override; /** * @brief Stop the periodic reporting loop. */ void stop() override; protected: std::set<std::string> dongles() const; private: std::set<std::string> m_dongles; HciInterfaceManager::Ptr m_hciManager; PeriodicRunner m_statisticsRunner; EventSource<HciListener> m_eventSource; mutable Poco::FastMutex m_lock; }; }
jozhalaj/gateway
src/jablotron/JablotronGadget.h
#pragma once #include <list> #include <string> #include <vector> #include <Poco/Timespan.h> #include "model/ModuleType.h" #include "model/RefreshTime.h" #include "model/SensorValue.h" #include "jablotron/JablotronReport.h" namespace BeeeOn { /** * @brief Representation of a real Jablotron Gadget registered * inside the associated Turris Dongle. */ class JablotronGadget { public: enum Type { NONE = -1, AC88, JA80L, JA81M, JA82SH, JA83M, JA83P, JA85ST, RC86K, TP82N, }; /** * @brief Information about a Jablotron Gadget device type. * Gadget types are distinguished by their address. A certain * address range denotes a gadget device type. */ struct Info { const uint32_t firstAddress; const uint32_t lastAddress; const Type type; const RefreshTime refreshTime; const std::list<ModuleType> modules; operator bool() const; bool operator !() const; std::string name() const; /** * @brief Parses the data payload of the given report and converts * it into BeeeOn-specific data format. */ std::vector<SensorValue> parse(const JablotronReport &report) const; /** * @returns gadget info instance based on the given address */ static Info resolve(const uint32_t address); /** * @returns primary address of the gadget which is usually the * address itself unless it is an address of RC-86K gadget */ static uint32_t primaryAddress(const uint32_t address); /** * @returns secondary address of the gadget. * @throws NotFoundException when the address is not of type RC-86K */ static uint32_t secondaryAddress(const uint32_t address); }; JablotronGadget( const unsigned int slot, const uint32_t address, const Info &info); unsigned int slot() const; uint32_t address() const; const Info &info() const; /** * @returns true if the gadget represents a secondary part which * applies especially to RC-86K. */ bool isSecondary() const; std::string toString() const; private: const unsigned int m_slot; const uint32_t m_address; const Info m_info; static const std::vector<Info> GADGETS; }; }
jozhalaj/gateway
src/server/AbstractGWSConnector.h
<reponame>jozhalaj/gateway<filename>src/server/AbstractGWSConnector.h #pragma once #include <queue> #include <Poco/Event.h> #include <Poco/Mutex.h> #include "gwmessage/GWMessage.h" #include "server/GWSConnector.h" #include "server/GWSPriorityAssigner.h" #include "util/Loggable.h" namespace BeeeOn { /** * @brief Most GWSConnector implementations would solve the issue * of sending prioritization and asynchronous queuing of outgoing * messages. The AbstractGWSConnector aims on this issue. * * AbstractGWSConnector implements a queuing mechanism for outgoing messages. * Each message is appended to a queue based on its priority. The queue * number 0 is the most urgent queue. * * Each queue contains a statistic of count of messages sent from * the queue. A message for output is selected based on the following * algorithm: * * 1. take queue[i] (initially i := 0) with status[i] * 2. sum all status[j] for j > i * 3. if the status[i] <= sum(status[all j]), use queue i * 4. i := i + 1, try again * * Empty or unused queues are skipped. Summarization... The first queue must * always send more messages then all the other queues. If the first queue * sends more messages then available in other queues (the first queue has been * satisfied), the following queue is used with the same algorithm. */ class AbstractGWSConnector : public GWSConnector, protected Loggable { public: AbstractGWSConnector(); void setOutputsCount(int count); void setPriorityAssigner(GWSPriorityAssigner::Ptr assigner); /** * @brief Setup queues based on configuration. This must * be called before the connector is started. */ void setupQueues(); /** * @brief Put the message into a queue and notify sender * to check queues for updates. */ void send(const GWMessage::Ptr message) override; protected: /** * @returns index of output queue to send from. */ size_t selectOutput() const; /** * @breif Update status of output queues. The given index * denotes queue that has been used to send a message. */ void updateOutputs(size_t i); /** * @returns true if the queue of the given index is valid * (existing queue) */ bool outputValid(size_t i) const; /** * @returns first message in the queue of the given index */ GWMessage::Ptr peekOutput(size_t i) const; /** * @brief Pop the first (oldest) message in the queue of the * given index. */ void popOutput(size_t i); protected: Poco::Event m_outputsUpdated; mutable Poco::Mutex m_outputLock; private: unsigned int m_outputsCount; std::vector<std::queue<GWMessage::Ptr>> m_outputs; std::vector<size_t> m_outputsStatus; GWSPriorityAssigner::Ptr m_priorityAssigner; }; }
jozhalaj/gateway
src/util/XmlTypeMappingParserHelper.h
#pragma once #include <iosfwd> #include <Poco/AutoPtr.h> #include <Poco/Logger.h> #include <Poco/SharedPtr.h> #include <Poco/DOM/Document.h> #include <Poco/DOM/Node.h> #include <Poco/DOM/NodeIterator.h> #include "model/ModuleType.h" #include "util/Loggable.h" namespace BeeeOn { /** * @brief Helper defining method for parsing an input stream as * an XML input. The purpose is to extract information about type * mapping. The class is stateful and represents a single loop over * the parsed XML document. * * The helper expects the following XML structure: * <pre> * <some-root> * ... * <some-mapping-group> * <map comment="Type xxx"> * <TECH-SPEC TECH-ATTR="xxx" /> * <beeeon type="temperature,outer" /> * <map> * <map comment="Type yyy"> * <TECH-SPEC TECH-ATTR="yyy" /> * <beeeon type="humidity" /> * </map> * ... * </some-mapping-group> * ... * </some-root> * </pre> * * The parser does not care about the depth of element <code><map></code>. * The <code><TECH-SPEC /></code> element is unknown to the helper * but it MUST be the previous sibling of the <code><beeeon /></code> element. * <code>TECH-ATTR</code> is technology-specific attribute that the parser * does not take care of either. The element <code><beeeon /></code> specifies * the BeeeOn type to map to. */ class XmlTypeMappingParserHelper : Loggable { public: /** * @param techNode - name of the technology-specific XML element * @param logger - logger to log into */ XmlTypeMappingParserHelper( const std::string &mappingGroup, const std::string &techNode, Poco::Logger &logger); /** * @brief Parse the given input stream and create its DOM representation * internally. */ void parseDOM(std::istream &in); /** * @returns the next available pair <code>(TECH-SPEC, ModuleType)</code>. * The <code>TECH-SPEC</code> must be parsed by upper layer. * @throws Poco::SyntaxException */ std::pair<Poco::AutoPtr<Poco::XML::Node>, ModuleType> next(); private: std::string m_mappingGroup; std::string m_techNode; Poco::AutoPtr<Poco::XML::Document> m_document; Poco::SharedPtr<Poco::XML::NodeIterator> m_iterator; }; }
jozhalaj/gateway
src/zwave/FibaroZWaveMapperRegistry.h
#pragma once #include "zwave/SpecificZWaveMapperRegistry.h" namespace BeeeOn { class FibaroZWaveMapperRegistry : public SpecificZWaveMapperRegistry { public: FibaroZWaveMapperRegistry(); private: class FGK101Mapper : public Mapper { public: FGK101Mapper( const ZWaveNode::Identity &id, const std::string &product); std::list<ModuleType> types() const override; SensorValue convert(const ZWaveNode::Value &value) const override; }; class FGSD002Mapper : public Mapper { public: FGSD002Mapper( const ZWaveNode::Identity &id, const std::string &product); std::list<ModuleType> types() const override; SensorValue convert(const ZWaveNode::Value &value) const override; }; }; }
jozhalaj/gateway
src/net/MqttClient.h
<gh_stars>1-10 #pragma once #include <Poco/SharedPtr.h> #include <Poco/Timespan.h> #include "net/MqttMessage.h" namespace BeeeOn { class MqttClient { public: typedef Poco::SharedPtr<MqttClient> Ptr; virtual ~MqttClient(); /** * @brief Publish a message on the topic included in the message. */ virtual void publish(const MqttMessage &msg) = 0; /** * Waiting for a new message according to given timeout. * Returns message, if there is any. Otherwise it waits * for a new message or timeout exception. * * This method should not be called by multiple threads, * received message could be given to only one thread. * * Timeout: * - 0 - non-blocking * - negative - blocking * - positive blocking with timeout */ virtual MqttMessage receive(const Poco::Timespan &timeout) = 0; }; }
jozhalaj/gateway
src/iqrf/IQRFMqttConnector.h
<gh_stars>1-10 #pragma once #include <map> #include <string> #include <Poco/Clock.h> #include <Poco/Mutex.h> #include <Poco/SharedPtr.h> #include <Poco/Timespan.h> #include "iqrf/IQRFJsonResponse.h" #include "loop/StopControl.h" #include "loop/StoppableRunnable.h" #include "model/GlobalID.h" #include "net/MqttClient.h" #include "util/Loggable.h" #include "util/WaitCondition.h" namespace BeeeOn { /** * @brief IQRFMqttConnector provides sending and receiving messages. * During data receiving, it is necessary to know identification of * JSON message (GlobalID). The identification of message is used * to bring sent and received message together. */ class IQRFMqttConnector final: public StoppableRunnable, private Loggable { public: typedef Poco::SharedPtr<IQRFMqttConnector> Ptr; IQRFMqttConnector(); void run() override; void stop() override; void setPublishTopic(const std::string &topic); void setMqttClient( MqttClient::Ptr mqttClient); void setDataTimeout(const Poco::Timespan &timeout); void setReceiveTimeout(const Poco::Timespan &timeout); void checkPublishTopic(); /** * @brief Send message using mqtt client to specific topic. */ void send(const std::string &msg); /** * @brief Receive message with given timeout and identification * of message. */ IQRFJsonResponse::Ptr receive( const GlobalID &id, const Poco::Timespan &timeout); private: void removeExpiredMessages(const Poco::Timespan &timeout); private: /** * @brief Represents a received JSON message and time. */ struct ReceivedData { Poco::Clock receivedAt; IQRFJsonResponse::Ptr message; }; private: StopControl m_stopControl; std::map<GlobalID, ReceivedData> m_data; Poco::Timespan m_messageTimeout; Poco::Timespan m_receiveTimeout; WaitCondition m_waitCondition; Poco::FastMutex m_dataLock; MqttClient::Ptr m_mqttClient; std::string m_publishTopic; }; }
jozhalaj/gateway
src/exporters/InMemoryQueuingStrategy.h
<filename>src/exporters/InMemoryQueuingStrategy.h<gh_stars>1-10 #pragma once #include <vector> #include <Poco/SharedPtr.h> #include "exporters/QueuingStrategy.h" namespace BeeeOn { /** * @brief Basic implementation of the QueuingStrategy interface. * * Serves as temporary non-persistent storage of SensorData. The data are held * in the std::vector. */ class InMemoryQueuingStrategy: public QueuingStrategy { public: typedef Poco::SharedPtr<InMemoryQueuingStrategy> Ptr; /** * @return True, if the vector is empty, false otherwise. */ bool empty() override; /** * @return actual size of the in-memory queue. */ size_t size(); /** * Adds the given data to the end of the vector. * @param data */ void push(const std::vector<SensorData> &data) override; /** * Peek the given count of data off the vector starting from the oldest one. * Calling this method is stable (returns the same results) until the pop() * method is called. * * @param data Vector to be filled with data * @param count Required count of data * @return Real count of data added to the "data" vector. */ size_t peek(std::vector<SensorData> &data, size_t count) override; /** * Pop the required amount of data off the vector. * @param count Number of data to be popped */ void pop(size_t count) override; private: std::vector<SensorData> m_vector; }; }
jozhalaj/gateway
src/bluetooth/BLESmartDevice.h
#pragma once #include <list> #include <string> #include <vector> #include <Poco/SharedPtr.h> #include <Poco/SynchronizedObject.h> #include <Poco/Timespan.h> #include "bluetooth/HciInterface.h" #include "core/PollableDevice.h" #include "model/DeviceID.h" #include "model/ModuleID.h" #include "model/ModuleType.h" #include "model/RefreshTime.h" #include "model/SensorData.h" #include "net/MACAddress.h" #include "util/Loggable.h" namespace BeeeOn { /** * @brief Abstract class representing generic Bluetooth Low Energy smart device. */ class BLESmartDevice : public PollableDevice, protected Poco::SynchronizedObject, protected Loggable { public: typedef Poco::SharedPtr<BLESmartDevice> Ptr; /** * @param &address MAC address of the device * @param &timeout timeout of actions as connect, read, write * @param hci reference to HCI */ BLESmartDevice( const MACAddress& address, const Poco::Timespan& timeout, const RefreshTime& refresh, const HciInterface::Ptr hci); virtual ~BLESmartDevice(); DeviceID id() const override; RefreshTime refresh() const override; MACAddress macAddress() const; virtual std::list<ModuleType> moduleTypes() const = 0; virtual std::string productName() const = 0; virtual std::string vendor() const = 0; /** * @brief When the device supports processing of advertising data, * it should call a watch() on the given HciInterface in this method * and a unwatch() in the destructor. When the method is re-called * it do not have any effect. */ virtual void pair( Poco::SharedPtr<HciInterface::WatchCallback> callback); /** * @brief Returns true if the device is pollable, otherwise false. */ virtual bool pollable() const; void poll(Distributor::Ptr distributor) override; /** * @brief Modifies the device module given by moduleID to a given * value. * @throws IOException in case of communication failure. * @throws NotImplementedException if the device does not support * modification of its state. */ virtual void requestModifyState( const ModuleID& moduleID, const double value); /** * @brief Transforms advertising data to SensorData. * @throws ProtocolException in case of bad received advertising data. * @throws NotImplementedException if the device does not support * processing of its advertising data. */ virtual SensorData parseAdvertisingData( const std::vector<unsigned char>& data) const; protected: DeviceID m_deviceId; MACAddress m_address; Poco::Timespan m_timeout; RefreshTime m_refresh; HciInterface::Ptr m_hci; }; }
jozhalaj/gateway
src/core/AbstractSeeker.h
#pragma once #include <Poco/Clock.h> #include <Poco/Mutex.h> #include <Poco/RunnableAdapter.h> #include <Poco/SharedPtr.h> #include <Poco/Timespan.h> #include <Poco/Thread.h> #include "util/AsyncWork.h" #include "util/Joiner.h" #include "util/Loggable.h" #include "loop/StopControl.h" namespace BeeeOn { /** * @brief AbstractSeeker represents an asynchronous process that seeks * for new devices in a certain network. It is basically a thread that * performs some technology-specific routines to discover new devices. * * A single AbstractSeeker instance can perform only 1 seek. For every * other seek a new AbstractSeeker must be created. */ class AbstractSeeker : public AsyncWork<>, protected Loggable { public: typedef Poco::SharedPtr<AbstractSeeker> Ptr; AbstractSeeker(const Poco::Timespan &duration); /** * @returns total duration of seeking */ Poco::Timespan duration() const; /** * @return time elapsed while seeking */ Poco::Timespan elapsed() const; /** * @brief Compute time that is remaining to finish * the seeking process. If the seeking has finished, * it returns 0. * * @return time remaining to finish of seeking */ Poco::Timespan remaining() const; /** * @brief Start the seeking thread. * @throws Poco::IllegalStateException in case the seeker was already started. */ void start(); /** * @brief Join the seeking thread via Joiner. */ bool tryJoin(const Poco::Timespan &timeout) override; /** * @brief Cancel seeking and wait for the thread to finish. */ void cancel() override; protected: void seek(); virtual void seekLoop(StopControl &control) = 0; private: Poco::Timespan m_duration; Poco::RunnableAdapter<AbstractSeeker> m_runnable; Poco::Thread m_thread; mutable Poco::FastMutex m_lock; Poco::Clock m_started; bool m_hasStarted; StopControl m_stopControl; Joiner m_joiner; }; }
jozhalaj/gateway
src/util/TypeMappingParser.h
#pragma once #include <iosfwd> #include <vector> #include "model/ModuleType.h" namespace BeeeOn { /** * @brief TypeMappingParser is an abstract class providing method * parse() that reads a given definition file (inpus stream). The file * contains mapping definitions between the target technology-specific * data types and the BeeeOn data types (ModuleType). */ template <typename TechType> class TypeMappingParser { public: /** * @brief Single mapping between technology-specific type * and the ModuleType. */ typedef std::pair<TechType, ModuleType> TypeMapping; /** * @brief Sequence of particular mappings. */ typedef std::vector<TypeMapping> TypeMappingSequence; virtual ~TypeMappingParser(); /** * @brief Parse the given input stream and construct sequence * of mappings between a technology-specific data type and * the BeeeOn ModuleType. The sequence is returned in the same * order as found in the input stream. */ virtual TypeMappingSequence parse(std::istream &in) = 0; }; template <typename TechType> TypeMappingParser<TechType>::~TypeMappingParser() { } }
jozhalaj/gateway
src/core/Result.h
#pragma once #include <Poco/AutoPtr.h> #include <Poco/Event.h> #include <Poco/RefCountedObject.h> #include "util/Castable.h" #include "util/Enum.h" namespace BeeeOn { class Answer; /* * Representation of the result that is created and set in * CommandHandler::handle(). Status of the Result is set to * PENDING after the result creation. * * The notification about the changed status is sent using notifyUpdated() * after the status is changed. It is automatically called in the * setStatus() method and it is processed by Answer. The setDirty(true) * is set after the notification setting. It means that the new result is * available in the Answer. * * The Answer and the Result share the common mutex. The operations that * change/get the state in the Answer and in the Result MUST be locked. * The methods in the Results are created for this purpose. */ class Result : public Poco::RefCountedObject, public Castable { public: typedef Poco::AutoPtr<Result> Ptr; typedef Poco::ScopedLock<Result> ScopedLock; struct StatusEnum { enum Raw { PENDING, SUCCESS, FAILED, }; static EnumHelper<Raw>::ValueMap &valueMap(); }; typedef Enum<StatusEnum> Status; Result(Poco::AutoPtr<Answer> answer); /* * It internally calls the notifyUpdated(). */ void setStatus(const Status status); Status status() const; /* * Notifies the waiting threads that this Result (and its Answer) were * changed. The call sets Answer::setDirty(true). */ void notifyUpdated(); void lock(); void unlock(); protected: ~Result(); private: Status m_status; Answer &m_answer; }; }
jozhalaj/gateway
src/sonoff/SonoffSC.h
<filename>src/sonoff/SonoffSC.h<gh_stars>1-10 #pragma once #include <list> #include <Poco/SharedPtr.h> #include <Poco/Timestamp.h> #include "model/ModuleType.h" #include "model/SensorData.h" #include "net/MqttMessage.h" #include "sonoff/SonoffDevice.h" #include "util/Loggable.h" namespace BeeeOn { /** * @brief The class represents Sonoff SC device. The class * allows to process the messages from the Sonoff SC with * the custom firmware (https://github.com/xbedna62/SonoffSC_firmware.git). * Its modules are temperature, humidity, noise, dust and light. */ class SonoffSC : public SonoffDevice { public: typedef Poco::SharedPtr<SonoffSC> Ptr; static const std::string PRODUCT_NAME; SonoffSC(const DeviceID& id, const RefreshTime &refresh); ~SonoffSC(); /** * @brief Parses the MQTT message from the Sonoff SC and creates * from it SensorData. */ SensorData parseMessage(const MqttMessage& message) override; }; }
jozhalaj/gateway
src/core/PollingKeeper.h
<filename>src/core/PollingKeeper.h #pragma once #include <map> #include <Poco/Mutex.h> #include "core/DevicePoller.h" #include "core/PollableDevice.h" namespace BeeeOn { /** * @brief PollingKeeper takes care of devices that are being polled. * It cancels all polled devices it manages upon request or destruction * to avoid leaking unstopped polled devices. */ class PollingKeeper { public: PollingKeeper(); /** * @brief Cancel all registered pollable devices. */ ~PollingKeeper(); /** * @brief Configure DevicePoller to use. */ void setDevicePoller(DevicePoller::Ptr poller); /** * @brief Register the given device and schedule it into * the underlying poller. */ void schedule(PollableDevice::Ptr device); /** * @brief Cancel polling of the device represented by the * given ID and unregister it. */ void cancel(const DeviceID &id); /** * @brief Cancel all registered pollable devices. */ void cancelAll(); /** * @brief Lookup a device the PollingKeeper takes care of. */ PollableDevice::Ptr lookup(const DeviceID &id) const; private: std::map<DeviceID, PollableDevice::Ptr> m_polled; DevicePoller::Ptr m_devicePoller; mutable Poco::FastMutex m_lock; }; }
jozhalaj/gateway
src/net/MosquittoClient.h
<reponame>jozhalaj/gateway<gh_stars>1-10 #pragma once #include <list> #include <queue> #include <set> #include <string> #include <Poco/AtomicCounter.h> #include <Poco/Event.h> #include <Poco/Mutex.h> #include <Poco/SharedPtr.h> #include <Poco/Timespan.h> #include <mosquittopp.h> #include "loop/StoppableRunnable.h" #include "net/MqttClient.h" #include "util/Loggable.h" namespace BeeeOn { /** * Mosquitto client runs in a thread. Before its run * it is necessary to set following parameters: * * - host: default localhost * - port: default 1883 * - reconnect wait timeout: 5 s * - client id: default - empty */ class MosquittoClient: Loggable, protected mosqpp::mosquittopp, public StoppableRunnable, public MqttClient { public: typedef Poco::SharedPtr<MosquittoClient> Ptr; MosquittoClient(); ~MosquittoClient(); /** * Keeps communication between the client and broker working. * * @see: https://mosquitto.org/api/files/mosquitto-h.html#mosquitto_loop */ void run() override; void stop() override; void setHost(const std::string &host); void setPort(int port); /** * Subscribe to a topic. */ void setSubTopics(const std::list<std::string> &subTopics); /** * Timeout between reconnecting to the server when server * connection is lost. */ void setReconnectTimeout(const Poco::Timespan &timeout); void setClientID(const std::string &id); std::string clientID() const; /** * Publish a message on a given topic. */ void publish(const MqttMessage &msq) override; /** * Waiting for a new message according to given timeout. * Returns message, if some message is in queue, otherwise * waiting for a new message or timeout exception. * * This method should not be called by multiple threads, * received message could be given to only one thread. * * Timeout: * - 0 - non-blocking * - negative - blocking * - positive blocking with timeout */ MqttMessage receive(const Poco::Timespan &timeout) override; protected: virtual std::string buildClientID() const; /** * Non-blocking connection to broker request. * After set client name must be call MosquittoClient::connect(); */ void connect(); private: /** * Setting clientID and connection to the server. After successful connection, * it is necessary to set m_isConnected variable to true. */ bool initConnection(); void subscribeToAll(); void throwMosquittoError(int returnCode) const; /** * Message variable contains data and name of topic. This variable and associated * memory will be freed by the library after the callback completes. * * @see: https://mosquitto.org/api/files/mosquitto-h.html#mosquitto_message_callback_set */ void on_message(const struct mosquitto_message *message) override; /** * Returns message from queue. */ MqttMessage nextMessage(); private: std::string m_clientID; std::string m_host; Poco::Timespan m_reconnectTimeout; int m_port; std::set<std::string> m_subTopics; Poco::AtomicCounter m_stop; Poco::Event m_receiveEvent; Poco::Event m_reconnectEvent; Poco::FastMutex m_queueMutex; std::queue<MqttMessage> m_msgQueue; }; }
jozhalaj/gateway
src/iqrf/response/DPACoordRemoveNodeResponse.h
<filename>src/iqrf/response/DPACoordRemoveNodeResponse.h #pragma once #include "iqrf/DPAResponse.h" namespace BeeeOn { class DPACoordRemoveNodeResponse final : public DPAResponse { public: typedef Poco::SharedPtr<DPACoordRemoveNodeResponse> Ptr; /** * @returns Number of bonded nodes on the coordinator. */ size_t count() const; }; }
jozhalaj/gateway
src/bluetooth/HciInfo.h
<gh_stars>1-10 #pragma once #include <string> #include "net/MACAddress.h" // forward-declaration struct hci_dev_info; namespace BeeeOn { /** * Provides information about a hci interface. */ class HciInfo { public: HciInfo(const struct hci_dev_info &info); std::string name() const; MACAddress address() const; uint32_t aclMtu() const; uint32_t aclPackets() const; uint32_t scoMtu() const; uint32_t scoPackets() const; uint32_t rxErrors() const; uint32_t txErrors() const; uint32_t rxEvents() const; uint32_t txCmds() const; uint32_t rxAcls() const; uint32_t txAcls() const; uint32_t rxScos() const; uint32_t txScos() const; uint32_t rxBytes() const; uint32_t txBytes() const; private: std::string m_name; MACAddress m_address; uint32_t m_aclMtu; uint32_t m_scoMtu; uint32_t m_aclPackets; uint32_t m_scoPackets; uint32_t m_rxErrors; uint32_t m_txErrors; uint32_t m_rxEvents; uint32_t m_txCmds; uint32_t m_rxAcls; uint32_t m_txAcls; uint32_t m_rxScos; uint32_t m_txScos; uint32_t m_rxBytes; uint32_t m_txBytes; }; }
jozhalaj/gateway
src/commands/DeviceUnpairResult.h
#pragma once #include <set> #include "core/Result.h" #include "model/DeviceID.h" namespace BeeeOn { /** * @brief DeviceUnpairResult holds set of devices that have * been unpaired. If the set is empty, no device have been * unpaired but the operation was successful. * * The result makes possible to change the device ID asked * to be unpaired to another one or to multple ones. */ class DeviceUnpairResult : public Result { public: typedef Poco::AutoPtr<DeviceUnpairResult> Ptr; DeviceUnpairResult(Poco::AutoPtr<Answer> answer); void setUnpaired(const std::set<DeviceID> &ids); const std::set<DeviceID> &unpaired() const; private: std::set<DeviceID> m_unpaired; }; }
jozhalaj/gateway
src/zwave/ZWaveNode.h
#pragma once #include <set> #include <string> #include <Poco/Timespan.h> namespace BeeeOn { /** * @brief ZWaveNode represents information from the Z-Wave network about * a particular node. Each Z-Wave node is identified by a home ID and * node ID. The node ID is a locally unique identifier. The home ID is * a globally unique (usually random generated) defined by the hardware * controller. * * It can be in one of two states: * * - not-queried - the mutable properties are probably invalid yet * - queried - the mutable probably are valid (the device is fully queried) */ class ZWaveNode { public: /** * @brief Identity of a Z-Wave node that can be used separately * without any instance of the ZWaveNode class. */ struct Identity { const uint32_t home; const uint8_t node; Identity(const uint32_t home, const uint8_t node); Identity &operator =(const Identity &other); bool operator ==(const Identity &other) const; bool operator !=(const Identity &other) const; bool operator <(const Identity &other) const; std::string toString() const; }; /** * @brief Command class representation of a Z-Wave value. * We support only a subset of command classes that are * relevant for using with the BeeeOn system. */ class CommandClass { public: enum { BASIC = 32, SWITCH_BINARY = 37, SENSOR_BINARY = 48, SENSOR_MULTILEVEL = 49, BATTERY = 128, WAKE_UP = 132, ALARM = 113, }; CommandClass( uint8_t id, uint8_t index, uint8_t instance, const std::string &name = ""); /** * @returns command class's ID (SWITCH_BINARY, BATTERY, ...) */ uint8_t id() const; /** * @returns index of the specific value represented by the command class */ uint8_t index() const; /** * @returns identifier for situations when certain command class is duplicated */ uint8_t instance() const; /** * @returns command class's name, it can be empty if not initialized */ std::string name() const; std::string toString() const; bool operator <(const CommandClass &cc) const; private: uint8_t m_id; uint8_t m_index; uint8_t m_instance; std::string m_name; }; /** * @brief Value coming from the Z-Wave network. It holds some * data (usually sensor data) and metadata to identify the * value semantics. */ class Value { public: Value(const ZWaveNode &node, const CommandClass &cc, const std::string &value, const std::string &unit = ""); Value(const Identity &node, const CommandClass &cc, const std::string &value, const std::string &unit = ""); /** * @returns the associated node's identity */ const Identity &node() const; /** * @returns command class that's value is represented */ const CommandClass &commandClass() const; /** * @returns value in string format (raw) */ std::string value() const; /** * @returns unit that the value is represented in */ std::string unit() const; /** * Interpret the value as a boolean. If the value cannot be * represented as boolean, an exception is thrown. * * @throw Poco::SyntaxException */ bool asBool() const; /** * Interpret the value as an unsigned 32-bit number stored * in the hexadecimal format. If the value cannot be parsed, * it throws an exception. */ uint32_t asHex32() const; /** * Interpret the value as a double (real) number. * If the value cannot be parsed, it throws an exception. */ double asDouble() const; /** * Interpret the value as signed int. If the underlying value * is real (double) and the argument floor is false then an * exception is thrown. * * @param floor if the underlying cannot be interpreted as int, * and floor is true, it would be interpreted as double and floored */ int asInt(bool floor = false) const; /** * Interpret the underlying value as temperature. The supported * units are C and F (according to Z-Wave). If the value is represented * in F (Farenheit) a conversion is applied. */ double asCelsius() const; /** * Interpret the underlying value as a value of luminance. The luminance * is returned in lux. If the underlying value is represented in percent, * a conversion is applied. */ double asLuminance() const; /** * Interpret the underlying value as a value of PM 2.5. The expected and * only supported unit is ug/m3. */ double asPM25() const; /** * Interpret the underlying value as a value of time. The expected and * only supported unit is seconds. */ Poco::Timespan asTime() const; std::string toString() const; private: Identity m_node; CommandClass m_commandClass; std::string m_value; std::string m_unit; }; /** * @brief Feature flags denoting supported features of a Z-Wave node. */ enum Support { SUPPORT_LISTENING = 0x01, SUPPORT_BEAMING = 0x02, SUPPORT_ROUTING = 0x04, SUPPORT_SECURITY = 0x08, SUPPORT_ZWAVEPLUS = 0x10, }; ZWaveNode(const Identity &id, bool controller = false); /** * @returns home ID, it is always valid */ uint32_t home() const; /** * @returns node ID, it is always valid */ uint8_t node() const; /** * @returns node identity, it is always valid */ const Identity &id() const; /** * @returns true if this node is the controller of the network, * it is always valid */ bool controller() const; /** * Set bitmap of support flags. */ void setSupport(uint32_t support); /** * @returns bitmap of support flags */ uint32_t support() const; /** * Set product ID reported by the node. */ void setProductId(uint16_t id); /** * @returns product ID as reported by the node itself. */ uint16_t productId() const; /** * Set name of the node product. */ void setProduct(const std::string &name); /** * @returns name of the node product. */ std::string product() const; /** * Set product type as reported by the node itself. */ void setProductType(uint16_t type); /** * @returns product type as reported by the node itself. */ uint16_t productType() const; /** * Set vendor ID as reported by the node itself. */ void setVendorId(uint16_t id); /** * @returns vendor ID as reported by the node itself. */ uint16_t vendorId() const; /** * Set name of the node's vendor (manufacturer). */ void setVendor(const std::string &vendor); /** * @returns name of the node's vendor (manufacturer) */ std::string vendor() const; /** * Set whether this node is already queried and thus * the mutable properties are set. */ void setQueried(bool queried); /** * @returns true if this node has been fully queried */ bool queried() const; void add(const CommandClass &cc); const std::set<CommandClass> &commandClasses() const; std::string toString() const; std::string toInfoString() const; bool operator <(const ZWaveNode &node) const; private: Identity m_id; bool m_controller; bool m_queried; uint32_t m_support; uint16_t m_productId; std::string m_product; uint16_t m_vendorId; std::string m_vendor; uint16_t m_productType; std::set<CommandClass> m_commandClasses; }; }
jozhalaj/gateway
src/bluetooth/TabuLumenSmartLite.h
<reponame>jozhalaj/gateway #pragma once #include <Poco/SharedPtr.h> #include <Poco/UUID.h> #include "bluetooth/BLESmartDevice.h" #include "util/ColorBrightness.h" namespace BeeeOn { /** * @brief The class represents Tabu Lumen TL 100S Smart Light. It allows * to control all its modules. */ class TabuLumenSmartLite : public BLESmartDevice { public: typedef Poco::SharedPtr<TabuLumenSmartLite> Ptr; private: /** * UUID of characteristics to modify device status and to authorize. */ static const Poco::UUID WRITE_VALUES; static const std::vector<uint8_t> ADD_KEY; static const std::vector<uint8_t> XOR_KEY; static const std::string LIGHT_NAME; static const std::string VENDOR_NAME; enum Command { LOGIN = 0x08, OFF = 0x00, ON_ACTION = 0x01 }; public: TabuLumenSmartLite( const MACAddress& address, const Poco::Timespan& timeout, const RefreshTime& refresh, const HciInterface::Ptr hci); ~TabuLumenSmartLite(); std::list<ModuleType> moduleTypes() const override; std::string productName() const override; std::string vendor() const override; void requestModifyState( const ModuleID& moduleID, const double value) override; static bool match(const std::string& modelID); protected: void modifyStatus(const int64_t value, const HciInterface::Ptr hci); void modifyBrightness(const int64_t value, const HciInterface::Ptr hci); void modifyColor(const int64_t value, const HciInterface::Ptr hci); void writeData( const std::vector<unsigned char>& data, const HciInterface::Ptr hci) const; /** * @brief Returns authorization message that must be sent to the device * after connection so that it can be manipulated with the device. */ std::vector<uint8_t> authorizationMessage() const; /** * Encrypting and decrypting message is taken from * https://github.com/mrquincle/luminosi/blob/master/web.js */ void encryptMessage(std::vector<uint8_t> &data) const; void decryptMessage(std::vector<uint8_t> &data) const; private: ColorBrightness m_colorBrightness; }; }
jozhalaj/gateway
src/zwave/ZWaveNodeInfo.h
<reponame>jozhalaj/gateway<gh_stars>1-10 #pragma once #include <list> #include <set> #include <string> #include <openzwave/Notification.h> #include "model/DeviceID.h" #include "model/ModuleID.h" #include "model/ModuleType.h" namespace BeeeOn { /** * This class contains information about Z-Wave device (node), * for example: name of product, vendor and their identification. * It also contains identification of device (node) in BeeeOn system * (DeviceID) and values that can be measured (OpenZWave::ValueID). */ class ZWaveNodeInfo { public: typedef std::pair<OpenZWave::ValueID, ModuleType> ZWaveValuePair; ZWaveNodeInfo(); static ZWaveNodeInfo build(uint32_t homeID, uint8_t nodeID); void setPaired(bool paired); bool paired() const; void setVendorName(const std::string &name); std::string vendorName() const; void setVendorID(uint32_t id); uint32_t vendorID() const; void setProductName(const std::string &name); std::string productName() const; void setProductID(uint32_t id); uint32_t productID() const; void setPolled(bool polled); bool polled() const; void setDeviceID(const DeviceID &deviceID); DeviceID deviceID() const; void addValueID(const OpenZWave::ValueID &valueID, const ModuleType &type); std::vector<ZWaveValuePair> valueIDs() const; ModuleID findModuleID(const OpenZWave::ValueID &valueID) const; OpenZWave::ValueID findValueID(const unsigned int &index) const; ModuleType findModuleType(const OpenZWave::ValueID &valueID) const; std::list<ModuleType> moduleTypes() const; private: std::vector<ZWaveValuePair> m_zwaveValues; bool m_polled; bool m_paired; std::string m_vendorName; uint32_t m_vendorID; std::string m_productName; uint32_t m_productID; DeviceID m_deviceID; }; }
jozhalaj/gateway
src/iqrf/DPAResponse.h
#pragma once #include <string> #include "iqrf/DPAMessage.h" namespace BeeeOn { /** * @brief Each response contains a header with: * * - NADR(2B) - network address * - PNUM(1B)- peripherals number * - CMD(1B) - command identification * - HWPID(2B) - hw profile * - ErrN(1B) - DPA error code * - DpaValue(1B) - local node's value * - PData(max 59B) - peripheral data, data that was received */ class DPAResponse : public DPAMessage { public: typedef Poco::SharedPtr<DPAResponse> Ptr; enum Type { PERIPHERAL_INFO = 0x80, BONDED_NODES = 0x82, BOND_NODE = 0x84, REMOVE_NODE = 0x85, }; /** * @see https://github.com/iqrfsdk/iqrf-daemon/wiki/JsonStructureDpa-v1#response--status-codes * @see https://github.com/iqrfsdk/clibdpa/blob/master/Dpa/DPA.h */ void setErrorCode(uint8_t errCode); uint8_t errorCode() const; void setDPAValue(uint8_t dpaValue); uint8_t dpaValue() const; /** * @brief Converts the header items and peripheral data * to string that is divided by dots. */ virtual std::string toDPAString() const override; /** * @brief Parses given message into general or specific response. */ static DPAResponse::Ptr fromRaw(const std::string &data); protected: DPAResponse(); DPAResponse( DPAMessage::NetworkAddress node, uint8_t pNumber, uint8_t pCommand, uint16_t hwPID, const std::vector<uint8_t> &pData, uint8_t errorCode, uint8_t dpaValue ); private: uint8_t m_errorCode; uint8_t m_dpaValue; }; }
jozhalaj/gateway
src/util/ChecksumSensorDataParser.h
#pragma once #include "util/SensorDataParser.h" namespace BeeeOn { /** * @brief ChecksumSensorDataParser parses data serialized by the * equivalently configured ChecksumSensorDataFormatter. It first * extracts the checksum at the beginning of the given string. * Then the wrapped parser is used to parse the rest. */ class ChecksumSensorDataParser : public SensorDataParser { public: ChecksumSensorDataParser(); ChecksumSensorDataParser(SensorDataParser::Ptr parser); /** * @brief Set delimiter between the prepended checksum and the * actual data part formatted by the wrapped formatter. */ void setDelimiter(const std::string &delimiter); void setParser(SensorDataParser::Ptr parser); /** * @brief Parse the given data string. Expect it to start * with a checksum following by the given delimiter. The * rest of the string is parsed by the wrapped parser. */ SensorData parse(const std::string &data) const override; protected: /** * @brief Parse the input data in case when the preset delimiter is empty. */ SensorData parseNoDelimiter(const std::string &data) const; /** * @brief Check the given checksum and parse the content * by the configured parser. */ SensorData checkAndParse( const std::string &prefix, const std::string &content) const; private: std::string m_delimiter; SensorDataParser::Ptr m_parser; }; }
jozhalaj/gateway
src/vdev/VirtualDeviceManager.h
#pragma once #include <queue> #include <string> #include <Poco/SharedPtr.h> #include <Poco/Timestamp.h> #include <Poco/Util/IniFileConfiguration.h> #include "core/DeviceManager.h" #include "core/PollingKeeper.h" #include "vdev/VirtualDevice.h" namespace BeeeOn { /** * Ensures configuration of virtual devices from configuration file * virtual-devices.ini and it is able to send NewDeviceCommand to CommandDispatcher * when device attempts to pair. * * It can send values from modules of registered devices. * * It also ensures reaction to commands sent from server: * * - GatewayListenCommand, DeviceAcceptCommand - device attempts to pair * - DeviceSetValueCommand - modification of module value * - DeviceUnpairCommand - device attempts to unpair */ class VirtualDeviceManager : public DeviceManager { public: VirtualDeviceManager(); void setDevicePoller(DevicePoller::Ptr poller); void run() override; void stop() override; /** * Sets path to configuration file. */ void setConfigFile(const std::string &path); /** * Loads setting of virtual devices from configuration file * and stores this information. */ void installVirtualDevices(); /** * Inserts item to map of virtual devices if there is no virtual * device with given identifier. */ void registerDevice(const VirtualDevice::Ptr virtualDevice); /** * Ensures sending of NewDeviceCommand to CommandDispatcher. */ void dispatchNewDevice(VirtualDevice::Ptr device); /** * Processes information about virtual device loaded from configuration * file. */ VirtualDevice::Ptr parseDevice( Poco::AutoPtr<Poco::Util::AbstractConfiguration> cfg); /** * Processes information about virtual module loaded from configuration * file. */ VirtualModule::Ptr parseModule( Poco::AutoPtr<Poco::Util::AbstractConfiguration> cfg, const ModuleID &moduleID); /** * Plans devices that are in a map of virtual devices and are paired. */ void scheduleAllEntries(); /** * Logs information about loaded virtual devices and modules. * Detail of information can be selected from possibilities: * information, debug, trace. */ void logDeviceParsed(VirtualDevice::Ptr device); /** * @brief Reschedule virtual devices after updating the remote status. */ void handleRemoteStatus( const DevicePrefix &prefix, const std::set<DeviceID> &devices, const DeviceStatusHandler::DeviceValues &values) override; protected: void handleGeneric(const Command::Ptr cmd, Result::Ptr result) override; /** * Reacts to GatewayListenCommand. It sends NewDeviceCommand if * device is not paired. */ void doListenCommand(const GatewayListenCommand::Ptr); /** * Reacts to DeviceAcceptCommand. Device has to be stored in map * of virtual devices and it has to be unpaired. If these conditions * are fulfilled, method inserts device into a calendar, it sets device * as paired and it plans next activation (data generation) of this device. */ void doDeviceAcceptCommand(const DeviceAcceptCommand::Ptr cmd); /** * Reacts to DeviceSetValueCommand. Device has to be in map of * virtual devices, it has to be sensor and reaction has to be * set to success. */ void doSetValueCommand(const DeviceSetValueCommand::Ptr cmd); /** * Reacts to DeviceUnpairCommand. Device has to be in map of * virtual devices and it has to be paired. */ void doUnpairCommand(const DeviceUnpairCommand::Ptr cmd); private: std::map<DeviceID, VirtualDevice::Ptr> m_virtualDevicesMap; std::string m_configFile; PollingKeeper m_pollingKeeper; bool m_requestDeviceList; Poco::FastMutex m_lock; }; }
jozhalaj/gateway
src/iqrf/request/DPAOSRestartRequest.h
<reponame>jozhalaj/gateway #pragma once #include "iqrf/DPARequest.h" namespace BeeeOn { class DPAOSRestartRequest final : public DPARequest { public: typedef Poco::SharedPtr<DPAOSRestartRequest> Ptr; DPAOSRestartRequest(uint8_t node); }; }
jozhalaj/gateway
src/core/PrefixCommand.h
<filename>src/core/PrefixCommand.h #pragma once #include "core/Command.h" #include "model/DevicePrefix.h" namespace BeeeOn { /** * @brief Ancestor for Commands that are related to * a specific DevicePrefix only. */ class PrefixCommand : public Command { public: PrefixCommand(const DevicePrefix &prefix); DevicePrefix prefix() const; private: DevicePrefix m_prefix; }; }
jozhalaj/gateway
src/belkin/BelkinWemoDevice.h
#pragma once #include <list> #include <Poco/Mutex.h> #include <Poco/SharedPtr.h> #include <Poco/Timespan.h> #include <Poco/URI.h> #include <Poco/DOM/Node.h> #include <Poco/DOM/NodeIterator.h> #include "core/PollableDevice.h" #include "model/DeviceID.h" #include "model/ModuleID.h" #include "model/ModuleType.h" #include "model/SensorData.h" #include "util/Loggable.h" namespace BeeeOn { /** * @brief Abstract class representing generic BelkinWemo device. */ class BelkinWemoDevice : public PollableDevice, protected Loggable { public: typedef Poco::SharedPtr<BelkinWemoDevice> Ptr; BelkinWemoDevice(const DeviceID& id, const RefreshTime &refresh); virtual ~BelkinWemoDevice(); DeviceID deviceID() const; DeviceID id() const override; RefreshTime refresh() const override; virtual bool requestModifyState(const ModuleID& moduleID, const double value) = 0; virtual SensorData requestState() = 0; void poll(Distributor::Ptr distributor) override; virtual std::list<ModuleType> moduleTypes() const = 0; virtual std::string name() const = 0; virtual Poco::FastMutex& lock(); /** * @brief Finds the first node with the given name * and returns it's value. When the value of node si empty * returns NULL. If the node with the given name does not exist * Poco::NotFoundException is raised. */ static Poco::XML::Node* findNode(Poco::XML::NodeIterator& iterator, const std::string& name); /** * @brief Finds all nodes with the given name * and returns their values. */ static std::list<Poco::XML::Node*> findNodes(Poco::XML::NodeIterator& iterator, const std::string& name); protected: const DeviceID m_deviceId; RefreshTime m_refresh; Poco::FastMutex m_lock; }; }
jozhalaj/gateway
src/iqrf/IQRFJsonResponse.h
<reponame>jozhalaj/gateway<filename>src/iqrf/IQRFJsonResponse.h #pragma once #include "iqrf/IQRFJsonRequest.h" #include "util/Enum.h" namespace BeeeOn { class IQRFJsonResponse : public IQRFJsonRequest { public: typedef Poco::SharedPtr<IQRFJsonResponse> Ptr; struct DpaErrorEnum { enum Raw { STATUS_NO_ERROR, ERROR_FAIL, ERROR_PCMD, ERROR_PNUM, ERROR_ADDR, ERROR_DATA_LEN, ERROR_DATA, ERROR_HWPID, ERROR_NADR, ERROR_IFACE_CUSTOM_HANDLER, ERROR_MISSING_CUSTOM_DPA_HANDLER, ERROR_TIMEOUT, STATUS_CONFIRMATION = 0xFF }; static EnumHelper<Raw>::ValueMap &valueMap(); }; typedef Enum<DpaErrorEnum> DpaError; /** * @brief The structure corresponds to the composition of the field contained * within the message data->raw * https://apidocs.iqrf.org/iqrf-gateway-daemon/json/#iqrf/iqrfRaw-response-1-0-0.json */ struct RawData { std::string request; std::string requestTs; std::string confirmation; std::string confirmationTs; std::string response; std::string responseTs; }; IQRFJsonResponse(); /** * @param response contains hex values separated by dot. */ void setResponse(const std::string &response); std::string response() const; /** * @param raw Content of raw data array inside JSON data object */ void setRawData(const RawData &raw); /** * @return Converts all data to one JSON string. */ std::string toString() override; /** * DPA error from IQRF daemon. Every error code is represented using * string that describes DPA error. */ DpaError errorCode() const; void setErrorCode(const DpaError &errCode); /** * @param stat_string GW daemon API status in string form * @param stat_num GW daemon API status */ void setStatus(const std::string& statString, int statNum); /** * @param identification IQRF GW daemon instance identification */ void setGWIdentification(const std::string& identification); /** * @param request contains hex values separated by dot. */ void setRequest(const std::string &request) override; std::string request() const override; private: RawData m_rawData; DpaError m_errorCode; std::string m_insId; std::string m_statusStr; int m_status = 0; }; }
jozhalaj/gateway
src/philips/PhilipsHueBridge.h
#pragma once #include <list> #include <string> #include <Poco/Mutex.h> #include <Poco/SharedPtr.h> #include <Poco/Timespan.h> #include <Poco/Dynamic/Var.h> #include <Poco/Net/HTTPRequest.h> #include <Poco/Net/SocketAddress.h> #include "credentials/PasswordCredentials.h" #include "net/HTTPEntireResponse.h" #include "net/MACAddress.h" #include "philips/PhilipsHueBridgeInfo.h" #include "util/CryptoConfig.h" #include "util/Loggable.h" namespace BeeeOn { /** * @brief The class represents Philips Hue Bridge. * Provides functions to control the bulbs. It means turn on, turn off, * modify dim, get state of bulb. */ class PhilipsHueBridge : protected Loggable { public: friend class PhilipsHueBulb; typedef Poco::SharedPtr<PhilipsHueBridge> Ptr; typedef uint64_t BulbID; static const Poco::Timespan SLEEP_BETWEEN_ATTEMPTS; /** * @brief Creates Philips Hue Bridge. If the device do not respond in * specified timeout, Poco::TimeoutException is thrown. * @param &address IP address and port where the device is listening. * @param &timeout HTTP timeout. */ PhilipsHueBridge( const Poco::Net::SocketAddress& address, const Poco::Timespan& timeout); /** * @brief Authorization of the gateway to Philips Hue Bridge. It starts * by sending an HTTP authorization request. After that, the user has to press * the button on the bridge at a certain time. This generates a username by * which we can control the bridge. */ std::string authorize(const std::string& deviceType = "BeeeOn#gateway"); /** * @brief Prepares POST HTTP request containing request to search new devices * command and sends it to device via HTTP. If the device do not * respond in specified timeout, Poco::TimeoutException is thrown. */ void requestSearchNewDevices(); /** * @brief Prepares GET HTTP request containing request device list * command and sends it to device via HTTP. If the device do not * respond in specified timeout, Poco::TimeoutException is thrown. * @return List of bulbs. Each bulb contains a type, ordinal number and identifier. * Example: {"Dimmable light", {1, 8877665544332211}} */ std::list<std::pair<std::string, std::pair<uint32_t, PhilipsHueBridge::BulbID>>> requestDeviceList(); /** * @brief Prepares JSON message containing request modify state * command of proper device and sends it to device via HTTP. * If the device do not respond in specified timeout, * Poco::TimeoutException is thrown. * @return If the request was successful or not. */ bool requestModifyState( const uint32_t ordinalNumber, const std::string& capability, const Poco::Dynamic::Var value); /** * @brief Prepares GET HTTP request containing request state * of proper device command and sends it to device via HTTP. * If the device do not respond in specified timeout, * Poco::TimeoutException is thrown. Return the body of HTTP response. */ std::string requestDeviceState(const uint32_t ordinalNumber); Poco::Net::SocketAddress address() const; void setAddress(const Poco::Net::SocketAddress& address); MACAddress macAddress() const; std::string username() const; void setCredentials(const Poco::SharedPtr<PasswordCredentials> credential, const Poco::SharedPtr<CryptoConfig> config); uint32_t countOfBulbs(); Poco::FastMutex& lock(); PhilipsHueBridgeInfo info(); private: void requestDeviceInfo(); /** * @brief Decodes BulbID from a string which is in format MAC address - endpoind id * (AA:BB:CC:DD:EE:FF:00:11-XX). */ PhilipsHueBridge::BulbID decodeBulbID(const std::string& strBulbID) const; /** * @brief Method is called by constructor of PhilipsBulb. */ void incrementCountOfBulbs(); /** * @brief Method is called by destructor of PhilipsBulb. */ void decrementCountOfBulbs(); HTTPEntireResponse sendRequest( Poco::Net::HTTPRequest& request, const std::string& message, const Poco::Net::SocketAddress& address, const Poco::Timespan& timeout); private: Poco::Net::SocketAddress m_address; MACAddress m_macAddr; Poco::SharedPtr<PasswordCredentials> m_credential; Poco::SharedPtr<CryptoConfig> m_cryptoConfig; Poco::FastMutex m_lockCountOfBulbs; int m_countOfBulbs; Poco::FastMutex m_lock; Poco::Timespan m_httpTimeout; }; }
jozhalaj/gateway
src/hotplug/AbstractHotplugMonitor.h
<filename>src/hotplug/AbstractHotplugMonitor.h #pragma once #include <list> #include <string> #include "hotplug/HotplugListener.h" #include "util/Loggable.h" namespace BeeeOn { class HotplugEvent; class AbstractHotplugMonitor : protected Loggable { public: void registerListener(HotplugListener::Ptr listener); protected: AbstractHotplugMonitor(); void logEvent(const HotplugEvent &event, const std::string &action) const; void fireAddEvent(const HotplugEvent &event); void fireRemoveEvent(const HotplugEvent &event); void fireChangeEvent(const HotplugEvent &event); void fireMoveEvent(const HotplugEvent &event); private: std::list<HotplugListener::Ptr> m_listeners; }; }
jozhalaj/gateway
src/server/GWSOptimisticExporter.h
<filename>src/server/GWSOptimisticExporter.h<gh_stars>1-10 #pragma once #include <set> #include <Poco/AtomicCounter.h> #include <Poco/Mutex.h> #include "core/Exporter.h" #include "gwmessage/GWMessage.h" #include "server/GWSConnector.h" #include "server/GWSListener.h" #include "util/Loggable.h" namespace BeeeOn { /** * @brief GWSOptimisticExporter implements exporting via GWSConnector. * It wraps the given SensorData instances and pass them to the * GWSConnector::send(). It also keeps track of the connectivity * to the remote server. Exporting is implemented optimistically, * we assume no network failures. If the number of non-confirmed * exports reached the limit exportNonConfirmed, no more exports * occures until a confirmation comes. */ class GWSOptimisticExporter : public Exporter, public GWSListener, Loggable { public: typedef Poco::SharedPtr<GWSOptimisticExporter> Ptr; GWSOptimisticExporter(); void setConnector(GWSConnector::Ptr connector); void setExportNonConfirmed(int count); /** * @brief Ship the given data via GWSConnector::send() to the * remote server. The connectivity status of the GWSConnector * is considered. * * @returns true if GWSConnector::send() succeeded, false if * there is no connectivity, no confirmations for the configured * number of outstanding exports or the GWSConnector::send() fails. */ bool ship(const SensorData &data) override; /** * @brief Process confirmations of exported data. */ void onOther(const GWMessage::Ptr message) override; /** * @brief Notice that the GWSConnector is connected. */ void onConnected(const GWSListener::Address &) override; /** * @brief Notice that the GWSConnector is disconnected. */ void onDisconnected(const GWSListener::Address &) override; private: size_t m_exportNonConfirmed; GWSConnector::Ptr m_connector; Poco::AtomicCounter m_connected; std::set<GlobalID> m_exported; Poco::FastMutex m_lock; }; }
jozhalaj/gateway
src/server/ServerAnswer.h
#pragma once #include <Poco/AutoPtr.h> #include "core/Answer.h" #include "model/GlobalID.h" #include "server/GWMessageContext.h" namespace BeeeOn { /** * @brief ServerAnswer extends regular Answer with ID of * corresponding received GWMessage, which was translated to dispatched * Command. This ID is used to create GWMessage to inform server * about execution status of this Command. */ class ServerAnswer : public Answer { public: typedef Poco::AutoPtr<ServerAnswer> Ptr; ServerAnswer(AnswerQueue &answerQueue, const GlobalID &id); ServerAnswer(const ServerAnswer&) = delete; void setID(const GlobalID &id); /** * Convert Answer to appropriate GWResponseWithAckContext if possible. */ GWResponseWithAckContext::Ptr toResponse(const GWResponse::Status &status) const; GlobalID id() const; private: GlobalID m_id; }; }
jozhalaj/gateway
src/belkin/BelkinWemoSwitch.h
#pragma once #include <list> #include <string> #include <Poco/Net/SocketAddress.h> #include <Poco/SharedPtr.h> #include <Poco/Timespan.h> #include "belkin/BelkinWemoStandaloneDevice.h" #include "model/ModuleType.h" #include "model/SensorData.h" namespace BeeeOn { /** * @brief The class represents Belkin WeMo Switch F7C027fr. * Provides functions to control the switch. It means turn on, turn off, get state. */ class BelkinWemoSwitch : public BelkinWemoStandaloneDevice { public: typedef Poco::SharedPtr<BelkinWemoSwitch> Ptr; /** * @brief Creates belkin wemo switch. If the device is not on network * throws Poco::TimeoutException also in this case it is blocking. * @param &address IP address and port where the device is listening. * @param &timeout HTTP timeout. */ BelkinWemoSwitch( const Poco::Net::SocketAddress& address, const Poco::Timespan &httpTimeout, const RefreshTime &refresh); ~BelkinWemoSwitch(); /** * @brief It sets the switch to the given state. */ bool requestModifyState(const ModuleID& moduleID, const double value) override; /** * @brief Prepares SOAP message containing request state * command and sends it to device via HTTP. If the device is * not on network throws Poco::TimeoutException also in this * case it is blocking. Request current state of the device * and return it as SensorData. * @return SensorData. */ SensorData requestState() override; std::list<ModuleType> moduleTypes() const override; std::string name() const override; /** * @brief It compares two switches based on DeviceID. */ bool operator==(const BelkinWemoSwitch& bws) const; }; }
jozhalaj/gateway
src/zwave/ZWaveMapperRegistry.h
<gh_stars>1-10 #pragma once #include <list> #include <string> #include <Poco/Nullable.h> #include <Poco/SharedPtr.h> #include "model/DeviceID.h" #include "model/ModuleType.h" #include "model/SensorValue.h" #include "zwave/ZWaveNode.h" namespace BeeeOn { /** * @brief ZWaveMapperRegistry is mostly intended to map Z-Wave specific data type * hierarchy to BeeeOn ModuleType. Based on the ZWaveNode metadata, it constructs * or looks up an appropriate Mapper object that knows how to interpret the * ZWaveNode::Value instances to the rest of the BeeeOn system. */ class ZWaveMapperRegistry { public: typedef Poco::SharedPtr<ZWaveMapperRegistry> Ptr; /** * @brief Map the ZWaveNode-specific data to the BeeeOn-specific ones. * It is assumed that the ZWaveNode instance (or its Value) passed into * the Mapper is the one used by ZWaveMapperRegistry::lookup(). */ class Mapper { public: typedef Poco::SharedPtr<Mapper> Ptr; Mapper(const ZWaveNode::Identity &id, const std::string &product); virtual ~Mapper(); /** * @brief The mapper can sometimes need to mangle a device ID * for a Z-Wave node. This is possible by overriding this method. * * The default implementation builds the ID from the home ID and * node ID. * * @returns ID of the given Z-Wave node identity */ virtual DeviceID buildID() const; /** * @returns fixed product name of the node if needed */ virtual std::string product() const; /** * @returns list of ModuleType instance for a particular Z-Wave node type */ virtual std::list<ModuleType> types() const = 0; /** * @brief Find module type by ID. */ Poco::Nullable<ModuleType> findType(const ModuleID &id) const; /** * @returns SensorValue representation of the ZWaveNode::Value instance */ virtual SensorValue convert(const ZWaveNode::Value &value) const = 0; /** * @returns Z-Wave value representing the given value of that module ID. * * @throws Poco::NotFoundException if no such controllable module ID is available * @throws Poco::NotImplementedException when such module ID is unsupported * for changes by this mapper */ virtual ZWaveNode::Value convert(const ModuleID &id, double value) const; protected: static DeviceID mangleID(const DeviceID &id, uint8_t bits); ZWaveNode::Identity identity() const; private: ZWaveNode::Identity m_identity; std::string m_product; }; virtual ~ZWaveMapperRegistry(); /** * @brief Try to resolve a Mapper implementation suitable for the given Z-Wave node. */ virtual Mapper::Ptr resolve(const ZWaveNode &node) = 0; }; }
jozhalaj/gateway
src/vektiva/VektivaSmarwi.h
<reponame>jozhalaj/gateway #pragma once #include <list> #include "model/DeviceID.h" #include "model/ModuleID.h" #include "model/ModuleType.h" #include "net/MqttClient.h" #include "net/MACAddress.h" #include "util/Loggable.h" #include "vektiva/VektivaSmarwiStatus.h" namespace BeeeOn { /** * @brief The class represents a standalone device Smarwi. * It allows to communicate with the actual device via MQTT client and * thus control it. */ class VektivaSmarwi : protected Loggable { public: typedef Poco::SharedPtr<VektivaSmarwi> Ptr; VektivaSmarwi( const MACAddress& macAddr, const std::string &remoteID); std::string remoteID(); MACAddress macAddress(); DeviceID deviceID(); std::list<ModuleType> moduleTypes() const; Poco::Net::IPAddress ipAddress(); void setIpAddress(const Poco::Net::IPAddress &ipAddress); std::string productName(); /** * @brief Attempts to change status of the device. * @param moduleID - what module to change * @param value - to what value to change to * @param mqttClient - which MQTT client to use */ void requestModifyState( const ModuleID &moduleID, double value, MqttClient::Ptr mqttClient); /** * @brief Creates Smarwi sensor data to send to registered exporters. * @param smarwiStatus - status of Smarwi status * @return SensorData - sensor data created out of SmarWiStatus */ SensorData createSensorData(const VektivaSmarwiStatus &smarwiStatus); /** * @brief Called internally when constructing the instance. * Creates DeviceID based on Mac address of device. * @return DeviceID - DeviceID created out of MAC address provided */ static DeviceID buildDeviceID( const MACAddress &macAddrStr); /** * @brief Constructs an MQTT message with the topic * "ion/<remoteId>/%<macAddress>/cmd" and message specified * in the command parameter. * @param remoteId - remoteId of the user, can be found in Smarwi settings * @param macAddress - mac address of Smarwi * @param command - command to send to Smarwi * @return MqttMessage on success */ static MqttMessage buildMqttMessage( const std::string &remoteId, const std::string &macAddress, const std::string &command); /** * @brief Parses Smarwi's status response to an object which is returned * if parsing is successful. * @param rcvmsg MQTT message received from Smarwi after status request * @return VektivaSmarwiStatus object representation of SmarWi * status message */ static VektivaSmarwiStatus parseStatusResponse( std::string &rcvmsg); protected: /** * @brief Function checks if module id and it's value is valid and if so, * publishes a command to change state of Smarwi. * @param moduleID - ID of the module * @param value - intended value * @param mqttClient - client ptr which will publish the message */ void publishModifyStateCommand( const ModuleID &moduleID, double value, MqttClient::Ptr mqttClient); /** * @brief After command to modify state was published, this function waits * until the message with correct status is received. * @param mqttClient - client ptr which will receive message */ void confirmStateModification( MqttClient::Ptr mqttClient); /** * @breif Builds simple topic regex to validate the incoming message' topic. * @return regex in string */ static std::string buildTopicRegex( const std::string &remoteId, const std::string &macAddress, const std::string &lastSegment); private: DeviceID m_deviceId; std::string m_remoteID; MACAddress m_macAddress; Poco::Net::IPAddress m_ipAddress; }; }
jozhalaj/gateway
src/psdev/PressureSensorManager.h
#pragma once #include <list> #include <string> #include <Poco/SharedPtr.h> #include <Poco/Timespan.h> #include "commands/DeviceAcceptCommand.h" #include "commands/DeviceUnpairCommand.h" #include "commands/GatewayListenCommand.h" #include "core/DeviceManager.h" #include "model/DeviceID.h" #include "model/ModuleType.h" #include "model/RefreshTime.h" namespace BeeeOn { /** * Manager for BeeeOn gateway's internal air pressure sensor. * Actuall value is obtained by reading from specified file typically * located in sysfs. * * This class instance is restricted for managing only one physical device * with one module representing pressure. * * Measured values are reported periodically with specified refresh time. * * This file is typically named "pressure0_input" */ class PressureSensorManager : public DeviceManager { public: PressureSensorManager(); ~PressureSensorManager(); void run() override; void stop() override; void setRefresh(const Poco::Timespan &refresh); /** * @brief sets the Path to Air Pressure Sensor device * entry output file. Reading from this file invoke measuring * of sensoric value and returns current measured Air pressure. */ void setPath(const std::string &path); void setVendor(const std::string &vendor); /** * @brief sets the expected unit, conversion of this unit * needs to be made before shipping measured value. */ void setUnit(const std::string &unit); /** * @brief Wake-up the main thread when received new status. */ void handleRemoteStatus( const DevicePrefix &prefix, const std::set<DeviceID> &devices, const DeviceStatusHandler::DeviceValues &values) override; protected: void handleAccept(const DeviceAcceptCommand::Ptr cmd) override; AsyncWork<>::Ptr startDiscovery(const Poco::Timespan &timeout) override; AsyncWork<std::set<DeviceID>>::Ptr startUnpair( const DeviceID &id, const Poco::Timespan &timeout) override; private: /** * @brief read value of air pressure and ship it to the Distributor. */ void shipValue(); DeviceID pairedID(); /** * @brief create DeviceID with PREFIX_PRESSURE_SENSOR. Suffix * is calculated by hash of specified path to device output file. */ DeviceID buildID(const std::string &path); /** * @brief convert the measured value to [hPa] for export of the data, based * on the set unit. */ double convertToHPA(const double value); private: RefreshTime m_refresh; std::string m_vendor; std::string m_path; std::string m_unit; }; }
jozhalaj/gateway
src/commands/DeviceSearchCommand.h
#pragma once #include <string> #include <Poco/Nullable.h> #include <Poco/Timespan.h> #include <Poco/Net/IPAddress.h> #include "core/PrefixCommand.h" #include "model/DeviceCriteria.h" #include "model/DevicePrefix.h" #include "net/MACAddress.h" namespace BeeeOn { /** * @brief DeviceSearchCommand requests a device manager to start * searching for a single device specified by either its: * * - IP address * - MAC address * - serial number * * This command is not mandatory to be supported. */ class DeviceSearchCommand : public PrefixCommand { public: typedef Poco::AutoPtr<DeviceSearchCommand> Ptr; DeviceSearchCommand( const DevicePrefix &prefix, const DeviceCriteria &criteria, const Poco::Timespan &duration); DeviceCriteria criteria() const; bool hasIPAddress() const; Poco::Net::IPAddress ipAddress() const; bool hasMACAddress() const; MACAddress macAddress() const; bool hasSerialNumber() const; uint64_t serialNumber() const; Poco::Timespan duration() const; std::string toString() const override; private: DeviceCriteria m_criteria; Poco::Timespan m_duration; }; }
jozhalaj/gateway
src/bluetooth/BeeWiSmartLite.h
<reponame>jozhalaj/gateway #pragma once #include <Poco/SharedPtr.h> #include <Poco/UUID.h> #include "bluetooth/BeeWiDevice.h" namespace BeeeOn { /** * @brief The class represents BeeWi smart led light. It allows * to gather and to control all its modules. */ class BeeWiSmartLite : public BeeWiDevice { public: typedef Poco::SharedPtr<BeeWiSmartLite> Ptr; static const std::string NAME; private: /** * UUID of characteristics containing actual values of all sensor modules. */ static const Poco::UUID ACTUAL_VALUES; /** * UUID of characteristics to modify device status. */ static const Poco::UUID WRITE_VALUES; public: enum Command { ON_OFF = 0x10, COLOR_TEMPERATURE = 0x11, BRIGHTNESS = 0x12, COLOR = 0x13 }; BeeWiSmartLite( const MACAddress& address, const Poco::Timespan& timeout, const RefreshTime& refresh, const HciInterface::Ptr hci); ~BeeWiSmartLite(); void requestModifyState( const ModuleID& moduleID, const double value) override; /** * <pre> * | ID (1 B) | 1 B | on/off (1 B) | 1 B | brightness (4 b) | color temperature (4 b) | color (3 B) | * </pre> */ SensorData parseAdvertisingData( const std::vector<unsigned char>& data) const override; static bool match(const std::string& modelID); protected: unsigned int brightnessToPercentages(const double value) const; unsigned char brightnessFromPercentages(const double percents) const; unsigned int colorTempToKelvins(const double value) const; unsigned char colorTempFromKelvins(const double temperature) const; }; }
jozhalaj/gateway
src/nemea/fields.h
<filename>src/nemea/fields.h #ifndef _UR_FIELDS_H_ #define _UR_FIELDS_H_ /************* THIS IS AUTOMATICALLY GENERATED FILE, DO NOT EDIT *************/ #include <unirec/unirec.h> #define F_ACKCount 0 #define F_ACKCount_T double #define F_ACKWaiting 1 #define F_ACKWaiting_T double #define F_BYTE 2 #define F_BYTE_T double #define F_CANCount 3 #define F_CANCount_T double #define F_CMDCLASS 4 #define F_CMDCLASS_T double #define F_GENRE 5 #define F_GENRE_T double #define F_GW_ID 6 #define F_GW_ID_T uint64_t #define F_DEV_ADDR 7 #define F_DEV_ADDR_T uint64_t #define F_INDEX 8 #define F_INDEX_T double #define F_INSTANCE 9 #define F_INSTANCE_T double #define F_NAKCount 10 #define F_NAKCount_T double #define F_OOFCount 11 #define F_OOFCount_T double #define F_SOFCount 12 #define F_SOFCount_T double #define F_TIME 13 #define F_TIME_T ur_time_t #define F_TYPE 14 #define F_TYPE_T double #define F_VALUE 15 #define F_VALUE_T double #define F_aclMtu 16 #define F_aclMtu_T double #define F_aclPackets 17 #define F_aclPackets_T double #define F_address 18 #define F_address_T double #define F_average 19 #define F_average_T double #define F_averageRequestRTT 20 #define F_averageRequestRTT_T double #define F_averageResponseRTT 21 #define F_averageResponseRTT_T double #define F_badChecksum 22 #define F_badChecksum_T double #define F_badroutes 23 #define F_badroutes_T double #define F_broadcastReadCount 24 #define F_broadcastReadCount_T double #define F_broadcastWriteCount 25 #define F_broadcastWriteCount_T double #define F_callbacks 26 #define F_callbacks_T double #define F_dropped 27 #define F_dropped_T double #define F_err_value 28 #define F_err_value_T double #define F_homeID 29 #define F_homeID_T double #define F_lastRequestRTT 30 #define F_lastRequestRTT_T double #define F_lastResponseRTT 31 #define F_lastResponseRTT_T double #define F_moving_average 32 #define F_moving_average_T double #define F_moving_median 33 #define F_moving_median_T double #define F_moving_variance 34 #define F_moving_variance_T double #define F_netBusy 35 #define F_netBusy_T double #define F_noACK 36 #define F_noACK_T double #define F_nodeID 37 #define F_nodeID_T double #define F_nonDelivery 38 #define F_nonDelivery_T double #define F_notIdle 39 #define F_notIdle_T double #define F_profile_value 40 #define F_profile_value_T double #define F_quality 41 #define F_quality_T double #define F_readAborts 42 #define F_readAborts_T double #define F_readCount 43 #define F_readCount_T double #define F_receiveDuplications 44 #define F_receiveDuplications_T double #define F_receiveUnsolicited 45 #define F_receiveUnsolicited_T double #define F_receivedCount 46 #define F_receivedCount_T double #define F_retries 47 #define F_retries_T double #define F_routedBusy 48 #define F_routedBusy_T double #define F_rxAcls 49 #define F_rxAcls_T double #define F_rxBytes 50 #define F_rxBytes_T double #define F_rxErrors 51 #define F_rxErrors_T double #define F_rxEvents 52 #define F_rxEvents_T double #define F_rxScos 53 #define F_rxScos_T double #define F_scoMtu 54 #define F_scoMtu_T double #define F_scoPackets 55 #define F_scoPackets_T double #define F_sentCount 56 #define F_sentCount_T double #define F_sentFailed 57 #define F_sentFailed_T double #define F_txAcls 58 #define F_txAcls_T double #define F_txBytes 59 #define F_txBytes_T double #define F_txCmds 60 #define F_txCmds_T double #define F_txErrors 61 #define F_txErrors_T double #define F_txScos 62 #define F_txScos_T double #define F_writeCount 63 #define F_writeCount_T double #define F_EVENT_TYPE 64 #define F_EVENT_TYPE_T double #define F_alert_desc 65 #define F_alert_desc_T char #define F_cmd 66 #define F_cmd_T char #define F_profile_key 67 #define F_profile_key_T char #define F_ur_key 68 #define F_ur_key_T char extern uint16_t ur_last_id; extern ur_static_field_specs_t UR_FIELD_SPECS_STATIC; extern ur_field_specs_t ur_field_specs; #endif
jozhalaj/gateway
src/conrad/ConradDeviceManager.h
<reponame>jozhalaj/gateway #pragma once #include <string> #include <Poco/Timespan.h> #include <Poco/JSON/Object.h> #include <Poco/URI.h> #include "core/DeviceManager.h" #include "conrad/ConradDevice.h" #include "model/DeviceID.h" #include "util/BlockingAsyncWork.h" #include "util/JsonUtil.h" namespace BeeeOn { /** * @brief The class implements the work with Conrad devices. Allows us * to process and execute the commands from server and gather * data from the devices. This class requires ZMQ interface that is * available at https://github.com/pepa-cz/conrad-interface. */ class ConradDeviceManager : public DeviceManager { public: ConradDeviceManager(); void run() override; void stop() override; /** * @brief Sets command ZMQ interface. */ void setCmdZmqIface(const std::string &cmdZmqIface); /** * @brief Sets event ZMQ interface. */ void setEventZmqIface(const std::string &eventZmqIface); protected: AsyncWork<>::Ptr startDiscovery(const Poco::Timespan &timeout) override; AsyncWork<std::set<DeviceID>>::Ptr startUnpair( const DeviceID &id, const Poco::Timespan &) override; void handleAccept(const DeviceAcceptCommand::Ptr cmd) override; /** * @brief Send request via ZMQ conrad interface and returns response. */ Poco::JSON::Object::Ptr sendCmdRequest(const std::string &request); /** * @brief Processes the incoming ZMQ message, which means creating * a new device or sending the gathered data to the server. */ void processMessage(const std::string &message); /** * @brief Creates instance of Conrad device appends it into m_devices. */ void createNewDeviceUnlocked(const DeviceID &deviceID, const std::string &type); private: Poco::URI m_cmdZmqIface; Poco::URI m_eventZmqIface; Poco::FastMutex m_devicesMutex; std::map<DeviceID, ConradDevice::Ptr> m_devices; }; }
jozhalaj/gateway
src/vektiva/VektivaDeviceManager.h
<filename>src/vektiva/VektivaDeviceManager.h #pragma once #include <vector> #include <Poco/Mutex.h> #include "core/AbstractSeeker.h" #include "core/DeviceManager.h" #include "model/DeviceID.h" #include "net/MqttClient.h" #include "net/MACAddress.h" #include "util/BlockingAsyncWork.h" #include "vektiva/VektivaSmarwi.h" namespace BeeeOn { /** * @brief Vektiva device manager provides an easy way to manage * devices that are compatible with implemented interface. * In the current state it's Smarwi windows maintainer. */ class VektivaDeviceManager : public DeviceManager { public: /** * @brief Provides searching of Vektiva devices on network via MQTT messages * in an own thread. */ class VektivaSeeker : public AbstractSeeker { public: typedef Poco::SharedPtr<VektivaSeeker> Ptr; VektivaSeeker(VektivaDeviceManager &parent, const Poco::Timespan &duration); protected: /** * Seeking for devices, processing and checking whether seek interval * timed out. * @param control */ void seekLoop(StopControl &) override; private: VektivaDeviceManager &m_parent; }; VektivaDeviceManager(); void run() override; void stop() override; void setMqttClient(MqttClient::Ptr mqttClient); void setStatusMqttClient(MqttClient::Ptr mqttClient); void setReceiveTimeout(const Poco::Timespan &timeout); protected: AsyncWork<>::Ptr startDiscovery(const Poco::Timespan &timeout) override; AsyncWork<std::set<DeviceID>>::Ptr startUnpair( const DeviceID &id, const Poco::Timespan &) override; AsyncWork<double>::Ptr startSetValue( const DeviceID &id, const ModuleID &module, const double value, const Poco::Timespan &) override; void handleAccept(const DeviceAcceptCommand::Ptr cmd) override; /** * @brief New device is being processed. If true is returned, * NewDeviceCommand can be dispatched. * @param newDevice the device to process * @return true on success, false otherwise */ bool updateDevice(VektivaSmarwi::Ptr newDevice); /** * @brief Finds a device with the corresponding device ID * and attempts to change the state of the selected module ID. * @param deviceID ID of the device to be modified * @param moduleID ID of the module to be modified * @param value value to change to * @throws InvalidArgumentException thrown when no device is found */ void modifyValue( const DeviceID &deviceID, const ModuleID &moduleID, const double value); /** * @brief Groups all actions that are done * when "status" message is received. * @param mqttMessage received by MQTT client */ void statusMessageAction(MqttMessage &mqttMessage); /** * @brief Groups all actions that are done * when "online" message is received. * @param mqttMessage received by MQTT client */ void onlineMessageAction(MqttMessage &mqttMessage); /** * @brief Clears all messages buffered in the MQTT client to assure * there are no previous messages when attempting to contact a device. */ void clearMqttMessageBuffer(); /** * @brief Parses the received message and according to its' content, * correct actions are performed. * @param message a message received by the MQTT client */ void analyzeMessage(MqttMessage &mqttMessage); /** * @brief Waits for a specified amount of time for a message * with the last segment of the topic equal to lastSegment argument * and device properties. * @param timeout how long to wait for the status message * @param lastSegment in the topic * @param device Vektiva device * @throws TimeoutException if timeout occured * @return MqttMessage */ MqttMessage messageReceivedInTime( const std::string &lastSegment, VektivaSmarwi::Ptr device); /** * @brief Sends Smarwi status to the exporters. * @param deviceId device ID of the device that has changed status * @param smarwiStatus status of Smarwi */ void shipSmarwiStatus( const DeviceID &deviceId, const VektivaSmarwiStatus &smarwiStatus); /** * @brief Dispatches NewDeviceCommand. * @param device device to dispatch */ void dispatchNewDevice(VektivaSmarwi::Ptr device); /** * @brief When status message is updated, info is parsed and device pointer * passed in argument is updated with info from the message. * @param timeout how long to wait for the status message * @param device Vektiva device * @return true if status message arrived, false otherwise */ bool receiveStatusMessageAndUpdate( VektivaSmarwi::Ptr device); /** * @brief Function to update any relevant info * that can be updated (e.g. IP address) * @param device device to update * @param smarwiStatus update with this data */ void updateDeviceInfo( VektivaSmarwi::Ptr device, const VektivaSmarwiStatus &smarwiStatus); /** * @brief Function to validate topic in received message * Last two parameters are optional and can either specify the exact * Remote ID and MAC address or if left blank, they'll check for rules * that topic have to have. * * Regex explained * ^ - regex from the beginning * ion/ - basic prefix for Smarwi * [^#\/]+ OR <REMOTEID - can input anything as RemoteID except # and / OR * topic has to be equal RemoteId specified as the parameter * /% - delimiter * [a-fA-F0-9]{12} OR <MACADDR> - any MAC address OR exact MAC address * specified in the parameter * /<LASTSEGMENT> - type of the message e.g. status / online / cmd * $ - until the end * * Examples: * isTopicValid( * "ion/dowarogxby/%aabbccaabbcc/online", * "online", * "dowarogxby", * "aabbccaabbcc") * returns true because every segment of the topic is * equal to the corresponding segments. * * isTopicValid( * "ion/dowarogxby/%aabbccaabbcc/status", * "online") * returns false because the last segment doesn't match * @param topic topic of received message * @param lastSegment is what should topic contain as the last word * @param remoteId remoteId that should topic be equal to * @param macAddr MAC address that should topic be equal to * @return true if valid, false otherwise */ bool isTopicValid( const std::string &topic, const std::string &lastSegment, const std::string &remoteId = "", const std::string &macAddr = ""); /** * @brief Exctracts Remote ID and MAC address from MQTT message' topic. * @param topic topic of received message * @return std::pair<std::string, std::string> First is a Remote ID, * the second is a MAC address. */ std::pair<std::string, std::string> retrieveDeviceInfoFromTopic(const std::string &topic); /** * @brief Escapes inputted string from regex control characters * @param regexString string to be escaped */ void escapeRegexString(std::string &regexString); private: /** * @brief Mutex for shared access to m_devices. */ Poco::FastMutex m_devicesMutex; /** * @brief Mutex for shared access to the MQTT client for manipulation * with Smarwis. */ Poco::FastMutex m_clientMqttMutex; /** * @brief List of found devices. */ std::map<DeviceID, VektivaSmarwi::Ptr> m_devices; /** * @brief MQTT client instance to manipulate with Smarwis. */ MqttClient::Ptr m_mqttClient; /** * @brief MQTT client instance which sole purpose is to receive messages * and analyze them. It is only used in the main loop and should not be * used anywhere else. */ MqttClient::Ptr m_mqttStatusClient; Poco::Timespan m_receiveTimeout; }; }
jozhalaj/gateway
src/zwave/SpecificZWaveMapperRegistry.h
#pragma once #include <map> #include <string> #include <Poco/SharedPtr.h> #include <Poco/Instantiator.h> #include "util/Loggable.h" #include "zwave/ZWaveMapperRegistry.h" namespace BeeeOn { /** * @brief SpecificZWaveMapperRegistry implements the method resolve() * generically. The subclass of SpecificZWaveMapperRegistry should * register a special instantiator creating the appropriate Mapper * implementation based on the vendor and product IDs of Z-Wave nodes. */ class SpecificZWaveMapperRegistry : public ZWaveMapperRegistry, protected Loggable { public: SpecificZWaveMapperRegistry(); Mapper::Ptr resolve(const ZWaveNode &node) override; /** * @brief Set the spec mapping where the map key is a string * in form: <code>VENDOR:PRODUCT</code> and the value is the * name of MapperInstantiator to be used. */ void setSpecMap(const std::map<std::string, std::string> &specMap); protected: /** * @brief Specification of a Z-Wave node to match. */ struct Spec { const uint16_t vendor; const uint16_t product; bool operator <(const Spec &other) const; std::string toString() const; static Spec parse(const std::string &input); }; /** * @brief Instantiator of specific Mapper implementations. */ class MapperInstantiator { public: typedef Poco::SharedPtr<MapperInstantiator> Ptr; virtual ~MapperInstantiator(); virtual Mapper::Ptr create(const ZWaveNode &node) = 0; }; /** * @brief Template implementation of MapperInstantiator creating * MapperType instances having constructor specified as: * <code>MapperType(const ZWaveNode::Identity &, const std::string &)</code>. */ template <typename MapperType> class SimpleMapperInstantiator : public MapperInstantiator { public: Mapper::Ptr create(const ZWaveNode &node) override { return new MapperType(node.id(), node.product()); } }; /** * @brief The subclass would call this method for each instantiator * type it offers. The name of instantiator is referred from the * specMap property. * * @see setSpecMap() */ void registerInstantiator( const std::string &name, MapperInstantiator::Ptr instantiator); private: typedef std::map<std::string, MapperInstantiator::Ptr> InstantiatorsMap; InstantiatorsMap m_instantiators; std::map<Spec, InstantiatorsMap::iterator> m_specMap; }; }
jozhalaj/gateway
src/zwave/OZWNotificationEvent.h
<filename>src/zwave/OZWNotificationEvent.h #pragma once #include <Notification.h> #include <Poco/Nullable.h> namespace BeeeOn { /** * @brief Low-level OpenZWave notification event. Because, the OpenZWave::Notification * cannot be copied nor cloned, we have to represent it explicitly and copy all its * contents. * * @see https://github.com/OpenZWave/open-zwave/blob/master/cpp/src/Notification.h */ class OZWNotificationEvent { public: /** * Copy contents of the given notification into the event * representation. */ OZWNotificationEvent(const OpenZWave::Notification &notification); /** * Shortcut to access home ID. */ uint32_t homeID() const { return m_valueId.GetHomeId(); } /** * Shortcut to access node ID. */ uint8_t nodeID() const { return m_valueId.GetNodeId(); } /** * @returns type of notification. */ OpenZWave::Notification::NotificationType type() const; /** * @returns identification of the reported value. * @see OpenZWave::ValueID */ OpenZWave::ValueID valueID() const; /** * Note different semantics at least for notifications of * types Type_SceneEvent, Type_Notification, Type_ControllerCommand, * Type_CreateButton, Type_DeleteButton, Type_ButtonOn, Type_ButtonOff, * Type_Group. * * @returns byte value with semantics specific for each type. * @see OpenZWave::Notification */ uint8_t byte() const; /** * The result is valid only for types Type_NodeEvent * and Type_ControllerCommand. * * @returns event as reported by notifications of types * NodeEvent and ControllerCommand. * @see OpenZWave::Notification */ Poco::Nullable<uint8_t> event() const; private: OpenZWave::Notification::NotificationType m_type; OpenZWave::ValueID m_valueId; uint8_t m_byte; Poco::Nullable<uint8_t> m_event; }; }
jozhalaj/gateway
src/hotplug/HotplugListener.h
#pragma once #include <Poco/SharedPtr.h> namespace BeeeOn { class HotplugEvent; class HotplugListener { public: typedef Poco::SharedPtr<HotplugListener> Ptr; virtual ~HotplugListener(); virtual void onAdd(const HotplugEvent &event); virtual void onRemove(const HotplugEvent &event); virtual void onChange(const HotplugEvent &event); virtual void onMove(const HotplugEvent &event); }; }
jozhalaj/gateway
src/conrad/WirelessShutterContact.h
#pragma once #include <list> #include <Poco/SharedPtr.h> #include "conrad/ConradDevice.h" #include "model/SensorData.h" namespace BeeeOn { /** * @brief The class represents a standalone device Conrad Wireless shutter * contact. It allows to communicate with the device via Conrad interface. */ class WirelessShutterContact : public ConradDevice { public: typedef Poco::SharedPtr<WirelessShutterContact> Ptr; static const std::string PRODUCT_NAME; WirelessShutterContact(const DeviceID& id, const RefreshTime &refresh); ~WirelessShutterContact(); /** * @brief Parses the message from Conrad interface and creates * from it SensorData. */ SensorData parseMessage(const Poco::JSON::Object::Ptr message) override; }; }
jozhalaj/gateway
src/zwave/ST02L1ZWaveMapperRegistry.h
<reponame>jozhalaj/gateway #pragma once #include "zwave/SpecificZWaveMapperRegistry.h" namespace BeeeOn { /** * @brief Support PIR sensor from different manufacturers that seems to * be based on the same PCB marked as ST02L1(V1), 20140514 RoHS. * * It covers sensors of 3 categories: * * - 3-in-1 PIR, Temperature, Illumination * - 3-in-1 Door/Window, Temperature, Illumination * - 4-in-1 PIR, Door/Window, Temperature, Illumination * * Each category has a corresponding Mapper implementation that can be * used in the specMap property as: * * - 3-in-1-pir * - 3-in-1 * - 4-in-1 */ class ST02L1ZWaveMapperRegistry : public SpecificZWaveMapperRegistry { public: ST02L1ZWaveMapperRegistry(); private: /** * @brief Convert values that generically apply for all 3 categories * of these sensors: temperature, illumination, battery, tempering. */ static SensorValue convert(const ZWaveNode::Value &value); /** * @brief Implements 3-in-1 variant of the sensor. Based on the argument * pirVariant given during instantiation, it implements either * PIR-variant or Door/Window-variant. */ class Device3in1Mapper : public Mapper { public: Device3in1Mapper( const ZWaveNode::Identity &id, const std::string &product, bool pirVariant = false); std::list<ModuleType> types() const override; SensorValue convert(const ZWaveNode::Value &value) const override; private: bool m_pirVariant; }; /** * @brief Helper class that calls its parent as Device3in1Mapper(true). */ class Device3in1WithPIRMapper : public Device3in1Mapper { public: Device3in1WithPIRMapper( const ZWaveNode::Identity &id, const std::string &product); }; /** * @brief Implements 4-in-1 variant of the sensor. */ class Device4in1Mapper : public Mapper { public: Device4in1Mapper( const ZWaveNode::Identity &id, const std::string &product); std::list<ModuleType> types() const override; SensorValue convert(const ZWaveNode::Value &value) const override; }; }; }
jozhalaj/gateway
src/zwave/ZWaveNetwork.h
#pragma once #include <set> #include <string> #include <vector> #include <Poco/SharedPtr.h> #include <Poco/Timespan.h> #include "zwave/ZWaveNode.h" namespace BeeeOn { /** * @brief ZWaveNetwork is an interface to a real Z-Wave network. * * It provides just high-level operations: * * - start and cancel of the inclusion process * - start and cancel of the node removal process * - access to high-level events by polling */ class ZWaveNetwork { public: typedef Poco::SharedPtr<ZWaveNetwork> Ptr; /** * @brief Representation of events reported by the ZWaveNetwork * implementation via the call pollEvent(). */ class PollEvent { public: enum Type { /** * @brief Dummy, nothing happens. It might come * when interrupted for some reason (termination). * It can be just a spurious wakeup. */ EVENT_NONE = 0, /** * @brief A new Z-Wave node has been detected. * There might be incomplete information about it. * Use method PollEvent::node() to access it. */ EVENT_NEW_NODE = 1, /** * @brief A Z-Wave node's information has been * updated. Use method PollEvent::node() to access it. */ EVENT_UPDATE_NODE = 2, /** * @brief A Z-Wave node has been removed from the Z-Wave * network. Use method PollEvent::node() to access it. */ EVENT_REMOVE_NODE = 3, /** * @brief Received data from a Z-Wave node. Use method * PollEvent::value() to access it. */ EVENT_VALUE = 4, /** * @brief Z-Wave inclusion process has started. */ EVENT_INCLUSION_START = 5, /** * @brief Z-Wave inclusion process has stopped. */ EVENT_INCLUSION_DONE = 7, /** * @brief Z-Wave node removal process has started. */ EVENT_REMOVE_NODE_START = 8, /** * @brief Z-Wave node removal process has stopped. */ EVENT_REMOVE_NODE_DONE = 9, /** * @brief All available Z-Wave nodes have been queried. */ EVENT_READY = 10, }; PollEvent(); ~PollEvent(); static PollEvent createNewNode(const ZWaveNode &node); static PollEvent createUpdateNode(const ZWaveNode &node); static PollEvent createRemoveNode(const ZWaveNode &node); static PollEvent createValue(const ZWaveNode::Value &value); static PollEvent createInclusionStart(); static PollEvent createInclusionDone(); static PollEvent createRemoveNodeStart(); static PollEvent createRemoveNodeDone(); static PollEvent createReady(); bool isNone() const { return type() == EVENT_NONE; } Type type() const; const ZWaveNode &node() const; const ZWaveNode::Value &value() const; std::string toString() const; protected: PollEvent(Type type); PollEvent(Type type, const ZWaveNode &node); PollEvent(const ZWaveNode::Value &value); private: Type m_type; Poco::SharedPtr<ZWaveNode> m_node; Poco::SharedPtr<ZWaveNode::Value> m_value; }; virtual ~ZWaveNetwork(); /** * @brief Poll for new events in the ZWaveNetwork. * * The call is blocking or non-blocking based on * the given timeout. */ virtual PollEvent pollEvent( const Poco::Timespan &timeout) = 0; /** * @brief Starts the Z-Wave network node inclusion process. * * The call is non-blocking. */ virtual void startInclusion() = 0; /** * @brief Cancel inclusion if it is running. */ virtual void cancelInclusion() = 0; /** * @brief Start node removal process in the Z-Wave network. * * The call is blocking. */ virtual void startRemoveNode() = 0; /** * @brief Cancel remove node if it is running. */ virtual void cancelRemoveNode() = 0; /** * @brief Interrupt any blocking calls currently in progress. */ virtual void interrupt() = 0; /** * @brief Post the given value into the Z-Wave network. There is no implicit * feedback about the result status. * * The method might throw Poco::NotImplementedException in case of setting * unsupported values or if not supported by the backend. */ virtual void postValue(const ZWaveNode::Value&) = 0; }; }
jozhalaj/gateway
src/zwave/ZWaveNodeEvent.h
#pragma once #include <cstdint> #include <map> namespace BeeeOn { /** * Statistics from ZWave network from one device. * * @see https://github.com/OpenZWave/open-zwave/blob/master/cpp/src/Node.h (struct NodeData) * @see http://www.openzwave.com/dev/classOpenZWave_1_1Manager.html (GetNodeStatistics()) */ class ZWaveNodeEvent { public: /** * Creates statistics data from node. */ ZWaveNodeEvent( const std::map<std::string, uint32_t> &stats, uint8_t nodeID); uint32_t sentCount() const; uint32_t sentFailed() const; uint32_t retries() const; uint32_t receivedCount() const; uint32_t receiveDuplications() const; uint32_t receiveUnsolicited() const; uint32_t lastRequestRTT() const; uint32_t lastResponseRTT() const; uint32_t averageRequestRTT() const; uint32_t averageResponseRTT() const; uint32_t quality() const; /** * ZWave device (node) identification. */ uint8_t nodeID() const; protected: uint32_t lookup(const std::string &key) const; private: uint8_t m_nodeID; // Identification of Z-Wave device. std::map<std::string, uint32_t> m_stats; }; }
jozhalaj/gateway
src/iqrf/IQRFJsonRequest.h
<reponame>jozhalaj/gateway #pragma once #include "iqrf/IQRFJsonMessage.h" namespace BeeeOn { class IQRFJsonRequest : public IQRFJsonMessage { public: typedef Poco::SharedPtr<IQRFJsonRequest> Ptr; IQRFJsonRequest(); /** * @param request contains hex values separated by dot. */ virtual void setRequest(const std::string &request); virtual std::string request() const; /** * @return Converts all data to one JSON string. * * @note [OPTIONAL] It is necessary to keep the correct order * of elements inside JSON. otherwise, some DPA messages * such as bindings do not work * @note Based on documentation of APIv2, * https://apidocs.iqrf.org/iqrf-gateway-daemon/json/#iqrf/iqrfRaw-request-1-0-0.json */ std::string toString() override; private: std::string m_request; }; }
MahdaSystem/MCP23S18
MCP23S18.h
<reponame>MahdaSystem/MCP23S18 /** ********************************************************************************** * @file MCP23S18.h * @author <NAME> (https://github.com/msthrax) * <NAME> (https://github.com/AliMoal) * @brief For working with MCP23S18 ********************************************************************************** * *! Copyright (c) 2021 Mahda Embedded System (MIT License) *! *! 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. *! ********************************************************************************** **/ #ifndef _MCP23S18_H_ #define _MCP23S18_H_ #ifdef __cplusplus extern "C" { #endif //* Includes ---------------------------------------------------------------------- // #include <stdint.h> #include <stdbool.h> //? User Configurations and Notes ------------------------------------------------- // // Important Notes: // 1. SPI Configuration: 8Bits, CPOL=LOW(0), CPHA=1EDGE(0), Max speed: 10MHz (referred to Datasheet) // 2. For interrupt, User must handle IRQ itself // 3. Comment MCP23S18_SAVE_DATA_VALUE define whenever you want Getting/Reading or Setting/Writing functions work FASTER. // !BE CAREFUL if you comment this, All the data in register(for Setting/Writing) or variable(for Getting/Reading) with every Get/Read or Set/Write function lost and get new ones // !It means that the deselected pins will set as ZERO! // !This is just for Pin configs and the deselected Ports will NOT be changed // *Although You can use WriteFast functions without commenting MCP23S18_SAVE_DATA_VALUE define //! 4. In this Library Delay IS NOT USED and You DO NOT NEED to initialize Delay functions !// #define MCP23S18_SAVE_DATA_VALUE // READ NOTE ABOVE NO. 3 #define MCP23S18_USE_MACRO_DELAY 1 // 0: Use handler delay ,So you have to set ADC_Delay_US in Handler | 1: use Macro delay, So you have to set MACRO_DELAY_US Macro // #define MCP23S18_MACRO_DELAY_US(x) // If you want to use Macro delay, place your delay function in microseconds here #define MCP23S18_Debug_Enable // Uncomment if you want to use (depends on printf in stdio.h) // #pragma anon_unions // UNIMPLEMENTED !!! Uncomment if you are using Keil software //? ------------------------------------------------------------------------------- // //! DO NOT USE OR EDIT THIS BLOCK ------------------------------------------------- // #if MCP23S18_USE_MACRO_DELAY == 0 #define MCP23S18_Delay_US(x) Handler->MCP23S18_Delay_US(x) #else #define MCP23S18_Delay_US(x) MACRO_DELAY_US(x) #ifndef MCP23S18_MACRO_DELAY_US #error "MCP23S18_MACRO_DELAY_US is not defined. Please Use handler delay or config MCP23S18_MACRO_DELAY_US macro, You can choose it on MCP23S18_USE_MACRO_DELAY define" #endif #endif //! ------------------------------------------------------------------------------- // /** ** ================================================================================== ** ##### Enums ##### ** ================================================================================== **/ //! For All Below Two-dimensional typedefs > First Dimension: GPIOA | Second Dimension: GPIOB !// // --------------- typedef uint8_t // MSB 1:Enable | 0:Disable LSB MCP23S18_Config_t[2]; // BANK | MIRROR | SEQOP | ---- | ---- | ODR | INTPOL | INTCC // INTCC: Interrupt Clearing Control | 0: GPIO register clears the interrupt | 1: INTCAP register clears the interrupt // INTPOL: Sets the polarity of the INT output pin | 0: Active-low | 1: Active-high // ODR: Configures the INT pin as an open-drain output | 0: Active driver output (INTPOL bit sets the polarity) | 1: Open-drain output (overrides the INTPOL bit) // UNIMPLEMENTED // UNIMPLEMENTED // SEQOP: Sequential Operation mode bit | 0: Sequential operation enabled, address pointer increments | 1: Sequential operation disabled, address pointer does not increment // MIRROR: INT pins mirror bit | 0: The INT pins are not connected. INTA is associated with Port A and INTB is associated with Port B | 1: The INT pins are internally connected in a wired OR configuration // BANK: Controls how the registers are addressed | 0: The registers are in the same bank (addresses are sequential) | 1: The registers associated with each port are separated into different banks // --------------- typedef uint8_t // GPIO Direction MCP23S18_Direction_t[2]; // Bit[0:7] To Pin[0:7] > 1: Input | 0: Output typedef uint8_t // GPIO Type MCP23S18_Type_t[2]; // Bit[0:7] To Pin[0:7] > 1: ActiveHigh | 0: ActiveLow typedef uint8_t // GPIO Pull Up MCP23S18_PullUp_t[2]; // Bit[0:7] To Pin[0:7] > 1: PullUpEnable | 0: PullUpDisable // --------------- typedef uint8_t // Interrupt Enable MCP23S18_IntEnable_t[2]; // Bit[0:7] To Pin[0:7] > 1: IntEnable | 0: IntDisable typedef uint8_t // Interrupt Default Value MCP23S18_IntDefaultVal_t[2]; // Bit[0:7] To Pin[0:7] > 1: 1 | 0: 0 typedef uint8_t // Interrupt Mode To Compare MCP23S18_IntCompare_t[2]; // Bit[0:7] To Pin[0:7] > 1: DefaultVal | 0: PreviousVal typedef uint8_t // Interrupt Flag MCP23S18_IntOccurred_t[2]; // Bit[0:7] To Pin[0:7] > 1: IntOccurred | 0: IntNOTOccurred typedef uint8_t // Interrupt Capture State MCP23S18_IntCaptureState_t[2]; // Bit[0:7] To Pin[0:7] > 1: IntLogicHigh | 0: IntLogicLow // --------------- typedef uint8_t // GPIO Value MCP23S18_GPIOState_t[2]; // Bit[0:7] To Pin[0:7] > 1: GPIOLogicHigh | 0: GPIOLogicLow /** ** ================================================================================== ** ##### Structs ##### ** ================================================================================== **/ /** * @brief Handling of library * @note Must be initialize at first before calling MCP23S18_Init function */ typedef struct MCP23S18_Handler_s { // Functions: void (*MCP23S18_CS_Low)(void); // Must be Initialize void (*MCP23S18_CS_High)(void); // Must be Initialize void (*MCP23S18_Spi_WriteByte)(uint8_t); // Must be Initialize uint8_t (*MCP23S18_Spi_ReadByte)(void); // Must be Initialize #if MCP23S18_USE_MACRO_DELAY == 0 void (*MCP23S18_Delay_US)(void); //! Must be initialized If You do not use Macro Delay Otherwise Pass it as NULL (Place here your delay in Microsecond) #endif // bool (*MCP23S18_INT0_Read)(void); // UNIMPLEMENTED // bool (*MCP23S18_INT1_Read)(void); // UNIMPLEMENTED // Variables: // bool SelectBank; // UNIMPLEMENTED // !!! DO NOT USE OR EDIT THIS !!! // FOR_SELECT_BANK_MACRO } MCP23S18_Handler_t; /** ** ================================================================================== ** ##### Public Functions ##### ** ================================================================================== **/ // Initialization Function: ------------------------------------------------------- // /** * @brief Initializes the library * @note Must be called at FIRST and ONCE! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_Init(MCP23S18_Handler_t *Handler); // Setting Functions: ------------------------------------------------------------- // /** * @brief Sets Configurations on IOCON registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param Config: See MCP23S18_Config_t * @retval None */ void MCP23S18_SetConfig(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Config_t Config); /** * @brief Gets Configurations from IOCON registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param Config: See MCP23S18_Config_t * @retval None */ void MCP23S18_GetConfig(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Config_t Config); /** * @brief Sets Pin Directions on IODIR registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param Direction: See MCP23S18_Direction_t * @retval None */ void MCP23S18_SetDirection(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Direction_t Direction); /** * @brief Gets Pin Directions from IODIR registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param Direction: See MCP23S18_Direction_t * @retval None */ void MCP23S18_GetDirection(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Direction_t Direction); /** * @brief Sets Pin Directions on IPOL registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param Type: See MCP23S18_Type_t * @retval None */ void MCP23S18_SetTypes(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Type_t Type); /** * @brief Gets Pin Directions from IPOL registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param Type: See MCP23S18_Type_t * @retval None */ void MCP23S18_GetTypes(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Type_t Type); /** * @brief Sets Pin Pull-up on GPPU registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param PullUp: See MCP23S18_PullUp_t * @retval None */ void MCP23S18_SetPullUp(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_PullUp_t PullUp); /** * @brief Gets Pin Pull-up from GPPU registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param PullUp: See MCP23S18_PullUp_t * @retval None */ void MCP23S18_GetPullUp(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_PullUp_t PullUp); /** * @brief Sets Pin Interrupt enabling on GPINTEN registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntEnable: See MCP23S18_IntEnable_t * @retval None */ void MCP23S18_SetIntEnable(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntEnable_t IntEnable); /** * @brief Gets Pin Interrupt enabling from GPINTEN registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntEnable: See MCP23S18_IntEnable_t * @retval None */ void MCP23S18_GetIntEnable(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntEnable_t IntEnable); /** * @brief Sets Pin Interrupt default value on DEFVAL registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntDefaultVal: See MCP23S18_IntDefaultVal_t * @retval None */ void MCP23S18_SetIntDefaultVal(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntDefaultVal_t IntDefaultVal); /** * @brief Gets Pin Interrupt default value from DEFVAL registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntDefaultVal: See MCP23S18_IntDefaultVal_t * @retval None */ void MCP23S18_GetIntDefaultVal(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntDefaultVal_t IntDefaultVal); /** * @brief Sets Pin Interrupt comparison mode on INTCON registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntCompare: See MCP23S18_IntCompare_t * @retval None */ void MCP23S18_SetIntCompare(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntCompare_t IntCompare); /** * @brief Gets Pin Interrupt comparison mode from INTCON registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntCompare: See MCP23S18_IntCompare_t * @retval None */ void MCP23S18_GetIntCompare(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntCompare_t IntCompare); /** * @brief Sets Pin Interrupt flags on INTF registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntOccurred: See MCP23S18_IntOccurred_t * @retval None */ void MCP23S18_SetIntOccurred(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntOccurred_t IntOccurred); /** * @brief Gets Pin Interrupt flags from INTF registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntOccurred: See MCP23S18_IntOccurred_t * @retval None */ void MCP23S18_GetIntOccurred(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntOccurred_t IntOccurred); /** * @brief Sets Pin Interrupt capturing state on INTCAP registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntCaptureState: See MCP23S18_IntCaptureState_t * @retval None */ void MCP23S18_SetIntCaptureState(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntCaptureState_t IntCaptureState); /** * @brief Gets Pin Interrupt capturing state from INTCAP registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntCaptureState: See MCP23S18_IntCaptureState_t * @retval None */ void MCP23S18_GetIntCaptureState(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntCaptureState_t IntCaptureState); // Read/Write Functions: ---------------------------------------------------------- // /** * @brief Reads Input pins from GPIO registers * @note To read Output pins use MCP23S18_ReadOutput function * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be read * @param MaskB: Mask for port B to choose which pins have to be read * @param GPIOState: See MCP23S18_GPIOState_t * @retval None */ void MCP23S18_ReadInput(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_GPIOState_t GPIOState); /** * @brief Reads Output pins state from OLAT registers * @note To read Input pins use MCP23S18_ReadInput function * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be read * @param MaskB: Mask for port B to choose which pins have to be read * @param GPIOState: See MCP23S18_GPIOState_t * @retval None */ void MCP23S18_ReadOutput(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_GPIOState_t GPIOState); /** * @brief Writes Output pins state on OLAT registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be written * @param MaskB: Mask for port B to choose which pins have to be written * @param GPIOState: See MCP23S18_GPIOState_t * @retval None */ void MCP23S18_WriteOutput(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_GPIOState_t GPIOState); /** * @brief Writes Output pins state on OLAT registers fast! * @note This Sets All New Data In GPIOState Variables * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be written * @param MaskB: Mask for port B to choose which pins have to be written * @param GPIOState: See MCP23S18_GPIOState_t * @retval None */ void MCP23S18_WriteOutputFAST(MCP23S18_Handler_t *Handler, MCP23S18_GPIOState_t GPIOState); /** * @brief Writes Output All port A pins HIGH on OLAT registers fast! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_WriteOutputPortAHighFAST(MCP23S18_Handler_t *Handler); /** * @brief Writes Output All port A pins LOW on OLAT registers fast! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_WriteOutputPortALowFAST(MCP23S18_Handler_t *Handler); /** * @brief Writes Output All port B pins HIGH on OLAT registers fast! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_WriteOutputPortBHighFAST(MCP23S18_Handler_t *Handler); /** * @brief Writes Output All port B pins LOW on OLAT registers fast! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_WriteOutputPortBLowFAST(MCP23S18_Handler_t *Handler); #ifdef _cplusplus } #endif #endif
MahdaSystem/MCP23S18
MCP23S18.c
/** ********************************************************************************** * @file MCP23S18.c * @author <NAME> (https://github.com/msthrax) * <NAME> (https://github.com/AliMoal) * @brief For working with MCP23S18 ********************************************************************************** * *! Copyright (c) 2021 Mahda Embedded System (MIT License) *! *! 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. *! ********************************************************************************** **/ //* Private Includes -------------------------------------------------------------- // #include "MCP23S18.h" //* Private Defines and Macros ---------------------------------------------------- // #define MCP23S18_USE_MACRO_SELECT_BANK // To Avoid From Conflict For Addressing | After commenting this, Toggle comment all "// FOR_SELECT_BANK_MACRO" Lines #define MCP23S18_WRITE_ADDR 0x40 // Default opcode address of the MCP23S18 #define MCP23S18_READ_ADDR 0x41 // Default opcode address of the MCP23S18 #define IODIRn_IO0 (1<<0) #define IODIRn_IO1 (1<<1) #define IODIRn_IO2 (1<<2) #define IODIRn_IO3 (1<<3) #define IODIRn_IO4 (1<<4) #define IODIRn_IO5 (1<<5) #define IODIRn_IO6 (1<<6) #define IODIRn_IO7 (1<<7) #define IPOLn_IP0 (1<<0) #define IPOLn_IP1 (1<<1) #define IPOLn_IP2 (1<<2) #define IPOLn_IP3 (1<<3) #define IPOLn_IP4 (1<<4) #define IPOLn_IP5 (1<<5) #define IPOLn_IP6 (1<<6) #define IPOLn_IP7 (1<<7) #define GPINTENn_GPINT0 (1<<0) #define GPINTENn_GPINT1 (1<<1) #define GPINTENn_GPINT2 (1<<2) #define GPINTENn_GPINT3 (1<<3) #define GPINTENn_GPINT4 (1<<4) #define GPINTENn_GPINT5 (1<<5) #define GPINTENn_GPINT6 (1<<6) #define GPINTENn_GPINT7 (1<<7) #define DEFVALn_DEF0 (1<<0) #define DEFVALn_DEF1 (1<<1) #define DEFVALn_DEF2 (1<<2) #define DEFVALn_DEF3 (1<<3) #define DEFVALn_DEF4 (1<<4) #define DEFVALn_DEF5 (1<<5) #define DEFVALn_DEF6 (1<<6) #define DEFVALn_DEF7 (1<<7) #define INTCONn_IOC0 (1<<0) #define INTCONn_IOC1 (1<<1) #define INTCONn_IOC2 (1<<2) #define INTCONn_IOC3 (1<<3) #define INTCONn_IOC4 (1<<4) #define INTCONn_IOC5 (1<<5) #define INTCONn_IOC6 (1<<6) #define INTCONn_IOC7 (1<<7) #define IOCON_INTCC (1<<0) #define IOCON_INTPOL (1<<1) #define IOCON_ODR (1<<2) #define IOCON_RSVD0 (1<<3) #define IOCON_RSVD1 (1<<4) #define IOCON_SEQOP (1<<5) #define IOCON_MIRROR (1<<6) #define IOCON_BANK (1<<7) #define IOX_ALLOUTPUT 0x00000000 #define IOX_ALLINPUT 0xFFFFFFFF #define IOX_ALLINVERTED 0x00000000 #define IOX_NONEINVERTED 0xFFFFFFFF //* Others ------------------------------------------------------------------------ // #ifdef MCP23S18_USE_MACRO_SELECT_BANK #define SelectBank 0 // 0: BANK0 | 1:BANK1 #else #define SelectBank Handler->SelectBank #endif #ifdef MCP23S18_Debug_Enable #include <stdio.h> // for debug #define PROGRAMLOG(arg...) printf(arg) #else #define PROGRAMLOG(arg...) #endif #define XtoStr(x) #x #define CheckAssert(x) if(!x) PROGRAMLOG("!ASSERT FAILED!\r\n"); return // To Avoid From Memory Conflict #define CheckAssertSTR(x) if(!x) PROGRAMLOG("!ASSERT FAILED: "XtoStr(x)" IS NOT IMPLIMENTED!\r\n"); return // To Avoid From Memory Conflict /** ** ================================================================================== ** ##### Private Enums ##### ** ================================================================================== **/ /** * @brief Registers Names */ enum RegisterNames{ IODIRA = 0, IODIRB, IPOLA, IPOLB, GPINTENA, GPINTENB, DEFVALA, DEFVALB, INTCONA, INTCONB, IOCONA, IOCONB, GPPUA, GPPUB, INTFA, INTFB, INTCAPA, INTCAPB, GPIOA, GPIOB, OLATA, OLATB }; /** ** ================================================================================== ** ##### Private Constants ##### ** ================================================================================== **/ /** * @brief Saving the Addresses of registers for each bank */ static const uint8_t BankAdd[2][22] = {// First Dir: BANK0 | Second Dir: BANK1 {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15}, {0x00, 0x10, 0x01, 0x11, 0x02, 0x12, 0x03, 0x13, 0x04, 0x14, 0x05, 0x15, 0x06, 0x16, 0x07, 0x17, 0x08, 0x18, 0x09, 0x19, 0x0A, 0x1A} }; /** *! ================================================================================== *! ##### Private Functions ##### *! ================================================================================== **/ /** * @brief Reads register value * @param MCP23S18_Handler: Pointer of library handler * @param reg: Address of register * @retval Read data */ static uint8_t MCP23S18_ReadReg(MCP23S18_Handler_t * MCP23S18_Handler, uint8_t reg) { MCP23S18_Handler->MCP23S18_CS_Low(); MCP23S18_Handler->MCP23S18_Spi_WriteByte(MCP23S18_READ_ADDR); MCP23S18_Handler->MCP23S18_Spi_WriteByte(reg); uint8_t ret = MCP23S18_Handler->MCP23S18_Spi_ReadByte(); MCP23S18_Handler->MCP23S18_CS_High(); return ret; } /** * @brief Write value to register * @param MCP23S18_Handler: Pointer of library handler * @param reg: Address of register * @param value: Date to be written * @retval None */ static void MCP23S18_WriteReg(MCP23S18_Handler_t * MCP23S18_Handler, uint8_t reg, uint8_t value) { MCP23S18_Handler->MCP23S18_CS_Low(); MCP23S18_Handler->MCP23S18_Spi_WriteByte(MCP23S18_WRITE_ADDR); MCP23S18_Handler->MCP23S18_Spi_WriteByte(reg); MCP23S18_Handler->MCP23S18_Spi_WriteByte(value); MCP23S18_Handler->MCP23S18_CS_High(); } /** ** ================================================================================== ** ##### Public Functions ##### ** ================================================================================== **/ // Initialization Function: ------------------------------------------------------- // /** * @brief Initializes the library * @note Must be called at FIRST and ONCE! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_Init(MCP23S18_Handler_t *Handler) { CheckAssertSTR(Handler->MCP23S18_CS_High); CheckAssertSTR(Handler->MCP23S18_CS_Low); CheckAssertSTR(Handler->MCP23S18_Spi_ReadByte); CheckAssertSTR(Handler->MCP23S18_Spi_WriteByte); #if MCP23S18_USE_MACRO_DELAY == 0 CheckAssertSTR(Handler->MCP23S18_Delay_US); #endif // SelectBank = 0; // POR/RST: BANK0 // FOR_SELECT_BANK_MACRO //? USER INIT CODE begin ?// //? USER INIT CODE End ?// PROGRAMLOG("IODIRA: 0x%02X | IODIRB: 0x%02X\r\n" "IPOLA: 0x%02X | IPOLB: 0x%02X\r\n" "GPINTENA: 0x%02X | GPINTENB: 0x%02X\r\n" "DEFVALA: 0x%02X | DEFVALB: 0x%02X\r\n" "INTCONA: 0x%02X | INTCONB: 0x%02X\r\n" "IOCONA: 0x%02X | IOCONB: 0x%02X\r\n" "GPPUA: 0x%02X | GPPUB: 0x%02X\r\n" "INTFA: 0x%02X | INTFB: 0x%02X\r\n" "INTCAPA: 0x%02X | INTCAPB: 0x%02X\r\n" "GPIOA: 0x%02X | GPIOB: 0x%02X\r\n" "OLATA: 0x%02X | OLATB: 0x%02X\r\n", MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IODIRA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IODIRB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IPOLA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IPOLB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPINTENA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPINTENB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][DEFVALA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][DEFVALB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCONA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCONB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IOCONA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IOCONB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPPUA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPPUB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTFA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTFB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCAPA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCAPB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPIOA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPIOB]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][OLATA]), MCP23S18_ReadReg(Handler, BankAdd[SelectBank][OLATB])); } // Setting Functions: ------------------------------------------------------------- // /** * @brief Sets Configurations on IOCON registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param Config: See MCP23S18_Config_t * @retval None */ void MCP23S18_SetConfig(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Config_t Config) { // IOCON Config[0] &= 0x7F; // For Now Must Use BANK0 // FOR_SELECT_BANK_MACRO Config[1] &= 0x7F; // For Now Must Use BANK0 // FOR_SELECT_BANK_MACRO #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IOCONA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IOCONA]) & (~MaskA)) | (MaskA & Config[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IOCONB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IOCONB]) & (~MaskB)) | (MaskB & Config[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IOCONA], MaskA & Config[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IOCONB], MaskB & Config[1]); #endif } /** * @brief Gets Configurations from IOCON registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param Config: See MCP23S18_Config_t * @retval None */ void MCP23S18_GetConfig(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Config_t Config) { // IOCON #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA Config[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IOCONA])) & MaskA) | (Config[0] & (~MaskA)); if (MaskB) // GPIOB Config[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IOCONB])) & MaskB) | (Config[1] & (~MaskB)); #else if (MaskA) // GPIOA Config[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IOCONA]) & MaskA; if (MaskB) // GPIOB Config[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IOCONB]) & MaskB; #endif } /** * @brief Sets Pin Directions on IODIR registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param Direction: See MCP23S18_Direction_t * @retval None */ void MCP23S18_SetDirection(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Direction_t Direction) { // IODIR #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IODIRA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IODIRA]) & (~MaskA)) | (MaskA & Direction[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IODIRB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IODIRB]) & (~MaskB)) | (MaskB & Direction[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IODIRA], MaskA & Direction[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IODIRB], MaskB & Direction[1]); #endif } /** * @brief Gets Pin Directions from IODIR registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param Direction: See MCP23S18_Direction_t * @retval None */ void MCP23S18_GetDirection(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Direction_t Direction) { // IODIR #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA Direction[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IODIRA])) & MaskA) | (Direction[0] & (~MaskA)); if (MaskB) // GPIOB Direction[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IODIRB])) & MaskB) | (Direction[1] & (~MaskB)); #else if (MaskA) // GPIOA Direction[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IODIRA]) & MaskA; if (MaskB) // GPIOB Direction[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IODIRB]) & MaskB; #endif } /** * @brief Sets Pin Directions on IPOL registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param Type: See MCP23S18_Type_t * @retval None */ void MCP23S18_SetTypes(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Type_t Type) { // IPOL #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IPOLA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IPOLA]) & (~MaskA)) | (MaskA & Type[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IPOLB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IPOLB]) & (~MaskB)) | (MaskB & Type[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IPOLA], MaskA & Type[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][IPOLB], MaskB & Type[1]); #endif } /** * @brief Gets Pin Directions from IPOL registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param Type: See MCP23S18_Type_t * @retval None */ void MCP23S18_GetTypes(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_Type_t Type) { // IPOL #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA Type[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IPOLA])) & MaskA) | (Type[0] & (~MaskA)); if (MaskB) // GPIOB Type[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IPOLB])) & MaskB) | (Type[1] & (~MaskB)); #else if (MaskA) // GPIOA Type[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IPOLA]) & MaskA; if (MaskB) // GPIOB Type[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][IPOLB]) & MaskB; #endif } /** * @brief Sets Pin Pull-up on GPPU registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param PullUp: See MCP23S18_PullUp_t * @retval None */ void MCP23S18_SetPullUp(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_PullUp_t PullUp) { // GPPU #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][GPPUA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPPUA]) & (~MaskA)) | (MaskA & PullUp[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][GPPUB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPPUB]) & (~MaskB)) | (MaskB & PullUp[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][GPPUA], MaskA & PullUp[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][GPPUB], MaskB & PullUp[1]); #endif } /** * @brief Gets Pin Pull-up from GPPU registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param PullUp: See MCP23S18_PullUp_t * @retval None */ void MCP23S18_GetPullUp(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_PullUp_t PullUp) { // GPPU #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA PullUp[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPPUA])) & MaskA) | (PullUp[0] & (~MaskA)); if (MaskB) // GPIOB PullUp[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPPUB])) & MaskB) | (PullUp[1] & (~MaskB)); #else if (MaskA) // GPIOA PullUp[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPPUA]) & MaskA; if (MaskB) // GPIOB PullUp[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPPUB]) & MaskB; #endif } /** * @brief Sets Pin Interrupt enabling on GPINTEN registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntEnable: See MCP23S18_IntEnable_t * @retval None */ void MCP23S18_SetIntEnable(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntEnable_t IntEnable) { // GPINTEN #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][GPINTENA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPINTENA]) & (~MaskA)) | (MaskA & IntEnable[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][GPINTENB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPINTENB]) & (~MaskB)) | (MaskB & IntEnable[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][GPINTENA], MaskA & IntEnable[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][GPINTENB], MaskB & IntEnable[1]); #endif } /** * @brief Gets Pin Interrupt enabling from GPINTEN registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntEnable: See MCP23S18_IntEnable_t * @retval None */ void MCP23S18_GetIntEnable(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntEnable_t IntEnable) { // GPINTEN #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA IntEnable[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPINTENA])) & MaskA) | (IntEnable[0] & (~MaskA)); if (MaskB) // GPIOB IntEnable[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPINTENB])) & MaskB) | (IntEnable[1] & (~MaskB)); #else if (MaskA) // GPIOA IntEnable[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPINTENA] & MaskA); if (MaskB) // GPIOB IntEnable[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPINTENB] & MaskB); #endif } /** * @brief Sets Pin Interrupt default value on DEFVAL registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntDefaultVal: See MCP23S18_IntDefaultVal_t * @retval None */ void MCP23S18_SetIntDefaultVal(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntDefaultVal_t IntDefaultVal) { // DEFVAL #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][DEFVALA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][DEFVALA]) & (~MaskA)) | (MaskA & IntDefaultVal[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][DEFVALB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][DEFVALB]) & (~MaskB)) | (MaskB & IntDefaultVal[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][DEFVALA], MaskA & IntDefaultVal[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][DEFVALB], MaskB & IntDefaultVal[1]); #endif } /** * @brief Gets Pin Interrupt default value from DEFVAL registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntDefaultVal: See MCP23S18_IntDefaultVal_t * @retval None */ void MCP23S18_GetIntDefaultVal(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntDefaultVal_t IntDefaultVal) { // DEFVAL #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA IntDefaultVal[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][DEFVALA])) & MaskA) | (IntDefaultVal[0] & (~MaskA)); if (MaskB) // GPIOB IntDefaultVal[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][DEFVALB])) & MaskB) | (IntDefaultVal[1] & (~MaskB)); #else if (MaskA) // GPIOA IntDefaultVal[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][DEFVALA]) & MaskA; if (MaskB) // GPIOB IntDefaultVal[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][DEFVALB]) & MaskB; #endif } /** * @brief Sets Pin Interrupt comparison mode on INTCON registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntCompare: See MCP23S18_IntCompare_t * @retval None */ void MCP23S18_SetIntCompare(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntCompare_t IntCompare) { // INTCON #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTCONA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCONA]) & (~MaskA)) | (MaskA & IntCompare[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTCONB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCONB]) & (~MaskB)) | (MaskB & IntCompare[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTCONA], MaskA & IntCompare[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTCONB], MaskB & IntCompare[1]); #endif } /** * @brief Gets Pin Interrupt comparison mode from INTCON registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntCompare: See MCP23S18_IntCompare_t * @retval None */ void MCP23S18_GetIntCompare(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntCompare_t IntCompare) { // INTCON #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA IntCompare[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCONA])) & MaskA) | (IntCompare[0] & (~MaskA)); if (MaskB) // GPIOB IntCompare[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCONB])) & MaskB) | (IntCompare[1] & (~MaskB)); #else if (MaskA) // GPIOA IntCompare[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCONA]) & MaskA; if (MaskB) // GPIOB IntCompare[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCONB]) & MaskB; #endif } /** * @brief Sets Pin Interrupt flags on INTF registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntOccurred: See MCP23S18_IntOccurred_t * @retval None */ void MCP23S18_SetIntOccurred(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntOccurred_t IntOccurred) { // INTF #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTFA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTFA]) & (~MaskA)) | (MaskA & IntOccurred[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTFB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTFB]) & (~MaskB)) | (MaskB & IntOccurred[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTFA], MaskA & IntOccurred[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTFB], MaskB & IntOccurred[1]); #endif } /** * @brief Gets Pin Interrupt flags from INTF registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntOccurred: See MCP23S18_IntOccurred_t * @retval None */ void MCP23S18_GetIntOccurred(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntOccurred_t IntOccurred) { // INTF #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA IntOccurred[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTFA])) & MaskA) | (IntOccurred[0] & (~MaskA)); if (MaskB) // GPIOB IntOccurred[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTFB])) & MaskB) | (IntOccurred[1] & (~MaskB)); #else if (MaskA) // GPIOA IntOccurred[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTFA]) & MaskA; if (MaskB) // GPIOB IntOccurred[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTFB]) & MaskB; #endif } /** * @brief Sets Pin Interrupt capturing state on INTCAP registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be set * @param MaskB: Mask for port B to choose which pins have to be set * @param IntCaptureState: See MCP23S18_IntCaptureState_t * @retval None */ void MCP23S18_SetIntCaptureState(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntCaptureState_t IntCaptureState) { // INTCAP #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTCAPA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCAPA]) & (~MaskA)) | (MaskA & IntCaptureState[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTCAPB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCAPB]) & (~MaskB)) | (MaskB & IntCaptureState[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTCAPA], MaskA & IntCaptureState[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][INTCAPB], MaskB & IntCaptureState[1]); #endif } /** * @brief Gets Pin Interrupt capturing state from INTCAP registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be get * @param MaskB: Mask for port B to choose which pins have to be get * @param IntCaptureState: See MCP23S18_IntCaptureState_t * @retval None */ void MCP23S18_GetIntCaptureState(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_IntCaptureState_t IntCaptureState) { // INTCAP #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA IntCaptureState[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCAPA])) & MaskA) | (IntCaptureState[0] & (~MaskA)); if (MaskB) // GPIOB IntCaptureState[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCAPB])) & MaskB) | (IntCaptureState[1] & (~MaskB)); #else if (MaskA) // GPIOA IntCaptureState[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCAPA]) & MaskA; if (MaskB) // GPIOB IntCaptureState[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][INTCAPB]) & MaskB; #endif } // Read/Write Functions: ---------------------------------------------------------- // /** * @brief Reads Input pins from GPIO registers * @note To read Output pins use MCP23S18_ReadOutput function * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be read * @param MaskB: Mask for port B to choose which pins have to be read * @param GPIOState: See MCP23S18_GPIOState_t * @retval None */ void MCP23S18_ReadInput(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_GPIOState_t GPIOState) { // GPIO #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA GPIOState[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPIOA])) & MaskA) | (GPIOState[0] & (~MaskA)); if (MaskB) // GPIOB GPIOState[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPIOB])) & MaskB) | (GPIOState[1] & (~MaskB)); #else if (MaskA) // GPIOA GPIOState[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPIOA]) & MaskA; if (MaskB) // GPIOB GPIOState[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][GPIOB]) & MaskB; #endif } /** * @brief Reads Output pins state from OLAT registers * @note To read Input pins use MCP23S18_ReadInput function * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be read * @param MaskB: Mask for port B to choose which pins have to be read * @param GPIOState: See MCP23S18_GPIOState_t * @retval None */ void MCP23S18_ReadOutput(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_GPIOState_t GPIOState) { // OLAT #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA GPIOState[0] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][OLATA])) & MaskA) | (GPIOState[0] & (~MaskA)); if (MaskB) // GPIOB GPIOState[1] = ((MCP23S18_ReadReg(Handler, BankAdd[SelectBank][OLATB])) & MaskB) | (GPIOState[1] & (~MaskB)); #else if (MaskA) // GPIOA GPIOState[0] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][OLATA]) & MaskA; if (MaskB) // GPIOB GPIOState[1] = MCP23S18_ReadReg(Handler, BankAdd[SelectBank][OLATB]) & MaskB; #endif } /** * @brief Writes Output pins state on OLAT registers * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be written * @param MaskB: Mask for port B to choose which pins have to be written * @param GPIOState: See MCP23S18_GPIOState_t * @retval None */ void MCP23S18_WriteOutput(MCP23S18_Handler_t *Handler, uint8_t MaskA, uint8_t MaskB, MCP23S18_GPIOState_t GPIOState) { // OLAT #ifdef MCP23S18_SAVE_DATA_VALUE if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATA], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][OLATA]) & (~MaskA)) | (MaskA & GPIOState[0])); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATB], (MCP23S18_ReadReg(Handler, BankAdd[SelectBank][OLATB]) & (~MaskB)) | (MaskB & GPIOState[1])); #else if (MaskA) // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATA], MaskA & GPIOState[0]); if (MaskB) // GPIOB MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATB], MaskB & GPIOState[1]); #endif } /** * @brief Writes Output pins state on OLAT registers fast! * @note This Sets All New Data In GPIOState Variables * @param Handler: Pointer of library handler * @param MaskA: Mask for port A to choose which pins have to be written * @param MaskB: Mask for port B to choose which pins have to be written * @param GPIOState: See MCP23S18_GPIOState_t * @retval None */ void MCP23S18_WriteOutputFAST(MCP23S18_Handler_t *Handler, MCP23S18_GPIOState_t GPIOState) { // OLAT MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATA], GPIOState[0]); // GPIOA MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATB], GPIOState[1]); // GPIOB } /** * @brief Writes Output All port A pins HIGH on OLAT registers fast! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_WriteOutputPortAHighFAST(MCP23S18_Handler_t *Handler) { // OLAT MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATA], 0xFF); // PROGRAMLOG("OLATA: 0x%X\r\n", // MCP23S18_ReadReg(MCP23S18_Handler, OLATA_BANK0)); } /** * @brief Writes Output All port A pins LOW on OLAT registers fast! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_WriteOutputPortALowFAST(MCP23S18_Handler_t *Handler) { // OLAT MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATA], 0x00); // PROGRAMLOG("OLATA: 0x%X\r\n", // MCP23S18_ReadReg(MCP23S18_Handler, OLATA_BANK0)); } /** * @brief Writes Output All port B pins HIGH on OLAT registers fast! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_WriteOutputPortBHighFAST(MCP23S18_Handler_t *Handler) { // OLAT MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATB], 0xFF); // PROGRAMLOG("OLATB: 0x%X\r\n", // MCP23S18_ReadReg(MCP23S18_Handler, OLATB_BANK0)); } /** * @brief Writes Output All port B pins LOW on OLAT registers fast! * @param Handler: Pointer of library handler * @retval None */ void MCP23S18_WriteOutputPortBLowFAST(MCP23S18_Handler_t *Handler) { // OLAT MCP23S18_WriteReg(Handler, BankAdd[SelectBank][OLATB], 0x00); // PROGRAMLOG("OLATB: 0x%X\r\n",0 // MCP23S18_ReadReg(MCP23S18_Handler, OLATB_BANK0)); } //----------------------------------------------------------------------------------------------------------------------------------------------