repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
damanivu/ClusterDuck-Protocol
Libraries/RadioLib/src/protocols/TransportLayer/TransportLayer.h
<filename>Libraries/RadioLib/src/protocols/TransportLayer/TransportLayer.h #ifndef _RADIOLIB_TRANSPORT_LAYER_H #define _RADIOLIB_TRANSPORT_LAYER_H #include "../../TypeDef.h" /*! \class TransportLayer \brief Provides common interface for protocols that run on modules with Internet connectivity, such as HTTP or MQTT. Because this class is used mainly as interface, all of its virtual members must be implemented in the module class. */ class TransportLayer { public: // constructor // this class is purely virtual and does not require explicit constructor // basic methods /*! \brief Open transport layer connection. \param host Host to connect to. \param protocol Transport protocol to use. Usually "TCP" or "UDP". \param port to be used for the connection. \param tcpKeepAlive TCP keep alive interval. Defaults to 0. \returns \ref status_codes */ virtual int16_t openTransportConnection(const char* host, const char* protocol, uint16_t port, uint16_t tcpKeepAlive = 0) = 0; /*! \brief Close transport layer connection. \returns \ref status_codes */ virtual int16_t closeTransportConnection() = 0; /*! \brief Send string-based data. \param string String data to be sent. \returns \ref status_codes */ virtual int16_t send(const char* data) = 0; /*! \brief Send arbitrary binary data. \param data Data to be sent. \param len Number of bytes to send. \returns \ref status_codes */ virtual int16_t send(uint8_t* data, uint32_t len) = 0; /*! \brief Receive data. \param data Pointer to array to save the received data. \param len Number of bytes to read. \param timeout Reception timeout in ms. Defaults to 10000. \returns \ref status_codes */ virtual size_t receive(uint8_t* data, size_t len, uint32_t timeout = 10000) = 0; /*! \brief Get number of received bytes. \param timeout Reception timeout in ms. Defaults to 10000. \param minBytes Minimum required number of bytes that must be received. \returns Number of received bytes, or 0 on timeout. */ virtual size_t getNumBytes(uint32_t timeout = 10000, size_t minBytes = 10) = 0; }; #endif
damanivu/ClusterDuck-Protocol
Libraries/RadioLib/src/ISerial.h
#ifndef _RADIOLIB_ISERIAL_H #define _RADIOLIB_ISERIAL_H #include "Module.h" #include <stdio.h> #include "WString.h" #include "Printable.h" /*! \class ISerial \brief Interface class for Arduino Serial. Only calls the appropriate methods for the active UART interface. */ class ISerial { public: ISerial(Module* mod); void begin(long); bool listen(); void end(); bool isListening(); bool stopListening(); bool overflow(); int peek(); size_t write(uint8_t); int read(); int available(); void flush(); size_t print(const __FlashStringHelper *); size_t print(const String &); size_t print(const char[]); size_t print(char); size_t print(unsigned char, int = DEC); size_t print(int, int = DEC); size_t print(unsigned int, int = DEC); size_t print(long, int = DEC); size_t print(unsigned long, int = DEC); size_t print(double, int = 2); size_t print(const Printable&); size_t println(const __FlashStringHelper *); size_t println(const String &s); size_t println(const char[]); size_t println(char); size_t println(unsigned char, int = DEC); size_t println(int, int = DEC); size_t println(unsigned int, int = DEC); size_t println(long, int = DEC); size_t println(unsigned long, int = DEC); size_t println(double, int = 2); size_t println(const Printable&); size_t println(void); #ifndef RADIOLIB_GODMODE protected: #endif Module* _mod; }; #endif
damanivu/ClusterDuck-Protocol
Libraries/RadioLib/src/modules/ESP8266/ESP8266.h
<filename>Libraries/RadioLib/src/modules/ESP8266/ESP8266.h #if !defined(_RADIOLIB_ESP8266_H) && !defined(ESP8266) #define _RADIOLIB_ESP8266_H #include "../../Module.h" #include "../../protocols/TransportLayer/TransportLayer.h" /*! \class ESP8266 \brief Control class for %ESP8266 module. Implements TransportLayer methods. */ class ESP8266: public TransportLayer { public: /*! \brief Default constructor. \param mod Instance of Module that will be used to communicate with the radio. */ ESP8266(Module* module); // basic methods /*! \brief Initialization method. \param speed Baud rate to use for UART interface. \returns \ref status_codes */ int16_t begin(long speed); /*! \brief Resets module using AT command. \returns \ref status_codes */ int16_t reset(); /*! \brief Joins access point. \param ssid Access point SSID. \param password Access point password. */ int16_t join(const char* ssid, const char* password); // transport layer methods (implementations of purely virtual methods in TransportMethod class) int16_t openTransportConnection(const char* host, const char* protocol, uint16_t port, uint16_t tcpKeepAlive = 0); int16_t closeTransportConnection(); int16_t send(const char* data); int16_t send(uint8_t* data, uint32_t len); size_t receive(uint8_t* data, size_t len, uint32_t timeout = 10000); size_t getNumBytes(uint32_t timeout = 10000, size_t minBytes = 10); #ifndef RADIOLIB_GODMODE private: #endif Module* _mod; }; #endif
damanivu/ClusterDuck-Protocol
Libraries/RadioLib/extras/ModuleTemplate.h
<gh_stars>1-10 /* RadioLib Module Template header file Before opening pull request, please make sure that: 1. All files MUST be compiled without errors using default Arduino IDE settings. 2. All files SHOULD be compiled without warnings with compiler warnings set to "All". 3. Example sketches MUST be working correctly and MUST be stable enough to run for prolonged periods of time. 4. Writing style SHOULD be consistent. 5. Comments SHOULD be in place for the most important chunks of code and SHOULD be free of typos. 6. To indent, 2 spaces MUST be used. If at any point you are unsure about the required style, please refer to the rest of the modules. */ #ifndef _RADIOLIB_<module_name>_H #define _RADIOLIB_<module_name>_H /* Header file for each module MUST include Module.h. The header file MAY include additional header files. */ #include "Module.h" /* Only use the following include if the module implements methods for OSI transport layer control. This concerns only modules similar to e.g. ESP8266. In this case, your class MUST implement all virtual methods of TransportLayer class. You also MUST provide crystal oscillator frequency and frequency configuration divisor step resolution to the TransportLayer constructor. */ //#include "../protocols/TransportLayer.h" /* Only use the following include if the module implements methods for OSI physical layer control. This concerns only modules similar to SX127x/RF69/CC1101 etc. In this case, your class MUST implement all virtual methods of PhysicalLayer class. */ //#include "../protocols/PhysicalLayer.h" /* Register map Definition of SPI/I2C register map SHOULD be placed here. The register map SHOULD have two parts: 1 - Address map: only defines register names and addresses. Register names MUST match names in official documentation (datasheets etc.). 2 - Variable map: defines variables inside register. This functions as a bit range map for a specific register. Bit range (MSB and LSB) as well as short description for each variable MUST be provided in a comment. See RF69 and SX127x header files for examples of register maps. */ // <module_name> register map | spaces up to this point #define <module_name>_REG_<register_name> 0x00 // <module_name>_REG_<register_name> MSB LSB DESCRIPTION #define <module_name>_<register_variable> 0b00000000 // 7 0 <description> /* Module class definition The module class MAY inherit from the following classes: 1 - ISerial: Interface for Arduino Serial class, intended as a thin wrapper for modules that directly take Serial input (e.g. HC-05). 2 - TransportLayer: In case the module implements methods for OSI transport layer control (e.g. ESP8266). 3 - PhysicalLayer: In case the module implements methods for OSI physical layer control (e.g. SX127x). */ class <module_name> { public: /* Constructor MUST have only one parameter "Module* mod". The class MAY implement additional overloaded constructors. */ // constructor <module_name>(Module* module); /* The class MUST implement at least one basic method called "begin". The "begin" method MUST initialize the module and return the status as int16_t type. */ // basic methods int16_t begin(); /* The class MAY implement additional methods. All implemented methods SHOULD return the status as int16_t type. */ #ifndef RADIOLIB_GODMODE private: #endif /* The class MUST contain private member "Module* _mod" */ Module* _mod; /* The class MAY contain additional private variables and/or methods. Private member variables MUST have a name prefixed with "_" (underscore, ASCII 0x5F) Usually, these are variables for saving module configuration, or methods that do not have to be exposed to the end user. */ }; #endif
damanivu/ClusterDuck-Protocol
cdpcfg.h
<filename>cdpcfg.h /* * CDP central compile-time configuration * * it will include optional * - cdpcfg-pre.h at the beginning * - cdpcfg-post.h at the end * * to customize your build, you could ... * - edit this file or * - copy it to cdpcfg-pre.h and edit _that_ or * - create a from-scratch cdpcfg-pre.h that just overrides f.ex. the board defines or * - create a cdpcfg-post.h to undef/define just parts */ // preload optional pre-cfg #ifndef CRPCFG_PRE #define CRPCFG_PRE #if __has_include("cdpcfg-pre.h") #include "cdpcfg-pre.h" #endif #endif // this is the actual main configuration section #ifndef CDPCFG #define CDPCFG /* * HARDWARE SECTION // BOARD PINS * the ARDUINO_* defs are set by the arduino build env */ /* * BOARD "ttgo lora" and "heltec lora" v1 * heltec pcb is white, ttgo pcb has heltec+ttgo markings * left top+middle in this picture * https://github.com/Xinyuan-LilyGO/TTGO-LoRa-Series * pio: board = ttgo-lora32-v1 */ #if defined(ARDUINO_TTGO_LoRa32_V1) #define CDPCFG_PIN_LED1 25 //Lora configurations #define CDPCFG_PIN_LORA_CS 18 #define CDPCFG_PIN_LORA_DIO0 26 #define CDPCFG_PIN_LORA_RST 23 // Oled Display settings #define CDPCFG_PIN_OLED_CLOCK 15 #define CDPCFG_PIN_OLED_DATA 4 #define CDPCFG_PIN_OLED_RESET 16 // actualy missing #define CDPCFG_PIN_LORA_DIO1 -1 /* * BOARD "ttgo lora v2" * top right in this picture * https://github.com/Xinyuan-LilyGO/TTGO-LoRa-Series * pio: board = ttgo-lora32-v2 */ #elif defined(ARDUINO_TTGO_LoRa32_V2) #define CDPCFG_PIN_BAT 35 #define CDPCFG_BAT_MULDIV 200/100 #define CDPCFG_PIN_LED1 25 //Lora configurations #define CDPCFG_PIN_LORA_CS 18 #define CDPCFG_PIN_LORA_DIO0 26 #define CDPCFG_PIN_LORA_RST 14 // Oled Display settings #define CDPCFG_PIN_OLED_CLOCK 22 #define CDPCFG_PIN_OLED_DATA 21 // actualy missing #define CDPCFG_PIN_OLED_RESET -1 #define CDPCFG_PIN_LORA_DIO1 -1 /* * BOARD "heltec wireless stick" * http://www.heltec.cn/project/wireless-stick/ * pio: board = heltec_wireless_stick */ #elif defined(ARDUINO_HELTEC_WIRELESS_STICK) #define CDPCFG_PIN_BAT 37 #define CDPCFG_BAT_MULDIV 320/100 #define CDPCFG_PIN_VEXT 21 #define CDPCFG_PIN_LED1 25 //Lora configurations #define CDPCFG_PIN_LORA_CS 18 #define CDPCFG_PIN_LORA_DIO0 26 #define CDPCFG_PIN_LORA_RST 14 // Oled Display settings #define CDPCFG_OLED_64x32 #define CDPCFG_PIN_OLED_CLOCK 15 #define CDPCFG_PIN_OLED_DATA 4 #define CDPCFG_PIN_OLED_RESET 16 // actualy missing #define CDPCFG_PIN_LORA_DIO1 -1 /* * BOARD "sparkfun lora gateway 1-channel" * https://www.sparkfun.com/products/15006 * pio: board = sparkfun_lora_gateway_1-channel */ #elif defined(SPARKFUN_LGW1C) // this is not an official ARDUINO_* define since this board doesnt have one //Lora configurations #define CDPCFG_PIN_LORA_CS 16 #define CDPCFG_PIN_LORA_DIO0 26 #define CDPCFG_PIN_LORA_DIO1 33 #define CDPCFG_PIN_LORA_DIO2 32 #define CDPCFG_PIN_LORA_RST 5 // Oled Display settings #define CDPCFG_OLED_NONE /* * BOARD "pycom lopy" * https://docs.pycom.io/datasheets/development/lopy/ * pio: board = lopy */ #elif defined(ARDUINO_LoPy) #define CDPCFG_PIN_ANT 16 //Lora configurations #define CDPCFG_PIN_LORA_CS 17 #define CDPCFG_PIN_LORA_DIO0 23 #define CDPCFG_PIN_LORA_RST 18 //special SPI #define CDPCFG_PIN_LORA_SPI_SCK 5 #define CDPCFG_PIN_LORA_SPI_MISO 19 #define CDPCFG_PIN_LORA_SPI_MOSI 27 #define CDPCFG_LORA_CLASS SX1272 // Oled Display settings #define CDPCFG_OLED_NONE // actualy missing #define CDPCFG_PIN_LORA_DIO1 -1 /* * BOARD "pycom lopy4" * https://docs.pycom.io/datasheets/development/lopy4/ * pio: board = lopy4 */ #elif defined(ARDUINO_LoPy4) #define CDPCFG_PIN_ANT 16 //Lora configurations #define CDPCFG_PIN_LORA_CS 18 #define CDPCFG_PIN_LORA_DIO0 23 #define CDPCFG_PIN_LORA_RST -1 //special SPI #define CDPCFG_PIN_LORA_SPI_SCK 5 #define CDPCFG_PIN_LORA_SPI_MISO 19 #define CDPCFG_PIN_LORA_SPI_MOSI 27 #define CDPCFG_LORA_CLASS SX1276 // Oled Display settings #define CDPCFG_OLED_NONE // actualy missing #define CDPCFG_PIN_LORA_DIO1 -1 #else #if !defined(ARDUINO_HELTEC_WIFI_LORA_32_V2) #warning "NO BOARD DEFINED, DEFAULTING TO HELTEC v2" #define CDPCFG_BOARD_DEFAULT #endif /* * BOARD "heltec lora v2" * https://heltec.org/project/wifi-lora-32/ * pio: board = heltec_wifi_lora_32_V2 */ #define CDPCFG_PIN_BAT 37 #define CDPCFG_BAT_MULDIV 320/100 #define CDPCFG_PIN_VEXT 21 #define CDPCFG_PIN_LED1 25 //Lora configurations #define CDPCFG_PIN_LORA_CS 18 #define CDPCFG_PIN_LORA_DIO0 26 #define CDPCFG_PIN_LORA_RST 14 // Oled Display settings #define CDPCFG_PIN_OLED_CLOCK 15 #define CDPCFG_PIN_OLED_DATA 4 #define CDPCFG_PIN_OLED_RESET 16 // actualy missing #define CDPCFG_PIN_LORA_DIO1 -1 #endif // non BOARD-specific config // Username and Password for OTA web page #define CDPCFG_UPDATE_USERNAME "username" #define CDPCFG_UPDATE_PASSWORD "password" // Serial Console Baud Rate #define CDPCFG_SERIAL_BAUD 115200 // Access point IP adress #define CDPCFG_AP_IP1 192 #define CDPCFG_AP_IP2 168 #define CDPCFG_AP_IP3 1 #define CDPCFG_AP_IP4 1 // Asyncwebserver Port #define CDPCFG_WEB_PORT 80 // Lora RF configuration #define CDPCFG_RF_LORA_FREQ 915.0 #define CDPCFG_RF_LORA_BW 125.0 #define CDPCFG_RF_LORA_SF 7 #define CDPCFG_RF_LORA_TXPOW 20 #define CDPCFG_RF_LORA_GAIN 0 // cdp configuration #define CDPCFG_CDP_BUFSIZE 256 #define CDPCFG_UUID_LEN 8 // Timer in milliseconds #define CDPCFG_MILLIS_ALIVE 1800000 #define CDPCFG_MILLIS_REBOOT 43200000 // RGB Led Pins #define CDPCFG_PIN_RGBLED_R 25 #define CDPCFG_PIN_RGBLED_G 4 #define CDPCFG_PIN_RGBLED_B 2 // semiautomatic section for setting defaults // set default modem #ifndef CDPCFG_LORA_CLASS #define CDPCFG_LORA_CLASS SX1276 #endif // set oled class #ifndef CDPCFG_OLED_CLASS #if defined(CDPCFG_OLED_NONE) // do nothing #elif defined(CDPCFG_OLED_64x32) // smaller displays #define CDPCFG_OLED_CLASS U8X8_SSD1306_64X32_NONAME_SW_I2C #else // classic default #define CDPCFG_OLED_CLASS U8X8_SSD1306_128X64_NONAME_SW_I2C #endif #endif #endif // CDPCFG // append optional post-cfg #ifndef CRPCFG_POST #define CRPCFG_POST #if __has_include("cdpcfg-post.h") #include "cdpcfg-post.h" #endif #endif
damanivu/ClusterDuck-Protocol
Libraries/RadioLib/src/modules/SX1231/SX1231.h
#ifndef _RADIOLIB_SX1231_H #define _RADIOLIB_SX1231_H #include "../../TypeDef.h" #include "../../Module.h" #include "../RF69/RF69.h" #define SX1231_CHIP_REVISION_2_A 0x21 #define SX1231_CHIP_REVISION_2_B 0x22 #define SX1231_CHIP_REVISION_2_C 0x23 //SX1231 specific register map #define SX1231_REG_TEST_OOK 0x6E //SX1231_REG_TEST_OOK #define SX1231_OOK_DELTA_THRESHOLD 0x0C /*! \class SX1231 \brief Control class for %SX1231 module. Overrides some methods from RF69 due to different register values. */ class SX1231: public RF69 { public: /*! \brief Default constructor. \param mod Instance of Module that will be used to communicate with the radio. */ SX1231(Module* mod); /*! \brief Initialization method. \param freq Carrier frequency in MHz. Defaults to 434.0 MHz. \param br Bit rate to be used in kbps. Defaults to 48.0 kbps. \param rxBw Receiver bandwidth in kHz. Defaults to 125.0 kHz. \param freqDev Frequency deviation from carrier frequency in kHz Defaults to 50.0 kHz. \param power Output power in dBm. Defaults to 13 dBm. \returns \ref status_codes */ int16_t begin(float freq = 434.0, float br = 48.0, float rxBw = 125.0, float freqDev = 50.0, int8_t power = 13); #ifndef RADIOLIB_GODMODE private: #endif uint8_t _chipRevision; }; #endif
skyfireitdiy/xmake
core/src/xmake/io/socket_sendto.c
/*!A cross-platform build utility based on Lua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2015-2020, TBOOX Open Source Group. * * @author ruki * @file socket_sendto.c * */ /* ////////////////////////////////////////////////////////////////////////////////////// * trace */ #define TB_TRACE_MODULE_NAME "socket_sendto" #define TB_TRACE_MODULE_DEBUG (0) /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "prefix.h" /* ////////////////////////////////////////////////////////////////////////////////////// * implementation */ // io.socket_sendto(sock, data, addr, port) tb_int_t xm_io_socket_sendto(lua_State* lua) { // check tb_assert_and_check_return_val(lua, 0); // check socket if (!xm_lua_ispointer(lua, 1)) { lua_pushinteger(lua, -1); lua_pushliteral(lua, "invalid socket!"); return 2; } // get socket tb_socket_ref_t sock = (tb_socket_ref_t)xm_lua_topointer(lua, 1); tb_check_return_val(sock, 0); // get data tb_size_t size = 0; tb_byte_t const* data = tb_null; if (lua_istable(lua, 2)) { // get data address lua_pushstring(lua, "data"); lua_gettable(lua, 2); data = (tb_byte_t const*)(tb_size_t)(tb_long_t)lua_tonumber(lua, -1); lua_pop(lua, 1); // get data size lua_pushstring(lua, "size"); lua_gettable(lua, 2); size = (tb_size_t)lua_tonumber(lua, -1); lua_pop(lua, 1); } else { size_t datasize = 0; data = (tb_byte_t const*)luaL_checklstring(lua, 2, &datasize); size = (tb_size_t)datasize; } if (!data || !size) { lua_pushinteger(lua, -1); lua_pushfstring(lua, "invalid data(%p) and size(%zu)!", data, size); return 2; } // get address tb_char_t const* addr = lua_tostring(lua, 3); tb_uint16_t port = (tb_uint16_t)luaL_checknumber(lua, 4); if (!addr || !port) { lua_pushinteger(lua, -1); lua_pushliteral(lua, "invalid address!"); return 2; } // get address family tb_size_t family = (tb_size_t)luaL_checknumber(lua, 5); // init ip address tb_ipaddr_t ipaddr; tb_ipaddr_set(&ipaddr, addr, port, (tb_uint8_t)family); // send data tb_long_t real = tb_socket_usend(sock, &ipaddr, data, size); lua_pushinteger(lua, (tb_int_t)real); return 1; }
skyfireitdiy/xmake
core/src/xmake/hash/sha256.c
/*!A cross-platform build utility based on Lua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2015-2020, TBOOX Open Source Group. * * @author ruki * @file sha256.c * */ /* ////////////////////////////////////////////////////////////////////////////////////// * trace */ #define TB_TRACE_MODULE_NAME "sha256" #define TB_TRACE_MODULE_DEBUG (0) /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "prefix.h" /* ////////////////////////////////////////////////////////////////////////////////////// * implementation */ tb_int_t xm_hash_sha256(lua_State* lua) { // check tb_assert_and_check_return_val(lua, 0); // get the filename tb_char_t const* filename = luaL_checkstring(lua, 1); tb_check_return_val(filename, 0); // load data from file tb_bool_t ok = tb_false; tb_stream_ref_t stream = tb_stream_init_from_file(filename, TB_FILE_MODE_RO); if (stream) { // open stream if (tb_stream_open(stream)) { // init sha256 tb_sha_t sha; tb_sha_init(&sha, TB_SHA_MODE_SHA2_256); // read data and update sha256 tb_byte_t data[TB_STREAM_BLOCK_MAXN]; while (!tb_stream_beof(stream)) { // read data tb_long_t real = tb_stream_read(stream, data, sizeof(data)); // ok? if (real > 0) tb_sha_spak(&sha, data, real); // no data? continue it else if (!real) { // wait real = tb_stream_wait(stream, TB_STREAM_WAIT_READ, tb_stream_timeout(stream)); tb_check_break(real > 0); // has read? tb_assert_and_check_break(real & TB_STREAM_WAIT_READ); } // failed or end? else break; } // exit sha256 tb_byte_t buffer[32]; tb_sha_exit(&sha, buffer, sizeof(buffer)); // make sha256 string tb_size_t i = 0; tb_size_t n = sha.digest_len << 2; tb_char_t s[256] = {0}; for (i = 0; i < n; ++i) tb_snprintf(s + (i << 1), 3, "%02x", buffer[i]); // save result lua_pushstring(lua, s); // ok ok = tb_true; } // exit stream tb_stream_exit(stream); } // failed? return nil if (!ok) lua_pushnil(lua); // ok return 1; }
skyfireitdiy/xmake
core/src/xmake/os/getwinsize.c
<filename>core/src/xmake/os/getwinsize.c /*!A cross-platform build utility based on Lua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2015-2020, TBOOX Open Source Group. * * @author TitanSnow * @file getwinsize.c * */ /* ////////////////////////////////////////////////////////////////////////////////////// * trace */ #define TB_TRACE_MODULE_NAME "getwinsize" #define TB_TRACE_MODULE_DEBUG (0) /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "prefix.h" #if defined(TB_CONFIG_OS_WINDOWS) && !defined(TB_COMPILER_LIKE_UNIX) # include <windows.h> #else # include <sys/ioctl.h> # include <errno.h> // for errno # include <unistd.h> // for STDOUT_FILENO #endif /* ////////////////////////////////////////////////////////////////////////////////////// * implementation */ // get console window size tb_int_t xm_os_getwinsize(lua_State* lua) { // check tb_assert_and_check_return_val(lua, 0); // init default window size (we will not consider winsize limit if cannot get it) tb_int_t w = TB_MAXS16, h = TB_MAXS16; // get winsize #if defined(TB_CONFIG_OS_WINDOWS) && !defined(TB_COMPILER_LIKE_UNIX) CONSOLE_SCREEN_BUFFER_INFO csbi; if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) { w = (tb_int_t)csbi.dwSize.X; h = (tb_int_t)csbi.dwSize.Y; } #else struct winsize size; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) { w = (tb_int_t)size.ws_col; h = (tb_int_t)size.ws_row; } #endif /* local winsize = os.getwinsize() * * return * { * width = -1 or .. * , height = -1 or .. * } */ lua_newtable(lua); lua_pushstring(lua, "width"); lua_pushinteger(lua, w); lua_settable(lua, -3); lua_pushstring(lua, "height"); lua_pushinteger(lua, h); lua_settable(lua, -3); // ok return 1; }
skyfireitdiy/xmake
core/src/xmake/io/file_open.c
/*!A cross-platform build utility based on Lua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2015-2020, TBOOX Open Source Group. * * @author OpportunityLiu, ruki * @file file_open.c * */ /* ////////////////////////////////////////////////////////////////////////////////////// * trace */ #define TB_TRACE_MODULE_NAME "file_open" #define TB_TRACE_MODULE_DEBUG (0) /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "prefix.h" /* ////////////////////////////////////////////////////////////////////////////////////// * macros */ // num of bytes read to guess encoding #define CHECK_SIZE (1024) // is utf-8 tail character #define IS_UTF8_TAIL(c) (c >= 0x80 && c < 0xc0) /* ////////////////////////////////////////////////////////////////////////////////////// * private implementation */ static tb_size_t xm_io_file_detect_charset(tb_byte_t const** data_ptr, tb_long_t size) { // check tb_assert(data_ptr && *data_ptr); tb_byte_t const* data = *data_ptr; tb_size_t charset = XM_IO_FILE_ENCODING_BINARY; do { // is luajit bitcode? open as binary if (size >= 3 && data[0] == 27 && data[1] == 'L' && data[2] == 'J') break; // utf-8 with bom if (size >= 3 && data[0] == 239 && data[1] == 187 && data[2] == 191) { charset = TB_CHARSET_TYPE_UTF8; data += 3; // skip bom break; } if (size >= 2) { // utf16be if (data[0] == 254 && data[1] == 255) { charset = TB_CHARSET_TYPE_UTF16 | TB_CHARSET_TYPE_BE; data += 2; // skip bom break; } // utf16le else if (data[0] == 255 && data[1] == 254) { charset = TB_CHARSET_TYPE_UTF16 | TB_CHARSET_TYPE_LE; data += 2; // skip bom break; } } tb_sint16_t utf16be_conf = 0; tb_sint16_t utf16le_conf = 0; tb_sint16_t utf8_conf = 0; tb_sint16_t ascii_conf = 0; tb_sint16_t zero_count = 0; for (tb_long_t i = 0; i < (size - 4) && i < CHECK_SIZE; i++) { if (data[i] == 0) zero_count++; if (data[i] < 0x80) ascii_conf++; else ascii_conf = TB_MINS16; if (i % 2 == 0) { if (data[i] == 0) utf16be_conf++; if (data[i + 1] == 0) utf16le_conf++; } if (IS_UTF8_TAIL(data[i])) ; else if (data[i] < 0x80) utf8_conf++; else if (data[i] >= 0xc0 && data[i] < 0xe0 && IS_UTF8_TAIL(data[i + 1])) utf8_conf++; else if (data[i] >= 0xe0 && data[i] < 0xf0 && IS_UTF8_TAIL(data[i + 1]) && IS_UTF8_TAIL(data[i + 2])) utf8_conf++; else if (data[i] >= 0xf0 && data[i] < 0xf8 && IS_UTF8_TAIL(data[i + 1]) && IS_UTF8_TAIL(data[i + 2]) && IS_UTF8_TAIL(data[i + 3])) utf8_conf++; else utf8_conf = TB_MINS16; } if (ascii_conf > 0 && zero_count <= 1) { charset = TB_CHARSET_TYPE_UTF8; break; } if (utf8_conf > 0 && zero_count <= 1) { charset = TB_CHARSET_TYPE_UTF8; break; } if (utf16be_conf > 0 && utf16be_conf > utf16le_conf) { charset = TB_CHARSET_TYPE_UTF16 | TB_CHARSET_TYPE_BE; break; } if (utf16le_conf > 0 && utf16le_conf >= utf16be_conf) { charset = TB_CHARSET_TYPE_UTF16 | TB_CHARSET_TYPE_LE; break; } if (utf8_conf > 0) { charset = TB_CHARSET_TYPE_UTF8; break; } #ifdef TB_CONFIG_OS_WINDOWS charset = TB_CHARSET_TYPE_ANSI; #endif } while (0); *data_ptr = data; return charset; } static tb_size_t xm_io_file_detect_encoding(tb_stream_ref_t stream, tb_long_t* pbomoff) { // check tb_assert_and_check_return_val(stream && pbomoff, XM_IO_FILE_ENCODING_BINARY); // detect encoding tb_byte_t* data = tb_null; tb_size_t encoding = XM_IO_FILE_ENCODING_BINARY; tb_long_t size = tb_stream_peek(stream, &data, CHECK_SIZE); if (size > 0) { tb_byte_t const* p = data; encoding = xm_io_file_detect_charset(&p, size); *pbomoff = p - data; } return encoding; } /* ////////////////////////////////////////////////////////////////////////////////////// * implementation */ // io.file_open(path, modestr) tb_int_t xm_io_file_open(lua_State* lua) { // check tb_assert_and_check_return_val(lua, 0); // get file path and mode tb_char_t const* path = luaL_checkstring(lua, 1); tb_char_t const* modestr = luaL_optstring(lua, 2, "r"); tb_assert_and_check_return_val(path && modestr, 0); // get file mode value tb_size_t mode; switch (modestr[0]) { case 'w': mode = TB_FILE_MODE_RW | TB_FILE_MODE_CREAT | TB_FILE_MODE_TRUNC; break; case 'a': mode = TB_FILE_MODE_RW | TB_FILE_MODE_APPEND | TB_FILE_MODE_CREAT; break; case 'r': default: mode = TB_FILE_MODE_RO; break; } // get file encoding tb_long_t bomoff = 0; tb_stream_ref_t stream = tb_null; tb_bool_t update = !!tb_strchr(modestr, '+'); tb_size_t encoding = XM_IO_FILE_ENCODING_UNKNOWN; if (modestr[1] == 'b' || (update && modestr[2] == 'b')) encoding = XM_IO_FILE_ENCODING_BINARY; else if (tb_strstr(modestr, "utf8") || tb_strstr(modestr, "utf-8")) encoding = TB_CHARSET_TYPE_UTF8; else if (tb_strstr(modestr, "utf16le") || tb_strstr(modestr, "utf-16le")) encoding = TB_CHARSET_TYPE_UTF16 | TB_CHARSET_TYPE_LE; else if (tb_strstr(modestr, "utf16be") || tb_strstr(modestr, "utf-16be")) encoding = TB_CHARSET_TYPE_UTF16 | TB_CHARSET_TYPE_BE; else if (tb_strstr(modestr, "utf16") || tb_strstr(modestr, "utf-16")) encoding = TB_CHARSET_TYPE_UTF16 | TB_CHARSET_TYPE_NE; else if (modestr[0] == 'w' || modestr[0] == 'a') // set to utf-8 if not specified for the writing mode encoding = TB_CHARSET_TYPE_UTF8; else if (modestr[0] == 'r') // detect encoding if not specified for the reading mode { stream = tb_stream_init_from_file(path, mode); if (stream && tb_stream_open(stream)) encoding = xm_io_file_detect_encoding(stream, &bomoff); else { if (stream) tb_stream_exit(stream); xm_io_return_error(lua, "file not found!"); } } else xm_io_return_error(lua, "invalid open mode!"); tb_assert_and_check_return_val(encoding != XM_IO_FILE_ENCODING_UNKNOWN, 0); // open file tb_bool_t open_ok = tb_false; tb_stream_ref_t file_ref = tb_null; tb_stream_ref_t fstream = tb_null; do { // init stream from file stream = stream? stream : tb_stream_init_from_file(path, mode); tb_assert_and_check_break(stream); // is transcode? tb_bool_t is_transcode = encoding != TB_CHARSET_TYPE_UTF8 && encoding != XM_IO_FILE_ENCODING_BINARY; if (is_transcode) { if (modestr[0] == 'r') fstream = tb_stream_init_filter_from_charset(stream, encoding, TB_CHARSET_TYPE_UTF8); else fstream = tb_stream_init_filter_from_charset(stream, TB_CHARSET_TYPE_UTF8, encoding); tb_assert_and_check_break(fstream); // use fstream as file file_ref = fstream; } else file_ref = stream; // open file stream if (!tb_stream_open(file_ref)) break; // skip bom characters if exists if (bomoff > 0 && !tb_stream_seek(stream, bomoff)) break; // ok open_ok = tb_true; } while (0); // open failed? if (!open_ok) { // exit stream if (stream) tb_stream_exit(stream); stream = tb_null; // exit charset stream filter if (fstream) tb_stream_exit(fstream); fstream = tb_null; // return errors xm_io_return_error(lua, "failed to open file!"); } // make file xm_io_file_t* file = (xm_io_file_t*)lua_newuserdata(lua, sizeof(xm_io_file_t)); tb_assert_and_check_return_val(file, 0); // init file file->file_ref = file_ref; file->stream = stream; file->fstream = fstream; file->mode = mode; file->type = XM_IO_FILE_TYPE_FILE; file->encoding = encoding; // init the read/write line cache buffer tb_buffer_init(&file->rcache); tb_buffer_init(&file->wcache); return 1; }
skyfireitdiy/xmake
core/src/xmake/os/rmdir.c
<filename>core/src/xmake/os/rmdir.c /*!A cross-platform build utility based on Lua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2015-2020, TBOOX Open Source Group. * * @author ruki * @file rmdir.c * */ /* ////////////////////////////////////////////////////////////////////////////////////// * trace */ #define TB_TRACE_MODULE_NAME "rmdir" #define TB_TRACE_MODULE_DEBUG (0) /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "prefix.h" /* ////////////////////////////////////////////////////////////////////////////////////// * private implementation */ static tb_bool_t xm_os_rmdir_empty(tb_char_t const* path, tb_file_info_t const* info, tb_cpointer_t priv) { // check tb_bool_t* is_emptydir = (tb_bool_t*)priv; tb_assert_and_check_return_val(path && info && is_emptydir, tb_false); // is emptydir? if (info->type == TB_FILE_TYPE_DIRECTORY || info->type == TB_FILE_TYPE_FILE) { // not emptydir *is_emptydir = tb_false; // break return tb_false; } // continue return tb_true; } static tb_bool_t xm_os_rmdir_remove(tb_char_t const* path, tb_file_info_t const* info, tb_cpointer_t priv) { // check tb_assert_and_check_return_val(path, tb_false); // is directory? if (info->type == TB_FILE_TYPE_DIRECTORY) { // is emptydir? tb_bool_t is_emptydir = tb_true; tb_directory_walk(path, tb_false, tb_true, xm_os_rmdir_empty, &is_emptydir); // trace tb_trace_d("path: %s, emptydir: %u", path, is_emptydir); // remove empty directory if (is_emptydir) tb_directory_remove(path); } // continue return tb_true; } /* ////////////////////////////////////////////////////////////////////////////////////// * implementation */ tb_int_t xm_os_rmdir(lua_State* lua) { // check tb_assert_and_check_return_val(lua, 0); // get the path tb_char_t const* path = luaL_checkstring(lua, 1); tb_check_return_val(path, 0); // only remove empty directory? tb_bool_t rmempty = lua_toboolean(lua, 2); if (rmempty) { // remove all empty directories tb_directory_walk(path, tb_true, tb_false, xm_os_rmdir_remove, tb_null); // remove empty root directory tb_bool_t is_emptydir = tb_true; tb_directory_walk(path, tb_false, tb_true, xm_os_rmdir_empty, &is_emptydir); if (is_emptydir) tb_directory_remove(path); // trace tb_trace_d("path: %s, emptydir: %u", path, is_emptydir); // ok? lua_pushboolean(lua, !tb_file_info(path, tb_null)); } else { // done os.rmdir(path) lua_pushboolean(lua, tb_directory_remove(path)); } // ok return 1; }
skyfireitdiy/xmake
core/src/xmake/io/pipe_open.c
<filename>core/src/xmake/io/pipe_open.c /*!A cross-platform build utility based on Lua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2015-2020, TBOOX Open Source Group. * * @author ruki * @file pipe_open.c * */ /* ////////////////////////////////////////////////////////////////////////////////////// * trace */ #define TB_TRACE_MODULE_NAME "pipe_open" #define TB_TRACE_MODULE_DEBUG (0) /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "prefix.h" /* ////////////////////////////////////////////////////////////////////////////////////// * implementation */ /* * io.pipe_open(name, mode, buffsize) */ tb_int_t xm_io_pipe_open(lua_State* lua) { // check tb_assert_and_check_return_val(lua, 0); // get pipe name and mode tb_char_t const* name = luaL_checkstring(lua, 1); tb_char_t const* modestr = luaL_optstring(lua, 2, "r"); tb_assert_and_check_return_val(name && modestr, 0); // get file mode value tb_size_t mode = TB_FILE_MODE_RO; if (modestr[0] == 'w') mode = TB_FILE_MODE_WO; // get buffer size tb_size_t buffsize = (tb_size_t)luaL_checknumber(lua, 3); // open pipe file tb_pipe_file_ref_t pipefile = tb_pipe_file_init(name, mode, buffsize); if (pipefile) xm_lua_pushpointer(lua, (tb_pointer_t)pipefile); else lua_pushnil(lua); return 1; }
skyfireitdiy/xmake
core/src/xmake/io/prefix.h
<reponame>skyfireitdiy/xmake /*!A cross-platform build utility based on Lua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2015-2020, TBOOX Open Source Group. * * @author ruki * @file prefix.h * */ #ifndef XM_IO_PREFIX_H #define XM_IO_PREFIX_H /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "../prefix.h" /* ////////////////////////////////////////////////////////////////////////////////////// * macros */ #define xm_io_file_is_file(file) ((file)->type == XM_IO_FILE_TYPE_FILE) #define xm_io_file_is_std(file) ((file)->type != XM_IO_FILE_TYPE_FILE) #define xm_io_file_is_tty(file) (!!((file)->type & XM_IO_FILE_FLAG_TTY)) // return io error #define xm_io_return_error(lua, error) \ do \ { \ lua_pushnil(lua); \ lua_pushliteral(lua, error); \ return 2; \ } while (0) /* ////////////////////////////////////////////////////////////////////////////////////// * types */ typedef enum __xm_io_file_type_e { XM_IO_FILE_TYPE_FILE = 0 //!< disk file , XM_IO_FILE_TYPE_STDIN = 1 , XM_IO_FILE_TYPE_STDOUT = 2 , XM_IO_FILE_TYPE_STDERR = 3 , XM_IO_FILE_FLAG_TTY = 0x10 //!< mark tty std stream } xm_io_file_type_e; /* use negetive numbers for this enum, its a extension for tb_charset_type_e * before adding new values, make sure they have not conflicts with values in tb_charset_type_e */ typedef enum __xm_io_file_encoding_e { XM_IO_FILE_ENCODING_UNKNOWN = -1 , XM_IO_FILE_ENCODING_BINARY = -2 } xm_io_file_encoding_e; // the file type typedef struct __xm_io_file_t { union { /* the normal file for XM_IO_FILE_TYPE_FILE * * direct: file_ref -> stream -> file * transcode: file_ref -> fstream -> stream -> file */ tb_stream_ref_t file_ref; // the standard io file tb_stdfile_ref_t std_ref; }; tb_stream_ref_t stream; // the file stream for XM_IO_FILE_TYPE_FILE tb_stream_ref_t fstream; // the file charset stream filter tb_size_t mode; // tb_file_mode_t tb_size_t type; // xm_io_file_type_e tb_size_t encoding; // value of xm_io_file_encoding_e or tb_charset_type_e tb_buffer_t rcache; // the read line cache buffer tb_buffer_t wcache; // the write line cache buffer } xm_io_file_t; #endif
skyfireitdiy/xmake
core/src/xmake/semver/select.c
<reponame>skyfireitdiy/xmake /*!A cross-platform build utility based on Lua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2015-2020, TBOOX Open Source Group. * * @author uael * @file select.c * */ /* ////////////////////////////////////////////////////////////////////////////////////// * trace */ #define TB_TRACE_MODULE_NAME "select" #define TB_TRACE_MODULE_DEBUG (0) /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "prefix.h" /* ////////////////////////////////////////////////////////////////////////////////////// * private implementation */ static tb_bool_t xm_semver_select_from_versions_tags(lua_State* lua, tb_int_t fromidx, semver_t* semver, semver_range_t const* range, semvers_t* matches) { // clear matches semvers_pclear(matches); // select all matches lua_Integer i = 0; luaL_checktype(lua, fromidx, LUA_TTABLE); for (i = lua_objlen(lua, fromidx); i > 0; --i) { lua_pushinteger(lua, i); lua_gettable(lua, fromidx); tb_char_t const* source_str = luaL_checkstring(lua, -1); if (source_str && semver_tryn(semver, source_str, tb_strlen(source_str)) == 0) { if (semver_range_pmatch(semver, range)) semvers_ppush(matches, *semver); else semver_dtor(semver); } } // no matches? tb_check_return_val(matches->length, tb_false); // sort matches semvers_psort(matches); // get the newest version semver_t top = semvers_ppop(matches); lua_createtable(lua, 0, 2); // return results lua_pushstring(lua, top.raw); lua_setfield(lua, -2, "version"); lua_pushstring(lua, fromidx == 2? "versions" : "tags"); lua_setfield(lua, -2, "source"); // exit the popped semver semver_dtor(&top); // ok return tb_true; } static tb_bool_t xm_semver_select_from_branches(lua_State* lua, tb_int_t fromidx, tb_char_t const* range_str, tb_size_t range_len) { lua_Integer i = 0; luaL_checktype(lua, fromidx, LUA_TTABLE); for (i = lua_objlen(lua, fromidx); i > 0; --i) { lua_pushinteger(lua, i); lua_gettable(lua, fromidx); tb_char_t const* source_str = luaL_checkstring(lua, -1); tb_check_continue(source_str); tb_size_t source_len = tb_strlen(source_str); if (source_len == range_len && tb_memcmp(source_str, range_str, source_len) == 0) { lua_createtable(lua, 0, 2); lua_pushlstring(lua, source_str, source_len); lua_setfield(lua, -2, "version"); lua_pushstring(lua, "branches"); lua_setfield(lua, -2, "source"); // ok return tb_true; } } // no matches return tb_false; } static tb_bool_t xm_semver_select_latest_from_versions_tags(lua_State* lua, tb_int_t fromidx, semver_t* semver, semvers_t* matches) { // clear matches semvers_pclear(matches); // push all versions to matches lua_Integer i = 0; luaL_checktype(lua, fromidx, LUA_TTABLE); for (i = lua_objlen(lua, fromidx); i > 0; --i) { lua_pushinteger(lua, i); lua_gettable(lua, fromidx); tb_char_t const* source_str = luaL_checkstring(lua, -1); if (source_str && semver_tryn(semver, source_str, tb_strlen(source_str)) == 0) semvers_ppush(matches, *semver); } // no matches? tb_check_return_val(matches->length, tb_false); // sort matches semvers_psort(matches); // get the newest match semver_t top = semvers_ppop(matches); lua_createtable(lua, 0, 2); // return results lua_pushstring(lua, top.raw); lua_setfield(lua, -2, "version"); lua_pushstring(lua, fromidx == 2? "versions" : "tags"); lua_setfield(lua, -2, "source"); // exit the popped semver semver_dtor(&top); // ok return tb_true; } /* ////////////////////////////////////////////////////////////////////////////////////// * implementation */ /* select version * * local versioninfo, errors = semver.select(">=1.5.0 <1.6", {"1.5.0", "1.5.1"}, {"v1.5.0", ..}, {"latest", "dev"}) */ tb_int_t xm_semver_select(lua_State* lua) { // check tb_assert_and_check_return_val(lua, 0); // select version tb_bool_t ok = tb_false; tb_bool_t is_range = tb_false; tb_char_t const* range_str = tb_null; semver_t semver = {0}; semvers_t matches = {0}; semver_range_t range = {0}; do { // get the version range string range_str = luaL_checkstring(lua, 1); tb_check_break(range_str); // get the range string length tb_size_t range_len = tb_strlen(range_str); // parse the version range string is_range = semver_rangen(&range, range_str, range_len) == 0; if (is_range) { // attempt to select version from the versions list first if (xm_semver_select_from_versions_tags(lua, 2, &semver, &range, &matches)) { ok = tb_true; break; } // attempt to select version from the tags list if (xm_semver_select_from_versions_tags(lua, 3, &semver, &range, &matches)) { ok = tb_true; break; } } // attempt to select version from the branches if (xm_semver_select_from_branches(lua, 4, range_str, range_len)) { ok = tb_true; break; } // select the latest version from the tags and versions if be latest if (!tb_strcmp(range_str, "latest")) { // attempt to select latest version from the versions list if (xm_semver_select_latest_from_versions_tags(lua, 2, &semver, &matches)) { ok = tb_true; break; } // attempt to select latest version from the tags list if (xm_semver_select_latest_from_versions_tags(lua, 3, &semver, &matches)) { ok = tb_true; break; } } } while (0); // exit matches semvers_dtor(matches); // exit range semver_range_dtor(&range); // failed? if (!ok) { if (!is_range) { lua_pushnil(lua); lua_pushfstring(lua, "unable to parse semver range '%s'", range_str); } lua_pushnil(lua); lua_pushfstring(lua, "unable to select version for range '%s'", range_str); return 2; } // ok return 1; }
skyfireitdiy/xmake
core/src/xmake/semver/prefix.h
<reponame>skyfireitdiy/xmake /*!A cross-platform build utility based on Lua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (C) 2015-2020, TBOOX Open Source Group. * * @author uael * @file prefix.h * */ #ifndef XM_SEMVER_PREFIX_H #define XM_SEMVER_PREFIX_H /* ////////////////////////////////////////////////////////////////////////////////////// * includes */ #include "../prefix.h" #include "semver.h" /* ////////////////////////////////////////////////////////////////////////////////////// * extern */ __tb_extern_c_enter__ /* ////////////////////////////////////////////////////////////////////////////////////// * interfaces */ /* push struct semver * * @param lua the lua context * @param semver the semver struct * */ tb_void_t lua_pushsemver(lua_State *lua, semver_t const* semver); /* ////////////////////////////////////////////////////////////////////////////////////// * leave */ __tb_extern_c_leave__ #endif
koenkooi/meta-minnow
recipes-multimedia/gstreamer/gstreamer-vaapi/gstvideoencoder.h
/* GStreamer * Copyright (C) 2008 <NAME> <<EMAIL>> * Copyright (C) 2011 <NAME> <<EMAIL>>. * Copyright (C) 2011 Nokia Corporation. All rights reserved. * Contact: <NAME> <<EMAIL>> * Copyright (C) 2012 Collabora Ltd. * Author : <NAME> <<EMAIL>> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef _GST_VIDEO_ENCODER_H_ #define _GST_VIDEO_ENCODER_H_ #include <gst/video/gstvideoutils.h> G_BEGIN_DECLS #define GST_TYPE_VIDEO_ENCODER \ (gst_video_encoder_get_type()) #define GST_VIDEO_ENCODER(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_VIDEO_ENCODER,GstVideoEncoder)) #define GST_VIDEO_ENCODER_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_VIDEO_ENCODER,GstVideoEncoderClass)) #define GST_VIDEO_ENCODER_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS((obj),GST_TYPE_VIDEO_ENCODER,GstVideoEncoderClass)) #define GST_IS_VIDEO_ENCODER(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_VIDEO_ENCODER)) #define GST_IS_VIDEO_ENCODER_CLASS(obj) \ (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_VIDEO_ENCODER)) #define GST_VIDEO_ENCODER_CAST(enc) ((GstVideoEncoder*)enc) /** * GST_VIDEO_ENCODER_SINK_NAME: * * The name of the templates for the sink pad. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_SINK_NAME "sink" /** * GST_VIDEO_ENCODER_SRC_NAME: * * The name of the templates for the source pad. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_SRC_NAME "src" /** * GST_VIDEO_ENCODER_FLOW_DROPPED: * * Returned when the event/buffer should be dropped. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_FLOW_DROPPED GST_FLOW_CUSTOM_SUCCESS_1 /** * GST_VIDEO_ENCODER_SRC_PAD: * @obj: a #GstVideoEncoder * * Gives the pointer to the source #GstPad object of the element. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_SRC_PAD(obj) (((GstVideoEncoder *) (obj))->srcpad) /** * GST_VIDEO_ENCODER_SINK_PAD: * @obj: a #GstVideoEncoder * * Gives the pointer to the sink #GstPad object of the element. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_SINK_PAD(obj) (((GstVideoEncoder *) (obj))->sinkpad) /** * GST_VIDEO_ENCODER_FLOW_NEED_DATA: * * Returned while parsing to indicate more data is needed. * * Since: 0.10.37 **/ #define GST_VIDEO_ENCODER_FLOW_NEED_DATA GST_FLOW_CUSTOM_SUCCESS /** * GST_VIDEO_ENCODER_FLOW_DROPPED: * * Returned when the event/buffer should be dropped. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_FLOW_DROPPED GST_FLOW_CUSTOM_SUCCESS_1 /** * GST_VIDEO_ENCODER_INPUT_SEGMENT: * @obj: base parse instance * * Gives the segment of the element. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_INPUT_SEGMENT(obj) (GST_VIDEO_ENCODER_CAST (obj)->input_segment) /** * GST_VIDEO_ENCODER_OUTPUT_SEGMENT: * @obj: base parse instance * * Gives the segment of the element. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_OUTPUT_SEGMENT(obj) (GST_VIDEO_ENCODER_CAST (obj)->output_segment) /** * GST_VIDEO_ENCODER_STREAM_LOCK: * @encoder: video encoder instance * * Obtain a lock to protect the encoder function from concurrent access. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_STREAM_LOCK(encoder) g_static_rec_mutex_lock (&GST_VIDEO_ENCODER (encoder)->stream_lock) /** * GST_VIDEO_ENCODER_STREAM_UNLOCK: * @encoder: video encoder instance * * Release the lock that protects the encoder function from concurrent access. * * Since: 0.10.37 */ #define GST_VIDEO_ENCODER_STREAM_UNLOCK(encoder) g_static_rec_mutex_unlock (&GST_VIDEO_ENCODER (encoder)->stream_lock) typedef struct _GstVideoEncoder GstVideoEncoder; typedef struct _GstVideoEncoderPrivate GstVideoEncoderPrivate; typedef struct _GstVideoEncoderClass GstVideoEncoderClass; /** * GstVideoEncoder: * * The opaque #GstVideoEncoder data structure. * * Since: 0.10.37 */ struct _GstVideoEncoder { /*< private >*/ GstElement element; /*< protected >*/ GstPad *sinkpad; GstPad *srcpad; /* protects all data processing, i.e. is locked * in the chain function, finish_frame and when * processing serialized events */ GStaticRecMutex stream_lock; /* MT-protected (with STREAM_LOCK) */ GstSegment input_segment; GstSegment output_segment; GstVideoEncoderPrivate *priv; /*< private >*/ gpointer _gst_reserved[GST_PADDING_LARGE]; }; /** * GstVideoEncoderClass: * @open: Optional. * Called when the element changes to GST_STATE_READY. * Allows opening external resources. Since: 0.10.37. * @close: Optional. * Called when the element changes to GST_STATE_NULL. * Allows closing external resources. Since: 0.10.37. * @start: Optional. * Called when the element starts processing. * Allows opening external resources. * @stop: Optional. * Called when the element stops processing. * Allows closing external resources. * @set_format: Optional. * Notifies subclass of incoming data format. * GstVideoCodecState fields have already been * set according to provided caps. * @handle_frame: Provides input frame to subclass. * @reset: Optional. * Allows subclass (encoder) to perform post-seek semantics reset. * @finish: Optional. * Called to request subclass to dispatch any pending remaining * data (e.g. at EOS). * @pre_push: Optional. * Allows subclass to push frame downstream in whatever * shape or form it deems appropriate. If not provided, * provided encoded frame data is simply pushed downstream. * @getcaps: Optional. * Allows for a custom sink getcaps implementation (e.g. * for multichannel input specification). If not implemented, * default returns gst_video_encoder_proxy_getcaps * applied to sink template caps. * @sink_event: Optional. * Event handler on the sink pad. This function should return * TRUE if the event was handled and should be discarded * (i.e. not unref'ed). * @src_event: Optional. * Event handler on the source pad. This function should return * TRUE if the event was handled and should be discarded * (i.e. not unref'ed). * * Subclasses can override any of the available virtual methods or not, as * needed. At minimum @handle_frame needs to be overridden, and @set_format * and @get_caps are likely needed as well. * * Since: 0.10.37 */ struct _GstVideoEncoderClass { /*< private >*/ GstElementClass element_class; /*< public >*/ /* virtual methods for subclasses */ gboolean (*open) (GstVideoEncoder *encoder); gboolean (*close) (GstVideoEncoder *encoder); gboolean (*start) (GstVideoEncoder *encoder); gboolean (*stop) (GstVideoEncoder *encoder); gboolean (*set_format) (GstVideoEncoder *encoder, GstVideoCodecState *state); GstFlowReturn (*handle_frame) (GstVideoEncoder *encoder, GstVideoCodecFrame *frame); gboolean (*reset) (GstVideoEncoder *encoder, gboolean hard); GstFlowReturn (*finish) (GstVideoEncoder *encoder); GstFlowReturn (*pre_push) (GstVideoEncoder *encoder, GstVideoCodecFrame *frame); GstCaps * (*getcaps) (GstVideoEncoder *enc); gboolean (*sink_event) (GstVideoEncoder *encoder, GstEvent *event); gboolean (*src_event) (GstVideoEncoder *encoder, GstEvent *event); /*< private >*/ gpointer _gst_reserved[GST_PADDING_LARGE]; }; GType gst_video_encoder_get_type (void); GstVideoCodecState* gst_video_encoder_get_output_state (GstVideoEncoder *encoder); GstVideoCodecState* gst_video_encoder_set_output_state (GstVideoEncoder * encoder, GstCaps * caps, GstVideoCodecState * reference); GstVideoCodecFrame* gst_video_encoder_get_frame (GstVideoEncoder *encoder, int frame_number); GstVideoCodecFrame* gst_video_encoder_get_oldest_frame (GstVideoEncoder *encoder); GList * gst_video_encoder_get_frames (GstVideoEncoder *encoder); GstFlowReturn gst_video_encoder_finish_frame (GstVideoEncoder *encoder, GstVideoCodecFrame *frame); GstCaps * gst_video_encoder_proxy_getcaps (GstVideoEncoder * enc, GstCaps * caps); void gst_video_encoder_set_discont (GstVideoEncoder *encoder); gboolean gst_video_encoder_get_discont (GstVideoEncoder *encoder); void gst_video_encoder_set_latency (GstVideoEncoder *encoder, GstClockTime min_latency, GstClockTime max_latency); void gst_video_encoder_get_latency (GstVideoEncoder *encoder, GstClockTime *min_latency, GstClockTime *max_latency); void gst_video_encoder_set_headers (GstVideoEncoder *encoder, GList *headers); G_END_DECLS #endif
paradoxpj/C-Guide-for-Beginners
BasicImplementations/Prime_Numbers.c
//Program to print all the prime numbers less than a given element #include<stdio.h> main() { int i,n,p,sum; printf("Enter a number!\n"); scanf("%d",&p); for(n=2;n<=p;n++) { sum=0; for(i=2;i<=n/2;i++) { if(n%i==0) sum=1; } if(sum==0) printf("%d\t",n); } }
paradoxpj/C-Guide-for-Beginners
BasicImplementations/Sum_of_array.c
//Program to sum an array #include<stdio.h> main() { int n; printf("Enter the strength of an arrya: "); scanf("%d",&n); int arr[n],i,sum=0; printf("Enter the elements of the array\n"); for(i=0;i<n;i++) scanf("%d",&arr[i]); for(i=0;i<n;i++) sum=sum+arr[i]; printf("sum is %d",sum); }
paradoxpj/C-Guide-for-Beginners
BasicImplementations/Temperature_Converter.c
<filename>BasicImplementations/Temperature_Converter.c #include<stdio.h> main() { float f,c; printf("Enter temperature in degree farheniet\n"); scanf("%f",&f); c=(f-32)/1.8; printf("Temperature in degree celcius is %f",c); }
alex-schneider/mpz
src/mpz_mutex.h
<filename>src/mpz_mutex.h /** * Copyright (c) <NAME> */ #ifndef _MEMPOOLZ_MUTEX_H_INCLUDE #define _MEMPOOLZ_MUTEX_H_INCLUDE /* ==================================================================================================== */ #include "mpz_core.h" /* ==================================================================================================== */ #ifdef MPZ_ENABLE_THREAD_SAFETY typedef pthread_mutex_t mpz_mutex_t; #endif /* MPZ_ENABLE_THREAD_SAFETY */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #define mpz_mutex_init(m, a) ( \ (mpz_int_t)pthread_mutex_init((m), (a)) \ ) #define mpz_mutex_lock(m) ( \ (mpz_int_t)pthread_mutex_lock((m)) \ ) #define mpz_mutex_unlock(m) ( \ (mpz_int_t)pthread_mutex_unlock((m)) \ ) #define mpz_mutex_destroy(m) ( \ (mpz_int_t)pthread_mutex_destroy((m)) \ ) /* ==================================================================================================== */ #endif /* _SERVERZ_MUTEX_H_INCLUDE */
alex-schneider/mpz
src/mpz_alloc.c
/** * Copyright (c) <NAME> */ #include "mpz_core.h" /* ==================================================================================================== */ /* PRIVATE STUFF: DECLARATIONS */ #define mpz_memalign(a, s) ({ mpz_void_t *p; (0 != posix_memalign(&p, (a), (s)) ? NULL : p); }) #define mpz_memzero(p, n) ({ memset((mpz_void_t *)(p), 0, (n)); }) #define mpz_align(s, a) (((s) + ((a) - 1)) & ~((a) - 1)) #define MPZ_ALLOC_ALIGNMENT (2 * sizeof(mpz_void_t *)) #ifdef MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS #define MPZ_SLOT_OVERHEAD (sizeof(mpz_uint32_t) * 2) #else #define MPZ_SLOT_OVERHEAD (sizeof(mpz_uint32_t) * 1) #endif /* MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS */ #define MPZ_SLOT_SIZE (sizeof(mpz_slot_t *) + MPZ_SLOT_OVERHEAD) #define MPZ_SLAB_SIZE (mpz_align(sizeof(mpz_slab_t), MPZ_ALLOC_ALIGNMENT)) #define MPZ_POOL_SIZE (mpz_align(sizeof(mpz_pool_t), MPZ_ALLOC_ALIGNMENT)) #define MPZ_SLAB_TO_SLOT(s) ((mpz_slot_t *)(((mpz_uchar_t *)(s)) + MPZ_SLAB_SIZE)) #define MPZ_SLOT_TO_SLAB(s) ((mpz_slab_t *)(((mpz_uchar_t *)(s)) - MPZ_SLAB_SIZE)) #define MPZ_SLOT_TO_DATA(s) ((mpz_void_t *)(((mpz_uchar_t *)(s)) + sizeof(mpz_uint32_t))) #define MPZ_DATA_TO_SLOT(d) ((mpz_slot_t *)(((mpz_uchar_t *)(d)) - sizeof(mpz_uint32_t))) #define MPZ_SLOT_FLAG_USED ((mpz_cuint32_t)(1 << 30)) #define MPZ_SLOT_FLAG_HUGE ((mpz_cuint32_t)(1 << 31)) #define MPZ_POOL_MIN_ALLOC (MPZ_SLOTS_ALIGNMENT) #define MPZ_POOL_MAX_ALLOC ((mpz_cuint32_t)((1 << 29) - 1)) #define MPZ_SLOT_READ_HEAD(s) ( \ (mpz_uint32_t *)(s) \ ) #define MPZ_SLOT_READ_SIZE(s) ( \ (mpz_uint32_t)((*MPZ_SLOT_READ_HEAD(s) << 2) >> 2) \ ) #ifdef MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS #define MPZ_FOOTER_MARK (0xFFFFFFFF) #define MPZ_SLOT_GOTO_FOOT(sl, si) ( \ (mpz_uint32_t *)((mpz_uchar_t *)(sl) + sizeof(mpz_uint32_t) + (si)) \ ) #define MPZ_SLOT_READ_FOOT(s) ( \ (mpz_uint32_t *)MPZ_SLOT_GOTO_FOOT((s), MPZ_SLOT_READ_SIZE(s)) \ ) #endif /* MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ MPZ_FORCE_INLINE mpz_void_t _mpz_pool_gc( mpz_pool_t *pool, mpz_cuint_t soft ); MPZ_FORCE_INLINE mpz_void_t *_mpz_palloc( mpz_pool_t *pool, mpz_size_t size, mpz_cuint_t zeroize ); MPZ_FORCE_INLINE mpz_void_t *_mpz_slab_create( mpz_pool_t *pool, mpz_csize_t size ); MPZ_FORCE_INLINE mpz_void_t _mpz_slab_init( mpz_pool_t *pool, mpz_slab_t *slab, mpz_cuint32_t size ); MPZ_FORCE_INLINE mpz_void_t _mpz_slab_push( mpz_pool_t *pool, mpz_slab_t *slab ); MPZ_FORCE_INLINE mpz_void_t _mpz_slab_free( mpz_pool_t *pool, mpz_slot_t *slot ); MPZ_FORCE_INLINE mpz_void_t _mpz_slot_init( mpz_slot_t *slot, mpz_cuint32_t size, mpz_cuint32_t flags ); /* ==================================================================================================== */ /* PUBLIC API */ mpz_pool_t *mpz_pool_create( mpz_void_t ) { mpz_pool_t *pool; mpz_uint_t idx; MPZ_CHECK_NULL(pool = mpz_memalign(MPZ_ALLOC_ALIGNMENT, MPZ_POOL_SIZE)); for (idx = MPZ_BINS; idx--; ) { pool->bins[idx] = NULL; } pool->slabs = NULL; #ifdef MPZ_ENABLE_THREAD_SAFETY mpz_mutex_init(&(pool->mutex), NULL); #endif /* MPZ_ENABLE_THREAD_SAFETY */ return pool; } mpz_int_t mpz_pool_reset( mpz_pool_t *pool ) { #ifdef MPZ_ENABLE_THREAD_SAFETY MPZ_CHECK_INT(pool, MPZ_FAILURE); if (0 != mpz_mutex_lock(&(pool->mutex))) { return MPZ_FAILURE; } #endif /* MPZ_ENABLE_THREAD_SAFETY */ _mpz_pool_gc(pool, 1); #ifdef MPZ_ENABLE_THREAD_SAFETY mpz_mutex_unlock(&(pool->mutex)); #endif /* MPZ_ENABLE_THREAD_SAFETY */ return MPZ_SUCCESS; } mpz_int_t mpz_pool_destroy( mpz_pool_t *pool ) { #ifdef MPZ_ENABLE_THREAD_SAFETY MPZ_CHECK_INT(pool, MPZ_FAILURE); if (0 != mpz_mutex_lock(&(pool->mutex))) { return MPZ_FAILURE; } #endif /* MPZ_ENABLE_THREAD_SAFETY */ _mpz_pool_gc(pool, 0); #ifdef MPZ_ENABLE_THREAD_SAFETY mpz_mutex_unlock(&(pool->mutex)); mpz_mutex_destroy(&(pool->mutex)); #endif /* MPZ_ENABLE_THREAD_SAFETY */ free(pool); return MPZ_SUCCESS; } mpz_void_t *mpz_pmalloc( mpz_pool_t *pool, mpz_csize_t size ) { return _mpz_palloc(pool, size, 0); } mpz_void_t *mpz_pcalloc( mpz_pool_t *pool, mpz_csize_t size ) { return _mpz_palloc(pool, size, 1); } mpz_int_t mpz_free( mpz_pool_t *pool, mpz_cvoid_t *data ) { mpz_slot_t *slot; mpz_uint32_t *head, size; mpz_uint_t idx; MPZ_CHECK_INT(pool, MPZ_FAILURE); MPZ_CHECK_INT(data, MPZ_FAILURE); #ifdef MPZ_ENABLE_THREAD_SAFETY if (0 != mpz_mutex_lock(&(pool->mutex))) { return MPZ_FAILURE; } #endif /* MPZ_ENABLE_THREAD_SAFETY */ slot = MPZ_DATA_TO_SLOT(data); head = MPZ_SLOT_READ_HEAD(slot); #ifdef MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS /* Check both "segmentation faults" and "double free" errors. */ if ((MPZ_FOOTER_MARK != *MPZ_SLOT_READ_FOOT(slot)) || (!(*head & MPZ_SLOT_FLAG_USED))) { raise(SIGSEGV); } #endif /* MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS */ if (*head & MPZ_SLOT_FLAG_HUGE) { _mpz_slab_free(pool, slot); #ifdef MPZ_ENABLE_THREAD_SAFETY mpz_mutex_unlock(&(pool->mutex)); #endif /* MPZ_ENABLE_THREAD_SAFETY */ return MPZ_SUCCESS; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ size = MPZ_SLOT_READ_SIZE(slot); #ifdef MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS /* Remove the "used" mark. */ _mpz_slot_init(slot, size, 0); #endif /* MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Push the slot into the bins-array. */ idx = MPZ_BIN_IDX(size); slot->next = pool->bins[idx]; pool->bins[idx] = slot; #ifdef MPZ_ENABLE_THREAD_SAFETY mpz_mutex_unlock(&(pool->mutex)); #endif /* MPZ_ENABLE_THREAD_SAFETY */ return MPZ_SUCCESS; } /* ==================================================================================================== */ /* PRIVATE STUFF: DEFINITIONS */ MPZ_FORCE_INLINE mpz_void_t _mpz_pool_gc( mpz_pool_t *pool, mpz_cuint_t soft ) { mpz_slab_t *slab, *next; mpz_slot_t *slot; mpz_uint_t idx; MPZ_CHECK_VOID(pool); MPZ_CHECK_VOID(pool->slabs); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ for (idx = MPZ_BINS; idx--; ) { pool->bins[idx] = NULL; } slab = pool->slabs; pool->slabs = NULL; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** * Slabs contain a huge slot are immediately destroyed. If "soft" * is set to 0, all other slabs are immediately destroyed, too, * otherwise the other slabs are reseted to theirs initial state * to permitt the pool to be efficiently reused. */ while (NULL != slab) { next = slab->next; slot = MPZ_SLAB_TO_SLOT(slab); if (!soft || (*MPZ_SLOT_READ_HEAD(slot) & MPZ_SLOT_FLAG_HUGE)) { _mpz_slab_free(pool, slot); } else { _mpz_slab_push(pool, slab); _mpz_slab_init(pool, slab, MPZ_SLOT_READ_SIZE(slot)); } slab = next; } } MPZ_FORCE_INLINE mpz_void_t *_mpz_palloc( mpz_pool_t *pool, mpz_size_t size, mpz_cuint_t zeroize ) { mpz_slab_t *slab; mpz_slot_t *slot; mpz_uint_t idx; MPZ_CHECK_NULL(pool); if (size < MPZ_POOL_MIN_ALLOC) { size = MPZ_POOL_MIN_ALLOC; } else if (size > MPZ_POOL_MAX_ALLOC) { return NULL; } #ifdef MPZ_ENABLE_THREAD_SAFETY if (0 != mpz_mutex_lock(&(pool->mutex))) { return NULL; } #endif /* MPZ_ENABLE_THREAD_SAFETY */ size += MPZ_SLOT_OVERHEAD; size = mpz_align(size, MPZ_SLOTS_ALIGNMENT); if (size > (MPZ_BINS << MPZ_BINS_BIT_SHIFT)) { /* We have to grab a new memory space from the OS. */ slab = _mpz_slab_create(pool, size + MPZ_SLOT_SIZE); MPZ_CHECK_NULL(slab); /* The new slab contains only a single huge slot. */ _mpz_slot_init(slot = MPZ_SLAB_TO_SLOT(slab), size, MPZ_SLOT_FLAG_HUGE|MPZ_SLOT_FLAG_USED); #ifdef MPZ_ENABLE_THREAD_SAFETY mpz_mutex_unlock(&(pool->mutex)); #endif /* MPZ_ENABLE_THREAD_SAFETY */ return MPZ_SLOT_TO_DATA(slot); } idx = MPZ_BIN_IDX(size); slot = pool->bins[idx]; if (NULL == slot) { /** * The pool is either completely empty (new) or consists of slabs * without empty slots for the requested size in the bins-list. * We have to grab a new memory space from the OS. */ slab = _mpz_slab_create(pool, (size + MPZ_SLOT_SIZE) * MPZ_SLAB_ALLOC_MUL); MPZ_CHECK_NULL(slab); _mpz_slab_init(pool, slab, size); } /* Pop a slot from the bins-array. */ slot = pool->bins[idx]; pool->bins[idx] = slot->next; #ifdef MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS /* Mark the slot as "used". */ _mpz_slot_init(slot, size, MPZ_SLOT_FLAG_USED); #endif /* MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS */ if (zeroize) { mpz_memzero(MPZ_SLOT_TO_DATA(slot), size); } #ifdef MPZ_ENABLE_THREAD_SAFETY mpz_mutex_unlock(&(pool->mutex)); #endif /* MPZ_ENABLE_THREAD_SAFETY */ return MPZ_SLOT_TO_DATA(slot); } MPZ_FORCE_INLINE mpz_void_t *_mpz_slab_create( mpz_pool_t *pool, mpz_csize_t size ) { mpz_slab_t *slab = mpz_memalign(MPZ_ALLOC_ALIGNMENT, size + MPZ_SLAB_SIZE); MPZ_CHECK_NULL(slab); _mpz_slab_push(pool, slab); return slab; } MPZ_FORCE_INLINE mpz_void_t _mpz_slab_init( mpz_pool_t *pool, mpz_slab_t *slab, mpz_cuint32_t size ) { mpz_slot_t *slot = MPZ_SLAB_TO_SLOT(slab); mpz_uint_t idx, i; idx = MPZ_BIN_IDX(size); for (i = 0; i < MPZ_SLAB_ALLOC_MUL; ++i) { /* Set slot metadata. */ _mpz_slot_init(slot, size, 0); if (i == (MPZ_SLAB_ALLOC_MUL - 1)) { /** * Handle the last slot: * * Append the content of the current bin at the * last slot of our slab and let the first slot * of our slab be the leader of the current bin. */ slot->next = pool->bins[idx]; pool->bins[idx] = MPZ_SLAB_TO_SLOT(slab); } else { /* Jump to the next slot. */ slot->next = (mpz_slot_t *)((mpz_uchar_t *)slot + (size + MPZ_SLOT_SIZE)); slot = slot->next; } } } MPZ_FORCE_INLINE mpz_void_t _mpz_slab_push( mpz_pool_t *pool, mpz_slab_t *slab ) { slab->prev = NULL; slab->next = pool->slabs; if (NULL != slab->next) { slab->next->prev = slab; } pool->slabs = slab; } MPZ_FORCE_INLINE mpz_void_t _mpz_slab_free( mpz_pool_t *pool, mpz_slot_t *slot ) { mpz_slab_t *slab = MPZ_SLOT_TO_SLAB(slot); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Remove the slab from the slabs list. */ if (NULL != slab->prev) { slab->prev->next = slab->next; } else { pool->slabs = slab->next; } if (NULL != slab->next) { slab->next->prev = slab->prev; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ free(slab); } MPZ_FORCE_INLINE mpz_void_t _mpz_slot_init( mpz_slot_t *slot, mpz_cuint32_t size, mpz_cuint32_t flags ) { /** * We have always to reset current state * using "0" in this bitwise operation. */ *MPZ_SLOT_READ_HEAD(slot) = (0 | flags | size); #ifdef MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS *MPZ_SLOT_GOTO_FOOT(slot, size) = MPZ_FOOTER_MARK; #endif /* MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS */ }
alex-schneider/mpz
src/mpz_alloc.h
<gh_stars>1-10 /** * Copyright (c) <NAME> */ #ifndef _MEMPOOLZ_API_H_INCLUDE #define _MEMPOOLZ_API_H_INCLUDE #include "mpz_core.h" /* ==================================================================================================== */ typedef struct _mpz_pool_s mpz_pool_t; typedef struct _mpz_slab_s mpz_slab_t; typedef struct _mpz_slot_s mpz_slot_t; struct _mpz_slot_s { mpz_void_t *data; mpz_slot_t *next; }; struct _mpz_slab_s { mpz_slab_t *prev; mpz_slab_t *next; }; struct _mpz_pool_s { mpz_slot_t *bins[MPZ_BINS]; mpz_slab_t *slabs; #ifdef MPZ_ENABLE_THREAD_SAFETY mpz_mutex_t mutex; #endif /* MPZ_ENABLE_THREAD_SAFETY */ }; /* ==================================================================================================== */ mpz_pool_t *mpz_pool_create( mpz_void_t ); mpz_int_t mpz_pool_reset( mpz_pool_t *pool ); mpz_int_t mpz_pool_destroy( mpz_pool_t *pool ); mpz_void_t *mpz_pmalloc( mpz_pool_t *pool, mpz_csize_t size ); mpz_void_t *mpz_pcalloc( mpz_pool_t *pool, mpz_csize_t size ); mpz_int_t mpz_free( mpz_pool_t *pool, mpz_cvoid_t *data ); /* ==================================================================================================== */ #endif /* _MEMPOOLZ_API_H_INCLUDE */
alex-schneider/mpz
src/mpz_core.h
<reponame>alex-schneider/mpz /** * Copyright (c) <NAME> */ #ifndef _MEMPOOLZ_CORE_H_INCLUDE #define _MEMPOOLZ_CORE_H_INCLUDE /* ==================================================================================================== */ #include <stdlib.h> #include <stdint.h> #include <string.h> /* ==================================================================================================== */ /* ==================================================================================================== */ /* ==================================================================================================== */ /* FOR DEVELOPER WHO WANT TO ADAPT THE MPZ TO THE REQUIREMENTS OF THEIR APPLICATIONS */ /** * Every project is unique and therefore has also individual requirements. Below * are some of the most important settings explained that developers can try out * for fine tuning of MPZ for their applications. * * * IMPORTANT INTRODUCTION: * * Among other things, MPZ is so fast because it works without expensive arithmetic * operations (e.g. divisions or modulo-operator) and works with a lot of very * fast bitshift operations. For that an important prerequisite must be fulfilled: * Using of power-of-two numbers for alignment, binning and indexing. */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** * The MPZ supports thread safety and may easy be used in multi-thread applications. * To disable this behavior just comment out the following definement. * * Disabling of this feature increases the performance of the MPZ. */ #define MPZ_ENABLE_THREAD_SAFETY /** * The MPZ implements simple checks for "segmentation faults" and "double free" * errors. In cases that an error is detected MPZ immediately raises an "SIGSEGV" * error. To disable this behavior just comment out the following definement. * * Disabling of this feature increases the performance of the MPZ. */ #define MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS /** * Total number of indexes in the bins-array (0 - 127). You can increase this number, * e.g. to be able to serve larger memory space directly from the pool, instead of * again and again allocating huge slabs from the OS. */ #define MPZ_BINS (128) /** * This alignment is used at all allocations of slots from the pool. At the same * time it is also the difference in bytes between each bin in the bins-array. So * a slot with the size of 8 bytes is stored in the bin with the index 0 and a slot * with the size of 1.024 bytes is stored in the bin with the index 127. If this * constant is modified, don't forget to modify the following const MPZ_BINS_BIT_SHIFT, * too. */ #define MPZ_SLOTS_ALIGNMENT (8) /** * This is the bit-shift using to calculate the index of the bins-array, as well, * for example, to determine if the MPZ needs to allocate a huge slab from the OS. * The constant MPZ_SLOTS_ALIGNMENT described above is very closely linked to this * constant, so changes should be applied to both constants simultaneously. */ #define MPZ_BINS_BIT_SHIFT (3) /** * If a new slab has to be allocated from the OS, the MPZ uses this multiplier to * allocate MPZ_SLAB_ALLOC_MUL numbers of the same requested slot size simultaneously * and to be able immediately to provide the remaining slots to the user if needed. * * Long detailed research has shown that a multiplier of 16 is optimal for both * small and large numbers of allocations, without the overhead becoming too large. */ #define MPZ_SLAB_ALLOC_MUL (16) /** * Since the given size has to be already aligned before calling this operation, * this operation is equals to "size / 8 - 1", but we don't want to use expensive * division operations. */ #define MPZ_BIN_IDX(size) (((size) >> MPZ_BINS_BIT_SHIFT) - 1) /* ==================================================================================================== */ /* ==================================================================================================== */ /* ==================================================================================================== */ typedef void mpz_void_t; typedef const void mpz_cvoid_t; typedef unsigned char mpz_uchar_t; typedef int mpz_int_t; typedef unsigned int mpz_uint_t; typedef const unsigned int mpz_cuint_t; typedef uint32_t mpz_uint32_t; typedef const uint32_t mpz_cuint32_t; typedef size_t mpz_size_t; typedef const size_t mpz_csize_t; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ #ifdef __GNUC__ #define MPZ_FORCE_INLINE static inline __attribute__((always_inline)) #else #define MPZ_FORCE_INLINE static inline #endif /* __GNUC__ */ #else #define MPZ_FORCE_INLINE static #endif /* __STDC_VERSION__ */ #define MPZ_CHECK_INT(p, i) ({ if (NULL == (p)) return (i); }) #define MPZ_CHECK_VOID(p) ({ if (NULL == (p)) return; }) #define MPZ_CHECK_NULL(p) ({ if (NULL == (p)) return NULL; }) #define MPZ_SUCCESS (0) #define MPZ_FAILURE (1) /* ==================================================================================================== */ #ifdef MPZ_ENABLE_THREAD_SAFETY #include <pthread.h> #endif /* MPZ_ENABLE_THREAD_SAFETY */ #ifdef MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS #include <signal.h> #endif /* MPZ_RAISE_SIGSEGV_ON_MEM_ERRORS */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #ifdef MPZ_ENABLE_THREAD_SAFETY #include "mpz_mutex.h" #endif /* MPZ_ENABLE_THREAD_SAFETY */ #include "mpz_alloc.h" /* ==================================================================================================== */ #endif /* _MEMPOOLZ_CORE_H_INCLUDE */
tworkshyd/v2-mcu2
mcu2/memory/memory.h
<filename>mcu2/memory/memory.h /**************************************************************************/ /*! @file hbad_memory.h @brief This module contains base addresses and range for oxygen calibration, ps1, ps2, dps1, dps2, methods to store and retrieve. @author Tworks @defgroup MemoryModule MemoryModule MemoryModule contains base addresses and range for oxygen calibration, ps1, ps2, dps1, dps2, methods to store and retrieve @{ */ /**************************************************************************/ #include "../BoardDefines.h" #include <extEEPROM.h> #include <EEPROM.h> /*! It is Default Data Write Addr< */ #define EEPROM_DEFAULT_DATA_WRITE_ADDR 0xA //10 /*! EEPROM Oxygen CALIB ADDR */ #define EEPROM_O2_CALIB_ADDR 0xC //12 - 22 #define NUM_OF_SAMPLES_O2 3 /*! EEPROM PG1 CALIB ADDR */ #define EEPROM_PG1_CALIB_ADDR 0x28 //40 - 78 #define NUM_OF_SAMPLES_PS1 19 /*!EEPROM PS2 CALIB ADDR */ #define EEPROM_PS2_CALIB_ADDR 0 #define NUM_OF_SAMPLES_PS2 0 /*!EEPROM DPS1 CALIB ADDR */ #define EEPROM_DPS1_CALIB_ADDR 0 #define NUM_OF_SAMPLES_DPS1 0 /*!EEPROM DPS2 CALIB ADDR */ #define EEPROM_DPS2_CALIB_ADDR 0 #define NUM_OF_SAMPLES_DPS2 0 /*!EEPROM I2C Address */ #define EEPROM_I2C_ADDR 0x50 //80 /*!< */ #define EEPROM_BASE_ADDR 0xC8 #define GUARD_VALUE 0x4 #define EEPROM_CALIBRATION_STORE_ADDR (EEPROM_BASE_ADDR + (MAX_CTRL_PARAMS*2) + GUARD_VALUE) #define EEPROM_MAX_SIZE 4096 //max size of the EEPROM i.e. 4K bytes #define EEPROM_WDT_DATA 0x0f80 //address to be used when WDT is reset which is (4k - 128) = 0x0f80 //"W" in ascii will be stored in this address which would indicate that the MCU was reset due to watchdog timer // This will also store the current state of the machine which will be restored. //enum used for specifing read write operation in the eeprom_ext_rw function in memory.cpp typedef enum { EEPROM_READ, EEPROM_WRITE } eeprom_ops; //const uint32_t totalKBytes = 64; /*!device size, number of devices, page size< */ extEEPROM hbad_mem(kbits_256, 1, 32, EEPROM_I2C_ADDR); /**************************************************************************/ /*! @brief Function to store specific the caliberated parameter. @param sensor_e sensor describes which sensor to be read. @param data returns the sensor data read from sensor @return 0 for success and error code for any failures */ /**************************************************************************/ void storeParam(ctrl_parameter_t param); /**************************************************************************/ /*! @brief Function to get specific the caliberated parameter. @param sensor_e sensor describes which sensor to be read. @param data returns the sensor data read from sensor @return 0 for success and error code for any failures */ /**************************************************************************/ void retrieveParam(ctrl_parameter_t param); /**************************************************************************/ /*! @brief Function to get all the caliberated parameter. @param sensor_e sensor describes which sensor to be read. @param data returns the sensor data read from sensor @return 0 for success and error code for any failures */ /**************************************************************************/ void getAllParamsFromMem(); /**************************************************************************/ /*! @brief Function to store the caliberated parameter on specific address with specified data. @param sensor_e sensor describes which sensor to be read. @param data returns the sensor data read from sensor @return 0 for success and error code for any failures */ /**************************************************************************/ void storeCalibParam(int storeAddress, int data); /**************************************************************************/ /*! @brief Function to retrieve the caliberated Parameter based on Address. @param sensor_e sensor describes which sensor to be read. @param data returns the sensor data read from sensor @return 0 for success and error code for any failures */ /**************************************************************************/ int retrieveCalibParam(int address); long int retrieve_sensor_data_long(int readAddress); void store_sensor_data_long(int storeAddress, long int data); int eeprom_ext_rw(unsigned int address, char *data, unsigned int size, eeprom_ops ops); /**@}*/
tworkshyd/v2-mcu2
mcu2/encoder/encoder.c
#include "../BoardDefines.h" //#include <Wire.h> #include <pins_arduino.h> //#include "../pinout.h"; // Keep track of last rotary value int lastCount = 100; // Updated by the ISR (Interrupt Service Routine) volatile int virtualPosition = 100; // ------------------------------------------------------------------ // INTERRUPT INTERRUPT INTERRUPT INTERRUPT INTERRUPT // ------------------------------------------------------------------ volatile int counter = 0; volatile static unsigned long last_interrupt_time = 0; volatile byte aFlag = 0; // let's us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent volatile byte bFlag = 0; // let's us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set) volatile int encoderPos = 0; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255 volatile int oldEncPos = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor) volatile byte reading = 0; //somewhere to store the direct values we read from our interrupt pins before checking to see if we have moved a whole detent int getEncoderPos() { if(oldEncPos != encoderPos) { // DebugPort.print("ENC: "); // DebugPort.println(encoderPos); oldEncPos = encoderPos; } return encoderPos; } void isrEncoderClk(){ VENT_DEBUG_FUNC_START(); cli(); //stop interrupts happening before we read pin values reading = PIND & 0xC; // read all eight pin values then strip away all but pinA and pinB's values if(reading == B00001100 && aFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge encoderPos --; //decrement the encoder's position count bFlag = 0; //reset flags for the next turn aFlag = 0; //reset flags for the next turn } else if (reading == B00000100) bFlag = 1; //signal that we're expecting pinB to signal the transition to detent from free rotation sei(); //restart interrupts VENT_DEBUG_FUNC_END(); } void isrEncoderDt(){ VENT_DEBUG_FUNC_START(); cli(); //stop interrupts happening before we read pin values reading = PIND & 0xC; //read all eight pin values then strip away all but pinA and pinB's values if (reading == B00001100 && bFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge encoderPos ++; //increment the encoder's position count bFlag = 0; //reset flags for the next turn aFlag = 0; //reset flags for the next turn } else if (reading == B00001000) aFlag = 1; //signal that we're expecting pinA to signal the transition to detent from free rotation sei(); //restart interrupts VENT_DEBUG_FUNC_END(); } bool switch_position_changed = false; void isr_processSwitch() { VENT_DEBUG_FUNC_START(); switch_position_changed = true; VENT_DEBUG_FUNC_END(); } RT_Events_T encoderScanIsr() { RT_Events_T retVal = RT_NONE; VENT_DEBUG_FUNC_START(); counter = getEncoderPos(); if (lastCount != counter) { if (lastCount < counter ) retVal = RT_INC; else retVal = RT_DEC; } lastCount = counter; VENT_DEBUG_FUNC_END(); return retVal; } void isr_processStartEdit() { static unsigned long lastSwitchTime = 0; unsigned long switchTime = millis(); VENT_DEBUG_FUNC_START(); if ((switchTime - lastSwitchTime) < DBNC_INTVL_SW) { VENT_DEBUG_FUNC_END(); return; } lastSwitchTime = switchTime; VENT_DEBUG_FUNC_END(); } unsigned long lastButtonPress = 0; int currentStateCLK; int lastStateCLK; boolean no_input = true; int btnState; RT_Events_T encoderScanUnblocked() { RT_Events_T eRTState_EnCoder = RT_NONE; VENT_DEBUG_FUNC_START(); // Read the current state of CLK eRTState_EnCoder = encoderScanIsr(); if ((eRTState_EnCoder == RT_INC) || (eRTState_EnCoder == RT_DEC)) no_input = false; // Read the button state int btnState = digitalRead(DISP_ENC_SW); //If we detect LOW signal, button is pressed if (btnState == LOW) { //if 50ms have passed since last LOW pulse, it means that the //button has been pressed, released and pressed again if ((millis() - lastButtonPress > 50) && switch_position_changed) { eRTState_EnCoder = RT_BT_PRESS; switch_position_changed = false; no_input = false; } // Remember last button press event lastButtonPress = millis(); } RT_Events_T returnState = eRTState_EnCoder; if (eRTState_EnCoder != RT_NONE) { digitalWrite(BUZZER_PIN, HIGH); delay(1); digitalWrite(BUZZER_PIN, LOW); // lcd.setCursor(5,0); // lcd.print(returnState); } // lcd.setCursor(7,0); // lcd.print(" "); // lcd.print(returnState); // VENT_DEBUG_FUNC_END(); return returnState; } RT_Events_T Encoder_Scan(void) { RT_Events_T eRTState = RT_NONE; VENT_DEBUG_FUNC_START(); no_input = true; while(no_input) { eRTState = encoderScanUnblocked(); } VENT_DEBUG_FUNC_END(); return(eRTState); }
tworkshyd/v2-mcu2
mcu2/lcd_display/ctrl_display.h
<reponame>tworkshyd/v2-mcu2<gh_stars>0 /**************************************************************************/ /*! @file ctrl_display.h @brief This Module contains @author Tworks @{ */ /**************************************************************************/ #pragma once #include "../BoardDefines.h" #include "lcd.h" #include "../encoder/encoder.h" #include "../sensors/sensormanager.h" #define MAIN_MENU_LENGTH 4 #define SUB_MENU1_LENGTH 3 boolean drawSplashScreenMenu = false; boolean _refreshSplashEditScreen = true; static int serviceLevelIndex = -1; static int statusScreenIndex = -2; #define SPLASH_EDIT_MENU_TIMEOUT 7000 void CurrentO2Value(int i); void ResetO2(int i); void CalibrateO2(int i); void CalibExit(int i); void Adc(); void Com(); void Sensor(); void Valves(); void ExitDaignostic(); // // fun_ptr_arr is an array of function pointers void (*oxygenCalibFunc_arr[4])(int) = {CurrentO2Value, ResetO2, CalibrateO2, CalibExit}; void (*diagnosticFunc_arr[5])() = {Adc, Com, Sensor, Valves, ExitDaignostic}; const char *diagnosticFuncName[5] = {" adc ", " com ", "sensor", "valves", " Exit "}; void drawServiceLevelScreen(int screenIndex, RT_Events_T eRTState); const char *oxySettings[4] = {"", " Reset ", "Calibrate", " Exit "}; //pot2 const char *mainMenu[MAIN_MENU_LENGTH] = {" exit diag mode", " O2-Calib", " Check ADS1115", " Read All"}; const char *subMenu1[SUB_MENU1_LENGTH] = {" 0% ", " 21%", "100%"}; //pot1 void diagO2Sensor(void); void diagAds1115(void); void sensorstatus(void); void diagSolStatus(void); #define TV_DEFAULT_VALUE 350 #define RR_DEFAULT_VALUE 12 #define PMAX_DEFAULT_VALUE 60 #define IER_DEFAULT_VALUE 2 #define DBNC_INTVL_SW 500 /*!< millisecs delay before switch debounce */ #define POT_HIGH 1023 /*!< maximum pot high value */ /*Let us start writing from the 16th memory location. This means Parameter 1 will be stored in locs with addr 16, 17, 18, 19 and Parameter 1 will be stored in 20, 21, 22, 23 and so on */ #define UNIT_CMH2O "cmH20" #define SAVE_FLAG " SAVE " /*!< defines the String for SAVE_FLAG */ #define SAVE_FLAG_CHOSEN "<SAVE>" /*!< defines the String for SAVE_FLAG_CHOSEN */ #define CANC_FLAG " CANCEL " /*!< defines the String for CANC_FLAG */ #define CANC_FLAG_CHOSEN "<CANCEL> " /*!< defines the String for CANC_FLAG_CHOSEN */ #define CAL_GP1 "Cal_GP1" #define CAL_GP2 "Cal_GP2" /*!< mode_headers array difines all the modes */ const unsigned char splashScreenTopBottomBuffer[21] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0}; const unsigned char splashScreenMiddleBuffer[21] = { 0xFF, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xFF, 0x0}; typedef enum { E_EXIT = 0, E_TV, E_BPM, E_FiO2, E_IER, E_PEEP, E_PIP, E_O2_INPUT, E_OP_MODE, SHOW_VOL, SHOW_PRESSURE, E_CALVALUE_GP1, E_CALVALUE_GP2, LCD_CONTRAST, OXYGEN_CALIB, MAX_EDIT_MENU_ITEMS = 15 } eMainMenu; #define MAX_CTRL_PARAMS 9 /*!< Total number of control parameters */ const String mainEditMenu[MAX_EDIT_MENU_ITEMS] = {"EXIT EDIT MENU", "TV : ", "RR : ", "FiO2 : ", "IER : ", "PEEP : ", "PIP : ", "O2in : ", "OpMode: ", "Volt : ", "Pres : "}; struct ctrl_parameter_t { const eMainMenu index; /*!< index variable stores the index according to the ctrl_parameter_t params array variables*/ const String parm_name; /*!< It describes the control parameter name */ const int readPortNum; /*!< It describes the pin number associated with control parameter*/ const int min_val; /*!< It describes the minimum value associated with control parameter */ const int max_val; /*!< It describes the maximum value associated with control parameter */ const String units; /*!< It describes the units associated with control parameter */ int incr; /*!< It describes the incrementation factor associated with control parameter */ int value_curr_mem; /*!< It describes the current memory value associated with control parameter */ int value_new_pot; /*!< It describes the current pot value associated with control parameter */ }; /*!< default values assigned according to the ctrl_parameter_t Structure variables for exit handler */ const ctrl_parameter_t exit_menu = {E_EXIT, mainEditMenu[E_EXIT], 0, 0, 0, "", 0, 0, 0}; /*!< default values assigned according to the ctrl_parameter_t Structure variables for tidal volume */ const ctrl_parameter_t tidl_volu = {E_TV, mainEditMenu[E_TV], TIDAL_VOLUME_PIN, 200, 650, "ml ", 50, 350, 0}; /*!< default values assigned according to the ctrl_parameter_t Structure variables for BPM */ const ctrl_parameter_t resp_rate = {E_BPM, mainEditMenu[E_BPM], RR_PIN, 4, 39, "BPM ", 1, 10, 0}; /*!< default values assigned according to the ctrl_parameter_t Structure variables for Fio2 */ const ctrl_parameter_t fio2_perc = {E_FiO2, mainEditMenu[E_FiO2], FiO2_PIN, 14, 99, "% ", 1, 0, 0}; /*!< default values assigned according to the ctrl_parameter_t Structure variables for IER Ratio */ //DISP_ENC_CLK // //READ THROUGH ENCODER const ctrl_parameter_t inex_rati = {E_IER, mainEditMenu[E_IER], IER_PIN, 0, 2, "ratio", 1, 2, 0}; /*!< default values assigned according to the ctrl_parameter_t Structure variables for PeeP */ const ctrl_parameter_t peep_pres = {E_PEEP, mainEditMenu[E_PEEP], DISP_ENC_CLK, //READ THROUGH ENCODER 0, 20, UNIT_CMH2O, 1, 0, 0}; /*!< default values assigned according to the ctrl_parameter_t Structure variables for PeakPressure */ const ctrl_parameter_t peak_press = {E_PIP, mainEditMenu[E_PIP], PMAX_PIN, 29, 99, UNIT_CMH2O, 1, 0, 0}; /*!< default values assigned according to the ctrl_parameter_t Structure variables for o2_input */ const ctrl_parameter_t o2_input = {E_O2_INPUT, mainEditMenu[E_O2_INPUT], 0, 0, 0, "", 0, 0, 0}; /*!< default values assigned according to the ctrl_parameter_t Structure variables for o2_input */ const ctrl_parameter_t op_mode = {E_OP_MODE, mainEditMenu[E_OP_MODE], 0, 0, 0, "", 0, 0, 0}; const ctrl_parameter_t show_voltage = {SHOW_VOL, mainEditMenu[SHOW_VOL], 0, 0, 0, "", 0, 0, 0}; const ctrl_parameter_t show_pressure = {SHOW_PRESSURE, mainEditMenu[SHOW_PRESSURE], 0, 0, 0, "", 0, 0, 0}; const ctrl_parameter_t cal_gp1 = {E_CALVALUE_GP1, CAL_GP1, 0, 0, 1024, "", 0, 0, 0}; const ctrl_parameter_t cal_gp2 = {E_CALVALUE_GP2, CAL_GP2, 0, 0, 1024, "", 0, 0, 0}; const ctrl_parameter_t lcd_contrast = {LCD_CONTRAST, "LCD Contrast", FiO2_PIN, -10, 90, "", 10, 0, 0}; const ctrl_parameter_t oxygenCalib = {OXYGEN_CALIB, " O2 Calibration", RR_PIN, -10, 90, "", 10, 0, 0}; /*!< Array contains all the control parameter values */ /*order should be same as in eMainMenu*/ static ctrl_parameter_t params[] = {exit_menu, tidl_volu, resp_rate, fio2_perc, inex_rati, peep_pres, peak_press, o2_input, op_mode, show_voltage, show_pressure, cal_gp1, cal_gp2, lcd_contrast, oxygenCalib}; // global variables here enum STATE { STATUS_MENU, STATUS_MENU_TO_EDIT_MENU, EDIT_MENU, EDIT_MENU_TO_SUB_EDIT_MENU, SUB_EDIT_MENU, SUB_EDIT_MENU_TO_EDIT_MENU, EDIT_MENU_TO_STATUS_MENU, }; enum eDisplayPrm { DISPLAY_TVI, DISPLAY_TVE, DISPLAY_PEEP, DISPLAY_PIP, DISPLAY_PLAT }; const char clearScreenBuffer[21] = { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0}; const char topBottomLineBuffer[18] = { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00}; static int aboutScreenIndex = 0; boolean errorStatus = false; boolean pressure_flag = false; boolean millivolt_flag = false; void SetDefaultAllParam(); void SetBasicParam(); void SetDefaultCalibration(); void exitFactory(); // fun_ptr_arr is an array of function pointers void (*fun_ptr_arr[])() = {SetDefaultAllParam, SetBasicParam, SetDefaultCalibration, exitFactory}; boolean showAboutScreenSubMenu = false; const char *factorySettings[4] = {"All Parameters", "TV,IER,RR,Pmax", " Calibration ", " Exit "}; class displayManager { public: /* Methods Used by Other Classes */ void displayManagerloop(float *sensor_data, sensorManager &sM); void errorDisplay(ErrorDef_T errorState); void setDisplayParam(eDisplayPrm param, float value); void clearDisplay(void); private: /* Utilities Methods */ float getDisplayParam(eDisplayPrm param); int rectifyBoundaries(int value, int minimum, int maximum); int getCalibratedParamFromPot(ctrl_parameter_t param); int getCalibValue(int potValue, int paramIndex); void drawRuntimeTopBottomLines(int currentPage, int totalPages, int topRight, int bottomLeft); /* Display Screens Related Methods */ void displayStatusScreen(float *sensor_data, int statusScreenIndex); void pressureSensorsStatusScreen(void); void ierRrOxygenStatusScreen(float *sensor_data); void tidalVolumeStatusScreen(void); /* Edit Screens Related Methods */ void editMenuHandler(RT_Events_T eRTState); void fio2SettingScreen(RT_Events_T eRTState); void aboutScreen(RT_Events_T eRTState); void lcdSettingScreen(RT_Events_T eRTState); void drawEditMenu(); /* Edit Screens Related Methods */ void drawServiceMenuScreen1(RT_Events_T eRTState); /*BOOTUP Screens Related Methods */ void drawSensorValueMenu(RT_Events_T eRTState); void drawSensorvoltageMenu(RT_Events_T eRTState); void drawOxygenCalibScreen(RT_Events_T eRTState, sensorManager sM); void drawDiagnosticScreen(RT_Events_T eRTState); void drawMessageScreen(const char* pHeading, int xPos, int yPos, const char* pMessage); //variables from here volatile STATE _dpState = STATUS_MENU; volatile short _currItem = 1; int _currentSaveFlag = 1; volatile unsigned long _lastEditMenuTime = 0; volatile unsigned long _lastSubEditMenuTime = 0; /*default true , we need to do lcd.clear once moved out from setup*/ bool _refreshRunTimeDisplay = true; bool _refreshEditScreenDisplay = true; long unsigned _lastDisplayTime = 0; long unsigned _lastEditDisplayTime = 0; sensorManager *m_sM; float m_display_tve = 0; float m_display_tvi = 0; float m_display_peep = 0; float m_display_plat = 0; float m_display_pip = 0; float m_o2_sensor_data = 0; }; /**@}*/
tworkshyd/v2-mcu2
mcu2/debug.h
/**************************************************************************/ /*! @file debug.h @brief This file defines and includes all of the debug related utilities @author Ritesh @date 6/10/2020 Initial revision @{ */ /**************************************************************************/ #include "BoardDefines.h" /*-----------------------------------------------*/ //Debug macros #define VENT_DEBUG_LEVEL_HIGH 3 #define VENT_DEBUG_LEVEL_INFO 2 #define VENT_DEBUG_LEVEL_ERR 1 #define VENT_DEBUG_LEVEL_NONE 0 #define VENT_DEBUG_LEVEL VENT_DEBUG_LEVEL_ERR #if VENT_DEBUG_LEVEL == VENT_DEBUG_LEVEL_HIGH #define VENT_DEBUG_FUNC_START() \ DebugPort.print(__func__); \ DebugPort.print(" Start..."); \ DebugPort.println() #define VENT_DEBUG_FUNC_END() \ DebugPort.print(" ...End "); \ DebugPort.print(__func__); \ DebugPort.println() #define VENT_DEBUG_INFO(message, result) VENT_DEBUG_ERROR(message, result) #define VENT_DEBUG_ERROR(message, err) \ DebugPort.print(__func__); \ DebugPort.print(": "); \ DebugPort.print(message); \ DebugPort.println(err) #elif VENT_DEBUG_LEVEL == VENT_DEBUG_LEVEL_INFO #define VENT_DEBUG_FUNC_START() #define VENT_DEBUG_FUNC_END() #define VENT_DEBUG_INFO(message, result) VENT_DEBUG_ERROR(message, result) #define VENT_DEBUG_ERROR(message, err) \ DebugPort.print(__func__); \ DebugPort.print(": "); \ DebugPort.print(message); \ DebugPort.println(err) #elif VENT_DEBUG_LEVEL == VENT_DEBUG_LEVEL_ERR #define VENT_DEBUG_FUNC_START() #define VENT_DEBUG_FUNC_END() #define VENT_DEBUG_INFO(message, result) #define VENT_DEBUG_ERROR(message, err) \ DebugPort.print(__func__); \ DebugPort.print(": "); \ DebugPort.print(message); \ DebugPort.println(err) #else #define VENT_DEBUG_FUNC_START() #define VENT_DEBUG_FUNC_END() #define VENT_DEBUG_ERROR(message, err) #define VENT_DEBUG_INFO(message, result) #endif /*-----------------------------------------------*/ /**@}*/
tworkshyd/v2-mcu2
mcu2/encoder/encoder.h
<filename>mcu2/encoder/encoder.h /** * @enum EnumType * @brief An enum description. */ #include "../BoardDefines.h" #pragma once typedef enum { RT_INC=0, RT_DEC, RT_BT_PRESS, RT_NONE }RT_Events_T; void isrEncoderClk(); RT_Events_T encoderScanIsr(); RT_Events_T encoderScanUnblocked() ; RT_Events_T Encoder_Scan(void);
tworkshyd/v2-mcu2
tests/eeprom/memory/memory.h
#include <extEEPROM.h> #include <EEPROM.h> /*!EEPROM I2C Address */ #define EEPROM_I2C_ADDR 0x50 //80 #define EEPROM_DEFAULT_DATA_WRITE_ADDR 0xA //10 #define EEPROM_ADDR 0xC //12 #define EEPROM_MAX_SIZE 4096 //max size of the EEPROM i.e. 4K bytes typedef enum { EEPROM_READ, EEPROM_WRITE } eeprom_ops; //const uint32_t totalKBytes = 64; /*!device size, number of devices, page size< */ extEEPROM hbad_mem(kbits_256, 1, 64, EEPROM_I2C_ADDR); void storeParam(int storeAddress, int data); int retrieveParam(int address); int eeprom_ext_rw(unsigned int address, int *data, unsigned int size, eeprom_ops ops); /**@}*/
tworkshyd/v2-mcu2
tests/uart/BoardDefines.h
<gh_stars>0 #ifndef __BOARD_INCLUDES_H__ #define __BOARD_INCLUDES_H__ #define VERSION_2_0 0 #define VERSION_2_1 1 #define VERSION_2_2 2 /// Define the Board Here #define BOARD_VERSION VERSION_2_1 #if BOARD_VERSION == VERSION_2_2 #pragma message("Board Version 2.2") #define DebugPort Serial2 #else #pragma message("Board Version 2.1/2.0") #define DebugPort Serial #endif #define ENABLE_BUZZER 0 //#define DEBUG_RECEIVED_DATA 1 #define PRINT_PROCESSING_TIME 0 #define ENABLE_O2_SUPPLY 0 #endif // __BOARD_INCLUDES_H__
tworkshyd/v2-mcu2
mcu2/lcd_display/lcd.h
/**************************************************************************/ /*! @file lcd.h @brief This Module contains all the configurations and Display details @author Tworks @{ */ /**************************************************************************/ #pragma once #include "../BoardDefines.h" #include <LiquidCrystal.h> #include <string.h> #define LCD_LENGTH_CHAR 20 /*!< Length of the LCD in terms of Char*/ #define LCD_HEIGHT_CHAR 4 /*!< Height of the LCD in terms of Char*/ #define NAME1_DISPLAY_POS 0 /*!< position where name1 to be displayed*/ #define VALUE1_DISPLAY_POS 5 /*!< position where value1 to be displayed*/ #define NAME2_DISPLAY_POS 11 /*!< position where name2 to be displayed*/ #define VALUE2_DISPLAY_POS 14 /*!< position where value2 to be displayed*/ #define PAR_SEP_CHAR ' ' /*!< space assigned for parameter seperation*/ #define POWER_FAILURE_MSG1 "POWER FAILURE" #define POWER_FAILURE_MSG2 "Check Power Supply" #define PATIENT_DISCONN_MSG1 "PATIENT DISCONNECTED" #define PATIENT_DISCONN_MSG2 "Check Breath Circuit" #define PEEP_MSG1 "PEEP NOT ACHIEVED" #define PEEP_MSG2 "Check Breath Circuit" #define AIR_SUPPLY_MSG1 "AIR SUPPLY FAILURE" #define AIR_SUPPLY_MSG2 "Check Breath Circuit" #define TV_MSG1 "TV NOT ACHIEVED" #define TV_MSG2 "Check Pressure Limit" #define TV_MSG3 "BVM, Breath Circuit" #define OXY_FAILURE_MSG1 "OXYGEN FAILURE" #define OXY_FAILURE_MSG2 "Check Oxygen Supply" #define BVM_FAILURE_MSG1 " BVM FAILURE" #define BVM_FAILURE_MSG2 "Check BVM" char paddedValue[10]; LiquidCrystal lcd(DISPLAY_RS_PIN, DISPLAY_EN_PIN, DISPLAY_4_PIN, DISPLAY_3_PIN, DISPLAY_2_PIN, DISPLAY_1_PIN); /** * @enum ControlStatesDef_T * @brief Following are the Control States during which Sensor data and user inputs are compared * to generate specific commands required for that state. */ typedef enum { NO_ERR = 0, ERR_OXY, ERR_BVM, ERR_TV, ERR_PEEP, ERR_PATIENT_DISCONN, } ErrorDef_T; void printPadded(int unpaddedNumber) { if (unpaddedNumber < 10) { lcd.print(" "); } else if (unpaddedNumber < 100) { lcd.print(" "); } lcd.print(unpaddedNumber); } void printEditValue(int unpaddedNumber) { if (unpaddedNumber < 10) { lcd.print("<"); lcd.print(" "); lcd.print(unpaddedNumber); lcd.print(" "); lcd.print(">"); } else if (unpaddedNumber < 100) { lcd.print("<"); lcd.print(" "); lcd.print(unpaddedNumber); lcd.print(">"); } else if (unpaddedNumber == 100) { lcd.print("<"); lcd.print(unpaddedNumber); lcd.print(">"); } } void printRRValue(int unpaddedNumber) { if (unpaddedNumber < 10) { lcd.print("<"); lcd.print(" "); lcd.print(unpaddedNumber); lcd.print(">"); } else if (unpaddedNumber < 100) { lcd.print("<"); lcd.print(unpaddedNumber); lcd.print(">"); } } //String emptyString="aaaaaaaaaaaaaaaaaaaaaaa"; /**@}*/
tworkshyd/v2-mcu2
mcu1/BoardDefines.h
<filename>mcu1/BoardDefines.h #ifndef __BOARD_INCLUDES_H__ #define __BOARD_INCLUDES_H__ #define VERSION_2_0 0 #define VERSION_2_1 1 #define VERSION_2_2 2 /// Define the Board Here #define BOARD_VERSION VERSION_2_2 #if BOARD_VERSION == VERSION_2_2 // #pragma message ("Board Version 2.2") #define DebugPort Serial2 #else #pragma message("Board Version 2.1/2.0") #define DebugPort Serial #endif #endif // __BOARD_INCLUDES_H__
tworkshyd/v2-mcu2
mcu2/BoardDefines.h
<reponame>tworkshyd/v2-mcu2<filename>mcu2/BoardDefines.h<gh_stars>0 #ifndef __BOARD_INCLUDES_H__ #define __BOARD_INCLUDES_H__ #define VERSION_2_0 0 #define VERSION_2_1 1 #define VERSION_2_2 2 /// Define the Board Here #define BOARD_VERSION VERSION_2_2 #if BOARD_VERSION == VERSION_2_2 // #pragma message("Board Version 2.2") #define DebugPort Serial2 #define OXYGEN_SENSOR_GAIN GAIN_EIGHT #else #pragma message("Board Version 2.1/2.0") #define DebugPort Serial #define OXYGEN_SENSOR_GAIN GAIN_ONE #endif #define ENABLE_BUZZER 0 //#define DEBUG_RECEIVED_DATA 1 #define PRINT_PROCESSING_TIME 0 #define ENABLE_O2_SUPPLY 0 #endif // __BOARD_INCLUDES_H__
tworkshyd/v2-mcu2
mcu2/state_control/statecontrol.h
/**************************************************************************/ /*! @file Control_StateMachine.h @brief Control StateMachine Module defines the state @author Tworks @defgroup StateControlModule StateControlModule Module is a stateMachine where sensors data and UI parameters data is read to take appropriate decision in the respective state. @{ */ /**************************************************************************/ #ifndef __STATECONTROL_H__ #define __STATECONTROL_H__ #define STPR_STP 0 /**< it gives the index value of the commands array to stop stepper motor*/ #define STPR_ON 1 /**< it gives the index value of the commands array to start stepper motor*/ #define OXY_SOLE_CYL_OFF 2 /**< it gives the index value of the commands array to oxygen solenoid cylinder line off*/ #define OXY_SOLE_CYL_ONN 3 /**< it gives the index value of the commands array to oxygen solenoid cylinder line on*/ #define OXY_SOLE_HOS_O2_OFF 4 /**< it gives the index value of the commands array to oxygen solenoid hospital line off*/ #define OXY_SOLE_HOS_O2_ONN 5 /**< it gives the index value of the commands array to oxygen solenoid hospital line on*/ #define INH_SOLE_OFF 6 /**< it gives the index value of the commands array to inhalation solenoid off*/ #define INH_SOLE_ONN 7 /**< it gives the index value of the commands array to inhalation solenoid on*/ #define EXH_SOLE_OFF 8 /**< it gives the index value of the commands array to exhalation solenoid off*/ #define EXH_SOLE_ONN 9 /**< it gives the index value of the commands array to exhalation solenoid on*/ #define PK_PR_REL_OFF 10 /**< it gives the index value of the commands array to peak pressure relief off*/ #define PK_PR_REL_ONN 11 /**< it gives the index value of the commands array to peak pressure relief on*/ #define SET_TID_VOL 12 /**< it gives the index value of the commands array to set tidal volume */ #define SET_BPM 13 /**< it gives the index value of the commands array to set BPM */ #define SET_PK_PR 14 /**< it gives the index value of the commands array to set peak pressure*/ #define SET_FIO2 15 /**<it gives the index value of the commands array to set Fio2*/ #define SET_IE_RATIO 16 /**< it gives the index value of the commands array to set inhalation exhalation ratio */ #define SL_EN_PARM_EDT 17 /**< it gives the index value of the commands array to slave entering parameter edit */ #define SL_COM_PARM_EDT 18 /**<it gives the index value of the commands array to slave completed parameter edit */ #define INIT_MASTER 19 /**<it gives the index value of the commands array to initialize master*/ #define INIT_STPR_MOD 20 /**< it gives the index value of the commands array to initialize stepper module*/ #define INIT_VALV_BLK 21 /**<it gives the index value of the commands array to initialize stepper module*/ #define INIT_BREATH_DET 22 /**<it gives the index value of the commands array to initialize breath detection*/ #define SYNCH "SY" #define COMP "01" #define EXPAN "03" /**< Unknown State is used when request structure is valid but makes no sense semantically */ #define VENTSLAVE "VS" /**< Unknown State is used when request structure is valid but makes no sense semantically */ #define START_DELIM '$' /**< Start Delimeter for the Command Structure*/ #define END_DELIM '&' /**< End Delimeter for the Command Structure*/ #define VENT_MAST "VM" /**< String to Identify Whether the request is from Ventilator Master or not*/ #define CMD_PACKET_SIZE 10 /**< Command Packet Data Size*/ #define TV_PARAM "P1" /**Tidal Volume */ /**< String is used to Identify which parameter needs to be Sent.In this case it is 0 param from Params Arrays */ #define RR_PARAM "P2" /**RR */ /**< String is used to Identify which parameter needs to be Sent.In this case it is 1 param from Params Arrays*/ #define IER_PARAM "P5" /**IER*/ /**< String is used to Identify which parameter needs to be Sent.In this case it is 4 param from Params Arrays*/ #define PEAK_PARAM "P6" /**peak*/ #define GP0_PARAM "P7" /** CAL_GP0*/ #define GP1_PARAM "P8" /**CAL_GP1*/ #define PARAMGP_RAW "G1" /**GP0 Raw value*/ #define PARAMGP_PRS "G2" /**GP0 pressure value*/ #define MIN_PRESSURE_FOR_MASKON 15 /** * @enum ControlStatesDef_T * @brief Following are the Control States during which Sensor data and user inputs are compared * to generate specific commands required for that state. */ typedef enum { CTRL_INIT=0, /**< Initiation State*/ CTRL_COMPRESSION, /**< Compression Cycle Start State */ CTRL_COMPRESSION_HOLD, /**< Compression Cycle Hold State */ CTRL_EXPANSION, /**< Expansion Cycle Start State */ CTRL_EXPANSION_HOLD, /**< Expansion Cycle Hold State */ CTRL_INHALE_DETECTION, /**< Inhale Detection State */ CTRL_STOP, /**< Stop state */ CTRL_DO_NOTHING, /**< Idle State */ CTRL_UNKNOWN_STATE, /**< Unknown State is used when request structure is valid but makes no sense semantically */ }ControlStatesDef_T; /**************************************************************************/ /*! @brief Function to create control command @param paramName parameter is used to create command using it. @param value parameter defines the actual to be sent in the command @return indicates Non-Null for SUCCESS and Null for FAILURE */ /**************************************************************************/ String Ctrl_CreateCommand(String paramName, long value); /**************************************************************************/ /*! @brief Function to perform specific operation based on the Current State @return indicates true for SUCCESS and false for FAILURE */ /**************************************************************************/ void Ctrl_StateMachine_Manager(const float *sensor_data, sensorManager &sM, displayManager &dM); /**************************************************************************/ /*! @brief Function to process the received data */ /**************************************************************************/ void Ctrl_ProcessRxData(displayManager &dM); /**************************************************************************/ /*! @brief Function to store the bufferred data into the local variable @param data parameter is the bufferred data */ /**************************************************************************/ void Ctrl_store_received_packet(String data); /**************************************************************************/ /*! @brief Function to send the command from commands array based on the index @param commandIndex parameter is used to index in the commands array @return indicates 0 for SUCCESS and -1 for FAILURE */ /**************************************************************************/ int Ctrl_send_packet(int commandIndex); /**************************************************************************/ /*! @brief Function to send the command based on the parameter and its value @param name parameter is used to send specific parameter @param value parameter is the actual data to be sent @return indicates Non-Null for SUCCESS and Null for FAILURE */ /**************************************************************************/ int Ctrl_send_packet(String name, long value); /**************************************************************************/ /*! @brief Function to change the state to INIT */ /**************************************************************************/ void Ctrl_Start(); /**************************************************************************/ /*! @brief Function to change the state to stop the stepper motor */ /**************************************************************************/ void Ctrl_Stop(); void mcu0_calibrate_sensor(); void mcu0_enable_sensors_pressure(bool en); void mcu0_enable_sensors_voltage(bool en); float mcu0_read_pressure(sensor_e s); int mcu0_read_rawvoltage(sensor_e s); int persist_write_calvalue(sensor_e s, float val); void initCtrlStateControl(void); /**@}*/ #endif /* __STATECONTROL_H__ */
tworkshyd/v2-mcu2
mcu1/control_board.h
<filename>mcu1/control_board.h /**************************************************************************/ /*! @file Variables.h @brief Ventilator Driver Module @author Tworks @defgroup VentilatorModule VentilatorModule Module to initialize and deinitialize the ventilator @{ */ /**************************************************************************/ #ifndef _relayModule_H #define _relayModule_H #include "BoardDefines.h" #define COMP_DIR LOW /*!< Defines the signal at Direction pin of motor driver for CCW rotation */ #define EXP_DIR HIGH /*!< Defines the signal at Direction pin of motor driver for CW rotation */ #define HOME_SENSE_VALUE LOW // 1 for PNP(LED glows when sensed, alway high) //0 for NPN (LED off when sensed, alway low) // 8mm for 3d printing lead screw // 10mm for mtr screws #define LEAD_SCREW_PITCH (10) /*!< Lead screw pitch is 12.0 mm, i.e when we rotate it by 360 degree then the linear travel will be 8.0 mm in a direction */ #define extra_exhale_travel (20.0) #define power_on_home_travel (200.0) #define Start_home_travel (200.0) #define MIN_RPM_NO_ACCEL (250.0) /*!< This setting removes accel/decel in motion profile below mentioned RPM */ #define CURVE_COMP_STEPS (21) /*!< During inhale motor forward motion is broken in 21 pieces to achieve trapozoidal motion profile */ #define CURVE_EXP_STEPS (21) /*!< During exhale motor return motion is broken in 21 pieces to achieve trapozoidal motion profile */ // A0-A15 D54 to D69 #define MOTOR_STEP_PIN 48 /*!< A14 Ouput for motor steps to control position & velocity */ // pulse_motor #define MOTOR_DIR_PIN 49 /*!< A15 Ouput for motor direction control CW/CCW */ #define HOME_SENSOR_PIN 27 /*!< A3 Input for detecting home position for Moving assembly */ #define INHALE_RELEASE_VLV_PIN 34 /*!< Ouput for inhale high pressure release line solenoid On/Off */ // Connector for j6 #define INHALE_VLV_PIN 32 /*!<A10 Ouput for Inhale line solenoid On/Off */ // Connector for j3 #define EXHALE_VLV_PIN 33 /*!< A11 Ouput for Exhale line solenoid On/Off */ // Connector for j4 #define O2Cyl_VLV_PIN 35 /*!< Ouput for Cylinder Oxygen line solenoid On/Off */ // Connector for j8 // For Indication (22-26) #define LED_1_PIN 22 #define LED_2_PIN 23 #define LED_3_PIN 24 #define LED_4_PIN 25 #define LED_5_PIN 26 // #define INDICATOR_LED 36 /*!< Ouput for Indicating which cycle is in progress. ON=Compression & OFF=Expansion */ #define INHALE_GAUGE_PRESSURE 1 #define EXHALE_GUAGE_PRESSURE 0 /*!< Normally Opened Valves */ #define EXHALE_VLV_OPEN() digitalWrite(EXHALE_VLV_PIN, LOW) /*!< Exhale line solenoid valve Open */ #define EXHALE_VLV_CLOSE() digitalWrite(EXHALE_VLV_PIN, HIGH) /*!< Exhale line solenoid valve Close */ #define INHALE_VLV_OPEN() digitalWrite(INHALE_VLV_PIN, LOW) /*!< Inhale line solenoid valve Open */ #define INHALE_VLV_CLOSE() digitalWrite(INHALE_VLV_PIN, HIGH) /*!< Inhale line solenoid valve Close */ /*!< Normally Closed Valves */ #define INHALE_RELEASE_VLV_OPEN() digitalWrite(INHALE_RELEASE_VLV_PIN, HIGH) /*!< Inhale line high pressure release solenoid valve Open */ #define INHALE_RELEASE_VLV_CLOSE() digitalWrite(INHALE_RELEASE_VLV_PIN, LOW) /*!< Inhale line high pressure release solenoid valve Close */ #define O2Cyl_VLV_OPEN() digitalWrite(O2Cyl_VLV_PIN, HIGH) /*!< Cylinder Oxygen line solenoid valve Open */ #define O2Cyl_VLV_CLOSE() digitalWrite(O2Cyl_VLV_PIN, LOW) /*!< Cylinder Oxygen line solenoid valve Close */ #define TV_PARAM "P1" /**Tidal Volume */ #define RR_PARAM "P2" /**RR */ #define IER_PARAM "P5" /**IER*/ #define PEAK_PARAM "P6" /**peak*/ #define GP0_PARAM "P7" /**CAL_GP0*/ #define GP1_PARAM "P8" /**CAL_GP1*/ // temp for providing Stroke length direclty on the fly.. #define STROKE_LENGTH "P9" /**Stroke length*/ #define START_DELIM '$' /**< Start Delimeter for the Command Structure*/ #define END_DELIM '&' /**< End Delimeter for the Command Structure*/ #define VENT_MAST "VS" /**< String to Identify Whether the request is from Ventilator Master or not*/ #define CMD_PACKET_SIZE (10) /**< Command Packet Data Size*/ #define COMP "01" #define EXPAN "03" #define PARAMGP_RAW "G1" /**GP0 Raw value*/ #define PARAMGP_PRS "G2" /**GP0 pressure value*/ bool send_pressure_data = false; bool send_millivolts_data = false; bool perform_calib_gp = false; volatile int Home_attempt_count = 0; volatile int stop_n_return_pulse_count = 0; volatile int O2_line_option = 0; // 0 = O2 cylinder, 1 = O2 Hosp line & 3 = both off volatile bool flag_Serial_requested = false; volatile float compression_min_speed = MIN_RPM_NO_ACCEL; /*!< This setting removes accel/decel in motion profile below mentioned RPM */ volatile float expansion_min_speed = MIN_RPM_NO_ACCEL; /*!< This setting removes accel/decel in motion profile below mentioned RPM */ volatile float micro_stepping = 800.0; /*!< Stepper motor mcro stepping setting, i.e. number of pulses need to rotate shaft by 360 degree */ volatile float run_pulse_count_1_full_movement = micro_stepping; /*!< Based on micro stepping for 360 degree, we need 800 pulses */ volatile float run_pulse_count_1_piece_compression = micro_stepping / 100; /*!< Pulses needed for 1 piece of motion profile */ volatile float run_pulse_count_1_piece_expansion = micro_stepping / 100; /*!< Pulses needed for 1 piece of motion profile */ volatile float home_speed_value = 200.0; /*!< Homing RPM default setting */ volatile float compression_speed = 300.0; /*!< Compression RPM default setting */ volatile float expansion_speed = 200.0; /*!< Expansion RPM default setting */ //this machanisum has 1:2 ratio adjusted formulas to reflect below data after belt ratio volatile int Par_editstat; /*!< Machine State used to run machine in Auto mode when UI goes in Parameter edit mode */ volatile float cycle_time; /*!< Calculated cycle time based on BPM setting */ volatile float inhale_time; /*!< Calculated inhale time based on BPM & IER setting */ volatile float exhale_time; /*!< Calculated exhale time based on BPM & IER setting */ volatile float inhale_hold_time = 0.5; /*!< Calculated inhale hold time based on inhale_hold_percentage & ihale_time setting */ volatile float inhale_hold_percentage = 10; /*!< Set Percentage Value for inhale hold time calculation */ volatile float tidal_volume = 350.0; /*!< Machine runtime Tidal Volume setting to calcualte equivalent Stroke length to compress */ volatile float BPM = 10.0; /*!< Machine runtime BPM setting to calculate cycle time */ volatile float peak_prsur = 40.0; /*!< Machine runtime PIP/PeakPressure/PAW */ volatile float FiO2 = 21.0; /*!< Machine runtime Air+Oxygen Percentage on inhale Line */ volatile float IER = 2.0; /*!< Machine runtime inhale:exhale ratio */ volatile float inhale_ratio = 1.0; /*!< Machine runtime inale ratio part is always 1.0 for us */ volatile float exhale_ratio = 2.0; /*!< Machine runtime exhale ration parts varies from 1 to 3 */ volatile float Stroke_length = 75.0; /*!< Machine runtime Auto calculated Stroke length based on Tidal Volume lookup table created based on our calibration.*/ volatile float Stroke_length_forced = 0.0; volatile float PEEP = 20.0; /*!< Machine runtime minimum PEEP value */ volatile float CAL_GP0 = 0.0; /*!< Machine runtime minimum PEEP value */ volatile float CAL_GP1 = 0.0; /*!< Machine runtime minimum PEEP value */ volatile float PIP = 0.0; volatile float PLAT = 0.0; float vout = 0.0; float pressure = 0.0; float Ipressure = 0.0; float Epressure = 0.0; float IRaw = 0; float ERaw = 0; volatile float tidal_volume_new = 350.0; /*!< User setable Tidal Volume setting to calcualte equivalent Stroke length to compress */ volatile float BPM_new = 10.0; /*!< User setable BPM setting to calculate cycle time */ volatile float IER_new = 2.0; /*!< User setable inhale:exhale ratio */ volatile float inhale_ratio_new = 1.0; /*!< User setable inale ratio part is always 1.0 for us */ volatile float exhale_ratio_new = 2.0; /*!< User setable exhale ration parts varies from 1 to 3 */ volatile float Stroke_length_new = 75.0; /*!< Auto calculated Stroke length based on Tidal Volume lookup table created based on our calibration.*/ volatile float PEEP_new = 20.0; /*!< User setable minimum PEEP value */ volatile float peak_prsur_new = 40.0; /*!< Machine runtime minimum PEEP value */ volatile float CAL_GP0_new = 0.0; /*!< Machine runtime minimum PEEP value */ volatile float CAL_GP1_new = 0.0; /*!< Machine runtime minimum PEEP value */ volatile long OCR1A_var; /*!< Timer OCRxA register value for a required frequency */ volatile long TCCR1B_var; /*!< Timer TCCRxB register value for a required frequency */ volatile float run_pulse_count = 0.0; /*!< Run time calcualted pulses value */ volatile float run_pulse_count_temp = 0.0; /*!< Run time pulses counter */ volatile long motion_profile_count_temp = 0; /*!< Tapoziodal motion profile Piece counter */ volatile float compression_step_array[21]; /*!< inhale pulse count for one piece of motion profile */ volatile float expansion_step_array[21]; /*!< exhale pulse count for one piece of motion profile */ volatile float compression_speed_array[21]; /*!< inhale velocity for one piece of motion profile */ volatile float expansion_speed_array[21]; /*!< exhale velocity for one piece of motion profile */ volatile long TCCR1B_comp_array[21]; /*!< inhale Timer TCCRxB register value for one piece of motion profile */ volatile long OCR1A_comp_array[21]; /*!< inhale Timer OCRxA register value for one piece of motion profile */ volatile long TCCR1B_exp_array[21]; /*!< exhale Timer TCCRxB register value for one piece of motion profile */ volatile long OCR1A_exp_array[21]; /*!< exhale Timer OCRxA register value for one piece of motion profile */ long c_start_millis = 0; /*!< Timer millis value for inhale start */ long c_end_millis = 0; /*!< Timer millis value for inhale stop */ long e_start_millis = 0; /*!< Timer millis value for exhale start */ long e_end_millis = 0; /*!< Timer millis value for exhale stop */ long e_timer_end_millis = 0; /*!< Timer millis value for exhale timer timeout end/stop */ volatile bool Emergency_motor_stop = false; /*!< Flag to stop sending further pulses to motor if value is true */ volatile bool run_motor = false; /*!< Flag to start the exhale or inhale motion profile */ volatile bool cycle_start = false; /*!< Flag to start/stop the machine */ volatile bool home_cycle = false; /*!< Flag to start homing cycle */ volatile bool comp_start = false; /*!< Flag to start inhale cycle */ volatile bool comp_end = false; /*!< Flag to indicates end of inhale cycle */ volatile bool exp_start = false; /*!< Flag to start inhale cycle */ volatile bool exp_end = false; /*!< Flag to indicates end of exhale cycle */ volatile bool exp_timer_end = false; /*!< Flag to indicate exhale timer timeout */ /**************************************************************************/ /*! @brief Function to convert all set parameter values to machine runtime values to execute the compression and expansion cycles. @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool convert_all_set_params_2_machine_values(void); /**************************************************************************/ /*! @brief Function to initialize Exhale cycle on the ventilator @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool Start_exhale_cycle(void); /**************************************************************************/ /*! @brief Function to initialize Inhale cycle on the ventilator @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool Start_inhale_cycle(void); /**************************************************************************/ /*! @brief Function to initialize Inhale cycle skipping the current exhale cycle as there is deman of breadth detected. @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool breathe_detected_skip_exhale_n_start_inhale(void); /**************************************************************************/ /*! @brief Function to stop the exhal time and set the exhale_timer_end flag, so that we can start inhale cycle. @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool Exhale_timer_timout(void); /**************************************************************************/ /*! @brief Function to start homing and initialize/Start the ventilator by setting the Cycle_Start = true.. @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool inti_Home_n_Start(void); /**************************************************************************/ /*! @brief Function to Deinitialize/Stop the ventilator by setting the Cycle_Start = false.. @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool inti_Stop_n_Home(void); /**************************************************************************/ /*! @brief Function to initilaze the timer to generate the square pulses for stepper motor to achieve perticulare RPM. @param rpm paramter to configure the rotation per minute for pushing assembly @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool initialize_timer1_for_set_RPM(float rpm); /**************************************************************************/ /*! @brief Function to Stop the Timer1 and stop all the pulses generate. @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool stop_timer(void); /**************************************************************************/ /*! @brief Function to process the serial command after complete packet is recieved and perform the action. @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool Prcs_RxData(void); /*****************************************************************T*********/ /*! @brief Function to open selected O2 valve when machine starts. @return indicates 0 for SUCCESS and 1 for FAILURE */ /**************************************************************************/ bool open_selected_O2_value(void); bool inti_all_Valves(void); bool inti_Start(void); #endif /**@}*/
Bobobot/Pacman_visualizer
src/map_container.h
<reponame>Bobobot/Pacman_visualizer<gh_stars>0 #pragma once #include <vector> #include <fstream> #include <string> #include <sstream> #include <limits> #include "map.h" class MapContainer { std::vector<Map> allMaps; int currentMapIndex; int width; int height; public: MapContainer(std::string fileName); Map currentMap(); void nextMap(); void previousMap(); int getWidth(); int getHeight(); };
Bobobot/Pacman_visualizer
src/pacman_visualizer.h
<reponame>Bobobot/Pacman_visualizer #pragma once #include <SDL.h> #include <SDL2_gfxPrimitives.h> #include <string> #include <vector> #include <sstream> #include "map.h" #include "point.h" static int const FPSTIMER = 0; //using Maze = std::vector<std::vector<char>>; class PacmanVisualizer { int width, height; SDL_Renderer* renderer; SDL_Window* window; std::string windowTitle = "Pacman"; int tileSize; bool initSDL(); void logErrorSDL(const char* errorMessage); void initTimer(); static Uint32 fpsTimerCallback(Uint32 delay, void * param); public: PacmanVisualizer(int width, int height); void resize(int width, int height); int getTileSize(); void drawMap(Map m); ~PacmanVisualizer(); };
Bobobot/Pacman_visualizer
src/point.h
<gh_stars>0 #pragma once struct Point { int x; int y; };
Bobobot/Pacman_visualizer
src/map.h
<gh_stars>0 #pragma once #include "point.h" class Map { public: int currentTick; int currentDepth; std::vector<std::vector<char>> data; std::vector<Point> pacmanTiles; std::vector<Point> ghostTiles; std::vector<char> operator[](int index) { return data[index]; } int getWidth() { return data.size(); } int getHeight() { return data[0].size(); } void clear() { data.clear(); pacmanTiles.clear(); ghostTiles.clear(); } };
Abellan09/SEI_Project
Jamming/esp8266_deauther-2.1.0/configs/DSTIKE_OLED_v1.5S/A_config.h
#ifndef config_h #define config_h // ===== DISPLAY LIBRARY ===== // #include "SSD1306Wire.h" // =========================== // // ===================== LED CONFIG ==================== // #define NEOPIXEL_LED #define LED_MODE_BRIGHTNESS 10 // brightness of LED modes #define LED_NEOPIXEL_NUM 1 #define LED_NEOPIXEL_PIN 15 #define LED_NEOPIXEL_MODE NEO_GRB + NEO_KHZ800 // ===================== DISPLAY CONFIG ==================== // #define USE_DISPLAY true // default display setting #define BUTTON_UP 12 #define BUTTON_DOWN 13 #define BUTTON_A 14 #define DEAUTHER_DISPLAY SSD1306Wire display = SSD1306Wire(0x3c, 5, 4); // for 0.96" OLED // ========================================================= // #endif
Abellan09/SEI_Project
Jamming/esp8266_deauther-2.1.0/configs/DSTIKE_Wristband_Mini/A_config.h
#ifndef config_h #define config_h // ===== DISPLAY LIBRARY ===== // #include "SH1106Wire.h" // =========================== // // ===================== LED CONFIG ==================== // #define NEOPIXEL_LED #define HIGHLIGHT_LED 16 #define LED_MODE_BRIGHTNESS 10 // brightness of LED modes #define LED_NEOPIXEL_NUM 1 #define LED_NEOPIXEL_PIN 15 #define LED_NEOPIXEL_MODE NEO_GRBW + NEO_KHZ800 // ===================== DISPLAY CONFIG ==================== // #define USE_DISPLAY true // default display setting #define BUTTON_UP 12 #define BUTTON_DOWN 13 #define BUTTON_A 14 #define DEAUTHER_DISPLAY SH1106Wire display = SH1106Wire(0x3c, 5, 4); // for 1.3" OLED // ========================================================= // #endif
Abellan09/SEI_Project
Jamming/esp8266_deauther-2.1.0/configs/MrRobotBadge_Dickbutt_Addon/A_config.h
#ifndef config_h #define config_h // ===== DISPLAY LIBRARY ===== // #include "SSD1306Wire.h" // =========================== // #define DEFAULT_SSID "Dickbutt " + bytesToStr(&(settings.getMacAP()[3]), 3) // ===================== LED CONFIG ==================== // #define DIGITAL_LED #define LED_ANODE false // common vcc (+) #define LED_PIN_R 255 // NodeMCU on-board LED #define LED_PIN_G 255 // 255 = LED disabled #define LED_PIN_B 2 // ESP-12 LED // ===================== DISPLAY CONFIG ==================== // #define USE_DISPLAY false // default display setting #define BUTTON_UP 14 #define BUTTON_DOWN 12 #define BUTTON_A 13 #define DEAUTHER_DISPLAY SSD1306Wire display = SSD1306Wire(0x3c, 5, 4); // for 0.96" OLED // ========================================================= // #endif
wangxaioli/Push
Example/Pushpresent/WLAppDelegate.h
<reponame>wangxaioli/Push // // WLAppDelegate.h // Pushpresent // // Created by <EMAIL> on 09/05/2018. // Copyright (c) 2018 <EMAIL>. All rights reserved. // @import UIKit; @interface WLAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
wangxaioli/Push
Example/Pods/Target Support Files/Pushpresent/Pushpresent-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double PushpresentVersionNumber; FOUNDATION_EXPORT const unsigned char PushpresentVersionString[];
wangxaioli/Push
Example/Pushpresent/WLSecondPresentViewController.h
<reponame>wangxaioli/Push // // WLSecondPresentViewController.h // PresentPush // // Created by wangxiaoli on 2018/9/4. // Copyright © 2018年 Sunshine. All rights reserved. // #import <UIKit/UIKit.h> @interface WLSecondPresentViewController : UIViewController @end
wangxaioli/Push
Example/Pushpresent/UINavigationController+WLNav.h
<reponame>wangxaioli/Push // // UINavigationController+WLNav.h // PresentPush // // Created by wangxiaoli on 2018/9/4. // Copyright © 2018年 Sunshine. All rights reserved. // #import <UIKit/UIKit.h> @interface UINavigationController (WLNav) - (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion; @end
dcrawbuck/Baby-C-Compiler
your_code.c
<gh_stars>0 // <NAME> 2020 // Baby C Compiler #include "your_code.h" #include "symbol_table.h" #include <stdlib.h> #include <stdio.h> #include <string.h> extern void yyerror(const char* s); // Write the implementations of the functions that do the real work here ASTNode* CreateNumNode(int num) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_NUM; node->num = num; return node; } ASTNode* CreateIdentNode(char* name) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_IDENT; node->name = name; Symbol* symbol = lookup(name); if (symbol != NULL) { node->symbol = symbol; } else { yyerror("Ident not declared"); } return node; } // Take a statement node and a statement list node and connect them together // to form a bigger statement list node (add the statement to the statement list). // Return a pointer to the bigger list that resulted from this linking ASTNode* CreateStatementListNode(ASTNode* st, ASTNode* stList) { // Link statement nodes together st->next = stList; return st; } ASTNode* CreateAdditionNode(ASTNode* expr, ASTNode* term) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_ARITH_OP; node->op = ADD_OP; node->left = expr; node->right = term; return node; } ASTNode* CreateSubtractionNode(ASTNode* expr, ASTNode* term) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_ARITH_OP; node->op = SUB_OP; node->left = expr; node->right = term; return node; } ASTNode* CreateMultiplicationNode(ASTNode* term, ASTNode* factor) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_ARITH_OP; node->op = MULT_OP; node->left = term; node->right = factor; return node; } ASTNode* CreateDivisionNode(ASTNode* term, ASTNode* factor) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_ARITH_OP; node->op = DIV_OP; node->left = term; node->right = factor; return node; } ASTNode* CreateAssignmentNode(ASTNode* lhs, ASTNode* expr) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_ASSIGN; node->left = lhs; node->right = expr; return node; } ASTNode* CreateIfNode(ASTNode* cond, ASTNode* body) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_IF; node->left = cond; node->middle = body; return node; } ASTNode* CreateIfElseNode(ASTNode* cond, ASTNode* body, ASTNode* elseNode) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_IF; node->left = cond; node->middle = body; node->right = elseNode; return node; } ASTNode* CreateOrNode(ASTNode* left, ASTNode* right) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_LOGIC_OP; node->left = left; node->right = right; node->op = OR_OP; return node; } ASTNode* CreateAndNode(ASTNode* left, ASTNode* right) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_LOGIC_OP; node->left = left; node->right = right; node->op = AND_OP; return node; } ASTNode* CreateCondNode(ASTNode* left, char* op, ASTNode* right) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_COMPARE; node->left = left; node->right = right; node->name = op; return node; } ASTNode* CreateOpNode(char* op) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_COMPARE; node->name = op; return node; } ASTNode* CreateWhileNode(ASTNode* cond, ASTNode* body) { ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode)); node->type = ASTNODE_WHILE; node->left = cond; node->right = body; return node; } void AddDeclaration(char* name) { Symbol* symbol = lookup(name); if (symbol != NULL) { char error[100]; strcpy(error, "Multiple declarations of "); strcat(error, "'"); strcat(error, name); yyerror(strcat(error, "'")); } else { insertInto(name, 1); } }
dcrawbuck/Baby-C-Compiler
symbol_table.h
// <NAME> 2020 // Baby C Compiler #ifndef SYMBOL_TABLE_H #define SYMBOL_TABLE_H typedef struct Symbol Symbol; struct Symbol { char* name; int value; int offset; }; Symbol** table; void symbolTableInit(); void insertInto(char* name, int value); struct Symbol* lookup(char* name); void resize(); int getHashValue(char* name, int size); #endif
dcrawbuck/Baby-C-Compiler
your_code.h
// <NAME> 2020 // Baby C Compiler #include "symbol_table.h" #ifndef YOUR_CODE_H #define YOUR_CODE_H typedef enum{ASTNODE_ARITH_OP, ASTNODE_LOGIC_OP, ASTNODE_COMPARE, ASTNODE_ASSIGN, ASTNODE_IDENT, ASTNODE_NUM, ASTNODE_IF, ASTNODE_WHILE } ASTNodeType; // Define all operation types (add, mult, etc) here. typedef enum { ADD_OP, SUB_OP, MULT_OP, DIV_OP, OR_OP, AND_OP } ASTOp; typedef struct ASTNode ASTNode; struct ASTNode { ASTNodeType type; ASTOp op; // The actual operation (add, mult, etc) int num; //Need to store the actual value for number nodes char *name; //Need to store the actual variable name for ident nodes ASTNode* left; // Left child ASTNode* right; // Right child ASTNode* middle; // middle child (only used in If/Else) // The following pointer is just a suggestion; you don't have to use it if you have a better design. ASTNode* next; // a pointer used to link statement nodes together in a statement list // Depending on your implementation, you may need to add other fields to this struct Symbol* symbol; }; // Add functions to create the different kinds of ASTNodes // These functions are called by the code embedded in the grammar. // Here are some samples: ASTNode* CreateNumNode(int num); ASTNode* CreateIdentNode(char* name); ASTNode* CreateStatementListNode(ASTNode* st, ASTNode* stList); ASTNode* CreateAdditionNode(ASTNode* expr, ASTNode* term); ASTNode* CreateSubtractionNode(ASTNode* expr, ASTNode* term); ASTNode* CreateMultiplicationNode(ASTNode* term, ASTNode* factor); ASTNode* CreateDivisionNode(ASTNode* term, ASTNode* factor); ASTNode* CreateAssignmentNode(ASTNode* lhs, ASTNode* expr); ASTNode* CreateIfNode(ASTNode* cond, ASTNode* body); ASTNode* CreateIfElseNode(ASTNode* cond, ASTNode* body, ASTNode* elseNode); ASTNode* CreateOrNode(ASTNode* left, ASTNode* right); ASTNode* CreateAndNode(ASTNode* left, ASTNode* right); //ASTNode* CreateCondNode(ASTNode* left, ASTNode* op, ASTNode* right); ASTNode* CreateCondNode(ASTNode* left, char* op, ASTNode* right); ASTNode* CreateOpNode(char* op); ASTNode* CreateWhileNode(ASTNode* cond, ASTNode* body); // Need a function to add a declaration to your symbol table void AddDeclaration(char* name); #endif
dcrawbuck/Baby-C-Compiler
symbol_table.c
// <NAME> 2020 // Baby C Compiler #include "symbol_table.h" #include <stdlib.h> #include <stdio.h> #include <string.h> int items = 0; int size = 100; int offset = 0; int debugPrint = 0; void symbolTableInit() { if(debugPrint) printf("symbolTableInit\n"); table = malloc(sizeof(Symbol*) * size); } void insertInto(char* name, int value) { if(debugPrint) printf("insertInto(%s, %d)\n", name, value); Symbol* symbol = (Symbol*)malloc(sizeof(Symbol)); symbol->name = strdup(name); symbol->value = value; symbol->offset = offset; offset += 4; int hashValue = getHashValue(name, size); while (table[hashValue] != NULL) { hashValue = (hashValue + 1) % size; } table[hashValue] = symbol; items += 1; if (items >= size) { resize(); } } Symbol* lookup(char* name) { if(debugPrint) printf("Symbol_Table.lookup(%s)...", name); int hashValue = getHashValue(name, size); while (table[hashValue] != NULL) { if (strcmp(table[hashValue]->name, name) == 0) { if(debugPrint) printf(" found!\n"); return table[hashValue]; } hashValue = (hashValue + 1) % size; } if(debugPrint) printf(" NOT FOUND\n"); return NULL; } int getHashValue(char* str, int size) { int hash = 0; int i; for (i = *str; i; i = *str++) { hash = (hash * 10) + i; } return hash % size; } void resize() { if(debugPrint) printf("Symbol_Table.resize(), items: %d\n", items); int newSize = size + 5; Symbol** newTable = malloc(sizeof(Symbol*) * newSize); int i; for (i = 0; i < size; i++) { if (table[i] != NULL) { Symbol* symbol = table[i]; int hashValue = getHashValue(symbol->name, newSize); while (newTable[hashValue] != NULL) { hashValue = (hashValue + 1) % newSize; } newTable[hashValue] = symbol; table[i] = NULL; } } size = newSize; table = newTable; free(newTable); }
dcrawbuck/Baby-C-Compiler
driver.c
// <NAME> 2020 // Baby C Compiler #include <stdio.h> #include <stdlib.h> #include "your_code.h" #include "symbol_table.h" #include "code_gen.h" extern FILE* yyin; extern int yyparse(); // A global variable that holds a pointer to the AST root ASTNode* gASTRoot; int main(int argc, char**argv) { if (argc != 2){ printf("ERROR: Invalid number of command-line arguments. Usage: bcc File_Name.bc\n"); exit(1); } yyin = fopen(argv[1], "r" ); if (yyin == NULL){ printf("ERROR: Failed to open the input file\n"); exit(1); } symbolTableInit(); // Call the parser. // Add embedded actions to the parser (in BabyC.y) to construct the AST and store its root in gASTRoot. yyparse(); fclose(yyin); // Now that the AST has been constructed, pass its root to the function that traverses it and generates the ILOC code. GenerateILOC(gASTRoot); }
dcrawbuck/Baby-C-Compiler
code_gen.c
// <NAME> 2020 // Baby C Compiler #include "code_gen.h" #include "your_code.h" #include "symbol_table.h" #include <stdlib.h> #include <stdio.h> #include <string.h> FILE* output; void GenerateILOC(ASTNode* node) { if (node != NULL) { // Create output file "testx.iloc" output = fopen("testx.iloc", "w"); // Start with root node Expr(node); // Close output file fclose(output); } } int Expr(ASTNode* node) { int debugPrint = 0; int t1 = 0, t2 = 0, result = 0, loopCount = 0; Symbol* symbol; if (node != NULL) { // ASTNodeType { ASTNODE_ARITH_OP, ASTNODE_LOGIC_OP, ASTNODE_COMPARE, ASTNODE_ASSIGN, ASTNODE_IDENT, ASTNODE_NUM, ASTNODE_IF, ASTNODE_WHILE } switch (node->type) { case ASTNODE_ARITH_OP: if (debugPrint) fprintf(output, "ASTNODE_ARITH_OP\n"); t1 = Expr(node->left); t2 = Expr(node->right); result = GetNextReg(); fprintf(output, "\t"); // ASTOp { ADD_OP, SUB_OP, MULT_OP, DIV_OP } switch (node->op) { case ADD_OP: fprintf(output, "add"); break; case SUB_OP: fprintf(output, "sub"); break; case MULT_OP: fprintf(output, "mult"); break; case DIV_OP: fprintf(output, "div"); break; default: fprintf(output, "ERROR: Invalid arthimetic operation: %d", node->op); break; } fprintf(output, " r%d, r%d -> r%d\n", t1, t2, result); break; case ASTNODE_LOGIC_OP: if (debugPrint) fprintf(output, "ASTNODE_LOGIC_OP\n"); // TODO: ASTNODE_LOGIC_OP if (node->left == NULL) { fprintf(output, "ERROR: node->left = NULL"); break; } if (node->right == NULL) { fprintf(output, "ERROR: node->right = NULL"); break; } t1 = Expr(node->left); t2 = Expr(node->right); result = GetNextReg(); fprintf(output, "\t"); // ASTOp { AND_OP, OR_OP } switch (node->op) { case AND_OP: fprintf(output, "and"); break; case OR_OP: fprintf(output, "or"); break; default: fprintf(output, "ERROR: Invalid arthimetic operation: %d", node->op); break; } fprintf(output, " r%d, r%d -> r%d\n", t1, t2, result); break; case ASTNODE_COMPARE: if (debugPrint) fprintf(output, "ASTNODE_COMPARE\n"); if (node->left != NULL) { if (debugPrint) fprintf(output, "->LEFT\n"); t1 = Expr(node->left); } else { fprintf(output, "ERROR: node->left = NULL"); break; } if (node->right != NULL) { if (debugPrint) fprintf(output, "->RIGHT\n"); t2 = Expr(node->right); } else { fprintf(output, "ERROR: node->right = NULL"); break; } result = GetNextReg(); fprintf(output, "\tcmp_%s r%d, r%d -> r%d\n", node->name, t1, t2, result); break; case ASTNODE_ASSIGN: if (debugPrint) fprintf(output, "ASTNODE_ASSIGN\n"); if (node->right != NULL) { if (debugPrint) fprintf(output, "->RIGHT\n"); t2 = Expr(node->right); } else { fprintf(output, "ERROR: node->right = NULL"); break; } if (node->left->name == NULL) { fprintf(output, "ERROR: node->left->name = NULL"); break; } symbol = lookup(node->left->name); if (symbol == NULL) { fprintf(output, "ERROR: lookup(node->name) = NULL"); break; } fprintf(output, "\tstoreAI r%d -> rarp, %d\n", t2, symbol->offset); break; case ASTNODE_IDENT: if (debugPrint) fprintf(output, "ASTNODE_IDENT\n"); result = GetNextReg(); symbol = lookup(node->name); if (symbol == NULL) { fprintf(output, "ERROR: lookup(node->name) = NULL"); break; } fprintf(output, "\tloadAI rarp, %d -> r%d\n", symbol->offset, result); break; case ASTNODE_NUM: if (debugPrint) fprintf(output, "ASTNODE_NUM\n"); result = GetNextReg(); fprintf(output, "\tloadi %d -> r%d\n", node->num, result); break; case ASTNODE_IF: if (debugPrint) fprintf(output, "ASTNODE_IF\n"); // TODO: ASTNODE_IF loopCount = GetNextLoopCount(); if (node->left == NULL) { fprintf(output, "ERROR: node->left = NULL"); break; } if (debugPrint) fprintf(output, "->LEFT\n"); // Condition t1 = Expr(node->left); // fprintf(output, "\tcbr r%d -> L%d_T, L%d_M\n", t1, loopCount, loopCount); fprintf(output, "\tcbr r%d -> L%d_T, L%d_", t1, loopCount, loopCount); if (node->right == NULL) { // No else fprintf(output, "M\n"); } else { // Else fprintf(output, "E\n"); } fprintf(output, "L%d_T:\n", loopCount); // THEN if (node->middle == NULL) { fprintf(output, "ERROR: node->middle = NULL"); break; } if (debugPrint) fprintf(output, "->MIDDLE\n"); Expr(node->middle); // ELSE? if (node->right != NULL) { fprintf(output, "\tjumpi -> L%d_M\n", loopCount); fprintf(output, "L%d_E:\n", loopCount); if (debugPrint) fprintf(output, "->RIGHT\n"); Expr(node->right); } fprintf(output, "L%d_M:\n", loopCount); // AFTER (node-> called automatically after switch) break; case ASTNODE_WHILE: if (debugPrint) fprintf(output, "ASTNODE_WHILE\n"); // TODO: ASTNODE_WHILE loopCount = GetNextLoopCount(); // CONDITION fprintf(output, "L%d_C:\n", loopCount); if (node->left == NULL) { fprintf(output, "ERROR: node->left = NULL"); break; } if (debugPrint) fprintf(output, "->LEFT\n"); // Condition t1 = Expr(node->left); fprintf(output, "\tcbr r%d -> L%d_B, L%d_O\n", t1, loopCount, loopCount); // BODY fprintf(output, "L%d_B:\n", loopCount); if (node->right == NULL) { fprintf(output, "ERROR: node->right = NULL"); break; } if (debugPrint) fprintf(output, "->RIGHT\n"); Expr(node->right); fprintf(output, "\tjumpi -> L%d_C\n", loopCount); // AFTER fprintf(output, "L%d_O:\n", loopCount); // (node-> called automatically after switch) break; default: if (debugPrint) fprintf(output, "default\n"); fprintf(output, "node->type: %d\n", node->type); // TODO: Error break; } } // If node is in StatementList then node->next will be not NULL // fprintf(output, "NEXT check\n"); if (node != NULL) { // fprintf(output, ">"); if (node->next != NULL) { // Execute next statement in list if (debugPrint) fprintf(output, "->NEXT\n"); Expr(node->next); } // fprintf(output, "\n"); } return result; } int currentRegister = 0; int GetNextReg() { currentRegister += 1; return currentRegister; } int currentLoopCount = 0; int GetNextLoopCount() { currentLoopCount += 1; return currentLoopCount; }
dcrawbuck/Baby-C-Compiler
code_gen.h
<reponame>dcrawbuck/Baby-C-Compiler<gh_stars>0 // <NAME> 2020 // Baby C Compiler #include "your_code.h" #ifndef CODE_GEN_H #define CODE_GEN_H // This is the function that generates ILOC code after the construction of the AST void GenerateILOC(ASTNode* node); int Expr(ASTNode* node); int GetNextReg(); int GetNextLoopCount(); #endif
PaulBryden/ROVER
src/arduino/libraries/Anansi/Types.h
#ifndef Types_h #define Types_h #include <iterator> #include <vector> using namespace std; typedef unsigned char byte; typedef struct { byte flags : 3; byte messageID : 5; byte targetService; byte sourceService; byte packetID; byte crc; } packet_header_t; typedef struct { byte numOfPacketsInMessage; byte typeOfMessage; byte messageBitfields; } message_header_t; typedef struct { packet_header_t packetHeader; vector<byte> dataContent; } packet_t; #define PACKET_SIZE 64 #define PACKET_HEADER_SIZE sizeof(packet_header_t) #define PACKET_CONTENT_SIZE PACKET_SIZE - PACKET_HEADER_SIZE #define MESSAGE_HEADER_SIZE 3 #endif
PaulBryden/ROVER
src/misc/msg_redundant/msg.h
typedef unsigned short int uint_t; typedef struct { unsigned char flags : 3; unsigned char messageID : 5; unsigned char targetService; unsigned char sourceService; unsigned char packetID; unsigned char CRC; } packet_header_t; typedef struct { unsigned char numOfPacketsInMessage; unsigned char typeOfMessage : 5; unsigned char messageBitfields : 3; } message_header_t; typedef struct { packet_header_t packetHeader; message_header_t messageHeader; unsigned char dataContent[]; } packet_message; typedef struct { packet_header_t packetHeader; unsigned char dataContent[0]; } packet_packet; typedef struct { packet_header_t packetHeader; char *dataContent; } example_packet_t; char *create_message(unsigned char targetService, unsigned char sourceService, char *dataContent, char messageType){ /**DO malloc and crc calculation, and header population here. return pointer to memory location containing packet data. It is then message passing’s responsibility to send the data off. **/ return 0; } void parse_raw_packet(char *rawPacket){ /**extract raw packet data from pointer and populate fields. Also execute relevant function based on parsed data, and pass relevant data to it.**/ return 0; }
PaulBryden/ROVER
src/pi_linux/inc/Service.h
#ifndef Service_h #define Service_h #ifdef NOARDUINO #include <DummyPort.h> #else #include <Port.h> #endif #include <iterator> #include <map> #include <string> class Service { private: byte _id; string _name; std::map<int, int> _portMap; // port id to distance bool _local; public: Service(byte id, string name, bool local); ~Service(); byte getId(); string getName(); int getOutgoingPort(); int getShortestDistance(); void setPortDistance(int port, int distance); void flagPort(int port); std::map<int, int> getPortMap(); }; #endif
PaulBryden/ROVER
src/misc/mpq_old/libraries/Msgs/Msgs.h
#ifndef Msgs_h #define Msgs_h #include "Arduino.h" #include <string> #define NO_OF_SERVICES 256 typedef unsigned short int uint_t; /* typedef struct { uint_t id : 8; char *name; uint_t port : 2; uint_t dist : 4; } service_t; typedef struct { service_t *from; service_t *to; char *content; } message_t; */ class Service { uint_t id; string name; uint_t port; uint_t dist; public: Service(uint_t id, string name, uint_t port, uint_t dist); }; class Message { Service from; Service to; string content; public: Message(); }; class Msgs { public: Msgs(); void readMessage(Message m); bool sendMessage(Message m); private: Service[] _serviceTable; Packet[] messageToPackets(Message m); Packet createPacket(char[] content); bool sendPacket(Packet p); char* serialisePacket(Packet p); bool writePacketToSerial(char[] p); }; #endif
PaulBryden/ROVER
src/pi_linux/inc/PacketQueue.h
#ifndef PacketQueue_h #define PacketQueue_h #include <Types.h> #include <Message.h> #include <iterator> #include <deque> #include <Comms.h> #include <PacketHandler.h> class PacketQueue { deque<packet_t> _queue; public: PacketQueue(); void addPacket(packet_t p); void popPacket(); Message checkPacketQueue(); Message buildMessage(vector<packet_t> p); }; #endif
PaulBryden/ROVER
src/pi_linux/inc/PacketHandler.h
#ifndef PacketHandler_h #define PacketHandler_h #include <Types.h> #ifdef NOARDUINO #include <cstring> #else #endif #include <Port.h> #include <iterator> #include <vector> #include <Comms.h> class PacketHandler { public: packet_t createPacket(byte flags,byte messageID, byte packetID, byte targetService, byte sourceService, vector<byte> dataContent); void sendPacket(packet_t p, int port); bool crcCheck(packet_t p); byte calculateCrc(packet_t p); }; #endif
PaulBryden/ROVER
src/arduino/libraries/Anansi/Comms.h
#ifndef Comms_h #define Comms_h #include <Types.h> #ifndef NOARDUINO #include <Port.h> #else #include <Port.h> #endif #include <MessageQueue.h> #include <ServiceTable.h> #include <iterator> #include <vector> #include <SerialPort.h> //extern PacketHandler handle; #include <PacketQueue.h> class Comms { public: static MessageQueue messageQueue; static ServiceTable serviceTable; static vector<Port*> portList; static PacketQueue packetQueue; Comms(); }; #endif
PaulBryden/ROVER
src/pi_linux/inc/Message.h
#ifndef Message_h #define Message_h #include <Types.h> #include <PacketHandler.h> #include <iterator> #include <vector> #include <deque> class Message { //private: //byte _messageID; //byte _targetService; //byte _sourceService; //vector<byte> _bodyContent; //message_header_t _messageHeader; //byte _typeOfMessage; //byte _messageBitfields; public: Message(byte messageID, byte targetService, byte sourceService, byte typeOfMessage, byte messageBitfields, vector<byte> bodyContent); vector<packet_t> toPackets(); byte _messageID; byte _targetService; byte _sourceService; byte _typeOfMessage; byte _messageBitfields; vector<byte> _bodyContent; void readMessage(); }; #endif
PaulBryden/ROVER
src/arduino/libraries/Anansi/MessageQueue.h
<gh_stars>1-10 #ifndef MessageQueue_h #define MessageQueue_h #include <iterator> #include <deque> #include <Message.h> class MessageQueue { public: void addMessage(Message m); void addPriorityMessage(Message m); deque<Message> getMessageQueue(); Message popMessage(); int queueSize(); }; #endif
PaulBryden/ROVER
src/misc/msg_redundant/msg_test.c
#include <stdio.h> #include <msg.h> #include <stdlib.h> char *generate_ping(char *data){ packet_message *packetTest=malloc(62); int sizeOfBody=1; //packet_packet packetTest; packetTest->packetHeader.flags=0x00; packetTest->packetHeader.messageID=0x01; packetTest->packetHeader.targetService=0xF1; packetTest->packetHeader.sourceService=0xF0; packetTest->packetHeader.packetID=0xF0; packetTest->packetHeader.CRC=0; packetTest->messageHeader.numOfPacketsInMessage=0x01; packetTest->messageHeader.typeOfMessage=0x00; packetTest->messageHeader.messageBitfields=0x00; packetTest->dataContent[0]= 0xF1; for (int i = 1; i < (((64-2)-8)-1); ++i){ packetTest->dataContent[i]=0; } unsigned char * px = (unsigned char*)packetTest; px = ((char*)px); return (char *)px; } int main() { printf("MSG DUMP:\n"); fflush(stdout); //const unsigned char * const px = (unsigned char*)packetTest; char *packetTest =generate_ping(packetTest); const unsigned char * const px = (unsigned char*)packetTest; for (int i = 0; i < (64); ++i){ printf("%02X ", px[i]); fflush(stdout); } /**printf("%x",(char*)&packetTest);*/ return 0; }
PaulBryden/ROVER
src/pi_linux/inc/PortIPAddr.h
<gh_stars>1-10 #ifndef PortIPAddr_h #define PortIPAddr_h #include <iterator> #include <vector> #include <string> #include <Types.h> #include <Port.h> #include <Comms.h> class PortIPAddr : public Port { public: PortIPAddr(int id); void read(); void handleData(char *data, int dataSize); void write(vector<byte> serializedPacket); packet_t getPacketFromBuffer(); }; #endif
PaulBryden/ROVER
src/pi_linux/inc/ServiceTable.h
<reponame>PaulBryden/ROVER #ifndef ServiceTable_h #define ServiceTable_h #include <Service.h> #include <MessageQueue.h> #include <iterator> #include <map> class ServiceTable { private: std::map<byte, Service*> _table; public: ServiceTable(); ~ServiceTable(); Service* getService(byte id); void addService(Service *s); void mergeTable(ServiceTable t); std::map<byte, Service*> getTable(); string toString(); }; #endif
PaulBryden/ROVER
src/pi_linux/inc/DummyPort.h
#ifdef NOARDUINO #ifndef DummyPort_h #define DummyPort_h #include <iterator> #include <vector> #include "Types.h" class Port { private: vector<byte> _buffer; string _serial; public: Port(string serial); Port(); int id; void read(); void write(vector<char> serializedPacket); packet_t getPacketFromBuffer(); }; #endif #endif
PaulBryden/ROVER
src/pi_linux/inc/Comms.h
#ifndef Comms_h #define Comms_h #include <Types.h> #include <Message.h> #include <Message.cpp> #ifndef NOARDUINO #include <Port.h> #else #include <DummyPort.h> #include <Port.h> #endif #include <MessageQueue.h> #include <MessageQueue.cpp> #include <ServiceTable.h> #include <ServiceTable.cpp> #include <Service.h> #include <Service.cpp> #include <iterator> #include <vector> extern PacketHandler handle; static MessageQueue messageQueue; static vector<Port*> portList; static ServiceTable serviceTable; #include <PacketQueue.h> #include <PacketQueue.cpp> static PacketQueue packetQueue; #include <PacketHandler.h> #include <PacketHandler.cpp> class Comms { public: Comms(); void sendMessage(Message m); void checkMessages(); void initialiseNode(std::vector<Port*> serials); }; #endif
PaulBryden/ROVER
src/arduino/avr-stl/include/avr_config.h
/* * avr_config.h * Contains values that you can change to customize the way that the library behaves * * Created on: 1 Jan 2011 * Author: <NAME> */ #ifndef __C4BCBBDE_67BC_4bb4_A5E1_7745E49AF0B6 #define __C4BCBBDE_67BC_4bb4_A5E1_7745E49AF0B6 #include <stdlib.h> namespace avrstl { // default alloc-ahead for vectors. quoting from the SGI docs: // // "It is crucial that the amount of growth is proportional to the current capacity(), // rather than a fixed constant: in the former case inserting a series of elements // into a vector is a linear time operation, and in the latter case it is quadratic." // // If this advice pertains to you, then uncomment the first line and comment out the second. // The default here in avr-land is to assume that memory is scarce. // template<typename T> size_t AvrVectorAllocAhead(size_t oldSize_) { return 2*oldSize_; } template<typename T> size_t AvrVectorAllocAhead(size_t oldSize_) { return 20+oldSize_; } // template<> size_t AvrVectorAllocAhead<char>(size_t oldSize_) { return 20+oldSize_; } // sample specialization for char // minimum buffer size allocated ahead by a deque inline size_t AvrDequeBufferSize() { return 20; } // alloc-ahead additional memory increment for strings. The default SGI implementation will add // the old size, doubling memory each time. We don't have memory to burn, so add 20 types each time template<typename T> size_t AvrStringAllocAheadIncrement(size_t oldSize_) { return 20; } } #endif
PaulBryden/ROVER
src/pi_linux/inc/Port.h
#ifndef Port_h #define Port_h #include <vector> #include "Types.h" class Port { public: vector<byte> _buffer; bool _start_last; bool _end_last; bool _packet_start_rcvd; int _id; virtual void read() =0; virtual void write(vector<byte> serializedPacket) =0; virtual packet_t getPacketFromBuffer() = 0; }; #endif
PaulBryden/ROVER
src/pi_linux/inc/MessageQueue.h
<reponame>PaulBryden/ROVER<gh_stars>1-10 #ifndef MessageQueue_h #define MessageQueue_h #include <Message.h> #include <iostream> class MessageQueue { deque<Message> _queue; public: void addMessage(Message m); void addPriorityMessage(Message m); deque<Message> getMessageQueue(); Message popMessage(); int queueSize(); }; #endif
PaulBryden/ROVER
src/arduino/libraries/Anansi/SerialPort.h
<filename>src/arduino/libraries/Anansi/SerialPort.h #ifndef SerialPort_h #define SerialPort_h #include <Port.h> #include <iterator> #include <HardwareSerial.h> class SerialPort : public Port{ public: SerialPort(int id, HardwareSerial *serial); void read(); void write(vector<byte> serializedPacket); packet_t getPacketFromBuffer(); }; #endif
PaulBryden/ROVER
src/pi_linux/inc/PortPi.h
#ifndef PortPi_h #define PortPi_h #include <iterator> #include <vector> #include <string> #include <Types.h> #include <Port.h> #include <Comms.h> #include <wiringSerial.c> class PortPi : public Port { public: PortPi(int id); void read(); void write(vector<byte> serializedPacket); packet_t getPacketFromBuffer(); }; #endif
lylwo317/redis-3.0-annotated
deps/hiredis/fmacros.h
#ifndef __HIREDIS_FMACRO_H #define __HIREDIS_FMACRO_H #if !defined(_BSD_SOURCE) #define _BSD_SOURCE #endif #if defined(__sun__) #define _POSIX_C_SOURCE 200112L #elif defined(__linux__) || defined(__OpenBSD__) || defined(__NetBSD__) #define _XOPEN_SOURCE \ 600 // 使用统一标准的函数行为。https://pubs.opengroup.org/onlinepubs/009695399/ #else #define _XOPEN_SOURCE #endif #endif
forwardkth/leetcode
first_round/hard/include/minimum_window_substring_76.h
<reponame>forwardkth/leetcode<filename>first_round/hard/include/minimum_window_substring_76.h // Given two strings s and t of lengths m and n respectively, //return the minimum window substring of s such that every character // in t (including duplicates) is included in the window. // If there is no such substring, return the empty string "". // The testcases will be generated such that the answer is unique. // A substring is a contiguous sequence of characters within the string. // Example 1: // Input: s = "ADOBECODEBANC", t = "ABC" // Output: "BANC" // Explanation: The minimum window substring "BANC" includes // 'A', 'B', and 'C' from string t. // Example 2: // Input: s = "a", t = "a" // Output: "a" // Explanation: The entire string s is the minimum window. // Example 3: // Input: s = "a", t = "aa" // Output: "" // Explanation: Both 'a's from t must be included in the window. // Since the largest window of s only has one 'a', return empty string. // Constraints: // m == s.length // n == t.length // 1 <= m, n <= 10 5cifang // s and t consist of uppercase and lowercase English letters. // Follow up: Could you find an algorithm that runs in O(m + n) time? //double pointers - sliding window #pragma once #include <vector> #include <algorithm> #include <numeric> using namespace std; class Solution { public: string minWindow(string s, string t) { } };
forwardkth/leetcode
first_round/easy/include/valid_parentheses_20.h
<gh_stars>1-10 // Given a string s containing just the characters '(', ')', '{', '}', // '[' and ']', determine if the input string is valid. // An input string is valid if: // Open brackets must be closed by the same type of brackets. // Open brackets must be closed in the correct order. // Example 1: // Input: s = "()" // Output: true // Example 2: // Input: s = "()[]{}" // Output: true // Example 3: // Input: s = "(]" // Output: false // Example 4: // Input: s = "([)]" // Output: false // Example 5: // Input: s = "{[]}" // Output: true // Constraints: // 1 <= s.length <= 10的四次方 // s consists of parentheses only '()[]{}'. #pragma once #include <string> #include <stack> using namespace std; // use stack class Solution { public: bool isValid(string s) { if(s.length() < 1 || s.length() % 2 != 0) { return false; } stack<char> stk; for(auto i : s) { if(i == '[' or i== '{' or i == '(') { stk.push(i); } else if(stk.empty() or (stk.top() == '[' and i != ']') or (stk.top() == '{' and i != '}') or (stk.top() == '(' and i != ')')) { return false; } else { stk.pop(); } } return stk.empty(); } };
forwardkth/leetcode
first_round/hard/include/candy_135.h
// There are n children standing in a line. Each child is assigned a rating // value given in the integer array ratings. // You are giving candies to these children subjected to the following // requirements: // Each child must have at least one candy. // Children with a higher rating get more candies than their neighbors. // Return the minimum number of candies you need to have to distribute // the candies to the children. // Example 1: // Input: ratings = [1,0,2] // Output: 5 // Explanation: You can allocate to the first, second and third child // with 2, 1, 2 candies respectively. // Example 2: // Input: ratings = [1,2,2] // Output: 4 // Explanation: You can allocate to the first, second and third child // with 1, 2, 1 candies respectively. // The third child gets 1 candy because it satisfies the above two conditions. // Constraints: // n == ratings.length // 1 <= n <= 2 * 10 4次方 // 0 <= ratings[i] <= 2 * 10 4次方 //greedy 贪心算法 #pragma once #include <vector> #include <algorithm> #include <numeric> using namespace std; class Solution { public: int candy(vector<int>& ratings) { auto size = ratings.size(); if(size < 2) return size; vector<int> candy_nums(size, 1); for(size_t i = 1; i < size; ++i) { if(ratings[i] > ratings[i - 1]) { candy_nums[i] = candy_nums[i - 1] + 1; } } for(size_t j = size - 1; j > 0; --j) //not! size can == 2 { if(ratings[j - 1] > ratings[j]) { // note this case in test case candy_nums[j - 1] = max(candy_nums[j] + 1, candy_nums[j - 1]); } } return accumulate(candy_nums.begin(), candy_nums.end(), 0); } };
forwardkth/leetcode
first_round/easy/include/add_two_nums.h
<gh_stars>1-10 /* * AddTwoNumsSolution.h * * Created on: Jan 29, 2019 * Author: chao */ //Description: //You are given two non-empty linked lists representing two non-negative integers. //The digits are stored in reverse order and each of their nodes contain a single digit. //Add the two numbers and return it as a linked list. // //You may assume the two numbers do not contain any leading zero, except the number 0 itself. // //Example: //Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) //Output: 7 -> 0 -> 8 //Explanation: 342 + 465 = 807. #pragma once #include <memory> using namespace std; //definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; class AddTwoNumsSolution1 { public: ListNode* AddTwoNums(ListNode* l1, ListNode* l2) { int carry = 0; ListNode* presult = new ListNode(0); ListNode *tresult = presult; for (ListNode *pl1 = l1, *pl2 = l2; ((pl2 != nullptr) || (pl1 != nullptr)); pl1 = (pl1 == nullptr ? nullptr : pl1->next), pl2 = ( pl2 == nullptr ? nullptr : pl2->next), presult = presult->next) { int vl1 = (pl1 == nullptr ? 0 : pl1->val); int vl2 = (pl2 == nullptr ? 0 : pl2->val); int vsum = (vl1 + vl2 + carry) % 10; carry = (vl1 + vl2 + carry) / 10; presult->next = new ListNode(vsum); } if (carry > 0) { presult->next = new ListNode(carry); } ListNode *rtresult = tresult->next; delete tresult; return rtresult; } }; //using the shared_ptr void deleteNode(ListNode* lx) { ListNode* node = lx; while(lx -> next != nullptr) { ListNode* node = lx; lx = lx -> next; delete node; } if(lx -> next == nullptr) { delete node; } }
forwardkth/leetcode
first_round/easy/include/longest_common_prefix_14.h
// Write a function to find the longest common prefix string amongst // an array of strings. // If there is no common prefix, return an empty string "". // Example 1: // Input: strs = ["flower","flow","flight"] // Output: "fl" // Example 2: // Input: strs = ["dog","racecar","car"] // Output: "" // Explanation: There is no common prefix among the input strings. // Constraints: // 1 <= strs.length <= 200 // 0 <= strs[i].length <= 200 // strs[i] consists of only lower-case English letters. #pragma once #include <unordered_map> #include <string> #include <vector> using namespace std; class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(0 == strs.size()) { string s{}; return s; } long unsigned int lenth_min = 200; string min_str{""}; for(vector<string>::iterator iter = strs.begin(); iter != strs.end(); ++iter) { if((*iter).length() < lenth_min) { lenth_min = (*iter).length(); min_str = (*iter); } } string result{""}; for(long unsigned int index = 0 ; index < lenth_min ; ++index) { for(vector<string>::iterator iter = strs.begin(); iter != strs.end(); ++iter) { if(min_str[index] != (*iter)[index]) { return result; } } result += min_str[index]; } return result; } };
forwardkth/leetcode
first_round/easy/include/merge_sorted_array_88.h
<reponame>forwardkth/leetcode<gh_stars>1-10 //88. Merge Sorted Array // You are given two integer arrays nums1 and nums2, sorted in non-decreasing // order, and two integers m and n, representing the number of elements in // nums1 and nums2 respectively. // Merge nums1 and nums2 into a single array sorted in non-decreasing order. // The final sorted array should not be returned by the function, // but instead be stored inside the array nums1. To accommodate this, // nums1 has a length of m + n, where the first m elements denote the elements // that should be merged, and the last n elements are set to 0 and // should be ignored. nums2 has a length of n. // Example 1: // Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 // Output: [1,2,2,3,5,6] // Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. // The result of the merge is [1,2,2,3,5,6] with the underlined elements coming // from nums1. // Example 2: // Input: nums1 = [1], m = 1, nums2 = [], n = 0 // Output: [1] // Explanation: The arrays we are merging are [1] and []. // The result of the merge is [1]. // Example 3: // Input: nums1 = [0], m = 0, nums2 = [1], n = 1 // Output: [1] // Explanation: The arrays we are merging are [] and [1]. // The result of the merge is [1]. // Note that because m = 0, there are no elements in nums1. // The 0 is only there to ensure the merge result can fit in nums1. // Constraints: // nums1.length == m + n // nums2.length == n // 0 <= m, n <= 200 // 1 <= m + n <= 200 // -109 <= nums1[i], nums2[j] <= 10 9 cifang //double pointer 太巧妙了 #pragma once #include<vector> using namespace std; class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int ptr = m-- + n-- -1; while(m >=0 and n >= 0) { nums1[ptr--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; } while(n >= 0) { nums1[ptr--] = nums2[n--]; } } };
forwardkth/leetcode
first_round/easy/include/add_two_nums_smartptr.h
<reponame>forwardkth/leetcode<filename>first_round/easy/include/add_two_nums_smartptr.h /* * AddTwoNumsSolutionSmartPtr.h * * Created on: Feb 4, 2019 * Author: <NAME> */ //Description: //You are given two non-empty linked lists representing two non-negative integers. //The digits are stored in reverse order and each of their nodes contain a single digit. //Add the two numbers and return it as a linked list. // //You may assume the two numbers do not contain any leading zero, except the number 0 itself. // //Example: //Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) //Output: 7 -> 0 -> 8 //Explanation: 342 + 465 = 807. #pragma once #include <gtest/gtest.h> #include <memory> using namespace std; //definition for singly-linked list. //shared_ptr version struct ListNodeShared { int val; std::shared_ptr<ListNodeShared> next; ListNodeShared(int x) : val(x), next(nullptr) { } }; // "next" pointer uses the smart_ptr class AddTwoNumsSolution2 { public: ListNodeShared* AddTwoNums(ListNodeShared* l1, ListNodeShared* l2) { int carry = 0; std::shared_ptr<ListNodeShared> presult = make_shared<ListNodeShared>(0); std::shared_ptr<ListNodeShared> tresult(presult); for (ListNodeShared *pl1 = l1, *pl2 = l2; ((pl2 != nullptr) || (pl1 != nullptr)); pl1 = (pl1 == nullptr ? nullptr : pl1->next.get()), pl2 = ( pl2 == nullptr ? nullptr : pl2->next.get()), presult = presult.get() ->next) { int vl1 = (pl1 == nullptr ? 0 : pl1->val); int vl2 = (pl2 == nullptr ? 0 : pl2->val); int vsum = (vl1 + vl2 + carry) % 10; carry = (vl1 + vl2 + carry) / 10; presult->next = make_shared<ListNodeShared>(vsum); } if (carry > 0) { presult->next = make_shared<ListNodeShared>(carry); } ListNodeShared *rtresult = tresult->next.get(); return rtresult; } }; // fully uses the smart_ptr class AddTwoNumsSolution3 { public: shared_ptr<ListNodeShared> AddTwoNums(shared_ptr<ListNodeShared> l1, shared_ptr<ListNodeShared> l2) { int carry = 0; std::shared_ptr<ListNodeShared> presult = make_shared<ListNodeShared>(0); std::shared_ptr<ListNodeShared> tresult(presult); for (shared_ptr<ListNodeShared> pl1 = l1, pl2 = l2; ((pl2 != nullptr) || (pl1 != nullptr)); pl1 = (pl1 == nullptr ? nullptr : pl1->next), pl2 = ( pl2 == nullptr ? nullptr : pl2->next), presult = presult->next) { int vl1 = (pl1 == nullptr ? 0 : pl1->val); int vl2 = (pl2 == nullptr ? 0 : pl2->val); int vsum = (vl1 + vl2 + carry) % 10; carry = (vl1 + vl2 + carry) / 10; presult->next = make_shared<ListNodeShared>(vsum); } if (carry > 0) { presult->next = make_shared<ListNodeShared>(carry); } return tresult->next; } };
forwardkth/leetcode
first_round/easy/include/palindrome_number_9.h
// Given an integer x, return true if x is palindrome integer. // An integer is a palindrome when it reads the same backward as forward. //For example, 121 is palindrome while 123 is not. // Example 1: // Input: x = 121 // Output: true // Example 2: // Input: x = -121 // Output: false // Explanation: From left to right, it reads -121. From right to left, // it becomes 121-. Therefore it is not a palindrome. // Example 3: // Input: x = 10 // Output: false // Explanation: Reads 01 from right to left. Therefore it is not a palindrome. // Example 4: // Input: x = -101 // Output: false // Constraints: // -231 <= x <= 231 - 1 #pragma once class Solution { public: bool isPalindrome(int x) { if(x < 0) { return false; } int origin_num = x; long int result_num = 0; while(x - (x % 10) != 0) { result_num *= 10; result_num += (x % 10); x = (x - (x % 10)) / 10; } result_num = result_num * 10 + x; if(origin_num == result_num) { return true; } else { return false; } } };
forwardkth/leetcode
first_round/easy/include/assign_cookies_455.h
<gh_stars>1-10 // Assume you are an awesome parent and want to give your children some cookies. // But, you should give each child at most one cookie. // Each child i has a greed factor g[i], which is the minimum size of a cookie // that the child will be content with; and each cookie j has a size s[j]. // If s[j] >= g[i], we can assign the cookie j to the child i, // and the child i will be content. Your goal is to maximize the number of your // content children and output the maximum number. // Example 1: // Input: g = [1,2,3], s = [1,1] // Output: 1 // Explanation: You have 3 children and 2 cookies. The greed factors of // 3 children are 1, 2, 3. // And even though you have 2 cookies, since their size is both 1, // you could only make the child whose greed factor is 1 content. // You need to output 1. // Example 2: // Input: g = [1,2], s = [1,2,3] // Output: 2 // Explanation: You have 2 children and 3 cookies. // The greed factors of 2 children are 1, 2. // You have 3 cookies and their sizes are big enough to gratify // all of the children, // You need to output 2. // Constraints: // 1 <= g.length <= 3 * 10 4次方 // 0 <= s.length <= 3 * 10 4次方 // 1 <= g[i], s[j] <= 231 - 1 //greedy 贪心算法 #pragma once #include <vector> #include <algorithm> using namespace std; class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(), g.end()); sort(s.begin(), s.end()); unsigned long int i = 0; unsigned long int j = 0; while(i < g.size() and j < s.size()) { if(s[j] >= g[i]) { ++i; } ++j; } return i; } };
forwardkth/leetcode
first_round/medium/include/linked_list_cycle_II_142.h
// Given the head of a linked list, return the node where the cycle begins. // If there is no cycle, return null. // There is a cycle in a linked list if there is some node in the list // that can be reached again by continuously following the next pointer. // Internally, pos is used to denote the index of the node that tail's // next pointer is connected to (0-indexed). It is -1 if there is no cycle. // Note that pos is not passed as a parameter. // Do not modify the linked list. // Example 1: // Input: head = [3,2,0,-4], pos = 1 // Output: tail connects to node index 1 // Explanation: There is a cycle in the linked list, // where tail connects to the second node. // Example 2: // Input: head = [1,2], pos = 0 // Output: tail connects to node index 0 // Explanation: There is a cycle in the linked list, // where tail connects to the first node. // Example 3: // Input: head = [1], pos = -1 // Output: no cycle // Explanation: There is no cycle in the linked list. // Constraints: // The number of the nodes in the list is in the range [0, 10 4cifang]. // -105 <= Node.val <= 10 5 cifang // pos is -1 or a valid index in the linked-list. // Follow up: Can you solve it using O(1) (i.e. constant) memory? // 对于链表找环路的问题,有一个通用的解法——快慢指针(Floyd 判圈法)。 #pragma once #include <vector> #include <algorithm> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode* fast_ptr = head; ListNode* slow_ptr = head; do { if(fast_ptr == nullptr || fast_ptr -> next == nullptr) { return nullptr; } fast_ptr = fast_ptr -> next -> next; slow_ptr = slow_ptr -> next; } while(fast_ptr != slow_ptr); fast_ptr = head; while(fast_ptr != slow_ptr) { fast_ptr = fast_ptr -> next; slow_ptr = slow_ptr -> next; } return fast_ptr; } };
forwardkth/leetcode
first_round/easy/include/roman_to_integer_13.h
<filename>first_round/easy/include/roman_to_integer_13.h // Roman numerals are represented by seven different symbols: // I, V, X, L, C, D and M. // Symbol Value // I 1 // V 5 // X 10 // L 50 // C 100 // D 500 // M 1000 // For example, 2 is written as II in Roman numeral, // just two one's added together. 12 is written as XII, which is simply X + II. // The number 27 is written as XXVII, which is XX + V + II. // Roman numerals are usually written largest to smallest from left to right. // However, the numeral for four is not IIII. // Instead, the number four is written as IV. // Because the one is before the five we subtract it making four. // The same principle applies to the number nine, which is written as IX. // There are six instances where subtraction is used: // I can be placed before V (5) and X (10) to make 4 and 9. // X can be placed before L (50) and C (100) to make 40 and 90. // C can be placed before D (500) and M (1000) to make 400 and 900. // Given a roman numeral, convert it to an integer. // Example 1: // Input: s = "III" // Output: 3 // Example 2: // Input: s = "IV" // Output: 4 // Example 3: // Input: s = "IX" // Output: 9 // Example 4: // Input: s = "LVIII" // Output: 58 // Explanation: L = 50, V= 5, III = 3. // Example 5: // Input: s = "MCMXCIV" // Output: 1994 // Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. #pragma once #include<unordered_map> #include<string> using namespace std; class Solution { public: int romanToInt(string s) { if( 0 == s.size()) { return 0; } unordered_map<char, int> roman_map { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000} }; int result = 0; int previous_num = 0; for(int i = s.size() - 1; i >= 0; --i) { if(roman_map[s[i]] >= previous_num) { result += roman_map[s[i]]; previous_num = roman_map[s[i]]; } else { result -= roman_map[s[i]]; previous_num = roman_map[s[i]]; } } return result; } };
forwardkth/leetcode
first_round/easy/include/two_sum_II_167.h
<gh_stars>1-10 // 167. Two Sum II - Input Array Is Sorted // Given a 1-indexed array of integers numbers that is already sorted // in non-decreasing order, find two numbers such that they add up to // a specific target number. Let these two numbers be numbers[index1] and // numbers[index2] where 1 <= index1 < index2 <= numbers.length. // Return the indices of the two numbers, index1 and index2, // added by one as an integer array [index1, index2] of length 2. // The tests are generated such that there is exactly one solution. // You may not use the same element twice. // Example 1: // Input: numbers = [2,7,11,15], target = 9 // Output: [1,2] // Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. // We return [1, 2]. // Example 2: // Input: numbers = [2,3,4], target = 6 // Output: [1,3] // Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. // We return [1, 3]. // Example 3: // Input: numbers = [-1,0], target = -1 // Output: [1,2] // Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. // We return [1, 2]. // Constraints: // 2 <= numbers.length <= 3 * 10 4cifang // -1000 <= numbers[i] <= 1000 // numbers is sorted in non-decreasing order. // -1000 <= target <= 1000 // The tests are generated such that there is exactly one solution. #pragma once #include<vector> using namespace std; class Solution1 //time limit exceeded { public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> result; for(vector<int>::iterator iter1 = numbers.begin(); iter1 != numbers.end() - 1; ++iter1) { for(vector<int>::iterator iter2 = iter1 + 1; iter2 != numbers.end(); ++iter2) { if(*iter2 == target - *iter1) { result.push_back(std::distance(numbers.begin(), iter1) + 1); result.push_back(std::distance(numbers.begin(), iter2) + 1); } } } return result; } }; class Solution2 { public: vector<int> twoSum(vector<int>& numbers, int target) { int left = 0; int right = numbers.size() -1; int sum = 0; while(left < right) { sum = numbers[left] + numbers[right]; if(sum == target) { break; } else if(sum < target) { ++left; } else if(sum > target) { --right; } } vector<int> result{left + 1, right + 1}; return result; } };
forwardkth/leetcode
first_round/medium/include/non_overlapping_intervals_435.h
// Given an array of intervals intervals where intervals[i] = [starti, endi], // return the minimum number of intervals you need to remove to make // the rest of // the intervals non-overlapping. // Example 1: // Input: intervals = [[1,2],[2,3],[3,4],[1,3]] // Output: 1 // Explanation: [1,3] can be removed and the rest of the intervals are // non-overlapping. // Example 2: // Input: intervals = [[1,2],[1,2],[1,2]] // Output: 2 // Explanation: You need to remove two [1,2] to make the rest of the intervals // non-overlapping. // Example 3: // Input: intervals = [[1,2],[2,3]] // Output: 0 // Explanation: You don't need to remove any of the intervals since // they're already non-overlapping. // Constraints: // 1 <= intervals.length <= 10 5次方 // intervals[i].length == 2 // -5 * 10 4次方 <= starti < endi <= 5 * 10 4次方 //greedy 贪心算法 #pragma once #include <vector> #include <algorithm> using namespace std; class Solution { public: int eraseOverlapIntervals(vector<vector<int>>& intervals) { size_t size = intervals.size(); if(0 == size) { return 0; } sort(intervals.begin(), intervals.end(), [](vector<int> a, vector<int> b) { return (a[1] < b[1]); }); int counter = 0; int previous_end = intervals[0][1]; for(size_t i = 1; i < size; ++i) { if(intervals[i][0] < previous_end) { ++counter; } else { previous_end = intervals[i][1]; } } return counter; } };
forwardkth/leetcode
first_round/easy/include/two_sum_1.h
/* * TwoSumSolution.h * * Created on: Jan 29, 2019 * Author: chao */ //Description: //Given an array of integers, return indices of the two numbers such that they //add up to a specific target. // //You may assume that each input would have exactly one solution, and you may //not use the same element twice. // //Example: // //Given nums = [2, 7, 11, 15], target = 9, // //Because nums[0] + nums[1] = 2 + 7 = 9, //return [0, 1]. #pragma once #include<vector> #include<string> #include<unordered_map> class TwoSumSolution1 { public: std::vector<int> twoSum(std::vector<int>& nums, int target) { std::unordered_map<int, int> num_map; for (size_t i = 0; i < nums.size(); ++i) { num_map[nums[i]] = i; } std::vector<int> result; for (size_t i = 0; i < nums.size(); ++i) { int diff = target - nums[i]; if (num_map.find(diff) != num_map.end() && (unsigned int) num_map[diff] != i) { result.push_back(i); result.push_back(num_map[diff]); return result; } } std::string s("there is no TwoSum solution!"); throw s; } };
cdalvaro2/Vibration-Normal-Modes-2D
computational-physics/graphics/MyOpenGL.h
// // MyOpenGL.h // Vibration Normal Modes 2D // // Created by <NAME> on 5/8/12. // Copyright (c) 2012 NEPTUNO. All rights reserved. // #pragma once #include <string> #include "../math/containers/vector.hpp" #include "../math/containers/matrix.hpp" // OPENGL namespace cda { namespace graphics { // OPENGL - CLASS #define Points 0x01 #define Lines 0x02 #define Shading 0x04 #define Axis_On 0x08 #define Rot_D 0x01 #define Zoom_D 0x02 #define WN_D 0x04 #define dt_D 0x08 #define WSize_D 0x10 #define Update_D 0x20 #define SetDefault 0x40 class OpenGL { private: float _rotX, _rotY, _rotZ; float _zoomX, _zoomY, _zoomZ; float _up_down, _left_right; float _limXmin, _limYmin, _limZmin, _limXmax, _limYmax, _limZmax; float _cX, _cY, _cZ; float _red, _green, _blue; float _vMax, _vMin; math::containers::Vector<double> _vX, _vY, _vZ; math::containers::Matrix<double> _mZ; void (* _updateData)(); public: // Plot options unsigned char _options; std::string _windowName; int _dt, _plots_calc; float _W, _H; // Init class static void initRendering(); // Set params static void setData(const math::containers::Vector<double> &x, const math::containers::Vector<double> &y, unsigned char setDefault); static void setData(const math::containers::Vector<double> &x, const math::containers::Vector<double> &y); static void setData(const math::containers::Vector<double> &x, const math::containers::Vector<double> &y, const math::containers::Vector<double> &z); static void setData(const math::containers::Vector<double> &x, const math::containers::Vector<double> &y, const math::containers::Vector<double> &z, unsigned char setDefault); static void setData(const math::containers::Vector<double> &x, const math::containers::Vector<double> &y, const math::containers::Matrix<double> &z); static void setData(const math::containers::Vector<double> &x, const math::containers::Vector<double> &y, const math::containers::Matrix<double> &z, unsigned char setDefault); // Set adjustments static void setColors(float red, float green, float blue); static void setZoomsD(float zoomX, float zoomY, unsigned char setDefault); static void setZooms(float zoomX, float zoomY); static void setZoomsD(float zoomX, float zoomY, float zoomZ, unsigned char setDefault); static void setZooms(float zoomX, float zoomY, float zoomZ); static void setAxisDirection(float rotX, float rotY, float rotZ, unsigned char setDefault); static void setAxisDirection(float rotX, float rotY, float rotZ); static void setStepTime(float dt_milli, unsigned char setDefault); static void setStepTime(float dt_milli); static void setWindowSize(float Width, float Height, unsigned char setDefault); static void setWindowSize(float Width, float Height); static void setUpdateData(void updateData(), unsigned char setDefault); static void setUpdateData(void updateData()); static void setWindowName(std::string windowName, unsigned char setDefault); static void setWindowName(std::string windowName); static void setDefaultParameters(unsigned char params); // Plot functions static void reshape2D(int Width, int Height); static void reshape3D(int Width, int Height); static void refreshCameraPosition(int value); // -- 2D functions -- static void display2D(); static void drawSolution2D(); static void timerFunction2D(int value); static void plotAxes2D(); static void center2D(); // -- 3D functions static void display3D(); static void drawSolution3D(); static void timerFunction3D(int value); static void plotAxes3D(); static void center3D(); // Keyboard and mouse functions #define UP 0x01 #define DOWN 0x02 #define RIGHT 0x04 #define LEFT 0x08 #define Z_in 0x10 #define Z_out 0x20 #define A_ 0x40 #define D_ 0x80 static void handleKeyPress(unsigned char key, int x, int y); static void handleKeyRelease(unsigned char key, int x, int y); static void handleSpecialKeyPress(int key, int x, int y); static void handleSpecialKeyReleased(int key, int x, int y); }; // COLORMAPS FOR OPENGL - CLASS #define JET 0x01 #define HOT_to_COLD 0x02 #define COOL 0x04 #define WINTER 0x08 #define HOT 0x10 #define SUMMER 0x20 #define JET_FIXED 0x40 class ColorMap { private: static float red, green, blue; static void Jet(float value, float min, float max); static void Hot_to_Cold(float value, float min, float max); static void Cool(float value, float min, float max); static void Winter(float value, float min, float max); static void Hot(float value, float min, float max); static void Summer(float value, float min, float max); static void Jet_Fixed(float value, float min, float max); public: static unsigned char colormap; static void setColor(float value, float min, float max); }; // PLOT FUNCTIONS - NAMESPACE void plot(math::containers::Vector<double> &x, math::containers::Vector<double> &y, unsigned char options, int argc, const char *argv[]); void plot(math::containers::Vector<double> &x, math::containers::Vector<double> &y, math::containers::Vector<double> &z, unsigned char options, int argc, const char *argv[]); void plot(const math::containers::Vector<double> &x, const math::containers::Vector<double> &y, const math::containers::Matrix<double> &z, unsigned char options, int argc, const char *argv[]); } }
cdalvaro2/Vibration-Normal-Modes-2D
Tests/TestsTools.h
// // TestsTools.h // Computational Physics // // Created by <NAME> on 15/06/2018. // Copyright © 2018 cdalvaro. All rights reserved. // #ifndef TestsTools_h #define TestsTools_h #define TESTS_TOOLS_DEFAULT_ACCURACY 1E-13 #import "../computational-physics/math/containers.hpp" @interface TestsTools : NSObject + (void)setDefaultWorkingDirectory; + (BOOL)compareMatrix: (cda::math::containers::Matrix<double>) compare withExpected: (cda::math::containers::Matrix<double>) expected whitAccuracy: (double) accuracy; + (BOOL)compareVector: (cda::math::containers::Vector<double>) compare withExpected: (cda::math::containers::Vector<double>) expected whitAccuracy: (double) accuracy; @end #endif /* Tools_h */
cdalvaro2/Vibration-Normal-Modes-2D
computational-physics/math/differential_equations/SolveEDP.h
<filename>computational-physics/math/differential_equations/SolveEDP.h // // Solve.h // Vibration Normal Modes 2D // // Created by <NAME> on 5/8/12. // Copyright (c) 2012 NEPTUNO. All rights reserved. // #pragma once // BOUNDARY CONDITIONS // Condiciones en la función #define BCL_f 0x01 // BCL - Boundary condition left #define BCR_f 0x02 // BCR - Boundary condition right #define BCT_f 0x04 // BCT - Boundary condition top #define BCB_f 0x08 // BCB - Boundary condition bottom // Condiciones en la derivada #define BCL_df 0x10 #define BCR_df 0x20 #define BCT_df 0x40 #define BCB_df 0x80 // Condición de contorno interior especial #define BCI_f 0x10 // BCI - Boundary condition intern // OPTIONS #define ITERATIONS 0x01 // Mostrará el número de iteraciones realizadas por el método. #define SAVE_DATA 0x02 #define IMPORT_DATA 0x04 #define PLOT_MATLAB 0x08 // Devolverá dos archivos en la ruta indicada, un .csv con los datos // y un .m con las instrucciones para pintar en MATLAB #define DESKTOP 0x10 #define DOCUMENTS 0x20 // Para el método de integración de diferencias finitas #define LUmethod 0x20 #define GSmethod 0x40 #include <iostream> #include <iomanip> #include <cmath> #include <fstream> #include "../containers.hpp" namespace cda { namespace math { namespace differential_equations { typedef double EDP_T; class EDP { private: // ECUACIÓN DE ONDAS // Para almacenar la situación anterior. containers::Vector<EDP_T> old1D; containers::Matrix<EDP_T> old2D; containers::Matrix<bool> fixedEDP; public: // --- RUTA PARA GUARDAR DATOS --- std::string pathEDP; // --- ECUACIONES DIFERENCIALES EN DERIVADAS PARCIALES --- // -- MÉTODO DE LAS DIFERENCIAS FINITAS - SISTEMAS DE 1 DIMENSIÓN -- // Resuelve ecuaciones diferenciales del tipo: Y''(x) + A(x)·Y'(x) + B(x)·Y(x) = C(x) + D // PARÁMETROS DE DEFINICIÓN DE LA FUNCIÓN EDP_T (* A)(EDP_T x), (* B)(EDP_T x), (* C)(EDP_T x); // C debe definirse como: C(x) + D containers::Vector<EDP_T> solveDIF_FIN(unsigned char bc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, EDP_T err); // CONDICIONES DE CONTORNO NORMALES -> PARA TODAS LAS FUNCIONES EDP_T (* BCL)(EDP_T x, EDP_T y), (* BCR)(EDP_T x, EDP_T y), (* BCT)(EDP_T x, EDP_T y), (* BCB)(EDP_T x, EDP_T y); // CONDICIONES DE CONTORNO ESPECIALES -> LAPLACE Y POISSON EDP_T (* SBCL)(EDP_T uR, EDP_T uT, EDP_T uB); EDP_T (* SBCR)(EDP_T uL, EDP_T uT, EDP_T uB); EDP_T (* SBCT)(EDP_T uL, EDP_T uR, EDP_T uB); EDP_T (* SBCB)(EDP_T uL, EDP_T uR, EDP_T uT); EDP_T (* SBCI)(EDP_T uL, EDP_T uR, EDP_T uT, EDP_T uB); // -- ECUACIONES DE LAPLACE Y POISSON - SISTEMAS DE 2 DIMENSIONES -- // Resuelve las ecuaciones diferenciales: ∆U(x,y) = 0 y ∆U(x,y) = F, F ≠ F(U) // - ECUACIÓN DE LAPLACE // Función principal / Método de resolución containers::Matrix<EDP_T> solveLAPLACE(unsigned char bc, unsigned char sbc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err, int tol); // Funciones de llamada. containers::Matrix<EDP_T> solveLAPLACE(unsigned char bc, unsigned char sbc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); containers::Matrix<EDP_T> solveLAPLACE(unsigned char bc, unsigned char sbc, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err, int tol); containers::Matrix<EDP_T> solveLAPLACE_NBC(unsigned char bc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); containers::Matrix<EDP_T> solveLAPLACE_SBC(unsigned char sbc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); containers::Matrix<EDP_T> solveLAPLACE_NBC(unsigned char bc, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); containers::Matrix<EDP_T> solveLAPLACE_SBC(unsigned char sbc, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); // POISSON // CONDICIÓN DE LA EC. DE POISSON // Es importante que esta función no dependa de otros puntos de la matriz. EDP_T (* F)(EDP_T x, EDP_T y); // - ECUACIÓN DE POISSON // Función principal / Método de resolución containers::Matrix<EDP_T> solvePOISSON(unsigned char bc, unsigned char sbc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err, int tol); // Funciones de llamada containers::Matrix<EDP_T> solvePOISSON(unsigned char bc, unsigned char sbc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); containers::Matrix<EDP_T> solvePOISSON(unsigned char bc, unsigned char sbc, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err, int tol); containers::Matrix<EDP_T> solvePOISSON_NBC(unsigned char bc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); containers::Matrix<EDP_T> solvePOISSON_SBC(unsigned char sbc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); containers::Matrix<EDP_T> solvePOISSON_NBC(unsigned char bc, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); containers::Matrix<EDP_T> solvePOISSON_SBC(unsigned char sbc, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI, EDP_T err); // -- ECUACIONES DE ONDA Y DE CALOR -- // Resuelve las EDPs de onda: ∂²u/∂t² = Q()·∆u y de calor: ∂u/∂t = Q()·∆u // PARÁMETROS EDP_T time, dt; EDP_T (* Q1D)(EDP_T x); // Constante o función Q() que acompaña al laplaciano en 1 dimensión. EDP_T (* Q2D)(EDP_T x, EDP_T y); // FUNCIONES DE LA EC. DE ONDA containers::Vector<EDP_T> solveWAVE(unsigned char bc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& cI, containers::Vector<EDP_T>& cId); containers::Vector<EDP_T> solveWAVE(unsigned char bc, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& cI, containers::Vector<EDP_T>& cId); containers::Matrix<EDP_T> solveWAVE(unsigned char bc, unsigned char opt, containers::Vector<EDP_T> &x, containers::Vector<EDP_T> &y, containers::Matrix<EDP_T> &cI, containers::Matrix<EDP_T> &cId, containers::Matrix<bool> &fixed); containers::Matrix<EDP_T> solveWave(unsigned char bc, containers::Vector<EDP_T> &x, containers::Vector<EDP_T> &y, containers::Matrix<EDP_T> &cI, containers::Matrix<EDP_T> &cId, containers::Matrix<bool> &fixed); containers::Matrix<EDP_T> solveWAVE(unsigned char bc, containers::Vector<EDP_T> &x, containers::Vector<EDP_T> &y, containers::Matrix<EDP_T> &cI, containers::Matrix<EDP_T> &cId); // FUNCIONES DE LA EC. DE CALOR // Elementos necesarios para la función EDP_T theta; containers::Vector<EDP_T> solveHEAT(unsigned char bc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y); containers::Vector<EDP_T> solveHEAT(unsigned char bc, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y); containers::Matrix<EDP_T> solveHEAT(unsigned char bc, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI); containers::Matrix<EDP_T> solveHEAT(unsigned char bc, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& cI); // -- ECUACIONES DEL TIPO -> ∂²u/∂t² = -k²u -- // Calcula los autovalores y autovectores de dicha ecuación. containers::Vector<EDP_T> eigenVAL_VEC(containers::Vector<EDP_T>& x, int mode, unsigned char bc,unsigned char opt); containers::Vector<EDP_T> eigenVAL_VEC(containers::Vector<EDP_T>& x, int mode, unsigned char bc); containers::Matrix<EDP_T> eigenVAL_VEC(containers::Vector<EDP_T> &x, containers::Vector<EDP_T> &y, int modeX, int modeY, unsigned char bc, unsigned char opt); containers::Matrix<EDP_T> eigenVAL_VEC(containers::Vector<EDP_T> &x, containers::Vector<EDP_T> &y, int modeX, int modeY, unsigned char bc); // -- FUNCIONES DE SALIDA -- void saveDATA(const std::string path, const std::string fileName, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& forSave); void saveDATA(const std::string path, const std::string fileName, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& forSave); void saveDATA(const std::string fileName, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y,containers:: Matrix<EDP_T>& forSave); void printMATLAB(const std::string path, const std::string fileName, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& forPrint); void printMATLAB(const std::string fileName, unsigned char opt, containers::Vector<EDP_T>& x, containers::Vector<EDP_T>& y, containers::Matrix<EDP_T>& forPrint); }; } /* namespace math */ } /* namespace differential_equations */ } /* namespace cda */
MichGedd/NDegreesOfWikipedia
include/WebCrawlerManager.h
<reponame>MichGedd/NDegreesOfWikipedia // // Created by micha on 2020-09-20. // #pragma once #include <iostream> #include <queue> #include <string> #include <pthread.h> #include "Graph.h" #include "WebCrawler.h" namespace NDegreesOfWikipedia { struct ThreadData { NDegreesOfWikipedia::WebCrawler *pwc; NDegreesOfWikipedia::Graph *pGraph; std::queue<NDegreesOfWikipedia::Node *> *pQueue; bool *killSig; int threadIdx; }; class WebCrawlerManager { public: WebCrawlerManager(std::string start, std::string end, int numThreads); void run(); private: std::queue<NDegreesOfWikipedia::Node *> queue; NDegreesOfWikipedia::Graph graph; std::string start, end; int numThreads; }; }
MichGedd/NDegreesOfWikipedia
include/Graph.h
// // Created by micha on 2020-09-20. // #pragma once #include <iostream> #include <string> #include <vector> #include <unordered_map> #include <stack> namespace NDegreesOfWikipedia { // Struct for graph nodes struct Node { std::string value; // Name of article Node *parentNode; // Pointer to parent node std::vector<Node *> childrenNodes; // List of pointers to child nodes }; class Graph { public: Graph(std::string value); void addNode(Node *parent, Node *nodeToAdd); Node *findNode(std::string nodeValue); bool nodeExists(std::string nodeValue); void addNodeConnection(Node *parent, Node *child); std::stack<Node *> findPathToRoot(Node *node); int size(); private: Node topNode; std::unordered_map<std::string , Node> hashmap; }; }
MichGedd/NDegreesOfWikipedia
include/WebCrawler.h
// // Created by micha on 2020-09-19. // #pragma once #include <iostream> #include <curl/curl.h> #include <nlohmann/json.hpp> #include <regex> #include <unistd.h> #include <mutex> #include <stack> namespace NDegreesOfWikipedia { inline std::mutex queueMutex = {}; // Queue Mutex inline std::mutex graphMutex = {}; // Graph Mutex class WebCrawler { public: WebCrawler(); [[noreturn]] void *run(void *threadid); static void *run_helper(void *threadData); bool webpageExists(std::string wikiPage); private: // Struct for cURL buffer struct CurlBuffer { char *memory; // Pointer for string size_t size; // Size of string }; static size_t callback(void *data, size_t size, size_t nmeb, void *userdata); std::vector<std::string> scrape(std::string html); std::string httpAndJSONParse(std::string wikiPage); struct CurlBuffer buffer; CURL *curl; CURLcode res; std::regex rgx; const std::string wikipediaFilters[7] = {"Help:", "Wikipedia:", "Portal:", "Template:", "Template_talk:", "Category:", "Special:"}; // Array of filters. Articles that start with these filters are not added to the graph }; }
josephlewis42/personal_codebase
xc/Lab09-DrivingStraight/src/uart.h
<reponame>josephlewis42/personal_codebase #ifndef uart_h #define uart_h void debug(const char values[]); #endif
josephlewis42/personal_codebase
xc/HW07-PID/src/hmc6352.h
<filename>xc/HW07-PID/src/hmc6352.h #ifndef HMC6352_H_ #define HMC6352_H_ #include "i2c.h" typedef enum { SLAVE_ADDRESS=0, MAGNETOMETER_X_OFFSET_MSB=1, MAGNETOMETER_X_OFFSET_LSB=2, MAGNETOMETER_Y_OFFSET_MSB=3, MAGNETOMETER_Y_OFFSET_LSB=4, TIME_DELAY=5, NUM_SUMMED_MEASUREMENTS=6, SOFTWARE_VERSION_NUMBER=7, OPERATION_MODE=8 } hmc6352_eeprom_address_t; unsigned int hmc6352_get_heading_degrees(i2c_p& i2c); unsigned char hmc6352_read_eeprom(i2c_p& i2c, hmc6352_eeprom_address_t eeprom_address); unsigned char hmc6352_read_ram(i2c_p& i2c, unsigned char ram_address); void hmc6352_start_user_calibration(i2c_p& i2c); void hmc6352_stop_user_calibration(i2c_p& i2c); void hmc6352_write_eeprom( i2c_p& i2c, hmc6352_eeprom_address_t eeprom_address, unsigned char value); void hmc6352_write_ram( i2c_p& i2c, unsigned char ram_address, unsigned char value); unsigned int hmc6352_get_heading_tenth_degrees(i2c_p& i2c); #endif /* HMC6352_H_ */
josephlewis42/personal_codebase
xc/Lab08-LinkedList/src/bfs.h
/* * bfs.h * * Created on: May 17, 2012 * Author: <NAME> <<EMAIL>> */ #ifndef BFS_H_ #define BFS_H_ # define MAZE_WIDTH 10 # define ELEMENT_COUNT (MAZE_WIDTH * MAZE_WIDTH) # define RANK(row, col) ((row) * MAZE_WIDTH + (col)) # define ROW(rank) ((rank) / MAZE_WIDTH) # define COL(rank) ((rank) % MAZE_WIDTH) int test_main(); #endif /* BFS_H_ */
josephlewis42/personal_codebase
xc/Lab09-DrivingStraight/src/utility.h
#ifndef UTILITY_H_ #define UTILITY_H_ #include <xs1.h> #define TICKS_PER_US (XS1_TIMER_HZ/1000000) #define TICKS_PER_MS (XS1_TIMER_HZ/1000) #define TICKS_PER_SEC (XS1_TIMER_HZ) #define MIN(x,y) (x > y ? y : x) #define MAX(x,y) (x > y ? x : y) #endif /* UTILITY_H_ */
josephlewis42/personal_codebase
xc/Lab07-Rotate90/src/pid.c
#include <math.h> #include <stdio.h> #include <stdlib.h> const double EPSILON = 0.0000001; /** int main(int argc, char** argv) { const double dt = 1.0, setpoint = 50.0; double prev_position = 0.0, error = 0.0, position = 0.0; double integral = 0, derivative = 0, output = 0.0; //sum of errors over time double Kp = .5, Ki = .3, Kd = .5; unsigned int i; if(argc != 4){ fprintf(stderr, "usage: %s <Kp> <Ki> <Kd>\n", argv[0]); return 1; } Kp = atof(argv[1]); Ki = atof(argv[2]); Kd = atof(argv[3]); fprintf(stdout, "# setpoint = %f, initial = %f, Kp = %f, Ki = %f, Kd = %f\n", setpoint, position, Kp, Ki, Kd); i = 1; fprintf(stdout, "%u\t%f\n", i, position); while(fabs(setpoint - position) > EPSILON){ error = setpoint - position; integral = integral + error*dt; derivative = (position - prev_position)/dt; output = (Kp*error) + (Ki*integral) + (Kd*derivative); prev_position = position; // for derivitive position += output; //Plant is itegral 1/s fprintf(stdout, "%u\t%f\n", i, position); i++; } return 0; } **/
josephlewis42/personal_codebase
xc/HW09-FinalVehicle/src/DistanceControlHelper.c
#include "DistanceControlHelper.h" float find_velocity_mm_per_ms(int width) { return -.0000009948052591 * width * width + .00367823322 * width - 3.246861274; } int find_pulse_duration_ms(int width, int dist_mm) { return (int) ((float) dist_mm / find_velocity_mm_per_ms(width)); }
josephlewis42/personal_codebase
xc/HW09-FinalVehicle/src/hmc6352.h
#ifndef HMC_DRIVER_H #define HMC_DRIVER_H #include "i2c.h" extern const unsigned char HMC6352_SLAVE_ADDRESS; extern const unsigned char HMC6352_MAGNETOMETER_X_OFFSET_MSB; extern const unsigned char HMC6352_MAGNETOMETER_X_OFFSET_LSB; extern const unsigned char HMC6352_MAGNETOMETER_Y_OFFSET_MSB; extern const unsigned char HMC6352_MAGNETOMETER_Y_OFFSET_LSB; extern const unsigned char HMC6352_TIME_DELAY_MS; extern const unsigned char HMC6352_NUM_SUMMED_MEASUREMENTS; extern const unsigned char HMC6352_SOFTWARE_VERSION; extern const unsigned char HMC6352_OPERATION_MODE; unsigned char hmc6352_read_eeprom( i2c_p& i2c, unsigned char eeprom_addr ); void hmc6352_write_eeprom(i2c_p& i2c, unsigned char eeprom_address, unsigned char value); unsigned char hmc6352_read_ram( i2c_p& i2c, unsigned char ram_addr ); void hmc6352_write_ram(i2c_p& i2c, unsigned char ram_addr, unsigned char value); void hmc6352_start_user_calibration(i2c_p& i2c); void hmc6352_stop_user_calibration(i2c_p& i2c); unsigned int hmc6352_get_heading_degrees(i2c_p& i2c); void hmc6352_calibrate_compass(i2c_p& i2c); #endif