repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
alonf/UniversalACRemote
ArduinoLoopManager.h
// ArduinoLoopManager.h #ifndef _ARDUINOLOOPMANAGER_h #define _ARDUINOLOOPMANAGER_h #include <functional> #include <initializer_list> #include <memory> #include "Singleton.h" #include<vector> class IProcessor { public: virtual void Loop() = 0; virtual ~IProcessor() {} }; typedef std::shared_ptr<IProcessor> processor_t; class ArduinoLoopManager : public Singleton<ArduinoLoopManager> { friend class Singleton<ArduinoLoopManager>; private: std::vector<processor_t> _processors; ArduinoLoopManager(std::initializer_list<processor_t> processors) : _processors(processors) {} public: void Loop() const { for (auto &&processor : _processors) { processor->Loop(); } } }; typedef std::shared_ptr<ArduinoLoopManager> ArduinoLoopManager_t; #endif
alonf/UniversalACRemote
DHTReader.h
<reponame>alonf/UniversalACRemote<gh_stars>1-10 #pragma once #include <DHT.h> #define DHTTYPE DHT22 class DHTReader { private: DHT _dht; public: DHTReader(); ~DHTReader(); float ReadTemperature(); float ReadHumidity(); };
alonf/UniversalACRemote
IRelectra.h
<filename>IRelectra.h /* * IRelectra * Thanks to <NAME> and Chris from AnalysIR */ #pragma once #ifndef IRelectra_h #define IRelectra_h //#include <IRremoteInt.h> #include <IRsend.h> enum class IRElectraMode : uint8_t { Cool = 0b001, Heat = 0b010, Fan = 0b101, Dry = 0b100, Auto = 0b011 }; enum class IRElectraFan : uint8_t { Low = 0b00, Medium = 0b01, High = 0b10, Auto = 0b11 }; enum class IRElectraSwing : uint8_t { Off = 0b0, On = 0b1 }; enum class IRElectraSleep : uint8_t { Off = 0b0, On = 0b1 }; enum class IRElectraIFeel : uint8_t { Off = 0b0, On = 0b1 }; enum class IRElectraPower : uint8_t { None = 0b0, OnOffToggle = 0b1 }; class IRelectra { public: // Ctor, remote will be used to send the raw IR data IRelectra(IRsend* remote); // Sends the specified configuration to the IR led using IRremote bool SendElectra(IRElectraPower power, IRElectraMode mode, IRElectraFan fan, int temperature, IRElectraSwing swing, IRElectraSleep sleep, IRElectraIFeel iFeel); private: IRsend* _remote; uint64_t EncodeElectra(IRElectraPower power, IRElectraMode mode, IRElectraFan fan, int temperature, IRElectraSwing swing, IRElectraSleep sleep, IRElectraIFeel iFeel); static void AddBit(uint16_t* p, int* i, char b); }; #endif
alonf/UniversalACRemote
ConfigurationManager.h
<filename>ConfigurationManager.h // ConfigurationManager.h #ifndef _CONFIGURATIONMANAGER_h #define _CONFIGURATIONMANAGER_h #include <algorithm> #include "Singleton.h" #include "WebServer.h" class ConfigurationManager : public Singleton<ConfigurationManager> { friend class Singleton<ConfigurationManager>; private: struct { unsigned char _magicNumber[6]; unsigned char pad[2]; //allignment char SSIDName[32]; char ACName[32]; //the given name for the Air Conditioner - for example: Parent Level char AccessPointPassword[64]; unsigned int milliSecondsButonLongTimePeriod; unsigned int milliSecondsButonVeryLongTimePeriod; } _eepromInformationBlock; const unsigned char _magicNumber[6] = { 'M', 'A', 'G', 'I', 'C', 0 }; bool CheckMagicNumber() const; void WriteMagicNumber(); void ClearMagicNumber(); void ReadEEPROMInfo(); void FlashEEPROMInfo(); ConfigurationManager(); public: String GetSSID() const; String GetAccessPointPassword() const; void SetWiFiCredentials(const String& SSID, const String& password); void SetACName(const String &ACName); String GetACName() const; void SetButonPressTimesMilliSeconds(unsigned int longPeriod, unsigned int veryLongPeriod); unsigned int GetLongPeriodButonPressTimesMilliSeconds() const { return _eepromInformationBlock.milliSecondsButonLongTimePeriod; } unsigned int GetVeryLongPeriodButonPressTimesMilliSeconds() const { return _eepromInformationBlock.milliSecondsButonVeryLongTimePeriod; } void FacrotyReset(); void FlashEEProm(); bool IsAccessPointMode() const { return !CheckMagicNumber(); } void DumpEEPromInfo(); }; typedef std::shared_ptr<ConfigurationManager> ConfigurationManager_t; #endif //_CONFIGURATIONMANAGER_h
alonf/UniversalACRemote
ACTypes.h
#pragma once #ifndef ACTYPES #define ACTYPES enum class ACMode { Cool, Heat, Fan, Dry, Auto, Humid, Recycle }; enum class ACFan { Low, Medium, High, Turbo, Auto }; enum class ACExtendedSwingMode { Off = 0, OnFull = 1, On1 = 2, On2 = 3, On3 = 4, On4 = 5, On5 = 6, OnFullLower = 7, OnFullMiddle = 8, OnFullUpper = 9 }; struct ACState { bool isPowerOn = true; int roomTemperature = 24; int roomHumidity = 70; ACMode mode = ACMode::Auto; ACFan fan = ACFan::Auto; int temperature = 24; bool isSwingOn = false; bool isSleepModeOn = false; int isiFeelModeOn = false; bool isXfanOn = false; bool isLightOn = false; ACExtendedSwingMode extendedSwing = ACExtendedSwingMode::Off; }; #endif //#define ACTYPES
alonf/UniversalACRemote
Configuration.h
// Configuration.h #pragma once #ifndef _CONFIGURATION_h #define _CONFIGURATION_h #define ELECTRA //#define TADIRAN //#define TADIRANTAC290 //Wifi Configuration static const char *SSID = "ACIoT"; //The default configuration access point ssid static const char *password = "<PASSWORD>"; //The default configuration access point password - at least 8 chars static const char *appKey = "apikey"; static const char *ApiKey = "{ca3c9e58-00c5-43cb-a2f5-cfed90b46b0e}"; //TODO: Move to EPROM const unsigned int defaultButtonLongTimePeriod = 5000; //5 seconds -> reset const unsigned int defaultButtonVeryLongTimePeriod = 20000; //20 seconds -> factory reset const int temperatureDeltaCalibration = -4; /* //WeMos configuration (Yarden & Children) const int pushButton = D3; const int redLed = D5; const int greenLed = D6; const int IRLED = D0; const int ButtonPressed = LOW; const int ButtonReleased = ButtonPressed == HIGH ? LOW : HIGH; const int DhtPin = D4; */ //configuration - Parent and living room const int pushButton = D1; const int redLed = D2; const int greenLed = D8; const int IRLED = D5; const int ButtonPressed = HIGH; const int ButtonReleased = ButtonPressed == HIGH ? LOW : HIGH; const int DhtPin = D4; #endif
alonf/UniversalACRemote
Util.h
// Util.h #ifndef _UTIL_h #define _UTIL_h #include <arduino.h> #include <algorithm> #include <vector> namespace Util { void software_Reboot(); //rebot the board template <typename T, std::size_t n> void String2Array(const String &str, T(&arr)[n]) { memset(arr, 0, n); memcpy(arr, str.c_str(), std::min(n - 1, str.length() + 1)); } template<typename TKey, typename TValue> class Map { private: std::vector<std::pair<TKey, TValue>> _vector; public: Map() = default; Map(const std::initializer_list<std::pair<TKey, TValue>>& list) { for (auto &element : list) { _vector.push_back(element); } } TValue& at(const TKey& key) { for (unsigned int i = 0; i < _vector.size(); ++i) { if (_vector[i].first == key) //found return _vector[i].second; } _vector.push_back(std::pair<TKey, TValue>(key, TValue())); return _vector.rbegin()->second; } const TValue& at(const TKey& key) const { for (int i = 0; i < _vector.size(); ++i) { if (_vector[i].first == key) //found return _vector[i].second; } return TValue(); } void clear() { _vector.clear(); } TValue &operator[](const TKey &key) { return at(key); } }; typedef Map<String, String> StringMap; } #endif
alonf/UniversalACRemote
LedsLogger.h
<reponame>alonf/UniversalACRemote #ifndef _LEDSLOGGER_h #define _LEDSLOGGER_h #include "arduino.h" #include <memory> #include "Singleton.h" #include "ArduinoLoopManager.h" #include <IPAddress.h> #include <queue> class LedsLogger : public Singleton<LedsLogger>, public IProcessor { private: friend class Singleton<LedsLogger>; class Led { private: const int _ledPin; int _ledValue = 0; int _lastSetVLedValue = 0; int _times = 0; int _blinkDelay = 0; unsigned long _startTime = 0; int _delayBeforeStart; int _currentBlinkingIpDigit; IPAddress _ipAddress; bool _bBlinkingIpAddress; int _currentBlinkingIpOctec; static int GetDigit(int from, int index); void DoBlink(int times, int delay, int delayBeforeStart = 0); void BlinkNextIpDigit(); public: Led(int ledPin); void Update(); void BlinkIpAddress(const IPAddress& ipAddress); void Blink(int times, int delay, int delayBeforeStart = 0); void Set(int value); }; Led _red; Led _green; LedsLogger(int redLedPin, int greenLedPin) : _red(redLedPin), _green(greenLedPin) {} public: void BlinkRed(int times, int delay, int delayBeforeStart = 0) { _red.Blink(times, delay, delayBeforeStart); } void BlinkGreen(int times, int delay, int delayBeforeStart = 0) { _green.Blink(times, delay, delayBeforeStart); } void SetRed(int value) { _red.Set(value); } void SetGreen(int value) { _green.Set(value); } void Loop() override { //call this function in a tight interval _red.Update(); _green.Update(); } void BlinkIpAddress(const IPAddress& ipAddress) { _green.BlinkIpAddress(ipAddress); } }; typedef std::shared_ptr<LedsLogger> LedsLoggerPtr_t; #endif
alonf/UniversalACRemote
Logger.h
// Logger.h #ifndef _LOGGER_h #define _LOGGER_h #include "arduino.h" #include "LedsLogger.h" #include "WebServer.h" #include <memory> #include "Singleton.h" #include "ArduinoLoopManager.h" class Logger : public Singleton<Logger>, public IProcessor { friend class Singleton<Logger>; private: LedsLoggerPtr_t _ledsLogger; Logger(int redLedPin, int greenLedPin, int baudRate); public: void Loop() override { _ledsLogger->Loop(); } void OnCommand(const String &commandName, int commandId) const; void WriteErrorMessage(const String &message, int blinks) const; void OnWiFiStatusChanged(const ConnectionStatus& status) const; void OnLongButtonPressDetection() const; void OnVeryLongButtonPressDetection() const; static void WriteMessage(const String& message); template<typename T> static void WriteMessage(const T& message) { Serial.println(message); } void TestLeds() const; }; typedef std::shared_ptr<Logger> LoggerPtr_t; #endif
alonf/UniversalACRemote
IRTadiran.h
<filename>IRTadiran.h #pragma once #ifndef IRTADIRAN_h #define IRTADIRAN_h #include <IRsend.h> enum class IRTadiranMode : uint8_t { Cool = 0, Heat = 1, Fan = 2, Humid = 3, Recycle = 4 }; enum class IRTadiranFan : uint8_t { Auto = 0, Low = 1, Medium = 2, High = 3, Turbo = 4 }; enum class IRTadiranSwing : uint8_t { Off = 0, OnFull = 1, On1 = 2, On2 = 3, On3 = 4, On4 = 5, On5 = 6, OnFullLower = 7, OnFullMiddle = 8, OnFullUpper = 9 }; enum class IRTadiranXFan : uint8_t { Off = 0, On = 1 }; enum class IRTadiranLight : uint8_t { On = 1, Off = 2 }; enum class IRTadiranPower : uint8_t { Off = 0, On = 1 }; class IRTadiran { public: // Ctor, remote will be used to send the raw IR data IRTadiran(IRsend* remote) : _remote(remote) {} // Sends the specified configuration to the IR led using IRremote void SendTadiran(IRTadiranPower power, IRTadiranMode mode, IRTadiranFan fan, int temperature, IRTadiranSwing swing, IRTadiranXFan xFan, IRTadiranLight light); private: IRsend * _remote; }; #endif //IRTADIRAN_h
alonf/UniversalACRemote
WebServer.h
// WebServer.h #ifndef _WEBSERVER_h #define _WEBSERVER_h #include "Arduino.h" #include <ESP8266WebServer.h> #undef ARDUINO_BOARD #define ARDUINO_BOARD "generic" #include <ESP8266mDNS.h> #include <String> #include <memory> #include "WiFiManager.h" #include "Singleton.h" #include "PubSub.h" #include "ArduinoLoopManager.h" #include "Util.h" #include "ACTypes.h" #include "ACCapabilities.h" struct DeviceSettings { bool isFactoryReset{}; String ssidName; String accessPointPassword; String ACNameStr; unsigned int longButtonPeriod{}; unsigned int veryLongButtonPeriod{}; }; typedef std::function<void(const String&, int)> WebNotificationPtr_t; class WebServer : public Singleton<WebServer>, public IProcessor { friend class Singleton<WebServer>; private: //char _htmlBuffer[3600]{}; //for setup html result char _htmlBuffer[6200]{}; //for setup html result std::unique_ptr<DeviceSettings> _deviceSettings{}; ESP8266WebServer _server; PubSub<WebServer, const String&, int> _pubsub; String _header; const String _authorizedUrl; bool _isInit = false; std::function<void(const DeviceSettings&)> _configurationUpdater; Util::StringMap _templateValuesMap; Util::Map<String, ACMode> _ACText2ModeMap = { {"AUTO", ACMode::Auto}, {"COOL", ACMode::Cool}, {"HEAT", ACMode::Heat}, {"FAN", ACMode::Fan}, {"DRY", ACMode::Dry}, { "HUMID", ACMode::Humid },{ "RECYCLE", ACMode::Recycle } }; Util::Map<String, ACFan> _ACText2FanMap = { { "AUTO", ACFan::Auto },{ "HIGH", ACFan::High },{ "LOW", ACFan::Low },{ "MEDIUM", ACFan::Medium },{ "TURBO", ACFan::Turbo } }; Util::Map<String, ACExtendedSwingMode> _ACText2ExtendedSwingModeMap = { { "OFF", ACExtendedSwingMode::Off }, {"ONFULL", ACExtendedSwingMode::OnFull }, {"ON1", ACExtendedSwingMode::On1}, {"ON2", ACExtendedSwingMode::On2 },{ "ON3", ACExtendedSwingMode::On3 },{ "ON4", ACExtendedSwingMode::On4},{ "ON5", ACExtendedSwingMode::On5 },{ "ONFULLLOWER", ACExtendedSwingMode::OnFullLower},{ "ONFULLMIDDLE", ACExtendedSwingMode::OnFullMiddle },{ "ONFULLUPPER", ACExtendedSwingMode::OnFullUpper} }; Util::Map<ACMode, String> _ACMode2TextMap = { { ACMode::Auto, "auto" },{ ACMode::Cool, "cool" },{ ACMode::Heat, "heat" },{ ACMode::Fan, "fan" },{ ACMode::Dry, "dry" },{ ACMode::Humid, "humid" },{ ACMode::Recycle, "recycle" } }; Util::Map<ACFan, String> _ACFan2TextMap = { { ACFan::Auto, "auto" },{ ACFan::High, "high" },{ ACFan::Low, "low" },{ ACFan::Medium, "medium" }, { ACFan::Turbo, "turbo" } }; Util::Map<ACExtendedSwingMode, String> _ACExtendedSwingMode2TextMap = { {ACExtendedSwingMode::Off, "off"},{ ACExtendedSwingMode::On1, "on1" },{ ACExtendedSwingMode::On2, "on2" },{ ACExtendedSwingMode::On3, "on3" },{ ACExtendedSwingMode::On4, "on4" },{ ACExtendedSwingMode::On5, "on5" },{ ACExtendedSwingMode::OnFullLower, "OnFullLower" },{ ACExtendedSwingMode::OnFullMiddle, "OnFullMiddle" }, { ACExtendedSwingMode::OnFullUpper, "OnFullUpper" } }; const ACCapabilities _acCapabilities; void SendBackHtml(const String &message); void UpdateStatus(ConnectionStatus status); std::function<ACState()> GetCurrentACState; std::function<void(bool)> SetACStateFromMonitorDevice; String CreateUrl(const String &s) const; bool GetServerArgBoolValue(const String &argName, ACCapabilities capability = ACCapabilities::None); void ProcessHTTPACView(); std::function<void(const ACState &)> UpdateACState; void PopulateHTMLSetupFromTemplate(const String& htmlTemplate, const Util::StringMap &map); WebServer(WiFiManagerPtr_t wifiManager, int port, const char *appKey, std::unique_ptr<DeviceSettings> deviceSettings, std::function<void (const ACState&)> updateACState, std::function<ACState()> getCurrentACState, std::function<void(bool)> setCACStateFromMonitorDevice, ACCapabilities acCapabilities); void HandleMain(); void ProcessHTTPSetupRequest(); void HandleSendAPScript(); void HandleSetup(); void HandleSendViewCSS(); void HandleSendAPList(); void HandleSetConfiguration(); void HandleResetAccessPoint(); void HandleError(); void HandleUpdateACStateFromMonitorDevice(); bool CheckSecurity(); void SendACState(); static bool GetSimpleJsonEntry(const String& text, String& variable, String& value, int& lastIndex); static void PopulateJsonStringMap(const String& body, Util::Map<String, String>& result); void SetACState(); void HandleGetCurrentTemperature(); void GetACState(); void SetACOnState(bool action); void TurnOn(); void TurnOff(); public: template<typename T> void SetWebSiteHeader(T header) { _header = std::forward<T>(header); } void Register(WebNotificationPtr_t subscriber) { _pubsub.Register(subscriber); } bool IsConnected() const; void Loop() override; void SetUpdateConfiguration(std::function<void(const DeviceSettings&)> configurationUpdater); }; typedef std::shared_ptr<WebServer> WebServerPtr_t; #endif
alonf/UniversalACRemote
Singleton.h
// Singleton.h #ifndef _SINGLETON_h #define _SINGLETON_h #include "arduino.h" #include <memory> template<typename T> class Singleton { private: static std::weak_ptr<T> _instance; public: virtual ~Singleton() = default; template<typename... Args> static std::shared_ptr<T> Create(Args&&... args) { auto instance = _instance.lock(); if (!instance) { // ReSharper disable CppSmartPointerVsMakeFunction instance = std::shared_ptr<T>(new T(std::forward<Args>(args)...)); // ReSharper restore CppSmartPointerVsMakeFunction _instance = instance; //support after ctor initialization instance->Intialize(instance); } return instance; } static std::shared_ptr<T> Instance() { return _instance.lock(); } virtual void Intialize(std::shared_ptr<T> instance) {}; Singleton() = default; Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; }; template<typename T> std::weak_ptr<T> Singleton<T>::_instance; #endif
alonf/UniversalACRemote
PushButtonManager.h
<filename>PushButtonManager.h<gh_stars>1-10 // PushButtonManager.h #ifndef _PUSHBUTTONMANAGER_h #define _PUSHBUTTONMANAGER_h #include "arduino.h" #include <functional> #include <memory> #include "Singleton.h" #include "ArduinoLoopManager.h" class IPushButtonActions { public: virtual void OnPress() = 0; //called when the user pressed and stopped the button for short period virtual int GetLongPressPeriod() = 0; //set the time that will be considered as a long press virtual void OnLongPressDetected() = 0; //called when the user presses for long time and continues to hold the button virtual void OnLongPress() = 0; //called when the user pressed and stopped the button for long period virtual int GetVeryLongPressPeriod() = 0; //called when the user presses for very long time and continues to hold virtual void OnVeryLongPressDetected() = 0; //called when the user presses for very long time and continues to hold the button virtual void OnVeryLongPress() = 0; //called when the user pressed and stopped the button for very long period virtual ~IPushButtonActions() {} }; typedef std::shared_ptr<IPushButtonActions> IPushButtonActionsPtr_t; class PushButtonManager : public Singleton<PushButtonManager>, public IProcessor { friend class Singleton<PushButtonManager>; private: const int _pin; int _previousButtonState = LOW; int _pressStartTime = 0; IPushButtonActionsPtr_t _pushButtonActions; bool _bLongDetection = false; bool _bVeryLongDetection = false; PushButtonManager(int pin, IPushButtonActionsPtr_t pushButtonActions); public: virtual ~PushButtonManager() { } void Loop() override; }; typedef std::shared_ptr<PushButtonManager> PushButtonManagerPtr_t; #endif
alonf/UniversalACRemote
WiFiManager.h
// WiFiManager.h #ifndef _WIFIMANAGER_h #define _WIFIMANAGER_h #include "Arduino.h" #include <ESP8266WiFi.h> #include <WiFiClientSecure.h> #include <WiFiUdp.h> #include <vector> #include <array> //#include <map> #include <memory> #include <functional> #include "Singleton.h" #include "ArduinoLoopManager.h" #include <list> #include "Util.h" enum class WiFiStatus { connected = 0, // assigned when connected to a WiFi network; noShield = 1, // assigned when no WiFi shield is present; idle = 2, // it is a temporary status assigned when WiFi.begin() is called and remains active until the number of attempts expires (resulting in WL_CONNECT_FAILED) or a connection is established (resulting in WL_CONNECTED); noSSID = 3, // assigned when no SSID are available; scanCompleted = 4, // assigned when the scan networks is completed; connectFailed = 5, // assigned when the connection fails for all the attempts; connectionLost = 6, // assigned when the connection is lost; dissconnected = 7, // assigned when disconnected from a network; }; struct AccessPointInfo { String SSID; int RSSI; bool isEncripted; }; class ConnectionStatus { friend class WiFiManager; private: const int _status; const IPAddress _localIP; bool _justConnected; bool _justDisconnected; bool _isAccessPointMode; static Util::Map<int, WiFiStatus> _statusMap; static std::array<String, 8> _messageMap; static std::list<AccessPointInfo> _accessPointList; static void ClearAccessPointList() { _accessPointList.clear(); } template<typename T> static void AddAccessPointInfo(T &&apInfo) { _accessPointList.push_back(std::forward<T>(apInfo)); } ConnectionStatus(int status, IPAddress localIP, bool justConnected = false, bool justDisconnected = false, bool isAccessPointMode = false) : _status(status), _localIP(localIP), _justConnected(justConnected), _justDisconnected(justDisconnected), _isAccessPointMode(isAccessPointMode) {} public: int WifiCode() const { return _status; } WiFiStatus Code() const { return _statusMap[_status]; } const String &Message() const {return _messageMap[_status];} IPAddress LocalIP() const { return _localIP; } bool IsJustConnected() const { return _justConnected; } bool IsJustDissconnected() const { return _justDisconnected; } bool IsConnected() const { return _status == WL_CONNECTED; } bool IsAccessPointModeOn() const { return _isAccessPointMode; } static const std::list<AccessPointInfo> &GetAccessPoints() { return _accessPointList; } }; typedef std::function<void (ConnectionStatus)> wifiNotificarionFunc_t; class WiFiManager : public Singleton<WiFiManager>, public IProcessor { friend class Singleton<WiFiManager>; private: std::vector<wifiNotificarionFunc_t> _subscribers; int _lastConnectionStatus; bool _accessPointMode = false; bool _accessPointModeHasBeenInit = false; bool _initiated = false; void UpdateStatus(); void NotifyAll(ConnectionStatus status) const; static void PopulateWiFiNetworks(); WiFiManager(const String &ssid, const String &password, bool isAccesspointMode); public: void RegisterClient(wifiNotificarionFunc_t notification); bool IsConnected() const; void Loop() override; void HandleAccessPointModeStatus(); }; typedef std::shared_ptr<WiFiManager> WiFiManagerPtr_t; #endif
alonf/UniversalACRemote
ACManager.h
// ACManager.h #ifndef _ACMANAGER_h #define _ACMANAGER_h #define RAWBUF 101 #include "Singleton.h" #include "ArduinoLoopManager.h" #include "Configuration.h" #include "Util.h" //#include <map> #ifdef ELECTRA #include "ACElectraController.h" #elif defined(TADIRAN) #include "ACTadiranController.h" #elif defined (TADIRANTAC290) #include "ACTadiranTac290Controller.h" #else #error("One AC type must be defined") #endif #include "ACController.h" class ACManager final : public Singleton<ACManager>, public IProcessor { friend class Singleton<ACManager>; private: #ifdef ELECTRA typedef ACController<ACElectraController> ACController_t; #elif defined(TADIRAN) typedef ACController<ACTadiranController> ACController_t; #elif defined (TADIRANTAC290) typedef ACController<ACTadiranTac290Controller> ACController_t; #else #error("One AC type must be defined") #endif ACController_t _acController; public: virtual void Intialize(std::shared_ptr<ACManager> This) override; Util::Map<ACMode, const char *> _ACMode2TextMap = { { ACMode::Auto, "auto" },{ ACMode::Cool, "cool" }, { ACMode::Heat, "heat" },{ ACMode::Fan, "fan" }, { ACMode::Dry, "dry" },{ ACMode::Recycle, "recycle" }, { ACMode::Humid, "humid" } }; Util::Map<ACFan, const char *> _ACFan2TextMap = { { ACFan::Auto, "auto" },{ ACFan::Turbo, "turbo" } , { ACFan::High, "high" }, { ACFan::Low, "low" },{ ACFan::Medium, "medium" } }; Util::Map<ACExtendedSwingMode, const char *> _ACExtendedSwingMode2TextMap = { { ACExtendedSwingMode::Off, "off" },{ ACExtendedSwingMode::On1, "on1" }, { ACExtendedSwingMode::On2, "on2" },{ ACExtendedSwingMode::On3, "on3" }, { ACExtendedSwingMode::On4, "on4" },{ ACExtendedSwingMode::On5, "on5" }, { ACExtendedSwingMode::OnFull, "on full" },{ ACExtendedSwingMode::OnFullLower, "on full lower" }, { ACExtendedSwingMode::OnFullMiddle, "on full middle" },{ ACExtendedSwingMode::OnFullUpper, "on full upper" }, }; Util::Map<bool, const char *> _ACOnOffTextMap = { { false, "off" },{ true, "on" } }; public: void OnButtonPressed(); void SendState(ACState acState); void SetACStateFromMonitorDevice(bool isAcOn) { _acController.SetACStateFromMonitorDevice(isAcOn); } bool IsPowerOn() const { return _acController.IsPowerOn(); } ACMode GetACMode() const { return _acController.GetACMode(); } ACFan GetACfan() const { return _acController.GetACfan(); } bool IsSwingModeOn() const { return _acController.IsSwingModeOn(); } bool IsSleepModeOn() const { return _acController.IsSleepModeOn(); } bool IsiFellModeOn() const { return _acController.IsiFeelModeOn(); } ACExtendedSwingMode GetACExtendedSwingMode() const { return _acController.GetExtendedSwingMode(); } bool IsXFanOn() const { return _acController.IsXFanOn(); } bool IsLightOn() const { return _acController.IsLightOn(); } ACState GetACState() const; ACCapabilities GetCapabilities() const { return _acController.GetCapabilities();} void Loop() override {} private: ACState _acStatus; }; typedef std::shared_ptr<ACManager> ACManagerPtr_t; #endif
alonf/UniversalACRemote
ACElectraController.h
<reponame>alonf/UniversalACRemote<filename>ACElectraController.h<gh_stars>1-10 #pragma once #ifndef ACELECTRACONTROLLER #define ACELECTRACONTROLLER #include "ACController.h" #include "Configuration.h" #include "IRelectra.h" class ACElectraController { typedef ACController<ACElectraController> Controller_t; private: IRsend _irsend; IRelectra _irElectra; bool _powerState = false; public: ACElectraController() : _irsend(IRLED), _irElectra(&_irsend) {} static ACCapabilities GetCapabilities() { return ACCapabilities::HasFanModeHigh | ACCapabilities::HasFanModeMedium | ACCapabilities::HasFanModeLow | ACCapabilities::HasFanModeAuto | ACCapabilities::HasACModeCool | ACCapabilities::HasACModeHeat | ACCapabilities::HasACModeDry | ACCapabilities::HasACModeFan | ACCapabilities::HasACModeAuto | ACCapabilities::HasSwingOnOff | ACCapabilities::HasSleepMode | ACCapabilities::HasiFeelMode; } void Initialize() { _irsend.begin(); Serial.println("ACElectraController begins..."); } void SetACStateFromMonitorDevice(bool isAcOn) { _powerState = isAcOn; } void SendAc(ACState state) { const IRElectraSwing swing = state.isSwingOn ? IRElectraSwing::On : IRElectraSwing::Off; const IRElectraPower power = state.isPowerOn != _powerState ? IRElectraPower::OnOffToggle : IRElectraPower::None; const IRElectraSleep sleep = state.isSleepModeOn ? IRElectraSleep::On : IRElectraSleep::Off; const IRElectraIFeel iFeel = state.isiFeelModeOn ? IRElectraIFeel::On : IRElectraIFeel::Off; _powerState = state.isPowerOn; IRElectraFan fan; switch (state.fan) { case ACFan::Low: fan = IRElectraFan::Low; break; case ACFan::Medium: fan = IRElectraFan::Medium; break; case ACFan::High: fan = IRElectraFan::High; break; case ACFan::Auto: default: fan = IRElectraFan::Auto; } IRElectraMode mode; switch (state.mode) { case ACMode::Cool: mode = IRElectraMode::Cool; break; case ACMode::Heat: mode = IRElectraMode::Heat; break; case ACMode::Fan: mode = IRElectraMode::Fan; break; case ACMode::Dry: mode = IRElectraMode::Dry; break; case ACMode::Auto: default: mode = IRElectraMode::Auto; } _irElectra.SendElectra(power, mode, fan, state.temperature, swing, sleep, iFeel); } }; #endif //ACELECTRACONTROLLER
alonf/UniversalACRemote
IRTadiranTac290.h
<filename>IRTadiranTac290.h /* * IRTadiranTac290 * Reverse engineering by <NAME> with AnalysIR */ #pragma once #ifndef IRTadeiranTac290_h #define IRTADIRANTAC290_H //#include <IRremoteInt.h> #include <IRsend.h> enum class IRTadiranTac290Mode : uint64_t { Cool = 0b10, Heat = 0b01, }; enum class IRTadiranTac290Fan : uint64_t { Low = 0b1, Turbo = 0b0, }; enum class IRTadiranTac290Power : uint64_t { Off = 0b0011, On = 0b1100 }; class IRTadiranTac290 { public: // Ctor, remote will be used to send the raw IR data IRTadiranTac290(IRsend* remote); // Sends the specified configuration to the IR led using IRremote bool SendTadiranTac290(IRTadiranTac290Power power, IRTadiranTac290Mode mode, IRTadiranTac290Fan fan, int temperature) const; private: const uint16_t zeroLength = 600; const uint16_t oneLenght = 1770; IRsend* _remote; void EncodeTadiranTac290(uint16_t *signal, IRTadiranTac290Power power, IRTadiranTac290Mode mode, IRTadiranTac290Fan fan, uint64_t temperature) const; }; #endif //IRTadiranTac290
alonf/UniversalACRemote
ACController.h
<filename>ACController.h #pragma once #ifndef ACCONTROLLER #define ACCONTROLLER #include <Arduino.h> #include "ACTypes.h" #include "ACCapabilities.h" /* * TRealACController: * TRealACController.SendAc(ACState state); * void TRealACController.Initialize(); * ACCapabilities TRealACController::Capabilities; */ template<typename TRealACController> class ACController { public: private: ACState _state {}; TRealACController _acController {}; public: void SendAc(const ACState &acState) { _state = acState; _acController.SendAc(_state); } bool IsPowerOn() const { return _state.isPowerOn; } ACMode GetACMode() const { return _state.mode; } ACFan GetACfan() const { return _state.fan; } bool IsSwingModeOn() const { return _state.isSwingOn;} bool IsSleepModeOn() const { return _state.isSleepModeOn; } bool IsiFeelModeOn() const { return _state.isiFeelModeOn; } unsigned char GetTemperature() const { return _state.temperature; } bool IsLightOn() const { return _state.isLightOn; } bool IsXFanOn() const { return _state.isXfanOn; } ACExtendedSwingMode GetExtendedSwingMode() const { return _state.extendedSwing; } ACState GetACState() const { return _state; } ACCapabilities GetCapabilities() const { return TRealACController::GetCapabilities(); } void Initialize() { _acController.Initialize(); } void SetACStateFromMonitorDevice(bool isAcOn) { _state.isPowerOn = isAcOn; _acController.SetACStateFromMonitorDevice(isAcOn); } }; #endif //ACCONTROLLER
alonf/UniversalACRemote
ACCapabilities.h
#pragma once #ifndef _ACCAPABILITIES #define _ACCAPABILITIES #include "IRTadiran.h" enum class ACCapabilities : unsigned int { None = 0, HasFanModeTurbo = 1 << 0, HasFanModeHigh = 1 << 1, HasFanModeMedium = 1 << 2, HasFanModeLow = 1 << 3, HasFanModeAuto = 1 << 4, HasACModeCool = 1 << 5, HasACModeHeat = 1 << 6, HasACModeDry = 1 << 7, HasACModeFan = 1 << 8, HasACModeHumid = 1 << 9, HasACModeRecycle = 1 << 10, HasACModeAuto = 1 << 11, HasSwingOnOff = 1 << 12, HasSleepMode = 1 << 13, HasOnOffLight = 1 << 14, HasOnOffXFan = 1 << 15, HasExtendedSwingMode = 1 << 16, HasiFeelMode = 1 << 17 }; inline ACCapabilities operator | (ACCapabilities lhs, ACCapabilities rhs) { return static_cast<ACCapabilities>(static_cast<unsigned int>(lhs) | static_cast<unsigned int>(rhs)); } inline ACCapabilities& operator |= (ACCapabilities& lhs, ACCapabilities rhs) { lhs = static_cast<ACCapabilities>(static_cast<unsigned int>(lhs) | static_cast<unsigned int>(rhs)); return lhs; } inline bool operator & (ACCapabilities lhs, ACCapabilities rhs) { const bool result = (static_cast<unsigned int>(lhs) & static_cast<unsigned int>(rhs)) != 0; return result; } #endif // _ACCAPABILITIES
alonf/UniversalACRemote
ACTadiranTac290Controller.h
<gh_stars>1-10 #pragma once #ifndef ACTADIRANTAC290CONTROLLER_H #define ACTADIRANTAC290CONTROLLER_H #include <IRsend.h> #include "ACController.h" #include "Configuration.h" #include "IRTadiranTac290.h" class ACTadiranTac290Controller { typedef ACController<ACTadiranTac290Controller> Controller_t; private: IRsend _irsend; IRTadiranTac290 _irTadiranTac290; public: static ACCapabilities GetCapabilities() { return ACCapabilities::HasFanModeTurbo | ACCapabilities::HasFanModeLow | ACCapabilities::HasACModeCool | ACCapabilities::HasACModeHeat; } explicit ACTadiranTac290Controller() : _irsend(IRLED), _irTadiranTac290(&_irsend) {} void Initialize() { _irsend.begin(); Serial.println("ACTadiranTac290Controller begins..."); } void SetACStateFromMonitorDevice(bool isAcOn) //no need to know. this AC has different code for on and off { } void SendAc(const ACState &state) const { const IRTadiranTac290Power power = state.isPowerOn ? IRTadiranTac290Power::On : IRTadiranTac290Power::Off; const IRTadiranTac290Fan fan = state.fan == ACFan::Low ? IRTadiranTac290Fan::Low : IRTadiranTac290Fan::Turbo; //default Turbo const IRTadiranTac290Mode mode = state.mode == ACMode::Heat ? IRTadiranTac290Mode::Heat : IRTadiranTac290Mode::Cool; //default cool _irTadiranTac290.SendTadiranTac290(power, mode, fan, state.temperature); } }; #endif //ACTADIRANTAC290CONTROLLER_H
alonf/UniversalACRemote
ACView.h
#pragma once #include <String> #ifndef _ACVIEW_h #define _ACVIEW_h #include "Configuration.h" /* * Since the view is different between the AC types, there is a different template for each of them. * In the future, a conditional element can be added to build a complex combined template */ #ifdef ELECTRA const static char ACViewHtmlTemplate[] PROGMEM = R"( <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><%=Title%></title> <link rel="stylesheet" type="text/css" href="view.css" media="all"> </head> <body id="main_body"> <div id="form_container"> <h1><a><%=Title%></a></h1> <form id="form_39821" class="appnitro" method="post" action="sendacstate"> <div class="form_description"> <h2><%=Title%>&emsp;Room:&nbsp;<%=RoomTemperature%>&deg;c&emsp;Humidity:&nbsp;<%=RoomHumidity%>&percnt;</h2> <input type="hidden" name="ApiKey" value="<%=ApiKey%>"></input> </div> <ul > <li> <label class="description" for="ACMode">Air Conditioner Mode </label> <span> <input id="ACModeAuto" name="ACMode" class="element radio" type="radio" value="AUTO" <%=ACModeAuto%>/> <label class="choice" for="ACModeAuto">Auto</label> <input id="ACModeCool" name="ACMode" class="element radio" type="radio" value="COOL" <%=ACModeCool%> /> <label class="choice" for="ACModeCool">Cool</label> <input id="ACModeHeat" name="ACMode" class="element radio" type="radio" value="HEAT" <%=ACModeHeat%>/> <label class="choice" for="ACModeHeat">Heat</label> <input id="ACModeFan" name="ACMode" class="element radio" type="radio" value="FAN" <%=ACModeFan%> /> <label class="choice" for="ACModeFan">Fan</label> <input id="ACModeDry" name="ACMode" class="element radio" type="radio" value="DRY" <%=ACModeDry%>/> <label class="choice" for="ACModeDry">Dry</label> </span> </li> <li> <label class="description" for="ACFan">Fan Speed </label> <span> <input id="FanModeAuto" name="ACFan" class="element radio" type="radio" value="AUTO" <%=FanModeAuto%> /> <label class="choice" for="FanModeAuto">Auto</label> <input id="FanModeLow" name="ACFan" class="element radio" type="radio" value="LOW" <%=FanModeLow%> /> <label class="choice" for="FanModeLow">Low</label> <input id="FanModeMedium" name="ACFan" class="element radio" type="radio" value="MEDIUM" <%=FanModeMedium%> /> <label class="choice" for="FanModeMedium">Medium</label> <input id="FanModeHigh" name="ACFan" class="element radio" type="radio" value="HIGH" <%=FanModeHigh%> /> <label class="choice" for="FanModeHigh">High</label> </span> </li> <li> <label class="description" for="operations">Operations</label> <span id="operations"> <input id="IsSwingOn" name="IsSwingOn" class="element checkbox" type="checkbox" value="true" <%=Swing%>/> <label class="choice" for="IsSwingOn">Swing</label> <input id="IsSleepOn" name="IsSleepOn" class="element checkbox" type="checkbox" value="true" <%=Sleep%> /> <label class="choice" for="IsSleepOn">Sleep</label> <input id="IsiFeelOn" name="IsiFeelOn" class="element checkbox" type="checkbox" value="true" <%=iFeel%> /> <label class="choice" for="IsiFeelOn">iFeel</label> <input id="IsPowerOn" name="IsPowerOn" class="element checkbox" type="checkbox" value="true" <%=PowerOn%> /> <label class="choice" for="IsPowerOn">Power On</label> </span> </li> <li> <label class="description" for="Temperature">Temperature </label> <div> <input id="Temperature" name="Temperature" class="element text medium" type="text" maxlength="255" value="<%=Temperature%>"/> </div> </li> <li class="buttons"> <input type="hidden" name="form_id" value="39821" /> <input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" /> </li> </ul> </form> </div> </body> </html> )"; #elif defined(TADIRAN) const static char ACViewHtmlTemplate[] PROGMEM = R"( <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><%=Title%></title> <link rel="stylesheet" type="text/css" href="view.css" media="all"> </head> <body id="main_body"> <div id="form_container"> <h1><a><%=Title%></a></h1> <form id="form_39821" class="appnitro" method="post" action="sendacstate"> <div class="form_description"> <h2><%=Title%>&emsp;Room:&nbsp;<%=RoomTemperature%>&deg;c&emsp;Humidity:&nbsp;<%=RoomHumidity%>&percnt;</h2> <input type="hidden" name="ApiKey" value="<%=ApiKey%>"></input> </div> <ul > <li> <label class="description" for="ACMode">Air Conditioner Mode </label> <span> <input id="ACModeCool" name="ACMode" class="element radio" type="radio" value="COOL" <%=ACModeCool%> /> <label class="choice" for="ACModeCool">Cool</label> <input id="ACModeHeat" name="ACMode" class="element radio" type="radio" value="HEAT" <%=ACModeHeat%>/> <label class="choice" for="ACModeHeat">Heat</label> <input id="ACModeFan" name="ACMode" class="element radio" type="radio" value="FAN" <%=ACModeFan%> /> <label class="choice" for="ACModeFan">Fan</label> <input id="ACModeHumid" name="ACMode" class="element radio" type="radio" value="HUMID" <%=ACModeHumid%>/> <label class="choice" for="ACModeHumid">Humid</label> <input id="ACModeRecycle" name="ACMode" class="element radio" type="radio" value="RECYCLE" <%=ACModeRecycle%>/> <label class="choice" for="ACModeRecycle">Recycle</label> </span> </li> <li> <label class="description" for="ACFan">Fan Speed</label> <span> <input id="FanModeAuto" name="ACFan" class="element radio" type="radio" value="AUTO" <%=FanModeAuto%> /> <label class="choice" for="FanModeAuto">Auto</label> <input id="FanModeLow" name="ACFan" class="element radio" type="radio" value="LOW" <%=FanModeLow%> /> <label class="choice" for="FanModeLow">Low</label> <input id="FanModeMedium" name="ACFan" class="element radio" type="radio" value="MEDIUM" <%=FanModeMedium%> /> <label class="choice" for="FanModeMedium">Medium</label> <input id="FanModeHigh" name="ACFan" class="element radio" type="radio" value="HIGH" <%=FanModeHigh%> /> <label class="choice" for="FanModeHigh">High</label> <input id="FanModeTurbo" name="ACFan" class="element radio" type="radio" value="TURBO" <%=FanModeTurbo%> /> <label class="choice" for="FanModeTurbo">Turbo</label> </span> </li> <li> <label class="description" for="Operations">Operations</label> <span> <input id="IsSwingOn" name="IsSwingOn" class="element checkbox" type="checkbox" value="true" <%=Swing%>/> <label class="choice" for="IsSwingOn">Swing</label> <input id="IsXFanOn" name="IsXFanOn" class="element checkbox" type="checkbox" value="true" <%=XFan%> /> <label class="choice" for="IsXFanOn">XFan</label> <input id="IsLightOn" name="IsLightOn" class="element checkbox" type="checkbox" value="true" <%=Light%> /> <label class="choice" for="IsLightOn">Light</label> <input id="IsPowerOn" name="IsPowerOn" class="element checkbox" type="checkbox" value="true" <%=PowerOn%> /> <label class="choice" for="IsPowerOn">Power On</label> </span> </li> <li> <label class="description">Swing Mode</label> <span> <input id="SW_1" name="ExtendedSwingMode" class="element radio" type="radio" value="OFF" <%=ACExtendedSwingModeOff%> /> <label class="choice" for="SW_1">Off</label> <input id="SW_2" name="ExtendedSwingMode" class="element radio" type="radio" value="ONFULL" <%=ACExtendedSwingModeOnFull%> /> <label class="choice" for="SW_2">On Full</label> <input id="SW_3" name="ExtendedSwingMode" class="element radio" type="radio" value="ON1" <%=ACExtendedSwingModeOn1%> /> <label class="choice" for="SW_3">On 1</label> <input id="SW_4" name="ExtendedSwingMode" class="element radio" type="radio" value="ON2" <%=ACExtendedSwingModeOn2%> /> <label class="choice" for="SW_4">On 2</label> <input id="SW_5" name="ExtendedSwingMode" class="element radio" type="radio" value="ON3" <%=ACExtendedSwingModeOn3%> /> <label class="choice" for="SW_5">On 3</label> <input id="SW_6" name="ExtendedSwingMode" class="element radio" type="radio" value="ON4" <%=ACExtendedSwingModeOn4%> /> <label class="choice" for="SW_6">On 4</label> <input id="SW_7" name="ExtendedSwingMode" class="element radio" type="radio" value="ON5" <%=ACExtendedSwingModeOn5%> /> <label class="choice" for="SW_7">On 5</label> <input id="SW_8" name="ExtendedSwingMode" class="element radio" type="radio" value="ONFULLLOWER" <%=ACExtendedSwingModeOnFullLower%> /> <label class="choice" for="SW_8">On Full Lower</label> <input id="SW_9" name="ExtendedSwingMode" class="element radio" type="radio" value="ONFULLMIDDLE" <%=ACExtendedSwingModeOnFullMiddle%> /> <label class="choice" for="SW_9">On Full Middle</label> <input id="SW_10" name="ExtendedSwingMode" class="element radio" type="radio" value="ONFULLUPPER" <%=ACExtendedSwingModeOnFullUpper%> /> <label class="choice" for="SW_10">On Full Upper</label> </span> </li> <li> <label class="description" for="Temperature">Temperature </label> <div> <input id="Temperature" name="Temperature" class="element text medium" type="text" maxlength="255" value="<%=Temperature%>"/> </div> </li> <li class="buttons"> <input type="hidden" name="form_id" value="39821" /> <input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" /> </li> </ul> </form> </div> </body> </html> )"; #elif defined(TADIRANTAC290) const static char ACViewHtmlTemplate[] PROGMEM = R"( <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><%=Title%></title> <link rel="stylesheet" type="text/css" href="view.css" media="all"> </head> <body id="main_body"> <div id="form_container"> <h1><a><%=Title%></a></h1> <form id="form_39821" class="appnitro" method="post" action="sendacstate"> <div class="form_description"> <h2><%=Title%>&emsp;Room:&nbsp;<%=RoomTemperature%>&deg;c&emsp;Humidity:&nbsp;<%=RoomHumidity%>&percnt;</h2> <input type="hidden" name="ApiKey" value="<%=ApiKey%>"></input> </div> <ul > <li> <label class="description" for="ACMode">Air Conditioner Mode </label> <span> <input id="ACModeCool" name="ACMode" class="element radio" type="radio" value="COOL" <%=ACModeCool%> /> <label class="choice" for="ACModeCool">Cool</label> <input id="ACModeHeat" name="ACMode" class="element radio" type="radio" value="HEAT" <%=ACModeHeat%>/> <label class="choice" for="ACModeHeat">Heat</label> </span> </li> <li> <label class="description" for="ACFan">Fan Speed </label> <span> <input id="FanModeLow" name="ACFan" class="element radio" type="radio" value="LOW" <%=FanModeLow%> /> <label class="choice" for="FanModeLow">Low</label> <input id="FanModeTurbo" name="ACFan" class="element radio" type="radio" value="TURBO" <%=FanModeTurbo%> /> <label class="choice" for="FanModeTurbo">Turbo</label> </span> </li> <li> <label class="description" for="operations">Operations</label> <span id="operations"> <input id="IsPowerOn" name="IsPowerOn" class="element checkbox" type="checkbox" value="true" <%=PowerOn%> /> <label class="choice" for="IsPowerOn">Power On</label> </span> </li> <li> <label class="description" for="Temperature">Temperature </label> <div> <input id="Temperature" name="Temperature" class="element text medium" type="text" maxlength="255" value="<%=Temperature%>"/> </div> </li> <li class="buttons"> <input type="hidden" name="form_id" value="39821" /> <input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" /> </li> </ul> </form> </div> </body> </html> )"; #else #error("One AC type must be defined") #endif #endif
alonf/UniversalACRemote
ACTadiranController.h
#pragma once #ifndef ACTADIRANCONTROLLER_H #define ACTADIRANCONTROLLER_H #include <IRsend.h> #include "ACController.h" #include "Configuration.h" #include "IRTadiran.h" class ACTadiranController { typedef ACController<ACTadiranController> Controller_t; private: IRsend _irsend; IRTadiran _irTadiran; public: static ACCapabilities GetCapabilities() { return ACCapabilities::HasFanModeTurbo | ACCapabilities::HasFanModeHigh | ACCapabilities::HasFanModeMedium | ACCapabilities::HasFanModeLow | ACCapabilities::HasFanModeAuto | ACCapabilities::HasACModeCool | ACCapabilities::HasACModeHeat | ACCapabilities::HasACModeHumid | ACCapabilities::HasACModeRecycle | ACCapabilities::HasACModeFan | ACCapabilities::HasSwingOnOff | ACCapabilities::HasOnOffLight | ACCapabilities::HasOnOffXFan | ACCapabilities::HasExtendedSwingMode; } explicit ACTadiranController() : _irsend(IRLED), _irTadiran(&_irsend) {} void Initialize() { _irsend.begin(); Serial.println("ACTadiranController begins..."); }; void SetACStateFromMonitorDevice(bool isAcOn) //no need to know. this AC has different code for on and off { } void SendAc(const ACState &state) { //const IRTadiranSwing swing = state.isSwingOn ? IRTadiranSwing::OnFull : IRTadiranSwing::Off; const IRTadiranPower power = state.isPowerOn ? IRTadiranPower::On : IRTadiranPower::Off; const IRTadiranLight light = state.isLightOn ? IRTadiranLight::On : IRTadiranLight::Off; const IRTadiranXFan xFan = state.isXfanOn ? IRTadiranXFan::On : IRTadiranXFan::Off; IRTadiranFan fan; switch (state.fan) { case ACFan::Low: fan = IRTadiranFan::Low; break; case ACFan::Medium: fan = IRTadiranFan::Medium; break; case ACFan::High: fan = IRTadiranFan::High; break; case ACFan::Turbo: fan = IRTadiranFan::Turbo; break; case ACFan::Auto: default: fan = IRTadiranFan::Auto; } IRTadiranMode mode; switch (state.mode) { case ACMode::Cool: mode = IRTadiranMode::Cool; break; case ACMode::Heat: mode = IRTadiranMode::Heat; break; case ACMode::Fan: mode = IRTadiranMode::Fan; break; case ACMode::Recycle: mode = IRTadiranMode::Recycle; break; case ACMode::Humid: mode = IRTadiranMode::Humid; break; case ACMode::Auto: default: mode = IRTadiranMode::Cool; } IRTadiranSwing swing {}; switch (state.extendedSwing) { case ACExtendedSwingMode::Off: swing = IRTadiranSwing::Off; break; case ACExtendedSwingMode::OnFull: swing = IRTadiranSwing::OnFull; break; case ACExtendedSwingMode::On1: swing = IRTadiranSwing::On1; break; case ACExtendedSwingMode::On2: swing = IRTadiranSwing::On2; break; case ACExtendedSwingMode::On3: swing = IRTadiranSwing::On3; break; case ACExtendedSwingMode::On4: swing = IRTadiranSwing::On4; break; case ACExtendedSwingMode::On5: swing = IRTadiranSwing::On5; break; case ACExtendedSwingMode::OnFullLower: swing = IRTadiranSwing::OnFullLower; break; case ACExtendedSwingMode::OnFullMiddle: swing = IRTadiranSwing::OnFullMiddle; break; case ACExtendedSwingMode::OnFullUpper: swing = IRTadiranSwing::OnFullUpper; break; default: swing = IRTadiranSwing::Off; } _irTadiran.SendTadiran(power, mode, fan, state.temperature, swing, xFan, light); } }; #endif //ACTADIRANCONTROLLER_H
Lizards/xdg-open-server
main.c
<gh_stars>1-10 #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/un.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/wait.h> #include <X11/Xlib.h> #define run(cmd, ...) { \ if (!fork()) { \ execlp(cmd, cmd, __VA_ARGS__, 0); \ exit(1); \ } \ wait(0); \ } static void * threadf(void * data) { char * socket_loc = data; int fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (fd < 0) { fprintf(stderr, "Can not create UNIX socket.\n"); exit(1); } struct sockaddr_un server_addr; memset(&server_addr, 0, sizeof(struct sockaddr_un)); server_addr.sun_family = AF_UNIX; strncpy(server_addr.sun_path, socket_loc, sizeof(server_addr.sun_path) - 1); if (bind(fd, (struct sockaddr *) &server_addr, sizeof(struct sockaddr_un)) < 0) { fprintf(stderr, "Can not bind UNIX socket.\n"); exit(1); } chmod(socket_loc, 0666); int buffer_size = 1024; char buffer[buffer_size]; while (1) { struct sockaddr_un client_addr; int length = sizeof(struct sockaddr_un); int bytes = recvfrom(fd, buffer, buffer_size - 1, 0, (struct sockaddr *) &client_addr, &length); if (bytes > 0) { buffer[bytes] = '\0'; char * substr = strchr(buffer, '\n'); if (substr != 0) { int index = substr - buffer; buffer[index] = '\0'; } run("xdg-open", buffer); } } exit(1); } static int error_handler(Display * display) { // Stop xdg-open-server with X exit(1); } int main(int argc, char ** argv) { int uid = getuid(); if (uid == 0) { fprintf(stderr, "Can start server from root.\n"); return 1; } char socket_dir[100]; sprintf(socket_dir, "/run/user/%d/xdg-open-server", uid); run("mkdir", "-p", socket_dir); chmod(socket_dir, 0700); struct stat filestat; if (stat(socket_dir, &filestat) != 0 || !S_ISDIR(filestat.st_mode)) { fprintf(stderr, "Not a directory: %s.\n", socket_dir); return 1; } Display * display; if (!(display = XOpenDisplay(0))) { fprintf(stderr, "Can open display.\n"); return 1; } char * display_var = getenv("DISPLAY"); if (!display_var || strlen(display_var) == 0) { fprintf(stderr, "Can not find display variable.\n", socket_dir); return 1; } char * socket_loc = malloc(100); sprintf(socket_loc, "%s/socket%s", socket_dir, display_var); unlink(socket_loc); pthread_t thread; if (pthread_create(&thread, 0, threadf, socket_loc)) { fprintf(stderr, "Can not create thread.\n"); return 1; } XSetIOErrorHandler(error_handler); while (1) { XEvent event; XNextEvent(display, &event); } return 0; }
IoanaRoibu/oop-2022
laborator 5/lab 5/Ford.h
<reponame>IoanaRoibu/oop-2022 #pragma once #include "Car.h" class Ford : public Car { public: void SetFuelCapacity(int fuel_cap) override; void SetFuelConsumption(int fuel_cons) override; void SetRainSpeed(int rain_speed) override; void SetSnowSpeed(int snow_speed) override; void SetSunnySpeed(int sunny_speed) override; int GetFuelCapacity(); int GetFuelConsumption(); int GetRainSpeed(); int GetSnowSpeed(); int GetSunnySpeed(); void name(); };
IoanaRoibu/oop-2022
problema2_lab 2/compara_studenti.h
//a header file for the global functions //5 global functions that compares two students in terms of name, grades, average. #include "student.h" #pragma once int compara_nume(Student s1, Student s2); int compara_mate(Student s1, Student s2); int compara_eng(Student s1, Student s2); int compara_ist(Student s1, Student s2); int compara_medie(Student s1, Student s2);
IoanaRoibu/oop-2022
laborator 5/lab 5/Circuit.h
<reponame>IoanaRoibu/oop-2022<filename>laborator 5/lab 5/Circuit.h #pragma once #include "Weather.h" #include "Car.h" #include "Dacia.h" #include "Ford.h" #include "Mazda.h" #include "Mercedes.h" #include "Toyota.h" class Circuit { int lungime; int car_nr=0; Car* cars[6]; int not_finish[6]={0}; Weather weather; int winner; public: void SetLength(int lenght); void SetWeather(Weather weather); void AddCar(Car * car); void Race(); void ShowWinner(); void ShowWhoDidNotFinis(); };
IoanaRoibu/oop-2022
laborator 5/lab 5/Car.h
#pragma once class Car { protected: int fuel_capacity, fuel_consumption, average_speed_rain, average_speed_snow, average_speed_sunny; public: virtual void SetFuelCapacity(int fuel_cap) = 0; virtual void SetFuelConsumption(int fuel_cons) = 0; virtual void SetRainSpeed(int rain_speed) = 0; virtual void SetSnowSpeed(int snow_speed) = 0; virtual void SetSunnySpeed(int sunny_speed) = 0; virtual int GetFuelCapacity() = 0; virtual int GetFuelConsumption() = 0; virtual int GetRainSpeed() = 0; virtual int GetSnowSpeed() = 0; virtual int GetSunnySpeed() = 0; virtual void name()= 0; };
IoanaRoibu/oop-2022
problema2_lab 2/student.h
<reponame>IoanaRoibu/oop-2022<filename>problema2_lab 2/student.h //a header file for the class #pragma once class Student { float Nota_mate; float Nota_eng; float Nota_ist; float Medie; char Nume[50]; public: void setname(char nume[]); //methods to setand get the name of the student const char* getname(); void setmate(float mate); //methods to setand get the grade for mathematics(a grade must be a float value from 1 to 10) float getmate(); void seteng(float eng); //methods to setand get the grade for English(a grade must be a float value from 1 to 10) float geteng(); void setist(float ist); //methods to setand get the grade for History(a grade must be a float value from 1 to 10) float getist(); float calculare_medie(); //a method that retrieves the average grad };
CalvinLeo/CLCircleProgressView
CLCircleProgressView/CLProgressView/CLProgressView.h
<gh_stars>1-10 // // 圆形进度条 // // Created by AEF_oycf on 2018/8/22. // Copyright © 2018年 AEF_oycf. All rights reserved. // #import <UIKit/UIKit.h> @interface CLProgressView : UIView @property (nonatomic, assign) CGFloat progressValue;// 进度 @property (nonatomic, strong) UIColor *trackColor; // 轨道颜色 @property (nonatomic, assign) CGFloat trackWidth; // 轨道宽度 @property (nonatomic, strong) UIColor *circleColor; // 进度条颜色 @property (nonatomic, assign) CGFloat circleWidth; // 进度条宽度 @property (nonatomic, assign) BOOL isShowContent; // 是否显示文本框 @property (nonatomic, strong) UIColor *contentColor;// 内容颜色 @property (nonatomic, strong) UIFont *contentFont; // 内容字体 @property (nonatomic, copy) NSString *contentText; // 内容 /* * 构造方法 * frame: 背景图的位置和宽高 * radius: 圆半径 */ - (instancetype)initWithBackFrame:(CGRect)frame radius:(CGFloat)radius; @end
DreamerZJ/ZJLaunchAdv
ZJLaunchAdvDemo/ZJLaunchAdv/ZJLaunchAdv/ZJProxy.h
<filename>ZJLaunchAdvDemo/ZJLaunchAdv/ZJLaunchAdv/ZJProxy.h<gh_stars>0 // // ZJProxy.h // Push // // Created by 张建 on 2017/12/8. // Copyright © 2017年 zhangjian. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface ZJProxy : NSProxy @property (nonatomic,readonly,weak) id targetObject; + (instancetype)zjProxyWithTarget:(id)target; @end NS_ASSUME_NONNULL_END
DreamerZJ/ZJLaunchAdv
ZJLaunchAdvDemo/ZJLaunchAdv/ZJLaunchAdv/ZJLaunchAdv.h
<gh_stars>0 // // ZJLaunchImageAdView.h // Push // // Created by zhangjian on 2017/12/29. // Copyright © 2017年 zhangjian. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSInteger,ZJAdType){ ZJAdTypeLogo = 0, //带有logo ZJAdTypeFullScreen, //全屏,不带lodo ZJAdTypeNone //无广告图 }; typedef NS_ENUM(NSUInteger, ZJSkipButtonType) { ZJSkipButtonTypeOvalTimeAndText = 0, //圆角矩形+文字+倒计时 ZJSkipButtonTypeOvalAnimationAndText, //圆角矩形+文字+动画 ZJSkipButtonTypeCircleAnimationAndText, //圆形+文字+动画 ZJSkipButtonTypeNone //无跳过按钮 }; @interface ZJAdConfiguration : NSObject /**广告图链接 默认为空*/ @property (nonatomic,copy) NSString *adImageUrl; /**广告展示类型 默认为无广告*/ @property (nonatomic,assign) ZJAdType adtype; /**按钮样式 默认为文字+倒计时*/ @property (nonatomic,assign) ZJSkipButtonType skipBtnType; /**显示时长 默认为3s*/ @property (nonatomic,assign) NSTimeInterval duration; /**动画环颜色*/ @property (nonatomic,strong) UIColor *animationCircleColor; @end /**配置block*/ typedef void(^ConfigurationSetBlock)(ZJAdConfiguration *configuration); /**跳过按钮点击block*/ typedef void(^ActionBlock)(void); /**结束block*/ typedef void(^CompletionBlock)(BOOL finished); @interface ZJLaunchAdv : UIView /**启动广告配置*/ @property (nonatomic,strong) ZJAdConfiguration *configuration; /** 创建带有configuration的广告图显示对象 @param configurationBlock 设置configuration的block @return 返回带有configuration的广告图显示对象 */ + (instancetype)zjLaunchImageView:(ConfigurationSetBlock)configurationBlock action:(void(^)(void))action completion:(void (^ __nullable)(BOOL finished))completion; NS_ASSUME_NONNULL_END @end
DreamerZJ/ZJLaunchAdv
ZJLaunchAdvDemo/ZJLaunchAdv/AppDelegate.h
<filename>ZJLaunchAdvDemo/ZJLaunchAdv/AppDelegate.h<gh_stars>0 // // AppDelegate.h // ZJLaunchAdv // // Created by zhangjian on 2018/1/3. // Copyright © 2018年 zhangjian. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
ipuustin/sql-parser
include/sqlparser/TableAccess.h
#pragma once #include <string> #include <set> #include <map> #include <iterator> #include <unordered_map> namespace hsql { typedef std::unordered_map<std::string, std::set<std::string>> TableAccessMap; class TableAccess { public: const std::string OpUnknown{"unknown"}; const std::string OpInsert{"insert"}; const std::string OpSelect{"select"}; const std::string OpShow{"show"}; const std::string OpUpdate{"update"}; const std::string OpDelete{"delete"}; const std::string OpCreate{"create"}; const std::string OpDrop{"drop"}; const std::string OpAlter{"alter"}; const std::string OpImport{"import"}; virtual void tablesAccessed(TableAccessMap &t) const = 0; static void addOperation(TableAccessMap &t, const char *table, const char *db, const std::string& op) { t[buildKey(table, db)].insert(op); } virtual ~TableAccess() {} private: static std::string buildKey(const char *table, const char *db) { std::string key; key.append(table); if (db != nullptr) { key.append(".").append(db); } return key; } }; } // namespace hsql
ipuustin/sql-parser
include/sqlparser/SQLStatement.h
#pragma once #include <vector> #include "TableAccess.h" #include "Expr.h" namespace hsql { enum StatementType { kStmtError, // unused kStmtSelect, kStmtImport, kStmtInsert, kStmtUpdate, kStmtDelete, kStmtCreate, kStmtDrop, kStmtPrepare, kStmtExecute, kStmtExport, kStmtRename, kStmtAlter, kStmtShow }; // Base struct for every SQL statement struct SQLStatement : public TableAccess { SQLStatement(StatementType type) : hints(nullptr), type_(type) {}; virtual ~SQLStatement() { if (hints != nullptr) { for (Expr* hint : *hints) { delete hint; } } delete hints; } StatementType type() const { return type_; } bool isType(StatementType type) const { return (type_ == type); } // Shorthand for isType(type). bool is(StatementType type) const { return isType(type); } // Length of the string in the SQL query string size_t stringLength; std::vector<Expr*>* hints; private: StatementType type_; }; } // namespace hsql
ipuustin/sql-parser
include/sqlparser/AlterStatement.h
#pragma once #include "SQLStatement.h" #include "SelectStatement.h" namespace hsql { enum AlterType { kAlterTable, kAlterSchema, kAlterDatabase }; // Represents SQL Alter statements. // Example: "ALTER TABLE students ADD column Id varchar (20)" struct AlterStatement : SQLStatement { AlterStatement(AlterType type); virtual ~AlterStatement(); void tablesAccessed(TableAccessMap& accessMap) const override { if (tableName != nullptr) { TableAccess::addOperation(accessMap, tableName, schema, TableAccess::OpAlter); } }; AlterType type; bool dflt; // default: false bool equal; // default: false char* schema; char* tableName; Expr* charsetName; ColumnDefinition* columns; }; } // namsepace hsql
ipuustin/sql-parser
include/sqlparser/DeleteStatement.h
#pragma once #include "SQLStatement.h" // Note: Implementations of constructors and destructors can be found in statements.cpp. namespace hsql { // Represents SQL Delete statements. // Example: "DELETE FROM students WHERE grade > 3.0" // Note: if (expr == nullptr) => delete all rows (truncate) struct DeleteStatement : SQLStatement { DeleteStatement(); virtual ~DeleteStatement(); void tablesAccessed(TableAccessMap& accessMap) const override { if (expr != nullptr) { expr->tablesAccessed(accessMap); } if (tableName != nullptr) { TableAccess::addOperation(accessMap, tableName, schema, TableAccess::OpDelete); } } bool low_priority; // default: false bool quick; // default: false bool ignore; // default: false char* schema; char* tableName; Expr* expr; }; } // namespace hsql
ipuustin/sql-parser
include/sqlparser/UpdateStatement.h
<reponame>ipuustin/sql-parser #pragma once #include "SQLStatement.h" namespace hsql { // Represents "column = value" expressions. struct UpdateClause { char* column; Expr* value; }; // Represents SQL Update statements. struct UpdateStatement : SQLStatement { UpdateStatement(); virtual ~UpdateStatement(); void tablesAccessed(TableAccessMap& accessMap) const override { if (updates != nullptr) { for (auto it = updates->begin(); it != updates->end(); ++it) { (*it)->value->tablesAccessed(accessMap); } } if (where != nullptr) { where->tablesAccessed(accessMap); } if (table != nullptr) { table->tablesAccessed(accessMap, TableAccess::OpUpdate); } }; // TODO: switch to char* instead of TableRef bool low_priority; // default: false bool ignore; // default: false TableRef* table; std::vector<UpdateClause*>* updates; Expr* where; }; } // namsepace hsql
ipuustin/sql-parser
include/sqlparser/PrepareStatement.h
<filename>include/sqlparser/PrepareStatement.h #pragma once #include "SQLStatement.h" namespace hsql { // Represents SQL Prepare statements. // Example: PREPARE test FROM 'SELECT * FROM test WHERE a = ?;' struct PrepareStatement : SQLStatement { PrepareStatement(): SQLStatement(kStmtPrepare), name(nullptr), query(nullptr) {} virtual ~PrepareStatement() { free(name); free(query); } void tablesAccessed(TableAccessMap&) const override {}; char* name; // The query that is supposed to be prepared. char* query; }; } // namsepace hsql
ipuustin/sql-parser
include/sqlparser/ShowStatement.h
<gh_stars>1-10 #pragma once #include "SQLStatement.h" // Note: Implementations of constructors and destructors can be found in statements.cpp. namespace hsql { enum ShowType { kShowColumns, kShowTables, kShowDatabases }; // Represents SQL SHOW statements. // Example "SHOW TABLES;" struct ShowStatement : SQLStatement { ShowStatement(ShowType type); virtual ~ShowStatement(); void tablesAccessed(TableAccessMap& accessMap) const override { TableAccess::addOperation(accessMap, name, schema, TableAccess::OpShow); }; ShowType type; char* schema; char* name; }; } // namespace hsql
ipuustin/sql-parser
include/sqlparser/ExecuteStatement.h
<gh_stars>1-10 #pragma once #include "SQLStatement.h" namespace hsql { // Represents SQL Execute statements. // Example: "EXECUTE ins_prep(100, "test", 2.3);" struct ExecuteStatement : SQLStatement { ExecuteStatement(); virtual ~ExecuteStatement(); void tablesAccessed(TableAccessMap& accessMap) const override { if (parameters != nullptr) { for (auto it = parameters->begin(); it != parameters->end(); ++it) { (*it)->tablesAccessed(accessMap); } } }; char* name; std::vector<Expr*>* parameters; }; } // namsepace hsql
ipuustin/sql-parser
include/sqlparser/InsertStatement.h
#pragma once #include "SQLStatement.h" #include "SelectStatement.h" namespace hsql { enum InsertType { kInsertValues, kInsertSelect }; // Represents SQL Insert statements. // Example: "INSERT INTO students VALUES ('Max', 1112233, 'Musterhausen', 2.3)" struct InsertStatement : SQLStatement { InsertStatement(InsertType type); virtual ~InsertStatement(); void tablesAccessed(TableAccessMap& accessMap) const override { if (tableName != nullptr) { TableAccess::addOperation(accessMap, tableName, schema, TableAccess::OpInsert); } if (values != nullptr) { for (auto it = values->begin(); it != values->end(); ++it) { (*it)->tablesAccessed(accessMap); } } if (select != nullptr) { select->tablesAccessed(accessMap); } }; InsertType type; bool priority; // default: false bool ignore; // default: false char* schema; char* tableName; std::vector<char*>* columns; std::vector<Expr*>* values; SelectStatement* select; }; } // namsepace hsql
ipuustin/sql-parser
include/sqlparser/Database.h
<reponame>ipuustin/sql-parser<gh_stars>1-10 #pragma once #include "Expr.h" #include <stdio.h> #include <vector> namespace hsql { struct DatabaseName { char* name; }; } // namespace hsql
ipuustin/sql-parser
include/sqlparser/statements.h
#pragma once #include "SelectStatement.h" #include "ImportStatement.h" #include "CreateStatement.h" #include "InsertStatement.h" #include "UpdateStatement.h" #include "DeleteStatement.h" #include "DropStatement.h" #include "AlterStatement.h" #include "PrepareStatement.h" #include "ExecuteStatement.h" #include "ShowStatement.h"
shreroa/CSE3320
sigqueue_example.c
// The MIT License (MIT) // // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Purpose: Demonstrate sending a signal via sigqueue #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> void sighandler(int signo, siginfo_t *info,void *ctx) { printf("SIGINT caught.\n"); printf("Data passed by siqueue in info->si_int: %d.\n",info->si_int); printf("Also can retrieve it in info->si_value.sival_int: %d.\n", info->si_value.sival_int); exit( EXIT_SUCCESS ); } int main(void) { struct sigaction act; /* Set up the signal handler */ act.sa_sigaction = sighandler; /* Zero out our mask. We won't be using it, but it's good practice to zero it out since we don't know if the compiler did it for us. */ sigemptyset(&act.sa_mask); act.sa_flags = SA_SIGINFO; /* Register the handler using sigaction */ if(sigaction(SIGINT,&act,NULL) == -1) { perror("sigaction: "); exit(EXIT_FAILURE); } /* Get my PID so I can send the signal to myself */ pid_t pid = getpid(); /* sigval is a union that lets us send a pointer or an int */ union sigval my_sigval; my_sigval.sival_int = 42; printf("Sending myself a SIGINT signal.\n"); if( sigqueue( pid, SIGINT, my_sigval ) == -1 ) { perror("sigqueue: "); exit(EXIT_FAILURE); } return 0; }
shreroa/CSE3320
pipe.c
<gh_stars>1-10 // The MIT License (MIT) // // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> // Demonstrate writing from one process to another using a pipe // gcc pipe.c -o pipe // To run: ./pipe <string> int main(int argc, char *argv[]) { int pfd[2]; pid_t cpid; char buf; assert(argc == 2); // Open the pipe if ( pipe(pfd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } // fork off a child process so we can use the pipe // to communicate beytween the two cpid = fork(); if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (cpid == 0) { // Close the write end of the pipe since the child // will read from the pipe close(pfd[1]); // Block and read from the pipe while (read(pfd[0], &buf, 1) > 0) { write(STDOUT_FILENO, &buf, 1); } write(STDOUT_FILENO, "\n", 1); // Done reading so close the pipe and exit close(pfd[0]); _exit(EXIT_SUCCESS); } else { // Close the read end of the pipe since the parent // just writes close(pfd[0]); // Write out the command line argument to the pipe write(pfd[1], argv[1], strlen(argv[1])); // Done, so close the pipe and wait for the child to exit close(pfd[1]); wait(NULL); exit(EXIT_SUCCESS); } }
shreroa/CSE3320
block_signal.c
<filename>block_signal.c<gh_stars>1-10 // The MIT License (MIT) // // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Purpose: Block signals with sigprocmask #include <stdio.h> #include <unistd.h> #include <signal.h> #include <string.h> int main (int argc, char *argv[]) { /* Declare a new segset mask we will fill with the signals we want to ignore */ sigset_t newmask; /* Empty out the sigset. We can't call memset as it's not guaranteed to clear the set */ sigemptyset( &newmask ); /* Add SIGINT to the set. This will allow us to ignore any ctrl-c presses */ sigaddset( &newmask, SIGINT ); sigaddset( &newmask, SIGTSTP ); /* Finally, add the new signal set to our process' control block signal mask element. This will block all SIGINT signals from reaching the process */ if( sigprocmask( SIG_BLOCK, &newmask, NULL ) < 0 ) { perror("sigprocmask "); } while (1) { sleep (1); } return 0; }
shreroa/CSE3320
fork.c
<reponame>shreroa/CSE3320 // The MIT License (MIT) // // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> /* fork() a child and print a message from the parent and a message from the child */ int main( void ) { pid_t pid = fork(); if( pid == -1 ) { // When fork() returns -1, an error happened. perror("fork failed: "); exit( EXIT_FAILURE ); } else if ( pid == 0 ) { // When fork() returns 0, we are in the child process. printf("Hello from the child process\n"); fflush(NULL); exit( EXIT_SUCCESS ); } else { // When fork() returns a positive number, we are in the parent // process and the return value is the PID of the newly created // child process. int status; // Force the parent process to wait until the child process // exits waitpid(pid, &status, 0 ); printf("Hello from the parent process\n"); fflush( NULL ); } return EXIT_SUCCESS; }
shreroa/CSE3320
mutex.c
#include <pthread.h> // for pthread_create, pthread_join, pthread_exit #include <stdio.h> // for printf #include <stdlib.h> // for exit #define NITER 1000000 pthread_mutex_t mutex; int count = 0; void * Count(void * a) { int i, tmp; for(i = 0; i < NITER; i++) { pthread_mutex_lock( &mutex ); tmp = count; /* copy the global count locally */ tmp = tmp+1; /* increment the local copy */ count = tmp; /* store the local value into the global count */ pthread_mutex_unlock( &mutex ); } } int main(int argc, char * argv[]) { pthread_t tid1, tid2; pthread_mutex_init( & mutex, NULL ); if(pthread_create(&tid1, NULL, Count, NULL)) { printf("\n ERROR creating thread 1"); exit(1); } if(pthread_create(&tid2, NULL, Count, NULL)) { printf("\n ERROR creating thread 2"); exit(1); } if(pthread_join(tid1, NULL)) /* wait for the thread 1 to finish */ { printf("\n ERROR joining thread"); exit(1); } if(pthread_join(tid2, NULL)) /* wait for the thread 2 to finish */ { printf("\n ERROR joining thread"); exit(1); } if (count < 2 * NITER) printf("\n BAD! count is [%d], should be %d\n", count, 2*NITER); else printf("\n OK! count is [%d]\n", count); pthread_exit(NULL); }
shreroa/CSE3320
shared_mem.c
// The MIT License (MIT) // // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Purpose: Demonstrate setting up a shared memory segment #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #define SHM_SIZE 1024 /* make it a 1K shared memory segment */ int main(int argc, char *argv[]) { key_t key; int shmid; char *data; int mode; if (argc > 2) { fprintf(stderr, "usage: shmdemo [data_to_write]\n"); exit(1); } /* make the key: */ if ((key = ftok("shared_mem.c", 'R')) == -1) { perror("ftok"); exit(1); } /* connect to (and possibly create) the segment: */ if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) { perror("shmget"); exit(1); } /* attach to the segment to get a pointer to it: */ data = shmat(shmid, (void *)0, 0); if (data == (char *)(-1)) { perror("shmat"); exit(1); } /* read or modify the segment, based on the command line: */ if (argc == 2) { printf("writing to segment: \"%s\"\n", argv[1]); strncpy(data, argv[1], SHM_SIZE); } else printf("segment contains: \"%s\"\n", data); /* detach from the segment: */ if (shmdt(data) == -1) { perror("shmdt"); exit(1); } return 0; }
shreroa/CSE3320
sigint_signal_block.c
// The MIT License (MIT) // // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <signal.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/time.h> // Purpose: Register a signal handler for ctrl-c (SIGINT) and demonstrate how to block signals void sig_int ( int signum ) { printf("Waiting 10 seconds to exit, but setting an alarm for 1 second. \nIf it's blocked it won't fire\n"); printf("Comment out line 27 to not block alarm.\n"); alarm(1); sigset_t sigmask; /* Create a mask set with SIGALRM in it */ sigemptyset(&sigmask); sigaddset( &sigmask, SIGALRM); /* Now block alarm signals in this handler */ sigprocmask( SIG_BLOCK, &sigmask, NULL ); struct timeval begin; struct timeval end; gettimeofday( &begin, NULL ); gettimeofday( &end, NULL ); int elapsed_time = end.tv_sec - begin.tv_sec; /* Rather than sleep let's do a busy wait and waste time */ while( elapsed_time < 10 ) { usleep(1); gettimeofday( &end, NULL ); elapsed_time = ( end.tv_sec + ( end.tv_usec / 1000000 ) ) - ( begin.tv_sec + ( begin.tv_usec / 1000000 ) ) ; } printf("Alarm didn't fire. Calling exit()\n"); exit( EXIT_SUCCESS ); } int main(int argc, char* argv[]) { /* Install the handler and check the return value. */ if (signal(SIGINT , sig_int ) < 0) { perror ("sigaction: "); return 1; } printf("Press ctrl-c\n"); while(1) { sleep(10); } }
shreroa/CSE3320
time.c
<gh_stars>1-10 #include <sys/time.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main () { struct timeval begin; struct timeval end; gettimeofday( &begin, NULL ); sleep(5); gettimeofday( &end, NULL ); int time_duration = ( ( end.tv_sec - begin.tv_sec ) * 1000000 + ( end.tv_usec - begin.tv_usec ) ); printf("Duration: %d\n", time_duration ); return 0; }
shreroa/CSE3320
memmap.c
<reponame>shreroa/CSE3320<gh_stars>1-10 // The MIT License (MIT) // // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <errno.h> #include <stdio.h> // Purpose: Demonstrate memory mapping a file and returning data from the file int main(int argc, char *argv[]) { int fd, offset; char *data; struct stat sbuf; if (argc != 2) { fprintf(stderr, "usage: mem_map offset\n"); exit(1); } if ((fd = open("mem_map.c", O_RDONLY)) == -1) { perror("open"); exit(1); } if (stat("mem_map.c", &sbuf) == -1) { perror("stat"); exit(1); } offset = atoi(argv[1]); if (offset < 0 || offset > sbuf.st_size-1) { fprintf(stderr, "mem_map: offset must be in the range 0-%d\n", sbuf.st_size-1); exit(1); } data = mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0) ; if (data == (caddr_t)(-1)) { perror("mmap"); exit(1); } printf("byte at offset %d is '%c'\n", offset, data[offset]); return 0; }
shreroa/CSE3320
multiple_signals.c
// The MIT License (MIT) // // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Purpose: Register multiple signals to a single handler #include <stdio.h> #include <unistd.h> #include <signal.h> #include <string.h> static void handle_signal (int sig ) { /* Determine which of the two signals were caught and print an appropriate message. */ switch( sig ) { case SIGINT: printf("Caught a SIGINT\n"); break; case SIGTSTP: printf("Caught a SIGTSTP\n"); break; default: printf("Unable to determine the signal\n"); break; } } static void handle_alarm ( int sig ) { printf("Caught alarm\n"); /* Resetting the alarm otherwise it's one and done */ alarm(1); } int main (int argc, char *argv[]) { struct sigaction act; /* Zero out the sigaction struct */ memset (&act, '\0', sizeof(act)); /* Set the handler to use the function handle_signal() */ act.sa_handler = &handle_signal; /* Install the handler for SIGINT and SIGTSTP and check the return value. */ if (sigaction(SIGINT , &act, NULL) < 0) { perror ("sigaction: "); return 1; } if (sigaction(SIGTSTP , &act, NULL) < 0) { perror ("sigaction: "); return 1; } /* Set the handler to use the function handle_alarm() */ act.sa_handler = &handle_alarm; if (sigaction(SIGALRM , &act, NULL) < 0) { perror ("sigalarm: "); return 1; } alarm(1); while (1) { sleep (1); } return 0; }
vkrotin/ASNotificationCenter
core/ASNotifiation.h
// // ASNotifiation.h // AppSafeNotificationCenter // // Created by <NAME> on 16.03.17. // Copyright © 2017 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> typedef NSString *ASNotificationName NS_EXTENSIBLE_STRING_ENUM; @interface ASNotifiation : NSObject @property (nonatomic, strong) id observer; @property (nonatomic, assign) SEL selector; @property (nonatomic, strong) ASNotificationName name; @property (nonatomic, strong) id object; @property (nonatomic, strong) NSDictionary *userInfo; -(instancetype) initObserver:(id) _observer selector:(SEL) _selector name:(ASNotificationName) _name object:(id) _object; @end
vkrotin/ASNotificationCenter
core/ASNotificationCenter.h
<gh_stars>0 // // ASNotificationCenter.h // AppSafeNotificationCenter // // Created by <NAME> on 16.03.17. // Copyright © 2017 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "ASNotifiation.h" #define _protectedCenter [ASNotificationCenter protectedCenter] @interface ASNotificationCenter : NSObject @property (class, readonly, strong) ASNotificationCenter *protectedCenter; - (void)addObserver:(id)observer selector:(SEL)aSelector name:(ASNotificationName)aName object:(id)anObject; - (void)postNotification:(ASNotifiation *)notification; - (void)postNotificationName:(ASNotificationName)aName object:(id)anObject; - (void)postNotificationName:(ASNotificationName)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo; - (void)removeObserver:(id)observer; - (void)removeObserver:(id)observer name:(ASNotificationName)aName object:(id)anObject; @end
vkrotin/ASNotificationCenter
Example/ASNotificationCenter/ASAppDelegate.h
// // ASAppDelegate.h // ASNotificationCenter // // Created by <NAME> on 03/16/2017. // Copyright (c) 2017 <NAME>. All rights reserved. // @import UIKit; @interface ASAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
vkrotin/ASNotificationCenter
Example/ASNotificationCenter/ASModalViewController.h
// // ASModalViewController.h // ASNotificationCenter // // Created by <NAME> on 16.03.17. // Copyright © 2017 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface ASModalViewController : UIViewController @end
vkrotin/ASNotificationCenter
Example/ASNotificationCenter/UIColor+ASRandom.h
<reponame>vkrotin/ASNotificationCenter // // UIColor+ASRandom.h // ASNotificationCenter // // Created by <NAME> on 16.03.17. // Copyright © 2017 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface UIColor (ASRandom) +(UIColor *) randomColor; @end
vkrotin/ASNotificationCenter
Example/Pods/Target Support Files/ASNotificationCenter/ASNotificationCenter-umbrella.h
<filename>Example/Pods/Target Support Files/ASNotificationCenter/ASNotificationCenter-umbrella.h<gh_stars>0 #ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "ASNotifiation.h" #import "ASNotificationCenter.h" FOUNDATION_EXPORT double ASNotificationCenterVersionNumber; FOUNDATION_EXPORT const unsigned char ASNotificationCenterVersionString[];
vkrotin/ASNotificationCenter
Example/ASNotificationCenter/ASViewController.h
// // ASViewController.h // ASNotificationCenter // // Created by <NAME> on 03/16/2017. // Copyright (c) 2017 <NAME>. All rights reserved. // @import UIKit; @interface ASViewController : UIViewController @end
CodeChalenges/vcd-delay-analyzer
include/utils.h
#ifndef UTILS_H #define UTILS_H unsigned char startsWith(const char* prefix, const char* str); #endif
CodeChalenges/vcd-delay-analyzer
src/signal.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "signal.h" void createSignal(Signal** signals, unsigned int* nsignals, char* name, char symbol) { Signal* newSignal = (Signal*)malloc(sizeof(newSignal)); newSignal->name = (char*)malloc(strlen(name) * sizeof(char)); strcpy(newSignal->name, name); newSignal->symbol = symbol; newSignal->currentSignalValue = 'X'; newSignal->hasPassedInIdle = 0; newSignal->lastSignalChangeTimestamp = 0; newSignal->shortestIdleDelay = UINT_MAX; newSignal->longestIdleDelay = 0; *signals = (Signal*)realloc(*signals, (++(*nsignals)) * sizeof(Signal)); (*signals)[*nsignals-1] = *newSignal; } Signal* findSignalBySymbol(Signal* signals, unsigned int nsignals, char symbol) { unsigned int i; for (i = 0; i < nsignals; i++) { if (signals[i].symbol == symbol) { return &signals[i]; } } return NULL; } void assignSignalUpdate(Signal *signal, unsigned char signalValue, int timestamp) { if (signalValue == 0) { signal->hasPassedInIdle = 1; } else if (signal->currentSignalValue == 0) { // Signal leaving idle state: // Calculate delay and and check shortest and longest boundaries unsigned int delay = timestamp - signal->lastSignalChangeTimestamp; if (delay < signal->shortestIdleDelay) { signal->shortestIdleDelay = delay; } if (delay > signal->longestIdleDelay) { signal->longestIdleDelay = delay; } } signal->currentSignalValue = signalValue; signal->lastSignalChangeTimestamp = timestamp; } void closeSignalCounters(Signal* signal, unsigned int timestamp) { if (signal->currentSignalValue == 0) { unsigned int delay = timestamp - signal->lastSignalChangeTimestamp; if (delay < signal->shortestIdleDelay) { signal->shortestIdleDelay = delay; } if (delay > signal->longestIdleDelay) { signal->longestIdleDelay = delay; } } } void printSignal(Signal* signal) { printf("[SIGNAL] Name: %-15s Symbol: %-3c lastSignalChangeTimestamp: %-6d ShortestIdleDelay: %-6d LongestIdleDelay: %d\n", signal->name, signal->symbol, signal->lastSignalChangeTimestamp, (signal->hasPassedInIdle) ? signal->shortestIdleDelay : -1, (signal->hasPassedInIdle) ? signal->longestIdleDelay : -1); }
CodeChalenges/vcd-delay-analyzer
include/signal.h
#ifndef SIGNAL_H #define SIGNAL_H typedef struct { char* name; char symbol; unsigned char currentSignalValue; unsigned char hasPassedInIdle; unsigned int lastSignalChangeTimestamp; unsigned int shortestIdleDelay; unsigned int longestIdleDelay; } Signal; /* Create a new signal */ void createSignal(Signal** signals, unsigned int* nsignals, char* name, char symbol); /* Find a signal by its symbol in VCD */ Signal* findSignalBySymbol(Signal* signals, unsigned int nsignals, char symbol); /* Assign a signal value change */ void assignSignalUpdate(Signal *signal, unsigned char signalValue, int timestamp); /* Close all signal counters */ void closeSignalCounters(Signal* signal, unsigned int timestamp); /* Print signal info */ void printSignal(Signal* signal); #endif
CodeChalenges/vcd-delay-analyzer
src/utils.c
#include <string.h> #include "utils.h" unsigned char startsWith(const char* prefix, const char* str) { size_t lenpre = strlen(prefix), lenstr = strlen(str); return lenstr < lenpre ? 0 : (strncmp(prefix, str, lenpre) == 0); }
CodeChalenges/vcd-delay-analyzer
src/main.c
<filename>src/main.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include "signal.h" #include "utils.h" int main(int argc, char* argv[]) { Signal* signals = NULL; unsigned int nsignals = 0; const char* vcd_file = argv[1]; char* name; char id; // Read VCD file FILE* fp; char* line = NULL; ssize_t len = 0; char* token = NULL; char* signalName = NULL; char signalId; if((fp = fopen(vcd_file, "r")) == NULL) { fprintf(stderr, "Failed to open VCD file: %s\n", vcd_file); exit(1); } unsigned char dumpVarsStarted = 0, dumpVarsEnded = 0; unsigned int timestamp = 0; while (getline(&line, &len, fp) != -1) { // Removing trailing line break if (line[strlen(line)-1] == '\n') { line[strlen(line)-1] = '\0'; } // Signal declaration line if (startsWith("$var", line)) { // Ignore the first 3 parts of string. // Signal symbol is in the 4o part. // Signal name is in the 5o part. strtok(line, " "); strtok(NULL, " "); strtok(NULL, " "); token = strtok(NULL, " "); signalName = strtok(NULL, " "); signalId = token[0]; createSignal(&signals, &nsignals, signalName, signalId); } else if (startsWith("$dumpvars", line)) { dumpVarsStarted = 1; } else if (startsWith("$end", line) && dumpVarsStarted) { dumpVarsEnded = 1; } else if (dumpVarsEnded) { if (line[0] == '#') { // Timestamp update char timestampStr[16]; strcpy(timestampStr, line+1); timestamp = atoi(timestampStr); } else { // Signal value update unsigned char value = line[0] - 0x30; char symbol = line[strlen(line)-1]; Signal* signal = findSignalBySymbol(signals, nsignals, symbol); assignSignalUpdate(signal, value, timestamp); } } } // close all signals counters unsigned int i; for (i = 0; i < nsignals; i++) { closeSignalCounters(&signals[i], timestamp); } printf("--- REPORT ---\n"); Signal *sigShortDelay = NULL, *sigLongDelay = NULL; for(i = 0; i < nsignals; i++) { printSignal(&signals[i]); if (sigShortDelay == NULL || signals[i].shortestIdleDelay < sigShortDelay->shortestIdleDelay) { sigShortDelay = &signals[i]; } if (sigLongDelay == NULL || signals[i].longestIdleDelay > sigLongDelay->longestIdleDelay) { sigLongDelay = &signals[i]; } } printf("\nNumber of Signals: %d\n", nsignals); printf("Shortest delay: signal \"%s\" with delay of %d\n", sigShortDelay ? sigShortDelay->name : "", sigShortDelay ? sigShortDelay->shortestIdleDelay : -1); printf("Longest delay: signal \"%s\" with delay of %d\n", sigLongDelay ? sigLongDelay->name : "", sigLongDelay ? sigLongDelay->longestIdleDelay : -1); return 0; }
matthewmascord/esp8266-blink
test/mocks/ets_sys.h
<reponame>matthewmascord/esp8266-blink #include <stdint.h> #ifndef _ETS_SYS_H_ #define _ETS_SYS_H_ #define ICACHE_FLASH_ATTR #define UART_CLK_FREQ 80*1000000 void uart_div_modify(uint8_t uart_no, uint32_t DivLatchValue); #endif
matthewmascord/esp8266-blink
test/mocks/osapi.h
<reponame>matthewmascord/esp8266-blink #include <stdint.h> #include <stdbool.h> #ifndef _OSAPI_H_ #define _OSAPI_H_ typedef void os_timer_func_t(void *timer_arg); typedef struct _os_timer_t_ { struct _os_timer_t_ *timer_next; uint32_t timer_expire; uint32_t timer_period; os_timer_func_t *timer_func; void *timer_arg; } os_timer_t; void os_timer_arm(os_timer_t *ptimer, uint32_t time, bool repeat_flag); void os_timer_disarm(os_timer_t *ptimer); void os_timer_setfn(os_timer_t *ptimer, os_timer_func_t *pfunction, void *parg); int os_printf_plus(const char *format, ...) __attribute__ ((format (printf, 1, 2))); #define os_printf os_printf_plus #endif
matthewmascord/esp8266-blink
test/mocks/user_interface.h
<gh_stars>0 #include <stdint.h> #include <stdbool.h> #ifndef _USER_INTERFACE_H_ #define _USER_INTERFACE_H_ typedef enum { SYSTEM_PARTITION_BOOTLOADER, SYSTEM_PARTITION_OTA_1, SYSTEM_PARTITION_OTA_2, SYSTEM_PARTITION_RF_CAL, SYSTEM_PARTITION_PHY_DATA, SYSTEM_PARTITION_SYSTEM_PARAMETER, SYSTEM_PARTITION_CUSTOMER_BEGIN = 100, } partition_type_t; typedef struct { partition_type_t type; /* the partition type */ uint32_t addr; /* the partition address */ uint32_t size; /* the partition size */ } partition_item_t; bool system_partition_table_regist( const partition_item_t* partition_table, uint32_t partition_num, uint32_t map ); #endif
matthewmascord/esp8266-blink
src/main.c
#include "main.h" #ifdef GDB_DEBUG #include "gdbstub.h" #endif #include <stddef.h> #include "gpio.h" #include "os_type.h" #include "user_interface.h" #define SPI_FLASH_SIZE_MAP 4 #define SYSTEM_PARTITION_OTA_SIZE 0x6A000 #define SYSTEM_PARTITION_OTA_2_ADDR 0x81000 #define SYSTEM_PARTITION_RF_CAL_ADDR 0x3fb000 #define SYSTEM_PARTITION_PHY_DATA_ADDR 0x3fc000 #define SYSTEM_PARTITION_SYSTEM_PARAMETER_ADDR 0x3fd000 #define SYSTEM_PARTITION_CUSTOMER_PRIV_PARAM_ADDR 0x7c000 #define SYSTEM_PARTITION_CUSTOMER_PRIV_PARAM SYSTEM_PARTITION_CUSTOMER_BEGIN static const partition_item_t at_partition_table[] = { { SYSTEM_PARTITION_BOOTLOADER, 0x0, 0x1000}, { SYSTEM_PARTITION_OTA_1, 0x1000, SYSTEM_PARTITION_OTA_SIZE}, { SYSTEM_PARTITION_OTA_2, SYSTEM_PARTITION_OTA_2_ADDR, SYSTEM_PARTITION_OTA_SIZE}, { SYSTEM_PARTITION_RF_CAL, SYSTEM_PARTITION_RF_CAL_ADDR, 0x1000}, { SYSTEM_PARTITION_PHY_DATA, SYSTEM_PARTITION_PHY_DATA_ADDR, 0x1000}, { SYSTEM_PARTITION_SYSTEM_PARAMETER, SYSTEM_PARTITION_SYSTEM_PARAMETER_ADDR, 0x3000}, { SYSTEM_PARTITION_CUSTOMER_PRIV_PARAM, SYSTEM_PARTITION_CUSTOMER_PRIV_PARAM_ADDR, 0x1000}, }; void ICACHE_FLASH_ATTR user_pre_init(void) { if(!system_partition_table_regist(at_partition_table, sizeof(at_partition_table)/sizeof(at_partition_table[0]),SPI_FLASH_SIZE_MAP)) { os_printf("system_partition_table_regist fail\r\n"); while(1); } } static const int pin = 2; os_timer_t timer; void DoBlinkyStuff() { if (GPIO_REG_READ(GPIO_OUT_ADDRESS) & (1 << pin)) { // set gpio low gpio_output_set(0, (1 << pin), 0, 0); } else { // set gpio high gpio_output_set((1 << pin), 0, 0, 0); } } void SetupTimer() { os_timer_setfn(&timer, (os_timer_func_t *)DoBlinkyStuff, NULL); os_timer_arm(&timer, 250, 1); } void EnablePins() { gpio_output_set(0, 0, (1 << pin), 0); } void ICACHE_FLASH_ATTR user_init(void) { uart_div_modify(0, UART_CLK_FREQ / 115200); #ifdef GDB_DEBUG gdbstub_init(); #endif gpio_init(); EnablePins(); SetupTimer(); }
matthewmascord/esp8266-blink
test/TestMain.c
#include "main.h" #include "unity.h" #include "Mockgpio.h" #include "Mockets_sys.h" #include "Mockosapi.h" #include "Mockgdbstub.h" #include <stdint.h> const uint32_t noPinsMask = 0; const uint32_t pinMask = 4; const uint32_t otherPinMask = 8; void setUp(void) { gpio_init_Ignore(); gpio_output_set_Ignore(); uart_div_modify_Ignore(); os_timer_setfn_Ignore(); os_timer_arm_Ignore(); gdbstub_init_Ignore(); } void tearDown(void) { } void test_UserInit_ShouldEnableTheUart(void) { uart_div_modify_Expect(0, 694); user_init(); } void test_UserInit_ShouldInitializeTheGpio(void) { gpio_init_Expect(); user_init(); } void test_UserInit_ShouldEnableTheCorrectPin(void) { gpio_output_set_Expect(0, 0, pinMask, 0); user_init(); } void test_UserInit_ShouldInitializeTheTimerCorrectly(void) { os_timer_setfn_Expect(&timer, (os_timer_func_t *)DoBlinkyStuff, NULL); user_init(); } void test_UserInit_ShouldSetTheTimer(void) { os_timer_arm_Expect(&timer, 250, true); user_init(); } void test_DoBlinkyStuff_ShouldSetTheOutputIfCleared(void) { GPIO_REG_READ_ExpectAndReturn(GPIO_OUT_ADDRESS, otherPinMask); gpio_output_set_Expect(pinMask, 0, 0, 0); DoBlinkyStuff(); } void test_DoBlinkyStuff_ShouldSetTheOutputIfNoOutputsAreSet(void) { GPIO_REG_READ_ExpectAndReturn(GPIO_OUT_ADDRESS, noPinsMask); gpio_output_set_Expect(pinMask, 0, 0, 0); DoBlinkyStuff(); } void test_DoBlinkyStuff_ShouldClearTheOutputIfSet(void) { GPIO_REG_READ_ExpectAndReturn(GPIO_OUT_ADDRESS, pinMask); gpio_output_set_Expect(0, pinMask, 0, 0); DoBlinkyStuff(); }
matthewmascord/esp8266-blink
src/main.h
#include "ets_sys.h" #include "osapi.h" void DoBlinkyStuff(void); void ICACHE_FLASH_ATTR user_init(void); extern os_timer_t timer;
matthewmascord/esp8266-blink
test/mocks/gpio.h
#include <stdint.h> #ifndef _GPIO_H_ #define _GPIO_H_ #define GPIO_OUT_ADDRESS (uint32_t) 0 void gpio_init(void); void gpio_output_set(uint32_t set_mask, uint32_t clear_mask, uint32_t enable_mask, uint32_t disable_mask); uint32_t GPIO_REG_READ(uint32_t address); #endif
1apple7seeds/ROSPlan
rosplan_knowledge_base/include/rosplan_knowledge_base/VALVisitorPredicate.h
<gh_stars>1-10 /** * This file describes VALVisitorPredicate class. * KMS VALVisitor classes are used to package PDDL things into ROS messages. */ #include <sstream> #include <string> #include <vector> #include "ptree.h" #include "VisitController.h" #include "rosplan_knowledge_msgs/DomainFormula.h" #ifndef KCL_valvisitor_predicate #define KCL_valvisitor_predicate namespace KCL_rosplan { class VALVisitorPredicate : public VAL::VisitController { private: public: /* message */ rosplan_knowledge_msgs::DomainFormula msg; /* visitor methods */ virtual void visit_pred_decl(VAL::pred_decl *); }; } // close namespace #endif
1apple7seeds/ROSPlan
rosplan_knowledge_base/src/VALfiles/ValidatorAPI.h
#ifndef VAL_API #define VAL_API #include <sstream> namespace VAL { bool checkPlan(const std::string& domain_file, const std::string& problem_file, std::stringstream& plan); }; #endif
1apple7seeds/ROSPlan
rosplan_knowledge_base/src/VALfiles/Environment.h
<filename>rosplan_knowledge_base/src/VALfiles/Environment.h /************************************************************************ * Copyright 2008, Strathclyde Planning Group, * Department of Computer and Information Sciences, * University of Strathclyde, Glasgow, UK * http://planning.cis.strath.ac.uk/ * * <NAME>, <NAME> and <NAME> - VAL * <NAME>well - PDDL Parser * * This file is part of VAL, the PDDL validator. * * VAL is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * VAL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VAL. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ /*----------------------------------------------------------------------------- VAL - The Automatic Plan Validator for PDDL+ $Date: 2009-02-05 10:50:12 $ $Revision: 1.2 $ <NAME>, <NAME> and <NAME> - PDDL+ and VAL <NAME>resswell - PDDL Parser <EMAIL> <EMAIL> <EMAIL> <EMAIL> By releasing this code we imply no warranty as to its reliability and its use is entirely at your own risk. Strathclyde Planning Group http://planning.cis.strath.ac.uk ----------------------------------------------------------------------------*/ #include <map> #include <vector> namespace VAL { class var_symbol; class const_symbol; class Validator; }; //#undef vector //#undef map using std::map; using std::vector; #ifndef __MYENVIRONMENT #define __MYENVIRONMENT //#define vector std::vector namespace VAL { template<class T> bool operator != (T & t1,T & t2) {return ! (t1==t2);}; struct Environment : public map<const var_symbol*,const const_symbol*> { static map<Validator*,vector<Environment *> > copies; double duration; Environment * copy(Validator * v) const { Environment * e = new Environment(*this); copies[v].push_back(e); //cout << "Copy of "<<this<<" to "<<e<<"\\\\\n"; return e; }; static void collect(Validator * v) { for(vector<Environment *>::iterator i = copies[v].begin();i != copies[v].end();++i) delete *i; copies[v].clear(); //cout << "Deleting the copies of enviroments here!\\\\\n"; }; }; template<class TI> struct EnvironmentParameterIterator { Environment * env; TI pi; EnvironmentParameterIterator(Environment * f,TI p) : env(f), pi(p) {}; // Having to cast the const is not good...currently we are forced to do it in order // to interact with Cascader, but should look at fixing it. const_symbol * operator*() { if(const_symbol * s = const_cast<const_symbol *>(dynamic_cast<const const_symbol *>(*pi))) { return s; }; return const_cast<const_symbol*>((*env)[dynamic_cast<const var_symbol *>(*pi)]); }; EnvironmentParameterIterator & operator++() { ++pi; return *this; }; bool operator==(const EnvironmentParameterIterator<TI> & li) const { return pi==li.pi; }; bool operator!=(const EnvironmentParameterIterator<TI> & li) const { return pi!=li.pi; }; }; template<class TI> EnvironmentParameterIterator<TI> makeIterator(Environment * f,TI p) { return EnvironmentParameterIterator<TI>(f,p); }; }; #endif
1apple7seeds/ROSPlan
rosplan_planning_system/include/rosplan_planning_system/PlanDispatch/EsterelPlanDispatcher.h
#include <stdlib.h> #include <map> #include <iostream> #include <string> #include <boost/regex.hpp> #include <boost/concept_check.hpp> #include "PlanDispatcher.h" #include "rosplan_knowledge_msgs/KnowledgeQueryService.h" #include "rosplan_knowledge_msgs/GetDomainOperatorDetailsService.h" #include "rosplan_knowledge_msgs/DomainOperator.h" #include "rosplan_knowledge_msgs/KnowledgeItem.h" #include "rosplan_dispatch_msgs/EsterelPlan.h" #include "std_msgs/String.h" #ifndef KCL_esterel_dispatcher #define KCL_esterel_dispatcher namespace KCL_rosplan { class EsterelPlanDispatcher: public PlanDispatcher { private: /** * @returns node ID associated with action ID if it exists, -1 otherwise */ int getNodeFromActionID(int action_id, bool end_node) { std::vector<rosplan_dispatch_msgs::EsterelPlanNode>::const_iterator ci = current_plan.nodes.begin(); for(; ci != current_plan.nodes.end(); ci++) { if(ci->action.action_id == action_id) { if(!end_node && ci->node_type == rosplan_dispatch_msgs::EsterelPlanNode::ACTION_START) return ci->node_id; else if(end_node && ci->node_type == rosplan_dispatch_msgs::EsterelPlanNode::ACTION_END) return ci->node_id; } } return -1; } // esterel plan methods void initialise(); // current plan and time plan was recevied rosplan_dispatch_msgs::EsterelPlan current_plan; double mission_start_time; // plan status std::map<int,bool> edge_active; std::map<int,bool> action_dispatched; bool state_changed; bool finished_execution; /* plan graph publisher */ bool printPlan(); ros::Publisher plan_graph_publisher; /* check preconditions are true */ bool checkPreconditions(rosplan_dispatch_msgs::ActionDispatch msg); ros::ServiceClient query_knowledge_client; ros::ServiceClient query_domain_client; public: /* constructor */ EsterelPlanDispatcher(ros::NodeHandle& nh); ~EsterelPlanDispatcher(); void planCallback(const rosplan_dispatch_msgs::EsterelPlan plan); void reset(); /* action dispatch methods */ bool dispatchPlanService(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res); bool dispatchPlan(double missionStartTime, double planStartTime); /* action feedback methods */ void feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg); }; } #endif
1apple7seeds/ROSPlan
rosplan_knowledge_base/include/rosplan_knowledge_base/DomainParser.h
<reponame>1apple7seeds/ROSPlan #include <ros/ros.h> #include <vector> #include <iostream> #include <fstream> #include "ptree.h" #include "FlexLexer.h" #ifndef KCL_domainparser #define KCL_domainparser extern int yyparse(); extern int yydebug; namespace VAL { extern analysis an_analysis; extern yyFlexLexer* yfl; }; /** * Domain storage and parsing. Uses VAL parser and storage. */ namespace KCL_rosplan { /*--------*/ /* parser */ /*--------*/ class DomainParser { private: public: /* VAL pointers */ VAL::analysis * val_analysis; VAL::domain* domain; /* domain information */ bool domain_parsed; std::string domain_name; /* domain parsing */ VAL::domain* parseDomain(const std::string domainPath); }; } #endif
1apple7seeds/ROSPlan
rosplan_knowledge_base/src/VALfiles/LaTeXSupport.h
/************************************************************************ * Copyright 2008, Strathclyde Planning Group, * Department of Computer and Information Sciences, * University of Strathclyde, Glasgow, UK * http://planning.cis.strath.ac.uk/ * * <NAME>, <NAME> and <NAME> - VAL * <NAME>well - PDDL Parser * * This file is part of VAL, the PDDL validator. * * VAL is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * VAL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VAL. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************/ /*----------------------------------------------------------------------------- VAL - The Automatic Plan Validator for PDDL+ $Date: 2009-02-05 10:50:20 $ $Revision: 1.2 $ <NAME>, <NAME> and <NAME> - PDDL+ and VAL <NAME>resswell - PDDL Parser <EMAIL> <EMAIL> <EMAIL> <EMAIL> By releasing this code we imply no warranty as to its reliability and its use is entirely at your own risk. Strathclyde Planning Group http://planning.cis.strath.ac.uk ----------------------------------------------------------------------------*/ #ifndef __LATEXSUPPORT #define __LATEXSUPPORT #include <vector> #include <string> #include <iostream> #include "Utils.h" #include "main.h" #include "Validator.h" using std::ostream; using std::string; using std::vector; namespace VAL { struct showList { void operator()(const pair<double,vector<string> > & ps) const { if(LaTeX) { string s; *report << ps.first<<" \\>"; for(vector<string>::const_iterator i = ps.second.begin(); i != ps.second.end() ; ++i) { s = *i; replaceSubStrings(s,"/","/\\-"); latexString(s); *report << "\\begin{minipage}[t]{12cm} " << s << " \\end{minipage}\\\\\n \\>"; }; *report << "\\\\\n"; } else { cout << "\nValue: " << ps.first << "\n "; copy(ps.second.begin(),ps.second.end(),ostream_iterator<string>(cout," ")); cout << "\n"; }; }; }; void displayFailedLaTeXList(vector<string> & vs); class LaTeXSupport { private: int NoGraphPoints; int noPoints; int noGCPages; int noGCPageRows; vector<string> ganttObjectsAndTypes; vector<string> ganttObjects; public: LaTeXSupport() : NoGraphPoints(500), noGCPages(0), noGCPageRows(0) {}; void LaTeXHeader(); void LaTeXPlanReportPrepare(char *); void LaTeXPlanReport(Validator * v,plan *); void LaTeXEnd(); void LaTeXGantt(Validator * v); void LaTeXGraphs(Validator * v); void LaTeXDomainAndProblem(); void LaTeXBuildGraph(ActiveCtsEffects * ace,const State * s); void setnoGCPages(int g) {noGCPages = g;}; void setnoGCPageRows(int g) {noGCPageRows = g;}; void setnoPoints(int n) { noPoints = n; if(noPoints < 10) noPoints = 10; else if(noPoints > 878) noPoints = 878; NoGraphPoints = noPoints; }; void addGanttObject(char * c) { ganttObjectsAndTypes.push_back(c); }; }; extern LaTeXSupport latex; }; #endif
1apple7seeds/ROSPlan
rosplan_planning_system/include/rosplan_planning_system/PlannerInterface/PlannerInterface.h
#include "ros/ros.h" #include "actionlib/server/simple_action_server.h" #include "std_msgs/String.h" #include "std_srvs/Empty.h" #include "rosplan_dispatch_msgs/PlanningService.h" #include "rosplan_dispatch_msgs/PlanAction.h" #ifndef KCL_planner_interface #define KCL_planner_interface /** * This file contains an interface to the planner. */ namespace KCL_rosplan { class PlannerInterface { private: protected: ros::NodeHandle* node_handle; actionlib::SimpleActionServer<rosplan_dispatch_msgs::PlanAction>* plan_server; /* params */ bool use_problem_topic; std::string planner_command; std::string domain_path; std::string problem_path; std::string problem_name; std::string data_path; /* planner outputs */ std::string planner_output; /* problem subscription */ std::string problem_instance; bool problem_instance_received; double problem_instance_time; /* planning */ virtual bool runPlanner() =0; public: void problemCallback(const std_msgs::String& problemInstance); bool runPlanningServerDefault(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res); bool runPlanningServerParams(rosplan_dispatch_msgs::PlanningService::Request &req, rosplan_dispatch_msgs::PlanningService::Response &res); void runPlanningServerAction(const rosplan_dispatch_msgs::PlanGoalConstPtr& goal); bool runPlanningServer(std::string domainPath, std::string problemPath, std::string dataPath, std::string plannerCommand, bool useProblemTopic); /* ROS interface */ ros::Publisher plan_publisher; }; } // close namespace #endif
1apple7seeds/ROSPlan
rosplan_knowledge_base/include/rosplan_knowledge_base/VALVisitorProblem.h
<reponame>1apple7seeds/ROSPlan<filename>rosplan_knowledge_base/include/rosplan_knowledge_base/VALVisitorProblem.h<gh_stars>1-10 /** * This file describes VALVisitorProblem class. * KMS VALVisitor classes are used to package PDDL things into ROS messages. */ #include <ros/ros.h> #include <sstream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include "ptree.h" #include "VisitController.h" #include "rosplan_knowledge_base/KnowledgeComparitor.h" #include "rosplan_knowledge_msgs/DomainFormula.h" #include "rosplan_knowledge_msgs/KnowledgeItem.h" #include "rosplan_knowledge_msgs/ExprComposite.h" #include "rosplan_knowledge_msgs/ExprBase.h" #ifndef KCL_valvisitor_problem #define KCL_valvisitor_problem namespace KCL_rosplan { class VALVisitorProblem : public VAL::VisitController { private: /* encoding state */ bool problem_cond_neg; bool problem_eff_neg; double problem_eff_time; VAL::domain* domain; VAL::problem* problem; bool effects_read; public: /* constructor */ VALVisitorProblem(VAL::domain* inputDomain, VAL::problem* inputProblem){ domain = inputDomain; problem = inputProblem; problem_eff_time = 0; effects_read = false; problem_cond_neg = false; problem_eff_neg = false; } /* messages */ rosplan_knowledge_msgs::DomainFormula last_prop; rosplan_knowledge_msgs::ExprComposite last_expr; rosplan_knowledge_msgs::DomainFormula last_func_term; std::map<std::string, std::vector<std::string> > instances; std::map<std::string, std::vector<std::string> > constants; std::vector<rosplan_knowledge_msgs::KnowledgeItem> facts; std::vector<rosplan_knowledge_msgs::KnowledgeItem> functions; std::vector<rosplan_knowledge_msgs::KnowledgeItem> goals; rosplan_knowledge_msgs::KnowledgeItem metric; /* timed initial literals */ std::vector<rosplan_knowledge_msgs::KnowledgeItem> timed_initial_literals; /* return methods */ std::map<std::string, std::vector<std::string> > returnInstances(); std::vector<rosplan_knowledge_msgs::KnowledgeItem> returnFacts(); std::vector<rosplan_knowledge_msgs::KnowledgeItem> returnFunctions(); std::vector<rosplan_knowledge_msgs::KnowledgeItem> returnGoals(); rosplan_knowledge_msgs::KnowledgeItem returnMetric(); std::vector<rosplan_knowledge_msgs::KnowledgeItem> returnTimedKnowledge(); /* visitor methods */ virtual void visit_proposition(VAL::proposition *); virtual void visit_operator_(VAL::operator_ *); virtual void visit_simple_goal(VAL::simple_goal *); virtual void visit_qfied_goal(VAL::qfied_goal *); virtual void visit_conj_goal(VAL::conj_goal *); virtual void visit_disj_goal(VAL::disj_goal *); virtual void visit_timed_goal(VAL::timed_goal *); virtual void visit_imply_goal(VAL::imply_goal *); virtual void visit_neg_goal(VAL::neg_goal *); virtual void visit_assignment(VAL::assignment * e); virtual void visit_simple_effect(VAL::simple_effect * e); virtual void visit_forall_effect(VAL::forall_effect * e); virtual void visit_cond_effect(VAL::cond_effect * e); virtual void visit_timed_effect(VAL::timed_effect * e); virtual void visit_timed_initial_literal(VAL::timed_initial_literal * s); virtual void visit_effect_lists(VAL::effect_lists * e); virtual void visit_comparison(VAL::comparison * c); virtual void visit_derivation_rule(VAL::derivation_rule * o); virtual void visit_metric_spec(VAL:: metric_spec * s); virtual void visit_plus_expression(VAL::plus_expression * s); virtual void visit_minus_expression(VAL::minus_expression * s); virtual void visit_mul_expression(VAL::mul_expression * s); virtual void visit_div_expression(VAL::div_expression * s); virtual void visit_uminus_expression(VAL::uminus_expression * s); virtual void visit_int_expression(VAL::int_expression * s); virtual void visit_float_expression(VAL::float_expression * s); virtual void visit_special_val_expr(VAL::special_val_expr * s); virtual void visit_func_term(VAL::func_term * s); }; } // close namespace #endif
1apple7seeds/ROSPlan
rosplan_planning_system/include/rosplan_planning_system/PlanDispatch/PlanDispatcher.h
/** * This file describes a class that dispatches a plan. */ #include "ros/ros.h" #include "rosplan_dispatch_msgs/ActionFeedback.h" #include "rosplan_dispatch_msgs/ActionDispatch.h" #include "std_srvs/Empty.h" #ifndef KCL_dispatcher #define KCL_dispatcher namespace KCL_rosplan { class PlanDispatcher { protected: ros::NodeHandle* node_handle; std::string action_dispatch_topic; std::string action_feedback_topic; /* dispatch state */ bool plan_received; std::map<int,bool> action_received; std::map<int,bool> action_completed; public: /* control callback */ bool cancelDispatchService(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) { ROS_INFO("KCL: (%s) Cancel plan command received.", ros::this_node::getName().c_str()); plan_cancelled = true; return true; } /* dispatch modes */ bool dispatch_paused; bool replan_requested; bool plan_cancelled; virtual void reset() =0; /* plan dispatch methods */ virtual bool dispatchPlan(double missionStartTime, double planStartTime) =0; virtual bool dispatchPlanService(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) =0; /* action feedback methods */ virtual void feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg) =0; /* action publishers */ ros::Publisher action_dispatch_publisher; ros::Publisher action_feedback_publisher; }; } #endif
1apple7seeds/ROSPlan
rosplan_interface_movebase/include/rosplan_interface_movebase/RPMoveBase.h
#include <ros/ros.h> #include <vector> #include <iostream> #include <fstream> #include <boost/foreach.hpp> #include "rosplan_action_interface/RPActionInterface.h" #include "actionlib/client/simple_action_client.h" #include "move_base_msgs/MoveBaseAction.h" #include "mongodb_store/message_store.h" #include "geometry_msgs/PoseStamped.h" #include "std_srvs/Empty.h" #ifndef KCL_movebase #define KCL_movebase /** * This file defines the RPMoveBase class. * RPMoveBase is used to connect ROSPlan to the MoveBase library. * PDDL "goto_waypoint" actions become "move_base_msgs::MoveBase" actions. * Waypoint goals are fetched by name from the SceneDB (implemented by mongoDB). */ namespace KCL_rosplan { class RPMoveBase: public RPActionInterface { private: mongodb_store::MessageStoreProxy message_store; actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> action_client; ros::ServiceClient clear_costmaps_client; public: /* constructor */ RPMoveBase(ros::NodeHandle &nh, std::string &actionserver); /* listen to and process action_dispatch topic */ bool concreteCallback(const rosplan_dispatch_msgs::ActionDispatch::ConstPtr& msg); }; } #endif
1apple7seeds/ROSPlan
rosplan_knowledge_base/include/rosplan_knowledge_base/KnowledgeBase.h
<filename>rosplan_knowledge_base/include/rosplan_knowledge_base/KnowledgeBase.h #include <ros/ros.h> #include <vector> #include <iostream> #include <fstream> #include "std_srvs/Empty.h" #include "rosplan_knowledge_msgs/KnowledgeUpdateService.h" #include "rosplan_knowledge_msgs/KnowledgeUpdateServiceArray.h" #include "rosplan_knowledge_msgs/KnowledgeQueryService.h" #include "rosplan_knowledge_msgs/GetDomainNameService.h" #include "rosplan_knowledge_msgs/GetDomainTypeService.h" #include "rosplan_knowledge_msgs/GetDomainAttributeService.h" #include "rosplan_knowledge_msgs/GetDomainOperatorService.h" #include "rosplan_knowledge_msgs/GetDomainOperatorDetailsService.h" #include "rosplan_knowledge_msgs/GetDomainPredicateDetailsService.h" #include "rosplan_knowledge_msgs/DomainFormula.h" #include "rosplan_knowledge_msgs/GetAttributeService.h" #include "rosplan_knowledge_msgs/GetInstanceService.h" #include "rosplan_knowledge_msgs/GetMetricService.h" #include "rosplan_knowledge_msgs/KnowledgeItem.h" #include "KnowledgeComparitor.h" #include "DomainParser.h" #include "ProblemParser.h" #include "VALVisitorOperator.h" #include "VALVisitorPredicate.h" #include "VALVisitorProblem.h" #ifndef KCL_knowledgebase #define KCL_knowledgebase namespace KCL_rosplan { class KnowledgeBase { private: /* adding items to the knowledge base */ void addKnowledge(rosplan_knowledge_msgs::KnowledgeItem &msg); void addMissionGoal(rosplan_knowledge_msgs::KnowledgeItem &msg); void addMissionMetric(rosplan_knowledge_msgs::KnowledgeItem &msg); /* removing items from the knowledge base */ void removeKnowledge(rosplan_knowledge_msgs::KnowledgeItem &msg); void removeMissionGoal(rosplan_knowledge_msgs::KnowledgeItem &msg); void removeMissionMetric(rosplan_knowledge_msgs::KnowledgeItem &msg); public: /* parsing domain using VAL */ DomainParser domain_parser; /* initial state from problem file using VAL */ ProblemParser problem_parser; /* PDDL model (current state) */ std::map<std::string, std::vector<std::string> > model_constants; std::map<std::string, std::vector<std::string> > model_instances; std::vector<rosplan_knowledge_msgs::KnowledgeItem> model_facts; std::vector<rosplan_knowledge_msgs::KnowledgeItem> model_functions; std::vector<rosplan_knowledge_msgs::KnowledgeItem> model_goals; rosplan_knowledge_msgs::KnowledgeItem model_metric; /* timed initial literals */ std::vector<rosplan_knowledge_msgs::KnowledgeItem> model_timed_initial_literals; /* conditional planning */ std::vector<std::vector<rosplan_knowledge_msgs::KnowledgeItem> > model_oneof_constraints; bool use_unknowns; /* add the initial state to the knowledge base */ void addInitialState(VAL::domain* domain, VAL::problem* problem); /* service methods for querying the model */ bool queryKnowledge(rosplan_knowledge_msgs::KnowledgeQueryService::Request &req, rosplan_knowledge_msgs::KnowledgeQueryService::Response &res); /* service methods for fetching the current state */ bool getInstances(rosplan_knowledge_msgs::GetInstanceService::Request &req, rosplan_knowledge_msgs::GetInstanceService::Response &res); bool getPropositions(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res); bool getFunctions(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res); bool getGoals(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res); bool getMetric(rosplan_knowledge_msgs::GetMetricService::Request &req, rosplan_knowledge_msgs::GetMetricService::Response &res); bool getTimedKnowledge(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res); /* service methods for adding and removing items to and from the current state */ bool updateKnowledgeArray(rosplan_knowledge_msgs::KnowledgeUpdateServiceArray::Request &req, rosplan_knowledge_msgs::KnowledgeUpdateServiceArray::Response &res); bool updateKnowledge(rosplan_knowledge_msgs::KnowledgeUpdateService::Request &req, rosplan_knowledge_msgs::KnowledgeUpdateService::Response &res); bool clearKnowledge(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res); /* service methods for fetching the domain details */ bool getDomainName(rosplan_knowledge_msgs::GetDomainNameService::Request &req, rosplan_knowledge_msgs::GetDomainNameService::Response &res); bool getTypes(rosplan_knowledge_msgs::GetDomainTypeService::Request &req, rosplan_knowledge_msgs::GetDomainTypeService::Response &res); bool getPredicates(rosplan_knowledge_msgs::GetDomainAttributeService::Request &req, rosplan_knowledge_msgs::GetDomainAttributeService::Response &res); bool getFunctionPredicates(rosplan_knowledge_msgs::GetDomainAttributeService::Request &req, rosplan_knowledge_msgs::GetDomainAttributeService::Response &res); bool getOperators(rosplan_knowledge_msgs::GetDomainOperatorService::Request &req, rosplan_knowledge_msgs::GetDomainOperatorService::Response &res); bool getOperatorDetails(rosplan_knowledge_msgs::GetDomainOperatorDetailsService::Request &req, rosplan_knowledge_msgs::GetDomainOperatorDetailsService::Response &res); bool getPredicateDetails(rosplan_knowledge_msgs::GetDomainPredicateDetailsService::Request &req, rosplan_knowledge_msgs::GetDomainPredicateDetailsService::Response &res); /* service methods for conditional planning */ bool updateKnowledgeConstraintsOneOf(rosplan_knowledge_msgs::KnowledgeUpdateServiceArray::Request &req, rosplan_knowledge_msgs::KnowledgeUpdateServiceArray::Response &res); // TODO bool getCurrentConstraintsOneOf(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res); /* main loop */ void runKnowledgeBase(); }; } #endif
1apple7seeds/ROSPlan
rosplan_knowledge_base/include/rosplan_knowledge_base/ProblemParser.h
#include <ros/ros.h> #include <vector> #include <iostream> #include <fstream> #include "FlexLexer.h" #include "ptree.h" #include "VisitController.h" #include "VALVisitorProblem.h" #ifndef KCL_problemparser #define KCL_problemparser extern int yyparse(); extern int yydebug; namespace VAL { extern analysis an_analysis; extern yyFlexLexer* yfl; }; /** * Problem file storage and parsing. Uses VAL parser and storage. */ namespace KCL_rosplan { /*--------*/ /* parser */ /*--------*/ class ProblemParser { private: public: /* VAL pointers */ VAL::analysis * val_analysis; VAL::problem* problem; /* Problem information */ bool problem_parsed; std::string problem_name; /* Problem parsing */ VAL::problem* parseProblem(const std::string ProblemPath); }; } #endif
1apple7seeds/ROSPlan
rosplan_planning_system/include/rosplan_planning_system/PlanDispatch/SimplePlanDispatcher.h
<gh_stars>1-10 /* * This file describes the class used to dispatch a Simple (sequential) PDDL plan. */ #include "PlanDispatcher.h" #include "rosplan_dispatch_msgs/CompletePlan.h" #include "rosplan_knowledge_msgs/KnowledgeQueryService.h" #include "rosplan_knowledge_msgs/GetDomainOperatorDetailsService.h" #include "rosplan_knowledge_msgs/DomainOperator.h" #include <map> #ifndef KCL_simple_dispatcher #define KCL_simple_dispatcher namespace KCL_rosplan { class SimplePlanDispatcher: public PlanDispatcher { private: // current plan and time plan was recevied rosplan_dispatch_msgs::CompletePlan current_plan; double mission_start_time; /* check preconditions are true */ bool checkPreconditions(rosplan_dispatch_msgs::ActionDispatch msg); ros::ServiceClient queryKnowledgeClient; ros::ServiceClient queryDomainClient; /* current action to dispatch */ int current_action; public: /* constructor */ SimplePlanDispatcher(ros::NodeHandle& nh); ~SimplePlanDispatcher(); void planCallback(const rosplan_dispatch_msgs::CompletePlan plan); void reset(); bool dispatchPlanService(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res); bool dispatchPlan(double missionStartTime, double planStartTime); void feedbackCallback(const rosplan_dispatch_msgs::ActionFeedback::ConstPtr& msg); }; } #endif
pwiklowski/ng-iot-esp32-rgb-led-driver
main/iot_device.h
/* * iot_device.h * * Created on: Jan 6, 2021 * Author: pwiklowski */ #ifndef MAIN_IOT_DEVICE_H_ #define MAIN_IOT_DEVICE_H_ void iot_device_start(); #endif /* MAIN_IOT_DEVICE_H_ */
pwiklowski/ng-iot-esp32-rgb-led-driver
main/led.h
<gh_stars>0 #ifndef __LED_H__ #define __LED_H__ #include "driver/gpio.h" #include "driver/ledc.h" #include <math.h> #define LED_PWM_RESOLUTION LEDC_TIMER_8_BIT #define LED_MAX_VALUE (pow(2, LED_PWM_RESOLUTION)-1) void led_init(); void led_set_rgb(uint8_t red, uint8_t green, uint8_t blue); void led_set_value(ledc_channel_config_t channel, uint8_t duty); #endif // __LED_H__invalid operands to binary ^ (have 'int' and 'double')
pwiklowski/ng-iot-esp32-rgb-led-driver
main/led.c
#include "led.h" #include "iot_device.h" #if defined(VARIANT_6CH) || defined(VARIANT_6CH_RGB) ledc_channel_config_t led_channel_6 = { .channel = LEDC_CHANNEL_0, .duty = 0, .gpio_num = 15, .speed_mode = LEDC_HIGH_SPEED_MODE, .hpoint = 0, .timer_sel = LEDC_TIMER_0 }; ledc_channel_config_t led_channel_5 = { .channel = LEDC_CHANNEL_1, .duty = 0, .gpio_num = 13, .speed_mode = LEDC_HIGH_SPEED_MODE, .hpoint = 0, .timer_sel = LEDC_TIMER_0 }; ledc_channel_config_t led_channel_4 = { .channel = LEDC_CHANNEL_2, .duty = 0, .gpio_num = 2, .speed_mode = LEDC_HIGH_SPEED_MODE, .hpoint = 0, .timer_sel = LEDC_TIMER_0 }; #endif ledc_channel_config_t led_channel_1 = { .channel = LEDC_CHANNEL_3, .duty = 0, .gpio_num = 22, .speed_mode = LEDC_HIGH_SPEED_MODE, .hpoint = 0, .timer_sel = LEDC_TIMER_0 }; ledc_channel_config_t led_channel_2 = { .channel = LEDC_CHANNEL_4, .duty = 0, .gpio_num = 19, .speed_mode = LEDC_HIGH_SPEED_MODE, .hpoint = 0, .timer_sel = LEDC_TIMER_0 }; ledc_channel_config_t led_channel_3 = { .channel = LEDC_CHANNEL_5, .duty = 0, .gpio_num = 23, .speed_mode = LEDC_HIGH_SPEED_MODE, .hpoint = 0, .timer_sel = LEDC_TIMER_0 }; void led_init() { ledc_timer_config_t ledc_timer = { .duty_resolution = LED_PWM_RESOLUTION, // resolution of PWM duty .freq_hz = 400, // frequency of PWM signal .speed_mode = LEDC_HIGH_SPEED_MODE, // timer mode .timer_num = LEDC_TIMER_0, // timer index .clk_cfg = LEDC_AUTO_CLK, // Auto select the source clock }; ledc_timer_config(&ledc_timer); #if defined(VARIANT_6CH) || defined(VARIANT_6CH_RGB) ledc_channel_config(&led_channel_6); ledc_channel_config(&led_channel_5); ledc_channel_config(&led_channel_4); #endif ledc_channel_config(&led_channel_1); ledc_channel_config(&led_channel_2); ledc_channel_config(&led_channel_3); } void led_set_value(ledc_channel_config_t channel, uint8_t duty) { ledc_set_duty(channel.speed_mode, channel.channel, duty); ledc_update_duty(channel.speed_mode, channel.channel); } void led_set_rgb(uint8_t red, uint8_t green, uint8_t blue) { #if defined(VARIANT_6CH_RGB) led_set_value(led_channel_6, red); led_set_value(led_channel_5, green); led_set_value(led_channel_4, blue); #endif #if defined(VARIANT_3CH_RGB) led_set_value(led_channel_3, red); led_set_value(led_channel_2, green); led_set_value(led_channel_1, blue); #endif }
pwiklowski/ng-iot-esp32-rgb-led-driver
main/iot_device.c
#include "cJSON.h" #include "iot.h" #include "led.h" #include <stdio.h> #include "esp_heap_caps.h" #include "esp_log.h" #include "esp_system.h" #include "led.h" #include <string.h> #include "iot_device.h" char *TAG = "IOT_DEVICE"; #define SCHEMA_RGB "{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"type\":\"object\",\"properties\":{\"red\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":255}, \"green\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":255}, \"blue\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":255},\"power\":{\"type\":\"number\",\"minimum\":0,\"maximum\":1}},\"required\":[\"red\", \"green\", \"blue\",\"power\"],\"additionalProperties\":false}" #define SCHEMA_SINGLE_CHANNEL "{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"type\":\"object\",\"properties\":{\"power\":{\"type\":\"number\",\"minimum\":0,\"maximum\":1}},\"required\":[\"power\"],\"additionalProperties\":false}" char device_uuid[38]; #if defined(VARIANT_3CH_RGB) || defined(VARIANT_6CH_RGB) char *VARIABLE_UUID = "56be315a-05b2-4f5e-8fd1-342b40c006fe"; cJSON *color_value; cJSON *color_value_red; cJSON *color_value_green; cJSON *color_value_blue; cJSON *color_value_power; #endif #if defined(VARIANT_6CH) cJSON *value_ch4; cJSON *value_ch4_power; char *VARIABLE_CH4_UUID = "d2e15ddd-95bb-4885-b63b-00f810dbfaa4"; cJSON *value_ch5; cJSON *value_ch5_power; char *VARIABLE_CH5_UUID = "d2e15ddd-95bb-4885-b63b-00f810dbfaa5"; cJSON *value_ch6; cJSON *value_ch6_power; char *VARIABLE_CH6_UUID = "d2e15ddd-95bb-4885-b63b-00f810dbfaa6"; extern ledc_channel_config_t led_channel_4; extern ledc_channel_config_t led_channel_5; extern ledc_channel_config_t led_channel_6; #endif #if defined(VARIANT_6CH) || defined(VARIANT_6CH_RGB) || defined(VARIANT_3CH) cJSON *value_ch1; cJSON *value_ch1_power; char *VARIABLE_CH1_UUID = "d2e15ddd-95bb-4885-b63b-00f810dbfaa1"; cJSON *value_ch2; cJSON *value_ch2_power; char *VARIABLE_CH2_UUID = "d2e15ddd-95bb-4885-b63b-00f810dbfaa2"; cJSON *value_ch3; cJSON *value_ch3_power; char *VARIABLE_CH3_UUID = "d2e15ddd-95bb-4885-b63b-00f810dbfaa3"; extern ledc_channel_config_t led_channel_1; extern ledc_channel_config_t led_channel_2; extern ledc_channel_config_t led_channel_3; #endif cJSON* iot_device_get_description() { char version[32]; char name[32]; iot_get_app_version(name, version); cJSON *device = cJSON_CreateObject(); cJSON_AddStringToObject(device, "name", name); cJSON_AddStringToObject(device, "deviceUuid", device_uuid); cJSON_AddStringToObject(device, "version", version); cJSON *vars = cJSON_AddObjectToObject(device, "vars"); #if defined(VARIANT_3CH_RGB) || defined(VARIANT_6CH_RGB) iot_create_variable_description(vars, VARIABLE_UUID, "color", "rw", SCHEMA_RGB, cJSON_Duplicate(color_value, true)); #endif #if defined(VARIANT_6CH) || defined(VARIANT_6CH_RGB) || defined(VARIANT_3CH) iot_create_variable_description(vars, VARIABLE_CH1_UUID, "ch1", "rw", SCHEMA_SINGLE_CHANNEL, cJSON_Duplicate(value_ch1, true)); iot_create_variable_description(vars, VARIABLE_CH2_UUID, "ch2", "rw", SCHEMA_SINGLE_CHANNEL, cJSON_Duplicate(value_ch2, true)); iot_create_variable_description(vars, VARIABLE_CH3_UUID, "ch3", "rw", SCHEMA_SINGLE_CHANNEL, cJSON_Duplicate(value_ch3, true)); #endif #if defined(VARIANT_6CH) iot_create_variable_description(vars, VARIABLE_CH4_UUID, "ch4", "rw", SCHEMA_SINGLE_CHANNEL, cJSON_Duplicate(value_ch4, true)); iot_create_variable_description(vars, VARIABLE_CH5_UUID, "ch5", "rw", SCHEMA_SINGLE_CHANNEL, cJSON_Duplicate(value_ch5, true)); iot_create_variable_description(vars, VARIABLE_CH6_UUID, "ch6", "rw", SCHEMA_SINGLE_CHANNEL, cJSON_Duplicate(value_ch6, true)); #endif return device; } void iot_set_value(char* variable_uuid, cJSON*newValue, cJSON* value, ledc_channel_config_t channel) { cJSON *newPower = cJSON_GetObjectItemCaseSensitive(newValue, "power"); cJSON *power = cJSON_GetObjectItemCaseSensitive(value, "power"); led_set_value(channel, LED_MAX_VALUE * newPower->valuedouble); cJSON_SetNumberValue(power, newPower->valuedouble); iot_send_value_changed_notifcation(device_uuid, variable_uuid, value); ESP_LOGI(TAG, "iot_device_value_updated %s %d",variable_uuid, (int)(LED_MAX_VALUE * newPower->valuedouble)); } void iot_device_event_handler(const char *payload, const size_t len) { cJSON *json = cJSON_Parse((char*) payload); int event_type = cJSON_GetObjectItemCaseSensitive(json, "type")->valueint; if (event_type == SetValue) { cJSON *args = cJSON_GetObjectItemCaseSensitive(json, "args"); cJSON *value = cJSON_GetObjectItemCaseSensitive(args, "value"); cJSON *variableUuid = cJSON_GetObjectItemCaseSensitive(args, "variableUuid"); ESP_LOGI(TAG, "iot_device_value_updated %s",variableUuid->valuestring); #if defined(VARIANT_3CH_RGB) || defined(VARIANT_6CH_RGB) if (strcmp(variableUuid->valuestring, VARIABLE_UUID) == 0) { cJSON *red = cJSON_GetObjectItemCaseSensitive(value, "red"); cJSON *green = cJSON_GetObjectItemCaseSensitive(value, "green"); cJSON *blue = cJSON_GetObjectItemCaseSensitive(value, "blue"); cJSON *power = cJSON_GetObjectItemCaseSensitive(value, "power"); led_set_rgb(power->valuedouble * red->valueint, power->valuedouble * green->valueint, power->valuedouble * blue->valueint); cJSON_SetNumberValue(color_value_power, power->valuedouble); cJSON_SetNumberValue(color_value_red, red->valueint); cJSON_SetNumberValue(color_value_green, green->valueint); cJSON_SetNumberValue(color_value_blue, blue->valueint); iot_send_value_changed_notifcation(device_uuid, VARIABLE_UUID, color_value); } #endif #if defined(VARIANT_6CH) || defined(VARIANT_6CH_RGB) || defined(VARIANT_3CH) if( strcmp(variableUuid->valuestring, VARIABLE_CH1_UUID) == 0) { iot_set_value(VARIABLE_CH1_UUID, value, value_ch1, led_channel_1); } else if( strcmp(variableUuid->valuestring, VARIABLE_CH2_UUID) == 0) { iot_set_value(VARIABLE_CH2_UUID, value, value_ch2, led_channel_2); } else if( strcmp(variableUuid->valuestring, VARIABLE_CH3_UUID) == 0) { iot_set_value(VARIABLE_CH3_UUID, value, value_ch3, led_channel_3); } #endif #if defined(VARIANT_6CH) if( strcmp(variableUuid->valuestring, VARIABLE_CH4_UUID) == 0) { iot_set_value(VARIABLE_CH4_UUID, value, value_ch4, led_channel_4); } else if( strcmp(variableUuid->valuestring, VARIABLE_CH5_UUID) == 0) { iot_set_value(VARIABLE_CH5_UUID, value, value_ch5, led_channel_5); } else if( strcmp(variableUuid->valuestring, VARIABLE_CH6_UUID) == 0) { iot_set_value(VARIABLE_CH6_UUID, value, value_ch6, led_channel_6); } #endif } else if (event_type == Hello) { int req_id = cJSON_GetObjectItemCaseSensitive(json, "reqId")->valueint; cJSON *res = cJSON_CreateObject(); cJSON* description = iot_device_get_description(); cJSON_AddItemToObject(res, "config", description); iot_device_send_response(req_id, res); } cJSON_Delete(json); } void iot_device_init() { iot_get_device_uuid(device_uuid); #if defined(VARIANT_3CH_RGB) || defined(VARIANT_6CH_RGB) color_value = cJSON_CreateObject(); color_value_red = cJSON_AddNumberToObject(color_value, "red", 0); color_value_green = cJSON_AddNumberToObject(color_value, "green", 0); color_value_blue = cJSON_AddNumberToObject(color_value, "blue", 0); color_value_power = cJSON_AddNumberToObject(color_value, "power", 0); #endif #if defined(VARIANT_6CH) || defined(VARIANT_6CH_RGB) || defined(VARIANT_3CH) value_ch1 = cJSON_CreateObject(); value_ch1_power = cJSON_AddNumberToObject(value_ch1, "power", 0); value_ch2 = cJSON_CreateObject(); value_ch2_power = cJSON_AddNumberToObject(value_ch2, "power", 0); value_ch3 = cJSON_CreateObject(); value_ch3_power = cJSON_AddNumberToObject(value_ch3, "power", 0); #endif #ifdef VARIANT_6CH value_ch4 = cJSON_CreateObject(); value_ch4_power = cJSON_AddNumberToObject(value_ch4, "power", 0); value_ch5 = cJSON_CreateObject(); value_ch5_power = cJSON_AddNumberToObject(value_ch5, "power", 0); value_ch6 = cJSON_CreateObject(); value_ch6_power = cJSON_AddNumberToObject(value_ch6, "power", 0); #endif led_init(); } void iot_device_deinit() { #if defined(VARIANT_3CH_RGB) || defined(VARIANT_6CH_RGB) cJSON_free(color_value); #endif #if defined(VARIANT_6CH) || defined(VARIANT_6CH_RGB) || defined(VARIANT_3CH) cJSON_free(value_ch1); cJSON_free(value_ch2); cJSON_free(value_ch3); #endif #ifdef VARIANT_6CH cJSON_free(value_ch4); cJSON_free(value_ch5); cJSON_free(value_ch6); #endif } void iot_device_start() { iot_init(); }
pwiklowski/ng-iot-esp32-rgb-led-driver
main/settings.c
/* * settings.h * * Created on: Jan 5, 2021 * Author: pwiklowski */ char* audience = "https%3A%2F%2Fwiklosoft.eu.auth0.com%2Fapi%2Fv2%2F"; char* scope = "name+email+profile+openid+offline_access"; char* AUTH_TOKEN_URL = "https://wiklosoft.eu.auth0.com/oauth/token"; char* AUTH_CODE_URL = "https://wiklosoft.eu.auth0.com/oauth/device/code"; char* OTA_IMAGE_URL = "https://ota.wiklosoft.com/iot-rgb-esp32.bin"; //char* IOT_SERVER_URL_TEMPLATE = "ws://192.168.1.28:8000/device?token=%s"; char* IOT_SERVER_URL_TEMPLATE ="wss://iot.wiklosoft.com/connect/device?token=%s"; int SOFTWARE_UPDATE_CHECK_INTERVAL_MIN = 24*60; int TOKEN_REFRESH_INTERVAL_MIN = 12*60; char* WIFI_SSID = ""; char* WIFI_PASS = ""; char* CLIENT_ID = ""; char* CLIENT_SECRET = "";
pwiklowski/ng-iot-esp32-rgb-led-driver
main/main.c
<filename>main/main.c #include "esp_log.h" #include "esp_spi_flash.h" #include "esp_system.h" #include "esp_task.h" #include "nvs_flash.h" #include "wifi.h" #include "iot_device.h" #include "settings.c" static const char *TAG = "main"; void app_main(void) { // Initialize NVS esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } wifi_init_sta(); iot_device_start(); }
ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-AdrianoMoreira07
complejos/src/complejo.h
/** * Universidad de La Laguna; Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática (1º) * Asignatura: Informática Básica * * @author <NAME> <<EMAIL>> * @brief Permite manejar números complejos * Funcionalidades: * - Representar complejos (forma binómica) * e imprimirlos en pantalla. * - Sumar y restar complejos. */ #ifndef COMPLEJO_H #define COMPLEJO_H class Complejo { public: Complejo(): real_{0}, imaginario_{0} {} Complejo(int real): real_{(double)real}, imaginario_{0} {} Complejo(double real, double imaginario): real_{real}, imaginario_{imaginario} {} /// Suma dos números complejos friend Complejo SumaCompleja(const Complejo& num1,const Complejo& num2); /// Resta dos números complejos friend Complejo RestaCompleja(const Complejo& num1,const Complejo& num2); /// Muestra por pantalla un número complejo void Imprimir() const; bool operator==(const Complejo& otro_complejo) const; private: double real_; double imaginario_; }; #endif
ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-AdrianoMoreira07
fechas/src/fecha.h
/** * Universidad de La Laguna; Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática (1º) * Asignatura: Informática Básica * * @author <NAME> <<EMAIL>> * @brief Clase Fecha */ #ifndef FECHA_H #define FECHA_H #include <string> #include <iostream> class Fecha { public: Fecha() {} Fecha(int dia_entrada, int mes_entrada, int anyo_entrada): dia_{dia_entrada}, mes_{mes_entrada}, anyo_{anyo_entrada} { Bisiesto(); } void CambiarDia (const int& nuevo_dia) {dia_ = nuevo_dia;} void CambiarMes (const int& nuevo_mes) {mes_ = nuevo_mes;} void CambiarAnyo (const int& nuevo_anyo) { anyo_ = nuevo_anyo; Bisiesto(); } const int& VerDia() const {return dia_;} const int& VerMes() const {return mes_;} const int& VerAnyo() const {return anyo_;} const bool& VerBisiesto() const {return bisiesto_;} std::string VerFecha() const { return (std::to_string(dia_)+"/"+std::to_string(mes_)+"/"+ std::to_string(anyo_)); } /* * Asigna a un objeto Fecha los valores de una * fecha en formato dd/mm/aaaa de tipo string * @param this Al que se le asigna la fecha * @param cadena De la que se extrae la fecha */ void operator=(const std::string& cadena); bool operator<(const Fecha& otra_fecha) const; bool operator>(const Fecha& otra_fecha) const; bool operator==(const Fecha& otra_fecha) const; private: int dia_{1}; int mes_{1}; int anyo_{2000}; bool bisiesto_{false}; //Determina si una fecha es bisiesta void Bisiesto() { if (anyo_ % 4 == 0 && anyo_ % 100 != 0) { bisiesto_ = true; } else { bisiesto_ = false; } } }; std::ostream& operator<<(std::ostream& out, const Fecha fecha); #endif
ULL-ESIT-IB-2020-2021/ib-practica12-oop-gtests-exercism-AdrianoMoreira07
fechas/src/inicio.h
/** * Universidad de La Laguna; Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática (1º) * Asignatura: Informática Básica * * @author <NAME> <<EMAIL>> * @brief Header para inicio.cc */ #ifndef INICIO_H #define INICIO_H /** * Muestra mensajes de ayuda o error * en funcion de los parámetros * * @param argc Número de parámetros de entrada del programa * @param argv Parámetros de entrada del programa * @return void */ void Inicio(int argc, char* argv[]); #endif
mephory/vselect
vselect.c
<reponame>mephory/vselect // Usage: vselect [OPTION]... FILENAME - select a rectangular area from an image // // Options: // -f FORMAT specify an output format // -t TITLE change window title // -h print this help // // FORMAT is any string that can contain the following vars: // %l / %x left side // %t / %y top side // %r right side // %b bottom side // %w width // %h height // // The default format is the default geometry syntax imagemagick uses: // %wx%h+%x+%y // // KEY AND MOUSE BINDINGS // // q quit // arrow up zoom in // arrow down zoom out // left mouse select rectangle // middle mouse move image // right mouse confirm and exit // TODO: // - display selections going out of bounds correctly // - display x,y,w,h while dragging the rectangle // - handle zoom+offset correctly (it's kind of weird right now) #include <cairo.h> #include <cairo-xlib.h> #include <X11/Xlib.h> #include <X11/keysym.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define DEFAULT_FORMAT "%wx%h+%x+%y" // Type definitions typedef struct { int x, y; } point_t; typedef struct { point_t start, end; } rect_t; typedef struct { char *format; char *filename; char *window_title; } options_t; typedef struct { rect_t sel; point_t offset; double zoom; int image_width; int image_height; } state_t; // Global variables Display *dpy; int screen; Window root; // Xlib stuff void initialize_xlib() { if (!(dpy=XOpenDisplay(NULL))) { fprintf(stderr, "ERROR: Could not open display\n"); exit(1); } screen = DefaultScreen(dpy); root = RootWindow(dpy, screen); } Window create_window(char *name, int width, int height) { Window win; win = XCreateSimpleWindow(dpy, root, 1, 1, width, height, 0, BlackPixel(dpy, screen), BlackPixel(dpy, screen)); XStoreName(dpy, win, name); XSelectInput(dpy, win, ExposureMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | KeyPressMask | StructureNotifyMask); return win; } // Utils int min(int a, int b) { return (a < b) ? a : b; } int max(int a, int b) { return (a > b) ? a : b; } int abs(int n) { return (n < 0) ? (-1) * n : n; } int getx(rect_t rect) { return min(rect.start.x, rect.end.x); } int gety(rect_t rect) { return min(rect.start.y, rect.end.y); } int getr(rect_t rect) { return max(rect.start.x, rect.end.x); } int getb(rect_t rect) { return max(rect.start.y, rect.end.y); } int getwidth(rect_t rect) { return abs(rect.end.x - rect.start.x); } int getheight(rect_t rect) { return abs(rect.end.y - rect.start.y); } char *itoa(int n) { char *str; int size = snprintf(NULL, 0, "%d", n); str = malloc(size); sprintf(str, "%d", n); return str; } char *str_replace(char *orig, char *rep, char *with) { char *result; // the return string char *ins; // the next insert point char *tmp; // varies int len_rep; // length of rep int len_with; // length of with int len_front; // distance between rep and end of last rep int count; // number of replacements if (!orig) return NULL; if (!rep) rep = ""; len_rep = strlen(rep); if (!with) with = ""; len_with = strlen(with); ins = orig; for (count = 0; tmp = strstr(ins, rep); ++count) { ins = tmp + len_rep; } // first time through the loop, all the variable are set correctly // from here on, // tmp points to the end of the result string // ins points to the next occurrence of rep in orig // orig points to the remainder of orig after "end of rep" tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1); if (!result) return NULL; while (count--) { ins = strstr(orig, rep); len_front = ins - orig; tmp = strncpy(tmp, orig, len_front) + len_front; tmp = strcpy(tmp, with) + len_with; orig += len_front + len_rep; // move to next "end of rep" } strcpy(tmp, orig); return result; } // cairo stuff cairo_status_t read_image(void *closure, unsigned char *data, unsigned int size) { FILE *f = (FILE *)closure; fread(data, size, 1, f); return CAIRO_STATUS_SUCCESS; } FILE *create_png_stream(char *filename) { char *command; int size = snprintf(NULL, 0, "convert \"%s\" png:- 2>/dev/null", filename); command = malloc(size); sprintf(command, "convert \"%s\" png:- 2>/dev/null", filename); FILE *f = popen(command, "r"); return f; } cairo_surface_t *open_image(char *filename) { cairo_surface_t *surface; FILE *f = create_png_stream(filename); surface = cairo_image_surface_create_from_png_stream(read_image, f); if (cairo_surface_status(surface) == CAIRO_STATUS_FILE_NOT_FOUND || cairo_surface_status(surface) == CAIRO_STATUS_READ_ERROR || cairo_surface_status(surface) == CAIRO_STATUS_NO_MEMORY) { fprintf(stderr, "ERROR: Could not open file\n"); exit(-1); } return surface; } char *output_string(state_t state, options_t options) { // TODO: Don't assume that's enough char *output = malloc(5000); strcpy(output, options.format); output = str_replace(output, "\%x", itoa(getx(state.sel))); output = str_replace(output, "\%y", itoa(gety(state.sel))); output = str_replace(output, "\%l", itoa(getx(state.sel))); output = str_replace(output, "\%t", itoa(gety(state.sel))); output = str_replace(output, "\%r", itoa(getr(state.sel))); output = str_replace(output, "\%b", itoa(getb(state.sel))); output = str_replace(output, "\%w", itoa(getwidth(state.sel))); output = str_replace(output, "\%h", itoa(getheight(state.sel))); return output; } void paint(cairo_surface_t *window, cairo_surface_t *image, state_t state, options_t options) { cairo_t *c; c = cairo_create(window); // highlighted area cairo_surface_t *highlighted = cairo_surface_create_for_rectangle( image, getx(state.sel), gety(state.sel), getwidth(state.sel), getheight(state.sel)); // draw to second buffer cairo_push_group(c); // zoom cairo_scale(c, state.zoom, state.zoom); // clear screen cairo_set_source_rgba(c, 0, 0, 0, 1); cairo_paint(c); // draw grayed out image cairo_set_source_surface(c, image, state.offset.x, state.offset.y); cairo_paint_with_alpha(c, .25); // draw highlighted part cairo_set_source_surface(c, highlighted, getx(state.sel) + state.offset.x, gety(state.sel) + state.offset.y); cairo_paint(c); cairo_move_to(c, 10, 10); cairo_set_source_rgb(c, 1, 1, 1); cairo_show_text(c, output_string(state, options)); // draw to actual buffer cairo_pop_group_to_source(c); cairo_paint(c); // free memory cairo_destroy(c); } void print_help() { printf("Usage: vselect [OPTION]... FILENAME - select a rectangular area from an image\n"); printf("\n"); printf("Options:\n"); printf(" -f FORMAT specify an output format\n"); printf(" -t TITLE change window title\n"); printf(" -h / --help print this help\n"); printf("\n"); printf("FORMAT is any string that can contain the following vars:\n"); printf(" %%l / %%x left side\n"); printf(" %%t / %%y top side\n"); printf(" %%r right side\n"); printf(" %%b bottom side\n"); printf(" %%w width\n"); printf(" %%h height\n"); printf("\n"); printf("The default format is the default geometry syntax imagemagick uses:\n"); printf(" %%wx%%h+%%x+%%y\n"); printf("\n"); printf("KEY AND MOUSE BINDINGS\n"); printf("\n"); printf("q quit\n"); printf("arrow up zoom in\n"); printf("arrow down zoom out\n"); printf("left mouse select rectangle\n"); printf("middle mouse move image\n"); printf("right mouse confirm and exit\n"); } options_t parse_args(int argc, char **argv) { options_t opts; opts.format = DEFAULT_FORMAT; opts.window_title = "vselect"; int format_flag_encountered = 0; int title_flag_encountered = 0; for (int i = 1; i < argc; i++) { // if there -h or --help, then just print usage and exit if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { print_help(); exit(0); } if (strcmp(argv[i], "-f") == 0) { format_flag_encountered = 1; continue; } if (strcmp(argv[i], "-t") == 0) { title_flag_encountered = 1; continue; } if (format_flag_encountered) { opts.format = argv[i]; format_flag_encountered = 0; } else if (title_flag_encountered) { opts.window_title = argv[i]; title_flag_encountered = 0; } else { opts.filename = argv[i]; } } if (strlen(opts.filename) == 0) { printf("ERROR: No filename given\n"); exit(1); } return opts; } point_t to_image_point(int x, int y, state_t state) { point_t p; p.x = min(state.image_width, max(0, x * (1 / state.zoom) - state.offset.x)); p.y = min(state.image_height, max(0, y * (1 / state.zoom) - state.offset.y)); return p; } void output(state_t state, options_t options) { char *output = output_string(state, options); printf("%s\n", output); fflush(stdout); } int main(int argc, char **argv) { XEvent ev; Window win; cairo_surface_t *window_surface; cairo_surface_t *image; options_t options; state_t state; // create initial state state.zoom = 1.0; state.offset.x = 0; state.offset.y = 0; state.sel.start.x = 0; state.sel.start.y = 0; state.sel.end.x = 0; state.sel.end.y = 0; // read command line arguments options = parse_args(argc, argv); // open the image and get the dimensions image = open_image(options.filename); state.image_width = cairo_image_surface_get_width(image); state.image_height = cairo_image_surface_get_height(image); // initialize and map x window with appropriate size initialize_xlib(); win = create_window(options.window_title, state.image_width, state.image_height); XMapWindow(dpy, win); window_surface = cairo_xlib_surface_create(dpy, win, DefaultVisual(dpy, 0), state.image_width + 1, state.image_height + 1); int drag_start_x, drag_start_y; int drag_last_x, drag_last_y; int break_from_mainloop = 0; while (!break_from_mainloop) { while (XPending(dpy) > 0) { XNextEvent(dpy, &ev); switch (ev.type) { case ConfigureNotify: cairo_xlib_surface_set_size(window_surface, ev.xconfigure.width, ev.xconfigure.height); break; case KeyPress: switch (XLookupKeysym(&ev.xkey, 0)) { // Press 'q' to quit case XK_q: exit(0); break; // Press 'Up' to zoom in case XK_Up: state.zoom += .1; break; // Press 'Down' to zoom out case XK_Down: state.zoom -= .1; break; } break; case ButtonPress: drag_start_x = ev.xbutton.x; drag_start_y = ev.xbutton.y; drag_last_x = ev.xbutton.x; drag_last_y = ev.xbutton.y; if (ev.xbutton.button == 1) { state.sel.start = to_image_point(drag_start_x, drag_start_y, state); state.sel.end = to_image_point(drag_start_x, drag_start_y, state); } break; case ButtonRelease: if (ev.xbutton.button == 3) { break_from_mainloop = 1; } break; case MotionNotify: if (ev.xmotion.state & Button1Mask) { // Button 1: make selection state.sel.start = to_image_point(drag_start_x, drag_start_y, state); state.sel.end = to_image_point(ev.xmotion.x, ev.xmotion.y, state); } if (ev.xmotion.state & Button2Mask) { // Button 3: adjust offset state.offset.x += ev.xmotion.x - drag_last_x; state.offset.y += ev.xmotion.y - drag_last_y; } drag_last_x = ev.xmotion.x; drag_last_y = ev.xmotion.y; break; } } usleep(25000); paint(window_surface, image, state, options); } output(state, options); exit(0); }
GiulioPN/bnlm
src/gamma_poisson.h
<reponame>GiulioPN/bnlm<filename>src/gamma_poisson.h #ifndef _CPYP_GAMMA_POISSON_H_ #define _CPYP_GAMMA_POISSON_H_ #include "m.h" namespace cpyp { // http://en.wikipedia.org/wiki/Conjugate_prior template <typename F> struct gamma_poisson { gamma_poisson(F shape, F rate) : a(shape), b(rate), n(), marginal(), llh() {} F prob(unsigned x) const { return exp(M<F>::log_negative_binom(x, a + marginal, 1.0 - (b + n) / (1 + b + n))); } void increment(unsigned x) { llh += M<F>::log_negative_binom(x, a + marginal, 1.0 - (b + n) / (1 + b + n)); ++n; marginal += x; } void decrement(unsigned x) { --n; marginal -= x; llh -= M<F>::log_negative_binom(x, a + marginal, 1.0 - (b + n) / (1 + b + n)); } F log_likelihood() const { return llh; } // if you want to infer (a,b), you'll need a likelihood function that // takes (a',b') as parameters and evaluates the likelihood. working out this // likelihood will mean you need to keep a list of the observations. since i // don't think in general you'd bother to infer (a,b), i didn't implement // this since it comes at the cost of more memory usage F a, b; // \lambda ~ Gamma(a,b) unsigned n, marginal; double llh; }; } // namespace cpyp #endif
GiulioPN/bnlm
src/uniform_vocab.h
<reponame>GiulioPN/bnlm #ifndef _UNIFORM_VOCAB_H_ #define _UNIFORM_VOCAB_H_ #include <cassert> #include <vector> namespace cpyp { // uniform distribution over a fixed vocabulary struct UniformVocabulary { UniformVocabulary(unsigned vs, double, double, double, double) : p0(1.0 / vs), draws() {} template<typename Engine> void increment(unsigned, const std::vector<unsigned>&, Engine&) { ++draws; } template<typename Engine> void decrement(unsigned, const std::vector<unsigned>&, Engine&) { --draws; assert(draws >= 0); } double prob(unsigned, const std::vector<unsigned>&) const { return p0; } template<typename Engine> void resample_hyperparameters(Engine&) {} double log_likelihood() const { return draws * log(p0); } template<class Archive> void serialize(Archive& ar, const unsigned int) { ar & p0; ar & draws; } double p0; int draws; }; } #endif
GiulioPN/bnlm
src/logval.h
#ifndef LOGVAL_H_ #define LOGVAL_H_ #define LOGVAL_CHECK_NEG false #include <iostream> #include <cstdlib> #include <cmath> #include <limits> #include <cassert> //TODO: template for supporting negation or not - most uses are for nonnegative "probs" only; probably some 10-20% speedup available template <class T> class LogVal { public: void print(std::ostream &o) const { if (s_) o<<"(-)"; o<<v_; } typedef LogVal<T> Self; LogVal() : s_(), v_(std::log(0)) {} LogVal(double x) : s_(std::signbit(x)), v_(s_ ? std::log(-x) : std::log(x)) {} const Self& operator=(double x) { s_ = std::signbit(x); v_ = s_ ? std::log(-x) : std::log(x); return *this; } LogVal(double lnx,bool sign) : s_(sign),v_(lnx) {} // maybe the below are faster than == 1 and == 0. i don't know. bool is_1() const { return v_==0&&s_==0; } bool is_0() const { return v_==std::log(0); } static Self One() { return Self(1); } static Self Zero() { return Self(); } static Self e() { return Self(1,false); } void logeq(const T& v) { s_ = false; v_ = v; } // just like std::signbit, negative means true. weird, i know bool signbit() const { return s_; } friend inline bool signbit(Self const& x) { return x.signbit(); } Self& besteq(const Self& a) { assert(!a.s_ && !s_); if (a.v_ < v_) v_=a.v_; return *this; } Self& operator+=(const Self& a) { if (a.is_0()) return *this; if (a.s_ == s_) { if (a.v_ < v_) { v_ = v_ + log1p(std::exp(a.v_ - v_)); } else { v_ = a.v_ + log1p(std::exp(v_ - a.v_)); } } else { if (a.v_ < v_) { v_ = v_ + log1p(-std::exp(a.v_ - v_)); } else { v_ = a.v_ + log1p(-std::exp(v_ - a.v_)); s_ = !s_; } } return *this; } Self& operator*=(const Self& a) { s_ = (s_ != a.s_); v_ += a.v_; return *this; } Self& operator/=(const Self& a) { s_ = (s_ != a.s_); v_ -= a.v_; return *this; } Self& operator-=(const Self& a) { Self b = a; b.negate(); return *this += b; } // Self(fabs(log(x)),x.s_) friend Self abslog(Self x) { if (x.v_<0) x.v_=-x.v_; return x; } Self& poweq(const T& power) { #if LOGVAL_CHECK_NEG if (s_) { std::cerr << "poweq(T) not implemented when s_ is true\n"; std::abort(); } else #endif v_ *= power; return *this; } //remember, s_ means negative. inline bool lt(Self const& o) const { return s_==o.s_ ? v_ < o.v_ : s_ > o.s_; } inline bool gt(Self const& o) const { return s_==o.s_ ? o.v_ < v_ : s_ < o.s_; } Self operator-() const { return Self(v_,!s_); } void negate() { s_ = !s_; } Self inverse() const { return Self(-v_,s_); } Self pow(const T& power) const { Self res = *this; res.poweq(power); return res; } Self root(const T& root) const { return pow(1/root); } T as_float() const { if (s_) return -std::exp(v_); else return std::exp(v_); } bool s_; T v_; }; // copy elision - as opposed to explicit copy of LogVal<T> const& o1, we should be able to construct Logval r=a+(b+c) as a single result in place in r. todo: return std::move(o1) - C++0x template<class T> LogVal<T> operator+(LogVal<T> o1, const LogVal<T>& o2) { o1 += o2; return o1; } template<class T> LogVal<T> operator*(LogVal<T> o1, const LogVal<T>& o2) { o1 *= o2; return o1; } template<class T> LogVal<T> operator/(LogVal<T> o1, const LogVal<T>& o2) { o1 /= o2; return o1; } template<class T> LogVal<T> operator-(LogVal<T> o1, const LogVal<T>& o2) { o1 -= o2; return o1; } template<class T> T log(const LogVal<T>& o) { #ifdef LOGVAL_CHECK_NEG if (o.s_) return log(-1.0); #endif return o.v_; } template<class T> LogVal<T> abs(const LogVal<T>& o) { if (o.s_) { LogVal<T> res = o; res.s_ = false; return res; } else { return o; } } template <class T> LogVal<T> pow(const LogVal<T>& b, const T& e) { return b.pow(e); } template <class T> bool operator==(const LogVal<T>& lhs, const LogVal<T>& rhs) { return (lhs.v_ == rhs.v_) && (lhs.s_ == rhs.s_); } template <class T> bool operator!=(const LogVal<T>& lhs, const LogVal<T>& rhs) { return !(lhs == rhs); } template <class T> bool operator<(const LogVal<T>& lhs, const LogVal<T>& rhs) { if (lhs.s_ == rhs.s_) { return (lhs.v_ < rhs.v_); } else { return lhs.s_ > rhs.s_; } } template <class T> bool operator<=(const LogVal<T>& lhs, const LogVal<T>& rhs) { return (lhs < rhs) || (lhs == rhs); } template <class T> bool operator>(const LogVal<T>& lhs, const LogVal<T>& rhs) { return !(lhs <= rhs); } template <class T> bool operator>=(const LogVal<T>& lhs, const LogVal<T>& rhs) { return !(lhs < rhs); } typedef LogVal<double> prob_t; #endif
GiulioPN/bnlm
src/uvector.h
#ifndef UVECTOR_H_ #define UVECTOR_H_ #include <vector> struct uvector_hash { size_t operator()(const std::vector<unsigned>& v) const { size_t h = v.size(); for (auto e : v) h ^= e + 0x9e3779b9 + (h<<6) + (h>>2); return h; } }; #endif
GiulioPN/bnlm
src/slice_sampler.h
//! slice-sampler.h is an MCMC slice sampler //! //! <NAME>, 1st August 2008 //! A few changes by <NAME>, Aug 13, 2012 #ifndef SLICE_SAMPLER_H #define SLICE_SAMPLER_H #include <algorithm> #include <cassert> #include <cmath> #include <iostream> #include <limits> #include <random> namespace cpyp { //! slice_sampler_rfc_type{} returns the value of a user-specified //! function if the argument is within range, or - infinity otherwise // template <typename F, typename Fn, typename U> struct slice_sampler_rfc_type { F min_x, max_x; const Fn& f; U max_nfeval, nfeval; slice_sampler_rfc_type(F min_x, F max_x, const Fn& f, U max_nfeval) : min_x(min_x), max_x(max_x), f(f), max_nfeval(max_nfeval), nfeval(0) { } F operator() (F x) { if (min_x < x && x < max_x) { assert(++nfeval <= max_nfeval); F fx = f(x); assert(std::isfinite(fx)); return fx; } return -std::numeric_limits<F>::infinity(); } }; // slice_sampler_rfc_type{} //! slice_sampler1d() implements the univariate "range doubling" slice sampler //! described in Neal (2003) "Slice Sampling", The Annals of Statistics 31(3), 705-767. // template <typename F, typename LogF, typename Engine> F slice_sampler1d(const LogF& logF0, //!< log of function to sample F x, //!< starting point Engine& eng, //!< random number engine F min_x = -std::numeric_limits<F>::infinity(), //!< minimum value of support F max_x = std::numeric_limits<F>::infinity(), //!< maximum value of support F w = 0.0, //!< guess at initial width unsigned nsamples=1, //!< number of samples to draw unsigned max_nfeval=200) //!< max number of function evaluations { typedef unsigned U; std::uniform_real_distribution<F> u01(F(0), F(1)); slice_sampler_rfc_type<F,LogF,U> logF(min_x, max_x, logF0, max_nfeval); assert(std::isfinite(x)); if (w <= 0.0) { // set w to a default width if (min_x > -std::numeric_limits<F>::infinity() && max_x < std::numeric_limits<F>::infinity()) w = (max_x - min_x)/4; else w = std::max(((x < 0.0) ? -x : x)/4, (F) 0.1); } assert(std::isfinite(w)); F logFx = logF(x); for (U sample = 0; sample < nsamples; ++sample) { F logY = logFx + log(u01(eng)+1e-100); //! slice logFx at this value assert(std::isfinite(logY)); F xl = x - w*u01(eng); //! lower bound on slice interval F logFxl = logF(xl); F xr = xl + w; //! upper bound on slice interval F logFxr = logF(xr); while (logY < logFxl || logY < logFxr) // doubling procedure if (u01(eng) < 0.5) logFxl = logF(xl -= xr - xl); else logFxr = logF(xr += xr - xl); F xl1 = xl; F xr1 = xr; while (true) { // shrinking procedure F x1 = xl1 + u01(eng)*(xr1 - xl1); if (logY < logF(x1)) { F xl2 = xl; // acceptance procedure F xr2 = xr; bool d = false; while (xr2 - xl2 > 1.1*w) { F xm = (xl2 + xr2)/2; if ((x < xm && x1 >= xm) || (x >= xm && x1 < xm)) d = true; if (x1 < xm) xr2 = xm; else xl2 = xm; if (d && logY >= logF(xl2) && logY >= logF(xr2)) goto unacceptable; } x = x1; goto acceptable; } goto acceptable; unacceptable: if (x1 < x) // rest of shrinking procedure xl1 = x1; else xr1 = x1; } acceptable: w = (4*w + (xr1 - xl1))/5; // update width estimate } return x; } } #endif // SLICE_SAMPLER_H