repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
gabrielefronze/TSystFitter
TSystFitter.h
// // Created by <NAME> on 25/06/2017. // #ifndef TSYSTFITTER_H #define TSYSTFITTER_H #include "TH1.h" #include "TSystFitSettings.h" #include <utility> #include <vector> #include <TVirtualPad.h> class TSystFitter { public: explicit TSystFitter(TH1 *histToFit) : fHistToFit((TH1*)histToFit->Clone("histToFit")){}; ~TSystFitter() { delete fHistToFit; }; void SetSystFitSettings(TSystFitSettings *settings){ fSystFitSettings = settings; }; void SetSystFitSettings(std::vector<TSystFitParameter> params){ fSystFitSettings = new TSystFitSettings(std::move(params)); }; void SystFit(TF1 *f1, Option_t *option, Option_t *goption, Double_t xmin, Double_t xmax); void SystFit(const char *formula, Option_t *option, Option_t *goption, Double_t xmin, Double_t xmax); std::vector<std::pair<TFitResultPtr,TString>> GetFitResults(){ return fFitResultsVector; }; std::vector<TF1> fFitFunctions; void PrintResults(TVirtualPad *pad); private: std::vector<std::pair<TFitResultPtr,TString>> fFitResultsVector; TSystFitSettings* fSystFitSettings; TH1 *fHistToFit; void SetConfiguration(TF1 *f1, unsigned long iConfig); }; #endif //TSYSTFITTER_H
7h30n3/hyperion.ng
include/webconfig/WebConfig.h
<reponame>7h30n3/hyperion.ng<filename>include/webconfig/WebConfig.h #ifndef WEBCONFIG_H #define WEBCONFIG_H #include <QObject> #include <QString> #include <string> #include <hyperion/Hyperion.h> class StaticFileServing; class WebConfig : public QObject { Q_OBJECT public: WebConfig (QObject * parent = NULL); virtual ~WebConfig (void); void start(); void stop(); private: Hyperion* _hyperion; QString _baseUrl; quint16 _port; StaticFileServing* _server; const QString WEBCONFIG_DEFAULT_PATH = ":/webconfig"; const quint16 WEBCONFIG_DEFAULT_PORT = 8099; }; #endif // WEBCONFIG_H
7h30n3/hyperion.ng
include/jsonserver/JsonServer.h
#pragma once // system includes #include <cstdint> // Qt includes #include <QTcpServer> #include <QSet> // Hyperion includes #include <hyperion/Hyperion.h> #include <utils/Logger.h> class JsonClientConnection; /// /// This class creates a TCP server which accepts connections wich can then send /// in JSON encoded commands. This interface to Hyperion is used by hyperion-remote /// to control the leds /// class JsonServer : public QObject { Q_OBJECT public: /// /// JsonServer constructor /// @param hyperion Hyperion instance /// @param port port number on which to start listening for connections /// JsonServer(uint16_t port = 19444); ~JsonServer(); /// /// @return the port number on which this TCP listens for incoming connections /// uint16_t getPort() const; private slots: /// /// Slot which is called when a client tries to create a new connection /// void newConnection(); /// /// Slot which is called when a client closes a connection /// @param connection The Connection object which is being closed /// void closedConnection(JsonClientConnection * connection); private: /// The TCP server object QTcpServer _server; /// List with open connections QSet<JsonClientConnection *> _openConnections; /// the logger instance Logger * _log; };
7h30n3/hyperion.ng
src/hyperiond/configMigratorBase.h
#pragma once #include <utils/Logger.h> #include <QString> class ConfigMigratorBase { public: ConfigMigratorBase(); ~ConfigMigratorBase(); protected: Logger * _log; };
7h30n3/hyperion.ng
include/grabber/AmlogicGrabber.h
<reponame>7h30n3/hyperion.ng #pragma once // STL includes #include <cstdint> #include <utils/Logger.h> // Utils includes #include <utils/Image.h> #include <utils/ColorBgr.h> #include <utils/VideoMode.h> /// /// The DispmanxFrameGrabber is used for creating snapshots of the display (screenshots) with a /// downsized and scaled resolution. /// class AmlogicGrabber { public: /// /// Construct a AmlogicGrabber that will capture snapshots with specified dimensions. /// /// @param[in] width The width of the captured screenshot /// @param[in] height The heigth of the captured screenshot /// AmlogicGrabber(const unsigned width, const unsigned height); ~AmlogicGrabber(); /// /// Set the video mode (2D/3D) /// @param[in] mode The new video mode /// void setVideoMode(const VideoMode videoMode); /// /// Captures a single snapshot of the display and writes the data to the given image. The /// provided image should have the same dimensions as the configured values (_width and /// _height) /// /// @param[out] image The snapped screenshot (should be initialized with correct width and /// height) /// @return Zero on success else negative /// int grabFrame(Image<ColorBgr> & image); /** * Returns true if video is playing over the amlogic chip * @return True if video is playing else false */ bool isVideoPlaying(); private: /// With of the captured snapshot [pixels] const unsigned _width; /// Height of the captured snapshot [pixels] const unsigned _height; /** The snapshot/capture device of the amlogic video chip */ int _amlogicCaptureDev; Logger * _log; };
7h30n3/hyperion.ng
include/utils/RgbTransform.h
<reponame>7h30n3/hyperion.ng #pragma once // STL includes #include <cstdint> /// /// Color transformation to adjust the saturation and value of a RGB color value /// class RgbTransform { public: /// /// Default constructor /// RgbTransform(); /// /// Constructor /// /// @param gammaR The used red gamma /// @param gammaG The used green gamma /// @param gammab The used blue gamma /// @param brightnessLow The used lower brightness /// @param brightnessHigh The used higher brightness /// RgbTransform(double gammaR, double gammaG, double gammaB, double brightnessLow, double brightnessHigh); /// /// Destructor /// ~RgbTransform(); /// @return The current red gamma value double getGammaR() const; /// @return The current green gamma value double getGammaG() const; /// @return The current blue gamma value double getGammaB() const; /// @param gamma New gamma value void setGamma(double gammaR,double gammaG=-1, double gammaB=-1); /// @return The current lower brightness double getBrightnessMin() const; /// @param gamma New lower brightness void setBrightnessMin(double brightness); /// @return The current lower brightness double getBrightness() const; /// @param gamma New lower brightness void setBrightness(double brightness); /// /// Apply the transform the the given RGB values. /// /// @param red The red color component /// @param green The green color component /// @param blue The blue color component /// /// @note The values are updated in place. /// void transform(uint8_t & red, uint8_t & green, uint8_t & blue); private: /// /// init /// /// @param gammaR The used red gamma /// @param gammaG The used green gamma /// @param gammab The used blue gamma /// @param brightnessLow The used lower brightness /// @param brightnessHigh The used higher brightness /// void init(double gammaR, double gammaG, double gammaB, double brightnessLow, double brightnessHigh); /// (re)-initilize the color mapping void initializeMapping(); /// The saturation gain double _brightnessLow; double _brightnessHigh; double _sumBrightnessLow; double _sumBrightnessHigh; double _gammaR; double _gammaG; double _gammaB; /// The mapping from input color to output color uint8_t _mappingR[256]; uint8_t _mappingG[256]; uint8_t _mappingB[256]; };
7h30n3/hyperion.ng
include/utils/GrabbingMode.h
<reponame>7h30n3/hyperion.ng #pragma once /** * Enumeration of the possible modes in which frame-grabbing is performed. */ enum GrabbingMode { /** Frame grabbing is switched off */ GRABBINGMODE_OFF, /** Frame grabbing during video */ GRABBINGMODE_VIDEO, GRABBINGMODE_PAUSE, GRABBINGMODE_PHOTO, GRABBINGMODE_AUDIO, GRABBINGMODE_MENU, GRABBINGMODE_SCREENSAVER, GRABBINGMODE_INVALID };
7h30n3/hyperion.ng
include/utils/RgbChannelAdjustment.h
#pragma once // STL includes #include <cstdint> #include <QString> #include <utils/Logger.h> /// Correction for a single color byte value /// All configuration values are unsigned int and assume the color value to be between 0 and 255 class RgbChannelAdjustment { public: /// Default constructor RgbChannelAdjustment(QString channelName=""); /// Constructor /// @param adjustR /// @param adjustG /// @param adjustB RgbChannelAdjustment(uint8_t adjustR, uint8_t adjustG, uint8_t adjustB, QString channelName=""); /// Destructor ~RgbChannelAdjustment(); /// setAdjustment RGB /// @param adjustR /// @param adjustG /// @param adjustB void setAdjustment(uint8_t adjustR, uint8_t adjustG, uint8_t adjustB); /// @return The current adjustR value uint8_t getAdjustmentR() const; /// @param threshold New adjustR value void setAdjustmentR(uint8_t adjustR); /// @return The current adjustG value uint8_t getAdjustmentG() const; /// @param gamma New adjustG value void setAdjustmentG(uint8_t adjustG); /// @return The current adjustB value uint8_t getAdjustmentB() const; /// @param blacklevel New adjustB value void setAdjustmentB(uint8_t adjustB); /// Transform the given array value /// @param input The input color bytes /// @return The corrected byte value uint8_t getAdjustmentR(uint8_t inputR) const; uint8_t getAdjustmentG(uint8_t inputG) const; uint8_t getAdjustmentB(uint8_t inputB) const; private: /// color channels enum ColorChannel { RED=0,GREEN=1, BLUE=2 }; /// (re)-initilize the color mapping void initializeMapping(); /// The adjustment of RGB channel uint8_t _adjust[3]; /// The mapping from input color to output color uint8_t _mapping[3][256]; /// Name of this channel, usefull for debug messages QString _channelName; /// Logger instance Logger * _log; };
7h30n3/hyperion.ng
libsrc/jsonserver/JsonClientConnection.h
#pragma once // stl includes #include <string> // Qt includes #include <QByteArray> #include <QTcpSocket> #include <QMutex> // Hyperion includes #include <hyperion/Hyperion.h> // util includes #include <utils/jsonschema/QJsonSchemaChecker.h> #include <utils/Logger.h> #include <utils/Components.h> class ImageProcessor; /// Constants and utility functions related to WebSocket opcodes /** * WebSocket Opcodes are 4 bits. See RFC6455 section 5.2. */ namespace OPCODE { enum value { CONTINUATION = 0x0, TEXT = 0x1, BINARY = 0x2, RSV3 = 0x3, RSV4 = 0x4, RSV5 = 0x5, RSV6 = 0x6, RSV7 = 0x7, CLOSE = 0x8, PING = 0x9, PONG = 0xA, CONTROL_RSVB = 0xB, CONTROL_RSVC = 0xC, CONTROL_RSVD = 0xD, CONTROL_RSVE = 0xE, CONTROL_RSVF = 0xF }; /// Check if an opcode is reserved /** * @param v The opcode to test. * @return Whether or not the opcode is reserved. */ inline bool reserved(value v) { return (v >= RSV3 && v <= RSV7) || (v >= CONTROL_RSVB && v <= CONTROL_RSVF); } /// Check if an opcode is invalid /** * Invalid opcodes are negative or require greater than 4 bits to store. * * @param v The opcode to test. * @return Whether or not the opcode is invalid. */ inline bool invalid(value v) { return (v > 0xF || v < 0); } /// Check if an opcode is for a control frame /** * @param v The opcode to test. * @return Whether or not the opcode is a control opcode. */ inline bool is_control(value v) { return v >= 0x8; } } struct find_schema: std::unary_function<EffectSchema, bool> { QString pyFile; find_schema(QString pyFile):pyFile(pyFile) { } bool operator()(EffectSchema const& schema) const { return schema.pyFile == pyFile; } }; struct find_effect: std::unary_function<EffectDefinition, bool> { QString effectName; find_effect(QString effectName) :effectName(effectName) { } bool operator()(EffectDefinition const& effectDefinition) const { return effectDefinition.name == effectName; } }; /// /// The Connection object created by \a JsonServer when a new connection is establshed /// class JsonClientConnection : public QObject { Q_OBJECT public: /// /// Constructor /// @param socket The Socket object for this connection /// @param hyperion The Hyperion server /// JsonClientConnection(QTcpSocket * socket); /// /// Destructor /// ~JsonClientConnection(); public slots: void componentStateChanged(const hyperion::Components component, bool enable); void streamLedcolorsUpdate(); void incommingLogMessage(Logger::T_LOG_MESSAGE); void setImage(int priority, const Image<ColorRgb> & image, int duration_ms); signals: /// /// Signal which is emitted when the connection is being closed /// @param connection This connection object /// void connectionClosed(JsonClientConnection * connection); private slots: /// /// Slot called when new data has arrived /// void readData(); /// /// Slot called when this connection is being closed /// void socketClosed(); private: /// /// Handle an incoming JSON message /// /// @param message the incoming message as string /// void handleMessage(const QString & message); /// /// Handle an incoming JSON Color message /// /// @param message the incoming message /// void handleColorCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON Image message /// /// @param message the incoming message /// void handleImageCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON Effect message /// /// @param message the incoming message /// void handleEffectCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON Effect message (Write JSON Effect) /// /// @param message the incoming message /// void handleCreateEffectCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON Effect message (Delete JSON Effect) /// /// @param message the incoming message /// void handleDeleteEffectCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON Server info message /// /// @param message the incoming message /// void handleServerInfoCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON Clear message /// /// @param message the incoming message /// void handleClearCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON Clearall message /// /// @param message the incoming message /// void handleClearallCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON Adjustment message /// /// @param message the incoming message /// void handleAdjustmentCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON SourceSelect message /// /// @param message the incoming message /// void handleSourceSelectCommand(const QJsonObject & message, const QString &command, const int tan); /// Handle an incoming JSON GetConfig message /// /// @param message the incoming message /// void handleConfigCommand(const QJsonObject & message, const QString &command, const int tan); /// Handle an incoming JSON GetConfig message /// /// @param message the incoming message /// void handleSchemaGetCommand(const QJsonObject & message, const QString &command, const int tan); /// Handle an incoming JSON GetConfig message /// /// @param message the incoming message /// void handleConfigGetCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON Component State message /// /// @param message the incoming message /// void handleComponentStateCommand(const QJsonObject & message, const QString &command, const int tan); /// Handle an incoming JSON Led Colors message /// /// @param message the incoming message /// void handleLedColorsCommand(const QJsonObject & message, const QString &command, const int tan); /// Handle an incoming JSON Logging message /// /// @param message the incoming message /// void handleLoggingCommand(const QJsonObject & message, const QString &command, const int tan); /// Handle an incoming JSON Proccessing message /// /// @param message the incoming message /// void handleProcessingCommand(const QJsonObject & message, const QString &command, const int tan); /// /// Handle an incoming JSON message of unknown type /// void handleNotImplemented(); /// /// Send a message to the connected client /// /// @param message The JSON message to send /// void sendMessage(const QJsonObject & message); void sendMessage(const QJsonObject & message, QTcpSocket * socket); /// /// Send a standard reply indicating success /// void sendSuccessReply(const QString &command="", const int tan=0); /// /// Send an error message back to the client /// /// @param error String describing the error /// void sendErrorReply(const QString & error, const QString &command="", const int tan=0); /// /// Do handshake for a websocket connection /// void doWebSocketHandshake(); /// /// Handle incoming websocket data frame /// void handleWebSocketFrame(); /// /// forward json message /// void forwardJsonMessage(const QJsonObject & message); /// /// Check if a JSON messag is valid according to a given JSON schema /// /// @param message JSON message which need to be checked /// @param schemaResource Qt Resource identifier with the JSON schema /// @param errors Output error message /// @param ignoreRequired ignore the required value in JSON schema /// /// @return true if message conforms the given JSON schema /// bool checkJson(const QJsonObject & message, const QString &schemaResource, QString & errors, bool ignoreRequired = false); /// The TCP-Socket that is connected tot the Json-client QTcpSocket * _socket; /// The processor for translating images to led-values ImageProcessor * _imageProcessor; /// Link to Hyperion for writing led-values to a priority channel Hyperion * _hyperion; /// The buffer used for reading data from the socket QByteArray _receiveBuffer; /// used for WebSocket detection and connection handling bool _webSocketHandshakeDone; /// The logger instance Logger * _log; /// Flag if forwarder is enabled bool _forwarder_enabled; /// timer for ledcolors streaming QTimer _timer_ledcolors; // streaming buffers QJsonObject _streaming_leds_reply; QJsonObject _streaming_image_reply; QJsonObject _streaming_logging_reply; /// flag to determine state of log streaming bool _streaming_logging_activated; /// mutex to determine state of image streaming QMutex _image_stream_mutex; /// timeout for live video refresh volatile qint64 _image_stream_timeout; // masks for fields in the basic header static uint8_t const BHB0_OPCODE = 0x0F; static uint8_t const BHB0_RSV3 = 0x10; static uint8_t const BHB0_RSV2 = 0x20; static uint8_t const BHB0_RSV1 = 0x40; static uint8_t const BHB0_FIN = 0x80; static uint8_t const BHB1_PAYLOAD = 0x7F; static uint8_t const BHB1_MASK = 0x80; static uint8_t const payload_size_code_16bit = 0x7E; // 126 static uint8_t const payload_size_code_64bit = 0x7F; // 127 };
7h30n3/hyperion.ng
libsrc/webconfig/QtHttpServer.h
#ifndef QTHTTPSERVER_H #define QTHTTPSERVER_H #include <QObject> #include <QString> #include <QHash> class QTcpSocket; class QTcpServer; class QtHttpRequest; class QtHttpReply; class QtHttpClientWrapper; class QtHttpServer : public QObject { Q_OBJECT public: explicit QtHttpServer (QObject * parent = Q_NULLPTR); static const QString & HTTP_VERSION; const QString & getServerName (void) const; quint16 getServerPort (void) const; QString getErrorString (void) const; public slots: void start (quint16 port = 0); void stop (void); void setServerName (const QString & serverName); signals: void started (quint16 port); void stopped (void); void error (const QString & msg); void clientConnected (const QString & guid); void clientDisconnected (const QString & guid); void requestNeedsReply (QtHttpRequest * request, QtHttpReply * reply); private slots: void onClientConnected (void); void onClientDisconnected (void); private: QString m_serverName; QTcpServer * m_sockServer; QHash<QTcpSocket *, QtHttpClientWrapper *> m_socksClientsHash; }; #endif // QTHTTPSERVER_H
7h30n3/hyperion.ng
include/effectengine/EffectDefinition.h
<filename>include/effectengine/EffectDefinition.h #pragma once // QT include #include <QString> #include <QJsonObject> struct EffectDefinition { QString name, script, file; QJsonObject args; };
7h30n3/hyperion.ng
src/hyperiond/configMigrator.h
<gh_stars>0 #pragma once #include "configMigratorBase.h" #include <QString> /// /// class that contains migration code /// helper code goeas to base class class ConfigMigrator : public ConfigMigratorBase { public: ConfigMigrator(); ~ConfigMigrator(); bool migrate(QString configFile, int fromVersion,int toVersion); private: void migrateFrom1(); };
7h30n3/hyperion.ng
libsrc/leddevice/LedDevicePiBlaster.h
#pragma once // Hyperion-Leddevice includes #include <leddevice/LedDevice.h> /// /// Implementation of the LedDevice interface for writing to pi-blaster based PWM LEDs /// class LedDevicePiBlaster : public LedDevice { public: /// /// Constructs specific LedDevice /// /// @param deviceConfig json device config /// LedDevicePiBlaster(const QJsonObject &deviceConfig); virtual ~LedDevicePiBlaster(); /// /// Sets configuration /// /// @param deviceConfig the json device config /// @return true if success bool init(const QJsonObject &deviceConfig); /// constructs leddevice static LedDevice* construct(const QJsonObject &deviceConfig); /// /// Attempts to open the piblaster-device. This will only succeed if the device is not yet open /// and the device is available. /// /// @return Zero on succes else negative /// int open(); private: /// /// Writes the colors to the PiBlaster device /// /// @param ledValues The color value for each led /// /// @return Zero on success else negative /// int write(const std::vector<ColorRgb> &ledValues); /// The name of the output device (very likely '/dev/pi-blaster') std::string _deviceName; int _gpio_to_led[64]; char _gpio_to_color[64]; /// File-Pointer to the PiBlaster device FILE * _fid; };
7h30n3/hyperion.ng
include/grabber/V4L2Grabber.h
#pragma once // stl includes #include <string> #include <vector> #include <map> // Qt includes #include <QObject> #include <QSocketNotifier> #include <QRectF> // util includes #include <utils/Image.h> #include <utils/ColorRgb.h> #include <utils/PixelFormat.h> #include <utils/VideoMode.h> #include <utils/ImageResampler.h> #include <utils/Logger.h> // grabber includes #include <grabber/VideoStandard.h> /// Capture class for V4L2 devices /// /// @see http://linuxtv.org/downloads/v4l-dvb-apis/capture-example.html class V4L2Grabber : public QObject { Q_OBJECT public: V4L2Grabber(const std::string & device, int input, VideoStandard videoStandard, PixelFormat pixelFormat, int width, int height, int frameDecimation, int horizontalPixelDecimation, int verticalPixelDecimation ); virtual ~V4L2Grabber(); QRectF getSignalDetectionOffset(); public slots: void setCropping(int cropLeft, int cropRight, int cropTop, int cropBottom); void set3D(VideoMode mode); void setSignalThreshold( double redSignalThreshold, double greenSignalThreshold, double blueSignalThreshold, int noSignalCounterThreshold); void setSignalDetectionOffset( double verticalMin, double horizontalMin, double verticalMax, double horizontalMax); bool start(); void stop(); signals: void newFrame(const Image<ColorRgb> & image); void readError(const char* err); private slots: int read_frame(); private: void getV4Ldevices(); bool init(); void uninit(); void open_device(); void close_device(); void init_read(unsigned int buffer_size); void init_mmap(); void init_userp(unsigned int buffer_size); void init_device(VideoStandard videoStandard, int input); void uninit_device(); void start_capturing(); void stop_capturing(); bool process_image(const void *p, int size); void process_image(const uint8_t *p); int xioctl(int request, void *arg); void throw_exception(const std::string &error); void throw_errno_exception(const std::string &error); private: enum io_method { IO_METHOD_READ, IO_METHOD_MMAP, IO_METHOD_USERPTR }; struct buffer { void *start; size_t length; }; private: std::string _deviceName; std::map<std::string,std::string> _v4lDevices; int _input; VideoStandard _videoStandard; io_method _ioMethod; int _fileDescriptor; std::vector<buffer> _buffers; PixelFormat _pixelFormat; int _width; int _height; int _lineLength; int _frameByteSize; int _frameDecimation; int _noSignalCounterThreshold; ColorRgb _noSignalThresholdColor; int _currentFrame; int _noSignalCounter; QSocketNotifier * _streamNotifier; ImageResampler _imageResampler; Logger * _log; bool _initialized; bool _deviceAutoDiscoverEnabled; bool _noSignalDetected; double _x_frac_min; double _y_frac_min; double _x_frac_max; double _y_frac_max; };
7h30n3/hyperion.ng
libsrc/leddevice/LedDeviceRawHID.h
<filename>libsrc/leddevice/LedDeviceRawHID.h #pragma once // Qt includes #include <QTimer> // hyperion include #include "ProviderHID.h" /// /// Implementation of the LedDevice interface for writing to an RawHID led device. /// class LedDeviceRawHID : public ProviderHID { Q_OBJECT public: /// /// Constructs specific LedDevice /// /// @param deviceConfig json device config /// LedDeviceRawHID(const QJsonObject &deviceConfig); /// constructs leddevice static LedDevice* construct(const QJsonObject &deviceConfig); private slots: /// Write the last data to the leds again void rewriteLeds(); private: /// /// Writes the led color values to the led-device /// /// @param ledValues The color-value per led /// @return Zero on succes else negative /// virtual int write(const std::vector<ColorRgb> & ledValues); };
7h30n3/hyperion.ng
libsrc/hyperion/LinearColorSmoothing.h
<gh_stars>0 #pragma once // STL includes #include <string> #include <vector> // Qt includes #include <QTimer> // hyperion incluse #include <leddevice/LedDevice.h> #include <utils/Components.h> /// Linear Smooting class /// /// This class processes the requested led values and forwards them to the device after applying /// a linear smoothing effect. This class can be handled as a generic LedDevice. class LinearColorSmoothing : public LedDevice { Q_OBJECT public: /// Constructor /// @param LedDevice the led device /// @param LedUpdatFrequency The frequency at which the leds will be updated (Hz) /// @param settingTime The time after which the updated led values have been fully applied (sec) /// @param updateDelay The number of frames to delay outgoing led updates LinearColorSmoothing(LedDevice *ledDevice, double ledUpdateFrequency, int settlingTime, unsigned updateDelay, bool continuousOutput); /// Destructor virtual ~LinearColorSmoothing(); /// write updated values as input for the smoothing filter /// /// @param ledValues The color-value per led /// @return Zero on succes else negative /// virtual int write(const std::vector<ColorRgb> &ledValues); /// Switch the leds off virtual int switchOff(); void setEnable(bool enable); bool enabled(); bool componentState() { return enabled(); }; private slots: /// Timer callback which writes updated led values to the led device void updateLeds(); private: /** * Pushes the colors into the output queue and popping the head to the led-device * * @param ledColors The colors to queue */ void queueColors(const std::vector<ColorRgb> & ledColors); /// The led device LedDevice * _ledDevice; /// The interval at which to update the leds (msec) const int64_t _updateInterval; /// The time after which the updated led values have been fully applied (msec) const int64_t _settlingTime; /// The Qt timer object QTimer _timer; /// The timestamp at which the target data should be fully applied int64_t _targetTime; /// The target led data std::vector<ColorRgb> _targetValues; /// The timestamp of the previously written led data int64_t _previousTime; /// The previously written led data std::vector<ColorRgb> _previousValues; /// The number of updates to keep in the output queue (delayed) before being output const unsigned _outputDelay; /// The output queue std::list<std::vector<ColorRgb> > _outputQueue; /// Prevent sending data to device when no intput data is sent bool _writeToLedsEnable; /// Flag for dis/enable continuous output to led device regardless there is new data or not bool _continuousOutput; bool _enabled; };
7h30n3/hyperion.ng
include/commandline/DoubleOption.h
<reponame>7h30n3/hyperion.ng<filename>include/commandline/DoubleOption.h #ifndef HYPERION_DOUBLECOMMANDLINEOPTION_H #define HYPERION_DOUBLECOMMANDLINEOPTION_H #include <QtCore> #include "ValidatorOption.h" namespace commandline { class DoubleOption: public ValidatorOption { protected: double _double; public: DoubleOption(const QString &name, const QString &description = QString(), const QString &valueName = QString(), const QString &defaultValue = QString(), double minimum = -INFINITY, double maximum = INFINITY, int decimals = 1000) : ValidatorOption(name, description, valueName, defaultValue) { setValidator(new QDoubleValidator(minimum, maximum, decimals)); } DoubleOption(const QStringList &names, const QString &description = QString(), const QString &valueName = QString(), const QString &defaultValue = QString(), double minimum = -INFINITY, double maximum = INFINITY, int decimals = 1000) : ValidatorOption(names, description, valueName, defaultValue) { setValidator(new QDoubleValidator(minimum, maximum, decimals)); } DoubleOption(const QCommandLineOption &other, double minimum = -INFINITY, double maximum = INFINITY, int decimals = 1000) : ValidatorOption(other) { setValidator(new QDoubleValidator(minimum, maximum, decimals)); } double getDouble(Parser &parser, bool *ok = 0); double *getDoublePtr(Parser &parser, bool *ok = 0); }; } #endif //HYPERION_DOUBLECOMMANDLINEOPTION_H
7h30n3/hyperion.ng
include/protoserver/ProtoConnectionWrapper.h
<gh_stars>0 // Qt includes #include <QObject> // hyperion includes #include <utils/Image.h> #include <utils/ColorRgb.h> #include <utils/GrabbingMode.h> #include <utils/VideoMode.h> // hyperion proto includes #include "protoserver/ProtoConnection.h" /// This class handles callbacks from the V4L2 and X11 grabber class ProtoConnectionWrapper : public QObject { Q_OBJECT public: ProtoConnectionWrapper(const QString &address, int priority, int duration_ms, bool skipProtoReply); virtual ~ProtoConnectionWrapper(); signals: /// /// Forwarding KODI Video Checker Message /// void setGrabbingMode(const GrabbingMode mode); void setVideoMode(const VideoMode videoMode); public slots: /// Handle a single image /// @param image The image to process void receiveImage(const Image<ColorRgb> & image); private: /// Priority for calls to Hyperion const int _priority; /// Duration for color calls to Hyperion const int _duration_ms; /// Hyperion proto connection object ProtoConnection _connection; };
7h30n3/hyperion.ng
libsrc/leddevice/LedDeviceFadeCandy.h
<filename>libsrc/leddevice/LedDeviceFadeCandy.h #pragma once // STL/Qt includes #include <QTcpSocket> // Leddevice includes #include <leddevice/LedDevice.h> /// /// Implementation of the LedDevice interface for sending to /// fadecandy/opc-server via network by using the 'open pixel control' protocol. /// class LedDeviceFadeCandy : public LedDevice { Q_OBJECT public: /// /// Constructs the LedDevice for fadecandy/opc server /// /// following code shows all config options /// @code /// "device" : /// { /// "name" : "MyPi", /// "type" : "fadecandy", /// "output" : "localhost", /// "colorOrder" : "rgb", /// "setFcConfig" : false, /// "gamma" : 1.0, /// "whitepoint" : [1.0, 1.0, 1.0], /// "dither" : false, /// "interpolation" : false, /// "manualLed" : false, /// "ledOn" : false /// }, ///@endcode /// /// @param deviceConfig json config for fadecandy /// LedDeviceFadeCandy(const QJsonObject &deviceConfig); /// /// Destructor of the LedDevice; closes the tcp client /// virtual ~LedDeviceFadeCandy(); /// constructs leddevice static LedDevice* construct(const QJsonObject &deviceConfig); /// /// Sets configuration /// /// @param deviceConfig the json device config /// @return true if success bool init(const QJsonObject &deviceConfig); /// /// Writes the led color values to the led-device /// /// @param ledValues The color-value per led /// @return Zero on succes else negative /// virtual int write(const std::vector<ColorRgb> & ledValues); private: QTcpSocket _client; std::string _host; uint16_t _port; unsigned _channel; QByteArray _opc_data; // fadecandy sysEx bool _setFcConfig; double _gamma; double _whitePoint_r; double _whitePoint_g; double _whitePoint_b; bool _noDither; bool _noInterp; bool _manualLED; bool _ledOnOff; /// try to establish connection to opc server, if not connected yet /// /// @return true if connection is established /// bool tryConnect(); /// return the conenction state /// /// @return True if connection established /// bool isConnected(); /// transfer current opc_data buffer to opc server /// /// @return amount of transfered bytes. -1 error while transfering, -2 error while connecting /// int transferData(); /// send system exclusive commands /// /// @param systemId fadecandy device identifier (for standard fadecandy always: 1) /// @param commandId id of command /// @param msg the sysEx message /// @return amount bytes written, -1 if fail int sendSysEx(uint8_t systemId, uint8_t commandId, QByteArray msg); /// sends the configuration to fcserver void sendFadeCandyConfiguration(); };
7h30n3/hyperion.ng
include/commandline/Option.h
#ifndef HYPERION_OPTION_H #define HYPERION_OPTION_H #include <QCommandLineOption> #include <QCommandLineParser> namespace commandline { class Parser; /* Note, this class and all it's derivatives store the validated results for caching. This means that unlike the * regular QCommandLineOption it is _not_ idempotent! */ class Option: public QCommandLineOption { protected: QString _error; public: Option(const QString &name, const QString &description = QString(), const QString &valueName = QString::null, const QString &defaultValue = QString() ) : QCommandLineOption(name, description, valueName, defaultValue) {} Option(const QStringList &names, const QString &description = QString(), const QString &valueName = QString::null, const QString &defaultValue = QString() ) : QCommandLineOption(names, description, valueName, defaultValue) {} Option(const QCommandLineOption &other) : QCommandLineOption(other) {} virtual bool validate(Parser &parser, QString &value); QString name() { return this->names().last();} QString getError() { return this->_error; } QString value(Parser &parser); std::string getStdString(Parser &parser); std::wstring getStdWString(Parser &parser); const char* getCString(Parser &parser); }; } #endif //HYPERION_OPTION_H
7h30n3/hyperion.ng
libsrc/hyperion/MultiColorAdjustment.h
<gh_stars>0 #pragma once // STL includes #include <vector> // Utils includes #include <utils/ColorRgb.h> // Hyperion includes #include <hyperion/ColorAdjustment.h> /// /// The LedColorTransform is responsible for performing color transformation from 'raw' colors /// received as input to colors mapped to match the color-properties of the leds. /// class MultiColorAdjustment { public: MultiColorAdjustment(const unsigned ledCnt); ~MultiColorAdjustment(); /** * Adds a new ColorAdjustment to this MultiColorTransform * * @param adjustment The new ColorAdjustment (ownership is transfered) */ void addAdjustment(ColorAdjustment * adjustment); void setAdjustmentForLed(const std::string& id, const unsigned startLed, const unsigned endLed); bool verifyAdjustments() const; /// /// Returns the identifier of all the unique ColorAdjustment /// /// @return The list with unique id's of the ColorAdjustment const std::vector<std::string> & getAdjustmentIds(); /// /// Returns the pointer to the ColorAdjustment with the given id /// /// @param id The identifier of the ColorAdjustment /// /// @return The ColorAdjustment with the given id (or nullptr if it does not exist) /// ColorAdjustment* getAdjustment(const std::string& id); /// /// Performs the color adjustment from raw-color to led-color /// /// @param ledColors The list with raw colors /// void applyAdjustment(std::vector<ColorRgb>& ledColors); private: /// List with transform ids std::vector<std::string> _adjustmentIds; /// List with unique ColorTransforms std::vector<ColorAdjustment*> _adjustment; /// List with a pointer to the ColorAdjustment for each individual led std::vector<ColorAdjustment*> _ledAdjustments; // logger instance Logger * _log; };
7h30n3/hyperion.ng
include/utils/FileUtils.h
#pragma once #include <QString> namespace FileUtils { QString getBaseName( QString sourceFile); QString getDirName( QString sourceFile); };
7h30n3/hyperion.ng
include/grabber/DispmanxWrapper.h
#pragma once // Utils includes #include <utils/Image.h> #include <utils/ColorRgb.h> #include <utils/ColorRgba.h> #include <utils/GrabbingMode.h> #include <utils/VideoMode.h> #include <hyperion/GrabberWrapper.h> // Forward class declaration class DispmanxFrameGrabber; class ImageProcessor; /// /// The DispmanxWrapper uses an instance of the DispmanxFrameGrabber to obtain ImageRgb's from the /// displayed content. This ImageRgb is processed to a ColorRgb for each led and commmited to the /// attached Hyperion. /// class DispmanxWrapper: public GrabberWrapper { Q_OBJECT public: /// /// Constructs the dispmanx frame grabber with a specified grab size and update rate. /// /// @param[in] grabWidth The width of the grabbed image [pixels] /// @param[in] grabHeight The height of the grabbed images [pixels] /// @param[in] updateRate_Hz The image grab rate [Hz] /// @param[in] hyperion The instance of Hyperion used to write the led values /// DispmanxWrapper(const unsigned grabWidth, const unsigned grabHeight, const unsigned updateRate_Hz, const int priority); /// /// Destructor of this dispmanx frame grabber. Releases any claimed resources. /// virtual ~DispmanxWrapper(); public slots: /// /// Performs a single frame grab and computes the led-colors /// virtual void action(); void setCropping(const unsigned cropLeft, const unsigned cropRight, const unsigned cropTop, const unsigned cropBottom); /// /// Set the video mode (2D/3D) /// @param[in] mode The new video mode /// void setVideoMode(const VideoMode videoMode); private: /// The update rate [Hz] const int _updateInterval_ms; /// The timeout of the led colors [ms] const int _timeout_ms; /// The image used for grabbing frames Image<ColorRgba> _image; /// The actual grabber DispmanxFrameGrabber * _grabber; /// The list with computed led colors std::vector<ColorRgb> _ledColors; };
7h30n3/hyperion.ng
include/grabber/X11Grabber.h
// Hyperion-utils includes #include <utils/Image.h> #include <utils/ColorRgb.h> #include <utils/ImageResampler.h> #include <utils/Logger.h> // X11 includes #include <X11/Xlib.h> #include <X11/extensions/Xrender.h> #include <X11/extensions/XShm.h> #include <sys/ipc.h> #include <sys/shm.h> class X11Grabber { public: X11Grabber(bool useXGetImage, int cropLeft, int cropRight, int cropTop, int cropBottom, int horizontalPixelDecimation, int verticalPixelDecimation); virtual ~X11Grabber(); /// /// Set the video mode (2D/3D) /// @param[in] mode The new video mode /// void setVideoMode(const VideoMode videoMode); bool Setup(); Image<ColorRgb> & grab(); /// /// Captures a single snapshot of the display and writes the data to the given image. The /// provided image should have the same dimensions as the configured values (_width and /// _height) /// /// @param[out] image The snapped screenshot (should be initialized with correct width and /// height) /// int grabFrame(Image<ColorRgb> & image); /// /// update dimension according current screen int updateScreenDimensions(); /// gets resulting height of image const unsigned getImageWidth() { return _croppedWidth; }; /// gets resulting width of image const unsigned getImageHeight() { return _croppedHeight; }; private: ImageResampler _imageResampler; bool _useXGetImage, _XShmAvailable, _XShmPixmapAvailable, _XRenderAvailable; int _cropLeft; int _cropRight; int _cropTop; int _cropBottom; XImage* _xImage; XShmSegmentInfo _shminfo; /// Reference to the X11 display (nullptr if not opened) Display* _x11Display; Window _window; XWindowAttributes _windowAttr; Pixmap _pixmap; XRenderPictFormat* _srcFormat; XRenderPictFormat* _dstFormat; XRenderPictureAttributes _pictAttr; Picture _srcPicture; Picture _dstPicture; XTransform _transform; int _horizontalDecimation; int _verticalDecimation; unsigned _screenWidth; unsigned _screenHeight; unsigned _croppedWidth; unsigned _croppedHeight; Image<ColorRgb> _image; void freeResources(); void setupResources(); Logger * _log; };
7h30n3/hyperion.ng
src/hyperiond/hyperiond.h
#pragma once #include <QObject> #ifdef ENABLE_DISPMANX #include <grabber/DispmanxWrapper.h> #else typedef QObject DispmanxWrapper; #endif #ifdef ENABLE_V4L2 #include <grabber/V4L2Wrapper.h> #else typedef QObject V4L2Wrapper; #endif #ifdef ENABLE_FB #include <grabber/FramebufferWrapper.h> #else typedef QObject FramebufferWrapper; #endif #ifdef ENABLE_AMLOGIC #include <grabber/AmlogicWrapper.h> #else typedef QObject AmlogicWrapper; #endif #ifdef ENABLE_OSX #include <grabber/OsxWrapper.h> #else typedef QObject OsxWrapper; #endif #ifdef ENABLE_X11 #include <grabber/X11Wrapper.h> #else typedef QObject X11Wrapper; #endif #include <utils/Logger.h> #include <kodivideochecker/KODIVideoChecker.h> #include <jsonserver/JsonServer.h> #include <protoserver/ProtoServer.h> #include <boblightserver/BoblightServer.h> #include <udplistener/UDPListener.h> #include <QJsonObject> class HyperionDaemon : public QObject { Q_OBJECT public: HyperionDaemon(QString configFile, QObject *parent=nullptr); ~HyperionDaemon(); int tryLoadConfig(const QString & configFile, const int schemaVersion); void loadConfig(const QString & configFile, const int neededConfigVersion); void run(); void startInitialEffect(); void createKODIVideoChecker(); void startNetworkServices(); // grabber creators void createGrabberV4L2(); void createSystemFrameGrabber(); public slots: void freeObjects(); private: void createGrabberDispmanx(); void createGrabberAmlogic(); void createGrabberFramebuffer(const QJsonObject & grabberConfig); void createGrabberOsx(const QJsonObject & grabberConfig); void createGrabberX11(const QJsonObject & grabberConfig); Logger* _log; QJsonObject _qconfig; KODIVideoChecker* _kodiVideoChecker; JsonServer* _jsonServer; ProtoServer* _protoServer; BoblightServer* _boblightServer; UDPListener* _udpListener; std::vector<V4L2Wrapper*> _v4l2Grabbers; DispmanxWrapper* _dispmanx; #ifdef ENABLE_X11 X11Wrapper* _x11Grabber; #endif AmlogicWrapper* _amlGrabber; FramebufferWrapper* _fbGrabber; OsxWrapper* _osxGrabber; Hyperion* _hyperion; unsigned _grabber_width; unsigned _grabber_height; unsigned _grabber_frequency; int _grabber_priority; unsigned _grabber_cropLeft; unsigned _grabber_cropRight; unsigned _grabber_cropTop; unsigned _grabber_cropBottom; };
7h30n3/hyperion.ng
include/hyperion/GrabberWrapper.h
#pragma once #include <QObject> #include <QTimer> #include <string> #include <utils/Logger.h> #include <utils/Components.h> #include <utils/GrabbingMode.h> #include <hyperion/Hyperion.h> class ImageProcessor; class GrabberWrapper : public QObject { Q_OBJECT public: GrabberWrapper(std::string grabberName, const int priority, hyperion::Components grabberComponentId=hyperion::COMP_GRABBER); virtual ~GrabberWrapper(); /// /// Starts the grabber wich produces led values with the specified update rate /// virtual bool start(); /// /// Stop grabber /// virtual void stop(); public slots: void componentStateChanged(const hyperion::Components component, bool enable); /// /// virtual method, should perform single frame grab and computes the led-colors /// virtual void action() = 0; /// /// Set the grabbing mode /// @param[in] mode The new grabbing mode /// void setGrabbingMode(const GrabbingMode mode); signals: void emitImage(int priority, const Image<ColorRgb> & image, const int timeout_ms); protected: void setColors(const std::vector<ColorRgb> &ledColors, const int timeout_ms); std::string _grabberName; /// Pointer to Hyperion for writing led values Hyperion * _hyperion; /// The priority of the led colors const int _priority; /// The timer for generating events with the specified update rate QTimer _timer; /// The Logger instance Logger * _log; // forwarding enabled bool _forward; /// The processor for transforming images to led colors ImageProcessor * _processor; hyperion::Components _grabberComponentId; };
7h30n3/hyperion.ng
include/grabber/FramebufferFrameGrabber.h
<reponame>7h30n3/hyperion.ng #pragma once // Utils includes #include <utils/Image.h> #include <utils/ColorRgb.h> #include <utils/VideoMode.h> #include <utils/ImageResampler.h> #include <utils/Logger.h> /// /// The FramebufferFrameGrabber is used for creating snapshots of the display (screenshots) /// class FramebufferFrameGrabber { public: /// /// Construct a FramebufferFrameGrabber that will capture snapshots with specified dimensions. /// /// @param[in] device The framebuffer device name/path /// @param[in] width The width of the captured screenshot /// @param[in] height The heigth of the captured screenshot /// FramebufferFrameGrabber(const std::string & device, const unsigned width, const unsigned height); ~FramebufferFrameGrabber(); /// /// Set the video mode (2D/3D) /// @param[in] mode The new video mode /// void setVideoMode(const VideoMode videoMode); /// /// Captures a single snapshot of the display and writes the data to the given image. The /// provided image should have the same dimensions as the configured values (_width and /// _height) /// /// @param[out] image The snapped screenshot (should be initialized with correct width and /// height) /// void grabFrame(Image<ColorRgb> & image); private: /// Framebuffer file descriptor int _fbfd; /// Pointer to framebuffer unsigned char * _fbp; /// Framebuffer device e.g. /dev/fb0 const std::string _fbDevice; /// With of the captured snapshot [pixels] const unsigned _width; /// Height of the captured snapshot [pixels] const unsigned _height; /// Image resampler for downscaling the image ImageResampler * _imgResampler; Logger * _log; };
7h30n3/hyperion.ng
libsrc/leddevice/LedDeviceTinkerforge.h
<gh_stars>0 #pragma once // STL includes #include <cstdio> // Hyperion-Leddevice includes #include <leddevice/LedDevice.h> extern "C" { #include <tinkerforge/ip_connection.h> #include <tinkerforge/bricklet_led_strip.h> } class LedDeviceTinkerforge : public LedDevice { public: /// /// Constructs specific LedDevice /// /// @param deviceConfig json device config /// LedDeviceTinkerforge(const QJsonObject &deviceConfig); virtual ~LedDeviceTinkerforge(); /// /// Sets configuration /// /// @param deviceConfig the json device config /// @return true if success bool init(const QJsonObject &deviceConfig); /// constructs leddevice static LedDevice* construct(const QJsonObject &deviceConfig); /// /// Attempts to open a connection to the master bricklet and the led strip bricklet. /// /// @return Zero on succes else negative /// int open(); private: /// /// Writes the colors to the led strip bricklet /// /// @param ledValues The color value for each led /// /// @return Zero on success else negative /// virtual int write(const std::vector<ColorRgb> &ledValues); /// /// Writes the data to the led strip blicklet int transferLedData(LEDStrip *ledstrip, unsigned int index, unsigned int length, uint8_t *redChannel, uint8_t *greenChannel, uint8_t *blueChannel); /// The host of the master brick std::string _host; /// The port of the master brick uint16_t _port; /// The uid of the led strip bricklet std::string _uid; /// The interval/rate unsigned _interval; /// ip connection handle IPConnection *_ipConnection; /// led strip handle LEDStrip *_ledStrip; /// buffer for red channel led data std::vector<uint8_t> _redChannel; /// buffer for red channel led data std::vector<uint8_t> _greenChannel; /// buffer for red channel led data std::vector<uint8_t> _blueChannel; /// buffer size of the color channels unsigned int _colorChannelSize; };
7h30n3/hyperion.ng
include/utils/RgbToRgbw.h
#pragma once #include <utils/ColorRgb.h> #include <utils/ColorRgbw.h> namespace RGBW { enum WhiteAlgorithm { INVALID, SUBTRACT_MINIMUM, SUB_MIN_WARM_ADJUST, WHITE_OFF }; WhiteAlgorithm stringToWhiteAlgorithm(std::string str); void Rgb_to_Rgbw(ColorRgb input, ColorRgbw * output, const WhiteAlgorithm algorithm); };
benkehoe/cpython
Parser/pegen_errors.c
#include <Python.h> #include <errcode.h> #include "tokenizer.h" #include "pegen.h" // TOKENIZER ERRORS void _PyPegen_raise_tokenizer_init_error(PyObject *filename) { if (!(PyErr_ExceptionMatches(PyExc_LookupError) || PyErr_ExceptionMatches(PyExc_SyntaxError) || PyErr_ExceptionMatches(PyExc_ValueError) || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) { return; } PyObject *errstr = NULL; PyObject *tuple = NULL; PyObject *type; PyObject *value; PyObject *tback; PyErr_Fetch(&type, &value, &tback); errstr = PyObject_Str(value); if (!errstr) { goto error; } PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None); if (!tmp) { goto error; } tuple = PyTuple_Pack(2, errstr, tmp); Py_DECREF(tmp); if (!value) { goto error; } PyErr_SetObject(PyExc_SyntaxError, tuple); error: Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(tback); Py_XDECREF(errstr); Py_XDECREF(tuple); } static inline void raise_unclosed_parentheses_error(Parser *p) { int error_lineno = p->tok->parenlinenostack[p->tok->level-1]; int error_col = p->tok->parencolstack[p->tok->level-1]; RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError, error_lineno, error_col, error_lineno, -1, "'%c' was never closed", p->tok->parenstack[p->tok->level-1]); } int _Pypegen_tokenizer_error(Parser *p) { if (PyErr_Occurred()) { return -1; } const char *msg = NULL; PyObject* errtype = PyExc_SyntaxError; Py_ssize_t col_offset = -1; switch (p->tok->done) { case E_TOKEN: msg = "invalid token"; break; case E_EOF: if (p->tok->level) { raise_unclosed_parentheses_error(p); } else { RAISE_SYNTAX_ERROR("unexpected EOF while parsing"); } return -1; case E_DEDENT: RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level"); return -1; case E_INTR: if (!PyErr_Occurred()) { PyErr_SetNone(PyExc_KeyboardInterrupt); } return -1; case E_NOMEM: PyErr_NoMemory(); return -1; case E_TABSPACE: errtype = PyExc_TabError; msg = "inconsistent use of tabs and spaces in indentation"; break; case E_TOODEEP: errtype = PyExc_IndentationError; msg = "too many levels of indentation"; break; case E_LINECONT: { col_offset = p->tok->cur - p->tok->buf - 1; msg = "unexpected character after line continuation character"; break; } default: msg = "unknown parsing error"; } RAISE_ERROR_KNOWN_LOCATION(p, errtype, p->tok->lineno, col_offset >= 0 ? col_offset : 0, p->tok->lineno, -1, msg); return -1; } int _Pypegen_raise_decode_error(Parser *p) { assert(PyErr_Occurred()); const char *errtype = NULL; if (PyErr_ExceptionMatches(PyExc_UnicodeError)) { errtype = "unicode error"; } else if (PyErr_ExceptionMatches(PyExc_ValueError)) { errtype = "value error"; } if (errtype) { PyObject *type; PyObject *value; PyObject *tback; PyObject *errstr; PyErr_Fetch(&type, &value, &tback); errstr = PyObject_Str(value); if (errstr) { RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr); Py_DECREF(errstr); } else { PyErr_Clear(); RAISE_SYNTAX_ERROR("(%s) unknown error", errtype); } Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(tback); } return -1; } static int _PyPegen_tokenize_full_source_to_check_for_errors(Parser *p) { // Tokenize the whole input to see if there are any tokenization // errors such as mistmatching parentheses. These will get priority // over generic syntax errors only if the line number of the error is // before the one that we had for the generic error. // We don't want to tokenize to the end for interactive input if (p->tok->prompt != NULL) { return 0; } PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1]; Py_ssize_t current_err_line = current_token->lineno; int ret = 0; for (;;) { const char *start; const char *end; switch (_PyTokenizer_Get(p->tok, &start, &end)) { case ERRORTOKEN: if (p->tok->level != 0) { int error_lineno = p->tok->parenlinenostack[p->tok->level-1]; if (current_err_line > error_lineno) { raise_unclosed_parentheses_error(p); ret = -1; goto exit; } } break; case ENDMARKER: break; default: continue; } break; } exit: if (PyErr_Occurred()) { Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(traceback); } else { PyErr_Restore(type, value, traceback); } return ret; } // PARSER ERRORS void * _PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...) { if (p->fill == 0) { va_list va; va_start(va, errmsg); _PyPegen_raise_error_known_location(p, errtype, 0, 0, 0, -1, errmsg, va); va_end(va); return NULL; } Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1]; Py_ssize_t col_offset; Py_ssize_t end_col_offset = -1; if (t->col_offset == -1) { if (p->tok->cur == p->tok->buf) { col_offset = 0; } else { const char* start = p->tok->buf ? p->tok->line_start : p->tok->buf; col_offset = Py_SAFE_DOWNCAST(p->tok->cur - start, intptr_t, int); } } else { col_offset = t->col_offset + 1; } if (t->end_col_offset != -1) { end_col_offset = t->end_col_offset + 1; } va_list va; va_start(va, errmsg); _PyPegen_raise_error_known_location(p, errtype, t->lineno, col_offset, t->end_lineno, end_col_offset, errmsg, va); va_end(va); return NULL; } static PyObject * get_error_line_from_tokenizer_buffers(Parser *p, Py_ssize_t lineno) { /* If the file descriptor is interactive, the source lines of the current * (multi-line) statement are stored in p->tok->interactive_src_start. * If not, we're parsing from a string, which means that the whole source * is stored in p->tok->str. */ assert((p->tok->fp == NULL && p->tok->str != NULL) || p->tok->fp == stdin); char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str; assert(cur_line != NULL); for (int i = 0; i < lineno - 1; i++) { cur_line = strchr(cur_line, '\n') + 1; } char *next_newline; if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line next_newline = cur_line + strlen(cur_line); } return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace"); } void * _PyPegen_raise_error_known_location(Parser *p, PyObject *errtype, Py_ssize_t lineno, Py_ssize_t col_offset, Py_ssize_t end_lineno, Py_ssize_t end_col_offset, const char *errmsg, va_list va) { PyObject *value = NULL; PyObject *errstr = NULL; PyObject *error_line = NULL; PyObject *tmp = NULL; p->error_indicator = 1; if (end_lineno == CURRENT_POS) { end_lineno = p->tok->lineno; } if (end_col_offset == CURRENT_POS) { end_col_offset = p->tok->cur - p->tok->line_start; } if (p->start_rule == Py_fstring_input) { const char *fstring_msg = "f-string: "; Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg); char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character if (!new_errmsg) { return (void *) PyErr_NoMemory(); } // Copy both strings into new buffer memcpy(new_errmsg, fstring_msg, strlen(fstring_msg)); memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg)); new_errmsg[len] = 0; errmsg = new_errmsg; } errstr = PyUnicode_FromFormatV(errmsg, va); if (!errstr) { goto error; } if (p->tok->fp_interactive) { error_line = get_error_line_from_tokenizer_buffers(p, lineno); } else if (p->start_rule == Py_file_input) { error_line = _PyErr_ProgramDecodedTextObject(p->tok->filename, (int) lineno, p->tok->encoding); } if (!error_line) { /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called, then we need to find the error line from some other source, because p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly failed or we're parsing from a string or the REPL. There's a third edge case where we're actually parsing from a file, which has an E_EOF SyntaxError and in that case `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which does not physically exist */ assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF); if (p->tok->lineno <= lineno && p->tok->inp > p->tok->buf) { Py_ssize_t size = p->tok->inp - p->tok->buf; error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace"); } else if (p->tok->fp == NULL || p->tok->fp == stdin) { error_line = get_error_line_from_tokenizer_buffers(p, lineno); } else { error_line = PyUnicode_FromStringAndSize("", 0); } if (!error_line) { goto error; } } if (p->start_rule == Py_fstring_input) { col_offset -= p->starting_col_offset; end_col_offset -= p->starting_col_offset; } Py_ssize_t col_number = col_offset; Py_ssize_t end_col_number = end_col_offset; if (p->tok->encoding != NULL) { col_number = _PyPegen_byte_offset_to_character_offset(error_line, col_offset); if (col_number < 0) { goto error; } if (end_col_number > 0) { Py_ssize_t end_col_offset = _PyPegen_byte_offset_to_character_offset(error_line, end_col_number); if (end_col_offset < 0) { goto error; } else { end_col_number = end_col_offset; } } } tmp = Py_BuildValue("(OiiNii)", p->tok->filename, lineno, col_number, error_line, end_lineno, end_col_number); if (!tmp) { goto error; } value = PyTuple_Pack(2, errstr, tmp); Py_DECREF(tmp); if (!value) { goto error; } PyErr_SetObject(errtype, value); Py_DECREF(errstr); Py_DECREF(value); if (p->start_rule == Py_fstring_input) { PyMem_Free((void *)errmsg); } return NULL; error: Py_XDECREF(errstr); Py_XDECREF(error_line); if (p->start_rule == Py_fstring_input) { PyMem_Free((void *)errmsg); } return NULL; } void _Pypegen_set_syntax_error(Parser* p, Token* last_token) { // Existing sintax error if (PyErr_Occurred()) { // Prioritize tokenizer errors to custom syntax errors raised // on the second phase only if the errors come from the parser. int is_tok_ok = (p->tok->done == E_DONE || p->tok->done == E_OK); if (is_tok_ok && PyErr_ExceptionMatches(PyExc_SyntaxError)) { _PyPegen_tokenize_full_source_to_check_for_errors(p); } // Propagate the existing syntax error. return; } // Initialization error if (p->fill == 0) { RAISE_SYNTAX_ERROR("error at start before reading any input"); } // Parser encountered EOF (End of File) unexpectedtly if (last_token->type == ERRORTOKEN && p->tok->done == E_EOF) { if (p->tok->level) { raise_unclosed_parentheses_error(p); } else { RAISE_SYNTAX_ERROR("unexpected EOF while parsing"); } return; } // Indentation error in the tokenizer if (last_token->type == INDENT || last_token->type == DEDENT) { RAISE_INDENTATION_ERROR(last_token->type == INDENT ? "unexpected indent" : "unexpected unindent"); return; } // Unknown error (generic case) // Use the last token we found on the first pass to avoid reporting // incorrect locations for generic syntax errors just because we reached // further away when trying to find specific syntax errors in the second // pass. RAISE_SYNTAX_ERROR_KNOWN_LOCATION(last_token, "invalid syntax"); // _PyPegen_tokenize_full_source_to_check_for_errors will override the existing // generic SyntaxError we just raised if errors are found. _PyPegen_tokenize_full_source_to_check_for_errors(p); }
lewis180777/YHNetwork
YHNetwork/YHNetwork.h
// // YHNetwork.h // YHNetwork // // Created by 陈亦海 on 16/2/19. // Copyright © 2016年 陈亦海. All rights reserved. // //! Project version number for YHNetwork. FOUNDATION_EXPORT double YHNetworkVersionNumber; //! Project version string for YHNetwork. FOUNDATION_EXPORT const unsigned char YHNetworkVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <YHNetwork/PublicHeader.h> /** * 若要上传sessionId 就先做如下保存 [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"] 其他的就不需要做了 */ #import "YHNetworking.h"
lewis180777/YHNetwork
Example/YHNetwork/YHViewController.h
<gh_stars>0 // // YHViewController.h // YHNetwork // // Created by lewis180777 on 04/10/2017. // Copyright (c) 2017 lewis180777. All rights reserved. // @import UIKit; @interface YHViewController : UIViewController @end
P8P-7/core
src/modules/motor-controller/include/goliath/motor-controller/motor_handle.h
#pragma once #include <goliath/foundation.h> #include "motor_controller.h" namespace goliath::handles { class MotorHandle : public Handle { public: MotorHandle(const size_t &handleId, const motor_controller::MotorId motorId) : Handle(handleId), id(motorId) {} motor_controller::MotorId getMotorId() const; private: motor_controller::MotorId id; }; }
P8P-7/core
src/modules/servo/include/goliath/servo/wings/commandbuilder/wing_command_builder.h
#pragma once #include <goliath/servo/repositories/wing_state_repository.h> #include <goliath/servo/wings/wing_command.h> #include <goliath/servo/wing_handle.h> namespace goliath::servo { class WingCommandBuilder { public: WingCommandBuilder(); explicit WingCommandBuilder(std::shared_ptr<handles::WingHandle> handle); WingCommandBuilder(std::shared_ptr<handles::WingHandle> handle, std::uint16_t speed, double angle); WingCommandBuilder(std::shared_ptr<handles::WingHandle> handle, std::uint16_t speed, double angle, Direction direction); WingCommandBuilder &setHandle(std::shared_ptr<handles::WingHandle> handle); WingCommandBuilder &setAngle(double angle); WingCommandBuilder &setDirection(Direction direction); WingCommandBuilder &setShortestDirection(const WingState &state, double threshold = 180); WingCommandBuilder &flipDirection(); WingCommandBuilder &setSpeed(std::uint16_t speed); std::shared_ptr<handles::WingHandle> getHandle() const; WingCommand build() const; private: std::shared_ptr<handles::WingHandle> handle; double angle; std::uint16_t speed; Direction direction; }; }
P8P-7/core
src/modules/servo/include/goliath/servo/wings/wing_controller.h
<filename>src/modules/servo/include/goliath/servo/wings/wing_controller.h #pragma once #include <goliath/servo/repositories/wing_state_repository.h> #include <goliath/servo/wings/wing_command.h> #include <goliath/servo/wing_handle.h> #include <goliath/servo/servo_mode.h> namespace goliath::servo { class WingController { public: explicit WingController(std::shared_ptr<repositories::WingStateRepository> wingStateRepository); void setWorldAngle(handles::WingHandle &handle, double angle, std::uint16_t speed, Direction direction = Direction::CLOCKWISE); void setAngle(handles::WingHandle &handle, double angle, std::uint16_t speed, bool waitForCompletion = true); void setMode(handles::WingHandle &handle, ServoMode mode); void setSpeed(handles::WingHandle &handle, std::uint16_t speed, servo::Direction direction = servo::Direction::COUNTER_CLOCKWISE); double getAngleFromServo(handles::WingHandle &handle) const; void calibrate(handles::WingHandle &handle); void execute(std::vector<servo::WingCommand> commands); private: friend class DeadzoneTransitionController; std::shared_ptr<repositories::WingStateRepository> wingStateRepository; void _setAngle(handles::WingHandle &handle, double angle, bool waitForCompletion = true); void _setMode(handles::WingHandle &handle, ServoMode mode); void _setSpeed(handles::WingHandle &handle, std::uint16_t speed, servo::Direction direction = servo::Direction::COUNTER_CLOCKWISE); }; }
P8P-7/core
src/modules/i2c/include/goliath/i2c/i2c_error.h
<gh_stars>1-10 #pragma once #include <string> #include <exception> /** * @file i2c_error.h * @author Group 7 - Informatica */ namespace goliath::exceptions { class I2cError : public std::exception { public: /** * @param device i2c device for which the exception occurred * @param reason reason the exception occurred */ I2cError(std::string device, std::string reason); /** * @see std::exception */ const char* what() const noexcept override; private: const std::string reason; }; }
P8P-7/core
src/modules/transitions/include/goliath/transitions/reel.h
#pragma once #include <memory> #include "phase.h" #include "tickable.h" /** * @file reel.h * @author Group 7 - Informatica */ namespace goliath::transitions { /** * @class goliath::transitions::Reel * @brief Collection of phases that can be one after another */ class Reel : public Tickable { public: using iterator = std::vector<double>::iterator; using const_iterator = std::vector<double>::const_iterator; explicit Reel(size_t ticksPerSecond); /** * @param callback Update on every tick */ Reel(size_t ticksPerSecond, std::function<void(double)> callback); Reel(const Reel &other); /** * @brief Add a phase to this reel by creating a new one */ void addPhase(std::chrono::milliseconds duration, double min, double max, std::function<double(double)> method); /** * @brief Add a predefined phase to this reel * @param phase The new phase to be added */ void addPhase(std::shared_ptr<Phase> phase); /** * @brief Get the value at the current tick * @return Value at current tick */ double getTick(); void tick() override; /** * @brief Checks whether the reel is not out of bounds * @return True if not out of bounds */ bool canTick() const; /** * @brief Get the amount of ticks in this reel * @return Amount of ticks */ size_t getNumberOfTicks() const; iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; private: std::vector<std::shared_ptr<Phase>> phases; std::vector<double> preCalculated; size_t ticks; Tick currentTick; std::shared_ptr<std::function<void(double)>> callback; }; }
P8P-7/core
src/modules/vision/include/goliath/vision/detectors/within_box_detector.h
<reponame>P8P-7/core #pragma once #include "line_detector.h" /** * @file within_box_detector.h * @author Group 7 - Informatica */ namespace goliath::vision { const int DISTANCE_FROM_EDGE_THRESHOLD = 5; const int DISTANCE_FOR_CORNER_THRESHOLD = 5; class WithinBoxDetector : public LineDetector { public: WithinBoxDetector(const cv::Mat &input, int threshold, double minLineLength, double maxLineGap); std::vector<cv::Vec4d> detect() const override; private: bool pointAtEdge(double point, int edge) const; bool lineIsCorner(cv::Vec4d& line, std::vector<cv::Vec4d>& others); bool pointIsCorner(cv::Vec4d& line1, cv::Vec4d& line2); }; }
P8P-7/core
src/controller/include/goliath/controller/commands/move_wing_command.h
<gh_stars>1-10 #pragma once #include <goliath/servo.h> #include "basic_command.h" #include "../handles.h" namespace goliath::commands { class MoveWingCommand : public BasicCommand { public: MoveWingCommand(const size_t &id, std::shared_ptr<repositories::WingStateRepository> repository); private: std::shared_ptr<repositories::WingStateRepository> repository; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; void executeServoCommand(std::shared_ptr<handles::WingHandle> handle, const proto::commands::ServoCommand &command); static size_t enumToHandle(proto::commands::ServoCommand_Motor motor); }; }
P8P-7/core
src/controller/include/goliath/controller/commands/wunderhorn_command.h
#pragma once #include <goliath/vision.h> #include <goliath/motor-controller.h> #include "../handles.h" #include "basic_command.h" /** * @file follow_line_command.h * @author Group 7 - Informatica */ namespace goliath::commands { /** * @class goliath::commands::WunderhornCommand * @brief Command that follows a line and pauses on a coled area in the center */ class WunderhornCommand : public BasicCommand { public: /** * @param id Command ID * @param config Optional configuration */ explicit WunderhornCommand(const size_t &id); private: handles::HandleMap handleMap; vision::RoiProcessor lineRoi; vision::RoiProcessor areaRoi; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; /** * @brief Follows a straight line until it stops * @param followLineDetector Detector * @param camera Webcam */ void follow_line(vision::FollowLineDetector &followLineDetector, vision::Webcam &camera, motor_controller::MotorController &motorController); void move(double direction, int speed, motor_controller::MotorController &motorController); }; }
P8P-7/core
src/controller/include/goliath/controller/command_item.h
#pragma once #include "commands/command.h" /** * @file command_item.h * @author Group 7 - Informatica */ namespace goliath::commands { enum class CommandStatus { STARTING, /**< Command is just getting started */ STARTED, /**< Command has already started */ STALE /**< Command is doing nothing (idle) */ }; /** * @struct goliath::commands::CommandItem * @brief Tuple storing both the status of the command and the command instance itself */ struct CommandItem { CommandItem(); /** * @param commandInstance Instance of a command * @param status Starting status */ CommandItem(std::shared_ptr<Command> commandInstance, CommandStatus status); std::shared_ptr<Command> instance; CommandStatus status; }; }
P8P-7/core
src/modules/emotions/include/goliath/emotions/repositories/emotion_repository.h
<reponame>P8P-7/core<filename>src/modules/emotions/include/goliath/emotions/repositories/emotion_repository.h #pragma once #include <repositories/EmotionRepository.pb.h> #include <goliath/foundation/repositories/repository.h> /** * @file emotion_repository.h * @author Group 7 - Informatica */ namespace goliath::repositories { /** * @class goliath::repositories::EmotionRepository * @brief Repository for current emotion */ class EmotionRepository : public Repository { public: using Emotion = proto::repositories::EmotionRepository; EmotionRepository(); std::unique_ptr<google::protobuf::Message> getMessage() override; const Emotion::Emotion &getCurrentEmotion() const; void setCurrentEmotion(const Emotion::Emotion &emotion); private: Emotion::Emotion currentEmotion; }; }
P8P-7/core
src/modules/vision/include/goliath/vision/detectors/cup_detector.h
#pragma once #include "detector.h" /** * @file cup_detector.h * @author Group 7 - Informatica */ namespace goliath::vision { const cv::Scalar COLOR_MIN(0, 254, 0); const cv::Scalar COLOR_MAX(0, 255, 0); constexpr double MIN_CONTOUR_SIZE = 500; class CupDetector : public Detector { public: CupDetector(const cv::Mat &input, double widthScalar, double heightScalar, double widthPow, double heightPow); std::vector<cv::Vec4d> detect() const override; private: double widthScalar, heightScalar, widthPow, heightPow; }; }
P8P-7/core
src/controller/include/goliath/controller/repositories/battery_repository.h
#pragma once #include <google/protobuf/message.h> #include <goliath/foundation/repositories/polling_repository.h> /** * @file battery_repository.h * @author Group 7 - Informatica */ namespace goliath::repositories { /** * @class goliath::repositories::BatteryRepository * @brief Repository containing battery level */ class BatteryRepository : public PollingRepository { public: /** * @return Battery level */ int getBatteryLevel() const; /** * @return Battery voltage */ int getBatteryVoltage() const; /** * @return Battery min voltage */ int getBatteryMinVoltage() const; /** * @return Battery max voltage */ int getBatteryMaxVoltage() const; void setBatteryVoltage(int voltage); size_t getPollingCommandId() override; /** * @return Protobuf */ std::unique_ptr<::google::protobuf::Message> getMessage() override; private: int voltage; const int minVoltage = 105; const int maxVoltage = 126; }; }
P8P-7/core
src/modules/vision/include/goliath/vision/detectors/color_region_detector.h
<filename>src/modules/vision/include/goliath/vision/detectors/color_region_detector.h<gh_stars>1-10 #pragma once #include "detector.h" /** * @file color_region_detector.h * @author Group 7 - Informatica */ namespace goliath::vision { /** * @class goliath::vision::ColorRegionDetector * @brief */ class ColorRegionDetector : public Detector { public: ColorRegionDetector(const cv::Mat& input, int hMin, int hMax, int sMin, int sMax); std::vector<cv::Vec4d> detect() const override; private: int hMin, hMax, sMin, sMax; }; }
P8P-7/core
src/controller/include/goliath/controller/commands/obstacle_course_command.h
<filename>src/controller/include/goliath/controller/commands/obstacle_course_command.h #pragma once #include <goliath/vision.h> #include <goliath/servo.h> #include <goliath/motor-controller.h> #include "basic_command.h" #include "../handles.h" /** * @file obstacle_course_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class ObstacleCourseCommand : public BasicCommand { public: ObstacleCourseCommand(const size_t &id, std::shared_ptr<repositories::WingStateRepository> repository); private: std::shared_ptr<repositories::WingStateRepository> repository; handles::HandleMap handleMap; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; void follow_line(vision::FollowLineDetector &followLineDetector, vision::Webcam &camera, motor_controller::MotorController &motorController); void move(double direction, int speed, motor_controller::MotorController &motorController); }; }
P8P-7/core
src/modules/vision/include/goliath/vision/detectors/line_detector.h
<gh_stars>1-10 #pragma once #include <memory> #include "detector.h" /** * @file line_detector.h * @author Group 7 - Informatica */ namespace goliath::vision { /** * @brief Default Rho */ const int DEFAULT_LINE_DETECTOR_RHO = 1; /** * @brief Default Theta */ const double DEFAULT_LINE_DETECTOR_THETA = CV_PI / 180; /** * @class goliath::vision::LineDetector * @brief Takes in an image and detects all lines in the image */ class LineDetector : public Detector { public: LineDetector(const cv::Mat& input, int threshold, double rho, double theta, double minLineLength, double maxLineGap); /** * @param input Input image * @param threshold Variable that changes how straight a line must be to be detected. * @param minLineLength Minimum length of the line * @param maxLineGap Maximum gap (pixels) between points on a line */ LineDetector(const cv::Mat& input, int threshold, double minLineLength, double maxLineGap); LineDetector(const LineDetector& other); /** * @return Vector of all detected lines */ std::vector<cv::Vec4d> detect() const override; /** * @return The longest lines in detected lines */ std::vector<cv::Vec4d> longestLines(std::shared_ptr<Detector> detector) const; std::vector<cv::Vec4d> longestLines(); protected: const int threshold; const double rho, theta, minLineLength, maxLineGap; }; }
P8P-7/core
src/modules/vision/include/goliath/vision/util/vision_error.h
#pragma once #include <exception> #include <string> /** * @file vision_error.h * @author Group 7 - Informatica */ /** * @namespace goliath::exceptions * @brief Contains all custom exceptions */ namespace goliath::exceptions { /** * @class goliath::exceptions::VisionError * @brief All errors related to the vision module */ class VisionError : public std::exception { public: /** * @param reason Reason for exception */ explicit VisionError(std::string reason); const char* what() const noexcept override; private: const std::string reason; }; }
P8P-7/core
src/modules/transitions/include/goliath/transitions.h
#pragma once /** * @file transitions.h * @author Group 7 - Informatica */ /** * @namespace goliath::transitions * @brief Module for smooth transitions between movements */ #include "transitions/methods/eases.h" #include "transitions/util/transition_error.h" #include "transitions/util/transition_utilities.h" #include "transitions/parallel_reel.h" #include "transitions/phase.h" #include "transitions/reel.h" #include "transitions/transition_executor.h"
P8P-7/core
src/controller/include/goliath/controller/repositories/system_status_repository.h
<gh_stars>1-10 #pragma once #include <atomic> #include <google/protobuf/message.h> #include <goliath/foundation/repositories/polling_repository.h> /** * @file system_status_repository.h * @author Group 7 - Informatica */ namespace goliath::repositories { /** * @class goliath::repositories::SystemStatusRepository * @brief Repository containing system info */ class SystemStatusRepository : public PollingRepository { public: SystemStatusRepository(); /** * @return Raspberry Pi CPU temperature */ double getTemperature() const; void setTemperature(double temperature); bool getFanStatus() const; void setFanStatus(bool enabled); size_t getPollingCommandId() override; /** * @return Protobuf */ std::unique_ptr<google::protobuf::Message> getMessage() override; private: std::atomic<double> temperature; std::atomic<bool> fanEnabled; }; }
P8P-7/core
src/modules/gpio/include/goliath/gpio.h
<reponame>P8P-7/core<filename>src/modules/gpio/include/goliath/gpio.h #pragma once /** * @file gpio/include/goliath/gpio.h * @author Group 7 - Informatica */ /** * @namespace goliath::gpio * @brief Contains all classes and function for interfacing the GPIO bus on the Raspberry Pi */ #include "gpio/gpio.h" #include "gpio/gpio_handle.h"
P8P-7/core
src/modules/servo/include/goliath/servo/wings/wing_command.h
#pragma once #include <goliath/servo/wing_handle.h> #include <goliath/servo/servo_mode.h> namespace goliath::servo { struct WingCommand { handles::WingHandle &handle; std::uint16_t speed; double angle; servo::Direction direction; }; }
P8P-7/core
src/controller/include/goliath/controller/watcher.h
#pragma once #include <goliath/foundation.h> #include <goliath/controller/command_executor.h> #include <atomic> #include <thread> #include <vector> #include <memory> #include <goliath/foundation/repositories/repository.h> #include <goliath/foundation/publisher_service.h> /** * @file watcher.h * @author Group 7 - Informatica */ namespace goliath::repositories { /** * @class goliath::repositories::Watcher * @brief watches multiple repositories for changes and sends them to the publisher service */ class Watcher { public: /** * @param pollingRate rate at which the watcher thread polls each repository * @param publisher service to which the watcher should publish a @see SynchronizeMessage */ Watcher(int polling_rate, foundation::PublisherService &publisher, std::shared_ptr<commands::CommandExecutor> &executor); /** * @brief Destructs the watcher and calls stop() */ ~Watcher(); /** * @brief Invalidates all repositories watched by this watcher */ void invalidateAll(); /** * @return true when any of the repositories is invalidated */ bool shouldSynchronize() const; /** * @brief Adds a repository to the watchlist * @param repo repository to be watched */ void watch(std::shared_ptr<Repository> repo); /** * @return all repositories watched by this watcher */ std::vector<std::shared_ptr<Repository>> getRepositories(); /** * @brief Start the watcher thread */ void start(); /** * @brief Stops the watcher thread */ void stop(); private: int pollingRate; foundation::PublisherService &publisher; std::vector<std::shared_ptr<Repository>> repositories; std::atomic<bool> running; std::thread thread; std::shared_ptr<commands::CommandExecutor> commandExecutor; void synchronize(); void run(); }; }
P8P-7/core
src/modules/vision/include/goliath/vision/detectors/detector.h
<reponame>P8P-7/core<gh_stars>1-10 #pragma once #include <opencv2/opencv.hpp> /** * @file detector.h * @author Group 7 - Informatica */ namespace goliath::vision { /** * @class goliath::vision::Detector * @brief Base class of detectors that take an input and detect a vector of shapes, colors or sizes. */ class Detector { public: /** * @param input Input Image */ explicit Detector(const cv::Mat &input); /** * @param other Copy constructor */ Detector(const Detector &other); virtual ~Detector(); /** * @return A vector of vectors representing different objects that can be referenced from other detectors or * commands. * It is abstract and can represent anything the implementation desires. */ virtual std::vector<cv::Vec4d> detect() const = 0; /** * @brief Update input image * @param input New input image */ void update(cv::Mat &input); protected: cv::Mat input; }; }
P8P-7/core
src/modules/motor-controller/include/goliath/motor-controller.h
#pragma once #include "motor-controller/motor_controller.h" #include "motor-controller/motor_handle.h"
P8P-7/core
src/controller/include/goliath/controller/commands/transport_rebuild_command.h
<gh_stars>1-10 #pragma once #include "basic_command.h" #include "../handles.h" /** * @file transport_rebuild_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class TransportRebuildCommand : public BasicCommand { public: explicit TransportRebuildCommand(const size_t &id); private: void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; }; }
P8P-7/core
src/controller/include/goliath/controller.h
#pragma once /** * @file controller.h * @author Group 7 - Informatica */ #include "controller/repositories/config_repository.h" #include "controller/repositories/command_status_repository.h" #include "controller/repositories/battery_repository.h" #include "controller/repositories/log_repository.h" #include "controller/repositories/system_status_repository.h" #include "controller/watcher.h" #include "controller/commands/command.h" #include "controller/commands/basic_command.h" #include "controller/commands/queue_command.h" #include "controller/commands/wunderhorn_command.h" #include "controller/commands/move_command.h" #include "controller/commands/move_wing_command.h" #include "controller/commands/move_arm_command.h" #include "controller/commands/grip_command.h" #include "controller/commands/dance_command.h" #include "controller/commands/enter_command.h" #include "controller/commands/interrupt_command_command.h" #include "controller/commands/invalidate_all_command.h" #include "controller/commands/line_dance_command.h" #include "controller/commands/obstacle_course_command.h" #include "controller/commands/synchronize_commands_command.h" #include "controller/commands/synchronize_system_status_command.h" #include "controller/commands/synchronize_battery_voltage_command.h" #include "controller/commands/transport_rebuild_command.h" #include "controller/commands/shutdown_command.h" #include "controller/commands/set_wing_position_command.h" #include "controller/command_executor.h" #include "controller/command_item.h" #include "controller/command_map.h" #include "controller/handles.h" #include "controller/handle_map.h"
P8P-7/core
src/modules/transitions/include/goliath/transitions/phase.h
#pragma once #include <chrono> #include <functional> #include <vector> #include "tickable.h" /** * @file phase.h * @author Group 7 - Informatica */ namespace goliath::transitions { /** * @class goliath::transitions::Phase * @brief A piece of a reel with form */ class Phase { public: using iterator = std::vector<double>::iterator; using const_iterator = std::vector<double>::const_iterator; /** * @param duration Length of this phase * @param ticksPerSecond Speed of this phase * @param min Lower bound of the phase (mapped to 0) * @param max Upper bound of the phase (mapped to 1) * @param method Type of transition (e. g. linear, eases) */ Phase(std::chrono::milliseconds duration, size_t ticksPerSecond, double min, double max, std::function<double(double)> method); /** * @brief Get value at specific tick * @param tick Tick * @return Value at tick */ double get(Tick tick) const; /** * @brief Get length of this phase * @return Duration */ const std::chrono::milliseconds getDuration() const; /** * @brief Get speed of this phase * @return Ticks per Second */ size_t getTicksPerSecond() const; /** * @brief Get total amount of ticks this phase uses * @return Total ticks */ size_t getNumberOfTicks() const; iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; private: const std::chrono::milliseconds duration; const size_t ticksPerSecond; const double min, max; const size_t ticks; std::vector<double> preCalculated; }; }
P8P-7/core
src/modules/emotions/include/goliath/emotions/emotion_handle.h
<reponame>P8P-7/core #pragma once #include <goliath/foundation.h> #include "repositories/emotion_repository.h" namespace goliath::handles { class EmotionHandle : public Handle { public: EmotionHandle(const size_t &handleId, const std::shared_ptr<repositories::EmotionRepository> &emotionRepository); std::shared_ptr<repositories::EmotionRepository> getEmotionRepository(); private: std::shared_ptr<repositories::EmotionRepository> emotionRepository; }; }
P8P-7/core
src/modules/transitions/include/goliath/transitions/parallel_reel.h
#pragma once #include <memory> #include "tickable.h" #include "reel.h" /** * @file parallel_reel.h * @author Group 7 - Informatica */ namespace goliath::transitions { /** * @class goliath::transitions::ParallelReel * @brief Runs multiple reels at the same time */ class ParallelReel : public Tickable { public: explicit ParallelReel(std::vector<std::shared_ptr<Reel>> reels); void tick() override; /** * @return Duration of longest reel */ std::chrono::milliseconds getDuration() const override; /** * @return Speed of all reels */ const size_t getTicksPerSecond() const override; private: const std::vector<std::shared_ptr<Reel>> reels; }; }
P8P-7/core
src/modules/transitions/include/goliath/transitions/transition_executor.h
<filename>src/modules/transitions/include/goliath/transitions/transition_executor.h #pragma once #include <memory> #include "tickable.h" /** * @file transition_executor.h * @author Group 7 - Informatica */ namespace goliath::transitions { /** * @class goliath::transitions::TransitionExecutor * @brief Executes a transition */ class TransitionExecutor { public: using Clock = std::chrono::high_resolution_clock; using TimePoint = std::chrono::time_point<Clock>; using Milliseconds = std::chrono::milliseconds; using Microseconds = std::chrono::microseconds; /** * @brief Executes a class implementing the tickable interface by taking their tps and duration and calling the * tick method within the specified duration * @param tickable Tickable to be run * @return Amount of skipped ticks */ static size_t execute(std::shared_ptr<Tickable> tickable); }; }
P8P-7/core
src/controller/include/goliath/controller/handles.h
<filename>src/controller/include/goliath/controller/handles.h #pragma once /** * @file handles.h * @author Group 7 - Informatica */ /** * @namespace goliath::handles * @brief Contains all handles and handle utilities */ #define HANDLE_LEFT_FRONT_WING_SERVO 0 #define HANDLE_LEFT_BACK_WING_SERVO 1 #define HANDLE_RIGHT_FRONT_WING_SERVO 2 #define HANDLE_RIGHT_BACK_WING_SERVO 3 #define HANDLE_GPIO_PIN_5 35 #define HANDLE_GPIO_PIN_FAN 36 #define HANDLE_BASE_ARM 4 #define HANDLE_FIRST_JOINT_ARM 5 #define HANDLE_SECOND_JOINT_ARM 6 #define HANDLE_GRIPPER_ARM 7 #define HANDLE_MOTOR_CONTROLLER 10 #define HANDLE_LEFT_FRONT_MOTOR 11 #define HANDLE_LEFT_BACK_MOTOR 12 #define HANDLE_RIGHT_FRONT_MOTOR 13 #define HANDLE_RIGHT_BACK_MOTOR 14 #define HANDLE_LED_CONTROLLER 20 #define HANDLE_I2C_BUS 50 #define HANDLE_EMOTIONS 60 #define HANDLE_CAM 101
P8P-7/core
src/modules/vision/include/goliath/vision/processors/roi_processor.h
<reponame>P8P-7/core #pragma once #include "processor.h" /** * @file roi_processor.h * @author Group 7 - Informatica */ namespace goliath::vision { /** * @brief Takes an input and returns a ROI selection from that image */ class RoiProcessor : public Processor { public: /** * @param input Input image * @param x Top left of ROI X * @param y Top left of ROI Y * @param w Width of ROI * @param h Height of ROI */ RoiProcessor(const cv::Mat &input, int x, int y, int w, int h); RoiProcessor(Processor &other, int x, int y, int w, int h); /** * @return ROI Selection of the input */ cv::Mat process() const override; const int getX() const; const int getY() const; const int getWidth() const; const int getHeight() const; private: const int x, y, w, h; }; }
P8P-7/core
src/controller/include/goliath/controller/commands/line_dance_command.h
#pragma once #include <goliath/gpio.h> #include <goliath/servo/wings/wing_command.h> #include <goliath/servo/wings/wing_controller.h> #include <goliath/servo/repositories/wing_state_repository.h> #include "basic_command.h" #include "../handles.h" /** * @file line_dance_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class LineDanceCommand : public BasicCommand { public: explicit LineDanceCommand(const size_t &id, const std::shared_ptr<repositories::WingStateRepository> &repository); void processPulse(); void startBeat(); void waitForBeat(); void listenGpio(std::shared_ptr<gpio::GPIO> gpioDevice); private: std::shared_ptr<repositories::WingStateRepository> repository; std::chrono::high_resolution_clock::time_point t0; std::chrono::high_resolution_clock::time_point t1; /** * @brief Represents whether a beat has been started or not */ std::atomic<bool> beatStarted{false}; std::mutex mutex; std::thread thread; /** * @brief Condition variable that can be waited on */ std::condition_variable beatStart; /** * @brief Used to calculate the running BPM */ std::deque<double> history; std::atomic<bool> hasBeat; /** * @brief Running BPM */ std::atomic<double> runningBpm{0.0}; /** * @brief Smallest possible BPM allowed */ double minimumAllowedBpm = 40.0; /** * @brief Largest possible BPM allowed */ double maximumAllowedBpm = 120.0; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; }; }
P8P-7/core
src/controller/include/goliath/controller/commands/synchronize_battery_voltage_command.h
#pragma once #include <goliath/servo.h> #include "basic_command.h" #include "../handles.h" #include "../repositories/battery_repository.h" /** * @file synchronize_battery_voltage_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class SynchronizeBatteryVoltageCommand : public BasicCommand { public: SynchronizeBatteryVoltageCommand(const size_t &id, std::shared_ptr<repositories::BatteryRepository> batteryRepository); private: std::shared_ptr<repositories::BatteryRepository> batteryRepository; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; int getVoltage(const std::shared_ptr<handles::ServoHandle> servoHandle); }; }
P8P-7/core
src/modules/openal/include/goliath/openal/util/openal_error.h
<reponame>P8P-7/core #pragma once #include <string> /** * @file openal_error.h * @author Group 7 - Informatica */ namespace goliath::exceptions { /** * @class goliath::exceptions::OpenalError * @brief All errors related to the audio module */ class OpenalError : public std::exception { public: /** * @param reason Reason for exception */ explicit OpenalError(std::string reason); const char* what() const noexcept override; private: const std::string reason; }; }
P8P-7/core
src/controller/include/goliath/controller/repositories/command_status_repository.h
#pragma once #include <string> #include <repositories/CommandStatusRepository.pb.h> #include <goliath/foundation/repositories/repository.h> #include "../command_item.h" /** * @file command_status_repository.h * @author Group 7 - Informatica */ namespace goliath::repositories { class CommandStatusRepository : public Repository { public: using CommandStatusItem = goliath::proto::repositories::CommandStatusItem; void addItem(size_t commandId); void addItem(size_t commandId, commands::CommandStatus status); void updateItem(size_t commandId, commands::CommandStatus status); std::unique_ptr<google::protobuf::Message> getMessage() override; private: std::map<int, commands::CommandStatus> items; }; }
P8P-7/core
src/controller/include/goliath/controller/commands/interrupt_command_command.h
<filename>src/controller/include/goliath/controller/commands/interrupt_command_command.h #pragma once #include "basic_command.h" #include "../command_map.h" /** * @file interrupt_command_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class InterruptCommandCommand : public BasicCommand { public: InterruptCommandCommand(const size_t &id, std::shared_ptr<CommandMap> &commandMap); private: std::shared_ptr<CommandMap> commandMap; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; }; }
P8P-7/core
src/modules/openal/include/goliath/openal.h
<reponame>P8P-7/core<filename>src/modules/openal/include/goliath/openal.h #pragma once /** * @file openal.h * @author Group 7 - Informatica */ /** * @namespace goliath::openal * @brief OpenAL module to handle anything audio-related on the software side. */ #include "openal/util/openal_error.h" #include "openal/device.h" #include "openal/context.h" #include "openal/microphone.h"
P8P-7/core
src/modules/vision/include/goliath/vision.h
#pragma once /** * @file vision.h * @author Group 7 - Informatica */ /** * @namespace goliath::vision * @brief Module for all things vision-related */ #include "vision/detectors/color_region_detector.h" #include "vision/detectors/cup_detector.h" #include "vision/detectors/detector.h" #include "vision/detectors/follow_line_detector.h" #include "vision/detectors/line_detector.h" #include "vision/detectors/within_box_detector.h" #include "vision/processors/canny_processor.h" #include "vision/processors/color_processor.h" #include "vision/processors/processor.h" #include "vision/processors/roi_processor.h" #include "vision/util/vision_error.h" #include "vision/webcam.h" #include "vision/webcam_handle.h"
P8P-7/core
src/modules/i2c/include/goliath/i2c/handles/i2c_slave_handle.h
<reponame>P8P-7/core #pragma once #include <goliath/foundation.h> /** * @file i2c_slave_handle.h * @author Group 7 - Informatica */ namespace goliath::i2c { using I2cAddress = std::uint8_t; } namespace goliath::handles { class I2cSlaveHandle : public Handle { public: I2cSlaveHandle(const size_t &id, const i2c::I2cAddress &address); /** * @return slave address */ const i2c::I2cAddress& getSlaveAddress() const; private: std::string device; i2c::I2cAddress address; }; }
P8P-7/core
src/modules/vision/include/goliath/vision/detectors/follow_line_detector.h
<gh_stars>1-10 #pragma once #include "detector.h" /** * @file follow_line_detector.h * @author Group 7 - Informatica */ namespace goliath::vision { /** * @enum goliath::vision::FollowLineDirection * @brief Represents a direction the robot should go in, outputted from the follow_line_detector. */ enum FollowLineDirection { ON_COURSE = 0, /**< Robot should continue going straight */ LEFT = 1, /**< Robot should go left */ RIGHT = 2, /**< Robot should go right */ NO_LINE = 3 /**< No single line detected */ }; /** * @class goliath::vision::FollowLineDetector * @brief Takes in an input image, splits it up into "boxes". Within those boxes it checks if there is a single * contour, if so take the center of that contour and compare it to the center of the box. This will return an * offset. Take the average of all offsets to determine if the robot should go straight, left or right. The second * value will be the distance from the edge of the box (percentage) the robot will have to turn. */ class FollowLineDetector : public Detector { public: /** * @param input Input Image * @param boxes Amount of boxes to create a ROI from * @param boxHeight The height of each of the boxes * @param boxesBottomMargin Margin to start bottom-most box from * @param boxesHorizontalMargin Margins on both sides of the boxes * @param minContourArea Minimal area of the contour within a box to be considered part of a line * @param maxContourArea Maximal area of the contour within a box to be considered part of a line */ FollowLineDetector(const cv::Mat& input, int boxes, int boxHeight, int boxesBottomMargin, int boxesHorizontalMargin, double minContourArea, double maxContourArea); /** * @brief Copy constructor */ FollowLineDetector(const FollowLineDetector& other); /** * @return Value [0][0] contains whether the robot should continue going straight, or go left/right. This value * is defined in the follow_line_direction enum. Value [0][1] contains the percentage from the edge of the * current box the camera is located. Can be used to determine the strength of the caterpillars. [0][2] Contains * the box used from the bottom up. [1] Contains the box represented as a Vec4b. */ std::vector<cv::Vec4d> detect() const override; private: const int boxes, boxHeight, boxesBottomMargin, boxesHorizontalMargin; const double minContourArea, maxContourArea; }; }
P8P-7/core
src/controller/include/goliath/controller/commands/enter_command.h
<reponame>P8P-7/core<filename>src/controller/include/goliath/controller/commands/enter_command.h<gh_stars>1-10 #pragma once #include <goliath/motor-controller.h> #include "../handles.h" #include "basic_command.h" /** * @file enter_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class EnterCommand : public BasicCommand { public: EnterCommand(const size_t &id); private: void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; }; }
P8P-7/core
src/modules/vision/include/goliath/vision/processors/color_processor.h
<gh_stars>1-10 #pragma once #include "processor.h" /** * @file color_processor.h * @author Group 7 - Informatica */ namespace goliath::vision { /** * @class goliath::vision::ColorProcessor * @brief Processor that returns an image with only colors within a specific range */ class ColorProcessor : public Processor { public: /** * @param inputBgr Input image * @param min Minimum color hsv range * @param max Maximum color hsv range */ ColorProcessor(const cv::Mat &inputBgr, const cv::Scalar &min, const cv::Scalar &max); ColorProcessor(Processor& other, const cv::Scalar &min, const cv::Scalar &max); /** * @return Black/white image from input with colors within a specific range */ cv::Mat process() const override; private: const cv::Scalar min; const cv::Scalar max; }; }
P8P-7/core
src/modules/motor-controller/include/goliath/motor-controller/motor_controller.h
<reponame>P8P-7/core<filename>src/modules/motor-controller/include/goliath/motor-controller/motor_controller.h #pragma once #include <cstdint> #include <goliath/i2c.h> #include <vector> namespace goliath::motor_controller { using MotorId = std::uint8_t; using MotorSpeed = std::uint8_t; /** * The physical motor controller has two pins for each motor to set in which direction it goes. * Each direction in this enum represents a state of a set of these pins. * * \warning Before the motor can change direction it has to be stalled. The motor controller does this for you, but this takes some time. */ enum class MotorDirection: std::uint8_t { /** * One of the pins is high, the other is low. */ FORWARDS = 0, /** * Counterpart of FORWARDS */ BACKWARDS = 1, /** * Both pins are low. Thus the motor is free to move. */ FREE = 2, /** * Both pins are high, so the motor is locked at its current position. */ LOCKED = 3 }; /** * Struct representing a current, or new motor status. */ struct MotorStatus { MotorId id; MotorDirection direction; MotorSpeed speed; }; /** * Handles all interaction with the physical motor controller */ class MotorController { public: /** * @param slave the slave on the i2c bus representing the motor controller */ explicit MotorController(i2c::I2cSlave &slave); MotorController(); /** * Sends a message to the physical controller to process. * @param command new motor status to process */ void sendCommand(const MotorStatus &command); template<typename IteratorType> void sendCommands(const IteratorType &begin, const IteratorType &end); /** * Retrieves all motors from the motor controller, but only uses the first byte to determine the number of motors. * @return number of motors connected to the motor controller */ size_t getNumberOfMotors(); /** * Retrieves all motors from the motor controller. * @return vector of all motors connected */ std::vector<MotorStatus> getMotors(); private: /** * Maximum supported of connected motors. */ const static size_t maxNumberOfMotors = 4; /** * Size of allocated buffer before receiving the command. */ const static size_t motorBufferSize = 1 + sizeof(MotorStatus) * maxNumberOfMotors; i2c::I2cSlave& slave; }; template<typename IteratorType> void MotorController::sendCommands(const IteratorType &begin, const IteratorType &end) { slave.write(begin, end); } }
P8P-7/core
src/modules/vision/include/goliath/vision/webcam_handle.h
#pragma once #include <goliath/foundation.h> #include "webcam.h" /** * @file webcam_handle.h * @author Group 7 - Informatica */ namespace goliath::handles { /** * @class goliath::handles::WebcamHandle * @brief Handle that locks webcams, passes the device to be used as VideoCapture */ class WebcamHandle : public Handle { public: /** * @param id Handle ID * @param device The recording device */ explicit WebcamHandle(const size_t &id, const int &device); /** * @return Currently set device */ const vision::Webcam& getDevice() const; private: const vision::Webcam device; }; }
P8P-7/core
src/controller/include/goliath/controller/commands/synchronize_system_status_command.h
#pragma once #include <thread> #include "../handles.h" #include "../repositories/system_status_repository.h" #include "basic_command.h" /** * @file fan_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class SynchronizeSystemStatusCommand : public BasicCommand { public: SynchronizeSystemStatusCommand(const size_t &id, std::shared_ptr<repositories::SystemStatusRepository> systemStatusRepository, double enableFanThreshold, double disableFanThreshold); private: static const std::string TEMPERATURE_FILE; std::shared_ptr<repositories::SystemStatusRepository> systemStatusRepository; double enableFanThreshold; double disableFanThreshold; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; }; }
P8P-7/core
src/modules/i2c/include/goliath/i2c/i2c_slave.h
#pragma once #include <string> #include "handles/i2c_bus_handle.h" #include "handles/i2c_slave_handle.h" #include "i2c_error.h" /** * @file i2c_slave.h * @author Group 7 - Informatica */ namespace goliath::i2c { class I2cSlave { public: /** * @brief Initializes an instance with a handle to a bus and a handle to a slave on that bus. * @param busHandle * @param slaveHandle */ I2cSlave(const handles::I2cBusHandle &busHandle, const handles::I2cSlaveHandle &slaveHandle); /** * @brief Initializes an instance with a bus handle and an address corresponding to a slave on that bus. * @param busHandle * @param slaveAddress */ I2cSlave(const handles::I2cBusHandle &busHandle, const I2cAddress &slaveAddress); ~I2cSlave(); /** * @warning Length of iterator should not be larger than the max value of @see I2cAddress. * * @tparam IteratorType type of iterator * @param begin begin of iterator * @param end end of iterator */ template<typename IteratorType> void write(IteratorType begin, IteratorType end) { auto tempLength = std::distance(begin, end) * sizeof(typename std::iterator_traits<IteratorType>::value_type); if (tempLength < std::numeric_limits<size_t>::min() || tempLength > std::numeric_limits<size_t>::max()) { throw goliath::exceptions::I2cError(device, "Buffer too large"); } auto length = static_cast<size_t>(tempLength); write(reinterpret_cast<const char *>(&*begin), length); } /** * @brief Write single byte to slave in one message. * @param value byte to write * @return the same instance of @see I2cSlave */ I2cSlave &operator<<(const char &value); /** * Writes anything at buffer with size length to the slave. * @param buffer pointer to start * @param length length of message * @return number of written bytes */ ssize_t write(const char *buffer, size_t length); /** * Request the slave to send something. * @param buffer pointer to start writing * @param length size of buffer * @return total number of bytes read */ ssize_t read(char *buffer, size_t length); private: std::string device; i2c::I2cAddress address; int file_descriptor; void setActiveSlaveOnBus(const i2c::I2cAddress &address); }; }
P8P-7/core
src/controller/include/goliath/controller/commands/move_command.h
<gh_stars>1-10 #pragma once #include "../handles.h" #include "queue_command.h" /** * @file move_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class MoveCommand : public QueueCommand { public: using MotorProto = proto::commands::MotorCommand::Motor; /** * @bief map of a protobuf motor id to a handle id representing the id */ const static std::map<proto::commands::MotorCommand_Motor, size_t> COMMAND_MOTOR_TO_HANDLE_MAP; explicit MoveCommand(const size_t &id); private: /** * Process queue items and combine multiple items in the queue to reduce traffic on the i2c bus */ void process() override; /** * Execute multiple commands and send to motor controller * @param commandMessages commands to process */ void execute(const std::vector<proto::commands::MotorCommand> &commandMessages); }; }
P8P-7/core
src/modules/gpio/include/goliath/gpio/gpio.h
<gh_stars>1-10 #pragma once #include <string> /** * @file gpio/gpio.h * @author Group 7 - Informatica */ namespace goliath::gpio { class GPIO { public: enum class MapPin { GPIO2 = 2, GPIO3 = 3, GPIO4 = 4, GPIO5 = 5, GPIO6 = 6, GPIO7 = 7, GPIO8 = 8, GPIO9 = 9, GPIO10 = 10, GPIO11 = 11, GPIO12 = 12, GPIO13 = 13, GPIO14 = 14, GPIO15 = 15, GPIO16 = 16, GPIO17 = 17, GPIO18 = 18, GPIO19 = 19, GPIO20 = 20, GPIO21 = 21, GPIO22 = 22, GPIO23 = 23, GPIO24 = 24, GPIO25 = 25, GPIO26 = 26, GPIO27 = 27, }; enum class State { Low = 0, High = 1, }; enum class Direction { Out = 0, In = 1 }; GPIO(); explicit GPIO(MapPin x); GPIO(MapPin x, Direction dir); GPIO(MapPin x, Direction dir, State val); void setup(MapPin x); void setup(MapPin x, Direction dir); void setup(MapPin x, Direction dir, State val); int exportGpio(); int unexportGpio(); int close(); int setdirGpio(std::string dir); int setdirGpio(int dir); int setvalGpio(std::string val); int setvalGpio(int val); int set(State val); int getvalGpio(std::string &val); int getvalGpio(int &val); int get(); std::string getGpionum(); int getiGpionum(); private: std::string gpionum; }; }
P8P-7/core
src/modules/servo/include/goliath/servo/servo_mode.h
<filename>src/modules/servo/include/goliath/servo/servo_mode.h #pragma once namespace goliath::servo { enum class ServoMode { WHEEL, JOINT }; enum class Direction { CLOCKWISE, COUNTER_CLOCKWISE }; }
P8P-7/core
src/controller/include/goliath/controller/commands/set_wing_position_command.h
#pragma once #include <goliath/servo.h> #include "../handles.h" #include "basic_command.h" /** * @file set_wing_position_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class SetWingPositionCommand : public BasicCommand { public: explicit SetWingPositionCommand(const size_t &id, std::shared_ptr<repositories::WingStateRepository> repository); private: std::shared_ptr<repositories::WingStateRepository> repository; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; void calibrate(handles::HandleMap &handles); void setFlat(handles::HandleMap &handles, std::uint16_t speed); void setUp(handles::HandleMap &handles, std::uint16_t speed); void setRamp(handles::HandleMap &handles, std::uint16_t speed); void setDown(handles::HandleMap &handles, std::uint16_t speed); servo::WingCommand buildCommand(handles::WingHandle &handle, std::uint16_t speed, double angle, servo::Direction direction); servo::WingCommand buildCommand(handles::WingHandle &handle, std::uint16_t speed, double angle); }; }
P8P-7/core
src/modules/vision/include/goliath/vision/processors/processor.h
<reponame>P8P-7/core<filename>src/modules/vision/include/goliath/vision/processors/processor.h #pragma once #include <opencv2/opencv.hpp> /** * @file processor.h * @author Group 7 - Informatica */ namespace goliath::vision { /** * @class goliath::vision::Processor * @brief Base class of processors that take in an input and manipulate in some way returning the output from the * virtual @see goliath::vision::processor#process method. */ class Processor { public: /** * @param input Input image */ explicit Processor(const cv::Mat& input); virtual ~Processor(); /** * @return Output image */ virtual cv::Mat process() const = 0; protected: /** * @brief Input image */ cv::Mat input; }; }
P8P-7/core
src/modules/openal/include/goliath/openal/context.h
#pragma once #include "device.h" /** * @file context.h * @author Group 7 - Informatica */ namespace goliath::openal { /** * @class goliath::openal::Context * @brief Context to be passed to different devices */ class Context { public: /** * @param device Device to set as main device within context * @param context Context address (Default NULL) */ Context(const Device &device, const ALCint *context); private: ALCcontext* alcContext; }; }
P8P-7/core
src/modules/servo/include/goliath/servo.h
#pragma once /** * @file gpio.h * @author Group 7 - Informatica */ /** * @namespace goliath::servo * @brief Contains all classes and function for interfacing a servo */ #include "servo/repositories/wing_state_repository.h" #include "servo/repositories/wing_state.h" #include "servo/wings/commandbuilder/wing_command_builder.h" #include "servo/wings/wing_command.h" #include "servo/wings/wing_controller.h" #include "servo/servo_handle.h" #include "servo/wing_handle.h" #include "servo/servo_mode.h"
P8P-7/core
src/modules/servo/include/goliath/servo/utilities.h
#pragma once #include "servo_mode.h" namespace goliath::servo { class Utilities { public: static Direction flipDirection(Direction direction); }; }
P8P-7/core
src/modules/transitions/include/goliath/transitions/tickable.h
<reponame>P8P-7/core #pragma once #include <chrono> /** * @file tickable.h * @author Group 7 - Informatica */ namespace goliath::transitions { using Tick = std::uint32_t; /** * @class goliath::transitions::Tickable * @brief Interface for defining whether a this transition can be executed or not */ class Tickable { public: /** * @param ticksPerSecond Speed of the transition */ Tickable(const size_t ticksPerSecond); /** * @brief Get the next tick value */ virtual void tick() = 0; /** * @return Length of this transition */ virtual std::chrono::milliseconds getDuration() const; /** * @return Get the speed of this transition */ virtual const size_t getTicksPerSecond() const; protected: mutable std::chrono::milliseconds duration; const size_t ticksPerSecond; }; }
P8P-7/core
src/controller/include/goliath/controller/commands/synchronize_commands_command.h
<filename>src/controller/include/goliath/controller/commands/synchronize_commands_command.h #pragma once #include "basic_command.h" #include "../repositories/command_status_repository.h" /** * @file synchronize_commands_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class SynchronizeCommandsCommand : public BasicCommand { public: SynchronizeCommandsCommand(const size_t &id, std::shared_ptr<repositories::CommandStatusRepository> &commandStatusRepository); private: std::shared_ptr<repositories::CommandStatusRepository> commandStatusRepository; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; }; }
P8P-7/core
src/modules/servo/include/goliath/servo/wing_handle.h
#pragma once #include <goliath/servo/servo_handle.h> #include <goliath/servo/servo_mode.h> namespace goliath::handles { class WingHandle : public ServoHandle { public: WingHandle(const size_t &id, const std::shared_ptr<dynamixel::Dynamixel> &device, std::size_t numberOfSectors, bool mirrorAngle, bool flipDirection, double offsetAngle); double getTranslatedWorldAngle(double angle) const; double getTranslatedAngle(double angle) const; std::size_t getTranslatedSector(std::size_t sector) const; servo::Direction getTranslatedDirection(servo::Direction direction) const; private: std::size_t numberOfSectors; bool mirrorAngle; bool flipDirection; double offsetAngle; }; }
P8P-7/core
src/controller/include/goliath/controller/repositories/config_repository.h
<filename>src/controller/include/goliath/controller/repositories/config_repository.h #pragma once #include <string> #include <repositories/ConfigRepository.pb.h> #include <goliath/foundation.h> /** * @file config_repository.h * @author Group 7 - Informatica */ namespace goliath::repositories { class ConfigRepository : public Repository { public: explicit ConfigRepository(std::string &configFile); std::shared_ptr<proto::repositories::ConfigRepository> getConfig(); std::unique_ptr<google::protobuf::Message> getMessage() override; private: std::string jsonString; }; }
P8P-7/core
src/modules/emotions/include/goliath/emotions.h
<filename>src/modules/emotions/include/goliath/emotions.h<gh_stars>1-10 #pragma once /** * @file emotions.h * @author Group 7 - Informatica */ /** * @namespace goliath::emotions * @brief Contains utilities to send emotions to emotion display Raspberry Pi */ #include "emotions/emotion_handle.h" #include "emotions/repositories/emotion_repository.h"
P8P-7/core
src/modules/openal/include/goliath/openal/microphone.h
<reponame>P8P-7/core #pragma once #include <chrono> #include <AL/al.h> #include <AL/alc.h> #include "device.h" /** * @file microphone.h * @author Group 7 - Informatica */ namespace goliath::openal { class Microphone : public Device { public: Microphone(ALCuint frequency, ALCenum format, ALCsizei bufferSize, ALchar* deviceName = nullptr); /** * @brief Records audio from the microphone and returns it into the buffer. * @warning Make the capture buffer is large enough to fit the audio within the specified duration! * @param captureBuffer Buffer where the recorded audio is stored * @param duration How long the microphone will record * @param interval Duration between each of the sample recordings */ void record(ALubyte *captureBuffer, std::chrono::microseconds duration, std::chrono::microseconds interval); private: ALubyte buffer; }; }
P8P-7/core
src/modules/gpio/include/goliath/gpio/gpio_handle.h
#pragma once #include <goliath/foundation.h> #include "gpio.h" /** * @file gpio_handle.h * @author Group 7 - Informatica */ namespace goliath::handles { /** * @class goliath::handles::gpio_handle * @brief Handle that locks GPIO pins */ class GPIOHandle : public Handle { public: /** * @param device The GPIO device. */ GPIOHandle(const size_t &id, std::shared_ptr<gpio::GPIO> device); /** * @return Currently set device */ std::shared_ptr<gpio::GPIO> getDevice(); private: std::shared_ptr<gpio::GPIO> device; }; }
P8P-7/core
src/modules/servo/include/goliath/servo/repositories/wing_state.h
<reponame>P8P-7/core #pragma once #include <cstddef> #include <cstdint> #include "../servo_mode.h" namespace goliath::servo { class WingState { public: WingState() = default; explicit WingState(const size_t &numberOfSectors); WingState(const WingState &other); void setWorldAngle(double angle); void reset(double newAngle); ServoMode getMode() const; void setMode(ServoMode mode); bool hasLostTracking() const; double getWorldAngle() const; double getAngle() const; void setAngle(double angle); size_t getSector() const; void setSector(size_t sector); size_t getNumberOfSectors() const; double getRatio() const; std::uint16_t getSpeed() const; void setSpeed(std::uint16_t speed); double getAngleFromWorldAngle(double angle) const; size_t getSectorFromWorldAngle(double angle) const; servo::Direction getDirectionFromWorldAngle(double angle, double threshold = 180) const; size_t getAdjacentSector(size_t sector, servo::Direction direction) const; size_t getNextSector(servo::Direction direction) const; private: size_t numberOfSectors; double angle; size_t sector; std::uint16_t speed; ServoMode mode; bool isTrackingLost; }; }
P8P-7/core
src/controller/include/goliath/controller/commands/invalidate_all_command.h
<filename>src/controller/include/goliath/controller/commands/invalidate_all_command.h #pragma once #include "../watcher.h" #include "../handles.h" #include "basic_command.h" /** * @file invalidate_command.h * @author Group 7 - Informatica */ namespace goliath::commands { class InvalidateAllCommand : public BasicCommand { public: InvalidateAllCommand(const size_t &id, std::shared_ptr<repositories::Watcher> watcher); private: std::shared_ptr<repositories::Watcher> watcher; void execute(handles::HandleMap &handles, const proto::CommandMessage &message) override; }; }
P8P-7/core
src/modules/led-strip-controller/include/goliath/led-strip-controller.h
<filename>src/modules/led-strip-controller/include/goliath/led-strip-controller.h #pragma once #include "led-strip-controller/led_strip_controller.h"
P8P-7/core
src/modules/servo/include/goliath/servo/repositories/wing_state_repository.h
<gh_stars>1-10 #pragma once #include <goliath/foundation.h> #include <repositories/WingStateRepository.pb.h> #include "wing_state.h" #include "../servo_mode.h" namespace goliath::repositories { class WingStateRepository : public Repository { public: const size_t numberOfSectors = 4; explicit WingStateRepository(const std::vector<size_t> &handles); void updateWorldAngle(const size_t &handleId, const double &angle, const size_t &sector); void setCurrentAngleToBaseAngle(const size_t &handleId, const double &angle); void updateAngle(const size_t &handleId, const double &angle); void updateMode(const size_t &handleId, const servo::ServoMode &mode); void updateSpeed(const size_t &handleId, std::uint16_t speed); const servo::WingState &getState(const size_t &handleId) const; bool hasLostTracking() const; std::unique_ptr<::google::protobuf::Message> getMessage() override; private: std::map<size_t, servo::WingState> states; }; }
P8P-7/core
src/controller/include/goliath/controller/handle_map.h
<filename>src/controller/include/goliath/controller/handle_map.h #pragma once #include <goliath/foundation.h> /** * @file handle_map.h * @author Group 7 - Informatica */ namespace goliath::handles { /** * @class goliath::handles::HandleMap * @brief Map of all handles mapped to an integer */ class HandleMap { public: using iterator = std::map<size_t, std::shared_ptr<Handle>>::iterator; using const_iterator = std::map<size_t, std::shared_ptr<Handle>>::const_iterator; HandleMap(); /** * @param map Starting map */ explicit HandleMap(const std::map<size_t, std::shared_ptr<Handle>> &map); HandleMap(const HandleMap &other); ~HandleMap(); /** * @brief Add a handle pair * @param handle Pointer to the handle itself */ template<typename HandleType> std::shared_ptr<HandleType> add(std::shared_ptr<HandleType> handle); template<typename HandleType, typename... Targs> std::shared_ptr<HandleType> add(const size_t &index, Targs... args); /** * @brief Get handles for a specific selecion of ID's * @param handles Vector of ID's you want to gather * @return HandleMap Selection */ HandleMap getHandles(const std::vector<size_t> &handles) const; /** * @brief Lock all handles for a specific command * @param commandId Command ID for the handle's to be locked on */ void lockAll(const size_t &commandId); /** * @brief Unlock all handles associated with a speciifc command */ void unlockAll(); std::shared_ptr<Handle>& operator[](const size_t &index); const std::shared_ptr<Handle>& operator[](const size_t &index) const; /** * @brief Begin iterator * @return Map iterator */ iterator begin(); /** * @brief End iterator * @return Map iterator */ iterator end(); /** * @brief Begin iterator * @return Constant map iterator */ const_iterator begin() const; /** * @brief End constant iterator * @return Constant map iterator */ const_iterator end() const; template<typename HandleType> std::shared_ptr<HandleType> get(const size_t &index) const; private: /** * @brief The map itself */ std::map<size_t, std::shared_ptr<Handle>> map; }; template<typename HandleType> std::shared_ptr<HandleType> HandleMap::get(const size_t &index) const { return std::static_pointer_cast<HandleType>(map.at(index)); } template<typename HandleType> std::shared_ptr<HandleType> HandleMap::add(std::shared_ptr<HandleType> handle) { map[handle->getId()] = handle; return handle; } template<typename HandleType, typename ...HandleArgs> std::shared_ptr<HandleType> HandleMap::add(const size_t &index, HandleArgs... args) { auto handle = std::make_shared<HandleType>(index, args...); map[index] = handle; return handle; } }
P8P-7/core
src/modules/i2c/include/goliath/i2c.h
#pragma once /** * @file i2c.h * @author Group 7 - Informatica */ /** * @namespace goliath::i2c * @brief Contains I2C utilities for connecting the Pi with an Arduino */ #include "i2c/handles/i2c_slave_handle.h" #include "i2c/handles/i2c_bus_handle.h" #include "i2c/i2c_error.h" #include "i2c/i2c_slave.h"
P8P-7/core
src/controller/include/goliath/controller/commands/command.h
#pragma once #include <thread> #include <mutex> #include <condition_variable> #include <CommandMessage.pb.h> #include "../handle_map.h" /** * @file command.h * @author Group 7 - Informatica */ /** * @namespace goliath::commands * @brief Contains all command and command utilities */ namespace goliath::commands { /** * @class goliath::commands::Command * @brief Command base class */ class Command { public: Command(const size_t &id, const std::vector<size_t> &requiredHandles); /** * @return id by which the command is known in a goliath::commands::CommandMap */ size_t getId() const; /** * @brief Execute a command * @param handles Handle map to be passed to command, contains only required handles in a locked state * @param message Arguments to be passed */ void execute(handles::HandleMap &handles, const proto::CommandMessage &message); /** * @brief Interrupt a command by setting the interrupted property */ virtual void interrupt(); /** * @brief Method to check wether a command is already interrupted * @return The value of interrupted */ bool isInterrupted() const; /** * @brief Handle getter * @return The handles this specific command requires */ const std::vector<size_t> &getRequiredHandles() const; /** * @brief Checks if a command can start by checking all the handles it occupies * @param command Command to check the occupying handles of * @return Whether or not all handles are free or not */ virtual bool canStart(const handles::HandleMap &handles) const; /** * Overriden by a child class. Should return true of a command can run in parallel * @return true if this command can run in parallel */ virtual bool canRunParallel() const; protected: /** * @brief Represents whether a command is currently running */ bool running; /** * @brief execute this command with a set of locked handles and the command message containing the parameters. * @param handles set of locked handles. All handles that are in getRequiredHandles() should be in here * @param message parameters to the command */ virtual void run(handles::HandleMap &handles, const proto::CommandMessage &message) = 0; void waitForInterrupt(); private: const size_t id; /** * @brief Represents whether a command is interrupted or not */ std::atomic<bool> interrupted; std::mutex mutex; /** * @brief Condition variable that can be waited on by infinite commands */ std::condition_variable interrupter; /** * @brief Handle this command requires */ const std::vector<size_t> requiredHandles; }; }