repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
ilariom/wildcat | src/core/s2x/mixer.h | #ifndef S2X_MIXER_H
#define S2X_MIXER_H
#include <SDL.h>
#include <SDL_mixer.h>
#include <unordered_map>
#include <string>
#include <cassert>
namespace s2x
{
class Mixer final
{
public:
constexpr static int frequency = 22050;
constexpr static int chunksize = 2048;
constexpr static int PLAY_INFINITE = -1;
public:
inline Mixer(int channels);
Mixer(const Mixer&) = delete;
Mixer(Mixer&&) = delete;
inline ~Mixer();
Mixer& operator=(const Mixer&) = delete;
Mixer& operator=(Mixer&&) = delete;
public:
inline bool loadEffect(const std::string& filePath);
inline bool loadMusic(const std::string& filePath);
inline void releaseEffect(const std::string& filePath);
inline void releaseMusic(const std::string& filePath);
// CHANNELS
inline int bindChannel(const std::string& filePath, int channel);
inline void playChannel(int channel, int loops = 1, int fadeIn = 0, int timeout = -1);
inline void haltChannel(int channel, int fadeOut = 0);
void volume(int channel, float vol) { Mix_Volume(channel, (int)(vol * MIX_MAX_VOLUME)); }
void mute(int channel) { Mix_Pause(channel); }
void unmute(int channel) { Mix_Resume(channel); }
void pan(int channel, float leftVol, float rightVol) { Mix_SetPanning(channel, (Uint8)(leftVol * 255), (Uint8)(rightVol * 255)); }
void distance(int channel, uint8_t distance) { Mix_SetDistance(channel, (Uint8)distance); }
inline void spatial(int channel, int16_t angle, uint8_t distance);
bool isPlaying(int channel) const { return (bool) Mix_Playing(channel); }
bool isPaused(int channel) const { return (bool) Mix_Paused(channel); }
int getChannelsCount() const { return this->channelsCount; }
// BGM
inline void playMusic(const std::string& filePath, int loops = -1, int fadeIn = 0);
inline void haltMusic(int fadeOut = 0);
void setMusicPosition(double seconds) { Mix_SetMusicPosition(seconds); }
void rewindMusic() { Mix_RewindMusic(); }
void pauseMusic() { Mix_PauseMusic(); }
void resumeMusic() { Mix_ResumeMusic(); }
void musicVolume(float vol) { Mix_VolumeMusic((int)(vol * MIX_MAX_VOLUME)); }
bool isMusicPaused() const { return (bool) Mix_PausedMusic(); }
bool isMusicPlaying() const { return (bool) Mix_PlayingMusic(); }
private:
std::unordered_map<std::string, std::pair<Mix_Chunk*, int>> fxs;
std::unordered_map<std::string, std::pair<Mix_Music*, int>> bgms;
std::unordered_map<int, Mix_Chunk*> boundChannels;
int channelsCount;
Mix_Music* currentBGM = nullptr;
};
inline Mixer::Mixer(int channels)
{
Mix_Init(MIX_INIT_MP3 | MIX_INIT_OGG | MIX_INIT_FLAC);
Mix_OpenAudio(frequency, MIX_DEFAULT_FORMAT, 2, chunksize);
Mix_AllocateChannels(channels);
this->channelsCount = channels;
}
inline Mixer::~Mixer()
{
Mix_CloseAudio();
Mix_Quit();
}
inline bool Mixer::loadEffect(const std::string& filePath)
{
auto it = this->fxs.find(filePath);
if(it != this->fxs.end())
{
this->fxs[filePath].second++;
return true;
}
std::pair<Mix_Chunk*, int> p = std::make_pair(
Mix_LoadWAV(filePath.c_str()),
1
);
if(p.first == nullptr)
return false;
this->fxs[filePath] = std::move(p);
return true;
}
inline bool Mixer::loadMusic(const std::string& filePath)
{
auto it = this->bgms.find(filePath);
if(it != this->bgms.end())
{
this->bgms[filePath].second++;
return true;
}
std::pair<Mix_Music*, int> p = std::make_pair(
Mix_LoadMUS(filePath.c_str()),
1
);
if(p.first == nullptr)
return false;
this->bgms[filePath] = std::move(p);
return true;
}
inline void Mixer::releaseEffect(const std::string& filePath)
{
if(this->fxs.find(filePath) == this->fxs.end())
return;
auto p = this->fxs[filePath];
p.second--;
if(p.second <= 0)
{
Mix_FreeChunk(p.first);
this->fxs.erase(filePath);
}
}
inline void Mixer::releaseMusic(const std::string& filePath)
{
if(this->bgms.find(filePath) == this->bgms.end())
return;
auto p = this->bgms[filePath];
p.second--;
if(p.second <= 0)
{
Mix_FreeMusic(p.first);
this->bgms.erase(filePath);
}
}
inline int Mixer::bindChannel(const std::string& filePath, int channel)
{
if(this->fxs.find(filePath) == this->fxs.end())
{
bool res = loadEffect(filePath);
assert(res);
}
this->boundChannels[channel] = this->fxs[filePath].first;
return channel;
}
inline void Mixer::playChannel(int channel, int loops, int fadeIn, int timeout)
{
if(this->boundChannels.find(channel) == this->boundChannels.end())
{
return;
}
Mix_Chunk* p = this->boundChannels[channel];
if(fadeIn > 0)
Mix_FadeInChannelTimed(channel, p, loops, fadeIn, timeout);
else
Mix_PlayChannel(channel, p, loops);
}
inline void Mixer::haltChannel(int channel, int fadeOut)
{
if(fadeOut > 0)
Mix_FadeOutChannel(channel, fadeOut);
else
Mix_HaltChannel(channel);
}
inline void Mixer::spatial(int channel, int16_t angle, uint8_t distance)
{
if(angle == 0 && distance == 0)
distance = 1;
Mix_SetPosition(channel, (Sint16)angle, (Uint8)distance);
}
inline void Mixer::playMusic(const std::string& filePath, int loops, int fadeIn)
{
if(this->bgms.find(filePath) == this->bgms.end())
{
bool res = loadMusic(filePath);
assert(res);
}
Mix_Music* m = this->bgms[filePath].first;
if(fadeIn > 0)
Mix_FadeInMusic(m, loops, fadeIn);
else
Mix_PlayMusic(m, loops);
this->currentBGM = m;
}
inline void Mixer::haltMusic(int fadeOut)
{
if(!this->currentBGM)
return;
if(fadeOut > 0)
Mix_FadeOutMusic(fadeOut);
else
Mix_HaltMusic();
this->currentBGM = nullptr;
}
}
#endif |
ilariom/wildcat | src/core/managers/EntityManager.h | #ifndef _WKT_ENTITY_MANAGER_H
#define _WKT_ENTITY_MANAGER_H
#include "ecs/Entity.h"
#include <unordered_map>
#include <vector>
namespace wkt {
namespace managers
{
class EntityManager final
{
public:
using iterator = std::unordered_map<wkt::ecs::Entity::EntityUniqueID, wkt::ecs::Entity>::iterator;
private:
using Entity = wkt::ecs::Entity;
public:
EntityManager() = default;
EntityManager(const EntityManager&) = delete;
EntityManager(EntityManager&&) = default;
~EntityManager() = default;
EntityManager& operator=(const EntityManager&) = delete;
EntityManager& operator=(EntityManager&&) = default;
public:
Entity& make();
void kill(Entity::EntityUniqueID id);
void kill(const Entity& en);
void gain(Entity&& en);
Entity* operator[](Entity::EntityUniqueID id);
void clean();
iterator begin() { return this->entities.begin(); }
iterator end() { return this->entities.end(); }
private:
std::vector<Entity::EntityUniqueID> toBeKilled;
std::unordered_map<Entity::EntityUniqueID, Entity> entities;
};
}}
#endif |
ilariom/wildcat | src/core/components/Table.h | #ifndef _WKT_TABLE_H
#define _WKT_TABLE_H
#include "ecs/Component.h"
#include <string>
#include <tuple>
#include <vector>
#include <algorithm>
#include <memory>
namespace wkt {
namespace components
{
class Table : public wkt::ecs::Component
{
public:
Table(const std::string& name) : name(name) { }
public:
bool unique() const override { return false; }
const std::string& getName() const { return this->name; }
private:
std::string name;
};
template<typename... types>
class Scheme : public Table
{
public:
Scheme(const std::string& name) : Table(name) { }
inline Scheme(const Scheme&);
Scheme(Scheme&&) = default;
inline Scheme& operator=(const Scheme&);
Scheme& operator=(Scheme&&) = default;
public:
inline void update(types... vals);
inline void remove(types... vals);
Scheme& operator+=(const std::tuple<types...>& t) { this->relation.push_back(t); return *this; }
inline std::tuple<types...>& operator[](size_t n);
template<int N>
Scheme selectWhere(typename std::tuple_element<N, std::tuple<types...>>::type value)
{
Scheme sr(getName());
sr.schemeRef = this->schemeRef == nullptr ? this : this->schemeRef;
for(auto& t : this->relation)
if(std::get<N>(t) == value)
sr += t;
return sr;
}
private:
std::vector<std::tuple<types...>> relation;
Scheme<types...>* schemeRef = nullptr;
};
template<typename... types>
inline void Scheme<types...>::update(types... vals)
{
auto t = std::make_tuple<types...>(std::forward<types>(vals)...);
this->relation.push_back(t);
}
template<typename... types>
inline void Scheme<types...>::remove(types... vals)
{
auto t = std::make_tuple<types...>(std::forward<types>(vals)...);
auto it = std::find(this->relation.begin(), this->relation.end(), t);
if(it != this->relation.end())
this->relation.erase(it);
}
template<typename... types>
inline Scheme<types...>::Scheme(const Scheme& sch)
{
this->relation = sch.relation;
this->schemeRef = nullptr;
}
template<typename... types>
inline Scheme<types...>& Scheme<types...>::operator=(const Scheme& sch)
{
this->relation = sch.relation;
this->schemeRef = nullptr;
return *this;
}
template<typename... types>
inline std::tuple<types...>& Scheme<types...>::operator[](size_t n)
{
if(this->schemeRef)
{
auto t = this->relation[n];
for(auto& v : this->schemeRef->relation)
if(v == t)
return v;
}
return this->relation[n];
}
template<typename... types>
std::shared_ptr<Table> make_table_from_scheme(const Scheme<types...>& scheme)
{
return std::make_shared<Table>(static_cast<Table>(scheme));
}
REGISTER_COMPONENT(Table, -7);
}}
#endif |
ilariom/wildcat | src/core/main_loop.h | <gh_stars>10-100
#ifndef _WKT_MAIN_LOOP_H
#define _WKT_MAIN_LOOP_H
namespace wkt
{
void mainLoop();
}
#endif |
ilariom/wildcat | src/core/ecs/comp_traits.h | <reponame>ilariom/wildcat
#ifndef _WKT_COMP_TRAITS_H
#define _WKT_COMP_TRAITS_H
#include <cstdint>
#define REGISTER_COMPONENT(type_name, type_id) \
template<> \
struct comp_traits<type_name> \
{ \
constexpr static int32_t id = type_id; \
}; \
\
template<> \
struct comp_id_traits<type_id> \
{ \
using type = type_name; \
};
#define REGISTER_DRAWABLE(type_name, type_id) \
REGISTER_COMPONENT(type_name, type_id) \
template<> \
struct drawable_traits<type_name> \
{ \
constexpr static bool value = true; \
};
#define REGISTER_SCRIPT(type_name) \
template<> \
struct comp_traits<type_name> \
{ \
constexpr static int32_t id = comp_traits<Script>::id; \
};
namespace wkt {
namespace components
{
template<typename C>
struct comp_traits;
template<int32_t type_id>
struct comp_id_traits;
template<typename C>
struct drawable_traits
{
constexpr static bool value = false;
};
template<typename C>
constexpr int32_t get_type_id()
{
return comp_traits<C>::id;
}
template<typename C>
constexpr bool is_drawable()
{
return drawable_traits<C>::value;
}
}}
#endif |
ilariom/wildcat | src/core/systems/RenderSystem.h | <gh_stars>10-100
#ifndef _WKT_RENDER_SYSTEM_H
#define _WKT_RENDER_SYSTEM_H
#include "ecs/System.h"
#include "components/Node.h"
#include "graphics/Director.h"
namespace wkt {
namespace systems
{
class RenderSystem : public wkt::ecs::HierarchicalSystem
{
public:
RenderSystem();
public:
bool operator()(wkt::components::Node&);
void setDirector(wkt::gph::Director* director) { this->director = director; }
private:
const wkt::gph::Director* director;
};
}}
#endif |
ilariom/wildcat | src/core/components/Sprite.h | <reponame>ilariom/wildcat
#ifndef _WKT_SPRITE_H
#define _WKT_SPRITE_H
#include "graphics/ShadedDrawable.h"
#include "graphics/SmartSurface.h"
#include "graphics/Color.h"
#include "math/wktmath.h"
#include <string>
namespace wkt {
namespace components
{
class Sprite : public wkt::gph::ShadedDrawable
{
public:
Sprite(const std::string& filename) : ss1(filename), ss2(ss1) { setBuffersTo(&ss1, &ss2); }
inline Sprite(const Sprite&);
inline Sprite(Sprite&&);
~Sprite() = default;
inline Sprite& operator=(const Sprite&);
inline Sprite& operator=(Sprite&&);
public:
bool unique() const override { return false; }
wkt::math::Size size() const { return this->ss1.size(); }
inline void setColor(const wkt::gph::Color&);
inline void setOpacity(uint8_t);
const wkt::gph::Color& getColor() const { return this->ss1.getColor(); }
uint8_t getOpacity() const { return this->ss1.getOpacity(); }
const std::string& getPath() const { return this->ss1.getPath(); }
void crop(const wkt::math::Rect& r)
{
this->ss1.crop(r);
this->ss2.crop(r);
}
private:
wkt::gph::SmartSurface ss1;
wkt::gph::SmartSurface ss2;
};
inline Sprite::Sprite(const Sprite& s) : ss1(s.ss1), ss2(s.ss2)
{
setBuffersTo(&this->ss1, &this->ss2);
}
inline Sprite::Sprite(Sprite&& s) : ss1(std::move(s.ss1)), ss2(std::move(s.ss2))
{
setBuffersTo(&this->ss1, &this->ss2);
}
inline Sprite& Sprite::operator=(const Sprite& s)
{
this->ss1 = wkt::gph::SmartSurface(s.ss1);
this->ss2 = wkt::gph::SmartSurface(s.ss2);
setBuffersTo(&this->ss1, &this->ss2);
return *this;
}
inline Sprite& Sprite::operator=(Sprite&& s)
{
std::swap(this->ss1, s.ss1);
std::swap(this->ss2, s.ss2);
setBuffersTo(&this->ss1, &this->ss2);
return *this;
}
inline void Sprite::setColor(const wkt::gph::Color& color)
{
this->ss1.setColor(color);
this->ss2.setColor(color);
}
inline void Sprite::setOpacity(uint8_t opacity)
{
this->ss1.setOpacity(opacity);
this->ss2.setOpacity(opacity);
}
REGISTER_DRAWABLE(Sprite, -3);
}}
#endif |
ilariom/wildcat | src/core/pixmanip/pixmanip.h | <reponame>ilariom/wildcat<filename>src/core/pixmanip/pixmanip.h
#ifndef WKT_SHADERS_H
#define WKT_SHADERS_H
#include "math/wktmath.h"
#include "math/numerical.h"
#include "graphics/Color.h"
#include "graphics/Pixel.h"
namespace wkt {
namespace pixmanip
{
class lighten
{
public:
lighten(float factor = 1) : factor(wkt::math::clamp(factor, 0, 1)) { }
inline wkt::gph::Color operator()(const wkt::gph::PixelIterator& p)
{
wkt::gph::Color c = *p;
float m = std::max({c.r, c.g, c.b});
float a = 1 / m;
return {
std::max(this->factor, a * c.r),
std::max(this->factor, a * c.g),
std::max(this->factor, a * c.b),
c.a
};
}
private:
float factor;
};
class darken
{
public:
darken(float factor = 0) : factor(wkt::math::clamp(factor, 0, 1)) { }
inline wkt::gph::Color operator()(const wkt::gph::PixelIterator& p)
{
wkt::gph::Color c = *p;
float m = std::max({c.r, c.g, c.b});
float a = 1 - m;
return {
std::min(this->factor, a * c.r),
std::min(this->factor, a * c.g),
std::min(this->factor, a * c.b),
c.a
};
}
private:
float factor;
};
class blackAndWhite
{
public:
blackAndWhite(float br = 1, float bg = 1, float bb = 1)
{
this->den = br + bg + bb;
this->br = br / this->den;
this->bg = bg / this->den;
this->bb = bb / this->den;
}
inline wkt::gph::Color operator()(const wkt::gph::PixelIterator& p)
{
wkt::gph::Color c = *p;
float v = (this->br * c.r + this->bg * c.g + this->bb * c.b) / this->den;
return {
v, v, v, c.a
};
}
private:
float br, bg, bb, den;
};
}}
#endif |
ilariom/wildcat | src/core/components/BoundingBox.h | <gh_stars>10-100
#ifndef WKT_BOUNDING_BOX
#define WKT_BOUNDING_BOX
#include "ecs/Component.h"
#include "math/wktmath.h"
#include <memory>
namespace wkt {
namespace components
{
struct BoundingBox : public wkt::ecs::Component, public wkt::math::Rect
{
virtual void update() { };
};
template<typename sz_src, typename pos_src, template<typename> class S = std::shared_ptr>
class BB : public BoundingBox
{
public:
void bindSizeTo(S<sz_src>& comp) { this->szcomp = comp; }
void bindPositionTo(S<pos_src>& comp) { this->poscomp = comp; }
inline void update() override;
private:
S<pos_src> poscomp;
S<sz_src> szcomp;
};
template<typename sz_src, typename pos_src, template<typename> class S>
inline void BB<sz_src, pos_src, S>::update()
{
if(this->poscomp)
this->origin = this->poscomp->getPosition();
if(this->szcomp)
this->size = this->szcomp->size();
}
struct FakePosSrc { wkt::math::vec2 zero; wkt::math::vec2& getPosition() { return zero; } };
template<typename sz_src, typename pos_src = FakePosSrc>
std::shared_ptr<BoundingBox> makeBoundingBox(std::shared_ptr<sz_src> szcomp = nullptr, std::shared_ptr<pos_src> poscomp = nullptr)
{
auto bb = std::make_shared<BB<sz_src, pos_src, std::shared_ptr>>();
if(szcomp)
bb->bindSizeTo(szcomp);
if(poscomp)
bb->bindPositionTo(poscomp);
if(szcomp || poscomp)
bb->update();
return std::static_pointer_cast<BoundingBox>(bb);
}
template<typename sz_src, typename pos_src = FakePosSrc>
std::shared_ptr<BB<sz_src, pos_src>> getBoundingBox(std::shared_ptr<BoundingBox> bb)
{
return std::static_pointer_cast<BB<sz_src, pos_src>>(bb);
}
REGISTER_COMPONENT(BoundingBox, -14);
}}
#endif |
ilariom/wildcat | src/core/graphics/SmartSurface.h | <gh_stars>10-100
#ifndef _WKT_SMART_SURFACE_H
#define _WKT_SMART_SURFACE_H
#include "s2x/video.h"
#include "math/wktmath.h"
#include "Color.h"
#include "Pixel.h"
#include <memory>
#include <string>
namespace wkt {
namespace gph
{
class SmartSurface
{
friend PixelIterator;
public:
SmartSurface(const std::string& filename, const wkt::math::Rect& crop = {});
SmartSurface(const s2x::Surface&);
SmartSurface(const SmartSurface&);
SmartSurface(SmartSurface&&) = default;
~SmartSurface() = default;
SmartSurface& operator=(const SmartSurface&);
SmartSurface& operator=(SmartSurface&&) = default;
public:
inline PixelIterator operator()(int x, int y);
inline const PixelIterator operator()(int x, int y) const;
s2x::Texture& getTexture();
inline wkt::math::Size size() const;
void resetSurface();
const std::string& getPath() const { return this->filename; }
void setColor(const Color& color) { this->color = color; }
const Color& getColor() const { return this->color; }
void setOpacity(uint8_t opacity) { this->opacity = opacity; }
uint8_t getOpacity() const { return this->opacity; }
void blit(const SmartSurface& other, const wkt::math::vec2& position);
void blit(const SmartSurface& other, const wkt::math::vec2& position, float scaleX, float scaleY);
void crop(const wkt::math::Rect& rect) { this->texRect = rect; }
const wkt::math::Rect& getTextureRect() const { return this->texRect; }
explicit operator bool() const { return static_cast<SDL_Surface*>(*this->activeSurface) != nullptr; }
private:
void copyOnAccess();
private:
std::shared_ptr<s2x::Surface> commonSurface;
std::shared_ptr<s2x::Texture> commonTexture;
std::unique_ptr<s2x::Surface> localSurface = nullptr;
std::unique_ptr<s2x::Texture> localTexture = nullptr;
s2x::Surface* activeSurface;
bool surfaceModified = false;
bool isAlreadyCloned = false;
std::string filename;
Color color = colors::WHITE;
uint8_t opacity = 255;
wkt::math::Rect texRect;
};
inline PixelIterator SmartSurface::operator()(int x, int y)
{
copyOnAccess();
PixelIterator p(*this, {(float)x, (float)y});
s2x::Pixel* pp = reinterpret_cast<s2x::Pixel*>(&p);
*pp = (*this->activeSurface)(x, y);
return p;
}
inline const PixelIterator SmartSurface::operator()(int x, int y) const
{
PixelIterator p(const_cast<SmartSurface&>(*this), {(float)x, (float)y});
s2x::Pixel* pp = &p;
*pp = (*this->activeSurface)(x, y);
return p;
}
inline wkt::math::Size SmartSurface::size() const
{
if(this->texRect.size.width > 0 && this->texRect.size.height > 0)
return this->texRect.size;
return this->activeSurface->size();
}
}}
#endif |
ilariom/wildcat | src/core/components/ScriptInterface.h | <filename>src/core/components/ScriptInterface.h
#ifndef WKT_SCRIPT_INTERFACE_H
#define WKT_SCRIPT_INTERFACE_H
#include "components/Script.h"
#include <functional>
namespace wkt {
namespace components
{
class ScriptInterface : public wkt::components::Script
{
public:
struct Responder
{
std::function<void()> init = nullptr;
std::function<void(const std::string&, const wkt::ecs::Entity&)> onMessage = nullptr;
std::function<void(duration)> update = nullptr;
};
public:
inline void init() override;
inline void onMessage(const std::string& msg, const wkt::ecs::Entity& sender) override;
inline void update(duration dt) override;
public:
Responder responder;
};
inline void ScriptInterface::init()
{
if (!this->responder.init)
return;
this->responder.init();
}
inline void ScriptInterface::onMessage(const std::string& msg, const wkt::ecs::Entity& sender)
{
if (!this->responder.onMessage)
return;
this->responder.onMessage(msg, sender);
}
inline void ScriptInterface::update(duration dt)
{
if (!this->responder.update)
return;
this->responder.update(dt);
}
REGISTER_COMPONENT(ScriptInterface, -16);
}}
#endif |
ilariom/wildcat | src/core/utils/recursors.h | <gh_stars>10-100
#ifndef _WKT_RECURSORS_H
#define _WKT_RECURSORS_H
#include <functional>
namespace wkt {
namespace utils
{
class AbstractRecursor
{
public:
virtual ~AbstractRecursor() = default;
public:
virtual void run() = 0;
};
template<typename node_type, typename hnd_ret_type>
class HierarchicalRecursor : public AbstractRecursor
{
public:
using handler = std::function<hnd_ret_type(node_type&)>;
public:
virtual ~HierarchicalRecursor() = default;
public:
void bindRoot(node_type root) { this->root = root; }
void bindHandler(handler hnd) { this->hnd = hnd; }
protected:
node_type& getRoot() { return this->root; }
handler& getHandler() { return this->hnd; }
private:
node_type root;
handler hnd;
};
template<typename obj_type, typename iter_type, typename hnd_ret_type>
class SequentialRecursor : public AbstractRecursor
{
public:
using iterator = iter_type;
using handler = std::function<hnd_ret_type(obj_type)>;
public:
virtual ~SequentialRecursor() = default;
public:
inline void bindIterators(iter_type begin, iter_type end);
void bindHandler(handler hnd) { this->hnd = hnd; }
protected:
iter_type begin() { return this->b; }
iter_type end() { return this->e; }
handler& getHandler() { return this->hnd; }
private:
iter_type b, e;
handler hnd;
};
template<typename obj_type, typename iter_type, typename hnd_ret_type>
inline void SequentialRecursor<obj_type, iter_type, hnd_ret_type>::bindIterators(iter_type begin, iter_type end)
{
this->b = begin;
this->e = end;
}
}}
#endif |
ilariom/wildcat | src/core/managers/SystemsManager.h | #ifndef _WKT_SYSTEMS_MANAGER_H
#define _WKT_SYSTEMS_MANAGER_H
#include "ecs/System.h"
#include "ecs/Entity.h"
#include "components/Node.h"
#include "managers/EntityManager.h"
#include <memory>
#include <vector>
#include <unordered_map>
namespace wkt {
namespace managers
{
class SystemsManager final
{
public:
SystemsManager() = default;
SystemsManager(const SystemsManager&) = delete;
SystemsManager(SystemsManager&&) = default;
~SystemsManager() = default;
SystemsManager& operator=(const SystemsManager&) = delete;
SystemsManager& operator=(SystemsManager&&) = default;
public:
SystemsManager& operator+=(std::unique_ptr<wkt::ecs::SequentialSystemBase> sys) { this->systems.push_back(std::move(sys)); return *this; }
SystemsManager& operator+=(std::unique_ptr<wkt::ecs::HierarchicalSystem> hsys) { this->hSystems.push_back(std::move(hsys)); return *this; }
void run(wkt::components::Node& node);
void run(typename EntityManager::iterator begin, typename EntityManager::iterator);
private:
std::vector<std::unique_ptr<wkt::ecs::System>> systems;
std::vector<std::unique_ptr<wkt::ecs::HierarchicalSystem>> hSystems;
};
}}
#endif |
ilariom/wildcat | src/core/graphics/Flipbook.h | <filename>src/core/graphics/Flipbook.h
#ifndef WKT_FLIPBOOK_H
#define WKT_FLIPBOOK_H
#include "math/wktmath.h"
#include <string>
#include <vector>
#include <memory>
#include <cstdint>
namespace wkt {
namespace gph
{
class Flipbook
{
public:
struct Card
{
Card() = default;
Card(std::string name, wkt::math::Rect rect, uint16_t times)
: name(name), rect(rect), times(times)
{ }
Card(wkt::math::Rect rect, uint16_t times)
: rect(rect), times(times)
{ }
Card(wkt::math::Rect rect)
: rect(rect), times(1)
{ }
std::string name;
wkt::math::Rect rect;
uint16_t times;
};
class flipbook_iterator
{
public:
flipbook_iterator(const Flipbook& fb, size_t idx);
flipbook_iterator(flipbook_iterator&&) = default;
public:
const Card& operator*() const;
flipbook_iterator& operator++();
bool operator==(const flipbook_iterator& o) const { return this->idx == o.idx; }
bool operator!=(const flipbook_iterator& o) const { return !(*this == o); }
private:
const Flipbook& fb;
size_t times;
size_t idx;
};
friend flipbook_iterator;
public:
Flipbook() = default;
Flipbook(std::vector<Card>&& cards) : cards(cards) { }
public:
void insert(size_t hint, const Card&);
void push(const Card&);
Card top();
void pop();
size_t size() const { return this->cards.size(); }
Card& operator[](const std::string& name);
const Card& operator[](const std::string& name) const;
flipbook_iterator begin() const { return flipbook_iterator { *this, 0 }; }
flipbook_iterator end() const { return flipbook_iterator { *this, size() }; }
private:
std::vector<Card> cards;
};
class FlipbookChannels
{
public:
size_t addChannel(const Flipbook&);
void setChannel(size_t, bool loop = false);
const Flipbook::Card& next();
bool hasNext() const;
size_t getCurrentChannel() const { return this->currentChannel; }
bool isLooping() const { return this->loop; }
private:
std::vector<Flipbook> channels;
std::shared_ptr<Flipbook::flipbook_iterator> it = nullptr;
size_t currentChannel;
bool loop;
};
}}
#endif |
ilariom/wildcat | src/core/graphics/Director.h | #ifndef WKT_DIRECTOR_H
#define WKT_DIRECTOR_H
#include "s2x/video.h"
#include "graphics/SmartSurface.h"
#include "graphics/Camera.h"
#include "components/Transform.h"
#include "math/wktmath.h"
namespace wkt {
namespace gph
{
class Director final
{
public:
Director(s2x::Renderer& ren) : ren(ren) { }
public:
void shot(SmartSurface&, const wkt::components::Transform& transform) const;
s2x::Renderer& getRenderer() const { return this->ren; }
Camera* getCamera() const { return this->camera; }
void setCamera(Camera* camera) { this->camera = camera; }
private:
s2x::Renderer& ren;
Camera* camera = nullptr;
};
}}
#endif |
ilariom/wildcat | src/core/ecs/Entity.h | #ifndef _SKR_ENTITY_H
#define _SKR_ENTITY_H
#include "Component.h"
#include "ComponentsVector.h"
#include "Drawable.h"
#include "utils/Multiset.h"
#include <unordered_map>
#include <vector>
#include <memory>
#include <functional>
namespace wkt {
namespace ecs
{
class Entity final
{
public:
using EntityUniqueID = unsigned long;
using iterator = wkt::utils::Multiset<Component::ComponentTypeID>::iterator;
public:
Entity();
Entity(const Entity&);
Entity(Entity&&) = default;
~Entity() = default;
Entity& operator=(const Entity&) = delete;
Entity& operator=(Entity&&) = default;
public:
EntityUniqueID getUID() const { return this->id; }
template<typename C = Component>
Entity& operator+=(std::shared_ptr<C> comp)
{
using namespace wkt::components;
comp->setEntity(this);
if(comp->unique())
{
this->components[get_type_id<C>()].clear();
}
this->components[get_type_id<C>()].push_back(std::static_pointer_cast<Component>(comp));
this->multiset.insert(get_type_id<C>());
if(is_drawable<C>())
{
this->drws.push_back(std::static_pointer_cast<Drawable>(std::static_pointer_cast<Component>(comp)));
}
return *this;
}
Entity& operator-=(const Component& comp);
Entity& remove(Component::ComponentUniqueID uid);
Entity& removeAll(Component::ComponentTypeID typeId);
template<typename C = Component>
ComponentsVector<C> query(Component::ComponentTypeID typeId) const
{
ComponentsVector<C> vec;
if(this->components.find(typeId) != this->components.end())
{
const ComponentsVector<>& cv = this->components.at(typeId);
vec = cv;
}
return vec;
}
template<typename C>
ComponentsVector<C> query() const
{
return query<C>(wkt::components::get_type_id<C>());
}
std::vector<std::shared_ptr<Drawable>>& drawables() { return this->drws; }
iterator begin() { return this->multiset.begin(); }
iterator end() { return this->multiset.end(); }
private:
void removeDrawable(const Component& drw);
private:
EntityUniqueID id;
using MapOfComps = std::unordered_map<Component::ComponentTypeID, ComponentsVector<>>;
MapOfComps components;
std::vector<std::shared_ptr<Drawable>> drws;
wkt::utils::Multiset<Component::ComponentTypeID> multiset;
};
}}
namespace std
{
template<>
struct hash<wkt::ecs::Entity>
{
size_t operator()(const wkt::ecs::Entity& e)
{
return std::hash<int>()(e.getUID());
}
};
}
#endif |
ilariom/wildcat | src/core/s2x/basics.h | #ifndef _S2X_BASICS_H
#define _S2X_BASICS_H
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <string>
namespace s2x
{
class Context
{
public:
explicit inline Context(int flags);
inline ~Context();
Context(const Context &) = delete;
Context(Context &&) = delete;
Context &operator=(const Context &) = delete;
Context &operator=(Context &&) = delete;
};
inline Context::Context(int flags)
{
SDL_Init(flags);
IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG | IMG_INIT_TIF);
TTF_Init();
}
inline Context::~Context()
{
SDL_Quit();
}
class Subsystem
{
public:
explicit Subsystem(int flags) : flags(flags) { SDL_InitSubSystem(flags); }
~Subsystem() { SDL_QuitSubSystem(flags); }
public:
bool wasInit() const { return SDL_WasInit(flags) & flags; }
private:
int flags;
};
namespace hints
{
void clearHints();
bool setHint(const std::string& name, const std::string& value);
bool setHint(const std::string& name, const std::string& value, SDL_HintPriority priority);
std::string getHint(const std::string& name);
}
namespace error
{
std::string get();
void clear();
void set(const std::string& msg);
}
std::string getBasePath();
std::string getPrefPath(const std::string& org, const std::string& app);
void log(const std::string& msg);
}
#endif |
ilariom/wildcat | src/core/s2x/events.h | <reponame>ilariom/wildcat
#ifndef _S2X_EVENTS_H
#define _S2X_EVENTS_H
#include <SDL.h>
#include <unordered_map>
#include <functional>
#include <vector>
#include <algorithm>
#include <initializer_list>
namespace s2x
{
struct EventListener
{
int tag;
std::function<void(const SDL_Event&)> handler;
};
inline bool operator==(const EventListener& e, const EventListener& f)
{
return e.tag == f.tag;
}
class EventManager
{
public:
using EventType = Uint32;
public:
inline bool poll();
void push(SDL_Event& ev) { SDL_PushEvent(&ev); }
void userInput() { while(poll()); }
void addListener(EventType t, const EventListener& l) { this->listeners[t].push_back(l); }
inline void addListener(std::initializer_list<EventType> events, const EventListener& l);
inline void removeListener(EventType t, const EventListener& l);
private:
SDL_Event cachedEvent;
std::unordered_map<EventType, std::vector<EventListener>> listeners;
};
inline bool EventManager::poll()
{
bool res = SDL_PollEvent(&cachedEvent);
if(!res)
{
return false;
}
if(this->listeners.find(cachedEvent.type) == this->listeners.end())
{
return res;
}
auto& vec = this->listeners[cachedEvent.type];
std::for_each(vec.begin(), vec.end(), [this] (const EventListener& el) {
el.handler(cachedEvent);
});
return true;
}
inline void EventManager::addListener(std::initializer_list<EventType> events, const EventListener& l)
{
for(EventType t : events)
addListener(t, l);
}
inline void EventManager::removeListener(EventType t, const EventListener& l)
{
if(this->listeners.find(t) == this->listeners.end())
{
return;
}
auto& vec = this->listeners[t];
auto it = std::find(vec.begin(), vec.end(), l);
if(it != vec.end())
{
vec.erase(it);
}
}
}
#endif |
ilariom/wildcat | src/core/systems/MessageSystem.h | <filename>src/core/systems/MessageSystem.h
#ifndef _WKT_MESSAGE_SYSTEM_H
#define _WKT_MESSAGE_SYSTEM_H
#include "ecs/System.h"
#include "ecs/Entity.h"
#include "components/Script.h"
#include "utils/Message.h"
#include <vector>
#include <string>
namespace wkt {
namespace systems
{
class MessageSystem : public wkt::ecs::SequentialSystem<wkt::components::Script>
{
public:
MessageSystem();
public:
void operator()(std::shared_ptr<wkt::components::Script>);
void shutdown() override;
private:
std::vector<wkt::utils::Message<std::string>> messages;
std::vector<wkt::ecs::Entity*> entities;
};
}}
#endif |
ilariom/wildcat | src/core/audio/basic_audio_engine.h | #ifndef WKT_BASIC_AUDIO_ENGINE_H
#define WKT_BASIC_AUDIO_ENGINE_H
#include "audio_engine_types.h"
#include "AudioStudio.h"
#include "SoundEngineer.h"
#include <string>
#include <functional>
namespace wkt {
namespace audio {
class FelixTheCat : public SoundEngineer
{
public:
FelixTheCat() : SoundEngineer("Felix The Cat")
{
insert("play-music", [] (Mixer& mixer, const SoundEvent& ev) {
mixer.playMusic(ev.msg);
});
insert("play-fx", [this] (Mixer& mixer, const SoundEvent& ev) {
mixer.bindChannel(ev.msg, this->channel);
mixer.playChannel(this->channel);
this->channel = (this->channel + 1) % AudioStudio::mixer_channels;
});
}
private:
int channel = 0;
};
}}
#endif
|
ilariom/wildcat | src/core/graphics/Pixel.h | <reponame>ilariom/wildcat<gh_stars>10-100
#ifndef _WKT_PIXEL_H
#define _WKT_PIXEL_H
#include "s2x/video.h"
#include "math/wktmath.h"
#include "Color.h"
namespace wkt {
namespace gph
{
class SmartSurface;
class PixelIterator final : public s2x::Pixel
{
public:
class ColorRef final : public Color
{
friend PixelIterator;
public:
explicit ColorRef(const PixelIterator& pi) : pi(pi) { *this += pi.get(); }
public:
ColorRef& operator=(const Color& c)
{
static_cast<Color>(*this) = c;
const_cast<PixelIterator&>(pi).set(c);
return *this;
}
private:
const PixelIterator& pi;
};
public:
PixelIterator(SmartSurface&, wkt::math::vec2&&);
PixelIterator(const PixelIterator&) = default;
PixelIterator(PixelIterator&&) = default;
public:
const PixelIterator operator+(const wkt::math::vec2& offset) const;
ColorRef operator*();
const ColorRef operator*() const;
const wkt::math::vec2& position() const { return this->pos; }
const wkt::math::Size size() const;
private:
void set(const Color& c);
Color get() const;
private:
SmartSurface& ss;
wkt::math::vec2 pos;
};
}}
#endif |
ilariom/wildcat | src/core/globals/Scene.h | #ifndef _WKT_SCENE_H
#define _WKT_SCENE_H
#include "SceneGraph.h"
#include "managers/ECSContext.h"
#include <vector>
#include <algorithm>
namespace wkt {
namespace scene
{
class Scene final : public wkt::managers::ECSContext
{
public:
using SceneGraphId = std::vector<SceneGraph>::size_type;
using iterator = std::vector<SceneGraph>::iterator;
public:
Scene() { push(); };
Scene(const Scene&) = delete;
Scene(Scene&&) = delete;
~Scene() = default;
Scene& operator=(const Scene&) = delete;
Scene& operator=(Scene&&) = delete;
public:
SceneGraph& operator[](SceneGraphId id) { return this->sceneGraphs[id]; }
inline SceneGraphId push();
inline SceneGraphId pop();
inline void erase(SceneGraphId id);
inline SceneGraph& getDefaultSceneGraph() { return this->sceneGraphs[0]; }
iterator begin() { return this->sceneGraphs.begin(); }
iterator end() { return this->sceneGraphs.end(); }
private:
std::vector<SceneGraph> sceneGraphs;
};
inline Scene::SceneGraphId Scene::push()
{
this->sceneGraphs.emplace_back();
return this->sceneGraphs.size() - 1;
}
inline Scene::SceneGraphId Scene::pop()
{
if(this->sceneGraphs.size() > 1)
this->sceneGraphs.pop_back();
return this->sceneGraphs.size();
}
inline void Scene::erase(Scene::SceneGraphId id)
{
this->sceneGraphs.erase(this->sceneGraphs.begin() + id);
}
wkt::scene::Scene& getRunningScene();
void runScene(std::shared_ptr<wkt::scene::Scene> scene);
}}
#endif |
ilariom/wildcat | src/core/utils/Message.h | <gh_stars>10-100
#ifndef _WKT_MESSAGE_H
#define _WKT_MESSAGE_H
#include "ecs/Entity.h"
#include "ecs/Component.h"
#include <string>
#include <unordered_set>
#include <numeric>
namespace wkt {
namespace utils
{
template<typename T>
class Message
{
private:
using Entity = wkt::ecs::Entity;
using EntityId = wkt::ecs::Entity::EntityUniqueID;
using Component = wkt::ecs::Component;
using ComponentTypeID = wkt::ecs::Component::ComponentTypeID;
public:
Message() = default;
Message(Entity* sender) : sdr(sender) { }
public:
inline Message& sendTo(EntityId id);
inline Message& dontSendTo(EntityId id);
inline Message& andFilter(ComponentTypeID id);
inline Message& orFilter(ComponentTypeID id);
void write(T&& content) { this->content = content; }
const T& read() const { return this->content; }
const Entity& sender() const { return *this->sdr; }
inline bool isReceiver(const Entity& rcv) const;
private:
T content;
Entity* sdr;
std::unordered_set<EntityId> sto;
std::unordered_set<EntityId> dsto;
std::unordered_set<ComponentTypeID> filtand;
std::unordered_set<ComponentTypeID> filtor;
};
template<typename T>
inline Message<T>& Message<T>::sendTo(EntityId id)
{
this->sto.insert(id);
this->dsto.erase(id);
return *this;
}
template<typename T>
inline Message<T>& Message<T>::dontSendTo(EntityId id)
{
this->sto.erase(id);
this->dsto.insert(id);
return *this;
}
template<typename T>
inline Message<T>& Message<T>::andFilter(ComponentTypeID id)
{
this->filtand.insert(id);
return *this;
}
template<typename T>
inline Message<T>& Message<T>::orFilter(ComponentTypeID id)
{
this->filtor.insert(id);
return *this;
}
template<typename T>
inline bool Message<T>::isReceiver(const Entity& rcv) const
{
EntityId eid = rcv.getUID();
bool inDontSendTo = this->dsto.find(eid) != this->dsto.end();
if(inDontSendTo)
return false;
bool inSendTo = this->sto.find(eid) != this->sto.end();
bool andFilters = this->filtand.empty() || std::accumulate(this->filtand.begin(), this->filtand.end(), true,
[&rcv] (bool inFilters, ComponentTypeID id) {
return inFilters && !rcv.query(id).empty();
});
if(!andFilters)
return false;
bool orFilters = this->filtor.empty() || std::accumulate(this->filtor.begin(), this->filtor.end(), false,
[&rcv] (bool inFilters, ComponentTypeID id) {
return inFilters || !rcv.query(id).empty();
});
return inSendTo && orFilters;
}
}}
#endif |
ilariom/wildcat | src/core/utils/interpolation.h | #ifndef WKT_INTERPOLATION_H
#define WKT_INTERPOLATION_H
namespace wkt
{
class Interpolator
{
public:
Interpolator() = default;
Interpolator(
float start,
float end,
float duration,
float delay = 0
)
: start(start)
, end(end)
, duration(duration)
, delay(delay)
{ }
public:
inline float update();
bool hasEnded() const { return this->t >= this->delay + this->duration; }
float getDelay() const { return this->delay; }
float getDuration() const { return this->duration; }
float getStart() const { return this->start; }
float getEnd() const { return this->end; }
float getTimeElapsed() const { return this->t; }
void setResolution(float resolution) { this->resolution = resolution; }
float getResolution() const { return this->resolution; }
void rewind() { this->t = 0; }
private:
float start, end, duration, delay;
float t = 0;
float resolution = .016667f;
};
inline float Interpolator::update()
{
if (this->t < this->delay)
{
return this->start;
}
this->t += this->resolution;
return this->start + (this->t - this->delay) * (this->end - this->start) / this->duration;
}
}
#endif |
ilariom/wildcat | src/core/components/Body.h | #ifndef WKT_BODY_H
#define WKT_BODY_H
#include "ecs/Component.h"
#include "math/wktmath.h"
#include <vector>
namespace wkt {
namespace components
{
class Transform;
class Body : public wkt::ecs::Component
{
public:
struct Box
{
float x0, y0, x1, y1;
wkt::math::vec2 topLeft() const;
wkt::math::vec2 topRight() const;
wkt::math::vec2 bottomLeft() const;
wkt::math::vec2 bottomRight() const;
float width() const;
float height() const;
wkt::math::Size size() const;
bool contains(const wkt::math::vec2&, const wkt::math::vec2&) const;
};
struct Config
{
float mass;
float torque;
Config()
: mass(1)
, torque(0)
{ }
};
public:
Body(
wkt::components::Transform& transform,
const Config& conf = {}
)
: transform(transform)
, conf(conf)
{ }
public:
bool hit(const wkt::math::vec2&) const;
bool hit(const Box&) const;
void push(const wkt::math::vec2&) const;
void torque(float) const;
std::vector<Box>& getBoxes() { return this->boxes; }
const std::vector<Box>& getBoxes() const { return this->boxes; }
bool unique() const override;
private:
std::vector<Box> boxes;
Config conf;
wkt::components::Transform& transform;
};
REGISTER_COMPONENT(Body, -17);
}}
#endif |
ilariom/wildcat | src/core/systems/KeyboardReceiverSystem.h | #ifndef _WKT_KEYBOARD_EVENT_SYSTEM_H
#define _WKT_KEYBOARD_EVENT_SYSTEM_H
#include "ecs/System.h"
#include "components/KeyboardReceiver.h"
#include "components/KeyboardEventReceiver.h"
#include "input/KeyboardProxy.h"
#include <vector>
namespace wkt {
namespace systems
{
class KeyboardSystemBase
{
public:
void init();
void shutdown();
public:
std::vector<wkt::events::KeyboardEventType>& getEvents() { return this->events; }
private:
std::vector<wkt::events::KeyboardEventType> events;
};
class KeyboardReceiverSystem : public wkt::ecs::SequentialSystem<wkt::components::KeyboardReceiver>
{
public:
KeyboardReceiverSystem();
public:
void init() override { this->ksb.init(); }
void operator()(std::shared_ptr<wkt::components::KeyboardReceiver>);
void shutdown() override { this->ksb.shutdown(); }
private:
std::vector<wkt::events::KeyboardEventType>& getEvents() { return this->ksb.getEvents(); }
private:
KeyboardSystemBase ksb;
};
class KeyboardEventReceiverSystem : public wkt::ecs::SequentialSystem<wkt::components::KeyboardEventReceiver>
{
public:
KeyboardEventReceiverSystem();
public:
void init() override { this->ksb.init(); }
void operator()(std::shared_ptr<wkt::components::KeyboardEventReceiver>);
void shutdown() override { this->ksb.shutdown(); }
private:
std::vector<wkt::events::KeyboardEventType>& getEvents() { return this->ksb.getEvents(); }
private:
KeyboardSystemBase ksb;
};
}}
#endif |
ilariom/wildcat | src/core/utils/json/webstrings.h | <filename>src/core/utils/json/webstrings.h
#ifndef strings_h
#define strings_h
#include <string>
#include <sstream>
#include <vector>
#include <cstdlib>
namespace webstrings
{
bool is_number(const std::string& s);
std::string hungarian_to_hyphen(const std::string& s);
std::vector<std::string> split_string(const std::string& str, const std::string& delimiter);
std::string trim(const std::string& str);
template<typename T>
void to_stringstream(std::stringstream& ss, T t)
{
ss << t;
}
template<typename T, typename... TS>
void to_stringstream(std::stringstream& ss, T t, TS... ts)
{
to_stringstream(ss, t);
to_stringstream(ss, ts...);
}
template<typename... TS>
std::string to_string(TS... ts)
{
std::stringstream ss;
to_stringstream(ss, ts...);
return ss.str();
}
template<typename T>
struct from_string_struct
{
T operator()(const std::string& str) = delete;
};
template<>
struct from_string_struct<float>
{
float operator()(const std::string& str)
{
return std::strtod(str.c_str(), nullptr);
}
};
template<>
struct from_string_struct<double>
{
double operator()(const std::string& str)
{
return std::strtod(str.c_str(), nullptr);
}
};
template<>
struct from_string_struct<int>
{
int operator()(const std::string& str)
{
return std::atoi(str.c_str());
}
};
template<typename T>
T from_string(const std::string& str)
{
return from_string_struct<T>()(str);
}
template<typename T>
std::pair<bool, T> safe_from_string(const std::string& str)
{
std::pair<bool, T> p;
p.first = is_number(str);
if(p.first)
{
p.second = from_string<T>(str);
}
return p;
}
}
#endif /* strings_h */
|
ilariom/wildcat | src/core/utils/Multiset.h | <filename>src/core/utils/Multiset.h<gh_stars>10-100
#ifndef _WKT_MULTISET_H
#define _WKT_MULTISET_H
#include <unordered_map>
namespace wkt {
namespace utils
{
template<typename T, typename Hasher = std::hash<T>>
class Multiset
{
public:
class iterator
{
public:
iterator(typename std::unordered_map<T, int, Hasher>::iterator it) : it(it) { }
public:
T& operator*() { return this->it.first; }
iterator& operator++() { ++it; return it.first; }
bool operator==(const iterator& i) { return this->it == i.it; }
private:
typename std::unordered_map<T, int, Hasher>::iterator it;
};
public:
inline void insert(const T& elem);
inline void erase(const T& elem);
inline bool has(const T& elem);
iterator begin() { return iterator(this->data.begin()); }
iterator end() { return iterator(this->data.end()); }
private:
std::unordered_map<T, int, Hasher> data;
};
template<typename T, typename H>
inline void Multiset<T, H>::insert(const T& elem)
{
if(this->data.find(elem) == this->data.end())
{
this->data[elem] = 0;
}
this->data[elem]++;
}
template<typename T, typename H>
inline void Multiset<T, H>::erase(const T& elem)
{
if(this->data.find(elem) == this->data.end())
return;
this->data[elem]--;
if(this->data[elem] <= 0)
this->data.erase(elem);
}
template<typename T, typename H>
inline bool Multiset<T, H>::has(const T& elem)
{
return this->data.find(elem) != this->data.end();
}
}}
#endif |
ilariom/wildcat | src/core/ecs/ComponentsVector.h | #ifndef _WKT_COMPONENTS_VECTOR_H
#define _WKT_COMPONENTS_VECTOR_H
#include "ecs/Component.h"
#include <vector>
#include <memory>
namespace wkt {
namespace ecs
{
template<typename C = Component>
class ComponentsVector final : public std::vector<std::shared_ptr<Component>>
{
public:
std::shared_ptr<C> get(size_type n) { return std::static_pointer_cast<C>(this->operator[](n)); }
std::shared_ptr<C> first() { return get(0); }
explicit operator bool() const { return !empty(); }
std::shared_ptr<C> operator*() { return first(); }
template<typename D = Component>
ComponentsVector<C>& operator=(const ComponentsVector<D>& other)
{
using vect = std::vector<std::shared_ptr<Component>>;
*static_cast<vect*>(this) = *static_cast<const vect*>(&other);
return *this;
}
template<typename D = Component>
ComponentsVector<C>& operator=(ComponentsVector<D>&& other)
{
using vect = std::vector<std::shared_ptr<Component>>;
*static_cast<vect*>(this) = std::move(*static_cast<const vect*>(&other));
return *this;
}
};
}}
#endif |
ilariom/wildcat | src/core/components/MouseReceiver.h | #ifndef _WKT_MOUSE_RECEIVER_H
#define _WKT_MOUSE_RECEIVER_H
#include "ecs/Component.h"
#include "input/MouseProxy.h"
#include <functional>
namespace wkt {
namespace components
{
class MouseReceiver : public wkt::ecs::Component
{
public:
std::function<void(const wkt::events::MouseButtonEvent&)> onButton = nullptr;
std::function<void(const wkt::events::MouseMotionEvent&)> onMotion = nullptr;
std::function<void(const wkt::events::MouseWheelEvent&)> onWheel = nullptr;
};
REGISTER_COMPONENT(MouseReceiver, -9);
}}
#endif |
ilariom/wildcat | src/core/components/Dictionary.h | #ifndef _WKT_DICTIONARY_H
#define _WKT_DICTIONARY_H
#include "ecs/Component.h"
#include <unordered_map>
#include <memory>
namespace wkt {
namespace components
{
class AbstractDictionary : public wkt::ecs::Component
{
public:
virtual ~AbstractDictionary() = default;
public:
bool unique() const override { return false; }
};
template<typename key_type, typename mapped_type, typename key_hasher = std::hash<key_type>>
class Dictionary : public AbstractDictionary, public std::unordered_map<key_type, mapped_type, key_hasher>
{ };
template<typename key_type, typename mapped_type, typename key_hasher>
Dictionary<key_type, mapped_type, key_hasher>& getDictionary(AbstractDictionary& ad)
{
return *static_cast<Dictionary<key_type, mapped_type, key_hasher>*>(&ad);
}
template<typename key_type, typename mapped_type, typename key_hasher>
std::shared_ptr<AbstractDictionary> make_abstract_dictionary_from(const Dictionary<key_type, mapped_type, key_hasher>& dict)
{
return std::static_pointer_cast<AbstractDictionary>(std::make_shared<Dictionary<key_type, mapped_type, key_hasher>>(dict));
}
template<typename key_type, typename mapped_type, typename key_hasher = std::hash<key_type>>
std::shared_ptr<Dictionary<key_type, mapped_type, key_hasher>> get_dictionary(const std::shared_ptr<AbstractDictionary>& ad)
{
return std::static_pointer_cast<Dictionary<key_type, mapped_type, key_hasher>>(ad);
}
REGISTER_COMPONENT(AbstractDictionary, -6);
}}
#endif |
ilariom/wildcat | src/core/graphics/FontCache.h | #ifndef _WKT_FONT_CACHE
#define _WKT_FONT_CACHE
#include "s2x/ttf.h"
#include <string>
#include <memory>
#include <unordered_map>
namespace wkt {
namespace gph
{
class FontCache final
{
public:
FontCache(const FontCache&) = delete;
FontCache(FontCache&&) = delete;
~FontCache() = default;
FontCache& operator=(const FontCache&) = delete;
FontCache& operator=(FontCache&&) = delete;
public:
static inline FontCache& getInstance();
inline std::shared_ptr<s2x::TrueTypeFont> operator()(const std::string&, int);
private:
FontCache() = default;
private:
std::unordered_map<std::string, std::shared_ptr<s2x::TrueTypeFont>> cache;
};
inline FontCache& FontCache::getInstance()
{
static FontCache sc;
return sc;
}
inline std::shared_ptr<s2x::TrueTypeFont> FontCache::operator()(const std::string& filename, int fontSize)
{
std::string key = filename + std::to_string(fontSize);
if(this->cache.find(key) == this->cache.end())
{
this->cache[key] = std::make_shared<s2x::TrueTypeFont>(filename, fontSize);
}
return this->cache[key];
}
}}
#endif |
ilariom/wildcat | src/core/components/Transform.h | <filename>src/core/components/Transform.h
#ifndef _SKR_TRANSFORM_H
#define _SKR_TRANSFORM_H
#include "ecs/Component.h"
#include "math/wktmath.h"
#include <cassert>
#include <math.h>
#include <limits>
namespace wkt {
namespace components
{
struct Coords
{
wkt::math::vec2 position { 0, 0 };
wkt::math::vec2 rotationAnchor { 0, 0 };
float rotation = 0;
float scaleX = 1;
float scaleY = 1;
Coords& operator*=(const Coords& other);
};
Coords operator*(const Coords& a, const Coords& b);
class Transform : public wkt::ecs::Component
{
private:
using ComponentTypeID = wkt::ecs::Component::ComponentTypeID;
public:
bool unique() const override { return true; }
inline void setPosition(float x, float y);
inline void setPosition(const wkt::math::vec2& position);
inline void setRotation(float rotation);
inline void setRotationAnchor(const wkt::math::vec2& ra);
inline void setScale(float scale);
inline void setScaleX(float scaleX);
inline void setScaleY(float scaleY);
inline void setScale(float scaleX, float scaleY);
const wkt::math::vec2& getPosition() const { return this->local.position; }
float getRotation() const { return this->local.rotation; }
const wkt::math::vec2& getRotationAnchor() const { return this->local.rotationAnchor; }
float getScaleX() const { return this->local.scaleX; }
float getScaleY() const { return this->local.scaleY; }
float getScale() const { assert(getScaleX() == getScaleY()); return getScaleX(); }
void addPosition(const wkt::math::vec2& moveBy) { setPosition(getPosition() + moveBy); }
void addRotation(float rotateBy) { setRotation(getRotation() + rotateBy); }
void addScaleX(float x) { setScaleX(getScaleX() + x); }
void addScaleY(float y) { setScaleY(getScaleY() + y); }
void addScale(float s) { setScale(getScale() + s); }
inline Transform& operator*=(const Transform& other);
inline Transform& invert();
inline wkt::math::vec2 operator*(const wkt::math::vec2& v);
void setParentCoordinates(Coords coords) { this->parent = std::move(coords); }
const Coords& getParentCoordinates() const { return this->parent; }
Coords getWorldCoordinates() const;
Coords getLocalCoordinates(const Coords& coords) const;
const Coords& getCoordinates() const { return this->local; }
void setCoords(const Coords& local) { this->local = local; }
private:
Coords local;
Coords parent;
};
inline void Transform::setPosition(float x, float y)
{
this->local.position.x = x;
this->local.position.y = y;
}
inline void Transform::setPosition(const wkt::math::vec2 &position)
{
this->local.position = position;
}
inline void Transform::setRotation(float rotation)
{
this->local.rotation = rotation;
}
inline void Transform::setRotationAnchor(const wkt::math::vec2& ra)
{
this->local.rotationAnchor = ra;
}
inline void Transform::setScale(float scale)
{
setScale(scale, scale);
}
inline void Transform::setScaleX(float scaleX)
{
this->local.scaleX = std::max(std::numeric_limits<float>::epsilon(), scaleX);
}
inline void Transform::setScaleY(float scaleY)
{
this->local.scaleY = std::max(std::numeric_limits<float>::epsilon(), scaleY);
}
inline void Transform::setScale(float scaleX, float scaleY)
{
this->local.scaleX = std::max(std::numeric_limits<float>::epsilon(), scaleX);
this->local.scaleY = std::max(std::numeric_limits<float>::epsilon(), scaleY);
}
inline Transform& Transform::operator*=(const Transform& other)
{
this->local *= other.local;
return *this;
}
inline Transform& Transform::invert()
{
this->local.position *= -1;
this->local.scaleX = 1.f / this->local.scaleX;
this->local.scaleY = 1.f / this->local.scaleY;
this->local.rotation *= -1;
return *this;
}
inline wkt::math::vec2 Transform::operator*(const wkt::math::vec2& v)
{
auto s = sinf(this->local.rotation);
auto c = cosf(this->local.rotation);
wkt::math::vec2 row1 { -s * this->local.scaleX, c };
wkt::math::vec2 row2 { c, s * this->local.scaleY };
return wkt::math::vec2 {
this->local.position.x + row1 * v,
this->local.position.y + row2 * v
};
}
REGISTER_COMPONENT(Transform, -2);
}}
#endif |
ilariom/wildcat | src/core/globals/World.h | #ifndef _WKT_WORLD_H
#define _WKT_WORLD_H
#include "managers/ECSContext.h"
namespace wkt
{
class World final : public wkt::managers::ECSContext
{
public:
World(const World&) = delete;
World(World&&) = delete;
~World() = default;
World& operator=(const World&) = delete;
World& operator=(World&&) = delete;
public:
static World& getInstance();
private:
World() = default;
};
}
#endif |
ilariom/wildcat | src/core/config.h | #ifndef _WKT_CONFIG_H
#define _WKT_CONFIG_H
#include <string>
namespace wkt
{
struct StartupConfig
{
std::string appName;
std::string orgName;
int windowWidth;
int windowHeight;
bool isFullscreen;
bool hardwareAccelerated;
unsigned int fps;
};
StartupConfig& getStartupConfig();
}
#endif |
ilariom/wildcat | src/core/graphics/SurfaceStream.h | #ifndef WKT_SURFACE_STREAM_H
#define WKT_SURFACE_STREAM_H
#include "SmartSurface.h"
#include "math/wktmath.h"
#include <vector>
namespace wkt {
namespace gph
{
class SurfaceStream final
{
public:
SurfaceStream(int width, int height) : target(s2x::Surface(width, height)) { this->positions.emplace_back(); }
SurfaceStream(const SurfaceStream&) = delete;
SurfaceStream(SurfaceStream&&) = delete;
~SurfaceStream() = default;
SurfaceStream& operator=(const SurfaceStream&) = delete;
SurfaceStream& operator=(SurfaceStream&&) = delete;
public:
SurfaceStream& operator<<(const wkt::gph::SmartSurface&);
SurfaceStream& operator<<(const wkt::math::vec2&);
wkt::gph::SmartSurface& sync();
wkt::gph::SmartSurface& read() { return this->target; }
const wkt::gph::SmartSurface& read() const { return this->target; }
private:
SmartSurface target;
std::vector<std::pair<const SmartSurface*, size_t>> surfaces;
std::vector<wkt::math::vec2> positions;
};
}}
#endif |
ilariom/wildcat | src/core/systems/ScriptSystem.h | <gh_stars>10-100
#ifndef _WKT_SCRIPT_SYSTEM_H
#define _WKT_SCRIPT_SYSTEM_H
#include "ecs/System.h"
#include "components/Script.h"
namespace wkt {
namespace systems
{
class ScriptSystem : public wkt::ecs::SequentialSystem<wkt::components::Script>
{
public:
ScriptSystem();
public:
void operator()(std::shared_ptr<wkt::components::Script>);
};
}}
#endif |
ilariom/wildcat | src/core/components/SurfacePainter.h | <filename>src/core/components/SurfacePainter.h
#ifndef WKT_SURFACE_PAINTER_H
#define WKT_SURFACE_PAINTER_H
#include "ecs/Drawable.h"
#include "graphics/SmartSurface.h"
namespace wkt {
namespace components
{
class SurfacePainter : public wkt::ecs::Drawable
{
using SmartSurface = wkt::gph::SmartSurface;
public:
explicit SurfacePainter(const SmartSurface& ss) : ss(ss) { }
explicit SurfacePainter(SmartSurface&& ss) : ss(std::move(ss)) { }
public:
void draw(const wkt::gph::Director& d, const wkt::components::Transform& t) override
{
d.shot(this->ss, t);
}
bool unique() const override { return false; }
SmartSurface& getSurface() { return this->ss; }
private:
SmartSurface ss;
};
REGISTER_DRAWABLE(SurfacePainter, -15);
}}
#endif |
ilariom/wildcat | src/core/components/Text.h | <reponame>ilariom/wildcat<gh_stars>10-100
#ifndef WKT_TEXT_H
#define WKT_TEXT_H
#include "ecs/Drawable.h"
#include "graphics/SmartSurface.h"
#include "graphics/Color.h"
#include "s2x/ttf.h"
#include <string>
#include <memory>
namespace wkt {
namespace components
{
class Text : public wkt::ecs::Drawable
{
public:
Text(const std::string& fontPath, int fontSize);
Text(const Text&);
Text(Text&&) = default;
~Text() = default;
Text& operator=(const Text&);
Text& operator=(Text&&) = default;
public:
void write(const std::string& text);
void setColor(const wkt::gph::Color& color) { this->color = color; }
void setOpacity(uint8_t opacity);
const std::string& getWrittenText() const { return this->text; }
const wkt::gph::Color& getColor() const { return this->color; }
uint8_t getOpacity() const { return this->opacity; }
void draw(const wkt::gph::Director&, const wkt::components::Transform&) override;
private:
std::string text;
wkt::gph::Color color = wkt::gph::colors::WHITE;
uint8_t opacity = 255;
std::shared_ptr<s2x::TrueTypeFont> ttf;
std::unique_ptr<wkt::gph::SmartSurface> ss = nullptr;
};
REGISTER_DRAWABLE(Text, -13);
}}
#endif |
ilariom/wildcat | src/core/components/JSON.h | #ifndef WKT_JSON_H
#define WKT_JSON_H
#include "ecs/Component.h"
#include "utils/json/webjson.h"
namespace wkt {
namespace components
{
class JSON : public wkt::ecs::Component, public webjson::Object
{ };
REGISTER_COMPONENT(JSON, -11);
}}
#endif |
ilariom/wildcat | src/core/graphics/Camera.h | #ifndef WKT_CAMERA_H
#define WKT_CAMERA_H
#include "math/wktmath.h"
#include "components/Transform.h"
namespace wkt {
namespace gph
{
class Camera
{
public:
void setPosition(const wkt::math::vec2& pos) { this->pos = pos; this->dirty = true; }
void setSize(const wkt::math::Size& sz) { this->sz = sz; this->dirty = true; }
void setRotation(float rot) { this->rot = rot; }
const wkt::math::vec2& position() const { return this->pos; }
const wkt::math::Size& size() const { return this->sz; }
float rotation() const { return this->rot; }
inline const wkt::math::Rect& getBoundingBox() const;
inline wkt::components::Transform getScreenCoordinates(const wkt::components::Transform& t) const;
private:
wkt::math::vec2 pos {0, 0};
wkt::math::Size sz;
mutable wkt::math::Rect boundingBox;
mutable bool dirty = false;
float rot = 0;
};
inline wkt::components::Transform Camera::getScreenCoordinates(const wkt::components::Transform& t) const
{
auto obj = t.getWorldCoordinates();
wkt::components::Transform scrCoords;
scrCoords.setPosition(obj.position - position());
scrCoords.setRotation(obj.rotation - rotation());
scrCoords.setRotationAnchor(obj.rotationAnchor);
return scrCoords;
}
inline const wkt::math::Rect& Camera::getBoundingBox() const
{
if(this->dirty)
{
this->boundingBox = {
position(),
size()
};
this->dirty = false;
}
return this->boundingBox;
}
}}
#endif |
ilariom/wildcat | src/core/math/wktmath.h | #ifndef _WKT_MATH_H
#define _WKT_MATH_H
#include "s2x/s2x_types.h"
#include <math.h>
#include <ostream>
namespace wkt {
namespace math
{
class vec2
{
public:
float x, y;
inline vec2& operator+=(const vec2&);
inline vec2& operator-=(const vec2&);
inline vec2& operator*=(float s);
float lengthSquared() const { return this->x * this->x + this->y * this->y; }
float length() const { return sqrtf(lengthSquared()); }
bool operator==(const vec2& v) const
{
return this->x == v.x && this->y == v.y;
}
bool operator!=(const vec2& v) const { return !(*this == v); }
};
inline vec2& vec2::operator+=(const vec2& v)
{
this->x += v.x;
this->y += v.y;
return *this;
}
inline vec2& vec2::operator-=(const vec2& v)
{
this->x -= v.x;
this->y -= v.y;
return *this;
}
inline vec2& vec2::operator*=(float s)
{
this->x *= s;
this->y *= s;
return *this;
}
inline vec2 operator+(const vec2& a, const vec2& b)
{
return vec2(a) += b;
}
inline vec2 operator-(const vec2& a, const vec2& b)
{
return vec2(a) -= b;
}
inline vec2 operator*(const vec2& v, float s)
{
return vec2(v) *= s;
}
inline vec2 operator*(float s, const vec2& v)
{
return v * s;
}
inline float operator*(const vec2& a, const vec2& b)
{
return a.x * b.x + a.y * b.y;
}
inline std::ostream& operator<<(std::ostream& os, const vec2& v)
{
os << "(" << v.x << ", " << v.y << ")";
return os;
}
class mat2
{
public:
mat2() = default;
mat2(const vec2 col1, const vec2& col2) : col1(col1), col2(col2) { }
mat2(float i11, float i21, float i12, float i22)
{
this->col1 = { i11, i21 };
this->col2 = { i12, i22 };
}
const vec2& firstColumn() const { return this->col1; }
const vec2& secondColumn() const { return this->col2; }
vec2 firstRow() const { return { col1.x, col2.x }; }
vec2 secondRow() const { return { col1.y, col2.y }; }
inline float& operator()(int i, int j);
const float& operator()(int i, int j) const { return (*this)(i, j); }
inline mat2& operator+=(const mat2& other);
inline mat2& operator-=(const mat2& other);
inline mat2& operator*=(float x);
inline mat2 operator*(const mat2& other);
vec2 transform(const vec2& v)
{
vec2 res;
res.x = col1.x * v.x + col2.x * v.y;
res.y = col1.y * v.x + col2.y * v.y;
return res;
}
private:
vec2 col1;
vec2 col2;
};
inline float& mat2::operator()(int i, int j)
{
return j == 1 ?
(i == 1 ? col1.x : col1.y)
: (i == 1) ? col2.x : col2.y;
}
inline mat2& mat2::operator+=(const mat2& other)
{
this->col1 += other.col1;
this->col2 += other.col2;
return *this;
}
inline mat2& mat2::operator-=(const mat2& other)
{
this->col1 -= other.col1;
this->col2 -= other.col2;
return *this;
}
inline mat2& mat2::operator*=(float x)
{
this->col1 *= x;
this->col2 *= x;
return *this;
}
inline mat2 operator+(const mat2& a, const mat2& b)
{
mat2 c = a;
c += b;
return c;
}
inline mat2 operator-(const mat2& a, const mat2& b)
{
mat2 c = a;
c -= b;
return c;
}
inline mat2 operator*(const mat2& a, float x)
{
mat2 c = a;
c *= x;
return c;
}
inline mat2 operator*(float x, const mat2& a)
{
return a * x;
}
inline mat2 mat2::operator*(const mat2& m)
{
mat2 res;
auto row1 = firstRow();
auto row2 = secondRow();
res.col1.x = row1 * m.firstColumn();
res.col2.x = row1 * m.secondColumn();
res.col1.y = row2 * m.firstColumn();
res.col2.y = row2 * m.secondColumn();
return res;
}
inline std::ostream& operator<<(std::ostream& os, const mat2& m)
{
os << "[" << m.firstColumn() << ", " << m.secondColumn() << "]";
return os;
}
struct Size
{
Size() = default;
Size(float width, float height) : width(width), height(height) {}
Size(const s2x::Size& sdls) : width((float)sdls.width), height((float)sdls.height) {}
explicit Size(const vec2 &v) : width(v.x), height(v.y) {}
explicit operator vec2() const { return vec2{this->width, this->height}; }
operator s2x::Size() const
{
return {
(int) this->width,
(int) this->height
};
}
float width = 0;
float height = 0;
};
inline Size operator*(const Size& a, const Size& b)
{
return Size(std::max(a.width, b.width), std::max(a.height, b.height));
}
inline Size operator/(const Size& a, const Size& b)
{
return Size(std::min(a.width, b.width), std::min(a.height, b.height));
}
inline bool operator<(const Size& a, const Size& b)
{
return a.width * a.height < b.width * b.height;
}
inline bool operator==(const Size& a, const Size& b)
{
return a.width == b.width && a.height == b.height;
}
inline bool operator!=(const Size& a, const Size& b)
{
return !(a == b);
}
inline std::ostream& operator<<(std::ostream& os, const Size& s)
{
os << "<" << s.width << ", " << s.height << ">";
return os;
}
struct Rect
{
Rect() = default;
Rect(const vec2& origin, const Size& size)
: origin(origin), size(size) {}
Rect(float x, float y, float width, float height) : origin{x, y}, size(width, height) {}
Rect(const SDL_Rect& sdlr) : origin{(float)sdlr.x, (float)sdlr.y}, size((float)sdlr.w, (float)sdlr.h) {}
vec2 origin;
Size size;
inline bool intersect(const Rect& rect);
inline bool intersect(const vec2& v);
operator SDL_Rect() const
{
return {
(int) this->origin.y,
(int) this->origin.x,
(int) this->size.width,
(int) this->size.height
};
}
};
inline bool Rect::intersect(const Rect& rect)
{
const vec2& upperLeft = rect.origin;
vec2 upperRight{rect.origin.x + rect.size.width, rect.origin.y};
vec2 lowerLeft{rect.origin.x, rect.origin.y + rect.size.height};
vec2 lowerRight{rect.origin.x + rect.size.width, rect.origin.y + rect.size.height};
return intersect(upperLeft) || intersect(upperRight) || intersect(lowerLeft) || intersect(lowerRight);
}
inline bool Rect::intersect(const vec2& v)
{
return this->origin.x <= v.x && v.x <= this->origin.x + this->size.width
&& this->origin.y <= v.y && v.y <= this->origin.y + this->size.height;
}
inline bool operator==(const Rect& a, const Rect& b)
{
return a.origin == b.origin && a.size == b.size;
}
inline bool operator!=(const Rect& a, const Rect& b)
{
return !(a == b);
}
inline std::ostream& operator<<(std::ostream& os, const Rect& v)
{
os << "{" << v.origin << ", " << v.size << "}";
return os;
}
}}
#endif |
ilariom/wildcat | src/core/components/Node.h | #ifndef _SKR_NODE_H
#define _SKR_NODE_H
#include "ecs/Component.h"
#include <vector>
#include <memory>
#include <algorithm>
namespace wkt {
namespace components
{
class Node : public wkt::ecs::Component
{
using Component = wkt::ecs::Component;
public:
inline void appendChild(std::shared_ptr<Node> node);
inline void removeChild(std::shared_ptr<Node> node);
void removeAllChildren() { this->children.clear(); }
inline void removeFromParent();
const Node* getParent() const { return this->parent; }
bool hasParent() const { return getParent() != nullptr; }
void prune(bool enable) { this->shouldPrune = enable; }
bool prune() const { return this->shouldPrune; }
const std::vector<std::shared_ptr<Node>>& getChildren() const { return this->children; }
void visit(std::function<bool(Node&)> fn);
private:
std::vector<std::shared_ptr<Node>> children;
Node* parent;
bool shouldPrune = false;
};
inline void Node::appendChild(std::shared_ptr<Node> node)
{
this->children.push_back(node);
node->parent = this;
}
inline void Node::removeChild(std::shared_ptr<Node> node)
{
auto it = std::find(this->children.begin(), this->children.end(), node);
if(it != this->children.end())
{
(*it)->parent = nullptr;
this->children.erase(it);
}
}
inline void Node::removeFromParent()
{
auto par = this->parent;
const auto& children = par->getChildren();
std::shared_ptr<Node> self = nullptr;
for(auto& ptr : children)
{
if(*ptr == *this)
{
self = ptr;
break;
}
}
if(self)
{
par->removeChild(self);
}
}
REGISTER_COMPONENT(Node, -1);
}} // wkt
#endif |
ilariom/wildcat | src/core/utils/json/webjson.h | <filename>src/core/utils/json/webjson.h
#ifndef json_h
#define json_h
#include <string>
#include <vector>
#include <unordered_map>
#include <cstdint>
#include <memory>
namespace webjson
{
class Object
{
public:
enum class Type
{
MAP,
VALUE,
ARRAY
};
public:
Object() = default;
Object(const Object&);
Object(Object&&) = default;
Object& operator=(const Object&);
Object& operator=(Object&&) = default;
~Object() = default;
public:
Object& operator[](const std::string& key);
Object& operator[](unsigned int index);
const Object& operator[](const std::string& key) const;
const Object& operator[](unsigned int index) const;
inline const Object& at(const std::string& key) const;
inline const Object& at(unsigned int index) const;
bool has(const std::string& key) const;
std::vector<std::string> getKeys() const;
void push(const Object& obj);
void operator=(const std::string& value);
void operator=(float value);
std::string asString() const;
float asNumber() const;
bool isMap() const { return type() == Type::MAP; }
bool isValue() const { return type() == Type::VALUE; }
bool isArray() const { return type() == Type::ARRAY; }
bool isEmpty() const { return this->value == "" && this->omap.empty() && this->vect.empty(); }
bool isNumber() const;
Type type() const { return this->objType; }
size_t size() const;
std::string toStyledString() const { return toStyledString(""); }
bool operator==(const Object& o) const
{
bool isValueEqual = isValue() && this->value == o.value;
bool isMapEqual = isMap() && this->omap == o.omap;
bool isArrayEqual = isArray() && this->vect == o.vect;
return type() == o.type()
&& (isValueEqual || isMapEqual || isArrayEqual);
}
private:
void setAsMap();
void setAsValue(const std::string& value);
void setAsArray();
std::string toStyledString(const std::string& tabs) const;
void setType(Type type) { this->objType = type; }
private:
Type objType = Type::VALUE;
std::string value;
std::unordered_map<std::string, std::shared_ptr<Object>> omap;
std::vector<std::shared_ptr<Object>> vect;
};
std::string stringify(const Object& json);
Object parse(const std::string& text, std::string* error = nullptr);
}
#endif /* json_h */
|
ilariom/wildcat | src/core/s2x/ttf.h | #ifndef S2X_TTF_H
#define S2X_TTF_H
#include <SDL.h>
#include <SDL_ttf.h>
#include "s2x/video.h"
#include <string>
namespace s2x
{
class TrueTypeFont final
{
public:
inline TrueTypeFont(const std::string& fontPath, int fontSize);
TrueTypeFont(const TrueTypeFont&) = delete;
TrueTypeFont(TrueTypeFont&&) = delete;
~TrueTypeFont() { TTF_CloseFont(this->resource); }
TrueTypeFont& operator=(const TrueTypeFont&) = delete;
TrueTypeFont& operator=(TrueTypeFont&&) = delete;
public:
operator TTF_Font*() const { return this->resource; }
const std::string& getFontPath() const { return this->fontPath; }
int getFontSize() const { return this->fontSize; }
Surface write(const std::string& text, SDL_Color color) { return Surface(TTF_RenderText_Blended(*this, text.c_str(), color)); }
private:
std::string fontPath;
int fontSize;
TTF_Font* resource = nullptr;
};
inline TrueTypeFont::TrueTypeFont(const std::string& fontPath, int fontSize) : fontPath(fontPath), fontSize(fontSize)
{
this->resource = TTF_OpenFont(fontPath.c_str(), fontSize);
}
}
#endif |
ilariom/wildcat | src/core/components/Script.h | <gh_stars>10-100
#ifndef _WKT_SCRIPT_H
#define _WKT_SCRIPT_H
#include "ecs/Component.h"
#include "ecs/Entity.h"
#include "utils/Message.h"
#include <string>
#include <chrono>
#include <vector>
namespace wkt {
namespace components
{
class Script : public wkt::ecs::Component
{
public:
using duration = std::chrono::milliseconds;
using time_point = std::chrono::high_resolution_clock::time_point;
using Message = wkt::utils::Message<std::string>;
public:
Script() = default;
virtual ~Script() noexcept = default;
public:
virtual void init() = 0;
virtual void onMessage(const std::string& msg, const wkt::ecs::Entity& sender) = 0;
virtual void update(duration dt) = 0;
public:
void scheduleUpdate() { this->updateScheduled = true; }
void unscheduleUpdate() { this->updateScheduled = false; }
bool isUpdateScheduled() const { return this->updateScheduled; }
bool unique() const override { return false; }
public:
const time_point& getLastTimePoint() const { return this->lastTimePoint; }
void setLastTimePoint(time_point tp) { this->lastTimePoint = std::move(tp); }
std::vector<Message>& messages() { return this->msgs; }
const std::string& getName() const { return this->name; }
void setName(const std::string& name) { this->name = name; }
protected:
Message makeMessage() { return Message(getEntity()); }
void sendMessage(Message msg) { this->msgs.push_back(std::move(msg)); }
private:
std::vector<Message> msgs;
std::string name;
time_point lastTimePoint = time_point(duration(0));
bool updateScheduled = false;
};
REGISTER_COMPONENT(Script, -4);
}}
#endif |
ilariom/wildcat | src/core/input/MouseProxy.h | #ifndef _WKT_MOUSE_PROXY_H
#define _WKT_MOUSE_PROXY_H
#include "s2x/events.h"
#include <cstdint>
#include <vector>
namespace wkt {
namespace events
{
enum class ButtonEvent { UP, DOWN };
enum class ButtonState { PRESSED, RELEASED };
enum class ButtonType { LEFT, MIDDLE, RIGHT, X1, X2, NONE };
struct MouseButtonEvent
{
ButtonEvent event;
ButtonType type;
ButtonState state;
uint8_t clicks;
int32_t x;
int32_t y;
};
inline ButtonType getButtonType(const SDL_MouseButtonEvent& ev)
{
switch(ev.button)
{
case SDL_BUTTON_LEFT: return ButtonType::LEFT;
case SDL_BUTTON_MIDDLE: return ButtonType::MIDDLE;
case SDL_BUTTON_RIGHT: return ButtonType::RIGHT;
case SDL_BUTTON_X1: return ButtonType::X1;
case SDL_BUTTON_X2: return ButtonType::X2;
}
return ButtonType::NONE;
}
inline MouseButtonEvent mouseButtonEventFromSDL(const SDL_MouseButtonEvent& ev)
{
return {
ev.type == SDL_MOUSEBUTTONDOWN ? ButtonEvent::DOWN : ButtonEvent::UP,
getButtonType(ev),
ev.state == SDL_PRESSED ? ButtonState::PRESSED : ButtonState::RELEASED,
(uint8_t) ev.clicks,
(int32_t) ev.x,
(int32_t) ev.y
};
}
struct MouseMotionEvent
{
int32_t x, y;
int32_t dx, dy;
std::vector<ButtonType> stateOfButtons;
};
inline std::vector<ButtonType> getButtonsDuringMotion(uint32_t state)
{
std::vector<ButtonType> res;
if((state & SDL_BUTTON_LMASK) == SDL_BUTTON_LMASK)
res.push_back(ButtonType::LEFT);
if((state & SDL_BUTTON_MMASK) == SDL_BUTTON_MMASK)
res.push_back(ButtonType::MIDDLE);
if((state & SDL_BUTTON_RMASK) == SDL_BUTTON_RMASK)
res.push_back(ButtonType::RIGHT);
if((state & SDL_BUTTON_X1MASK) == SDL_BUTTON_X1MASK)
res.push_back(ButtonType::X1);
if((state & SDL_BUTTON_X2MASK) == SDL_BUTTON_X2MASK)
res.push_back(ButtonType::X2);
return res;
}
struct MouseWheelEvent
{
int32_t dx, dy;
};
inline MouseWheelEvent& adjustMouseWheelEventForDirection(MouseWheelEvent&& mwe, uint32_t direction)
{
if(direction == SDL_MOUSEWHEEL_FLIPPED)
{
mwe.dx *= -1;
mwe.dy *= -1;
}
return mwe;
}
class MouseProxy
{
public:
void operator()(const SDL_Event& ev)
{
switch(ev.type)
{
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
this->buttonEvents.push_back(mouseButtonEventFromSDL(ev.button));
break;
case SDL_MOUSEMOTION:
this->motionEvents.push_back({
ev.motion.x,
ev.motion.y,
ev.motion.xrel,
ev.motion.yrel,
getButtonsDuringMotion(ev.motion.state)
});
break;
case SDL_MOUSEWHEEL:
this->wheelEvents.push_back(adjustMouseWheelEventForDirection({
ev.wheel.x,
ev.wheel.y,
}, ev.wheel.direction));
break;
}
}
std::vector<MouseButtonEvent>&& takeButtonEvents() { return std::move(this->buttonEvents); }
std::vector<MouseMotionEvent>&& takeMotionEvents() { return std::move(this->motionEvents); }
std::vector<MouseWheelEvent>&& takeWheelEvents() { return std::move(this->wheelEvents); }
void close()
{
this->buttonEvents.clear();
this->motionEvents.clear();
this->wheelEvents.clear();
}
private:
std::vector<MouseButtonEvent> buttonEvents;
std::vector<MouseMotionEvent> motionEvents;
std::vector<MouseWheelEvent> wheelEvents;
};
}}
#endif |
ilariom/wildcat | src/core/ecs/Component.h | #ifndef _SKR_COMPONENT_H
#define _SKR_COMPONENT_H
#include "comp_traits.h"
#include <functional>
#include <vector>
#include <memory>
namespace wkt {
namespace ecs
{
class Entity;
class Component
{
public:
using ComponentUniqueID = unsigned long;
using ComponentTypeID = int32_t;
public:
Component();
Component(const Component&);
Component(Component&&) = default;
virtual ~Component() = default;
Component& operator=(const Component&);
Component& operator=(Component&&) = default;
public:
ComponentUniqueID getUID() const { return this->id; }
virtual bool unique() const;
Entity* getEntity() const { return this->entity; }
private:
friend class Entity;
void setEntity(Entity* entity) { this->entity = entity; }
private:
ComponentUniqueID id;
Entity* entity;
};
inline bool operator==(const Component& a, const Component& b)
{
return a.getUID() == b.getUID();
}
template<typename C, template<typename> class smart_ptr>
C* comp_cast(smart_ptr<Component> sp)
{
return static_cast<C*>(sp.get());
}
}}
namespace std
{
template<>
struct hash<wkt::ecs::Component>
{
size_t operator()(const wkt::ecs::Component& c)
{
return std::hash<int>()(c.getUID());
}
};
}
#endif |
IoTBits/esp-adf | examples/dueros/main/duer_audio_wrapper.c | <filename>examples/dueros/main/duer_audio_wrapper.c
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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.
*
*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
#include <freertos/semphr.h>
#include "duer_audio_wrapper.h"
#include "lightduer_voice.h"
#include "recorder_engine.h"
#include "esp_audio.h"
#include "esp_log.h"
#include "audio_element.h"
#include "audio_mem.h"
#include "audio_hal.h"
#include "audio_common.h"
#include "fatfs_stream.h"
#include "raw_stream.h"
#include "i2s_stream.h"
#include "wav_decoder.h"
#include "wav_encoder.h"
#include "mp3_decoder.h"
#include "aac_decoder.h"
#include "http_stream.h"
static SemaphoreHandle_t s_mutex;
static int duer_playing_type = DUER_AUDIO_TYPE_UNKOWN;
esp_audio_handle_t player;
static const char *TAG = "AUDIO_WRAPPER";
static int player_pause = 0;
static int audio_pos = 0;
static void esp_audio_state_task (void *para)
{
QueueHandle_t que = (QueueHandle_t) para;
esp_audio_state_t esp_state = {0};
while (1) {
xQueueReceive(que, &esp_state, portMAX_DELAY);
ESP_LOGI(TAG, "esp_auido status:%x,err:%x", esp_state.status, esp_state.err_msg);
if ((esp_state.status == AUDIO_STATUS_STOPED)
|| (esp_state.status == AUDIO_STATUS_ERROR)) {
if (duer_playing_type == DUER_AUDIO_TYPE_SPEECH) {
duer_playing_type = DUER_AUDIO_TYPE_UNKOWN;
duer_dcs_speech_on_finished();
ESP_LOGE(TAG, "duer_dcs_speech_on_finished,%d", duer_playing_type);
} else if ((duer_playing_type == DUER_AUDIO_TYPE_MUSIC) && (player_pause == 0)) {
// duer_playing_type = 0;
duer_dcs_audio_on_finished();
ESP_LOGE(TAG, "duer_dcs_audio_on_finished, %d", duer_playing_type);
}
}
}
vTaskDelete(NULL);
}
int _http_stream_event_handle(http_stream_event_msg_t *msg)
{
if (msg->event_id == HTTP_STREAM_RESOLVE_ALL_TRACKS) {
return ESP_OK;
}
if (msg->event_id == HTTP_STREAM_FINISH_TRACK) {
return http_stream_next_track(msg->el);
}
if (msg->event_id == HTTP_STREAM_FINISH_PLAYLIST) {
return http_stream_restart(msg->el);
}
return ESP_OK;
}
static void setup_player(void)
{
if (player) {
return ;
}
esp_audio_cfg_t cfg = {
.in_stream_buf_size = 20 * 1024,
.out_stream_buf_size = 4096,
.evt_que = NULL,
.resample_rate = 48000,
.hal = NULL,
.task_prio = 5,
};
audio_hal_codec_config_t audio_hal_codec_cfg = AUDIO_HAL_ES8388_DEFAULT();
cfg.hal = audio_hal_init(&audio_hal_codec_cfg, 0);
cfg.evt_que = xQueueCreate(3, sizeof(esp_audio_state_t));
audio_hal_ctrl_codec(cfg.hal, AUDIO_HAL_CODEC_MODE_DECODE, AUDIO_HAL_CTRL_START);
player = esp_audio_create(&cfg);
xTaskCreate(esp_audio_state_task, "player_task", 3 * 1024, cfg.evt_que, 1, NULL);
// Create readers and add to esp_audio
fatfs_stream_cfg_t fs_reader = {
.type = AUDIO_STREAM_READER,
};
i2s_stream_cfg_t i2s_reader = I2S_STREAM_CFG_DEFAULT();
i2s_reader.type = AUDIO_STREAM_READER;
esp_audio_input_stream_add(player, fatfs_stream_init(&fs_reader));
esp_audio_input_stream_add(player, i2s_stream_init(&i2s_reader));
http_stream_cfg_t http_cfg = HTTP_STREAM_CFG_DEFAULT();
http_cfg.event_handle = _http_stream_event_handle;
http_cfg.type = AUDIO_STREAM_READER;
http_cfg.enable_playlist_parser = true;
audio_element_handle_t http_stream_reader = http_stream_init(&http_cfg);
esp_audio_input_stream_add(player, http_stream_reader);
// Create writers and add to esp_audio
fatfs_stream_cfg_t fs_writer = {
.type = AUDIO_STREAM_WRITER,
};
i2s_stream_cfg_t i2s_writer = I2S_STREAM_CFG_DEFAULT();
i2s_writer.type = AUDIO_STREAM_WRITER;
esp_audio_output_stream_add(player, i2s_stream_init(&i2s_writer));
esp_audio_output_stream_add(player, fatfs_stream_init(&fs_writer));
// Add decoders and encoders to esp_audio
wav_decoder_cfg_t wav_dec_cfg = DEFAULT_WAV_DECODER_CONFIG();
mp3_decoder_cfg_t mp3_dec_cfg = DEFAULT_MP3_DECODER_CONFIG();
mp3_dec_cfg.task_core = 1;
aac_decoder_cfg_t aac_cfg = DEFAULT_AAC_DECODER_CONFIG();
aac_cfg.task_core = 1;
esp_audio_codec_lib_add(player, AUDIO_CODEC_TYPE_DECODER, aac_decoder_init(&aac_cfg));
esp_audio_codec_lib_add(player, AUDIO_CODEC_TYPE_DECODER, wav_decoder_init(&wav_dec_cfg));
esp_audio_codec_lib_add(player, AUDIO_CODEC_TYPE_DECODER, mp3_decoder_init(&mp3_dec_cfg));
audio_element_handle_t m4a_dec_cfg = aac_decoder_init(&aac_cfg);
audio_element_set_tag(m4a_dec_cfg, "m4a");
esp_audio_codec_lib_add(player, AUDIO_CODEC_TYPE_DECODER, m4a_dec_cfg);
audio_element_handle_t ts_dec_cfg = aac_decoder_init(&aac_cfg);
audio_element_set_tag(ts_dec_cfg, "ts");
esp_audio_codec_lib_add(player, AUDIO_CODEC_TYPE_DECODER, ts_dec_cfg);
wav_encoder_cfg_t wav_enc_cfg = DEFAULT_WAV_ENCODER_CONFIG();
esp_audio_codec_lib_add(player, AUDIO_CODEC_TYPE_ENCODER, wav_encoder_init(&wav_enc_cfg));
// Set default volume
esp_audio_vol_set(player, 45);
AUDIO_MEM_SHOW(TAG);
ESP_LOGI(TAG, "esp_audio instance is:%p", player);
}
void duer_dcs_init(void)
{
static bool is_first_time = true;
ESP_LOGI(TAG, "duer_dcs_init");
setup_player();
duer_dcs_framework_init();
duer_dcs_voice_input_init();
duer_dcs_voice_output_init();
duer_dcs_speaker_control_init();
duer_dcs_audio_player_init();
if (s_mutex == NULL) {
s_mutex = xSemaphoreCreateMutex();
if (s_mutex == NULL) {
ESP_LOGE(TAG, "Failed to create mutex");
} else {
ESP_LOGD(TAG, "Create mutex success");
}
}
if (is_first_time) {
is_first_time = false;
duer_dcs_sync_state();
}
}
void duer_audio_wrapper_pause()
{
esp_audio_pause(player);
duer_dcs_audio_active_paused();
}
int duer_audio_wrapper_get_state()
{
esp_audio_state_t st = {0};
esp_audio_state_get(player, &st);
return st.status;
}
void duer_dcs_listen_handler(void)
{
ESP_LOGI(TAG, "enable_listen_handler, open mic");
rec_engine_trigger_start();
}
void duer_dcs_stop_listen_handler(void)
{
ESP_LOGI(TAG, "stop_listen, close mic");
rec_engine_trigger_stop();
}
void duer_dcs_volume_set_handler(int volume)
{
ESP_LOGI(TAG, "set_volume to %d", volume);
int ret = esp_audio_vol_set(player, volume);
if (ret == 0) {
ESP_LOGI(TAG, "report on_volume_changed");
duer_dcs_on_volume_changed();
}
}
void duer_dcs_volume_adjust_handler(int volume)
{
ESP_LOGI(TAG, "adj_volume by %d", volume);
int vol = 0;
esp_audio_vol_get(player, &vol);
vol += volume;
int ret = esp_audio_vol_set(player, vol);
if (ret == 0) {
ESP_LOGI(TAG, "report on_volume_changed");
duer_dcs_on_volume_changed();
}
}
void duer_dcs_mute_handler(duer_bool is_mute)
{
ESP_LOGI(TAG, "set_mute to %d", (int)is_mute);
int ret = 0;
if (is_mute) {
ret = esp_audio_vol_set(player, 0);
}
if (ret == 0) {
ESP_LOGI(TAG, "report on_mute");
duer_dcs_on_mute();
}
}
void duer_dcs_get_speaker_state(int *volume, duer_bool *is_mute)
{
ESP_LOGI(TAG, "duer_dcs_get_speaker_state");
*volume = 60;
*is_mute = false;
int ret = 0;
int vol = 0;
ret = esp_audio_vol_get(player, &vol);
if (ret != 0) {
ESP_LOGE(TAG, "Failed to get volume");
} else {
*volume = vol;
if (vol != 0) {
*is_mute = false;
} else {
*is_mute = true;
}
}
}
void duer_dcs_speak_handler(const char *url)
{
ESP_LOGI(TAG, "Playing speak: %s", url);
esp_audio_play(player, AUDIO_CODEC_TYPE_DECODER, url, 0);
xSemaphoreTake(s_mutex, portMAX_DELAY);
duer_playing_type = DUER_AUDIO_TYPE_SPEECH;
xSemaphoreGive(s_mutex);
}
void duer_dcs_audio_play_handler(const duer_dcs_audio_info_t *audio_info)
{
ESP_LOGI(TAG, "Playing audio offset:%d url:%s", audio_info->offset, audio_info->url);
esp_audio_play(player, AUDIO_CODEC_TYPE_DECODER, audio_info->url, audio_info->offset);
xSemaphoreTake(s_mutex, portMAX_DELAY);
duer_playing_type = DUER_AUDIO_TYPE_MUSIC;
player_pause = 0;
xSemaphoreGive(s_mutex);
}
void duer_dcs_audio_stop_handler()
{
ESP_LOGI(TAG, "Stop audio play");
xSemaphoreTake(s_mutex, portMAX_DELAY);
int status = duer_playing_type;
xSemaphoreGive(s_mutex);
if (status == 1) {
ESP_LOGI(TAG, "Is playing speech, no need to stop");
} else {
esp_audio_stop(player, TERMINATION_TYPE_NOW);
}
}
void duer_dcs_audio_pause_handler()
{
ESP_LOGI(TAG, "DCS pause audio play");
esp_audio_pos_get(player, &audio_pos);
player_pause = 1;
esp_audio_stop(player, 0);
}
void duer_dcs_audio_resume_handler(const duer_dcs_audio_info_t *audio_info)
{
ESP_LOGI(TAG, "Resume audio play,offset:%d, url:%s,", audio_info->offset, audio_info->url);
player_pause = 0;
esp_audio_play(player, AUDIO_CODEC_TYPE_DECODER, audio_info->url, audio_pos);
}
int duer_dcs_audio_get_play_progress()
{
int ret = 0;
uint32_t total_size = 0;
int position = 0;
ret = esp_audio_pos_get(player, &position);
if (ret == 0) {
ESP_LOGI(TAG, "Get play position %d of %d", position, total_size);
return position;
} else {
ESP_LOGE(TAG, "Failed to get play progress.");
return -1;
}
}
duer_audio_type_t duer_dcs_get_player_type()
{
return duer_playing_type;
}
int duer_dcs_set_player_type(duer_audio_type_t num)
{
duer_playing_type = num;
return 0;
}
void duer_dcs_audio_active_paused()
{
if (duer_dcs_send_play_control_cmd(DCS_PAUSE_CMD)) {
ESP_LOGE(TAG, "Send DCS_PAUSE_CMD to DCS failed");
}
ESP_LOGD(TAG, "duer_dcs_audio_active_paused");
}
void duer_dcs_audio_active_play()
{
if (duer_dcs_send_play_control_cmd(DCS_PLAY_CMD)) {
ESP_LOGE(TAG, "Send DCS_PLAY_CMD to DCS failed");
}
ESP_LOGD(TAG, "duer_dcs_audio_active_play");
}
void duer_dcs_audio_active_previous()
{
if (duer_dcs_send_play_control_cmd(DCS_PREVIOUS_CMD)) {
ESP_LOGE(TAG, "Send DCS_PREVIOUS_CMD to DCS failed");
}
ESP_LOGD(TAG, "Fduer_dcs_audio_active_previous");
}
void duer_dcs_audio_active_next()
{
if (duer_dcs_send_play_control_cmd(DCS_NEXT_CMD)) {
ESP_LOGE(TAG, "Send DCS_NEXT_CMD to DCS failed");
}
ESP_LOGD(TAG, "duer_dcs_audio_active_next");
}
|
IoTBits/esp-adf | examples/dueros/main/dueros_task.c | /*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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.
*
*/
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"
#include "freertos/event_groups.h"
#include "esp_audio_device_info.h"
#include "duer_audio_wrapper.h"
#include "lightduer_ota_notifier.h"
#include "lightduer_voice.h"
#include "lightduer_connagent.h"
#include "lightduer_dcs.h"
#include "periph_touch.h"
#include "esp_peripherals.h"
#include "periph_sdcard.h"
#include "periph_wifi.h"
#include "periph_button.h"
#include "board.h"
#include "sdkconfig.h"
#include "audio_mem.h"
#include "dueros_task.h"
#include "recorder_engine.h"
#include "esp_audio.h"
#include "esp_log.h"
#include "led.h"
#include "audio_element.h"
#include "audio_pipeline.h"
#include "audio_mem.h"
#include "i2s_stream.h"
#include "raw_stream.h"
#include "filter_resample.h"
#define DUEROS_TASK_PRIORITY 5
#define DUEROS_TASK_SIZE 6*1024
#define RECORD_SAMPLE_RATE (16000)
#define FRACTION_BITS (8)
#define CLAMPS_MAX_SHORT (32767)
#define CLAMPS_MIN_SHORT (-32768)
#define RECORD_DEBUG 0
static const char *TAG = "DUEROS";
static TimerHandle_t retry_login_timer;
extern esp_audio_handle_t player;
static esp_periph_handle_t wifi_periph_handle;
static xQueueHandle duer_que;
static TaskHandle_t wifi_set_tsk_handle;
static bool duer_login_success;
static EventGroupHandle_t duer_task_evts;
const static int WIFI_CONNECT_BIT = BIT0;
extern const uint8_t _duer_profile_start[] asm("_binary_duer_profile_start");
extern const uint8_t _duer_profile_end[] asm("_binary_duer_profile_end");
typedef enum {
DUER_CMD_UNKNOWN,
DUER_CMD_LOGIN,
DUER_CMD_CONNECTED,
DUER_CMD_START,
DUER_CMD_STOP,
DUER_CMD_QUIT,
} duer_task_cmd_t;
typedef enum {
DUER_STATE_IDLE,
DUER_STATE_CONNECTING,
DUER_STATE_CONNECTED,
DUER_STATE_START,
DUER_STATE_STOP,
} duer_task_state_t;
typedef struct {
duer_task_cmd_t type;
uint32_t *pdata;
int index;
int len;
} duer_task_msg_t;
static duer_task_state_t duer_state = DUER_STATE_IDLE;
static void duer_que_send(void *que, duer_task_cmd_t type, void *data, int index, int len, int dir)
{
duer_task_msg_t evt = {0};
evt.type = type;
evt.pdata = data;
evt.index = index;
evt.len = len;
if (dir) {
xQueueSendToFront(que, &evt, 0) ;
} else {
xQueueSend(que, &evt, 0);
}
}
void rec_engine_cb(rec_event_type_t type, void *user_data)
{
if (REC_EVENT_WAKEUP_START == type) {
ESP_LOGI(TAG, "rec_engine_cb - REC_EVENT_WAKEUP_START");
if (duer_state == DUER_STATE_START) {
return;
}
if (duer_audio_wrapper_get_state() == AUDIO_STATUS_RUNNING) {
duer_audio_wrapper_pause();
}
led_indicator_set(0, led_work_mode_turn_on);
} else if (REC_EVENT_VAD_START == type) {
ESP_LOGI(TAG, "rec_engine_cb - REC_EVENT_VAD_START");
duer_que_send(duer_que, DUER_CMD_START, NULL, 0, 0, 0);
} else if (REC_EVENT_VAD_STOP == type) {
if (duer_state == DUER_STATE_START) {
duer_que_send(duer_que, DUER_CMD_STOP, NULL, 0, 0, 0);
led_indicator_set(0, led_work_mode_turn_off);
}
ESP_LOGI(TAG, "rec_engine_cb - REC_EVENT_VAD_STOP, state:%d", duer_state);
} else if (REC_EVENT_WAKEUP_END == type) {
if (duer_state == DUER_STATE_START) {
duer_que_send(duer_que, DUER_CMD_STOP, NULL, 0, 0, 0);
}
led_indicator_set(0, led_work_mode_turn_off);
ESP_LOGI(TAG, "rec_engine_cb - REC_EVENT_WAKEUP_END");
} else {
}
}
void retry_login_timer_cb(xTimerHandle tmr)
{
ESP_LOGE(TAG, "Func:%s", __func__);
duer_que_send(duer_que, DUER_CMD_LOGIN, NULL, 0, 0, 0);
xTimerStop(tmr, 0);
}
static void report_info_task(void *pvParameters)
{
int ret;
ret = duer_report_device_info();
if (ret != DUER_OK) {
ESP_LOGE(TAG, "Report device info failed ret:%d", ret);
}
vTaskDelete(NULL);
}
static void duer_event_hook(duer_event_t *event)
{
if (!event) {
ESP_LOGE(TAG, "NULL event!!!");
}
ESP_LOGE(TAG, "event: %d", event->_event);
switch (event->_event) {
case DUER_EVENT_STARTED:
// Initialize the DCS API
duer_dcs_init();
duer_login_success = true;
duer_que_send(duer_que, DUER_CMD_CONNECTED, NULL, 0, 0, 0);
ESP_LOGE(TAG, "event: DUER_EVENT_STARTED");
xTaskCreate(&report_info_task, "report_info_task", 1024 * 2, NULL, 5, NULL);
break;
case DUER_EVENT_STOPPED:
ESP_LOGE(TAG, "event: DUER_EVENT_STOPPED");
duer_login_success = false;
duer_que_send(duer_que, DUER_CMD_QUIT, NULL, 0, 0, 0);
break;
}
}
static void duer_login(void)
{
int sz = _duer_profile_end - _duer_profile_start;
char *data = audio_calloc_inner(1, sz);
if (NULL == data) {
ESP_LOGE(TAG, "audio_malloc failed");
}
memcpy(data, _duer_profile_start, sz);
ESP_LOGI(TAG, "duer_start, len:%d\n%s", sz, data);
duer_start(data, sz);
audio_free((void *)data);
}
static esp_err_t recorder_pipeline_open(void **handle)
{
audio_element_handle_t i2s_stream_reader;
audio_pipeline_handle_t recorder;
audio_hal_codec_config_t audio_hal_codec_cfg = AUDIO_HAL_ES8388_DEFAULT();
audio_hal_handle_t hal = audio_hal_init(&audio_hal_codec_cfg, 0);
audio_hal_ctrl_codec(hal, AUDIO_HAL_CODEC_MODE_ENCODE, AUDIO_HAL_CTRL_START);
audio_pipeline_cfg_t pipeline_cfg = DEFAULT_AUDIO_PIPELINE_CONFIG();
recorder = audio_pipeline_init(&pipeline_cfg);
if (NULL == recorder) {
return ESP_FAIL;
}
i2s_stream_cfg_t i2s_cfg = I2S_STREAM_CFG_DEFAULT();
i2s_cfg.type = AUDIO_STREAM_READER;
i2s_stream_reader = i2s_stream_init(&i2s_cfg);
audio_element_info_t i2s_info = {0};
audio_element_getinfo(i2s_stream_reader, &i2s_info);
i2s_info.bits = 16;
i2s_info.channels = 2;
i2s_info.sample_rates = 48000;
audio_element_setinfo(i2s_stream_reader, &i2s_info);
rsp_filter_cfg_t rsp_cfg = DEFAULT_RESAMPLE_FILTER_CONFIG();
rsp_cfg.src_rate = 48000;
rsp_cfg.src_ch = 2;
rsp_cfg.dest_rate = 16000;
rsp_cfg.dest_ch = 1;
rsp_cfg.type = AUDIO_CODEC_TYPE_ENCODER;
audio_element_handle_t filter = rsp_filter_init(&rsp_cfg);
raw_stream_cfg_t raw_cfg = RAW_STREAM_CFG_DEFAULT();
raw_cfg.type = AUDIO_STREAM_READER;
audio_element_handle_t raw_read = raw_stream_init(&raw_cfg);
audio_pipeline_register(recorder, i2s_stream_reader, "i2s");
audio_pipeline_register(recorder, filter, "filter");
audio_pipeline_register(recorder, raw_read, "raw");
audio_pipeline_link(recorder, (const char *[]) {"i2s", "filter", "raw"}, 3);
audio_pipeline_run(recorder);
ESP_LOGI(TAG, "Recorder has been created");
*handle = recorder;
return ESP_OK;
}
static esp_err_t recorder_pipeline_read(void *handle, char *data, int data_size)
{
raw_stream_read(audio_pipeline_get_el_by_tag((audio_pipeline_handle_t)handle, "raw"), data, data_size);
return ESP_OK;
}
static esp_err_t recorder_pipeline_close(void *handle)
{
audio_pipeline_deinit(handle);
return ESP_OK;
}
static void dueros_task(void *pvParameters)
{
duer_initialize();
duer_set_event_callback(duer_event_hook);
duer_init_device_info();
uint8_t *voiceData = audio_calloc(1, REC_ONE_BLOCK_SIZE);
if (NULL == voiceData) {
ESP_LOGE(TAG, "Func:%s, Line:%d, Malloc failed", __func__, __LINE__);
return;
}
static duer_task_msg_t duer_msg;
// xEventGroupWaitBits(duer_task_evts, WIFI_CONNECT_BIT, false, true, 5000 / portTICK_PERIOD_MS);
rec_config_t eng = DEFAULT_REC_ENGINE_CONFIG();
eng.vad_off_delay_ms = 800;
eng.wakeup_time_ms = 10 * 1000;
eng.evt_cb = rec_engine_cb;
eng.open = recorder_pipeline_open;
eng.close = recorder_pipeline_close;
eng.fetch = recorder_pipeline_read;
eng.extension = NULL;
eng.support_encoding = false;
eng.user_data = NULL;
rec_engine_create(&eng);
int retry_time = 1000 / portTICK_PERIOD_MS;
int retry_num = 1;
retry_login_timer = xTimerCreate("tm_duer_login", retry_time,
pdFALSE, NULL, retry_login_timer_cb);
FILE *file = NULL;
#if RECORD_DEBUG
file = fopen("/sdcard/rec_adf_1.wav", "w+");
if (NULL == file) {
ESP_LOGW(TAG, "open rec_adf_1.wav failed,[%d]", __LINE__);
}
#endif
int task_run = 1;
while (task_run) {
if (xQueueReceive(duer_que, &duer_msg, portMAX_DELAY)) {
if (duer_msg.type == DUER_CMD_LOGIN) {
ESP_LOGE(TAG, "Recv Que DUER_CMD_LOGIN");
if (duer_state == DUER_STATE_IDLE) {
duer_login();
duer_state = DUER_STATE_CONNECTING;
} else {
ESP_LOGW(TAG, "DUER_CMD_LOGIN connecting,duer_state = %d", duer_state);
}
} else if (duer_msg.type == DUER_CMD_CONNECTED) {
ESP_LOGI(TAG, "Dueros DUER_CMD_CONNECTED, duer_state:%d", duer_state);
duer_state = DUER_STATE_CONNECTED;
retry_num = 1;
} else if (duer_msg.type == DUER_CMD_START) {
if (duer_state < DUER_STATE_CONNECTED) {
ESP_LOGW(TAG, "Dueros has not connected, state:%d", duer_state);
continue;
}
ESP_LOGI(TAG, "Recv Que DUER_CMD_START");
duer_voice_start(RECORD_SAMPLE_RATE);
duer_dcs_on_listen_started();
duer_state = DUER_STATE_START;
while (1) {
int ret = rec_engine_data_read(voiceData, REC_ONE_BLOCK_SIZE, 110 / portTICK_PERIOD_MS);
ESP_LOGD(TAG, "index = %d", ret);
if ((ret == 0) || (ret == -1)) {
break;
}
if (file) {
fwrite(voiceData, 1, REC_ONE_BLOCK_SIZE, file);
}
ret = duer_voice_send(voiceData, REC_ONE_BLOCK_SIZE);
if (ret < 0) {
ESP_LOGE(TAG, "duer_voice_send failed ret:%d", ret);
break;
}
}
} else if (duer_msg.type == DUER_CMD_STOP) {
ESP_LOGI(TAG, "Dueros DUER_CMD_STOP");
if (file) {
fclose(file);
}
duer_voice_stop();
duer_state = DUER_STATE_STOP;
} else if (duer_msg.type == DUER_CMD_QUIT && (duer_state != DUER_STATE_IDLE)) {
if (duer_login_success) {
duer_stop();
}
duer_state = DUER_STATE_IDLE;
if (PERIPH_WIFI_SETTING == periph_wifi_is_connected(wifi_periph_handle)) {
continue;
}
if (retry_num < 128) {
retry_num *= 2;
ESP_LOGI(TAG, "Dueros DUER_CMD_QUIT reconnect, retry_num:%d", retry_num);
} else {
ESP_LOGE(TAG, "Dueros reconnect failed,time num:%d ", retry_num);
xTimerStop(retry_login_timer, portMAX_DELAY);
break;
}
xTimerStop(retry_login_timer, portMAX_DELAY);
xTimerChangePeriod(retry_login_timer, retry_time * retry_num, portMAX_DELAY);
xTimerStart(retry_login_timer, portMAX_DELAY);
}
}
}
free(voiceData);
vTaskDelete(NULL);
}
void wifi_set_task (void *para)
{
periph_wifi_config_start(wifi_periph_handle, WIFI_CONFIG_ESPTOUCH);
if (ESP_OK == periph_wifi_config_wait_done(wifi_periph_handle, 30000 / portTICK_PERIOD_MS)) {
ESP_LOGI(TAG, "Wi-Fi setting successfully");
} else {
ESP_LOGE(TAG, "Wi-Fi setting timeout");
}
wifi_set_tsk_handle = NULL;
vTaskDelete(NULL);
}
esp_err_t periph_callback(audio_event_iface_msg_t *event, void *context)
{
ESP_LOGD(TAG, "Periph Event received: src_type:%x, source:%p cmd:%d, data:%p, data_len:%d",
event->source_type, event->source, event->cmd, event->data, event->data_len);
switch (event->source_type) {
case PERIPH_ID_BUTTON: {
if ((int)event->data == GPIO_REC && event->cmd == PERIPH_BUTTON_PRESSED) {
ESP_LOGI(TAG, "PERIPH_NOTIFY_KEY_REC");
rec_engine_trigger_start();
} else if ((int)event->data == GPIO_MODE &&
((event->cmd == PERIPH_BUTTON_RELEASE) || (event->cmd == PERIPH_BUTTON_LONG_RELEASE))) {
ESP_LOGI(TAG, "PERIPH_NOTIFY_KEY_REC_QUIT");
}
break;
}
case PERIPH_ID_TOUCH: {
if ((int)event->data == TOUCH_PAD_NUM4 && event->cmd == PERIPH_BUTTON_PRESSED) {
int player_volume = 0;
esp_audio_vol_get(player, &player_volume);
player_volume -= 10;
if (player_volume < 0) {
player_volume = 0;
}
esp_audio_vol_set(player, player_volume);
ESP_LOGI(TAG, "AUDIO_USER_KEY_VOL_DOWN [%d]", player_volume);
} else if ((int)event->data == TOUCH_PAD_NUM4 && (event->cmd == PERIPH_BUTTON_RELEASE)) {
} else if ((int)event->data == TOUCH_PAD_NUM7 && event->cmd == PERIPH_BUTTON_PRESSED) {
int player_volume = 0;
esp_audio_vol_get(player, &player_volume);
player_volume += 10;
if (player_volume > 100) {
player_volume = 100;
}
esp_audio_vol_set(player, player_volume);
ESP_LOGI(TAG, "AUDIO_USER_KEY_VOL_UP [%d]", player_volume);
} else if ((int)event->data == TOUCH_PAD_NUM7 && (event->cmd == PERIPH_BUTTON_RELEASE)) {
} else if ((int)event->data == TOUCH_PAD_NUM8 && event->cmd == PERIPH_BUTTON_PRESSED) {
ESP_LOGI(TAG, "AUDIO_USER_KEY_PLAY [%d]", __LINE__);
} else if ((int)event->data == TOUCH_PAD_NUM8 && (event->cmd == PERIPH_BUTTON_RELEASE)) {
} else if ((int)event->data == TOUCH_PAD_NUM9 && event->cmd == PERIPH_BUTTON_PRESSED) {
ESP_LOGI(TAG, "AUDIO_USER_KEY_WIFI_SET [%d]", __LINE__);
if (NULL == wifi_set_tsk_handle) {
if (xTaskCreate(wifi_set_task, "WifiSetTask", 3 * 1024, duer_que,
DUEROS_TASK_PRIORITY, &wifi_set_tsk_handle) != pdPASS) {
ESP_LOGE(TAG, "Error create WifiSetTask");
}
led_indicator_set(0, led_work_mode_setting);
} else {
ESP_LOGW(TAG, "WifiSetTask has already running");
}
} else if ((int)event->data == TOUCH_PAD_NUM9 && (event->cmd == PERIPH_BUTTON_RELEASE)) {
}
break;
}
case PERIPH_ID_WIFI: {
if (event->cmd == PERIPH_WIFI_CONNECTED) {
ESP_LOGI(TAG, "PERIPH_WIFI_CONNECTED [%d]", __LINE__);
duer_que_send(duer_que, DUER_CMD_LOGIN, NULL, 0, 0, 0);
led_indicator_set(0, led_work_mode_connectok);
// xEventGroupSetBits(duer_task_evts, WIFI_CONNECT_BIT);
} else if (event->cmd == PERIPH_WIFI_DISCONNECTED) {
ESP_LOGI(TAG, "PERIPH_WIFI_DISCONNECTED [%d]", __LINE__);
led_indicator_set(0, led_work_mode_disconnect);
}
break;
}
default:
break;
}
return ESP_OK;
}
void duer_service_create(void)
{
esp_log_level_set("*", ESP_LOG_INFO);
ESP_LOGI(TAG, "ADF version is %s", ADF_VER);
duer_que = xQueueCreate(3, sizeof(duer_task_msg_t));
configASSERT(duer_que);
esp_periph_config_t periph_cfg = {
.user_context = NULL,
.event_handle = periph_callback,
};
if (ESP_EXISTS == esp_periph_init(&periph_cfg)) {
esp_periph_set_callback(periph_callback);
}
periph_button_cfg_t btn_cfg = {
.gpio_mask = GPIO_SEL_36 | GPIO_SEL_39, //REC BTN & MODE BTN
};
esp_periph_handle_t button_handle = periph_button_init(&btn_cfg);
esp_periph_start(button_handle);
periph_touch_cfg_t touch_cfg = {
.touch_mask = TOUCH_PAD_SEL4 | TOUCH_PAD_SEL7 | TOUCH_PAD_SEL8 | TOUCH_PAD_SEL9,
.tap_threshold_percent = 70,
};
esp_periph_handle_t touch_periph = periph_touch_init(&touch_cfg);
esp_periph_start(touch_periph);
periph_sdcard_cfg_t sdcard_cfg = {
.root = "/sdcard",
.card_detect_pin = SD_CARD_INTR_GPIO, //GPIO_NUM_34
};
esp_periph_handle_t sdcard_handle = periph_sdcard_init(&sdcard_cfg);
esp_periph_start(sdcard_handle);
while (!periph_sdcard_is_mounted(sdcard_handle)) {
vTaskDelay(300 / portTICK_PERIOD_MS);
}
periph_wifi_cfg_t wifi_cfg = {
.ssid = CONFIG_WIFI_SSID,
.password = CONFIG_WIFI_PASSWORD,
};
wifi_periph_handle = periph_wifi_init(&wifi_cfg);
esp_periph_start(wifi_periph_handle);
duer_task_evts = xEventGroupCreate();
if (xTaskCreatePinnedToCore(dueros_task, "duerosTask", DUEROS_TASK_SIZE, duer_que,
DUEROS_TASK_PRIORITY, NULL, 0) != pdPASS) {
ESP_LOGE(TAG, "Error create duerosTask");
return;
}
}
|
IoTBits/esp-adf | components/audio_pipeline/audio_pipeline.c | <reponame>IoTBits/esp-adf<filename>components/audio_pipeline/audio_pipeline.c
/*
* ESPRESSIF MIT License
*
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
* it is 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.
*
*/
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_log.h"
#include "audio_element.h"
#include "rom/queue.h"
#include "audio_pipeline.h"
#include "audio_event_iface.h"
#include "audio_mem.h"
#include "audio_common.h"
#include "audio_mutex.h"
#include "ringbuf.h"
#include "audio_error.h"
static const char *TAG = "AUDIO_PIPELINE";
typedef struct ringbuf_item {
STAILQ_ENTRY(ringbuf_item) next;
ringbuf_handle_t rb;
bool linked;
bool kept_ctx;
} ringbuf_item_t;
typedef STAILQ_HEAD(ringbuf_list, ringbuf_item) ringbuf_list_t;
typedef struct audio_element_item {
STAILQ_ENTRY(audio_element_item) next;
audio_element_handle_t el;
bool linked;
bool kept_ctx;
audio_element_status_t el_state;
} audio_element_item_t;
typedef STAILQ_HEAD(audio_element_list, audio_element_item) audio_element_list_t;
struct audio_pipeline {
audio_element_list_t el_list;
ringbuf_list_t rb_list;
audio_element_state_t state;
xSemaphoreHandle lock;
bool linked;
audio_event_iface_handle_t listener;
};
static audio_element_item_t *audio_pipeline_get_el_item_by_tag(audio_pipeline_handle_t pipeline, const char *tag)
{
audio_element_item_t *item;
STAILQ_FOREACH(item, &pipeline->el_list, next) {
char *el_tag = audio_element_get_tag(item->el);
if (el_tag && strcasecmp(el_tag, tag) == 0) {
return item;
}
}
return NULL;
}
static esp_err_t audio_pipeline_change_state(audio_pipeline_handle_t pipeline, audio_element_state_t new_state)
{
pipeline->state = new_state;
return ESP_OK;
}
static void audio_pipeline_register_element(audio_pipeline_handle_t pipeline, audio_element_handle_t el)
{
audio_element_item_t *el_item = audio_calloc(1, sizeof(audio_element_item_t));
AUDIO_MEM_CHECK(TAG, el_item, return);
el_item->el = el;
el_item->linked = true;
STAILQ_INSERT_TAIL(&pipeline->el_list, el_item, next);
}
static void audio_pipeline_unregister_element(audio_pipeline_handle_t pipeline, audio_element_handle_t el)
{
audio_element_item_t *el_item, *tmp;
STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, tmp) {
if (el_item->el == el) {
STAILQ_REMOVE(&pipeline->el_list, el_item, audio_element_item, next);
audio_free(el_item);
}
}
}
static void add_rb_to_audio_pipeline(audio_pipeline_handle_t pipeline, ringbuf_handle_t rb)
{
ringbuf_item_t *rb_item = (ringbuf_item_t *)audio_calloc(1, sizeof(ringbuf_item_t));
AUDIO_MEM_CHECK(TAG, rb_item, return);
rb_item->rb = rb;
STAILQ_INSERT_TAIL(&pipeline->rb_list, rb_item, next);
}
audio_element_handle_t audio_pipeline_get_el_by_tag(audio_pipeline_handle_t pipeline, const char *tag)
{
if (tag == NULL || pipeline == NULL) {
ESP_LOGE(TAG, "Invalid parameters, tag:%p, p:%p", tag, pipeline);
return NULL;
}
audio_element_item_t *item;
STAILQ_FOREACH(item, &pipeline->el_list, next) {
char *el_tag = audio_element_get_tag(item->el);
if (el_tag && strcasecmp(el_tag, tag) == 0) {
return item->el;
}
}
return NULL;
}
esp_err_t audio_pipeline_set_listener(audio_pipeline_handle_t pipeline, audio_event_iface_handle_t listener)
{
audio_element_item_t *el_item;
if (pipeline->listener) {
audio_pipeline_remove_listener(pipeline);
}
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
if (el_item->linked == false) {
continue;
}
if (audio_element_msg_set_listener(el_item->el, listener) != ESP_OK) {
ESP_LOGE(TAG, "Error register event with: %s", (char *)audio_element_get_tag(el_item->el));
return ESP_FAIL;
}
}
pipeline->listener = listener;
return ESP_OK;
}
esp_err_t audio_pipeline_remove_listener(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
if (pipeline->listener == NULL) {
ESP_LOGW(TAG, "There are no listener registered");
return ESP_FAIL;
}
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
if (el_item->linked == false) {
continue;
}
if (audio_element_msg_remove_listener(el_item->el, pipeline->listener) != ESP_OK) {
ESP_LOGE(TAG, "Error unregister event with: %s", audio_element_get_tag(el_item->el));
return ESP_FAIL;
}
}
pipeline->listener = NULL;
return ESP_OK;
}
audio_pipeline_handle_t audio_pipeline_init(audio_pipeline_cfg_t *config)
{
audio_pipeline_handle_t pipeline;
bool _success =
(
(pipeline = audio_calloc(1, sizeof(struct audio_pipeline))) &&
(pipeline->lock = mutex_create())
);
AUDIO_MEM_CHECK(TAG, _success, return NULL);
STAILQ_INIT(&pipeline->el_list);
STAILQ_INIT(&pipeline->rb_list);
pipeline->state = AEL_STATE_INIT;
return pipeline;
}
esp_err_t audio_pipeline_deinit(audio_pipeline_handle_t pipeline)
{
audio_pipeline_terminate(pipeline);
audio_pipeline_unlink(pipeline);
mutex_destroy(pipeline->lock);
audio_free(pipeline);
return ESP_OK;
}
esp_err_t audio_pipeline_register(audio_pipeline_handle_t pipeline, audio_element_handle_t el, const char *name)
{
audio_pipeline_unregister(pipeline, el);
audio_element_set_tag(el, name);
audio_element_item_t *el_item = audio_calloc(1, sizeof(audio_element_item_t));
AUDIO_MEM_CHECK(TAG, el_item, return ESP_ERR_NO_MEM);
el_item->el = el;
el_item->linked = false;
STAILQ_INSERT_TAIL(&pipeline->el_list, el_item, next);
return ESP_OK;
}
esp_err_t audio_pipeline_unregister(audio_pipeline_handle_t pipeline, audio_element_handle_t el)
{
audio_element_set_tag(el, NULL);
audio_element_item_t *el_item, *tmp;
STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, tmp) {
if (el_item->el == el) {
STAILQ_REMOVE(&pipeline->el_list, el_item, audio_element_item, next);
audio_free(el_item);
return ESP_OK;
}
}
return ESP_FAIL;
}
esp_err_t audio_pipeline_resume(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
bool wait_first_el = true;
esp_err_t ret = ESP_OK;
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
ESP_LOGD(TAG, "audio_pipeline_resume,linked:%d, state:%d,[%p]", el_item->linked, audio_element_get_state(el_item->el), el_item->el);
if (false == el_item->linked) {
continue;
}
if (wait_first_el) {
ret |= audio_element_resume(el_item->el, 0, portMAX_DELAY);
wait_first_el = false;
} else {
ret |= audio_element_resume(el_item->el, 0, 0);
}
}
return ret;
}
esp_err_t audio_pipeline_pause(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
if (false == el_item->linked) {
continue;
}
ESP_LOGD(TAG, "audio_pipeline_pause [%s] %p", audio_element_get_tag(el_item->el), el_item->el);
audio_element_pause(el_item->el);
}
return ESP_OK;
}
esp_err_t audio_pipeline_run(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
if (pipeline->state != AEL_STATE_INIT) {
ESP_LOGW(TAG, "Pipeline already started");
return ESP_OK;
}
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
ESP_LOGD(TAG, "start el, linked:%d, state:%d,[%p]", el_item->linked, audio_element_get_state(el_item->el), el_item->el);
if (el_item->linked
&& ((AEL_STATE_INIT == audio_element_get_state(el_item->el))
|| (AEL_STATE_STOPPED == audio_element_get_state(el_item->el))
|| (AEL_STATE_FINISHED == audio_element_get_state(el_item->el))
|| (AEL_STATE_ERROR == audio_element_get_state(el_item->el)))) {
audio_element_run(el_item->el);
}
}
AUDIO_MEM_SHOW(TAG);
if (ESP_FAIL == audio_pipeline_resume(pipeline)) {
ESP_LOGE(TAG, "audio_pipeline_resume failed");
audio_pipeline_change_state(pipeline, AEL_STATE_ERROR);
audio_pipeline_terminate(pipeline);
return ESP_FAIL;
} else {
audio_pipeline_change_state(pipeline, AEL_STATE_RUNNING);
}
ESP_LOGI(TAG, "Pipeline started");
return ESP_OK;
}
esp_err_t audio_pipeline_terminate(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
ESP_LOGD(TAG, "Destroy audio_pipeline elements");
audio_pipeline_stop(pipeline);
audio_pipeline_wait_for_stop(pipeline);
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
if (el_item->linked) {
audio_element_terminate(el_item->el);
}
}
return ESP_OK;
}
esp_err_t audio_pipeline_stop(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
ESP_LOGD(TAG, "audio_element_stop");
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
if (el_item->linked) {
audio_element_stop(el_item->el);
}
}
return ESP_OK;
}
esp_err_t audio_pipeline_wait_for_stop(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
ESP_LOGD(TAG, "audio_pipeline_wait_for_stop");
if (pipeline->state != AEL_STATE_RUNNING) {
return ESP_FAIL;
}
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
if (el_item->linked) {
audio_element_wait_for_stop(el_item->el);
audio_element_reset_input_ringbuf(el_item->el);
audio_element_reset_output_ringbuf(el_item->el);
}
}
audio_pipeline_change_state(pipeline, AEL_STATE_INIT);
return ESP_OK;
}
esp_err_t audio_pipeline_link(audio_pipeline_handle_t pipeline, const char *link_tag[], int link_num)
{
int i = 0;
bool first = false, last = false;
ringbuf_handle_t rb = NULL;
ringbuf_item_t *rb_item;
if (pipeline->linked) {
audio_pipeline_unlink(pipeline);
}
for (i = 0; i < link_num; i++) {
audio_element_item_t *item = audio_pipeline_get_el_item_by_tag(pipeline, link_tag[i]);
if (item == NULL) {
ESP_LOGE(TAG, "There is 1 link_tag invalid: %s", link_tag[i]);
return ESP_FAIL;
}
item->linked = true;
audio_element_handle_t el = item->el;
/* Create and Link ringubffer */
first = (i == 0);
last = (i == link_num - 1);
if (last) {
audio_element_set_input_ringbuf(el, rb);
} else {
if (!first) {
audio_element_set_input_ringbuf(el, rb);
}
bool _success = (
(rb_item = audio_calloc(1, sizeof(ringbuf_item_t))) &&
(rb = rb_create(audio_element_get_output_ringbuf_size(el), 1))
);
AUDIO_MEM_CHECK(TAG, _success, {
free(rb_item);
return ESP_ERR_NO_MEM;
});
rb_item->rb = rb;
rb_item->linked = true;
STAILQ_INSERT_TAIL(&pipeline->rb_list, rb_item, next);
audio_element_set_output_ringbuf(el, rb);
ESP_LOGI(TAG, "audio_pipeline_link:%p, %s, %p", el, link_tag[i], rb);
}
}
pipeline->linked = true;
return ESP_OK;
}
esp_err_t audio_pipeline_unlink(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
ringbuf_item_t *rb_item, *tmp;
if (!pipeline->linked) {
return ESP_OK;
}
audio_pipeline_remove_listener(pipeline);
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
if (el_item->linked) {
el_item->linked = false;
audio_element_set_output_ringbuf(el_item->el, NULL);
audio_element_set_input_ringbuf(el_item->el, NULL);
ESP_LOGD(TAG, "audio_pipeline_unlink, %p, %s", el_item->el, audio_element_get_tag(el_item->el));
}
}
STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, tmp) {
STAILQ_REMOVE(&pipeline->rb_list, rb_item, ringbuf_item, next);
rb_destroy(rb_item->rb);
rb_item->linked = false;
audio_free(rb_item);
ESP_LOGD(TAG, "audio_pipeline_unlink, RB, %p,", rb_item->rb);
}
ESP_LOGI(TAG, "audio_pipeline_unlinked");
STAILQ_INIT(&pipeline->rb_list);
pipeline->linked = false;
return ESP_OK;
}
esp_err_t audio_pipeline_register_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...)
{
va_list args;
va_start(args, element_1);
while (element_1) {
audio_pipeline_register_element(pipeline, element_1);
element_1 = va_arg(args, audio_element_handle_t);
}
va_end(args);
return ESP_OK;
}
esp_err_t audio_pipeline_unregister_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...)
{
va_list args;
va_start(args, element_1);
while (element_1) {
audio_pipeline_unregister_element(pipeline, element_1);
element_1 = va_arg(args, audio_element_handle_t);
}
va_end(args);
return ESP_OK;
}
esp_err_t audio_pipeline_link_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...)
{
va_list args;
int idx = 0;
bool first = false;
ringbuf_handle_t rb = NULL;
if (pipeline->linked) {
audio_pipeline_unlink(pipeline);
}
va_start(args, element_1);
while (element_1) {
audio_element_handle_t el = element_1;
audio_element_item_t *el_item = audio_calloc(1, sizeof(audio_element_item_t));
AUDIO_MEM_CHECK(TAG, el_item, return ESP_ERR_NO_MEM);
el_item->el = el;
el_item->linked = true;
STAILQ_INSERT_TAIL(&pipeline->el_list, el_item, next);
idx ++;
first = (idx == 1);
element_1 = va_arg(args, audio_element_handle_t);
if (NULL == element_1) {
audio_element_set_input_ringbuf(el, rb);
} else {
if (!first) {
audio_element_set_input_ringbuf(el, rb);
}
rb = rb_create(audio_element_get_output_ringbuf_size(el), 1);
AUDIO_MEM_CHECK(TAG, rb, return ESP_ERR_NO_MEM);
add_rb_to_audio_pipeline(pipeline, rb);
audio_element_set_output_ringbuf(el, rb);
}
ESP_LOGD(TAG, "element is %p, rb:%p", el, rb);
}
pipeline->linked = true;
va_end(args);
return ESP_OK;
}
esp_err_t audio_pipeline_link_insert(audio_pipeline_handle_t pipeline, bool first, audio_element_handle_t prev, ringbuf_handle_t conect_rb, audio_element_handle_t next)
{
if (first) {
audio_pipeline_register_element(pipeline, prev);
}
ESP_LOGD(TAG, "element is prev:%p, rb:%p, next:%p", prev, conect_rb, next);
audio_pipeline_register_element(pipeline, next);
audio_element_set_output_ringbuf(prev, conect_rb);
audio_element_set_input_ringbuf(next, conect_rb);
add_rb_to_audio_pipeline(pipeline, conect_rb);
pipeline->linked = true;
return ESP_OK;
}
esp_err_t audio_pipeline_listen_more(audio_pipeline_handle_t pipeline, audio_element_handle_t element_1, ...)
{
va_list args;
va_start(args, element_1);
while (element_1) {
audio_element_handle_t el = element_1;
element_1 = va_arg(args, audio_element_handle_t);
QueueHandle_t que = audio_element_get_event_queue(el);
audio_event_iface_msg_t dummy = {0};
while (1) {
if (xQueueReceive(que, &dummy, 0) == pdTRUE) {
ESP_LOGD(TAG, "Listen_more el:%p, que :%p, OK", el, que);
} else {
ESP_LOGD(TAG, "Listen_more el:%p, que :%p, FAIL", el, que);
break;
}
}
}
va_end(args);
return ESP_OK;
}
esp_err_t audio_pipeline_check_items_state(audio_pipeline_handle_t pipeline, audio_element_handle_t el, audio_element_status_t status)
{
audio_element_item_t *item;
int el_cnt = 0;
int el_sta_cnt = 0;
audio_element_item_t *it = audio_pipeline_get_el_item_by_tag(pipeline, audio_element_get_tag(el));
it->el_state = status;
STAILQ_FOREACH(item, &pipeline->el_list, next) {
if (false == item->linked) {
continue;
}
el_cnt ++;
ESP_LOGD(TAG, "pipeline check state,pipeline:%p, el:%p, state:%d, status:%d", pipeline, item->el, item->el_state, status);
if ((AEL_STATUS_NONE != item->el_state) && (status == item->el_state)) {
el_sta_cnt++;
}
}
if (el_cnt && (el_sta_cnt == el_cnt)) {
return ESP_OK;
} else {
return ESP_FAIL;
}
}
esp_err_t audio_pipeline_reset_items_state(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
ESP_LOGD(TAG, "audio_pipeline_reset_items_state");
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
if (el_item->linked) {
el_item->el_state = AEL_STATUS_NONE;
}
}
return ESP_OK;
}
esp_err_t audio_pipeline_reset_ringbuffer(audio_pipeline_handle_t pipeline)
{
audio_element_item_t *el_item;
STAILQ_FOREACH(el_item, &pipeline->el_list, next) {
if (el_item->linked) {
audio_element_reset_input_ringbuf(el_item->el);
audio_element_reset_output_ringbuf(el_item->el);
}
}
return ESP_OK;
}
esp_err_t audio_pipeline_breakup_elements(audio_pipeline_handle_t pipeline, audio_element_handle_t kept_ctx_el)
{
if (pipeline == NULL) {
ESP_LOGE(TAG, "%s have invalid args, %p", __func__, pipeline);
return ESP_ERR_INVALID_ARG;
}
audio_pipeline_remove_listener(pipeline);
audio_element_item_t *el_item, *el_tmp;
ringbuf_item_t *rb_item, *tmp;
bool kept = false;
STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, el_tmp) {
if (!el_item->linked) {
continue;
}
if (kept && el_item->el != kept_ctx_el) {
el_item->linked = false;
audio_element_set_input_ringbuf(el_item->el, NULL);
audio_element_set_output_ringbuf(el_item->el, NULL);
ESP_LOGD(TAG, "%d, el:%p, %s, in_rb:%p, out_rb:%p", __LINE__, el_item->el, audio_element_get_tag(el_item->el),
audio_element_get_input_ringbuf(el_item->el), audio_element_get_output_ringbuf(el_item->el));
} else {
STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, tmp) {
ESP_LOGD(TAG, "%d, el:%p, %s, in_rb:%p, out_rb:%p", __LINE__, el_item->el, audio_element_get_tag(el_item->el),
audio_element_get_input_ringbuf(el_item->el), audio_element_get_output_ringbuf(el_item->el));
if (rb_item->rb == audio_element_get_output_ringbuf(el_item->el)) {
el_item->linked = false;
el_item->kept_ctx = true;
rb_item->kept_ctx = true;
kept = true;
break;
}
rb_item->kept_ctx = true;
}
}
}
STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, tmp) {
ESP_LOGD(TAG, "%d, reset rb:%p kept:%d,linked:%d", __LINE__, rb_item->rb, rb_item->kept_ctx, rb_item->linked );
if (rb_item->kept_ctx == false) {
rb_item->linked = false;
rb_reset(rb_item->rb);
}
}
pipeline->linked = false;
audio_pipeline_change_state(pipeline, AEL_STATE_INIT);
return ESP_OK;
}
esp_err_t audio_pipeline_relink(audio_pipeline_handle_t pipeline, const char *link_tag[], int link_num)
{
if (pipeline == NULL
|| link_tag == NULL) {
ESP_LOGE(TAG, "%s have invalid args, %p, %p", __func__, pipeline, link_tag);
return ESP_ERR_INVALID_ARG;
}
if (pipeline->linked) {
ESP_LOGE(TAG, "%s pipeline is already linked, can't relink", __func__);
return ESP_FAIL;
}
esp_err_t ret = ESP_OK;
audio_element_item_t *el_item, *el_tmp;
ringbuf_item_t *rb_item, *rb_tmp;
ringbuf_handle_t rb = NULL;
bool first = false, last = false;
for (int i = 0; i < link_num; i++) {
audio_element_item_t *src_el_item = audio_pipeline_get_el_item_by_tag(pipeline, link_tag[i]);
if (src_el_item == NULL) {
ESP_LOGE(TAG, "There is link_tag invalid: %s", link_tag[i]);
ret = ESP_FAIL;
goto relink_err;
}
audio_element_handle_t el = NULL;
ringbuf_item_t *cur_rb_item = NULL;
STAILQ_FOREACH_SAFE(el_item, &pipeline->el_list, next, el_tmp) {
ESP_LOGD(TAG, "%d, linked:%d, kept:%d, %s, %p, %s, %p", __LINE__, el_item->linked, el_item->kept_ctx,
audio_element_get_tag(el_item->el), el_item->el, link_tag[i], src_el_item->el);
if ((el_item->linked == false)
&& (src_el_item->el == el_item->el)) {
el = el_item->el;
audio_element_reset_state(el);
break;
}
}
if (el == NULL) {
ESP_LOGE(TAG, "Can't find element, wanted_el:%s", link_tag[i]);
ret = ESP_FAIL;
goto relink_err;
}
src_el_item->linked = true;
STAILQ_FOREACH_SAFE(rb_item, &pipeline->rb_list, next, rb_tmp) {
ESP_LOGD(TAG, "%d, rb:%p kept:%d,linked:%d", __LINE__, rb_item->rb, rb_item->kept_ctx, rb_item->linked );
if (rb_item->linked == false && rb_item->kept_ctx == false) {
cur_rb_item = rb_item;
cur_rb_item->linked = true;
break;
}
if (src_el_item->kept_ctx) {
ringbuf_handle_t tmp_rb = audio_element_get_output_ringbuf(src_el_item->el);
if (rb_item->rb == tmp_rb && rb_item->kept_ctx == true) {
cur_rb_item = rb_item;
cur_rb_item->linked = true;
src_el_item->kept_ctx = false;
ESP_LOGI(TAG, "found kept rb:%p kept:%d,linked:%d, el:%p, name:%s", rb_item->rb, rb_item->kept_ctx,
rb_item->linked, src_el_item->el, audio_element_get_tag(src_el_item->el));
break;
}
}
}
ESP_LOGD(TAG, "%d, el:%p, %s last:%d, rb_item:%p", __LINE__, el, audio_element_get_tag(el_item->el),
last, cur_rb_item);
first = (i == 0);
last = (i == link_num - 1);
if ((last == false) && (cur_rb_item == NULL)) {
ringbuf_handle_t tmp_rb = NULL;
bool _success = (
(cur_rb_item = audio_calloc(1, sizeof(ringbuf_item_t))) &&
(tmp_rb = rb_create(audio_element_get_output_ringbuf_size(el), 1))
);
AUDIO_MEM_CHECK(TAG, _success, {
free(cur_rb_item);
return ESP_ERR_NO_MEM;
});
cur_rb_item->rb = tmp_rb;
cur_rb_item->linked = true;
STAILQ_INSERT_TAIL(&pipeline->rb_list, cur_rb_item, next);
ESP_LOGW(TAG, "create new rb, linked:%d, rb:%p, cur_el:%s", el_item->linked, cur_rb_item->rb, audio_element_get_tag(el_item->el));
}
ESP_LOGD(TAG, "%d, el:%p, %s, rb:%p, first:%d, last:%d", __LINE__, el,
audio_element_get_tag(el), rb, first, last);
if (last) {
audio_element_set_input_ringbuf(el, rb);
} else {
if (!first) {
audio_element_set_input_ringbuf(el, rb);
}
rb = cur_rb_item->rb;
audio_element_set_output_ringbuf(el, rb);
}
}
relink_err:
return ret;
}
|
IoTBits/esp-adf | components/audio_hal/board/audiosom32_carrier_v3.h | <reponame>IoTBits/esp-adf
/*
Website: www.iot-bits.com
Copyright (C) 2016-2018, IoTBits (Author: <NAME>), all right reserved.
E-mail: <EMAIL>
Personal website: www.PratikPanda.com
The code referencing this license is open source software. Redistribution
and use of the code in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistribution of original and modified source code must retain the
above copyright notice, this condition and the following disclaimer.
This software is provided by the copyright holder and contributors "AS IS"
and any warranties related to this software are DISCLAIMED. The copyright
owner or contributors are NOT LIABLE for any damages caused by use of this
software.
*/
#ifndef _AUDIOSOM32_CARRIER_V3_H_
#define _AUDIOSOM32_CARRIER_V3_H_
/* I2C codec GPIOs */
#define IIC_CLK 5
#define IIC_DATA 18
/* I2S codec GPIOs */
#define IIS_SCLK 22
#define IIS_LCLK 21
#define IIS_DSIN 19
#define IIS_DOUT 23
#define IIS_MCLK 0
/* LED GPIO */
#define USER_LED 25
#endif |
IoTBits/esp-adf | components/audio_hal/driver/audiosom32/audiosom32_codec.h | /*
Website: www.iot-bits.com
Copyright (C) 2016-2018, IoTBits (Author: <NAME>), all right reserved.
E-mail: <EMAIL>
Personal website: www.PratikPanda.com
The code referencing this license is open source software. Redistribution
and use of the code in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistribution of original and modified source code must retain the
above copyright notice, this condition and the following disclaimer.
This software is provided by the copyright holder and contributors "AS IS"
and any warranties related to this software are DISCLAIMED. The copyright
owner or contributors are NOT LIABLE for any damages caused by use of this
software.
*/
#ifndef _AUDIOSOM32_CODEC_H_
#define _AUDIOSOM32_CODEC_H_
#include "esp_types.h"
#include "audio_hal.h"
#include "driver/i2c.h"
// AudioSOM32 codec address
#define AS32_CODEC_ADDR 0x0A
#define AS32_CODEC_I2C_NUM 0
// AudioSOM32 codec register addresses
#define AS32_CHIP_ID 0x0000
#define AS32_CHIP_DIG_POWER 0x0002
#define AS32_CHIP_CLK_CTRL 0x0004
#define AS32_CHIP_I2S_CTRL 0x0006
#define AS32_CHIP_SSS_CTRL 0x000A
#define AS32_CHIP_ADCDAC_CTRL 0x000E
#define AS32_CHIP_DAC_VOL 0x0010
#define AS32_CHIP_PAD_STRENGTH 0x0014
#define AS32_CHIP_ANA_ADC_CTRL 0x0020
#define AS32_CHIP_ANA_HP_CTRL 0x0022
#define AS32_CHIP_ANA_CTRL 0x0024
#define AS32_CHIP_LINREG_CTRL 0x0026
#define AS32_CHIP_REF_CTRL 0x0028
#define AS32_CHIP_MIC_CTRL 0x002A
#define AS32_CHIP_LINE_OUT_CTRL 0x002C
#define AS32_CHIP_LINE_OUT_VOL 0x002E
#define AS32_CHIP_ANA_POWER 0x0030
#define AS32_CHIP_PLL_CTRL 0x0032
#define AS32_CHIP_CLK_TOP_CTRL 0x0034
#define AS32_SHIP_ANA_STATUS 0x0036
#define AS32_CHIP_ANA_TEST1 0x0038
#define AS32_CHIP_ANA_TEST2 0x003A
#define AS32_CHIP_SHORT_CTRL 0x003C
#define AS32_DAP_CONTROL 0x0100
#define AS32_DAP_PEQ 0x0102
#define AS32_DAP_BASS_ENHANCE 0x0104
#define AS32_DAP_BASS_ENHANCE_CTRL 0x0106
#define AS32_DAP_AUDIO_EQ 0x0108
#define AS32_DAP_SGTL_SURROUND 0x010A
#define AS32_DAP_FILTER_COEF_ACCESS 0x010C
#define AS32_DAP_COEF_WR_B0_MSB 0x010E
#define AS32_DAP_COEF_WR_B0_LSB 0x0110
#define AS32_DAP_AUDIO_EQ_BASS_BAND0 0x0116
#define AS32_DAP_AUDIO_EQ_BAND1 0x0118
#define AS32_DAP_AUDIO_EQ_BAND2 0x011A
#define AS32_DAP_AUDIO_EQ_BAND3 0x011C
#define AS32_DAP_AUDIO_EQ_TREBLE_BAND4 0x011E
#define AS32_DAP_MAIN_CHAN 0x0120
#define AS32_DAP_MIX_CHAN 0x0122
#define AS32_DAP_AVC_CTRL 0x0124
#define AS32_DAP_AVC_THRESHOLD 0x0126
#define AS32_DAP_AVC_ATTACK 0x0128
#define AS32_DAP_AVC_DECAY 0x012A
#define AS32_DAP_COEF_WR_B1_MSB 0x012C
#define AS32_DAP_COEF_WR_B1_LSB 0x012E
#define AS32_DAP_COEF_WR_B2_MSB 0x0130
#define AS32_DAP_COEF_WR_B2_LSB 0x0132
#define AS32_DAP_COEF_WR_A1_MSB 0x0134
#define AS32_DAP_COEF_WR_A1_LSB 0x0136
#define AS32_DAP_COEF_WR_A2_MSB 0x0138
#define AS32_DAP_COEF_WR_A2_LSB 0x013A
// Interface types for audiosom32
// Changing ADC or DAC has effect on all assoc peripherals
// Tuning HP, LOUT, etc achieves individual control over that input/output
typedef enum{
AS32_IFACE_MIN = -1,
AS32_IFACE_ADC = 0,
AS32_IFACE_MIC,
AS32_IFACE_DAC,
AS32_IFACE_HP,
AS32_IFACE_LOUT,
AS32_IFACE_MAX
} as32_iface_t;
typedef enum{
AS32_BLOCK_ADC = 0,
AS32_BLOCK_DAC,
AS32_BLOCK_DAP,
AS32_BLOCK_DIN,
AS32_BLOCK_DOUT
} as32_block_t;
typedef enum{
AS32_MODE_MIN = -1,
AS32_MODE_SLAVE = 0,
AS32_MODE_MASTER,
AS32_MODE_MAX
} as32_mode_t;
// I2S data format
typedef enum {
AS32_I2S_MIN = -1,
AS32_I2S_NORMAL = 0,
AS32_I2S_LEFT = 1,
AS32_I2S_RIGHT = 2,
AS32_I2S_DSP = 3,
AS32_I2S_MAX
} as32_i2s_fmt_t;
// I2S bits per sample
typedef enum {
BIT_LENGTH_MIN = -1,
BIT_LENGTH_16BITS = 0x3,
BIT_LENGTH_20BITS = 0x2,
BIT_LENGTH_24BITS = 0x1,
BIT_LENGTH_32BITS = 0x0,
BIT_LENGTH_MAX
} as32_bits_length_t;
typedef enum {
D2SE_PGA_GAIN_MIN = -1,
D2SE_PGA_GAIN_DIS = 0,
D2SE_PGA_GAIN_EN = 1,
D2SE_PGA_GAIN_MAX =2,
} as32_pga_t;
// Input sources for ADC
typedef enum {
ADC_INPUT_MIN = -1,
ADC_INPUT_MIC = 0x0,
ADC_INPUT_LINEIN = 0x1,
ADC_INPUT_MAX,
} as32_adc_input_t;
// Output channels for the DAC
typedef enum {
DAC_OUTPUT_MIN = -1,
DAC_OUTPUT_HP = 0x1,
DAC_OUTPUT_LINEOUT = 0x2,
DAC_OUTPUT_ALL = 0x3,
DAC_OUTPUT_MAX,
} as32_dac_output_t;
typedef enum {
MIC_GAIN_MIN = -1,
MIC_GAIN_0DB = 0x0,
MIC_GAIN_20DB = 0x1,
MIC_GAIN_30DB = 0x2,
MIC_GAIN_40DB = 0x3,
MIC_GAIN_MAX,
} as32_mic_gain_t;
typedef enum {
ES_MODULE_MIN = -1,
ES_MODULE_ADC = 0x01,
ES_MODULE_DAC = 0x02,
ES_MODULE_ADC_DAC = 0x03,
ES_MODULE_LINE = 0x04,
ES_MODULE_MAX
} as32_module_t;
/*
typedef enum {
MUTE_MIN = -1,
MUTE_ADC = 0x0,
MUTE_HP = 0x4,
MUTE_LO = 0x8,
MUTE_MAX
} as32_block_t;
*/
typedef enum {
BLOCK_MIN = -1,
BLOCK_MIC = 0,
BLOCK_LINEIN = 1,
BLOCK_ADC = 2,
BLOCK_DAP = 3,
BLOCK_DAC = 4,
BLOCK_HP = 5,
BLOCK_LINEOUT = 6,
BLOCK_MAX
} as32_block_t;
typedef enum {
ES_MODE_MIN = -1,
ES_MODE_SLAVE = 0x00,
ES_MODE_MASTER = 0x01,
ES_MODE_MAX,
} as32_mode_t;
typedef enum {
ES_I2S_MIN = -1,
ES_I2S_NORMAL = 0,
ES_I2S_LEFT = 1,
ES_I2S_RIGHT = 2,
ES_I2S_DSP = 3,
ES_I2S_MAX
} as32_i2s_fmt_t;
typedef struct {
es_sclk_div_t sclk_div; /*!< bits clock divide */
es_lclk_div_t lclk_div; /*!< WS clock divide */
} as32_i2s_clock_t;
/**
* @brief Initialize audioSOM32 codec chip
* Sets up the codec as configured in argument
* Physical interfaces are set up here
*
* @param cfg configuration of audiosom32 codec
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_init(audio_hal_codec_config_t *cfg);
/**
* @brief Deinitialize audioSOM32 codec chip
* Resets the codec config and returns it to POR defaults
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_codec_deinit(void);
/**
* @brief Configure audiosom32 I2S format
* Config I2S format related registers in codec
*
* @param cfg: audiosom32 I2S format
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_config_fmt(as32_i2s_fmt_t cfg);
/**
* @brief Configure I2s clock in master mode
* Configure all ESP32 timed signals based on settings
*
* @param cfg: set bits clock and WS clock
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_i2s_config_clock(es_i2s_clock_t cfg);
/**
* @brief Configure audiosom32 data sample bits
* Set sample length in the codec, applies to all DAC, ADC, etc
* @param bit_per_sample: bit number of per sample
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_set_bits_per_sample(es_bits_length_t bit_per_sample);
/**
* @brief Start up as32 codec chip modules
* Power on and activate codec modules based on mode input
*
* @param mode: set ADC or DAC or both
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_start(es_module_t mode);
/**
* @brief Stop audiosom32 codec chip
* Power off modules based on input
*
* @param mode: set ADC or DAC or both
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_stop(es_module_t mode);
/**
* @brief Set voice volume
* Set the ADC volume levels
*
* @param volume: voice volume (0~100)
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_set_voice_volume(int volume);
/**
* @brief Get voice volume, 0-100
* Return the ADC volume
*
* @param[out] *volume: voice volume (0~100)
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_get_voice_volume(int *volume);
/**
* @brief Configure audiosom32 DAC mute mode
* Mute the codec ADCs
*
* @param enable enable(1) or disable(0)
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_set_voice_mute(int enable);
/**
* @brief Get audiosom32 DAC mute status
* Return codec ADC mute status
*
* @return
* - -1 Parameter error
* - 0 voice mute disable
* - 1 voice mute enable
*/
esp_err_t as32_get_voice_mute(void);
/**
* @brief Set audiosom32 mic gain
* Set MIC gain in dB at codec
*
* @param gain db of mic gain
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_set_mic_gain(as32_mic_gain_t gain);
/**
* @brief Set audiosom32 ADC input mode
* Configure the input signal source for ADC
*
* @param input adc input mode
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_config_adc_input(as32_adc_input_t input);
/**
* @brief Set audiosom32 DAC output mode
* Configure the DAC input source
*
* @param output dac output mode
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_config_dac_output(as32_dac_output_t output);
/**
* @brief Configure audiosom32 codec mode and I2S interface
*
* @param mode codec mode
* @param iface I2S config
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface);
/**
* @brief Control audiosom32 codec chip
*
* @param mode codec mode
* @param ctrl_state start or stop decode or encode progress
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state);
/**
* @brief Set audiosom32 PA power
*
* @param enable true for enable PA power, false for disable PA power
*
* @return
* - void
*/
void as32_pa_power(bool enable);
#endif |
IoTBits/esp-adf | components/audio_hal/driver/audiosom32/audiosom32_codec.c | /*
Website: www.iot-bits.com
Copyright (C) 2016-2018, IoTBits (Author: <NAME>), all right reserved.
E-mail: <EMAIL>
Personal website: www.PratikPanda.com
The code referencing this license is open source software. Redistribution
and use of the code in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistribution of original and modified source code must retain the
above copyright notice, this condition and the following disclaimer.
This software is provided by the copyright holder and contributors "AS IS"
and any warranties related to this software are DISCLAIMED. The copyright
owner or contributors are NOT LIABLE for any damages caused by use of this
software.
*/
#include <string.h>
#include "esp_log.h"
#include "driver/i2c.h"
#include "audiosom32_codec.h"
#include "board.h"
static const char *AS_TAG = "AUDIOSOM_CODEC";
#define ES_ASSERT(a, format, b, ...) \
if ((a) != 0) { \
ESP_LOGE(AS_TAG, format, ##__VA_ARGS__); \
return b;\
}
// SDA is fixed to IO18
// SCL is fixed at IO5
// Pull-up enabled, regardless of external PU
// Clock speed fixed to 100kHz
static i2c_config_t as32_i2c_conf = {
.mode = I2C_MODE_MASTER;
.sda_io_num = IIC_DATA;
.sda_pullup_en = GPIO_PULLUP_ENABLE;
.scl_io_num = IIC_CLK;
.scl_pullup_en = GPIO_PULLUP_ENABLE;
.master.clk_speed = 100000;
};
/* Write operation:
• Start condition
• Device address with the R/W bit cleared to indicate write
• Send two bytes for the 16 bit register address (most significant byte first)
• Send two bytes for the 16 bits of data to be written to the register (most significant byte first)
• Stop condition
*/
esp_err_t as32_write_reg (i2c_port_t i2c_num, uint16_t reg_addr, uint16_t reg_val)
{
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
uint8_t dwr[4];
// Start condition
i2c_master_start(cmd);
// Address + Write bit
i2c_master_write_byte(cmd, (AUDIOBIT_I2C_ADDR<<1)|WRITE_BIT, ACK_CHECK_EN);
// MSB for reg address
//i2c_master_write_byte(cmd, (reg_addr>>8)&0xFF, ACK_CHECK_EN);
dwr[0] = (reg_addr>>8)&0xFF;
// LSB for reg address
//i2c_master_write_byte(cmd, (reg_addr&0xFF), ACK_CHECK_EN);
dwr[1] = (reg_addr&0xFF);
// MSB for reg data
//i2c_master_write_byte(cmd, (reg_val>>8)&0xFF, ACK_CHECK_EN);
dwr[2] = (reg_val>>8)&0xFF;
// LSB for reg data
//i2c_master_write_byte(cmd, (reg_val&0xFF), ACK_CHECK_EN);
dwr[3] = (reg_val&0xFF);
i2c_master_write(cmd, dwr, 4, ACK_CHECK_EN);
i2c_master_stop(cmd);
// Execute and return status
esp_err_t ret = i2c_master_cmd_begin(i2c_num, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
return ret;
}
/* Read operation:
• Start condition
• Device address with the R/W bit cleared to indicate write
• Send two bytes for the 16 bit register address (most significant byte first)
• Stop Condition followed by start condition (or a single restart condition)
• Device address with the R/W bit set to indicate read
• Read two bytes from the addressed register (most significant byte first)
• Stop condition
*/
esp_err_t as32_read_reg (i2c_port_t i2c_num, uint16_t reg_addr, uint16_t *reg_val)
{
uint8_t *byte_val = reg_val; // This will cause warning, please ignore
esp_err_t ret;
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
// Start condition
i2c_master_start(cmd);
// Address + Write bit
i2c_master_write_byte(cmd, (AUDIOBIT_I2C_ADDR<<1)|WRITE_BIT, ACK_CHECK_EN);
// MSB for reg address
i2c_master_write_byte(cmd, (reg_addr>>8)&0xFF, ACK_CHECK_EN);
// LSB for reg address
i2c_master_write_byte(cmd, (reg_addr&0xFF), ACK_CHECK_EN);
// Restart (stop + start)
i2c_master_start(cmd);
// Address + read
i2c_master_write_byte(cmd, (AUDIOBIT_I2C_ADDR<<1)|READ_BIT, ACK_CHECK_EN);
// MSB for reg data
i2c_master_read(cmd, byte_val + 1, 1, ACK_VAL);
// LSB for reg data
i2c_master_read_byte(cmd, byte_val, NACK_VAL);
i2c_master_stop(cmd);
// Execute and return status, should return 0
ret = i2c_master_cmd_begin(i2c_num, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
return ret;
}
esp_err_t as32_write_reg_mask (i2c_port_t i2c_num, uint16_t reg_addr, uint16_t mask, uint16_t val)
{
uint16_t read_val;
// Read the concerned register
if (as32_read_reg (i2c_num, reg_addr, &read_val) != ESP_OK)
return ESP_FAIL;
read_val &= ~mask;
read_val |= val;
if (as32_write_reg (i2c_num, reg_addr, read_val) != ESP_OK)
return ESP_FAIL;
}
/**
* @brief i2c master initialization
*/
void as32_codec_i2c_init()
{
int res, i2c_master_port = AS32_CODEC_I2C_NUM;
i2c_param_config(AS32_CODEC_I2C_NUM, &as32_i2c_conf);
i2c_driver_install(AS32_CODEC_I2C_NUM, as32_i2c_conf.mode, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
}
/**
* @brief Configure ADC and DAC volume.
*
* @param mode: set ADC or DAC or both
* @param volume: 0 to 100, -1 sets AVC
* @param dot: dot parameter is ignored
* @return
* - (-1) Parameter error
* - (0) Success
*/
static int as32_set_volume(as32_iface_t iface, int volume)
{
if (volume < 0 || volume > 100)
{
ESP_LOGW(AS_TAG, "Warning: Volume out of bounds, clipped!\n");
if (volume < 0)
volume = 0;
if (volume > 100)
volume = 100;
}
switch (iface)
{
case AS32_IFACE_ADC:
// Change ADC volume
break;
case AS32_IFACE_MIC:
// Change MIC input volume
break;
case AS32_IFACE_DAC:
// Change DAC volume
break;
case AS32_IFACE_HP:
// Change HP volume
break;
case AS32_IFACE_LOUT:
// Change LOUT volume
break;
default:
return -1;
}
}
/**
* @brief Power Management
*
* @param mod: if ES_POWER_CHIP, the whole chip including ADC and DAC is enabled
* @param enable: false to disable true to enable
*
* @return
* - (-1) Error
* - (0) Success
*/
int as32_power_control(as32_block_t block, bool en)
{
if (en)
{
// Enable ORed blocks
}
else
{
// Disable ORed blocks
}
}
/**
* @brief Config I2s clock in MSATER mode
*
* @param cfg.sclkDiv: generate SCLK by dividing MCLK in MSATER mode
* @param cfg.lclkDiv: generate LCLK by dividing MCLK in MSATER mode
*
* @return
* - (-1) Error
* - (0) Success
*/
int as32_i2s_config_clock(as32_i2s_clock_t cfg)
{
// ????
}
/**
* @brief Initialize audioSOM32 codec chip
* Sets up the codec as configured in argument
* Physical interfaces are set up here
*
* @param cfg configuration of audiosom32 codec
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_init(audio_hal_codec_config_t *cfg)
{
}
/**
* @brief Configure audiosom32 I2S format
* Config I2S format related registers in codec
*
* @param cfg: audiosom32 I2S format
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_config_fmt(es_i2s_fmt_t cfg);
{
}
/**
* @brief Set voice volume (0-100)
* Set the ADC volume levels
*
* @param volume: voice volume (0~100)
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_set_volume(as32_block_t block, int volume)
{
}
/**
* @brief Get voice volume, 0-100
* Return the ADC volume
*
* @param[out] *volume: voice volume (0~100)
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t as32_get_volume(as32_block_t block, int *volume)
{
}
/**
* @brief Configure ES8388 data sample bits
*
* @param mode: set ADC or DAC or all
* @param bitPerSample: see BitsLength
*
* @return
* - (-1) Parameter error
* - (0) Success
*/
esp_err_t as32_set_bits_per_sample(as32_bits_length_t bits_length)
{
return as32_write_reg_mask (AS32_CODEC_I2C_NUM, AS32_CHIP_I2S_CTRL, 0x3<<4, bits_length);
}
/**
* @brief Configure audiosom32 DAC mute mode
* Mute the codec DACs
*
* @param enable enable(1) or disable(0)
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_set_mute(as32_mute_t mute)
{
esp_err_t err;
if (mute & (1<<MUTE_ADC))
{
// Mute ADC
err = as32_write_reg_mask (AS32_CODEC_I2C_NUM, AS32_CHIP_ANA_CTRL, (1<<MUTE_ADC), (1<<MUTE_ADC));
if (err != ESP_OK)
return ESP_FAIL;
}
else if (mute & (1<<MUTE_ADC))
{
// Mute the HP
err = as32_write_reg_mask (AS32_CODEC_I2C_NUM, AS32_CHIP_ANA_CTRL, (1<<MUTE_HP), (1<<MUTE_HP));
if (err != ESP_OK)
return ESP_FAIL;
}
else if (mute & (1<<MUTE_LO))
{
// Mute LO
err = as32_write_reg_mask (AS32_CODEC_I2C_NUM, AS32_CHIP_ANA_CTRL, (1<<MUTE_LO), (1<<MUTE_LO));
if (err != ESP_OK)
return ESP_FAIL;
}
else
{
return ESP_FAIL;
}
return ESP_OK;
}
/**
* @brief Get audiosom32 DAC mute status
* Return codec ADC mute status
*
* @return
* - -1 Parameter error
* - 0 voice mute disable
* - 1 voice mute enable
*/
esp_err_t as32_get_mute(as32_mute_t *mute)
{
uint16_t read_val;
if (as32_read_reg (AS32_CODEC_I2C_NUM, AS32_CHIP_ANA_CTRL, &read_val) != ESP_OK)
return ESP_FAIL;
*mute = read_val & ((1<<MUTE_ADC) | (1<<MUTE_HP) | (1<<MUTE_LO));
return ESP_OK;
}
/**
* @brief Set audiosom32 DAC output mode
* Configure the DAC input source
*
* @param output dac output mode
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_config_dac_output(as32_dac_output_t output)
{
switch (output)
{
case DAC_OUTPUT_HP:
return as32_write_reg_mask (AS32_CODEC_I2C_NUM, AS32_CHIP_ANA_CTRL, 0x1 << 6, 0);
break;
case DAC_OUTPUT_LINEOUT:
// Always connected to Line Out
return ESP_OK;
break;
case DAC_OUTPUT_ALL:
return as32_write_reg_mask (AS32_CODEC_I2C_NUM, AS32_CHIP_ANA_CTRL, 0x1 << 6, 0);
break;
default:
return ESP_FAIL;
break;
}
}
/**
* @brief Set audiosom32 ADC input mode
* Configure the input signal source for ADC
*
* @param input adc input mode
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_config_adc_input(as32_adc_input_t input)
{
return as32_write_reg_mask (AS32_CODEC_I2C_NUM, AS32_CHIP_ANA_CTRL, 0x1 << 2, input << 2);
}
/**
* @brief Set audiosom32 mic gain
* Set MIC gain in dB at codec
*
* @param gain db of mic gain
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_set_mic_gain(as32_mic_gain_t gain)
{
// Write 0x002A, bits 1:0
return as32_write_reg_mask (AS32_CODEC_I2C_NUM, AS32_CHIP_MIC_CTRL, 0x0003, gain);
}
/**
* @brief Control audiosom32 codec chip
*
* @param mode codec mode
* @param ctrl_state start or stop decode or encode progress
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state)
{
}
/**
* @brief Configure audiosom32 codec mode and I2S interface
*
* @param mode codec mode
* @param iface I2S config
*
* @return
* - ESP_FAIL Parameter error
* - ESP_OK Success
*/
esp_err_t as32_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface)
{
}
/**
* @brief Set audiosom32 PA power
*
* @param enable true for enable PA power, false for disable PA power
*
* @return
* - void
*/
void as32_pa_power(bool enable)
{
}
/*
static i2s_config_t as32_i2s_config = {
.mode = I2S_MODE_MASTER | I2S_MODE_TX, // Only TX
.sample_rate = AUDIOBIT_SAMPLERATE, // Default: 48kHz
.bits_per_sample = AUDIOBIT_BITSPERSAMPLE, //16-bit per channel
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, //2-channels
.communication_format = I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB,
.dma_buf_count = 6,
.dma_buf_len = 512, //
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1 //Interrupt level 1
};
static i2s_pin_config_t as32_i2s_pin_config = {
.bck_io_num = AUDIOBIT_BCK,
.ws_io_num = AUDIOBIT_LRCLK,
.data_out_num = AUDIOBIT_DOUT,
.data_in_num = AUDIOBIT_DIN //Not used
};
*/
|
KevinLinGit/incubator-doris | be/src/olap/column_data.h | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#ifndef DORIS_BE_SRC_OLAP_COLUMN_FILE_COLUMN_DATA_H
#define DORIS_BE_SRC_OLAP_COLUMN_FILE_COLUMN_DATA_H
#include <string>
#include <string>
#include "gen_cpp/olap_file.pb.h"
#include "olap/column_predicate.h"
#include "olap/delete_handler.h"
#include "olap/olap_common.h"
#include "olap/olap_cond.h"
#include "olap/segment_group.h"
#include "olap/row_block.h"
#include "olap/row_cursor.h"
#include "util/runtime_profile.h"
namespace doris {
class OLAPTable;
class SegmentReader;
// This class is column data reader. this class will be used in two case.
class ColumnData {
public:
static ColumnData* create(SegmentGroup* segment_group);
explicit ColumnData(SegmentGroup* segment_group);
~ColumnData();
// 为了与之前兼容, 暴露部分index的接口
Version version() const {
return _segment_group->version();
}
VersionHash version_hash() const {
return _segment_group->version_hash();
}
bool delete_flag() const {
return _segment_group->delete_flag();
}
uint32_t num_segments() const {
return _segment_group->num_segments();
}
// 查询数据文件类型
DataFileType data_file_type() {
return _data_file_type;
}
OLAPStatus init();
OLAPStatus prepare_block_read(
const RowCursor* start_key, bool find_start_key,
const RowCursor* end_key, bool find_end_key,
RowBlock** first_block);
OLAPStatus get_next_block(RowBlock** row_block);
void set_read_params(
const std::vector<uint32_t>& return_columns,
const std::vector<uint32_t>& seek_columns,
const std::set<uint32_t>& load_bf_columns,
const Conditions& conditions,
const std::vector<ColumnPredicate*>& col_predicates,
bool is_using_cache,
RuntimeState* runtime_state);
OLAPStatus get_first_row_block(RowBlock** row_block);
OLAPStatus get_next_row_block(RowBlock** row_block);
// Only used to binary search in full-key find row
const RowCursor* seek_and_get_current_row(const RowBlockPosition& position);
void set_stats(OlapReaderStatistics* stats) {
_stats = stats;
}
void set_delete_handler(const DeleteHandler& delete_handler) {
_delete_handler = delete_handler;
}
void set_delete_status(const DelCondSatisfied delete_status) {
_delete_status = delete_status;
}
// 开放接口查询_eof,让外界知道数据读取是否正常终止
// 因为这个函数被频繁访问, 从性能考虑, 放在基类而不是虚函数
bool eof() { return _eof; }
void set_eof(bool eof) { _eof = eof; }
bool* eof_ptr() { return &_eof; }
bool empty() const { return _segment_group->empty(); }
bool zero_num_rows() const { return _segment_group->zero_num_rows(); }
bool delta_pruning_filter();
int delete_pruning_filter();
uint64_t get_filted_rows();
SegmentGroup* segment_group() const { return _segment_group; }
void set_segment_group(SegmentGroup* segment_group) { _segment_group = segment_group; }
int64_t num_rows() const { return _segment_group->num_rows(); }
const std::vector<uint32_t>& seek_columns() const { return _seek_columns; }
private:
DISALLOW_COPY_AND_ASSIGN(ColumnData);
// To compatable with schmea change read, use this function to init column data
// for schema change read. Only called in get_first_row_block
OLAPStatus _schema_change_init();
// Try to seek to 'key'. If this funciton returned with OLAP_SUCCESS, current_row()
// point to the first row meet the requirement.
// If there is no such row, OLAP_ERR_DATA_EOF will return.
// If error happend, other code will return
OLAPStatus _seek_to_row(const RowCursor& key, bool find_key, bool is_end_key);
// seek to block_pos without load that block, caller must call _get_block()
// to load _read_block with data. If without_filter is false, this will seek to
// other block. Because the seeked block may be filtered by condition or delete.
OLAPStatus _seek_to_block(const RowBlockPosition &block_pos, bool without_filter);
OLAPStatus _find_position_by_short_key(
const RowCursor& key, bool find_last_key, RowBlockPosition *position);
OLAPStatus _find_position_by_full_key(
const RowCursor& key, bool find_last_key, RowBlockPosition *position);
// Used in _seek_to_row, this function will goto next row that vaild for this
// ColumnData
OLAPStatus _next_row(const RowCursor** row, bool without_filter);
// get block from reader, just read vector batch from _current_segment.
// The read batch return by got_batch.
OLAPStatus _get_block_from_reader(
VectorizedRowBatch** got_batch, bool without_filter, int rows_read);
// get block from segment reader. If this function returns OLAP_SUCCESS
OLAPStatus _get_block(bool without_filter, int rows_read = 0);
const RowCursor* _current_row() {
_read_block->get_row(_read_block->pos(), &_cursor);
return &_cursor;
}
private:
DataFileType _data_file_type;
SegmentGroup* _segment_group;
// 当到达文件末尾或者到达end key时设置此标志
bool _eof;
const Conditions* _conditions;
const std::vector<ColumnPredicate*>* _col_predicates;
DeleteHandler _delete_handler;
DelCondSatisfied _delete_status;
RuntimeState* _runtime_state;
OlapReaderStatistics _owned_stats;
OlapReaderStatistics* _stats = &_owned_stats;
OLAPTable* _table;
// whether in normal read, use return columns to load block
bool _is_normal_read = false;
bool _end_key_is_set = false;
bool _is_using_cache;
bool _segment_eof = false;
bool _need_eval_predicates = false;
std::vector<uint32_t> _return_columns;
std::vector<uint32_t> _seek_columns;
std::set<uint32_t> _load_bf_columns;
SegmentReader* _segment_reader;
std::unique_ptr<VectorizedRowBatch> _seek_vector_batch;
std::unique_ptr<VectorizedRowBatch> _read_vector_batch;
std::unique_ptr<RowBlock> _read_block = nullptr;
RowCursor _cursor;
RowCursor _short_key_cursor;
// Record when last key is found
uint32_t _current_block = 0;
uint32_t _current_segment;
uint32_t _next_block;
uint32_t _end_segment;
uint32_t _end_block;
int64_t _end_row_index = 0;
size_t _num_rows_per_block;
};
class ColumnDataComparator {
public:
ColumnDataComparator(
RowBlockPosition position,
ColumnData* olap_data,
const SegmentGroup* segment_group)
: _start_block_position(position),
_olap_data(olap_data),
_segment_group(segment_group) {}
~ColumnDataComparator() {}
// less comparator function
bool operator()(const iterator_offset_t& index, const RowCursor& key) const {
return _compare(index, key, COMPARATOR_LESS);
}
// larger comparator function
bool operator()(const RowCursor& key, const iterator_offset_t& index) const {
return _compare(index, key, COMPARATOR_LARGER);
}
private:
bool _compare(
const iterator_offset_t& index,
const RowCursor& key,
ComparatorEnum comparator_enum) const {
OLAPStatus res = OLAP_SUCCESS;
RowBlockPosition position = _start_block_position;
if (OLAP_SUCCESS != (res = _segment_group->advance_row_block(index, &position))) {
LOG(WARNING) << "fail to advance row block. res=" << res;
throw ComparatorException();
}
const RowCursor* helper_cursor = _olap_data->seek_and_get_current_row(position);
if (helper_cursor == nullptr) {
LOG(WARNING) << "fail to seek and get current row.";
throw ComparatorException();
}
if (COMPARATOR_LESS == comparator_enum) {
return helper_cursor->cmp(key) < 0;
} else {
return helper_cursor->cmp(key) > 0;
}
}
const RowBlockPosition _start_block_position;
ColumnData* _olap_data;
const SegmentGroup* _segment_group;
};
} // namespace doris
#endif // DORIS_BE_SRC_OLAP_COLUMN_FILE_COLUMN_DATA_H
|
maxymania/fantastic-octo-dollop | src/lwstack/iif.h | /*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include "pipeline.h"
/*
* iif.h:
* IP Input Filter
*/
struct IPM4 {
uint32be_t addr;
uint32be_t mask;
struct IPM4* next;
};
struct IPM6 {
uint64_t addr[2];
uint64_t mask[2];
struct IPM6* next;
};
struct IPM {
struct IPM4 *ip4;
struct IPM6 *ip6;
};
struct IPAll {
struct IPM *src;
struct IPM *dest;
};
/* args must be `struct IPAll' */
proc_result_t iif_input(odp_packet_t pkt,void* args);
|
maxymania/fantastic-octo-dollop | src/lwstack/pipeline.h | /*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include <odp.h>
/*
* pipeline.h:
* Pipeline specific defs.
*/
typedef enum {
NA_FORGET, /* Drop, but do not free! */
NA_DROP, /* Drop packet and free it! */
NA_CONTINUE, /* Continue to the next element in the chain! */
} next_action_t;
typedef struct{
odp_packet_t packet_handle;
next_action_t next_action;
} proc_result_t;
typedef proc_result_t (*process_function_t)(odp_packet_t pkt,void* args);
|
maxymania/fantastic-octo-dollop | src/prog/odp_prog.c | <reponame>maxymania/fantastic-octo-dollop
/*
Copyright (C) 2016 <NAME>
This software is provided 'as-is', without any express or implied warranty.
This license and the above notice may not be removed or altered from any
source file and must appear in every source file that contains any substantial
part of this source file. You may use this software, or code extracted from it,
as desired.
*/
#include <odp.h>
int main(int argc, char *argv[]){
odp_init_global(NULL, NULL);
odp_init_local(ODP_THREAD_CONTROL);
return 0;
}
|
maxymania/fantastic-octo-dollop | src/lwstack/pkt_info.c | <gh_stars>0
/*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "pkt_info.h"
//#include <odp/helper/tcp.h>
#include <odp/helper/ip.h>
typedef struct{ uint64_t d[2]; } ipv6addr;
typedef struct{ uint16be_t src,dest; } ports;
proc_result_t pktinf_input(odp_packet_t pkt,void* args) ODP_HOT_CODE;
proc_result_t pktinf_input(odp_packet_t pkt,void* args){
proc_result_t result;
struct pkt_info *info = args;
result.packet_handle = pkt;
result.next_action = NA_CONTINUE;
if(odp_packet_has_ipv4(pkt)){
odph_ipv4hdr_t* hdr = odp_packet_l3_ptr(pkt,NULL);
*((uint32be_t*)info->src_ip) = hdr->src_addr;
*((uint32be_t*)info->dst_ip) = hdr->dst_addr;
}else if(odp_packet_has_ipv6(pkt)){
odph_ipv6hdr_t* hdr = odp_packet_l3_ptr(pkt,NULL);
*((ipv6addr*)info->src_ip) = *((ipv6addr*)hdr->src_addr);
*((ipv6addr*)info->dst_ip) = *((ipv6addr*)hdr->dst_addr);
}
if(odp_packet_has_tcp(pkt)||odp_packet_has_udp(pkt)||odp_packet_has_sctp(pkt)){
ports p = *((ports*)odp_packet_l4_ptr(pkt,NULL));
info->src_port = p.src;
info->dst_port = p.dest;
}
return result;
}
|
maxymania/fantastic-octo-dollop | src/lwstack/portif.c | /*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "portif.h"
#include "pkt_info.h"
static int portif_filter(uint16be_t port,struct PortMatch* match) ODP_HOT_CODE;
proc_result_t portif_input(odp_packet_t pkt,void* args) ODP_HOT_CODE;
static int portif_filter(uint16be_t port,struct PortMatch* match){
struct PortRange* range = match->range;
uint16be_t* list = match->list;
uint16_t i = 0,n = match->listLen;
if(range){
i = odp_be_to_cpu_16(port);
do{
if((i>=range->start) && (i<=range->end)) /* Found a range! */
return 1;
}while(range = range->next);
return 0;
}
for(;i<n;++i){
if(list[i]==port)return 1;
}
return 0;
}
proc_result_t portif_input(odp_packet_t pkt,void* args){
proc_result_t result;
struct pkt_info* info = odp_packet_user_area(pkt);
struct PortAll* filter = args;
result.packet_handle = pkt;
result.next_action = NA_DROP;
if(!odp_likely(odp_packet_has_tcp(pkt)||odp_packet_has_udp(pkt)||odp_packet_has_sctp(pkt) ))
return result;
if(portif_filter(info->src_port,filter->src)&&
portif_filter(info->dst_port,filter->dst))
result.next_action = NA_CONTINUE;
return result;
}
|
maxymania/fantastic-octo-dollop | src/lwstack/iif.c | <reponame>maxymania/fantastic-octo-dollop
/*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "iif.h"
#include "pkt_info.h"
struct ip6i {
uint64_t p[2];
};
static int iif_v4(struct pkt_info* info,struct IPM *src,struct IPM *dest) ODP_HOT_CODE;
static int iif_v6(struct pkt_info* info,struct IPM *src,struct IPM *dest) ODP_HOT_CODE;
proc_result_t iif_input(odp_packet_t pkt,void* args) ODP_HOT_CODE;
static int iif_v4(struct pkt_info* info,struct IPM *src,struct IPM *dest) {
struct IPM4 *f;
uint32be_t ip;
ip = *((uint32be_t*)info->src_ip);
if(odp_likely(src!=NULL)){
f = src->ip4;
while(f){
/* we assume a long linear search! */
if(odp_unlikely((f->mask&ip)==f->addr))
goto SRC_OK;
f=f->next;
}
return 0;
}
SRC_OK:
ip = *((uint32be_t*)info->dst_ip);
if(odp_likely(dest!=NULL)){
f = dest->ip4;
while(f){
/* we assume a long linear search! */
if(odp_unlikely((f->mask&ip)==f->addr))
return 1;
f=f->next;
}
return 0;
}
return 1;
}
static int iif_v6(struct pkt_info* info,struct IPM *src,struct IPM *dest) {
struct IPM6 *f;
struct ip6i i;
i = *((struct ip6i*)info->src_ip);
if(odp_likely(src!=NULL)){
f = src->ip6;
while(f){
/* we assume a long linear search! */
if(odp_unlikely( ((f->mask[0]&i.p[0])==(f->addr[0]))&&((f->mask[1]&i.p[1])==(f->addr[1])) ))
goto SRC_OK;
f=f->next;
}
return 0;
}
SRC_OK:
i = *((struct ip6i*)info->src_ip);
if(odp_likely(dest!=NULL)){
f = dest->ip6;
while(f){
/* we assume a long linear search! */
if(odp_unlikely( ((f->mask[0]&i.p[0])==(f->addr[0]))&&((f->mask[1]&i.p[1])==(f->addr[1])) ))
return 1;
f=f->next;
}
return 0;
}
return 1;
}
proc_result_t iif_input(odp_packet_t pkt,void* args){
proc_result_t result;
struct IPAll* filter = args;
struct pkt_info* info = odp_packet_user_area(pkt);
result.packet_handle = pkt;
if(odp_packet_has_ipv6(pkt))
result.next_action = iif_v6(info,filter->src,filter->dest)?NA_CONTINUE:NA_DROP;
else if(odp_likely(odp_packet_has_ipv4(pkt)))
result.next_action = iif_v4(info,filter->src,filter->dest)?NA_CONTINUE:NA_DROP;
else result.next_action = NA_DROP;
return result;
}
|
maxymania/fantastic-octo-dollop | src/lwstack/tfif.c | <reponame>maxymania/fantastic-octo-dollop
/*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "tfif.h"
#include <odp/helper/tcp.h>
//proc_result_t tfif_input(odp_packet_t pkt,void* args) ODP_HOT_CODE;
proc_result_t tfif_input(odp_packet_t pkt,void* args){
proc_result_t result;
struct TCPAll filter = *((struct TCPAll*)args);
odph_tcphdr_t* hdr = odp_packet_l3_ptr(pkt,NULL);
result.packet_handle = pkt;
result.next_action = ((hdr->doffset_flags&filter.mask)==filter.data)?NA_CONTINUE:NA_DROP;
return result;
}
|
maxymania/fantastic-octo-dollop | src/prog/host.c | /*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdio.h>
#include <odp.h>
#include <odp/helper/linux.h>
#include <odp/helper/eth.h>
#include <odp/helper/ip.h>
#include <ustack/netinput.h>
struct iofix {
odp_pktio_t pktio;
};
#define PKT_LIST_SIZE 16
static void *iot_burst(void *arg) {
struct iofix fix = *((struct iofix*)arg);
odp_packet_t pkt_list [PKT_LIST_SIZE];
int packets,i;
for(;;){
packets = odp_pktio_recv(fix.pktio, pkt_list, PKT_LIST_SIZE);
//printf("packets: %d\n",packets);
for(i=0;i<packets;++i){
net_input(pkt_list[i]);
}
}
return NULL;
}
#undef PKT_LIST_SIZE
odp_pool_t open_pool(const char* name,int num){
odp_pool_param_t params;
/* Create packet pool */
odp_pool_param_init(¶ms);
params.pkt.seg_len = (1<<14)-192;
params.pkt.len = (1<<14)-192;
params.pkt.num = num;
params.type = ODP_POOL_PACKET;
return odp_pool_create(name, ¶ms);
}
odp_pktio_t open_nic(const char* dev,odp_pool_t pool){
odp_pktio_t pktio;
//odp_queue_t inq_def;
//odp_queue_param_t qparam;
odp_pktio_param_t pktio_param;
pktio_param.in_mode = ODP_PKTIN_MODE_RECV;
pktio_param.out_mode = ODP_PKTOUT_MODE_SEND;
pktio = odp_pktio_open(dev, pool, &pktio_param);
odp_pktio_start(pktio);
return pktio;
}
#define MAX_WORKERS 32
odph_linux_pthread_t thread_tbl[MAX_WORKERS];
int main(int argc, char *argv[]){
if(argc<2)return 1;
int i,n,cpu;
odp_cpumask_t cpumask;
odp_init_global(NULL, NULL);
odp_init_local(ODP_THREAD_CONTROL);
struct iofix fix;
odp_pool_t pool = open_pool("pktin_pool",1024);
//fix.pktio = open_nic("mytap",pool);
fix.pktio = open_nic(argv[1],pool);
n = odp_cpumask_default_worker(&cpumask, MAX_WORKERS);
odph_linux_pthread_create(thread_tbl, &cpumask,
iot_burst,&fix,ODP_THREAD_WORKER);
odph_linux_pthread_join(thread_tbl, n);
return 0;
}
|
maxymania/fantastic-octo-dollop | src/ustack/arp.c | /*
*
* Copyright 2016 <NAME>
* Copyright 2011-2015 by <NAME>. FNET Community.
* Copyright 2008-2010 by <NAME>. Freescale Semiconductor, 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 "arp.h"
#include "fnet_arp.h"
uint32be_t ipv4_address = 0;
void arp_input(odp_packet_t pkt){
uint32_t size;
odph_ethaddr_t eth_address;
odp_pktio_t nic = odp_packet_input(pkt);
if(odp_unlikely(nic==ODP_PKTIO_INVALID)) goto DISCARD;
if(odp_unlikely(odp_pktio_mac_addr(nic,ð_address,sizeof(eth_address))<0))
goto DISCARD;
fnet_arp_header_t *arp_hdr = odp_packet_l3_ptr(pkt,&size);
if( size < sizeof(arp_hdr)
|| (odp_be_to_cpu_16(arp_hdr->hard_type) != FNET_ARP_HARD_TYPE)
|| (arp_hdr->hard_size != FNET_ARP_HARD_SIZE)
|| (odp_be_to_cpu_16(arp_hdr->prot_type) != ODPH_ETHTYPE_IPV4)
|| (arp_hdr->prot_size != FNET_ARP_PROT_SIZE) )
goto DISCARD;
if(odp_unlikely(arp_hdr->sender_prot_addr == ipv4_address)) {
goto DISCARD;
}
// TODO: add arp entry to a table.
if ((odp_be_to_cpu_16(arp_hdr->op) == FNET_ARP_OP_REQUEST) && (arp_hdr->targer_prot_addr == ipv4_address))
{
odph_ethhdr_t *eth_hdr = odp_packet_l2_ptr(pkt,NULL);
arp_hdr->op = odp_cpu_to_be_16(FNET_ARP_OP_REPLY); /* Opcode */
arp_hdr->target_hard_addr = arp_hdr->sender_hard_addr;
arp_hdr->sender_hard_addr = eth_address;
uint32be_t myip = arp_hdr->targer_prot_addr;
arp_hdr->targer_prot_addr = arp_hdr->sender_prot_addr;
arp_hdr->sender_prot_addr = myip;
eth_hdr->dst = eth_hdr->src;
eth_hdr->src = eth_address;
if(odp_unlikely(odp_pktio_send(nic,&pkt,1)<1))
goto DISCARD;
return;
}
DISCARD:
odp_packet_free(pkt);
}
|
maxymania/fantastic-octo-dollop | src/lwstack/tfif.h | /*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include "pipeline.h"
/*
* tfif.h:
* TCP Flags Input Filter
*/
/*
* (odph_tcphdr_t*)->doffset_flags;
*/
struct TCPAll{
uint16be_t mask;
uint16be_t data;
};
/* args must be `struct TCPAll' */
proc_result_t tfif_input(odp_packet_t pkt,void* args);
|
maxymania/fantastic-octo-dollop | src/ustack/netinput.c | /*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <ustack/netinput.h>
#include "arp.h"
#include <stdio.h>
void net_input(odp_packet_t pkt){
if(odp_unlikely(odp_packet_has_error(pkt)))
goto DISCARD;
if(odp_packet_has_tcp(pkt)){
printf("has_tcp_packet\n");
goto DISCARD;
}else if(odp_packet_has_udp(pkt)) {
printf("has_udp_packet\n");
goto DISCARD;
}else if(odp_packet_has_arp(pkt)) {
arp_input(pkt);
return;
}else if(odp_packet_has_icmp(pkt)) {
printf("has_icmp_packet\n");
goto DISCARD;
}
DISCARD:
odp_packet_free(pkt);
}
|
maxymania/fantastic-octo-dollop | src/lwstack/portif.h | /*
*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include "pipeline.h"
/*
* portif.h:
* Port Input Filter
*/
struct PortRange {
uint16_t start,end;
struct PortRange* next;
};
struct PortMatch {
struct PortRange* range;
uint16be_t* list;
uint16_t listLen;
};
struct PortAll {
struct PortMatch* src;
struct PortMatch* dst;
};
/* args must be `struct PortMatch' */
proc_result_t portif_input(odp_packet_t pkt,void* args);
|
pattop/po-plugins | descriptor.h | #pragma once
#include <ladspa.h>
#include <string>
/*
* descriptor - take a copy of a LADSPA_Descriptor and change label and name
*
* This is helpful when using the same descriptor with different port counts.
*/
class descriptor {
public:
descriptor(const LADSPA_Descriptor &, std::string &&label,
std::string &&name);
descriptor(descriptor &&);
const LADSPA_Descriptor *get();
private:
LADSPA_Descriptor d_;
std::string label_;
std::string name_;
};
/*
* register_plugin - register a plugin descriptor
*/
void register_plugin(descriptor &&);
|
pattop/po-plugins | biquad.h | <filename>biquad.h
#pragma once
#include <cstddef>
class biquad_coefficients;
/*
* biquad - simple biquad filter
*
* For details on how this works see the Audio EQ Cookbook.
*/
class biquad {
public:
void run(const biquad_coefficients &,
const float *input, float *output, size_t samples);
private:
double x1 = 0, x2 = 0, y1 = 0, y2 = 0;
};
class biquad_coefficients {
public:
void peaking_eq(double f0, double gain, double Q, double fs);
void lpf1(double f0, double fs);
void lpf(double f0, double Q, double fs);
void hpf1(double f0, double fs);
void hpf(double f0, double Q, double fs);
void low_shelf(double f0, double gain, double Q, double fs);
void high_shelf(double f0, double gain, double Q, double fs);
private:
double b0 = 0, b1 = 0, b2 = 0, a1 = 0, a2 = 0;
friend class biquad;
};
|
pattop/po-plugins | ladspa_ids.h | #pragma once
#warning USING DEVELOPMENT IDs
namespace ladspa_ids {
constexpr auto peaking = 100;
constexpr auto linkwitz_riley_lowpass = 108;
constexpr auto linkwitz_riley_highpass = 116;
constexpr auto low_shelf = 124;
constexpr auto high_shelf = 132;
constexpr auto delay = 140;
constexpr auto invert = 148;
constexpr auto gain = 156;
constexpr auto butterworth_lowpass = 164;
constexpr auto butterworth_highpass = 172;
}
|
gian2705/Parse-SDK-Arduino | src/internal/ParseUtils.h | <reponame>gian2705/Parse-SDK-Arduino<gh_stars>10-100
/*
* Copyright (c) 2015, Parse, LLC. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Parse.
*
* As with any software that integrates with the Parse platform, your use of
* this software is subject to the Parse Terms of Service
* [https://www.parse.com/about/terms]. This copyright 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 Utils_h
#define Utils_h
/*! \file ParseUtils.h
* \brief ParseUtils object for the Yun
* include Parse.h, not this file
*/
/*! \class ParseUtils
* \brief Utility class.
*/
class ParseUtils {
public:
/*! \fn static int getStringFromJSON(const char* data, const char *key, char* value, int size)
* \brief A very lightweight JSON parser to get the string value by key
*
* \param data - JSON string to parse
* \param key - key to find
* \param value - returned value (always as string) or NULL if just to check values'presence
* \param size - size of the return buffer
* \result 1 if found 0 otherwise
*/
static int getStringFromJSON(const char* data, const char *key, char* value, int size) {
const char* found = NULL;
int inString = 0;
int json = 0;
int backslash = 0;
int endWithQuote = 1;
int keyLen = strlen(key);
int escape = 0;
int jsonLevel = 0;
if (!data || !key || !*key)
return 0;
for (found = data; *found; ++found) {
if (strncmp(found, key, keyLen)) {
switch (*found) {
case '\"':
inString = 1 - inString;
break;
case '\\':
if (inString) {
if (*(found + 1))
++found;
}
break;
case '{':
case '[': // treat array as JSON
if (!inString) {
++jsonLevel;
}
break;
case '}':
case ']':
if (!inString) {
--jsonLevel;
if (jsonLevel < 0) {
// Quit on malformed json
return 0;
}
}
break;
}
continue;
} else if (jsonLevel > 1) {
continue;
}
found += keyLen;
if (*found != '\"') {
data = found;
continue;
} else {
++found;
for (; *found == ' ' || *found == '\t'; ++found);
if (*found != ':') {
data = found;
continue;
}
++found;
for (; *found == ' ' || *found == '\t'; ++found);
if (*found == '{' || *found == '[') {
json = 1;
endWithQuote = 0;
} else {
if (*found != '\"')
endWithQuote = 0;
}
break;
}
}
if (!*found)
return 0;
if (!value)
return 1;
if (endWithQuote)
++found;
inString = !json;
jsonLevel = 0;
for (; size > 1 && *found; --size, ++found, ++value) {
if (backslash) {
backslash = 0;
*value = *found;
continue;
}
switch (*found) {
case '{':
case '[':
if (!inString)
++jsonLevel;
break;
case '}':
case ']':
if (!endWithQuote) {
if (!inString) {
if (jsonLevel) {
--jsonLevel;
if (jsonLevel < 0) {
// Quit on malformed json
return 0;
}
}
if (!jsonLevel) {
if (json) {
*value = *found;
++value;
}
goto RETURN_VALUE;
}
break;
}
// Fall through
} else {
// Fall through
}
case '\"':
case ',':
if (endWithQuote && *found != '\"')
break;
if (*found == '\"') //if(!json)
inString = 1 - inString;
if (!json)
goto RETURN_VALUE;
break;
case '\\': backslash = 1; break;
}
*value = *found;
}
RETURN_VALUE:
*value = 0;
if (!*found) // malformed JSON
return 0;
return 1;
}
/*! \fn static int getIntFromJSON(const char* data, const char* key)
* \brief A very lightweight JSON parser to get the integer value by key
*
* \param data - JSON string to parse
* \param key - key to find
* \param value - returned integer value, 0 if key not found
*/
static int getIntFromJSON(const char* data, const char* key) {
char* value = new char[10];
if (ParseUtils::getStringFromJSON(data, key, value, 10)) {
String c = value;
int v = c.toInt();
delete[] value;
return v;
}
delete[] value;
return 0;
}
/*! \fn static double getFloatFromJSON(const char* data, const char* key)
* \brief A very lightweight JSON parser to get the float value by key
*
* \param data - JSON string to parse
* \param key - key to find
* \param value - returned double value, .0 if key not found
*/
static double getFloatFromJSON(const char* data, const char* key) {
char* value = new char[10];
if (ParseUtils::getStringFromJSON(data, key, value, 10)) {
String c = value;
double v = c.toFloat();
delete[] value;
return v;
}
delete[] value;
return .0;
}
/*! \fn static double getFloatFromJSON(const char* data, const char* key)
* \brief A very lightweight JSON parser to get the boolean value by key
*
* \param data - JSON string to parse
* \param key - key to find
* \param value - returned boolean value. false if key not found
*/
static bool getBooleanFromJSON(const char* data, const char* key) {
char* value = new char[10];
if (ParseUtils::getStringFromJSON(data, key, value, 10)) {
String c = value;
bool v = (c == "true")?true:false;
delete[] value;
return v;
}
delete[] value;
return false;
}
static bool isSanitizedString(const String& userData) {
static char badChars[] = " \t\n\r";
int k;
int i;
for(k = 0; k < userData.length(); k++) {
for(i = 0; i < strlen(badChars); i++) {
if(userData[k] == badChars[i]){
return false;
}
}
}
return true;
}
};
#endif
|
gian2705/Parse-SDK-Arduino | src/internal/ParseQuery.h | <filename>src/internal/ParseQuery.h<gh_stars>10-100
/*
* Copyright (c) 2015, Parse, LLC. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Parse.
*
* As with any software that integrates with the Parse platform, your use of
* this software is subject to the Parse Terms of Service
* [https://www.parse.com/about/terms]. This copyright 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 ParseQuery_h
#define ParseQuery_h
#include "ParseRequest.h"
/*! \file ParseQuery.h
* \brief ParseQuery object for the Yun
* include Parse.h, not this file
*/
/*! \class ParseQuery
* \brief Class responsible for query encapsulation
*/
class ParseQuery : public ParseRequest {
private:
String whereClause;
String order;
String returnedFields;
int limit;
int skip;
void addConditionKey(const char* key);
void addConditionNum(const char* key, const char* comparator, double value);
public:
/*! \fn ParseQuery()
* \brief Constructor of ParseCloudFunction object
*/
ParseQuery();
/*! \fn void whereExists(const char* key)
* \brief Add a constraint for finding objects that contain the given key.
*
* \param key - the key that should exist.
*/
void whereExists(const char* key);
/*! \fn void whereDoesNotExist(const char* key)
* \brief add a constraint for finding objects that does not contain the given key.
*
* \param key - the key that should not exist.
*/
void whereDoesNotExist(const char* key);
/*** string condition ***/
/*! \fn void whereEqualTo(const char* key, const char* value)
* \brief add a constraint to the query that requires a particular key's value to be equal to the provided string value.
*
* \param key - The key to check.
* \param value - The value that the ParseObject must contain.
*/
void whereEqualTo(const char* key, const char* value);
/*! \fn void whereNotEqualTo(const char* key, const char* value)
* \brief add a constraint to the query that requires a particular key's value not equal to the provided string value.
*
* \param key - The key to check.
* \param value - The value that must not be equalled.
*/
void whereNotEqualTo(const char* key, const char* value);
/*** boolean condition ***/
/*! \fn void whereEqualTo(const char* key, bool value)
* \brief add a constraint to the query that requires a particular key's value to be equal to the provided boolean value.
*
* \param key - The key to check.
* \param value - The value that the ParseObject must contain.
*/
void whereEqualTo(const char* key, bool value);
/*! \fn void whereNotEqualTo(const char* key, bool value)
* \brief add a constraint to the query that requires a particular key's value to be equal to the provided string value.
*
* \param key - The key to check.
* \param value - The value that must not be equalled.
*/
void whereNotEqualTo(const char* key, bool value);
/*** integer number condition ***/
/*! \fn void whereEqualTo(const char* key, int value)
* \brief add a constraint to the query that requires a particular key's value to be equal to the provided string value.
*
* \param key - The key to check.
* \param value - The value that the ParseObject must contain.
*/
void whereEqualTo(const char* key, int value);
/*! \fn void whereNotEqualTo(const char* key, int value)
* \brief add a constraint to the query that requires a particular key's value to be equal to the provided string value.
*
* \param key - The key to check.
* \param value - The value that must not be equalled.
*/
void whereNotEqualTo(const char* key, int value);
/*! \fn void whereLessThan(const char* key, int value)
* \brief add a constraint to the query that requires a particular key's value to be less than the provided value.
*
* \param key - The key to check.
* \param value - The value that provides an upper bound.
*/
void whereLessThan(const char* key, int value);
/*! \fn void whereGreaterThan(const char* key, int value)
* \brief add a constraint to the query that requires a particular key's value to be greater than the provided value.
*
* \param key - The key to check.
* \param value - The value that provides an lower bound.
*/
void whereGreaterThan(const char* key, int value);
/*! \fn void whereLessThanOrEqualTo(const char* key, int value)
* \brief add a constraint to the query that requires a particular key's value to be less than or equal to the provided value.
*
* \param key - The key to check.
* \param value - The value that provides an upper bound.
*/
void whereLessThanOrEqualTo(const char* key, int value);
/*! \fn void whereGreaterThanOrEqualTo(const char* key, int value)
* \brief add a constraint to the query that requires a particular key's value to be greater than or equal to the provided value.
*
* \param key - The key to check.
* \param value - The value that provides an lower bound.
*/
void whereGreaterThanOrEqualTo(const char* key, int value);
/*** double number condition ***/
/*! \fn void whereEqualTo(const char* key, double value)
* \brief add a constraint to the query that requires a particular key's value to be equal to the provided value.
*
* \param key - The key to check.
* \param value - The value that the ParseObject must contain.
*/
void whereEqualTo(const char* key, double value);
/*! \fn void whereNotEqualTo(const char* key, double value)
* \brief add a constraint to the query that requires a particular key's value not equal to the provided double value.
*
* \param key - The key to check.
* \param value - The value that must not be equalled.
*/
void whereNotEqualTo(const char* key, double value);
/*! \fn void whereLessThan(const char* key, double value)
* \brief add a constraint to the query that requires a particular key's value to be less than the provided value.
*
* \param key - The key to check.
* \param value - The value that provides an upper bound.
*/
void whereLessThan(const char* key, double value);
/*! \fn void whereGreaterThan(const char* key, double value)
* \brief add a constraint to the query that requires a particular key's value to be greater than the provided value.
*
* \param key - The key to check.
* \param value - The value that provides an lower bound.
*/
void whereGreaterThan(const char* key, double value);
/*! \fn void whereLessThanOrEqualTo(const char* key, double value)
* \brief add a constraint to the query that requires a particular key's value to be less than or equal to the provided value.
*
* \param key - The key to check.
* \param value - The value that provides an upper bound.
*/
void whereLessThanOrEqualTo(const char* key, double value);
/*! \fn void whereGreaterThanOrEqualTo(const char* key, double value)
* \brief add a constraint to the query that requires a particular key's value to be greater than or equal to the provided value.
*
* \param key - The key to check.
* \param value - The value that provides an lower bound.
*/
void whereGreaterThanOrEqualTo(const char* key, double value);
/*! \fn void setLimit(int n)
* \brief controls the maximum number of results that are returned.
*
* controls the maximum number of results that are returned.
* setting a negative limit denotes retrieval without a limit.
* the default limit is 100, with a maximum of 1000 results being returned at a time.
*
* \param n - limit.
*/
void setLimit(int n);
/*! \fn void setSkip(int n)
* \brief controls the number of results to skip before returning any results.
*
* \param n - number to skip.
*/
void setSkip(int n);
/*! \fn void setKeys(const char* keys)
* \brief restrict the fields of returned ParseObjects to only include the provided keys.
*
* \param keys - Keys to include. seperate multiple keys with comma
* e.g. "score,name"
*/
void setKeys(const char* keys);
/*! \fn void orderBy(const char* key)
* \brief sorts the results in ascending/descending order by the given key.
*
* \param keys - Keys to sort on.
* use "field_name" for ascending order
* use a negative sign "-field_name" for descending order
* seperate multiple keys with comma e.g. "score,-name"
*/
void orderBy(const char* keys);
/*! \fn ParseResponse send() override
* \brief launch query and execute
*
* \result response of the request.
*/
ParseResponse send();
};
#endif
|
gian2705/Parse-SDK-Arduino | src/internal/ParsePush.h | <filename>src/internal/ParsePush.h
/*
* Copyright (c) 2015, Parse, LLC. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Parse.
*
* As with any software that integrates with the Parse platform, your use of
* this software is subject to the Parse Terms of Service
* [https://www.parse.com/about/terms]. This copyright 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 ParsePush_h
#define ParsePush_h
#include "ConnectionClient.h"
#include "ParseResponse.h"
/*! \file ParsePush.h
* \brief ParsePush object for the Yun
* include Parse.h, not this file
*/
/*! \class ParsePush
* \brief Class with a push. Not created directly.
*/
class ParsePush : public ParseResponse {
protected:
ParsePush(ConnectionClient* pushClient);
#if defined (ARDUINO_SAMD_ZERO) || defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_UNO_GSM)
char lookahead[5];
void setLookahead(const char *read_data);
void read();
#endif // defined (ARDUINO_SAMD_ZERO)
public:
/*! \fn void close()
* \brief free resource including data buffer.
*
*/
void close();
friend class ParseClient;
};
#endif
|
gian2705/Parse-SDK-Arduino | src/internal/ParseRequest.h | /*
* Copyright (c) 2015, Parse, LLC. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Parse.
*
* As with any software that integrates with the Parse platform, your use of
* this software is subject to the Parse Terms of Service
* [https://www.parse.com/about/terms]. This copyright 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 ParseRequest_h
#define ParseRequest_h
#include "ParseInternal.h"
#include "ParseResponse.h"
/*! \file ParseRequest.h
* \brief ParseRequest object for the Yun
* include Parse.h, not this file
*/
/*! \class ParseRequest
* \brief Class responsible for Parse requests
*/
class ParseRequest {
protected:
String httpPath;
String requestBody;
bool isBodySet;
public:
/*! \fn ParseRequest()
* \brief Constructor of ParseRequest object
*/
ParseRequest();
/*! \fn ~ParseRequest()
* \brief Destructor of ParseRequest object
*/
~ParseRequest();
/*! \fn void setClassName(const char* className)
* \brief set the ParseObject class name in which request will be performed.
*
* NOTE: ONLY use when request(GET/UPDATE/DELETE/CREATE/QUERY) is related with object
* for system object "Installation/User/Role", use "_Installatoin/_User/_Role" for className
* DO NOT setClassName for ParseCloudFunction, use setFunctionName
* DO NOT setClassName for ParseCloudFunction, use setEventName
*
* \param className class name.
*/
void setClassName(const char* className);
/*! \fn void setObjectId(const char* objectId)
* \brief set the ParseObject object id in which request will be performed.
*
* NOTE: ONLY setObjectId for GET/UPDATE/DELETE request on a specific object
* for CREATE request, a new object id will be return on response
*
* \param objectId object id.
*/
void setObjectId(const char* objectId);
/*! \fn virtual ParseResponse send()
* \brief execute the parse request.
*
* \result response of request
*/
virtual ParseResponse send() = 0;
};
#endif
|
gian2705/Parse-SDK-Arduino | src/Parse.h | /*
* Copyright (c) 2015, Parse, LLC. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Parse.
*
* As with any software that integrates with the Parse platform, your use of
* this software is subject to the Parse Terms of Service
* [https://www.parse.com/about/terms]. This copyright 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 PARSE_H_
#define PARSE_H_
/*! \mainpage Parse Arduino Yun SDK
*
* The Parse Arduino Yun SDK offers set of classes that enable the use of the
* <a href="https://parse.com">Parse platform</a> Wire-API applications running on
* Arduino Yun platform.
*/
/*! \file Parse.h
* \brief Main include file for object in Yun SDK
* include this file, not individual object files.
*/
#include <internal/ParseClient.h>
#include <internal/ParseResponse.h>
#include <internal/ParsePush.h>
#include <internal/ParseQuery.h>
#include <internal/ParseUtils.h>
#include <internal/ParseObjectCreate.h>
#include <internal/ParseObjectDelete.h>
#include <internal/ParseObjectGet.h>
#include <internal/ParseObjectUpdate.h>
#include <internal/ParseCloudFunction.h>
#include <internal/ParseTrackEvent.h>
#endif
|
gian2705/Parse-SDK-Arduino | src/internal/ParseObjectCreate.h | /*
* Copyright (c) 2015, Parse, LLC. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Parse.
*
* As with any software that integrates with the Parse platform, your use of
* this software is subject to the Parse Terms of Service
* [https://www.parse.com/about/terms]. This copyright 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 ParseObjectCreate_h
#define ParseObjectCreate_h
#include "ParseRequest.h"
/*! \file ParseObjectCreate.h
* \brief ParseObjectCreate object for the Yun
* include Parse.h, not this file
*/
/*! \class ParseObjectCreate
* \brief Class responsible for new Parse object creation
*/
class ParseObjectCreate : public ParseRequest {
protected:
void addKey(const char* key);
public:
/*! \fn ParseObjectCreate()
* \brief Constructor of ParseObjectCreate object
*/
ParseObjectCreate() : ParseRequest() {}
/*! \fn void add(const char* key, int d)
* \brief Add a key and integer value pair to object.
*
* \param key The key name.
* \param d The value.
*/
void add(const char* key, int d);
/*! \fn void add(const char* key, double d)
* \brief Add a key and double value pair to object.
*
* \param key The key name.
* \param d The value.
*/
void add(const char* key, double d);
/*! \fn add(const char* key, const char* s)
* \brief add a key and string value pair to object.
*
* \param key The key name.
* \param s The value.
*/
void add(const char* key, const char* s);
/*! \fn void add(const char* key, bool b)
* \brief add a key and boolean value pair to object.
*
* \param key The key name.
* \param b The value.
*/
void add(const char* key, bool b);
/*! \fn void addGeoPoint(const char* key, double lat, double lon)
* \brief add a key and GeoPoint value pair to object.
*
* \param key The key name.
* \param lat The latitude value.
* \param lon The logitude value.
*/
void addGeoPoint(const char* key, double lat, double lon);
/*! \fn void addJSONValue(const char* key, const char* json)
* \brief add a key and json value pair to object.
*
* \param key The key name.
* \param json The value.
*/
void addJSONValue(const char* key, const char* json);
/*! \fn void addJSONValue(const char* key, const String& json)
* \brief add a key and json value pair to object.
*
* \param key The key name.
* \param json The value.
*/
void addJSONValue(const char* key, const String& json);
/*! \fn void setJSONBody(const char* jsonBody)
* \brief set the json body of object directly.
*
* NOTE: this will remove all previous key-value pairs set if there are any
* \param jsonBody The new JSON body.
*/
void setJSONBody(const char* jsonBody);
/*! \fn void setJSONBody(const String& jsonBody)
* \brief set the json body of object directly.
*
* NOTE: this will remove all previous key-value pairs set if there are any
* \param jsonBody The new JSON body.
*/
void setJSONBody(const String& jsonBody);
/*! \fn virtual ParseResponse send()
* \brief launch the object creation request and execute.
*
*/
virtual ParseResponse send();
};
#endif
|
gian2705/Parse-SDK-Arduino | src/internal/ParseObjectUpdate.h | <filename>src/internal/ParseObjectUpdate.h
/*
* Copyright (c) 2015, Parse, LLC. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Parse.
*
* As with any software that integrates with the Parse platform, your use of
* this software is subject to the Parse Terms of Service
* [https://www.parse.com/about/terms]. This copyright 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 ParseObjectUpdate_h
#define ParseObjectUpdate_h
#include "ParseObjectCreate.h"
/*! \file ParseObjectUpdate.h
* \brief ParseObjectUpdate object for the Yun
* include Parse.h, not this file
*/
/*! \class ParseObjectUpdate
* \brief Class responsible for object update
*/
class ParseObjectUpdate : public ParseObjectCreate {
public:
/*! \fn ParseObjectUpdate()
* \brief Constructor of ParseObjectUpdate object
*/
ParseObjectUpdate();
/*! \fn ParseResponse send() override
* \brief launch the update object request and execute.
*
* \result the response
*/
ParseResponse send();
};
#endif
|
appleMini/Skybox | Skybox/Classes/Skybox.h | //
// Skybox.h
// AFNetworking
//
// Created by <NAME> on 2017/11/30.
//
#import <Foundation/Foundation.h>
#import "Utils.h"
|
appleMini/Skybox | Skybox/Classes/Utils.h | //
// Utils.h
// FBSnapshotTestCase
//
// Created by <NAME> on 2017/11/29.
//
#import <Foundation/Foundation.h>
@interface Utils : NSObject
+ (int)sum:(int)a B:(int)b;
@end
|
appleMini/Skybox | Example/Skybox/SKViewController.h | //
// SKViewController.h
// Skybox
//
// Created by appleMini on 11/29/2017.
// Copyright (c) 2017 appleMini. All rights reserved.
//
@import UIKit;
@interface SKViewController : UIViewController
@end
|
wonderful27x/OpenCvFaceTrackLean | WYOpenCv/WYOpenCv.h | <reponame>wonderful27x/OpenCvFaceTrackLean<gh_stars>0
// WYOpenCv.h: 标准系统包含文件的包含文件
// 或项目特定的包含文件。
#pragma once
#include <iostream>
#include <opencv2/opencv.hpp>
#define ENABLE_LBP
//#define ENABLE_SAMPLES
using namespace std;
using namespace cv;
//动态人脸检测需要用的适配器,官方demo复制而来
//E:\OPENCV\opencv4.1.2\INSTALL\opencv\sources\samples\android\face-detection\jni\DetectionBasedTracker_jni.cpp
class CascadeDetectorAdapter : public DetectionBasedTracker::IDetector
{
public:
CascadeDetectorAdapter(cv::Ptr<cv::CascadeClassifier> detector) :
IDetector(),
Detector(detector)
{
CV_Assert(detector);
}
void detect(const cv::Mat& Image, std::vector<cv::Rect>& objects)
{
Detector->detectMultiScale(Image, objects, scaleFactor, minNeighbours, 0, minObjSize, maxObjSize);
}
virtual ~CascadeDetectorAdapter()
{
}
private:
CascadeDetectorAdapter();
cv::Ptr<cv::CascadeClassifier> Detector;
};
// TODO: 在此处引用程序需要的其他标头。
|
msharov/casycom | app.h | <reponame>msharov/casycom<filename>app.h
// This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "msg.h"
#ifdef __cplusplus
extern "C" {
#endif
//----------------------------------------------------------------------
// PApp
typedef void (*MFN_App_init)(void* o, argc_t argc, argv_t argv);
typedef void (*MFN_App_signal)(void* o, unsigned sig, pid_t child_pid, int child_status);
typedef struct _DApp {
iid_t interface;
MFN_App_init App_init;
MFN_App_signal App_signal;
} DApp;
extern const Interface i_App;
void PApp_init (const Proxy* pp, argc_t argc, argv_t argv) noexcept NONNULL();
void PApp_signal (const Proxy* pp, unsigned sig, pid_t child_pid, int child_status) noexcept NONNULL();
#define CASYCOM_MAIN(oapp) \
int main (int argc, argv_t argv) { \
casycom_framework_init (&oapp, argc, argv); \
return casycom_main(); \
}
#ifdef __cplusplus
} // extern "C"
#endif
|
msharov/casycom | stm.h | <gh_stars>1-10
// This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "util.h"
typedef struct _RStm {
const char* _p;
const char* _end;
} RStm;
typedef struct _WStm {
char* _p;
char* _end;
} WStm;
#ifdef __cplusplus
extern "C" {
namespace {
#endif
static inline size_t casystm_read_available (const RStm* s)
{ return s->_end - s->_p; }
static inline bool casystm_can_read (const RStm* s, size_t sz)
{ return s->_p + sz <= s->_end; }
static inline void casystm_read_skip (RStm* s, size_t sz)
{ assert (casystm_can_read(s,sz)); s->_p += sz; }
static inline void casystm_unread (RStm* s, size_t sz)
{ s->_p -= sz; }
static inline void casystm_read_skip_to_end (RStm* s)
{ s->_p = s->_end; }
static inline void casystm_read_data (RStm* s, void* buf, size_t sz)
{ const void* p = s->_p; casystm_read_skip (s, sz); memcpy (buf, p, sz); }
static inline bool casystm_is_read_aligned (const RStm* s, size_t grain)
{ return !(((uintptr_t)s->_p) % grain); }
static inline void casystm_read_align (RStm* s, size_t grain)
{ s->_p = (const char*) ceilg ((uintptr_t) s->_p, grain); }
static inline size_t casystm_write_available (const RStm* s)
{ return s->_end - s->_p; }
static inline bool casystm_can_write (const WStm* s, size_t sz)
{ return s->_p + sz <= s->_end; }
static inline void casystm_write_skip (WStm* s, size_t sz)
{ assert (casystm_can_write(s,sz)); s->_p += sz; }
static inline void casystm_write_skip_to_end (WStm* s)
{ s->_p = s->_end; }
static inline void casystm_write_data (WStm* s, const void* buf, size_t sz)
{ void* p = s->_p; casystm_write_skip (s, sz); memcpy (p, buf, sz); }
static inline bool casystm_is_write_aligned (const WStm* s, size_t grain)
{ return !(((uintptr_t)s->_p) % grain); }
#define CASYSTM_READ_POD(name,type)\
static inline type casystm_read_##name (RStm* s) {\
assert (casystm_is_read_aligned (s, _Alignof(type)));\
casystm_read_skip (s, sizeof(type));\
return ((type*)s->_p)[-1];\
}
CASYSTM_READ_POD (uint8, uint8_t)
CASYSTM_READ_POD (int8, int8_t)
CASYSTM_READ_POD (uint16, uint16_t)
CASYSTM_READ_POD (int16, int16_t)
CASYSTM_READ_POD (uint32, uint32_t)
CASYSTM_READ_POD (int32, int32_t)
CASYSTM_READ_POD (uint64, uint64_t)
CASYSTM_READ_POD (int64, int64_t)
CASYSTM_READ_POD (float, float)
CASYSTM_READ_POD (double, double)
CASYSTM_READ_POD (bool, uint8_t)
#define CASYSTM_WRITE_POD(name,type)\
static inline void casystm_write_##name (WStm* s, type v) {\
assert (casystm_is_write_aligned (s, _Alignof(type)));\
casystm_write_skip (s, sizeof(type));\
((type*)s->_p)[-1] = v;\
}
CASYSTM_WRITE_POD (uint8, uint8_t)
CASYSTM_WRITE_POD (int8, int8_t)
CASYSTM_WRITE_POD (uint16, uint16_t)
CASYSTM_WRITE_POD (int16, int16_t)
CASYSTM_WRITE_POD (uint32, uint32_t)
CASYSTM_WRITE_POD (int32, int32_t)
CASYSTM_WRITE_POD (uint64, uint64_t)
CASYSTM_WRITE_POD (int64, int64_t)
CASYSTM_WRITE_POD (float, float)
CASYSTM_WRITE_POD (double, double)
CASYSTM_WRITE_POD (bool, uint8_t)
static inline void casystm_write_align (WStm* s, size_t grain) {
while (!casystm_is_write_aligned (s, grain))
casystm_write_uint8 (s, 0);
}
static inline size_t casystm_size_string (const char* v) {
size_t l = v ? strlen(v) : 0;
return ceilg (sizeof(uint32_t)+l+!!l, 4);
}
static inline void* casystm_read_ptr (RStm* s)
{ return (void*)(uintptr_t) casystm_read_uint64(s); }
static inline void casystm_write_ptr (WStm* s, const void* p)
{ casystm_write_uint64 (s, (uintptr_t) p); }
#ifdef __cplusplus
} // namespace
#endif
const char* casystm_read_string (RStm* s) noexcept;
void casystm_write_string (WStm* s, const char* v) noexcept;
#ifdef __cplusplus
} // extern "C"
#endif
|
msharov/casycom | test/ping.h | <reponame>msharov/casycom<filename>test/ping.h<gh_stars>1-10
// This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
// You would normally include casycom.h this way
//#include <casycom.h>
// But for the purpose of building the tests, local headers are
// included directly to ensure they are used instead of installed.
#include "../app.h"
#include "../timer.h"
#include "../io.h"
#include "../xsrv.h"
//----------------------------------------------------------------------
// For communication between objects, both sides of the link must be
// defined as well as the interface. The interface object, by convention
// named i_Name, is of type Interface and contains its name, method
// names and signatures, and the dispatch method pointer. The proxy
// "object" is used to send messages to the remote object, and contains
// methods mirroring those on the remote object, that are implemented
// by marshalling the arguments into a message. The remote object is
// created by the framework, using the Factory f_Name, when the message
// is to be delivered.
// Method types for the dispatch table
typedef void (*MFN_Ping_ping)(void* o, uint32_t v);
// The dispatch table for the dispatch method
typedef struct _DPing {
const Interface* interface; // Pointer to the interface this DTable implements
MFN_Ping_ping Ping_ping; // void Ping_ping (void* vo, uint32_t u, const Msg* msg)
} DPing;
// Ping proxy methods, matching the list in DPing
void PPing_ping (const Proxy* pp, uint32_t v);
// This is the interface object; iid_t is the pointer to it.
extern const Interface i_Ping;
//----------------------------------------------------------------------
// Replies are reply interfaces, conventionally named NameR
// Implementation is the same as above
typedef void (*MFN_PingR_ping)(void* o, uint32_t v);
typedef struct _DPingR {
const Interface* interface;
MFN_PingR_ping PingR_ping;
} DPingR;
void PPingR_Ping (const Proxy* pp, uint32_t v);
extern const Interface i_PingR;
//----------------------------------------------------------------------
// This is the server object, to pass to casycom_register
extern const Factory f_Ping;
//----------------------------------------------------------------------
// Define a synchronous write to avoid race conditions between processes
#define LOG(...) {printf(__VA_ARGS__);fflush(stdout);}
|
msharov/casycom | msg.h | <filename>msg.h
// This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "stm.h"
//----------------------------------------------------------------------
typedef uint16_t oid_t;
enum {
oid_Broadcast,
oid_App,
oid_First,
oid_Last = 32000-1
};
typedef const char* methodid_t;
typedef struct _Interface {
const void* dispatch;
methodid_t name;
methodid_t method[];
} Interface;
typedef const Interface* iid_t;
typedef struct _Proxy {
iid_t interface;
oid_t src;
oid_t dest;
} Proxy;
#define PROXY_INIT {}
typedef struct _Msg {
Proxy h;
uint32_t imethod;
uint32_t size;
oid_t extid;
uint8_t fdoffset;
uint8_t reserved;
void* body;
} Msg;
enum {
NO_FD_IN_MESSAGE = UINT8_MAX,
MESSAGE_HEADER_ALIGNMENT = 8,
MESSAGE_BODY_ALIGNMENT = MESSAGE_HEADER_ALIGNMENT,
method_invalid = (uint32_t)-2,
method_create_object = (uint32_t)-1
};
typedef struct _DTable {
const iid_t interface;
} DTable;
#define DMETHOD(o,m) .m = (MFN_##m) o##_##m
typedef void (*pfn_dispatch)(const void* dtable, void* o, const Msg* msg);
//----------------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
Msg* casymsg_begin (const Proxy* pp, uint32_t imethod, uint32_t sz) noexcept NONNULL() MALLOCLIKE;
void casymsg_from_vector (const Proxy* pp, uint32_t imethod, void* body) noexcept NONNULL();
void casymsg_forward (const Proxy* pp, Msg* msg) noexcept NONNULL();
void casycom_queue_message (Msg* msg) noexcept NONNULL(); ///< In main.c
uint32_t casyiface_count_methods (iid_t iid) noexcept;
size_t casymsg_validate_signature (const Msg* msg) noexcept NONNULL();
#ifdef __cplusplus
namespace {
#endif
static inline const char* casymsg_interface_name (const Msg* msg) { return msg->h.interface->name; }
static inline const char* casymsg_method_name (const Msg* msg) {
assert ((msg->imethod == method_create_object || casyiface_count_methods(msg->h.interface) > msg->imethod) && "invalid method index in message");
return msg->h.interface->method[(int32_t)msg->imethod];
}
static inline const char* casymsg_signature (const Msg* msg) {
const char* mname = casymsg_method_name (msg);
assert (mname && "invalid method in message");
return mname + strlen(mname) + 1;
}
static inline RStm casymsg_read (const Msg* msg)
{ return (RStm) { msg->body, msg->body + msg->size }; }
static inline WStm casymsg_write (Msg* msg)
{ return (WStm) { msg->body, msg->body + msg->size }; }
static inline void casymsg_end (Msg* msg)
{ casycom_queue_message (msg); }
static inline void casymsg_write_fd (Msg* msg, WStm* os, int fd) {
size_t fdoffset = os->_p - (char*) msg->body;
assert (fdoffset != NO_FD_IN_MESSAGE && "file descriptors must be passed in the first 252 bytes of the message");
assert (msg->fdoffset == NO_FD_IN_MESSAGE && "only one file descriptor can be passed per message");
msg->fdoffset = fdoffset;
casystm_write_int32 (os, fd);
}
static inline int casymsg_read_fd (const Msg* msg UNUSED, RStm* is) {
assert ((size_t)(is->_p - (char*) msg->body) == msg->fdoffset && "there is no file descriptor at this offset");
return casystm_read_int32 (is);
}
#define casymsg_free(msg) \
do { if (msg) xfree (msg->body); xfree (msg); } while (false)
static inline void casymsg_default_dispatch (const void* dtable UNUSED, void* o UNUSED, const Msg* msg)
{
if (msg->imethod != method_create_object)
assert (!"Invalid method index in message");
}
#ifdef __cplusplus
} // namespace
} // extern "C"
#endif
|
msharov/casycom | test/ping.c | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#include "ping.h"
//{{{ Ping interface ---------------------------------------------------
// Indexes for Ping methods, for the imethod field in the message.
// This is used only when marshalling the message and during its
// dispatch. Remember to keep this synchronized with the dtable.
enum { method_Ping_ping };
// Each interface method has a corresponding proxy method, called
// as if the proxy was the remote object. The proxy methods marshal
// the arguments into a message object and put it in the queue.
void PPing_ping (const Proxy* pp, uint32_t v)
{
assert (pp->interface == &i_Ping && "the given proxy is for a different interface");
// casymsg_begin will create a message of the given size (here sizeof(v))
Msg* msg = casymsg_begin (pp, method_Ping_ping, sizeof(v));
// casystm functions are defined in stm.h
WStm os = casymsg_write (msg);
casystm_write_uint32 (&os, v);
// When done, call casymsg_end. It will check for errors and queue the message.
casymsg_end (msg);
}
// dispatch function for the Ping interface
// The arguments are the destination object, its dispatch table, and the message
static void Ping_dispatch (const DPing* dtable, void* o, const Msg* msg)
{
// The message stores the method as an index into the interface.method array
if (msg->imethod == method_Ping_ping) { // Use constant defined above
RStm is = casymsg_read (msg);
uint32_t v = casystm_read_uint32 (&is);
dtable->Ping_ping (o, v);
} else // To handle errors, call the default dispatch for unknown methods
casymsg_default_dispatch (dtable, o, msg);
}
// The interface definition, containing the name, method list, and
// dispatch function pointer.
const Interface i_Ping = {
.name = "Ping",
.dispatch = Ping_dispatch,
.method = { "ping\0u", NULL }
};
//}}}-------------------------------------------------------------------
//{{{ PingR interface
enum { method_PingR_ping };
void PPingR_ping (const Proxy* pp, uint32_t v)
{
assert (pp->interface == &i_PingR && "the given proxy is for a different interface");
Msg* msg = casymsg_begin (pp, method_PingR_ping, sizeof(v));
WStm os = casymsg_write (msg);
casystm_write_uint32 (&os, v);
casymsg_end (msg);
}
static void PingR_dispatch (const DPingR* dtable, void* o, const Msg* msg)
{
if (msg->imethod == method_PingR_ping) {
RStm is = casymsg_read (msg);
uint32_t v = casystm_read_uint32 (&is);
dtable->PingR_ping (o, v);
} else
casymsg_default_dispatch (dtable, o, msg);
}
// The interface definition, containing the name, method list, and
// dispatch function pointer.
const Interface i_PingR = {
.name = "PingR",
.dispatch = PingR_dispatch,
.method = { "ping\0u", NULL }
};
//}}}-------------------------------------------------------------------
//{{{ Ping server object
// The ping server object data
typedef struct _Ping {
Proxy reply;
unsigned npings;
} Ping;
// The constructor for the object, called when the first message sent
// to it arrives. It must return a valid object pointer. Here, a new
// object is allocated and returned. (xalloc will zero the memory)
// msg->dest is the new object's oid, which may be saved if needed.
static void* Ping_create (const Msg* msg)
{
LOG ("Created Ping %u\n", msg->h.dest);
Ping* po = xalloc (sizeof(Ping));
po->reply = casycom_create_reply_proxy (&i_PingR, msg);
return po;
}
// Object destructor. If defined, must free the object.
static void Ping_destroy (void* o)
{
LOG ("Destroy Ping\n");
xfree (o);
}
// Method implementing the Ping.ping interface method
static void Ping_Ping_ping (Ping* o, uint32_t u)
{
LOG ("Ping: %u, %u total\n", u, ++o->npings);
PPingR_ping (&o->reply, u);
}
// The Ping DTable for the Ping interface
static const DPing d_Ping_Ping = {
.interface = &i_Ping,
// There are two ways to define the methods. First, you could
// use the same signature as defined in DPing, which requires
// the passed in object to be a void* (because when the interface
// is declared, this server object is not and can not be unknown)
// .Ping_ping = Ping_Ping_ping
// You then have to cast that to the object type in each method.
// The second way is to define the method with the typed object
// pointer and use the DMETHOD macro to cast it in the DTable.
// The advantage is not having to cast in the method, the
// disadvantage is that the method's signature is not checked.
DMETHOD (Ping, Ping_ping)
};
// Factory defines the methods required to create objects of this
// type. The framework will do so when receiving a message addressed
// to an interface listed in the .dtable array.
const Factory f_Ping = {
.create = Ping_create,
.destroy = Ping_destroy,
// Lists each interface implemented by this object
.dtable = { &d_Ping_Ping, NULL }
};
//}}}-------------------------------------------------------------------
|
msharov/casycom | xsrv.h | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "xcom.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*MFN_ExternServer_open)(void* vo, int fd, const iid_t* exported_interfaces, bool close_when_empty);
typedef void (*MFN_ExternServer_close)(void* vo);
typedef struct _DExternServer {
iid_t interface;
MFN_ExternServer_open ExternServer_open;
MFN_ExternServer_close ExternServer_close;
} DExternServer;
void PExternServer_open (const Proxy* pp, int fd, const iid_t* exported_interfaces, bool close_when_empty) noexcept NONNULL(1);
void PExternServer_close (const Proxy* pp) noexcept NONNULL();
int PExternServer_bind (const Proxy* pp, const struct sockaddr* addr, socklen_t addrlen, const iid_t* exported_interfaces) noexcept NONNULL();
int PExternServer_bind_local (const Proxy* pp, const char* path, const iid_t* exported_interfaces) noexcept NONNULL();
int PExternServer_bind_user_local (const Proxy* pp, const char* sockname, const iid_t* exported_interfaces) noexcept NONNULL();
int PExternServer_bind_system_local (const Proxy* pp, const char* sockname, const iid_t* exported_interfaces) noexcept NONNULL();
extern const Interface i_ExternServer;
extern const Factory f_ExternServer;
//{{{ PExternServer_bind variants --------------------------------------
#ifdef __cplusplus
namespace {
#endif
/// Create local IPv4 socket at given ip and port
static inline int PExternServer_bind_ip4 (const Proxy* pp, in_addr_t ip, in_port_t port, const iid_t* exported_interfaces)
{
struct sockaddr_in addr = {
.sin_family = PF_INET,
#ifdef UC_VERSION
.sin_addr = ip,
#else
.sin_addr = { ip },
#endif
.sin_port = port
};
return PExternServer_bind (pp, (const struct sockaddr*) &addr, sizeof(addr), exported_interfaces);
}
/// Create local IPv4 socket at given port on the loopback interface
static inline int PExternServer_bind_local_ip4 (const Proxy* pp, in_port_t port, const iid_t* exported_interfaces)
{ return PExternServer_bind_ip4 (pp, INADDR_LOOPBACK, port, exported_interfaces); }
/// Create local IPv6 socket at given ip and port
static inline int PExternServer_bind_ip6 (const Proxy* pp, struct in6_addr ip, in_port_t port, const iid_t* exported_interfaces)
{
struct sockaddr_in6 addr = {
.sin6_family = PF_INET6,
.sin6_addr = ip,
.sin6_port = port
};
return PExternServer_bind (pp, (const struct sockaddr*) &addr, sizeof(addr), exported_interfaces);
}
/// Create local IPv6 socket at given ip and port
static inline int PExternServer_bind_local_ip6 (const Proxy* pp, in_port_t port, const iid_t* exported_interfaces)
{
struct sockaddr_in6 addr = {
.sin6_family = PF_INET6,
.sin6_addr = IN6ADDR_LOOPBACK_INIT,
.sin6_port = port
};
return PExternServer_bind (pp, (const struct sockaddr*) &addr, sizeof(addr), exported_interfaces);
}
#ifdef __cplusplus
} // namespace
} // extern "C"
#endif
//}}}-------------------------------------------------------------------
|
msharov/casycom | test/nfwrk.c | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#include "ping.h"
#include <sys/wait.h>
#include <signal.h>
//----------------------------------------------------------------------
// In an application that already uses an event-driven framework and has
// a message loop, casycom can be used in non-framework mode. While it is
// possible to just run casycom_main in a separate thread (message sending
// is thread safe), enabling threading can have disastrous consequences
// for code not designed to handle it. In this example, casycom is used
// one message loop pass at a time, integrating into a different toplevel
// message loop.
//
// A casycom object is still needed to serve as a destination for reply
// messages. It will, however, not be created as an App object, and need
// not be unique.
typedef struct _PingCaller {
Proxy pingp;
unsigned npings;
Proxy externp;
pid_t server_pid;
} PingCaller;
//----------------------------------------------------------------------
// Connecting to a server is done as shown in ipcom. In this example,
// only the PingCaller_fork_and_pipe method is implemented, and both sides
// use the non-framework operation.
//
static void PingCaller_fork_and_pipe (PingCaller* o);
// List of imported/exported interfaces
static const iid_t eil_Ping[] = { &i_Ping, NULL };
//----------------------------------------------------------------------
// The PingCaller object will serve as the starting point for the outgoing
// Ping and as the recipient of the PingR reply. On the server side, it
// receives the ExternR_connected message and does nothing else.
static void* PingCaller_create (const Msg* msg)
{
PingCaller* o = xalloc (sizeof(PingCaller));
//
// Both sides will need an Extern object. PingCaller oid is the
// destination of the (dummy) message creating this object.
//
o->externp = casycom_create_proxy (&i_Extern, msg->h.dest);
//
// The constructor initiates what the App did in ipcom: spawn
// the server and create an Extern connection. Then, on the client
// side, the Ping request is sent.
//
PingCaller_fork_and_pipe (o);
return o;
}
static void PingCaller_fork_and_pipe (PingCaller* o)
{
// This is the same code as in ipcom
int socks[2];
if (0 > socketpair (PF_LOCAL, SOCK_STREAM| SOCK_NONBLOCK| SOCK_CLOEXEC, 0, socks))
return casycom_error ("socketpair: %s", strerror(errno));
int fr = fork();
if (fr < 0)
return casycom_error ("fork: %s", strerror(errno));
if (fr == 0) { // Server side
close (socks[0]);
casycom_register (&f_Ping); // This is the exported interface
PExtern_open (&o->externp, socks[1], EXTERN_SERVER, NULL, eil_Ping);
} else { // Client side
o->server_pid = fr;
close (socks[1]);
PExtern_open (&o->externp, socks[0], EXTERN_CLIENT, eil_Ping, NULL);
}
}
static void PingCaller_ExternR_connected (PingCaller* o, const ExternInfo* einfo UNUSED)
{
if (!o->server_pid)
return; // the server side will just listen
LOG ("Connected to server.\n");
o->pingp = casycom_create_proxy (&i_Ping, o->externp.src);
PPing_ping (&o->pingp, 1);
}
static void PingCaller_PingR_ping (PingCaller* o, uint32_t u)
{
LOG ("Ping %u reply received; count %u\n", u, ++o->npings);
if (o->npings < 5)
PPing_ping (&o->pingp, o->npings);
else
casycom_quit (EXIT_SUCCESS);
}
static const DPingR d_PingCaller_PingR = {
.interface = &i_PingR,
DMETHOD (PingCaller, PingR_ping)
};
static const DExternR d_PingCaller_ExternR = {
.interface = &i_ExternR,
DMETHOD (PingCaller, ExternR_connected)
};
static const Factory f_PingCaller = {
.create = PingCaller_create,
.dtable = { &d_PingCaller_PingR, &d_PingCaller_ExternR, NULL }
};
//----------------------------------------------------------------------
static void on_child_signal (int signo UNUSED) { waitpid (-1, NULL, 0); }
//----------------------------------------------------------------------
int main (void)
{
// casycom_init differs from casycom_framework_init in not requiring
// an app object. It also does not register signal handlers. It does,
// however, register cleanup handlers for casycom and any objects it
// will create and own.
//
casycom_init();
casycom_enable_externs();
//
// Without casycom's signal handlers, need to catch SIGCHLD
// to cleanly handle the server side's exit.
//
signal (SIGCHLD, on_child_signal);
//
// Because there is no App, no casycom objects exist initially.
//
// An object can be created by sending a message to it. Proxies
// without a source objects should pass oid_Broadcast as the source
// id to casycom_create_proxy
//
// Objects can also be created explicitly, by interface. In this
// example, PingCaller implements the PingR interface, and so it
// can be created for it. One advantage of this method is that
// the pointer to the object is obtained. The pointer is still
// managed by casycom and must not be deleted or accessed after
// it is marked unused (which is the usual way of requesting
// casycom object deletion).
//
casycom_register (&f_PingCaller);
// PingCaller* pco = (PingCaller*)
casycom_create_object (&i_PingR);
//
// A top-level message loop will wait for some exit condition.
// For example, an Xlib event loop will wait for the window to
// close. When using casycom, the loop will also need to check
// for casycom quitting condition. This is necessary for error
// handling to work, in which case it would indicate the destruction
// of the above created PingCaller object.
//
while (!casycom_is_quitting()) { // Add other loop conditions here
// Add top-level message processing here. For example,
// XNextEvent might go here or in the while condition.
//
// The message loop's main purpose is to process messages
// casycom_loop_once will process all messages in the output
// queue, and then will swap the queues. It also checks for
// watched fds and notifies appropriate objects by message,
// but never waits for fd activity. It returns false when no
// messages exist in any queue, a condition indicating that
// the loop should wait for fds to produce something useful.
//
bool haveMessages = casycom_loop_once();
//
// Once message processing is done for this round, the
// appropriate thing to do is to wait on file descriptors.
// Putting the process to sleep is a good thing for prolonging
// the life of the computer. casycom's Timer object normally
// takes care of this, and if no other file descriptors need
// watching, the default poll call can be used as:
// Timer_run_timer (haveMessages ? 0 : -1)
// waiting indefinitely when no messages are present.
//
// If other fds are being polled, such as the Xlib connection
// to the X server, a pollfd list will have to be built here.
// Timer_watch_list_size provides an estimate of how many fds
// are being watched. (An estimate because some of them are
// just timers) That number is a good starting point for
// sizing the fds array.
//
size_t nFds = Timer_watch_list_size();
if (nFds) {
struct pollfd fds [nFds];
//
// After, or before, filling in the non-casycom fds, casycom
// watched fds can be added. The return value is the number
// of fds actually added. A pointer to the timeout variable
// can be provided to support pure timers.
//
int timeout = 0;
nFds = Timer_watch_list_for_poll (fds, nFds, (haveMessages || casycom_is_quitting()) ? NULL : &timeout);
//
// Now poll can be called to wait on the results
//
poll (fds, nFds, timeout);
//
// Here the results can be checked for non-casycom fds.
// Timer will check casycom fds in casycom_loop_once.
// Nothing else to do, so go to the next iteration.
//
} else if (!haveMessages) {
//
// On the server side, when the client connection is terminated
// the Extern object is destroyed. When there are no messages
// and no fds being watched, the server should quit. This is
// done by casycom_main, but in non-framework mode this
// condition is not necessarily a reason to quit. In this example
// it is, so add a check for it here.
//
casycom_quit (EXIT_SUCCESS);
}
}
return casycom_exit_code();
}
|
msharov/casycom | io.h | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "main.h"
#include "vector.h"
#ifdef __cplusplus
extern "C" {
#endif
//----------------------------------------------------------------------
// Abstract async IO interface to read and write CharVector buffers
typedef void (*MFN_IO_read)(void* o, CharVector* d);
typedef void (*MFN_IO_write)(void* o, CharVector* d);
typedef struct _DIO {
const Interface* interface;
MFN_IO_read IO_read;
MFN_IO_write IO_write;
} DIO;
// read some data into the given buffer.
void PIO_read (const Proxy* pp, CharVector* d) noexcept;
// Write all the data in the given buffer.
void PIO_write (const Proxy* pp, CharVector* d) noexcept;
extern const Interface i_IO;
//----------------------------------------------------------------------
// Notifications from the IO interface
typedef void (*MFN_IOR_read)(void* o, CharVector* d);
typedef void (*MFN_IOR_written)(void* o, CharVector* d);
typedef struct _DIOR {
const Interface* interface;
MFN_IOR_read IOR_read;
MFN_IOR_written IOR_written;
} DIOR;
// Sent when some data is read into the buffer
void PIOR_read (const Proxy* pp, CharVector* d) noexcept;
// Sent when the entire requested block has been written
void PIOR_written (const Proxy* pp, CharVector* d) noexcept;
extern const Interface i_IOR;
//----------------------------------------------------------------------
// Implementation of the above IO interface for file descriptors
typedef void (*MFN_FdIO_attach)(void* o, int fd);
typedef struct _DFdIO {
const Interface* interface;
MFN_FdIO_attach FdIO_attach;
} DFdIO;
// attach to the given file descriptor. The object will not close it.
void PFdIO_attach (const Proxy* pp, int fd) noexcept;
extern const Interface i_FdIO;
//----------------------------------------------------------------------
extern const Factory f_FdIO;
//----------------------------------------------------------------------
#ifdef __cplusplus
} // extern "C"
#endif
|
msharov/casycom | test/fwork.c | <filename>test/fwork.c<gh_stars>1-10
// This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#include "ping.h"
// The simplest way to use casycom is in framework mode, which provides
// an event loop, a standard main, and enables fully object-oriented way
// of managing root-level control flow and data by using an app object.
// The app object is constructed from main and destructed with an atexit
// handler. Additionally, framework mode installs signal handlers and
// converts incoming signals to events delivered to the app object.
//
typedef struct _App {
Proxy pingp;
unsigned npings;
} App;
// App object constructor. Note the naming convention, used in lieu of C++ class scope
static void* App_create (const Msg* msg UNUSED)
{
// Only one app objects can exist, so use the singleton pattern
static App app = {};
if (!app.pingp.interface) { // use the proxy to detect already initialized case
// Each addressable object must be registered
casycom_register (&f_Ping);
// To create an object, create a proxy object for it
app.pingp = casycom_create_proxy (&i_Ping, oid_App);
}
return &app;
}
static void App_destroy (void* o UNUSED) {} // Singletons do not need destruction
// Implements the init method of App interface on the App object. Note the naming convention.
static void App_App_init (App* app, argc_t argc UNUSED, argv_t argv UNUSED)
{
// Now the ping object can be accessed using PPing methods
PPing_ping (&app->pingp, 1);
}
// Implements the ping method of the PingR interface. In casycom, all method
// calls are one-way and can not return a value. The design is instead fully
// asynchronous, requiring the use of an event loop. Instead of per-method
// replies, a complete reply interface may be associated with an interface.
// By convention, reply interfaces are postfixed with an R.
//
static void App_PingR_ping (App* app, uint32_t u)
{
LOG ("Ping %u reply received in app; count %u\n", u, ++app->npings);
casycom_quit (EXIT_SUCCESS);
}
// Objects are created using an Factory, containing a list of all
// interfaces implemented by the object. Each interface is associated
// with a dispatch table, containing methods receiving messages for that
// interface. The app must implement at least the App interface.
//
static const DApp d_App_App = {
.interface = &i_App,
DMETHOD (App, App_init)
};
// Here PingR is also implemented to receive Ping replies
//
// (If you forget to implement an interface, but a message for it is sent
// to the object, an assert will fire in debug builds. Release builds will
// crash dereferencing a NULL, because ignoring a message can have serious
// consequences such as user data loss. Such problems must be fixed during
// development. Debug builds contain many other asserts to catch a variety
// of errors, and so should always be used during development)
//
static const DPingR d_App_PingR = {
.interface = &i_PingR,
DMETHOD (App, PingR_ping)
};
// The dtables are then listed in the .dtable field of the factory
static const Factory f_App = {
.create = App_create,
.destroy = App_destroy,
.dtable = { &d_App_App, &d_App_PingR, NULL }
};
// The default main can be generated with a macro taking the app factory
CASYCOM_MAIN (f_App)
|
msharov/casycom | timer.h | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "main.h"
#include <sys/poll.h>
#ifdef __cplusplus
extern "C" {
#endif
//----------------------------------------------------------------------
// Timer protocol constants
enum ETimerWatchCmd {
WATCH_STOP = 0,
WATCH_READ = POLLIN,
WATCH_WRITE = POLLOUT,
WATCH_RDWR = WATCH_READ| WATCH_WRITE,
WATCH_TIMER = POLLMSG,
WATCH_READ_TIMER = WATCH_READ| WATCH_TIMER,
WATCH_WRITE_TIMER = WATCH_WRITE| WATCH_TIMER,
WATCH_RDWR_TIMER = WATCH_RDWR| WATCH_TIMER
};
typedef uint64_t casytimer_t;
enum {
TIMER_MAX = INT64_MAX,
TIMER_NONE = UINT64_MAX
};
//----------------------------------------------------------------------
// PTimer
typedef void (*MFN_Timer_watch)(void* vo, enum ETimerWatchCmd cmd, int fd, casytimer_t timer);
typedef struct _DTimer {
iid_t interface;
MFN_Timer_watch Timer_watch;
} DTimer;
extern const Interface i_Timer;
//----------------------------------------------------------------------
void PTimer_watch (const Proxy* pp, enum ETimerWatchCmd cmd, int fd, casytimer_t timeoutms);
//----------------------------------------------------------------------
// PTimerR
typedef void (*MFN_TimerR_timer)(void* vo, int fd, const Msg* msg);
typedef struct _DTimerR {
iid_t interface;
MFN_TimerR_timer TimerR_timer;
} DTimerR;
extern const Interface i_TimerR;
//----------------------------------------------------------------------
void PTimerR_timer (const Proxy* pp, int fd);
//----------------------------------------------------------------------
extern const Factory f_Timer;
bool Timer_run_timer (int toWait) noexcept;
casytimer_t Timer_now (void) noexcept;
size_t Timer_watch_list_size (void) noexcept;
size_t Timer_watch_list_for_poll (struct pollfd* fds, size_t fdslen, int* timeout) noexcept NONNULL(1);
//----------------------------------------------------------------------
// PTimer inlines
#ifdef __cplusplus
namespace {
#endif
static inline void PTimer_stop (const Proxy* pp)
{ PTimer_watch (pp, WATCH_STOP, -1, TIMER_NONE); }
static inline void PTimer_timer (const Proxy* pp, casytimer_t timeoutms)
{ PTimer_watch (pp, WATCH_TIMER, -1, timeoutms); }
static inline void PTimer_wait_read (const Proxy* pp, int fd)
{ PTimer_watch (pp, WATCH_READ, fd, TIMER_NONE); }
static inline void PTimer_wait_write (const Proxy* pp, int fd)
{ PTimer_watch (pp, WATCH_WRITE, fd, TIMER_NONE); }
static inline void PTimer_wait_rdwr (const Proxy* pp, int fd)
{ PTimer_watch (pp, WATCH_RDWR, fd, TIMER_NONE); }
static inline void PTimer_wait_read_with_timeout (const Proxy* pp, int fd, casytimer_t timeoutms)
{ PTimer_watch (pp, WATCH_READ_TIMER, fd, timeoutms); }
static inline void PTimer_wait_write_with_timeout (const Proxy* pp, int fd, casytimer_t timeoutms)
{ PTimer_watch (pp, WATCH_WRITE_TIMER, fd, timeoutms); }
static inline void PTimer_wait_rdwr_with_timeout (const Proxy* pp, int fd, casytimer_t timeoutms)
{ PTimer_watch (pp, WATCH_RDWR_TIMER, fd, timeoutms); }
#ifdef __cplusplus
} // namespace
} // extern "C"
#endif
|
msharov/casycom | test/ipcom.c | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#include "ping.h"
//----------------------------------------------------------------------
typedef struct _App {
Proxy pingp;
unsigned npings;
Proxy externp;
pid_t server_pid;
} App;
//----------------------------------------------------------------------
// It is easy to connect to and to create object servers with casycom.
// ipcom illustrates the three common methods of doing so:
// App_client demonstrates how to connect to an object server.
static void App_client (App* app);
// App_server demonstrates how to create an object server.
static void App_server (App* app);
// App_pipe demonstrates how to create an object server on a socket pipe.
static void App_pipe (App* app);
// App_fork_and_pipe launches object server and connects to it
// using a socketpair pipe. This can be used for private servers,
// but here it is just to make running the automated test easy.
static void App_fork_and_pipe (App* app);
// When you run an object server, you must specify a list of interfaces
// it is capable of instantiating. In this example, the only interface
// exported is i_Ping (see ping.h). The client side sends a NULL export
// list when it only imports interfaces.
static const iid_t eil_Ping[] = { &i_Ping, NULL };
// Object servers can be run on a UNIX socket or a TCP port. ipcom shows
// the UNIX socket version. These sockets are created in system standard
// locations; typically /run for root processes or /run/user/<uid> for
// processes launched by the user. If you also implement systemd socket
// activation (see below), any other sockets can be used.
static const char c_IPCOM_socket_name[] = "ipcom.socket";
//----------------------------------------------------------------------
// Singleton App, like in the fwork example
static void* App_create (const Msg* msg UNUSED)
{ static App o = {}; return &o; }
static void App_destroy (void* p UNUSED) {}
static void App_App_init (App* app, argc_t argc, argv_t argv)
{
// Process command line arguments to determine mode of operation
enum {
mode_Test, // Fork and send commands through a socket pair
mode_client, // Connect to c_IPCOM_socket_name
mode_server, // Listen at c_IPCOM_socket_name
mode_pipe // Connect to socket on stdin
} mode = mode_Test;
for (int opt; 0 < (opt = getopt (argc, argv, "cspd"));) {
if (opt == 'c')
mode = mode_client;
else if (opt == 's')
mode = mode_server;
else if (opt == 'p')
mode = mode_pipe;
else if (opt == 'd')
casycom_enable_debug_output();
else {
LOG ("Usage: ipcom [-csd]\n"
" -c\trun as client only\n"
" -s\trun as server only\n"
" -p\tattach to socket pipe on stdin\n"
" -d\tenable debug tracing\n");
exit (EXIT_SUCCESS);
}
}
// Communication between processes requires the use of the Extern
// interface and auxillary factories for creating passthrough local
// objects representing both the remote and local addressable objects.
//
// The client side creates the Extern object on an fd connected to
// the server socket and supplies the list of imported interfaces.
// The imported object types can then be transparently created in
// the same manner local objects are.
//
// Both sides need to start by enabling the externs functionality:
casycom_enable_externs();
switch (mode) {
default: App_fork_and_pipe (app); break;
case mode_client: App_client (app); break;
case mode_server: App_server (app); break;
case mode_pipe: App_pipe (app); break;
}
}
static void App_fork_and_pipe (App* app)
{
// To simplify this test program, use the same executable for both
// client and server, forking, and communicating through a socket pair
int socks[2];
if (0 > socketpair (PF_LOCAL, SOCK_STREAM| SOCK_NONBLOCK, 0, socks))
return casycom_error ("socketpair: %s", strerror(errno));
int fr = fork();
if (fr < 0)
return casycom_error ("fork: %s", strerror(errno));
if (fr == 0) { // Server side
close (socks[0]);
dup2 (socks[1], STDIN_FILENO);
App_pipe (app);
} else { // Client side
app->server_pid = fr;
app->externp = casycom_create_proxy (&i_Extern, oid_App);
close (socks[1]);
// List interfaces that can be accessed from outside.
// On the client side, Ping is imported and no interfaces are exported.
PExtern_open (&app->externp, socks[0], EXTERN_CLIENT, eil_Ping, NULL);
}
}
static void App_client (App* app)
{
// Clients create Extern objects connected to a specific socket
app->externp = casycom_create_proxy (&i_Extern, oid_App);
//
// connect_user_local connects to the named UNIX socket in the user's runtime
// directory (typically /run/user/<uid>). There are also connect_system_local
// for connecting to system services, and methods for connecting to TCP services,
// connect_ip4, connect_local_ip4, etc. See xcom.h.
//
if (0 > PExtern_connect_user_local (&app->externp, c_IPCOM_socket_name, eil_Ping))
// Connect and Bind calls connect or bind immediately, and so can return errors here
casycom_error ("Extern_connect_user_local: %s", strerror(errno));
// Not launching the server, so disable pid checks
app->server_pid = getpid();
}
static void App_server (App* app)
{
// When writing a server, it is recommended to use the ExternServer
// object to manage the sockets being listened to. It will create
// Extern objects for each accepted connection. For the purpose of
// this example, only one socket is listened on, but additional
// ExternServer objects can be created to serve on more sockets.
//
casycom_register (&f_ExternServer);
casycom_register (&f_Ping);
app->externp = casycom_create_proxy (&i_ExternServer, oid_App);
//
// For flexibility it is recommended to implement systemd socket activation.
// Doing so is very simple; sd_listen_fds returns the number of fds passed to
// the process by systemd. The fds start at SD_LISTEN_FDS_START. To keep the
// example simple, only the first one is used; create more ExternServer objects
// to listen on more than one socket.
//
if (sd_listen_fds())
PExternServer_open (&app->externp, SD_LISTEN_FDS_START+0, eil_Ping, true);
else { // If no sockets were passed from systemd, create one manually
// Use bind_user_local to create the socket in XDG_RUNTIME_DIR,
// the standard location for sockets of user services.
// See other bind variants in xsrv.h.
if (0 > PExternServer_bind_user_local (&app->externp, c_IPCOM_socket_name, eil_Ping))
casycom_error ("ExternServer_bind_user_local: %s", strerror(errno));
}
}
static void App_pipe (App* app)
{
// When a private object server is needed, it can be launched with
// PExtern_LaunchPipe and will communicate on only one connection,
// the socket on stdin. In this case, ExternServer is not needed
// and only one Extern object is created.
casycom_register (&f_Ping);
app->externp = casycom_create_proxy (&i_Extern, oid_App);
PExtern_open (&app->externp, STDIN_FILENO, EXTERN_SERVER, NULL, eil_Ping);
}
// When a client connects, ExternServer will forward the ExternR_connected message
// here. This is the appropriate place to check that all the imports are satisfied,
// authenticate the connection (if using a UNIX socket), and create objects.
//
static void App_ExternR_connected (App* app, const ExternInfo* einfo)
{
// Both directly connected Extern objects and ExternServer objects send this reply.
if (!app->server_pid)
return; // log only the client side
// ExternInfo contains the list of interfaces available on this connection, so
// here is the right place to check that the expected interfaces can be created.
if (einfo->interfaces.size < 1 || einfo->interfaces.d[0] != &i_Ping) {
casycom_error ("Connected to server that does not support the Ping interface");
return;
}
LOG ("Connected to server. Imported %zu interface: %s\n", einfo->interfaces.size, einfo->interfaces.d[0]->name);
// ExternInfo can be obtained outside this function with casycom_extern_info
// using the Extern object oid, or with casycom_extern_object_info, using the
// oid of the COMRelay connecting an object to an Extern object (the COMRelay
// sends the messages originating from a remote client, so the served object
// constructor receives a message from it). The ExternInfo also specifies
// whether the connection is a UNIX socket (allowing passing fds and credentials),
// and client process credentials, if available. This information may be
// useful for choosing file transmission mode, or for authentication.
//
// To create a remote object, create a proxy object for it
// (This is exactly the same as accessing a local object)
app->pingp = casycom_create_proxy (&i_Ping, oid_App);
// ... which can then be accessed through the proxy methods.
PPing_ping (&app->pingp, 1);
}
// The ping replies are received exactly the same way as from a local
// object. But now the object resides in the server process and the
// message is read from the socket.
static void App_PingR_ping (App* app, uint32_t u)
{
LOG ("Ping %u reply received in app; count %u\n", u, ++app->npings);
casycom_quit (EXIT_SUCCESS);
}
static const DApp d_App_App = {
.interface = &i_App,
DMETHOD (App, App_init)
};
static const DPingR d_App_PingR = {
.interface = &i_PingR,
DMETHOD (App, PingR_ping)
};
static const DExternR d_App_ExternR = {
.interface = &i_ExternR,
DMETHOD (App, ExternR_connected)
};
static const Factory f_App = {
.create = App_create,
.destroy = App_destroy,
.dtable = { &d_App_App, &d_App_PingR, &d_App_ExternR, NULL }
};
CASYCOM_MAIN (f_App)
|
msharov/casycom | app.c | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#include "app.h"
//----------------------------------------------------------------------
// PApp
enum {
method_App_init,
method_App_signal
};
void PApp_init (const Proxy* pp, argc_t argc, argv_t argv)
{
Msg* msg = casymsg_begin (pp, method_App_init, 12);
WStm os = casymsg_write (msg);
casystm_write_ptr (&os, argv);
casystm_write_uint32 (&os, argc);
casymsg_end (msg);
}
void PApp_signal (const Proxy* pp, unsigned sig, pid_t child_pid, int child_status)
{
Msg* msg = casymsg_begin (pp, method_App_signal, 12);
WStm os = casymsg_write (msg);
casystm_write_uint32 (&os, sig);
casystm_write_uint32 (&os, child_pid);
casystm_write_int32 (&os, child_status);
casymsg_end (msg);
}
static void PApp_dispatch (const DApp* dtable, void* o, const Msg* msg)
{
if (msg->imethod == method_App_init) {
RStm is = casymsg_read (msg);
argv_t argv = casystm_read_ptr (&is);
argc_t argc = casystm_read_uint32 (&is);
if (dtable->App_init)
dtable->App_init (o, argc, argv);
} else if (msg->imethod == method_App_signal) {
RStm is = casymsg_read (msg);
unsigned sig = casystm_read_uint32 (&is);
pid_t child_pid = casystm_read_uint32 (&is);
int child_status = casystm_read_int32 (&is);
if (dtable->App_signal)
dtable->App_signal (o, sig, child_pid, child_status);
} else
casymsg_default_dispatch (dtable, o, msg);
}
const Interface i_App = {
.dispatch = PApp_dispatch,
.name = "App",
.method = { "init\0xu", "signal\0uui", NULL }
};
|
msharov/casycom | vector.h | <gh_stars>1-10
// This file is part of the casycom project
//
// Copyright (c) 2017 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "config.h"
typedef int (*vector_compare_fn_t)(const void*, const void*);
typedef struct _CharVector {
char* d;
size_t size;
size_t allocated;
size_t elsize;
} CharVector;
// Declares a vector for the given type.
// Use the VECTOR macro to instantiate it. Fields are marked const to
// ensure only the vector_ functions modify it.
#define DECLARE_VECTOR_TYPE(name,type) \
typedef struct _##name { \
type* const d; \
const size_t size; \
const size_t allocated; \
const size_t elsize; \
} name
#define VECTOR_INIT(vtype) { .elsize = sizeof(*(((vtype*)NULL)->d)) }
#define VECTOR(vtype,name) vtype name = VECTOR_INIT(vtype)
#define VECTOR_MEMBER_INIT(vtype,name) vector_init(&(name), sizeof(*(((vtype*)NULL)->d)))
#define vector_begin(v) (v)->d
#define vector_end(v) ((v)->d+(v)->size)
#define vector_foreach(vtype,p,v) for (vtype *p = vector_begin(&(v)), *p##end = vector_end(&(v)); p < p##end; ++p)
#define vector_p2i(v,p) ((p)-vector_begin(v))
void vector_reserve (void* v, size_t sz) noexcept NONNULL();
void vector_deallocate (void* v) noexcept NONNULL();
void vector_insert (void* vv, size_t ip, const void* e) noexcept NONNULL();
void vector_insert_n (void* v, size_t ip, const void* e, size_t esz) noexcept NONNULL();
void* vector_emplace (void* vv, size_t ip) noexcept NONNULL();
void* vector_emplace_n (void* vv, size_t ip, size_t n) noexcept NONNULL();
void vector_erase_n (void* v, size_t ep, size_t n) noexcept NONNULL();
void vector_swap (void* v1, void* v2) noexcept NONNULL();
size_t vector_lower_bound (const void* vv, vector_compare_fn_t cmp, const void* e) noexcept NONNULL();
size_t vector_upper_bound (const void* vv, vector_compare_fn_t cmp, const void* e) noexcept NONNULL();
void vector_copy (void* vv1, const void* vv2) noexcept NONNULL();
#ifdef __cplusplus
namespace {
#endif
static inline NONNULL() void vector_init (void* vv, size_t elsz) {
CharVector* v = vv;
v->d = NULL;
v->size = 0;
v->allocated = 0;
v->elsize = elsz;
}
static inline NONNULL() void vector_erase (void* v, size_t ep)
{ vector_erase_n (v, ep, 1); }
static inline NONNULL() void vector_push_back (void* vv, const void* e)
{ CharVector* v = vv; vector_insert (vv, v->size, e); }
static inline NONNULL() void vector_append_n (void* vv, const void* e, size_t n)
{ CharVector* v = vv; vector_insert_n (vv, v->size, e, n); }
static inline NONNULL() void* vector_emplace_back (void* vv)
{ CharVector* v = vv; return vector_emplace (vv, v->size); }
static inline NONNULL() void vector_pop_back (void* vv)
{ CharVector* v = vv; vector_erase (vv, v->size-1); }
static inline NONNULL() void vector_clear (void* vv)
{ CharVector* v = vv; v->size = 0; }
static inline NONNULL() void vector_link (void* vv, const void* e, size_t n) {
CharVector* v = vv;
assert (!v->d && "This vector is already linked to something. Unlink or deallocate first.");
v->d = (void*) e; v->size = n;
}
static inline NONNULL() void vector_unlink (void* vv)
{ CharVector* v = vv; v->d = NULL; v->size = v->allocated = 0; }
static inline NONNULL() void vector_detach (void* vv)
{ vector_unlink (vv); }
static inline NONNULL() void vector_attach (void* vv, void* e, size_t n) {
vector_link (vv, e, n);
CharVector* v = vv;
v->allocated = v->size;
}
static inline NONNULL() void vector_resize (void* vv, size_t sz) {
CharVector* v = vv;
vector_reserve (v, sz);
v->size = sz;
}
static inline NONNULL() size_t vector_insert_sorted (void* vv, vector_compare_fn_t cmp, const void* e) {
size_t ip = vector_upper_bound (vv, cmp, e);
vector_insert (vv, ip, e);
return ip;
}
static inline NONNULL() void vector_sort (void* vv, vector_compare_fn_t cmp)
{ CharVector* v = vv; qsort (v->d, v->size, v->elsize, cmp); }
#ifdef __cplusplus
} // namespace
#endif
//----------------------------------------------------------------------
// This template macro generates ctor, dtor, erase_n, and clear for
// an object vector type containing objects with otype_ctor and otype_dtor
// functions defined.
#define IMPLEMENT_OBJECT_VECTOR_CTOR_DTOR(scope,vtype,otype)\
scope void vtype##_ctor (vtype* v) \
{ VECTOR_MEMBER_INIT (vtype, *v); } \
scope void vtype##_erase_n (vtype* v, size_t ep, size_t n)\
{ \
for (size_t i = ep; i < ep+n; ++i) \
otype##_dtor (&v->d[i]); \
vector_erase_n (v, ep, n); \
} \
scope void vtype##_clear (vtype* v) \
{ vtype##_erase_n (v, 0, v->size); }\
scope void vtype##_dtor (vtype* v) \
{ \
vtype##_clear (v); \
vector_deallocate (v); \
}
// Declarations for the generated functions, if needed
#define DECLARE_OBJECT_VECTOR_CTOR_DTOR(vtype)\
void vtype##_ctor (vtype* v); \
void vtype##_erase_n (vtype* v, size_t ep, size_t n);\
void vtype##_clear (vtype* v); \
void vtype##_dtor (vtype* v)
|
msharov/casycom | msg.c | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#include "main.h"
#include "vector.h"
Msg* casymsg_begin (const Proxy* pp, uint32_t imethod, uint32_t sz)
{
Msg* msg = xalloc (sizeof(Msg));
msg->h = *pp;
msg->imethod = imethod;
msg->fdoffset = NO_FD_IN_MESSAGE;
if ((msg->size = sz))
msg->body = xalloc (ceilg (sz, MESSAGE_BODY_ALIGNMENT));
return msg;
}
void casymsg_from_vector (const Proxy* pp, uint32_t imethod, void* body)
{
Msg* msg = casymsg_begin (pp, imethod, 0);
WStm os = casymsg_write (msg);
CharVector* vbody = body;
size_t asz = ceilg (vbody->size * vbody->elsize, MESSAGE_BODY_ALIGNMENT);
vector_reserve (vbody, divide_ceil (asz,vbody->elsize));
msg->body = vbody->d;
msg->size = vbody->size * vbody->elsize;
vector_detach (vbody);
casystm_write_skip_to_end (&os);
casymsg_end (msg);
}
void casymsg_forward (const Proxy* pp, Msg* msg)
{
Msg* fwm = casymsg_begin (pp, msg->imethod, 0);
fwm->h.interface = msg->h.interface;
fwm->body = msg->body;
fwm->size = msg->size;
fwm->extid = msg->extid;
fwm->fdoffset = msg->fdoffset;
msg->size = 0;
msg->body = NULL;
casymsg_end (fwm);
}
//----------------------------------------------------------------------
uint32_t casyiface_count_methods (iid_t iid)
{
uint32_t n = 0;
if (!iid) return n;
for (const char* const* i = iid->method; *i; ++i)
++n;
return n;
}
static size_t casymsg_sigelement_size (char c)
{
static const struct { char sym; uint8_t sz; } syms[] =
{{'y',1},{'b',1},{'n',2},{'q',2},{'i',4},{'u',4},{'h',4},{'x',8},{'t',8}};
for (unsigned i = 0; i < ARRAY_SIZE(syms); ++i)
if (syms[i].sym == c)
return syms[i].sz;
return 0;
}
static const char* casymsg_skip_one_sigelement (const char* sig)
{
unsigned parens = 0;
do {
if (*sig == '(')
++parens;
else if (*sig == ')')
--parens;
} while (*++sig && parens);
return sig;
}
static size_t casymsg_sig_alignment (const char* sig)
{
size_t sz = casymsg_sigelement_size (*sig);
if (sz)
return sz; // fixed size elements are aligned to size
if (*sig == 'a' || *sig == 's')
return 4;
else if (*sig == '(') {
for (const char* elend = casymsg_skip_one_sigelement(sig++)-1; sig < elend; sig = casymsg_skip_one_sigelement(sig)) {
size_t elal = casymsg_sig_alignment (sig);
if (elal > sz)
sz = elal;
}
} else
assert (!"Invalid signature element while determining alignment");
return sz;
}
static size_t casymsg_validate_read_align (RStm* buf, size_t sz, size_t grain)
{
size_t alignsz = ceilg(sz,grain)-sz;
if (!casystm_can_read (buf, alignsz))
return 0;
casystm_read_skip (buf, alignsz);
return alignsz;
}
static size_t casymsg_validate_sigelement (const char** sig, RStm* buf)
{
size_t sz = casymsg_sigelement_size (**sig);
assert ((sz || **sig == '(' || **sig == 'a' || **sig == 's') && "invalid character in method signature");
if (sz) { // Zero size is returned for compound elements, which are structs, arrays, or strings.
++*sig; // single char element
if (!casystm_can_read (buf, sz) || !casystm_is_read_aligned (buf, sz))
return 0; // invalid data in buf
casystm_read_skip (buf, sz);
} else if (**sig == '(') { // Structs. Scan forward until ')'.
size_t sal = casymsg_sig_alignment (*sig);
++*sig;
sz += casymsg_validate_read_align (buf, sz, sal);
for (size_t ssz; **sig && **sig != ')'; sz += ssz)
if (!(ssz = casymsg_validate_sigelement (sig, buf))) // invalid data in buf, return 0 as error
return 0;
sz += casymsg_validate_read_align (buf, sz, sal);
} else if (**sig == 'a' || **sig == 's') { // Arrays and strings
if (!casystm_can_read (buf, 4))
return 0;
uint32_t nel = casystm_read_uint32 (buf); // number of elements in the array
sz += 4;
size_t elsz = 1, elal = 4; // strings are equivalent to "ac"
if (*((*sig)++) == 'a') { // arrays are followed by an element sig "a(uqq)"
elsz = casymsg_sigelement_size (**sig);
elal = casymsg_sig_alignment (*sig);
if (elal < 4)
elal = 4;
}
if (elsz) { // optimization for the common case of fixed-element array
casystm_read_align (buf, elal);
elsz *= nel;
if (!casystm_can_read (buf, elsz))
return 0;
casystm_read_skip (buf, elsz);
sz += elsz;
} else {
for (uint32_t i = 0; i < nel; ++i, sz += elsz) { // read each element
const char* elsig = *sig; // for each element, pass in the same element sig
if (!(elsz = casymsg_validate_sigelement (&elsig, buf))) // invalid data in buf, return 0 as error
return 0;
}
}
if ((*sig)[-1] == 'a') // skip the array element sig for arrays; strings do not have one
*sig = casymsg_skip_one_sigelement (*sig);
else { // for strings, verify zero-termination
casystm_unread (buf, 1);
if (casystm_read_uint8 (buf))
return 0;
}
sz += casymsg_validate_read_align (buf, sz, elal);
}
return sz;
}
size_t casymsg_validate_signature (const Msg* msg)
{
RStm is = casymsg_read(msg);
size_t sz = 0;
for (const char* sig = casymsg_signature(msg); *sig;) {
size_t elsz = casymsg_validate_sigelement (&sig, &is);
if (!elsz)
return 0;
sz += elsz;
}
return sz;
}
|
msharov/casycom | main.h | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "msg.h"
typedef struct _Factory {
void* (*create)(const Msg* msg);
void (*destroy)(void* o);
void (*object_destroyed)(void* o, oid_t oid);
bool (*error)(void* o, oid_t eoid, const char* msg);
const void* const dtable[];
} Factory;
#ifdef __cplusplus
extern "C" {
#endif
void casycom_init (void) noexcept;
void casycom_reset (void) noexcept;
void casycom_framework_init (const Factory* oapp, argc_t argc, argv_t argv) noexcept NONNULL(1);
int casycom_main (void) noexcept;
void casycom_quit (int exitCode) noexcept;
bool casycom_is_quitting (void) noexcept;
bool casycom_is_failed (void) noexcept;
int casycom_exit_code (void) noexcept;
bool casycom_loop_once (void) noexcept;
typedef void* (pfn_object_init)(const Msg* msg);
void casycom_register (const Factory* o) noexcept NONNULL();
void casycom_register_default (const Factory* o) noexcept;
void* casycom_create_object (const iid_t iid) noexcept NONNULL();
iid_t casycom_interface_by_name (const char* iname) noexcept NONNULL();
Proxy casycom_create_proxy (iid_t iid, oid_t src) noexcept;
Proxy casycom_create_proxy_to (iid_t iid, oid_t src, oid_t dest) noexcept;
void casycom_destroy_proxy (Proxy* pp) noexcept NONNULL();
void casycom_error (const char* fmt, ...) noexcept PRINTFARGS(1,2);
bool casycom_forward_error (oid_t oid, oid_t eoid) noexcept;
void casycom_mark_unused (const void* o) noexcept NONNULL();
oid_t casycom_oid_of_object (const void* o) noexcept NONNULL();
#ifndef NDEBUG
extern bool casycom_debug_msg_trace;
#define DEBUG_MSG_TRACE casycom_debug_msg_trace
#define DEBUG_PRINTF(...) do { if (DEBUG_MSG_TRACE) { fflush (stderr); printf (__VA_ARGS__); fflush (stdout); } } while (false)
#else
#define DEBUG_MSG_TRACE false
#define DEBUG_PRINTF(...) do {} while (false)
#endif
void casycom_debug_message_dump (const Msg* msg) noexcept;
void casycom_debug_dump_link_table (void) noexcept;
#ifdef __cplusplus
namespace {
#endif
static inline Proxy casycom_create_reply_proxy (iid_t iid, const Msg* msg)
{ return casycom_create_proxy_to (iid, msg->h.dest, msg->h.src); }
#ifndef NDEBUG
static inline void casycom_enable_debug_output (void)
{ casycom_debug_msg_trace = true; }
static inline void casycom_disable_debug_output (void)
{ casycom_debug_msg_trace = false; }
#else
static inline void casycom_enable_debug_output (void) {}
static inline void casycom_disable_debug_output (void) {}
#endif
#ifdef __cplusplus
} // namespace
} // extern "C"
#endif
|
msharov/casycom | xsrv.c | <gh_stars>1-10
// This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#include "xsrv.h"
#include "timer.h"
#include <sys/stat.h>
#include <sys/un.h>
#include <paths.h>
#include <fcntl.h>
//{{{ PExternServer ----------------------------------------------------
enum {
method_ExternServer_open,
method_ExternServer_close
};
void PExternServer_open (const Proxy* pp, int fd, const iid_t* exported_interfaces, bool close_when_empty)
{
assert (pp->interface == &i_ExternServer && "this proxy is for a different interface");
Msg* msg = casymsg_begin (pp, method_ExternServer_open, 8+4+1);
WStm os = casymsg_write (msg);
casystm_write_ptr (&os, exported_interfaces);
casystm_write_int32 (&os, fd);
casystm_write_bool (&os, close_when_empty);
casymsg_end (msg);
}
void PExternServer_close (const Proxy* pp)
{
assert (pp->interface == &i_ExternServer && "this proxy is for a different interface");
casymsg_end (casymsg_begin (pp, method_ExternServer_close, 0));
}
static void PExternServer_dispatch (const DExternServer* dtable, void* o, const Msg* msg)
{
assert (dtable->interface == &i_ExternServer && "dispatch given dtable for a different interface");
if (msg->imethod == method_ExternServer_open) {
RStm is = casymsg_read (msg);
const iid_t* exported_interfaces = casystm_read_ptr (&is);
int fd = casystm_read_int32 (&is);
bool close_when_empty = casystm_read_bool (&is);
dtable->ExternServer_open (o, fd, exported_interfaces, close_when_empty);
} else if (msg->imethod == method_ExternServer_close)
dtable->ExternServer_close (o);
else
casymsg_default_dispatch (dtable, o, msg);
}
const Interface i_ExternServer = {
.name = "ExternServer",
.dispatch = PExternServer_dispatch,
.method = { "open\0xib", "close\0", NULL }
};
//}}}-------------------------------------------------------------------
//{{{ PExternServer_bind
typedef struct _LocalSocketPath {
char* path;
int fd;
} LocalSocketPath;
DECLARE_VECTOR_TYPE (LocalSocketPathVector, LocalSocketPath);
// Local sockets must be removed manually after closing
static void ExternServer_register_local_name (int fd, const char* path)
{
static VECTOR (LocalSocketPathVector, pathvec);
if (path) {
LocalSocketPath* p = vector_emplace_back (&pathvec);
p->path = strdup (path);
p->fd = fd;
} else {
for (size_t i = 0; i < pathvec.size; ++i) {
if (pathvec.d[i].fd == fd) {
unlink (pathvec.d[i].path);
free (pathvec.d[i].path);
vector_erase (&pathvec, i--);
}
}
}
}
/// create server socket bound to the given address
int PExternServer_bind (const Proxy* pp, const struct sockaddr* addr, socklen_t addrlen, const iid_t* exported_interfaces)
{
int fd = socket (addr->sa_family, SOCK_STREAM| SOCK_NONBLOCK| SOCK_CLOEXEC, IPPROTO_IP);
if (fd < 0)
return fd;
if (0 > bind (fd, addr, addrlen) && errno != EINPROGRESS) {
DEBUG_PRINTF ("[E] Failed to bind to socket: %s\n", strerror(errno));
close (fd);
return -1;
}
if (0 > listen (fd, SOMAXCONN)) {
DEBUG_PRINTF ("[E] Failed to listen to socket: %s\n", strerror(errno));
close (fd);
return -1;
}
if (addr->sa_family == PF_LOCAL)
ExternServer_register_local_name (fd, ((const struct sockaddr_un*)addr)->sun_path);
PExternServer_open (pp, fd, exported_interfaces, false);
return fd;
}
/// create local socket with given path
int PExternServer_bind_local (const Proxy* pp, const char* path, const iid_t* exported_interfaces)
{
struct sockaddr_un addr;
addr.sun_family = PF_LOCAL;
if ((int) ARRAY_SIZE(addr.sun_path) <= snprintf (ARRAY_BLOCK(addr.sun_path), "%s", path)) {
errno = ENAMETOOLONG;
return -1;
}
DEBUG_PRINTF ("[X] Creating server socket %s\n", addr.sun_path);
int fd = PExternServer_bind (pp, (const struct sockaddr*) &addr, sizeof(addr), exported_interfaces);
if (0 > chmod (addr.sun_path, DEFFILEMODE))
DEBUG_PRINTF ("[E] Failed to change socket permissions: %s\n", strerror(errno));
return fd;
}
/// create local socket of the given name in the system standard location for such
int PExternServer_bind_system_local (const Proxy* pp, const char* sockname, const iid_t* exported_interfaces)
{
struct sockaddr_un addr;
addr.sun_family = PF_LOCAL;
if ((int) ARRAY_SIZE(addr.sun_path) <= snprintf (ARRAY_BLOCK(addr.sun_path), _PATH_VARRUN "%s", sockname)) {
errno = ENAMETOOLONG;
return -1;
}
DEBUG_PRINTF ("[X] Creating server socket %s\n", addr.sun_path);
int fd = PExternServer_bind (pp, (const struct sockaddr*) &addr, sizeof(addr), exported_interfaces);
if (0 > chmod (addr.sun_path, DEFFILEMODE))
DEBUG_PRINTF ("[E] Failed to change socket permissions: %s\n", strerror(errno));
return fd;
}
/// create local socket of the given name in the user standard location for such
int PExternServer_bind_user_local (const Proxy* pp, const char* sockname, const iid_t* exported_interfaces)
{
struct sockaddr_un addr;
addr.sun_family = PF_LOCAL;
const char* runtimeDir = getenv ("XDG_RUNTIME_DIR");
if (!runtimeDir)
runtimeDir = _PATH_TMP;
if ((int) ARRAY_SIZE(addr.sun_path) <= snprintf (ARRAY_BLOCK(addr.sun_path), "%s/%s", runtimeDir, sockname)) {
errno = ENAMETOOLONG;
return -1;
}
DEBUG_PRINTF ("[X] Creating server socket %s\n", addr.sun_path);
int fd = PExternServer_bind (pp, (const struct sockaddr*) &addr, sizeof(addr), exported_interfaces);
if (0 > chmod (addr.sun_path, S_IRUSR| S_IWUSR))
DEBUG_PRINTF ("[E] Failed to change socket permissions: %s\n", strerror(errno));
return fd;
}
//}}}-------------------------------------------------------------------
//{{{ ExternServer
DECLARE_VECTOR_TYPE (ProxyVector, Proxy);
typedef struct _ExternServer {
Proxy reply;
int fd;
Proxy timer;
bool close_when_empty;
const iid_t* exported_interfaces;
ProxyVector pconn;
} ExternServer;
static void* ExternServer_create (const Msg* msg)
{
ExternServer* o = xalloc (sizeof(ExternServer));
o->reply = casycom_create_reply_proxy (&i_ExternR, msg);
o->fd = -1;
o->timer = casycom_create_proxy (&i_Timer, o->reply.src);
VECTOR_MEMBER_INIT (ProxyVector, o->pconn);
return o;
}
static void ExternServer_destroy (void* vo)
{
ExternServer* o = vo;
ExternServer_register_local_name (o->fd, NULL);
free (o);
}
static bool ExternServer_error (void* vo, oid_t eoid, const char* msg)
{
ExternServer* o = vo;
for (size_t i = 0; i < o->pconn.size; ++i) {
if (o->pconn.d[i].dest == eoid) {
casycom_log (LOG_ERR, "%s", msg);
return true; // error in accepted socket. Handle by logging the error and removing record in object_destroyed.
}
}
return false;
}
static void ExternServer_object_destroyed (void* vo, oid_t oid)
{
DEBUG_PRINTF ("[X] Client connection %hu dropped\n", oid);
ExternServer* o = vo;
for (size_t i = 0; i < o->pconn.size; ++i) {
if (o->pconn.d[i].dest == oid) {
casycom_destroy_proxy (&o->pconn.d[i]);
vector_erase (&o->pconn, i--);
}
}
if (!o->pconn.size && o->close_when_empty)
casycom_mark_unused (o);
}
static void ExternServer_TimerR_timer (ExternServer* o, int fd, const Msg* msg UNUSED)
{
assert (fd == o->fd);
for (int cfd; 0 <= (cfd = accept (fd, NULL, NULL));) {
Proxy* pconn = vector_emplace_back (&o->pconn);
*pconn = casycom_create_proxy (&i_Extern, o->reply.src);
DEBUG_PRINTF ("[X] Client connection accepted on fd %d\n", cfd);
PExtern_open (pconn, cfd, EXTERN_SERVER, NULL, o->exported_interfaces);
}
if (errno == EAGAIN) {
DEBUG_PRINTF ("[X] Resuming wait on fd %d\n", fd);
PTimer_wait_read (&o->timer, fd);
} else {
DEBUG_PRINTF ("[X] Accept failed with error %s\n", strerror(errno));
casycom_error ("accept: %s", strerror(errno));
casycom_mark_unused (o);
}
}
static void ExternServer_ExternServer_open (ExternServer* o, int fd, const iid_t* exported_interfaces, bool close_when_empty)
{
assert (o->fd == -1 && "each ExternServer instance can only listen to one socket");
o->fd = fd;
o->exported_interfaces = exported_interfaces;
o->close_when_empty = close_when_empty;
fcntl (o->fd, F_SETFL, O_NONBLOCK| fcntl (o->fd, F_GETFL));
ExternServer_TimerR_timer (o, fd, NULL);
}
static void ExternServer_ExternServer_close (ExternServer* o)
{
casycom_mark_unused (o);
}
static void ExternServer_ExternR_connected (ExternServer* o, const ExternInfo* einfo)
{
PExternR_connected (&o->reply, einfo);
}
static const DExternServer d_ExternServer_ExternServer = {
.interface = &i_ExternServer,
DMETHOD (ExternServer, ExternServer_open),
DMETHOD (ExternServer, ExternServer_close)
};
static const DTimerR d_ExternServer_TimerR = {
.interface = &i_TimerR,
DMETHOD (ExternServer, TimerR_timer)
};
static const DExternR d_ExternServer_ExternR = {
.interface = &i_ExternR,
DMETHOD (ExternServer, ExternR_connected)
};
const Factory f_ExternServer = {
.create = ExternServer_create,
.destroy = ExternServer_destroy,
.error = ExternServer_error,
.object_destroyed = ExternServer_object_destroyed,
.dtable = {
&d_ExternServer_ExternServer,
&d_ExternServer_TimerR,
&d_ExternServer_ExternR,
NULL
}
};
//}}}-------------------------------------------------------------------
|
msharov/casycom | xcom.c | <reponame>msharov/casycom
// This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#include "xcom.h"
#include "timer.h"
#include <fcntl.h>
#include <sys/un.h>
#include <paths.h>
//{{{ COM interface ----------------------------------------------------
typedef void (*MFN_COM_error)(void* vo, const char* error, const Msg* msg);
typedef void (*MFN_COM_export)(void* vo, const char* elist, const Msg* msg);
typedef void (*MFN_COM_delete)(void* vo, const Msg* msg);
typedef struct _DCOM {
iid_t interface;
MFN_COM_error COM_error;
MFN_COM_export COM_export;
MFN_COM_delete COM_delete;
} DCOM;
//}}}-------------------------------------------------------------------
//{{{ PCOM
static void COMRelay_COM_message (void* vo, Msg* msg);
//----------------------------------------------------------------------
enum {
method_COM_error,
method_COM_export,
method_COM_delete
};
static Msg* PCOM_error_message (const Proxy* pp, const char* error)
{
Msg* msg = casymsg_begin (pp, method_COM_error, casystm_size_string(error));
WStm os = casymsg_write (msg);
casystm_write_string (&os, error);
assert (msg->size == casymsg_validate_signature (msg) && "message data does not match method signature");
return msg;
}
static Msg* PCOM_export_message (const Proxy* pp, const char* elist)
{
Msg* msg = casymsg_begin (pp, method_COM_export, casystm_size_string(elist));
WStm os = casymsg_write (msg);
casystm_write_string (&os, elist);
assert (msg->size == casymsg_validate_signature (msg) && "message data does not match method signature");
return msg;
}
static Msg* PCOM_delete_message (const Proxy* pp)
{
Msg* msg = casymsg_begin (pp, method_COM_delete, 0);
assert (msg->size == casymsg_validate_signature (msg) && "message data does not match method signature");
return msg;
}
//----------------------------------------------------------------------
static void PCOM_create_object (const Proxy* pp)
{
casymsg_end (casymsg_begin (pp, method_create_object, 0));
}
static void PCOM_dispatch (const DCOM* dtable, void* o, Msg* msg);
static const Interface i_COM = {
.name = "COM",
.dispatch = PCOM_dispatch,
.method = { "error\0s", "export\0s", "delete\0", NULL }
};
static void PCOM_dispatch (const DCOM* dtable, void* o, Msg* msg)
{
if (msg->h.interface != &i_COM)
COMRelay_COM_message (o, msg);
else if (msg->imethod == method_COM_error) {
RStm is = casymsg_read (msg);
const char* error = casystm_read_string (&is);
dtable->COM_error (o, error, msg);
} else if (msg->imethod == method_COM_export) {
RStm is = casymsg_read (msg);
const char* elist = casystm_read_string (&is);
if (dtable->COM_export)
dtable->COM_export (o, elist, msg);
} else if (msg->imethod == method_COM_delete)
dtable->COM_delete (o, msg);
else
casymsg_default_dispatch (dtable, o, msg);
}
//}}}-------------------------------------------------------------------
//{{{ PExtern
enum {
method_Extern_open,
method_Extern_close
};
void PExtern_open (const Proxy* pp, int fd, enum EExternType atype, const iid_t* imported_interfaces, const iid_t* exported_interfaces)
{
assert (pp->interface == &i_Extern && "this proxy is for a different interface");
Msg* msg = casymsg_begin (pp, method_Extern_open, 4+4+8+8);
WStm os = casymsg_write (msg);
casystm_write_int32 (&os, fd);
casystm_write_uint32 (&os, atype);
casystm_write_ptr (&os, imported_interfaces);
casystm_write_ptr (&os, exported_interfaces);
casymsg_end (msg);
}
void PExtern_close (const Proxy* pp)
{
casymsg_end (casymsg_begin (pp, method_Extern_close, 0));
}
static void PExtern_dispatch (const DExtern* dtable, void* o, const Msg* msg)
{
assert (dtable->interface == &i_Extern && "dispatch given dtable for a different interface");
if (msg->imethod == method_Extern_open) {
RStm is = casymsg_read (msg);
int fd = casystm_read_int32 (&is);
enum EExternType atype = casystm_read_uint32 (&is);
const iid_t* imported_interfaces = casystm_read_ptr (&is);
const iid_t* exported_interfaces = casystm_read_ptr (&is);
dtable->Extern_open (o, fd, atype, imported_interfaces, exported_interfaces);
} else if (msg->imethod == method_Extern_close)
dtable->Extern_close (o);
else
casymsg_default_dispatch (dtable, o, msg);
}
const Interface i_Extern = {
.name = "Extern",
.dispatch = PExtern_dispatch,
.method = { "open\0iuxx", "close\0", NULL }
};
//}}}-------------------------------------------------------------------
//{{{ PExtern_connect
int PExtern_connect (const Proxy* pp, const struct sockaddr* addr, socklen_t addrlen, const iid_t* imported_interfaces)
{
int fd = socket (addr->sa_family, SOCK_STREAM| SOCK_NONBLOCK| SOCK_CLOEXEC, IPPROTO_IP);
if (fd < 0)
return fd;
if (0 > connect (fd, addr, addrlen) && errno != EINPROGRESS && errno != EINTR) {
DEBUG_PRINTF ("[E] Failed to connect to socket: %s\n", strerror(errno));
close (fd);
return -1;
}
PExtern_open (pp, fd, EXTERN_CLIENT, imported_interfaces, NULL);
return fd;
}
/// create local socket with given path
int PExtern_connect_local (const Proxy* pp, const char* path, const iid_t* imported_interfaces)
{
struct sockaddr_un addr;
addr.sun_family = PF_LOCAL;
if (ARRAY_SIZE(addr.sun_path) <= (size_t) snprintf (ARRAY_BLOCK(addr.sun_path), "%s", path)) {
errno = ENAMETOOLONG;
return -1;
}
DEBUG_PRINTF ("[X] connecting to socket %s\n", addr.sun_path);
return PExtern_connect (pp, (const struct sockaddr*) &addr, sizeof(addr), imported_interfaces);
}
/// create local socket of the given name in the system standard location for such
int PExtern_connect_system_local (const Proxy* pp, const char* sockname, const iid_t* imported_interfaces)
{
struct sockaddr_un addr;
addr.sun_family = PF_LOCAL;
if (ARRAY_SIZE(addr.sun_path) <= (size_t) snprintf (ARRAY_BLOCK(addr.sun_path), _PATH_VARRUN "%s", sockname)) {
errno = ENAMETOOLONG;
return -1;
}
DEBUG_PRINTF ("[X] connecting to socket %s\n", addr.sun_path);
return PExtern_connect (pp, (const struct sockaddr*) &addr, sizeof(addr), imported_interfaces);
}
/// create local socket of the given name in the user standard location for such
int PExtern_connect_user_local (const Proxy* pp, const char* sockname, const iid_t* imported_interfaces)
{
struct sockaddr_un addr;
addr.sun_family = PF_LOCAL;
const char* runtimeDir = getenv ("XDG_RUNTIME_DIR");
if (!runtimeDir)
runtimeDir = _PATH_TMP;
if (ARRAY_SIZE(addr.sun_path) <= (size_t) snprintf (ARRAY_BLOCK(addr.sun_path), "%s/%s", runtimeDir, sockname)) {
errno = ENAMETOOLONG;
return -1;
}
DEBUG_PRINTF ("[X] connecting to socket %s\n", addr.sun_path);
return PExtern_connect (pp, (const struct sockaddr*) &addr, sizeof(addr), imported_interfaces);
}
int PExtern_launch_pipe (const Proxy* pp, const char* exe, const char* arg, const iid_t* imported_interfaces)
{
// Check if executable exists before the fork to allow proper error handling
char exepath [PATH_MAX];
const char* exefp = executable_in_path (exe, ARRAY_BLOCK(exepath));
if (!exefp) {
errno = ENOENT;
return -1;
}
// create socket pipe, will be connected to stdin in server
enum { socket_ClientSide, socket_ServerSide, socket_N };
int socks [socket_N];
if (0 > socketpair (PF_LOCAL, SOCK_STREAM| SOCK_NONBLOCK, 0, socks))
return -1;
int fr = fork();
if (fr < 0) {
close (socks[socket_ClientSide]);
close (socks[socket_ServerSide]);
return -1;
}
if (fr == 0) { // Server side
close (socks[socket_ClientSide]);
dup2 (socks[socket_ServerSide], STDIN_FILENO);
execl (exefp, exe, arg, NULL);
// If exec failed, log the error and exit
casycom_log (LOG_ERR, "Error: failed to launch pipe to '%s %s': %s\n", exe, arg, strerror(errno));
casycom_disable_debug_output();
exit (EXIT_FAILURE);
} else { // Client side
close (socks[socket_ServerSide]);
PExtern_open (pp, socks[socket_ClientSide], EXTERN_CLIENT, imported_interfaces, NULL);
}
return socks[0];
}
//}}}-------------------------------------------------------------------
//{{{ PExternR
enum { method_ExternR_connected };
void PExternR_connected (const Proxy* pp, const ExternInfo* einfo)
{
assert (pp->interface == &i_ExternR && "this proxy is for a different interface");
Msg* msg = casymsg_begin (pp, method_ExternR_connected, 8);
WStm os = casymsg_write (msg);
casystm_write_ptr (&os, einfo);
casymsg_end (msg);
}
static void PExternR_dispatch (const DExternR* dtable, void* o, const Msg* msg)
{
assert (dtable->interface == &i_ExternR && "dispatch given dtable for a different interface");
if (msg->imethod == method_ExternR_connected) {
RStm is = casymsg_read (msg);
const ExternInfo* einfo = casystm_read_ptr (&is);
if (dtable->ExternR_connected)
dtable->ExternR_connected (o, einfo);
} else
casymsg_default_dispatch (dtable, o, msg);
}
const Interface i_ExternR = {
.name = "ExternR",
.dispatch = PExternR_dispatch,
.method = { "connected\0x", NULL }
};
//}}}-------------------------------------------------------------------
//{{{ Extern
//----------------------------------------------------------------------
//{{{2 Module data
DECLARE_VECTOR_TYPE (MsgVector, Msg*);
enum { MAX_MSG_HEADER_SIZE = UINT8_MAX-8 };
enum {
extid_COM,
extid_ClientBase = extid_COM, // Set these up to be equal to COMRelay nodeid on the client
extid_ClientLast = extid_ClientBase+oid_Last,
extid_ServerBase = extid_ClientLast+1, // and nodeid + halfrange on the server (32000 is 0x7d00, mostly round number in both bases)
extid_ServerLast = extid_ServerBase+oid_Last
};
typedef struct _ExtMsgHeader {
uint32_t sz; ///< message body size, aligned to c_Msgceilgment
uint16_t extid; ///< Destination node iid
uint8_t fdoffset; ///< Offset to file descriptor in message body, if passing
uint8_t hsz; ///< Full size of header
} ExtMsgHeader;
typedef union _ExtMsgHeaderBuf {
ExtMsgHeader h;
char d [MAX_MSG_HEADER_SIZE];
} ExtMsgHeaderBuf;
typedef struct _COMConn {
Proxy proxy;
uint16_t extid;
} COMConn;
DECLARE_VECTOR_TYPE (COMConnVector, COMConn);
typedef struct _Extern {
Proxy reply;
int fd;
uint32_t outHWritten;
uint32_t outBWritten;
uint32_t inHRead;
uint32_t inBRead;
Msg* inMsg;
const iid_t* exported_interfaces;
const iid_t* all_imported_interfaces;
ExternInfo info;
COMConnVector conns;
MsgVector outgoing;
Proxy timer;
int inLastFd;
ExtMsgHeaderBuf inHBuf;
} Extern;
DECLARE_VECTOR_TYPE (ExternsVector, Extern*);
static VECTOR (ExternsVector, _Extern_externs);
//----------------------------------------------------------------------
static COMConn* Extern_COMConn_by_extid (Extern* o, uint16_t extid);
static bool Extern_is_interface_exported (const Extern* o, iid_t iid);
static bool Extern_is_valid_socket (Extern* o);
static bool Extern_validate_message (Extern* o, Msg* msg);
static bool Extern_validate_message_header (const Extern* o, const ExtMsgHeader* h);
static bool Extern_writing (Extern* o);
static iid_t Extern_lookup_in_msg_interface (const Extern* o);
static uint32_t Extern_lookup_in_msg_method (const Extern* o, const Msg* msg);
static void Extern_Extern_close (Extern* o);
static void Extern_queue_incoming_message (Extern* o, Msg* msg);
static void Extern_queue_outgoing_message (Extern* o, Msg* msg);
static void Extern_reading (Extern* o);
static void Extern_set_credentials_passing (Extern* o, int enable);
static void Extern_TimerR_timer (Extern* o, int fd, const Msg* msg);
//}}}2------------------------------------------------------------------
//{{{2 Interfaces
static void* Extern_create (const Msg* msg)
{
Extern* o = xalloc (sizeof(Extern));
vector_push_back (&_Extern_externs, &o);
o->reply = casycom_create_reply_proxy (&i_ExternR, msg);
o->info.oid = o->reply.src;
o->fd = -1;
o->inLastFd = -1;
o->timer = casycom_create_proxy (&i_Timer, msg->h.dest);
VECTOR_MEMBER_INIT (COMConnVector, o->conns);
VECTOR_MEMBER_INIT (InterfaceVector, o->info.interfaces);
VECTOR_MEMBER_INIT (MsgVector, o->outgoing);
return o;
}
static void Extern_destroy (void* vo)
{
Extern* o = vo;
if (o->fd >= 0) {
close (o->fd);
o->fd = -1;
}
if (o->inLastFd >= 0) {
close (o->inLastFd);
o->inLastFd = -1;
}
casymsg_free (o->inMsg);
for (size_t i = 0; i < o->outgoing.size; ++i)
casymsg_free (o->outgoing.d[i]);
vector_deallocate (&o->outgoing);
vector_deallocate (&o->info.interfaces);
vector_deallocate (&o->conns);
for (size_t ei = 0; ei < _Extern_externs.size; ++ei)
if (_Extern_externs.d[ei] == o)
vector_erase (&_Extern_externs, ei--);
if (!_Extern_externs.size)
vector_deallocate (&_Extern_externs);
xfree (o);
}
static void Extern_Extern_open (Extern* o, int fd, enum EExternType atype, const iid_t* imported_interfaces, const iid_t* exported_interfaces)
{
o->fd = fd;
o->info.is_client = atype == EXTERN_CLIENT;
o->all_imported_interfaces = imported_interfaces; // o->info.interfaces will be set when COM_export message arrives
o->exported_interfaces = exported_interfaces;
if (!Extern_is_valid_socket (o)) {
casycom_error ("incompatible socket type");
return Extern_Extern_close (o);
}
if (o->info.is_unix_socket)
Extern_set_credentials_passing (o, true);
// To complete the handshake, create the list of export interfaces
char exlist[256] = {}, *pexlist = &exlist[0];
for (const iid_t* ei = o->exported_interfaces; ei && *ei; ++ei)
pexlist += sprintf (pexlist, "%s,", (*ei)->name);
assert (pexlist < &exlist[ARRAY_SIZE(exlist)] && "too many exported interfaces");
pexlist[-1] = 0; // Replace last comma
// Send the exported interfaces list in a COM_export message
const Proxy comp = { .interface = &i_COM, .dest = o->info.oid, .src = o->info.oid };
Extern_queue_outgoing_message (o, PCOM_export_message (&comp, exlist));
// Queueing will also initialize the fd timer
}
static void Extern_Extern_close (Extern* o)
{
if (o->fd >= 0) {
close (o->fd);
o->fd = -1;
}
casycom_mark_unused (o);
}
static Extern* Extern_find_by_interface (iid_t iid)
{
for (size_t ei = 0; ei < _Extern_externs.size; ++ei) {
Extern* e = _Extern_externs.d[ei];
for (size_t ii = 0; ii < e->info.interfaces.size; ++ii)
if (e->info.interfaces.d[ii] == iid)
return e;
}
return NULL;
}
static Extern* Extern_find_by_id (oid_t oid)
{
for (size_t ei = 0; ei < _Extern_externs.size; ++ei) {
Extern* e = _Extern_externs.d[ei];
for (size_t ii = 0; ii < e->conns.size; ++ii)
if (e->conns.d[ii].proxy.dest == oid)
return e;
}
return NULL;
}
static void Extern_COM_error (Extern* o, const char* e, const Msg* msg UNUSED)
{
// Error arriving to extid_COM indicates an error in the Extern
// object on the other side, terminating the connection.
casycom_error ("%s", e);
Extern_Extern_close (o);
}
static void Extern_COM_export (Extern* o, const char* ilist, const Msg* msg UNUSED)
{
// The export list arrives during the handshake and contains a
// comma-separated list of interfaces exported by the other side.
vector_clear (&o->info.interfaces); // Changing the list afterwards is also allowed.
for (const char* iname = ilist; iname && *iname; ++ilist) {
if (!*ilist || *ilist == ',') {
// info.interfaces contains iid_ts from all_imported_interfaces that are in ilist
for (const iid_t* iii = o->all_imported_interfaces; iii && *iii; ++iii)
if (0 == strncmp ((*iii)->name, iname, ilist-iname))
vector_push_back (&o->info.interfaces, iii);
iname = ilist;
}
}
// Now that the info.interfaces list is filled, the handshake is complete
PExternR_connected (&o->reply, &o->info);
}
static void Extern_COM_delete (Extern* o, const Msg* msg UNUSED)
{
Extern_Extern_close (o);
}
static const DCOM d_Extern_COM = {
.interface = &i_COM,
DMETHOD (Extern, COM_error),
DMETHOD (Extern, COM_export),
DMETHOD (Extern, COM_delete)
};
//}}}2------------------------------------------------------------------
//{{{2 Socket management
static bool Extern_is_valid_socket (Extern* o)
{
// The incoming socket must be a stream socket
int v;
socklen_t l = sizeof(v);
if (getsockopt (o->fd, SOL_SOCKET, SO_TYPE, &v, &l) < 0 || v != SOCK_STREAM)
return false;
// And it must match the family (PF_LOCAL or PF_INET)
struct sockaddr_storage ss;
l = sizeof(ss);
if (getsockname(o->fd, (struct sockaddr*) &ss, &l) < 0)
return false;
o->info.is_unix_socket = false;
if (ss.ss_family == PF_LOCAL)
o->info.is_unix_socket = true;
else if (ss.ss_family != PF_INET)
return false;
// If matches, need to set the fd nonblocking for the poll loop to work
int f = fcntl (o->fd, F_GETFL);
if (f < 0)
return false;
if (0 > fcntl (o->fd, F_SETFL, f| O_NONBLOCK| O_CLOEXEC))
return false;
return true;
}
#ifdef SCM_CREDS // BSD interface
#define SCM_CREDENTIALS SCM_CREDS
#define SO_PASSCRED LOCAL_PEERCRED
#define ucred cmsgcred
#elif !defined(SCM_CREDENTIALS)
#error "socket credentials passing not supported"
#endif
static void Extern_set_credentials_passing (Extern* o, int enable)
{
if (o->fd < 0 || !o->info.is_unix_socket)
return;
if (0 > setsockopt (o->fd, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable))) {
casycom_error ("setsockopt(SO_PASSCRED): %s", strerror(errno));
Extern_Extern_close (o);
}
}
static void Extern_TimerR_timer (Extern* o, int fd UNUSED, const Msg* msg UNUSED)
{
if (o->fd >= 0)
Extern_reading (o);
enum ETimerWatchCmd tcmd = WATCH_READ;
if (o->fd >= 0 && Extern_writing (o))
tcmd = WATCH_RDWR;
if (o->fd >= 0)
PTimer_watch (&o->timer, tcmd, o->fd, TIMER_NONE);
}
//}}}2------------------------------------------------------------------
//{{{2 reading
static DEFINE_ALIAS_CAST(cred_alias_cast, ExternCredentials)
static DEFINE_ALIAS_CAST(int_alias_cast, int)
static void Extern_reading (Extern* o)
{
for (;;) { // Read until EAGAIN
// create iovecs for input
// There are three of them, representing the three parts of each
// message: the fixed header (2), the header strings (0), and the
// message body. The common case is to read the variable parts
// and the fixed header of the next message in each recvmsg call.
struct iovec iov[3] = {};
if (o->inHRead >= sizeof(o->inHBuf.h)) {
assert (o->inMsg && "the message must be created after the fixed header is read");
iov[0].iov_base = &o->inHBuf.d[o->inHRead];
iov[0].iov_len = o->inHBuf.h.hsz - o->inHRead;
iov[1].iov_base = (char*) o->inMsg->body + o->inBRead;
iov[1].iov_len = o->inMsg->size - o->inBRead;
iov[2].iov_base = &o->inHBuf.h;
iov[2].iov_len = sizeof(o->inHBuf.h);
} else { // Fixed header partially read
iov[2].iov_base = &o->inHBuf.d[o->inHRead];
iov[2].iov_len = sizeof(o->inHBuf.h) - o->inHRead;
}
// Build struct for recvmsg
struct msghdr mh = {
.msg_iov = iov,
.msg_iovlen = ARRAY_SIZE(iov)
};
// Ancillary space for fd and credentials
char cmsgbuf [CMSG_SPACE(sizeof(int)) + CMSG_SPACE(sizeof(struct ucred))] = {};
mh.msg_control = cmsgbuf;
mh.msg_controllen = sizeof(cmsgbuf);
// Receive some data
int br = recvmsg (o->fd, &mh, 0);
if (br <= 0) {
if (!br || errno == ECONNRESET) // br == 0 when remote end closes. No error then, just need to close this end too.
DEBUG_PRINTF ("[X] %hu.Extern: rsocket %d closed by the other end\n", o->info.oid, o->fd);
else {
if (errno == EINTR)
continue;
if (errno == EAGAIN)
return;
casycom_error ("recvmsg: %s", strerror(errno));
}
return Extern_Extern_close (o);
}
DEBUG_PRINTF ("[X] Read %d bytes from socket %d\n", br, o->fd);
// Check if ancillary data was passed
for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg)) {
if (cmsg->cmsg_type == SCM_CREDENTIALS) {
o->info.creds = *cred_alias_cast (CMSG_DATA(cmsg));
Extern_set_credentials_passing (o, false); // Checked when the socket is connected. Changing credentials (such as by passing the socket to another process) is not supported.
DEBUG_PRINTF ("[X] Received credentials: pid=%u,uid=%u,gid=%u\n", o->info.creds.pid, o->info.creds.uid, o->info.creds.gid);
} else if (cmsg->cmsg_type == SCM_RIGHTS) {
if (o->inLastFd >= 0) {
casycom_error ("multiple file descriptors received in one message");
return Extern_Extern_close (o);
}
o->inLastFd = *int_alias_cast (CMSG_DATA(cmsg));
DEBUG_PRINTF ("[X] Received fd %d\n", o->inLastFd);
}
}
// Adjust read sizes
unsigned hbr = br;
if (hbr > iov[0].iov_len)
hbr = iov[0].iov_len;
o->inHRead += hbr;
br -= hbr;
unsigned bbr = br;
if (bbr > iov[1].iov_len)
bbr = iov[1].iov_len;
o->inBRead += bbr;
br -= bbr;
// Check if a message has been completed
if (o->inMsg && bbr == iov[1].iov_len) {
if (DEBUG_MSG_TRACE) {
DEBUG_PRINTF ("[X] message for extid %u of size %u completed:\n", o->inMsg->extid, o->inMsg->size);
hexdump (o->inHBuf.d, o->inHBuf.h.hsz);
hexdump (o->inMsg->body, o->inMsg->size);
}
assert (o->inBRead == o->inMsg->size);
if (!Extern_validate_message (o, o->inMsg)) {
casycom_error ("invalid message");
return Extern_Extern_close (o);
}
// If it has, queue it and reset inMsg pointer
if (o->inMsg)
Extern_queue_incoming_message (o, o->inMsg);
o->inMsg = NULL;
o->inHRead = 0;
o->inBRead = 0;
// Clear variable header data
memset (&o->inHBuf.d[sizeof(o->inHBuf.h)], 0, sizeof(o->inHBuf)-sizeof(o->inHBuf.h));
}
// Check for partial fixed header read
if (br) {
assert (!o->inMsg && o->inHRead <= sizeof(o->inHBuf.h));
o->inHRead += br;
}
// Check if a new message can be started
if (br && o->inHRead >= sizeof(o->inHBuf.h)) {
assert (o->inHRead == sizeof(o->inHBuf.h) && !o->inMsg && "internal error: message data read, but message not complete");
if (!Extern_validate_message_header (o, &o->inHBuf.h)) {
casycom_error ("invalid message");
return Extern_Extern_close (o);
}
o->inMsg = casymsg_begin (&o->reply, method_create_object, o->inHBuf.h.sz);
o->inMsg->extid = o->inHBuf.h.extid;
o->inMsg->fdoffset = o->inHBuf.h.fdoffset;
}
}
}
//}}}2------------------------------------------------------------------
//{{{2 Incoming message processing
static bool Extern_validate_message_header (const Extern* o UNUSED, const ExtMsgHeader* h)
{
if (h->hsz & (MESSAGE_HEADER_ALIGNMENT-1))
return false;
if (h->sz & (MESSAGE_BODY_ALIGNMENT-1))
return false;
if (h->fdoffset != NO_FD_IN_MESSAGE && h->fdoffset+4u > h->sz)
return false;
return true;
}
static COMConn* Extern_COMConn_by_extid (Extern* o, uint16_t extid)
{
for (size_t i = 0; i < o->conns.size; ++i)
if (o->conns.d[i].extid == extid)
return &o->conns.d[i];
return NULL;
}
static COMConn* Extern_COMConn_by_oid (Extern* o, oid_t oid)
{
for (size_t i = 0; i < o->conns.size; ++i)
if (o->conns.d[i].proxy.dest == oid)
return &o->conns.d[i];
return NULL;
}
static bool Extern_validate_message (Extern* o, Msg* msg)
{
// The interface and method names are now read, so can get the local pointers for them
msg->h.interface = Extern_lookup_in_msg_interface (o);
if (!msg->h.interface) {
DEBUG_PRINTF ("[X] Unable to find the message interface\n");
return false;
}
msg->imethod = Extern_lookup_in_msg_method (o, msg);
if (msg->imethod == method_invalid) {
DEBUG_PRINTF ("[X] Invalid method index in message\n");
return false;
}
// And validate the message body by signature
size_t vmsize = casymsg_validate_signature (msg);
if (ceilg (vmsize, MESSAGE_BODY_ALIGNMENT) != msg->size) { // Written size must be the aligned real size
DEBUG_PRINTF ("[X] message body fails signature verification\n");
return false;
}
msg->size = vmsize; // The written size was its aligned value. The real value comes from the validator.
if (msg->fdoffset != NO_FD_IN_MESSAGE) {
DEBUG_PRINTF ("[X] Setting message file descriptor to %d at %hhu\n", o->inLastFd, msg->fdoffset);
*int_alias_cast((char*) msg->body + msg->fdoffset) = o->inLastFd;
o->inLastFd = -1;
}
if (msg->extid == extid_COM) {
if (msg->h.interface != &i_COM)
DEBUG_PRINTF ("[X] extid_COM may only be used for the COM interface\n");
return msg->h.interface == &i_COM;
}
// Look up existing object for this extid
COMConn* conn = Extern_COMConn_by_extid (o, msg->extid);
if (!conn) { // If not present, then this is a request to create one
// Do not create object for COM messages (such as COM delete)
if (msg->h.interface == &i_COM) {
DEBUG_PRINTF ("[X] Ignoring COM message to extid %hu\n", msg->extid);
casymsg_free (msg);
o->inMsg = NULL; // to skip queue_incoming_message in caller
return true;
}
// Prohibit creation of objects not on the export list
if (!Extern_is_interface_exported (o, msg->h.interface)) {
DEBUG_PRINTF ("[X] message addressed to interface not on export list\n");
return false;
}
// Verify that the other end set the extid of new object in appropriate range
if (msg->extid >= extid_ClientLast || (o->info.is_client && (msg->extid < extid_ServerBase || msg->extid >= extid_ServerLast))) {
DEBUG_PRINTF ("[X] Invalid extid in message\n");
return false;
}
// create the new connection object
conn = vector_emplace_back (&o->conns);
conn->proxy = casycom_create_proxy (&i_COM, o->info.oid);
// The remote end sets the extid
conn->extid = msg->extid;
PCOM_create_object (&conn->proxy);
DEBUG_PRINTF ("[X] New incoming connection %hu -> %hu.%s, extid %hu\n", conn->proxy.src, conn->proxy.dest, casymsg_interface_name(msg), conn->extid);
}
// Translate the extid into local addresses
msg->h.src = conn->proxy.src;
msg->h.dest = conn->proxy.dest;
return true;
}
static void Extern_queue_incoming_message (Extern* o, Msg* msg)
{
if (msg->extid == extid_COM) {
PCOM_dispatch (&d_Extern_COM, o, msg);
casymsg_free (msg);
} else {
DEBUG_PRINTF ("[X] Queueing incoming message[%u] %hu -> %hu.%s.%s\n", msg->size, msg->h.src, msg->h.dest, casymsg_interface_name(msg), casymsg_method_name(msg));
casymsg_end (msg);
}
}
static iid_t Extern_lookup_in_msg_interface (const Extern* o)
{
const char* iname = &o->inHBuf.d[sizeof(o->inHBuf.h)];
assert (o->inHRead < MAX_MSG_HEADER_SIZE && o->inHRead >= sizeof(o->inHBuf.h)+5);
if (o->inHBuf.d[o->inHRead-1]) // Interface name and method must be nul terminated
return NULL;
return casycom_interface_by_name (iname);
}
static bool Extern_is_interface_exported (const Extern* o, iid_t iid)
{
if (!o->exported_interfaces)
return false;
for (const Interface* const* ii = o->exported_interfaces; *ii; ++ii)
if (iid == *ii)
return true;
return false;
}
static uint32_t Extern_lookup_in_msg_method (const Extern* o, const Msg* msg)
{
const char* hend = &o->inHBuf.d[o->inHBuf.h.hsz];
const char* iname = &o->inHBuf.d[sizeof(o->inHBuf.h)];
const char* mname = strnext (iname);
if (mname >= hend)
return method_invalid;
const char* msig = strnext (mname);
if (msig >= hend)
return method_invalid;
const char* mend = strnext (msig);
if (mend > hend)
return method_invalid;
size_t mnsize = mend - mname;
for (uint32_t mi = 0; msg->h.interface->method[mi]; ++mi) {
const char* m = msg->h.interface->method[mi];
size_t msz = strnext(strnext(m)) - m;
if (mnsize == msz && 0 == memcmp (m, mname, msz))
return mi;
}
return method_invalid;
}
//}}}2------------------------------------------------------------------
//{{{2 writing
static void Extern_queue_outgoing_message (Extern* o, Msg* msg)
{
if (msg->h.dest == o->info.oid) // messages to the Extern object itself have extid_COM
msg->extid = extid_COM;
else {
COMConn* conn = Extern_COMConn_by_oid (o, msg->h.dest);
if (!conn) {
conn = vector_emplace_back (&o->conns);
// create the reply proxy from Extern to the COMRelay
conn->proxy = casycom_create_proxy_to (&i_COM, o->info.oid, msg->h.dest);
// Extids are assigned from oid with side-based offset
conn->extid = msg->h.dest + (o->info.is_client ? extid_ClientBase : extid_ServerBase);
DEBUG_PRINTF ("[X] New outgoing connection %hu -> %hu.%s, extid %hu\n", msg->h.src, msg->h.dest, casymsg_interface_name(msg), conn->extid);
}
msg->extid = conn->extid;
// Once the object is deleted, the COMConn record must be recreated because it is linked to a specific object interface
if (msg->h.interface == &i_COM && msg->imethod == method_COM_delete) {
DEBUG_PRINTF ("[X] destroying connection with extid %hu\n", conn->extid);
vector_erase (&o->conns, conn - o->conns.d);
}
}
vector_push_back (&o->outgoing, &msg);
Extern_TimerR_timer (o, 0, NULL);
}
static bool Extern_writing (Extern* o)
{
// Write all queued messages
while (o->outgoing.size) {
Msg* msg = o->outgoing.d[0];
// Marshal message header
ExtMsgHeaderBuf hbuf = {};
hbuf.h.sz = ceilg (msg->size, MESSAGE_BODY_ALIGNMENT);
hbuf.h.extid = msg->extid;
hbuf.h.fdoffset = msg->fdoffset;
char* phstr = &hbuf.d[sizeof(hbuf.h)];
const char* iname = casymsg_interface_name(msg);
const char* mname = casymsg_method_name(msg);
const char* msig = strnext (mname);
assert (sizeof(ExtMsgHeader)+strlen(iname)+1+strlen(mname)+1+strlen(msig)+1 <= MAX_MSG_HEADER_SIZE && "the interface and method names for this message are too long to export");
char* phend = stpcpy (stpcpy (stpcpy (phstr, iname)+1, mname)+1, msig)+1;
hbuf.h.hsz = sizeof(hbuf.h) + ceilg (phend - phstr, MESSAGE_HEADER_ALIGNMENT);
// create iovecs for output
struct iovec iov[2] = {};
if (hbuf.h.hsz > o->outHWritten) {
iov[0].iov_base = &hbuf.d[o->outHWritten];
iov[0].iov_len = hbuf.h.hsz - o->outHWritten;
}
if (hbuf.h.sz > o->outBWritten) {
iov[1].iov_base = (char*) msg->body + o->outBWritten;
iov[1].iov_len = hbuf.h.sz - o->outBWritten;
}
// Build outgoing struct for sendmsg
struct msghdr mh = {
.msg_iov = iov,
.msg_iovlen = ARRAY_SIZE(iov)
};
// Add fd if being passed
char fdbuf [CMSG_SPACE(sizeof(int))] = {};
int fdpassed = -1;
if (hbuf.h.fdoffset != NO_FD_IN_MESSAGE) {
mh.msg_control = fdbuf;
mh.msg_controllen = sizeof(fdbuf);
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&mh);
cmsg->cmsg_len = sizeof(fdbuf);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
fdpassed = *int_alias_cast((char*) msg->body + hbuf.h.fdoffset);
*int_alias_cast(CMSG_DATA (cmsg)) = fdpassed;
}
// And try writing it all
int bw = sendmsg (o->fd, &mh, MSG_NOSIGNAL);
if (bw <= 0) {
if (!bw || errno == ECONNRESET) // bw == 0 when remote end closes. No error then, just need to close this end too.
DEBUG_PRINTF ("[X] %hu.Extern: wsocket %d closed by the other end\n", o->info.oid, o->fd);
else {
if (errno == EINTR)
continue;
if (errno == EAGAIN)
return true;
casycom_error ("sendmsg: %s", strerror(errno));
}
Extern_Extern_close (o);
return false;
}
DEBUG_PRINTF ("[X] Wrote %d of %u bytes of message %s.%s to socket %d\n", bw, hbuf.h.hsz+hbuf.h.sz, casymsg_interface_name(msg), casymsg_method_name(msg), o->fd);
// Adjust written sizes
unsigned hbw = bw;
if (hbw > iov[0].iov_len)
hbw = iov[0].iov_len;
o->outHWritten += hbw;
bw -= hbw;
o->outBWritten += bw;
assert (o->outBWritten <= hbuf.h.sz && "sendmsg wrote more than given");
// close the fd once successfully passed
if (fdpassed >= 0) {
close (fdpassed);
fdpassed = -1;
// And prevent it being passed more than once
msg->fdoffset = NO_FD_IN_MESSAGE;
}
// Check if message has been fully written, and move to the next one if so
if (o->outBWritten >= hbuf.h.sz) {
o->outHWritten = 0;
o->outBWritten = 0;
casymsg_free (o->outgoing.d[0]);
vector_erase (&o->outgoing, 0);
}
}
return false;
}
//}}}2------------------------------------------------------------------
//{{{2 ExternInfo lookup interface
const ExternInfo* casycom_extern_info (oid_t eid)
{
for (size_t ei = 0; ei < _Extern_externs.size; ++ei)
if (_Extern_externs.d[ei]->info.oid == eid)
return &_Extern_externs.d[ei]->info;
return NULL;
}
const ExternInfo* casycom_extern_object_info (oid_t oid)
{
const Extern* e = Extern_find_by_id (oid);
return e ? &e->info : NULL;
}
//}}}2------------------------------------------------------------------
//{{{2 Dtables and factory
static const DExtern d_Extern_Extern = {
.interface = &i_Extern,
DMETHOD (Extern, Extern_open),
DMETHOD (Extern, Extern_close)
};
static const DTimerR d_Extern_TimerR = {
.interface = &i_TimerR,
DMETHOD (Extern, TimerR_timer)
};
static const Factory f_Extern = {
.create = Extern_create,
.destroy = Extern_destroy,
.dtable = { &d_Extern_Extern, &d_Extern_TimerR, NULL }
};
//}}}2
//}}}-------------------------------------------------------------------
//{{{ COMRelay object
typedef struct _COMRelay {
Proxy localp; ///< Proxy to the local object
oid_t externid; ///< oid of the extern connection
Extern* pExtern; ///< Outgoing connection
} COMRelay;
//----------------------------------------------------------------------
static void* COMRelay_create (const Msg* msg)
{
COMRelay* o = xalloc (sizeof(COMRelay));
// COM objects are created in one of two ways:
// 1. By message going out-of-process, via the default object mechanism
// This results in msg->h.interface containing the imported interface.
// The local object already exists, and its proxy is created here.
// 2. By message coming into the process, sent by Extern object. Extern
// will explicitly create a COM intermediate by sending a COM message
// with method_create_object. The message with the real interface will
// follow immediately after, and localp will be created in COMRelay_COM_message.
if (msg->h.interface != &i_COM) {
o->localp = casycom_create_reply_proxy (&i_COM, msg);
o->pExtern = Extern_find_by_interface (msg->h.interface);
} else
o->pExtern = Extern_find_by_id (msg->h.dest);
if (o->pExtern) {
o->externid = o->pExtern->info.oid;
// COMRelay does not send any messages to the Extern object, it calls its
// functions directly. But having a proxy link allows object_destroyed notification.
casycom_create_proxy_to (&i_COM, msg->h.dest, o->externid);
}
return o;
}
static void COMRelay_COM_message (void* vo, Msg* msg)
{
COMRelay* o = vo;
// The local object proxy is created in the constructor when the COM
// object is created by it. When the COM object is created by Extern
// for an exported interface, then the first message will create the
// appropriate object using its interface.
if (!o->localp.interface)
o->localp = casycom_create_proxy (msg->h.interface, msg->h.dest);
if (!o->pExtern)
return casycom_error ("could not find outgoing connection for interface %s", casymsg_interface_name(msg));
if (msg->h.src != o->localp.dest) // Incoming message - forward to local
return casymsg_forward (&o->localp, msg);
// Outgoing message - queue in extern
Msg* qm = casymsg_begin (&msg->h, msg->imethod, 0); // Need to create a new message owned here
*qm = *msg;
msg->size = 0; // The body is now owned by qm
msg->body = NULL;
Extern_queue_outgoing_message (o->pExtern, qm);
}
static void COMRelay_destroy (void* vo)
{
COMRelay* o = vo;
// The relay is destroyed when:
// 1. The local object is destroyed. COM delete message is sent to the
// remote side as notification.
// 2. The remote object is destroyed. The relay is marked unused in
// COMRelay_COM_delete and the extern pointer is reset to prevent
// further messages to remote object. Here, no message is sent.
// 3. The Extern object is destroyed. pExtern is reset in
// COMRelay_object_destroyed, and no message is sent here.
if (o->pExtern) {
const Proxy failp = { // The message comes from the real object
.interface = &i_COM,
.src = o->localp.dest,
.dest = o->localp.src
};
Extern_queue_outgoing_message (o->pExtern, PCOM_delete_message (&failp));
}
xfree (o);
}
static bool COMRelay_error (void* vo, oid_t eoid, const char* msg)
{
COMRelay* o = vo;
// An unhandled error in the local object is forwarded to the remote
// object. At this point it will be considered handled. The remote
// will decide whether to delete itself, which will propagate here.
if (o->pExtern && eoid == o->localp.dest) {
const Proxy failp = { // The message comes from the real object
.interface = &i_COM,
.src = o->localp.dest,
.dest = o->localp.src
};
DEBUG_PRINTF ("[X] COMRelay forwarding error to extern creator\n");
Extern_queue_outgoing_message (o->pExtern, PCOM_error_message (&failp, msg));
return true; // handled on the remote end.
}
// Errors occuring in the Extern object or elsewhere can not be handled
// by forwarding, so fall back to default handling.
return false;
}
static void COMRelay_object_destroyed (void* vo, oid_t oid)
{
COMRelay* o = vo;
if (oid == o->externid) // Extern connection destroyed
o->pExtern = NULL; // no further messages are to be sent there.
casycom_mark_unused (o);
}
//----------------------------------------------------------------------
static void COMRelay_COM_error (COMRelay* o, const char* error, const Msg* msg UNUSED)
{
// COM_error is received for errors in the remote object. The remote
// object is destroyed and COM_delete will shortly follow. Here, create
// a local error and send it to the local object.
casycom_error ("%s", error);
casycom_forward_error (o->localp.dest, o->localp.src);
}
static void COMRelay_COM_delete (COMRelay* o, const Msg* msg UNUSED)
{
// COM_delete indicates that the remote object has been destroyed.
o->pExtern = NULL; // No further messages are to be sent.
casycom_mark_unused (o); // The relay and local object are to be destroyed.
}
//----------------------------------------------------------------------
static const DCOM d_COMRelay_COM = {
.interface = &i_COM,
DMETHOD (COMRelay, COM_error),
DMETHOD (COMRelay, COM_delete)
};
const Factory f_COMRelay = {
.create = COMRelay_create,
.destroy = COMRelay_destroy,
.object_destroyed = COMRelay_object_destroyed,
.error = COMRelay_error,
.dtable = { &d_COMRelay_COM, NULL }
};
//----------------------------------------------------------------------
/// Enables extern connections.
void casycom_enable_externs (void)
{
casycom_register (&f_Timer);
casycom_register (&f_Extern);
casycom_register_default (&f_COMRelay);
}
//}}}-------------------------------------------------------------------
|
msharov/casycom | util.h | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "config.h"
#include <syslog.h>
//{{{ Memory management ------------------------------------------------
// Types for main args
typedef unsigned argc_t;
#ifdef UC_VERSION
typedef const char** argv_t;
#else
typedef char* const* argv_t;
#endif
#ifdef __cplusplus
extern "C" {
template <typename T, size_t N> constexpr inline size_t ARRAY_SIZE (T(&a)[N]) { return N; }
#else
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
#endif
#define ARRAY_BLOCK(a) a, ARRAY_SIZE(a)
static inline constexpr size_t floorg (size_t n, size_t grain) { return n - n % grain; }
static inline constexpr size_t ceilg (size_t n, size_t grain) { return floorg (n+grain-1, grain); }
static inline constexpr size_t divide_ceil (size_t n1,size_t n2){ return (n1 + n2-1) / n2; }
#ifndef UC_VERSION
static inline const char* strnext (const char* s) { return s+strlen(s)+1; }
#endif
void* xalloc (size_t sz) noexcept MALLOCLIKE;
void* xrealloc (void* p, size_t sz) noexcept MALLOCLIKE;
#define xfree(p) do { if (p) { free(p); p = NULL; } } while (false)
// Define explicit aliasing cast to work around strict aliasing rules
#define DEFINE_ALIAS_CAST(name,type) \
type* name (void* p) { union { void* p; type* t; } __attribute__((may_alias)) cs = { .p = p }; return cs.t; }
//}}}-------------------------------------------------------------------
//{{{ Debugging
#ifndef NDEBUG
void casycom_log (int type, const char* fmt, ...) noexcept PRINTFARGS(2,3);
void casycom_backtrace (void) noexcept;
#else
#define casycom_log(type,...) syslog(type,__VA_ARGS__)
#endif
#ifndef UC_VERSION
void hexdump (const void* pv, size_t n) noexcept;
#endif
//}}}-------------------------------------------------------------------
//{{{ Miscellaneous
// Systemd socket activation support
enum { SD_LISTEN_FDS_START = 3 };
unsigned sd_listen_fds (void) noexcept;
#ifndef UC_VERSION
const char* executable_in_path (const char* efn, char* exe, size_t exesz) noexcept NONNULL();
#endif
#ifdef __cplusplus
namespace {
#endif
// Use in lock wait loops to relax the CPU load
static inline void tight_loop_pause (void)
{
#if __i386__ || __x86_64__
__builtin_ia32_pause();
#else
usleep (1);
#endif
}
static inline void acquire_lock (_Atomic(bool)* l)
{ do { tight_loop_pause(); } while (atomic_exchange (l, true)); }
static inline void release_lock (_Atomic(bool)* l)
{ *l = false; }
#ifdef __cplusplus
} // namespace
} // extern "C"
#endif
//}}}-------------------------------------------------------------------
|
msharov/casycom | casycom.h | // This file is part of the casycom project
//
// Copyright (c) 2015 by <NAME> <<EMAIL>>
// This file is free software, distributed under the ISC license.
#pragma once
#include "casycom/main.h"
#include "casycom/app.h"
#include "casycom/timer.h"
#include "casycom/io.h"
#include "casycom/xsrv.h"
|