repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
onox/wayland-ada
wayland_client_ada/src/errno.c
// SPDX-License-Identifier: Apache-2.0 // Copyright (c) 2020 onox <<EMAIL>> #include <errno.h> int get_errno(void) { // Defined in ISO C99 standard return errno; }
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/HAL/HAL_AVR/inc/SanityCheck.h
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * Test AVR-specific configuration values for errors at compile-time. */ /** * Digipot requirement */ #if ENABLED(DIGIPOT_MCP4018) #if !defined(DIGIPOTS_I2C_SDA_X) || !defined(DIGIPOTS_I2C_SDA_Y) || !defined(DIGIPOTS_I2C_SDA_Z) \ || !defined(DIGIPOTS_I2C_SDA_E0) || !defined(DIGIPOTS_I2C_SDA_E1) #error "DIGIPOT_MCP4018 requires DIGIPOTS_I2C_SDA_* pins to be defined." #endif #endif /** * Checks for FAST PWM */ #if ENABLED(FAST_PWM_FAN) && (ENABLED(USE_OCR2A_AS_TOP) && defined(TCCR2)) #error "USE_OCR2A_AS_TOP does not apply to devices with a single output TIMER2" #endif /** * Sanity checks for Spindle / Laser PWM */ #if ENABLED(SPINDLE_LASER_PWM) #if SPINDLE_LASER_PWM_PIN == 4 || WITHIN(SPINDLE_LASER_PWM_PIN, 11, 13) #error "Counter/Timer for SPINDLE_LASER_PWM_PIN is used by a system interrupt." #elif NUM_SERVOS > 0 && (WITHIN(SPINDLE_LASER_PWM_PIN, 2, 3) || SPINDLE_LASER_PWM_PIN == 5) #error "Counter/Timer for SPINDLE_LASER_PWM_PIN is used by the servo system." #endif #endif /** * The Trinamic library includes SoftwareSerial.h, leading to a compile error. */ #if HAS_TRINAMIC && ENABLED(ENDSTOP_INTERRUPTS_FEATURE) #error "TMCStepper includes SoftwareSerial.h which is incompatible with ENDSTOP_INTERRUPTS_FEATURE. Disable ENDSTOP_INTERRUPTS_FEATURE to continue." #endif #if TMC_HAS_SW_SERIAL && ENABLED(MONITOR_DRIVER_STATUS) #error "MONITOR_DRIVER_STATUS causes performance issues when used with SoftwareSerial-connected drivers. Disable MONITOR_DRIVER_STATUS or use hardware serial to continue." #endif
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/pins/lpc1769/pins_TH3D_EZBOARD.h
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * TH3D EZBoard pin assignments */ #ifndef MCU_LPC1769 #error "Oops! Make sure you have the LPC1769 environment selected in your IDE." #endif #define BOARD_INFO_NAME "TH3D EZBoard" #define BOARD_WEBSITE_URL "th3dstudio.com" // // Servos // #define SERVO0_PIN P2_04 // // Limit Switches // #define X_STOP_PIN P1_24 #define Y_STOP_PIN P1_25 #define Z_STOP_PIN P1_26 // // Filament Runout Sensor // #ifndef FIL_RUNOUT_PIN #define FIL_RUNOUT_PIN P1_27 #endif // // Steppers // #define X_STEP_PIN P2_00 #define X_DIR_PIN P1_16 #define X_ENABLE_PIN P1_17 #define Y_STEP_PIN P2_01 #define Y_DIR_PIN P1_10 #define Y_ENABLE_PIN P1_09 #define Z_STEP_PIN P2_02 #define Z_DIR_PIN P1_15 #define Z_ENABLE_PIN P1_14 #define E0_STEP_PIN P2_03 #define E0_DIR_PIN P1_04 #define E0_ENABLE_PIN P1_08 #define E1_STEP_PIN P2_08 #define E1_DIR_PIN P2_13 #define E1_ENABLE_PIN P4_29 #if HAS_DRIVER(TMC2208) // // TMC2208 stepper drivers // Software serial // #define X_SERIAL_TX_PIN P0_04 #define X_SERIAL_RX_PIN P0_05 #define Y_SERIAL_TX_PIN P0_10 #define Y_SERIAL_RX_PIN P0_11 #define Z_SERIAL_TX_PIN P0_19 #define Z_SERIAL_RX_PIN P0_20 #define E0_SERIAL_TX_PIN P0_22 #define E0_SERIAL_RX_PIN P0_21 // Reduce baud rate to improve software serial reliability #define TMC_BAUD_RATE 19200 #endif // // Temp Sensors // 3.3V max when defined as an Analog Input! // #if TEMP_SENSOR_0 == 20 // PT100 Adapter #define TEMP_0_PIN P0_02_A7 // Analog Input #else #define TEMP_0_PIN P0_23_A0 // Analog Input P0_23 #endif #define TEMP_BED_PIN P0_24_A1 // Analog Input P0_24 #define TEMP_1_PIN P0_25_A2 // Analog Input P0_25 #if ENABLED(FILAMENT_WIDTH_SENSOR) #define FILWIDTH_PIN P0_26_A3 // Analog Input P0_26 #else #define TEMP_2_PIN P0_26_A3 // Analog Input P0_26 #endif // // Heaters / Fans // #define HEATER_BED_PIN P2_05 #define HEATER_0_PIN P2_07 #ifndef FAN_PIN #define FAN_PIN P2_06 #endif #define FAN1_PIN P1_22 // // Auto fans // #define AUTO_FAN_PIN P1_22 // FET 3 #define ORIG_E0_AUTO_FAN_PIN AUTO_FAN_PIN #define ORIG_E1_AUTO_FAN_PIN AUTO_FAN_PIN #define ORIG_E2_AUTO_FAN_PIN AUTO_FAN_PIN // // SD Card // #define SDCARD_CONNECTION ONBOARD #define SCK_PIN P0_07 #define MISO_PIN P0_08 #define MOSI_PIN P0_09 #define ONBOARD_SD_CS_PIN P0_06 #define SS_PIN ONBOARD_SD_CS_PIN // // LCD / Controller // /** * _____ * 5V | · · | GND * (LCD_EN) P0_18 | · · | P0_16 (LCD_RS) * (LCD_D4) P0_15 | · · | P3_25 (BTN_EN2) * (RESET) P2_11 | · · | P3_26 (BTN_EN1) * (BTN_ENC) P1_30 | · · | P1_31 (BEEPER) * ----- * EXP1 * * LCD_PINS_D5, D6, and D7 are not present in the EXP1 connector, and will need to be * defined to use the REPRAP_DISCOUNT_SMART_CONTROLLER. * * A remote SD card is currently not supported because the pins routed to the EXP2 * connector are shared with the onboard SD card. * */ #if ENABLED(CR10_STOCKDISPLAY) #define BEEPER_PIN P1_31 #define BTN_EN1 P3_26 #define BTN_EN2 P3_25 #define BTN_ENC P1_30 #define LCD_PINS_RS P0_16 #define LCD_PINS_ENABLE P0_18 #define LCD_PINS_D4 P0_15 #define KILL_PIN P2_11 #elif HAS_SPI_LCD #error "Only the CR10_STOCKDISPLAY is supported with TH3D EZBoard." #endif
DDilshani/CO326-project
firmware/grbl-Mega/src/sleep.h
/* sleep.h - Sleep methods header file Part of Grbl Copyright (c) 2016 <NAME> Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ #ifndef sleep_h #define sleep_h #include "grbl.h" // Initialize sleep timer void sleep_init(); // Checks running conditions for sleep. If satisfied, enables sleep countdown and executes // sleep mode upon elapse. void sleep_check(); #endif
DDilshani/CO326-project
firmware/grbl-Mega/src/config.h
<gh_stars>0 /* config.h - compile time configuration Part of Grbl Copyright (c) 2017-2018 <NAME> Copyright (c) 2012-2016 <NAME> for Gnea Research LLC Copyright (c) 2009-2011 <NAME> Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ // This file contains compile-time configurations for Grbl's internal system. // This file is used to define the number of axix and their names, // define homing sequences or specific needs, i.e. // performance tuning or adjusting to non-typical machines. // IMPORTANT: Any changes here requires a full re-compiling of the source code to propagate them. #ifndef config_h #define config_h #include "grbl.h" // For Arduino IDE compatibility. // Define CPU pin map and default settings. // NOTE: OEMs can avoid the need to maintain/update the defaults.h and cpu_map.h files and use only // one configuration file by placing their specific defaults and pin map at the bottom of this file. // If doing so, simply comment out these two defines and see instructions below. //#define DEFAULTS_GENERIC //#define CPU_MAP_2560_INITIAL // To use with RAMPS 1.4 Board, comment out the above defines and uncomment the next two defines #define DEFAULTS_RAMPS_BOARD #define CPU_MAP_2560_RAMPS_BOARD // Serial baud rate // #define BAUD_RATE 230400 #define BAUD_RATE 115200 // Axis array index values. Must start with 0 and be continuous. #ifdef DEFAULTS_RAMPS_BOARD // 4, 5 & 6 axis support only for RAMPS 1.4 (for the moment :-)...) #define N_AXIS 3 // Number of axes #define N_AXIS_LINEAR 3 // Number of linears axis #else #define N_AXIS 3 // Number of axes = 3 if not DEFAULTS_RAMPS_BOARD #endif #define AXIS_1 0 // Axis indexing value. Must start with 0 and be continuous. #define AXIS_1_NAME 'X' #define AXIS_2 1 #define AXIS_2_NAME 'Y' #define AXIS_3 2 #define AXIS_3_NAME 'Z' #if N_AXIS <3 #error "N_AXIS must be >= 3. N_AXIS < 3 is not implemented." #endif #if N_AXIS > 3 #define AXIS_4 3 #define AXIS_4_NAME 'A' // Letter of axis number 4 #endif #if N_AXIS > 4 #define AXIS_5 4 #define AXIS_5_NAME 'B' // Letter of axis number 5 #endif #if N_AXIS > 5 #define AXIS_6 5 #define AXIS_6_NAME 'C' // Letter of axis number 6 #endif #if N_AXIS > 6 #error "N_AXIS must be <= 6. N_AXIS > 6 is not implemented." #endif // Define realtime command special characters. These characters are 'picked-off' directly from the // serial read data stream and are not passed to the grbl line execution parser. Select characters // that do not and must not exist in the streamed g-code program. ASCII control characters may be // used, if they are available per user setup. Also, extended ASCII codes (>127), which are never in // g-code programs, maybe selected for interface programs. // NOTE: If changed, manually update help message in report.c. #define CMD_RESET 0x18 // ctrl-x. #define CMD_STATUS_REPORT '?' #define CMD_CYCLE_START '~' #define CMD_FEED_HOLD '!' // NOTE: All override realtime commands must be in the extended ASCII character set, starting // at character value 128 (0x80) and up to 255 (0xFF). If the normal set of realtime commands, // such as status reports, feed hold, reset, and cycle start, are moved to the extended set // space, serial.c's RX ISR will need to be modified to accomodate the change. // #define CMD_RESET 0x80 // #define CMD_STATUS_REPORT 0x81 // #define CMD_CYCLE_START 0x82 // #define CMD_FEED_HOLD 0x83 #define CMD_SAFETY_DOOR 0x84 #define CMD_JOG_CANCEL 0x85 #define CMD_DEBUG_REPORT 0x86 // Only when DEBUG enabled, sends debug report in '{}' braces. #define CMD_FEED_OVR_RESET 0x90 // Restores feed override value to 100%. #define CMD_FEED_OVR_COARSE_PLUS 0x91 #define CMD_FEED_OVR_COARSE_MINUS 0x92 #define CMD_FEED_OVR_FINE_PLUS 0x93 #define CMD_FEED_OVR_FINE_MINUS 0x94 #define CMD_RAPID_OVR_RESET 0x95 // Restores rapid override value to 100%. #define CMD_RAPID_OVR_MEDIUM 0x96 #define CMD_RAPID_OVR_LOW 0x97 // #define CMD_RAPID_OVR_EXTRA_LOW 0x98 // *NOT SUPPORTED* #define CMD_SPINDLE_OVR_RESET 0x99 // Restores spindle override value to 100%. #define CMD_SPINDLE_OVR_COARSE_PLUS 0x9A #define CMD_SPINDLE_OVR_COARSE_MINUS 0x9B #define CMD_SPINDLE_OVR_FINE_PLUS 0x9C #define CMD_SPINDLE_OVR_FINE_MINUS 0x9D #define CMD_SPINDLE_OVR_STOP 0x9E #define CMD_COOLANT_FLOOD_OVR_TOGGLE 0xA0 #define CMD_COOLANT_MIST_OVR_TOGGLE 0xA1 // If homing is enabled, homing init lock sets Grbl into an alarm state upon power up. This forces // the user to perform the homing cycle (or override the locks) before doing anything else. This is // mainly a safety feature to remind the user to home, since position is unknown to Grbl. // #define HOMING_INIT_LOCK // Comment to disable // Define the homing cycle patterns with bitmasks. The homing cycle first performs a search mode // to quickly engage the limit switches, followed by a slower locate mode, and finished by a short // pull-off motion to disengage the limit switches. The following HOMING_CYCLE_x defines are executed // in order starting with suffix 0 and completes the homing routine for the specified-axes only. If // an axis is omitted from the defines, it will not home, nor will the system update its position. // Meaning that this allows for users with non-standard cartesian machines, such as a lathe (x then z, // with no y), to configure the homing cycle behavior to their needs. // NOTE: The homing cycle is designed to allow sharing of limit pins, if the axes are not in the same // cycle, but this requires some pin settings changes in cpu_map.h file. For example, the default homing // cycle can share the Z limit pin with either X or Y limit pins, since they are on different cycles. // By sharing a pin, this frees up a precious IO pin for other purposes. In theory, all axes limit pins // may be reduced to one pin, if all axes are homed with seperate cycles, or vice versa, all three axes // on separate pin, but homed in one cycle. Also, it should be noted that the function of hard limits // will not be affected by pin sharing. // NOTE: Defaults are set for a traditional 3-axis CNC machine. Z-axis first to clear, followed by X & Y. #ifdef DEFAULTS_RAMPS_BOARD #if N_AXIS == 4 // 4 axis : homing #define HOMING_CYCLE_0 (1<<AXIS_4) // Home 4th axis (A) #define HOMING_CYCLE_1 (1<<AXIS_1) // Home X axis #define HOMING_CYCLE_2 (1<<AXIS_2) // Home Y axis #define HOMING_CYCLE_3 (1<<AXIS_3) // OPTIONAL: Home Z axis #elif N_AXIS == 5 // 5 axis : homing /*#define HOMING_CYCLE_0 (1<<AXIS_4) // Home 4th axis (A) define HOMING_CYCLE_1 (1<<AXIS_5) // Home 5th axis (B) #define HOMING_CYCLE_2 (1<<AXIS_1) // Home X axis #define HOMING_CYCLE_3 (1<<AXIS_2) // Home Y axis #define HOMING_CYCLE_4 (1<<AXIS_3) // OPTIONAL: Home Z axis*/ #define HOMING_CYCLE_0 (1<<AXIS_1) // Home X axis #define HOMING_CYCLE_1 (1<<AXIS_3) // Home Y axis #elif N_AXIS == 6 // 6 axis : homing #define HOMING_CYCLE_0 (1<<AXIS_4) // Home 4th axis (A) #define HOMING_CYCLE_1 (1<<AXIS_5) // Home 5th axis (B) #define HOMING_CYCLE_2 (1<<AXIS_6) // Home 6th axis (C) #define HOMING_CYCLE_3 (1<<AXIS_1) // Home X axis #define HOMING_CYCLE_4 (1<<AXIS_3) // Home Y axis #define HOMING_CYCLE_5 (1<<AXIS_2) // OPTIONAL: Home Z axis #else // Classic 3 axis #define HOMING_CYCLE_0 (1<<AXIS_3) // REQUIRED: First move Z to clear workspace. #define HOMING_CYCLE_1 ((1<<AXIS_1)|(1<<AXIS_2)) #endif #else #define HOMING_CYCLE_0 (1<<AXIS_3) // REQUIRED: First move Z to clear workspace. #define HOMING_CYCLE_1 ((1<<AXIS_1)|(1<<AXIS_2)) // OPTIONAL: Then move X,Y at the same time. // #define HOMING_CYCLE_2 // OPTIONAL: Uncomment and add axes mask to enable #endif // DEFAULTS_RAMPS_BOARD // NOTE: The following are two examples to setup homing for 2-axis machines. // #define HOMING_CYCLE_0 ((1<<AXIS_1)|(1<<AXIS_2)) // NOT COMPATIBLE WITH COREXY: Homes both X-Y in one cycle. // #define HOMING_CYCLE_0 (1<<AXIS_1) // COREXY COMPATIBLE: First home X // #define HOMING_CYCLE_1 (1<<AXIS_2) // COREXY COMPATIBLE: Then home Y // Number of homing cycles performed after when the machine initially jogs to limit switches. // This help in preventing overshoot and should improve repeatability. This value should be one or // greater. #define N_HOMING_LOCATE_CYCLE 1 // Integer (1-128) // Enables single axis homing commands. $HX, $HY, and $HZ for X, Y, and Z-axis homing. The full homing // cycle is still invoked by the $H command. This is disabled by default. It's here only to address // users that need to switch between a two-axis and three-axis machine. This is actually very rare. // If you have a two-axis machine, DON'T USE THIS. Instead, just alter the homing cycle for two-axes. #define HOMING_SINGLE_AXIS_COMMANDS // Default disabled. Uncomment to enable. // After homing, Grbl will set by default the entire machine space into negative space, as is typical // for professional CNC machines, regardless of where the limit switches are located. Uncomment this // define to force Grbl to always set the machine origin at the homed location despite switch orientation. #define HOMING_FORCE_SET_ORIGIN // Uncomment to enable. // Number of blocks Grbl executes upon startup. These blocks are stored in EEPROM, where the size // and addresses are defined in settings.h. With the current settings, up to 2 startup blocks may // be stored and executed in order. These startup blocks would typically be used to set the g-code // parser state depending on user preferences. #define N_STARTUP_LINE 2 // Integer (1-2) // Number of floating decimal points printed by Grbl for certain value types. These settings are // determined by realistic and commonly observed values in CNC machines. For example, position // values cannot be less than 0.001mm or 0.0001in, because machines can not be physically more // precise this. So, there is likely no need to change these, but you can if you need to here. // NOTE: Must be an integer value from 0 to ~4. More than 4 may exhibit round-off errors. #define N_DECIMAL_COORDVALUE_INCH 4 // Coordinate or position value in inches #define N_DECIMAL_COORDVALUE_MM 3 // Coordinate or position value in mm #define N_DECIMAL_RATEVALUE_INCH 1 // Rate or velocity value in in/min #define N_DECIMAL_RATEVALUE_MM 0 // Rate or velocity value in mm/min #define N_DECIMAL_SETTINGVALUE 3 // Decimals for floating point setting values #define N_DECIMAL_RPMVALUE 0 // RPM value in rotations per min. // If your machine has two limits switches wired in parallel to one axis, you will need to enable // this feature. Since the two switches are sharing a single pin, there is no way for Grbl to tell // which one is enabled. This option only effects homing, where if a limit is engaged, Grbl will // alarm out and force the user to manually disengage the limit switch. Otherwise, if you have one // limit switch for each axis, don't enable this option. By keeping it disabled, you can perform a // homing cycle while on the limit switch and not have to move the machine off of it. // #define LIMITS_TWO_SWITCHES_ON_AXES // Upon a successful probe cycle, this option provides immediately feedback of the probe coordinates // through an automatically generated message. If disabled, users can still access the last probe // coordinates through Grbl '$#' print parameters. #define MESSAGE_PROBE_COORDINATES // Enabled by default. Comment to disable. // This option causes the feed hold input to act as a safety door switch. A safety door, when triggered, // immediately forces a feed hold and then safely de-energizes the machine. Resuming is blocked until // the safety door is re-engaged. When it is, Grbl will re-energize the machine and then resume on the // previous tool path, as if nothing happened. #define ENABLE_SAFETY_DOOR_INPUT_PIN // Default disabled. Uncomment to enable. // After the safety door switch has been toggled and restored, this setting sets the power-up delay // between restoring the spindle and coolant and resuming the cycle. #define SAFETY_DOOR_SPINDLE_DELAY 4.0 // Float (seconds) #define SAFETY_DOOR_COOLANT_DELAY 1.0 // Float (seconds) // Enable CoreXY kinematics. Use ONLY with CoreXY machines. // IMPORTANT: If homing is enabled, you must reconfigure the homing cycle #defines above to // #define HOMING_CYCLE_0 (1<<AXIS_1) and #define HOMING_CYCLE_1 (1<<AXIS_2) // NOTE: This configuration option alters the motion of the X and Y axes to principle of operation // defined at (http://corexy.com/theory.html). Motors are assumed to positioned and wired exactly as // described, if not, motions may move in strange directions. Grbl requires the CoreXY A and B motors // have the same steps per mm internally. // #define COREXY // Default disabled. Uncomment to enable. // Inverts pin logic of the control command pins based on a mask. This essentially means you can use // normally-closed switches on the specified pins, rather than the default normally-open switches. // NOTE: The top option will mask and invert all control pins. The bottom option is an example of // inverting only two control pins, the safety door and reset. See cpu_map.h for other bit definitions. // #define INVERT_CONTROL_PIN_MASK CONTROL_MASK // Default disabled. Uncomment to disable. // #define INVERT_CONTROL_PIN_MASK ((1<<CONTROL_SAFETY_DOOR_BIT)|(CONTROL_RESET_BIT)) // Default disabled. // Inverts select limit pin states based on the following mask. This effects all limit pin functions, // such as hard limits and homing. However, this is different from overall invert limits setting. // This build option will invert only the limit pins defined here, and then the invert limits setting // will be applied to all of them. This is useful when a user has a mixed set of limit pins with both // normally-open(NO) and normally-closed(NC) switches installed on their machine. // NOTE: PLEASE DO NOT USE THIS, unless you have a situation that needs it. // #define INVERT_LIMIT_PIN_MASK ((1<<X_LIMIT_BIT)|(1<<Y_LIMIT_BIT)) // Default disabled. Uncomment to enable. #ifdef DEFAULTS_RAMPS_BOARD // Only enable the following line if you have - (min) limit switches attached //#define INVERT_MIN_LIMIT_PIN_MASK ((1<<AXIS_1) | (1<<AXIS_2) | (1<<AXIS_3)) // Only enable the following line if you have + (max) limit switches attached //#define INVERT_MAX_LIMIT_PIN_MASK ((1<<AXIS_1) | (1<<AXIS_2) | (1<<AXIS_3)) #endif // Inverts the spindle enable pin from low-disabled/high-enabled to low-enabled/high-disabled. Useful // for some pre-built electronic boards. // #define INVERT_SPINDLE_ENABLE_PIN // Default disabled. Uncomment to enable. // Inverts the selected coolant pin from low-disabled/high-enabled to low-enabled/high-disabled. Useful // for some pre-built electronic boards. // #define INVERT_COOLANT_FLOOD_PIN // Default disabled. Uncomment to enable. // #define INVERT_COOLANT_MIST_PIN // Default disabled. Note: Enable M7 mist coolant in config.h // When Grbl powers-cycles or is hard reset with the Arduino reset button, Grbl boots up with no ALARM // by default. This is to make it as simple as possible for new users to start using Grbl. When homing // is enabled and a user has installed limit switches, Grbl will boot up in an ALARM state to indicate // Grbl doesn't know its position and to force the user to home before proceeding. This option forces // Grbl to always initialize into an ALARM state regardless of homing or not. This option is more for // OEMs and LinuxCNC users that would like this power-cycle behavior. // #define FORCE_INITIALIZATION_ALARM // Default disabled. Uncomment to enable. // At power-up or a reset, Grbl will check the limit switch states to ensure they are not active // before initialization. If it detects a problem and the hard limits setting is enabled, Grbl will // simply message the user to check the limits and enter an alarm state, rather than idle. Grbl will // not throw an alarm message. #define CHECK_LIMITS_AT_INIT // --------------------------------------------------------------------------------------- // ADVANCED CONFIGURATION OPTIONS: // Enables code for debugging purposes. Not for general use and always in constant flux. // #define DEBUG // Uncomment to enable. Default disabled. // Configure rapid, feed, and spindle override settings. These values define the max and min // allowable override values and the coarse and fine increments per command received. Please // note the allowable values in the descriptions following each define. #define DEFAULT_FEED_OVERRIDE 100 // 100%. Don't change this value. #define MAX_FEED_RATE_OVERRIDE 200 // Percent of programmed feed rate (100-255). Usually 120% or 200% #define MIN_FEED_RATE_OVERRIDE 10 // Percent of programmed feed rate (1-100). Usually 50% or 1% #define FEED_OVERRIDE_COARSE_INCREMENT 10 // (1-99). Usually 10%. #define FEED_OVERRIDE_FINE_INCREMENT 1 // (1-99). Usually 1%. #define DEFAULT_RAPID_OVERRIDE 100 // 100%. Don't change this value. #define RAPID_OVERRIDE_MEDIUM 50 // Percent of rapid (1-99). Usually 50%. #define RAPID_OVERRIDE_LOW 25 // Percent of rapid (1-99). Usually 25%. // #define RAPID_OVERRIDE_EXTRA_LOW 5 // *NOT SUPPORTED* Percent of rapid (1-99). Usually 5%. #define DEFAULT_SPINDLE_SPEED_OVERRIDE 100 // 100%. Don't change this value. #define MAX_SPINDLE_SPEED_OVERRIDE 200 // Percent of programmed spindle speed (100-255). Usually 200%. #define MIN_SPINDLE_SPEED_OVERRIDE 10 // Percent of programmed spindle speed (1-100). Usually 10%. #define SPINDLE_OVERRIDE_COARSE_INCREMENT 10 // (1-99). Usually 10%. #define SPINDLE_OVERRIDE_FINE_INCREMENT 1 // (1-99). Usually 1%. // When a M2 or M30 program end command is executed, most g-code states are restored to their defaults. // This compile-time option includes the restoring of the feed, rapid, and spindle speed override values // to their default values at program end. #define RESTORE_OVERRIDES_AFTER_PROGRAM_END // Default enabled. Comment to disable. // The status report change for Grbl v1.1 and after also removed the ability to disable/enable most data // fields from the report. This caused issues for GUI developers, who've had to manage several scenarios // and configurations. The increased efficiency of the new reporting style allows for all data fields to // be sent without potential performance issues. // NOTE: The options below are here only provide a way to disable certain data fields if a unique // situation demands it, but be aware GUIs may depend on this data. If disabled, it may not be compatible. #define REPORT_FIELD_BUFFER_STATE // Default enabled. Comment to disable. #define REPORT_FIELD_PIN_STATE // Default enabled. Comment to disable. #define REPORT_FIELD_CURRENT_FEED_SPEED // Default enabled. Comment to disable. #define REPORT_FIELD_WORK_COORD_OFFSET // Default enabled. Comment to disable. #define REPORT_FIELD_OVERRIDES // Default enabled. Comment to disable. #define REPORT_FIELD_LINE_NUMBERS // Default enabled. Comment to disable. // Some status report data isn't necessary for realtime, only intermittently, because the values don't // change often. The following macros configures how many times a status report needs to be called before // the associated data is refreshed and included in the status report. However, if one of these value // changes, Grbl will automatically include this data in the next status report, regardless of what the // count is at the time. This helps reduce the communication overhead involved with high frequency reporting // and agressive streaming. There is also a busy and an idle refresh count, which sets up Grbl to send // refreshes more often when its not doing anything important. With a good GUI, this data doesn't need // to be refreshed very often, on the order of a several seconds. // NOTE: WCO refresh must be 2 or greater. OVR refresh must be 1 or greater. #define REPORT_OVR_REFRESH_BUSY_COUNT 20 // (1-255) #define REPORT_OVR_REFRESH_IDLE_COUNT 10 // (1-255) Must be less than or equal to the busy count #define REPORT_WCO_REFRESH_BUSY_COUNT 30 // (2-255) #define REPORT_WCO_REFRESH_IDLE_COUNT 10 // (2-255) Must be less than or equal to the busy count // The temporal resolution of the acceleration management subsystem. A higher number gives smoother // acceleration, particularly noticeable on machines that run at very high feedrates, but may negatively // impact performance. The correct value for this parameter is machine dependent, so it's advised to // set this only as high as needed. Approximate successful values can widely range from 50 to 200 or more. // NOTE: Changing this value also changes the execution time of a segment in the step segment buffer. // When increasing this value, this stores less overall time in the segment buffer and vice versa. Make // certain the step segment buffer is increased/decreased to account for these changes. #define ACCELERATION_TICKS_PER_SECOND 100 // Adaptive Multi-Axis Step Smoothing (AMASS) is an advanced feature that does what its name implies, // smoothing the stepping of multi-axis motions. This feature smooths motion particularly at low step // frequencies below 10kHz, where the aliasing between axes of multi-axis motions can cause audible // noise and shake your machine. At even lower step frequencies, AMASS adapts and provides even better // step smoothing. See stepper.c for more details on the AMASS system works. #define ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING // Default enabled. Comment to disable. // Sets the maximum step rate allowed to be written as a Grbl setting. This option enables an error // check in the settings module to prevent settings values that will exceed this limitation. The maximum // step rate is strictly limited by the CPU speed and will change if something other than an AVR running // at 16MHz is used. // NOTE: For now disabled, will enable if flash space permits. // #define MAX_STEP_RATE_HZ 30000 // Hz // By default, Grbl sets all input pins to normal-high operation with their internal pull-up resistors // enabled. This simplifies the wiring for users by requiring only a switch connected to ground, // although its recommended that users take the extra step of wiring in low-pass filter to reduce // electrical noise detected by the pin. If the user inverts the pin in Grbl settings, this just flips // which high or low reading indicates an active signal. In normal operation, this means the user // needs to connect a normal-open switch, but if inverted, this means the user should connect a // normal-closed switch. // The following options disable the internal pull-up resistors, sets the pins to a normal-low // operation, and switches must be now connect to Vcc instead of ground. This also flips the meaning // of the invert pin Grbl setting, where an inverted setting now means the user should connect a // normal-open switch and vice versa. // NOTE: All pins associated with the feature are disabled, i.e. XYZ limit pins, not individual axes. // WARNING: When the pull-ups are disabled, this requires additional wiring with pull-down resistors! //#define DISABLE_LIMIT_PIN_PULL_UP //#define DISABLE_PROBE_PIN_PULL_UP //#define DISABLE_CONTROL_PIN_PULL_UP // Sets which axis the tool length offset is applied. Assumes the spindle is always parallel with // the selected axis with the tool oriented toward the negative direction. In other words, a positive // tool length offset value is subtracted from the current location. #define TOOL_LENGTH_OFFSET_AXIS AXIS_3 // Default z-axis. Valid values are AXIS_1, AXIS_2, or AXIS_3. // Used by variable spindle output only. This forces the PWM output to a minimum duty cycle when enabled. // The PWM pin will still read 0V when the spindle is disabled. Most users will not need this option, but // it may be useful in certain scenarios. This minimum PWM settings coincides with the spindle rpm minimum // setting, like rpm max to max PWM. This is handy if you need a larger voltage difference between 0V disabled // and the voltage set by the minimum PWM for minimum rpm. This difference is 0.02V per PWM value. So, when // minimum PWM is at 1, only 0.02 volts separate enabled and disabled. At PWM 5, this would be 0.1V. Keep // in mind that you will begin to lose PWM resolution with increased minimum PWM values, since you have less // and less range over the total 255 PWM levels to signal different spindle speeds. // NOTE: Compute duty cycle at the minimum PWM by this equation: (% duty cycle)=(SPINDLE_PWM_MIN_VALUE/255)*100 // #define SPINDLE_PWM_MIN_VALUE 5 // Default disabled. Uncomment to enable. Must be greater than zero. Integer (1-255). // Alters the behavior of the spindle enable pin. By default, Grbl will not disable the enable pin if // spindle speed is zero and M3/4 is active, but still sets the PWM output to zero. This allows the users // to know if the spindle is active and use it as an additional control input. However, in some use cases, // a user may want the enable pin to disable with a zero spindle speed and re-enable when spindle speed is // greater than zero. This option does that. // #define SPINDLE_ENABLE_OFF_WITH_ZERO_SPEED // Default disabled. Uncomment to enable. // With this enabled, Grbl sends back an echo of the line it has received, which has been pre-parsed (spaces // removed, capitalized letters, no comments) and is to be immediately executed by Grbl. Echoes will not be // sent upon a line buffer overflow, but should for all normal lines sent to Grbl. For example, if a user // sendss the line 'g1 x1.032 y2.45 (test comment)', Grbl will echo back in the form '[echo: G1X1.032Y2.45]'. // NOTE: Only use this for debugging purposes!! When echoing, this takes up valuable resources and can effect // performance. If absolutely needed for normal operation, the serial write buffer should be greatly increased // to help minimize transmission waiting within the serial write protocol. // #define REPORT_ECHO_LINE_RECEIVED // Default disabled. Uncomment to enable. // Minimum planner junction speed. Sets the default minimum junction speed the planner plans to at // every buffer block junction, except for starting from rest and end of the buffer, which are always // zero. This value controls how fast the machine moves through junctions with no regard for acceleration // limits or angle between neighboring block line move directions. This is useful for machines that can't // tolerate the tool dwelling for a split second, i.e. 3d printers or laser cutters. If used, this value // should not be much greater than zero or to the minimum value necessary for the machine to work. #define MINIMUM_JUNCTION_SPEED 0.0 // (mm/min) // Sets the minimum feed rate the planner will allow. Any value below it will be set to this minimum // value. This also ensures that a planned motion always completes and accounts for any floating-point // round-off errors. Although not recommended, a lower value than 1.0 mm/min will likely work in smaller // machines, perhaps to 0.1mm/min, but your success may vary based on multiple factors. #define MINIMUM_FEED_RATE 1.0 // (mm/min) // Number of arc generation iterations by small angle approximation before exact arc trajectory // correction with expensive sin() and cos() calcualtions. This parameter maybe decreased if there // are issues with the accuracy of the arc generations, or increased if arc execution is getting // bogged down by too many trig calculations. #define N_ARC_CORRECTION 12 // Integer (1-255) // The arc G2/3 g-code standard is problematic by definition. Radius-based arcs have horrible numerical // errors when arc at semi-circles(pi) or full-circles(2*pi). Offset-based arcs are much more accurate // but still have a problem when arcs are full-circles (2*pi). This define accounts for the floating // point issues when offset-based arcs are commanded as full circles, but get interpreted as extremely // small arcs with around machine epsilon (1.2e-7rad) due to numerical round-off and precision issues. // This define value sets the machine epsilon cutoff to determine if the arc is a full-circle or not. // NOTE: Be very careful when adjusting this value. It should always be greater than 1.2e-7 but not too // much greater than this. The default setting should capture most, if not all, full arc error situations. #define ARC_ANGULAR_TRAVEL_EPSILON 5E-7 // Float (radians) // Time delay increments performed during a dwell. The default value is set at 50ms, which provides // a maximum time delay of roughly 55 minutes, more than enough for most any application. Increasing // this delay will increase the maximum dwell time linearly, but also reduces the responsiveness of // run-time command executions, like status reports, since these are performed between each dwell // time step. Also, keep in mind that the Arduino delay timer is not very accurate for long delays. #define DWELL_TIME_STEP 50 // Integer (1-255) (milliseconds) // Creates a delay between the direction pin setting and corresponding step pulse by creating // another interrupt (Timer2 compare) to manage it. The main Grbl interrupt (Timer1 compare) // sets the direction pins, and does not immediately set the stepper pins, as it would in // normal operation. The Timer2 compare fires next to set the stepper pins after the step // pulse delay time, and Timer2 overflow will complete the step pulse, except now delayed // by the step pulse time plus the step pulse delay. (Thanks langwadt for the idea!) // NOTE: Uncomment to enable. The recommended delay must be > 3us, and, when added with the // user-supplied step pulse time, the total time must not exceed 127us. Reported successful // values for certain setups have ranged from 5 to 20us. // #define STEP_PULSE_DELAY 10 // Step pulse delay in microseconds. Default disabled. // The number of linear motions in the planner buffer to be planned at any give time. The vast // majority of RAM that Grbl uses is based on this buffer size. Only increase if there is extra // available RAM, like when re-compiling for a Mega or Sanguino. Or decrease if the Arduino // begins to crash due to the lack of available RAM or if the CPU is having trouble keeping // up with planning new incoming motions as they are executed. // #define BLOCK_BUFFER_SIZE 36 // Uncomment to override default in planner.h. // Governs the size of the intermediary step segment buffer between the step execution algorithm // and the planner blocks. Each segment is set of steps executed at a constant velocity over a // fixed time defined by ACCELERATION_TICKS_PER_SECOND. They are computed such that the planner // block velocity profile is traced exactly. The size of this buffer governs how much step // execution lead time there is for other Grbl processes have to compute and do their thing // before having to come back and refill this buffer, currently at ~50msec of step moves. // #define SEGMENT_BUFFER_SIZE 10 // Uncomment to override default in stepper.h. // Line buffer size from the serial input stream to be executed. Also, governs the size of // each of the startup blocks, as they are each stored as a string of this size. Make sure // to account for the available EEPROM at the defined memory address in settings.h and for // the number of desired startup blocks. // NOTE: 80 characters is not a problem except for extreme cases, but the line buffer size // can be too small and g-code blocks can get truncated. Officially, the g-code standards // support up to 256 characters. In future versions, this default will be increased, when // we know how much extra memory space we can re-invest into this. // #define LINE_BUFFER_SIZE 256 // Uncomment to override default in protocol.h // Serial send and receive buffer size. The receive buffer is often used as another streaming // buffer to store incoming blocks to be processed by Grbl when its ready. Most streaming // interfaces will character count and track each block send to each block response. So, // increase the receive buffer if a deeper receive buffer is needed for streaming and avaiable // memory allows. The send buffer primarily handles messages in Grbl. Only increase if large // messages are sent and Grbl begins to stall, waiting to send the rest of the message. // NOTE: Buffer size values must be greater than zero and less than 256. // #define RX_BUFFER_SIZE 255 // Uncomment to override defaults in serial.h // #define TX_BUFFER_SIZE 255 // The maximum line length of a data string stored in EEPROM. Used by startup lines and build // info. This size differs from the LINE_BUFFER_SIZE as the EEPROM is usually limited in size. // NOTE: Be very careful when changing this value. Check EEPROM address locations to make sure // these string storage locations won't corrupt one another. // #define EEPROM_LINE_SIZE 80 // Uncomment to override defaults in settings.h // Toggles XON/XOFF software flow control for serial communications. Not officially supported // due to problems involving the Atmega8U2 USB-to-serial chips on current Arduinos. The firmware // on these chips do not support XON/XOFF flow control characters and the intermediate buffer // in the chips cause latency and overflow problems with standard terminal programs. However, // using specifically-programmed UI's to manage this latency problem has been confirmed to work. // As well as, older FTDI FT232RL-based Arduinos(Duemilanove) are known to work with standard // terminal programs since their firmware correctly manage these XON/XOFF characters. In any // case, please report any successes to grbl administrators! // #define ENABLE_XONXOFF // Default disabled. Uncomment to enable. // A simple software debouncing feature for hard limit switches. When enabled, the interrupt // monitoring the hard limit switch pins will enable the Arduino's watchdog timer to re-check // the limit pin state after a delay of about 32msec. This can help with CNC machines with // problematic false triggering of their hard limit switches, but it WILL NOT fix issues with // electrical interference on the signal cables from external sources. It's recommended to first // use shielded signal cables with their shielding connected to ground (old USB/computer cables // work well and are cheap to find) and wire in a low-pass circuit into each limit pin. // #define ENABLE_SOFTWARE_DEBOUNCE // Default disabled. Uncomment to enable. // Configures the position after a probing cycle during Grbl's check mode. Disabled sets // the position to the probe target, when enabled sets the position to the start position. // #define SET_CHECK_MODE_PROBE_TO_START // Default disabled. Uncomment to enable. // Force Grbl to check the state of the hard limit switches when the processor detects a pin // change inside the hard limit ISR routine. By default, Grbl will trigger the hard limits // alarm upon any pin change, since bouncing switches can cause a state check like this to // misread the pin. When hard limits are triggered, they should be 100% reliable, which is the // reason that this option is disabled by default. Only if your system/electronics can guarantee // that the switches don't bounce, we recommend enabling this option. This will help prevent // triggering a hard limit when the machine disengages from the switch. // NOTE: This option has no effect if SOFTWARE_DEBOUNCE is enabled. // #define HARD_LIMIT_FORCE_STATE_CHECK // Default disabled. Uncomment to enable. // Adjusts homing cycle search and locate scalars. These are the multipliers used by Grbl's // homing cycle to ensure the limit switches are engaged and cleared through each phase of // the cycle. The search phase uses the axes max-travel setting times the SEARCH_SCALAR to // determine distance to look for the limit switch. Once found, the locate phase begins and // uses the homing pull-off distance setting times the LOCATE_SCALAR to pull-off and re-engage // the limit switch. // NOTE: Both of these values must be greater than 1.0 to ensure proper function. // #define HOMING_AXIS_SEARCH_SCALAR 1.5 // Uncomment to override defaults in limits.c. // #define HOMING_AXIS_LOCATE_SCALAR 10.0 // Uncomment to override defaults in limits.c. // Enable the '$RST=*', '$RST=$', and '$RST=#' eeprom restore commands. There are cases where // these commands may be undesirable. Simply comment the desired macro to disable it. // NOTE: See SETTINGS_RESTORE_ALL macro for customizing the `$RST=*` command. #define ENABLE_RESTORE_EEPROM_WIPE_ALL // '$RST=*' Default enabled. Comment to disable. #define ENABLE_RESTORE_EEPROM_DEFAULT_SETTINGS // '$RST=$' Default enabled. Comment to disable. #define ENABLE_RESTORE_EEPROM_CLEAR_PARAMETERS // '$RST=#' Default enabled. Comment to disable. // Defines the EEPROM data restored upon a settings version change and `$RST=*` command. Whenever the // the settings or other EEPROM data structure changes between Grbl versions, Grbl will automatically // wipe and restore the EEPROM. This macro controls what data is wiped and restored. This is useful // particularily for OEMs that need to retain certain data. For example, the BUILD_INFO string can be // written into the Arduino EEPROM via a seperate .INO sketch to contain product data. Altering this // macro to not restore the build info EEPROM will ensure this data is retained after firmware upgrades. // NOTE: Uncomment to override defaults in settings.h // #define SETTINGS_RESTORE_ALL (SETTINGS_RESTORE_DEFAULTS | SETTINGS_RESTORE_PARAMETERS | SETTINGS_RESTORE_STARTUP_LINES | SETTINGS_RESTORE_BUILD_INFO) // Enable the '$I=(string)' build info write command. If disabled, any existing build info data must // be placed into EEPROM via external means with a valid checksum value. This macro option is useful // to prevent this data from being over-written by a user, when used to store OEM product data. // NOTE: If disabled and to ensure Grbl can never alter the build info line, you'll also need to enable // the SETTING_RESTORE_ALL macro above and remove SETTINGS_RESTORE_BUILD_INFO from the mask. // NOTE: See the included grblWrite_BuildInfo.ino example file to write this string seperately. #define ENABLE_BUILD_INFO_WRITE_COMMAND // '$I=' Default enabled. Comment to disable. // AVR processors require all interrupts to be disabled during an EEPROM write. This includes both // the stepper ISRs and serial comm ISRs. In the event of a long EEPROM write, this ISR pause can // cause active stepping to lose position and serial receive data to be lost. This configuration // option forces the planner buffer to completely empty whenever the EEPROM is written to prevent // any chance of lost steps. // However, this doesn't prevent issues with lost serial RX data during an EEPROM write, especially // if a GUI is premptively filling up the serial RX buffer simultaneously. It's highly advised for // GUIs to flag these gcodes (G10,G28.1,G30.1) to always wait for an 'ok' after a block containing // one of these commands before sending more data to eliminate this issue. // NOTE: Most EEPROM write commands are implicitly blocked during a job (all '$' commands). However, // coordinate set g-code commands (G10,G28/30.1) are not, since they are part of an active streaming // job. At this time, this option only forces a planner buffer sync with these g-code commands. #define FORCE_BUFFER_SYNC_DURING_EEPROM_WRITE // Default enabled. Comment to disable. // In Grbl v0.9 and prior, there is an old outstanding bug where the `WPos:` work position reported // may not correlate to what is executing, because `WPos:` is based on the g-code parser state, which // can be several motions behind. This option forces the planner buffer to empty, sync, and stop // motion whenever there is a command that alters the work coordinate offsets `G10,G43.1,G92,G54-59`. // This is the simplest way to ensure `WPos:` is always correct. Fortunately, it's exceedingly rare // that any of these commands are used need continuous motions through them. #define FORCE_BUFFER_SYNC_DURING_WCO_CHANGE // Default enabled. Comment to disable. // By default, Grbl disables feed rate overrides for all G38.x probe cycle commands. Although this // may be different than some pro-class machine control, it's arguable that it should be this way. // Most probe sensors produce different levels of error that is dependent on rate of speed. By // keeping probing cycles to their programmed feed rates, the probe sensor should be a lot more // repeatable. If needed, you can disable this behavior by uncommenting the define below. // #define ALLOW_FEED_OVERRIDE_DURING_PROBE_CYCLES // Default disabled. Uncomment to enable. // Enables and configures parking motion methods upon a safety door state. Primarily for OEMs // that desire this feature for their integrated machines. At the moment, Grbl assumes that // the parking motion only involves one axis, although the parking implementation was written // to be easily refactored for any number of motions on different axes by altering the parking // source code. At this time, Grbl only supports parking one axis (typically the Z-axis) that // moves in the positive direction upon retracting and negative direction upon restoring position. // The motion executes with a slow pull-out retraction motion, power-down, and a fast park. // Restoring to the resume position follows these set motions in reverse: fast restore to // pull-out position, power-up with a time-out, and plunge back to the original position at the // slower pull-out rate. // NOTE: Still a work-in-progress. Machine coordinates must be in all negative space and // does not work with HOMING_FORCE_SET_ORIGIN enabled. Parking motion also moves only in // positive direction. // #define PARKING_ENABLE // Default disabled. Uncomment to enable // Configure options for the parking motion, if enabled. #define PARKING_AXIS AXIS_3 // Define which axis that performs the parking motion #define PARKING_TARGET -5.0 // Parking axis target. In mm, as machine coordinate [-max_travel,0]. #define PARKING_RATE 500.0 // Parking fast rate after pull-out in mm/min. #define PARKING_PULLOUT_RATE 100.0 // Pull-out/plunge slow feed rate in mm/min. #define PARKING_PULLOUT_INCREMENT 5.0 // Spindle pull-out and plunge distance in mm. Incremental distance. // Must be positive value or equal to zero. // Enables a special set of M-code commands that enables and disables the parking motion. // These are controlled by `M56`, `M56 P1`, or `M56 Px` to enable and `M56 P0` to disable. // The command is modal and will be set after a planner sync. Since it is g-code, it is // executed in sync with g-code commands. It is not a real-time command. // NOTE: PARKING_ENABLE is required. By default, M56 is active upon initialization. Use // DEACTIVATE_PARKING_UPON_INIT to set M56 P0 as the power-up default. // #define ENABLE_PARKING_OVERRIDE_CONTROL // Default disabled. Uncomment to enable // #define DEACTIVATE_PARKING_UPON_INIT // Default disabled. Uncomment to enable. // This option will automatically disab // Enables and configures Grbl's sleep mode feature. If the spindle or coolant are powered and Grbl // is not actively moving or receiving any commands, a sleep timer will start. If any data or commands // are received, the sleep timer will reset and restart until the above condition are not satisfied. // If the sleep timer elaspes, Grbl will immediately execute the sleep mode by shutting down the spindle // and coolant and entering a safe sleep state. If parking is enabled, Grbl will park the machine as // well. While in sleep mode, only a hard/soft reset will exit it and the job will be unrecoverable. // NOTE: Sleep mode is a safety feature, primarily to address communication disconnect problems. To // keep Grbl from sleeping, employ a stream of '?' status report commands as a connection "heartbeat". // #define SLEEP_ENABLE // Default disabled. Uncomment to enable. #define SLEEP_DURATION 5.0 // Float (0.25 - 61.0) seconds before sleep mode is executed. // This option will automatically disable the laser during a feed hold by invoking a spindle stop // override immediately after coming to a stop. However, this also means that the laser still may // be reenabled by disabling the spindle stop override, if needed. This is purely a safety feature // to ensure the laser doesn't inadvertently remain powered while at a stop and cause a fire. #define DISABLE_LASER_DURING_HOLD // Default enabled. Comment to disable. // Enables a piecewise linear model of the spindle PWM/speed output. Requires a solution by the // 'fit_nonlinear_spindle.py' script in the /doc/script folder of the repo. See file comments // on how to gather spindle data and run the script to generate a solution. // #define ENABLE_PIECEWISE_LINEAR_SPINDLE // Default disabled. Uncomment to enable. // N_PIECES, RPM_MAX, RPM_MIN, RPM_POINTxx, and RPM_LINE_XX constants are all set and given by // the 'fit_nonlinear_spindle.py' script solution. Used only when ENABLE_PIECEWISE_LINEAR_SPINDLE // is enabled. Make sure the constant values are exactly the same as the script solution. // NOTE: When N_PIECES < 4, unused RPM_LINE and RPM_POINT defines are not required and omitted. #define N_PIECES 4 // Integer (1-4). Number of piecewise lines used in script solution. #define RPM_MAX 11686.4 // Max RPM of model. $30 > RPM_MAX will be limited to RPM_MAX. #define RPM_MIN 202.5 // Min RPM of model. $31 < RPM_MIN will be limited to RPM_MIN. #define RPM_POINT12 6145.4 // Used N_PIECES >=2. Junction point between lines 1 and 2. #define RPM_POINT23 9627.8 // Used N_PIECES >=3. Junction point between lines 2 and 3. #define RPM_POINT34 10813.9 // Used N_PIECES = 4. Junction point between lines 3 and 4. #define RPM_LINE_A1 3.197101e-03 // Used N_PIECES >=1. A and B constants of line 1. #define RPM_LINE_B1 -3.526076e-1 #define RPM_LINE_A2 1.722950e-2 // Used N_PIECES >=2. A and B constants of line 2. #define RPM_LINE_B2 8.588176e+01 #define RPM_LINE_A3 5.901518e-02 // Used N_PIECES >=3. A and B constants of line 3. #define RPM_LINE_B3 4.881851e+02 #define RPM_LINE_A4 1.203413e-01 // Used N_PIECES = 4. A and B constants of line 4. #define RPM_LINE_B4 1.151360e+03 /* --------------------------------------------------------------------------------------- OEM Single File Configuration Option Instructions: Paste the cpu_map and default setting definitions below without an enclosing #ifdef. Comment out the CPU_MAP_xxx and DEFAULT_xxx defines at the top of this file, and the compiler will ignore the contents of defaults.h and cpu_map.h and use the definitions below. */ // Paste CPU_MAP definitions here. // Paste default settings definitions here. #endif
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/lcd/language/language_ca.h
<reponame>DDilshani/CO326-project /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * Catalan * * LCD Menu Messages * See also http://marlinfw.org/docs/development/lcd_language.html * */ namespace Language_ca { using namespace Language_en; // Inherit undefined strings from English constexpr uint8_t CHARSIZE = 2; PROGMEM Language_Str LANGUAGE = _UxGT("Catalan"); PROGMEM Language_Str WELCOME_MSG = MACHINE_NAME _UxGT(" preparada."); PROGMEM Language_Str MSG_MEDIA_INSERTED = _UxGT("Targeta detectada."); PROGMEM Language_Str MSG_MEDIA_REMOVED = _UxGT("Targeta extreta."); PROGMEM Language_Str MSG_LCD_ENDSTOPS = _UxGT("Endstops"); PROGMEM Language_Str MSG_MAIN = _UxGT("Menú principal"); PROGMEM Language_Str MSG_AUTOSTART = _UxGT("Inici automatic"); PROGMEM Language_Str MSG_DISABLE_STEPPERS = _UxGT("Desactiva motors"); PROGMEM Language_Str MSG_DEBUG_MENU = _UxGT("Menu de depuracio"); PROGMEM Language_Str MSG_PROGRESS_BAR_TEST = _UxGT("Test barra progres"); PROGMEM Language_Str MSG_AUTO_HOME = _UxGT("Ves a l'origen"); PROGMEM Language_Str MSG_AUTO_HOME_X = _UxGT("X a origen"); PROGMEM Language_Str MSG_AUTO_HOME_Y = _UxGT("Y a origen"); PROGMEM Language_Str MSG_AUTO_HOME_Z = _UxGT("Z a origen"); PROGMEM Language_Str MSG_LEVEL_BED_HOMING = _UxGT("Origen XYZ"); PROGMEM Language_Str MSG_LEVEL_BED_WAITING = _UxGT("Premeu per iniciar"); PROGMEM Language_Str MSG_LEVEL_BED_NEXT_POINT = _UxGT("Següent punt"); PROGMEM Language_Str MSG_LEVEL_BED_DONE = _UxGT("Anivellament fet!"); PROGMEM Language_Str MSG_SET_HOME_OFFSETS = _UxGT("Ajusta decalatge"); PROGMEM Language_Str MSG_HOME_OFFSETS_APPLIED = _UxGT("Decalatge aplicat"); PROGMEM Language_Str MSG_SET_ORIGIN = _UxGT("Estableix origen"); PROGMEM Language_Str MSG_PREHEAT_1 = _UxGT("Preescalfa ") PREHEAT_1_LABEL; PROGMEM Language_Str MSG_PREHEAT_1_H = _UxGT("Preescalfa ") PREHEAT_1_LABEL " ~"; PROGMEM Language_Str MSG_PREHEAT_1_END = _UxGT("Preheat ") PREHEAT_1_LABEL _UxGT(" End"); PROGMEM Language_Str MSG_PREHEAT_1_END_E = _UxGT("Preheat ") PREHEAT_1_LABEL _UxGT(" End ~"); PROGMEM Language_Str MSG_PREHEAT_1_ALL = _UxGT("Preheat ") PREHEAT_1_LABEL _UxGT(" Tot"); PROGMEM Language_Str MSG_PREHEAT_1_BEDONLY = _UxGT("Preheat ") PREHEAT_1_LABEL _UxGT(" Llit"); PROGMEM Language_Str MSG_PREHEAT_1_SETTINGS = _UxGT("Preheat ") PREHEAT_1_LABEL _UxGT(" Conf."); PROGMEM Language_Str MSG_PREHEAT_2 = _UxGT("Preescalfa ") PREHEAT_2_LABEL; PROGMEM Language_Str MSG_PREHEAT_2_H = _UxGT("Preescalfa ") PREHEAT_2_LABEL " ~"; PROGMEM Language_Str MSG_PREHEAT_2_END = _UxGT("Preheat ") PREHEAT_2_LABEL _UxGT(" End"); PROGMEM Language_Str MSG_PREHEAT_2_END_E = _UxGT("Preheat ") PREHEAT_2_LABEL _UxGT(" End ~"); PROGMEM Language_Str MSG_PREHEAT_2_ALL = _UxGT("Preheat ") PREHEAT_2_LABEL _UxGT(" Tot"); PROGMEM Language_Str MSG_PREHEAT_2_BEDONLY = _UxGT("Preheat ") PREHEAT_2_LABEL _UxGT(" Llit"); PROGMEM Language_Str MSG_PREHEAT_2_SETTINGS = _UxGT("Preheat ") PREHEAT_2_LABEL _UxGT(" Conf."); PROGMEM Language_Str MSG_COOLDOWN = _UxGT("Refreda"); PROGMEM Language_Str MSG_SWITCH_PS_ON = _UxGT("Switch power on"); PROGMEM Language_Str MSG_SWITCH_PS_OFF = _UxGT("Switch power off"); PROGMEM Language_Str MSG_EXTRUDE = _UxGT("Extrudeix"); PROGMEM Language_Str MSG_RETRACT = _UxGT("Retreu"); PROGMEM Language_Str MSG_MOVE_AXIS = _UxGT("Mou eixos"); PROGMEM Language_Str MSG_BED_LEVELING = _UxGT("Anivella llit"); PROGMEM Language_Str MSG_LEVEL_BED = _UxGT("Anivella llit"); PROGMEM Language_Str MSG_MOVING = _UxGT("Movent.."); PROGMEM Language_Str MSG_FREE_XY = _UxGT("XY lliures"); PROGMEM Language_Str MSG_MOVE_X = _UxGT("Mou X"); PROGMEM Language_Str MSG_MOVE_Y = _UxGT("Mou Y"); PROGMEM Language_Str MSG_MOVE_Z = _UxGT("Mou Z"); PROGMEM Language_Str MSG_MOVE_E = _UxGT("Extrusor"); PROGMEM Language_Str MSG_MOVE_EN = _UxGT("Extrusor *"); PROGMEM Language_Str MSG_MOVE_Z_DIST = _UxGT("Mou %smm"); PROGMEM Language_Str MSG_MOVE_01MM = _UxGT("Mou 0.1mm"); PROGMEM Language_Str MSG_MOVE_1MM = _UxGT("Mou 1mm"); PROGMEM Language_Str MSG_MOVE_10MM = _UxGT("Mou 10mm"); PROGMEM Language_Str MSG_SPEED = _UxGT("Velocitat"); PROGMEM Language_Str MSG_BED_Z = _UxGT("Llit Z"); PROGMEM Language_Str MSG_NOZZLE = _UxGT("Nozzle"); PROGMEM Language_Str MSG_NOZZLE_N = _UxGT("Nozzle ~"); PROGMEM Language_Str MSG_BED = _UxGT("Llit"); PROGMEM Language_Str MSG_FAN_SPEED = _UxGT("Vel. Ventilador"); PROGMEM Language_Str MSG_FAN_SPEED_N = _UxGT("Vel. Ventilador ~"); PROGMEM Language_Str MSG_FLOW = _UxGT("Flux"); PROGMEM Language_Str MSG_FLOW_N = _UxGT("Flux ~"); PROGMEM Language_Str MSG_VTRAV_MIN = _UxGT("VViatge min"); PROGMEM Language_Str MSG_AMAX_A = _UxGT("Accel. max ") LCD_STR_A; PROGMEM Language_Str MSG_AMAX_B = _UxGT("Accel. max ") LCD_STR_B; PROGMEM Language_Str MSG_AMAX_C = _UxGT("Accel. max ") LCD_STR_C; PROGMEM Language_Str MSG_AMAX_E = _UxGT("Accel. max ") LCD_STR_E; PROGMEM Language_Str MSG_AMAX_EN = _UxGT("Accel. max *"); PROGMEM Language_Str MSG_A_RETRACT = _UxGT("Accel. retracc"); PROGMEM Language_Str MSG_A_TRAVEL = _UxGT("Accel. Viatge"); PROGMEM Language_Str MSG_STEPS_PER_MM = _UxGT("Passos/mm"); PROGMEM Language_Str MSG_A_STEPS = LCD_STR_A _UxGT("passos/mm"); PROGMEM Language_Str MSG_B_STEPS = LCD_STR_B _UxGT("passos/mm"); PROGMEM Language_Str MSG_C_STEPS = LCD_STR_C _UxGT("passos/mm"); PROGMEM Language_Str MSG_E_STEPS = _UxGT("Epassos/mm"); PROGMEM Language_Str MSG_EN_STEPS = _UxGT("*passos/mm"); PROGMEM Language_Str MSG_TEMPERATURE = _UxGT("Temperatura"); PROGMEM Language_Str MSG_MOTION = _UxGT("Moviment"); PROGMEM Language_Str MSG_FILAMENT = _UxGT("Filament"); PROGMEM Language_Str MSG_VOLUMETRIC_ENABLED = _UxGT("E en mm³"); PROGMEM Language_Str MSG_FILAMENT_DIAM = _UxGT("Diam. Fil."); PROGMEM Language_Str MSG_FILAMENT_DIAM_E = _UxGT("Diam. Fil. *"); PROGMEM Language_Str MSG_CONTRAST = _UxGT("Contrast de LCD"); PROGMEM Language_Str MSG_STORE_EEPROM = _UxGT("Desa memoria"); PROGMEM Language_Str MSG_LOAD_EEPROM = _UxGT("Carrega memoria"); PROGMEM Language_Str MSG_RESTORE_FAILSAFE = _UxGT("Restaura valors"); PROGMEM Language_Str MSG_REFRESH = LCD_STR_REFRESH _UxGT("Actualitza"); PROGMEM Language_Str MSG_INFO_SCREEN = _UxGT("Pantalla Info."); PROGMEM Language_Str MSG_PREPARE = _UxGT("Prepara"); PROGMEM Language_Str MSG_TUNE = _UxGT("Ajusta"); PROGMEM Language_Str MSG_PAUSE_PRINT = _UxGT("Pausa impressio"); PROGMEM Language_Str MSG_RESUME_PRINT = _UxGT("Repren impressio"); PROGMEM Language_Str MSG_STOP_PRINT = _UxGT("Atura impressio."); PROGMEM Language_Str MSG_MEDIA_MENU = _UxGT("Imprimeix de SD"); PROGMEM Language_Str MSG_NO_MEDIA = _UxGT("No hi ha targeta"); PROGMEM Language_Str MSG_DWELL = _UxGT("En repos..."); PROGMEM Language_Str MSG_USERWAIT = _UxGT("Esperant usuari.."); PROGMEM Language_Str MSG_PRINT_ABORTED = _UxGT("Imp. cancelada"); PROGMEM Language_Str MSG_NO_MOVE = _UxGT("Sense moviment."); PROGMEM Language_Str MSG_KILLED = _UxGT("MATAT."); PROGMEM Language_Str MSG_STOPPED = _UxGT("ATURADA."); PROGMEM Language_Str MSG_CONTROL_RETRACT = _UxGT("Retreu mm"); PROGMEM Language_Str MSG_CONTROL_RETRACT_SWAP = _UxGT("Swap Retreure mm"); PROGMEM Language_Str MSG_CONTROL_RETRACTF = _UxGT("Retreu V"); PROGMEM Language_Str MSG_CONTROL_RETRACT_ZHOP = _UxGT("Aixeca mm"); PROGMEM Language_Str MSG_CONTROL_RETRACT_RECOVER = _UxGT("DesRet +mm"); PROGMEM Language_Str MSG_CONTROL_RETRACT_RECOVER_SWAP = _UxGT("Swap DesRet +mm"); PROGMEM Language_Str MSG_CONTROL_RETRACT_RECOVERF = _UxGT("DesRet V"); PROGMEM Language_Str MSG_AUTORETRACT = _UxGT("Auto retraccio"); PROGMEM Language_Str MSG_FILAMENTCHANGE = _UxGT("Canvia filament"); PROGMEM Language_Str MSG_FILAMENTCHANGE_E = _UxGT("Canvia filament *"); PROGMEM Language_Str MSG_INIT_MEDIA = _UxGT("Inicialitza SD"); PROGMEM Language_Str MSG_CHANGE_MEDIA = _UxGT("Canvia SD"); PROGMEM Language_Str MSG_ZPROBE_OUT = _UxGT("Sonda Z fora"); PROGMEM Language_Str MSG_BLTOUCH_RESET = _UxGT("Reinicia BLTouch"); PROGMEM Language_Str MSG_HOME_FIRST = _UxGT("Home %s%s%s primer"); PROGMEM Language_Str MSG_ZPROBE_ZOFFSET = _UxGT("Decalatge Z"); PROGMEM Language_Str MSG_BABYSTEP_X = _UxGT("Micropas X"); PROGMEM Language_Str MSG_BABYSTEP_Y = _UxGT("Micropas Y"); PROGMEM Language_Str MSG_BABYSTEP_Z = _UxGT("Micropas Z"); PROGMEM Language_Str MSG_ENDSTOP_ABORT = _UxGT("Cancel. Endstop"); PROGMEM Language_Str MSG_HEATING_FAILED_LCD = _UxGT("Error al escalfar"); PROGMEM Language_Str MSG_ERR_REDUNDANT_TEMP = _UxGT("Err: TEMP REDUNDANT"); PROGMEM Language_Str MSG_THERMAL_RUNAWAY = _UxGT("THERMAL RUNAWAY"); PROGMEM Language_Str MSG_ERR_MAXTEMP = _UxGT("Err: TEMP MAXIMA"); PROGMEM Language_Str MSG_ERR_MINTEMP = _UxGT("Err: TEMP MINIMA"); PROGMEM Language_Str MSG_ERR_Z_HOMING = _UxGT("Home XY primer"); PROGMEM Language_Str MSG_HALTED = _UxGT("IMPRESSORA PARADA"); PROGMEM Language_Str MSG_PLEASE_RESET = _UxGT("Reinicieu"); PROGMEM Language_Str MSG_SHORT_DAY = _UxGT("d"); // One character only PROGMEM Language_Str MSG_SHORT_HOUR = _UxGT("h"); // One character only PROGMEM Language_Str MSG_SHORT_MINUTE = _UxGT("m"); // One character only PROGMEM Language_Str MSG_HEATING = _UxGT("Escalfant..."); PROGMEM Language_Str MSG_BED_HEATING = _UxGT("Escalfant llit..."); PROGMEM Language_Str MSG_DELTA_CALIBRATE = _UxGT("Calibratge Delta"); PROGMEM Language_Str MSG_DELTA_CALIBRATE_X = _UxGT("Calibra X"); PROGMEM Language_Str MSG_DELTA_CALIBRATE_Y = _UxGT("Calibra Y"); PROGMEM Language_Str MSG_DELTA_CALIBRATE_Z = _UxGT("Calibra Z"); PROGMEM Language_Str MSG_DELTA_CALIBRATE_CENTER = _UxGT("Calibra el centre"); PROGMEM Language_Str MSG_INFO_MENU = _UxGT("Quant a la impr."); PROGMEM Language_Str MSG_INFO_PRINTER_MENU = _UxGT("Info Impressora"); PROGMEM Language_Str MSG_INFO_STATS_MENU = _UxGT("Estadistiques"); PROGMEM Language_Str MSG_INFO_BOARD_MENU = _UxGT("Info placa"); PROGMEM Language_Str MSG_INFO_THERMISTOR_MENU = _UxGT("Termistors"); PROGMEM Language_Str MSG_INFO_EXTRUDERS = _UxGT("Extrusors"); PROGMEM Language_Str MSG_INFO_BAUDRATE = _UxGT("Baud"); PROGMEM Language_Str MSG_INFO_PROTOCOL = _UxGT("Protocol"); PROGMEM Language_Str MSG_CASE_LIGHT = _UxGT("Llum"); #if LCD_WIDTH >= 20 PROGMEM Language_Str MSG_INFO_PRINT_COUNT = _UxGT("Total impressions"); PROGMEM Language_Str MSG_INFO_COMPLETED_PRINTS = _UxGT("Acabades"); PROGMEM Language_Str MSG_INFO_PRINT_TIME = _UxGT("Temps imprimint"); PROGMEM Language_Str MSG_INFO_PRINT_LONGEST = _UxGT("Treball mes llarg"); PROGMEM Language_Str MSG_INFO_PRINT_FILAMENT = _UxGT("Total extrudit"); #else PROGMEM Language_Str MSG_INFO_PRINT_COUNT = _UxGT("Impressions"); PROGMEM Language_Str MSG_INFO_COMPLETED_PRINTS = _UxGT("Acabades"); PROGMEM Language_Str MSG_INFO_PRINT_TIME = _UxGT("Total"); PROGMEM Language_Str MSG_INFO_PRINT_LONGEST = _UxGT("Mes llarg"); PROGMEM Language_Str MSG_INFO_PRINT_FILAMENT = _UxGT("Extrudit"); #endif PROGMEM Language_Str MSG_INFO_MIN_TEMP = _UxGT("Temp. mínima"); PROGMEM Language_Str MSG_INFO_MAX_TEMP = _UxGT("Temp. màxima"); PROGMEM Language_Str MSG_INFO_PSU = _UxGT("Font alimentacio"); PROGMEM Language_Str MSG_DRIVE_STRENGTH = _UxGT("Força motor"); PROGMEM Language_Str MSG_DAC_PERCENT_X = _UxGT("X Driver %"); PROGMEM Language_Str MSG_DAC_PERCENT_Y = _UxGT("Y Driver %"); PROGMEM Language_Str MSG_DAC_PERCENT_Z = _UxGT("Z Driver %"); PROGMEM Language_Str MSG_DAC_PERCENT_E = _UxGT("E Driver %"); PROGMEM Language_Str MSG_DAC_EEPROM_WRITE = _UxGT("DAC EEPROM Write"); PROGMEM Language_Str MSG_FILAMENT_CHANGE_OPTION_RESUME = _UxGT("Repren impressió"); PROGMEM Language_Str MSG_EXPECTED_PRINTER = _UxGT("Impressora incorrecta"); // // Filament Change screens show up to 3 lines on a 4-line display // ...or up to 2 lines on a 3-line display // #if LCD_HEIGHT >= 4 PROGMEM Language_Str MSG_FILAMENT_CHANGE_INIT = _UxGT(MSG_3_LINE("Esperant per", "iniciar el canvi", "de filament")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_UNLOAD = _UxGT(MSG_2_LINE("Esperant per", "treure filament")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_INSERT = _UxGT(MSG_3_LINE("Poseu filament", "i premeu el boto", "per continuar...")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_HEAT = _UxGT(MSG_2_LINE("Premeu boto per", "escalfar nozzle.")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_HEATING = _UxGT(MSG_2_LINE("Escalfant nozzle", "Espereu...")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_LOAD = _UxGT(MSG_2_LINE("Esperant carrega", "de filament")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_RESUME = _UxGT(MSG_2_LINE("Esperant per", "reprendre")); #else // LCD_HEIGHT < 4 PROGMEM Language_Str MSG_FILAMENT_CHANGE_INIT = _UxGT(MSG_1_LINE("Espereu...")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_UNLOAD = _UxGT(MSG_1_LINE("Expulsant...")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_INSERT = _UxGT(MSG_1_LINE("Insereix i prem")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_HEATING = _UxGT(MSG_1_LINE("Escalfant...")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_LOAD = _UxGT(MSG_1_LINE("Carregant...")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_RESUME = _UxGT(MSG_1_LINE("Reprenent...")); #endif // LCD_HEIGHT < 4 }
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/HAL/shared/servo.h
<reponame>DDilshani/CO326-project /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * servo.h - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2 * Copyright (c) 2009 <NAME>. All right reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * * A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method. * The servos are pulsed in the background using the value most recently written using the write() method * * Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached. * Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four. * The sequence used to seize timers is defined in timers.h * * The methods are: * * Servo - Class for manipulating servo motors connected to Arduino pins. * * attach(pin ) - Attaches a servo motor to an i/o pin. * attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds * default min is 544, max is 2400 * * write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds) * writeMicroseconds() - Sets the servo pulse width in microseconds * read() - Gets the last written servo pulse width as an angle between 0 and 180. * readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release) * attached() - Returns true if there is a servo attached. * detach() - Stops an attached servos from pulsing its i/o pin. * move(angle) - Sequence of attach(0), write(angle), * With DEACTIVATE_SERVOS_AFTER_MOVE wait SERVO_DELAY and detach. */ #if IS_TEENSY32 #include "../HAL_TEENSY31_32/Servo.h" #elif IS_TEENSY35 || IS_TEENSY36 #include "../HAL_TEENSY35_36/Servo.h" #elif defined(TARGET_LPC1768) #include "../HAL_LPC1768/Servo.h" #elif defined(__STM32F1__) || defined(TARGET_STM32F1) #include "../HAL_STM32F1/Servo.h" #elif defined(STM32GENERIC) && defined(STM32F4) #include "../HAL_STM32_F4_F7/Servo.h" #elif defined(ARDUINO_ARCH_STM32) #include "../HAL_STM32/Servo.h" #elif defined(ARDUINO_ARCH_ESP32) #include "../HAL_ESP32/Servo.h" #else #include <stdint.h> #if defined(__AVR__) || defined(ARDUINO_ARCH_SAM) || defined(__SAMD51__) // we're good to go #else #error "This library only supports boards with an AVR, SAM3X or SAMD51 processor." #endif #define Servo_VERSION 2 // software version of this library class Servo { public: Servo(); int8_t attach(const int pin); // attach the given pin to the next free channel, set pinMode, return channel number (-1 on fail) int8_t attach(const int pin, const int min, const int max); // as above but also sets min and max values for writes. void detach(); void write(int value); // if value is < 200 it is treated as an angle, otherwise as pulse width in microseconds void writeMicroseconds(int value); // write pulse width in microseconds void move(const int value); // attach the servo, then move to value // if value is < 200 it is treated as an angle, otherwise as pulse width in microseconds // if DEACTIVATE_SERVOS_AFTER_MOVE wait SERVO_DELAY, then detach int read(); // returns current pulse width as an angle between 0 and 180 degrees int readMicroseconds(); // returns current pulse width in microseconds for this servo (was read_us() in first release) bool attached(); // return true if this servo is attached, otherwise false private: uint8_t servoIndex; // index into the channel data for this servo int8_t min; // minimum is this value times 4 added to MIN_PULSE_WIDTH int8_t max; // maximum is this value times 4 added to MAX_PULSE_WIDTH }; #endif
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/HAL/HAL_LPC1768/inc/SanityCheck.h
<reponame>DDilshani/CO326-project /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once #if PIO_PLATFORM_VERSION < 1001 #error "nxplpc-arduino-lpc176x package is out of date, Please update the PlatformIO platforms, frameworks and libraries. You may need to remove the platform and let it reinstall automatically." #endif #if PIO_FRAMEWORK_VERSION < 2002 #error "framework-arduino-lpc176x package is out of date, Please update the PlatformIO platforms, frameworks and libraries." #endif /** * Detect an old pins file by checking for old ADC pins values. */ #define _OLD_TEMP_PIN(P) PIN_EXISTS(P) && _CAT(P,_PIN) <= 7 && _CAT(P,_PIN) != 2 && _CAT(P,_PIN) != 3 #if _OLD_TEMP_PIN(TEMP_BED) #error "TEMP_BED_PIN must be defined using the Pn_nn or Pn_nn_An format. (See the included pins files)." #elif _OLD_TEMP_PIN(TEMP_0) #error "TEMP_0_PIN must be defined using the Pn_nn or Pn_nn_An format. (See the included pins files)." #elif _OLD_TEMP_PIN(TEMP_1) #error "TEMP_1_PIN must be defined using the Pn_nn or Pn_nn_An format. (See the included pins files)." #elif _OLD_TEMP_PIN(TEMP_2) #error "TEMP_2_PIN must be defined using the Pn_nn or Pn_nn_An format. (See the included pins files)." #elif _OLD_TEMP_PIN(TEMP_3) #error "TEMP_3_PIN must be defined using the Pn_nn or Pn_nn_An format. (See the included pins files)." #elif _OLD_TEMP_PIN(TEMP_4) #error "TEMP_4_PIN must be defined using the Pn_nn or Pn_nn_An format. (See the included pins files)." #elif _OLD_TEMP_PIN(TEMP_5) #error "TEMP_5_PIN must be defined using the Pn_nn or Pn_nn_An format. (See the included pins files)." #elif _OLD_TEMP_PIN(TEMP_6) #error "TEMP_6_PIN must be defined using the Pn_nn or Pn_nn_An format. (See the included pins files)." #elif _OLD_TEMP_PIN(TEMP_7) #error "TEMP_7_PIN must be defined using the Pn_nn or Pn_nn_An format. (See the included pins files)." #endif #undef _OLD_TEMP_PIN /** * Because PWM hardware channels all share the same frequency, along with the * fallback software channels, FAST_PWM_FAN is incompatible with Servos. */ #if NUM_SERVOS > 0 && ENABLED(FAST_PWM_FAN) #error "BLTOUCH and Servos are incompatible with FAST_PWM_FAN on LPC176x boards." #endif /** * Test LPC176x-specific configuration values for errors at compile-time. */ //#if ENABLED(SPINDLE_LASER_PWM) && !(SPINDLE_LASER_PWM_PIN == 4 || SPINDLE_LASER_PWM_PIN == 6 || SPINDLE_LASER_PWM_PIN == 11) // #error "SPINDLE_LASER_PWM_PIN must use SERVO0, SERVO1 or SERVO3 connector" //#endif #if IS_RE_ARM_BOARD && ENABLED(REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER) && HAS_DRIVER(TMC2130) && DISABLED(TMC_USE_SW_SPI) #error "Re-ARM with REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER and TMC2130 require TMC_USE_SW_SPI" #endif #if ENABLED(BAUD_RATE_GCODE) #error "BAUD_RATE_GCODE is not yet supported on LPC176x." #endif
DDilshani/CO326-project
firmware/grbl-Mega/src/defaults.h
<filename>firmware/grbl-Mega/src/defaults.h /* defaults.h - defaults settings configuration file Part of Grbl Copyright (c) 2017-2018 <NAME> Copyright (c) 2012-2016 <NAME> for Gnea Research LLC Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ /* The defaults.h file serves as a central default settings selector for different machine types, from DIY CNC mills to CNC conversions of off-the-shelf machines. The settings files listed here are supplied by users, so your results may vary. However, this should give you a good starting point as you get to know your machine and tweak the settings for your nefarious needs. NOTE: Ensure one and only one of these DEFAULTS_XXX values is defined in config.h */ #ifndef defaults_h #ifdef DEFAULTS_GENERIC // Grbl generic default settings. Should work across different machines. #define DEFAULT_AXIS1_STEPS_PER_UNIT 200.0 #define DEFAULT_AXIS2_STEPS_PER_UNIT 800.0 #define DEFAULT_AXIS3_STEPS_PER_UNIT 800.0 #define DEFAULT_AXIS1_MAX_RATE 1000.0 // mm/min #define DEFAULT_AXIS2_MAX_RATE 300.0 // mm/min #define DEFAULT_AXIS3_MAX_RATE 300.0 // mm/min #define DEFAULT_AXIS1_ACCELERATION 100 // 10*60*60 mm/min^2 = 10 mm/sec^2 #define DEFAULT_AXIS2_ACCELERATION 100 // 10*60*60 mm/min^2 = 10 mm/sec^2 #define DEFAULT_AXIS3_ACCELERATION 100 // 10*60*60 mm/min^2 = 10 mm/sec^2 #define DEFAULT_AXIS1_MAX_TRAVEL 800.0 // mm NOTE: Must be a positive value. #define DEFAULT_AXIS2_MAX_TRAVEL 500.0 // mm NOTE: Must be a positive value. #define DEFAULT_AXIS3_MAX_TRAVEL 180.0 // mm NOTE: Must be a positive value. #define DEFAULT_SPINDLE_RPM_MAX 1000.0 // rpm #define DEFAULT_SPINDLE_RPM_MIN 0.0 // rpm #define DEFAULT_STEP_PULSE_MICROSECONDS 10 #define DEFAULT_STEPPING_INVERT_MASK 0 #define DEFAULT_DIRECTION_INVERT_MASK 0 #define DEFAULT_STEPPER_IDLE_LOCK_TIME 250 // msec (0-254, 255 keeps steppers enabled) #define DEFAULT_STATUS_REPORT_MASK 1 // MPos enabled #define DEFAULT_JUNCTION_DEVIATION 0.01 // mm #define DEFAULT_ARC_TOLERANCE 0.002 // mm #define DEFAULT_REPORT_INCHES 0 // false #define DEFAULT_INVERT_ST_ENABLE 0 // false #define DEFAULT_INVERT_LIMIT_PINS 0 // false #define DEFAULT_SOFT_LIMIT_ENABLE 0 // false #define DEFAULT_HARD_LIMIT_ENABLE 0 // false #define DEFAULT_INVERT_PROBE_PIN 0 // false #define DEFAULT_LASER_MODE 0 // false #define DEFAULT_HOMING_ENABLE 1 // false #define DEFAULT_HOMING_DIR_MASK 7 // move positive dir #define DEFAULT_HOMING_FEED_RATE 250 // mm/min #define DEFAULT_HOMING_SEEK_RATE 1000 // mm/min #define DEFAULT_HOMING_DEBOUNCE_DELAY 250 // msec (0-65k) #define DEFAULT_HOMING_PULLOFF 2.0 // mm #endif #ifdef DEFAULTS_RAMPS_BOARD #define DEFAULT_AXIS1_STEPS_PER_UNIT 200 #define DEFAULT_AXIS2_STEPS_PER_UNIT 800 #define DEFAULT_AXIS3_STEPS_PER_UNIT 800 #define DEFAULT_AXIS1_MAX_RATE 2000.0 // 9000 mm/min = 9000/60 = 150 mm/sec #define DEFAULT_AXIS2_MAX_RATE 500.0 // 9000 mm/min = 9000/60 = 150 mm/sec #define DEFAULT_AXIS3_MAX_RATE 500.0 // 300 mm/min = 300/60 = 5 mm/sec #define DEFAULT_AXIS1_ACCELERATION (100.0*60*60) // 300*60*60 mm/min^2 = 300 mm/sec^2 #define DEFAULT_AXIS2_ACCELERATION (100.0*60*60) // 300*60*60 mm/min^2 = 300 mm/sec^2 #define DEFAULT_AXIS3_ACCELERATION (100.0*60*60) // 100*60*60 mm/min^2 = 100 mm/sec^2 #define DEFAULT_AXIS1_MAX_TRAVEL 800.0 // mm #define DEFAULT_AXIS2_MAX_TRAVEL 500.0 // mm #define DEFAULT_AXIS3_MAX_TRAVEL 180.0 // mm #if N_AXIS > 3 #define DEFAULT_AXIS4_STEPS_PER_UNIT 800 // Direct drive : (200 pas par tours * 1/16 microsteps)/360° #define DEFAULT_AXIS4_MAX_RATE 1000 // °/mn #define DEFAULT_AXIS4_ACCELERATION (100.0*60*60) // 100*60*60 mm/min^2 = 100 mm/sec^2 #define DEFAULT_AXIS4_MAX_TRAVEL 360.0 // ° #endif #if N_AXIS > 4 #define DEFAULT_AXIS5_STEPS_PER_UNIT 800 // Direct drive : (200 pas par tours * 1/16 microsteps)/360° #define DEFAULT_AXIS5_MAX_RATE 1000 // °/mn #define DEFAULT_AXIS5_ACCELERATION (100.0*60*60) // 100*60*60 mm/min^2 = 100 mm/sec^2 #define DEFAULT_AXIS5_MAX_TRAVEL 180.0 // ° #endif #if N_AXIS > 5 #define DEFAULT_AXIS6_STEPS_PER_UNIT 800 // Direct drive : (200 pas par tours * 1/16 microsteps)/360° #define DEFAULT_AXIS6_MAX_RATE 1000 // °/mn #define DEFAULT_AXIS6_ACCELERATION (100.0*60*60) // 100*60*60 mm/min^2 = 100 mm/sec^2 #define DEFAULT_AXIS6_MAX_TRAVEL 180.0 // ° #endif #define DEFAULT_SPINDLE_RPM_MAX 1000.0 // rpm #define DEFAULT_SPINDLE_RPM_MIN 0.0 // rpm #define DEFAULT_STEP_PULSE_MICROSECONDS 10 #define DEFAULT_STEPPING_INVERT_MASK 0 #define DEFAULT_DIRECTION_INVERT_MASK 0 #define DEFAULT_STEPPER_IDLE_LOCK_TIME 254 // msec (0-254, 255 keeps steppers enabled) #define DEFAULT_STATUS_REPORT_MASK 1 // MPos enabled #define DEFAULT_JUNCTION_DEVIATION 0.02 // mm #define DEFAULT_ARC_TOLERANCE 0.002 // mm #define DEFAULT_REPORT_INCHES 0 // false #define DEFAULT_INVERT_ST_ENABLE 0 // false #define DEFAULT_INVERT_LIMIT_PINS 0 // false #define DEFAULT_SOFT_LIMIT_ENABLE 1 // true #define DEFAULT_HARD_LIMIT_ENABLE 0 // false #define DEFAULT_INVERT_PROBE_PIN 0 // false #define DEFAULT_LASER_MODE 1 // false #define DEFAULT_HOMING_ENABLE 1 // true #define DEFAULT_HOMING_DIR_MASK 7 // move positive dir #define DEFAULT_HOMING_FEED_RATE 250 // mm/min #define DEFAULT_HOMING_SEEK_RATE 1000 // mm/min #define DEFAULT_HOMING_DEBOUNCE_DELAY 250 // msec (0-65k) #define DEFAULT_HOMING_PULLOFF 3 // mm #endif #endif
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/lcd/language/language_gl.h
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * Galician language (ISO "gl") * * LCD Menu Messages * See also http://marlinfw.org/docs/development/lcd_language.html * */ #define DISPLAY_CHARSET_ISO10646_1 #define NOT_EXTENDED_ISO10646_1_5X7 namespace Language_gl { using namespace Language_en; // Inherit undefined strings from English constexpr uint8_t CHARSIZE = 1; PROGMEM Language_Str LANGUAGE = _UxGT("Galician"); PROGMEM Language_Str WELCOME_MSG = MACHINE_NAME _UxGT(" lista."); PROGMEM Language_Str MSG_MEDIA_INSERTED = _UxGT("Tarxeta inserida"); PROGMEM Language_Str MSG_MEDIA_REMOVED = _UxGT("Tarxeta retirada"); PROGMEM Language_Str MSG_LCD_ENDSTOPS = _UxGT("FinCarro"); PROGMEM Language_Str MSG_MAIN = _UxGT("Menu principal"); PROGMEM Language_Str MSG_AUTOSTART = _UxGT("Autoarranque"); PROGMEM Language_Str MSG_DISABLE_STEPPERS = _UxGT("Apagar motores"); PROGMEM Language_Str MSG_AUTO_HOME = _UxGT("Ir a orixe"); PROGMEM Language_Str MSG_AUTO_HOME_X = _UxGT("Ir orixe X"); PROGMEM Language_Str MSG_AUTO_HOME_Y = _UxGT("Ir orixe Y"); PROGMEM Language_Str MSG_AUTO_HOME_Z = _UxGT("Ir orixe Z"); PROGMEM Language_Str MSG_LEVEL_BED_HOMING = _UxGT("Ir orixes XYZ"); PROGMEM Language_Str MSG_LEVEL_BED_WAITING = _UxGT("Prema pulsador"); PROGMEM Language_Str MSG_LEVEL_BED_NEXT_POINT = _UxGT("Seguinte punto"); PROGMEM Language_Str MSG_LEVEL_BED_DONE = _UxGT("Nivelado feito"); PROGMEM Language_Str MSG_SET_HOME_OFFSETS = _UxGT("Offsets na orixe"); PROGMEM Language_Str MSG_HOME_OFFSETS_APPLIED = _UxGT("Offsets fixados"); PROGMEM Language_Str MSG_SET_ORIGIN = _UxGT("Fixar orixe"); PROGMEM Language_Str MSG_PREHEAT_1 = _UxGT("Prequentar ") PREHEAT_1_LABEL; PROGMEM Language_Str MSG_PREHEAT_1_H = _UxGT("Prequentar ") PREHEAT_1_LABEL " ~"; PROGMEM Language_Str MSG_PREHEAT_1_END = _UxGT("Preque. ") PREHEAT_1_LABEL _UxGT(" Bico"); PROGMEM Language_Str MSG_PREHEAT_1_END_E = _UxGT("Preque. ") PREHEAT_1_LABEL _UxGT(" Bico ~"); PROGMEM Language_Str MSG_PREHEAT_1_ALL = _UxGT("Preque. ") PREHEAT_1_LABEL _UxGT(" Todo"); PROGMEM Language_Str MSG_PREHEAT_1_BEDONLY = _UxGT("Preque. ") PREHEAT_1_LABEL _UxGT(" Cama"); PROGMEM Language_Str MSG_PREHEAT_1_SETTINGS = _UxGT("Preque. ") PREHEAT_1_LABEL _UxGT(" conf"); PROGMEM Language_Str MSG_PREHEAT_2 = _UxGT("Prequentar ") PREHEAT_2_LABEL; PROGMEM Language_Str MSG_PREHEAT_2_H = _UxGT("Prequentar ") PREHEAT_2_LABEL " ~"; PROGMEM Language_Str MSG_PREHEAT_2_END = _UxGT("Preque. ") PREHEAT_2_LABEL _UxGT(" Bico"); PROGMEM Language_Str MSG_PREHEAT_2_END_E = _UxGT("Preque. ") PREHEAT_2_LABEL _UxGT(" Bico ~"); PROGMEM Language_Str MSG_PREHEAT_2_ALL = _UxGT("Preque. ") PREHEAT_2_LABEL _UxGT(" Todo"); PROGMEM Language_Str MSG_PREHEAT_2_BEDONLY = _UxGT("Preque. ") PREHEAT_2_LABEL _UxGT(" Cama"); PROGMEM Language_Str MSG_PREHEAT_2_SETTINGS = _UxGT("Preque. ") PREHEAT_2_LABEL _UxGT(" conf"); PROGMEM Language_Str MSG_COOLDOWN = _UxGT("Arrefriar"); PROGMEM Language_Str MSG_SWITCH_PS_ON = _UxGT("Acender"); PROGMEM Language_Str MSG_SWITCH_PS_OFF = _UxGT("Apagar"); PROGMEM Language_Str MSG_EXTRUDE = _UxGT("Extrudir"); PROGMEM Language_Str MSG_RETRACT = _UxGT("Retraer"); PROGMEM Language_Str MSG_MOVE_AXIS = _UxGT("Mover eixe"); PROGMEM Language_Str MSG_BED_LEVELING = _UxGT("Nivelar cama"); PROGMEM Language_Str MSG_LEVEL_BED = _UxGT("Nivelar cama"); PROGMEM Language_Str MSG_MOVE_X = _UxGT("Mover X"); PROGMEM Language_Str MSG_MOVE_Y = _UxGT("Mover Y"); PROGMEM Language_Str MSG_MOVE_Z = _UxGT("Mover Z"); PROGMEM Language_Str MSG_MOVE_E = _UxGT("Extrusor"); PROGMEM Language_Str MSG_MOVE_EN = _UxGT("Extrusor *"); PROGMEM Language_Str MSG_MOVE_Z_DIST = _UxGT("Mover %smm"); PROGMEM Language_Str MSG_MOVE_01MM = _UxGT("Mover 0.1mm"); PROGMEM Language_Str MSG_MOVE_1MM = _UxGT("Mover 1mm"); PROGMEM Language_Str MSG_MOVE_10MM = _UxGT("Mover 10mm"); PROGMEM Language_Str MSG_SPEED = _UxGT("Velocidade"); PROGMEM Language_Str MSG_BED_Z = _UxGT("Cama Z"); PROGMEM Language_Str MSG_NOZZLE = _UxGT("Bico"); PROGMEM Language_Str MSG_NOZZLE_N = _UxGT("Bico ~"); PROGMEM Language_Str MSG_BED = _UxGT("Cama"); PROGMEM Language_Str MSG_FAN_SPEED = _UxGT("Velocidade vent."); PROGMEM Language_Str MSG_FAN_SPEED_N = _UxGT("Velocidade vent. ~"); PROGMEM Language_Str MSG_FLOW = _UxGT("Fluxo"); PROGMEM Language_Str MSG_FLOW_N = _UxGT("Fluxo ~"); PROGMEM Language_Str MSG_MIN = " " LCD_STR_THERMOMETER _UxGT(" Min"); PROGMEM Language_Str MSG_MAX = " " LCD_STR_THERMOMETER _UxGT(" Max"); PROGMEM Language_Str MSG_FACTOR = " " LCD_STR_THERMOMETER _UxGT(" Fact"); PROGMEM Language_Str MSG_SELECT = _UxGT("Escolla"); PROGMEM Language_Str MSG_SELECT_E = _UxGT("Escolla *"); PROGMEM Language_Str MSG_ACC = _UxGT("Acel"); PROGMEM Language_Str MSG_STEPS_PER_MM = _UxGT("Pasos/mm"); PROGMEM Language_Str MSG_A_STEPS = LCD_STR_A _UxGT(" pasos/mm"); PROGMEM Language_Str MSG_B_STEPS = LCD_STR_B _UxGT(" pasos/mm"); PROGMEM Language_Str MSG_C_STEPS = LCD_STR_C _UxGT(" pasos/mm"); PROGMEM Language_Str MSG_E_STEPS = _UxGT("E pasos/mm"); PROGMEM Language_Str MSG_EN_STEPS = _UxGT("* pasos/mm"); PROGMEM Language_Str MSG_TEMPERATURE = _UxGT("Temperatura"); PROGMEM Language_Str MSG_MOTION = _UxGT("Movemento"); PROGMEM Language_Str MSG_FILAMENT = _UxGT("Filamento"); PROGMEM Language_Str MSG_VOLUMETRIC_ENABLED = _UxGT("E en mm³"); PROGMEM Language_Str MSG_FILAMENT_DIAM = _UxGT("Diam. fil."); PROGMEM Language_Str MSG_FILAMENT_DIAM_E = _UxGT("Diam. fil. *"); PROGMEM Language_Str MSG_CONTRAST = _UxGT("Constraste LCD"); PROGMEM Language_Str MSG_STORE_EEPROM = _UxGT("Gardar en memo."); PROGMEM Language_Str MSG_LOAD_EEPROM = _UxGT("Cargar de memo."); PROGMEM Language_Str MSG_RESTORE_FAILSAFE = _UxGT("Cargar de firm."); PROGMEM Language_Str MSG_REFRESH = LCD_STR_REFRESH _UxGT("Volver a cargar"); PROGMEM Language_Str MSG_INFO_SCREEN = _UxGT("Monitorizacion"); PROGMEM Language_Str MSG_PREPARE = _UxGT("Preparar"); PROGMEM Language_Str MSG_TUNE = _UxGT("Axustar"); PROGMEM Language_Str MSG_PAUSE_PRINT = _UxGT("Pausar impres."); PROGMEM Language_Str MSG_RESUME_PRINT = _UxGT("Seguir impres."); PROGMEM Language_Str MSG_STOP_PRINT = _UxGT("Deter impres."); PROGMEM Language_Str MSG_MEDIA_MENU = _UxGT("Tarxeta SD"); PROGMEM Language_Str MSG_NO_MEDIA = _UxGT("Sen tarxeta SD"); PROGMEM Language_Str MSG_DWELL = _UxGT("En repouso..."); PROGMEM Language_Str MSG_USERWAIT = _UxGT("A espera..."); PROGMEM Language_Str MSG_PRINT_ABORTED = _UxGT("Impre. cancelada"); PROGMEM Language_Str MSG_NO_MOVE = _UxGT("Sen movemento."); PROGMEM Language_Str MSG_KILLED = _UxGT("PROGRAMA MORTO"); PROGMEM Language_Str MSG_STOPPED = _UxGT("PROGRAMA PARADO"); PROGMEM Language_Str MSG_CONTROL_RETRACT = _UxGT("Retraccion mm"); PROGMEM Language_Str MSG_CONTROL_RETRACT_SWAP = _UxGT("Cambio retra. mm"); PROGMEM Language_Str MSG_CONTROL_RETRACTF = _UxGT("Retraccion V"); PROGMEM Language_Str MSG_CONTROL_RETRACT_ZHOP = _UxGT("Alzar Z mm"); PROGMEM Language_Str MSG_CONTROL_RETRACT_RECOVER = _UxGT("Recup. retra. mm"); PROGMEM Language_Str MSG_CONTROL_RETRACT_RECOVER_SWAP = _UxGT("Cambio recup. mm"); PROGMEM Language_Str MSG_CONTROL_RETRACT_RECOVERF = _UxGT("Recuperacion V"); PROGMEM Language_Str MSG_AUTORETRACT = _UxGT("Retraccion auto."); PROGMEM Language_Str MSG_FILAMENTCHANGE = _UxGT("Cambiar filamen."); PROGMEM Language_Str MSG_FILAMENTCHANGE_E = _UxGT("Cambiar filamen. *"); PROGMEM Language_Str MSG_INIT_MEDIA = _UxGT("Iniciando SD"); PROGMEM Language_Str MSG_CHANGE_MEDIA = _UxGT("Cambiar SD"); PROGMEM Language_Str MSG_ZPROBE_OUT = _UxGT("Sonda-Z sen cama"); PROGMEM Language_Str MSG_BLTOUCH_SELFTEST = _UxGT("Comprobar BLTouch"); PROGMEM Language_Str MSG_BLTOUCH_RESET = _UxGT("Iniciar BLTouch"); PROGMEM Language_Str MSG_ZPROBE_ZOFFSET = _UxGT("Offset Z"); PROGMEM Language_Str MSG_BABYSTEP_X = _UxGT("Micropaso X"); PROGMEM Language_Str MSG_BABYSTEP_Y = _UxGT("Micropaso Y"); PROGMEM Language_Str MSG_BABYSTEP_Z = _UxGT("Micropaso Z"); PROGMEM Language_Str MSG_ENDSTOP_ABORT = _UxGT("Erro fin carro"); PROGMEM Language_Str MSG_HEATING_FAILED_LCD = _UxGT("Fallo quentando"); PROGMEM Language_Str MSG_ERR_REDUNDANT_TEMP = _UxGT("Erro temperatura"); PROGMEM Language_Str MSG_THERMAL_RUNAWAY = _UxGT("Temp. excesiva"); PROGMEM Language_Str MSG_HALTED = _UxGT("SISTEMA MORTO"); PROGMEM Language_Str MSG_PLEASE_RESET = _UxGT("Debe reiniciar!"); PROGMEM Language_Str MSG_HEATING = _UxGT("Quentando..."); PROGMEM Language_Str MSG_BED_HEATING = _UxGT("Quentando cama..."); PROGMEM Language_Str MSG_DELTA_CALIBRATE = _UxGT("Calibracion Delta"); PROGMEM Language_Str MSG_DELTA_CALIBRATE_X = _UxGT("Calibrar X"); PROGMEM Language_Str MSG_DELTA_CALIBRATE_Y = _UxGT("Calibrar Y"); PROGMEM Language_Str MSG_DELTA_CALIBRATE_Z = _UxGT("Calibrar Z"); PROGMEM Language_Str MSG_DELTA_CALIBRATE_CENTER = _UxGT("Calibrar Centro"); PROGMEM Language_Str MSG_INFO_MENU = _UxGT("Acerca de..."); PROGMEM Language_Str MSG_INFO_PRINTER_MENU = _UxGT("Informacion"); PROGMEM Language_Str MSG_INFO_STATS_MENU = _UxGT("Estadisticas"); PROGMEM Language_Str MSG_INFO_BOARD_MENU = _UxGT("Placa nai"); PROGMEM Language_Str MSG_INFO_THERMISTOR_MENU = _UxGT("Termistores"); PROGMEM Language_Str MSG_INFO_EXTRUDERS = _UxGT("Extrusores"); PROGMEM Language_Str MSG_INFO_BAUDRATE = _UxGT("Baudios"); PROGMEM Language_Str MSG_INFO_PROTOCOL = _UxGT("Protocolo"); PROGMEM Language_Str MSG_CASE_LIGHT = _UxGT("Luz"); #if LCD_WIDTH >= 20 PROGMEM Language_Str MSG_INFO_PRINT_COUNT = _UxGT("Total traballos"); PROGMEM Language_Str MSG_INFO_COMPLETED_PRINTS = _UxGT("Total completos"); PROGMEM Language_Str MSG_INFO_PRINT_TIME = _UxGT("Tempo impresion"); PROGMEM Language_Str MSG_INFO_PRINT_LONGEST = _UxGT("Traballo +longo"); PROGMEM Language_Str MSG_INFO_PRINT_FILAMENT = _UxGT("Total extruido"); #else PROGMEM Language_Str MSG_INFO_PRINT_COUNT = _UxGT("Traballos"); PROGMEM Language_Str MSG_INFO_COMPLETED_PRINTS = _UxGT("Completos"); PROGMEM Language_Str MSG_INFO_PRINT_TIME = _UxGT("Tempo"); PROGMEM Language_Str MSG_INFO_PRINT_LONGEST = _UxGT("O +longo"); PROGMEM Language_Str MSG_INFO_PRINT_FILAMENT = _UxGT("Extruido"); #endif PROGMEM Language_Str MSG_INFO_MIN_TEMP = _UxGT("Min Temp"); PROGMEM Language_Str MSG_INFO_MAX_TEMP = _UxGT("Max Temp"); PROGMEM Language_Str MSG_INFO_PSU = _UxGT("Fonte alime."); PROGMEM Language_Str MSG_DRIVE_STRENGTH = _UxGT("Potencia motor"); PROGMEM Language_Str MSG_DAC_EEPROM_WRITE = _UxGT("Garda DAC EEPROM"); PROGMEM Language_Str MSG_FILAMENT_CHANGE_OPTION_RESUME = _UxGT("Segue traballo"); PROGMEM Language_Str MSG_EXPECTED_PRINTER = _UxGT("Impresora incorrecta"); #if LCD_HEIGHT >= 4 // Up to 3 lines allowed PROGMEM Language_Str MSG_FILAMENT_CHANGE_INIT = _UxGT(MSG_3_LINE("Agarde para", "iniciar troco", "de filamento")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_UNLOAD = _UxGT(MSG_3_LINE("Agarde pola", "descarga do", "filamento")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_INSERT = _UxGT(MSG_3_LINE("Introduza o", "filamento e", "faga click")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_LOAD = _UxGT(MSG_3_LINE("Agarde pola", "carga do", "filamento")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_RESUME = _UxGT(MSG_3_LINE("Agarde para", "seguir co", "traballo")); #else // LCD_HEIGHT < 4 // Up to 2 lines allowed PROGMEM Language_Str MSG_FILAMENT_CHANGE_INIT = _UxGT(MSG_1_LINE("Agarde...")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_UNLOAD = _UxGT(MSG_1_LINE("Descargando...")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_INSERT = _UxGT(MSG_1_LINE("Introduza e click")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_LOAD = _UxGT(MSG_1_LINE("Cargando...")); PROGMEM Language_Str MSG_FILAMENT_CHANGE_RESUME = _UxGT(MSG_1_LINE("Seguindo...")); #endif // LCD_HEIGHT < 4 }
DDilshani/CO326-project
firmware/grbl-Mega/src/sleep.c
<reponame>DDilshani/CO326-project /* sleep.c - determines and executes sleep procedures Part of Grbl Copyright (c) 2016 <NAME> Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ #include "grbl.h" #define SLEEP_SEC_PER_OVERFLOW (65535.0*64.0/F_CPU) // With 16-bit timer size and prescaler #define SLEEP_COUNT_MAX (SLEEP_DURATION/SLEEP_SEC_PER_OVERFLOW) volatile uint8_t sleep_counter; // Initialize sleep counters and enable timer. static void sleep_enable() { sleep_counter = 0; // Reset sleep counter TCNT3 = 0; // Reset timer3 counter register TIMSK3 |= (1<<TOIE3); // Enable timer3 overflow interrupt } // Disable sleep timer. static void sleep_disable() { TIMSK3 &= ~(1<<TOIE3); } // Disable timer overflow interrupt // Initialization routine for sleep timer. void sleep_init() { // Configure Timer 3: Sleep Counter Overflow Interrupt // NOTE: By using an overflow interrupt, the timer is automatically reloaded upon overflow. TCCR3B = 0; // Normal operation. Overflow. TCCR3A = 0; TCCR3B = (TCCR3B & ~((1<<CS32) | (1<<CS31))) | (1<<CS30); // Stop timer // TCCR3B |= (1<<CS32); // Enable timer with 1/256 prescaler. ~4.4min max with uint8 and 1.05sec/tick // TCCR3B |= (1<<CS31); // Enable timer with 1/8 prescaler. ~8.3sec max with uint8 and 32.7msec/tick TCCR3B |= (1<<CS31)|(1<<CS30); // Enable timer with 1/64 prescaler. ~66.8sec max with uint8 and 0.262sec/tick // TCCR3B |= (1<<CS32)|(1<<CS30); // Enable timer with 1/1024 prescaler. ~17.8min max with uint8 and 4.19sec/tick sleep_disable(); } // Increment sleep counter with each timer overflow. ISR(TIMER3_OVF_vect) { sleep_counter++; } // Starts sleep timer if running conditions are satified. When elaped, sleep mode is executed. static void sleep_execute() { // Fetch current number of buffered characters in serial RX buffer. uint8_t rx_initial = serial_get_rx_buffer_count(); // Enable sleep counter sleep_enable(); do { // Monitor for any new RX serial data or external events (queries, buttons, alarms) to exit. if ( (serial_get_rx_buffer_count() > rx_initial) || sys_rt_exec_state || sys_rt_exec_alarm ) { // Disable sleep timer and return to normal operation. sleep_disable(); return; } } while(sleep_counter <= SLEEP_COUNT_MAX); // If reached, sleep counter has expired. Execute sleep procedures. // Notify user that Grbl has timed out and will be parking. // To exit sleep, resume or reset. Either way, the job will not be recoverable. report_feedback_message(MESSAGE_SLEEP_MODE); system_set_exec_state_flag(EXEC_SLEEP); } // Checks running conditions for sleep. If satisfied, enables sleep countdown and executes // sleep mode upon elapse. // NOTE: Sleep procedures can be blocking, since Grbl isn't receiving any commands, nor moving. // Hence, make sure any valid running state that executes the sleep timer is not one that is moving. void sleep_check() { // The sleep execution feature will continue only if the machine is in an IDLE or HOLD state and // has any powered components enabled. // NOTE: With overrides or in laser mode, modal spindle and coolant state are not guaranteed. Need // to directly monitor and record running state during parking to ensure proper function. if (gc_state.modal.spindle || gc_state.modal.coolant) { if (sys.state == STATE_IDLE) { sleep_execute(); } else if ((sys.state & STATE_HOLD) && (sys.suspend & SUSPEND_HOLD_COMPLETE)) { sleep_execute(); } else if (sys.state == STATE_SAFETY_DOOR && (sys.suspend & SUSPEND_RETRACT_COMPLETE)) { sleep_execute(); } } }
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/module/planner.h
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * planner.h * * Buffer movement commands and manage the acceleration profile plan * * Derived from Grbl * Copyright (c) 2009-2011 <NAME> */ #include "../MarlinCore.h" #include "motion.h" #include "../gcode/queue.h" #if ENABLED(DELTA) #include "delta.h" #endif #if ABL_PLANAR #include "../libs/vector_3.h" // for matrix_3x3 #endif #if ENABLED(FWRETRACT) #include "../feature/fwretract.h" #endif #if ENABLED(MIXING_EXTRUDER) #include "../feature/mixing.h" #endif #if HAS_CUTTER #include "../feature/spindle_laser.h" #endif // Feedrate for manual moves #ifdef MANUAL_FEEDRATE constexpr xyze_feedrate_t _mf = MANUAL_FEEDRATE, manual_feedrate_mm_s { _mf.x / 60.0f, _mf.y / 60.0f, _mf.z / 60.0f, _mf.e / 60.0f }; #endif enum BlockFlagBit : char { // Recalculate trapezoids on entry junction. For optimization. BLOCK_BIT_RECALCULATE, // Nominal speed always reached. // i.e., The segment is long enough, so the nominal speed is reachable if accelerating // from a safe speed (in consideration of jerking from zero speed). BLOCK_BIT_NOMINAL_LENGTH, // The block is segment 2+ of a longer move BLOCK_BIT_CONTINUED, // Sync the stepper counts from the block BLOCK_BIT_SYNC_POSITION }; enum BlockFlag : char { BLOCK_FLAG_RECALCULATE = _BV(BLOCK_BIT_RECALCULATE), BLOCK_FLAG_NOMINAL_LENGTH = _BV(BLOCK_BIT_NOMINAL_LENGTH), BLOCK_FLAG_CONTINUED = _BV(BLOCK_BIT_CONTINUED), BLOCK_FLAG_SYNC_POSITION = _BV(BLOCK_BIT_SYNC_POSITION) }; /** * struct block_t * * A single entry in the planner buffer. * Tracks linear movement over multiple axes. * * The "nominal" values are as-specified by gcode, and * may never actually be reached due to acceleration limits. */ typedef struct block_t { volatile uint8_t flag; // Block flags (See BlockFlag enum above) - Modified by ISR and main thread! // Fields used by the motion planner to manage acceleration float nominal_speed_sqr, // The nominal speed for this block in (mm/sec)^2 entry_speed_sqr, // Entry speed at previous-current junction in (mm/sec)^2 max_entry_speed_sqr, // Maximum allowable junction entry speed in (mm/sec)^2 millimeters, // The total travel of this block in mm acceleration; // acceleration mm/sec^2 union { abce_ulong_t steps; // Step count along each axis abce_long_t position; // New position to force when this sync block is executed }; uint32_t step_event_count; // The number of step events required to complete this block #if EXTRUDERS > 1 uint8_t extruder; // The extruder to move (if E move) #else static constexpr uint8_t extruder = 0; #endif #if ENABLED(MIXING_EXTRUDER) MIXER_BLOCK_FIELD; // Normalized color for the mixing steppers #endif // Settings for the trapezoid generator uint32_t accelerate_until, // The index of the step event on which to stop acceleration decelerate_after; // The index of the step event on which to start decelerating #if ENABLED(S_CURVE_ACCELERATION) uint32_t cruise_rate, // The actual cruise rate to use, between end of the acceleration phase and start of deceleration phase acceleration_time, // Acceleration time and deceleration time in STEP timer counts deceleration_time, acceleration_time_inverse, // Inverse of acceleration and deceleration periods, expressed as integer. Scale depends on CPU being used deceleration_time_inverse; #else uint32_t acceleration_rate; // The acceleration rate used for acceleration calculation #endif uint8_t direction_bits; // The direction bit set for this block (refers to *_DIRECTION_BIT in config.h) // Advance extrusion #if ENABLED(LIN_ADVANCE) bool use_advance_lead; uint16_t advance_speed, // STEP timer value for extruder speed offset ISR max_adv_steps, // max. advance steps to get cruising speed pressure (not always nominal_speed!) final_adv_steps; // advance steps due to exit speed float e_D_ratio; #endif uint32_t nominal_rate, // The nominal step rate for this block in step_events/sec initial_rate, // The jerk-adjusted step rate at start of block final_rate, // The minimal rate at exit acceleration_steps_per_s2; // acceleration steps/sec^2 #if HAS_CUTTER cutter_power_t cutter_power; // Power level for Spindle, Laser, etc. #endif #if FAN_COUNT > 0 uint8_t fan_speed[FAN_COUNT]; #endif #if ENABLED(BARICUDA) uint8_t valve_pressure, e_to_p_pressure; #endif #if HAS_SPI_LCD uint32_t segment_time_us; #endif #if ENABLED(POWER_LOSS_RECOVERY) uint32_t sdpos; #endif } block_t; #define HAS_POSITION_FLOAT ANY(LIN_ADVANCE, SCARA_FEEDRATE_SCALING, GRADIENT_MIX, LCD_SHOW_E_TOTAL) #define BLOCK_MOD(n) ((n)&(BLOCK_BUFFER_SIZE-1)) typedef struct { uint32_t max_acceleration_mm_per_s2[XYZE_N], // (mm/s^2) M201 XYZE min_segment_time_us; // (µs) M205 B float axis_steps_per_mm[XYZE_N]; // (steps) M92 XYZE - Steps per millimeter feedRate_t max_feedrate_mm_s[XYZE_N]; // (mm/s) M203 XYZE - Max speeds float acceleration, // (mm/s^2) M204 S - Normal acceleration. DEFAULT ACCELERATION for all printing moves. retract_acceleration, // (mm/s^2) M204 R - Retract acceleration. Filament pull-back and push-forward while standing still in the other axes travel_acceleration; // (mm/s^2) M204 T - Travel acceleration. DEFAULT ACCELERATION for all NON printing moves. feedRate_t min_feedrate_mm_s, // (mm/s) M205 S - Minimum linear feedrate min_travel_feedrate_mm_s; // (mm/s) M205 T - Minimum travel feedrate } planner_settings_t; #if DISABLED(SKEW_CORRECTION) #define XY_SKEW_FACTOR 0 #define XZ_SKEW_FACTOR 0 #define YZ_SKEW_FACTOR 0 #endif typedef struct { #if ENABLED(SKEW_CORRECTION_GCODE) float xy; #if ENABLED(SKEW_CORRECTION_FOR_Z) float xz, yz; #else const float xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR; #endif #else const float xy = XY_SKEW_FACTOR, xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR; #endif } skew_factor_t; class Planner { public: /** * The move buffer, calculated in stepper steps * * block_buffer is a ring buffer... * * head,tail : indexes for write,read * head==tail : the buffer is empty * head!=tail : blocks are in the buffer * head==(tail-1)%size : the buffer is full * * Writer of head is Planner::buffer_segment(). * Reader of tail is Stepper::isr(). Always consider tail busy / read-only */ static block_t block_buffer[BLOCK_BUFFER_SIZE]; static volatile uint8_t block_buffer_head, // Index of the next block to be pushed block_buffer_nonbusy, // Index of the first non busy block block_buffer_planned, // Index of the optimally planned block block_buffer_tail; // Index of the busy block, if any static uint16_t cleaning_buffer_counter; // A counter to disable queuing of blocks static uint8_t delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks #if ENABLED(DISTINCT_E_FACTORS) static uint8_t last_extruder; // Respond to extruder change #endif #if EXTRUDERS static int16_t flow_percentage[EXTRUDERS]; // Extrusion factor for each extruder static float e_factor[EXTRUDERS]; // The flow percentage and volumetric multiplier combine to scale E movement #endif #if DISABLED(NO_VOLUMETRICS) static float filament_size[EXTRUDERS], // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder volumetric_area_nominal, // Nominal cross-sectional area volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner // May be auto-adjusted by a filament width sensor #endif static planner_settings_t settings; static uint32_t max_acceleration_steps_per_s2[XYZE_N]; // (steps/s^2) Derived from mm_per_s2 static float steps_to_mm[XYZE_N]; // Millimeters per step #if DISABLED(CLASSIC_JERK) static float junction_deviation_mm; // (mm) M205 J #if ENABLED(LIN_ADVANCE) static float max_e_jerk // Calculated from junction_deviation_mm #if ENABLED(DISTINCT_E_FACTORS) [EXTRUDERS] #endif ; #endif #endif #if HAS_CLASSIC_JERK #if HAS_LINEAR_E_JERK static xyz_pos_t max_jerk; // (mm/s^2) M205 XYZ - The largest speed change requiring no acceleration. #else static xyze_pos_t max_jerk; // (mm/s^2) M205 XYZE - The largest speed change requiring no acceleration. #endif #endif #if HAS_LEVELING static bool leveling_active; // Flag that bed leveling is enabled #if ABL_PLANAR static matrix_3x3 bed_level_matrix; // Transform to compensate for bed level #endif #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) static float z_fade_height, inverse_z_fade_height; #endif #else static constexpr bool leveling_active = false; #endif #if ENABLED(LIN_ADVANCE) static float extruder_advance_K[EXTRUDERS]; #endif #if HAS_POSITION_FLOAT static xyze_pos_t position_float; #endif #if IS_KINEMATIC static xyze_pos_t position_cart; #endif static skew_factor_t skew_factor; #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT) static bool abort_on_endstop_hit; #endif private: /** * The current position of the tool in absolute steps * Recalculated if any axis_steps_per_mm are changed by gcode */ static xyze_long_t position; /** * Speed of previous path line segment */ static xyze_float_t previous_speed; /** * Nominal speed of previous path line segment (mm/s)^2 */ static float previous_nominal_speed_sqr; /** * Limit where 64bit math is necessary for acceleration calculation */ static uint32_t cutoff_long; #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) static float last_fade_z; #endif #if ENABLED(DISABLE_INACTIVE_EXTRUDER) /** * Counters to manage disabling inactive extruders */ static uint8_t g_uc_extruder_last_move[EXTRUDERS]; #endif // DISABLE_INACTIVE_EXTRUDER #ifdef XY_FREQUENCY_LIMIT // Used for the frequency limit #define MAX_FREQ_TIME_US (uint32_t)(1000000.0 / XY_FREQUENCY_LIMIT) // Old direction bits. Used for speed calculations static unsigned char old_direction_bits; // Segment times (in µs). Used for speed calculations static xy_ulong_t axis_segment_time_us[3]; #endif #if HAS_SPI_LCD volatile static uint32_t block_buffer_runtime_us; //Theoretical block buffer runtime in µs #endif public: /** * Instance Methods */ Planner(); void init(); /** * Static (class) Methods */ static void reset_acceleration_rates(); static void refresh_positioning(); static void set_max_acceleration(const uint8_t axis, float targetValue); static void set_max_feedrate(const uint8_t axis, float targetValue); static void set_max_jerk(const AxisEnum axis, float targetValue); #if EXTRUDERS FORCE_INLINE static void refresh_e_factor(const uint8_t e) { e_factor[e] = (flow_percentage[e] * 0.01f #if DISABLED(NO_VOLUMETRICS) * volumetric_multiplier[e] #endif ); } #endif // Manage fans, paste pressure, etc. static void check_axes_activity(); // Update multipliers based on new diameter measurements static void calculate_volumetric_multipliers(); #if ENABLED(FILAMENT_WIDTH_SENSOR) void apply_filament_width_sensor(const int8_t encoded_ratio); static inline float volumetric_percent(const bool vol) { return 100.0f * (vol ? volumetric_area_nominal / volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] : volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] ); } #endif #if DISABLED(NO_VOLUMETRICS) FORCE_INLINE static void set_filament_size(const uint8_t e, const float &v) { filament_size[e] = v; // make sure all extruders have some sane value for the filament size for (uint8_t i = 0; i < COUNT(filament_size); i++) if (!filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA; } #endif #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) /** * Get the Z leveling fade factor based on the given Z height, * re-calculating only when needed. * * Returns 1.0 if planner.z_fade_height is 0.0. * Returns 0.0 if Z is past the specified 'Fade Height'. */ static inline float fade_scaling_factor_for_z(const float &rz) { static float z_fade_factor = 1; if (!z_fade_height) return 1; if (rz >= z_fade_height) return 0; if (last_fade_z != rz) { last_fade_z = rz; z_fade_factor = 1 - rz * inverse_z_fade_height; } return z_fade_factor; } FORCE_INLINE static void force_fade_recalc() { last_fade_z = -999.999f; } FORCE_INLINE static void set_z_fade_height(const float &zfh) { z_fade_height = zfh > 0 ? zfh : 0; inverse_z_fade_height = RECIPROCAL(z_fade_height); force_fade_recalc(); } FORCE_INLINE static bool leveling_active_at_z(const float &rz) { return !z_fade_height || rz < z_fade_height; } #else FORCE_INLINE static float fade_scaling_factor_for_z(const float&) { return 1; } FORCE_INLINE static bool leveling_active_at_z(const float&) { return true; } #endif #if ENABLED(SKEW_CORRECTION) FORCE_INLINE static void skew(float &cx, float &cy, const float &cz) { if (WITHIN(cx, X_MIN_POS + 1, X_MAX_POS) && WITHIN(cy, Y_MIN_POS + 1, Y_MAX_POS)) { const float sx = cx - cy * skew_factor.xy - cz * (skew_factor.xz - (skew_factor.xy * skew_factor.yz)), sy = cy - cz * skew_factor.yz; if (WITHIN(sx, X_MIN_POS, X_MAX_POS) && WITHIN(sy, Y_MIN_POS, Y_MAX_POS)) { cx = sx; cy = sy; } } } FORCE_INLINE static void skew(xyz_pos_t &raw) { skew(raw.x, raw.y, raw.z); } FORCE_INLINE static void unskew(float &cx, float &cy, const float &cz) { if (WITHIN(cx, X_MIN_POS, X_MAX_POS) && WITHIN(cy, Y_MIN_POS, Y_MAX_POS)) { const float sx = cx + cy * skew_factor.xy + cz * skew_factor.xz, sy = cy + cz * skew_factor.yz; if (WITHIN(sx, X_MIN_POS, X_MAX_POS) && WITHIN(sy, Y_MIN_POS, Y_MAX_POS)) { cx = sx; cy = sy; } } } FORCE_INLINE static void unskew(xyz_pos_t &raw) { unskew(raw.x, raw.y, raw.z); } #endif // SKEW_CORRECTION #if HAS_LEVELING /** * Apply leveling to transform a cartesian position * as it will be given to the planner and steppers. */ static void apply_leveling(xyz_pos_t &raw); static void unapply_leveling(xyz_pos_t &raw); FORCE_INLINE static void force_unapply_leveling(xyz_pos_t &raw) { leveling_active = true; unapply_leveling(raw); leveling_active = false; } #endif #if ENABLED(FWRETRACT) static void apply_retract(float &rz, float &e); FORCE_INLINE static void apply_retract(xyze_pos_t &raw) { apply_retract(raw.z, raw.e); } static void unapply_retract(float &rz, float &e); FORCE_INLINE static void unapply_retract(xyze_pos_t &raw) { unapply_retract(raw.z, raw.e); } #endif #if HAS_POSITION_MODIFIERS FORCE_INLINE static void apply_modifiers(xyze_pos_t &pos #if HAS_LEVELING , bool leveling = #if PLANNER_LEVELING true #else false #endif #endif ) { #if ENABLED(SKEW_CORRECTION) skew(pos); #endif #if HAS_LEVELING if (leveling) apply_leveling(pos); #endif #if ENABLED(FWRETRACT) apply_retract(pos); #endif } FORCE_INLINE static void unapply_modifiers(xyze_pos_t &pos #if HAS_LEVELING , bool leveling = #if PLANNER_LEVELING true #else false #endif #endif ) { #if ENABLED(FWRETRACT) unapply_retract(pos); #endif #if HAS_LEVELING if (leveling) unapply_leveling(pos); #endif #if ENABLED(SKEW_CORRECTION) unskew(pos); #endif } #endif // HAS_POSITION_MODIFIERS // Number of moves currently in the planner including the busy block, if any FORCE_INLINE static uint8_t movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_tail); } // Number of nonbusy moves currently in the planner FORCE_INLINE static uint8_t nonbusy_movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_nonbusy); } // Remove all blocks from the buffer FORCE_INLINE static void clear_block_buffer() { block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail = 0; } // Check if movement queue is full FORCE_INLINE static bool is_full() { return block_buffer_tail == next_block_index(block_buffer_head); } // Get count of movement slots free FORCE_INLINE static uint8_t moves_free() { return BLOCK_BUFFER_SIZE - 1 - movesplanned(); } /** * Planner::get_next_free_block * * - Get the next head indices (passed by reference) * - Wait for the number of spaces to open up in the planner * - Return the first head block */ FORCE_INLINE static block_t* get_next_free_block(uint8_t &next_buffer_head, const uint8_t count=1) { // Wait until there are enough slots free while (moves_free() < count) { idle(); } // Return the first available block next_buffer_head = next_block_index(block_buffer_head); return &block_buffer[block_buffer_head]; } /** * Planner::_buffer_steps * * Add a new linear movement to the buffer (in terms of steps). * * target - target position in steps units * fr_mm_s - (target) speed of the move * extruder - target extruder * millimeters - the length of the movement, if known * * Returns true if movement was buffered, false otherwise */ static bool _buffer_steps(const xyze_long_t &target #if HAS_POSITION_FLOAT , const xyze_pos_t &target_float #endif #if IS_KINEMATIC && DISABLED(CLASSIC_JERK) , const xyze_float_t &delta_mm_cart #endif , feedRate_t fr_mm_s, const uint8_t extruder, const float &millimeters=0.0 ); /** * Planner::_populate_block * * Fills a new linear movement in the block (in terms of steps). * * target - target position in steps units * fr_mm_s - (target) speed of the move * extruder - target extruder * millimeters - the length of the movement, if known * * Returns true is movement is acceptable, false otherwise */ static bool _populate_block(block_t * const block, bool split_move, const xyze_long_t &target #if HAS_POSITION_FLOAT , const xyze_pos_t &target_float #endif #if IS_KINEMATIC && DISABLED(CLASSIC_JERK) , const xyze_float_t &delta_mm_cart #endif , feedRate_t fr_mm_s, const uint8_t extruder, const float &millimeters=0.0 ); /** * Planner::buffer_sync_block * Add a block to the buffer that just updates the position */ static void buffer_sync_block(); #if IS_KINEMATIC private: // Allow do_homing_move to access internal functions, such as buffer_segment. friend void do_homing_move(const AxisEnum, const float, const feedRate_t); #endif /** * Planner::buffer_segment * * Add a new linear movement to the buffer in axis units. * * Leveling and kinematics should be applied ahead of calling this. * * a,b,c,e - target positions in mm and/or degrees * fr_mm_s - (target) speed of the move * extruder - target extruder * millimeters - the length of the movement, if known */ static bool buffer_segment(const float &a, const float &b, const float &c, const float &e #if IS_KINEMATIC && DISABLED(CLASSIC_JERK) , const xyze_float_t &delta_mm_cart #endif , const feedRate_t &fr_mm_s, const uint8_t extruder, const float &millimeters=0.0 ); FORCE_INLINE static bool buffer_segment(abce_pos_t &abce #if IS_KINEMATIC && DISABLED(CLASSIC_JERK) , const xyze_float_t &delta_mm_cart #endif , const feedRate_t &fr_mm_s, const uint8_t extruder, const float &millimeters=0.0 ) { return buffer_segment(abce.a, abce.b, abce.c, abce.e #if IS_KINEMATIC && DISABLED(CLASSIC_JERK) , delta_mm_cart #endif , fr_mm_s, extruder, millimeters); } public: /** * Add a new linear movement to the buffer. * The target is cartesian. It's translated to * delta/scara if needed. * * rx,ry,rz,e - target position in mm or degrees * fr_mm_s - (target) speed of the move (mm/s) * extruder - target extruder * millimeters - the length of the movement, if known * inv_duration - the reciprocal if the duration of the movement, if known (kinematic only if feeedrate scaling is enabled) */ static bool buffer_line(const float &rx, const float &ry, const float &rz, const float &e, const feedRate_t &fr_mm_s, const uint8_t extruder, const float millimeters=0.0 #if ENABLED(SCARA_FEEDRATE_SCALING) , const float &inv_duration=0.0 #endif ); FORCE_INLINE static bool buffer_line(const xyze_pos_t &cart, const feedRate_t &fr_mm_s, const uint8_t extruder, const float millimeters=0.0 #if ENABLED(SCARA_FEEDRATE_SCALING) , const float &inv_duration=0.0 #endif ) { return buffer_line(cart.x, cart.y, cart.z, cart.e, fr_mm_s, extruder, millimeters #if ENABLED(SCARA_FEEDRATE_SCALING) , inv_duration #endif ); } /** * Set the planner.position and individual stepper positions. * Used by G92, G28, G29, and other procedures. * * The supplied position is in the cartesian coordinate space and is * translated in to machine space as needed. Modifiers such as leveling * and skew are also applied. * * Multiplies by axis_steps_per_mm[] and does necessary conversion * for COREXY / COREXZ / COREYZ to set the corresponding stepper positions. * * Clears previous speed values. */ static void set_position_mm(const float &rx, const float &ry, const float &rz, const float &e); FORCE_INLINE static void set_position_mm(const xyze_pos_t &cart) { set_position_mm(cart.x, cart.y, cart.z, cart.e); } static void set_e_position_mm(const float &e); /** * Set the planner.position and individual stepper positions. * * The supplied position is in machine space, and no additional * conversions are applied. */ static void set_machine_position_mm(const float &a, const float &b, const float &c, const float &e); FORCE_INLINE static void set_machine_position_mm(const abce_pos_t &abce) { set_machine_position_mm(abce.a, abce.b, abce.c, abce.e); } /** * Get an axis position according to stepper position(s) * For CORE machines apply translation from ABC to XYZ. */ static float get_axis_position_mm(const AxisEnum axis); // SCARA AB axes are in degrees, not mm #if IS_SCARA FORCE_INLINE static float get_axis_position_degrees(const AxisEnum axis) { return get_axis_position_mm(axis); } #endif // Called to force a quick stop of the machine (for example, when // a Full Shutdown is required, or when endstops are hit) static void quick_stop(); // Called when an endstop is triggered. Causes the machine to stop inmediately static void endstop_triggered(const AxisEnum axis); // Triggered position of an axis in mm (not core-savvy) static float triggered_position_mm(const AxisEnum axis); // Block until all buffered steps are executed / cleaned static void synchronize(); // Wait for moves to finish and disable all steppers static void finish_and_disable(); // Periodic tick to handle cleaning timeouts // Called from the Temperature ISR at ~1kHz static void tick() { if (cleaning_buffer_counter) { --cleaning_buffer_counter; #if ENABLED(SD_FINISHED_STEPPERRELEASE) && defined(SD_FINISHED_RELEASECOMMAND) if (!cleaning_buffer_counter) queue.inject_P(PSTR(SD_FINISHED_RELEASECOMMAND)); #endif } } /** * Does the buffer have any blocks queued? */ FORCE_INLINE static bool has_blocks_queued() { return (block_buffer_head != block_buffer_tail); } /** * The current block. nullptr if the buffer is empty. * This also marks the block as busy. * WARNING: Called from Stepper ISR context! */ static block_t* get_current_block() { // Get the number of moves in the planner queue so far const uint8_t nr_moves = movesplanned(); // If there are any moves queued ... if (nr_moves) { // If there is still delay of delivery of blocks running, decrement it if (delay_before_delivering) { --delay_before_delivering; // If the number of movements queued is less than 3, and there is still time // to wait, do not deliver anything if (nr_moves < 3 && delay_before_delivering) return nullptr; delay_before_delivering = 0; } // If we are here, there is no excuse to deliver the block block_t * const block = &block_buffer[block_buffer_tail]; // No trapezoid calculated? Don't execute yet. if (TEST(block->flag, BLOCK_BIT_RECALCULATE)) return nullptr; #if HAS_SPI_LCD block_buffer_runtime_us -= block->segment_time_us; // We can't be sure how long an active block will take, so don't count it. #endif // As this block is busy, advance the nonbusy block pointer block_buffer_nonbusy = next_block_index(block_buffer_tail); // Push block_buffer_planned pointer, if encountered. if (block_buffer_tail == block_buffer_planned) block_buffer_planned = block_buffer_nonbusy; // Return the block return block; } // The queue became empty #if HAS_SPI_LCD clear_block_buffer_runtime(); // paranoia. Buffer is empty now - so reset accumulated time to zero. #endif return nullptr; } /** * "Discard" the block and "release" the memory. * Called when the current block is no longer needed. * NB: There MUST be a current block to call this function!! */ FORCE_INLINE static void discard_current_block() { if (has_blocks_queued()) block_buffer_tail = next_block_index(block_buffer_tail); } #if HAS_SPI_LCD static uint16_t block_buffer_runtime() { #ifdef __AVR__ // Protect the access to the variable. Only required for AVR, as // any 32bit CPU offers atomic access to 32bit variables bool was_enabled = STEPPER_ISR_ENABLED(); if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT(); #endif millis_t bbru = block_buffer_runtime_us; #ifdef __AVR__ // Reenable Stepper ISR if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT(); #endif // To translate µs to ms a division by 1000 would be required. // We introduce 2.4% error here by dividing by 1024. // Doesn't matter because block_buffer_runtime_us is already too small an estimation. bbru >>= 10; // limit to about a minute. NOMORE(bbru, 0xFFFFul); return bbru; } static void clear_block_buffer_runtime() { #ifdef __AVR__ // Protect the access to the variable. Only required for AVR, as // any 32bit CPU offers atomic access to 32bit variables bool was_enabled = STEPPER_ISR_ENABLED(); if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT(); #endif block_buffer_runtime_us = 0; #ifdef __AVR__ // Reenable Stepper ISR if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT(); #endif } #endif #if ENABLED(AUTOTEMP) static float autotemp_min, autotemp_max, autotemp_factor; static bool autotemp_enabled; static void getHighESpeed(); static void autotemp_M104_M109(); #endif #if HAS_LINEAR_E_JERK FORCE_INLINE static void recalculate_max_e_jerk() { #define GET_MAX_E_JERK(N) SQRT(SQRT(0.5) * junction_deviation_mm * (N) * RECIPROCAL(1.0 - SQRT(0.5))) #if ENABLED(DISTINCT_E_FACTORS) for (uint8_t i = 0; i < EXTRUDERS; i++) max_e_jerk[i] = GET_MAX_E_JERK(settings.max_acceleration_mm_per_s2[E_AXIS_N(i)]); #else max_e_jerk = GET_MAX_E_JERK(settings.max_acceleration_mm_per_s2[E_AXIS]); #endif } #endif private: /** * Get the index of the next / previous block in the ring buffer */ static constexpr uint8_t next_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index + 1); } static constexpr uint8_t prev_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index - 1); } /** * Calculate the distance (not time) it takes to accelerate * from initial_rate to target_rate using the given acceleration: */ static float estimate_acceleration_distance(const float &initial_rate, const float &target_rate, const float &accel) { if (accel == 0) return 0; // accel was 0, set acceleration distance to 0 return (sq(target_rate) - sq(initial_rate)) / (accel * 2); } /** * Return the point at which you must start braking (at the rate of -'accel') if * you start at 'initial_rate', accelerate (until reaching the point), and want to end at * 'final_rate' after traveling 'distance'. * * This is used to compute the intersection point between acceleration and deceleration * in cases where the "trapezoid" has no plateau (i.e., never reaches maximum speed) */ static float intersection_distance(const float &initial_rate, const float &final_rate, const float &accel, const float &distance) { if (accel == 0) return 0; // accel was 0, set intersection distance to 0 return (accel * 2 * distance - sq(initial_rate) + sq(final_rate)) / (accel * 4); } /** * Calculate the maximum allowable speed squared at this point, in order * to reach 'target_velocity_sqr' using 'acceleration' within a given * 'distance'. */ static float max_allowable_speed_sqr(const float &accel, const float &target_velocity_sqr, const float &distance) { return target_velocity_sqr - 2 * accel * distance; } #if ENABLED(S_CURVE_ACCELERATION) /** * Calculate the speed reached given initial speed, acceleration and distance */ static float final_speed(const float &initial_velocity, const float &accel, const float &distance) { return SQRT(sq(initial_velocity) + 2 * accel * distance); } #endif static void calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor); static void reverse_pass_kernel(block_t* const current, const block_t * const next); static void forward_pass_kernel(const block_t * const previous, block_t* const current, uint8_t block_index); static void reverse_pass(); static void forward_pass(); static void recalculate_trapezoids(); static void recalculate(); #if DISABLED(CLASSIC_JERK) FORCE_INLINE static void normalize_junction_vector(xyze_float_t &vector) { float magnitude_sq = 0; LOOP_XYZE(idx) if (vector[idx]) magnitude_sq += sq(vector[idx]); vector *= RSQRT(magnitude_sq); } FORCE_INLINE static float limit_value_by_axis_maximum(const float &max_value, xyze_float_t &unit_vec) { float limit_value = max_value; LOOP_XYZE(idx) if (unit_vec[idx]) // Avoid divide by zero NOMORE(limit_value, ABS(settings.max_acceleration_mm_per_s2[idx] / unit_vec[idx])); return limit_value; } #endif // !CLASSIC_JERK }; #define PLANNER_XY_FEEDRATE() (_MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS])) extern Planner planner;
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/feature/babystep.h
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfigPre.h" #if IS_CORE || EITHER(BABYSTEP_XY, I2C_POSITION_ENCODERS) #define BS_TODO_AXIS(A) A #else #define BS_TODO_AXIS(A) 0 #endif #if ENABLED(BABYSTEP_DISPLAY_TOTAL) #if ENABLED(BABYSTEP_XY) #define BS_TOTAL_AXIS(A) A #else #define BS_TOTAL_AXIS(A) 0 #endif #endif class Babystep { public: static volatile int16_t steps[BS_TODO_AXIS(Z_AXIS) + 1]; static int16_t accum; // Total babysteps in current edit #if ENABLED(BABYSTEP_DISPLAY_TOTAL) static int16_t axis_total[BS_TOTAL_AXIS(Z_AXIS) + 1]; // Total babysteps since G28 static inline void reset_total(const AxisEnum axis) { if (true #if ENABLED(BABYSTEP_XY) && axis == Z_AXIS #endif ) axis_total[BS_TOTAL_AXIS(axis)] = 0; } #endif static void add_steps(const AxisEnum axis, const int16_t distance); static void add_mm(const AxisEnum axis, const float &mm); static void task(); private: static void step_axis(const AxisEnum axis); }; extern Babystep babystep;
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/pins/ramps/pins_RAMPS_OLD.h
<filename>firmware/Marlin-2.0.x/Marlin/src/pins/ramps/pins_RAMPS_OLD.h /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * Arduino Mega with RAMPS v1.0, v1.1, v1.2 pin assignments */ #if !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) #error "Oops! Select 'Arduino/Genuino Mega or Mega 2560' in 'Tools > Board.'" #endif #define BOARD_INFO_NAME "RAMPS <1.2" // Uncomment the following line for RAMPS v1.0 //#define RAMPS_V_1_0 // // Limit Switches // #define X_MIN_PIN 3 #define X_MAX_PIN 2 #define Y_MIN_PIN 16 #define Y_MAX_PIN 17 #define Z_MIN_PIN 18 #define Z_MAX_PIN 19 // // Z Probe (when not Z_MIN_PIN) // #ifndef Z_MIN_PROBE_PIN #define Z_MIN_PROBE_PIN 19 #endif // // Steppers // #define X_STEP_PIN 26 #define X_DIR_PIN 28 #define X_ENABLE_PIN 24 #define Y_STEP_PIN 38 #define Y_DIR_PIN 40 #define Y_ENABLE_PIN 36 #define Z_STEP_PIN 44 #define Z_DIR_PIN 46 #define Z_ENABLE_PIN 42 #define E0_STEP_PIN 32 #define E0_DIR_PIN 34 #define E0_ENABLE_PIN 30 // // Temperature Sensors // #define TEMP_0_PIN 2 // Analog Input #define TEMP_BED_PIN 1 // Analog Input // SPI for Max6675 or Max31855 Thermocouple #if DISABLED(SDSUPPORT) #define MAX6675_SS_PIN 66 // Don't use 53 if there is even the remote possibility of using Display/SD card #else #define MAX6675_SS_PIN 66 // Don't use 49 as this is tied to the switch inside the SD card socket to detect if there is an SD card present #endif // // Heaters / Fans // #if ENABLED(RAMPS_V_1_0) #define HEATER_0_PIN 12 #define HEATER_BED_PIN -1 #ifndef FAN_PIN #define FAN_PIN 11 #endif #else // RAMPS_V_1_1 or RAMPS_V_1_2 #define HEATER_0_PIN 10 #define HEATER_BED_PIN 8 #ifndef FAN_PIN #define FAN_PIN 9 #endif #endif // // Misc. Functions // #define SDPOWER_PIN 48 #define SDSS 53 #define LED_PIN 13 #define CASE_LIGHT_PIN 45 // Hardware PWM // // M3/M4/M5 - Spindle/Laser Control // #define SPINDLE_LASER_ENA_PIN 41 // Pullup or pulldown! #define SPINDLE_LASER_PWM_PIN 45 // Hardware PWM #define SPINDLE_DIR_PIN 43
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/feature/tmc_util.h
<gh_stars>0 /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfig.h" #include "../lcd/ultralcd.h" #if HAS_TRINAMIC #include <TMCStepper.h> #include "../module/planner.h" #define CHOPPER_DEFAULT_12V { 3, -1, 1 } #define CHOPPER_DEFAULT_19V { 4, 1, 1 } #define CHOPPER_DEFAULT_24V { 4, 2, 1 } #define CHOPPER_DEFAULT_36V { 5, 2, 4 } #define CHOPPER_PRUSAMK3_24V { 3, -2, 6 } #define CHOPPER_MARLIN_119 { 5, 2, 3 } #if ENABLED(MONITOR_DRIVER_STATUS) && !defined(MONITOR_DRIVER_STATUS_INTERVAL_MS) #define MONITOR_DRIVER_STATUS_INTERVAL_MS 500u #endif constexpr uint16_t _tmc_thrs(const uint16_t msteps, const uint32_t thrs, const uint32_t spmm) { return 12650000UL * msteps / (256 * thrs * spmm); } template<char AXIS_LETTER, char DRIVER_ID> class TMCStorage { protected: // Only a child class has access to constructor => Don't create on its own! "Poor man's abstract class" TMCStorage() {} public: uint16_t val_mA = 0; #if ENABLED(MONITOR_DRIVER_STATUS) uint8_t otpw_count = 0, error_count = 0; bool flag_otpw = false; inline bool getOTPW() { return flag_otpw; } inline void clear_otpw() { flag_otpw = 0; } #endif inline uint16_t getMilliamps() { return val_mA; } inline void printLabel() { SERIAL_CHAR(AXIS_LETTER); if (DRIVER_ID > '0') SERIAL_CHAR(DRIVER_ID); } struct { #if HAS_STEALTHCHOP bool stealthChop_enabled = false; #endif #if ENABLED(HYBRID_THRESHOLD) uint8_t hybrid_thrs = 0; #endif #if USE_SENSORLESS int16_t homing_thrs = 0; #endif } stored; }; template<class TMC, char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> class TMCMarlin : public TMC, public TMCStorage<AXIS_LETTER, DRIVER_ID> { public: TMCMarlin(const uint16_t cs_pin, const float RS) : TMC(cs_pin, RS) {} TMCMarlin(const uint16_t cs_pin, const float RS, const uint8_t axis_chain_index) : TMC(cs_pin, RS, axis_chain_index) {} TMCMarlin(const uint16_t CS, const float RS, const uint16_t pinMOSI, const uint16_t pinMISO, const uint16_t pinSCK) : TMC(CS, RS, pinMOSI, pinMISO, pinSCK) {} TMCMarlin(const uint16_t CS, const float RS, const uint16_t pinMOSI, const uint16_t pinMISO, const uint16_t pinSCK, const uint8_t axis_chain_index) : TMC(CS, RS, pinMOSI, pinMISO, pinSCK, axis_chain_index) {} inline uint16_t rms_current() { return TMC::rms_current(); } inline void rms_current(uint16_t mA) { this->val_mA = mA; TMC::rms_current(mA); } inline void rms_current(const uint16_t mA, const float mult) { this->val_mA = mA; TMC::rms_current(mA, mult); } #if HAS_STEALTHCHOP inline void refresh_stepping_mode() { this->en_pwm_mode(this->stored.stealthChop_enabled); } inline bool get_stealthChop_status() { return this->en_pwm_mode(); } #endif #if ENABLED(HYBRID_THRESHOLD) uint32_t get_pwm_thrs() { return _tmc_thrs(this->microsteps(), this->TPWMTHRS(), planner.settings.axis_steps_per_mm[AXIS_ID]); } void set_pwm_thrs(const uint32_t thrs) { TMC::TPWMTHRS(_tmc_thrs(this->microsteps(), thrs, planner.settings.axis_steps_per_mm[AXIS_ID])); #if HAS_LCD_MENU this->stored.hybrid_thrs = thrs; #endif } #endif #if USE_SENSORLESS inline int16_t homing_threshold() { return TMC::sgt(); } void homing_threshold(int16_t sgt_val) { sgt_val = (int16_t)constrain(sgt_val, sgt_min, sgt_max); TMC::sgt(sgt_val); #if HAS_LCD_MENU this->stored.homing_thrs = sgt_val; #endif } #if ENABLED(SPI_ENDSTOPS) bool test_stall_status(); #endif #endif #if HAS_LCD_MENU inline void refresh_stepper_current() { rms_current(this->val_mA); } #if ENABLED(HYBRID_THRESHOLD) inline void refresh_hybrid_thrs() { set_pwm_thrs(this->stored.hybrid_thrs); } #endif #if USE_SENSORLESS inline void refresh_homing_thrs() { homing_threshold(this->stored.homing_thrs); } #endif #endif static constexpr int8_t sgt_min = -64, sgt_max = 63; }; template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> class TMCMarlin<TMC2208Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> : public TMC2208Stepper, public TMCStorage<AXIS_LETTER, DRIVER_ID> { public: TMCMarlin(Stream * SerialPort, const float RS, const uint8_t) : TMC2208Stepper(SerialPort, RS) {} TMCMarlin(const uint16_t RX, const uint16_t TX, const float RS, const uint8_t, const bool has_rx=true) : TMC2208Stepper(RX, TX, RS, has_rx) {} uint16_t rms_current() { return TMC2208Stepper::rms_current(); } inline void rms_current(const uint16_t mA) { this->val_mA = mA; TMC2208Stepper::rms_current(mA); } inline void rms_current(const uint16_t mA, const float mult) { this->val_mA = mA; TMC2208Stepper::rms_current(mA, mult); } #if HAS_STEALTHCHOP inline void refresh_stepping_mode() { en_spreadCycle(!this->stored.stealthChop_enabled); } inline bool get_stealthChop_status() { return !this->en_spreadCycle(); } #endif #if ENABLED(HYBRID_THRESHOLD) uint32_t get_pwm_thrs() { return _tmc_thrs(this->microsteps(), this->TPWMTHRS(), planner.settings.axis_steps_per_mm[AXIS_ID]); } void set_pwm_thrs(const uint32_t thrs) { TMC2208Stepper::TPWMTHRS(_tmc_thrs(this->microsteps(), thrs, planner.settings.axis_steps_per_mm[AXIS_ID])); #if HAS_LCD_MENU this->stored.hybrid_thrs = thrs; #endif } #endif #if HAS_LCD_MENU inline void refresh_stepper_current() { rms_current(this->val_mA); } #if ENABLED(HYBRID_THRESHOLD) inline void refresh_hybrid_thrs() { set_pwm_thrs(this->stored.hybrid_thrs); } #endif #endif }; template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> class TMCMarlin<TMC2209Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> : public TMC2209Stepper, public TMCStorage<AXIS_LETTER, DRIVER_ID> { public: TMCMarlin(Stream * SerialPort, const float RS, const uint8_t addr) : TMC2209Stepper(SerialPort, RS, addr) {} TMCMarlin(const uint16_t RX, const uint16_t TX, const float RS, const uint8_t addr, const bool) : TMC2209Stepper(RX, TX, RS, addr) {} uint8_t get_address() { return slave_address; } uint16_t rms_current() { return TMC2209Stepper::rms_current(); } inline void rms_current(const uint16_t mA) { this->val_mA = mA; TMC2209Stepper::rms_current(mA); } inline void rms_current(const uint16_t mA, const float mult) { this->val_mA = mA; TMC2209Stepper::rms_current(mA, mult); } #if HAS_STEALTHCHOP inline void refresh_stepping_mode() { en_spreadCycle(!this->stored.stealthChop_enabled); } inline bool get_stealthChop_status() { return !this->en_spreadCycle(); } #endif #if ENABLED(HYBRID_THRESHOLD) uint32_t get_pwm_thrs() { return _tmc_thrs(this->microsteps(), this->TPWMTHRS(), planner.settings.axis_steps_per_mm[AXIS_ID]); } void set_pwm_thrs(const uint32_t thrs) { TMC2209Stepper::TPWMTHRS(_tmc_thrs(this->microsteps(), thrs, planner.settings.axis_steps_per_mm[AXIS_ID])); #if HAS_LCD_MENU this->stored.hybrid_thrs = thrs; #endif } #endif #if USE_SENSORLESS inline int16_t homing_threshold() { return TMC2209Stepper::SGTHRS(); } void homing_threshold(int16_t sgt_val) { sgt_val = (int16_t)constrain(sgt_val, sgt_min, sgt_max); TMC2209Stepper::SGTHRS(sgt_val); #if HAS_LCD_MENU this->stored.homing_thrs = sgt_val; #endif } #endif #if HAS_LCD_MENU inline void refresh_stepper_current() { rms_current(this->val_mA); } #if ENABLED(HYBRID_THRESHOLD) inline void refresh_hybrid_thrs() { set_pwm_thrs(this->stored.hybrid_thrs); } #endif #if USE_SENSORLESS inline void refresh_homing_thrs() { homing_threshold(this->stored.homing_thrs); } #endif #endif static constexpr uint8_t sgt_min = 0, sgt_max = 255; }; template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> class TMCMarlin<TMC2660Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> : public TMC2660Stepper, public TMCStorage<AXIS_LETTER, DRIVER_ID> { public: TMCMarlin(const uint16_t cs_pin, const float RS, const uint8_t) : TMC2660Stepper(cs_pin, RS) {} TMCMarlin(const uint16_t CS, const float RS, const uint16_t pinMOSI, const uint16_t pinMISO, const uint16_t pinSCK, const uint8_t) : TMC2660Stepper(CS, RS, pinMOSI, pinMISO, pinSCK) {} inline uint16_t rms_current() { return TMC2660Stepper::rms_current(); } inline void rms_current(const uint16_t mA) { this->val_mA = mA; TMC2660Stepper::rms_current(mA); } #if USE_SENSORLESS inline int16_t homing_threshold() { return TMC2660Stepper::sgt(); } void homing_threshold(int16_t sgt_val) { sgt_val = (int16_t)constrain(sgt_val, sgt_min, sgt_max); TMC2660Stepper::sgt(sgt_val); #if HAS_LCD_MENU this->stored.homing_thrs = sgt_val; #endif } #endif #if HAS_LCD_MENU inline void refresh_stepper_current() { rms_current(this->val_mA); } #if USE_SENSORLESS inline void refresh_homing_thrs() { homing_threshold(this->stored.homing_thrs); } #endif #endif static constexpr int8_t sgt_min = -64, sgt_max = 63; }; template<typename TMC> void tmc_print_current(TMC &st) { st.printLabel(); SERIAL_ECHOLNPAIR(" driver current: ", st.getMilliamps()); } #if ENABLED(MONITOR_DRIVER_STATUS) template<typename TMC> void tmc_report_otpw(TMC &st) { st.printLabel(); SERIAL_ECHOPGM(" temperature prewarn triggered: "); serialprint_truefalse(st.getOTPW()); SERIAL_EOL(); } template<typename TMC> void tmc_clear_otpw(TMC &st) { st.clear_otpw(); st.printLabel(); SERIAL_ECHOLNPGM(" prewarn flag cleared"); } #endif #if ENABLED(HYBRID_THRESHOLD) template<typename TMC> void tmc_print_pwmthrs(TMC &st) { st.printLabel(); SERIAL_ECHOLNPAIR(" stealthChop max speed: ", st.get_pwm_thrs()); } #endif #if USE_SENSORLESS template<typename TMC> void tmc_print_sgt(TMC &st) { st.printLabel(); SERIAL_ECHOPGM(" homing sensitivity: "); SERIAL_PRINTLN(st.homing_threshold(), DEC); } #endif void monitor_tmc_drivers(); void test_tmc_connection(const bool test_x, const bool test_y, const bool test_z, const bool test_e); #if ENABLED(TMC_DEBUG) #if ENABLED(MONITOR_DRIVER_STATUS) void tmc_set_report_interval(const uint16_t update_interval); #endif void tmc_report_all(const bool print_x, const bool print_y, const bool print_z, const bool print_e); void tmc_get_registers(const bool print_x, const bool print_y, const bool print_z, const bool print_e); #endif /** * TMC2130-specific sensorless homing using stallGuard2. * stallGuard2 only works when in spreadCycle mode. * spreadCycle and stealthChop are mutually-exclusive. * * Defined here because of limitations with templates and headers. */ #if USE_SENSORLESS // Track enabled status of stealthChop and only re-enable where applicable struct sensorless_t { bool x, y, z, x2, y2, z2, z3, z4; }; #if ENABLED(IMPROVE_HOMING_RELIABILITY) extern millis_t sg_guard_period; constexpr uint16_t default_sg_guard_duration = 400; struct slow_homing_t { xy_ulong_t acceleration; #if HAS_CLASSIC_JERK xy_float_t jerk_xy; #endif }; #endif bool tmc_enable_stallguard(TMC2130Stepper &st); void tmc_disable_stallguard(TMC2130Stepper &st, const bool restore_stealth); bool tmc_enable_stallguard(TMC2209Stepper &st); void tmc_disable_stallguard(TMC2209Stepper &st, const bool restore_stealth); bool tmc_enable_stallguard(TMC2660Stepper); void tmc_disable_stallguard(TMC2660Stepper, const bool); #if ENABLED(SPI_ENDSTOPS) template<class TMC, char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> bool TMCMarlin<TMC, AXIS_LETTER, DRIVER_ID, AXIS_ID>::test_stall_status() { this->switchCSpin(LOW); // read stallGuard flag from TMC library, will handle HW and SW SPI TMC2130_n::DRV_STATUS_t drv_status{0}; drv_status.sr = this->DRV_STATUS(); this->switchCSpin(HIGH); return drv_status.stallGuard; } #endif // SPI_ENDSTOPS #endif // USE_SENSORLESS #if TMC_HAS_SPI void tmc_init_cs_pins(); #endif #endif // HAS_TRINAMIC
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/pins/esp32/pins_MRR_ESPE.h
/** * Marlin 3D Printer Firmware * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * MRR ESPE pin assignments * MRR ESPE is a 3D printer control board based on the ESP32 microcontroller. * Supports 5 stepper drivers (using I2S stepper stream), heated bed, * single hotend, and LCD controller. */ #ifndef ARDUINO_ARCH_ESP32 #error "Oops! Select an ESP32 board in 'Tools > Board.'" #elif EXTRUDERS > 2 || E_STEPPERS > 2 #error "MRR ESPE only supports two E Steppers. Comment out this line to continue." #elif HOTENDS > 1 #error "MRR ESPE currently supports only one hotend. Comment out this line to continue." #endif #define BOARD_INFO_NAME "MRR ESPE" #define BOARD_WEBSITE_URL "github.com/maplerainresearch/MRR_ESPE" #define DEFAULT_MACHINE_NAME BOARD_INFO_NAME // // Limit Switches // #define X_STOP_PIN 35 #define Y_STOP_PIN 32 #define Z_STOP_PIN 33 // // Enable I2S stepper stream // #undef I2S_STEPPER_STREAM #define I2S_STEPPER_STREAM #undef LIN_ADVANCE // Currently, I2S stream does not work with linear advance #define I2S_WS 26 #define I2S_BCK 25 #define I2S_DATA 27 // // Steppers // #define X_STEP_PIN 129 #define X_DIR_PIN 130 #define X_ENABLE_PIN 128 //#define X_CS_PIN 21 #define Y_STEP_PIN 132 #define Y_DIR_PIN 133 #define Y_ENABLE_PIN 131 //#define Y_CS_PIN 22 #define Z_STEP_PIN 135 #define Z_DIR_PIN 136 #define Z_ENABLE_PIN 134 //#define Z_CS_PIN 5 // SS_PIN #define E0_STEP_PIN 138 #define E0_DIR_PIN 139 #define E0_ENABLE_PIN 137 //#define E0_CS_PIN 21 #define E1_STEP_PIN 141 #define E1_DIR_PIN 142 #define E1_ENABLE_PIN 140 //#define E1_CS_PIN 22 #define Z2_STEP_PIN 141 #define Z2_DIR_PIN 142 #define Z2_ENABLE_PIN 140 //#define Z2_CS_PIN 5 // // Temperature Sensors // #define TEMP_0_PIN 36 // Analog Input #define TEMP_1_PIN 34 // Analog Input #define TEMP_BED_PIN 39 // Analog Input // // Heaters / Fans // #define HEATER_0_PIN 145 // 2 #define FAN_PIN 146 // 15 #define HEATER_BED_PIN 144 // 4 #define CONTROLLER_FAN_PIN 147 //#define E0_AUTO_FAN_PIN 148 // need to update Configuration_adv.h @section extruder //#define E1_AUTO_FAN_PIN 149 // need to update Configuration_adv.h @section extruder #define FAN1_PIN 149 // // MicroSD card // #define MOSI_PIN 23 #define MISO_PIN 19 #define SCK_PIN 18 #define SDSS 5 #define USES_SHARED_SPI // SPI is shared by SD card with TMC SPI drivers ////////////////////////// // LCDs and Controllers // ////////////////////////// #if HAS_GRAPHICAL_LCD #define LCD_PINS_RS 13 #define LCD_PINS_ENABLE 17 #define LCD_PINS_D4 16 #if ENABLED(CR10_STOCKDISPLAY) #define BEEPER_PIN 151 #elif ENABLED(REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER) #define BEEPER_PIN 151 //#define LCD_PINS_D5 150 //#define LCD_PINS_D6 151 //#define LCD_PINS_D7 153 #else #error "Only CR10_STOCKDISPLAY and REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER are currently supported. Comment out this line to continue." #endif #define BTN_EN1 0 #define BTN_EN2 12 #define BTN_ENC 14 #endif // HAS_GRAPHICAL_LCD
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/HAL/HAL_LPC1768/HAL.h
<gh_stars>0 /** * Marlin 3D Printer Firmware * * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * Copyright (c) 2016 <NAME> <EMAIL> * Copyright (c) 2015-2016 <NAME> <EMAIL> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * HAL_LPC1768/HAL.h * Hardware Abstraction Layer for NXP LPC1768 */ #define CPU_32_BIT void HAL_init(); #include <stdint.h> #include <stdarg.h> #include <algorithm> extern "C" volatile uint32_t _millis; #include "../shared/Marduino.h" #include "../shared/math_32bit.h" #include "../shared/HAL_SPI.h" #include "fastio.h" #include "watchdog.h" #include "timers.h" #include "MarlinSerial.h" #include <adc.h> #include <pinmapping.h> #include <CDCSerial.h> // // Default graphical display delays // #ifndef ST7920_DELAY_1 #define ST7920_DELAY_1 DELAY_NS(600) #endif #ifndef ST7920_DELAY_2 #define ST7920_DELAY_2 DELAY_NS(750) #endif #ifndef ST7920_DELAY_3 #define ST7920_DELAY_3 DELAY_NS(750) #endif #if SERIAL_PORT == -1 #define MYSERIAL0 UsbSerial #elif SERIAL_PORT == 0 #define MYSERIAL0 MSerial #elif SERIAL_PORT == 1 #define MYSERIAL0 MSerial1 #elif SERIAL_PORT == 2 #define MYSERIAL0 MSerial2 #elif SERIAL_PORT == 3 #define MYSERIAL0 MSerial3 #else #error "SERIAL_PORT must be from -1 to 3. Please update your configuration." #endif #ifdef SERIAL_PORT_2 #if SERIAL_PORT_2 == SERIAL_PORT #error "SERIAL_PORT_2 must be different than SERIAL_PORT. Please update your configuration." #elif SERIAL_PORT_2 == -1 #define MYSERIAL1 UsbSerial #elif SERIAL_PORT_2 == 0 #define MYSERIAL1 MSerial #elif SERIAL_PORT_2 == 1 #define MYSERIAL1 MSerial1 #elif SERIAL_PORT_2 == 2 #define MYSERIAL1 MSerial2 #elif SERIAL_PORT_2 == 3 #define MYSERIAL1 MSerial3 #else #error "SERIAL_PORT_2 must be from -1 to 3. Please update your configuration." #endif #define NUM_SERIAL 2 #else #define NUM_SERIAL 1 #endif #ifdef DGUS_SERIAL_PORT #if DGUS_SERIAL_PORT == SERIAL_PORT #error "DGUS_SERIAL_PORT must be different than SERIAL_PORT. Please update your configuration." #elif defined(SERIAL_PORT_2) && DGUS_SERIAL_PORT == SERIAL_PORT_2 #error "DGUS_SERIAL_PORT must be different than SERIAL_PORT_2. Please update your configuration." #elif DGUS_SERIAL_PORT == -1 #define DGUS_SERIAL UsbSerial #elif DGUS_SERIAL_PORT == 0 #define DGUS_SERIAL MSerial #elif DGUS_SERIAL_PORT == 1 #define DGUS_SERIAL MSerial1 #elif DGUS_SERIAL_PORT == 2 #define DGUS_SERIAL MSerial2 #elif DGUS_SERIAL_PORT == 3 #define DGUS_SERIAL MSerial3 #else #error "DGUS_SERIAL_PORT must be from -1 to 3. Please update your configuration." #endif #endif // // Interrupts // #define CRITICAL_SECTION_START uint32_t primask = __get_PRIMASK(); __disable_irq() #define CRITICAL_SECTION_END if (!primask) __enable_irq() #define ISRS_ENABLED() (!__get_PRIMASK()) #define ENABLE_ISRS() __enable_irq() #define DISABLE_ISRS() __disable_irq() // // Utility functions // #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" int freeMemory(); #pragma GCC diagnostic pop // // ADC API // #define ADC_MEDIAN_FILTER_SIZE (23) // Higher values increase step delay (phase shift), // (ADC_MEDIAN_FILTER_SIZE + 1) / 2 sample step delay (12 samples @ 500Hz: 24ms phase shift) // Memory usage per ADC channel (bytes): (6 * ADC_MEDIAN_FILTER_SIZE) + 16 // 8 * ((6 * 23) + 16 ) = 1232 Bytes for 8 channels #define ADC_LOWPASS_K_VALUE (2) // Higher values increase rise time // Rise time sample delays for 100% signal convergence on full range step // (1 : 13, 2 : 32, 3 : 67, 4 : 139, 5 : 281, 6 : 565, 7 : 1135, 8 : 2273) // K = 6, 565 samples, 500Hz sample rate, 1.13s convergence on full range step // Memory usage per ADC channel (bytes): 4 (32 Bytes for 8 channels) #define HAL_ADC_RESOLUTION 12 // 15 bit maximum, raw temperature is stored as int16_t #define HAL_ADC_FILTERED // Disable oversampling done in Marlin as ADC values already filtered in HAL using FilteredADC = LPC176x::ADC<ADC_LOWPASS_K_VALUE, ADC_MEDIAN_FILTER_SIZE>; extern uint32_t HAL_adc_reading; [[gnu::always_inline]] inline void HAL_start_adc(const pin_t pin) { HAL_adc_reading = FilteredADC::read(pin) >> (16 - HAL_ADC_RESOLUTION); // returns 16bit value, reduce to required bits } [[gnu::always_inline]] inline uint16_t HAL_read_adc() { return HAL_adc_reading; } #define HAL_adc_init() #define HAL_ANALOG_SELECT(pin) FilteredADC::enable_channel(pin) #define HAL_START_ADC(pin) HAL_start_adc(pin) #define HAL_READ_ADC() HAL_read_adc() #define HAL_ADC_READY() (true) // Test whether the pin is valid constexpr bool VALID_PIN(const pin_t pin) { return LPC176x::pin_is_valid(pin); } // Get the analog index for a digital pin constexpr int8_t DIGITAL_PIN_TO_ANALOG_PIN(const pin_t pin) { return (LPC176x::pin_is_valid(pin) && LPC176x::pin_has_adc(pin)) ? pin : -1; } // Return the index of a pin number constexpr int16_t GET_PIN_MAP_INDEX(const pin_t pin) { return LPC176x::pin_index(pin); } // Get the pin number at the given index constexpr pin_t GET_PIN_MAP_PIN(const int16_t index) { return LPC176x::pin_index(index); } // Parse a G-code word into a pin index int16_t PARSED_PIN_INDEX(const char code, const int16_t dval); // P0.6 thru P0.9 are for the onboard SD card #define HAL_SENSITIVE_PINS P0_06, P0_07, P0_08, P0_09 #define HAL_IDLETASK 1 void HAL_idletask(); #define PLATFORM_M997_SUPPORT void flashFirmware(int16_t value); /** * set_pwm_frequency * Set the frequency of the timer corresponding to the provided pin * All Hardware PWM pins run at the same frequency and all * Software PWM pins run at the same frequency */ void set_pwm_frequency(const pin_t pin, int f_desired); /** * set_pwm_duty * Set the PWM duty cycle of the provided pin to the provided value * Optionally allows inverting the duty cycle [default = false] * Optionally allows changing the maximum size of the provided value to enable finer PWM duty control [default = 255] */ void set_pwm_duty(const pin_t pin, const uint16_t v, const uint16_t v_size=255, const bool invert=false); // Reset source void HAL_clear_reset_source(void); uint8_t HAL_get_reset_source(void);
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/lcd/extensible_ui/lib/ftdi_eve_touch_ui/screens/screens.h
/************* * screens.h * *************/ /**************************************************************************** * Written By <NAME> 2017 - Aleph Objects, Inc. * * Written By <NAME> 2018 - Aleph Objects, Inc. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * To view a copy of the GNU General Public License, go to the following * * location: <http://www.gnu.org/licenses/>. * ****************************************************************************/ #pragma once #include "../ftdi_eve_lib/ftdi_eve_lib.h" #include "../language/language.h" #include "../theme/theme.h" #include "string_format.h" extern tiny_timer_t refresh_timer; /********************************* DL CACHE SLOTS ******************************/ // In order to reduce SPI traffic, we cache display lists (DL) in RAMG. This // is done using the CLCD::DLCache class, which takes a unique ID for each // cache location. These IDs are defined here: enum { STATUS_SCREEN_CACHE, MENU_SCREEN_CACHE, TUNE_SCREEN_CACHE, ADJUST_OFFSETS_SCREEN_CACHE, ALERT_BOX_CACHE, SPINNER_CACHE, ADVANCED_SETTINGS_SCREEN_CACHE, MOVE_AXIS_SCREEN_CACHE, TEMPERATURE_SCREEN_CACHE, STEPS_SCREEN_CACHE, STEPPER_CURRENT_SCREEN_CACHE, STEPPER_BUMP_SENSITIVITY_SCREEN_CACHE, ZOFFSET_SCREEN_CACHE, NOZZLE_OFFSET_SCREEN_CACHE, BACKLASH_COMPENSATION_SCREEN_CACHE, MAX_FEEDRATE_SCREEN_CACHE, MAX_VELOCITY_SCREEN_CACHE, MAX_ACCELERATION_SCREEN_CACHE, DEFAULT_ACCELERATION_SCREEN_CACHE, #if DISABLED(CLASSIC_JERK) JUNC_DEV_SCREEN_CACHE, #else JERK_SCREEN_CACHE, #endif #if HAS_CASE_LIGHT CASE_LIGHT_SCREEN_CACHE, #endif #if EITHER(LIN_ADVANCE, FILAMENT_RUNOUT_SENSOR) FILAMENT_MENU_CACHE, #endif #if ENABLED(LIN_ADVANCE) LINEAR_ADVANCE_SCREEN_CACHE, #endif #if ENABLED(FILAMENT_RUNOUT_SENSOR) FILAMENT_RUNOUT_SCREEN_CACHE, #endif #if ENABLED(TOUCH_UI_LULZBOT_BIO) PRINTING_SCREEN_CACHE, #endif #if ENABLED(TOUCH_UI_COCOA_PRESS) PREHEAT_TIMER_SCREEN_CACHE, #endif CHANGE_FILAMENT_SCREEN_CACHE, INTERFACE_SETTINGS_SCREEN_CACHE, INTERFACE_SOUNDS_SCREEN_CACHE, LOCK_SCREEN_CACHE, FILES_SCREEN_CACHE, DISPLAY_TIMINGS_SCREEN_CACHE }; // To save MCU RAM, the status message is "baked" in to the status screen // cache, so we reserve a large chunk of memory for the DL cache #define STATUS_SCREEN_DL_SIZE 2048 #define ALERT_BOX_DL_SIZE 3072 #define SPINNER_DL_SIZE 3072 #define FILE_SCREEN_DL_SIZE 3072 #define PRINTING_SCREEN_DL_SIZE 2048 /************************* MENU SCREEN DECLARATIONS *************************/ class BaseScreen : public UIScreen { protected: #ifdef LCD_TIMEOUT_TO_STATUS static uint32_t last_interaction; #endif static bool buttonIsPressed(uint8_t tag); public: static bool buttonStyleCallback(CommandProcessor &, uint8_t, uint8_t &, uint16_t &, bool); static void reset_menu_timeout(); static void onEntry(); static void onIdle(); }; class BootScreen : public BaseScreen, public UncachedScreen { private: static void showSplashScreen(); public: static void onRedraw(draw_mode_t); static void onIdle(); }; class AboutScreen : public BaseScreen, public UncachedScreen { public: static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; #if ENABLED(PRINTCOUNTER) class StatisticsScreen : public BaseScreen, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; #endif class KillScreen { // The KillScreen is behaves differently than the // others, so we do not bother extending UIScreen. public: static void show(const char*); }; class DialogBoxBaseClass : public BaseScreen { protected: template<typename T> static void drawMessage(const T, int16_t font = 0); static void drawYesNoButtons(uint8_t default_btn = 0); static void drawOkayButton(); static void drawSpinner(); static void drawButton(const progmem_str); static void onRedraw(draw_mode_t) {}; public: static bool onTouchEnd(uint8_t tag); static void onIdle(); }; class AlertDialogBox : public DialogBoxBaseClass, public CachedScreen<ALERT_BOX_CACHE,ALERT_BOX_DL_SIZE> { public: static void onEntry(); static void onRedraw(draw_mode_t); template<typename T> static void show(T); template<typename T> static void showError(T); static void hide(); }; class RestoreFailsafeDialogBox : public DialogBoxBaseClass, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; class SaveSettingsDialogBox : public DialogBoxBaseClass, public UncachedScreen { private: static bool needs_save; public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); static void promptToSaveSettings(); static void settingsChanged() {needs_save = true;} }; class ConfirmStartPrintDialogBox : public DialogBoxBaseClass, public UncachedScreen { private: inline static const char *getShortFilename() {return getFilename(false);} inline static const char *getLongFilename() {return getFilename(true);} static const char *getFilename(bool longName); public: static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t); static void show(uint8_t file_index); }; class ConfirmAbortPrintDialogBox : public DialogBoxBaseClass, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; #if ENABLED(CALIBRATION_GCODE) class ConfirmAutoCalibrationDialogBox : public DialogBoxBaseClass, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; #endif class ConfirmUserRequestAlertBox : public AlertDialogBox { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t); static void hide(); static void show(const char*); }; class SpinnerDialogBox : public DialogBoxBaseClass, public CachedScreen<SPINNER_CACHE,SPINNER_DL_SIZE> { public: static void onRedraw(draw_mode_t); static void onIdle(); static void show(const progmem_str); static void hide(); static void enqueueAndWait_P(const progmem_str commands); static void enqueueAndWait_P(const progmem_str message, const progmem_str commands); }; #if NONE(TOUCH_UI_LULZBOT_BIO, TOUCH_UI_COCOA_PRESS) class StatusScreen : public BaseScreen, public CachedScreen<STATUS_SCREEN_CACHE,STATUS_SCREEN_DL_SIZE> { private: static void draw_axis_position(draw_mode_t); static void draw_temperature(draw_mode_t); static void draw_progress(draw_mode_t); static void draw_interaction_buttons(draw_mode_t); static void draw_status_message(draw_mode_t, const char * const); public: static void loadBitmaps(); static void setStatusMessage(const char *); static void setStatusMessage(progmem_str); static void onRedraw(draw_mode_t); static void onStartup(); static void onEntry(); static void onIdle(); static bool onTouchEnd(uint8_t tag); }; #else class StatusScreen : public BaseScreen, public CachedScreen<STATUS_SCREEN_CACHE> { private: static float increment; static bool jog_xy; static bool fine_motion; static void draw_temperature(draw_mode_t what); static void draw_syringe(draw_mode_t what); static void draw_arrows(draw_mode_t what); static void draw_overlay_icons(draw_mode_t what); static void draw_fine_motion(draw_mode_t what); static void draw_buttons(draw_mode_t what); public: static void loadBitmaps(); static void unlockMotors(); static void setStatusMessage(const char *); static void setStatusMessage(progmem_str); static void onRedraw(draw_mode_t); static bool onTouchStart(uint8_t tag); static bool onTouchHeld(uint8_t tag); static bool onTouchEnd(uint8_t tag); static void onIdle(); }; #endif #if ENABLED(TOUCH_UI_LULZBOT_BIO) class BioPrintingDialogBox : public BaseScreen, public CachedScreen<PRINTING_SCREEN_CACHE,PRINTING_SCREEN_DL_SIZE> { private: static void draw_status_message(draw_mode_t, const char * const); static void draw_progress(draw_mode_t); static void draw_time_remaining(draw_mode_t); static void draw_interaction_buttons(draw_mode_t); public: static void onRedraw(draw_mode_t); static void show(); static void setStatusMessage(const char *); static void setStatusMessage(progmem_str); static void onIdle(); static bool onTouchEnd(uint8_t tag); }; class BioConfirmHomeXYZ : public DialogBoxBaseClass, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; class BioConfirmHomeE : public DialogBoxBaseClass, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; #endif #if ENABLED(TOUCH_UI_COCOA_PRESS) class PreheatTimerScreen : public BaseScreen, public CachedScreen<PREHEAT_TIMER_SCREEN_CACHE> { private: static uint16_t secondsRemaining(); static void draw_message(draw_mode_t); static void draw_time_remaining(draw_mode_t); static void draw_interaction_buttons(draw_mode_t); public: static void onRedraw(draw_mode_t); static void onEntry(); static void onIdle(); static bool onTouchEnd(uint8_t tag); }; #endif class MainMenu : public BaseScreen, public CachedScreen<MENU_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; class TuneMenu : public BaseScreen, public CachedScreen<TUNE_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; class TouchCalibrationScreen : public BaseScreen, public UncachedScreen { public: static void onRefresh(); static void onEntry(); static void onRedraw(draw_mode_t); static void onIdle(); }; class TouchRegistersScreen : public BaseScreen, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; class AdvancedSettingsMenu : public BaseScreen, public CachedScreen<ADVANCED_SETTINGS_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; class ChangeFilamentScreen : public BaseScreen, public CachedScreen<CHANGE_FILAMENT_SCREEN_CACHE> { private: static uint8_t getSoftenTemp(); static ExtUI::extruder_t getExtruder(); static void drawTempGradient(uint16_t x, uint16_t y, uint16_t w, uint16_t h); static uint32_t getTempColor(uint32_t temp); static void doPurge(); public: static void onEntry(); static void onExit(); static void onRedraw(draw_mode_t); static bool onTouchStart(uint8_t tag); static bool onTouchEnd(uint8_t tag); static bool onTouchHeld(uint8_t tag); static void onIdle(); }; class BaseNumericAdjustmentScreen : public BaseScreen { public: enum precision_default_t { DEFAULT_LOWEST, DEFAULT_MIDRANGE, DEFAULT_HIGHEST }; protected: class widgets_t { private: draw_mode_t _what; uint8_t _line; uint32_t _color; uint8_t _decimals; progmem_str _units; enum style_t { BTN_NORMAL, BTN_ACTION, BTN_TOGGLE, BTN_DISABLED, TEXT_AREA, TEXT_LABEL } _style; protected: void _draw_increment_btn(CommandProcessor &, uint8_t line, const uint8_t tag); void _button(CommandProcessor &, uint8_t tag, int16_t x, int16_t y, int16_t w, int16_t h, progmem_str, bool enabled = true, bool highlight = false); void _button_style(CommandProcessor &cmd, style_t style); public: widgets_t(draw_mode_t); widgets_t &color(uint32_t color) {_color = color; return *this;} widgets_t &units(progmem_str units) {_units = units; return *this;} widgets_t &draw_mode(draw_mode_t what) {_what = what; return *this;} widgets_t &precision(uint8_t decimals, precision_default_t = DEFAULT_HIGHEST); void heading (progmem_str label); void adjuster_sram_val (uint8_t tag, progmem_str label, const char *value, bool is_enabled = true); void adjuster (uint8_t tag, progmem_str label, const char *value, bool is_enabled = true); void adjuster (uint8_t tag, progmem_str label, float value=0, bool is_enabled = true); void button (uint8_t tag, progmem_str label, bool is_enabled = true); void text_field (uint8_t tag, progmem_str label, const char *value, bool is_enabled = true); void two_buttons (uint8_t tag1, progmem_str label1, uint8_t tag2, progmem_str label2, bool is_enabled = true); void toggle (uint8_t tag, progmem_str label, bool value, bool is_enabled = true); void home_buttons (uint8_t tag); void increments (); }; static float getIncrement(); public: static void onEntry(); static bool onTouchEnd(uint8_t tag); }; class MoveAxisScreen : public BaseNumericAdjustmentScreen, public CachedScreen<MOVE_AXIS_SCREEN_CACHE> { private: static float getManualFeedrate(uint8_t axis, float increment_mm); public: static void setManualFeedrate(ExtUI::axis_t, float increment_mm); static void setManualFeedrate(ExtUI::extruder_t, float increment_mm); static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); static void onIdle(); }; class StepsScreen : public BaseNumericAdjustmentScreen, public CachedScreen<STEPS_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #if HAS_TRINAMIC class StepperCurrentScreen : public BaseNumericAdjustmentScreen, public CachedScreen<STEPPER_CURRENT_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; class StepperBumpSensitivityScreen : public BaseNumericAdjustmentScreen, public CachedScreen<STEPPER_BUMP_SENSITIVITY_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #endif #if HAS_BED_PROBE class ZOffsetScreen : public BaseNumericAdjustmentScreen, public CachedScreen<ZOFFSET_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #endif #if HOTENDS > 1 class NozzleOffsetScreen : public BaseNumericAdjustmentScreen, public CachedScreen<NOZZLE_OFFSET_SCREEN_CACHE> { public: static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #endif #if ENABLED(BABYSTEPPING) class NudgeNozzleScreen : public BaseNumericAdjustmentScreen, public CachedScreen<ADJUST_OFFSETS_SCREEN_CACHE> { public: static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); static bool onTouchHeld(uint8_t tag); static void onIdle(); }; #endif #if ENABLED(BACKLASH_GCODE) class BacklashCompensationScreen : public BaseNumericAdjustmentScreen, public CachedScreen<BACKLASH_COMPENSATION_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #endif class FeedratePercentScreen : public BaseNumericAdjustmentScreen, public CachedScreen<MAX_FEEDRATE_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; class MaxVelocityScreen : public BaseNumericAdjustmentScreen, public CachedScreen<MAX_VELOCITY_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; class MaxAccelerationScreen : public BaseNumericAdjustmentScreen, public CachedScreen<MAX_ACCELERATION_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; class DefaultAccelerationScreen : public BaseNumericAdjustmentScreen, public CachedScreen<DEFAULT_ACCELERATION_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #if DISABLED(CLASSIC_JERK) class JunctionDeviationScreen : public BaseNumericAdjustmentScreen, public CachedScreen<JUNC_DEV_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #else class JerkScreen : public BaseNumericAdjustmentScreen, public CachedScreen<JERK_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #endif #if HAS_CASE_LIGHT class CaseLightScreen : public BaseNumericAdjustmentScreen, public CachedScreen<CASE_LIGHT_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #endif #if EITHER(LIN_ADVANCE, FILAMENT_RUNOUT_SENSOR) class FilamentMenu : public BaseNumericAdjustmentScreen, public CachedScreen<FILAMENT_MENU_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; #endif #if ENABLED(FILAMENT_RUNOUT_SENSOR) class FilamentRunoutScreen : public BaseNumericAdjustmentScreen, public CachedScreen<FILAMENT_RUNOUT_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #endif #if ENABLED(LIN_ADVANCE) class LinearAdvanceScreen : public BaseNumericAdjustmentScreen, public CachedScreen<LINEAR_ADVANCE_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #endif class TemperatureScreen : public BaseNumericAdjustmentScreen, public CachedScreen<TEMPERATURE_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; class InterfaceSoundsScreen : public BaseScreen, public CachedScreen<INTERFACE_SOUNDS_SCREEN_CACHE> { public: enum event_t { PRINTING_STARTED = 0, PRINTING_FINISHED = 1, PRINTING_FAILED = 2, NUM_EVENTS }; private: friend class InterfaceSettingsScreen; static uint8_t event_sounds[NUM_EVENTS]; static const char* getSoundSelection(event_t); static void toggleSoundSelection(event_t); static void setSoundSelection(event_t, const FTDI::SoundPlayer::sound_t*); public: static void playEventSound(event_t, FTDI::play_mode_t = FTDI::PLAY_ASYNCHRONOUS); static void defaultSettings(); static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchStart(uint8_t tag); static bool onTouchEnd(uint8_t tag); static void onIdle(); }; class InterfaceSettingsScreen : public BaseScreen, public CachedScreen<INTERFACE_SETTINGS_SCREEN_CACHE> { private: struct persistent_data_t { uint32_t touch_transform_a; uint32_t touch_transform_b; uint32_t touch_transform_c; uint32_t touch_transform_d; uint32_t touch_transform_e; uint32_t touch_transform_f; uint16_t passcode; uint8_t display_brightness; int8_t display_h_offset_adj; int8_t display_v_offset_adj; uint8_t sound_volume; uint8_t bit_flags; uint8_t event_sounds[InterfaceSoundsScreen::NUM_EVENTS]; }; public: #ifdef ARCHIM2_SPI_FLASH_EEPROM_BACKUP_SIZE static bool backupEEPROM(); #endif static void saveSettings(char *); static void loadSettings(const char *); static void defaultSettings(); static void failSafeSettings(); static void onStartup(); static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchStart(uint8_t tag); static bool onTouchEnd(uint8_t tag); static void onIdle(); }; class LockScreen : public BaseScreen, public CachedScreen<LOCK_SCREEN_CACHE> { private: friend InterfaceSettingsScreen; static uint16_t passcode; static char & message_style(); static uint16_t compute_checksum(); static void onPasscodeEntered(); public: static bool is_enabled(); static void check_passcode(); static void enable(); static void disable(); static void set_hash(uint16_t pass) {passcode = pass;}; static uint16_t get_hash() {return passcode;}; static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; class FilesScreen : public BaseScreen, public CachedScreen<FILES_SCREEN_CACHE, FILE_SCREEN_DL_SIZE> { private: #ifdef TOUCH_UI_PORTRAIT static constexpr uint8_t header_h = 2; static constexpr uint8_t footer_h = 2; static constexpr uint8_t files_per_page = 11; #else static constexpr uint8_t header_h = 1; static constexpr uint8_t footer_h = 1; static constexpr uint8_t files_per_page = 6; #endif static uint8_t getTagForLine(uint8_t line) {return line + 2;} static uint8_t getLineForTag(uint8_t tag) {return tag - 2;} static uint16_t getFileForTag(uint8_t tag); static uint16_t getSelectedFileIndex(); inline static const char *getSelectedShortFilename() {return getSelectedFilename(false);} inline static const char *getSelectedLongFilename() {return getSelectedFilename(true);} static const char *getSelectedFilename(bool longName); static void drawFileButton(const char* filename, uint8_t tag, bool is_dir, bool is_highlighted); static void drawFileList(); static void drawHeader(); static void drawFooter(); static void drawSelectedFile(); static void gotoPage(uint8_t); public: static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); static void onIdle(); }; class EndstopStatesScreen : public BaseScreen, public UncachedScreen { public: static void onEntry(); static void onExit(); static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); static void onIdle(); }; class DisplayTuningScreen : public BaseNumericAdjustmentScreen, public CachedScreen<DISPLAY_TIMINGS_SCREEN_CACHE> { public: static void onRedraw(draw_mode_t); static bool onTouchHeld(uint8_t tag); }; #if ENABLED(TOUCH_UI_DEVELOPER_MENU) class DeveloperMenu : public BaseScreen, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; class ConfirmEraseFlashDialogBox : public DialogBoxBaseClass, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; class WidgetsScreen : public BaseScreen, public UncachedScreen { public: static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchStart(uint8_t tag); static void onIdle(); }; class StressTestScreen : public BaseScreen, public UncachedScreen { private: static void drawDots(uint16_t x, uint16_t y, uint16_t h, uint16_t v); static bool watchDogTestNow(); static void recursiveLockup(); static void iterativeLockup(); static void runTestOnBootup(bool enable); public: static void startupCheck(); static void onEntry(); static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); static void onIdle(); }; #endif class MediaPlayerScreen : public BaseScreen, public UncachedScreen { private: typedef int16_t media_streamer_func_t(void *obj, void *buff, size_t bytes); public: static bool playCardMedia(); static bool playBootMedia(); static void onEntry(); static void onRedraw(draw_mode_t); static void playStream(void *obj, media_streamer_func_t*); }; #if NUM_LANGUAGES > 1 class LanguageMenu : public BaseScreen, public UncachedScreen { public: static void onRedraw(draw_mode_t); static bool onTouchEnd(uint8_t tag); }; #endif
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/HAL/platforms.h
<reponame>DDilshani/CO326-project /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once #ifdef __AVR__ #define HAL_PLATFORM HAL_AVR #elif defined(ARDUINO_ARCH_SAM) #define HAL_PLATFORM HAL_DUE #elif defined(__MK20DX256__) #define HAL_PLATFORM HAL_TEENSY31_32 #elif defined(__MK64FX512__) || defined(__MK66FX1M0__) #define HAL_PLATFORM HAL_TEENSY35_36 #elif defined(TARGET_LPC1768) #define HAL_PLATFORM HAL_LPC1768 #elif defined(__STM32F1__) || defined(TARGET_STM32F1) #define HAL_PLATFORM HAL_STM32F1 #elif defined(STM32GENERIC) && (defined(STM32F4) || defined(STM32F7)) #define HAL_PLATFORM HAL_STM32_F4_F7 #elif defined(ARDUINO_ARCH_STM32) #define HAL_PLATFORM HAL_STM32 #elif defined(ARDUINO_ARCH_ESP32) #define HAL_PLATFORM HAL_ESP32 #elif defined(__PLAT_LINUX__) #define HAL_PLATFORM HAL_LINUX #elif defined(__SAMD51__) #define HAL_PLATFORM HAL_SAMD51 #else #error "Unsupported Platform!" #endif #define XSTR_(M) #M #define XSTR(M) XSTR_(M) #define HAL_PATH(PATH, NAME) XSTR(PATH/HAL_PLATFORM/NAME)
DDilshani/CO326-project
firmware/grbl-Mega/src/serial.h
/* serial.c - Low level functions for sending and recieving bytes via the serial port Part of Grbl Copyright (c) 2011-2016 <NAME> for Gnea Research LLC Copyright (c) 2009-2011 <NAME> Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ #ifndef serial_h #define serial_h #ifndef RX_BUFFER_SIZE #define RX_BUFFER_SIZE 255 #endif #ifndef TX_BUFFER_SIZE #define TX_BUFFER_SIZE 255 #endif #define SERIAL_NO_DATA 0xff void serial_init(); // Writes one byte to the TX serial buffer. Called by main program. void serial_write(uint8_t data); // Write à string to the TX serial buffer. (for debugging) void serial_putstring(char* StringPtr); // Fetches the first byte in the serial read buffer. Called by main program. uint8_t serial_read(); // Reset and empty data in read buffer. Used by e-stop and reset. void serial_reset_read_buffer(); // Returns the number of bytes available in the RX serial buffer. uint8_t serial_get_rx_buffer_available(); // Returns the number of bytes used in the RX serial buffer. // NOTE: Deprecated. Not used unless classic status reports are enabled in config.h. uint8_t serial_get_rx_buffer_count(); // Returns the number of bytes used in the TX serial buffer. // NOTE: Not used except for debugging and ensuring no TX bottlenecks. uint8_t serial_get_tx_buffer_count(); #endif
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/HAL/HAL_STM32/HAL.h
/** * Marlin 3D Printer Firmware * * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * Copyright (c) 2016 <NAME> <EMAIL> * Copyright (c) 2015-2016 <NAME> <EMAIL> * Copyright (c) 2017 <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once #define CPU_32_BIT #include "../../core/macros.h" #include "../shared/Marduino.h" #include "../shared/math_32bit.h" #include "../shared/HAL_SPI.h" #include "fastio.h" #include "watchdog.h" #include "../../inc/MarlinConfigPre.h" #include <stdint.h> #ifdef USBCON #include <USBSerial.h> #endif // ------------------------ // Defines // ------------------------ #if SERIAL_PORT == 0 #error "SERIAL_PORT cannot be 0. (Port 0 does not exist.) Please update your configuration." #elif SERIAL_PORT == -1 #define MYSERIAL0 SerialUSB #elif SERIAL_PORT == 1 #define MYSERIAL0 Serial1 #elif SERIAL_PORT == 2 #define MYSERIAL0 Serial2 #elif SERIAL_PORT == 3 #define MYSERIAL0 Serial3 #elif SERIAL_PORT == 4 #define MYSERIAL0 Serial4 #elif SERIAL_PORT == 5 #define MYSERIAL0 Serial5 #elif SERIAL_PORT == 6 #define MYSERIAL0 Serial6 #else #error "SERIAL_PORT must be from -1 to 6. Please update your configuration." #endif #ifdef SERIAL_PORT_2 #define NUM_SERIAL 2 #if SERIAL_PORT_2 == 0 #error "SERIAL_PORT_2 cannot be 0. (Port 0 does not exist.) Please update your configuration." #elif SERIAL_PORT_2 == SERIAL_PORT #error "SERIAL_PORT_2 must be different than SERIAL_PORT. Please update your configuration." #elif SERIAL_PORT_2 == -1 #define MYSERIAL1 SerialUSB #elif SERIAL_PORT_2 == 1 #define MYSERIAL1 Serial1 #elif SERIAL_PORT_2 == 2 #define MYSERIAL1 Serial2 #elif SERIAL_PORT_2 == 3 #define MYSERIAL1 Serial3 #elif SERIAL_PORT_2 == 4 #define MYSERIAL1 Serial4 #elif SERIAL_PORT_2 == 5 #define MYSERIAL1 Serial5 #elif SERIAL_PORT_2 == 6 #define MYSERIAL1 Serial6 #else #error "SERIAL_PORT_2 must be from -1 to 6. Please update your configuration." #endif #else #define NUM_SERIAL 1 #endif #if HAS_DGUS_LCD #if DGUS_SERIAL_PORT == 0 #error "DGUS_SERIAL_PORT cannot be 0. (Port 0 does not exist.) Please update your configuration." #elif DGUS_SERIAL_PORT == SERIAL_PORT #error "DGUS_SERIAL_PORT must be different than SERIAL_PORT. Please update your configuration." #elif defined(SERIAL_PORT_2) && DGUS_SERIAL_PORT == SERIAL_PORT_2 #error "DGUS_SERIAL_PORT must be different than SERIAL_PORT_2. Please update your configuration." #elif DGUS_SERIAL_PORT == -1 #define DGUS_SERIAL SerialUSB #elif DGUS_SERIAL_PORT == 1 #define DGUS_SERIAL Serial1 #elif DGUS_SERIAL_PORT == 2 #define DGUS_SERIAL Serial2 #elif DGUS_SERIAL_PORT == 3 #define DGUS_SERIAL Serial3 #elif DGUS_SERIAL_PORT == 4 #define DGUS_SERIAL Serial4 #elif DGUS_SERIAL_PORT == 5 #define DGUS_SERIAL Serial5 #elif DGUS_SERIAL_PORT == 6 #define DGUS_SERIAL Serial6 #else #error "DGUS_SERIAL_PORT must be from -1 to 6. Please update your configuration." #endif #define DGUS_SERIAL_GET_TX_BUFFER_FREE DGUS_SERIAL.availableForWrite #endif #include "timers.h" /** * TODO: review this to return 1 for pins that are not analog input */ #ifndef analogInputToDigitalPin #define analogInputToDigitalPin(p) (p) #endif #define CRITICAL_SECTION_START uint32_t primask = __get_PRIMASK(); __disable_irq() #define CRITICAL_SECTION_END if (!primask) __enable_irq() #define ISRS_ENABLED() (!__get_PRIMASK()) #define ENABLE_ISRS() __enable_irq() #define DISABLE_ISRS() __disable_irq() #define cli() __disable_irq() #define sei() __enable_irq() // On AVR this is in math.h? #define square(x) ((x)*(x)) #ifndef strncpy_P #define strncpy_P(dest, src, num) strncpy((dest), (src), (num)) #endif // Fix bug in pgm_read_ptr #undef pgm_read_ptr #define pgm_read_ptr(addr) (*(addr)) // ------------------------ // Types // ------------------------ typedef int16_t pin_t; #define HAL_SERVO_LIB libServo // ------------------------ // Public Variables // ------------------------ // result of last ADC conversion extern uint16_t HAL_adc_result; // ------------------------ // Public functions // ------------------------ // Memory related #define __bss_end __bss_end__ // Enable hooks into setup for HAL void HAL_init(); // Clear reset reason void HAL_clear_reset_source(); // Reset reason uint8_t HAL_get_reset_source(); void _delay_ms(const int delay); extern "C" char* _sbrk(int incr); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" static inline int freeMemory() { volatile char top; return &top - reinterpret_cast<char*>(_sbrk(0)); } #pragma GCC diagnostic pop // // EEPROM // // Wire library should work for i2c EEPROMs void eeprom_write_byte(uint8_t *pos, unsigned char value); uint8_t eeprom_read_byte(uint8_t *pos); void eeprom_read_block(void *__dst, const void *__src, size_t __n); void eeprom_update_block(const void *__src, void *__dst, size_t __n); // // ADC // #define HAL_ANALOG_SELECT(pin) pinMode(pin, INPUT) inline void HAL_adc_init() {} #define HAL_START_ADC(pin) HAL_adc_start_conversion(pin) #define HAL_ADC_RESOLUTION 10 #define HAL_READ_ADC() HAL_adc_result #define HAL_ADC_READY() true void HAL_adc_start_conversion(const uint8_t adc_pin); uint16_t HAL_adc_get_result(); #define GET_PIN_MAP_PIN(index) index #define GET_PIN_MAP_INDEX(pin) pin #define PARSED_PIN_INDEX(code, dval) parser.intval(code, dval) #define PLATFORM_M997_SUPPORT void flashFirmware(int16_t value);
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/module/stepper/TMC26X.h
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * stepper/TMC26X.h * Stepper driver indirection for TMC26X drivers */ #include "../../inc/MarlinConfig.h" // TMC26X drivers have STEP/DIR on normal pins, but ENABLE via SPI #include <SPI.h> #if defined(STM32GENERIC) && defined(STM32F7) #include "../../HAL/HAL_STM32_F4_F7/STM32F7/TMC2660.h" #else #include <TMC26XStepper.h> #endif void tmc26x_init_to_defaults(); // X Stepper #if AXIS_DRIVER_TYPE_X(TMC26X) extern TMC26XStepper stepperX; #define X_ENABLE_INIT() NOOP #define X_ENABLE_WRITE(STATE) stepperX.setEnabled(STATE) #define X_ENABLE_READ() stepperX.isEnabled() #endif // Y Stepper #if AXIS_DRIVER_TYPE_Y(TMC26X) extern TMC26XStepper stepperY; #define Y_ENABLE_INIT() NOOP #define Y_ENABLE_WRITE(STATE) stepperY.setEnabled(STATE) #define Y_ENABLE_READ() stepperY.isEnabled() #endif // Z Stepper #if AXIS_DRIVER_TYPE_Z(TMC26X) extern TMC26XStepper stepperZ; #define Z_ENABLE_INIT() NOOP #define Z_ENABLE_WRITE(STATE) stepperZ.setEnabled(STATE) #define Z_ENABLE_READ() stepperZ.isEnabled() #endif // X2 Stepper #if HAS_X2_ENABLE && AXIS_DRIVER_TYPE_X2(TMC26X) extern TMC26XStepper stepperX2; #define X2_ENABLE_INIT() NOOP #define X2_ENABLE_WRITE(STATE) stepperX2.setEnabled(STATE) #define X2_ENABLE_READ() stepperX2.isEnabled() #endif // Y2 Stepper #if HAS_Y2_ENABLE && AXIS_DRIVER_TYPE_Y2(TMC26X) extern TMC26XStepper stepperY2; #define Y2_ENABLE_INIT() NOOP #define Y2_ENABLE_WRITE(STATE) stepperY2.setEnabled(STATE) #define Y2_ENABLE_READ() stepperY2.isEnabled() #endif // Z2 Stepper #if HAS_Z2_ENABLE && AXIS_DRIVER_TYPE_Z2(TMC26X) extern TMC26XStepper stepperZ2; #define Z2_ENABLE_INIT() NOOP #define Z2_ENABLE_WRITE(STATE) stepperZ2.setEnabled(STATE) #define Z2_ENABLE_READ() stepperZ2.isEnabled() #endif // Z3 Stepper #if HAS_Z3_ENABLE && AXIS_DRIVER_TYPE_Z3(TMC26X) extern TMC26XStepper stepperZ3; #define Z3_ENABLE_INIT() NOOP #define Z3_ENABLE_WRITE(STATE) stepperZ3.setEnabled(STATE) #define Z3_ENABLE_READ() stepperZ3.isEnabled() #endif // Z4 Stepper #if HAS_Z4_ENABLE && AXIS_DRIVER_TYPE_Z4(TMC26X) extern TMC26XStepper stepperZ4; #define Z4_ENABLE_INIT() NOOP #define Z4_ENABLE_WRITE(STATE) stepperZ4.setEnabled(STATE) #define Z4_ENABLE_READ() stepperZ4.isEnabled() #endif // E0 Stepper #if AXIS_DRIVER_TYPE_E0(TMC26X) extern TMC26XStepper stepperE0; #define E0_ENABLE_INIT() NOOP #define E0_ENABLE_WRITE(STATE) stepperE0.setEnabled(STATE) #define E0_ENABLE_READ() stepperE0.isEnabled() #endif // E1 Stepper #if AXIS_DRIVER_TYPE_E1(TMC26X) extern TMC26XStepper stepperE1; #define E1_ENABLE_INIT() NOOP #define E1_ENABLE_WRITE(STATE) stepperE1.setEnabled(STATE) #define E1_ENABLE_READ() stepperE1.isEnabled() #endif // E2 Stepper #if AXIS_DRIVER_TYPE_E2(TMC26X) extern TMC26XStepper stepperE2; #define E2_ENABLE_INIT() NOOP #define E2_ENABLE_WRITE(STATE) stepperE2.setEnabled(STATE) #define E2_ENABLE_READ() stepperE2.isEnabled() #endif // E3 Stepper #if AXIS_DRIVER_TYPE_E3(TMC26X) extern TMC26XStepper stepperE3; #define E3_ENABLE_INIT() NOOP #define E3_ENABLE_WRITE(STATE) stepperE3.setEnabled(STATE) #define E3_ENABLE_READ() stepperE3.isEnabled() #endif // E4 Stepper #if AXIS_DRIVER_TYPE_E4(TMC26X) extern TMC26XStepper stepperE4; #define E4_ENABLE_INIT() NOOP #define E4_ENABLE_WRITE(STATE) stepperE4.setEnabled(STATE) #define E4_ENABLE_READ() stepperE4.isEnabled() #endif // E5 Stepper #if AXIS_DRIVER_TYPE_E5(TMC26X) extern TMC26XStepper stepperE5; #define E5_ENABLE_INIT() NOOP #define E5_ENABLE_WRITE(STATE) stepperE5.setEnabled(STATE) #define E5_ENABLE_READ() stepperE5.isEnabled() #endif // E6 Stepper #if AXIS_DRIVER_TYPE_E6(TMC26X) extern TMC26XStepper stepperE6; #define E6_ENABLE_INIT() NOOP #define E6_ENABLE_WRITE(STATE) stepperE6.setEnabled(STATE) #define E6_ENABLE_READ() stepperE6.isEnabled() #endif // E7 Stepper #if AXIS_DRIVER_TYPE_E7(TMC26X) extern TMC26XStepper stepperE7; #define E7_ENABLE_INIT() NOOP #define E7_ENABLE_WRITE(STATE) stepperE7.setEnabled(STATE) #define E7_ENABLE_READ() stepperE7.isEnabled() #endif
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/pins/lpc1769/pins_AZTEEG_X5_MINI.h
<reponame>DDilshani/CO326-project /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * Azteeg X5 MINI pin assignments */ #ifndef MCU_LPC1769 #error "Oops! Make sure you have the LPC1769 environment selected in your IDE." #endif #ifndef BOARD_INFO_NAME #define BOARD_INFO_NAME "Azteeg X5 MINI" #endif #define BOARD_WEBSITE_URL "tiny.cc/x5_mini" // // LED // #define LED_PIN P1_18 // // Servos // #define SERVO0_PIN P1_29 // // Limit Switches // #define X_STOP_PIN P1_24 #define Y_STOP_PIN P1_26 #define Z_STOP_PIN P1_28 #ifndef FIL_RUNOUT_PIN #define FIL_RUNOUT_PIN P2_04 #endif #ifndef FILWIDTH_PIN #define FILWIDTH_PIN P0_25_A2 // Analog Input (P0_25) #endif // // Steppers // #define X_STEP_PIN P2_01 #define X_DIR_PIN P0_11 #define X_ENABLE_PIN P0_10 #define Y_STEP_PIN P2_02 #define Y_DIR_PIN P0_20 #define Y_ENABLE_PIN P0_19 #define Z_STEP_PIN P2_03 #define Z_DIR_PIN P0_22 #define Z_ENABLE_PIN P0_21 #define E0_STEP_PIN P2_00 #define E0_DIR_PIN P0_05 #define E0_ENABLE_PIN P0_04 // // DIGIPOT slave addresses // #ifndef DIGIPOT_I2C_ADDRESS_A #define DIGIPOT_I2C_ADDRESS_A 0x2C // unshifted slave address for first DIGIPOT #endif #ifndef DIGIPOT_I2C_ADDRESS_B #define DIGIPOT_I2C_ADDRESS_B 0x2E // unshifted slave address for second DIGIPOT #endif // // Temperature Sensors // 3.3V max when defined as an analog input // #define TEMP_BED_PIN P0_23_A0 // A0 (TH1) #define TEMP_0_PIN P0_24_A1 // A1 (TH2) // // Heaters / Fans // #define HEATER_BED_PIN P2_07 #define HEATER_0_PIN P2_05 #ifndef FAN_PIN #define FAN_PIN P0_26 #endif #define FAN1_PIN P1_25 // // Display // #if HAS_SPI_LCD #if ENABLED(CR10_STOCKDISPLAY) // Re-Arm can support Creality stock display without SD card reader and single cable on EXP3. // Re-Arm J3 pins 1 (p1.31) & 2 (P3.26) are not used. Stock cable will need to have one // 10-pin IDC connector trimmed or replaced with a 12-pin IDC connector to fit J3. // Requires REVERSE_ENCODER_DIRECTION in Configuration.h #define BEEPER_PIN P2_11 // J3-3 & AUX-4 #define BTN_EN1 P0_16 // J3-7 & AUX-4 #define BTN_EN2 P1_23 // J3-5 & AUX-4 #define BTN_ENC P3_25 // J3-4 & AUX-4 #define LCD_PINS_RS P0_15 // J3-9 & AUX-4 (CS) #define LCD_PINS_ENABLE P0_18 // J3-10 & AUX-3 (SID, MOSI) #define LCD_PINS_D4 P2_06 // J3-8 & AUX-3 (SCK, CLK) #else #define BTN_EN1 P3_26 // (31) J3-2 & AUX-4 #define BTN_EN2 P3_25 // (33) J3-4 & AUX-4 #define BTN_ENC P2_11 // (35) J3-3 & AUX-4 #define SD_DETECT_PIN P1_31 // (49) not 5V tolerant J3-1 & AUX-3 #define KILL_PIN P1_22 // (41) J5-4 & AUX-4 #define LCD_PINS_RS P0_16 // (16) J3-7 & AUX-4 #define LCD_SDSS P0_16 // (16) J3-7 & AUX-4 #define LCD_BACKLIGHT_PIN P0_16 // (16) J3-7 & AUX-4 - only used on DOGLCD controllers #define LCD_PINS_ENABLE P0_18 // (51) (MOSI) J3-10 & AUX-3 #define LCD_PINS_D4 P0_15 // (52) (SCK) J3-9 & AUX-3 #define DOGLCD_A0 P2_06 // (59) J3-8 & AUX-2 #if ENABLED(REPRAPWORLD_KEYPAD) #define SHIFT_OUT P0_18 // (51) (MOSI) J3-10 & AUX-3 #define SHIFT_CLK P0_15 // (52) (SCK) J3-9 & AUX-3 #define SHIFT_LD P1_31 // (49) not 5V tolerant J3-1 & AUX-3 #elif DISABLED(NEWPANEL) //#define SHIFT_OUT P2_11 // (35) J3-3 & AUX-4 //#define SHIFT_CLK P3_26 // (31) J3-2 & AUX-4 //#define SHIFT_LD P3_25 // (33) J3-4 & AUX-4 //#define SHIFT_EN P1_22 // (41) J5-4 & AUX-4 #endif #if ANY(VIKI2, miniVIKI) //#define LCD_SCREEN_ROT_180 #define BEEPER_PIN P1_30 // (37) may change if cable changes #define DOGLCD_CS P0_26 // (63) J5-3 & AUX-2 #define DOGLCD_SCK SCK_PIN #define DOGLCD_MOSI MOSI_PIN #define STAT_LED_BLUE_PIN P0_26 // (63) may change if cable changes #define STAT_LED_RED_PIN P1_21 // ( 6) may change if cable changes #else #if ENABLED(ULTIPANEL) #define LCD_PINS_D5 P1_17 // (71) ENET_MDIO #define LCD_PINS_D6 P1_14 // (73) ENET_RX_ER #define LCD_PINS_D7 P1_10 // (75) ENET_RXD1 #endif #define BEEPER_PIN P1_30 // (37) not 5V tolerant #define DOGLCD_CS P0_16 // (16) #endif #if ENABLED(MINIPANEL) // GLCD features // Uncomment screen orientation //#define LCD_SCREEN_ROT_90 //#define LCD_SCREEN_ROT_180 //#define LCD_SCREEN_ROT_270 #endif #endif #endif // HAS_SPI_LCD // // SD Support // #ifndef SDCARD_CONNECTION #define SDCARD_CONNECTION ONBOARD #endif #define ONBOARD_SD_CS_PIN P0_06 // Chip select for "System" SD card #if SD_CONNECTION_IS(LCD) #define SCK_PIN P0_15 #define MISO_PIN P0_17 #define MOSI_PIN P0_18 #define SS_PIN P1_23 #elif SD_CONNECTION_IS(ONBOARD) #undef SD_DETECT_PIN #define SCK_PIN P0_07 #define MISO_PIN P0_08 #define MOSI_PIN P0_09 #define SS_PIN ONBOARD_SD_CS_PIN #elif SD_CONNECTION_IS(CUSTOM_CABLE) #error "No custom SD drive cable defined for this board." #endif
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/inc/Conditionals_LCD.h
<filename>firmware/Marlin-2.0.x/Marlin/src/inc/Conditionals_LCD.h /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * Conditionals_LCD.h * Conditionals that need to be set before Configuration_adv.h or pins.h */ #if ENABLED(CARTESIO_UI) #define DOGLCD #define IS_ULTIPANEL #elif ENABLED(ZONESTAR_LCD) #define ADC_KEYPAD #define IS_RRW_KEYPAD #define REPRAPWORLD_KEYPAD_MOVE_STEP 10.0 #define ADC_KEY_NUM 8 #define IS_ULTIPANEL // This helps to implement ADC_KEYPAD menus #define REVERSE_MENU_DIRECTION #define ENCODER_PULSES_PER_STEP 1 #define ENCODER_STEPS_PER_MENU_ITEM 1 #define ENCODER_FEEDRATE_DEADZONE 2 #elif ENABLED(RADDS_DISPLAY) #define IS_ULTIPANEL #define ENCODER_PULSES_PER_STEP 2 #elif EITHER(ANET_FULL_GRAPHICS_LCD, BQ_LCD_SMART_CONTROLLER) #define IS_RRD_FG_SC #elif ANY(miniVIKI, VIKI2, ELB_FULL_GRAPHIC_CONTROLLER, AZSMZ_12864) #define IS_ULTRA_LCD #define DOGLCD #define IS_ULTIPANEL #if ENABLED(miniVIKI) #define U8GLIB_ST7565_64128N #elif ENABLED(VIKI2) #define U8GLIB_ST7565_64128N #elif ENABLED(ELB_FULL_GRAPHIC_CONTROLLER) #define U8GLIB_LM6059_AF #define SD_DETECT_INVERTED #elif ENABLED(AZSMZ_12864) #define U8GLIB_ST7565_64128N #endif #elif ENABLED(OLED_PANEL_TINYBOY2) #define IS_U8GLIB_SSD1306 #define IS_ULTIPANEL #elif ENABLED(RA_CONTROL_PANEL) #define LCD_I2C_TYPE_PCA8574 #define LCD_I2C_ADDRESS 0x27 // I2C Address of the port expander #define IS_ULTIPANEL #elif ENABLED(REPRAPWORLD_GRAPHICAL_LCD) #define DOGLCD #define U8GLIB_ST7920 #define IS_ULTIPANEL #elif ENABLED(CR10_STOCKDISPLAY) #define IS_RRD_FG_SC #ifndef ST7920_DELAY_1 #define ST7920_DELAY_1 DELAY_NS(125) #endif #ifndef ST7920_DELAY_2 #define ST7920_DELAY_2 DELAY_NS(125) #endif #ifndef ST7920_DELAY_3 #define ST7920_DELAY_3 DELAY_NS(125) #endif #elif ENABLED(MKS_12864OLED) #define IS_RRD_SC #define U8GLIB_SH1106 #elif ENABLED(MKS_12864OLED_SSD1306) #define IS_RRD_SC #define IS_U8GLIB_SSD1306 #elif EITHER(MKS_MINI_12864, ENDER2_STOCKDISPLAY) #define MINIPANEL #elif ANY(FYSETC_MINI_12864_X_X, FYSETC_MINI_12864_1_2, FYSETC_MINI_12864_2_0, FYSETC_MINI_12864_2_1, FYSETC_GENERIC_12864_1_1) #define FYSETC_MINI_12864 #define DOGLCD #define IS_ULTIPANEL #define LED_COLORS_REDUCE_GREEN #if ENABLED(PSU_CONTROL) && EITHER(FYSETC_MINI_12864_2_0, FYSETC_MINI_12864_2_1) #define LED_BACKLIGHT_TIMEOUT 10000 #endif // Require LED backlighting enabled #if EITHER(FYSETC_MINI_12864_1_2, FYSETC_MINI_12864_2_0) #define RGB_LED #elif ENABLED(FYSETC_MINI_12864_2_1) #define LED_CONTROL_MENU #define NEOPIXEL_LED #undef NEOPIXEL_TYPE #define NEOPIXEL_TYPE NEO_RGB #if NEOPIXEL_PIXELS < 3 #undef NEOPIXELS_PIXELS #define NEOPIXEL_PIXELS 3 #endif #ifndef NEOPIXEL_BRIGHTNESS #define NEOPIXEL_BRIGHTNESS 127 #endif //#define NEOPIXEL_STARTUP_TEST #endif #elif ENABLED(ULTI_CONTROLLER) #define IS_ULTIPANEL #define U8GLIB_SSD1309 #define LCD_RESET_PIN LCD_PINS_D6 // This controller need a reset pin #define ENCODER_PULSES_PER_STEP 2 #define ENCODER_STEPS_PER_MENU_ITEM 2 #elif ENABLED(MAKEBOARD_MINI_2_LINE_DISPLAY_1602) #define IS_RRD_SC #define LCD_WIDTH 16 #define LCD_HEIGHT 2 #endif #if ENABLED(IS_RRD_FG_SC) #define REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER #endif #if EITHER(MAKRPANEL, MINIPANEL) #define IS_ULTIPANEL #define DOGLCD #if ENABLED(MAKRPANEL) #define U8GLIB_ST7565_64128N #endif #endif #if ENABLED(IS_U8GLIB_SSD1306) #define U8GLIB_SSD1306 #endif #if ENABLED(OVERLORD_OLED) #define IS_ULTIPANEL #define U8GLIB_SH1106 /** * PCA9632 for buzzer and LEDs via i2c * No auto-inc, red and green leds switched, buzzer */ #define PCA9632 #define PCA9632_NO_AUTO_INC #define PCA9632_GRN 0x00 #define PCA9632_RED 0x02 #define PCA9632_BUZZER #define PCA9632_BUZZER_DATA { 0x09, 0x02 } #define ENCODER_PULSES_PER_STEP 1 // Overlord uses buttons #define ENCODER_STEPS_PER_MENU_ITEM 1 #endif // 128x64 I2C OLED LCDs - SSD1306/SSD1309/SH1106 #define HAS_SSD1306_OLED_I2C ANY(U8GLIB_SSD1306, U8GLIB_SSD1309, U8GLIB_SH1106) #if HAS_SSD1306_OLED_I2C #define IS_ULTRA_LCD #define DOGLCD #endif // ST7920-based graphical displays #if ANY(REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER, LCD_FOR_MELZI, SILVER_GATE_GLCD_CONTROLLER) #define DOGLCD #define U8GLIB_ST7920 #define IS_RRD_SC #endif // RepRapDiscount LCD or Graphical LCD with rotary click encoder #if ENABLED(IS_RRD_SC) #define REPRAP_DISCOUNT_SMART_CONTROLLER #endif /** * SPI Ultipanels */ // Basic Ultipanel-like displays #if ANY(ULTIMAKERCONTROLLER, REPRAP_DISCOUNT_SMART_CONTROLLER, G3D_PANEL, RIGIDBOT_PANEL, PANEL_ONE, U8GLIB_SH1106) #define IS_ULTIPANEL #endif // Einstart OLED has Cardinal nav via pins defined in pins_EINSTART-S.h #if ENABLED(U8GLIB_SH1106_EINSTART) #define DOGLCD #define IS_ULTIPANEL #endif // FSMC/SPI TFT Panels #if ENABLED(FSMC_GRAPHICAL_TFT) #define DOGLCD #define IS_ULTIPANEL #define DELAYED_BACKLIGHT_INIT #endif /** * I2C Panels */ #if EITHER(LCD_SAINSMART_I2C_1602, LCD_SAINSMART_I2C_2004) #define LCD_I2C_TYPE_PCF8575 #define LCD_I2C_ADDRESS 0x27 // I2C Address of the port expander #if ENABLED(LCD_SAINSMART_I2C_2004) #define LCD_WIDTH 20 #define LCD_HEIGHT 4 #endif #elif ENABLED(LCD_I2C_PANELOLU2) // PANELOLU2 LCD with status LEDs, separate encoder and click inputs #define LCD_I2C_TYPE_MCP23017 #define LCD_I2C_ADDRESS 0x20 // I2C Address of the port expander #define LCD_USE_I2C_BUZZER // Enable buzzer on LCD (optional) #define IS_ULTIPANEL #elif ENABLED(LCD_I2C_VIKI) /** * Panucatt VIKI LCD with status LEDs, integrated click & L/R/U/P buttons, separate encoder inputs * * This uses the LiquidTWI2 library v1.2.3 or later ( https://github.com/lincomatic/LiquidTWI2 ) * Make sure the LiquidTWI2 directory is placed in the Arduino or Sketchbook libraries subdirectory. * Note: The pause/stop/resume LCD button pin should be connected to the Arduino * BTN_ENC pin (or set BTN_ENC to -1 if not used) */ #define LCD_I2C_TYPE_MCP23017 #define LCD_I2C_ADDRESS 0x20 // I2C Address of the port expander #define LCD_USE_I2C_BUZZER // Enable buzzer on LCD (requires LiquidTWI2 v1.2.3 or later) #define IS_ULTIPANEL #define ENCODER_FEEDRATE_DEADZONE 4 #define STD_ENCODER_PULSES_PER_STEP 1 #define STD_ENCODER_STEPS_PER_MENU_ITEM 2 #elif ENABLED(G3D_PANEL) #define STD_ENCODER_PULSES_PER_STEP 2 #define STD_ENCODER_STEPS_PER_MENU_ITEM 1 #elif ANY(REPRAP_DISCOUNT_SMART_CONTROLLER, miniVIKI, VIKI2, ELB_FULL_GRAPHIC_CONTROLLER, AZSMZ_12864, OLED_PANEL_TINYBOY2, BQ_LCD_SMART_CONTROLLER, LCD_I2C_PANELOLU2) #define STD_ENCODER_PULSES_PER_STEP 4 #define STD_ENCODER_STEPS_PER_MENU_ITEM 1 #endif #ifndef STD_ENCODER_PULSES_PER_STEP #if ENABLED(TOUCH_BUTTONS) #define STD_ENCODER_PULSES_PER_STEP 2 #else #define STD_ENCODER_PULSES_PER_STEP 5 #endif #endif #ifndef STD_ENCODER_STEPS_PER_MENU_ITEM #define STD_ENCODER_STEPS_PER_MENU_ITEM 1 #endif #ifndef ENCODER_PULSES_PER_STEP #define ENCODER_PULSES_PER_STEP STD_ENCODER_PULSES_PER_STEP #endif #ifndef ENCODER_STEPS_PER_MENU_ITEM #define ENCODER_STEPS_PER_MENU_ITEM STD_ENCODER_STEPS_PER_MENU_ITEM #endif #ifndef ENCODER_FEEDRATE_DEADZONE #define ENCODER_FEEDRATE_DEADZONE 6 #endif // Shift register panels // --------------------- // 2 wire Non-latching LCD SR from: // https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/schematics#!shiftregister-connection #if ENABLED(FF_INTERFACEBOARD) #define SR_LCD_3W_NL // Non latching 3 wire shift register #define IS_ULTIPANEL #elif ENABLED(SAV_3DLCD) #define SR_LCD_2W_NL // Non latching 2 wire shift register #define IS_ULTIPANEL #endif #if ENABLED(IS_ULTIPANEL) #define ULTIPANEL #endif #if ENABLED(ULTIPANEL) #define IS_ULTRA_LCD #ifndef NEWPANEL #define NEWPANEL #endif #endif #if ENABLED(IS_ULTRA_LCD) #define ULTRA_LCD #endif #if ENABLED(IS_RRW_KEYPAD) #define REPRAPWORLD_KEYPAD #endif // Keypad needs a move step #if ENABLED(REPRAPWORLD_KEYPAD) #define NEWPANEL #ifndef REPRAPWORLD_KEYPAD_MOVE_STEP #define REPRAPWORLD_KEYPAD_MOVE_STEP 1.0 #endif #endif // Extensible UI serial touch screens. (See src/lcd/extensible_ui) #if ANY(MALYAN_LCD, DGUS_LCD, TOUCH_UI_FTDI_EVE) #define IS_EXTUI #define EXTENSIBLE_UI #endif // Aliases for LCD features #define HAS_SPI_LCD ENABLED(ULTRA_LCD) #define HAS_DISPLAY (HAS_SPI_LCD || ENABLED(EXTENSIBLE_UI)) #define HAS_GRAPHICAL_LCD ENABLED(DOGLCD) #define HAS_CHARACTER_LCD (HAS_SPI_LCD && !HAS_GRAPHICAL_LCD) #define HAS_LCD_MENU (ENABLED(ULTIPANEL) && DISABLED(NO_LCD_MENUS)) #define HAS_ADC_BUTTONS ENABLED(ADC_KEYPAD) #define HAS_DGUS_LCD ANY(DGUS_LCD_UI_ORIGIN, DGUS_LCD_UI_FYSETC, DGUS_LCD_UI_HIPRECY) /** * Extruders have some combination of stepper motors and hotends * so we separate these concepts into the defines: * * EXTRUDERS - Number of Selectable Tools * HOTENDS - Number of hotends, whether connected or separate * E_STEPPERS - Number of actual E stepper motors * E_MANUAL - Number of E steppers for LCD move options * */ #if EXTRUDERS == 0 #undef DISTINCT_E_FACTORS #undef SINGLENOZZLE #undef SWITCHING_EXTRUDER #undef SWITCHING_NOZZLE #undef MIXING_EXTRUDER #undef MK2_MULTIPLEXER #undef PRUSA_MMU2 #endif #if ENABLED(SWITCHING_EXTRUDER) // One stepper for every two EXTRUDERS #if EXTRUDERS > 4 #define E_STEPPERS 3 #elif EXTRUDERS > 2 #define E_STEPPERS 2 #else #define E_STEPPERS 1 #endif #if DISABLED(SWITCHING_NOZZLE) #define HOTENDS E_STEPPERS #endif #elif ENABLED(MIXING_EXTRUDER) #define E_STEPPERS MIXING_STEPPERS #define E_MANUAL 1 #define DUAL_MIXING_EXTRUDER (MIXING_STEPPERS == 2) #elif ENABLED(SWITCHING_TOOLHEAD) #define E_STEPPERS EXTRUDERS #define E_MANUAL EXTRUDERS #elif ENABLED(PRUSA_MMU2) #define E_STEPPERS 1 #endif // No inactive extruders with MK2_MULTIPLEXER or SWITCHING_NOZZLE #if EITHER(MK2_MULTIPLEXER, SWITCHING_NOZZLE) #undef DISABLE_INACTIVE_EXTRUDER #endif // Prusa MK2 Multiplexer and MMU 2.0 force SINGLENOZZLE #if EITHER(MK2_MULTIPLEXER, PRUSA_MMU2) #define SINGLENOZZLE #endif #if EITHER(SINGLENOZZLE, MIXING_EXTRUDER) // One hotend, one thermistor, no XY offset #undef HOTENDS #define HOTENDS 1 #undef HOTEND_OFFSET_X #undef HOTEND_OFFSET_Y #endif #ifndef HOTENDS #define HOTENDS EXTRUDERS #endif #ifndef E_STEPPERS #define E_STEPPERS EXTRUDERS #endif #ifndef E_MANUAL #define E_MANUAL EXTRUDERS #endif #define HOTEND_LOOP() for (int8_t e = 0; e < HOTENDS; e++) #define DO_SWITCH_EXTRUDER (ENABLED(SWITCHING_EXTRUDER) && (DISABLED(SWITCHING_NOZZLE) || SWITCHING_EXTRUDER_SERVO_NR != SWITCHING_NOZZLE_SERVO_NR)) #define SWITCHING_NOZZLE_TWO_SERVOS defined(SWITCHING_NOZZLE_E1_SERVO_NR) #define HAS_HOTEND_OFFSET (HOTENDS > 1) #define HAS_DUPLICATION_MODE EITHER(DUAL_X_CARRIAGE, MULTI_NOZZLE_DUPLICATION) /** * DISTINCT_E_FACTORS affects how some E factors are accessed */ #if ENABLED(DISTINCT_E_FACTORS) && E_STEPPERS > 1 #define XYZE_N (XYZ + E_STEPPERS) #define E_AXIS_N(E) AxisEnum(E_AXIS + E) #define UNUSED_E(E) NOOP #else #undef DISTINCT_E_FACTORS #define XYZE_N XYZE #define E_AXIS_N(E) E_AXIS #define UNUSED_E(E) UNUSED(E) #endif /** * The BLTouch Probe emulates a servo probe * and uses "special" angles for its state. */ #if ENABLED(BLTOUCH) #ifndef Z_PROBE_SERVO_NR #define Z_PROBE_SERVO_NR 0 #endif #ifndef NUM_SERVOS #define NUM_SERVOS (Z_PROBE_SERVO_NR + 1) #endif #undef DEACTIVATE_SERVOS_AFTER_MOVE #if NUM_SERVOS == 1 #undef SERVO_DELAY #define SERVO_DELAY { 50 } #endif // Always disable probe pin inverting for BLTouch #undef Z_MIN_PROBE_ENDSTOP_INVERTING #define Z_MIN_PROBE_ENDSTOP_INVERTING false #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) #undef Z_MIN_ENDSTOP_INVERTING #define Z_MIN_ENDSTOP_INVERTING false #endif #endif #ifndef PREHEAT_1_LABEL #define PREHEAT_1_LABEL "PLA" #endif #ifndef PREHEAT_2_LABEL #define PREHEAT_2_LABEL "ABS" #endif /** * Set a flag for a servo probe */ #define HAS_Z_SERVO_PROBE (defined(Z_PROBE_SERVO_NR) && Z_PROBE_SERVO_NR >= 0) /** * Set flags for enabled probes */ #define HAS_BED_PROBE (HAS_Z_SERVO_PROBE || ANY(FIX_MOUNTED_PROBE, NOZZLE_AS_PROBE, TOUCH_MI_PROBE, Z_PROBE_ALLEN_KEY, Z_PROBE_SLED, SOLENOID_PROBE, SENSORLESS_PROBING, RACK_AND_PINION_PROBE)) #define PROBE_SELECTED (HAS_BED_PROBE || EITHER(PROBE_MANUALLY, MESH_BED_LEVELING)) #if HAS_BED_PROBE #define HAS_PROBE_XY_OFFSET DISABLED(NOZZLE_AS_PROBE) #define HAS_CUSTOM_PROBE_PIN DISABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) #define HOMING_Z_WITH_PROBE (Z_HOME_DIR < 0 && !HAS_CUSTOM_PROBE_PIN) #ifndef Z_PROBE_LOW_POINT #define Z_PROBE_LOW_POINT -5 #endif #if ENABLED(Z_PROBE_ALLEN_KEY) #define PROBE_TRIGGERED_WHEN_STOWED_TEST // Extra test for Allen Key Probe #endif #ifdef MULTIPLE_PROBING #if EXTRA_PROBING #define TOTAL_PROBING (MULTIPLE_PROBING + EXTRA_PROBING) #else #define TOTAL_PROBING MULTIPLE_PROBING #endif #endif #else // Clear probe pin settings when no probe is selected #undef Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN #endif #ifdef GRID_MAX_POINTS_X #define GRID_MAX_POINTS ((GRID_MAX_POINTS_X) * (GRID_MAX_POINTS_Y)) #endif #define HAS_EXTRA_ENDSTOPS ANY(X_DUAL_ENDSTOPS, Y_DUAL_ENDSTOPS, Z_MULTI_ENDSTOPS) #define HAS_SOFTWARE_ENDSTOPS EITHER(MIN_SOFTWARE_ENDSTOPS, MAX_SOFTWARE_ENDSTOPS) #define HAS_RESUME_CONTINUE ANY(EXTENSIBLE_UI, NEWPANEL, EMERGENCY_PARSER) #define HAS_COLOR_LEDS ANY(BLINKM, RGB_LED, RGBW_LED, PCA9632, PCA9533, NEOPIXEL_LED) #define HAS_LEDS_OFF_FLAG (BOTH(PRINTER_EVENT_LEDS, SDSUPPORT) && HAS_RESUME_CONTINUE) #define HAS_PRINT_PROGRESS EITHER(SDSUPPORT, LCD_SET_PROGRESS_MANUALLY) #define HAS_PRINT_PROGRESS_PERMYRIAD (HAS_PRINT_PROGRESS && EITHER(PRINT_PROGRESS_SHOW_DECIMALS, SHOW_REMAINING_TIME)) #define HAS_SERVICE_INTERVALS (ENABLED(PRINTCOUNTER) && (SERVICE_INTERVAL_1 > 0 || SERVICE_INTERVAL_2 > 0 || SERVICE_INTERVAL_3 > 0)) #define HAS_FILAMENT_SENSOR ENABLED(FILAMENT_RUNOUT_SENSOR) #define HAS_GAMES ANY(MARLIN_BRICKOUT, MARLIN_INVADERS, MARLIN_SNAKE, MARLIN_MAZE) #define HAS_GAME_MENU (1 < ENABLED(MARLIN_BRICKOUT) + ENABLED(MARLIN_INVADERS) + ENABLED(MARLIN_SNAKE) + ENABLED(MARLIN_MAZE)) #define IS_SCARA ENABLED(MORGAN_SCARA) #define IS_KINEMATIC (ENABLED(DELTA) || IS_SCARA) #define IS_CARTESIAN !IS_KINEMATIC #ifndef INVERT_X_DIR #define INVERT_X_DIR false #endif #ifndef INVERT_Y_DIR #define INVERT_Y_DIR false #endif #ifndef INVERT_Z_DIR #define INVERT_Z_DIR false #endif #ifndef INVERT_E_DIR #define INVERT_E_DIR false #endif #if ENABLED(SLIM_LCD_MENUS) #define BOOT_MARLIN_LOGO_SMALL #endif #define IS_RE_ARM_BOARD MB(RAMPS_14_RE_ARM_EFB, RAMPS_14_RE_ARM_EEB, RAMPS_14_RE_ARM_EFF, RAMPS_14_RE_ARM_EEF, RAMPS_14_RE_ARM_SF) #define HAS_SDCARD_CONNECTION EITHER(TARGET_LPC1768, ADAFRUIT_GRAND_CENTRAL_M4) #define HAS_LINEAR_E_JERK (DISABLED(CLASSIC_JERK) && ENABLED(LIN_ADVANCE)) #ifndef SPI_SPEED #define SPI_SPEED SPI_FULL_SPEED #endif
DDilshani/CO326-project
firmware/grbl-Mega/src/protocol.h
<gh_stars>1-10 /* protocol.h - controls Grbl execution protocol and procedures Part of Grbl Copyright (c) 2011-2016 <NAME> for Gnea Research LLC Copyright (c) 2009-2011 <NAME> Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ #ifndef protocol_h #define protocol_h // Line buffer size from the serial input stream to be executed. #ifndef LINE_BUFFER_SIZE #define LINE_BUFFER_SIZE 256 #endif // Starts Grbl main loop. It handles all incoming characters from the serial port and executes // them as they complete. It is also responsible for finishing the initialization procedures. void protocol_main_loop(); // Checks and executes a realtime command at various stop points in main program void protocol_execute_realtime(); void protocol_exec_rt_system(); // Executes the auto cycle feature, if enabled. void protocol_auto_cycle_start(); // Block until all buffered steps are executed void protocol_buffer_synchronize(); #endif
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/HAL/HAL_STM32/pinsDebug_STM32GENERIC.h
<reponame>DDilshani/CO326-project /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once /** * Support routines for STM32GENERIC (Maple) */ /** * Translation of routines & variables used by pinsDebug.h */ #ifdef BOARD_NR_GPIO_PINS // Only in STM32GENERIC (Maple) #ifdef __STM32F1__ #include "../HAL_STM32F1/fastio.h" #elif defined(STM32F4) || defined(STM32F7) #include "../HAL_STM32_F4_F7/fastio.h" #else #include "fastio.h" #endif extern const stm32_pin_info PIN_MAP[BOARD_NR_GPIO_PINS]; #define NUM_DIGITAL_PINS BOARD_NR_GPIO_PINS #define NUMBER_PINS_TOTAL BOARD_NR_GPIO_PINS #define VALID_PIN(pin) (pin >= 0 && pin < BOARD_NR_GPIO_PINS) #define GET_ARRAY_PIN(p) pin_t(pin_array[p].pin) #define pwm_status(pin) PWM_PIN(pin) #define digitalRead_mod(p) extDigitalRead(p) #define PRINT_PIN(p) do{ sprintf_P(buffer, PSTR("%3hd "), int16_t(p)); SERIAL_ECHO(buffer); }while(0) #define PRINT_PORT(p) print_port(p) #define PRINT_ARRAY_NAME(x) do{ sprintf_P(buffer, PSTR("%-" STRINGIFY(MAX_NAME_LENGTH) "s"), pin_array[x].name); SERIAL_ECHO(buffer); }while(0) #define MULTI_NAME_PAD 21 // space needed to be pretty if not first name assigned to a pin // pins that will cause hang/reset/disconnect in M43 Toggle and Watch utilities #ifndef M43_NEVER_TOUCH #define M43_NEVER_TOUCH(Q) (Q >= 9 && Q <= 12) // SERIAL/USB pins PA9(TX) PA10(RX) #endif static inline int8_t get_pin_mode(pin_t pin) { return VALID_PIN(pin) ? _GET_MODE(pin) : -1; } static inline pin_t DIGITAL_PIN_TO_ANALOG_PIN(pin_t pin) { if (!VALID_PIN(pin)) return -1; int8_t adc_channel = int8_t(PIN_MAP[pin].adc_channel); #ifdef NUM_ANALOG_INPUTS if (adc_channel >= NUM_ANALOG_INPUTS) adc_channel = ADCx; #endif return pin_t(adc_channel); } static inline bool IS_ANALOG(pin_t pin) { if (!VALID_PIN(pin)) return false; if (PIN_MAP[pin].adc_channel != ADCx) { #ifdef NUM_ANALOG_INPUTS if (PIN_MAP[pin].adc_channel >= NUM_ANALOG_INPUTS) return false; #endif return _GET_MODE(pin) == GPIO_INPUT_ANALOG && !M43_NEVER_TOUCH(pin); } return false; } static inline bool GET_PINMODE(const pin_t pin) { return VALID_PIN(pin) && !IS_INPUT(pin); } static inline bool GET_ARRAY_IS_DIGITAL(const int16_t array_pin) { const pin_t pin = GET_ARRAY_PIN(array_pin); return (!IS_ANALOG(pin) #ifdef NUM_ANALOG_INPUTS || PIN_MAP[pin].adc_channel >= NUM_ANALOG_INPUTS #endif ); } #include "../../inc/MarlinConfig.h" // Allow pins/pins.h to set density static inline void pwm_details(const pin_t pin) { if (PWM_PIN(pin)) { timer_dev * const tdev = PIN_MAP[pin].timer_device; const uint8_t channel = PIN_MAP[pin].timer_channel; const char num = ( #if defined(STM32_HIGH_DENSITY) || defined(STM32_XL_DENSITY) tdev == &timer8 ? '8' : tdev == &timer5 ? '5' : #endif tdev == &timer4 ? '4' : tdev == &timer3 ? '3' : tdev == &timer2 ? '2' : tdev == &timer1 ? '1' : '?' ); char buffer[10]; sprintf_P(buffer, PSTR(" TIM%c CH%c"), num, ('0' + channel)); SERIAL_ECHO(buffer); } } static inline void print_port(pin_t pin) { const char port = 'A' + char(pin >> 4); // pin div 16 const int16_t gbit = PIN_MAP[pin].gpio_bit; char buffer[8]; sprintf_P(buffer, PSTR("P%c%hd "), port, gbit); if (gbit < 10) SERIAL_CHAR(' '); SERIAL_ECHO(buffer); } #endif // BOARD_NR_GPIO_PINS
DDilshani/CO326-project
firmware/Marlin-2.0.x/Marlin/src/pins/stm32/pins_BTT_GTR_V1_0.h
<reponame>DDilshani/CO326-project<filename>firmware/Marlin-2.0.x/Marlin/src/pins/stm32/pins_BTT_GTR_V1_0.h<gh_stars>1-10 /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 <NAME> / <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once #ifndef TARGET_STM32F4 #error "Oops! Select an STM32F4 board in 'Tools > Board.'" #elif HOTENDS > 8 || E_STEPPERS > 8 #error "BIGTREE GTR V1.0 supports up to 8 hotends / E-steppers." #elif HOTENDS > MAX_EXTRUDERS || E_STEPPERS > MAX_EXTRUDERS #error "Marlin extruder/hotends limit! Increase MAX_EXTRUDERS to continue." #endif #define BOARD_INFO_NAME "BIGTREE GTR 1.0" // Use one of these or SDCard-based Emulation will be used //#define I2C_EEPROM //#define SRAM_EEPROM_EMULATION // Use BackSRAM-based EEPROM emulation //#define FLASH_EEPROM_EMULATION // Use Flash-based EEPROM emulation #define TP // Enable to define servo and probe pins // // Servos // #if ENABLED(TP) #define SERVO0_PIN PB11 #endif #define PS_ON_PIN PH6 // // Limit Switches // #define X_MIN_PIN PF2 #define X_MAX_PIN PG14 #define Y_MIN_PIN PC13 #define Y_MAX_PIN PG9 #define Z_MIN_PIN PE0 #define Z_MAX_PIN PD3 // // Pins on the extender // //#define X_MIN_PIN PI4 //#define X2_MIN_PIN PF12 //#define Y_MIN_PIN PF4 //#define Y2_MIN_PIN PI7 //#define Z_MIN_PIN PF6 #if ENABLED(TP) && !defined(Z_MIN_PROBE_PIN) #define Z_MIN_PROBE_PIN PH11 // Z Probe must be PH11 #endif // // Steppers // #define X_STEP_PIN PC15 #define X_DIR_PIN PF0 #define X_ENABLE_PIN PF1 #ifndef X_CS_PIN #define X_CS_PIN PC14 #endif #define Y_STEP_PIN PE3 #define Y_DIR_PIN PE2 #define Y_ENABLE_PIN PE4 #ifndef Y_CS_PIN #define Y_CS_PIN PE1 #endif #define Z_STEP_PIN PB8 #define Z_DIR_PIN PB7 // PB7 #define Z_ENABLE_PIN PB9 #ifndef Z_CS_PIN #define Z_CS_PIN PB5 #endif #define E0_STEP_PIN PG12 #define E0_DIR_PIN PG11 #define E0_ENABLE_PIN PG13 #ifndef E0_CS_PIN #define E0_CS_PIN PG10 #endif #define E1_STEP_PIN PD6 #define E1_DIR_PIN PD5 #define E1_ENABLE_PIN PD7 #ifndef E1_CS_PIN #define E1_CS_PIN PD4 #endif #define E2_STEP_PIN PD1 #define E2_DIR_PIN PD0 #define E2_ENABLE_PIN PD2 #ifndef E2_CS_PIN #define E2_CS_PIN PC12 #endif #define E3_STEP_PIN PF3 #define E3_DIR_PIN PG3 #define E3_ENABLE_PIN PF8 #ifndef E3_CS_PIN #define E3_CS_PIN PG4 #endif #define E4_STEP_PIN PD14 #define E4_DIR_PIN PD11 #define E4_ENABLE_PIN PG2 #ifndef E4_CS_PIN #define E4_CS_PIN PE15 #endif #define E5_STEP_PIN PE12 #define E5_DIR_PIN PE10 #define E5_ENABLE_PIN PF14 #ifndef E5_CS_PIN #define E5_CS_PIN PE7 #endif #define E6_STEP_PIN PG0 #define E6_DIR_PIN PG1 #define E6_ENABLE_PIN PE8 #ifndef E6_CS_PIN #define E6_CS_PIN PF15 #endif #define E7_STEP_PIN PH12 #define E7_DIR_PIN PH15 #define E7_ENABLE_PIN PI0 #ifndef E7_CS_PIN #define E7_CS_PIN PH14 #endif // // Software SPI pins for TMC2130 stepper drivers // #if ENABLED(TMC_USE_SW_SPI) #ifndef TMC_SW_MOSI #define TMC_SW_MOSI PG15 #endif #ifndef TMC_SW_MISO #define TMC_SW_MISO PB6 #endif #ifndef TMC_SW_SCK #define TMC_SW_SCK PB3 #endif #endif #if HAS_TMC220x /** * TMC2208/TMC2209 stepper drivers * * Hardware serial communication ports. * If undefined software serial is used according to the pins below */ //#define X_HARDWARE_SERIAL Serial //#define X2_HARDWARE_SERIAL Serial1 //#define Y_HARDWARE_SERIAL Serial1 //#define Y2_HARDWARE_SERIAL Serial1 //#define Z_HARDWARE_SERIAL Serial1 //#define Z2_HARDWARE_SERIAL Serial1 //#define E0_HARDWARE_SERIAL Serial1 //#define E1_HARDWARE_SERIAL Serial1 //#define E2_HARDWARE_SERIAL Serial1 //#define E3_HARDWARE_SERIAL Serial1 //#define E4_HARDWARE_SERIAL Serial1 //#define E5_HARDWARE_SERIAL Serial1 //#define E6_HARDWARE_SERIAL Serial1 //#define E7_HARDWARE_SERIAL Serial1 // // Software serial // #define X_SERIAL_TX_PIN PC14 #define X_SERIAL_RX_PIN PC14 #define Y_SERIAL_TX_PIN PE1 #define Y_SERIAL_RX_PIN PE1 #define Z_SERIAL_TX_PIN PB5 #define Z_SERIAL_RX_PIN PB5 #define E0_SERIAL_TX_PIN PG10 #define E0_SERIAL_RX_PIN PG10 #define E1_SERIAL_TX_PIN PD4 #define E1_SERIAL_RX_PIN PD4 #define E2_SERIAL_TX_PIN PC12 #define E2_SERIAL_RX_PIN PC12 #define E3_SERIAL_TX_PIN PG4 #define E3_SERIAL_RX_PIN PG4 #define E4_SERIAL_TX_PIN PE15 #define E4_SERIAL_RX_PIN PE15 #define E5_SERIAL_TX_PIN PE7 #define E5_SERIAL_RX_PIN PE7 #define E6_SERIAL_TX_PIN PF15 #define E6_SERIAL_RX_PIN PF15 #define E7_SERIAL_TX_PIN PH14 #define E7_SERIAL_RX_PIN PH14 // Reduce baud rate to improve software serial reliability #define TMC_BAUD_RATE 19200 #endif // // Temperature Sensors // #define TEMP_0_PIN PC1 // T1 <-> E0 #define TEMP_1_PIN PC2 // T2 <-> E1 #define TEMP_2_PIN PC3 // T3 <-> E2 #define TEMP_3_PIN PA3 // T4 <-> E3 #define TEMP_4_PIN PF9 // T5 <-> E4 #define TEMP_5_PIN PF10 // T6 <-> E5 //#define TEMP_6_PIN PF7 // T7 <-> E6 //#define TEMP_7_PIN PF5 // T8 <-> E7 #define TEMP_BED_PIN PC0 // T0 <-> Bed // SPI for Max6675 or Max31855 Thermocouple // Uses a separate SPI bus // If you have a two-way thermocouple, you can customize two THERMO_CSx_PIN pins (x:1~2) #define THERMO_SCK_PIN PI1 // SCK #define THERMO_DO_PIN PI2 // MISO #define THERMO_CS1_PIN PH9 // CS1 #define THERMO_CS2_PIN PH2 // CS2 #define MAX6675_SS_PIN THERMO_CS1_PIN #define MAX6675_SS2_PIN THERMO_CS2_PIN #define MAX6675_SCK_PIN THERMO_SCK_PIN #define MAX6675_DO_PIN THERMO_DO_PIN // // Heaters / Fans // #define HEATER_0_PIN PB1 // Heater0 #define HEATER_1_PIN PA1 // Heater1 #define HEATER_2_PIN PB0 // Heater2 #define HEATER_3_PIN PD15 // Heater3 #define HEATER_4_PIN PD13 // Heater4 #define HEATER_5_PIN PD12 // Heater5 //#define HEATER_6_PIN PE13 // Heater6 //#define HEATER_7_PIN PI6 // Heater7 #define HEATER_BED_PIN PA2 // Hotbed #define FAN_PIN PE5 // Fan0 #define FAN1_PIN PE6 // Fan1 #define FAN2_PIN PC8 // Fan2 #define FAN3_PIN PI5 // Fan3 #define FAN4_PIN PE9 // Fan4 #define FAN5_PIN PE11 // Fan5 //#define FAN6_PIN PC9 // Fan6 //#define FAN7_PIN PE14 // Fan7 // // By default the onboard SD (SPI1) is enabled // #define CUSTOM_SPI_PINS #if DISABLED(CUSTOM_SPI_PINS) #define SDSS PB12 #endif // HAL SPI1 pins group #if ENABLED(CUSTOM_SPI_PINS) #define SDSS PA4 #define SD_DETECT_PIN PC4 #define LCD_SDSS PA4 #define SCK_PIN PA5 #define MISO_PIN PA6 #define MOSI_PIN PA7 #define SS_PIN PA4 // Chip select for SD card used by Marlin #endif /** * _____ _____ * NC | · · | GND 5V | · · | GND * RESET | · · | PB10(SD_DETECT) (LCD_D7) PG5 | · · | PG6 (LCD_D6) * (MOSI)PB15 | · · | PH10(BTN_EN2) (LCD_D5) PG7 | · · | PG8 (LCD_D4) * (SD_SS)PB12 | · · | PD10(BTN_EN1) (LCD_RS) PA8 | · · | PC10 (LCD_EN) * (SCK)PB13 | · · | PB14(MISO) (BTN_ENC) PA15 | · · | PC11 (BEEPER) *  ̄ ̄  ̄ ̄ * EXP2 EXP1 */ // // LCDs and Controllers // #if HAS_SPI_LCD #define BEEPER_PIN PC11 #define BTN_ENC PA15 #if ENABLED(CR10_STOCKDISPLAY) #define LCD_PINS_RS PA8 #define BTN_EN1 PD10 #define BTN_EN2 PH10 #define LCD_PINS_ENABLE PG7 #define LCD_PINS_D4 PG8 //#undef ST7920_DELAY_1 //#undef ST7920_DELAY_2 //#undef ST7920_DELAY_3 #else #define LCD_PINS_RS PA8 #define BTN_EN1 PD10 #define BTN_EN2 PH10 #if DISABLED(CUSTOM_SPI_PINS) #define SD_DETECT_PIN PB10 #define LCD_SDSS PB12 #endif #define LCD_PINS_ENABLE PC10 #define LCD_PINS_D4 PG8 #if ENABLED(FYSETC_MINI_12864) #define DOGLCD_CS PC10 #define DOGLCD_A0 PA8 //#define LCD_BACKLIGHT_PIN -1 #define LCD_RESET_PIN PG8 // Must be high or open for LCD to operate normally. #if EITHER(FYSETC_MINI_12864_1_2, FYSETC_MINI_12864_2_0) #ifndef RGB_LED_R_PIN #define RGB_LED_R_PIN PG7 #endif #ifndef RGB_LED_G_PIN #define RGB_LED_G_PIN PG6 #endif #ifndef RGB_LED_B_PIN #define RGB_LED_B_PIN PG5 #endif #elif ENABLED(FYSETC_MINI_12864_2_1) #define NEOPIXEL_PIN PF13 #endif #endif // !FYSETC_MINI_12864 #if ENABLED(ULTIPANEL) #define LCD_PINS_D5 PG7 #define LCD_PINS_D6 PG6 #define LCD_PINS_D7 PG5 #endif #endif // Alter timing for graphical display #if HAS_GRAPHICAL_LCD #define BOARD_ST7920_DELAY_1 DELAY_NS(96) #define BOARD_ST7920_DELAY_2 DELAY_NS(48) #define BOARD_ST7920_DELAY_3 DELAY_NS(600) #endif //#define DOGLCD_CS PB12 //#define DOGLCD_A0 PA8 //#define LCD_PINS_DC PB14 //#define DOGLCD_MOSI PB15 #endif // HAS_SPI_LCD
Muffo/busFace
src/c/busFace.c
#include <pebble.h> static Window *s_main_window; static TextLayer *s_time_layer; static TextLayer *s_bus_layer[3]; static GFont s_time_font; static GFont s_bus_font; static char s_time_buffer[8]; static char s_bus_buffer[16]; static void main_window_load(Window *window) { // Get information about the Window Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); // ==================== Time ==================== s_time_layer = text_layer_create( GRect(0, 5, bounds.size.w, 50)); s_time_font = fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_BRACIOLA_B_48)); text_layer_set_background_color(s_time_layer, GColorClear); text_layer_set_text_color(s_time_layer, GColorGreen); text_layer_set_font(s_time_layer, s_time_font); text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter); // Add it as a child layer to the Window's root layer layer_add_child(window_layer, text_layer_get_layer(s_time_layer)); // ==================== Bus ==================== s_bus_layer[0] = text_layer_create( GRect(0, 75, bounds.size.w, 25)); s_bus_layer[1] = text_layer_create( GRect(0, 100, bounds.size.w, 25)); s_bus_layer[2] = text_layer_create( GRect(0, 125, bounds.size.w, 25)); int i; s_bus_font = fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_BRACIOLA_R_24)); for (i = 0; i < 3; ++i) { text_layer_set_background_color(s_bus_layer[i], GColorClear); text_layer_set_text_color(s_bus_layer[i], GColorWhite); text_layer_set_font(s_bus_layer[i], s_bus_font); text_layer_set_text_alignment(s_bus_layer[i], GTextAlignmentLeft); // Add it as a child layer to the Window's root layer layer_add_child(window_layer, text_layer_get_layer(s_bus_layer[i])); } text_layer_set_text(s_bus_layer[0], "Next bus in"); text_layer_set_text(s_bus_layer[2], "(scheduled)"); text_layer_set_text_color(s_bus_layer[2], GColorRed); layer_set_hidden(text_layer_get_layer(s_bus_layer[2]), true); } static void main_window_unload(Window *window) { // Destroy TextLayer text_layer_destroy(s_time_layer); fonts_unload_custom_font(s_time_font); int i; for (i = 0; i < 3; ++i) { text_layer_destroy(s_bus_layer[i]); } fonts_unload_custom_font(s_bus_font); } static void update_time() { // Get a tm structure time_t temp = time(NULL); struct tm *tick_time = localtime(&temp); // Write the current hours and minutes into a buffer strftime(s_time_buffer, sizeof(s_time_buffer), clock_is_24h_style() ? "%H:%M" : "%I:%M", tick_time); text_layer_set_text(s_time_layer, s_time_buffer); } static void tick_handler(struct tm *tick_time, TimeUnits units_changed) { // Update the time as soon as we enter in the next minute if (tick_time->tm_sec == 0) { update_time(); } // Get bus update every 20 seconds if (tick_time->tm_sec % 20 == 0) { DictionaryIterator *iter; app_message_outbox_begin(&iter); dict_write_uint8(iter, 0, 0); app_message_outbox_send(); } } static void inbox_received_callback(DictionaryIterator *iterator, void *context) { APP_LOG(APP_LOG_LEVEL_DEBUG, "[%s] Received stuff", __func__); // Read tuples for data Tuple *due_in_tuple = dict_find(iterator, MESSAGE_KEY_DUEIN); Tuple *scheduled_tuple = dict_find(iterator, MESSAGE_KEY_SCHEDULED); if (due_in_tuple && scheduled_tuple ) { snprintf(s_bus_buffer, sizeof(s_bus_buffer), "%s", due_in_tuple->value->cstring); text_layer_set_text(s_bus_layer[1], s_bus_buffer); APP_LOG(APP_LOG_LEVEL_DEBUG, "[%s] Updating time: %s", __func__, s_bus_buffer); layer_set_hidden(text_layer_get_layer(s_bus_layer[2]), !scheduled_tuple->value->int8); } } static void inbox_dropped_callback(AppMessageResult reason, void *context) { APP_LOG(APP_LOG_LEVEL_ERROR, "Message dropped!"); } static void outbox_failed_callback(DictionaryIterator *iterator, AppMessageResult reason, void *context) { APP_LOG(APP_LOG_LEVEL_ERROR, "Outbox send failed!"); } static void outbox_sent_callback(DictionaryIterator *iterator, void *context) { APP_LOG(APP_LOG_LEVEL_INFO, "Outbox send success!"); } static void init() { // Create main Window element and assign to pointer s_main_window = window_create(); // Set handlers to manage the elements inside the Window window_set_window_handlers(s_main_window, (WindowHandlers) { .load = main_window_load, .unload = main_window_unload }); window_set_background_color(s_main_window, GColorBlack); // Show the Window on the watch, with animated=true window_stack_push(s_main_window, true); // Make sure the time is displayed from the start update_time(); // Register with TickTimerService tick_timer_service_subscribe(SECOND_UNIT, tick_handler); // Register app message callbacks app_message_register_inbox_received(inbox_received_callback); app_message_register_inbox_dropped(inbox_dropped_callback); app_message_register_outbox_failed(outbox_failed_callback); app_message_register_outbox_sent(outbox_sent_callback); // Open AppMessage const int inbox_size = 128; const int outbox_size = 128; app_message_open(inbox_size, outbox_size); } static void deinit() { // Destroy Window window_destroy(s_main_window); } int main(void) { init(); APP_LOG(APP_LOG_LEVEL_DEBUG, "Done initializing, pushed window: %p", s_main_window); app_event_loop(); deinit(); }
simontime/libnx
nx/include/switch/applets/web.h
/** * @file web.h * @brief Wrapper for using the WifiWebAuthApplet LibraryApplet. * @author p-sam * @copyright libnx Authors */ #pragma once #include "../types.h" #include "../services/applet.h" typedef struct { u8 unk_x0[0x4]; char url[0xFC]; } WebWifiPageArgUrl; typedef struct { WebWifiPageArgUrl url1; WebWifiPageArgUrl url2; u8 unk_x200[0x300]; u8 unk_x500[0x18]; } WebWifiPageArg; typedef struct { WebWifiPageArg arg; } WebWifiConfig; void webWifiCreate(WebWifiConfig* config, const char* url); Result webWifiShow(WebWifiConfig* config);
simontime/libnx
nx/include/switch/applets/libapplet.h
<gh_stars>0 /** * @file libapplet.h * @brief LibraryApplet wrapper. * @author yellows8 * @copyright libnx Authors */ #pragma once #include "../types.h" #include "../services/applet.h" /// CommonArguments typedef struct { u32 CommonArgs_version; u32 CommonArgs_size; u32 LaVersion; ///< LibraryApplet API version s32 ExpectedThemeColor; ///< Set to the output from \ref appletGetThemeColorType by \ref libappletArgsCreate. u8 PlayStartupSound; ///< bool flag, default is false. u8 pad[7]; u64 tick; } LibAppletArgs; /** * @brief Creates a LibAppletArgs struct. * @param a LibAppletArgs struct. * @param version LaVersion for \ref LibAppletArgs. */ void libappletArgsCreate(LibAppletArgs* a, u32 version); /** * @brief Sets the PlayStartupSound field in \ref LibAppletArgs. * @param a LibAppletArgs struct. * @param flag Value for \ref LibAppletArgs PlayStartupSound. */ void libappletArgsSetPlayStartupSound(LibAppletArgs* a, bool flag); /** * @brief Sets the tick field in LibAppletArgs, then creates a storage with it which is pushed to the AppletHolder via \ref appletHolderPushInData. * @param a LibAppletArgs struct. * @param h AppletHolder object. */ Result libappletArgsPush(LibAppletArgs* a, AppletHolder *h); /** * @brief Creates a storage using the input buffer which is pushed to the AppletHolder via \ref appletHolderPushInData. * @param h AppletHolder object. * @param buffer Input data buffer. * @param size Input data size. */ Result libappletPushInData(AppletHolder *h, const void* buffer, size_t size); /// Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this. /// Returns to the main Home Menu, equivalent to pressing the HOME button. Result libappletRequestHomeMenu(void); /// Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this. /// Equivalent to entering "System Update" under System Settings. When leaving this, it returns to the main Home Menu. Result libappletRequestJumpToSystemUpdate(void);
simontime/libnx
nx/source/applets/web.c
<reponame>simontime/libnx #include <string.h> #include <malloc.h> #include "types.h" #include "result.h" #include "services/applet.h" #include "applets/libapplet.h" #include "applets/web.h" static void _webWifiUrlCreate(WebWifiPageArgUrl* argUrl, const char* url) { strncpy(argUrl->url, url, sizeof(argUrl->url)-1); } void webWifiCreate(WebWifiConfig* config, const char* url) { memset(config, 0, sizeof(WebWifiConfig)); _webWifiUrlCreate(&config->arg.url1, url); _webWifiUrlCreate(&config->arg.url2, url); } Result webWifiShow(WebWifiConfig* config) { Result rc = 0; AppletHolder holder; rc = appletCreateLibraryApplet(&holder, AppletId_wifiWebAuth, LibAppletMode_AllForeground); if (R_FAILED(rc)) return rc; LibAppletArgs commonargs; libappletArgsCreate(&commonargs, 0); rc = libappletArgsPush(&commonargs, &holder); if (R_SUCCEEDED(rc)) rc = libappletPushInData(&holder, &config->arg, sizeof(config->arg)); if (R_SUCCEEDED(rc)) rc = appletHolderStart(&holder); if (R_SUCCEEDED(rc)) { appletHolderJoin(&holder); LibAppletExitReason reason = appletHolderGetExitReason(&holder); if (reason == LibAppletExitReason_Canceled || reason == LibAppletExitReason_Abnormal || reason == LibAppletExitReason_Unexpected) { rc = MAKERESULT(Module_Libnx, LibnxError_LibAppletBadExit); } } appletHolderClose(&holder); return rc; }
simontime/libnx
nx/include/switch/services/es.h
/** * @file es.h * @brief ETicket service IPC wrapper. * @author simontime * @copyright libnx Authors */ #pragma once #include "../kernel/ipc.h" #include "../services/sm.h" Result esInitialize(void); void esExit(void); Result esCountCommmonTicket(u32* out); Result esCountPersonalizedTicket(u32* out);
simontime/libnx
nx/source/services/es.c
/** * @file es.c * @brief ETicket service IPC wrapper. * @author simontime * @copyright libnx Authors */ #include "services/es.h" #include "arm/atomics.h" static Service g_esSrv; static u64 g_RefCnt; Result esInitialize(void) { atomicIncrement64(&g_RefCnt); if (serviceIsActive(&g_esSrv)) return 0; return smGetService(&g_esSrv, "es"); } void esExit(void) { if (atomicDecrement64(&g_RefCnt) == 0) serviceClose(&g_esSrv); } Result esCountCommmonTicket(u32* out) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = ipcPrepareHeader(&c, sizeof *raw); raw->magic = SFCI_MAGIC; raw->cmd_id = 9; Result rc = serviceIpcDispatch(&g_esSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u32 out; } *resp = r.Raw; rc = resp->result; *out = resp->out; } return rc; } Result esCountPersonalizedTicket(u32* out) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = ipcPrepareHeader(&c, sizeof *raw); raw->magic = SFCI_MAGIC; raw->cmd_id = 10; Result rc = serviceIpcDispatch(&g_esSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u32 out; } *resp = r.Raw; rc = resp->result; *out = resp->out; } return rc; }
simontime/libnx
nx/source/services/ns.c
#include "types.h" #include "result.h" #include "arm/atomics.h" #include "kernel/ipc.h" #include "kernel/detect.h" #include "services/sm.h" #include "services/ns.h" static Service g_nsAppManSrv, g_nsGetterSrv, g_nsvmSrv, g_nsdevSrv; static u64 g_nsRefCnt, g_nsvmRefCnt, g_nsdevRefCnt; static Result _nsGetInterface(Service* srv_out, u64 cmd_id); Result nsInitialize(void) { Result rc=0; atomicIncrement64(&g_nsRefCnt); if (serviceIsActive(&g_nsGetterSrv) || serviceIsActive(&g_nsAppManSrv)) return 0; if(!kernelAbove300()) return smGetService(&g_nsAppManSrv, "ns:am"); rc = smGetService(&g_nsGetterSrv, "ns:am2");//TODO: Support the other services?(Only useful when ns:am2 isn't accessible) if (R_FAILED(rc)) return rc; rc = _nsGetInterface(&g_nsAppManSrv, 7996); if (R_FAILED(rc)) serviceClose(&g_nsGetterSrv); return rc; } void nsExit(void) { if (atomicDecrement64(&g_nsRefCnt) == 0) { serviceClose(&g_nsAppManSrv); if(!kernelAbove300()) return; serviceClose(&g_nsGetterSrv); } } Result nsdevInitialize(void) { atomicIncrement64(&g_nsdevRefCnt); if (serviceIsActive(&g_nsdevSrv)) return 0; return smGetService(&g_nsdevSrv, "ns:dev"); } void nsdevExit(void) { if (atomicDecrement64(&g_nsdevRefCnt) == 0) serviceClose(&g_nsdevSrv); } static Result _nsGetInterface(Service* srv_out, u64 cmd_id) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = cmd_id; Result rc = serviceIpcDispatch(&g_nsGetterSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; } *resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { serviceCreate(srv_out, r.Handles[0]); } } return rc; } Result nsListApplicationRecord(NsApplicationRecord* buffer, size_t size, size_t entry_offset, size_t* out_entrycount) { IpcCommand c; ipcInitialize(&c); ipcAddRecvBuffer(&c, buffer, size, 0); struct { u64 magic; u64 cmd_id; u32 entry_offset; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 0; raw->entry_offset = entry_offset; Result rc = serviceIpcDispatch(&g_nsAppManSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u32 entry_count; } *resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && out_entrycount) *out_entrycount = resp->entry_count; } return rc; } Result nsListApplicationContentMetaStatus(u64 titleID, u32 index, NsApplicationContentMetaStatus* buffer, size_t size, size_t* out_entrycount) { IpcCommand c; ipcInitialize(&c); ipcAddRecvBuffer(&c, buffer, size, 0); struct { u64 magic; u64 cmd_id; u32 index; u64 titleID; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 601; raw->index = index; raw->titleID = titleID; Result rc = serviceIpcDispatch(&g_nsAppManSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u32 entry_count; } *resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && out_entrycount) *out_entrycount = resp->entry_count; } return rc; } Result nsGetApplicationControlData(u8 flag, u64 titleID, NsApplicationControlData* buffer, size_t size, size_t* actual_size) { IpcCommand c; ipcInitialize(&c); ipcAddRecvBuffer(&c, buffer, size, 0); struct { u64 magic; u64 cmd_id; u8 flag; u64 titleID; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 400; raw->flag = flag; raw->titleID = titleID; Result rc = serviceIpcDispatch(&g_nsAppManSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u64 actual_size; } *resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && actual_size) *actual_size = resp->actual_size; } return rc; } Result nsGetTotalSpaceSize(FsStorageId storage_id, u64 *size) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u64 storage_id; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 47; raw->storage_id = storage_id; Result rc = serviceIpcDispatch(&g_nsAppManSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u64 size; } *resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && size) *size = resp->size; } return rc; } Result nsGetFreeSpaceSize(FsStorageId storage_id, u64 *size) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u64 storage_id; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 48; raw->storage_id = storage_id; Result rc = serviceIpcDispatch(&g_nsAppManSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u64 size; } *resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && size) *size = resp->size; } return rc; } Result nsvmInitialize(void) { if (!kernelAbove300()) return 0; atomicIncrement64(&g_nsvmRefCnt); if (serviceIsActive(&g_nsvmSrv)) return 0; return smGetService(&g_nsvmSrv, "ns:vm"); } void nsvmExit(void) { if (!kernelAbove300()) return; if (atomicDecrement64(&g_nsvmRefCnt) == 0) { serviceClose(&g_nsvmSrv); } } Result nsvmNeedsUpdateVulnerability(bool *out) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 1200; Result rc; if (kernelAbove300()) rc = serviceIpcDispatch(&g_nsvmSrv); else rc = serviceIpcDispatch(&g_nsAppManSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u8 out; } *resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && out) *out = resp->out; } return rc; } Result nsvmGetSafeSystemVersion(u16 *out) { if (!kernelAbove300()) return MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer); IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 1202; Result rc = serviceIpcDispatch(&g_nsvmSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u16 out; } *resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && out) *out = resp->out; } return rc; } Result nsdevLaunchProgram(u64* out_pid, const NsLaunchProperties* properties, u32 flags) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u32 flags; u32 pad; NsLaunchProperties properties; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 0; raw->flags = flags; raw->pad = 0; raw->properties = *properties; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u64 pid; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { if (out_pid) *out_pid = resp->pid; } } return rc; } Result nsdevTerminateProcess(u64 pid) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u64 pid; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 1; raw->pid = pid; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; } Result nsdevTerminateProgram(u64 tid) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u64 tid; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 2; raw->tid = tid; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; } Result nsdevGetShellEvent(Event* out) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 4; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { eventLoadRemote(out, r.Handles[0], true); } } return rc; } Result nsdevGetShellEventInfo(NsShellEventInfo* out) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 5; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u32 event; u32 pad; u64 process_id; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { if (out) { out->event = (NsShellEvent)resp->event; out->process_id = resp->process_id; } } } return rc; } Result nsdevTerminateApplication(void) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 6; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; } Result nsdevPrepareLaunchProgramFromHost(NsLaunchProperties* out, const char* path, size_t path_len) { IpcCommand c; ipcInitialize(&c); ipcAddSendBuffer(&c, path, path_len, BufferType_Normal); struct { u64 magic; u64 cmd_id; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 7; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; NsLaunchProperties properties; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { if (out) *out = resp->properties; } } return rc; } Result nsdevLaunchApplication(u64* out_pid, u64 app_title_id, u32 flags) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u32 flags; u32 pad; u64 app_title_id; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 8; raw->flags = flags; raw->pad = 0; raw->app_title_id = app_title_id; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u64 pid; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { if (out_pid) *out_pid = resp->pid; } } return rc; } Result nsdevLaunchApplicationWithStorageId(u64* out_pid, u64 app_title_id, u32 flags, u8 app_storage_id, u8 patch_storage_id) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u8 app_storage_id; u8 patch_storage_id; u16 pad; u32 flags; u64 app_title_id; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 9; raw->app_storage_id = app_storage_id; raw->patch_storage_id = patch_storage_id; raw->pad = 0; raw->flags = flags; raw->app_title_id = app_title_id; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u64 pid; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { if (out_pid) *out_pid = resp->pid; } } return rc; } Result nsdevIsSystemMemoryResourceLimitBoosted(bool* out) { if (!kernelAbove600()) return MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer); IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 10; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u8 boosted; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { if (out) *out = resp->boosted != 0; } } return rc; } Result nsdevGetRunningApplicationProcessId(u64* out_pid) { if (!kernelAbove600()) return MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer); IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 11; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u64 pid; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { if (out_pid) *out_pid = resp->pid; } } return rc; } Result nsdevSetCurrentApplicationRightsEnvironmentCanBeActive(bool can_be_active) { if (!kernelAbove600()) return MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer); IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u8 can_be_active; } *raw; raw = serviceIpcPrepareHeader(&g_nsdevSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 12; raw->can_be_active = can_be_active ? 1 : 0; Result rc = serviceIpcDispatch(&g_nsdevSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&g_nsdevSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; }
simontime/libnx
nx/source/services/usbhs.c
<filename>nx/source/services/usbhs.c #include <string.h> #include "types.h" #include "result.h" #include "arm/cache.h" #include "kernel/ipc.h" #include "kernel/detect.h" #include "services/usb.h" #include "services/usbhs.h" #include "services/sm.h" static Service g_usbHsSrv; static Event g_usbHsInterfaceStateChangeEvent = {0}; static Result _usbHsBindClientProcess(Handle prochandle); static Result _usbHsGetEvent(Service* srv, Event* event_out, u64 cmd_id); Result usbHsInitialize(void) { if (serviceIsActive(&g_usbHsSrv)) return MAKERESULT(Module_Libnx, LibnxError_AlreadyInitialized); Result rc = 0; rc = smGetService(&g_usbHsSrv, "usb:hs"); if (R_SUCCEEDED(rc)) { rc = serviceConvertToDomain(&g_usbHsSrv); } if (R_SUCCEEDED(rc) && kernelAbove200()) rc = _usbHsBindClientProcess(CUR_PROCESS_HANDLE); // GetInterfaceStateChangeEvent if (R_SUCCEEDED(rc)) rc = _usbHsGetEvent(&g_usbHsSrv, &g_usbHsInterfaceStateChangeEvent, kernelAbove200() ? 6 : 5); if (R_FAILED(rc)) { eventClose(&g_usbHsInterfaceStateChangeEvent); serviceClose(&g_usbHsSrv); } return rc; } void usbHsExit(void) { if (!serviceIsActive(&g_usbHsSrv)) return; eventClose(&g_usbHsInterfaceStateChangeEvent); serviceClose(&g_usbHsSrv); } Event* usbHsGetInterfaceStateChangeEvent(void) { return &g_usbHsInterfaceStateChangeEvent; } static Result _usbHsCmdNoIO(Service* s, u64 cmd_id) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = serviceIpcPrepareHeader(s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = cmd_id; Result rc = serviceIpcDispatch(s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; } static Result _usbHsBindClientProcess(Handle prochandle) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; ipcSendHandleCopy(&c, prochandle); raw = serviceIpcPrepareHeader(&g_usbHsSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 0; Result rc = serviceIpcDispatch(&g_usbHsSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&g_usbHsSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; } static Result _usbHsGetEvent(Service* srv, Event* event_out, u64 cmd_id) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = serviceIpcPrepareHeader(srv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = cmd_id; Result rc = serviceIpcDispatch(srv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(srv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { eventLoadRemote(event_out, r.Handles[0], false); } } return rc; } static Result _usbHsQueryInterfaces(u64 base_cmdid, const UsbHsInterfaceFilter* filter, UsbHsInterface* interfaces, size_t interfaces_maxsize, s32* total_entries) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; UsbHsInterfaceFilter filter; } *raw; ipcAddRecvBuffer(&c, interfaces, interfaces_maxsize, BufferType_Normal); raw = serviceIpcPrepareHeader(&g_usbHsSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = kernelAbove200() ? base_cmdid+1 : base_cmdid; raw->filter = *filter; Result rc = serviceIpcDispatch(&g_usbHsSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; s32 total_entries; } *resp; serviceIpcParse(&g_usbHsSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && total_entries) *total_entries = resp->total_entries; } return rc; } Result usbHsQueryAllInterfaces(const UsbHsInterfaceFilter* filter, UsbHsInterface* interfaces, size_t interfaces_maxsize, s32* total_entries) { return _usbHsQueryInterfaces(0, filter, interfaces, interfaces_maxsize, total_entries); } Result usbHsQueryAvailableInterfaces(const UsbHsInterfaceFilter* filter, UsbHsInterface* interfaces, size_t interfaces_maxsize, s32* total_entries) { return _usbHsQueryInterfaces(1, filter, interfaces, interfaces_maxsize, total_entries); } Result usbHsQueryAcquiredInterfaces(UsbHsInterface* interfaces, size_t interfaces_maxsize, s32* total_entries) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; ipcAddRecvBuffer(&c, interfaces, interfaces_maxsize, BufferType_Normal); raw = serviceIpcPrepareHeader(&g_usbHsSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = kernelAbove200() ? 3 : 2; Result rc = serviceIpcDispatch(&g_usbHsSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; s32 total_entries; } *resp; serviceIpcParse(&g_usbHsSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && total_entries) *total_entries = resp->total_entries; } return rc; } Result usbHsCreateInterfaceAvailableEvent(Event* event, bool autoclear, u8 index, const UsbHsInterfaceFilter* filter) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u8 index; u8 pad; UsbHsInterfaceFilter filter; } *raw; raw = serviceIpcPrepareHeader(&g_usbHsSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = kernelAbove200() ? 4 : 3; raw->index = index; raw->filter = *filter; Result rc = serviceIpcDispatch(&g_usbHsSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&g_usbHsSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { eventLoadRemote(event, r.Handles[0], autoclear); } } return rc; } Result usbHsDestroyInterfaceAvailableEvent(Event* event, u8 index) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u8 index; } *raw; raw = serviceIpcPrepareHeader(&g_usbHsSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = kernelAbove200() ? 5 : 4; raw->index = index; Result rc = serviceIpcDispatch(&g_usbHsSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&g_usbHsSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } eventClose(event); return rc; } Result usbHsAcquireUsbIf(UsbHsClientIfSession* s, UsbHsInterface *interface) { IpcCommand c; ipcInitialize(&c); memset(s, 0, sizeof(UsbHsClientIfSession)); memcpy(&s->inf, interface, sizeof(UsbHsInterface)); s->ID = interface->inf.ID; struct { u64 magic; u64 cmd_id; s32 ID; } *raw; if (!kernelAbove300()) { ipcAddRecvBuffer(&c, &s->inf.inf, sizeof(UsbHsInterfaceInfo), BufferType_Normal); } else { //These buffer addresses are the inverse of what official sw does - needed to get the correct UsbHsInterface output for some reason. ipcAddRecvBuffer(&c, &s->inf.pathstr, sizeof(UsbHsInterface) - sizeof(UsbHsInterfaceInfo), BufferType_Normal); ipcAddRecvBuffer(&c, &s->inf.inf, sizeof(UsbHsInterfaceInfo), BufferType_Normal); } raw = serviceIpcPrepareHeader(&g_usbHsSrv, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = kernelAbove200() ? 7 : 6; raw->ID = s->ID; Result rc = serviceIpcDispatch(&g_usbHsSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&g_usbHsSrv, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { serviceCreateSubservice(&s->s, &g_usbHsSrv, &r, 0); } } if (R_SUCCEEDED(rc)) { rc = _usbHsGetEvent(&s->s, &s->event0, 0); if (kernelAbove200()) rc = _usbHsGetEvent(&s->s, &s->eventCtrlXfer, 6); if (R_FAILED(rc)) { serviceClose(&s->s); eventClose(&s->event0); eventClose(&s->eventCtrlXfer); } } return rc; } void usbHsIfClose(UsbHsClientIfSession* s) { serviceClose(&s->s); eventClose(&s->event0); eventClose(&s->eventCtrlXfer); memset(s, 0, sizeof(UsbHsClientIfSession)); } static Result _usbHsIfGetInf(UsbHsClientIfSession* s, UsbHsInterfaceInfo* inf, u8 id, u64 cmd_id) { IpcCommand c; ipcInitialize(&c); if (inf==NULL) inf = &s->inf.inf; struct { u64 magic; u64 cmd_id; u8 id; } *raw; ipcAddRecvBuffer(&c, inf, sizeof(UsbHsInterfaceInfo), BufferType_Normal); raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = cmd_id; raw->id = id; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; } Result usbHsIfSetInterface(UsbHsClientIfSession* s, UsbHsInterfaceInfo* inf, u8 id) { return _usbHsIfGetInf(s, inf, id, 1); } Result usbHsIfGetAlternateInterface(UsbHsClientIfSession* s, UsbHsInterfaceInfo* inf, u8 id) { return _usbHsIfGetInf(s, inf, id, 3); } Result usbHsIfGetInterface(UsbHsClientIfSession* s, UsbHsInterfaceInfo* inf) { IpcCommand c; ipcInitialize(&c); if (inf==NULL) inf = &s->inf.inf; struct { u64 magic; u64 cmd_id; } *raw; ipcAddRecvBuffer(&c, inf, sizeof(UsbHsInterfaceInfo), BufferType_Normal); raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 2; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; } Result usbHsIfGetCurrentFrame(UsbHsClientIfSession* s, u32* out) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = kernelAbove200() ? 4 : 5; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u32 out; } *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && out) *out = resp->out; } return rc; } static Result _usbHsIfSubmitControlRequest(UsbHsClientIfSession* s, u8 bRequest, u8 bmRequestType, u16 wValue, u16 wIndex, u16 wLength, void* buffer, u32 timeoutInMs, u32* transferredSize) { bool dir = (bmRequestType & USB_ENDPOINT_IN) != 0; size_t bufsize = (wLength + 0xFFF) & ~0xFFF; armDCacheFlush(buffer, wLength); IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u8 bRequest; u8 bmRequestType; u16 wValue; u16 wIndex; u16 wLength; u32 timeoutInMs; } PACKED *raw; if (dir) ipcAddRecvBuffer(&c, buffer, bufsize, BufferType_Normal); if (!dir) ipcAddSendBuffer(&c, buffer, bufsize, BufferType_Normal); raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = dir ? 6 : 7; raw->bRequest = bRequest; raw->bmRequestType = bmRequestType; raw->wValue = wValue; raw->wIndex = wIndex; raw->wLength = wLength; raw->timeoutInMs = timeoutInMs; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u32 transferredSize; } *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && transferredSize) *transferredSize = resp->transferredSize; } if (dir) armDCacheFlush(buffer, wLength); return rc; } static Result _usbHsIfCtrlXferAsync(UsbHsClientIfSession* s, u8 bmRequestType, u8 bRequest, u16 wValue, u16 wIndex, u16 wLength, void* buffer) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u8 bmRequestType; u8 bRequest; u16 wValue; u16 wIndex; u16 wLength; u64 buffer; } PACKED *raw; raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 5; raw->bmRequestType = bmRequestType; raw->bRequest = bRequest; raw->wValue = wValue; raw->wIndex = wIndex; raw->wLength = wLength; raw->buffer = (u64)buffer; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; } static Result _usbHsIfGetCtrlXferReport(UsbHsClientIfSession* s, UsbHsXferReport* report) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; ipcAddRecvBuffer(&c, report, sizeof(UsbHsXferReport), BufferType_Normal); raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 7; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; } *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; } return rc; } Result usbHsIfCtrlXfer(UsbHsClientIfSession* s, u8 bmRequestType, u8 bRequest, u16 wValue, u16 wIndex, u16 wLength, void* buffer, u32* transferredSize) { Result rc=0; UsbHsXferReport report; if (!kernelAbove200()) return _usbHsIfSubmitControlRequest(s, bRequest, bmRequestType, wValue, wIndex, wLength, buffer, 0, transferredSize); rc = _usbHsIfCtrlXferAsync(s, bmRequestType, bRequest, wValue, wIndex, wLength, buffer); if (R_FAILED(rc)) return rc; rc = eventWait(&s->eventCtrlXfer, U64_MAX); if (R_FAILED(rc)) return rc; eventClear(&s->eventCtrlXfer); memset(&report, 0, sizeof(report)); rc = _usbHsIfGetCtrlXferReport(s, &report); if (R_FAILED(rc)) return rc; *transferredSize = report.transferredSize; rc = report.res; return rc; } Result usbHsIfOpenUsbEp(UsbHsClientIfSession* s, UsbHsClientEpSession* ep, u16 maxUrbCount, u32 maxXferSize, struct usb_endpoint_descriptor *desc) { IpcCommand c; ipcInitialize(&c); memset(ep, 0, sizeof(UsbHsClientEpSession)); struct { u64 magic; u64 cmd_id; u16 maxUrbCount; u32 epType; u32 epNumber; u32 epDirection; u32 maxXferSize; } *raw; raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = kernelAbove200() ? 9 : 4; raw->maxUrbCount = maxUrbCount; raw->epType = (desc->bmAttributes & USB_TRANSFER_TYPE_MASK) + 1; raw->epNumber = desc->bEndpointAddress & USB_ENDPOINT_ADDRESS_MASK; raw->epDirection = (desc->bEndpointAddress & USB_ENDPOINT_IN) == 0 ? 0x1 : 0x2; raw->maxXferSize = maxXferSize; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; struct usb_endpoint_descriptor desc; } PACKED *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) memcpy(&ep->desc, &resp->desc, sizeof(struct usb_endpoint_descriptor)); if (R_SUCCEEDED(rc)) { serviceCreateSubservice(&ep->s, &s->s, &r, 0); } } if (R_SUCCEEDED(rc)) { if (kernelAbove200()) { rc = _usbHsCmdNoIO(&ep->s, 3);//Populate if (R_SUCCEEDED(rc)) rc = _usbHsGetEvent(&ep->s, &ep->eventXfer, 2); } if (R_FAILED(rc)) { serviceClose(&ep->s); eventClose(&ep->eventXfer); } } return rc; } Result usbHsIfResetDevice(UsbHsClientIfSession* s) { return _usbHsCmdNoIO(&s->s, 8); } void usbHsEpClose(UsbHsClientEpSession* s) { if (!serviceIsActive(&s->s)) return; _usbHsCmdNoIO(&s->s, kernelAbove200() ? 1 : 3);//Close serviceClose(&s->s); eventClose(&s->eventXfer); memset(s, 0, sizeof(UsbHsClientIfSession)); } static Result _usbHsEpSubmitRequest(UsbHsClientEpSession* s, void* buffer, u32 size, u32 timeoutInMs, u32* transferredSize) { bool dir = (s->desc.bEndpointAddress & USB_ENDPOINT_IN) != 0; size_t bufsize = (size + 0xFFF) & ~0xFFF; armDCacheFlush(buffer, size); IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u32 size; u32 timeoutInMs;//? } *raw; if (dir) ipcAddRecvBuffer(&c, buffer, bufsize, BufferType_Normal); if (!dir) ipcAddSendBuffer(&c, buffer, bufsize, BufferType_Normal); raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = dir ? 1 : 0; raw->size = size; raw->timeoutInMs = timeoutInMs; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u32 transferredSize; } *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && transferredSize) *transferredSize = resp->transferredSize; } if (dir) armDCacheFlush(buffer, size); return rc; } static Result _usbHsEpPostBufferAsync(UsbHsClientEpSession* s, void* buffer, u32 size, u64 unk, u32* xferId) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u32 size; u64 buffer; u64 unk; } *raw; raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 4; raw->size = size; raw->buffer = (u64)buffer; raw->unk = unk; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u32 xferId; } *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && xferId) *xferId = resp->xferId; } return rc; } static Result _usbHsEpGetXferReport(UsbHsClientEpSession* s, UsbHsXferReport* reports, u32 max_reports, u32* count) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u32 max_reports; } *raw; ipcAddRecvBuffer(&c, reports, sizeof(UsbHsXferReport) * max_reports, BufferType_Normal); raw = serviceIpcPrepareHeader(&s->s, &c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 5; raw->max_reports = max_reports; Result rc = serviceIpcDispatch(&s->s); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; struct { u64 magic; u64 result; u32 count; } *resp; serviceIpcParse(&s->s, &r, sizeof(*resp)); resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc) && count) *count = resp->count; } return rc; } Result usbHsEpPostBuffer(UsbHsClientEpSession* s, void* buffer, u32 size, u32* transferredSize) { Result rc=0; u32 xferId=0; u32 count=0; UsbHsXferReport report; if (!kernelAbove200()) return _usbHsEpSubmitRequest(s, buffer, size, 0, transferredSize); rc = _usbHsEpPostBufferAsync(s, buffer, size, 0, &xferId); if (R_FAILED(rc)) return rc; rc = eventWait(&s->eventXfer, U64_MAX); if (R_FAILED(rc)) return rc; eventClear(&s->eventXfer); memset(&report, 0, sizeof(report)); rc = _usbHsEpGetXferReport(s, &report, 1, &count); if (R_FAILED(rc)) return rc; if (count<1) return MAKERESULT(Module_Libnx, LibnxError_BadInput); *transferredSize = report.transferredSize; rc = report.res; return rc; }
simontime/libnx
nx/include/switch/services/hid.h
<gh_stars>0 /** * @file hid.h * @brief Human input device (hid) service IPC wrapper. * @author shinyquagsire23 * @author yellows8 * @copyright libnx Authors */ #pragma once #include "../types.h" #include "../kernel/event.h" #include "../services/sm.h" // Begin enums and output structs typedef enum { MOUSE_LEFT = BIT(0), MOUSE_RIGHT = BIT(1), MOUSE_MIDDLE = BIT(2), MOUSE_FORWARD = BIT(3), MOUSE_BACK = BIT(4), } HidMouseButton; typedef enum { KBD_MOD_LCTRL = BIT(0), KBD_MOD_LSHIFT = BIT(1), KBD_MOD_LALT = BIT(2), KBD_MOD_LMETA = BIT(3), KBD_MOD_RCTRL = BIT(4), KBD_MOD_RSHIFT = BIT(5), KBD_MOD_RALT = BIT(6), KBD_MOD_RMETA = BIT(7), KBD_MOD_CAPSLOCK = BIT(8), KBD_MOD_SCROLLLOCK = BIT(9), KBD_MOD_NUMLOCK = BIT(10), } HidKeyboardModifier; typedef enum { KBD_NONE = 0x00, KBD_ERR_OVF = 0x01, KBD_A = 0x04, KBD_B = 0x05, KBD_C = 0x06, KBD_D = 0x07, KBD_E = 0x08, KBD_F = 0x09, KBD_G = 0x0a, KBD_H = 0x0b, KBD_I = 0x0c, KBD_J = 0x0d, KBD_K = 0x0e, KBD_L = 0x0f, KBD_M = 0x10, KBD_N = 0x11, KBD_O = 0x12, KBD_P = 0x13, KBD_Q = 0x14, KBD_R = 0x15, KBD_S = 0x16, KBD_T = 0x17, KBD_U = 0x18, KBD_V = 0x19, KBD_W = 0x1a, KBD_X = 0x1b, KBD_Y = 0x1c, KBD_Z = 0x1d, KBD_1 = 0x1e, KBD_2 = 0x1f, KBD_3 = 0x20, KBD_4 = 0x21, KBD_5 = 0x22, KBD_6 = 0x23, KBD_7 = 0x24, KBD_8 = 0x25, KBD_9 = 0x26, KBD_0 = 0x27, KBD_ENTER = 0x28, KBD_ESC = 0x29, KBD_BACKSPACE = 0x2a, KBD_TAB = 0x2b, KBD_SPACE = 0x2c, KBD_MINUS = 0x2d, KBD_EQUAL = 0x2e, KBD_LEFTBRACE = 0x2f, KBD_RIGHTBRACE = 0x30, KBD_BACKSLASH = 0x31, KBD_HASHTILDE = 0x32, KBD_SEMICOLON = 0x33, KBD_APOSTROPHE = 0x34, KBD_GRAVE = 0x35, KBD_COMMA = 0x36, KBD_DOT = 0x37, KBD_SLASH = 0x38, KBD_CAPSLOCK = 0x39, KBD_F1 = 0x3a, KBD_F2 = 0x3b, KBD_F3 = 0x3c, KBD_F4 = 0x3d, KBD_F5 = 0x3e, KBD_F6 = 0x3f, KBD_F7 = 0x40, KBD_F8 = 0x41, KBD_F9 = 0x42, KBD_F10 = 0x43, KBD_F11 = 0x44, KBD_F12 = 0x45, KBD_SYSRQ = 0x46, KBD_SCROLLLOCK = 0x47, KBD_PAUSE = 0x48, KBD_INSERT = 0x49, KBD_HOME = 0x4a, KBD_PAGEUP = 0x4b, KBD_DELETE = 0x4c, KBD_END = 0x4d, KBD_PAGEDOWN = 0x4e, KBD_RIGHT = 0x4f, KBD_LEFT = 0x50, KBD_DOWN = 0x51, KBD_UP = 0x52, KBD_NUMLOCK = 0x53, KBD_KPSLASH = 0x54, KBD_KPASTERISK = 0x55, KBD_KPMINUS = 0x56, KBD_KPPLUS = 0x57, KBD_KPENTER = 0x58, KBD_KP1 = 0x59, KBD_KP2 = 0x5a, KBD_KP3 = 0x5b, KBD_KP4 = 0x5c, KBD_KP5 = 0x5d, KBD_KP6 = 0x5e, KBD_KP7 = 0x5f, KBD_KP8 = 0x60, KBD_KP9 = 0x61, KBD_KP0 = 0x62, KBD_KPDOT = 0x63, KBD_102ND = 0x64, KBD_COMPOSE = 0x65, KBD_POWER = 0x66, KBD_KPEQUAL = 0x67, KBD_F13 = 0x68, KBD_F14 = 0x69, KBD_F15 = 0x6a, KBD_F16 = 0x6b, KBD_F17 = 0x6c, KBD_F18 = 0x6d, KBD_F19 = 0x6e, KBD_F20 = 0x6f, KBD_F21 = 0x70, KBD_F22 = 0x71, KBD_F23 = 0x72, KBD_F24 = 0x73, KBD_OPEN = 0x74, KBD_HELP = 0x75, KBD_PROPS = 0x76, KBD_FRONT = 0x77, KBD_STOP = 0x78, KBD_AGAIN = 0x79, KBD_UNDO = 0x7a, KBD_CUT = 0x7b, KBD_COPY = 0x7c, KBD_PASTE = 0x7d, KBD_FIND = 0x7e, KBD_MUTE = 0x7f, KBD_VOLUMEUP = 0x80, KBD_VOLUMEDOWN = 0x81, KBD_CAPSLOCK_ACTIVE = 0x82 , KBD_NUMLOCK_ACTIVE = 0x83 , KBD_SCROLLLOCK_ACTIVE = 0x84 , KBD_KPCOMMA = 0x85, KBD_KPLEFTPAREN = 0xb6, KBD_KPRIGHTPAREN = 0xb7, KBD_LEFTCTRL = 0xe0, KBD_LEFTSHIFT = 0xe1, KBD_LEFTALT = 0xe2, KBD_LEFTMETA = 0xe3, KBD_RIGHTCTRL = 0xe4, KBD_RIGHTSHIFT = 0xe5, KBD_RIGHTALT = 0xe6, KBD_RIGHTMETA = 0xe7, KBD_MEDIA_PLAYPAUSE = 0xe8, KBD_MEDIA_STOPCD = 0xe9, KBD_MEDIA_PREVIOUSSONG = 0xea, KBD_MEDIA_NEXTSONG = 0xeb, KBD_MEDIA_EJECTCD = 0xec, KBD_MEDIA_VOLUMEUP = 0xed, KBD_MEDIA_VOLUMEDOWN = 0xee, KBD_MEDIA_MUTE = 0xef, KBD_MEDIA_WWW = 0xf0, KBD_MEDIA_BACK = 0xf1, KBD_MEDIA_FORWARD = 0xf2, KBD_MEDIA_STOP = 0xf3, KBD_MEDIA_FIND = 0xf4, KBD_MEDIA_SCROLLUP = 0xf5, KBD_MEDIA_SCROLLDOWN = 0xf6, KBD_MEDIA_EDIT = 0xf7, KBD_MEDIA_SLEEP = 0xf8, KBD_MEDIA_COFFEE = 0xf9, KBD_MEDIA_REFRESH = 0xfa, KBD_MEDIA_CALC = 0xfb } HidKeyboardScancode; typedef enum { TYPE_PROCONTROLLER = BIT(0), TYPE_HANDHELD = BIT(1), TYPE_JOYCON_PAIR = BIT(2), TYPE_JOYCON_LEFT = BIT(3), TYPE_JOYCON_RIGHT = BIT(4), } HidControllerType; typedef enum { LAYOUT_PROCONTROLLER = 0, ///< Pro Controller or Hid gamepad. LAYOUT_HANDHELD = 1, ///< Two Joy-Con docked to rails. LAYOUT_SINGLE = 2, ///< Single Joy-Con or pair of Joy-Con, only available in dual-mode with no orientation adjustment. LAYOUT_LEFT = 3, ///< Only single-mode raw left Joy-Con state, no orientation adjustment. LAYOUT_RIGHT = 4, ///< Only single-mode raw right Joy-Con state, no orientation adjustment. LAYOUT_DEFAULT_DIGITAL = 5, ///< Same as next, but sticks have 8-direction values only. LAYOUT_DEFAULT = 6, ///< Safe default. Single-mode and \ref HidJoyHoldType_Horizontal: Joy-Con have buttons/sticks rotated for orientation, where physical Z(L/R) are unavailable and S(L/R) are mapped to L/R (with physical L/R unavailable). } HidControllerLayoutType; typedef enum { COLORS_NONEXISTENT = BIT(1), } HidControllerColorDescription; typedef enum { KEY_A = BIT(0), ///< A KEY_B = BIT(1), ///< B KEY_X = BIT(2), ///< X KEY_Y = BIT(3), ///< Y KEY_LSTICK = BIT(4), ///< Left Stick Button KEY_RSTICK = BIT(5), ///< Right Stick Button KEY_L = BIT(6), ///< L KEY_R = BIT(7), ///< R KEY_ZL = BIT(8), ///< ZL KEY_ZR = BIT(9), ///< ZR KEY_PLUS = BIT(10), ///< Plus KEY_MINUS = BIT(11), ///< Minus KEY_DLEFT = BIT(12), ///< D-Pad Left KEY_DUP = BIT(13), ///< D-Pad Up KEY_DRIGHT = BIT(14), ///< D-Pad Right KEY_DDOWN = BIT(15), ///< D-Pad Down KEY_LSTICK_LEFT = BIT(16), ///< Left Stick Left KEY_LSTICK_UP = BIT(17), ///< Left Stick Up KEY_LSTICK_RIGHT = BIT(18), ///< Left Stick Right KEY_LSTICK_DOWN = BIT(19), ///< Left Stick Down KEY_RSTICK_LEFT = BIT(20), ///< Right Stick Left KEY_RSTICK_UP = BIT(21), ///< Right Stick Up KEY_RSTICK_RIGHT = BIT(22), ///< Right Stick Right KEY_RSTICK_DOWN = BIT(23), ///< Right Stick Down KEY_SL_LEFT = BIT(24), ///< SL on Left Joy-Con KEY_SR_LEFT = BIT(25), ///< SR on Left Joy-Con KEY_SL_RIGHT = BIT(26), ///< SL on Right Joy-Con KEY_SR_RIGHT = BIT(27), ///< SR on Right Joy-Con // Pseudo-key for at least one finger on the touch screen KEY_TOUCH = BIT(28), // Buttons by orientation (for single Joy-Con), also works with Joy-Con pairs, Pro Controller KEY_JOYCON_RIGHT = BIT(0), KEY_JOYCON_DOWN = BIT(1), KEY_JOYCON_UP = BIT(2), KEY_JOYCON_LEFT = BIT(3), // Generic catch-all directions, also works for single Joy-Con KEY_UP = KEY_DUP | KEY_LSTICK_UP | KEY_RSTICK_UP, ///< D-Pad Up or Sticks Up KEY_DOWN = KEY_DDOWN | KEY_LSTICK_DOWN | KEY_RSTICK_DOWN, ///< D-Pad Down or Sticks Down KEY_LEFT = KEY_DLEFT | KEY_LSTICK_LEFT | KEY_RSTICK_LEFT, ///< D-Pad Left or Sticks Left KEY_RIGHT = KEY_DRIGHT | KEY_LSTICK_RIGHT | KEY_RSTICK_RIGHT, ///< D-Pad Right or Sticks Right KEY_SL = KEY_SL_LEFT | KEY_SL_RIGHT, ///< SL on Left or Right Joy-Con KEY_SR = KEY_SR_LEFT | KEY_SR_RIGHT, ///< SR on Left or Right Joy-Con } HidControllerKeys; typedef enum { JOYSTICK_LEFT = 0, JOYSTICK_RIGHT = 1, JOYSTICK_NUM_STICKS = 2, } HidControllerJoystick; typedef enum { CONTROLLER_STATE_CONNECTED = BIT(0), CONTROLLER_STATE_WIRED = BIT(1), } HidControllerConnectionState; typedef enum { CONTROLLER_PLAYER_1 = 0, CONTROLLER_PLAYER_2 = 1, CONTROLLER_PLAYER_3 = 2, CONTROLLER_PLAYER_4 = 3, CONTROLLER_PLAYER_5 = 4, CONTROLLER_PLAYER_6 = 5, CONTROLLER_PLAYER_7 = 6, CONTROLLER_PLAYER_8 = 7, CONTROLLER_HANDHELD = 8, CONTROLLER_UNKNOWN = 9, CONTROLLER_P1_AUTO = 10, ///< Not an actual HID-sysmodule ID. Only for hidKeys*()/hidJoystickRead()/hidSixAxisSensorValuesRead()/hidGetControllerType()/hidGetControllerColors()/hidIsControllerConnected(). Automatically uses CONTROLLER_PLAYER_1 when connected, otherwise uses CONTROLLER_HANDHELD. } HidControllerID; typedef enum { HidJoyHoldType_Default = 0, ///< Default / Joy-Con held vertically. HidJoyHoldType_Horizontal = 1, ///< Joy-Con held horizontally with HID state orientation adjustment, see \ref HidControllerLayoutType. } HidJoyHoldType; typedef struct touchPosition { u32 id; u32 px; u32 py; u32 dx; u32 dy; u32 angle; } touchPosition; typedef struct JoystickPosition { s32 dx; s32 dy; } JoystickPosition; typedef struct MousePosition { u32 x; u32 y; u32 velocityX; u32 velocityY; u32 scrollVelocityX; u32 scrollVelocityY; } MousePosition; typedef struct HidVector { float x; float y; float z; } HidVector; typedef struct SixAxisSensorValues { HidVector accelerometer; HidVector gyroscope; HidVector unk; HidVector orientation[3]; } SixAxisSensorValues; #define JOYSTICK_MAX (0x8000) #define JOYSTICK_MIN (-0x8000) // End enums and output structs // Begin HidTouchScreen typedef struct HidTouchScreenHeader { u64 timestampTicks; u64 numEntries; u64 latestEntry; u64 maxEntryIndex; u64 timestamp; } HidTouchScreenHeader; typedef struct HidTouchScreenEntryHeader { u64 timestamp; u64 numTouches; } HidTouchScreenEntryHeader; typedef struct HidTouchScreenEntryTouch { u64 timestamp; u32 padding; u32 touchIndex; u32 x; u32 y; u32 diameterX; u32 diameterY; u32 angle; u32 padding_2; } HidTouchScreenEntryTouch; typedef struct HidTouchScreenEntry { HidTouchScreenEntryHeader header; HidTouchScreenEntryTouch touches[16]; u64 unk; } HidTouchScreenEntry; typedef struct HidTouchScreen { HidTouchScreenHeader header; HidTouchScreenEntry entries[17]; u8 padding[0x3c0]; } HidTouchScreen; // End HidTouchScreen // Begin HidMouse typedef struct HidMouseHeader { u64 timestampTicks; u64 numEntries; u64 latestEntry; u64 maxEntryIndex; } HidMouseHeader; typedef struct HidMouseEntry { u64 timestamp; u64 timestamp_2; MousePosition position; u64 buttons; } HidMouseEntry; typedef struct HidMouse { HidMouseHeader header; HidMouseEntry entries[17]; u8 padding[0xB0]; } HidMouse; // End HidMouse // Begin HidKeyboard typedef struct HidKeyboardHeader { u64 timestampTicks; u64 numEntries; u64 latestEntry; u64 maxEntryIndex; } HidKeyboardHeader; typedef struct HidKeyboardEntry { u64 timestamp; u64 timestamp_2; u64 modifier; u32 keys[8]; } HidKeyboardEntry; typedef struct HidKeyboard { HidKeyboardHeader header; HidKeyboardEntry entries[17]; u8 padding[0x28]; } HidKeyboard; // End HidKeyboard // Begin HidController typedef struct HidControllerMAC { u64 timestamp; u8 mac[0x8]; u64 unk; u64 timestamp_2; } HidControllerMAC; typedef struct HidControllerHeader { u32 type; u32 isHalf; u32 singleColorsDescriptor; u32 singleColorBody; u32 singleColorButtons; u32 splitColorsDescriptor; u32 leftColorBody; u32 leftColorButtons; u32 rightColorBody; u32 rightColorButtons; } HidControllerHeader; /// Info struct extracted from HidControllerHeader. /// Color fields are zero when not set. This can happen even when the *Set fields are set to true. typedef struct HidControllerColors { bool singleSet; ///< Set to true when the below fields are valid. u32 singleColorBody; ///< RGBA Single Body Color u32 singleColorButtons; ///< RGBA Single Buttons Color bool splitSet; ///< Set to true when the below fields are valid. u32 leftColorBody; ///< RGBA Left Body Color u32 leftColorButtons; ///< RGBA Left Buttons Color u32 rightColorBody; ///< RGBA Right Body Color u32 rightColorButtons; ///< RGBA Right Buttons Color } HidControllerColors; typedef struct HidControllerLayoutHeader { u64 timestampTicks; u64 numEntries; u64 latestEntry; u64 maxEntryIndex; } HidControllerLayoutHeader; typedef struct HidControllerInputEntry { u64 timestamp; u64 timestamp_2; u64 buttons; JoystickPosition joysticks[JOYSTICK_NUM_STICKS]; u64 connectionState; } HidControllerInputEntry; typedef struct HidControllerLayout { HidControllerLayoutHeader header; HidControllerInputEntry entries[17]; } HidControllerLayout; typedef struct HidControllerSixAxisHeader { u64 timestamp; u64 numEntries; u64 latestEntry; u64 maxEntryIndex; } HidControllerSixAxisHeader; typedef struct HidControllerSixAxisEntry { u64 timestamp; u64 unk_1; u64 timestamp_2; SixAxisSensorValues values; u64 unk_3; } HidControllerSixAxisEntry; typedef struct HidControllerSixAxisLayout { HidControllerSixAxisHeader header; HidControllerSixAxisEntry entries[17]; } HidControllerSixAxisLayout; typedef struct HidController { HidControllerHeader header; HidControllerLayout layouts[7]; HidControllerSixAxisLayout sixaxis[6]; u8 unk_1[0x40]; HidControllerMAC macLeft; HidControllerMAC macRight; u8 unk_2[0xDF8]; } HidController; // End HidController typedef struct HidSharedMemory { u8 header[0x400]; HidTouchScreen touchscreen; HidMouse mouse; HidKeyboard keyboard; u8 unkSection1[0x400]; u8 unkSection2[0x400]; u8 unkSection3[0x400]; u8 unkSection4[0x400]; u8 unkSection5[0x200]; u8 unkSection6[0x200]; u8 unkSection7[0x200]; u8 unkSection8[0x800]; u8 controllerSerials[0x4000]; HidController controllers[10]; u8 unkSection9[0x4600]; } HidSharedMemory; typedef struct HidVibrationDeviceInfo { u32 unk_x0; u32 unk_x4; ///< 0x1 for left-joycon, 0x2 for right-joycon. } HidVibrationDeviceInfo; typedef struct HidVibrationValue { float amp_low; ///< Low Band amplitude. 1.0f: Max amplitude. float freq_low; ///< Low Band frequency in Hz. float amp_high; ///< High Band amplitude. 1.0f: Max amplitude. float freq_high; ///< High Band frequency in Hz. } HidVibrationValue; Result hidInitialize(void); void hidExit(void); void hidReset(void); Service* hidGetSessionService(void); void* hidGetSharedmemAddr(void); void hidSetControllerLayout(HidControllerID id, HidControllerLayoutType layoutType); HidControllerLayoutType hidGetControllerLayout(HidControllerID id); HidControllerType hidGetControllerType(HidControllerID id); void hidGetControllerColors(HidControllerID id, HidControllerColors *colors); bool hidIsControllerConnected(HidControllerID id); void hidScanInput(void); u64 hidKeysHeld(HidControllerID id); u64 hidKeysDown(HidControllerID id); u64 hidKeysUp(HidControllerID id); u64 hidMouseButtonsHeld(void); u64 hidMouseButtonsDown(void); u64 hidMouseButtonsUp(void); void hidMouseRead(MousePosition *pos); bool hidKeyboardModifierHeld(HidKeyboardModifier modifier); bool hidKeyboardModifierDown(HidKeyboardModifier modifier); bool hidKeyboardModifierUp(HidKeyboardModifier modifier); bool hidKeyboardHeld(HidKeyboardScancode key); bool hidKeyboardDown(HidKeyboardScancode key); bool hidKeyboardUp(HidKeyboardScancode key); u32 hidTouchCount(void); void hidTouchRead(touchPosition *pos, u32 point_id); void hidJoystickRead(JoystickPosition *pos, HidControllerID id, HidControllerJoystick stick); u32 hidSixAxisSensorValuesRead(SixAxisSensorValues *values, HidControllerID id, u32 num_entries); /// This can be used to check what CONTROLLER_P1_AUTO uses. /// Returns 0 when CONTROLLER_PLAYER_1 is connected, otherwise returns 1 for handheld-mode. bool hidGetHandheldMode(void); /// This is automatically called with CONTROLLER_PLAYER_{1-8} and CONTROLLER_HANDHELD in \ref hidInitialize. /// count must be <=10. Each entry in buf must be CONTROLLER_PLAYER_{1-8} or CONTROLLER_HANDHELD. Result hidSetSupportedNpadIdType(HidControllerID *buf, size_t count); /// Sets which controller types are supported. This is automatically called with all types in \ref hidInitialize. Result hidSetSupportedNpadStyleSet(HidControllerType type); /// Gets an event with the specified autoclear for the input controller. /// The user *must* close the event when finished with it / before the app exits. /// This is signaled when the \ref hidGetControllerType output is updated for the controller. Result hidAcquireNpadStyleSetUpdateEventHandle(HidControllerID id, Event* event, bool autoclear); /// Sets the hold-type, see \ref HidJoyHoldType. Result hidSetNpadJoyHoldType(HidJoyHoldType type); /// Use this if you want to use a single joy-con as a dedicated CONTROLLER_PLAYER_*. /// When used, both joy-cons in a pair should be used with this (CONTROLLER_PLAYER_1 and CONTROLLER_PLAYER_2 for example). /// id must be CONTROLLER_PLAYER_*. Result hidSetNpadJoyAssignmentModeSingleByDefault(HidControllerID id); /// Use this if you want to use a pair of joy-cons as a single CONTROLLER_PLAYER_*. Only necessary if you want to use this mode in your application after \ref hidSetNpadJoyAssignmentModeSingleByDefault was used with this pair of joy-cons. /// Used automatically during app startup/exit for all controllers. /// When used, both joy-cons in a pair should be used with this (CONTROLLER_PLAYER_1 and CONTROLLER_PLAYER_2 for example). /// id must be CONTROLLER_PLAYER_*. Result hidSetNpadJoyAssignmentModeDual(HidControllerID id); /// Merge two single joy-cons into a dual-mode controller. Use this after \ref hidSetNpadJoyAssignmentModeDual, when \ref hidSetNpadJoyAssignmentModeSingleByDefault was previously used (this includes using this manually at application exit). /// To be successful, id0/id1 must correspond to controller types TYPE_JOYCON_LEFT/TYPE_JOYCON_RIGHT, or TYPE_JOYCON_RIGHT/TYPE_JOYCON_LEFT. /// If successful, the id of the resulting dual controller is set to id0. Result hidMergeSingleJoyAsDualJoy(HidControllerID id0, HidControllerID id1); Result hidInitializeVibrationDevices(u32 *VibrationDeviceHandles, size_t total_handles, HidControllerID id, HidControllerType type); /// Gets HidVibrationDeviceInfo for the specified VibrationDeviceHandle. Result hidGetVibrationDeviceInfo(u32 *VibrationDeviceHandle, HidVibrationDeviceInfo *VibrationDeviceInfo); /// Send the VibrationValue to the specified VibrationDeviceHandle. Result hidSendVibrationValue(u32 *VibrationDeviceHandle, HidVibrationValue *VibrationValue); /// Gets the current HidVibrationValue for the specified VibrationDeviceHandle. Result hidGetActualVibrationValue(u32 *VibrationDeviceHandle, HidVibrationValue *VibrationValue); /// Sets whether vibration is allowed, this also affects the config displayed by System Settings. Result hidPermitVibration(bool flag); /// Gets whether vibration is allowed. Result hidIsVibrationPermitted(bool *flag); /// Send VibrationValues[index] to VibrationDeviceHandles[index], where count is the number of entries in the VibrationDeviceHandles/VibrationValues arrays. Result hidSendVibrationValues(u32 *VibrationDeviceHandles, HidVibrationValue *VibrationValues, size_t count); /// Gets SixAxisSensorHandles. total_handles==2 can only be used with TYPE_JOYCON_PAIR. Result hidGetSixAxisSensorHandles(u32 *SixAxisSensorHandles, size_t total_handles, HidControllerID id, HidControllerType type); /// Starts the SixAxisSensor for the specified handle. Result hidStartSixAxisSensor(u32 SixAxisSensorHandle); /// Stops the SixAxisSensor for the specified handle. Result hidStopSixAxisSensor(u32 SixAxisSensorHandle);
simontime/libnx
nx/include/switch/display/types.h
/** * @file types.h * @brief Definitions for Android-related types and enumerations. * @copyright libnx Authors */ #pragma once #include "../types.h" // From Android PixelFormat.h & graphics-base-v1.0.h. enum { PIXEL_FORMAT_RGBA_8888 = 1U, PIXEL_FORMAT_RGBX_8888 = 2U, PIXEL_FORMAT_RGB_888 = 3U, PIXEL_FORMAT_RGB_565 = 4U, PIXEL_FORMAT_BGRA_8888 = 5U, PIXEL_FORMAT_RGBA_5551 = 6U, PIXEL_FORMAT_RGBA_4444 = 7U, PIXEL_FORMAT_YCRCB_420_SP = 17U, PIXEL_FORMAT_RAW16 = 32U, PIXEL_FORMAT_BLOB = 33U, PIXEL_FORMAT_IMPLEMENTATION_DEFINED = 34U, PIXEL_FORMAT_YCBCR_420_888 = 35U, PIXEL_FORMAT_Y8 = 0x20203859U, PIXEL_FORMAT_Y16 = 0x20363159U, PIXEL_FORMAT_YV12 = 0x32315659U, }; // From Android gralloc.h. enum { /* buffer is never read in software */ GRALLOC_USAGE_SW_READ_NEVER = 0x00000000U, /* buffer is rarely read in software */ GRALLOC_USAGE_SW_READ_RARELY = 0x00000002U, /* buffer is often read in software */ GRALLOC_USAGE_SW_READ_OFTEN = 0x00000003U, /* mask for the software read values */ GRALLOC_USAGE_SW_READ_MASK = 0x0000000FU, /* buffer is never written in software */ GRALLOC_USAGE_SW_WRITE_NEVER = 0x00000000U, /* buffer is rarely written in software */ GRALLOC_USAGE_SW_WRITE_RARELY = 0x00000020U, /* buffer is often written in software */ GRALLOC_USAGE_SW_WRITE_OFTEN = 0x00000030U, /* mask for the software write values */ GRALLOC_USAGE_SW_WRITE_MASK = 0x000000F0U, /* buffer will be used as an OpenGL ES texture */ GRALLOC_USAGE_HW_TEXTURE = 0x00000100U, /* buffer will be used as an OpenGL ES render target */ GRALLOC_USAGE_HW_RENDER = 0x00000200U, /* buffer will be used by the 2D hardware blitter */ GRALLOC_USAGE_HW_2D = 0x00000400U, /* buffer will be used by the HWComposer HAL module */ GRALLOC_USAGE_HW_COMPOSER = 0x00000800U, /* buffer will be used with the framebuffer device */ GRALLOC_USAGE_HW_FB = 0x00001000U, /* buffer should be displayed full-screen on an external display when * possible */ GRALLOC_USAGE_EXTERNAL_DISP = 0x00002000U, /* Must have a hardware-protected path to external display sink for * this buffer. If a hardware-protected path is not available, then * either don't composite only this buffer (preferred) to the * external sink, or (less desirable) do not route the entire * composition to the external sink. */ GRALLOC_USAGE_PROTECTED = 0x00004000U, /* buffer may be used as a cursor */ GRALLOC_USAGE_CURSOR = 0x00008000U, /* buffer will be used with the HW video encoder */ GRALLOC_USAGE_HW_VIDEO_ENCODER = 0x00010000U, /* buffer will be written by the HW camera pipeline */ GRALLOC_USAGE_HW_CAMERA_WRITE = 0x00020000U, /* buffer will be read by the HW camera pipeline */ GRALLOC_USAGE_HW_CAMERA_READ = 0x00040000U, /* buffer will be used as part of zero-shutter-lag queue */ GRALLOC_USAGE_HW_CAMERA_ZSL = 0x00060000U, /* mask for the camera access values */ GRALLOC_USAGE_HW_CAMERA_MASK = 0x00060000U, /* mask for the software usage bit-mask */ GRALLOC_USAGE_HW_MASK = 0x00071F00U, /* buffer will be used as a RenderScript Allocation */ GRALLOC_USAGE_RENDERSCRIPT = 0x00100000U, }; // From Android window.h. /* attributes queriable with query() */ enum { NATIVE_WINDOW_WIDTH = 0, NATIVE_WINDOW_HEIGHT = 1, NATIVE_WINDOW_FORMAT = 2, //... // NATIVE_WINDOW_DEFAULT_WIDTH = 6, //These two return invalid data. // NATIVE_WINDOW_DEFAULT_HEIGHT = 7, }; // From Android window.h. /* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */ enum { //... /* Buffers will be queued after being filled using the CPU */ NATIVE_WINDOW_API_CPU = 2, //... }; // From Android hardware.h. /** * Transformation definitions * * IMPORTANT NOTE: * HAL_TRANSFORM_ROT_90 is applied CLOCKWISE and AFTER HAL_TRANSFORM_FLIP_{H|V}. * */ enum { /* flip source image horizontally (around the vertical axis) */ HAL_TRANSFORM_FLIP_H = 0x01, /* flip source image vertically (around the horizontal axis)*/ HAL_TRANSFORM_FLIP_V = 0x02, /* rotate source image 90 degrees clockwise */ HAL_TRANSFORM_ROT_90 = 0x04, /* rotate source image 180 degrees */ HAL_TRANSFORM_ROT_180 = 0x03, /* rotate source image 270 degrees clockwise */ HAL_TRANSFORM_ROT_270 = 0x07, }; // From Android window.h. /* parameter for NATIVE_WINDOW_SET_BUFFERS_TRANSFORM */ enum { /* flip source image horizontally */ NATIVE_WINDOW_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H, /* flip source image vertically */ NATIVE_WINDOW_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V, /* rotate source image 90 degrees clock-wise */ NATIVE_WINDOW_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90, /* rotate source image 180 degrees */ NATIVE_WINDOW_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180, /* rotate source image 270 degrees clock-wise */ NATIVE_WINDOW_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270, }; // From Android native_handle.h. typedef struct { int version; int num_fds; int num_ints; } NativeHandle;
MrMarshy/ESP32-CAM-Tensorflow-lite-Person-Detect
main/esp/index.h
<gh_stars>1-10 R"(<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>ESP32 OV2460</title> <style> body { font-family: Arial,Helvetica,sans-serif; background: #181818; color: #EFEFEF; font-size: 16px } h2 { font-size: 18px } section.main { display: flex } #menu,section.main { flex-direction: column } #menu { display: none; flex-wrap: nowrap; min-width: 340px; background: #363636; padding: 8px; border-radius: 4px; margin-top: -10px; margin-right: 10px; } #content { display: flex; flex-wrap: wrap; align-items: stretch } figure { padding: 0px; margin: 0; -webkit-margin-before: 0; margin-block-start: 0; -webkit-margin-after: 0; margin-block-end: 0; -webkit-margin-start: 0; margin-inline-start: 0; -webkit-margin-end: 0; margin-inline-end: 0 } figure img { display: block; width: 100%; height: auto; border-radius: 4px; margin-top: 8px; } @media (min-width: 800px) and (orientation:landscape) { #content { display:flex; flex-wrap: nowrap; align-items: stretch } figure img { display: block; max-width: 100%; max-height: calc(100vh - 40px); width: auto; height: auto } figure { padding: 0 0 0 0px; margin: 0; -webkit-margin-before: 0; margin-block-start: 0; -webkit-margin-after: 0; margin-block-end: 0; -webkit-margin-start: 0; margin-inline-start: 0; -webkit-margin-end: 0; margin-inline-end: 0 } } section#buttons { display: flex; flex-wrap: nowrap; justify-content: space-between } #nav-toggle { cursor: pointer; display: block } #nav-toggle-cb { outline: 0; opacity: 0; width: 0; height: 0 } #nav-toggle-cb:checked+#menu { display: flex } .input-group { display: flex; flex-wrap: nowrap; line-height: 22px; margin: 5px 0 } .input-group>label { display: inline-block; padding-right: 10px; min-width: 47% } .input-group input,.input-group select { flex-grow: 1 } .range-max,.range-min { display: inline-block; padding: 0 5px } button { display: block; margin: 5px; padding: 0 12px; border: 0; line-height: 28px; cursor: pointer; color: #fff; background: #ff3034; border-radius: 5px; font-size: 16px; outline: 0 } button:hover { background: #ff494d } button:active { background: #f21c21 } button.disabled { cursor: default; background: #a0a0a0 } input[type=range] { -webkit-appearance: none; width: 100%; height: 22px; background: #363636; cursor: pointer; margin: 0 } input[type=range]:focus { outline: 0 } input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 2px; cursor: pointer; background: #EFEFEF; border-radius: 0; border: 0 solid #EFEFEF } input[type=range]::-webkit-slider-thumb { border: 1px solid rgba(0,0,30,0); height: 22px; width: 22px; border-radius: 50px; background: #ff3034; cursor: pointer; -webkit-appearance: none; margin-top: -11.5px } input[type=range]:focus::-webkit-slider-runnable-track { background: #EFEFEF } input[type=range]::-moz-range-track { width: 100%; height: 2px; cursor: pointer; background: #EFEFEF; border-radius: 0; border: 0 solid #EFEFEF } input[type=range]::-moz-range-thumb { border: 1px solid rgba(0,0,30,0); height: 22px; width: 22px; border-radius: 50px; background: #ff3034; cursor: pointer } input[type=range]::-ms-track { width: 100%; height: 2px; cursor: pointer; background: 0 0; border-color: transparent; color: transparent } input[type=range]::-ms-fill-lower { background: #EFEFEF; border: 0 solid #EFEFEF; border-radius: 0 } input[type=range]::-ms-fill-upper { background: #EFEFEF; border: 0 solid #EFEFEF; border-radius: 0 } input[type=range]::-ms-thumb { border: 1px solid rgba(0,0,30,0); height: 22px; width: 22px; border-radius: 50px; background: #ff3034; cursor: pointer; height: 2px } input[type=range]:focus::-ms-fill-lower { background: #EFEFEF } input[type=range]:focus::-ms-fill-upper { background: #363636 } .switch { display: block; position: relative; line-height: 22px; font-size: 16px; height: 22px } .switch input { outline: 0; opacity: 0; width: 0; height: 0 } .slider { width: 50px; height: 22px; border-radius: 22px; cursor: pointer; background-color: grey } .slider,.slider:before { display: inline-block; transition: .4s } .slider:before { position: relative; content: ""; border-radius: 50%; height: 16px; width: 16px; left: 4px; top: 3px; background-color: #fff } input:checked+.slider { background-color: #ff3034 } input:checked+.slider:before { -webkit-transform: translateX(26px); transform: translateX(26px) } select { border: 1px solid #363636; font-size: 14px; height: 22px; outline: 0; border-radius: 5px } .image-container { position: relative; min-width: 160px } .close { position: absolute; right: 5px; top: 5px; background: #ff3034; width: 16px; height: 16px; border-radius: 100px; color: #fff; text-align: center; line-height: 18px; cursor: pointer } .hidden { display: none } </style> </head> <body> <section class="main"> <div id="logo"> <label for="nav-toggle-cb" id="nav-toggle">&#9776;&nbsp;&nbsp;Toggle OV2640 settings</label> </div> <div id="content"> <div id="sidebar"> <input type="checkbox" id="nav-toggle-cb" checked="checked"> <nav id="menu"> <div class="input-group" id="framesize-group"> <label for="framesize">Resolution</label> <select id="framesize" class="default-action"> <option value="10">UXGA(1600x1200)</option> <option value="9">SXGA(1280x1024)</option> <option value="8">XGA(1024x768)</option> <option value="7">SVGA(800x600)</option> <option value="6">VGA(640x480)</option> <option value="5" selected="selected">CIF(400x296)</option> <option value="4">QVGA(320x240)</option> <option value="3">HQVGA(240x176)</option> <option value="0">QQVGA(160x120)</option> </select> </div> <div class="input-group" id="quality-group"> <label for="quality">Quality</label> <div class="range-min">0</div> <input type="range" id="quality" min="0" max="63" value="10" class="default-action"> <div class="range-max">63</div> </div> <div class="input-group" id="brightness-group"> <label for="brightness">Brightness</label> <div class="range-min">-2</div> <input type="range" id="brightness" min="-2" max="2" value="0" class="default-action"> <div class="range-max">2</div> </div> <div class="input-group" id="contrast-group"> <label for="contrast">Contrast</label> <div class="range-min">-2</div> <input type="range" id="contrast" min="-2" max="2" value="0" class="default-action"> <div class="range-max">2</div> </div> <div class="input-group" id="saturation-group"> <label for="saturation">Saturation</label> <div class="range-min">-2</div> <input type="range" id="saturation" min="-2" max="2" value="0" class="default-action"> <div class="range-max">2</div> </div> <div class="input-group" id="special_effect-group"> <label for="special_effect">Special Effect</label> <select id="special_effect" class="default-action"> <option value="0" selected="selected">No Effect</option> <option value="1">Negative</option> <option value="2">Grayscale</option> <option value="3">Red Tint</option> <option value="4">Green Tint</option> <option value="5">Blue Tint</option> <option value="6">Sepia</option> </select> </div> <div class="input-group" id="awb_gain-group"> <label for="awb_gain">AWB Gain</label> <div class="switch"> <input id="awb_gain" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="awb_gain"></label> </div> </div> <div class="input-group" id="wb_mode-group"> <label for="wb_mode">White Balance</label> <select id="wb_mode" class="default-action"> <option value="-1" selected="selected">Off</option> <option value="0" selected="selected">Auto</option> <option value="1">Sunny</option> <option value="2">Cloudy</option> <option value="3">Office</option> <option value="4">Home</option> </select> </div> <div class="input-group" id="aec-group"> <label for="aec">AEC SENSOR</label> <div class="switch"> <input id="aec" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="aec"></label> </div> </div> <div class="input-group" id="aec2-group"> <label for="aec2">AEC DSP</label> <div class="switch"> <input id="aec2" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="aec2"></label> </div> </div> <div class="input-group" id="ae_level-group"> <label for="ae_level">AE Level</label> <div class="range-min">-2</div> <input type="range" id="ae_level" min="-2" max="2" value="0" class="default-action"> <div class="range-max">2</div> </div> <div class="input-group" id="aec_value-group"> <label for="aec_value">Exposure</label> <div class="range-min">0</div> <input type="range" id="aec_value" min="0" max="1200" value="204" class="default-action"> <div class="range-max">1200</div> </div> <div class="input-group" id="agc-group"> <label for="agc">AGC</label> <div class="switch"> <input id="agc" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="agc"></label> </div> </div> <div class="input-group hidden" id="agc_gain-group"> <label for="agc_gain">Gain</label> <div class="range-min">1x</div> <input type="range" id="agc_gain" min="0" max="30" value="5" class="default-action"> <div class="range-max">31x</div> </div> <div class="input-group" id="gainceiling-group"> <label for="gainceiling">Gain Ceiling</label> <div class="range-min">2x</div> <input type="range" id="gainceiling" min="0" max="6" value="0" class="default-action"> <div class="range-max">128x</div> </div> <div class="input-group" id="bpc-group"> <label for="bpc">BPC</label> <div class="switch"> <input id="bpc" type="checkbox" class="default-action"> <label class="slider" for="bpc"></label> </div> </div> <div class="input-group" id="wpc-group"> <label for="wpc">WPC</label> <div class="switch"> <input id="wpc" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="wpc"></label> </div> </div> <div class="input-group" id="raw_gma-group"> <label for="raw_gma">Raw GMA</label> <div class="switch"> <input id="raw_gma" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="raw_gma"></label> </div> </div> <div class="input-group" id="lenc-group"> <label for="lenc">Lens Correction</label> <div class="switch"> <input id="lenc" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="lenc"></label> </div> </div> <div class="input-group" id="hmirror-group"> <label for="hmirror">H-Mirror</label> <div class="switch"> <input id="hmirror" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="hmirror"></label> </div> </div> <div class="input-group" id="vflip-group"> <label for="vflip">V-Flip</label> <div class="switch"> <input id="vflip" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="vflip"></label> </div> </div> <div class="input-group" id="dcw-group"> <label for="dcw">DCW (Downsize EN)</label> <div class="switch"> <input id="dcw" type="checkbox" class="default-action" checked="checked"> <label class="slider" for="dcw"></label> </div> </div> <div class="input-group" id="interval-group"> <label for="interval">Time-Lapse Interval [ms]</label> <input type="number" id="interval" min="0" max="1000000000" value="1000" class="default-action"> </div> <section id="buttons"> <button id="get-still">Get Still</button> <button id="toggle-lapse">Start Time-Lapse</button> <button id="toggle-stream">Start Stream</button> </section> </nav> </div> <figure> <div id="stream-container" class="image-container hidden"> <div class="close" id="close-stream">×</div> <img id="stream" src=""> </div> </figure> </div> </section> <script> document.addEventListener('DOMContentLoaded', function (event) { var baseHost = document.location.origin var streamUrl = baseHost + ':81' const hide = el => { el.classList.add('hidden') } const show = el => { el.classList.remove('hidden') } const disable = el => { el.classList.add('disabled') el.disabled = true } const enable = el => { el.classList.remove('disabled') el.disabled = false } const updateValue = (el, value, updateRemote) => { updateRemote = updateRemote == null ? true : updateRemote let initialValue if (el.type === 'checkbox') { initialValue = el.checked value = !!value el.checked = value } else { initialValue = el.value el.value = value } if (updateRemote && initialValue !== value) { updateConfig(el); } else if(!updateRemote) { if(el.id === "aec"){ value ? hide(exposure) : show(exposure) } else if(el.id === "agc") { if (value) { show(gainCeiling) hide(agcGain) } else { hide(gainCeiling) show(agcGain) } } else if(el.id === "awb_gain"){ value ? show(wb) : hide(wb) } } } function updateConfig (el) { let value switch (el.type) { case 'checkbox': value = el.checked ? 1 : 0 break case 'range': break case 'select-one': value = el.value break case 'button': break case 'submit': value = '1' break case 'number': value = el.value break default: return } const query = `${baseHost}/control?var=${el.id}&val=${value}` fetch(query) .then(response => { console.log(`request to ${query} finished, status: ${response.status}`) }) } document .querySelectorAll('.close') .forEach(el => { el.onclick = () => { hide(el.parentNode) } }) // read initial values fetch(`${baseHost}/status`) .then(function (response) { return response.json() }) .then(function (state) { document .querySelectorAll('.default-action') .forEach(el => { updateValue(el, state[el.id], false) }) }) const view = document.getElementById('stream') const viewContainer = document.getElementById('stream-container') const stillButton = document.getElementById('get-still') const streamButton = document.getElementById('toggle-stream') const lapseButton = document.getElementById('toggle-lapse') const closeButton = document.getElementById('close-stream') const stopStream = () => { window.stop(); streamButton.innerHTML = 'Start Stream' } const stopLapse = () => { lapseButton.innerHTML = 'Start Time-Lapse' const query = `${baseHost}/stopLapse` fetch(query) .then(response => { console.log(`request to ${query} finished, status: ${response.status}`) }) } const startStream = () => { view.src = `${streamUrl}/stream` show(viewContainer) streamButton.innerHTML = 'Stop Stream' } const startLapse = () => { lapseButton.innerHTML = 'Stop Time-Lapse' const query = `${baseHost}/startLapse` fetch(query) .then(response => { console.log(`request to ${query} finished, status: ${response.status}`) }) } // Attach actions to buttons stillButton.onclick = () => { stopStream() view.src = `${baseHost}/capture?_cb=${Date.now()}` show(viewContainer) } closeButton.onclick = () => { stopStream() hide(viewContainer) } streamButton.onclick = () => { const streamEnabled = streamButton.innerHTML === 'Stop Stream' if (streamEnabled) { stopStream() } else { startStream() } } lapseButton.onclick = () => { const lapseEnabled = lapseButton.innerHTML === 'Stop Time-Lapse' if (lapseEnabled) { stopLapse() } else { startLapse() } //updateConfig(lapseButton) } // Attach default on change action document .querySelectorAll('.default-action') .forEach(el => { el.onchange = () => updateConfig(el) }) // Custom actions // Gain const agc = document.getElementById('agc') const agcGain = document.getElementById('agc_gain-group') const gainCeiling = document.getElementById('gainceiling-group') agc.onchange = () => { updateConfig(agc) if (agc.checked) { show(gainCeiling) hide(agcGain) } else { hide(gainCeiling) show(agcGain) } } // Exposure const aec = document.getElementById('aec') const exposure = document.getElementById('aec_value-group') aec.onchange = () => { updateConfig(aec) aec.checked ? hide(exposure) : show(exposure) } // AWB const awb = document.getElementById('awb_gain') const wb = document.getElementById('wb_mode-group') awb.onchange = () => { updateConfig(awb) awb.checked ? show(wb) : hide(wb) } }) </script> </body> </html> )"
MrMarshy/ESP32-CAM-Tensorflow-lite-Person-Detect
main/esp/app_httpd.h
#ifndef APP_HTTPD_H_ #define APP_HTTPD_H_ void startCameraServer(); #endif // APP_HTTPD_H_
MrMarshy/ESP32-CAM-Tensorflow-lite-Person-Detect
main/esp/wifi_sta.h
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "../main_functions.h" #include "esp_log.h" #include "esp_system.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_system.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_camera.h" #include "esp_log.h" #include "nvs_flash.h" #include "lwip/err.h" #include "lwip/sys.h" #include "app_httpd.h" #ifdef __cplusplus extern "C" { #endif // Set in menuconfig .. or override here #define EXAMPLE_ESP_WIFI_SSID CONFIG_EXAMPLE_WIFI_SSID #define EXAMPLE_ESP_WIFI_PASS CONFIG_EXAMPLE_WIFI_PASSWORD #define EXAMPLE_ESP_MAXIMUM_RETRY 3 void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data); void wifi_init_sta(void); void app_main(); #ifdef __cplusplus } #endif
MrMarshy/ESP32-CAM-Tensorflow-lite-Person-Detect
main/esp/wifi_sta.c
<filename>main/esp/wifi_sta.c /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "../main_functions.h" #include "esp_log.h" #include "esp_system.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_system.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_camera.h" #include "esp_log.h" #include "nvs_flash.h" #include "lwip/err.h" #include "lwip/sys.h" #include "app_httpd.h" #include "wifi_sta.h" /* * WIFI event handler */ static const int WIFI_CONNECTED_BIT = BIT0; static const int WIFI_FAIL_BIT = BIT1; static const char *TAG = "wifi_sta"; static int s_retry_num = 0; // Event group static EventGroupHandle_t s_wifi_event_group; void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { esp_wifi_connect(); } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) { esp_wifi_connect(); s_retry_num++; ESP_LOGI(TAG, "retry to connect to the AP"); } else { xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT); } ESP_LOGI(TAG,"connect to the AP fail"); } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data; ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip)); s_retry_num = 0; xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); } } void wifi_init_sta(void) { s_wifi_event_group = xEventGroupCreate(); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); esp_netif_create_default_wifi_sta(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL)); wifi_config_t wifi_config = { .sta = { .ssid = EXAMPLE_ESP_WIFI_SSID, .password = <PASSWORD>, /* Setting a password implies station will connect to all security modes including WEP/WPA. * However these modes are deprecated and not advisable to be used. Incase your Access point * doesn't support WPA2, these mode can be enabled by commenting below line */ .threshold.authmode = WIFI_AUTH_WPA2_PSK, .pmf_cfg = { .capable = true, .required = false }, }, }; ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) ); ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) ); ESP_ERROR_CHECK(esp_wifi_start() ); ESP_LOGI(TAG, "wifi_init_sta finished."); /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */ EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdFALSE, pdFALSE, portMAX_DELAY); /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually * happened. */ if (bits & WIFI_CONNECTED_BIT) { ESP_LOGI(TAG, "connected to access point"); } else if (bits & WIFI_FAIL_BIT) { ESP_LOGI(TAG, "Failed to connect to access point"); } else { ESP_LOGE(TAG, "UNEXPECTED EVENT"); } ESP_ERROR_CHECK(esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler)); ESP_ERROR_CHECK(esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler)); vEventGroupDelete(s_wifi_event_group); }
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/hash.h
/*********************************************************************** * Copyright (c) 2014 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef SECP256K1_HASH_H #define SECP256K1_HASH_H #include <stdlib.h> #include <stdint.h> typedef struct { uint32_t s[8]; uint32_t buf[16]; /* In big endian */ size_t bytes; } rustsecp256k1_v0_4_0_sha256; static void rustsecp256k1_v0_4_0_sha256_initialize(rustsecp256k1_v0_4_0_sha256 *hash); static void rustsecp256k1_v0_4_0_sha256_write(rustsecp256k1_v0_4_0_sha256 *hash, const unsigned char *data, size_t size); static void rustsecp256k1_v0_4_0_sha256_finalize(rustsecp256k1_v0_4_0_sha256 *hash, unsigned char *out32); typedef struct { rustsecp256k1_v0_4_0_sha256 inner, outer; } rustsecp256k1_v0_4_0_hmac_sha256; static void rustsecp256k1_v0_4_0_hmac_sha256_initialize(rustsecp256k1_v0_4_0_hmac_sha256 *hash, const unsigned char *key, size_t size); static void rustsecp256k1_v0_4_0_hmac_sha256_write(rustsecp256k1_v0_4_0_hmac_sha256 *hash, const unsigned char *data, size_t size); static void rustsecp256k1_v0_4_0_hmac_sha256_finalize(rustsecp256k1_v0_4_0_hmac_sha256 *hash, unsigned char *out32); typedef struct { unsigned char v[32]; unsigned char k[32]; int retry; } rustsecp256k1_v0_4_0_rfc6979_hmac_sha256; static void rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_initialize(rustsecp256k1_v0_4_0_rfc6979_hmac_sha256 *rng, const unsigned char *key, size_t keylen); static void rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_generate(rustsecp256k1_v0_4_0_rfc6979_hmac_sha256 *rng, unsigned char *out, size_t outlen); static void rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_finalize(rustsecp256k1_v0_4_0_rfc6979_hmac_sha256 *rng); #endif /* SECP256K1_HASH_H */
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/scalar.h
/*********************************************************************** * Copyright (c) 2014 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef SECP256K1_SCALAR_H #define SECP256K1_SCALAR_H #include "num.h" #include "util.h" #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" #endif #if defined(EXHAUSTIVE_TEST_ORDER) #include "scalar_low.h" #elif defined(SECP256K1_WIDEMUL_INT128) #include "scalar_4x64.h" #elif defined(SECP256K1_WIDEMUL_INT64) #include "scalar_8x32.h" #else #error "Please select wide multiplication implementation" #endif /** Clear a scalar to prevent the leak of sensitive data. */ static void rustsecp256k1_v0_4_0_scalar_clear(rustsecp256k1_v0_4_0_scalar *r); /** Access bits from a scalar. All requested bits must belong to the same 32-bit limb. */ static unsigned int rustsecp256k1_v0_4_0_scalar_get_bits(const rustsecp256k1_v0_4_0_scalar *a, unsigned int offset, unsigned int count); /** Access bits from a scalar. Not constant time. */ static unsigned int rustsecp256k1_v0_4_0_scalar_get_bits_var(const rustsecp256k1_v0_4_0_scalar *a, unsigned int offset, unsigned int count); /** Set a scalar from a big endian byte array. The scalar will be reduced modulo group order `n`. * In: bin: pointer to a 32-byte array. * Out: r: scalar to be set. * overflow: non-zero if the scalar was bigger or equal to `n` before reduction, zero otherwise (can be NULL). */ static void rustsecp256k1_v0_4_0_scalar_set_b32(rustsecp256k1_v0_4_0_scalar *r, const unsigned char *bin, int *overflow); /** Set a scalar from a big endian byte array and returns 1 if it is a valid * seckey and 0 otherwise. */ static int rustsecp256k1_v0_4_0_scalar_set_b32_seckey(rustsecp256k1_v0_4_0_scalar *r, const unsigned char *bin); /** Set a scalar to an unsigned integer. */ static void rustsecp256k1_v0_4_0_scalar_set_int(rustsecp256k1_v0_4_0_scalar *r, unsigned int v); /** Convert a scalar to a byte array. */ static void rustsecp256k1_v0_4_0_scalar_get_b32(unsigned char *bin, const rustsecp256k1_v0_4_0_scalar* a); /** Add two scalars together (modulo the group order). Returns whether it overflowed. */ static int rustsecp256k1_v0_4_0_scalar_add(rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_scalar *a, const rustsecp256k1_v0_4_0_scalar *b); /** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ static void rustsecp256k1_v0_4_0_scalar_cadd_bit(rustsecp256k1_v0_4_0_scalar *r, unsigned int bit, int flag); /** Multiply two scalars (modulo the group order). */ static void rustsecp256k1_v0_4_0_scalar_mul(rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_scalar *a, const rustsecp256k1_v0_4_0_scalar *b); /** Shift a scalar right by some amount strictly between 0 and 16, returning * the low bits that were shifted off */ static int rustsecp256k1_v0_4_0_scalar_shr_int(rustsecp256k1_v0_4_0_scalar *r, int n); /** Compute the square of a scalar (modulo the group order). */ static void rustsecp256k1_v0_4_0_scalar_sqr(rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_scalar *a); /** Compute the inverse of a scalar (modulo the group order). */ static void rustsecp256k1_v0_4_0_scalar_inverse(rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_scalar *a); /** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ static void rustsecp256k1_v0_4_0_scalar_inverse_var(rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_scalar *a); /** Compute the complement of a scalar (modulo the group order). */ static void rustsecp256k1_v0_4_0_scalar_negate(rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_scalar *a); /** Check whether a scalar equals zero. */ static int rustsecp256k1_v0_4_0_scalar_is_zero(const rustsecp256k1_v0_4_0_scalar *a); /** Check whether a scalar equals one. */ static int rustsecp256k1_v0_4_0_scalar_is_one(const rustsecp256k1_v0_4_0_scalar *a); /** Check whether a scalar, considered as an nonnegative integer, is even. */ static int rustsecp256k1_v0_4_0_scalar_is_even(const rustsecp256k1_v0_4_0_scalar *a); /** Check whether a scalar is higher than the group order divided by 2. */ static int rustsecp256k1_v0_4_0_scalar_is_high(const rustsecp256k1_v0_4_0_scalar *a); /** Conditionally negate a number, in constant time. * Returns -1 if the number was negated, 1 otherwise */ static int rustsecp256k1_v0_4_0_scalar_cond_negate(rustsecp256k1_v0_4_0_scalar *a, int flag); #ifndef USE_NUM_NONE /** Convert a scalar to a number. */ static void rustsecp256k1_v0_4_0_scalar_get_num(rustsecp256k1_v0_4_0_num *r, const rustsecp256k1_v0_4_0_scalar *a); /** Get the order of the group as a number. */ static void rustsecp256k1_v0_4_0_scalar_order_get_num(rustsecp256k1_v0_4_0_num *r); #endif /** Compare two scalars. */ static int rustsecp256k1_v0_4_0_scalar_eq(const rustsecp256k1_v0_4_0_scalar *a, const rustsecp256k1_v0_4_0_scalar *b); /** Find r1 and r2 such that r1+r2*2^128 = k. */ static void rustsecp256k1_v0_4_0_scalar_split_128(rustsecp256k1_v0_4_0_scalar *r1, rustsecp256k1_v0_4_0_scalar *r2, const rustsecp256k1_v0_4_0_scalar *k); /** Find r1 and r2 such that r1+r2*lambda = k, * where r1 and r2 or their negations are maximum 128 bits long (see rustsecp256k1_v0_4_0_ge_mul_lambda). */ static void rustsecp256k1_v0_4_0_scalar_split_lambda(rustsecp256k1_v0_4_0_scalar *r1, rustsecp256k1_v0_4_0_scalar *r2, const rustsecp256k1_v0_4_0_scalar *k); /** Multiply a and b (without taking the modulus!), divide by 2**shift, and round to the nearest integer. Shift must be at least 256. */ static void rustsecp256k1_v0_4_0_scalar_mul_shift_var(rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_scalar *a, const rustsecp256k1_v0_4_0_scalar *b, unsigned int shift); /** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. Both *r and *a must be initialized.*/ static void rustsecp256k1_v0_4_0_scalar_cmov(rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_scalar *a, int flag); #endif /* SECP256K1_SCALAR_H */
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/ecdsa.h
/*********************************************************************** * Copyright (c) 2013, 2014 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef SECP256K1_ECDSA_H #define SECP256K1_ECDSA_H #include <stddef.h> #include "scalar.h" #include "group.h" #include "ecmult.h" static int rustsecp256k1_v0_4_0_ecdsa_sig_parse(rustsecp256k1_v0_4_0_scalar *r, rustsecp256k1_v0_4_0_scalar *s, const unsigned char *sig, size_t size); static int rustsecp256k1_v0_4_0_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_scalar *s); static int rustsecp256k1_v0_4_0_ecdsa_sig_verify(const rustsecp256k1_v0_4_0_ecmult_context *ctx, const rustsecp256k1_v0_4_0_scalar* r, const rustsecp256k1_v0_4_0_scalar* s, const rustsecp256k1_v0_4_0_ge *pubkey, const rustsecp256k1_v0_4_0_scalar *message); static int rustsecp256k1_v0_4_0_ecdsa_sig_sign(const rustsecp256k1_v0_4_0_ecmult_gen_context *ctx, rustsecp256k1_v0_4_0_scalar* r, rustsecp256k1_v0_4_0_scalar* s, const rustsecp256k1_v0_4_0_scalar *seckey, const rustsecp256k1_v0_4_0_scalar *message, const rustsecp256k1_v0_4_0_scalar *nonce, int *recid); #endif /* SECP256K1_ECDSA_H */
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/valgrind_ctime_test.c
/*********************************************************************** * Copyright (c) 2020 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #include <valgrind/memcheck.h> #include "include/secp256k1.h" #include "assumptions.h" #include "util.h" #ifdef ENABLE_MODULE_ECDH # include "include/rustsecp256k1_v0_4_0_ecdh.h" #endif #ifdef ENABLE_MODULE_RECOVERY # include "include/rustsecp256k1_v0_4_0_recovery.h" #endif #ifdef ENABLE_MODULE_EXTRAKEYS # include "include/rustsecp256k1_v0_4_0_extrakeys.h" #endif #ifdef ENABLE_MODULE_SCHNORRSIG #include "include/secp256k1_schnorrsig.h" #endif int main(void) { rustsecp256k1_v0_4_0_context* ctx; rustsecp256k1_v0_4_0_ecdsa_signature signature; rustsecp256k1_v0_4_0_pubkey pubkey; size_t siglen = 74; size_t outputlen = 33; int i; int ret; unsigned char msg[32]; unsigned char key[32]; unsigned char sig[74]; unsigned char spubkey[33]; #ifdef ENABLE_MODULE_RECOVERY rustsecp256k1_v0_4_0_ecdsa_recoverable_signature recoverable_signature; int recid; #endif #ifdef ENABLE_MODULE_EXTRAKEYS rustsecp256k1_v0_4_0_keypair keypair; #endif if (!RUNNING_ON_VALGRIND) { fprintf(stderr, "This test can only usefully be run inside valgrind.\n"); fprintf(stderr, "Usage: libtool --mode=execute valgrind ./valgrind_ctime_test\n"); exit(1); } /** In theory, testing with a single secret input should be sufficient: * If control flow depended on secrets the tool would generate an error. */ for (i = 0; i < 32; i++) { key[i] = i + 65; } for (i = 0; i < 32; i++) { msg[i] = i + 1; } ctx = rustsecp256k1_v0_4_0_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_DECLASSIFY); /* Test keygen. */ VALGRIND_MAKE_MEM_UNDEFINED(key, 32); ret = rustsecp256k1_v0_4_0_ec_pubkey_create(ctx, &pubkey, key); VALGRIND_MAKE_MEM_DEFINED(&pubkey, sizeof(rustsecp256k1_v0_4_0_pubkey)); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret); CHECK(rustsecp256k1_v0_4_0_ec_pubkey_serialize(ctx, spubkey, &outputlen, &pubkey, SECP256K1_EC_COMPRESSED) == 1); /* Test signing. */ VALGRIND_MAKE_MEM_UNDEFINED(key, 32); ret = rustsecp256k1_v0_4_0_ecdsa_sign(ctx, &signature, msg, key, NULL, NULL); VALGRIND_MAKE_MEM_DEFINED(&signature, sizeof(rustsecp256k1_v0_4_0_ecdsa_signature)); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret); CHECK(rustsecp256k1_v0_4_0_ecdsa_signature_serialize_der(ctx, sig, &siglen, &signature)); #ifdef ENABLE_MODULE_ECDH /* Test ECDH. */ VALGRIND_MAKE_MEM_UNDEFINED(key, 32); ret = rustsecp256k1_v0_4_0_ecdh(ctx, msg, &pubkey, key, NULL, NULL); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret == 1); #endif #ifdef ENABLE_MODULE_RECOVERY /* Test signing a recoverable signature. */ VALGRIND_MAKE_MEM_UNDEFINED(key, 32); ret = rustsecp256k1_v0_4_0_ecdsa_sign_recoverable(ctx, &recoverable_signature, msg, key, NULL, NULL); VALGRIND_MAKE_MEM_DEFINED(&recoverable_signature, sizeof(recoverable_signature)); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret); CHECK(rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_serialize_compact(ctx, sig, &recid, &recoverable_signature)); CHECK(recid >= 0 && recid <= 3); #endif VALGRIND_MAKE_MEM_UNDEFINED(key, 32); ret = rustsecp256k1_v0_4_0_ec_seckey_verify(ctx, key); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret == 1); VALGRIND_MAKE_MEM_UNDEFINED(key, 32); ret = rustsecp256k1_v0_4_0_ec_seckey_negate(ctx, key); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret == 1); VALGRIND_MAKE_MEM_UNDEFINED(key, 32); VALGRIND_MAKE_MEM_UNDEFINED(msg, 32); ret = rustsecp256k1_v0_4_0_ec_seckey_tweak_add(ctx, key, msg); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret == 1); VALGRIND_MAKE_MEM_UNDEFINED(key, 32); VALGRIND_MAKE_MEM_UNDEFINED(msg, 32); ret = rustsecp256k1_v0_4_0_ec_seckey_tweak_mul(ctx, key, msg); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret == 1); /* Test context randomisation. Do this last because it leaves the context tainted. */ VALGRIND_MAKE_MEM_UNDEFINED(key, 32); ret = rustsecp256k1_v0_4_0_context_randomize(ctx, key); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret); /* Test keypair_create and keypair_xonly_tweak_add. */ #ifdef ENABLE_MODULE_EXTRAKEYS VALGRIND_MAKE_MEM_UNDEFINED(key, 32); ret = rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, key); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret == 1); /* The tweak is not treated as a secret in keypair_tweak_add */ VALGRIND_MAKE_MEM_DEFINED(msg, 32); ret = rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(ctx, &keypair, msg); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret == 1); #endif #ifdef ENABLE_MODULE_SCHNORRSIG VALGRIND_MAKE_MEM_UNDEFINED(key, 32); ret = rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, key); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret == 1); ret = rustsecp256k1_v0_4_0_schnorrsig_sign(ctx, sig, msg, &keypair, NULL, NULL); VALGRIND_MAKE_MEM_DEFINED(&ret, sizeof(ret)); CHECK(ret == 1); #endif rustsecp256k1_v0_4_0_context_destroy(ctx); return 0; }
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/tests_exhaustive.c
<filename>secp256k1-sys/depend/secp256k1/src/tests_exhaustive.c /*********************************************************************** * Copyright (c) 2016 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" #endif #include <stdio.h> #include <stdlib.h> #include <time.h> #undef USE_ECMULT_STATIC_PRECOMPUTATION #ifndef EXHAUSTIVE_TEST_ORDER /* see group_impl.h for allowable values */ #define EXHAUSTIVE_TEST_ORDER 13 #endif #include "include/secp256k1.h" #include "assumptions.h" #include "group.h" #include "secp256k1.c" #include "testrand_impl.h" static int count = 2; /** stolen from tests.c */ void ge_equals_ge(const rustsecp256k1_v0_4_0_ge *a, const rustsecp256k1_v0_4_0_ge *b) { CHECK(a->infinity == b->infinity); if (a->infinity) { return; } CHECK(rustsecp256k1_v0_4_0_fe_equal_var(&a->x, &b->x)); CHECK(rustsecp256k1_v0_4_0_fe_equal_var(&a->y, &b->y)); } void ge_equals_gej(const rustsecp256k1_v0_4_0_ge *a, const rustsecp256k1_v0_4_0_gej *b) { rustsecp256k1_v0_4_0_fe z2s; rustsecp256k1_v0_4_0_fe u1, u2, s1, s2; CHECK(a->infinity == b->infinity); if (a->infinity) { return; } /* Check a.x * b.z^2 == b.x && a.y * b.z^3 == b.y, to avoid inverses. */ rustsecp256k1_v0_4_0_fe_sqr(&z2s, &b->z); rustsecp256k1_v0_4_0_fe_mul(&u1, &a->x, &z2s); u2 = b->x; rustsecp256k1_v0_4_0_fe_normalize_weak(&u2); rustsecp256k1_v0_4_0_fe_mul(&s1, &a->y, &z2s); rustsecp256k1_v0_4_0_fe_mul(&s1, &s1, &b->z); s2 = b->y; rustsecp256k1_v0_4_0_fe_normalize_weak(&s2); CHECK(rustsecp256k1_v0_4_0_fe_equal_var(&u1, &u2)); CHECK(rustsecp256k1_v0_4_0_fe_equal_var(&s1, &s2)); } void random_fe(rustsecp256k1_v0_4_0_fe *x) { unsigned char bin[32]; do { rustsecp256k1_v0_4_0_testrand256(bin); if (rustsecp256k1_v0_4_0_fe_set_b32(x, bin)) { return; } } while(1); } /** END stolen from tests.c */ static uint32_t num_cores = 1; static uint32_t this_core = 0; SECP256K1_INLINE static int skip_section(uint64_t* iter) { if (num_cores == 1) return 0; *iter += 0xe7037ed1a0b428dbULL; return ((((uint32_t)*iter ^ (*iter >> 32)) * num_cores) >> 32) != this_core; } int rustsecp256k1_v0_4_0_nonce_function_smallint(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int attempt) { rustsecp256k1_v0_4_0_scalar s; int *idata = data; (void)msg32; (void)key32; (void)algo16; /* Some nonces cannot be used because they'd cause s and/or r to be zero. * The signing function has retry logic here that just re-calls the nonce * function with an increased `attempt`. So if attempt > 0 this means we * need to change the nonce to avoid an infinite loop. */ if (attempt > 0) { *idata = (*idata + 1) % EXHAUSTIVE_TEST_ORDER; } rustsecp256k1_v0_4_0_scalar_set_int(&s, *idata); rustsecp256k1_v0_4_0_scalar_get_b32(nonce32, &s); return 1; } void test_exhaustive_endomorphism(const rustsecp256k1_v0_4_0_ge *group) { int i; for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) { rustsecp256k1_v0_4_0_ge res; rustsecp256k1_v0_4_0_ge_mul_lambda(&res, &group[i]); ge_equals_ge(&group[i * EXHAUSTIVE_TEST_LAMBDA % EXHAUSTIVE_TEST_ORDER], &res); } } void test_exhaustive_addition(const rustsecp256k1_v0_4_0_ge *group, const rustsecp256k1_v0_4_0_gej *groupj) { int i, j; uint64_t iter = 0; /* Sanity-check (and check infinity functions) */ CHECK(rustsecp256k1_v0_4_0_ge_is_infinity(&group[0])); CHECK(rustsecp256k1_v0_4_0_gej_is_infinity(&groupj[0])); for (i = 1; i < EXHAUSTIVE_TEST_ORDER; i++) { CHECK(!rustsecp256k1_v0_4_0_ge_is_infinity(&group[i])); CHECK(!rustsecp256k1_v0_4_0_gej_is_infinity(&groupj[i])); } /* Check all addition formulae */ for (j = 0; j < EXHAUSTIVE_TEST_ORDER; j++) { rustsecp256k1_v0_4_0_fe fe_inv; if (skip_section(&iter)) continue; rustsecp256k1_v0_4_0_fe_inv(&fe_inv, &groupj[j].z); for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) { rustsecp256k1_v0_4_0_ge zless_gej; rustsecp256k1_v0_4_0_gej tmp; /* add_var */ rustsecp256k1_v0_4_0_gej_add_var(&tmp, &groupj[i], &groupj[j], NULL); ge_equals_gej(&group[(i + j) % EXHAUSTIVE_TEST_ORDER], &tmp); /* add_ge */ if (j > 0) { rustsecp256k1_v0_4_0_gej_add_ge(&tmp, &groupj[i], &group[j]); ge_equals_gej(&group[(i + j) % EXHAUSTIVE_TEST_ORDER], &tmp); } /* add_ge_var */ rustsecp256k1_v0_4_0_gej_add_ge_var(&tmp, &groupj[i], &group[j], NULL); ge_equals_gej(&group[(i + j) % EXHAUSTIVE_TEST_ORDER], &tmp); /* add_zinv_var */ zless_gej.infinity = groupj[j].infinity; zless_gej.x = groupj[j].x; zless_gej.y = groupj[j].y; rustsecp256k1_v0_4_0_gej_add_zinv_var(&tmp, &groupj[i], &zless_gej, &fe_inv); ge_equals_gej(&group[(i + j) % EXHAUSTIVE_TEST_ORDER], &tmp); } } /* Check doubling */ for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) { rustsecp256k1_v0_4_0_gej tmp; rustsecp256k1_v0_4_0_gej_double(&tmp, &groupj[i]); ge_equals_gej(&group[(2 * i) % EXHAUSTIVE_TEST_ORDER], &tmp); rustsecp256k1_v0_4_0_gej_double_var(&tmp, &groupj[i], NULL); ge_equals_gej(&group[(2 * i) % EXHAUSTIVE_TEST_ORDER], &tmp); } /* Check negation */ for (i = 1; i < EXHAUSTIVE_TEST_ORDER; i++) { rustsecp256k1_v0_4_0_ge tmp; rustsecp256k1_v0_4_0_gej tmpj; rustsecp256k1_v0_4_0_ge_neg(&tmp, &group[i]); ge_equals_ge(&group[EXHAUSTIVE_TEST_ORDER - i], &tmp); rustsecp256k1_v0_4_0_gej_neg(&tmpj, &groupj[i]); ge_equals_gej(&group[EXHAUSTIVE_TEST_ORDER - i], &tmpj); } } void test_exhaustive_ecmult(const rustsecp256k1_v0_4_0_context *ctx, const rustsecp256k1_v0_4_0_ge *group, const rustsecp256k1_v0_4_0_gej *groupj) { int i, j, r_log; uint64_t iter = 0; for (r_log = 1; r_log < EXHAUSTIVE_TEST_ORDER; r_log++) { for (j = 0; j < EXHAUSTIVE_TEST_ORDER; j++) { if (skip_section(&iter)) continue; for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) { rustsecp256k1_v0_4_0_gej tmp; rustsecp256k1_v0_4_0_scalar na, ng; rustsecp256k1_v0_4_0_scalar_set_int(&na, i); rustsecp256k1_v0_4_0_scalar_set_int(&ng, j); rustsecp256k1_v0_4_0_ecmult(&ctx->ecmult_ctx, &tmp, &groupj[r_log], &na, &ng); ge_equals_gej(&group[(i * r_log + j) % EXHAUSTIVE_TEST_ORDER], &tmp); if (i > 0) { rustsecp256k1_v0_4_0_ecmult_const(&tmp, &group[i], &ng, 256); ge_equals_gej(&group[(i * j) % EXHAUSTIVE_TEST_ORDER], &tmp); } } } } } typedef struct { rustsecp256k1_v0_4_0_scalar sc[2]; rustsecp256k1_v0_4_0_ge pt[2]; } ecmult_multi_data; static int ecmult_multi_callback(rustsecp256k1_v0_4_0_scalar *sc, rustsecp256k1_v0_4_0_ge *pt, size_t idx, void *cbdata) { ecmult_multi_data *data = (ecmult_multi_data*) cbdata; *sc = data->sc[idx]; *pt = data->pt[idx]; return 1; } void test_exhaustive_ecmult_multi(const rustsecp256k1_v0_4_0_context *ctx, const rustsecp256k1_v0_4_0_ge *group) { int i, j, k, x, y; uint64_t iter = 0; rustsecp256k1_v0_4_0_scratch *scratch = rustsecp256k1_v0_4_0_scratch_create(&ctx->error_callback, 4096); for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) { for (j = 0; j < EXHAUSTIVE_TEST_ORDER; j++) { for (k = 0; k < EXHAUSTIVE_TEST_ORDER; k++) { for (x = 0; x < EXHAUSTIVE_TEST_ORDER; x++) { if (skip_section(&iter)) continue; for (y = 0; y < EXHAUSTIVE_TEST_ORDER; y++) { rustsecp256k1_v0_4_0_gej tmp; rustsecp256k1_v0_4_0_scalar g_sc; ecmult_multi_data data; rustsecp256k1_v0_4_0_scalar_set_int(&data.sc[0], i); rustsecp256k1_v0_4_0_scalar_set_int(&data.sc[1], j); rustsecp256k1_v0_4_0_scalar_set_int(&g_sc, k); data.pt[0] = group[x]; data.pt[1] = group[y]; rustsecp256k1_v0_4_0_ecmult_multi_var(&ctx->error_callback, &ctx->ecmult_ctx, scratch, &tmp, &g_sc, ecmult_multi_callback, &data, 2); ge_equals_gej(&group[(i * x + j * y + k) % EXHAUSTIVE_TEST_ORDER], &tmp); } } } } } rustsecp256k1_v0_4_0_scratch_destroy(&ctx->error_callback, scratch); } void r_from_k(rustsecp256k1_v0_4_0_scalar *r, const rustsecp256k1_v0_4_0_ge *group, int k, int* overflow) { rustsecp256k1_v0_4_0_fe x; unsigned char x_bin[32]; k %= EXHAUSTIVE_TEST_ORDER; x = group[k].x; rustsecp256k1_v0_4_0_fe_normalize(&x); rustsecp256k1_v0_4_0_fe_get_b32(x_bin, &x); rustsecp256k1_v0_4_0_scalar_set_b32(r, x_bin, overflow); } void test_exhaustive_verify(const rustsecp256k1_v0_4_0_context *ctx, const rustsecp256k1_v0_4_0_ge *group) { int s, r, msg, key; uint64_t iter = 0; for (s = 1; s < EXHAUSTIVE_TEST_ORDER; s++) { for (r = 1; r < EXHAUSTIVE_TEST_ORDER; r++) { for (msg = 1; msg < EXHAUSTIVE_TEST_ORDER; msg++) { for (key = 1; key < EXHAUSTIVE_TEST_ORDER; key++) { rustsecp256k1_v0_4_0_ge nonconst_ge; rustsecp256k1_v0_4_0_ecdsa_signature sig; rustsecp256k1_v0_4_0_pubkey pk; rustsecp256k1_v0_4_0_scalar sk_s, msg_s, r_s, s_s; rustsecp256k1_v0_4_0_scalar s_times_k_s, msg_plus_r_times_sk_s; int k, should_verify; unsigned char msg32[32]; if (skip_section(&iter)) continue; rustsecp256k1_v0_4_0_scalar_set_int(&s_s, s); rustsecp256k1_v0_4_0_scalar_set_int(&r_s, r); rustsecp256k1_v0_4_0_scalar_set_int(&msg_s, msg); rustsecp256k1_v0_4_0_scalar_set_int(&sk_s, key); /* Verify by hand */ /* Run through every k value that gives us this r and check that *one* works. * Note there could be none, there could be multiple, ECDSA is weird. */ should_verify = 0; for (k = 0; k < EXHAUSTIVE_TEST_ORDER; k++) { rustsecp256k1_v0_4_0_scalar check_x_s; r_from_k(&check_x_s, group, k, NULL); if (r_s == check_x_s) { rustsecp256k1_v0_4_0_scalar_set_int(&s_times_k_s, k); rustsecp256k1_v0_4_0_scalar_mul(&s_times_k_s, &s_times_k_s, &s_s); rustsecp256k1_v0_4_0_scalar_mul(&msg_plus_r_times_sk_s, &r_s, &sk_s); rustsecp256k1_v0_4_0_scalar_add(&msg_plus_r_times_sk_s, &msg_plus_r_times_sk_s, &msg_s); should_verify |= rustsecp256k1_v0_4_0_scalar_eq(&s_times_k_s, &msg_plus_r_times_sk_s); } } /* nb we have a "high s" rule */ should_verify &= !rustsecp256k1_v0_4_0_scalar_is_high(&s_s); /* Verify by calling verify */ rustsecp256k1_v0_4_0_ecdsa_signature_save(&sig, &r_s, &s_s); memcpy(&nonconst_ge, &group[sk_s], sizeof(nonconst_ge)); rustsecp256k1_v0_4_0_pubkey_save(&pk, &nonconst_ge); rustsecp256k1_v0_4_0_scalar_get_b32(msg32, &msg_s); CHECK(should_verify == rustsecp256k1_v0_4_0_ecdsa_verify(ctx, &sig, msg32, &pk)); } } } } } void test_exhaustive_sign(const rustsecp256k1_v0_4_0_context *ctx, const rustsecp256k1_v0_4_0_ge *group) { int i, j, k; uint64_t iter = 0; /* Loop */ for (i = 1; i < EXHAUSTIVE_TEST_ORDER; i++) { /* message */ for (j = 1; j < EXHAUSTIVE_TEST_ORDER; j++) { /* key */ if (skip_section(&iter)) continue; for (k = 1; k < EXHAUSTIVE_TEST_ORDER; k++) { /* nonce */ const int starting_k = k; rustsecp256k1_v0_4_0_ecdsa_signature sig; rustsecp256k1_v0_4_0_scalar sk, msg, r, s, expected_r; unsigned char sk32[32], msg32[32]; rustsecp256k1_v0_4_0_scalar_set_int(&msg, i); rustsecp256k1_v0_4_0_scalar_set_int(&sk, j); rustsecp256k1_v0_4_0_scalar_get_b32(sk32, &sk); rustsecp256k1_v0_4_0_scalar_get_b32(msg32, &msg); rustsecp256k1_v0_4_0_ecdsa_sign(ctx, &sig, msg32, sk32, rustsecp256k1_v0_4_0_nonce_function_smallint, &k); rustsecp256k1_v0_4_0_ecdsa_signature_load(ctx, &r, &s, &sig); /* Note that we compute expected_r *after* signing -- this is important * because our nonce-computing function function might change k during * signing. */ r_from_k(&expected_r, group, k, NULL); CHECK(r == expected_r); CHECK((k * s) % EXHAUSTIVE_TEST_ORDER == (i + r * j) % EXHAUSTIVE_TEST_ORDER || (k * (EXHAUSTIVE_TEST_ORDER - s)) % EXHAUSTIVE_TEST_ORDER == (i + r * j) % EXHAUSTIVE_TEST_ORDER); /* Overflow means we've tried every possible nonce */ if (k < starting_k) { break; } } } } /* We would like to verify zero-knowledge here by counting how often every * possible (s, r) tuple appears, but because the group order is larger * than the field order, when coercing the x-values to scalar values, some * appear more often than others, so we are actually not zero-knowledge. * (This effect also appears in the real code, but the difference is on the * order of 1/2^128th the field order, so the deviation is not useful to a * computationally bounded attacker.) */ } #ifdef ENABLE_MODULE_RECOVERY #include "src/modules/recovery/tests_exhaustive_impl.h" #endif #ifdef ENABLE_MODULE_EXTRAKEYS #include "src/modules/extrakeys/tests_exhaustive_impl.h" #endif #ifdef ENABLE_MODULE_SCHNORRSIG #include "src/modules/schnorrsig/tests_exhaustive_impl.h" #endif int main(int argc, char** argv) { int i; rustsecp256k1_v0_4_0_gej groupj[EXHAUSTIVE_TEST_ORDER]; rustsecp256k1_v0_4_0_ge group[EXHAUSTIVE_TEST_ORDER]; unsigned char rand32[32]; rustsecp256k1_v0_4_0_context *ctx; /* Disable buffering for stdout to improve reliability of getting * diagnostic information. Happens right at the start of main because * setbuf must be used before any other operation on the stream. */ setbuf(stdout, NULL); /* Also disable buffering for stderr because it's not guaranteed that it's * unbuffered on all systems. */ setbuf(stderr, NULL); printf("Exhaustive tests for order %lu\n", (unsigned long)EXHAUSTIVE_TEST_ORDER); /* find iteration count */ if (argc > 1) { count = strtol(argv[1], NULL, 0); } printf("test count = %i\n", count); /* find random seed */ rustsecp256k1_v0_4_0_testrand_init(argc > 2 ? argv[2] : NULL); /* set up split processing */ if (argc > 4) { num_cores = strtol(argv[3], NULL, 0); this_core = strtol(argv[4], NULL, 0); if (num_cores < 1 || this_core >= num_cores) { fprintf(stderr, "Usage: %s [count] [seed] [numcores] [thiscore]\n", argv[0]); return 1; } printf("running tests for core %lu (out of [0..%lu])\n", (unsigned long)this_core, (unsigned long)num_cores - 1); } while (count--) { /* Build context */ ctx = rustsecp256k1_v0_4_0_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); rustsecp256k1_v0_4_0_testrand256(rand32); CHECK(rustsecp256k1_v0_4_0_context_randomize(ctx, rand32)); /* Generate the entire group */ rustsecp256k1_v0_4_0_gej_set_infinity(&groupj[0]); rustsecp256k1_v0_4_0_ge_set_gej(&group[0], &groupj[0]); for (i = 1; i < EXHAUSTIVE_TEST_ORDER; i++) { rustsecp256k1_v0_4_0_gej_add_ge(&groupj[i], &groupj[i - 1], &rustsecp256k1_v0_4_0_ge_const_g); rustsecp256k1_v0_4_0_ge_set_gej(&group[i], &groupj[i]); if (count != 0) { /* Set a different random z-value for each Jacobian point, except z=1 is used in the last iteration. */ rustsecp256k1_v0_4_0_fe z; random_fe(&z); rustsecp256k1_v0_4_0_gej_rescale(&groupj[i], &z); } /* Verify against ecmult_gen */ { rustsecp256k1_v0_4_0_scalar scalar_i; rustsecp256k1_v0_4_0_gej generatedj; rustsecp256k1_v0_4_0_ge generated; rustsecp256k1_v0_4_0_scalar_set_int(&scalar_i, i); rustsecp256k1_v0_4_0_ecmult_gen(&ctx->ecmult_gen_ctx, &generatedj, &scalar_i); rustsecp256k1_v0_4_0_ge_set_gej(&generated, &generatedj); CHECK(group[i].infinity == 0); CHECK(generated.infinity == 0); CHECK(rustsecp256k1_v0_4_0_fe_equal_var(&generated.x, &group[i].x)); CHECK(rustsecp256k1_v0_4_0_fe_equal_var(&generated.y, &group[i].y)); } } /* Run the tests */ test_exhaustive_endomorphism(group); test_exhaustive_addition(group, groupj); test_exhaustive_ecmult(ctx, group, groupj); test_exhaustive_ecmult_multi(ctx, group); test_exhaustive_sign(ctx, group); test_exhaustive_verify(ctx, group); #ifdef ENABLE_MODULE_RECOVERY test_exhaustive_recovery(ctx, group); #endif #ifdef ENABLE_MODULE_EXTRAKEYS test_exhaustive_extrakeys(ctx, group); #endif #ifdef ENABLE_MODULE_SCHNORRSIG test_exhaustive_schnorrsig(ctx); #endif rustsecp256k1_v0_4_0_context_destroy(ctx); } rustsecp256k1_v0_4_0_testrand_finish(); printf("no problems found\n"); return 0; }
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/assumptions.h
/*********************************************************************** * Copyright (c) 2020 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef SECP256K1_ASSUMPTIONS_H #define SECP256K1_ASSUMPTIONS_H #include <limits.h> #include "util.h" /* This library, like most software, relies on a number of compiler implementation defined (but not undefined) behaviours. Although the behaviours we require are essentially universal we test them specifically here to reduce the odds of experiencing an unwelcome surprise. */ struct rustsecp256k1_v0_4_0_assumption_checker { /* This uses a trick to implement a static assertion in C89: a type with an array of negative size is not allowed. */ int dummy_array[( /* Bytes are 8 bits. */ (CHAR_BIT == 8) && /* No integer promotion for uint32_t. This ensures that we can multiply uintXX_t values where XX >= 32 without signed overflow, which would be undefined behaviour. */ (UINT_MAX <= UINT32_MAX) && /* Conversions from unsigned to signed outside of the bounds of the signed type are implementation-defined. Verify that they function as reinterpreting the lower bits of the input in two's complement notation. Do this for conversions: - from uint(N)_t to int(N)_t with negative result - from uint(2N)_t to int(N)_t with negative result - from int(2N)_t to int(N)_t with negative result - from int(2N)_t to int(N)_t with positive result */ /* To int8_t. */ ((int8_t)(uint8_t)0xAB == (int8_t)-(int8_t)0x55) && ((int8_t)(uint16_t)0xABCD == (int8_t)-(int8_t)0x33) && ((int8_t)(int16_t)(uint16_t)0xCDEF == (int8_t)(uint8_t)0xEF) && ((int8_t)(int16_t)(uint16_t)0x9234 == (int8_t)(uint8_t)0x34) && /* To int16_t. */ ((int16_t)(uint16_t)0xBCDE == (int16_t)-(int16_t)0x4322) && ((int16_t)(uint32_t)0xA1B2C3D4 == (int16_t)-(int16_t)0x3C2C) && ((int16_t)(int32_t)(uint32_t)0xC1D2E3F4 == (int16_t)(uint16_t)0xE3F4) && ((int16_t)(int32_t)(uint32_t)0x92345678 == (int16_t)(uint16_t)0x5678) && /* To int32_t. */ ((int32_t)(uint32_t)0xB2C3D4E5 == (int32_t)-(int32_t)0x4D3C2B1B) && ((int32_t)(uint64_t)0xA123B456C789D012ULL == (int32_t)-(int32_t)0x38762FEE) && ((int32_t)(int64_t)(uint64_t)0xC1D2E3F4A5B6C7D8ULL == (int32_t)(uint32_t)0xA5B6C7D8) && ((int32_t)(int64_t)(uint64_t)0xABCDEF0123456789ULL == (int32_t)(uint32_t)0x23456789) && /* To int64_t. */ ((int64_t)(uint64_t)0xB123C456D789E012ULL == (int64_t)-(int64_t)0x4EDC3BA928761FEEULL) && #if defined(SECP256K1_WIDEMUL_INT128) ((int64_t)(((uint128_t)0xA1234567B8901234ULL << 64) + 0xC5678901D2345678ULL) == (int64_t)-(int64_t)0x3A9876FE2DCBA988ULL) && (((int64_t)(int128_t)(((uint128_t)0xB1C2D3E4F5A6B7C8ULL << 64) + 0xD9E0F1A2B3C4D5E6ULL)) == (int64_t)(uint64_t)0xD9E0F1A2B3C4D5E6ULL) && (((int64_t)(int128_t)(((uint128_t)0xABCDEF0123456789ULL << 64) + 0x0123456789ABCDEFULL)) == (int64_t)(uint64_t)0x0123456789ABCDEFULL) && /* To int128_t. */ ((int128_t)(((uint128_t)0xB1234567C8901234ULL << 64) + 0xD5678901E2345678ULL) == (int128_t)(-(int128_t)0x8E1648B3F50E80DCULL * 0x8E1648B3F50E80DDULL + 0x5EA688D5482F9464ULL)) && #endif /* Right shift on negative signed values is implementation defined. Verify that it acts as a right shift in two's complement with sign extension (i.e duplicating the top bit into newly added bits). */ ((((int8_t)0xE8) >> 2) == (int8_t)(uint8_t)0xFA) && ((((int16_t)0xE9AC) >> 4) == (int16_t)(uint16_t)0xFE9A) && ((((int32_t)0x937C918A) >> 9) == (int32_t)(uint32_t)0xFFC9BE48) && ((((int64_t)0xA8B72231DF9CF4B9ULL) >> 19) == (int64_t)(uint64_t)0xFFFFF516E4463BF3ULL) && #if defined(SECP256K1_WIDEMUL_INT128) ((((int128_t)(((uint128_t)0xCD833A65684A0DBCULL << 64) + 0xB349312F71EA7637ULL)) >> 39) == (int128_t)(((uint128_t)0xFFFFFFFFFF9B0674ULL << 64) + 0xCAD0941B79669262ULL)) && #endif 1) * 2 - 1]; }; #endif /* SECP256K1_ASSUMPTIONS_H */
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/modules/recovery/main_impl.h
/*********************************************************************** * Copyright (c) 2013-2015 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef SECP256K1_MODULE_RECOVERY_MAIN_H #define SECP256K1_MODULE_RECOVERY_MAIN_H #include "include/secp256k1_recovery.h" static void rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_load(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_scalar* r, rustsecp256k1_v0_4_0_scalar* s, int* recid, const rustsecp256k1_v0_4_0_ecdsa_recoverable_signature* sig) { (void)ctx; if (sizeof(rustsecp256k1_v0_4_0_scalar) == 32) { /* When the rustsecp256k1_v0_4_0_scalar type is exactly 32 byte, use its * representation inside rustsecp256k1_v0_4_0_ecdsa_signature, as conversion is very fast. * Note that rustsecp256k1_v0_4_0_ecdsa_signature_save must use the same representation. */ memcpy(r, &sig->data[0], 32); memcpy(s, &sig->data[32], 32); } else { rustsecp256k1_v0_4_0_scalar_set_b32(r, &sig->data[0], NULL); rustsecp256k1_v0_4_0_scalar_set_b32(s, &sig->data[32], NULL); } *recid = sig->data[64]; } static void rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_save(rustsecp256k1_v0_4_0_ecdsa_recoverable_signature* sig, const rustsecp256k1_v0_4_0_scalar* r, const rustsecp256k1_v0_4_0_scalar* s, int recid) { if (sizeof(rustsecp256k1_v0_4_0_scalar) == 32) { memcpy(&sig->data[0], r, 32); memcpy(&sig->data[32], s, 32); } else { rustsecp256k1_v0_4_0_scalar_get_b32(&sig->data[0], r); rustsecp256k1_v0_4_0_scalar_get_b32(&sig->data[32], s); } sig->data[64] = recid; } int rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_parse_compact(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_ecdsa_recoverable_signature* sig, const unsigned char *input64, int recid) { rustsecp256k1_v0_4_0_scalar r, s; int ret = 1; int overflow = 0; (void)ctx; ARG_CHECK(sig != NULL); ARG_CHECK(input64 != NULL); ARG_CHECK(recid >= 0 && recid <= 3); rustsecp256k1_v0_4_0_scalar_set_b32(&r, &input64[0], &overflow); ret &= !overflow; rustsecp256k1_v0_4_0_scalar_set_b32(&s, &input64[32], &overflow); ret &= !overflow; if (ret) { rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_save(sig, &r, &s, recid); } else { memset(sig, 0, sizeof(*sig)); } return ret; } int rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_serialize_compact(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *output64, int *recid, const rustsecp256k1_v0_4_0_ecdsa_recoverable_signature* sig) { rustsecp256k1_v0_4_0_scalar r, s; (void)ctx; ARG_CHECK(output64 != NULL); ARG_CHECK(sig != NULL); ARG_CHECK(recid != NULL); rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_load(ctx, &r, &s, recid, sig); rustsecp256k1_v0_4_0_scalar_get_b32(&output64[0], &r); rustsecp256k1_v0_4_0_scalar_get_b32(&output64[32], &s); return 1; } int rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_convert(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_ecdsa_signature* sig, const rustsecp256k1_v0_4_0_ecdsa_recoverable_signature* sigin) { rustsecp256k1_v0_4_0_scalar r, s; int recid; (void)ctx; ARG_CHECK(sig != NULL); ARG_CHECK(sigin != NULL); rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, sigin); rustsecp256k1_v0_4_0_ecdsa_signature_save(sig, &r, &s); return 1; } static int rustsecp256k1_v0_4_0_ecdsa_sig_recover(const rustsecp256k1_v0_4_0_ecmult_context *ctx, const rustsecp256k1_v0_4_0_scalar *sigr, const rustsecp256k1_v0_4_0_scalar* sigs, rustsecp256k1_v0_4_0_ge *pubkey, const rustsecp256k1_v0_4_0_scalar *message, int recid) { unsigned char brx[32]; rustsecp256k1_v0_4_0_fe fx; rustsecp256k1_v0_4_0_ge x; rustsecp256k1_v0_4_0_gej xj; rustsecp256k1_v0_4_0_scalar rn, u1, u2; rustsecp256k1_v0_4_0_gej qj; int r; if (rustsecp256k1_v0_4_0_scalar_is_zero(sigr) || rustsecp256k1_v0_4_0_scalar_is_zero(sigs)) { return 0; } rustsecp256k1_v0_4_0_scalar_get_b32(brx, sigr); r = rustsecp256k1_v0_4_0_fe_set_b32(&fx, brx); (void)r; VERIFY_CHECK(r); /* brx comes from a scalar, so is less than the order; certainly less than p */ if (recid & 2) { if (rustsecp256k1_v0_4_0_fe_cmp_var(&fx, &rustsecp256k1_v0_4_0_ecdsa_const_p_minus_order) >= 0) { return 0; } rustsecp256k1_v0_4_0_fe_add(&fx, &rustsecp256k1_v0_4_0_ecdsa_const_order_as_fe); } if (!rustsecp256k1_v0_4_0_ge_set_xo_var(&x, &fx, recid & 1)) { return 0; } rustsecp256k1_v0_4_0_gej_set_ge(&xj, &x); rustsecp256k1_v0_4_0_scalar_inverse_var(&rn, sigr); rustsecp256k1_v0_4_0_scalar_mul(&u1, &rn, message); rustsecp256k1_v0_4_0_scalar_negate(&u1, &u1); rustsecp256k1_v0_4_0_scalar_mul(&u2, &rn, sigs); rustsecp256k1_v0_4_0_ecmult(ctx, &qj, &xj, &u2, &u1); rustsecp256k1_v0_4_0_ge_set_gej_var(pubkey, &qj); return !rustsecp256k1_v0_4_0_gej_is_infinity(&qj); } int rustsecp256k1_v0_4_0_ecdsa_sign_recoverable(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_ecdsa_recoverable_signature *signature, const unsigned char *msghash32, const unsigned char *seckey, rustsecp256k1_v0_4_0_nonce_function noncefp, const void* noncedata) { rustsecp256k1_v0_4_0_scalar r, s; int ret, recid; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); ARG_CHECK(msghash32 != NULL); ARG_CHECK(signature != NULL); ARG_CHECK(seckey != NULL); ret = rustsecp256k1_v0_4_0_ecdsa_sign_inner(ctx, &r, &s, &recid, msghash32, seckey, noncefp, noncedata); rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_save(signature, &r, &s, recid); return ret; } int rustsecp256k1_v0_4_0_ecdsa_recover(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_pubkey *pubkey, const rustsecp256k1_v0_4_0_ecdsa_recoverable_signature *signature, const unsigned char *msghash32) { rustsecp256k1_v0_4_0_ge q; rustsecp256k1_v0_4_0_scalar r, s; rustsecp256k1_v0_4_0_scalar m; int recid; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_context_is_built(&ctx->ecmult_ctx)); ARG_CHECK(msghash32 != NULL); ARG_CHECK(signature != NULL); ARG_CHECK(pubkey != NULL); rustsecp256k1_v0_4_0_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, signature); VERIFY_CHECK(recid >= 0 && recid < 4); /* should have been caught in parse_compact */ rustsecp256k1_v0_4_0_scalar_set_b32(&m, msghash32, NULL); if (rustsecp256k1_v0_4_0_ecdsa_sig_recover(&ctx->ecmult_ctx, &r, &s, &q, &m, recid)) { rustsecp256k1_v0_4_0_pubkey_save(pubkey, &q); return 1; } else { memset(pubkey, 0, sizeof(*pubkey)); return 0; } } #endif /* SECP256K1_MODULE_RECOVERY_MAIN_H */
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/field_impl.h
<filename>secp256k1-sys/depend/secp256k1/src/field_impl.h /*********************************************************************** * Copyright (c) 2013, 2014 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef SECP256K1_FIELD_IMPL_H #define SECP256K1_FIELD_IMPL_H #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" #endif #include "util.h" #include "num.h" #if defined(SECP256K1_WIDEMUL_INT128) #include "field_5x52_impl.h" #elif defined(SECP256K1_WIDEMUL_INT64) #include "field_10x26_impl.h" #else #error "Please select wide multiplication implementation" #endif SECP256K1_INLINE static int rustsecp256k1_v0_4_0_fe_equal(const rustsecp256k1_v0_4_0_fe *a, const rustsecp256k1_v0_4_0_fe *b) { rustsecp256k1_v0_4_0_fe na; rustsecp256k1_v0_4_0_fe_negate(&na, a, 1); rustsecp256k1_v0_4_0_fe_add(&na, b); return rustsecp256k1_v0_4_0_fe_normalizes_to_zero(&na); } SECP256K1_INLINE static int rustsecp256k1_v0_4_0_fe_equal_var(const rustsecp256k1_v0_4_0_fe *a, const rustsecp256k1_v0_4_0_fe *b) { rustsecp256k1_v0_4_0_fe na; rustsecp256k1_v0_4_0_fe_negate(&na, a, 1); rustsecp256k1_v0_4_0_fe_add(&na, b); return rustsecp256k1_v0_4_0_fe_normalizes_to_zero_var(&na); } static int rustsecp256k1_v0_4_0_fe_sqrt(rustsecp256k1_v0_4_0_fe *r, const rustsecp256k1_v0_4_0_fe *a) { /** Given that p is congruent to 3 mod 4, we can compute the square root of * a mod p as the (p+1)/4'th power of a. * * As (p+1)/4 is an even number, it will have the same result for a and for * (-a). Only one of these two numbers actually has a square root however, * so we test at the end by squaring and comparing to the input. * Also because (p+1)/4 is an even number, the computed square root is * itself always a square (a ** ((p+1)/4) is the square of a ** ((p+1)/8)). */ rustsecp256k1_v0_4_0_fe x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1; int j; VERIFY_CHECK(r != a); /** The binary representation of (p + 1)/4 has 3 blocks of 1s, with lengths in * { 2, 22, 223 }. Use an addition chain to calculate 2^n - 1 for each block: * 1, [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223] */ rustsecp256k1_v0_4_0_fe_sqr(&x2, a); rustsecp256k1_v0_4_0_fe_mul(&x2, &x2, a); rustsecp256k1_v0_4_0_fe_sqr(&x3, &x2); rustsecp256k1_v0_4_0_fe_mul(&x3, &x3, a); x6 = x3; for (j=0; j<3; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x6, &x6); } rustsecp256k1_v0_4_0_fe_mul(&x6, &x6, &x3); x9 = x6; for (j=0; j<3; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x9, &x9); } rustsecp256k1_v0_4_0_fe_mul(&x9, &x9, &x3); x11 = x9; for (j=0; j<2; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x11, &x11); } rustsecp256k1_v0_4_0_fe_mul(&x11, &x11, &x2); x22 = x11; for (j=0; j<11; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x22, &x22); } rustsecp256k1_v0_4_0_fe_mul(&x22, &x22, &x11); x44 = x22; for (j=0; j<22; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x44, &x44); } rustsecp256k1_v0_4_0_fe_mul(&x44, &x44, &x22); x88 = x44; for (j=0; j<44; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x88, &x88); } rustsecp256k1_v0_4_0_fe_mul(&x88, &x88, &x44); x176 = x88; for (j=0; j<88; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x176, &x176); } rustsecp256k1_v0_4_0_fe_mul(&x176, &x176, &x88); x220 = x176; for (j=0; j<44; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x220, &x220); } rustsecp256k1_v0_4_0_fe_mul(&x220, &x220, &x44); x223 = x220; for (j=0; j<3; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x223, &x223); } rustsecp256k1_v0_4_0_fe_mul(&x223, &x223, &x3); /* The final result is then assembled using a sliding window over the blocks. */ t1 = x223; for (j=0; j<23; j++) { rustsecp256k1_v0_4_0_fe_sqr(&t1, &t1); } rustsecp256k1_v0_4_0_fe_mul(&t1, &t1, &x22); for (j=0; j<6; j++) { rustsecp256k1_v0_4_0_fe_sqr(&t1, &t1); } rustsecp256k1_v0_4_0_fe_mul(&t1, &t1, &x2); rustsecp256k1_v0_4_0_fe_sqr(&t1, &t1); rustsecp256k1_v0_4_0_fe_sqr(r, &t1); /* Check that a square root was actually calculated */ rustsecp256k1_v0_4_0_fe_sqr(&t1, r); return rustsecp256k1_v0_4_0_fe_equal(&t1, a); } static void rustsecp256k1_v0_4_0_fe_inv(rustsecp256k1_v0_4_0_fe *r, const rustsecp256k1_v0_4_0_fe *a) { rustsecp256k1_v0_4_0_fe x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1; int j; /** The binary representation of (p - 2) has 5 blocks of 1s, with lengths in * { 1, 2, 22, 223 }. Use an addition chain to calculate 2^n - 1 for each block: * [1], [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223] */ rustsecp256k1_v0_4_0_fe_sqr(&x2, a); rustsecp256k1_v0_4_0_fe_mul(&x2, &x2, a); rustsecp256k1_v0_4_0_fe_sqr(&x3, &x2); rustsecp256k1_v0_4_0_fe_mul(&x3, &x3, a); x6 = x3; for (j=0; j<3; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x6, &x6); } rustsecp256k1_v0_4_0_fe_mul(&x6, &x6, &x3); x9 = x6; for (j=0; j<3; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x9, &x9); } rustsecp256k1_v0_4_0_fe_mul(&x9, &x9, &x3); x11 = x9; for (j=0; j<2; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x11, &x11); } rustsecp256k1_v0_4_0_fe_mul(&x11, &x11, &x2); x22 = x11; for (j=0; j<11; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x22, &x22); } rustsecp256k1_v0_4_0_fe_mul(&x22, &x22, &x11); x44 = x22; for (j=0; j<22; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x44, &x44); } rustsecp256k1_v0_4_0_fe_mul(&x44, &x44, &x22); x88 = x44; for (j=0; j<44; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x88, &x88); } rustsecp256k1_v0_4_0_fe_mul(&x88, &x88, &x44); x176 = x88; for (j=0; j<88; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x176, &x176); } rustsecp256k1_v0_4_0_fe_mul(&x176, &x176, &x88); x220 = x176; for (j=0; j<44; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x220, &x220); } rustsecp256k1_v0_4_0_fe_mul(&x220, &x220, &x44); x223 = x220; for (j=0; j<3; j++) { rustsecp256k1_v0_4_0_fe_sqr(&x223, &x223); } rustsecp256k1_v0_4_0_fe_mul(&x223, &x223, &x3); /* The final result is then assembled using a sliding window over the blocks. */ t1 = x223; for (j=0; j<23; j++) { rustsecp256k1_v0_4_0_fe_sqr(&t1, &t1); } rustsecp256k1_v0_4_0_fe_mul(&t1, &t1, &x22); for (j=0; j<5; j++) { rustsecp256k1_v0_4_0_fe_sqr(&t1, &t1); } rustsecp256k1_v0_4_0_fe_mul(&t1, &t1, a); for (j=0; j<3; j++) { rustsecp256k1_v0_4_0_fe_sqr(&t1, &t1); } rustsecp256k1_v0_4_0_fe_mul(&t1, &t1, &x2); for (j=0; j<2; j++) { rustsecp256k1_v0_4_0_fe_sqr(&t1, &t1); } rustsecp256k1_v0_4_0_fe_mul(r, a, &t1); } static void rustsecp256k1_v0_4_0_fe_inv_var(rustsecp256k1_v0_4_0_fe *r, const rustsecp256k1_v0_4_0_fe *a) { #if defined(USE_FIELD_INV_BUILTIN) rustsecp256k1_v0_4_0_fe_inv(r, a); #elif defined(USE_FIELD_INV_NUM) rustsecp256k1_v0_4_0_num n, m; static const rustsecp256k1_v0_4_0_fe negone = SECP256K1_FE_CONST( 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, 0xFFFFFC2EUL ); /* secp256k1 field prime, value p defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */ static const unsigned char prime[32] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F }; unsigned char b[32]; int res; rustsecp256k1_v0_4_0_fe c = *a; rustsecp256k1_v0_4_0_fe_normalize_var(&c); rustsecp256k1_v0_4_0_fe_get_b32(b, &c); rustsecp256k1_v0_4_0_num_set_bin(&n, b, 32); rustsecp256k1_v0_4_0_num_set_bin(&m, prime, 32); rustsecp256k1_v0_4_0_num_mod_inverse(&n, &n, &m); rustsecp256k1_v0_4_0_num_get_bin(b, 32, &n); res = rustsecp256k1_v0_4_0_fe_set_b32(r, b); (void)res; VERIFY_CHECK(res); /* Verify the result is the (unique) valid inverse using non-GMP code. */ rustsecp256k1_v0_4_0_fe_mul(&c, &c, r); rustsecp256k1_v0_4_0_fe_add(&c, &negone); CHECK(rustsecp256k1_v0_4_0_fe_normalizes_to_zero_var(&c)); #else #error "Please select field inverse implementation" #endif } static void rustsecp256k1_v0_4_0_fe_inv_all_var(rustsecp256k1_v0_4_0_fe *r, const rustsecp256k1_v0_4_0_fe *a, size_t len) { rustsecp256k1_v0_4_0_fe u; size_t i; if (len < 1) { return; } VERIFY_CHECK((r + len <= a) || (a + len <= r)); r[0] = a[0]; i = 0; while (++i < len) { rustsecp256k1_v0_4_0_fe_mul(&r[i], &r[i - 1], &a[i]); } rustsecp256k1_v0_4_0_fe_inv_var(&u, &r[--i]); while (i > 0) { size_t j = i--; rustsecp256k1_v0_4_0_fe_mul(&r[j], &r[i], &u); rustsecp256k1_v0_4_0_fe_mul(&u, &u, &a[j]); } r[0] = u; } static int rustsecp256k1_v0_4_0_fe_is_quad_var(const rustsecp256k1_v0_4_0_fe *a) { #ifndef USE_NUM_NONE unsigned char b[32]; rustsecp256k1_v0_4_0_num n; rustsecp256k1_v0_4_0_num m; /* secp256k1 field prime, value p defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */ static const unsigned char prime[32] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F }; rustsecp256k1_v0_4_0_fe c = *a; rustsecp256k1_v0_4_0_fe_normalize_var(&c); rustsecp256k1_v0_4_0_fe_get_b32(b, &c); rustsecp256k1_v0_4_0_num_set_bin(&n, b, 32); rustsecp256k1_v0_4_0_num_set_bin(&m, prime, 32); return rustsecp256k1_v0_4_0_num_jacobi(&n, &m) >= 0; #else rustsecp256k1_v0_4_0_fe r; return rustsecp256k1_v0_4_0_fe_sqrt(&r, a); #endif } static const rustsecp256k1_v0_4_0_fe rustsecp256k1_v0_4_0_fe_one = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1); #endif /* SECP256K1_FIELD_IMPL_H */
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/modules/extrakeys/main_impl.h
/*********************************************************************** * Copyright (c) 2020 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef _SECP256K1_MODULE_EXTRAKEYS_MAIN_ #define _SECP256K1_MODULE_EXTRAKEYS_MAIN_ #include "include/secp256k1.h" #include "include/secp256k1_extrakeys.h" static SECP256K1_INLINE int rustsecp256k1_v0_4_0_xonly_pubkey_load(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_ge *ge, const rustsecp256k1_v0_4_0_xonly_pubkey *pubkey) { return rustsecp256k1_v0_4_0_pubkey_load(ctx, ge, (const rustsecp256k1_v0_4_0_pubkey *) pubkey); } static SECP256K1_INLINE void rustsecp256k1_v0_4_0_xonly_pubkey_save(rustsecp256k1_v0_4_0_xonly_pubkey *pubkey, rustsecp256k1_v0_4_0_ge *ge) { rustsecp256k1_v0_4_0_pubkey_save((rustsecp256k1_v0_4_0_pubkey *) pubkey, ge); } int rustsecp256k1_v0_4_0_xonly_pubkey_parse(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_xonly_pubkey *pubkey, const unsigned char *input32) { rustsecp256k1_v0_4_0_ge pk; rustsecp256k1_v0_4_0_fe x; VERIFY_CHECK(ctx != NULL); ARG_CHECK(pubkey != NULL); memset(pubkey, 0, sizeof(*pubkey)); ARG_CHECK(input32 != NULL); if (!rustsecp256k1_v0_4_0_fe_set_b32(&x, input32)) { return 0; } if (!rustsecp256k1_v0_4_0_ge_set_xo_var(&pk, &x, 0)) { return 0; } if (!rustsecp256k1_v0_4_0_ge_is_in_correct_subgroup(&pk)) { return 0; } rustsecp256k1_v0_4_0_xonly_pubkey_save(pubkey, &pk); return 1; } int rustsecp256k1_v0_4_0_xonly_pubkey_serialize(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *output32, const rustsecp256k1_v0_4_0_xonly_pubkey *pubkey) { rustsecp256k1_v0_4_0_ge pk; VERIFY_CHECK(ctx != NULL); ARG_CHECK(output32 != NULL); memset(output32, 0, 32); ARG_CHECK(pubkey != NULL); if (!rustsecp256k1_v0_4_0_xonly_pubkey_load(ctx, &pk, pubkey)) { return 0; } rustsecp256k1_v0_4_0_fe_get_b32(output32, &pk.x); return 1; } /** Keeps a group element as is if it has an even Y and otherwise negates it. * y_parity is set to 0 in the former case and to 1 in the latter case. * Requires that the coordinates of r are normalized. */ static int rustsecp256k1_v0_4_0_extrakeys_ge_even_y(rustsecp256k1_v0_4_0_ge *r) { int y_parity = 0; VERIFY_CHECK(!rustsecp256k1_v0_4_0_ge_is_infinity(r)); if (rustsecp256k1_v0_4_0_fe_is_odd(&r->y)) { rustsecp256k1_v0_4_0_fe_negate(&r->y, &r->y, 1); y_parity = 1; } return y_parity; } int rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_xonly_pubkey *xonly_pubkey, int *pk_parity, const rustsecp256k1_v0_4_0_pubkey *pubkey) { rustsecp256k1_v0_4_0_ge pk; int tmp; VERIFY_CHECK(ctx != NULL); ARG_CHECK(xonly_pubkey != NULL); ARG_CHECK(pubkey != NULL); if (!rustsecp256k1_v0_4_0_pubkey_load(ctx, &pk, pubkey)) { return 0; } tmp = rustsecp256k1_v0_4_0_extrakeys_ge_even_y(&pk); if (pk_parity != NULL) { *pk_parity = tmp; } rustsecp256k1_v0_4_0_xonly_pubkey_save(xonly_pubkey, &pk); return 1; } int rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_pubkey *output_pubkey, const rustsecp256k1_v0_4_0_xonly_pubkey *internal_pubkey, const unsigned char *tweak32) { rustsecp256k1_v0_4_0_ge pk; VERIFY_CHECK(ctx != NULL); ARG_CHECK(output_pubkey != NULL); memset(output_pubkey, 0, sizeof(*output_pubkey)); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_context_is_built(&ctx->ecmult_ctx)); ARG_CHECK(internal_pubkey != NULL); ARG_CHECK(tweak32 != NULL); if (!rustsecp256k1_v0_4_0_xonly_pubkey_load(ctx, &pk, internal_pubkey) || !rustsecp256k1_v0_4_0_ec_pubkey_tweak_add_helper(&ctx->ecmult_ctx, &pk, tweak32)) { return 0; } rustsecp256k1_v0_4_0_pubkey_save(output_pubkey, &pk); return 1; } int rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(const rustsecp256k1_v0_4_0_context* ctx, const unsigned char *tweaked_pubkey32, int tweaked_pk_parity, const rustsecp256k1_v0_4_0_xonly_pubkey *internal_pubkey, const unsigned char *tweak32) { rustsecp256k1_v0_4_0_ge pk; unsigned char pk_expected32[32]; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_context_is_built(&ctx->ecmult_ctx)); ARG_CHECK(internal_pubkey != NULL); ARG_CHECK(tweaked_pubkey32 != NULL); ARG_CHECK(tweak32 != NULL); if (!rustsecp256k1_v0_4_0_xonly_pubkey_load(ctx, &pk, internal_pubkey) || !rustsecp256k1_v0_4_0_ec_pubkey_tweak_add_helper(&ctx->ecmult_ctx, &pk, tweak32)) { return 0; } rustsecp256k1_v0_4_0_fe_normalize_var(&pk.x); rustsecp256k1_v0_4_0_fe_normalize_var(&pk.y); rustsecp256k1_v0_4_0_fe_get_b32(pk_expected32, &pk.x); return rustsecp256k1_v0_4_0_memcmp_var(&pk_expected32, tweaked_pubkey32, 32) == 0 && rustsecp256k1_v0_4_0_fe_is_odd(&pk.y) == tweaked_pk_parity; } static void rustsecp256k1_v0_4_0_keypair_save(rustsecp256k1_v0_4_0_keypair *keypair, const rustsecp256k1_v0_4_0_scalar *sk, rustsecp256k1_v0_4_0_ge *pk) { rustsecp256k1_v0_4_0_scalar_get_b32(&keypair->data[0], sk); rustsecp256k1_v0_4_0_pubkey_save((rustsecp256k1_v0_4_0_pubkey *)&keypair->data[32], pk); } static int rustsecp256k1_v0_4_0_keypair_seckey_load(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_scalar *sk, const rustsecp256k1_v0_4_0_keypair *keypair) { int ret; ret = rustsecp256k1_v0_4_0_scalar_set_b32_seckey(sk, &keypair->data[0]); /* We can declassify ret here because sk is only zero if a keypair function * failed (which zeroes the keypair) and its return value is ignored. */ rustsecp256k1_v0_4_0_declassify(ctx, &ret, sizeof(ret)); ARG_CHECK(ret); return ret; } /* Load a keypair into pk and sk (if non-NULL). This function declassifies pk * and ARG_CHECKs that the keypair is not invalid. It always initializes sk and * pk with dummy values. */ static int rustsecp256k1_v0_4_0_keypair_load(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_scalar *sk, rustsecp256k1_v0_4_0_ge *pk, const rustsecp256k1_v0_4_0_keypair *keypair) { int ret; const rustsecp256k1_v0_4_0_pubkey *pubkey = (const rustsecp256k1_v0_4_0_pubkey *)&keypair->data[32]; /* Need to declassify the pubkey because pubkey_load ARG_CHECKs if it's * invalid. */ rustsecp256k1_v0_4_0_declassify(ctx, pubkey, sizeof(*pubkey)); ret = rustsecp256k1_v0_4_0_pubkey_load(ctx, pk, pubkey); if (sk != NULL) { ret = ret && rustsecp256k1_v0_4_0_keypair_seckey_load(ctx, sk, keypair); } if (!ret) { *pk = rustsecp256k1_v0_4_0_ge_const_g; if (sk != NULL) { *sk = rustsecp256k1_v0_4_0_scalar_one; } } return ret; } int rustsecp256k1_v0_4_0_keypair_create(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_keypair *keypair, const unsigned char *seckey32) { rustsecp256k1_v0_4_0_scalar sk; rustsecp256k1_v0_4_0_ge pk; int ret = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(keypair != NULL); memset(keypair, 0, sizeof(*keypair)); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); ARG_CHECK(seckey32 != NULL); ret = rustsecp256k1_v0_4_0_ec_pubkey_create_helper(&ctx->ecmult_gen_ctx, &sk, &pk, seckey32); rustsecp256k1_v0_4_0_keypair_save(keypair, &sk, &pk); rustsecp256k1_v0_4_0_memczero(keypair, sizeof(*keypair), !ret); rustsecp256k1_v0_4_0_scalar_clear(&sk); return ret; } int rustsecp256k1_v0_4_0_keypair_pub(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_pubkey *pubkey, const rustsecp256k1_v0_4_0_keypair *keypair) { VERIFY_CHECK(ctx != NULL); ARG_CHECK(pubkey != NULL); memset(pubkey, 0, sizeof(*pubkey)); ARG_CHECK(keypair != NULL); memcpy(pubkey->data, &keypair->data[32], sizeof(*pubkey)); return 1; } int rustsecp256k1_v0_4_0_keypair_xonly_pub(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_xonly_pubkey *pubkey, int *pk_parity, const rustsecp256k1_v0_4_0_keypair *keypair) { rustsecp256k1_v0_4_0_ge pk; int tmp; VERIFY_CHECK(ctx != NULL); ARG_CHECK(pubkey != NULL); memset(pubkey, 0, sizeof(*pubkey)); ARG_CHECK(keypair != NULL); if (!rustsecp256k1_v0_4_0_keypair_load(ctx, NULL, &pk, keypair)) { return 0; } tmp = rustsecp256k1_v0_4_0_extrakeys_ge_even_y(&pk); if (pk_parity != NULL) { *pk_parity = tmp; } rustsecp256k1_v0_4_0_xonly_pubkey_save(pubkey, &pk); return 1; } int rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_keypair *keypair, const unsigned char *tweak32) { rustsecp256k1_v0_4_0_ge pk; rustsecp256k1_v0_4_0_scalar sk; int y_parity; int ret; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_context_is_built(&ctx->ecmult_ctx)); ARG_CHECK(keypair != NULL); ARG_CHECK(tweak32 != NULL); ret = rustsecp256k1_v0_4_0_keypair_load(ctx, &sk, &pk, keypair); memset(keypair, 0, sizeof(*keypair)); y_parity = rustsecp256k1_v0_4_0_extrakeys_ge_even_y(&pk); if (y_parity == 1) { rustsecp256k1_v0_4_0_scalar_negate(&sk, &sk); } ret &= rustsecp256k1_v0_4_0_ec_seckey_tweak_add_helper(&sk, tweak32); ret &= rustsecp256k1_v0_4_0_ec_pubkey_tweak_add_helper(&ctx->ecmult_ctx, &pk, tweak32); rustsecp256k1_v0_4_0_declassify(ctx, &ret, sizeof(ret)); if (ret) { rustsecp256k1_v0_4_0_keypair_save(keypair, &sk, &pk); } rustsecp256k1_v0_4_0_scalar_clear(&sk); return ret; } #endif
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/ecmult_gen_impl.h
<filename>secp256k1-sys/depend/secp256k1/src/ecmult_gen_impl.h /*********************************************************************** * Copyright (c) 2013, 2014, 2015 <NAME>, <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef SECP256K1_ECMULT_GEN_IMPL_H #define SECP256K1_ECMULT_GEN_IMPL_H #include "util.h" #include "scalar.h" #include "group.h" #include "ecmult_gen.h" #include "hash_impl.h" #ifdef USE_ECMULT_STATIC_PRECOMPUTATION #include "ecmult_static_context.h" #endif #ifndef USE_ECMULT_STATIC_PRECOMPUTATION static const size_t SECP256K1_ECMULT_GEN_CONTEXT_PREALLOCATED_SIZE = ROUND_TO_ALIGN(sizeof(*((rustsecp256k1_v0_4_0_ecmult_gen_context*) NULL)->prec)); #else static const size_t SECP256K1_ECMULT_GEN_CONTEXT_PREALLOCATED_SIZE = 0; #endif static void rustsecp256k1_v0_4_0_ecmult_gen_context_init(rustsecp256k1_v0_4_0_ecmult_gen_context *ctx) { ctx->prec = NULL; } static void rustsecp256k1_v0_4_0_ecmult_gen_context_build(rustsecp256k1_v0_4_0_ecmult_gen_context *ctx, void **prealloc) { #ifndef USE_ECMULT_STATIC_PRECOMPUTATION rustsecp256k1_v0_4_0_ge prec[ECMULT_GEN_PREC_N * ECMULT_GEN_PREC_G]; rustsecp256k1_v0_4_0_gej gj; rustsecp256k1_v0_4_0_gej nums_gej; int i, j; size_t const prealloc_size = SECP256K1_ECMULT_GEN_CONTEXT_PREALLOCATED_SIZE; void* const base = *prealloc; #endif if (ctx->prec != NULL) { return; } #ifndef USE_ECMULT_STATIC_PRECOMPUTATION ctx->prec = (rustsecp256k1_v0_4_0_ge_storage (*)[ECMULT_GEN_PREC_N][ECMULT_GEN_PREC_G])manual_alloc(prealloc, prealloc_size, base, prealloc_size); /* get the generator */ rustsecp256k1_v0_4_0_gej_set_ge(&gj, &rustsecp256k1_v0_4_0_ge_const_g); /* Construct a group element with no known corresponding scalar (nothing up my sleeve). */ { static const unsigned char nums_b32[33] = "The scalar for this x is unknown"; rustsecp256k1_v0_4_0_fe nums_x; rustsecp256k1_v0_4_0_ge nums_ge; int r; r = rustsecp256k1_v0_4_0_fe_set_b32(&nums_x, nums_b32); (void)r; VERIFY_CHECK(r); r = rustsecp256k1_v0_4_0_ge_set_xo_var(&nums_ge, &nums_x, 0); (void)r; VERIFY_CHECK(r); rustsecp256k1_v0_4_0_gej_set_ge(&nums_gej, &nums_ge); /* Add G to make the bits in x uniformly distributed. */ rustsecp256k1_v0_4_0_gej_add_ge_var(&nums_gej, &nums_gej, &rustsecp256k1_v0_4_0_ge_const_g, NULL); } /* compute prec. */ { rustsecp256k1_v0_4_0_gej precj[ECMULT_GEN_PREC_N * ECMULT_GEN_PREC_G]; /* Jacobian versions of prec. */ rustsecp256k1_v0_4_0_gej gbase; rustsecp256k1_v0_4_0_gej numsbase; gbase = gj; /* PREC_G^j * G */ numsbase = nums_gej; /* 2^j * nums. */ for (j = 0; j < ECMULT_GEN_PREC_N; j++) { /* Set precj[j*PREC_G .. j*PREC_G+(PREC_G-1)] to (numsbase, numsbase + gbase, ..., numsbase + (PREC_G-1)*gbase). */ precj[j*ECMULT_GEN_PREC_G] = numsbase; for (i = 1; i < ECMULT_GEN_PREC_G; i++) { rustsecp256k1_v0_4_0_gej_add_var(&precj[j*ECMULT_GEN_PREC_G + i], &precj[j*ECMULT_GEN_PREC_G + i - 1], &gbase, NULL); } /* Multiply gbase by PREC_G. */ for (i = 0; i < ECMULT_GEN_PREC_B; i++) { rustsecp256k1_v0_4_0_gej_double_var(&gbase, &gbase, NULL); } /* Multiply numbase by 2. */ rustsecp256k1_v0_4_0_gej_double_var(&numsbase, &numsbase, NULL); if (j == ECMULT_GEN_PREC_N - 2) { /* In the last iteration, numsbase is (1 - 2^j) * nums instead. */ rustsecp256k1_v0_4_0_gej_neg(&numsbase, &numsbase); rustsecp256k1_v0_4_0_gej_add_var(&numsbase, &numsbase, &nums_gej, NULL); } } rustsecp256k1_v0_4_0_ge_set_all_gej_var(prec, precj, ECMULT_GEN_PREC_N * ECMULT_GEN_PREC_G); } for (j = 0; j < ECMULT_GEN_PREC_N; j++) { for (i = 0; i < ECMULT_GEN_PREC_G; i++) { rustsecp256k1_v0_4_0_ge_to_storage(&(*ctx->prec)[j][i], &prec[j*ECMULT_GEN_PREC_G + i]); } } #else (void)prealloc; ctx->prec = (rustsecp256k1_v0_4_0_ge_storage (*)[ECMULT_GEN_PREC_N][ECMULT_GEN_PREC_G])rustsecp256k1_v0_4_0_ecmult_static_context; #endif rustsecp256k1_v0_4_0_ecmult_gen_blind(ctx, NULL); } static int rustsecp256k1_v0_4_0_ecmult_gen_context_is_built(const rustsecp256k1_v0_4_0_ecmult_gen_context* ctx) { return ctx->prec != NULL; } static void rustsecp256k1_v0_4_0_ecmult_gen_context_finalize_memcpy(rustsecp256k1_v0_4_0_ecmult_gen_context *dst, const rustsecp256k1_v0_4_0_ecmult_gen_context *src) { #ifndef USE_ECMULT_STATIC_PRECOMPUTATION if (src->prec != NULL) { /* We cast to void* first to suppress a -Wcast-align warning. */ dst->prec = (rustsecp256k1_v0_4_0_ge_storage (*)[ECMULT_GEN_PREC_N][ECMULT_GEN_PREC_G])(void*)((unsigned char*)dst + ((unsigned char*)src->prec - (unsigned char*)src)); } #else (void)dst, (void)src; #endif } static void rustsecp256k1_v0_4_0_ecmult_gen_context_clear(rustsecp256k1_v0_4_0_ecmult_gen_context *ctx) { rustsecp256k1_v0_4_0_scalar_clear(&ctx->blind); rustsecp256k1_v0_4_0_gej_clear(&ctx->initial); ctx->prec = NULL; } static void rustsecp256k1_v0_4_0_ecmult_gen(const rustsecp256k1_v0_4_0_ecmult_gen_context *ctx, rustsecp256k1_v0_4_0_gej *r, const rustsecp256k1_v0_4_0_scalar *gn) { rustsecp256k1_v0_4_0_ge add; rustsecp256k1_v0_4_0_ge_storage adds; rustsecp256k1_v0_4_0_scalar gnb; int bits; int i, j; memset(&adds, 0, sizeof(adds)); *r = ctx->initial; /* Blind scalar/point multiplication by computing (n-b)G + bG instead of nG. */ rustsecp256k1_v0_4_0_scalar_add(&gnb, gn, &ctx->blind); add.infinity = 0; for (j = 0; j < ECMULT_GEN_PREC_N; j++) { bits = rustsecp256k1_v0_4_0_scalar_get_bits(&gnb, j * ECMULT_GEN_PREC_B, ECMULT_GEN_PREC_B); for (i = 0; i < ECMULT_GEN_PREC_G; i++) { /** This uses a conditional move to avoid any secret data in array indexes. * _Any_ use of secret indexes has been demonstrated to result in timing * sidechannels, even when the cache-line access patterns are uniform. * See also: * "A word of warning", CHES 2013 Rump Session, by <NAME> and <NAME> * (https://cryptojedi.org/peter/data/chesrump-20130822.pdf) and * "Cache Attacks and Countermeasures: the Case of AES", RSA 2006, * by <NAME>, <NAME>, and <NAME> * (https://www.tau.ac.il/~tromer/papers/cache.pdf) */ rustsecp256k1_v0_4_0_ge_storage_cmov(&adds, &(*ctx->prec)[j][i], i == bits); } rustsecp256k1_v0_4_0_ge_from_storage(&add, &adds); rustsecp256k1_v0_4_0_gej_add_ge(r, r, &add); } bits = 0; rustsecp256k1_v0_4_0_ge_clear(&add); rustsecp256k1_v0_4_0_scalar_clear(&gnb); } /* Setup blinding values for rustsecp256k1_v0_4_0_ecmult_gen. */ static void rustsecp256k1_v0_4_0_ecmult_gen_blind(rustsecp256k1_v0_4_0_ecmult_gen_context *ctx, const unsigned char *seed32) { rustsecp256k1_v0_4_0_scalar b; rustsecp256k1_v0_4_0_gej gb; rustsecp256k1_v0_4_0_fe s; unsigned char nonce32[32]; rustsecp256k1_v0_4_0_rfc6979_hmac_sha256 rng; int overflow; unsigned char keydata[64] = {0}; if (seed32 == NULL) { /* When seed is NULL, reset the initial point and blinding value. */ rustsecp256k1_v0_4_0_gej_set_ge(&ctx->initial, &rustsecp256k1_v0_4_0_ge_const_g); rustsecp256k1_v0_4_0_gej_neg(&ctx->initial, &ctx->initial); rustsecp256k1_v0_4_0_scalar_set_int(&ctx->blind, 1); } /* The prior blinding value (if not reset) is chained forward by including it in the hash. */ rustsecp256k1_v0_4_0_scalar_get_b32(nonce32, &ctx->blind); /** Using a CSPRNG allows a failure free interface, avoids needing large amounts of random data, * and guards against weak or adversarial seeds. This is a simpler and safer interface than * asking the caller for blinding values directly and expecting them to retry on failure. */ memcpy(keydata, nonce32, 32); if (seed32 != NULL) { memcpy(keydata + 32, seed32, 32); } rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_initialize(&rng, keydata, seed32 ? 64 : 32); memset(keydata, 0, sizeof(keydata)); /* Accept unobservably small non-uniformity. */ rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); overflow = !rustsecp256k1_v0_4_0_fe_set_b32(&s, nonce32); overflow |= rustsecp256k1_v0_4_0_fe_is_zero(&s); rustsecp256k1_v0_4_0_fe_cmov(&s, &rustsecp256k1_v0_4_0_fe_one, overflow); /* Randomize the projection to defend against multiplier sidechannels. */ rustsecp256k1_v0_4_0_gej_rescale(&ctx->initial, &s); rustsecp256k1_v0_4_0_fe_clear(&s); rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); rustsecp256k1_v0_4_0_scalar_set_b32(&b, nonce32, NULL); /* A blinding value of 0 works, but would undermine the projection hardening. */ rustsecp256k1_v0_4_0_scalar_cmov(&b, &rustsecp256k1_v0_4_0_scalar_one, rustsecp256k1_v0_4_0_scalar_is_zero(&b)); rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_finalize(&rng); memset(nonce32, 0, 32); rustsecp256k1_v0_4_0_ecmult_gen(ctx, &gb, &b); rustsecp256k1_v0_4_0_scalar_negate(&b, &b); ctx->blind = b; ctx->initial = gb; rustsecp256k1_v0_4_0_scalar_clear(&b); rustsecp256k1_v0_4_0_gej_clear(&gb); } #endif /* SECP256K1_ECMULT_GEN_IMPL_H */
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/modules/ecdh/main_impl.h
<reponame>gregdhill/rust-secp256k1<filename>secp256k1-sys/depend/secp256k1/src/modules/ecdh/main_impl.h /*********************************************************************** * Copyright (c) 2015 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef SECP256K1_MODULE_ECDH_MAIN_H #define SECP256K1_MODULE_ECDH_MAIN_H #include "include/secp256k1_ecdh.h" #include "ecmult_const_impl.h" static int ecdh_hash_function_sha256(unsigned char *output, const unsigned char *x32, const unsigned char *y32, void *data) { unsigned char version = (y32[31] & 0x01) | 0x02; rustsecp256k1_v0_4_0_sha256 sha; (void)data; rustsecp256k1_v0_4_0_sha256_initialize(&sha); rustsecp256k1_v0_4_0_sha256_write(&sha, &version, 1); rustsecp256k1_v0_4_0_sha256_write(&sha, x32, 32); rustsecp256k1_v0_4_0_sha256_finalize(&sha, output); return 1; } const rustsecp256k1_v0_4_0_ecdh_hash_function rustsecp256k1_v0_4_0_ecdh_hash_function_sha256 = ecdh_hash_function_sha256; const rustsecp256k1_v0_4_0_ecdh_hash_function rustsecp256k1_v0_4_0_ecdh_hash_function_default = ecdh_hash_function_sha256; int rustsecp256k1_v0_4_0_ecdh(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *output, const rustsecp256k1_v0_4_0_pubkey *point, const unsigned char *scalar, rustsecp256k1_v0_4_0_ecdh_hash_function hashfp, void *data) { int ret = 0; int overflow = 0; rustsecp256k1_v0_4_0_gej res; rustsecp256k1_v0_4_0_ge pt; rustsecp256k1_v0_4_0_scalar s; unsigned char x[32]; unsigned char y[32]; VERIFY_CHECK(ctx != NULL); ARG_CHECK(output != NULL); ARG_CHECK(point != NULL); ARG_CHECK(scalar != NULL); if (hashfp == NULL) { hashfp = rustsecp256k1_v0_4_0_ecdh_hash_function_default; } rustsecp256k1_v0_4_0_pubkey_load(ctx, &pt, point); rustsecp256k1_v0_4_0_scalar_set_b32(&s, scalar, &overflow); overflow |= rustsecp256k1_v0_4_0_scalar_is_zero(&s); rustsecp256k1_v0_4_0_scalar_cmov(&s, &rustsecp256k1_v0_4_0_scalar_one, overflow); rustsecp256k1_v0_4_0_ecmult_const(&res, &pt, &s, 256); rustsecp256k1_v0_4_0_ge_set_gej(&pt, &res); /* Compute a hash of the point */ rustsecp256k1_v0_4_0_fe_normalize(&pt.x); rustsecp256k1_v0_4_0_fe_normalize(&pt.y); rustsecp256k1_v0_4_0_fe_get_b32(x, &pt.x); rustsecp256k1_v0_4_0_fe_get_b32(y, &pt.y); ret = hashfp(output, x, y, data); memset(x, 0, 32); memset(y, 0, 32); rustsecp256k1_v0_4_0_scalar_clear(&s); return !!ret & !overflow; } #endif /* SECP256K1_MODULE_ECDH_MAIN_H */
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/eckey_impl.h
/*********************************************************************** * Copyright (c) 2013, 2014 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef SECP256K1_ECKEY_IMPL_H #define SECP256K1_ECKEY_IMPL_H #include "eckey.h" #include "scalar.h" #include "field.h" #include "group.h" #include "ecmult_gen.h" static int rustsecp256k1_v0_4_0_eckey_pubkey_parse(rustsecp256k1_v0_4_0_ge *elem, const unsigned char *pub, size_t size) { if (size == 33 && (pub[0] == SECP256K1_TAG_PUBKEY_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_ODD)) { rustsecp256k1_v0_4_0_fe x; return rustsecp256k1_v0_4_0_fe_set_b32(&x, pub+1) && rustsecp256k1_v0_4_0_ge_set_xo_var(elem, &x, pub[0] == SECP256K1_TAG_PUBKEY_ODD); } else if (size == 65 && (pub[0] == SECP256K1_TAG_PUBKEY_UNCOMPRESSED || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD)) { rustsecp256k1_v0_4_0_fe x, y; if (!rustsecp256k1_v0_4_0_fe_set_b32(&x, pub+1) || !rustsecp256k1_v0_4_0_fe_set_b32(&y, pub+33)) { return 0; } rustsecp256k1_v0_4_0_ge_set_xy(elem, &x, &y); if ((pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD) && rustsecp256k1_v0_4_0_fe_is_odd(&y) != (pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD)) { return 0; } return rustsecp256k1_v0_4_0_ge_is_valid_var(elem); } else { return 0; } } static int rustsecp256k1_v0_4_0_eckey_pubkey_serialize(rustsecp256k1_v0_4_0_ge *elem, unsigned char *pub, size_t *size, int compressed) { if (rustsecp256k1_v0_4_0_ge_is_infinity(elem)) { return 0; } rustsecp256k1_v0_4_0_fe_normalize_var(&elem->x); rustsecp256k1_v0_4_0_fe_normalize_var(&elem->y); rustsecp256k1_v0_4_0_fe_get_b32(&pub[1], &elem->x); if (compressed) { *size = 33; pub[0] = rustsecp256k1_v0_4_0_fe_is_odd(&elem->y) ? SECP256K1_TAG_PUBKEY_ODD : SECP256K1_TAG_PUBKEY_EVEN; } else { *size = 65; pub[0] = SECP256K1_TAG_PUBKEY_UNCOMPRESSED; rustsecp256k1_v0_4_0_fe_get_b32(&pub[33], &elem->y); } return 1; } static int rustsecp256k1_v0_4_0_eckey_privkey_tweak_add(rustsecp256k1_v0_4_0_scalar *key, const rustsecp256k1_v0_4_0_scalar *tweak) { rustsecp256k1_v0_4_0_scalar_add(key, key, tweak); return !rustsecp256k1_v0_4_0_scalar_is_zero(key); } static int rustsecp256k1_v0_4_0_eckey_pubkey_tweak_add(const rustsecp256k1_v0_4_0_ecmult_context *ctx, rustsecp256k1_v0_4_0_ge *key, const rustsecp256k1_v0_4_0_scalar *tweak) { rustsecp256k1_v0_4_0_gej pt; rustsecp256k1_v0_4_0_scalar one; rustsecp256k1_v0_4_0_gej_set_ge(&pt, key); rustsecp256k1_v0_4_0_scalar_set_int(&one, 1); rustsecp256k1_v0_4_0_ecmult(ctx, &pt, &pt, &one, tweak); if (rustsecp256k1_v0_4_0_gej_is_infinity(&pt)) { return 0; } rustsecp256k1_v0_4_0_ge_set_gej(key, &pt); return 1; } static int rustsecp256k1_v0_4_0_eckey_privkey_tweak_mul(rustsecp256k1_v0_4_0_scalar *key, const rustsecp256k1_v0_4_0_scalar *tweak) { int ret; ret = !rustsecp256k1_v0_4_0_scalar_is_zero(tweak); rustsecp256k1_v0_4_0_scalar_mul(key, key, tweak); return ret; } static int rustsecp256k1_v0_4_0_eckey_pubkey_tweak_mul(const rustsecp256k1_v0_4_0_ecmult_context *ctx, rustsecp256k1_v0_4_0_ge *key, const rustsecp256k1_v0_4_0_scalar *tweak) { rustsecp256k1_v0_4_0_scalar zero; rustsecp256k1_v0_4_0_gej pt; if (rustsecp256k1_v0_4_0_scalar_is_zero(tweak)) { return 0; } rustsecp256k1_v0_4_0_scalar_set_int(&zero, 0); rustsecp256k1_v0_4_0_gej_set_ge(&pt, key); rustsecp256k1_v0_4_0_ecmult(ctx, &pt, &pt, tweak, &zero); rustsecp256k1_v0_4_0_ge_set_gej(key, &pt); return 1; } #endif /* SECP256K1_ECKEY_IMPL_H */
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/modules/extrakeys/tests_impl.h
<reponame>gregdhill/rust-secp256k1<filename>secp256k1-sys/depend/secp256k1/src/modules/extrakeys/tests_impl.h /*********************************************************************** * Copyright (c) 2020 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef _SECP256K1_MODULE_EXTRAKEYS_TESTS_ #define _SECP256K1_MODULE_EXTRAKEYS_TESTS_ #include "secp256k1_extrakeys.h" static rustsecp256k1_v0_4_0_context* api_test_context(int flags, int *ecount) { rustsecp256k1_v0_4_0_context *ctx0 = rustsecp256k1_v0_4_0_context_create(flags); rustsecp256k1_v0_4_0_context_set_error_callback(ctx0, counting_illegal_callback_fn, ecount); rustsecp256k1_v0_4_0_context_set_illegal_callback(ctx0, counting_illegal_callback_fn, ecount); return ctx0; } void test_xonly_pubkey(void) { rustsecp256k1_v0_4_0_pubkey pk; rustsecp256k1_v0_4_0_xonly_pubkey xonly_pk, xonly_pk_tmp; rustsecp256k1_v0_4_0_ge pk1; rustsecp256k1_v0_4_0_ge pk2; rustsecp256k1_v0_4_0_fe y; unsigned char sk[32]; unsigned char xy_sk[32]; unsigned char buf32[32]; unsigned char ones32[32]; unsigned char zeros64[64] = { 0 }; int pk_parity; int i; int ecount; rustsecp256k1_v0_4_0_context *none = api_test_context(SECP256K1_CONTEXT_NONE, &ecount); rustsecp256k1_v0_4_0_context *sign = api_test_context(SECP256K1_CONTEXT_SIGN, &ecount); rustsecp256k1_v0_4_0_context *verify = api_test_context(SECP256K1_CONTEXT_VERIFY, &ecount); rustsecp256k1_v0_4_0_testrand256(sk); memset(ones32, 0xFF, 32); rustsecp256k1_v0_4_0_testrand256(xy_sk); CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(sign, &pk, sk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, &xonly_pk, &pk_parity, &pk) == 1); /* Test xonly_pubkey_from_pubkey */ ecount = 0; CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, &xonly_pk, &pk_parity, &pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(sign, &xonly_pk, &pk_parity, &pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(verify, &xonly_pk, &pk_parity, &pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, NULL, &pk_parity, &pk) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, &xonly_pk, NULL, &pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, &xonly_pk, &pk_parity, NULL) == 0); CHECK(ecount == 2); memset(&pk, 0, sizeof(pk)); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, &xonly_pk, &pk_parity, &pk) == 0); CHECK(ecount == 3); /* Choose a secret key such that the resulting pubkey and xonly_pubkey match. */ memset(sk, 0, sizeof(sk)); sk[0] = 1; CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(ctx, &pk, sk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(ctx, &xonly_pk, &pk_parity, &pk) == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&pk, &xonly_pk, sizeof(pk)) == 0); CHECK(pk_parity == 0); /* Choose a secret key such that pubkey and xonly_pubkey are each others * negation. */ sk[0] = 2; CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(ctx, &pk, sk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(ctx, &xonly_pk, &pk_parity, &pk) == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&xonly_pk, &pk, sizeof(xonly_pk)) != 0); CHECK(pk_parity == 1); rustsecp256k1_v0_4_0_pubkey_load(ctx, &pk1, &pk); rustsecp256k1_v0_4_0_pubkey_load(ctx, &pk2, (rustsecp256k1_v0_4_0_pubkey *) &xonly_pk); CHECK(rustsecp256k1_v0_4_0_fe_equal(&pk1.x, &pk2.x) == 1); rustsecp256k1_v0_4_0_fe_negate(&y, &pk2.y, 1); CHECK(rustsecp256k1_v0_4_0_fe_equal(&pk1.y, &y) == 1); /* Test xonly_pubkey_serialize and xonly_pubkey_parse */ ecount = 0; CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(none, NULL, &xonly_pk) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(none, buf32, NULL) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(buf32, zeros64, 32) == 0); CHECK(ecount == 2); { /* A pubkey filled with 0s will fail to serialize due to pubkey_load * special casing. */ rustsecp256k1_v0_4_0_xonly_pubkey pk_tmp; memset(&pk_tmp, 0, sizeof(pk_tmp)); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(none, buf32, &pk_tmp) == 0); } /* pubkey_load called illegal callback */ CHECK(ecount == 3); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(none, buf32, &xonly_pk) == 1); ecount = 0; CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_parse(none, NULL, buf32) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_parse(none, &xonly_pk, NULL) == 0); CHECK(ecount == 2); /* Serialization and parse roundtrip */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, &xonly_pk, NULL, &pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(ctx, buf32, &xonly_pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_parse(ctx, &xonly_pk_tmp, buf32) == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&xonly_pk, &xonly_pk_tmp, sizeof(xonly_pk)) == 0); /* Test parsing invalid field elements */ memset(&xonly_pk, 1, sizeof(xonly_pk)); /* Overflowing field element */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_parse(none, &xonly_pk, ones32) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&xonly_pk, zeros64, sizeof(xonly_pk)) == 0); memset(&xonly_pk, 1, sizeof(xonly_pk)); /* There's no point with x-coordinate 0 on secp256k1 */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_parse(none, &xonly_pk, zeros64) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&xonly_pk, zeros64, sizeof(xonly_pk)) == 0); /* If a random 32-byte string can not be parsed with ec_pubkey_parse * (because interpreted as X coordinate it does not correspond to a point on * the curve) then xonly_pubkey_parse should fail as well. */ for (i = 0; i < count; i++) { unsigned char rand33[33]; rustsecp256k1_v0_4_0_testrand256(&rand33[1]); rand33[0] = SECP256K1_TAG_PUBKEY_EVEN; if (!rustsecp256k1_v0_4_0_ec_pubkey_parse(ctx, &pk, rand33, 33)) { memset(&xonly_pk, 1, sizeof(xonly_pk)); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_parse(ctx, &xonly_pk, &rand33[1]) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&xonly_pk, zeros64, sizeof(xonly_pk)) == 0); } else { CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_parse(ctx, &xonly_pk, &rand33[1]) == 1); } } CHECK(ecount == 2); rustsecp256k1_v0_4_0_context_destroy(none); rustsecp256k1_v0_4_0_context_destroy(sign); rustsecp256k1_v0_4_0_context_destroy(verify); } void test_xonly_pubkey_tweak(void) { unsigned char zeros64[64] = { 0 }; unsigned char overflows[32]; unsigned char sk[32]; rustsecp256k1_v0_4_0_pubkey internal_pk; rustsecp256k1_v0_4_0_xonly_pubkey internal_xonly_pk; rustsecp256k1_v0_4_0_pubkey output_pk; int pk_parity; unsigned char tweak[32]; int i; int ecount; rustsecp256k1_v0_4_0_context *none = api_test_context(SECP256K1_CONTEXT_NONE, &ecount); rustsecp256k1_v0_4_0_context *sign = api_test_context(SECP256K1_CONTEXT_SIGN, &ecount); rustsecp256k1_v0_4_0_context *verify = api_test_context(SECP256K1_CONTEXT_VERIFY, &ecount); memset(overflows, 0xff, sizeof(overflows)); rustsecp256k1_v0_4_0_testrand256(tweak); rustsecp256k1_v0_4_0_testrand256(sk); CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(ctx, &internal_pk, sk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, &internal_xonly_pk, &pk_parity, &internal_pk) == 1); ecount = 0; CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(none, &output_pk, &internal_xonly_pk, tweak) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(sign, &output_pk, &internal_xonly_pk, tweak) == 0); CHECK(ecount == 2); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, &output_pk, &internal_xonly_pk, tweak) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, NULL, &internal_xonly_pk, tweak) == 0); CHECK(ecount == 3); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, &output_pk, NULL, tweak) == 0); CHECK(ecount == 4); /* NULL internal_xonly_pk zeroes the output_pk */ CHECK(rustsecp256k1_v0_4_0_memcmp_var(&output_pk, zeros64, sizeof(output_pk)) == 0); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, &output_pk, &internal_xonly_pk, NULL) == 0); CHECK(ecount == 5); /* NULL tweak zeroes the output_pk */ CHECK(rustsecp256k1_v0_4_0_memcmp_var(&output_pk, zeros64, sizeof(output_pk)) == 0); /* Invalid tweak zeroes the output_pk */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, &output_pk, &internal_xonly_pk, overflows) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&output_pk, zeros64, sizeof(output_pk)) == 0); /* A zero tweak is fine */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, &output_pk, &internal_xonly_pk, zeros64) == 1); /* Fails if the resulting key was infinity */ for (i = 0; i < count; i++) { rustsecp256k1_v0_4_0_scalar scalar_tweak; /* Because sk may be negated before adding, we need to try with tweak = * sk as well as tweak = -sk. */ rustsecp256k1_v0_4_0_scalar_set_b32(&scalar_tweak, sk, NULL); rustsecp256k1_v0_4_0_scalar_negate(&scalar_tweak, &scalar_tweak); rustsecp256k1_v0_4_0_scalar_get_b32(tweak, &scalar_tweak); CHECK((rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, &output_pk, &internal_xonly_pk, sk) == 0) || (rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, &output_pk, &internal_xonly_pk, tweak) == 0)); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&output_pk, zeros64, sizeof(output_pk)) == 0); } /* Invalid pk with a valid tweak */ memset(&internal_xonly_pk, 0, sizeof(internal_xonly_pk)); rustsecp256k1_v0_4_0_testrand256(tweak); ecount = 0; CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, &output_pk, &internal_xonly_pk, tweak) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&output_pk, zeros64, sizeof(output_pk)) == 0); rustsecp256k1_v0_4_0_context_destroy(none); rustsecp256k1_v0_4_0_context_destroy(sign); rustsecp256k1_v0_4_0_context_destroy(verify); } void test_xonly_pubkey_tweak_check(void) { unsigned char zeros64[64] = { 0 }; unsigned char overflows[32]; unsigned char sk[32]; rustsecp256k1_v0_4_0_pubkey internal_pk; rustsecp256k1_v0_4_0_xonly_pubkey internal_xonly_pk; rustsecp256k1_v0_4_0_pubkey output_pk; rustsecp256k1_v0_4_0_xonly_pubkey output_xonly_pk; unsigned char output_pk32[32]; unsigned char buf32[32]; int pk_parity; unsigned char tweak[32]; int ecount; rustsecp256k1_v0_4_0_context *none = api_test_context(SECP256K1_CONTEXT_NONE, &ecount); rustsecp256k1_v0_4_0_context *sign = api_test_context(SECP256K1_CONTEXT_SIGN, &ecount); rustsecp256k1_v0_4_0_context *verify = api_test_context(SECP256K1_CONTEXT_VERIFY, &ecount); memset(overflows, 0xff, sizeof(overflows)); rustsecp256k1_v0_4_0_testrand256(tweak); rustsecp256k1_v0_4_0_testrand256(sk); CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(ctx, &internal_pk, sk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, &internal_xonly_pk, &pk_parity, &internal_pk) == 1); ecount = 0; CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(verify, &output_pk, &internal_xonly_pk, tweak) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(verify, &output_xonly_pk, &pk_parity, &output_pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(ctx, buf32, &output_xonly_pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(none, buf32, pk_parity, &internal_xonly_pk, tweak) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(sign, buf32, pk_parity, &internal_xonly_pk, tweak) == 0); CHECK(ecount == 2); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(verify, buf32, pk_parity, &internal_xonly_pk, tweak) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(verify, NULL, pk_parity, &internal_xonly_pk, tweak) == 0); CHECK(ecount == 3); /* invalid pk_parity value */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(verify, buf32, 2, &internal_xonly_pk, tweak) == 0); CHECK(ecount == 3); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(verify, buf32, pk_parity, NULL, tweak) == 0); CHECK(ecount == 4); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(verify, buf32, pk_parity, &internal_xonly_pk, NULL) == 0); CHECK(ecount == 5); memset(tweak, 1, sizeof(tweak)); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(ctx, &internal_xonly_pk, NULL, &internal_pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(ctx, &output_pk, &internal_xonly_pk, tweak) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(ctx, &output_xonly_pk, &pk_parity, &output_pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(ctx, output_pk32, &output_xonly_pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(ctx, output_pk32, pk_parity, &internal_xonly_pk, tweak) == 1); /* Wrong pk_parity */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(ctx, output_pk32, !pk_parity, &internal_xonly_pk, tweak) == 0); /* Wrong public key */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(ctx, buf32, &internal_xonly_pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(ctx, buf32, pk_parity, &internal_xonly_pk, tweak) == 0); /* Overflowing tweak not allowed */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(ctx, output_pk32, pk_parity, &internal_xonly_pk, overflows) == 0); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(ctx, &output_pk, &internal_xonly_pk, overflows) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&output_pk, zeros64, sizeof(output_pk)) == 0); CHECK(ecount == 5); rustsecp256k1_v0_4_0_context_destroy(none); rustsecp256k1_v0_4_0_context_destroy(sign); rustsecp256k1_v0_4_0_context_destroy(verify); } /* Starts with an initial pubkey and recursively creates N_PUBKEYS - 1 * additional pubkeys by calling tweak_add. Then verifies every tweak starting * from the last pubkey. */ #define N_PUBKEYS 32 void test_xonly_pubkey_tweak_recursive(void) { unsigned char sk[32]; rustsecp256k1_v0_4_0_pubkey pk[N_PUBKEYS]; unsigned char pk_serialized[32]; unsigned char tweak[N_PUBKEYS - 1][32]; int i; rustsecp256k1_v0_4_0_testrand256(sk); CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(ctx, &pk[0], sk) == 1); /* Add tweaks */ for (i = 0; i < N_PUBKEYS - 1; i++) { rustsecp256k1_v0_4_0_xonly_pubkey xonly_pk; memset(tweak[i], i + 1, sizeof(tweak[i])); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(ctx, &xonly_pk, NULL, &pk[i]) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(ctx, &pk[i + 1], &xonly_pk, tweak[i]) == 1); } /* Verify tweaks */ for (i = N_PUBKEYS - 1; i > 0; i--) { rustsecp256k1_v0_4_0_xonly_pubkey xonly_pk; int pk_parity; CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(ctx, &xonly_pk, &pk_parity, &pk[i]) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(ctx, pk_serialized, &xonly_pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(ctx, &xonly_pk, NULL, &pk[i - 1]) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(ctx, pk_serialized, pk_parity, &xonly_pk, tweak[i - 1]) == 1); } } #undef N_PUBKEYS void test_keypair(void) { unsigned char sk[32]; unsigned char zeros96[96] = { 0 }; unsigned char overflows[32]; rustsecp256k1_v0_4_0_keypair keypair; rustsecp256k1_v0_4_0_pubkey pk, pk_tmp; rustsecp256k1_v0_4_0_xonly_pubkey xonly_pk, xonly_pk_tmp; int pk_parity, pk_parity_tmp; int ecount; rustsecp256k1_v0_4_0_context *none = api_test_context(SECP256K1_CONTEXT_NONE, &ecount); rustsecp256k1_v0_4_0_context *sign = api_test_context(SECP256K1_CONTEXT_SIGN, &ecount); rustsecp256k1_v0_4_0_context *verify = api_test_context(SECP256K1_CONTEXT_VERIFY, &ecount); CHECK(sizeof(zeros96) == sizeof(keypair)); memset(overflows, 0xFF, sizeof(overflows)); /* Test keypair_create */ ecount = 0; rustsecp256k1_v0_4_0_testrand256(sk); CHECK(rustsecp256k1_v0_4_0_keypair_create(none, &keypair, sk) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(zeros96, &keypair, sizeof(keypair)) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_keypair_create(verify, &keypair, sk) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(zeros96, &keypair, sizeof(keypair)) == 0); CHECK(ecount == 2); CHECK(rustsecp256k1_v0_4_0_keypair_create(sign, &keypair, sk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_create(sign, NULL, sk) == 0); CHECK(ecount == 3); CHECK(rustsecp256k1_v0_4_0_keypair_create(sign, &keypair, NULL) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(zeros96, &keypair, sizeof(keypair)) == 0); CHECK(ecount == 4); /* Invalid secret key */ CHECK(rustsecp256k1_v0_4_0_keypair_create(sign, &keypair, zeros96) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(zeros96, &keypair, sizeof(keypair)) == 0); CHECK(rustsecp256k1_v0_4_0_keypair_create(sign, &keypair, overflows) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(zeros96, &keypair, sizeof(keypair)) == 0); /* Test keypair_pub */ ecount = 0; rustsecp256k1_v0_4_0_testrand256(sk); CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, sk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_pub(none, &pk, &keypair) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_pub(none, NULL, &keypair) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_keypair_pub(none, &pk, NULL) == 0); CHECK(ecount == 2); CHECK(rustsecp256k1_v0_4_0_memcmp_var(zeros96, &pk, sizeof(pk)) == 0); /* Using an invalid keypair is fine for keypair_pub */ memset(&keypair, 0, sizeof(keypair)); CHECK(rustsecp256k1_v0_4_0_keypair_pub(none, &pk, &keypair) == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(zeros96, &pk, sizeof(pk)) == 0); /* keypair holds the same pubkey as pubkey_create */ CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(sign, &pk, sk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_create(sign, &keypair, sk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_pub(none, &pk_tmp, &keypair) == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&pk, &pk_tmp, sizeof(pk)) == 0); /** Test keypair_xonly_pub **/ ecount = 0; rustsecp256k1_v0_4_0_testrand256(sk); CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, sk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(none, &xonly_pk, &pk_parity, &keypair) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(none, NULL, &pk_parity, &keypair) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(none, &xonly_pk, NULL, &keypair) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(none, &xonly_pk, &pk_parity, NULL) == 0); CHECK(ecount == 2); CHECK(rustsecp256k1_v0_4_0_memcmp_var(zeros96, &xonly_pk, sizeof(xonly_pk)) == 0); /* Using an invalid keypair will set the xonly_pk to 0 (first reset * xonly_pk). */ CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(none, &xonly_pk, &pk_parity, &keypair) == 1); memset(&keypair, 0, sizeof(keypair)); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(none, &xonly_pk, &pk_parity, &keypair) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(zeros96, &xonly_pk, sizeof(xonly_pk)) == 0); CHECK(ecount == 3); /** keypair holds the same xonly pubkey as pubkey_create **/ CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(sign, &pk, sk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(none, &xonly_pk, &pk_parity, &pk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_create(sign, &keypair, sk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(none, &xonly_pk_tmp, &pk_parity_tmp, &keypair) == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&xonly_pk, &xonly_pk_tmp, sizeof(pk)) == 0); CHECK(pk_parity == pk_parity_tmp); rustsecp256k1_v0_4_0_context_destroy(none); rustsecp256k1_v0_4_0_context_destroy(sign); rustsecp256k1_v0_4_0_context_destroy(verify); } void test_keypair_add(void) { unsigned char sk[32]; rustsecp256k1_v0_4_0_keypair keypair; unsigned char overflows[32]; unsigned char zeros96[96] = { 0 }; unsigned char tweak[32]; int i; int ecount = 0; rustsecp256k1_v0_4_0_context *none = api_test_context(SECP256K1_CONTEXT_NONE, &ecount); rustsecp256k1_v0_4_0_context *sign = api_test_context(SECP256K1_CONTEXT_SIGN, &ecount); rustsecp256k1_v0_4_0_context *verify = api_test_context(SECP256K1_CONTEXT_VERIFY, &ecount); CHECK(sizeof(zeros96) == sizeof(keypair)); rustsecp256k1_v0_4_0_testrand256(sk); rustsecp256k1_v0_4_0_testrand256(tweak); memset(overflows, 0xFF, 32); CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, sk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(none, &keypair, tweak) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(sign, &keypair, tweak) == 0); CHECK(ecount == 2); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(verify, &keypair, tweak) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(verify, NULL, tweak) == 0); CHECK(ecount == 3); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(verify, &keypair, NULL) == 0); CHECK(ecount == 4); /* This does not set the keypair to zeroes */ CHECK(rustsecp256k1_v0_4_0_memcmp_var(&keypair, zeros96, sizeof(keypair)) != 0); /* Invalid tweak zeroes the keypair */ CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, sk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(ctx, &keypair, overflows) == 0); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&keypair, zeros96, sizeof(keypair)) == 0); /* A zero tweak is fine */ CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, sk) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(ctx, &keypair, zeros96) == 1); /* Fails if the resulting keypair was (sk=0, pk=infinity) */ for (i = 0; i < count; i++) { rustsecp256k1_v0_4_0_scalar scalar_tweak; rustsecp256k1_v0_4_0_keypair keypair_tmp; rustsecp256k1_v0_4_0_testrand256(sk); CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, sk) == 1); memcpy(&keypair_tmp, &keypair, sizeof(keypair)); /* Because sk may be negated before adding, we need to try with tweak = * sk as well as tweak = -sk. */ rustsecp256k1_v0_4_0_scalar_set_b32(&scalar_tweak, sk, NULL); rustsecp256k1_v0_4_0_scalar_negate(&scalar_tweak, &scalar_tweak); rustsecp256k1_v0_4_0_scalar_get_b32(tweak, &scalar_tweak); CHECK((rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(ctx, &keypair, sk) == 0) || (rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(ctx, &keypair_tmp, tweak) == 0)); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&keypair, zeros96, sizeof(keypair)) == 0 || rustsecp256k1_v0_4_0_memcmp_var(&keypair_tmp, zeros96, sizeof(keypair_tmp)) == 0); } /* Invalid keypair with a valid tweak */ memset(&keypair, 0, sizeof(keypair)); rustsecp256k1_v0_4_0_testrand256(tweak); ecount = 0; CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(verify, &keypair, tweak) == 0); CHECK(ecount == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&keypair, zeros96, sizeof(keypair)) == 0); /* Only seckey part of keypair invalid */ CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, sk) == 1); memset(&keypair, 0, 32); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(verify, &keypair, tweak) == 0); CHECK(ecount == 2); /* Only pubkey part of keypair invalid */ CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, sk) == 1); memset(&keypair.data[32], 0, 64); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(verify, &keypair, tweak) == 0); CHECK(ecount == 3); /* Check that the keypair_tweak_add implementation is correct */ CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair, sk) == 1); for (i = 0; i < count; i++) { rustsecp256k1_v0_4_0_xonly_pubkey internal_pk; rustsecp256k1_v0_4_0_xonly_pubkey output_pk; rustsecp256k1_v0_4_0_pubkey output_pk_xy; rustsecp256k1_v0_4_0_pubkey output_pk_expected; unsigned char pk32[32]; int pk_parity; rustsecp256k1_v0_4_0_testrand256(tweak); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(ctx, &internal_pk, NULL, &keypair) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_tweak_add(ctx, &keypair, tweak) == 1); CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(ctx, &output_pk, &pk_parity, &keypair) == 1); /* Check that it passes xonly_pubkey_tweak_add_check */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(ctx, pk32, &output_pk) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add_check(ctx, pk32, pk_parity, &internal_pk, tweak) == 1); /* Check that the resulting pubkey matches xonly_pubkey_tweak_add */ CHECK(rustsecp256k1_v0_4_0_keypair_pub(ctx, &output_pk_xy, &keypair) == 1); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_tweak_add(ctx, &output_pk_expected, &internal_pk, tweak) == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&output_pk_xy, &output_pk_expected, sizeof(output_pk_xy)) == 0); /* Check that the secret key in the keypair is tweaked correctly */ CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(ctx, &output_pk_expected, &keypair.data[0]) == 1); CHECK(rustsecp256k1_v0_4_0_memcmp_var(&output_pk_xy, &output_pk_expected, sizeof(output_pk_xy)) == 0); } rustsecp256k1_v0_4_0_context_destroy(none); rustsecp256k1_v0_4_0_context_destroy(sign); rustsecp256k1_v0_4_0_context_destroy(verify); } void run_extrakeys_tests(void) { /* xonly key test cases */ test_xonly_pubkey(); test_xonly_pubkey_tweak(); test_xonly_pubkey_tweak_check(); test_xonly_pubkey_tweak_recursive(); /* keypair tests */ test_keypair(); test_keypair_add(); } #endif
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/modules/extrakeys/tests_exhaustive_impl.h
/*********************************************************************** * Copyright (c) 2020 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef _SECP256K1_MODULE_EXTRAKEYS_TESTS_EXHAUSTIVE_ #define _SECP256K1_MODULE_EXTRAKEYS_TESTS_EXHAUSTIVE_ #include "src/modules/extrakeys/main_impl.h" #include "include/secp256k1_extrakeys.h" static void test_exhaustive_extrakeys(const rustsecp256k1_v0_4_0_context *ctx, const rustsecp256k1_v0_4_0_ge* group) { rustsecp256k1_v0_4_0_keypair keypair[EXHAUSTIVE_TEST_ORDER - 1]; rustsecp256k1_v0_4_0_pubkey pubkey[EXHAUSTIVE_TEST_ORDER - 1]; rustsecp256k1_v0_4_0_xonly_pubkey xonly_pubkey[EXHAUSTIVE_TEST_ORDER - 1]; int parities[EXHAUSTIVE_TEST_ORDER - 1]; unsigned char xonly_pubkey_bytes[EXHAUSTIVE_TEST_ORDER - 1][32]; int i; for (i = 1; i < EXHAUSTIVE_TEST_ORDER; i++) { rustsecp256k1_v0_4_0_fe fe; rustsecp256k1_v0_4_0_scalar scalar_i; unsigned char buf[33]; int parity; rustsecp256k1_v0_4_0_scalar_set_int(&scalar_i, i); rustsecp256k1_v0_4_0_scalar_get_b32(buf, &scalar_i); /* Construct pubkey and keypair. */ CHECK(rustsecp256k1_v0_4_0_keypair_create(ctx, &keypair[i - 1], buf)); CHECK(rustsecp256k1_v0_4_0_ec_pubkey_create(ctx, &pubkey[i - 1], buf)); /* Construct serialized xonly_pubkey from keypair. */ CHECK(rustsecp256k1_v0_4_0_keypair_xonly_pub(ctx, &xonly_pubkey[i - 1], &parities[i - 1], &keypair[i - 1])); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(ctx, xonly_pubkey_bytes[i - 1], &xonly_pubkey[i - 1])); /* Parse the xonly_pubkey back and verify it matches the previously serialized value. */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_parse(ctx, &xonly_pubkey[i - 1], xonly_pubkey_bytes[i - 1])); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(ctx, buf, &xonly_pubkey[i - 1])); CHECK(rustsecp256k1_v0_4_0_memcmp_var(xonly_pubkey_bytes[i - 1], buf, 32) == 0); /* Construct the xonly_pubkey from the pubkey, and verify it matches the same. */ CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_from_pubkey(ctx, &xonly_pubkey[i - 1], &parity, &pubkey[i - 1])); CHECK(parity == parities[i - 1]); CHECK(rustsecp256k1_v0_4_0_xonly_pubkey_serialize(ctx, buf, &xonly_pubkey[i - 1])); CHECK(rustsecp256k1_v0_4_0_memcmp_var(xonly_pubkey_bytes[i - 1], buf, 32) == 0); /* Compare the xonly_pubkey bytes against the precomputed group. */ rustsecp256k1_v0_4_0_fe_set_b32(&fe, xonly_pubkey_bytes[i - 1]); CHECK(rustsecp256k1_v0_4_0_fe_equal_var(&fe, &group[i].x)); /* Check the parity against the precomputed group. */ fe = group[i].y; rustsecp256k1_v0_4_0_fe_normalize_var(&fe); CHECK(rustsecp256k1_v0_4_0_fe_is_odd(&fe) == parities[i - 1]); /* Verify that the higher half is identical to the lower half mirrored. */ if (i > EXHAUSTIVE_TEST_ORDER / 2) { CHECK(rustsecp256k1_v0_4_0_memcmp_var(xonly_pubkey_bytes[i - 1], xonly_pubkey_bytes[EXHAUSTIVE_TEST_ORDER - i - 1], 32) == 0); CHECK(parities[i - 1] == 1 - parities[EXHAUSTIVE_TEST_ORDER - i - 1]); } } /* TODO: keypair/xonly_pubkey tweak tests */ } #endif
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/secp256k1.c
/*********************************************************************** * Copyright (c) 2013-2015 <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #include "include/secp256k1.h" #include "include/secp256k1_preallocated.h" #include "assumptions.h" #include "util.h" #include "num_impl.h" #include "field_impl.h" #include "scalar_impl.h" #include "group_impl.h" #include "ecmult_impl.h" #include "ecmult_const_impl.h" #include "ecmult_gen_impl.h" #include "ecdsa_impl.h" #include "eckey_impl.h" #include "hash_impl.h" #include "scratch_impl.h" #include "selftest.h" #if defined(VALGRIND) # include <valgrind/memcheck.h> #endif #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ rustsecp256k1_v0_4_0_callback_call(&ctx->illegal_callback, #cond); \ return 0; \ } \ } while(0) #define ARG_CHECK_NO_RETURN(cond) do { \ if (EXPECT(!(cond), 0)) { \ rustsecp256k1_v0_4_0_callback_call(&ctx->illegal_callback, #cond); \ } \ } while(0) #ifndef USE_EXTERNAL_DEFAULT_CALLBACKS #include <stdlib.h> #include <stdio.h> static void rustsecp256k1_v0_4_0_default_illegal_callback_fn(const char* str, void* data) { (void)data; fprintf(stderr, "[libsecp256k1] illegal argument: %s\n", str); abort(); } static void rustsecp256k1_v0_4_0_default_error_callback_fn(const char* str, void* data) { (void)data; fprintf(stderr, "[libsecp256k1] internal consistency check failed: %s\n", str); abort(); } #else void rustsecp256k1_v0_4_0_default_illegal_callback_fn(const char* str, void* data); void rustsecp256k1_v0_4_0_default_error_callback_fn(const char* str, void* data); #endif static const rustsecp256k1_v0_4_0_callback default_illegal_callback = { rustsecp256k1_v0_4_0_default_illegal_callback_fn, NULL }; static const rustsecp256k1_v0_4_0_callback default_error_callback = { rustsecp256k1_v0_4_0_default_error_callback_fn, NULL }; struct rustsecp256k1_v0_4_0_context_struct { rustsecp256k1_v0_4_0_ecmult_context ecmult_ctx; rustsecp256k1_v0_4_0_ecmult_gen_context ecmult_gen_ctx; rustsecp256k1_v0_4_0_callback illegal_callback; rustsecp256k1_v0_4_0_callback error_callback; int declassify; }; static const rustsecp256k1_v0_4_0_context rustsecp256k1_v0_4_0_context_no_precomp_ = { { 0 }, { 0 }, { rustsecp256k1_v0_4_0_default_illegal_callback_fn, 0 }, { rustsecp256k1_v0_4_0_default_error_callback_fn, 0 }, 0 }; const rustsecp256k1_v0_4_0_context *rustsecp256k1_v0_4_0_context_no_precomp = &rustsecp256k1_v0_4_0_context_no_precomp_; size_t rustsecp256k1_v0_4_0_context_preallocated_size(unsigned int flags) { size_t ret = ROUND_TO_ALIGN(sizeof(rustsecp256k1_v0_4_0_context)); /* A return value of 0 is reserved as an indicator for errors when we call this function internally. */ VERIFY_CHECK(ret != 0); if (EXPECT((flags & SECP256K1_FLAGS_TYPE_MASK) != SECP256K1_FLAGS_TYPE_CONTEXT, 0)) { rustsecp256k1_v0_4_0_callback_call(&default_illegal_callback, "Invalid flags"); return 0; } if (flags & SECP256K1_FLAGS_BIT_CONTEXT_SIGN) { ret += SECP256K1_ECMULT_GEN_CONTEXT_PREALLOCATED_SIZE; } if (flags & SECP256K1_FLAGS_BIT_CONTEXT_VERIFY) { ret += SECP256K1_ECMULT_CONTEXT_PREALLOCATED_SIZE; } return ret; } size_t rustsecp256k1_v0_4_0_context_preallocated_clone_size(const rustsecp256k1_v0_4_0_context* ctx) { size_t ret = ROUND_TO_ALIGN(sizeof(rustsecp256k1_v0_4_0_context)); VERIFY_CHECK(ctx != NULL); if (rustsecp256k1_v0_4_0_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)) { ret += SECP256K1_ECMULT_GEN_CONTEXT_PREALLOCATED_SIZE; } if (rustsecp256k1_v0_4_0_ecmult_context_is_built(&ctx->ecmult_ctx)) { ret += SECP256K1_ECMULT_CONTEXT_PREALLOCATED_SIZE; } return ret; } rustsecp256k1_v0_4_0_context* rustsecp256k1_v0_4_0_context_preallocated_create(void* prealloc, unsigned int flags) { void* const base = prealloc; size_t prealloc_size; rustsecp256k1_v0_4_0_context* ret; if (!rustsecp256k1_v0_4_0_selftest()) { rustsecp256k1_v0_4_0_callback_call(&default_error_callback, "self test failed"); } prealloc_size = rustsecp256k1_v0_4_0_context_preallocated_size(flags); if (prealloc_size == 0) { return NULL; } VERIFY_CHECK(prealloc != NULL); ret = (rustsecp256k1_v0_4_0_context*)manual_alloc(&prealloc, sizeof(rustsecp256k1_v0_4_0_context), base, prealloc_size); ret->illegal_callback = default_illegal_callback; ret->error_callback = default_error_callback; rustsecp256k1_v0_4_0_ecmult_context_init(&ret->ecmult_ctx); rustsecp256k1_v0_4_0_ecmult_gen_context_init(&ret->ecmult_gen_ctx); /* Flags have been checked by rustsecp256k1_v0_4_0_context_preallocated_size. */ VERIFY_CHECK((flags & SECP256K1_FLAGS_TYPE_MASK) == SECP256K1_FLAGS_TYPE_CONTEXT); if (flags & SECP256K1_FLAGS_BIT_CONTEXT_SIGN) { rustsecp256k1_v0_4_0_ecmult_gen_context_build(&ret->ecmult_gen_ctx, &prealloc); } if (flags & SECP256K1_FLAGS_BIT_CONTEXT_VERIFY) { rustsecp256k1_v0_4_0_ecmult_context_build(&ret->ecmult_ctx, &prealloc); } ret->declassify = !!(flags & SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY); return (rustsecp256k1_v0_4_0_context*) ret; } rustsecp256k1_v0_4_0_context* rustsecp256k1_v0_4_0_context_preallocated_clone(const rustsecp256k1_v0_4_0_context* ctx, void* prealloc) { size_t prealloc_size; rustsecp256k1_v0_4_0_context* ret; VERIFY_CHECK(ctx != NULL); ARG_CHECK(prealloc != NULL); prealloc_size = rustsecp256k1_v0_4_0_context_preallocated_clone_size(ctx); ret = (rustsecp256k1_v0_4_0_context*)prealloc; memcpy(ret, ctx, prealloc_size); rustsecp256k1_v0_4_0_ecmult_gen_context_finalize_memcpy(&ret->ecmult_gen_ctx, &ctx->ecmult_gen_ctx); rustsecp256k1_v0_4_0_ecmult_context_finalize_memcpy(&ret->ecmult_ctx, &ctx->ecmult_ctx); return ret; } void rustsecp256k1_v0_4_0_context_preallocated_destroy(rustsecp256k1_v0_4_0_context* ctx) { ARG_CHECK_NO_RETURN(ctx != rustsecp256k1_v0_4_0_context_no_precomp); if (ctx != NULL) { rustsecp256k1_v0_4_0_ecmult_context_clear(&ctx->ecmult_ctx); rustsecp256k1_v0_4_0_ecmult_gen_context_clear(&ctx->ecmult_gen_ctx); } } void rustsecp256k1_v0_4_0_context_set_illegal_callback(rustsecp256k1_v0_4_0_context* ctx, void (*fun)(const char* message, void* data), const void* data) { ARG_CHECK_NO_RETURN(ctx != rustsecp256k1_v0_4_0_context_no_precomp); if (fun == NULL) { fun = rustsecp256k1_v0_4_0_default_illegal_callback_fn; } ctx->illegal_callback.fn = fun; ctx->illegal_callback.data = data; } void rustsecp256k1_v0_4_0_context_set_error_callback(rustsecp256k1_v0_4_0_context* ctx, void (*fun)(const char* message, void* data), const void* data) { ARG_CHECK_NO_RETURN(ctx != rustsecp256k1_v0_4_0_context_no_precomp); if (fun == NULL) { fun = rustsecp256k1_v0_4_0_default_error_callback_fn; } ctx->error_callback.fn = fun; ctx->error_callback.data = data; } /* Mark memory as no-longer-secret for the purpose of analysing constant-time behaviour * of the software. This is setup for use with valgrind but could be substituted with * the appropriate instrumentation for other analysis tools. */ static SECP256K1_INLINE void rustsecp256k1_v0_4_0_declassify(const rustsecp256k1_v0_4_0_context* ctx, const void *p, size_t len) { #if defined(VALGRIND) if (EXPECT(ctx->declassify,0)) VALGRIND_MAKE_MEM_DEFINED(p, len); #else (void)ctx; (void)p; (void)len; #endif } static int rustsecp256k1_v0_4_0_pubkey_load(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_ge* ge, const rustsecp256k1_v0_4_0_pubkey* pubkey) { if (sizeof(rustsecp256k1_v0_4_0_ge_storage) == 64) { /* When the rustsecp256k1_v0_4_0_ge_storage type is exactly 64 byte, use its * representation inside rustsecp256k1_v0_4_0_pubkey, as conversion is very fast. * Note that rustsecp256k1_v0_4_0_pubkey_save must use the same representation. */ rustsecp256k1_v0_4_0_ge_storage s; memcpy(&s, &pubkey->data[0], sizeof(s)); rustsecp256k1_v0_4_0_ge_from_storage(ge, &s); } else { /* Otherwise, fall back to 32-byte big endian for X and Y. */ rustsecp256k1_v0_4_0_fe x, y; rustsecp256k1_v0_4_0_fe_set_b32(&x, pubkey->data); rustsecp256k1_v0_4_0_fe_set_b32(&y, pubkey->data + 32); rustsecp256k1_v0_4_0_ge_set_xy(ge, &x, &y); } ARG_CHECK(!rustsecp256k1_v0_4_0_fe_is_zero(&ge->x)); return 1; } static void rustsecp256k1_v0_4_0_pubkey_save(rustsecp256k1_v0_4_0_pubkey* pubkey, rustsecp256k1_v0_4_0_ge* ge) { if (sizeof(rustsecp256k1_v0_4_0_ge_storage) == 64) { rustsecp256k1_v0_4_0_ge_storage s; rustsecp256k1_v0_4_0_ge_to_storage(&s, ge); memcpy(&pubkey->data[0], &s, sizeof(s)); } else { VERIFY_CHECK(!rustsecp256k1_v0_4_0_ge_is_infinity(ge)); rustsecp256k1_v0_4_0_fe_normalize_var(&ge->x); rustsecp256k1_v0_4_0_fe_normalize_var(&ge->y); rustsecp256k1_v0_4_0_fe_get_b32(pubkey->data, &ge->x); rustsecp256k1_v0_4_0_fe_get_b32(pubkey->data + 32, &ge->y); } } int rustsecp256k1_v0_4_0_ec_pubkey_parse(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_pubkey* pubkey, const unsigned char *input, size_t inputlen) { rustsecp256k1_v0_4_0_ge Q; VERIFY_CHECK(ctx != NULL); ARG_CHECK(pubkey != NULL); memset(pubkey, 0, sizeof(*pubkey)); ARG_CHECK(input != NULL); if (!rustsecp256k1_v0_4_0_eckey_pubkey_parse(&Q, input, inputlen)) { return 0; } if (!rustsecp256k1_v0_4_0_ge_is_in_correct_subgroup(&Q)) { return 0; } rustsecp256k1_v0_4_0_pubkey_save(pubkey, &Q); rustsecp256k1_v0_4_0_ge_clear(&Q); return 1; } int rustsecp256k1_v0_4_0_ec_pubkey_serialize(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *output, size_t *outputlen, const rustsecp256k1_v0_4_0_pubkey* pubkey, unsigned int flags) { rustsecp256k1_v0_4_0_ge Q; size_t len; int ret = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(outputlen != NULL); ARG_CHECK(*outputlen >= ((flags & SECP256K1_FLAGS_BIT_COMPRESSION) ? 33u : 65u)); len = *outputlen; *outputlen = 0; ARG_CHECK(output != NULL); memset(output, 0, len); ARG_CHECK(pubkey != NULL); ARG_CHECK((flags & SECP256K1_FLAGS_TYPE_MASK) == SECP256K1_FLAGS_TYPE_COMPRESSION); if (rustsecp256k1_v0_4_0_pubkey_load(ctx, &Q, pubkey)) { ret = rustsecp256k1_v0_4_0_eckey_pubkey_serialize(&Q, output, &len, flags & SECP256K1_FLAGS_BIT_COMPRESSION); if (ret) { *outputlen = len; } } return ret; } static void rustsecp256k1_v0_4_0_ecdsa_signature_load(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_scalar* r, rustsecp256k1_v0_4_0_scalar* s, const rustsecp256k1_v0_4_0_ecdsa_signature* sig) { (void)ctx; if (sizeof(rustsecp256k1_v0_4_0_scalar) == 32) { /* When the rustsecp256k1_v0_4_0_scalar type is exactly 32 byte, use its * representation inside rustsecp256k1_v0_4_0_ecdsa_signature, as conversion is very fast. * Note that rustsecp256k1_v0_4_0_ecdsa_signature_save must use the same representation. */ memcpy(r, &sig->data[0], 32); memcpy(s, &sig->data[32], 32); } else { rustsecp256k1_v0_4_0_scalar_set_b32(r, &sig->data[0], NULL); rustsecp256k1_v0_4_0_scalar_set_b32(s, &sig->data[32], NULL); } } static void rustsecp256k1_v0_4_0_ecdsa_signature_save(rustsecp256k1_v0_4_0_ecdsa_signature* sig, const rustsecp256k1_v0_4_0_scalar* r, const rustsecp256k1_v0_4_0_scalar* s) { if (sizeof(rustsecp256k1_v0_4_0_scalar) == 32) { memcpy(&sig->data[0], r, 32); memcpy(&sig->data[32], s, 32); } else { rustsecp256k1_v0_4_0_scalar_get_b32(&sig->data[0], r); rustsecp256k1_v0_4_0_scalar_get_b32(&sig->data[32], s); } } int rustsecp256k1_v0_4_0_ecdsa_signature_parse_der(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) { rustsecp256k1_v0_4_0_scalar r, s; VERIFY_CHECK(ctx != NULL); ARG_CHECK(sig != NULL); ARG_CHECK(input != NULL); if (rustsecp256k1_v0_4_0_ecdsa_sig_parse(&r, &s, input, inputlen)) { rustsecp256k1_v0_4_0_ecdsa_signature_save(sig, &r, &s); return 1; } else { memset(sig, 0, sizeof(*sig)); return 0; } } int rustsecp256k1_v0_4_0_ecdsa_signature_parse_compact(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_ecdsa_signature* sig, const unsigned char *input64) { rustsecp256k1_v0_4_0_scalar r, s; int ret = 1; int overflow = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(sig != NULL); ARG_CHECK(input64 != NULL); rustsecp256k1_v0_4_0_scalar_set_b32(&r, &input64[0], &overflow); ret &= !overflow; rustsecp256k1_v0_4_0_scalar_set_b32(&s, &input64[32], &overflow); ret &= !overflow; if (ret) { rustsecp256k1_v0_4_0_ecdsa_signature_save(sig, &r, &s); } else { memset(sig, 0, sizeof(*sig)); } return ret; } int rustsecp256k1_v0_4_0_ecdsa_signature_serialize_der(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *output, size_t *outputlen, const rustsecp256k1_v0_4_0_ecdsa_signature* sig) { rustsecp256k1_v0_4_0_scalar r, s; VERIFY_CHECK(ctx != NULL); ARG_CHECK(output != NULL); ARG_CHECK(outputlen != NULL); ARG_CHECK(sig != NULL); rustsecp256k1_v0_4_0_ecdsa_signature_load(ctx, &r, &s, sig); return rustsecp256k1_v0_4_0_ecdsa_sig_serialize(output, outputlen, &r, &s); } int rustsecp256k1_v0_4_0_ecdsa_signature_serialize_compact(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *output64, const rustsecp256k1_v0_4_0_ecdsa_signature* sig) { rustsecp256k1_v0_4_0_scalar r, s; VERIFY_CHECK(ctx != NULL); ARG_CHECK(output64 != NULL); ARG_CHECK(sig != NULL); rustsecp256k1_v0_4_0_ecdsa_signature_load(ctx, &r, &s, sig); rustsecp256k1_v0_4_0_scalar_get_b32(&output64[0], &r); rustsecp256k1_v0_4_0_scalar_get_b32(&output64[32], &s); return 1; } int rustsecp256k1_v0_4_0_ecdsa_signature_normalize(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_ecdsa_signature *sigout, const rustsecp256k1_v0_4_0_ecdsa_signature *sigin) { rustsecp256k1_v0_4_0_scalar r, s; int ret = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(sigin != NULL); rustsecp256k1_v0_4_0_ecdsa_signature_load(ctx, &r, &s, sigin); ret = rustsecp256k1_v0_4_0_scalar_is_high(&s); if (sigout != NULL) { if (ret) { rustsecp256k1_v0_4_0_scalar_negate(&s, &s); } rustsecp256k1_v0_4_0_ecdsa_signature_save(sigout, &r, &s); } return ret; } int rustsecp256k1_v0_4_0_ecdsa_verify(const rustsecp256k1_v0_4_0_context* ctx, const rustsecp256k1_v0_4_0_ecdsa_signature *sig, const unsigned char *msghash32, const rustsecp256k1_v0_4_0_pubkey *pubkey) { rustsecp256k1_v0_4_0_ge q; rustsecp256k1_v0_4_0_scalar r, s; rustsecp256k1_v0_4_0_scalar m; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_context_is_built(&ctx->ecmult_ctx)); ARG_CHECK(msghash32 != NULL); ARG_CHECK(sig != NULL); ARG_CHECK(pubkey != NULL); rustsecp256k1_v0_4_0_scalar_set_b32(&m, msghash32, NULL); rustsecp256k1_v0_4_0_ecdsa_signature_load(ctx, &r, &s, sig); return (!rustsecp256k1_v0_4_0_scalar_is_high(&s) && rustsecp256k1_v0_4_0_pubkey_load(ctx, &q, pubkey) && rustsecp256k1_v0_4_0_ecdsa_sig_verify(&ctx->ecmult_ctx, &r, &s, &q, &m)); } static SECP256K1_INLINE void buffer_append(unsigned char *buf, unsigned int *offset, const void *data, unsigned int len) { memcpy(buf + *offset, data, len); *offset += len; } static int nonce_function_rfc6979(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { unsigned char keydata[112]; unsigned int offset = 0; rustsecp256k1_v0_4_0_rfc6979_hmac_sha256 rng; unsigned int i; /* We feed a byte array to the PRNG as input, consisting of: * - the private key (32 bytes) and message (32 bytes), see RFC 6979 3.2d. * - optionally 32 extra bytes of data, see RFC 6979 3.6 Additional Data. * - optionally 16 extra bytes with the algorithm name. * Because the arguments have distinct fixed lengths it is not possible for * different argument mixtures to emulate each other and result in the same * nonces. */ buffer_append(keydata, &offset, key32, 32); buffer_append(keydata, &offset, msg32, 32); if (data != NULL) { buffer_append(keydata, &offset, data, 32); } if (algo16 != NULL) { buffer_append(keydata, &offset, algo16, 16); } rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_initialize(&rng, keydata, offset); memset(keydata, 0, sizeof(keydata)); for (i = 0; i <= counter; i++) { rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); } rustsecp256k1_v0_4_0_rfc6979_hmac_sha256_finalize(&rng); return 1; } const rustsecp256k1_v0_4_0_nonce_function rustsecp256k1_v0_4_0_nonce_function_rfc6979 = nonce_function_rfc6979; const rustsecp256k1_v0_4_0_nonce_function rustsecp256k1_v0_4_0_nonce_function_default = nonce_function_rfc6979; static int rustsecp256k1_v0_4_0_ecdsa_sign_inner(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_scalar* r, rustsecp256k1_v0_4_0_scalar* s, int* recid, const unsigned char *msg32, const unsigned char *seckey, rustsecp256k1_v0_4_0_nonce_function noncefp, const void* noncedata) { rustsecp256k1_v0_4_0_scalar sec, non, msg; int ret = 0; int is_sec_valid; unsigned char nonce32[32]; unsigned int count = 0; /* Default initialization here is important so we won't pass uninit values to the cmov in the end */ *r = rustsecp256k1_v0_4_0_scalar_zero; *s = rustsecp256k1_v0_4_0_scalar_zero; if (recid) { *recid = 0; } if (noncefp == NULL) { noncefp = rustsecp256k1_v0_4_0_nonce_function_default; } /* Fail if the secret key is invalid. */ is_sec_valid = rustsecp256k1_v0_4_0_scalar_set_b32_seckey(&sec, seckey); rustsecp256k1_v0_4_0_scalar_cmov(&sec, &rustsecp256k1_v0_4_0_scalar_one, !is_sec_valid); rustsecp256k1_v0_4_0_scalar_set_b32(&msg, msg32, NULL); while (1) { int is_nonce_valid; ret = !!noncefp(nonce32, msg32, seckey, NULL, (void*)noncedata, count); if (!ret) { break; } is_nonce_valid = rustsecp256k1_v0_4_0_scalar_set_b32_seckey(&non, nonce32); /* The nonce is still secret here, but it being invalid is is less likely than 1:2^255. */ rustsecp256k1_v0_4_0_declassify(ctx, &is_nonce_valid, sizeof(is_nonce_valid)); if (is_nonce_valid) { ret = rustsecp256k1_v0_4_0_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, r, s, &sec, &msg, &non, recid); /* The final signature is no longer a secret, nor is the fact that we were successful or not. */ rustsecp256k1_v0_4_0_declassify(ctx, &ret, sizeof(ret)); if (ret) { break; } } count++; } /* We don't want to declassify is_sec_valid and therefore the range of * seckey. As a result is_sec_valid is included in ret only after ret was * used as a branching variable. */ ret &= is_sec_valid; memset(nonce32, 0, 32); rustsecp256k1_v0_4_0_scalar_clear(&msg); rustsecp256k1_v0_4_0_scalar_clear(&non); rustsecp256k1_v0_4_0_scalar_clear(&sec); rustsecp256k1_v0_4_0_scalar_cmov(r, &rustsecp256k1_v0_4_0_scalar_zero, !ret); rustsecp256k1_v0_4_0_scalar_cmov(s, &rustsecp256k1_v0_4_0_scalar_zero, !ret); if (recid) { const int zero = 0; rustsecp256k1_v0_4_0_int_cmov(recid, &zero, !ret); } return ret; } int rustsecp256k1_v0_4_0_ecdsa_sign(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_ecdsa_signature *signature, const unsigned char *msghash32, const unsigned char *seckey, rustsecp256k1_v0_4_0_nonce_function noncefp, const void* noncedata) { rustsecp256k1_v0_4_0_scalar r, s; int ret; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); ARG_CHECK(msghash32 != NULL); ARG_CHECK(signature != NULL); ARG_CHECK(seckey != NULL); ret = rustsecp256k1_v0_4_0_ecdsa_sign_inner(ctx, &r, &s, NULL, msghash32, seckey, noncefp, noncedata); rustsecp256k1_v0_4_0_ecdsa_signature_save(signature, &r, &s); return ret; } int rustsecp256k1_v0_4_0_ec_seckey_verify(const rustsecp256k1_v0_4_0_context* ctx, const unsigned char *seckey) { rustsecp256k1_v0_4_0_scalar sec; int ret; VERIFY_CHECK(ctx != NULL); ARG_CHECK(seckey != NULL); ret = rustsecp256k1_v0_4_0_scalar_set_b32_seckey(&sec, seckey); rustsecp256k1_v0_4_0_scalar_clear(&sec); return ret; } static int rustsecp256k1_v0_4_0_ec_pubkey_create_helper(const rustsecp256k1_v0_4_0_ecmult_gen_context *ecmult_gen_ctx, rustsecp256k1_v0_4_0_scalar *seckey_scalar, rustsecp256k1_v0_4_0_ge *p, const unsigned char *seckey) { rustsecp256k1_v0_4_0_gej pj; int ret; ret = rustsecp256k1_v0_4_0_scalar_set_b32_seckey(seckey_scalar, seckey); rustsecp256k1_v0_4_0_scalar_cmov(seckey_scalar, &rustsecp256k1_v0_4_0_scalar_one, !ret); rustsecp256k1_v0_4_0_ecmult_gen(ecmult_gen_ctx, &pj, seckey_scalar); rustsecp256k1_v0_4_0_ge_set_gej(p, &pj); return ret; } int rustsecp256k1_v0_4_0_ec_pubkey_create(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_pubkey *pubkey, const unsigned char *seckey) { rustsecp256k1_v0_4_0_ge p; rustsecp256k1_v0_4_0_scalar seckey_scalar; int ret = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(pubkey != NULL); memset(pubkey, 0, sizeof(*pubkey)); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); ARG_CHECK(seckey != NULL); ret = rustsecp256k1_v0_4_0_ec_pubkey_create_helper(&ctx->ecmult_gen_ctx, &seckey_scalar, &p, seckey); rustsecp256k1_v0_4_0_pubkey_save(pubkey, &p); rustsecp256k1_v0_4_0_memczero(pubkey, sizeof(*pubkey), !ret); rustsecp256k1_v0_4_0_scalar_clear(&seckey_scalar); return ret; } int rustsecp256k1_v0_4_0_ec_seckey_negate(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *seckey) { rustsecp256k1_v0_4_0_scalar sec; int ret = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(seckey != NULL); ret = rustsecp256k1_v0_4_0_scalar_set_b32_seckey(&sec, seckey); rustsecp256k1_v0_4_0_scalar_cmov(&sec, &rustsecp256k1_v0_4_0_scalar_zero, !ret); rustsecp256k1_v0_4_0_scalar_negate(&sec, &sec); rustsecp256k1_v0_4_0_scalar_get_b32(seckey, &sec); rustsecp256k1_v0_4_0_scalar_clear(&sec); return ret; } int rustsecp256k1_v0_4_0_ec_privkey_negate(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *seckey) { return rustsecp256k1_v0_4_0_ec_seckey_negate(ctx, seckey); } int rustsecp256k1_v0_4_0_ec_pubkey_negate(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_pubkey *pubkey) { int ret = 0; rustsecp256k1_v0_4_0_ge p; VERIFY_CHECK(ctx != NULL); ARG_CHECK(pubkey != NULL); ret = rustsecp256k1_v0_4_0_pubkey_load(ctx, &p, pubkey); memset(pubkey, 0, sizeof(*pubkey)); if (ret) { rustsecp256k1_v0_4_0_ge_neg(&p, &p); rustsecp256k1_v0_4_0_pubkey_save(pubkey, &p); } return ret; } static int rustsecp256k1_v0_4_0_ec_seckey_tweak_add_helper(rustsecp256k1_v0_4_0_scalar *sec, const unsigned char *tweak32) { rustsecp256k1_v0_4_0_scalar term; int overflow = 0; int ret = 0; rustsecp256k1_v0_4_0_scalar_set_b32(&term, tweak32, &overflow); ret = (!overflow) & rustsecp256k1_v0_4_0_eckey_privkey_tweak_add(sec, &term); rustsecp256k1_v0_4_0_scalar_clear(&term); return ret; } int rustsecp256k1_v0_4_0_ec_seckey_tweak_add(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *seckey, const unsigned char *tweak32) { rustsecp256k1_v0_4_0_scalar sec; int ret = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(seckey != NULL); ARG_CHECK(tweak32 != NULL); ret = rustsecp256k1_v0_4_0_scalar_set_b32_seckey(&sec, seckey); ret &= rustsecp256k1_v0_4_0_ec_seckey_tweak_add_helper(&sec, tweak32); rustsecp256k1_v0_4_0_scalar_cmov(&sec, &rustsecp256k1_v0_4_0_scalar_zero, !ret); rustsecp256k1_v0_4_0_scalar_get_b32(seckey, &sec); rustsecp256k1_v0_4_0_scalar_clear(&sec); return ret; } int rustsecp256k1_v0_4_0_ec_privkey_tweak_add(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *seckey, const unsigned char *tweak32) { return rustsecp256k1_v0_4_0_ec_seckey_tweak_add(ctx, seckey, tweak32); } static int rustsecp256k1_v0_4_0_ec_pubkey_tweak_add_helper(const rustsecp256k1_v0_4_0_ecmult_context* ecmult_ctx, rustsecp256k1_v0_4_0_ge *p, const unsigned char *tweak32) { rustsecp256k1_v0_4_0_scalar term; int overflow = 0; rustsecp256k1_v0_4_0_scalar_set_b32(&term, tweak32, &overflow); return !overflow && rustsecp256k1_v0_4_0_eckey_pubkey_tweak_add(ecmult_ctx, p, &term); } int rustsecp256k1_v0_4_0_ec_pubkey_tweak_add(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_pubkey *pubkey, const unsigned char *tweak32) { rustsecp256k1_v0_4_0_ge p; int ret = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_context_is_built(&ctx->ecmult_ctx)); ARG_CHECK(pubkey != NULL); ARG_CHECK(tweak32 != NULL); ret = rustsecp256k1_v0_4_0_pubkey_load(ctx, &p, pubkey); memset(pubkey, 0, sizeof(*pubkey)); ret = ret && rustsecp256k1_v0_4_0_ec_pubkey_tweak_add_helper(&ctx->ecmult_ctx, &p, tweak32); if (ret) { rustsecp256k1_v0_4_0_pubkey_save(pubkey, &p); } return ret; } int rustsecp256k1_v0_4_0_ec_seckey_tweak_mul(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *seckey, const unsigned char *tweak32) { rustsecp256k1_v0_4_0_scalar factor; rustsecp256k1_v0_4_0_scalar sec; int ret = 0; int overflow = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(seckey != NULL); ARG_CHECK(tweak32 != NULL); rustsecp256k1_v0_4_0_scalar_set_b32(&factor, tweak32, &overflow); ret = rustsecp256k1_v0_4_0_scalar_set_b32_seckey(&sec, seckey); ret &= (!overflow) & rustsecp256k1_v0_4_0_eckey_privkey_tweak_mul(&sec, &factor); rustsecp256k1_v0_4_0_scalar_cmov(&sec, &rustsecp256k1_v0_4_0_scalar_zero, !ret); rustsecp256k1_v0_4_0_scalar_get_b32(seckey, &sec); rustsecp256k1_v0_4_0_scalar_clear(&sec); rustsecp256k1_v0_4_0_scalar_clear(&factor); return ret; } int rustsecp256k1_v0_4_0_ec_privkey_tweak_mul(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *seckey, const unsigned char *tweak32) { return rustsecp256k1_v0_4_0_ec_seckey_tweak_mul(ctx, seckey, tweak32); } int rustsecp256k1_v0_4_0_ec_pubkey_tweak_mul(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_pubkey *pubkey, const unsigned char *tweak32) { rustsecp256k1_v0_4_0_ge p; rustsecp256k1_v0_4_0_scalar factor; int ret = 0; int overflow = 0; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_context_is_built(&ctx->ecmult_ctx)); ARG_CHECK(pubkey != NULL); ARG_CHECK(tweak32 != NULL); rustsecp256k1_v0_4_0_scalar_set_b32(&factor, tweak32, &overflow); ret = !overflow && rustsecp256k1_v0_4_0_pubkey_load(ctx, &p, pubkey); memset(pubkey, 0, sizeof(*pubkey)); if (ret) { if (rustsecp256k1_v0_4_0_eckey_pubkey_tweak_mul(&ctx->ecmult_ctx, &p, &factor)) { rustsecp256k1_v0_4_0_pubkey_save(pubkey, &p); } else { ret = 0; } } return ret; } int rustsecp256k1_v0_4_0_context_randomize(rustsecp256k1_v0_4_0_context* ctx, const unsigned char *seed32) { VERIFY_CHECK(ctx != NULL); if (rustsecp256k1_v0_4_0_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)) { rustsecp256k1_v0_4_0_ecmult_gen_blind(&ctx->ecmult_gen_ctx, seed32); } return 1; } int rustsecp256k1_v0_4_0_ec_pubkey_combine(const rustsecp256k1_v0_4_0_context* ctx, rustsecp256k1_v0_4_0_pubkey *pubnonce, const rustsecp256k1_v0_4_0_pubkey * const *pubnonces, size_t n) { size_t i; rustsecp256k1_v0_4_0_gej Qj; rustsecp256k1_v0_4_0_ge Q; ARG_CHECK(pubnonce != NULL); memset(pubnonce, 0, sizeof(*pubnonce)); ARG_CHECK(n >= 1); ARG_CHECK(pubnonces != NULL); rustsecp256k1_v0_4_0_gej_set_infinity(&Qj); for (i = 0; i < n; i++) { rustsecp256k1_v0_4_0_pubkey_load(ctx, &Q, pubnonces[i]); rustsecp256k1_v0_4_0_gej_add_ge(&Qj, &Qj, &Q); } if (rustsecp256k1_v0_4_0_gej_is_infinity(&Qj)) { return 0; } rustsecp256k1_v0_4_0_ge_set_gej(&Q, &Qj); rustsecp256k1_v0_4_0_pubkey_save(pubnonce, &Q); return 1; } #ifdef ENABLE_MODULE_ECDH # include "modules/ecdh/main_impl.h" #endif #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/main_impl.h" #endif #ifdef ENABLE_MODULE_EXTRAKEYS # include "modules/extrakeys/main_impl.h" #endif #ifdef ENABLE_MODULE_SCHNORRSIG # include "modules/schnorrsig/main_impl.h" #endif
gregdhill/rust-secp256k1
secp256k1-sys/depend/secp256k1/src/modules/schnorrsig/main_impl.h
<gh_stars>1-10 /*********************************************************************** * Copyright (c) 2018-2020 <NAME>, <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #ifndef _SECP256K1_MODULE_SCHNORRSIG_MAIN_ #define _SECP256K1_MODULE_SCHNORRSIG_MAIN_ #include "include/secp256k1.h" #include "include/secp256k1_schnorrsig.h" #include "hash.h" /* Initializes SHA256 with fixed midstate. This midstate was computed by applying * SHA256 to SHA256("BIP0340/nonce")||SHA256("BIP0340/nonce"). */ static void rustsecp256k1_v0_4_0_nonce_function_bip340_sha256_tagged(rustsecp256k1_v0_4_0_sha256 *sha) { rustsecp256k1_v0_4_0_sha256_initialize(sha); sha->s[0] = 0x46615b35ul; sha->s[1] = 0xf4bfbff7ul; sha->s[2] = 0x9f8dc671ul; sha->s[3] = 0x83627ab3ul; sha->s[4] = 0x60217180ul; sha->s[5] = 0x57358661ul; sha->s[6] = 0x21a29e54ul; sha->s[7] = 0x68b07b4cul; sha->bytes = 64; } /* Initializes SHA256 with fixed midstate. This midstate was computed by applying * SHA256 to SHA256("BIP0340/aux")||SHA256("BIP0340/aux"). */ static void rustsecp256k1_v0_4_0_nonce_function_bip340_sha256_tagged_aux(rustsecp256k1_v0_4_0_sha256 *sha) { rustsecp256k1_v0_4_0_sha256_initialize(sha); sha->s[0] = 0x24dd3219ul; sha->s[1] = 0x4eba7e70ul; sha->s[2] = 0xca0fabb9ul; sha->s[3] = 0x0fa3166dul; sha->s[4] = 0x3afbe4b1ul; sha->s[5] = 0x4c44df97ul; sha->s[6] = 0x4aac2739ul; sha->s[7] = 0x249e850aul; sha->bytes = 64; } /* algo16 argument for nonce_function_bip340 to derive the nonce exactly as stated in BIP-340 * by using the correct tagged hash function. */ static const unsigned char bip340_algo16[16] = "BIP0340/nonce\0\0\0"; static int nonce_function_bip340(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *xonly_pk32, const unsigned char *algo16, void *data) { rustsecp256k1_v0_4_0_sha256 sha; unsigned char masked_key[32]; int i; if (algo16 == NULL) { return 0; } if (data != NULL) { rustsecp256k1_v0_4_0_nonce_function_bip340_sha256_tagged_aux(&sha); rustsecp256k1_v0_4_0_sha256_write(&sha, data, 32); rustsecp256k1_v0_4_0_sha256_finalize(&sha, masked_key); for (i = 0; i < 32; i++) { masked_key[i] ^= key32[i]; } } /* Tag the hash with algo16 which is important to avoid nonce reuse across * algorithms. If this nonce function is used in BIP-340 signing as defined * in the spec, an optimized tagging implementation is used. */ if (rustsecp256k1_v0_4_0_memcmp_var(algo16, bip340_algo16, 16) == 0) { rustsecp256k1_v0_4_0_nonce_function_bip340_sha256_tagged(&sha); } else { int algo16_len = 16; /* Remove terminating null bytes */ while (algo16_len > 0 && !algo16[algo16_len - 1]) { algo16_len--; } rustsecp256k1_v0_4_0_sha256_initialize_tagged(&sha, algo16, algo16_len); } /* Hash (masked-)key||pk||msg using the tagged hash as per the spec */ if (data != NULL) { rustsecp256k1_v0_4_0_sha256_write(&sha, masked_key, 32); } else { rustsecp256k1_v0_4_0_sha256_write(&sha, key32, 32); } rustsecp256k1_v0_4_0_sha256_write(&sha, xonly_pk32, 32); rustsecp256k1_v0_4_0_sha256_write(&sha, msg32, 32); rustsecp256k1_v0_4_0_sha256_finalize(&sha, nonce32); return 1; } const rustsecp256k1_v0_4_0_nonce_function_hardened rustsecp256k1_v0_4_0_nonce_function_bip340 = nonce_function_bip340; /* Initializes SHA256 with fixed midstate. This midstate was computed by applying * SHA256 to SHA256("BIP0340/challenge")||SHA256("BIP0340/challenge"). */ static void rustsecp256k1_v0_4_0_schnorrsig_sha256_tagged(rustsecp256k1_v0_4_0_sha256 *sha) { rustsecp256k1_v0_4_0_sha256_initialize(sha); sha->s[0] = 0x9cecba11ul; sha->s[1] = 0x23925381ul; sha->s[2] = 0x11679112ul; sha->s[3] = 0xd1627e0ful; sha->s[4] = 0x97c87550ul; sha->s[5] = 0x003cc765ul; sha->s[6] = 0x90f61164ul; sha->s[7] = 0x33e9b66aul; sha->bytes = 64; } static void rustsecp256k1_v0_4_0_schnorrsig_challenge(rustsecp256k1_v0_4_0_scalar* e, const unsigned char *r32, const unsigned char *msg32, const unsigned char *pubkey32) { unsigned char buf[32]; rustsecp256k1_v0_4_0_sha256 sha; /* tagged hash(r.x, pk.x, msg32) */ rustsecp256k1_v0_4_0_schnorrsig_sha256_tagged(&sha); rustsecp256k1_v0_4_0_sha256_write(&sha, r32, 32); rustsecp256k1_v0_4_0_sha256_write(&sha, pubkey32, 32); rustsecp256k1_v0_4_0_sha256_write(&sha, msg32, 32); rustsecp256k1_v0_4_0_sha256_finalize(&sha, buf); /* Set scalar e to the challenge hash modulo the curve order as per * BIP340. */ rustsecp256k1_v0_4_0_scalar_set_b32(e, buf, NULL); } int rustsecp256k1_v0_4_0_schnorrsig_sign(const rustsecp256k1_v0_4_0_context* ctx, unsigned char *sig64, const unsigned char *msg32, const rustsecp256k1_v0_4_0_keypair *keypair, rustsecp256k1_v0_4_0_nonce_function_hardened noncefp, void *ndata) { rustsecp256k1_v0_4_0_scalar sk; rustsecp256k1_v0_4_0_scalar e; rustsecp256k1_v0_4_0_scalar k; rustsecp256k1_v0_4_0_gej rj; rustsecp256k1_v0_4_0_ge pk; rustsecp256k1_v0_4_0_ge r; unsigned char buf[32] = { 0 }; unsigned char pk_buf[32]; unsigned char seckey[32]; int ret = 1; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); ARG_CHECK(sig64 != NULL); ARG_CHECK(msg32 != NULL); ARG_CHECK(keypair != NULL); if (noncefp == NULL) { noncefp = rustsecp256k1_v0_4_0_nonce_function_bip340; } ret &= rustsecp256k1_v0_4_0_keypair_load(ctx, &sk, &pk, keypair); /* Because we are signing for a x-only pubkey, the secret key is negated * before signing if the point corresponding to the secret key does not * have an even Y. */ if (rustsecp256k1_v0_4_0_fe_is_odd(&pk.y)) { rustsecp256k1_v0_4_0_scalar_negate(&sk, &sk); } rustsecp256k1_v0_4_0_scalar_get_b32(seckey, &sk); rustsecp256k1_v0_4_0_fe_get_b32(pk_buf, &pk.x); ret &= !!noncefp(buf, msg32, seckey, pk_buf, bip340_algo16, ndata); rustsecp256k1_v0_4_0_scalar_set_b32(&k, buf, NULL); ret &= !rustsecp256k1_v0_4_0_scalar_is_zero(&k); rustsecp256k1_v0_4_0_scalar_cmov(&k, &rustsecp256k1_v0_4_0_scalar_one, !ret); rustsecp256k1_v0_4_0_ecmult_gen(&ctx->ecmult_gen_ctx, &rj, &k); rustsecp256k1_v0_4_0_ge_set_gej(&r, &rj); /* We declassify r to allow using it as a branch point. This is fine * because r is not a secret. */ rustsecp256k1_v0_4_0_declassify(ctx, &r, sizeof(r)); rustsecp256k1_v0_4_0_fe_normalize_var(&r.y); if (rustsecp256k1_v0_4_0_fe_is_odd(&r.y)) { rustsecp256k1_v0_4_0_scalar_negate(&k, &k); } rustsecp256k1_v0_4_0_fe_normalize_var(&r.x); rustsecp256k1_v0_4_0_fe_get_b32(&sig64[0], &r.x); rustsecp256k1_v0_4_0_schnorrsig_challenge(&e, &sig64[0], msg32, pk_buf); rustsecp256k1_v0_4_0_scalar_mul(&e, &e, &sk); rustsecp256k1_v0_4_0_scalar_add(&e, &e, &k); rustsecp256k1_v0_4_0_scalar_get_b32(&sig64[32], &e); rustsecp256k1_v0_4_0_memczero(sig64, 64, !ret); rustsecp256k1_v0_4_0_scalar_clear(&k); rustsecp256k1_v0_4_0_scalar_clear(&sk); memset(seckey, 0, sizeof(seckey)); return ret; } int rustsecp256k1_v0_4_0_schnorrsig_verify(const rustsecp256k1_v0_4_0_context* ctx, const unsigned char *sig64, const unsigned char *msg32, const rustsecp256k1_v0_4_0_xonly_pubkey *pubkey) { rustsecp256k1_v0_4_0_scalar s; rustsecp256k1_v0_4_0_scalar e; rustsecp256k1_v0_4_0_gej rj; rustsecp256k1_v0_4_0_ge pk; rustsecp256k1_v0_4_0_gej pkj; rustsecp256k1_v0_4_0_fe rx; rustsecp256k1_v0_4_0_ge r; unsigned char buf[32]; int overflow; VERIFY_CHECK(ctx != NULL); ARG_CHECK(rustsecp256k1_v0_4_0_ecmult_context_is_built(&ctx->ecmult_ctx)); ARG_CHECK(sig64 != NULL); ARG_CHECK(msg32 != NULL); ARG_CHECK(pubkey != NULL); if (!rustsecp256k1_v0_4_0_fe_set_b32(&rx, &sig64[0])) { return 0; } rustsecp256k1_v0_4_0_scalar_set_b32(&s, &sig64[32], &overflow); if (overflow) { return 0; } if (!rustsecp256k1_v0_4_0_xonly_pubkey_load(ctx, &pk, pubkey)) { return 0; } /* Compute e. */ rustsecp256k1_v0_4_0_fe_get_b32(buf, &pk.x); rustsecp256k1_v0_4_0_schnorrsig_challenge(&e, &sig64[0], msg32, buf); /* Compute rj = s*G + (-e)*pkj */ rustsecp256k1_v0_4_0_scalar_negate(&e, &e); rustsecp256k1_v0_4_0_gej_set_ge(&pkj, &pk); rustsecp256k1_v0_4_0_ecmult(&ctx->ecmult_ctx, &rj, &pkj, &e, &s); rustsecp256k1_v0_4_0_ge_set_gej_var(&r, &rj); if (rustsecp256k1_v0_4_0_ge_is_infinity(&r)) { return 0; } rustsecp256k1_v0_4_0_fe_normalize_var(&r.y); return !rustsecp256k1_v0_4_0_fe_is_odd(&r.y) && rustsecp256k1_v0_4_0_fe_equal_var(&rx, &r.x); } #endif
bitcoincandyofficial/bitcoincandy-code
src/consensus/params.h
// Copyright (c) 2009-2010 <NAME> // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CONSENSUS_PARAMS_H #define BITCOIN_CONSENSUS_PARAMS_H #include "uint256.h" #include <map> #include <string> namespace Consensus { enum DeploymentPos { DEPLOYMENT_TESTDUMMY, // Deployment of BIP68, BIP112, and BIP113. DEPLOYMENT_CSV, // NOTE: Also add new deployments to VersionBitsDeploymentInfo in // versionbits.cpp MAX_VERSION_BITS_DEPLOYMENTS }; /** * Struct for each individual consensus rule change using BIP9. */ struct BIP9Deployment { /** Bit position to select the particular bit in nVersion. */ int bit; /** Start MedianTime for version bits miner confirmation. Can be a date in * the past */ int64_t nStartTime; /** Timeout/expiry MedianTime for the deployment attempt. */ int64_t nTimeout; }; /** * Parameters that influence chain consensus. */ struct Params { uint256 hashGenesisBlock; int nSubsidyHalvingInterval; /** Block height and hash at which BIP34 becomes active */ int BIP34Height; uint256 BIP34Hash; /** Block height at which BIP65 becomes active */ int BIP65Height; /** Block height at which BIP66 becomes active */ int BIP66Height; /** Block height at which UAHF kicks in */ int uahfHeight; /** Block height at which CDHF kicks in --add by hmc*/ int cdyHeight; /** Block height at which the new daa rule becomes active */ int nNewRuleHeight; /** Block height at which Zawy's LWMA difficulty algorithm becomes active */ int CDYZawyLWMAHeight; /** Block height at which Equihash<144,5> becomes active */ int CDYEquihashForkHeight; /** Height to publish compensing coins*/ uint32_t nCompenseHeight; /** Height to publish cdy community pool protection plan to prevent attacks, decrease sell pressure */ uint32_t nPoolProtectionPlan; // validated pool list std::vector<std::string> validPoolAddresses; /** Limit BITCOIN_MAX_FUTURE_BLOCK_TIME **/ int64_t CDYMaxFutureBlockTime; /** Unix time used for MTP activation of May 15 2018, hardfork */ int monolithActivationTime; /** Block height at which the new DAA becomes active */ /** The first post-fork block of Bitcoin blockchain. **/ uint256 BitcoinPostforkBlock; uint32_t BitcoinPostforkTime; int daaHeight; /** Block height at which OP_RETURN replay protection stops */ int antiReplayOpReturnSunsetHeight; /** Committed OP_RETURN value for replay protection */ std::vector<uint8_t> antiReplayOpReturnCommitment; /** * Minimum blocks including miner confirmation of the total of 2016 blocks * in a retargeting period, (nPowTargetTimespan / nPowTargetSpacing) which * is also used for BIP9 deployments. * Examples: 1916 for 95%, 1512 for testchains. */ uint32_t nRuleChangeActivationThreshold; uint32_t nMinerConfirmationWindow; BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]; /** Proof of work parameters */ uint256 powLimit; uint256 powLimitLegacy; uint256 powLimitStart; const uint256& PowLimit(bool postfork) const { return postfork ? powLimit : powLimitLegacy; } bool fPowAllowMinDifficultyBlocks; bool fPowNoRetargeting; int64_t nPowTargetSpacing; int64_t nPowTargetSpacingCDY; int64_t nPowTargetTimespanLegacy; int64_t DifficultyAdjustmentInterval() const { return nPowTargetTimespanLegacy / nPowTargetSpacing; } //Zcash logic for diff adjustment int64_t nDigishieldAveragingWindow; int64_t nDigishieldMaxAdjustDown; int64_t nDigishieldMaxAdjustUp; int64_t DigishieldAveragingWindowTimespan() const { return nDigishieldAveragingWindow * nPowTargetSpacingCDY; } int64_t DigishieldMinActualTimespan() const { return (DigishieldAveragingWindowTimespan() * (100 - nDigishieldMaxAdjustUp )) / 100; } int64_t DigishieldMaxActualTimespan() const { return (DigishieldAveragingWindowTimespan() * (100 + nDigishieldMaxAdjustDown)) / 100; } uint256 nMinimumChainWork; uint256 defaultAssumeValid; // Params for Zawy's LWMA difficulty adjustment algorithm. (Used by testnet and regtest) int64_t nZawyLwmaAveragingWindow; // N int64_t nZawyLwmaAjustedWeight; // k = (N+1)/2 * 0.9989^(500/N) * T }; } // namespace Consensus #endif // BITCOIN_CONSENSUS_PARAMS_H
julieeen/KleeFL
example/example.c
<reponame>julieeen/KleeFL #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int buffer[256]; void init_buffer(){ int i; for (i = 0; i < 256; ++i){ buffer[i] = i; } } int processing_data(char * filename) { char stack_buffer[32]; char* heap_buffer = malloc(32); FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen(filename, "r"); if (fp == NULL) exit(EXIT_FAILURE); // processing lines in file while ((read = getline(&line, &len, fp)) != -1) { //printf("parsing line of length %zu :", read); printf("read> %s", line); // skip short lines if(read < 5) continue; // BUG: BUFFER OVERFLOW // DETECTED BY Klee->AFL setup // line starts with "stack", load rest of line to stack_buff if(!strncmp(line,"stack",5)){ //printf("found mem load marker\n"); char copy[read-5]; strncpy(copy, line+5, strlen(line)-1); strcpy(stack_buffer, copy); printf("load to stack: %s", stack_buffer); continue; } // BUG: DIV BY ZERO (could be also format string vuln?) // line starts with "value" if(!strncmp(line,"value",5)){ //printf("found mem load marker\n"); char copy[read-5]; strncpy(copy, line+5, strlen(line)-1); int value = atoi(copy); float a = (100/(42-value)); printf("\ncalc 100/(42-%d) \n",value); // found by KLEE (and AFL) printf("= %f\n",a); continue; } // BUG: OUT OF BOUNDS READ // found by AFL if(!strncmp(line,"buffr",5)){ //printf("found mem load marker\n"); init_buffer(); char copy[read-5]; strncpy(copy, line+5, strlen(line)-1); int value = atoi(copy); printf("\nread value from buffer[%d]\n",value); printf("= %d\n",buffer[value]); printf("\ncalc 100/(42-buffer[%d]) \n", buffer[value]); float a = (100/(42-buffer[value])); printf("= %f\n",a); continue; } } return 0; } int main (int argc, char **argv){ int hflag = 0; char* file_input = NULL; int index; int c; int heap_mode = 0; int stack_mode = 0; opterr = 0; while ((c = getopt (argc, argv, "hf:")) != -1) switch (c){ case 'h': hflag = 1; break; case 'f': file_input = optarg; break; case '?': if (optopt == 'f') fprintf (stderr, "Option -%c requires input file\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } for (index = optind; index < argc; index++){ printf ("Non-option argument %s\n", argv[index]); // here you can find an official not suported option \o/ if(!strcmp(argv[index], "secret_mode")){ printf("You found the super secret mode!\n"); return 0; } } if(hflag){ printf("Helptext: "); printf("One can use one of the following options:\n"); printf("-h\t\tshow this help text\n"); printf("-f <file>\tdo calc based on a file input\n"); printf("???\t\tmore options still under development\n"); return 0; } if(file_input){ processing_data(file_input); return 0; } return 0; }
julieeen/KleeFL
example/example_old.c
<filename>example/example_old.c #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int DEF_BUF_SIZE = 8; int history[4] = { 100, 42, -42, 33 }; int read_from_file(char *); int main (int argc, char **argv){ int hflag = 0; int iflag = 0; int pflag = 0; char stack_buffer[11]; char* heap_buffer = malloc(11); char* file_input = NULL; char* user_input = NULL; int index; int c; int heap_mode = 0; int stack_mode = 0; int hist_index = 0; opterr = 0; while ((c = getopt (argc, argv, "hi:f:p:")) != -1) switch (c){ case 'h': hflag = 1; break; // case 'i': iflag = 1; user_input = optarg; break; case 'f': file_input = optarg; break; // case 'p': pflag = 1; hist_index = atoi(optarg); break; case '?': // if (optopt == 'i') // fprintf (stderr, "Option -%c requires an input argument\n", optopt); else if (optopt == 'f') fprintf (stderr, "Option -%c requires input file\n", optopt); // else if (optopt == 'p') // fprintf (stderr, "Option -%c requires history index num\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } for (index = optind; index < argc; index++){ printf ("Non-option argument %s\n", argv[index]); if(!strcmp(argv[index], "stack")){ printf("You found the super secret stack mode!\n"); stack_mode = 1; } if(!strcmp(argv[index], "heap")){ printf("You found the super secret heap mode!\n"); heap_mode = 1; } } if(hflag){ printf("Helptext: "); printf("One can use one of the following options:\n"); printf("-h\t\tshow this help text\n"); printf("-i\t\tdo calc based on a given number\n"); printf("-f <file>\tdo calc based on a file input\n"); printf("-p {prev} \tdo calc based on previous input\n"); printf("???\t\tmore options always still under development\n"); return 0; } // BUG: stack overflow if file contains to long string if(stack_mode && file_input){ printf("(secret) strcpy buffer code :X\n"); FILE *fp; fp = fopen(file_input,"r"); if(fp == NULL){ perror("Error: "); exit(EXIT_FAILURE); } char line[1024]; if(strlen(fgets(line, sizeof(line), fp)) > 0){ printf("copy %lu bytes to stack\n",strlen(line)); strcpy(stack_buffer, line); } return 0; } // BUG: heap overflow if file contains to long string if(heap_mode && file_input){ printf("strcpy file on heap :X\n"); FILE *fp; fp = fopen(file_input,"r"); // read file if(fp == NULL){ perror("Error: "); exit(EXIT_FAILURE); } char line[1024]; if(strlen(fgets(line, sizeof(line), fp)) > 0){ printf("copy %lu bytes to stack\n",strlen(line)); strcpy(stack_buffer, line); // BUG: BUFFER OVERFLOW (SEGFAULT) } strcpy(heap_buffer, line); // BUG: HEAP OVERFLOW return 0; } // BUG when index = 2, Found by klee (fast) // BUG when index out of bounds, Found by klee (fast) if(pflag){ printf("Do calc based on history[%d]: %d\n", hist_index, history[hist_index]); int saved_value = history[hist_index]; // BUG: OUT OF BOUND INDEX SEGFAULT float a = (100 / (42+saved_value)); printf("magic(%d) = %f \n",saved_value, a); return 0; } // BUG when file_value == user_value if(iflag && file_input){ printf("calculation based on file and user input :) \n"); int user_value = atof(user_input); int file_value = read_from_file(file_input); float a = (100 / (user_value - file_value)); printf("magic(%d,%d) = %f \n",user_value, file_value, a); return 0; } // BUG when user input = 42, found by klee (fast) if(iflag){ printf("Calculating with user input: %s\n",user_input); int user_value = atoi(user_input); float a = (100/(42-user_value)); printf("f(%d) = %f \n",user_value, a); return 0; } // BUG when file_value = 42, Found by klee (midtime) if(file_input){ printf("super safe file read and calculate\n"); int user_value = read_from_file(file_input); printf("calculate with value: %d \n",user_value); float a = (100/(42-user_value)); printf("f(%d) = %f \n",user_value, a); return 0; } return 0; } // safe read from file int read_from_file(char * file_input){ FILE *fp; fp = fopen(file_input,"r"); // read file if(fp == NULL){ perror("Error: "); exit(EXIT_FAILURE); } // maxint = 2147483647 char buffer[11]; if(!fgets(buffer, sizeof(buffer), fp)){ printf("nothing to read\n"); exit(EXIT_FAILURE); } buffer[10] = '\x00'; return atoi(buffer); }
junipertcy/network-archaeology
generators/src/models.h
<gh_stars>0 #ifndef MODELS_H #define MODELS_H #include "growth_model.h" #include "unstructured_models/delayed.h" #include "structured_models/bianconi_barabasi.h" #include "structured_models/gn.h" #endif // MODELS_h
junipertcy/network-archaeology
generators/src/unstructured_models/delayed.h
#ifndef DELAYED_H #define DELAYED_H #include <cmath> #include "../growth_model.h" #include "../types.h" class delayed_model : public unstructured_model { public: // no seed constructor delayed_model(double a, double alpha, double b, double mu, double tau); void intialize(unsigned int T); // overloaded step function void step(unsigned int t, std::mt19937& engine); // model specific double p(unsigned int t) const; double weight(id_t token) const; private: double_vec_t params_; }; #endif // DELAYED_H
junipertcy/network-archaeology
generators/src/gn_gen_model.h
#ifndef GN_GEN_MODEL_H #define GN_GEN_MODEL_H #include <cmath> #include "growth_model.h" #include "types.h" class gn_gen_model_t : public structured_model_t { public: // no seed constructor gn_gen_model_t(double a, double alpha, double b, unsigned int m1, unsigned int m2, double mu, double tau, bool directed=false); void intialize(unsigned int T); // overloaded step function void step(unsigned int t, std::mt19937& engine); // model specific double weight(id_t token) const; double p(unsigned int t) const; private: double a_; double alpha_; double b_; unsigned int m1_; unsigned int m2_; double mu_; double tau_; adj_list_t adj_list_; bool directed_; }; #endif // GN_GEN_MODEL_H
junipertcy/network-archaeology
generators/src/config.h
#define HAVE_LIBBOOST_PROGRAM_OPTIONS 0 #define HAVE_STEADY_CLOCK 1 #define NDEBUG 1
junipertcy/network-archaeology
generators/src/structured_models/gn.h
#ifndef GN_H #define GN_H #include <cmath> #include "../growth_model.h" #include "../types.h" class gn_model : public structured_model { public: // no seed constructor gn_model(double gamma, unsigned int m); void intialize(unsigned int T); // overloaded step function void step(unsigned int t, std::mt19937& engine); // model specific double weight(id_t token) const; private: double gamma_; unsigned int m_; }; class generalized_gn_model : public structured_model { public: // no seed constructor generalized_gn_model(double a, double alpha, double b, unsigned int m1, unsigned int m2, double gamma, double tau, bool directed=false); void intialize(unsigned int T); // overloaded step function void step(unsigned int t, std::mt19937& engine); // model specific double weight(id_t token) const; double p(unsigned int t) const; private: double a_; double alpha_; double b_; unsigned int m1_; unsigned int m2_; double gamma_; double tau_; adj_list_t adj_list_; bool directed_; }; #endif // GN_H
junipertcy/network-archaeology
generators/src/structured_models/bianconi_barabasi.h
<gh_stars>0 #ifndef BIANCONI_BARABASI_H #define BIANCONI_BARABASI_H #include <cmath> #include <random> #include "../growth_model.h" #include "../types.h" class bianconi_barabasi_model : public structured_model { public: // no seed constructor bianconi_barabasi_model(double mu, double nu, double avg=1, double std=0, unsigned int m=1); void intialize(unsigned int T); // overloaded step function void step(unsigned int t, std::mt19937& engine); // model specific double weight(id_t token) const; private: double mu_; double nu_; unsigned int m_; double avg_; std::normal_distribution<double> normal_distribution_; }; #endif // BIANCONI_BARABASI_H
junipertcy/network-archaeology
generators/src/types.h
#ifndef TYPES_H #define TYPES_H #include <vector> #include <set> #include <utility> typedef unsigned int id_t; typedef std::pair<id_t, id_t> edge_t; typedef std::vector<edge_t> edge_list_t; typedef std::multiset<id_t> neighbourhood_t; typedef std::vector<neighbourhood_t> adj_list_t; typedef struct mcmc_move_t { id_t t; id_t token; } mcmc_move_t; typedef std::vector<unsigned int> uint_vec_t; typedef std::vector<id_t> id_vec_t; typedef std::vector<int> int_vec_t; typedef std::vector<float> float_vec_t; typedef std::vector<double> double_vec_t; typedef std::vector< std::vector<unsigned int> > uint_mat_t; typedef std::vector< std::vector<int> > int_mat_t; typedef std::vector< std::vector<float> > float_mat_t; #endif // TYPES_H
junipertcy/network-archaeology
generators/src/growth_model.h
<reponame>junipertcy/network-archaeology<filename>generators/src/growth_model.h #ifndef GROWTH_MODEL_H #define GROWTH_MODEL_H #include <iostream> #include <map> #include <random> #include "types.h" class growth_model { protected: // history of the system id_vec_t history_; id_t max_token_; // map of tokens to their state variables (degree, fitness, momentum, etc.) std::map<id_t, double_vec_t> token_states_; double normalization_; // sum of all token absolute weights (weight function dependent) // internal distribution std::uniform_real_distribution<> rand_real_; public: growth_model() : rand_real_(0, 1) {;} /// @name Virtual functions //{@ // advance the model one step virtual void step(unsigned int t, std::mt19937& engine) {return;} // reset history virtual void intialize(unsigned int T) {history_.reserve(T); return;} // absolute weight of a token given its state virtual double weight(id_t token) const {return 1.0;} //@} /// @name Accessors //@{ id_t random_token(std::mt19937 & engine) { double accu = 0; double random_real = rand_real_(engine) * normalization_; for (auto const & kv : token_states_) { accu += weight(kv.first); if (random_real <= accu) return kv.first; } return max_token_; } void print_states(std::ostream& os) const { for (auto const & kv: token_states_) { for (auto const & v: kv.second) { os << v << " "; } os << "\n"; } return; } id_vec_t get_history() const {return history_;} virtual void print_history(std::ostream& os) const {return;} //@} void run(unsigned int T, std::mt19937& engine) { intialize(T); for (unsigned int t = 0; t < T; ++t) step(t, engine); } }; class unstructured_model : public growth_model { public: void print_history(std::ostream& os) const { for (auto t: history_) os << t << "\n"; return; } }; class structured_model : public growth_model { public: void print_history(std::ostream& os) const { for (unsigned int t = 0; t < history_.size(); t+=2) { if (history_[t] > history_[t + 1]) { os << history_[t + 1] << " " << history_[t] << "\n"; } else { os << history_[t] << " " << history_[t + 1] << "\n"; } } return; } }; #endif // GROWTH_MODEL_H
myluoxz/osm-research.cpp
src/edge.h
#ifndef EDGE_H_ #define EDGE_H_ #include "node.h" struct Edge { public: int from, to; double w; // map<string, string> attrs; }; bool operator < (const Edge &x, const Edge &y) { return x.from == y.from ? x.to < y.to : x.from < y.from; } #endif /// EDGE_H_
myluoxz/osm-research.cpp
src/graph.h
#ifndef GRAPH_H_ #define GRAPH_H_ #include "edge.h" #include <string> #include <vector> class Graph { public: int V, E; double minlat = 1000, maxlat = -1000, minlon = 1000, maxlon = -1000; std::vector<Node> ns; std::vector<std::vector<Edge>> es; Graph(); Graph (int _V); Graph (const std::string& filename); void Serialize(const std::string& filename); }; #endif /// GRAPH_H_
myluoxz/osm-research.cpp
src/node.h
<reponame>myluoxz/osm-research.cpp #ifndef NODE_H_ #define NODE_H_ struct Node { public: int id; double lat, lon; // map<string, string> attrs; }; #endif /// NODE_H_
myluoxz/osm-research.cpp
lib/UnionFind/union_find.h
<reponame>myluoxz/osm-research.cpp<filename>lib/UnionFind/union_find.h #ifndef UNION_FIND_H_ #define UNION_FIND_H_ #include <vector> struct UnionFind { std::vector<int> parent; UnionFind (int n) : parent(n, -1) {} int root(int x); bool merge(int x, int y); }; #endif /// UNION_FIND_H_
romanarranz/DSD
P1/listas_c/llist.c
/* llist printer RPC client by <NAME> */ #include "llist.h" list *mk_list(char *data, int key, color c) { list *lst; lst = (list*)malloc(sizeof(list)); if (lst == NULL) return NULL; lst->data = data; lst->key = key; lst->col = c; lst->next = NULL; return lst; } int main(int argc, char *argv[]) { list *l, *new; CLIENT *cl; int *result; if (argc < 2) return 1; l = new = mk_list("one", 1, ORANGE); new = mk_list("two", 2, TURQUOISE); new->next = l; l = new; new = mk_list("three", 3, ORANGE); new->next = l; l = new; cl = clnt_create(argv[1], PRINTER, PRINTER_V1, "tcp"); if (cl == NULL) { printf("error: could not connect to server.\n"); return 1; } result = print_list_1(l, cl); if (result == NULL) { printf("error: RPC failed!\n"); return 1; } printf("client: server says it printed %d items.\n", *result); return 0; }
romanarranz/DSD
P1/rpc_programa/rpc.h
/* * Please do not edit this file. * It was generated using rpcgen. */ #ifndef _RPC_H_RPCGEN #define _RPC_H_RPCGEN #include <rpc/rpc.h> #ifdef __cplusplus extern "C" { #endif struct suma_1_argument { int arg1; int arg2; }; typedef struct suma_1_argument suma_1_argument; #define SUMA 0x20000001 #define SUMAVER 1 #if defined(__STDC__) || defined(__cplusplus) #define suma 1 extern int * suma_1(int , int , CLIENT *); extern int * suma_1_svc(int , int , struct svc_req *); extern int suma_1_freeresult (SVCXPRT *, xdrproc_t, caddr_t); #else /* K&R C */ #define suma 1 extern int * suma_1(); extern int * suma_1_svc(); extern int suma_1_freeresult (); #endif /* K&R C */ /* the xdr functions */ #if defined(__STDC__) || defined(__cplusplus) extern bool_t xdr_suma_1_argument (XDR *, suma_1_argument*); #else /* K&R C */ extern bool_t xdr_suma_1_argument (); #endif /* K&R C */ #ifdef __cplusplus } #endif #endif /* !_RPC_H_RPCGEN */
romanarranz/DSD
P1/msg_programa1/rprintmsg.c
<filename>P1/msg_programa1/rprintmsg.c /* Archivo rprintmsg.c: programa cliente */ #include <stdio.h> #include "msg.h" main(argc, argv) int argc; char *argv[]; { CLIENT *clnt; int *result; char *server; char *message; if (argc != 3) { fprintf(stderr, "uso: %s maquina mensaje\n", argv[0]); exit(1); } server = argv[1]; message = argv[2]; /* Crea estructura de datos(handle) del proceso cliente para el servidor designado */ clnt = clnt_create(server, MESSAGEPROG, PRINTMESSAGEVERS,"visible"); if (clnt == (CLIENT *)NULL) { /* No se pudo establecer conexion con el servidor */ clnt_pcreateerror(server); exit(1); } /* Llamada remota al procedimiento en el servidor */ result = printmessage_1(&message, clnt); if (result == (int *)NULL) { /* Ocurrio un error durante la llamada al servidor */ clnt_perror(clnt, server); exit(1); } if (*result == 0) { /* El servidor fue incapaz de imprimir nuestro mensaje */ fprintf(stderr, "%s: no pudo imprimir el mensaje\n", argv[0]); exit(1); } printf("Mensaje enviado a %s\n", server); clnt_destroy( clnt ); exit(0); }
romanarranz/DSD
P1/calculadora/calculadora_clnt.c
<reponame>romanarranz/DSD /* * Please do not edit this file. * It was generated using rpcgen. */ #include <memory.h> /* for memset */ #include "calculadora.h" /* Default timeout can be changed using clnt_control() */ static struct timeval TIMEOUT = { 25, 0 }; double * suma_1(int arg1, int arg2, CLIENT *clnt) { suma_1_argument arg; static double clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); arg.arg1 = arg1; arg.arg2 = arg2; if (clnt_call (clnt, suma, (xdrproc_t) xdr_suma_1_argument, (caddr_t) &arg, (xdrproc_t) xdr_double, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } double * resta_1(int arg1, int arg2, CLIENT *clnt) { resta_1_argument arg; static double clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); arg.arg1 = arg1; arg.arg2 = arg2; if (clnt_call (clnt, resta, (xdrproc_t) xdr_resta_1_argument, (caddr_t) &arg, (xdrproc_t) xdr_double, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } double * multiplicacion_1(int arg1, int arg2, CLIENT *clnt) { multiplicacion_1_argument arg; static double clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); arg.arg1 = arg1; arg.arg2 = arg2; if (clnt_call (clnt, multiplicacion, (xdrproc_t) xdr_multiplicacion_1_argument, (caddr_t) &arg, (xdrproc_t) xdr_double, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } double * division_1(int arg1, int arg2, CLIENT *clnt) { division_1_argument arg; static double clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); arg.arg1 = arg1; arg.arg2 = arg2; if (clnt_call (clnt, division, (xdrproc_t) xdr_division_1_argument, (caddr_t) &arg, (xdrproc_t) xdr_double, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); }
romanarranz/DSD
P1/asociaciones/asociaciones_clnt.c
/* * Please do not edit this file. * It was generated using rpcgen. */ #include <memory.h> /* for memset */ #include "asociaciones.h" /* Default timeout can be changed using clnt_control() */ static struct timeval TIMEOUT = { 25, 0 }; Estado * ponerasociacion_1(ID arg1, Clave arg2, Valor arg3, CLIENT *clnt) { ponerasociacion_1_argument arg; static Estado clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); arg.arg1 = arg1; arg.arg2 = arg2; arg.arg3 = arg3; if (clnt_call (clnt, PonerAsociacion, (xdrproc_t) xdr_ponerasociacion_1_argument, (caddr_t) &arg, (xdrproc_t) xdr_Estado, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } valor_estado * obtenerasociacion_1(ID arg1, Clave arg2, CLIENT *clnt) { obtenerasociacion_1_argument arg; static valor_estado clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); arg.arg1 = arg1; arg.arg2 = arg2; if (clnt_call (clnt, ObtenerAsociacion, (xdrproc_t) xdr_obtenerasociacion_1_argument, (caddr_t) &arg, (xdrproc_t) xdr_valor_estado, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } Estado * borrarasociacion_1(ID arg1, Clave arg2, CLIENT *clnt) { borrarasociacion_1_argument arg; static Estado clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); arg.arg1 = arg1; arg.arg2 = arg2; if (clnt_call (clnt, BorrarAsociacion, (xdrproc_t) xdr_borrarasociacion_1_argument, (caddr_t) &arg, (xdrproc_t) xdr_Estado, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } asociacion_estado * enumerar_1(ID arg1, CLIENT *clnt) { static asociacion_estado clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, Enumerar, (xdrproc_t) xdr_ID, (caddr_t) &arg1, (xdrproc_t) xdr_asociacion_estado, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); }
romanarranz/DSD
P1/asociaciones/asociaciones_xdr.c
/* * Please do not edit this file. * It was generated using rpcgen. */ #include "asociaciones.h" bool_t xdr_Estado (XDR *xdrs, Estado *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_ID (XDR *xdrs, ID *objp) { register int32_t *buf; if (!xdr_int (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_Clave (XDR *xdrs, Clave *objp) { register int32_t *buf; if (!xdr_string (xdrs, objp, 255)) return FALSE; return TRUE; } bool_t xdr_Valor (XDR *xdrs, Valor *objp) { register int32_t *buf; if (!xdr_string (xdrs, objp, 255)) return FALSE; return TRUE; } bool_t xdr_asociacion (XDR *xdrs, asociacion *objp) { register int32_t *buf; if (!xdr_Clave (xdrs, &objp->clave)) return FALSE; if (!xdr_Valor (xdrs, &objp->valor)) return FALSE; if (!xdr_pointer (xdrs, (char **)&objp->next, sizeof (asociacion), (xdrproc_t) xdr_asociacion)) return FALSE; return TRUE; } bool_t xdr_valor_estado (XDR *xdrs, valor_estado *objp) { register int32_t *buf; if (!xdr_Valor (xdrs, &objp->valor)) return FALSE; if (!xdr_Estado (xdrs, &objp->s)) return FALSE; return TRUE; } bool_t xdr_asociacion_estado (XDR *xdrs, asociacion_estado *objp) { register int32_t *buf; if (!xdr_pointer (xdrs, (char **)&objp->asoc, sizeof (asociacion), (xdrproc_t) xdr_asociacion)) return FALSE; if (!xdr_Estado (xdrs, &objp->s)) return FALSE; return TRUE; } bool_t xdr_ponerasociacion_1_argument (XDR *xdrs, ponerasociacion_1_argument *objp) { if (!xdr_ID (xdrs, &objp->arg1)) return FALSE; if (!xdr_Clave (xdrs, &objp->arg2)) return FALSE; if (!xdr_Valor (xdrs, &objp->arg3)) return FALSE; return TRUE; } bool_t xdr_obtenerasociacion_1_argument (XDR *xdrs, obtenerasociacion_1_argument *objp) { if (!xdr_ID (xdrs, &objp->arg1)) return FALSE; if (!xdr_Clave (xdrs, &objp->arg2)) return FALSE; return TRUE; } bool_t xdr_borrarasociacion_1_argument (XDR *xdrs, borrarasociacion_1_argument *objp) { if (!xdr_ID (xdrs, &objp->arg1)) return FALSE; if (!xdr_Clave (xdrs, &objp->arg2)) return FALSE; return TRUE; }
romanarranz/DSD
P1/rpc_programa/rpc_client.c
<reponame>romanarranz/DSD /* * This is sample code generated by rpcgen. * These are only templates and you can use them * as a guideline for developing your own functions. */ #include "rpc.h" void suma_1(char *host) { CLIENT *clnt; int *result_1; int suma_1_arg1; int suma_1_arg2; #ifndef DEBUG clnt = clnt_create (host, SUMA, SUMAVER, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ result_1 = suma_1(suma_1_arg1, suma_1_arg2, clnt); if (result_1 == (int *) NULL) { clnt_perror (clnt, "call failed"); } #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ } int main (int argc, char *argv[]) { char *host; if (argc < 2) { printf ("usage: %s server_host\n", argv[0]); exit (1); } host = argv[1]; suma_1 (host); exit (0); }
romanarranz/DSD
P1/asociaciones/backups/asociaciones.h
<reponame>romanarranz/DSD /* * Please do not edit this file. * It was generated using rpcgen. */ #ifndef _ASOCIACIONES_H_RPCGEN #define _ASOCIACIONES_H_RPCGEN #include <rpc/rpc.h> #ifdef __cplusplus extern "C" { #endif enum Estado { OK = 0, Sustitucion = 1, NoEncontrado = 2, }; typedef enum Estado Estado; typedef int ID; typedef char *Clave; typedef char *Valor; struct asociacion { Clave clave; Valor valor; struct asociacion *next; }; typedef struct asociacion asociacion; struct valor_estado { Valor valor; Estado s; }; typedef struct valor_estado valor_estado; struct asociacion_estado { asociacion *asoc; Estado s; }; typedef struct asociacion_estado asociacion_estado; struct ponerasociacion_1_argument { ID arg1; Clave arg2; Valor arg3; }; typedef struct ponerasociacion_1_argument ponerasociacion_1_argument; struct obtenerasociacion_1_argument { ID arg1; Clave arg2; }; typedef struct obtenerasociacion_1_argument obtenerasociacion_1_argument; struct borrarasociacion_1_argument { ID arg1; Clave arg2; }; typedef struct borrarasociacion_1_argument borrarasociacion_1_argument; #define ASOCIACIONES 0x20000002 #define ASOCIACIONESVER 1 #if defined(__STDC__) || defined(__cplusplus) #define PonerAsociacion 1 extern Estado * ponerasociacion_1(ID , Clave , Valor , CLIENT *); extern Estado * ponerasociacion_1_svc(ID , Clave , Valor , struct svc_req *); #define ObtenerAsociacion 2 extern valor_estado * obtenerasociacion_1(ID , Clave , CLIENT *); extern valor_estado * obtenerasociacion_1_svc(ID , Clave , struct svc_req *); #define BorrarAsociacion 3 extern Estado * borrarasociacion_1(ID , Clave , CLIENT *); extern Estado * borrarasociacion_1_svc(ID , Clave , struct svc_req *); #define Enumerar 4 extern asociacion_estado * enumerar_1(ID , CLIENT *); extern asociacion_estado * enumerar_1_svc(ID , struct svc_req *); extern int asociaciones_1_freeresult (SVCXPRT *, xdrproc_t, caddr_t); #else /* K&R C */ #define PonerAsociacion 1 extern Estado * ponerasociacion_1(); extern Estado * ponerasociacion_1_svc(); #define ObtenerAsociacion 2 extern valor_estado * obtenerasociacion_1(); extern valor_estado * obtenerasociacion_1_svc(); #define BorrarAsociacion 3 extern Estado * borrarasociacion_1(); extern Estado * borrarasociacion_1_svc(); #define Enumerar 4 extern asociacion_estado * enumerar_1(); extern asociacion_estado * enumerar_1_svc(); extern int asociaciones_1_freeresult (); #endif /* K&R C */ /* the xdr functions */ #if defined(__STDC__) || defined(__cplusplus) extern bool_t xdr_Estado (XDR *, Estado*); extern bool_t xdr_ID (XDR *, ID*); extern bool_t xdr_Clave (XDR *, Clave*); extern bool_t xdr_Valor (XDR *, Valor*); extern bool_t xdr_asociacion (XDR *, asociacion*); extern bool_t xdr_valor_estado (XDR *, valor_estado*); extern bool_t xdr_asociacion_estado (XDR *, asociacion_estado*); extern bool_t xdr_ponerasociacion_1_argument (XDR *, ponerasociacion_1_argument*); extern bool_t xdr_obtenerasociacion_1_argument (XDR *, obtenerasociacion_1_argument*); extern bool_t xdr_borrarasociacion_1_argument (XDR *, borrarasociacion_1_argument*); #else /* K&R C */ extern bool_t xdr_Estado (); extern bool_t xdr_ID (); extern bool_t xdr_Clave (); extern bool_t xdr_Valor (); extern bool_t xdr_asociacion (); extern bool_t xdr_valor_estado (); extern bool_t xdr_asociacion_estado (); extern bool_t xdr_ponerasociacion_1_argument (); extern bool_t xdr_obtenerasociacion_1_argument (); extern bool_t xdr_borrarasociacion_1_argument (); #endif /* K&R C */ #ifdef __cplusplus } #endif #endif /* !_ASOCIACIONES_H_RPCGEN */
romanarranz/DSD
P1/rpc_programa/rpc_clnt.c
<reponame>romanarranz/DSD /* * Please do not edit this file. * It was generated using rpcgen. */ #include <memory.h> /* for memset */ #include "rpc.h" /* Default timeout can be changed using clnt_control() */ static struct timeval TIMEOUT = { 25, 0 }; int * suma_1(int arg1, int arg2, CLIENT *clnt) { suma_1_argument arg; static int clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); arg.arg1 = arg1; arg.arg2 = arg2; if (clnt_call (clnt, suma, (xdrproc_t) xdr_suma_1_argument, (caddr_t) &arg, (xdrproc_t) xdr_int, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); }
romanarranz/DSD
P1/rpc_programa/rpc_xdr.c
/* * Please do not edit this file. * It was generated using rpcgen. */ #include "rpc.h" bool_t xdr_suma_1_argument (XDR *xdrs, suma_1_argument *objp) { if (!xdr_int (xdrs, &objp->arg1)) return FALSE; if (!xdr_int (xdrs, &objp->arg2)) return FALSE; return TRUE; }
romanarranz/DSD
P1/calculadora/calculadora_client.c
<reponame>romanarranz/DSD<gh_stars>0 #include "calculadora.h" #include <stdio.h> #include <stdlib.h> void calculadora_1(char *host, int operando1, char operador, int operando2) { CLIENT *clnt; double *result, *result2; char op; int a, b; #ifndef DEBUG clnt = clnt_create (host, CALCULADORA, CALCULADORAVER, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ a = operando1; op = operador; b = operando2; printf("%i %c %i = ", a, op, b); switch(op){ case '+': result = suma_1(a, b, clnt); printf("%lf \n", *result); break; case '-': result = resta_1(a, b, clnt); printf("%lf \n", *result); break; case 'x': result = multiplicacion_1(a, b, clnt); printf("%lf \n", *result); break; case '/': result = division_1(a, b, clnt); printf("%lf \n", *result); break; }; if( result == NULL) { clnt_perror (clnt, "call failed"); } #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ } int main (int argc, char *argv[]) { char *host; int operando1, operando2; char operador; if (argc != 5) { printf ("usage: %s <hostname/ip> <entero> <operador> <entero>\n", argv[0]); exit (1); } host = argv[1]; operando1 = atoi(argv[2]); operador = (char)argv[3][0]; operando2 = atoi(argv[4]); calculadora_1 (host, operando1, operador, operando2); exit (0); }
romanarranz/DSD
P1/rpc_programa/rpc_server.c
<filename>P1/rpc_programa/rpc_server.c /* * This is sample code generated by rpcgen. * These are only templates and you can use them * as a guideline for developing your own functions. */ #include "rpc.h" int * suma_1_svc(int arg1, int arg2, struct svc_req *rqstp) { static int result; /* * insert server code here */ return &result; }
romanarranz/DSD
P1/msg_programa1/msg_proc.c
/* msg_proc.c: implementacion del procedimiento remoto */ #include <stdio.h> #include "msg.h" /* el archivo lo genera rpcgen */ int * printmessage_1(msg, req) char **msg; struct svc_req *req; /* detalles de la llamada */ { static int result; /* es obligatorio que sea estatica */ FILE *f; f = fopen("/dev/console", "w"); if (f == (FILE *)NULL) { result = 0; return (&result); } fprintf(f,"%s\n", *msg); fclose(f); result = 1; return (&result); }
romanarranz/DSD
P1/asociaciones/backups/asociaciones_server.c
#include "asociaciones.h" typedef struct ListaDeAsociaciones{ ID id; asociacion *inicio; asociacion *fin; struct ListaDeAsociaciones * sig; } Lista; Lista * primero = (Lista *) NULL; Lista * ultimo = (Lista *) NULL; Estado * ponerasociacion_1_svc(ID arg1, Clave arg2, Valor arg3, struct svc_req *rqstp) { static Estado result; if( primero == NULL ){ // reservo memoria para la nueva celda de la lista Lista * nuevo = (Lista *) malloc (sizeof(Lista)); nuevo->id = arg1; nuevo->inicio = NULL; nuevo->fin = NULL; nuevo->sig = NULL; // reservo memoria para la nueva asociacion de la celda de la lista asociacion * key_value = (asociacion *) malloc (sizeof(asociacion)); key_value->clave = (char *) malloc (255 * sizeof (char)); key_value->valor = (char *) malloc (255 * sizeof (char)); strcpy( key_value->clave, arg2); strcpy( key_value->valor, arg3); key_value->next = NULL; nuevo->inicio = key_value; nuevo->fin = key_value; primero = nuevo; ultimo = nuevo; result = OK; } else { int findID = 0; int findAsoc = 0; Lista * aux = primero; asociacion * aux2; while( aux != NULL && findID == 0 ){ // si encontramos el id en la lista de asociaciones insertamos una nueva asociacion en esa celda if( arg1 == aux->id ){ findID = 1; // procedemos a ver si la clave que queremos insertar ya existe en la lista de asociaciones aux2 = aux->inicio; while(aux2 != NULL && findAsoc == 0){ if(strcmp( aux2->clave , arg2) == 0){ findAsoc = 1; strcpy(aux2->valor, arg3); result = Sustitucion; } aux2 = aux2->next; } // si no se encontró la clave en la lista de asociaciones la insertamos al final la nueva asociacion if(findAsoc == 0) { asociacion * key_value = (asociacion *) malloc (sizeof(asociacion)); key_value->clave = (char *) malloc (255 * sizeof (char)); key_value->valor = (char *) malloc (255 * sizeof (char)); strcpy( key_value->clave, arg2); strcpy( key_value->valor, arg3); key_value->next = NULL; if(aux->inicio != NULL && aux->fin != NULL){ aux->fin->next = key_value; aux->fin = key_value; } else { aux->inicio = key_value; aux->fin = key_value; } result = OK; } } aux = aux->sig; } // si NO hemos encontrado el id en la lista de asociaciones insertarmos una nueva celda en la lista if(findID == 0) { // reservo memoria para la nueva celda de la lista Lista * nuevo = (Lista *) malloc (sizeof(Lista)); nuevo->id = arg1; nuevo->inicio = NULL; nuevo->fin = NULL; nuevo->sig = NULL; // reservo memoria para la nueva asociacion de esa celda de la lista asociacion * key_value = (asociacion *) malloc (sizeof(asociacion)); key_value->clave = (char *) malloc (255 * sizeof (char)); key_value->valor = (char *) malloc (255 * sizeof (char)); strcpy( key_value->clave, arg2); strcpy( key_value->valor, arg3); key_value->next = NULL; nuevo->inicio = key_value; nuevo->fin = key_value; if(primero != NULL && ultimo != NULL){ ultimo->sig = nuevo; ultimo = nuevo; } else { primero = nuevo; ultimo = nuevo; } result = OK; } } /* Lista * aux = primero; asociacion * aux2; while(aux != NULL){ aux2 = aux->inicio; while(aux2 != NULL){ printf("## %i : %s -> %s\n", aux->id, aux2->clave, aux2->valor); aux2 = aux2->next; } aux = aux->sig; } printf("------------\n"); */ return &result; } valor_estado * obtenerasociacion_1_svc(ID arg1, Clave arg2, struct svc_req *rqstp) { static valor_estado result; Lista * aux = primero; asociacion * aux2; while(aux != NULL) { if(arg1 == aux->id) { aux2 = aux->inicio; while(aux2 != NULL) { if(strcmp(arg2 ,aux2->clave) == 0){ result.valor = aux2->valor; result.s = OK; return &result; } aux2 = aux2->next; } } aux = aux->sig; } result.valor = ""; result.s = NoEncontrado; return &result; } Estado * borrarasociacion_1_svc(ID arg1, Clave arg2, struct svc_req *rqstp) { static Estado result; Lista * aux = primero; asociacion * aux2, * aux3; int i = 0; while( aux != NULL ){ if(arg1 == aux->id) { aux2 = aux->inicio; aux3 = aux->inicio->next; // en caso de que sea el primero se borra y fin if(strcmp(arg2, aux2->clave) == 0 && i == 0){ asociacion * borrar = aux2; aux2 = aux3; free(borrar->clave); free(borrar->valor); free(borrar); aux->inicio = aux3; result = OK; return &result; } else { // si no fuera el primero hay que buscarlo while(aux3 != NULL){ if(strcmp(arg2, aux3->clave) == 0 && i >= 0){ asociacion * borrar = aux3; aux2->next = aux3->next; free(borrar->clave); free(borrar->valor); free(borrar); result = OK; return &result; } aux2 = aux2->next; aux3 = aux3->next; i++; } } } i = 0; aux = aux->sig; } result = NoEncontrado; return &result; } asociacion_estado * enumerar_1_svc(ID arg1, struct svc_req *rqstp) { static asociacion_estado result; Lista * aux = primero; while( aux != NULL ) { if( arg1 == aux->id ) { result.asoc = aux->inicio; result.s = OK; return &result; } aux = aux->sig; } result.asoc = NULL; result.s = NoEncontrado; return &result; }
romanarranz/DSD
P1/listas_c/llist_svc_proc.c
/* llist printer RPC server implementation by <NAME> */ #include <stdlib.h> #include "llist.h" int result; /* print out a list, returning the number of items printed */ int *print_list_1_svc(list *lst, struct svc_req *req) { list *ptr; ptr = lst; result = 0; while (ptr != NULL) { printf("{%s, ", ptr->data); printf("%d, ", ptr->key); switch (ptr->col) { case ORANGE: printf("orange"); break; case PUCE: printf("puce"); break; case TURQUOISE: printf("turquoise"); } printf("}\n"); result++; ptr = ptr->next; } return &result; } int *sum_list_1_svc(list *lst, struct svc_req *req) { list *ptr; ptr = lst; result = 0; while (ptr != NULL) { result += ptr->key; ptr = ptr->next; } return &result; }
romanarranz/DSD
P1/calculadora/calculadora.h
<filename>P1/calculadora/calculadora.h /* * Please do not edit this file. * It was generated using rpcgen. */ #ifndef _CALCULADORA_H_RPCGEN #define _CALCULADORA_H_RPCGEN #include <rpc/rpc.h> #ifdef __cplusplus extern "C" { #endif struct suma_1_argument { int arg1; int arg2; }; typedef struct suma_1_argument suma_1_argument; struct resta_1_argument { int arg1; int arg2; }; typedef struct resta_1_argument resta_1_argument; struct multiplicacion_1_argument { int arg1; int arg2; }; typedef struct multiplicacion_1_argument multiplicacion_1_argument; struct division_1_argument { int arg1; int arg2; }; typedef struct division_1_argument division_1_argument; #define CALCULADORA 0x20000001 #define CALCULADORAVER 1 #if defined(__STDC__) || defined(__cplusplus) #define suma 1 extern double * suma_1(int , int , CLIENT *); extern double * suma_1_svc(int , int , struct svc_req *); #define resta 2 extern double * resta_1(int , int , CLIENT *); extern double * resta_1_svc(int , int , struct svc_req *); #define multiplicacion 3 extern double * multiplicacion_1(int , int , CLIENT *); extern double * multiplicacion_1_svc(int , int , struct svc_req *); #define division 4 extern double * division_1(int , int , CLIENT *); extern double * division_1_svc(int , int , struct svc_req *); extern int calculadora_1_freeresult (SVCXPRT *, xdrproc_t, caddr_t); #else /* K&R C */ #define suma 1 extern double * suma_1(); extern double * suma_1_svc(); #define resta 2 extern double * resta_1(); extern double * resta_1_svc(); #define multiplicacion 3 extern double * multiplicacion_1(); extern double * multiplicacion_1_svc(); #define division 4 extern double * division_1(); extern double * division_1_svc(); extern int calculadora_1_freeresult (); #endif /* K&R C */ /* the xdr functions */ #if defined(__STDC__) || defined(__cplusplus) extern bool_t xdr_suma_1_argument (XDR *, suma_1_argument*); extern bool_t xdr_resta_1_argument (XDR *, resta_1_argument*); extern bool_t xdr_multiplicacion_1_argument (XDR *, multiplicacion_1_argument*); extern bool_t xdr_division_1_argument (XDR *, division_1_argument*); #else /* K&R C */ extern bool_t xdr_suma_1_argument (); extern bool_t xdr_resta_1_argument (); extern bool_t xdr_multiplicacion_1_argument (); extern bool_t xdr_division_1_argument (); #endif /* K&R C */ #ifdef __cplusplus } #endif #endif /* !_CALCULADORA_H_RPCGEN */
romanarranz/DSD
P1/asociaciones/asociaciones_svc.c
<gh_stars>0 /* * Please do not edit this file. * It was generated using rpcgen. */ #include "asociaciones.h" #include <stdio.h> #include <stdlib.h> #include <rpc/pmap_clnt.h> #include <string.h> #include <memory.h> #include <sys/socket.h> #include <netinet/in.h> #ifndef SIG_PF #define SIG_PF void(*)(int) #endif static Estado * _ponerasociacion_1 (ponerasociacion_1_argument *argp, struct svc_req *rqstp) { return (ponerasociacion_1_svc(argp->arg1, argp->arg2, argp->arg3, rqstp)); } static valor_estado * _obtenerasociacion_1 (obtenerasociacion_1_argument *argp, struct svc_req *rqstp) { return (obtenerasociacion_1_svc(argp->arg1, argp->arg2, rqstp)); } static Estado * _borrarasociacion_1 (borrarasociacion_1_argument *argp, struct svc_req *rqstp) { return (borrarasociacion_1_svc(argp->arg1, argp->arg2, rqstp)); } static asociacion_estado * _enumerar_1 (ID *argp, struct svc_req *rqstp) { return (enumerar_1_svc(*argp, rqstp)); } static void asociaciones_1(struct svc_req *rqstp, register SVCXPRT *transp) { union { ponerasociacion_1_argument ponerasociacion_1_arg; obtenerasociacion_1_argument obtenerasociacion_1_arg; borrarasociacion_1_argument borrarasociacion_1_arg; ID enumerar_1_arg; } argument; char *result; xdrproc_t _xdr_argument, _xdr_result; char *(*local)(char *, struct svc_req *); switch (rqstp->rq_proc) { case NULLPROC: (void) svc_sendreply (transp, (xdrproc_t) xdr_void, (char *)NULL); return; case PonerAsociacion: _xdr_argument = (xdrproc_t) xdr_ponerasociacion_1_argument; _xdr_result = (xdrproc_t) xdr_Estado; local = (char *(*)(char *, struct svc_req *)) _ponerasociacion_1; break; case ObtenerAsociacion: _xdr_argument = (xdrproc_t) xdr_obtenerasociacion_1_argument; _xdr_result = (xdrproc_t) xdr_valor_estado; local = (char *(*)(char *, struct svc_req *)) _obtenerasociacion_1; break; case BorrarAsociacion: _xdr_argument = (xdrproc_t) xdr_borrarasociacion_1_argument; _xdr_result = (xdrproc_t) xdr_Estado; local = (char *(*)(char *, struct svc_req *)) _borrarasociacion_1; break; case Enumerar: _xdr_argument = (xdrproc_t) xdr_ID; _xdr_result = (xdrproc_t) xdr_asociacion_estado; local = (char *(*)(char *, struct svc_req *)) _enumerar_1; break; default: svcerr_noproc (transp); return; } memset ((char *)&argument, 0, sizeof (argument)); if (!svc_getargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) { svcerr_decode (transp); return; } result = (*local)((char *)&argument, rqstp); if (result != NULL && !svc_sendreply(transp, (xdrproc_t) _xdr_result, result)) { svcerr_systemerr (transp); } if (!svc_freeargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) { fprintf (stderr, "%s", "unable to free arguments"); exit (1); } return; } int main (int argc, char **argv) { register SVCXPRT *transp; pmap_unset (ASOCIACIONES, ASOCIACIONESVER); transp = svcudp_create(RPC_ANYSOCK); if (transp == NULL) { fprintf (stderr, "%s", "cannot create udp service."); exit(1); } if (!svc_register(transp, ASOCIACIONES, ASOCIACIONESVER, asociaciones_1, IPPROTO_UDP)) { fprintf (stderr, "%s", "unable to register (ASOCIACIONES, ASOCIACIONESVER, udp)."); exit(1); } transp = svctcp_create(RPC_ANYSOCK, 0, 0); if (transp == NULL) { fprintf (stderr, "%s", "cannot create tcp service."); exit(1); } if (!svc_register(transp, ASOCIACIONES, ASOCIACIONESVER, asociaciones_1, IPPROTO_TCP)) { fprintf (stderr, "%s", "unable to register (ASOCIACIONES, ASOCIACIONESVER, tcp)."); exit(1); } svc_run (); fprintf (stderr, "%s", "svc_run returned"); exit (1); /* NOTREACHED */ }
romanarranz/DSD
P1/asociaciones/backups/asociaciones_client.c
<filename>P1/asociaciones/backups/asociaciones_client.c<gh_stars>0 #include "asociaciones.h" void asociaciones_1(char *host, int opcion) { CLIENT *clnt; #ifndef DEBUG clnt = clnt_create (host, ASOCIACIONES, ASOCIACIONESVER, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ ID id; Clave key = malloc(sizeof(char) * 255); Valor dato = malloc(sizeof(char) * 255); Estado * result_1; valor_estado * result_2; asociacion_estado * result_4; switch(opcion){ case 1: printf("ID: "); scanf("%i",&id); printf("\n"); printf("Clave: "); scanf("%253s",key); printf("\n"); printf("Valor: "); scanf("%253s",dato); printf("\n"); result_1 = ponerasociacion_1(id, key, dato, clnt); if (result_1 == NULL) clnt_perror (clnt, "call failed"); else { if(*result_1 == OK) printf("Estado de la operacion -> OK\n"); else if(*result_1 == Sustitucion) printf("Estado de la operacion -> Sustitucion\n"); else printf("Estado de la operacion -> NoEncontrado\n"); } break; case 2: printf("ID: "); scanf("%i",&id); printf("\n"); printf("Clave: "); scanf("%253s",key); printf("\n"); result_2 = obtenerasociacion_1(id, key, clnt); if(result_2 == NULL) clnt_perror (clnt, "call failed"); else { if((*result_2).s == OK){ printf("Estado: OK\n"); printf("Valor: %s\n", (char *)(*result_2).valor); } else printf("Estado: NoEncontrado\n"); } break; case 3: printf("ID: "); scanf("%i",&id); printf("\n"); printf("Clave: "); scanf("%253s",key); printf("\n"); result_1 = borrarasociacion_1(id, key, clnt); if(result_1 == NULL) clnt_perror(clnt, "call failed"); else { if(*result_1 == OK) printf("Estado de la operacion -> OK\n"); else printf("Estado de la operacion -> NoEncontrado\n"); } break; case 4: printf("ID: "); scanf("%i",&id); printf("\n"); result_4 = enumerar_1(id, clnt); if(result_4 == NULL) clnt_perror (clnt, "call failed"); else { if((*result_4).s == OK) { printf("Estado: OK\n"); asociacion * aux = (*result_4).asoc; while(aux != NULL) { printf("[%s , %s ]\n", aux->clave, aux->valor); aux = aux->next; } } else printf("Estado: NoEncontrado\n"); } break; }; #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ // Libero la memoria que he reservado con malloc free(key); free(dato); } int main (int argc, char *argv[]) { char *host; int opcion = 0; if (argc < 2) { printf ("usage: %s server_host\n", argv[0]); exit (1); } host = argv[1]; do { printf("# ------------------- Conjuntos de Asociaciones -------------------\n"); printf("1. PonerAsociacion - ID x Clave x Valor -> Estado\n"); printf("2. ObtenerAsociacion - ID x Clave -> Valor x Estado\n"); printf("3. BorrarAsociacion - ID x Clave -> Estado\n"); printf("4. Enumerar - ID -> Conjunto de Claves x Valores x Estado\n"); printf("5. Salir\n\n"); printf("Seleccione la opcion: "); scanf("%i", &opcion); printf("\n\n"); asociaciones_1 (host, opcion); } while(opcion != 5); exit (0); }
romanarranz/DSD
P1/calculadora/calculadora_server.c
#include "calculadora.h" double * suma_1_svc(int arg1, int arg2, struct svc_req *rqstp) { static double result; result = arg1 + arg2; return &result; } double * resta_1_svc(int arg1, int arg2, struct svc_req *rqstp) { static double result; result = arg1 - arg2; return &result; } double * multiplicacion_1_svc(int arg1, int arg2, struct svc_req *rqstp) { static double result; result = arg1 * arg2; return &result; } double * division_1_svc(int arg1, int arg2, struct svc_req *rqstp) { static double result; result = (arg1 + 0.0) / arg2; // con el truco de sumar 0.0 conseguimos obtener los decimales de la division return &result; }
romanarranz/DSD
P1/calculadora/calculadora_svc.c
/* * Please do not edit this file. * It was generated using rpcgen. */ #include "calculadora.h" #include <stdio.h> #include <stdlib.h> #include <rpc/pmap_clnt.h> #include <string.h> #include <memory.h> #include <sys/socket.h> #include <netinet/in.h> #ifndef SIG_PF #define SIG_PF void(*)(int) #endif static double * _suma_1 (suma_1_argument *argp, struct svc_req *rqstp) { return (suma_1_svc(argp->arg1, argp->arg2, rqstp)); } static double * _resta_1 (resta_1_argument *argp, struct svc_req *rqstp) { return (resta_1_svc(argp->arg1, argp->arg2, rqstp)); } static double * _multiplicacion_1 (multiplicacion_1_argument *argp, struct svc_req *rqstp) { return (multiplicacion_1_svc(argp->arg1, argp->arg2, rqstp)); } static double * _division_1 (division_1_argument *argp, struct svc_req *rqstp) { return (division_1_svc(argp->arg1, argp->arg2, rqstp)); } static void calculadora_1(struct svc_req *rqstp, register SVCXPRT *transp) { union { suma_1_argument suma_1_arg; resta_1_argument resta_1_arg; multiplicacion_1_argument multiplicacion_1_arg; division_1_argument division_1_arg; } argument; char *result; xdrproc_t _xdr_argument, _xdr_result; char *(*local)(char *, struct svc_req *); switch (rqstp->rq_proc) { case NULLPROC: (void) svc_sendreply (transp, (xdrproc_t) xdr_void, (char *)NULL); return; case suma: _xdr_argument = (xdrproc_t) xdr_suma_1_argument; _xdr_result = (xdrproc_t) xdr_double; local = (char *(*)(char *, struct svc_req *)) _suma_1; break; case resta: _xdr_argument = (xdrproc_t) xdr_resta_1_argument; _xdr_result = (xdrproc_t) xdr_double; local = (char *(*)(char *, struct svc_req *)) _resta_1; break; case multiplicacion: _xdr_argument = (xdrproc_t) xdr_multiplicacion_1_argument; _xdr_result = (xdrproc_t) xdr_double; local = (char *(*)(char *, struct svc_req *)) _multiplicacion_1; break; case division: _xdr_argument = (xdrproc_t) xdr_division_1_argument; _xdr_result = (xdrproc_t) xdr_double; local = (char *(*)(char *, struct svc_req *)) _division_1; break; default: svcerr_noproc (transp); return; } memset ((char *)&argument, 0, sizeof (argument)); if (!svc_getargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) { svcerr_decode (transp); return; } result = (*local)((char *)&argument, rqstp); if (result != NULL && !svc_sendreply(transp, (xdrproc_t) _xdr_result, result)) { svcerr_systemerr (transp); } if (!svc_freeargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) { fprintf (stderr, "%s", "unable to free arguments"); exit (1); } return; } int main (int argc, char **argv) { register SVCXPRT *transp; pmap_unset (CALCULADORA, CALCULADORAVER); transp = svcudp_create(RPC_ANYSOCK); if (transp == NULL) { fprintf (stderr, "%s", "cannot create udp service."); exit(1); } if (!svc_register(transp, CALCULADORA, CALCULADORAVER, calculadora_1, IPPROTO_UDP)) { fprintf (stderr, "%s", "unable to register (CALCULADORA, CALCULADORAVER, udp)."); exit(1); } transp = svctcp_create(RPC_ANYSOCK, 0, 0); if (transp == NULL) { fprintf (stderr, "%s", "cannot create tcp service."); exit(1); } if (!svc_register(transp, CALCULADORA, CALCULADORAVER, calculadora_1, IPPROTO_TCP)) { fprintf (stderr, "%s", "unable to register (CALCULADORA, CALCULADORAVER, tcp)."); exit(1); } svc_run (); fprintf (stderr, "%s", "svc_run returned"); exit (1); /* NOTREACHED */ }
SethRobinson/ardumanarduman_arduboylib11
Player.h
// *************************************************************** // Player - Creation date: 05/29/2016 // ------------------------------------------------------------- // Robinson Technologies Copyright (C) 2016 - All Rights Reserved // // *************************************************************** // Programmer(s): <NAME> (<EMAIL>) // *************************************************************** #ifndef Player_h__ #define Player_h__ #define CRUMB_COUNT 24 #include "Utils.h" const unsigned char player_right_open[] PROGMEM = { 0x07, 0x05, 0x05, }; const unsigned char player_right_closed[] PROGMEM = { 0x07, 0x07, 0x07, }; const unsigned char player_left_open[] PROGMEM = { 0x05, 0x05, 0x07, }; const unsigned char player_up_open[] PROGMEM = { 0x07, 0x04, 0x07, }; //yeah, it's the same as the ghost, so what const unsigned char player_down_open[] PROGMEM = { 0x07, 0x01, 0x07, }; struct Breadcrumb { int16_t m_x; int16_t m_y; uint8_t m_dir; }; #define POWER_PILL_COUNT 4 class PowerPill { public: uint8_t m_x; uint8_t m_y; bool m_active; void Render() { if (m_active) arduboy.drawBitmap(m_x-1, m_y-1, solid_box, PLAY_W,PLAY_H, 1); } void UnRender() { arduboy.drawBitmap(m_x-1, m_y-1, solid_box, PLAY_W,PLAY_H, 0); } void Setup(uint8_t x, uint8_t y) { m_x = x; m_y = y; m_active = true; } }; class CrumbManager { public: CrumbManager() { Reset(); } void Reset() { memset(m_crumbArray, 0, sizeof(m_crumbArray)); m_curCrumb =0; } uint8_t GetDirToPlayer(int16_t x, int16_t y) { for (int i=0; i < CRUMB_COUNT; i++) { if (m_crumbArray[i].m_x == x && m_crumbArray[i].m_y == y) { //player was here, and we know which way he went! return m_crumbArray[i].m_dir; } } return 0; } void AddCrumb(int16_t x, int16_t y, uint8_t dir) { if (m_crumbArray[m_curCrumb].m_x == x && m_crumbArray[m_curCrumb].m_y == y) { //same as before, don't need to add it, but should update the dir m_crumbArray[m_curCrumb].m_dir= dir; return; } m_curCrumb = (m_curCrumb+1)%CRUMB_COUNT; //LogMsg("Setting crumb id %d to %s", m_curCrumb, DirToText(dir)); m_crumbArray[m_curCrumb].m_x = x; m_crumbArray[m_curCrumb].m_y = y; m_crumbArray[m_curCrumb].m_dir= dir; } uint8_t m_curCrumb; Breadcrumb m_crumbArray[CRUMB_COUNT]; }; extern CrumbManager crumbManager; class Player { public: Player(); void ResetGame(); void ResetLevel(); void ResetStatus(); void OnPowerPillGet(); bool PowerIsActive(); long GetPowerTimeLeft(); bool PowerIsActiveDisplay(); void OnKilledGhost(); void AddScore(long score); void Update(); bool LevelPassed(); void Blit(bool color); void UnRender(); void Render(); void OnHurt(); void Melt(uint16_t y); void OnEndOfLoop(); float m_x; float m_y; uint8_t m_curDir; uint32_t m_score; //don't change format uint8_t m_inputState; const uint8_t *pBitmap; float m_speed; uint8_t m_wasHurt; uint8_t m_livesLeft; uint8_t m_noAnimate; long m_slowTimer; uint16_t m_pelletsEaten; PowerPill m_pills[POWER_PILL_COUNT]; long m_powerTimer; uint8_t m_ghostsKilled; long m_sfxTimer; bool m_bGotExtraLife; //get an extra life at 10k }; #endif // Player_h__
SethRobinson/ardumanarduman_arduboylib11
ConvertToArduboy11.h
#ifndef ConvertToArduboy11_h__ #define ConvertToArduboy11_h__ #include <Arduboy.h> extern Arduboy arduboy; #define text arduboy class ArduboyPlaytune { public: ArduboyPlaytune() { } void playScore(const byte*score) { arduboy.tunes.playScore(score); } void tone(unsigned int frequency, unsigned long duration) { arduboy.tunes.tone(frequency, duration); } void initChannel(byte pin) { arduboy.tunes.initChannel(pin); } }; #endif // ConvertToArduboy11_h__
SethRobinson/ardumanarduman_arduboylib11
Ghost.h
// *************************************************************** // Ghost - Creation date: 05/29/2016 // ------------------------------------------------------------- // Robinson Technologies Copyright (C) 2016 - All Rights Reserved // // *************************************************************** // Programmer(s): <NAME> (<EMAIL>) // *************************************************************** #ifndef Ghost_h__ #define Ghost_h__ #include "Utils.h" #include "Player.h" #include "ardu_main.h" extern Player player; extern uint8_t GHOST_COUNT; const unsigned char ghost_bmp[] PROGMEM = { 0x07, 0x01, 0x07, }; class Ghost { public: Ghost(); ~Ghost(); void SetPauseTimer(long time); float GetAdjustedSpeed(); void ResetPosition(); void SetLastTurnedSpot(int16_t x, int16_t y); bool IsNewTurnSpot(int16_t x, int16_t y); bool IsChasing(); void Update(); void Blit(bool color, bool bDying); void UnRender(); void Render(bool bDying); void SetGhostID(int8_t id){m_id = id;} void OnReleasePellet(uint8_t foodX, uint8_t foodY); void ResetForNewGame(); float m_x; float m_y; uint8_t m_curDir; float m_speed; uint8_t m_foodX,m_foodY; long m_pauseTimer; uint8_t m_id; int16_t m_oldX, m_oldY; bool m_bIsChasing; unsigned long m_thinkTimer; }; extern Ghost ghosts[GHOST_MAX]; void DontDrawPelletHere(uint8_t x, uint8_t y); uint8_t RandomTurn(uint8_t dir); void ResetGhostPositions(bool bNewGame); #endif // Ghost_h__
SethRobinson/ardumanarduman_arduboylib11
Fruit.h
// *************************************************************** // Fruit - Creation date: 06/02/2016 // ------------------------------------------------------------- // Robinson Technologies Copyright (C) 2016 - All Rights Reserved // // *************************************************************** // Programmer(s): <NAME> (<EMAIL>) // *************************************************************** #ifndef Fruit_h__ #define Fruit_h__ class Fruit { public: Fruit(); ~Fruit(); void ResetForNewLevel(); void OnPlayerDie(); void Update(); void OnPelletEaten(); void Render(); void UnRender(); void RenderSideFruits(); private: bool m_bActive; unsigned long m_killTimer; }; extern Fruit fruit; #endif // Fruit_h__
SethRobinson/ardumanarduman_arduboylib11
level_bitmaps.h
<reponame>SethRobinson/ardumanarduman_arduboylib11 const unsigned char level[] PROGMEM = { 0xff, 0x01, 0x01, 0x41, 0x01, 0x01, 0xc9, 0x41, 0x41, 0xc9, 0x01, 0x01, 0x49, 0x01, 0x01, 0x7f, 0x40, 0x40, 0x7f, 0x01, 0x01, 0x49, 0x01, 0x01, 0xc9, 0x41, 0x41, 0xc9, 0x01, 0x01, 0x49, 0x01, 0x01, 0xc9, 0x41, 0x41, 0x49, 0x41, 0x41, 0x49, 0x41, 0x41, 0xc9, 0x01, 0x01, 0x49, 0x01, 0x01, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x01, 0x01, 0x49, 0x01, 0x01, 0xc9, 0x41, 0x41, 0x49, 0x41, 0x41, 0x49, 0x41, 0x41, 0xc9, 0x01, 0x01, 0x49, 0x01, 0x01, 0xc9, 0x41, 0x41, 0xc9, 0x01, 0x01, 0x49, 0x01, 0x01, 0x7f, 0x40, 0x40, 0x7f, 0x01, 0x01, 0x49, 0x01, 0x01, 0xc9, 0x41, 0x41, 0xc9, 0x01, 0x01, 0x41, 0x01, 0x01, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0xf2, 0x90, 0x90, 0x92, 0x90, 0x90, 0x92, 0x90, 0x90, 0x9f, 0x80, 0x80, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x80, 0x80, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x80, 0x80, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x80, 0x80, 0x9f, 0x90, 0x90, 0x92, 0x90, 0x90, 0x92, 0x90, 0x90, 0xf2, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x24, 0x00, 0x00, 0xff, 0x00, 0x00, 0x3f, 0x20, 0x20, 0x24, 0x20, 0x20, 0x24, 0x20, 0x20, 0xe4, 0x00, 0x00, 0x24, 0x00, 0x00, 0xe4, 0x20, 0x20, 0xe4, 0x00, 0x00, 0x24, 0x00, 0x00, 0xe4, 0x20, 0x20, 0x24, 0x20, 0x20, 0x24, 0x20, 0x20, 0xe4, 0x00, 0x00, 0x04, 0x00, 0x00, 0xe0, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xe0, 0x00, 0x00, 0x04, 0x00, 0x00, 0xe4, 0x20, 0x20, 0x24, 0x20, 0x20, 0x24, 0x20, 0x20, 0xe4, 0x00, 0x00, 0x24, 0x00, 0x00, 0xe4, 0x20, 0x20, 0xe4, 0x00, 0x00, 0x24, 0x00, 0x00, 0xe4, 0x20, 0x20, 0x24, 0x20, 0x20, 0x24, 0x20, 0x20, 0x3f, 0x00, 0x00, 0xff, 0x00, 0x00, 0x24, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0xc9, 0x41, 0x41, 0x49, 0x41, 0x41, 0x49, 0x41, 0x41, 0x49, 0x41, 0x41, 0x49, 0x40, 0x40, 0x49, 0x40, 0x40, 0x7f, 0x00, 0x00, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x00, 0x00, 0x7f, 0x40, 0x40, 0x49, 0x40, 0x40, 0x49, 0x41, 0x41, 0x49, 0x41, 0x41, 0x49, 0x41, 0x41, 0x49, 0x41, 0x41, 0xc9, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0x93, 0x82, 0x82, 0x92, 0x82, 0x82, 0x92, 0x82, 0x82, 0x92, 0x82, 0x82, 0x92, 0x02, 0x02, 0x92, 0x02, 0x02, 0xfe, 0x00, 0x00, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x00, 0x00, 0xfe, 0x02, 0x02, 0x92, 0x02, 0x02, 0x92, 0x82, 0x82, 0x92, 0x82, 0x82, 0x92, 0x82, 0x82, 0x92, 0x82, 0x82, 0x93, 0x00, 0x00, 0x92, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x24, 0x00, 0x00, 0xff, 0x00, 0x00, 0xfc, 0x04, 0x04, 0x24, 0x04, 0x04, 0x24, 0x04, 0x04, 0x27, 0x00, 0x00, 0x24, 0x00, 0x00, 0x27, 0x04, 0x04, 0x27, 0x00, 0x00, 0x24, 0x00, 0x00, 0x27, 0x04, 0x04, 0x24, 0x04, 0x04, 0x24, 0x04, 0x04, 0x27, 0x00, 0x00, 0x20, 0x00, 0x00, 0x07, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x07, 0x00, 0x00, 0x20, 0x00, 0x00, 0x27, 0x04, 0x04, 0x24, 0x04, 0x04, 0x24, 0x04, 0x04, 0x27, 0x00, 0x00, 0x24, 0x00, 0x00, 0x27, 0x04, 0x04, 0x27, 0x00, 0x00, 0x24, 0x00, 0x00, 0x27, 0x04, 0x04, 0x24, 0x04, 0x04, 0x24, 0x04, 0x04, 0xfc, 0x00, 0x00, 0xff, 0x00, 0x00, 0x24, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0x4f, 0x09, 0x09, 0x49, 0x09, 0x09, 0x49, 0x09, 0x09, 0xf9, 0x01, 0x01, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x01, 0x01, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x01, 0x01, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x01, 0x01, 0xf9, 0x09, 0x09, 0x49, 0x09, 0x09, 0x49, 0x09, 0x09, 0x4f, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x49, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x80, 0x80, 0x82, 0x80, 0x80, 0x93, 0x82, 0x82, 0x93, 0x80, 0x80, 0x92, 0x80, 0x80, 0xfe, 0x02, 0x02, 0xfe, 0x80, 0x80, 0x92, 0x80, 0x80, 0x93, 0x82, 0x82, 0x93, 0x80, 0x80, 0x92, 0x80, 0x80, 0x93, 0x82, 0x82, 0x92, 0x82, 0x82, 0x92, 0x82, 0x82, 0x93, 0x80, 0x80, 0x92, 0x80, 0x80, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x80, 0x80, 0x92, 0x80, 0x80, 0x93, 0x82, 0x82, 0x92, 0x82, 0x82, 0x92, 0x82, 0x82, 0x93, 0x80, 0x80, 0x92, 0x80, 0x80, 0x93, 0x82, 0x82, 0x93, 0x80, 0x80, 0x92, 0x80, 0x80, 0xfe, 0x02, 0x02, 0xfe, 0x80, 0x80, 0x92, 0x80, 0x80, 0x93, 0x82, 0x82, 0x93, 0x80, 0x80, 0x82, 0x80, 0x80, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
SethRobinson/ardumanarduman_arduboylib11
Music.h
const byte PROGMEM level_intro [] = { //all music written by Seth. And yes, you know what they were "inspired" by 0x90,55, 0x91,19, 0,71, 0x80, 0,71, 0x81, 0x90,67, 0,71, 0x80, 0,71, 0x90,62, 0,71, 0x80, 0,71, 0x90,59, 0,71, 0x80, 0,5, 0x90,20, 0x91,56, 0,71, 0x81, 0,71, 0x80, 0x90,68, 0,71, 0x80, 0,71, 0x90,63, 0,71, 0x80, 0,71, 0x90,32, 0x91,60, 0,71, 0x81, 0,65, 0x91,19, 0,5, 0x80, 0,59, 0,71, 0x81, 0x90,67, 0,71, 0x80, 0,71, 0x90,62, 0,77, 0x80, 0,65, 0x90,59, 0,77, 0x80, 0,5, 0x90,63, 0x91,30, 0,71, 0x80, 0x90,64, 0,65, 0x81, 0x80, 0x90,65, 0,77, 0x91,64, 0x80, 0,65, 0x81, 0,17, 0x90,67, 0x91,31, 0,148, 0x80, 0x81, 0xf0}; const byte PROGMEM music_kill_ghost [] = { 0,18, 0x90,73, 0,88, 0x91,74, 0,41, 0x80, 0,67, 0x90,76, 0,20, 0x81, 0,39, 0x91,78, 0,59, 0x80, 0,91, 0x81, 0xf0}; const byte PROGMEM music_bonus [] = { 0,18, 0x90,84, 0,192, 0x91,88, 0,49, 0x80, 0,57, 0x90,91, 0,67, 0x81, 0,59, 0x91,96, 0,127, 0x80, 0,114, 0x81, 0xf0}; const byte PROGMEM music_finish_level [] = { 0,11, 0x90,79, 0x91,75, 1,23, 0x80, 0x81, 0,214, 0,35, 0x90,65, 0,35, 0x91,81, 1,29, 0x81, 0,244, 0x80, 0,5, 0x90,67, 0,35, 0x91,79, 1,29, 0x81, 3,136, 0x80, 0,5, 0xf0}; const byte PROGMEM music_death [] = { 0,39, 0x90,84, 0,119, 0x80, 0,28, 0x90,83, 0,88, 0x80, 0,41, 0x90,82, 0,96, 0x80, 0,23, 0x90,81, 0,101, 0x80, 0,20, 0x90,80, 0,78, 0x80, 0,10, 0x90,79, 0,67, 0x80, 0,33, 0x90,78, 0,78, 0x80, 0,31, 0x90,77, 0,75, 0x80, 0,44, 0x90,76, 0,85, 0x80, 0,13, 0x90,75, 0,80, 0x80, 0,10, 0x90,74, 0,88, 0x80, 0x90,73, 0,221, 0x80, 0xf0};
SethRobinson/ardumanarduman_arduboylib11
Highscores.h
#ifndef Highscores_h__ #define Highscores_h__ #include "ardu_main.h" #include "Arduboy.h" void enterInitials(); void displayHighScores(byte file); bool enterHighScore(byte file); //returns true if new highscore was added #endif // Highscores_h__
SethRobinson/ardumanarduman_arduboylib11
Utils.h
#ifndef Utils_h__ #define Utils_h__ #include "Arduboy.h" #include "ConvertToArduboy11.h" extern Arduboy arduboy; //extern AbPrinter text; extern ArduboyPlaytune tunes; extern uint8_t g_level; #define PLAY_W 3 #define PLAY_H 3 const unsigned char solid_box[] PROGMEM = { 0x07, 0x07, 0x07, }; char * DirToText(uint8_t dir); void MovePosition(float *pXInOut, float *pYInOut, uint8_t dir, float amount); bool HitWall(int16_t x, int16_t y); bool CanGoRight(int16_t x, int16_t y); bool CanGoUp(int16_t x, int16_t y); bool CanGoLeft(int16_t x, int16_t y); bool CanGoDown(int16_t x, int16_t y); bool CanTurn(int16_t x, int16_t y, uint8_t dir); bool IsInTunnel(int16_t x, int16_t y); float EntitiesAreTouching(float ax, float ay, float bx, float by, float width ); void WorldWrapY(float &yInOut); bool GetFoodWeAreOn(uint8_t *pFoodOutX,uint8_t *pFoodOutY, int16_t posX, int16_t posY); size_t printNumberFancy(uint8_t x, uint8_t y, long n, bool bCentered, bool bVertical); #endif // Utils_h__