code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /**************************************************************************************** * Teensy 4.1 (IMXRT1062) Breadboard pin assignments * Requires the Teensyduino software with Teensy 4.1 selected in Arduino IDE! * https://www.pjrc.com/teensy/teensyduino.html ****************************************************************************************/ #include "env_validate.h" #define BOARD_INFO_NAME "Teensy4.1" /** * Plan for Teensy 4.0 and Teensy 4.1: * USB * GND |-----#####-----| VIN (3.65 TO 5.5V) * X_STEP_PIN CS1 RX1 PWM 0 | ##### | GND * X_DIR_PIN MISO1 TX1 PWM 1 | | 3.3V * Y_STEP_PIN PWM 2 | | 23 A9 PWM SERVO1_PIN * Y_DIR_PIN PWM 3 | | 22 A8 PWM SERVO0_PIN * Z_STEP_PIN PWM 4 | | 21 A7 RX5 * Z_DIR_PIN PWM 5 | | 20 A6 TX5 FILWIDTH_PIN * X_ENABLE_PIN PWM 6 | | 19 A5 PWM SCL0 * Y_ENABLE_PIN RX2 PWM 7 | | 18 A4 PWM SDA0 HEATER_1_PIN * Z_ENABLE_PIN TX2 PWM 8 | | 17 A3 RX4 SDA1 * E0_STEP_PIN PWM 9 | | 16 A2 TX4 SCL1 TEMP_0_PIN * E0_DIR_PIN PWM 10 | | 15 A1 PWM RX3 TEMP_BED_PIN * MOSI_PIN MOSI0 PWM 11 | | 14 A0 PWM TX3 TEMP_1_PIN * MISO_PIN MISO0 PWM 12 | | 13 LED PWM SCK0 SCK_PIN * 3.3V | | GND * Z_STOP_PIN PWM 24 | | 41 A17 * E0_ENABLE_PIN PWM 25 | | 40 A16 * FAN0_PIN MOSI1 26 | | 39 A15 MISO1 X_STOP_PIN * Z-PROBE PWR SCK1 27 | * * * * * | 38 A14 Y_STOP_PIN * SOL1_PIN RX7 PWM 28 | | 37 PWM HEATER_0_PIN * FAN0_PIN TX7 PWM 29 | | 36 PWM HEATER_BED_PIN * X_CS_PIN 30 | | 35 TX8 E1_ENABLE_PIN * y_CS_PIN 31 | SDCARD | 34 RX8 E1_DIR_PIN * Z_CS_PIN 32 |_______________| 33 PWM E1_STEP_PIN */ // // Servos // #define SERVO0_PIN 22 #define SERVO1_PIN 23 // // Limit Switches // #define X_STOP_PIN 39 #define Y_STOP_PIN 38 #define Z_STOP_PIN 24 // // Steppers // #define X_STEP_PIN 0 #define X_DIR_PIN 1 #define X_ENABLE_PIN 6 //#define X_CS_PIN 30 #define Y_STEP_PIN 2 #define Y_DIR_PIN 3 #define Y_ENABLE_PIN 7 //#define Y_CS_PIN 31 #define Z_STEP_PIN 4 #define Z_DIR_PIN 5 #define Z_ENABLE_PIN 8 //#define Z_CS_PIN 32 #define E0_STEP_PIN 9 #define E0_DIR_PIN 10 #define E0_ENABLE_PIN 25 #define E1_STEP_PIN 33 #define E1_DIR_PIN 34 #define E1_ENABLE_PIN 35 // // Heaters / Fans // #define HEATER_0_PIN 37 #define HEATER_1_PIN 18 #define HEATER_BED_PIN 36 #ifndef FAN0_PIN #define FAN0_PIN 29 #endif // // Temperature Sensors // #define TEMP_0_PIN 2 // Extruder / Analog pin numbering: 2 => A2 #define TEMP_1_PIN 0 #define TEMP_BED_PIN 1 // Bed / Analog pin numbering // // Misc. Functions // #define LED_PIN 13 #define SOL0_PIN 28 //#define PS_ON_PIN 1 //#define FILWIDTH_PIN 6 // A6 #ifndef SDCARD_CONNECTION #define SDCARD_CONNECTION ONBOARD #endif
2301_81045437/Marlin
Marlin/src/pins/teensy4/pins_TEENSY41.h
C
agpl-3.0
5,410
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ /** * Arduino Sd2Card Library * Copyright (c) 2009 by William Greiman * Updated with backports of the latest SdFat library from the same author * * This file is part of the Arduino Sd2Card Library */ #include "../inc/MarlinConfig.h" #if NEED_SD2CARD_SPI /* Enable FAST CRC computations - You can trade speed for FLASH space if * needed by disabling the following define */ #define FAST_CRC 1 #include "Sd2Card.h" #include "../MarlinCore.h" #if DISABLED(SD_NO_DEFAULT_TIMEOUT) #ifndef SD_INIT_TIMEOUT #define SD_INIT_TIMEOUT 2000u // (ms) Init timeout #elif SD_INIT_TIMEOUT < 0 #error "SD_INIT_TIMEOUT must be greater than or equal to 0." #endif #ifndef SD_ERASE_TIMEOUT #define SD_ERASE_TIMEOUT 10000u // (ms) Erase timeout #elif SD_ERASE_TIMEOUT < 0 #error "SD_ERASE_TIMEOUT must be greater than or equal to 0." #endif #ifndef SD_READ_TIMEOUT #define SD_READ_TIMEOUT 300u // (ms) Read timeout #elif SD_READ_TIMEOUT < 0 #error "SD_READ_TIMEOUT must be greater than or equal to 0." #endif #ifndef SD_WRITE_TIMEOUT #define SD_WRITE_TIMEOUT 600u // (ms) Write timeout #elif SD_WRITE_TIMEOUT < 0 #error "SD_WRITE_TIMEOUT must be greater than or equal to 0." #endif #endif // SD_NO_DEFAULT_TIMEOUT #if ENABLED(SD_CHECK_AND_RETRY) #ifndef SD_RETRY_COUNT #define SD_RETRY_COUNT 3 #elif SD_RETRY_COUNT < 1 #error "SD_RETRY_COUNT must be greater than or equal to 1." #endif #endif #if ENABLED(SD_CHECK_AND_RETRY) static bool crcSupported = true; #ifdef FAST_CRC static const uint8_t crctab7[] PROGMEM = { 0x00,0x09,0x12,0x1B,0x24,0x2D,0x36,0x3F,0x48,0x41,0x5A,0x53,0x6C,0x65,0x7E,0x77, 0x19,0x10,0x0B,0x02,0x3D,0x34,0x2F,0x26,0x51,0x58,0x43,0x4A,0x75,0x7C,0x67,0x6E, 0x32,0x3B,0x20,0x29,0x16,0x1F,0x04,0x0D,0x7A,0x73,0x68,0x61,0x5E,0x57,0x4C,0x45, 0x2B,0x22,0x39,0x30,0x0F,0x06,0x1D,0x14,0x63,0x6A,0x71,0x78,0x47,0x4E,0x55,0x5C, 0x64,0x6D,0x76,0x7F,0x40,0x49,0x52,0x5B,0x2C,0x25,0x3E,0x37,0x08,0x01,0x1A,0x13, 0x7D,0x74,0x6F,0x66,0x59,0x50,0x4B,0x42,0x35,0x3C,0x27,0x2E,0x11,0x18,0x03,0x0A, 0x56,0x5F,0x44,0x4D,0x72,0x7B,0x60,0x69,0x1E,0x17,0x0C,0x05,0x3A,0x33,0x28,0x21, 0x4F,0x46,0x5D,0x54,0x6B,0x62,0x79,0x70,0x07,0x0E,0x15,0x1C,0x23,0x2A,0x31,0x38, 0x41,0x48,0x53,0x5A,0x65,0x6C,0x77,0x7E,0x09,0x00,0x1B,0x12,0x2D,0x24,0x3F,0x36, 0x58,0x51,0x4A,0x43,0x7C,0x75,0x6E,0x67,0x10,0x19,0x02,0x0B,0x34,0x3D,0x26,0x2F, 0x73,0x7A,0x61,0x68,0x57,0x5E,0x45,0x4C,0x3B,0x32,0x29,0x20,0x1F,0x16,0x0D,0x04, 0x6A,0x63,0x78,0x71,0x4E,0x47,0x5C,0x55,0x22,0x2B,0x30,0x39,0x06,0x0F,0x14,0x1D, 0x25,0x2C,0x37,0x3E,0x01,0x08,0x13,0x1A,0x6D,0x64,0x7F,0x76,0x49,0x40,0x5B,0x52, 0x3C,0x35,0x2E,0x27,0x18,0x11,0x0A,0x03,0x74,0x7D,0x66,0x6F,0x50,0x59,0x42,0x4B, 0x17,0x1E,0x05,0x0C,0x33,0x3A,0x21,0x28,0x5F,0x56,0x4D,0x44,0x7B,0x72,0x69,0x60, 0x0E,0x07,0x1C,0x15,0x2A,0x23,0x38,0x31,0x46,0x4F,0x54,0x5D,0x62,0x6B,0x70,0x79 }; static uint8_t CRC7(const uint8_t *data, uint8_t n) { uint8_t crc = 0; while (n > 0) { crc = pgm_read_byte(&crctab7[ (crc << 1) ^ *data++ ]); n--; } return (crc << 1) | 1; } #else static uint8_t CRC7(const uint8_t *data, uint8_t n) { uint8_t crc = 0; for (uint8_t i = 0; i < n; ++i) { uint8_t d = data[i]; d ^= crc << 1; if (d & 0x80) d ^= 9; crc = d ^ (crc & 0x78) ^ (crc << 4) ^ ((crc >> 3) & 15); crc &= 0x7F; } crc = (crc << 1) ^ (crc << 4) ^ (crc & 0x70) ^ ((crc >> 3) & 0x0F); return crc | 1; } #endif #endif // Send command and return error code. Return zero for OK uint8_t DiskIODriver_SPI_SD::cardCommand(const uint8_t cmd, const uint32_t arg) { #if ENABLED(SDCARD_COMMANDS_SPLIT) if (cmd != CMD12) chipDeselect(); #endif // Select card chipSelect(); #if SD_WRITE_TIMEOUT waitNotBusy(SD_WRITE_TIMEOUT); // Wait up to 600 ms (by default) if busy #endif uint8_t *pa = (uint8_t *)(&arg); #if ENABLED(SD_CHECK_AND_RETRY) // Form message uint8_t d[6] = { uint8_t(cmd | 0x40), pa[3], pa[2], pa[1], pa[0] }; // Add crc d[5] = CRC7(d, 5); // Send message for (uint8_t k = 0; k < 6; ++k) spiSend(d[k]); #else // Send command spiSend(cmd | 0x40); // Send argument for (int8_t i = 3; i >= 0; i--) spiSend(pa[i]); // Send CRC - correct for CMD0 with arg zero or CMD8 with arg 0X1AA spiSend(cmd == CMD0 ? 0X95 : 0X87); #endif // Skip stuff byte for stop read if (cmd == CMD12) spiRec(); // Wait for response for (uint8_t i = 0; ((status_ = spiRec()) & 0x80) && i != 0xFF; i++) { /* Intentionally left empty */ } return status_; } /** * Determine the size of an SD flash memory card. * * \return The number of 512 byte data blocks in the card * or zero if an error occurs. */ uint32_t DiskIODriver_SPI_SD::cardSize() { csd_t csd; if (!readCSD(&csd)) return 0; if (csd.v1.csd_ver == 0) { uint8_t read_bl_len = csd.v1.read_bl_len; uint16_t c_size = (csd.v1.c_size_high << 10) | (csd.v1.c_size_mid << 2) | csd.v1.c_size_low; uint8_t c_size_mult = (csd.v1.c_size_mult_high << 1) | csd.v1.c_size_mult_low; return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7); } else if (csd.v2.csd_ver == 1) { uint32_t c_size = ((uint32_t)csd.v2.c_size_high << 16) | (csd.v2.c_size_mid << 8) | csd.v2.c_size_low; return (c_size + 1) << 10; } else { error(SD_CARD_ERROR_BAD_CSD); return 0; } } void DiskIODriver_SPI_SD::chipDeselect() { extDigitalWrite(chipSelectPin_, HIGH); spiSend(0xFF); // Ensure MISO goes high impedance } void DiskIODriver_SPI_SD::chipSelect() { spiInit(spiRate_); extDigitalWrite(chipSelectPin_, LOW); } /** * Erase a range of blocks. * * \param[in] firstBlock The address of the first block in the range. * \param[in] lastBlock The address of the last block in the range. * * \note This function requests the SD card to do a flash erase for a * range of blocks. The data on the card after an erase operation is * either 0 or 1, depends on the card vendor. The card must support * single block erase. * * \return true for success, false for failure. */ bool DiskIODriver_SPI_SD::erase(uint32_t firstBlock, uint32_t lastBlock) { if (ENABLED(SDCARD_READONLY)) return false; bool success = false; do { csd_t csd; if (!readCSD(&csd)) break; // check for single block erase if (!csd.v1.erase_blk_en) { // erase size mask uint8_t m = (csd.v1.sector_size_high << 1) | csd.v1.sector_size_low; if ((firstBlock & m) || ((lastBlock + 1) & m)) { // error card can't erase specified area error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); break; } } if (type_ != SD_CARD_TYPE_SDHC) { firstBlock <<= 9; lastBlock <<= 9; } if (cardCommand(CMD32, firstBlock) || cardCommand(CMD33, lastBlock) || cardCommand(CMD38, 0)) { error(SD_CARD_ERROR_ERASE); break; } #if SD_ERASE_TIMEOUT if (!waitNotBusy(SD_ERASE_TIMEOUT)) { error(SD_CARD_ERROR_ERASE_TIMEOUT); break; } #else while (spiRec() != 0xFF) {} #endif success = true; } while (0); chipDeselect(); return success; } /** * Determine if card supports single block erase. * * \return true if single block erase is supported. * false if single block erase is not supported. */ bool DiskIODriver_SPI_SD::eraseSingleBlockEnable() { csd_t csd; return readCSD(&csd) ? csd.v1.erase_blk_en : false; } /** * Initialize an SD flash memory card. * * \param[in] sckRateID SPI clock rate selector. See setSckRate(). * \param[in] chipSelectPin SD chip select pin number. * * \return true for success, false for failure. * The reason for failure can be determined by calling errorCode() and errorData(). */ bool DiskIODriver_SPI_SD::init(const uint8_t sckRateID, const pin_t chipSelectPin) { #if IS_TEENSY_35_36 || IS_TEENSY_40_41 chipSelectPin_ = BUILTIN_SDCARD; const uint8_t ret = SDHC_CardInit(); type_ = SDHC_CardGetType(); return (ret == 0); #endif errorCode_ = type_ = 0; chipSelectPin_ = chipSelectPin; // 16-bit init start time allows over a minute #if SD_INIT_TIMEOUT const millis_t init_timeout = millis() + SD_INIT_TIMEOUT; #define INIT_TIMEOUT() ELAPSED(millis(), init_timeout) #else #define INIT_TIMEOUT() false #endif uint32_t arg; hal.watchdog_refresh(); // In case init takes too long // Set pin modes #if ENABLED(ZONESTAR_12864OLED) if (chipSelectPin_ != DOGLCD_CS) { SET_OUTPUT(DOGLCD_CS); WRITE(DOGLCD_CS, HIGH); } #else extDigitalWrite(chipSelectPin_, HIGH); // For some CPUs pinMode can write the wrong data so init desired data value first pinMode(chipSelectPin_, OUTPUT); // Solution for #8746 by @benlye #endif spiBegin(); // Set SCK rate for initialization commands spiRate_ = SPI_SD_INIT_RATE; spiInit(spiRate_); // Must supply min of 74 clock cycles with CS high. for (uint8_t i = 0; i < 10; ++i) spiSend(0xFF); hal.watchdog_refresh(); // In case init takes too long // Command to go idle in SPI mode while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) { if (INIT_TIMEOUT()) { error(SD_CARD_ERROR_CMD0); goto FAIL; } } #if ENABLED(SD_CHECK_AND_RETRY) crcSupported = (cardCommand(CMD59, 1) == R1_IDLE_STATE); #endif hal.watchdog_refresh(); // In case init takes too long // check SD version for (;;) { if (cardCommand(CMD8, 0x1AA) == (R1_ILLEGAL_COMMAND | R1_IDLE_STATE)) { type(SD_CARD_TYPE_SD1); break; } // Get the last byte of r7 response for (uint8_t i = 0; i < 4; ++i) status_ = spiRec(); if (status_ == 0xAA) { type(SD_CARD_TYPE_SD2); break; } if (INIT_TIMEOUT()) { error(SD_CARD_ERROR_CMD8); goto FAIL; } } hal.watchdog_refresh(); // In case init takes too long // Initialize card and send host supports SDHC if SD2 arg = type() == SD_CARD_TYPE_SD2 ? 0x40000000 : 0; while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) { // Check for timeout if (INIT_TIMEOUT()) { error(SD_CARD_ERROR_ACMD41); goto FAIL; } } // If SD2 read OCR register to check for SDHC card if (type() == SD_CARD_TYPE_SD2) { if (cardCommand(CMD58, 0)) { error(SD_CARD_ERROR_CMD58); goto FAIL; } if ((spiRec() & 0xC0) == 0xC0) type(SD_CARD_TYPE_SDHC); // Discard rest of ocr - contains allowed voltage range for (uint8_t i = 0; i < 3; ++i) spiRec(); } chipDeselect(); ready = true; return setSckRate(sckRateID); FAIL: chipDeselect(); ready = false; return false; } /** * Read a 512 byte block from an SD card. * * \param[in] blockNumber Logical block to be read. * \param[out] dst Pointer to the location that will receive the data. * \return true for success, false for failure. */ bool DiskIODriver_SPI_SD::readBlock(uint32_t blockNumber, uint8_t * const dst) { #if IS_TEENSY_35_36 || IS_TEENSY_40_41 return 0 == SDHC_CardReadBlock(dst, blockNumber); #endif if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; // Use address if not SDHC card #if ENABLED(SD_CHECK_AND_RETRY) uint8_t retryCnt = SD_RETRY_COUNT; for (;;) { if (cardCommand(CMD17, blockNumber)) error(SD_CARD_ERROR_CMD17); else if (readData(dst, 512)) return true; chipDeselect(); if (!--retryCnt) break; cardCommand(CMD12, 0); // Try sending a stop command, ignore the result. errorCode_ = 0; } return false; #else if (cardCommand(CMD17, blockNumber)) { error(SD_CARD_ERROR_CMD17); chipDeselect(); return false; } else return readData(dst, 512); #endif } /** * Read one data block in a multiple block read sequence * * \param[in] dst Pointer to the location for the data to be read. * * \return true for success, false for failure. */ bool DiskIODriver_SPI_SD::readData(uint8_t * const dst) { chipSelect(); return readData(dst, 512); } #if ENABLED(SD_CHECK_AND_RETRY) #ifdef FAST_CRC static const uint16_t crctab16[] PROGMEM = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 }; // faster CRC-CCITT // uses the x^16,x^12,x^5,x^1 polynomial. static uint16_t CRC_CCITT(const uint8_t *data, size_t n) { uint16_t crc = 0; for (size_t i = 0; i < n; i++) crc = pgm_read_word(&crctab16[(crc >> 8 ^ data[i]) & 0xFF]) ^ (crc << 8); return crc; } #else // slower CRC-CCITT // uses the x^16,x^12,x^5,x^1 polynomial. static uint16_t CRC_CCITT(const uint8_t *data, size_t n) { uint16_t crc = 0; for (size_t i = 0; i < n; i++) { crc = (uint8_t)(crc >> 8) | (crc << 8); crc ^= data[i]; crc ^= (uint8_t)(crc & 0xFF) >> 4; crc ^= crc << 12; crc ^= (crc & 0xFF) << 5; } return crc; } #endif #endif // SD_CHECK_AND_RETRY bool DiskIODriver_SPI_SD::readData(uint8_t * const dst, const uint16_t count) { bool success = false; #if SD_READ_TIMEOUT const millis_t read_timeout = millis() + SD_READ_TIMEOUT; #define READ_TIMEOUT() ELAPSED(millis(), read_timeout) #else #define READ_TIMEOUT() false #endif while ((status_ = spiRec()) == 0xFF) { // Wait for start block token if (READ_TIMEOUT()) { error(SD_CARD_ERROR_READ_TIMEOUT); goto FAIL; } } if (status_ == DATA_START_BLOCK) { spiRead(dst, count); // Transfer data const uint16_t recvCrc = ((uint16_t)spiRec() << 8) | (uint16_t)spiRec(); #if ENABLED(SD_CHECK_AND_RETRY) success = !crcSupported || recvCrc == CRC_CCITT(dst, count); if (!success) error(SD_CARD_ERROR_READ_CRC); #else success = true; UNUSED(recvCrc); #endif } else error(SD_CARD_ERROR_READ); FAIL: chipDeselect(); return success; } /** read CID or CSR register */ bool DiskIODriver_SPI_SD::readRegister(const uint8_t cmd, void * const buf) { uint8_t * const dst = reinterpret_cast<uint8_t*>(buf); if (cardCommand(cmd, 0)) { error(SD_CARD_ERROR_READ_REG); chipDeselect(); return false; } return readData(dst, 16); } /** * Start a read multiple blocks sequence. * * \param[in] blockNumber Address of first block in sequence. * * \note This function is used with readData() and readStop() for optimized * multiple block reads. SPI chipSelect must be low for the entire sequence. * * \return true for success, false for failure. */ bool DiskIODriver_SPI_SD::readStart(uint32_t blockNumber) { if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; const bool success = !cardCommand(CMD18, blockNumber); if (!success) error(SD_CARD_ERROR_CMD18); chipDeselect(); return success; } /** * End a read multiple blocks sequence. * * \return true for success, false for failure. */ bool DiskIODriver_SPI_SD::readStop() { chipSelect(); const bool success = !cardCommand(CMD12, 0); if (!success) error(SD_CARD_ERROR_CMD12); chipDeselect(); return success; } /** * Set the SPI clock rate. * * \param[in] sckRateID A value in the range [0, 6]. * * The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum * SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128 * for \a scsRateID = 6. * * \return The value one, true, is returned for success and the value zero, * false, is returned for an invalid value of \a sckRateID. */ bool DiskIODriver_SPI_SD::setSckRate(const uint8_t sckRateID) { const bool success = (sckRateID <= 6); if (success) spiRate_ = sckRateID; else error(SD_CARD_ERROR_SCK_RATE); return success; } /** * Wait for card to become not-busy * \param[in] timeout_ms Timeout to abort. * \return true for success, false for timeout. */ bool DiskIODriver_SPI_SD::waitNotBusy(const millis_t timeout_ms) { const millis_t wait_timeout = millis() + timeout_ms; while (spiRec() != 0xFF) if (ELAPSED(millis(), wait_timeout)) return false; return true; } void DiskIODriver_SPI_SD::error(const uint8_t code) { errorCode_ = code; } /** * Write a 512 byte block to an SD card. * * \param[in] blockNumber Logical block to be written. * \param[in] src Pointer to the location of the data to be written. * \return true for success, false for failure. */ bool DiskIODriver_SPI_SD::writeBlock(uint32_t blockNumber, const uint8_t * const src) { if (ENABLED(SDCARD_READONLY)) return false; #if IS_TEENSY_35_36 || IS_TEENSY_40_41 return 0 == SDHC_CardWriteBlock(src, blockNumber); #endif if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; // Use address if not SDHC card bool success = !cardCommand(CMD24, blockNumber); if (!success) { error(SD_CARD_ERROR_CMD24); } else if (writeData(DATA_START_BLOCK, src)) { #if SD_WRITE_TIMEOUT success = waitNotBusy(SD_WRITE_TIMEOUT); // Wait for flashing to complete if (!success) error(SD_CARD_ERROR_WRITE_TIMEOUT); #else while (spiRec() != 0xFF) {} #endif if (success) { success = !(cardCommand(CMD13, 0) || spiRec()); // Response is r2 so get and check two bytes for nonzero if (!success) error(SD_CARD_ERROR_WRITE_PROGRAMMING); } } chipDeselect(); return success; } /** * Write one data block in a multiple block write sequence * \param[in] src Pointer to the location of the data to be written. * \return true for success, false for failure. */ bool DiskIODriver_SPI_SD::writeData(const uint8_t * const src) { if (ENABLED(SDCARD_READONLY)) return false; chipSelect(); bool success = false; do { // Wait for previous write to finish #if SD_WRITE_TIMEOUT if (!waitNotBusy(SD_WRITE_TIMEOUT)) { error(SD_CARD_ERROR_WRITE_MULTIPLE); break; } #else while (spiRec() != 0xFF) {} #endif success = writeData(WRITE_MULTIPLE_TOKEN, src); } while (0); chipDeselect(); return success; } // Send one block of data for write block or write multiple blocks bool DiskIODriver_SPI_SD::writeData(const uint8_t token, const uint8_t * const src) { if (ENABLED(SDCARD_READONLY)) return false; const uint16_t crc = TERN(SD_CHECK_AND_RETRY, CRC_CCITT(src, 512), 0xFFFF); spiSendBlock(token, src); spiSend(crc >> 8); spiSend(crc & 0xFF); status_ = spiRec(); if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) { error(SD_CARD_ERROR_WRITE); chipDeselect(); return false; } return true; } /** * Start a write multiple blocks sequence. * * \param[in] blockNumber Address of first block in sequence. * \param[in] eraseCount The number of blocks to be pre-erased. * * \note This function is used with writeData() and writeStop() * for optimized multiple block writes. * * \return true for success, false for failure. */ bool DiskIODriver_SPI_SD::writeStart(uint32_t blockNumber, const uint32_t eraseCount) { if (ENABLED(SDCARD_READONLY)) return false; bool success = false; if (!cardAcmd(ACMD23, eraseCount)) { // Send pre-erase count if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; // Use address if not SDHC card success = !cardCommand(CMD25, blockNumber); if (!success) error(SD_CARD_ERROR_CMD25); } else error(SD_CARD_ERROR_ACMD23); chipDeselect(); return success; } /** * End a write multiple blocks sequence. * * \return true for success, false for failure. */ bool DiskIODriver_SPI_SD::writeStop() { if (ENABLED(SDCARD_READONLY)) return false; chipSelect(); bool success = false; do { #if SD_WRITE_TIMEOUT if (!waitNotBusy(SD_WRITE_TIMEOUT)) { error(SD_CARD_ERROR_STOP_TRAN); break; } #else while (spiRec() != 0xFF) {} #endif spiSend(STOP_TRAN_TOKEN); #if SD_WRITE_TIMEOUT if (!waitNotBusy(SD_WRITE_TIMEOUT)) break; #else while (spiRec() != 0xFF) {} #endif success = true; } while (0); chipDeselect(); return success; } #endif // NEED_SD2CARD_SPI
2301_81045437/Marlin
Marlin/src/sd/Sd2Card.cpp
C++
agpl-3.0
23,302
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * \file * \brief Sd2Card class for V2 SD/SDHC cards */ /** * Arduino Sd2Card Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include "SdFatConfig.h" #include "SdInfo.h" #include "disk_io_driver.h" #include <stdint.h> // SD card errors typedef enum : uint8_t { SD_CARD_ERROR_CMD0 = 0x01, // Timeout error for command CMD0 (initialize card in SPI mode) SD_CARD_ERROR_CMD8 = 0x02, // CMD8 was not accepted - not a valid SD card SD_CARD_ERROR_CMD12 = 0x03, // Card returned an error response for CMD12 (write stop) SD_CARD_ERROR_CMD17 = 0x04, // Card returned an error response for CMD17 (read block) SD_CARD_ERROR_CMD18 = 0x05, // Card returned an error response for CMD18 (read multiple block) SD_CARD_ERROR_CMD24 = 0x06, // Card returned an error response for CMD24 (write block) SD_CARD_ERROR_CMD25 = 0x07, // WRITE_MULTIPLE_BLOCKS command failed SD_CARD_ERROR_CMD58 = 0x08, // Card returned an error response for CMD58 (read OCR) SD_CARD_ERROR_ACMD23 = 0x09, // SET_WR_BLK_ERASE_COUNT failed SD_CARD_ERROR_ACMD41 = 0x0A, // ACMD41 initialization process timeout SD_CARD_ERROR_BAD_CSD = 0x0B, // Card returned a bad CSR version field SD_CARD_ERROR_ERASE = 0x0C, // Erase block group command failed SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0x0D, // Card not capable of single block erase SD_CARD_ERROR_ERASE_TIMEOUT = 0x0E, // Erase sequence timed out SD_CARD_ERROR_READ = 0x0F, // Card returned an error token instead of read data SD_CARD_ERROR_READ_REG = 0x10, // Read CID or CSD failed SD_CARD_ERROR_READ_TIMEOUT = 0x11, // Timeout while waiting for start of read data SD_CARD_ERROR_STOP_TRAN = 0x12, // Card did not accept STOP_TRAN_TOKEN SD_CARD_ERROR_WRITE = 0x13, // Card returned an error token as a response to a write operation SD_CARD_ERROR_WRITE_BLOCK_ZERO = 0x14, // REMOVE - not used ... attempt to write protected block zero SD_CARD_ERROR_WRITE_MULTIPLE = 0x15, // Card did not go ready for a multiple block write SD_CARD_ERROR_WRITE_PROGRAMMING = 0x16, // Card returned an error to a CMD13 status check after a write SD_CARD_ERROR_WRITE_TIMEOUT = 0x17, // Timeout occurred during write programming SD_CARD_ERROR_SCK_RATE = 0x18, // Incorrect rate selected SD_CARD_ERROR_INIT_NOT_CALLED = 0x19, // init() not called // 0x1A is unused now, it was: card returned an error for CMD59 (CRC_ON_OFF) SD_CARD_ERROR_READ_CRC = 0x1B // Invalid read CRC } sd_error_code_t; // card types uint8_t const SD_CARD_TYPE_SD1 = 1, // Standard capacity V1 SD card SD_CARD_TYPE_SD2 = 2, // Standard capacity V2 SD card SD_CARD_TYPE_SDHC = 3; // High Capacity SD card /** * Define SOFTWARE_SPI to use bit-bang SPI */ #if ANY(MEGA_SOFT_SPI, USE_SOFTWARE_SPI) #define SOFTWARE_SPI #endif #if IS_TEENSY_35_36 || IS_TEENSY_40_41 #include "NXP_SDHC.h" #define BUILTIN_SDCARD 254 #endif /** * \class Sd2Card * \brief Raw access to SD and SDHC flash memory cards. */ class DiskIODriver_SPI_SD : public DiskIODriver { public: DiskIODriver_SPI_SD() : errorCode_(SD_CARD_ERROR_INIT_NOT_CALLED), type_(0) {} bool erase(uint32_t firstBlock, uint32_t lastBlock); bool eraseSingleBlockEnable(); /** * Set SD error code. * \param[in] code value for error code. */ void error(const uint8_t code); /** * \return error code for last error. See Sd2Card.h for a list of error codes. */ inline int errorCode() const { return errorCode_; } /** \return error data for last error. */ inline int errorData() const { return status_; } /** * Initialize an SD flash memory card with default clock rate and chip * select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). * * \return true for success or false for failure. */ bool init(const uint8_t sckRateID, const pin_t chipSelectPin) override; bool setSckRate(const uint8_t sckRateID); /** * Return the card type: SD V1, SD V2 or SDHC * \return 0 - SD V1, 1 - SD V2, or 3 - SDHC. */ int type() const { return type_; } /** * Read a card's CID register. The CID contains card identification * information such as Manufacturer ID, Product name, Product serial * number and Manufacturing date. * * \param[out] cid pointer to area for returned data. * * \return true for success or false for failure. */ bool readCID(cid_t * const cid) { return readRegister(CMD10, cid); } /** * Read a card's CSD register. The CSD contains Card-Specific Data that * provides information regarding access to the card's contents. * * \param[out] csd pointer to area for returned data. * * \return true for success or false for failure. */ inline bool readCSD(csd_t * const csd) override { return readRegister(CMD9, csd); } bool readData(uint8_t * const dst) override; bool readStart(uint32_t blockNumber) override; bool readStop() override; bool writeData(const uint8_t * const src) override; bool writeStart(uint32_t blockNumber, const uint32_t eraseCount) override; bool writeStop() override; bool readBlock(uint32_t blockNumber, uint8_t * const dst) override; bool writeBlock(uint32_t blockNumber, const uint8_t * const src) override; uint32_t cardSize() override; bool isReady() override { return ready; }; void idle() override {} private: bool ready = false; uint8_t chipSelectPin_, errorCode_, spiRate_, status_, type_; // private functions inline uint8_t cardAcmd(const uint8_t cmd, const uint32_t arg) { cardCommand(CMD55, 0); return cardCommand(cmd, arg); } uint8_t cardCommand(const uint8_t cmd, const uint32_t arg); bool readData(uint8_t * const dst, const uint16_t count); bool readRegister(const uint8_t cmd, void * const buf); void chipDeselect(); void chipSelect(); inline void type(const uint8_t value) { type_ = value; } bool waitNotBusy(const millis_t timeout_ms); bool writeData(const uint8_t token, const uint8_t * const src); };
2301_81045437/Marlin
Marlin/src/sd/Sd2Card.h
C++
agpl-3.0
7,208
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfig.h" #include "SdInfo.h" #include "disk_io_driver.h" bool SDIO_Init(); bool SDIO_ReadBlock(uint32_t block, uint8_t *dst); bool SDIO_WriteBlock(uint32_t block, const uint8_t *src); bool SDIO_IsReady(); uint32_t SDIO_GetCardSize(); class DiskIODriver_SDIO : public DiskIODriver { public: bool init(const uint8_t sckRateID=0, const pin_t chipSelectPin=0) override { return SDIO_Init(); } bool readCSD(csd_t *csd) override { return false; } bool readStart(const uint32_t block) override { curBlock = block; return true; } bool readData(uint8_t *dst) override { return readBlock(curBlock++, dst); } bool readStop() override { curBlock = -1; return true; } bool writeStart(const uint32_t block, const uint32_t) override { curBlock = block; return true; } bool writeData(const uint8_t *src) override { return writeBlock(curBlock++, src); } bool writeStop() override { curBlock = -1; return true; } bool readBlock(uint32_t block, uint8_t *dst) override { return SDIO_ReadBlock(block, dst); } bool writeBlock(uint32_t block, const uint8_t *src) override { return SDIO_WriteBlock(block, src); } uint32_t cardSize() override { return SDIO_GetCardSize(); } bool isReady() override { return SDIO_IsReady(); } void idle() override {} private: uint32_t curBlock; };
2301_81045437/Marlin
Marlin/src/sd/Sd2Card_sdio.h
C++
agpl-3.0
2,517
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #if __GNUC__ > 8 #pragma GCC diagnostic ignored "-Waddress-of-packed-member" #endif /** * sd/SdBaseFile.cpp * * Arduino SdFat Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include "../inc/MarlinConfig.h" #if HAS_MEDIA #include "SdBaseFile.h" #include "../MarlinCore.h" SdBaseFile *SdBaseFile::cwd_ = 0; // Pointer to Current Working Directory // callback function for date/time void (*SdBaseFile::dateTime_)(uint16_t *date, uint16_t *time) = 0; // add a cluster to a file bool SdBaseFile::addCluster() { if (ENABLED(SDCARD_READONLY)) return false; if (!vol_->allocContiguous(1, &curCluster_)) return false; // if first cluster of file link to directory entry if (firstCluster_ == 0) { firstCluster_ = curCluster_; flags_ |= F_FILE_DIR_DIRTY; } return true; } // Add a cluster to a directory file and zero the cluster. // return with first block of cluster in the cache bool SdBaseFile::addDirCluster() { if (ENABLED(SDCARD_READONLY)) return false; uint32_t block; // max folder size if (fileSize_ / sizeof(dir_t) >= 0xFFFF) return false; if (!addCluster()) return false; if (!vol_->cacheFlush()) return false; block = vol_->clusterStartBlock(curCluster_); // set cache to first block of cluster vol_->cacheSetBlockNumber(block, true); // zero first block of cluster memset(vol_->cacheBuffer_.data, 0, 512); // zero rest of cluster for (uint8_t i = 1; i < vol_->blocksPerCluster_; i++) { if (!vol_->writeBlock(block + i, vol_->cacheBuffer_.data)) return false; } // Increase directory file size by cluster size fileSize_ += 512UL << vol_->clusterSizeShift_; return true; } // cache a file's directory entry // cache the current "dirBlock_" and return the entry at index "dirIndex_" // return pointer to cached entry or null for failure dir_t* SdBaseFile::cacheDirEntry(const uint8_t action) { if (!vol_->cacheRawBlock(dirBlock_, action)) return nullptr; return vol_->cache()->dir + dirIndex_; } /** * Close a file and force cached data and directory information * to be written to the storage device. * * \return true for success, false for failure. * Reasons for failure include no file is open or an I/O error. */ bool SdBaseFile::close() { bool rtn = sync(); type_ = FAT_FILE_TYPE_CLOSED; return rtn; } /** * Check for contiguous file and return its raw block range. * * \param[out] bgnBlock the first block address for the file. * \param[out] endBlock the last block address for the file. * * \return true for success, false for failure. * Reasons for failure include file is not contiguous, file has zero length * or an I/O error occurred. */ bool SdBaseFile::contiguousRange(uint32_t * const bgnBlock, uint32_t * const endBlock) { // error if no blocks if (firstCluster_ == 0) return false; for (uint32_t c = firstCluster_; ; c++) { uint32_t next; if (!vol_->fatGet(c, &next)) return false; // check for contiguous if (next != (c + 1)) { // error if not end of chain if (!vol_->isEOC(next)) return false; *bgnBlock = vol_->clusterStartBlock(firstCluster_); *endBlock = vol_->clusterStartBlock(c) + vol_->blocksPerCluster_ - 1; return true; } } return false; } /** * Create and open a new contiguous file of a specified size. * * \note This function only supports short DOS 8.3 names. * See open() for more information. * * \param[in] dirFile The directory where the file will be created. * \param[in] path A path with a valid DOS 8.3 file name. * \param[in] size The desired file size. * * \return true for success, false for failure. * Reasons for failure include \a path contains * an invalid DOS 8.3 file name, the FAT volume has not been initialized, * a file is already open, the file already exists, the root * directory is full or an I/O error. */ bool SdBaseFile::createContiguous(SdBaseFile * const dirFile, const char * const path, const uint32_t size) { if (ENABLED(SDCARD_READONLY)) return false; uint32_t count; // don't allow zero length file if (size == 0) return false; if (!open(dirFile, path, O_CREAT | O_EXCL | O_RDWR)) return false; // calculate number of clusters needed count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1; // allocate clusters if (!vol_->allocContiguous(count, &firstCluster_)) { remove(); return false; } fileSize_ = size; // insure sync() will update dir entry flags_ |= F_FILE_DIR_DIRTY; return sync(); } /** * Return a file's directory entry. * * \param[out] dir Location for return of the file's directory entry. * * \return true for success, false for failure. */ bool SdBaseFile::dirEntry(dir_t *dir) { // make sure fields on SD are correct if (!sync()) return false; // read entry dir_t *p = cacheDirEntry(SdVolume::CACHE_FOR_READ); if (!p) return false; // copy to caller's struct memcpy(dir, p, sizeof(dir_t)); return true; } /** * Format the name field of \a dir into the 13 byte array * \a name in standard 8.3 short name format. * * \param[in] dir The directory structure containing the name. * \param[out] name A 13 byte char array for the formatted name. */ void SdBaseFile::dirName(const dir_t &dir, char *name) { uint8_t j = 0; for (uint8_t i = 0; i < 11; ++i) { if (dir.name[i] == ' ')continue; if (i == 8) name[j++] = '.'; name[j++] = dir.name[i]; } name[j] = 0; } /** * Test for the existence of a file in a directory * * \param[in] name Name of the file to be tested for. * * The calling instance must be an open directory file. * * dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory * dirFile. * * \return true if the file exists else false. */ bool SdBaseFile::exists(const char *name) { SdBaseFile file; return file.open(this, name, O_READ); } /** * Get a string from a file. * * fgets() reads bytes from a file into the array pointed to by \a str, until * \a num - 1 bytes are read, or a delimiter is read and transferred to \a str, * or end-of-file is encountered. The string is then terminated * with a null byte. * * fgets() deletes CR, '\\r', from the string. This insures only a '\\n' * terminates the string for Windows text files which use CRLF for newline. * * \param[out] str Pointer to the array where the string is stored. * \param[in] num Maximum number of characters to be read * (including the final null byte). Usually the length * of the array \a str is used. * \param[in] delim Optional set of delimiters. The default is "\n". * * \return For success fgets() returns the length of the string in \a str. * If no data is read, fgets() returns zero for EOF or -1 if an error occurred. **/ int16_t SdBaseFile::fgets(char *str, int16_t num, char *delim) { char ch; int16_t n = 0; int16_t r = -1; while ((n + 1) < num && (r = read(&ch, 1)) == 1) { // delete CR if (ch == '\r') continue; str[n++] = ch; if (!delim) { if (ch == '\n') break; } else { if (strchr(delim, ch)) break; } } if (r < 0) { // read error return -1; } str[n] = '\0'; return n; } /** * Get a file's name * * \param[out] name An array of 13 characters for the file's name. * * \return true for success, false for failure. */ bool SdBaseFile::getDosName(char * const name) { if (!isOpen()) return false; if (isRoot()) { name[0] = '/'; name[1] = '\0'; return true; } // cache entry dir_t *p = cacheDirEntry(SdVolume::CACHE_FOR_READ); if (!p) return false; // format name dirName(*p, name); return true; } void SdBaseFile::getpos(filepos_t * const pos) { pos->position = curPosition_; pos->cluster = curCluster_; } /** * List directory contents. * * \param[in] pr Print stream for list. * * \param[in] flags The inclusive OR of * * LS_DATE - %Print file modification date * * LS_SIZE - %Print file size. * * LS_R - Recursive list of subdirectories. * * \param[in] indent Amount of space before file name. Used for recursive * list to indicate subdirectory level. */ void SdBaseFile::ls(const uint8_t flags/*=0*/, const uint8_t indent/*=0*/) { rewind(); int8_t status; while ((status = lsPrintNext(flags, indent))) { if (status > 1 && (flags & LS_R)) { const uint16_t index = curPosition() / 32 - 1; SdBaseFile s; if (s.open(this, index, O_READ)) s.ls(flags, indent + 2); seekSet(32 * (index + 1)); } } } // saves 32 bytes on stack for ls recursion // return 0 - EOF, 1 - normal file, or 2 - directory int8_t SdBaseFile::lsPrintNext(const uint8_t flags, const uint8_t indent) { dir_t dir; uint8_t w = 0; while (1) { if (read(&dir, sizeof(dir)) != sizeof(dir)) return 0; if (dir.name[0] == DIR_NAME_FREE) return 0; // skip deleted entry and entries for . and .. if (dir.name[0] != DIR_NAME_DELETED && dir.name[0] != '.' && DIR_IS_FILE_OR_SUBDIR(&dir)) break; } // indent for dir level for (uint8_t i = 0; i < indent; ++i) SERIAL_CHAR(' '); // print name for (uint8_t i = 0; i < 11; ++i) { if (dir.name[i] == ' ')continue; if (i == 8) { SERIAL_CHAR('.'); w++; } SERIAL_CHAR(dir.name[i]); w++; } if (DIR_IS_SUBDIR(&dir)) { SERIAL_CHAR('/'); w++; } if (flags & (LS_DATE | LS_SIZE)) { while (w++ < 14) SERIAL_CHAR(' '); } // print modify date/time if requested if (flags & LS_DATE) { SERIAL_CHAR(' '); printFatDate(dir.lastWriteDate); SERIAL_CHAR(' '); printFatTime(dir.lastWriteTime); } // print size if requested if (!DIR_IS_SUBDIR(&dir) && (flags & LS_SIZE)) { SERIAL_CHAR(' '); SERIAL_ECHO(dir.fileSize); } SERIAL_EOL(); return DIR_IS_FILE(&dir) ? 1 : 2; } /** * Calculate a checksum for an 8.3 filename * * \param name The 8.3 file name to calculate * * \return The checksum byte */ uint8_t lfn_checksum(const uint8_t *name) { uint8_t sum = 0; for (uint8_t i = 11; i; i--) sum = ((sum & 1) << 7) + (sum >> 1) + *name++; return sum; } // Format directory name field from a 8.3 name string bool SdBaseFile::make83Name(const char *str, uint8_t * const name, const char **ptr) { uint8_t n = 7, // Max index until a dot is found i = 11; while (i) name[--i] = ' '; // Set whole FILENAME.EXT to spaces while (*str && *str != '/') { // For each character, until nul or '/' uint8_t c = *str++; // Get char and advance if (c == '.') { // For a dot... if (n == 10) return false; // Already moved the max index? fail! n = 10; // Move the max index for full 8.3 name i = 8; // Move up to the extension place } else { // Fail for illegal characters PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); while (uint8_t b = pgm_read_byte(p++)) if (b == c) return false; if (i > n || c < 0x21 || c == 0x7F) return false; // Check size, non-printable characters name[i++] = c + (WITHIN(c, 'a', 'z') ? 'A' - 'a' : 0); // Uppercase required for 8.3 name } } *ptr = str; // Set passed pointer to the end return name[0] != ' '; // Return true if any name was set } /** * Make a new directory. * * \param[in] parent An open SdFat instance for the directory that will contain * the new directory. * * \param[in] path A path with a valid 8.3 DOS name for the new directory. * * \param[in] pFlag Create missing parent directories if true. * * \return true for success, false for failure. * Reasons for failure include this file is already open, \a parent is not a * directory, \a path is invalid or already exists in \a parent. */ bool SdBaseFile::mkdir(SdBaseFile *parent, const char *path, const bool pFlag/*=true*/) { if (ENABLED(SDCARD_READONLY)) return false; SdBaseFile dir1, dir2, *sub = &dir1; SdBaseFile * const start = parent; #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) uint8_t dlname[LONG_FILENAME_LENGTH]; #endif if (!parent || isOpen()) return false; if (*path == '/') { while (*path == '/') path++; if (!parent->isRoot()) { if (!dir2.openRoot(parent->vol_)) return false; parent = &dir2; } } uint8_t dname[11]; for (;;) { if (!TERN(LONG_FILENAME_WRITE_SUPPORT, parsePath(path, dname, dlname, &path), make83Name(path, dname, &path))) return false; while (*path == '/') path++; if (!*path) break; if (!sub->open(parent, dname OPTARG(LONG_FILENAME_WRITE_SUPPORT, dlname), O_READ)) { if (!pFlag || !sub->mkdir(parent, dname OPTARG(LONG_FILENAME_WRITE_SUPPORT, dlname))) return false; } if (parent != start) parent->close(); parent = sub; sub = parent != &dir1 ? &dir1 : &dir2; } return mkdir(parent, dname OPTARG(LONG_FILENAME_WRITE_SUPPORT, dlname)); } bool SdBaseFile::mkdir(SdBaseFile * const parent, const uint8_t dname[11] OPTARG(LONG_FILENAME_WRITE_SUPPORT, const uint8_t dlname[LONG_FILENAME_LENGTH]) ) { if (ENABLED(SDCARD_READONLY)) return false; if (!parent->isDir()) return false; // create a normal file if (!open(parent, dname OPTARG(LONG_FILENAME_WRITE_SUPPORT, dlname), O_CREAT | O_EXCL | O_RDWR)) return false; // convert file to directory flags_ = O_READ; type_ = FAT_FILE_TYPE_SUBDIR; // allocate and zero first cluster if (!addDirCluster()) return false; // force entry to SD if (!sync()) return false; // cache entry - should already be in cache due to sync() call dir_t *p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); if (!p) return false; // change directory entry attribute p->attributes = DIR_ATT_DIRECTORY; // make entry for '.' dir_t d; memcpy(&d, p, sizeof(d)); d.name[0] = '.'; for (uint8_t i = 1; i < 11; ++i) d.name[i] = ' '; // cache block for '.' and '..' uint32_t block = vol_->clusterStartBlock(firstCluster_); if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false; // copy '.' to block memcpy(&vol_->cache()->dir[0], &d, sizeof(d)); // make entry for '..' d.name[1] = '.'; if (parent->isRoot()) { d.firstClusterLow = 0; d.firstClusterHigh = 0; } else { d.firstClusterLow = parent->firstCluster_ & 0xFFFF; d.firstClusterHigh = parent->firstCluster_ >> 16; } // copy '..' to block memcpy(&vol_->cache()->dir[1], &d, sizeof(d)); // write first block return vol_->cacheFlush(); } /** * Open a file in the current working directory. * * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. * * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t). * * \return true for success, false for failure. */ bool SdBaseFile::open(const char * const path, const uint8_t oflag) { return open(cwd_, path, oflag); } /** * Open a file or directory by name. * * \param[in] dirFile An open SdFat instance for the directory containing the * file to be opened. * * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. * * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive * OR of flags from the following list * * O_READ - Open for reading. * * O_RDONLY - Same as O_READ. * * O_WRITE - Open for writing. * * O_WRONLY - Same as O_WRITE. * * O_RDWR - Open for reading and writing. * * O_APPEND - If set, the file offset shall be set to the end of the * file prior to each write. * * O_AT_END - Set the initial position at the end of the file. * * O_CREAT - If the file exists, this flag has no effect except as noted * under O_EXCL below. Otherwise, the file shall be created * * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. * * O_SYNC - Call sync() after each write. This flag should not be used with * write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class. * These functions do character at a time writes so sync() will be called * after each byte. * * O_TRUNC - If the file exists and is a regular file, and the file is * successfully opened and is not read only, its length shall be truncated to 0. * * WARNING: A given file must not be opened by more than one SdBaseFile object * of file corruption may occur. * * \note Directory files must be opened read only. Write and truncation is * not allowed for directory files. * * \return true for success, false for failure. * Reasons for failure include this file is already open, \a dirFile is not * a directory, \a path is invalid, the file does not exist * or can't be opened in the access mode specified by oflag. */ bool SdBaseFile::open(SdBaseFile * const dirFile, const char *path, const uint8_t oflag) { uint8_t dname[11]; SdBaseFile dir1, dir2; SdBaseFile *parent = dirFile, *sub = &dir1; #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) uint8_t dlname[LONG_FILENAME_LENGTH]; #endif if (!dirFile || isOpen()) return false; if (*path == '/') { // Path starts with '/' if (!dirFile->isRoot()) { // Is the passed dirFile the root? if (!dir2.openRoot(dirFile->vol_)) return false; // Get the root in dir2, if possible parent = &dir2; // Change 'parent' to point at the root dir } while (*path == '/') path++; // Skip all leading slashes } for (;;) { if (!TERN(LONG_FILENAME_WRITE_SUPPORT, parsePath(path, dname, dlname, &path), make83Name(path, dname, &path))) return false; while (*path == '/') path++; if (!*path) break; if (TERN0(LONG_FILENAME_WRITE_SUPPORT, !sub->open(parent, dname, dlname, O_READ))) return false; if (parent != dirFile) parent->close(); parent = sub; sub = parent != &dir1 ? &dir1 : &dir2; } return open(parent, dname OPTARG(LONG_FILENAME_WRITE_SUPPORT, dlname), oflag); } // open with filename in dname and long filename in dlname bool SdBaseFile::open(SdBaseFile * const dirFile, const uint8_t dname[11] OPTARG(LONG_FILENAME_WRITE_SUPPORT, const uint8_t dlname[LONG_FILENAME_LENGTH]) , const uint8_t oflag ) { bool emptyFound = false, fileFound = false; uint8_t index = 0; dir_t *p; #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) // LFN - Long File Name support const bool useLFN = dlname[0] != 0; bool lfnFileFound = false; vfat_t *pvFat; uint8_t emptyCount = 0, emptyIndex = 0, reqEntriesNum = useLFN ? getLFNEntriesNum((char*)dlname) + 1 : 1, lfnNameLength = useLFN ? strlen((char*)dlname) : 0, lfnName[LONG_FILENAME_LENGTH], lfnSequenceNumber = 0, lfnChecksum = 0; #endif // Rewind this dir vol_ = dirFile->vol_; dirFile->rewind(); // search for file while (dirFile->curPosition_ < dirFile->fileSize_) { // Get absolute index position index = (dirFile->curPosition_ >> 5) IF_DISABLED(LONG_FILENAME_WRITE_SUPPORT, & 0x0F); // Get next entry if (!(p = dirFile->readDirCache())) return false; // Check empty status: Is entry empty? if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { // Count the contiguous available entries in which (eventually) fit the new dir entry, if it's a write operation if (!emptyFound) { #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) if (emptyCount == 0) emptyIndex = index; // Incr empty entries counter // If found the required empty entries, mark it if (++emptyCount == reqEntriesNum) { dirBlock_ = dirFile->vol_->cacheBlockNumber(); dirIndex_ = index & 0xF; emptyFound = true; } #else dirBlock_ = dirFile->vol_->cacheBlockNumber(); dirIndex_ = index; emptyFound = true; #endif } // Done if no entries follow if (p->name[0] == DIR_NAME_FREE) break; } else { // Entry not empty #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) // Reset empty counter if (!emptyFound) emptyCount = 0; // Search for SFN or LFN? if (!useLFN) { // Check using SFN: file found? if (!memcmp(dname, p->name, 11)) { fileFound = true; break; } } else { // Check using LFN: LFN not found? continue search for LFN if (!lfnFileFound) { // Is this dir a LFN? if (isDirLFN(p)) { // Get VFat dir entry pvFat = (vfat_t *) p; // Get checksum from the last entry of the sequence if (pvFat->sequenceNumber & 0x40) { lfnChecksum = pvFat->checksum; ZERO(lfnName); } // Get LFN sequence number lfnSequenceNumber = pvFat->sequenceNumber & 0x1F; if (WITHIN(lfnSequenceNumber, 1, reqEntriesNum)) { // Check checksum for all other entries with the starting checksum fetched before if (lfnChecksum == pvFat->checksum) { // Set chunk of LFN from VFAT entry into lfnName getLFNName(pvFat, (char *)lfnName, lfnSequenceNumber); TERN_(UTF_FILENAME_SUPPORT, convertUtf16ToUtf8((char *)lfnName)); // LFN found? if (!strncasecmp((char*)dlname, (char*)lfnName, lfnNameLength)) lfnFileFound = true; } } } } else { // Complete LFN found, check for related SFN // Check if only the SFN checksum match because the filename may be different due to different truncation methods if (!isDirLFN(p) && (lfnChecksum == lfn_checksum(p->name))) { fileFound = true; break; } else lfnFileFound = false; // SFN not valid for the LFN found, reset LFN FileFound } } #else if (!memcmp(dname, p->name, 11)) { fileFound = true; break; } #endif // LONG_FILENAME_WRITE_SUPPORT } } if (fileFound) { // don't open existing file if O_EXCL if (oflag & O_EXCL) return false; TERN_(LONG_FILENAME_WRITE_SUPPORT, index &= 0xF); } else { // don't create unless O_CREAT and O_WRITE if ((oflag & (O_CREAT | O_WRITE)) != (O_CREAT | O_WRITE)) return false; #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) // Use bookmark index if found empty entries if (emptyFound) index = emptyIndex; // Make room for needed entries while (emptyCount < reqEntriesNum) { p = dirFile->readDirCache(); if (!p) break; emptyCount++; } while (emptyCount < reqEntriesNum) { if (dirFile->type_ == FAT_FILE_TYPE_ROOT_FIXED) return false; // add and zero cluster for dirFile - first cluster is in cache for write if (!dirFile->addDirCluster()) return false; emptyCount += dirFile->vol_->blocksPerCluster() * 16; } // Move to 1st entry to write if (!dirFile->seekSet(32 * index)) return false; // Dir entries write loop: [LFN] + SFN(1) for (uint8_t dirWriteIdx = 0; dirWriteIdx < reqEntriesNum; ++dirWriteIdx) { index = (dirFile->curPosition_ / 32) & 0xF; p = dirFile->readDirCache(); // LFN or SFN Entry? if (dirWriteIdx < reqEntriesNum - 1) { // Write LFN Entries pvFat = (vfat_t *) p; // initialize as empty file memset(pvFat, 0, sizeof(*pvFat)); lfnSequenceNumber = (reqEntriesNum - dirWriteIdx - 1) & 0x1F; pvFat->attributes = DIR_ATT_LONG_NAME; pvFat->checksum = lfn_checksum(dname); // Set sequence number and mark as last LFN entry if it's the 1st loop pvFat->sequenceNumber = lfnSequenceNumber | (dirWriteIdx == 0 ? 0x40 : 0); // Set LFN name block setLFNName(pvFat, (char*)dlname, lfnSequenceNumber); } else { // Write SFN Entry // initialize as empty file memset(p, 0, sizeof(*p)); memcpy(p->name, dname, 11); // set timestamps if (dateTime_) { // call user date/time function dateTime_(&p->creationDate, &p->creationTime); } else { // use default date/time p->creationDate = FAT_DEFAULT_DATE; p->creationTime = FAT_DEFAULT_TIME; } p->lastAccessDate = p->creationDate; p->lastWriteDate = p->creationDate; p->lastWriteTime = p->creationTime; } // write entry to SD dirFile->vol_->cacheSetDirty(); if (!dirFile->vol_->cacheFlush()) return false; } #else // !LONG_FILENAME_WRITE_SUPPORT if (emptyFound) { index = dirIndex_; p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); if (!p) return false; } else { if (dirFile->type_ == FAT_FILE_TYPE_ROOT_FIXED) return false; // add and zero cluster for dirFile - first cluster is in cache for write if (!dirFile->addDirCluster()) return false; // use first entry in cluster p = dirFile->vol_->cache()->dir; index = 0; } // initialize as empty file memset(p, 0, sizeof(*p)); memcpy(p->name, dname, 11); // set timestamps if (dateTime_) { // call user date/time function dateTime_(&p->creationDate, &p->creationTime); } else { // use default date/time p->creationDate = FAT_DEFAULT_DATE; p->creationTime = FAT_DEFAULT_TIME; } p->lastAccessDate = p->creationDate; p->lastWriteDate = p->creationDate; p->lastWriteTime = p->creationTime; // write entry to SD if (!dirFile->vol_->cacheFlush()) return false; #endif // !LONG_FILENAME_WRITE_SUPPORT } // open entry in cache return openCachedEntry(index, oflag); } /** * Open a file by index. * * \param[in] dirFile An open SdFat instance for the directory. * * \param[in] index The \a index of the directory entry for the file to be * opened. The value for \a index is (directory file position)/32. * * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. * * See open() by path for definition of flags. * \return true for success or false for failure. */ bool SdBaseFile::open(SdBaseFile *dirFile, uint16_t index, const uint8_t oflag) { vol_ = dirFile->vol_; // error if already open if (isOpen() || !dirFile) return false; // don't open existing file if O_EXCL - user call error if (oflag & O_EXCL) return false; // seek to location of entry if (!dirFile->seekSet(32 * index)) return false; // read entry into cache dir_t *p = dirFile->readDirCache(); if (!p) return false; // error if empty slot or '.' or '..' if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { return false; } // open cached entry return openCachedEntry(index & 0xF, oflag); } // open a cached directory entry. Assumes vol_ is initialized bool SdBaseFile::openCachedEntry(const uint8_t dirIndex, const uint8_t oflag) { dir_t *p; #if ENABLED(SDCARD_READONLY) if (oflag & (O_WRITE | O_CREAT | O_TRUNC)) goto FAIL; #endif // location of entry in cache p = &vol_->cache()->dir[dirIndex]; // write or truncate is an error for a directory or read-only file if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) { if (oflag & (O_WRITE | O_TRUNC)) goto FAIL; } // remember location of directory entry on SD dirBlock_ = vol_->cacheBlockNumber(); dirIndex_ = dirIndex; // copy first cluster number for directory fields firstCluster_ = (uint32_t)p->firstClusterHigh << 16; firstCluster_ |= p->firstClusterLow; // make sure it is a normal file or subdirectory if (DIR_IS_FILE(p)) { fileSize_ = p->fileSize; type_ = FAT_FILE_TYPE_NORMAL; } else if (DIR_IS_SUBDIR(p)) { if (!vol_->chainSize(firstCluster_, &fileSize_)) goto FAIL; type_ = FAT_FILE_TYPE_SUBDIR; } else goto FAIL; // save open flags for read/write flags_ = oflag & F_OFLAG; // set to start of file curCluster_ = 0; curPosition_ = 0; if ((oflag & O_TRUNC) && !truncate(0)) return false; return oflag & O_AT_END ? seekEnd(0) : true; FAIL: type_ = FAT_FILE_TYPE_CLOSED; return false; } /** * Open the next file or subdirectory in a directory. * * \param[in] dirFile An open SdFat instance for the directory containing the * file to be opened. * * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. * * See open() by path for definition of flags. * \return true for success or false for failure. */ bool SdBaseFile::openNext(SdBaseFile *dirFile, const uint8_t oflag) { if (!dirFile) return false; // error if already open if (isOpen()) return false; vol_ = dirFile->vol_; while (1) { uint8_t index = 0xF & (dirFile->curPosition_ >> 5); // read entry into cache dir_t *p = dirFile->readDirCache(); if (!p) return false; // done if last entry if (p->name[0] == DIR_NAME_FREE) return false; // skip empty slot or '.' or '..' if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { continue; } // must be file or dir if (DIR_IS_FILE_OR_SUBDIR(p)) { return openCachedEntry(index, oflag); } } return false; } #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) /** * Check if dir is a long file name entry (LFN) * * \param[in] dir Parent of this directory will be opened. Must not be root. * \return true if the dir is a long file name entry (LFN) */ bool SdBaseFile::isDirLFN(const dir_t* dir) { if (DIR_IS_LONG_NAME(dir)) { vfat_t *VFAT = (vfat_t*)dir; // Sanity-check the VFAT entry. The first cluster is always set to zero. // The sequence number should be higher than 0 and lower than maximum allowed by VFAT spec if ((VFAT->firstClusterLow == 0) && WITHIN((VFAT->sequenceNumber & 0x1F), 1, MAX_VFAT_ENTRIES)) return true; } return false; } /** * Check if dirname string is a long file name (LFN) * * \param[in] dirname The string to check * \return true if the dirname is a long file name (LFN) * \return false if the dirname is a short file name 8.3 (SFN) */ bool SdBaseFile::isDirNameLFN(const char * const dirname) { uint8_t length = strlen(dirname), idx = length; bool dotFound = false; if (idx > 12) return true; // LFN due to filename length > 12 ("filename.ext") // Check dot(s) position while (idx) { if (dirname[--idx] == '.') { if (!dotFound) { // Last dot (extension) is allowed only // in position [1..8] from start or [0..3] from end for SFN else it's a LFN // A filename starting with "." is a LFN (eg. ".file" ->in SFN-> "file~1 ") // A filename ending with "." is a SFN (if length <= 9) (eg. "file." ->in SFN-> "file ") if (idx > 8 || idx == 0 || (length - idx - 1) > 3) return true; // LFN due to dot extension position dotFound = true; } else { // Found another dot, is a LFN return true; } } } // If no dots found, the filename must be of max 8 characters if ((!dotFound) && length > 8) return true; // LFN due to max filename (without extension) length return false; } /** * Parse path and return 8.3 format and LFN filenames (if the parsed path is a LFN) * The SFN is without dot ("FILENAMEEXT") * The LFN is complete ("Filename.ext") */ bool SdBaseFile::parsePath(const char *path, uint8_t * const name, uint8_t * const lname, const char **ptrNextPath) { // Init randomizer for SFN generation randomSeed(millis()); // Parse the LFN uint8_t ilfn = 0; bool lastDotFound = false; const char *pLastDot = 0; const char *lfnpath = path; uint8_t c; while (*lfnpath && *lfnpath != '/') { if (ilfn == LONG_FILENAME_LENGTH - 1) return false; // Name too long c = *lfnpath++; // Get char and advance // Fail for illegal characters PGM_P p = PSTR("|<>^+=?/[];:,*\"\\"); while (uint8_t b = pgm_read_byte(p++)) if (b == c) return false; // Check reserved characters if (c < 0x20 || c == 0x7F) return false; // Check non-printable characters if (c == '.' && (lfnpath - 1) > path) { // Skip dot '.' check in 1st position // Save last dot pointer (skip if starts with '.') pLastDot = lfnpath - 1; lastDotFound = true; } lname[ilfn++] = c; // Set LFN character } // Terminate LFN lname[ilfn] = 0; // Parse/generate 8.3 SFN. Will take // until 8 characters for the filename part // until 3 characters for the extension part (if exists) // Add 4 more characters if name part < 3 // Add '~cnt' characters if it's a LFN const bool isLFN = isDirNameLFN((char*)lname); uint8_t n = isLFN ? 5 : 7, // Max index for each component of the file: // starting with 7 or 5 (if LFN) // switch to 10 for extension if the last dot is found i = 11; while (i) name[--i] = ' '; // Set whole FILENAMEEXT to spaces while (*path && *path != '/') { c = *path++; // Get char and advance // Skip spaces and dots (if it's not the last dot) if (c == ' ') continue; if (c == '.' && (!lastDotFound || (lastDotFound && path < pLastDot))) continue; // Fail for illegal characters PGM_P p = PSTR("|<>^+=?/[];:,*\"\\"); while (uint8_t b = pgm_read_byte(p++)) if (b == c) return false; // Check reserved characters if (c < 0x21 || c == 0x7F) return false; // Check non-printable characters // Is last dot? if (c == '.') { // Switch to extension part n = 10; i = 8; } // If in valid range add the character else if (i <= n) // Check size for 8.3 format name[i++] = c + (WITHIN(c, 'a', 'z') ? 'A' - 'a' : 0); // Uppercase required for 8.3 name } // If it's a LFN then the SFN always need: // - A minimal of 3 characters (otherwise 4 chars are added) // - The '~cnt' at the end if (isLFN) { // Get the 1st free character uint8_t iFree = 0; while (1) if (name[iFree++] == ' ' || iFree == 11) break; iFree--; // Check minimal length if (iFree < 3) { // Append 4 extra characters name[iFree++] = random(0,24) + 'A'; name[iFree++] = random(0,24) + 'A'; name[iFree++] = random(0,24) + 'A'; name[iFree++] = random(0,24) + 'A'; } // Append '~cnt' characters if (iFree > 5) iFree = 5; // Force the append in the last 3 characters of name part name[iFree++] = '~'; name[iFree++] = random(1,9) + '0'; name[iFree++] = random(1,9) + '0'; } // Check if LFN is needed if (!isLFN) lname[0] = 0; // Zero LFN *ptrNextPath = path; // Set passed pointer to the end return name[0] != ' '; // Return true if any name was set } /** * Get the LFN filename block from a dir. Get the block in lname at startOffset */ void SdBaseFile::getLFNName(vfat_t *pFatDir, char *lname, const uint8_t sequenceNumber) { const uint8_t startOffset = (sequenceNumber - 1) * FILENAME_LENGTH; for (uint8_t i = 0; i < FILENAME_LENGTH; ++i) { const uint16_t utf16_ch = (i >= 11) ? pFatDir->name3[i - 11] : (i >= 5) ? pFatDir->name2[i - 5] : pFatDir->name1[i]; #if ENABLED(UTF_FILENAME_SUPPORT) // We can't reconvert to UTF-8 here as UTF-8 is variable-size encoding, but joining LFN blocks // needs static bytes addressing. So here just store full UTF-16LE words to re-convert later. const uint16_t idx = (startOffset + i) * 2; // This is fixed as FAT LFN always contain UTF-16LE encoding lname[idx] = utf16_ch & 0xFF; lname[idx + 1] = (utf16_ch >> 8) & 0xFF; #else // Replace all multibyte characters to '_' lname[startOffset + i] = (utf16_ch > 0xFF) ? '_' : (utf16_ch & 0xFF); #endif } } /** * Set the LFN filename block lname to a dir. Put the block based on sequence number */ void SdBaseFile::setLFNName(vfat_t *pFatDir, char *lname, const uint8_t sequenceNumber) { const uint8_t startOffset = (sequenceNumber - 1) * FILENAME_LENGTH, nameLength = strlen(lname); for (uint8_t i = 0; i < FILENAME_LENGTH; ++i) { uint16_t ch = 0; if ((startOffset + i) < nameLength) ch = lname[startOffset + i]; else if ((startOffset + i) > nameLength) ch = 0xFFFF; // Set char if (i < 5) pFatDir->name1[i] = ch; else if (i < 11) pFatDir->name2[i - 5] = ch; else pFatDir->name3[i - 11] = ch; } } #endif // LONG_FILENAME_WRITE_SUPPORT #if 0 /** * Open a directory's parent directory. * * \param[in] dir Parent of this directory will be opened. Must not be root. * * \return true for success, false for failure. */ bool SdBaseFile::openParent(SdBaseFile *dir) { dir_t entry; SdBaseFile file; uint32_t c; uint32_t cluster; uint32_t lbn; // error if already open or dir is root or dir is not a directory if (isOpen() || !dir || dir->isRoot() || !dir->isDir()) return false; vol_ = dir->vol_; // position to '..' if (!dir->seekSet(32)) return false; // read '..' entry if (dir->read(&entry, sizeof(entry)) != 32) return false; // verify it is '..' if (entry.name[0] != '.' || entry.name[1] != '.') return false; // start cluster for '..' cluster = entry.firstClusterLow; cluster |= (uint32_t)entry.firstClusterHigh << 16; if (cluster == 0) return openRoot(vol_); // start block for '..' lbn = vol_->clusterStartBlock(cluster); // first block of parent dir if (!vol_->cacheRawBlock(lbn, SdVolume::CACHE_FOR_READ)) return false; dir_t *p = &vol_->cacheBuffer_.dir[1]; // verify name for '../..' if (p->name[0] != '.' || p->name[1] != '.') return false; // '..' is pointer to first cluster of parent. open '../..' to find parent if (p->firstClusterHigh == 0 && p->firstClusterLow == 0) { if (!file.openRoot(dir->volume())) return false; } else if (!file.openCachedEntry(1, O_READ)) return false; // search for parent in '../..' do { if (file.readDir(&entry, nullptr) != 32) return false; c = entry.firstClusterLow; c |= (uint32_t)entry.firstClusterHigh << 16; } while (c != cluster); // open parent return open(&file, file.curPosition() / 32 - 1, O_READ); } #endif /** * Open a volume's root directory. * * \param[in] vol The FAT volume containing the root directory to be opened. * * \return true for success, false for failure. * Reasons for failure include the file is already open, the FAT volume has * not been initialized or it a FAT12 volume. */ bool SdBaseFile::openRoot(SdVolume *vol) { // error if file is already open if (isOpen()) return false; if (vol->fatType() == 16 || (FAT12_SUPPORT && vol->fatType() == 12)) { type_ = FAT_FILE_TYPE_ROOT_FIXED; firstCluster_ = 0; fileSize_ = 32 * vol->rootDirEntryCount(); } else if (vol->fatType() == 32) { type_ = FAT_FILE_TYPE_ROOT32; firstCluster_ = vol->rootDirStart(); if (!vol->chainSize(firstCluster_, &fileSize_)) return false; } else // volume is not initialized, invalid, or FAT12 without support return false; vol_ = vol; // read only flags_ = O_READ; // set to start of file curCluster_ = curPosition_ = 0; // root has no directory entry dirBlock_ = dirIndex_ = 0; return true; } /** * Return the next available byte without consuming it. * * \return The byte if no error and not at eof else -1; */ int SdBaseFile::peek() { filepos_t pos; getpos(&pos); int c = read(); if (c >= 0) setpos(&pos); return c; } // print uint8_t with width 2 static void print2u(const uint8_t v) { if (v < 10) SERIAL_CHAR('0'); SERIAL_ECHO(v); } /** * %Print a directory date field to Serial. * * Format is yyyy-mm-dd. * * \param[in] fatDate The date field from a directory entry. */ /** * %Print a directory date field. * * Format is yyyy-mm-dd. * * \param[in] pr Print stream for output. * \param[in] fatDate The date field from a directory entry. */ void SdBaseFile::printFatDate(const uint16_t fatDate) { SERIAL_ECHO(FAT_YEAR(fatDate)); SERIAL_CHAR('-'); print2u(FAT_MONTH(fatDate)); SERIAL_CHAR('-'); print2u(FAT_DAY(fatDate)); } /** * %Print a directory time field. * * Format is hh:mm:ss. * * \param[in] pr Print stream for output. * \param[in] fatTime The time field from a directory entry. */ void SdBaseFile::printFatTime(const uint16_t fatTime) { print2u(FAT_HOUR(fatTime)); SERIAL_CHAR(':'); print2u(FAT_MINUTE(fatTime)); SERIAL_CHAR(':'); print2u(FAT_SECOND(fatTime)); } /** * Print a file's name to Serial * * \return true for success, false for failure. */ bool SdBaseFile::printName() { char name[FILENAME_LENGTH]; if (!getDosName(name)) return false; SERIAL_ECHO(name); return true; } /** * Read the next byte from a file. * * \return For success read returns the next byte in the file as an int. * If an error occurs or end of file is reached -1 is returned. */ int16_t SdBaseFile::read() { uint8_t b; return read(&b, 1) == 1 ? b : -1; } /** * Read data from a file starting at the current position. * * \param[out] buf Pointer to the location that will receive the data. * * \param[in] nbyte Maximum number of bytes to read. * * \return For success read() returns the number of bytes read. * A value less than \a nbyte, including zero, will be returned * if end of file is reached. * If an error occurs, read() returns -1. Possible errors include * read() called before a file has been opened, corrupt file system * or an I/O error occurred. */ int16_t SdBaseFile::read(void * const buf, uint16_t nbyte) { uint8_t *dst = reinterpret_cast<uint8_t*>(buf); uint16_t offset, toRead; uint32_t block; // raw device block number // error if not open or write only if (!isOpen() || !(flags_ & O_READ)) return -1; // max bytes left in file NOMORE(nbyte, fileSize_ - curPosition_); // amount left to read toRead = nbyte; while (toRead > 0) { offset = curPosition_ & 0x1FF; // offset in block if (type_ == FAT_FILE_TYPE_ROOT_FIXED) { block = vol_->rootDirStart() + (curPosition_ >> 9); } else { uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); if (offset == 0 && blockOfCluster == 0) { // start of new cluster if (curPosition_ == 0) curCluster_ = firstCluster_; // use first cluster in file else if (!vol_->fatGet(curCluster_, &curCluster_)) // get next cluster from FAT return -1; } block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; } uint16_t n = toRead; // amount to be read from current block NOMORE(n, 512 - offset); // no buffering needed if n == 512 if (n == 512 && block != vol_->cacheBlockNumber()) { if (!vol_->readBlock(block, dst)) return -1; } else { // read block to cache and copy data to caller if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return -1; uint8_t *src = vol_->cache()->data + offset; memcpy(dst, src, n); } dst += n; curPosition_ += n; toRead -= n; } return nbyte; } /** * Read the next entry in a directory. * * \param[out] dir The dir_t struct that will receive the data. * * \return For success return a non-zero value (number of bytes read). * A value of zero will be returned if end of dir is reached. * If an error occurs, readDir() returns -1. Possible errors: * - readDir() called on unopened dir * - not a directory file * - bad dir entry * - I/O error */ int8_t SdBaseFile::readDir(dir_t * const dir, char * const longFilename) { int16_t n; // if not a directory file or miss-positioned return an error if (!isDir() || (0x1F & curPosition_)) return -1; #define INVALIDATE_LONGNAME() (longFilename[0] = longFilename[1] = '\0') // If we have a longFilename buffer, mark it as invalid. // If a long filename is found it will be filled automatically. if (longFilename) INVALIDATE_LONGNAME(); uint8_t checksum_error = 0xFF, checksum = 0; while (1) { n = read(dir, sizeof(dir_t)); if (n != sizeof(dir_t)) return n ? -1 : 0; // Last entry if DIR_NAME_FREE if (dir->name[0] == DIR_NAME_FREE) return 0; // Skip deleted entry and entry for . and .. if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') { if (longFilename) INVALIDATE_LONGNAME(); // Invalidate erased file long name, if any continue; } if (longFilename) { // Fill the long filename if we have a long filename entry. // Long filename entries are stored before the short filename. if (DIR_IS_LONG_NAME(dir)) { vfat_t *VFAT = (vfat_t*)dir; // Sanity-check the VFAT entry. The first cluster is always set to zero. And the sequence number should be higher than 0 if (VFAT->firstClusterLow == 0) { const uint8_t seq = VFAT->sequenceNumber & 0x1F; if (WITHIN(seq, 1, VFAT_ENTRIES_LIMIT)) { if (seq == 1) { checksum = VFAT->checksum; checksum_error = 0; } else if (checksum != VFAT->checksum) // orphan detected checksum_error = 1; #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) getLFNName(VFAT, longFilename, seq); // Get chunk of LFN from VFAT entry #else // !LONG_FILENAME_WRITE_SUPPORT n = (seq - 1) * (FILENAME_LENGTH); for (uint8_t i = 0; i < FILENAME_LENGTH; ++i) { const uint16_t utf16_ch = (i >= 11) ? VFAT->name3[i - 11] : (i >= 5) ? VFAT->name2[i - 5] : VFAT->name1[i]; #if ENABLED(UTF_FILENAME_SUPPORT) // We can't reconvert to UTF-8 here as UTF-8 is variable-size encoding, but joining LFN blocks // needs static bytes addressing. So here just store full UTF-16LE words to re-convert later. uint16_t idx = (n + i) * 2; // This is fixed as FAT LFN always contain UTF-16LE encoding longFilename[idx] = utf16_ch & 0xFF; longFilename[idx + 1] = (utf16_ch >> 8) & 0xFF; #else // Replace multibyte character with '_' longFilename[n + i] = (utf16_ch > 0xFF) ? '_' : (utf16_ch & 0xFF); #endif } #endif // !LONG_FILENAME_WRITE_SUPPORT // If this VFAT entry is the last one, add a NUL terminator at the end of the string if (VFAT->sequenceNumber & 0x40) longFilename[LONG_FILENAME_CHARSIZE * TERN(LONG_FILENAME_WRITE_SUPPORT, seq * FILENAME_LENGTH, (n + FILENAME_LENGTH))] = '\0'; } } } else { if (!checksum_error && lfn_checksum(dir->name) != checksum) checksum_error = 1; // orphan detected if (checksum_error) INVALIDATE_LONGNAME(); } } // Post-process normal file or subdirectory longname, if any if (DIR_IS_FILE_OR_SUBDIR(dir)) { #if ENABLED(UTF_FILENAME_SUPPORT) // Is there a long filename to decode? if (longFilename) { n = convertUtf16ToUtf8(longFilename); } #endif return n; } // DIR_IS_FILE_OR_SUBDIR } } #if ENABLED(UTF_FILENAME_SUPPORT) uint8_t SdBaseFile::convertUtf16ToUtf8(char * const longFilename) { #if LONG_FILENAME_CHARSIZE > 2 // Add warning for developers for unsupported 3-byte cases. // (Converting 2-byte codepoints to 3-byte in-place would break the rest of filename.) #error "Currently filename re-encoding is done in-place. It may break the remaining chars to use 3-byte codepoints." #endif int16_t n; // Reset n to the start of the long name n = 0; for (uint16_t idx = 0; idx < (LONG_FILENAME_LENGTH); idx += 2) { // idx is fixed since FAT LFN always contains UTF-16LE encoding const uint16_t utf16_ch = longFilename[idx] | (longFilename[idx + 1] << 8); if (0xD800 == (utf16_ch & 0xF800)) // Surrogate pair - encode as '_' longFilename[n++] = '_'; else if (0 == (utf16_ch & 0xFF80)) // Encode as 1-byte UTF-8 char longFilename[n++] = utf16_ch & 0x007F; else if (0 == (utf16_ch & 0xF800)) { // Encode as 2-byte UTF-8 char longFilename[n++] = 0xC0 | ((utf16_ch >> 6) & 0x1F); longFilename[n++] = 0x80 | ( utf16_ch & 0x3F); } else { #if LONG_FILENAME_CHARSIZE > 2 // Encode as 3-byte UTF-8 char longFilename[n++] = 0xE0 | ((utf16_ch >> 12) & 0x0F); longFilename[n++] = 0xC0 | ((utf16_ch >> 6) & 0x3F); longFilename[n++] = 0xC0 | ( utf16_ch & 0x3F); #else // Encode as '_' longFilename[n++] = '_'; #endif } if (0 == utf16_ch) break; // End of filename } // idx return n; } #endif // UTF_FILENAME_SUPPORT // Read next directory entry into the cache // Assumes file is correctly positioned dir_t* SdBaseFile::readDirCache() { uint8_t i; // error if not directory if (!isDir()) return 0; // index of entry in cache i = (curPosition_ >> 5) & 0xF; // use read to locate and cache block if (read() < 0) return 0; // advance to next entry curPosition_ += 31; // return pointer to entry return vol_->cache()->dir + i; } /** * Remove a file. * * The directory entry and all data for the file are deleted. * * \note This function should not be used to delete the 8.3 version of a * file that has a long name. For example if a file has the long name * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". * * \return true for success, false for failure. * Reasons for failure include the file read-only, is a directory, * or an I/O error occurred. */ bool SdBaseFile::remove() { if (ENABLED(SDCARD_READONLY)) return false; // free any clusters - will fail if read-only or directory if (!truncate(0)) return false; // cache directory entry dir_t *d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); if (!d) return false; #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) // get SFN checksum before name rewrite (needed for LFN deletion) const uint8_t sfn_checksum = lfn_checksum(d->name); #endif // mark entry deleted d->name[0] = DIR_NAME_DELETED; // set this file closed type_ = FAT_FILE_TYPE_CLOSED; // write entry to SD #if DISABLED(LONG_FILENAME_WRITE_SUPPORT) return vol_->cacheFlush(); #else // LONG_FILENAME_WRITE_SUPPORT flags_ = 0; if (!vol_->cacheFlush()) return false; // Check if the entry has a LFN bool lastEntry = false; // loop back to search for any LFN entries related to this file for (uint8_t sequenceNumber = 1; sequenceNumber <= VFAT_ENTRIES_LIMIT; ++sequenceNumber) { dirIndex_ = (dirIndex_ - 1) & 0xF; if (dirBlock_ == 0) break; if (dirIndex_ == 0xF) dirBlock_--; dir_t *dir = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); if (!dir) return false; // check for valid LFN: not deleted, not top dirs (".", ".."), must be a LFN if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.' || !isDirLFN(dir)) break; // check coherent LFN: checksum and sequenceNumber must match vfat_t* dirlfn = (vfat_t*) dir; if (dirlfn->checksum != sfn_checksum || (dirlfn->sequenceNumber & 0x1F) != sequenceNumber) break; // orphan entry // is last entry of LFN ? lastEntry = (dirlfn->sequenceNumber & 0x40); // mark as deleted dirlfn->sequenceNumber = DIR_NAME_DELETED; // Flush to SD if (!vol_->cacheFlush()) return false; // exit on last entry of LFN deleted if (lastEntry) break; } // Restore current index //if (!seekSet(32UL * dirIndex_)) return false; //dirIndex_ += prevDirIndex; return true; #endif // LONG_FILENAME_WRITE_SUPPORT } /** * Remove a file. * * The directory entry and all data for the file are deleted. * * \param[in] dirFile The directory that contains the file. * \param[in] path Path for the file to be removed. * * \note This function should not be used to delete the 8.3 version of a * file that has a long name. For example if a file has the long name * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". * * \return true for success, false for failure. * Reasons for failure include the file is a directory, is read only, * \a dirFile is not a directory, \a path is not found * or an I/O error occurred. */ bool SdBaseFile::remove(SdBaseFile * const dirFile, const char * const path) { if (ENABLED(SDCARD_READONLY)) return false; SdBaseFile file; return file.open(dirFile, path, O_WRITE) ? file.remove() : false; } bool SdBaseFile::hide(const bool hidden) { if (ENABLED(SDCARD_READONLY)) return false; // must be an open file or subdirectory if (!(isFile() || isSubDir())) return false; // sync() and cache directory entry sync(); dir_t *d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); if (!d) return false; uint8_t a = d->attributes; if (hidden) a |= DIR_ATT_HIDDEN; else a &= ~DIR_ATT_HIDDEN; if (a != d->attributes) { d->attributes = a; return vol_->cacheFlush(); } return true; } /** * Rename a file or subdirectory. * * \param[in] dirFile Directory for the new path. * \param[in] newPath New path name for the file/directory. * * \return true for success, false for failure. * Reasons for failure include \a dirFile is not open or is not a directory * file, newPath is invalid or already exists, or an I/O error occurs. */ bool SdBaseFile::rename(SdBaseFile * const dirFile, const char * const newPath) { if (ENABLED(SDCARD_READONLY)) return false; uint32_t dirCluster = 0; // must be an open file or subdirectory if (!(isFile() || isSubDir())) return false; // can't move file if (vol_ != dirFile->vol_) return false; // sync() and cache directory entry sync(); dir_t *d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); if (!d) return false; // save directory entry dir_t entry; memcpy(&entry, d, sizeof(entry)); // mark entry deleted d->name[0] = DIR_NAME_DELETED; // make directory entry for new path SdBaseFile file; if (isFile()) { if (!file.open(dirFile, newPath, O_CREAT | O_EXCL | O_WRITE)) { goto restore; } } else { // don't create missing path prefix components if (!file.mkdir(dirFile, newPath, false)) { goto restore; } // save cluster containing new dot dot dirCluster = file.firstCluster_; } // change to new directory entry dirBlock_ = file.dirBlock_; dirIndex_ = file.dirIndex_; // mark closed to avoid possible destructor close call file.type_ = FAT_FILE_TYPE_CLOSED; // cache new directory entry d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); if (!d) return false; // copy all but name field to new directory entry memcpy(&d->attributes, &entry.attributes, sizeof(entry) - sizeof(d->name)); // update dot dot if directory if (dirCluster) { // get new dot dot uint32_t block = vol_->clusterStartBlock(dirCluster); if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) return false; memcpy(&entry, &vol_->cache()->dir[1], sizeof(entry)); // free unused cluster if (!vol_->freeChain(dirCluster)) return false; // store new dot dot block = vol_->clusterStartBlock(firstCluster_); if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) return false; memcpy(&vol_->cache()->dir[1], &entry, sizeof(entry)); } return vol_->cacheFlush(); restore: if ((d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE))) { // restore entry d->name[0] = entry.name[0]; vol_->cacheFlush(); } return false; } /** * Remove a directory file. * * The directory file will be removed only if it is empty and is not the * root directory. rmdir() follows DOS and Windows and ignores the * read-only attribute for the directory. * * \note This function should not be used to delete the 8.3 version of a * directory that has a long name. For example if a directory has the * long name "New folder" you should not delete the 8.3 name "NEWFOL~1". * * \return true for success, false for failure. * Reasons for failure include the file is not a directory, is the root * directory, is not empty, or an I/O error occurred. */ bool SdBaseFile::rmdir() { if (ENABLED(SDCARD_READONLY)) return false; // must be open subdirectory if (!isSubDir()) return false; rewind(); // make sure directory is empty while (curPosition_ < fileSize_) { dir_t *p = readDirCache(); if (!p) return false; // done if past last used entry if (p->name[0] == DIR_NAME_FREE) break; // skip empty slot, '.' or '..' if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; // error not empty if (DIR_IS_FILE_OR_SUBDIR(p)) return false; } // convert empty directory to normal file for remove type_ = FAT_FILE_TYPE_NORMAL; flags_ |= O_WRITE; return remove(); } /** * Recursively delete a directory and all contained files. * * This is like the Unix/Linux 'rm -rf *' if called with the root directory * hence the name. * * Warning - This will remove all contents of the directory including * subdirectories. The directory will then be removed if it is not root. * The read-only attribute for files will be ignored. * * \note This function should not be used to delete the 8.3 version of * a directory that has a long name. See remove() and rmdir(). * * \return true for success, false for failure. */ bool SdBaseFile::rmRfStar() { if (ENABLED(SDCARD_READONLY)) return false; uint32_t index; SdBaseFile f; rewind(); while (curPosition_ < fileSize_) { // remember position index = curPosition_ / 32; dir_t *p = readDirCache(); if (!p) return false; // done if past last entry if (p->name[0] == DIR_NAME_FREE) break; // skip empty slot or '.' or '..' if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; // skip if part of long file name or volume label in root if (!DIR_IS_FILE_OR_SUBDIR(p)) continue; if (!f.open(this, index, O_READ)) return false; if (f.isSubDir()) { // recursively delete if (!f.rmRfStar()) return false; } else { // ignore read-only f.flags_ |= O_WRITE; if (!f.remove()) return false; } // position to next entry if required if (curPosition_ != (32 * (index + 1))) { if (!seekSet(32 * (index + 1))) return false; } } // don't try to delete root if (!isRoot()) { if (!rmdir()) return false; } return true; } /** * Create a file object and open it in the current working directory. * * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. * * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t). */ SdBaseFile::SdBaseFile(const char * const path, const uint8_t oflag) { type_ = FAT_FILE_TYPE_CLOSED; writeError = false; open(path, oflag); } /** * Sets a file's position. * * \param[in] pos The new position in bytes from the beginning of the file. * * \return true for success, false for failure. */ bool SdBaseFile::seekSet(const uint32_t pos) { uint32_t nCur, nNew; // error if file not open or seek past end of file if (!isOpen() || pos > fileSize_) return false; if (type_ == FAT_FILE_TYPE_ROOT_FIXED) { curPosition_ = pos; return true; } if (pos == 0) { curCluster_ = curPosition_ = 0; // set position to start of file return true; } // calculate cluster index for cur and new position nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9); nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9); if (nNew < nCur || curPosition_ == 0) curCluster_ = firstCluster_; // must follow chain from first cluster else nNew -= nCur; // advance from curPosition while (nNew--) if (!vol_->fatGet(curCluster_, &curCluster_)) return false; curPosition_ = pos; return true; } void SdBaseFile::setpos(filepos_t * const pos) { curPosition_ = pos->position; curCluster_ = pos->cluster; } /** * The sync() call causes all modified data and directory fields * to be written to the storage device. * * \return true for success, false for failure. * Reasons for failure include a call to sync() before a file has been * opened or an I/O error. */ bool SdBaseFile::sync() { // only allow open files and directories if (ENABLED(SDCARD_READONLY) || !isOpen()) goto FAIL; if (flags_ & F_FILE_DIR_DIRTY) { dir_t *d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); // check for deleted by another open file object if (!d || d->name[0] == DIR_NAME_DELETED) goto FAIL; // do not set filesize for dir files if (!isDir()) d->fileSize = fileSize_; // update first cluster fields d->firstClusterLow = firstCluster_ & 0xFFFF; d->firstClusterHigh = firstCluster_ >> 16; // set modify time if user supplied a callback date/time function if (dateTime_) { dateTime_(&d->lastWriteDate, &d->lastWriteTime); d->lastAccessDate = d->lastWriteDate; } // clear directory dirty flags_ &= ~F_FILE_DIR_DIRTY; } return vol_->cacheFlush(); FAIL: writeError = true; return false; } /** * Copy a file's timestamps * * \param[in] file File to copy timestamps from. * * \note * Modify and access timestamps may be overwritten if a date time callback * function has been set by dateTimeCallback(). * * \return true for success, false for failure. */ bool SdBaseFile::timestamp(SdBaseFile * const file) { dir_t dir; // get timestamps if (!file->dirEntry(&dir)) return false; // update directory fields if (!sync()) return false; dir_t *d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); if (!d) return false; // copy timestamps d->lastAccessDate = dir.lastAccessDate; d->creationDate = dir.creationDate; d->creationTime = dir.creationTime; d->creationTimeTenths = dir.creationTimeTenths; d->lastWriteDate = dir.lastWriteDate; d->lastWriteTime = dir.lastWriteTime; // write back entry return vol_->cacheFlush(); } /** * Set a file's timestamps in its directory entry. * * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive * OR of flags from the following list * * T_ACCESS - Set the file's last access date. * * T_CREATE - Set the file's creation date and time. * * T_WRITE - Set the file's last write/modification date and time. * * \param[in] year Valid range 1980 - 2107 inclusive. * * \param[in] month Valid range 1 - 12 inclusive. * * \param[in] day Valid range 1 - 31 inclusive. * * \param[in] hour Valid range 0 - 23 inclusive. * * \param[in] minute Valid range 0 - 59 inclusive. * * \param[in] second Valid range 0 - 59 inclusive * * \note It is possible to set an invalid date since there is no check for * the number of days in a month. * * \note * Modify and access timestamps may be overwritten if a date time callback * function has been set by dateTimeCallback(). * * \return true for success, false for failure. */ bool SdBaseFile::timestamp(const uint8_t flags, const uint16_t year, const uint8_t month, const uint8_t day, const uint8_t hour, const uint8_t minute, const uint8_t second) { if (ENABLED(SDCARD_READONLY)) return false; uint16_t dirDate, dirTime; if (!isOpen() || year < 1980 || year > 2107 || month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 59) { return false; } // update directory entry if (!sync()) return false; dir_t *d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); if (!d) return false; dirDate = FAT_DATE(year, month, day); dirTime = FAT_TIME(hour, minute, second); if (flags & T_ACCESS) { d->lastAccessDate = dirDate; } if (flags & T_CREATE) { d->creationDate = dirDate; d->creationTime = dirTime; // seems to be units of 1/100 second not 1/10 as Microsoft states d->creationTimeTenths = second & 1 ? 100 : 0; } if (flags & T_WRITE) { d->lastWriteDate = dirDate; d->lastWriteTime = dirTime; } return vol_->cacheFlush(); } /** * Truncate a file to a specified length. The current file position * will be maintained if it is less than or equal to \a length otherwise * it will be set to end of file. * * \param[in] length The desired length for the file. * * \return true for success, false for failure. * Reasons for failure include file is read only, file is a directory, * \a length is greater than the current file size or an I/O error occurs. */ bool SdBaseFile::truncate(uint32_t length) { if (ENABLED(SDCARD_READONLY)) return false; uint32_t newPos; // error if not a normal file or read-only if (!isFile() || !(flags_ & O_WRITE)) return false; // error if length is greater than current size if (length > fileSize_) return false; // fileSize and length are zero - nothing to do if (fileSize_ == 0) return true; // remember position for seek after truncation newPos = curPosition_ > length ? length : curPosition_; // position to last cluster in truncated file if (!seekSet(length)) return false; if (length == 0) { // free all clusters if (!vol_->freeChain(firstCluster_)) return false; firstCluster_ = 0; } else { uint32_t toFree; if (!vol_->fatGet(curCluster_, &toFree)) return false; if (!vol_->isEOC(toFree)) { // free extra clusters if (!vol_->freeChain(toFree)) return false; // current cluster is end of chain if (!vol_->fatPutEOC(curCluster_)) return false; } } fileSize_ = length; // need to update directory entry flags_ |= F_FILE_DIR_DIRTY; if (!sync()) return false; // set file to correct position return seekSet(newPos); } /** * Write data to an open file. * * \note Data is moved to the cache but may not be written to the * storage device until sync() is called. * * \param[in] buf Pointer to the location of the data to be written. * * \param[in] nbyte Number of bytes to write. * * \return For success write() returns the number of bytes written, always * \a nbyte. If an error occurs, write() returns -1. Possible errors * include write() is called before a file has been opened, write is called * for a read-only file, device is full, a corrupt file system or an I/O error. */ int16_t SdBaseFile::write(const void *buf, const uint16_t nbyte) { #if ENABLED(SDCARD_READONLY) writeError = true; return -1; #endif // convert void* to uint8_t* - must be before goto statements const uint8_t *src = reinterpret_cast<const uint8_t*>(buf); // number of bytes left to write - must be before goto statements uint16_t nToWrite = nbyte; // error if not a normal file or is read-only if (!isFile() || !(flags_ & O_WRITE)) goto FAIL; // seek to end of file if append flag if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { if (!seekEnd()) goto FAIL; } while (nToWrite > 0) { uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); uint16_t blockOffset = curPosition_ & 0x1FF; if (blockOfCluster == 0 && blockOffset == 0) { // start of new cluster if (curCluster_ == 0) { if (firstCluster_ == 0) { // allocate first cluster of file if (!addCluster()) goto FAIL; } else { curCluster_ = firstCluster_; } } else { uint32_t next; if (!vol_->fatGet(curCluster_, &next)) goto FAIL; if (vol_->isEOC(next)) { // add cluster if at end of chain if (!addCluster()) goto FAIL; } else { curCluster_ = next; } } } // max space in block uint16_t n = 512 - blockOffset; // lesser of space and amount to write NOMORE(n, nToWrite); // block for data write uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; if (n == 512) { // full block - don't need to use cache if (vol_->cacheBlockNumber() == block) { // invalidate cache if block is in cache vol_->cacheSetBlockNumber(0xFFFFFFFF, false); } if (!vol_->writeBlock(block, src)) goto FAIL; } else { if (blockOffset == 0 && curPosition_ >= fileSize_) { // start of new block don't need to read into cache if (!vol_->cacheFlush()) goto FAIL; // set cache dirty and SD address of block vol_->cacheSetBlockNumber(block, true); } else { // rewrite part of block if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) goto FAIL; } uint8_t *dst = vol_->cache()->data + blockOffset; memcpy(dst, src, n); } curPosition_ += n; src += n; nToWrite -= n; } if (curPosition_ > fileSize_) { // update fileSize and insure sync will update dir entry fileSize_ = curPosition_; flags_ |= F_FILE_DIR_DIRTY; } else if (dateTime_ && nbyte) { // insure sync will update modified date and time flags_ |= F_FILE_DIR_DIRTY; } if (flags_ & O_SYNC) { if (!sync()) goto FAIL; } return nbyte; FAIL: // return for write error writeError = true; return -1; } #endif // HAS_MEDIA
2301_81045437/Marlin
Marlin/src/sd/SdBaseFile.cpp
C++
agpl-3.0
71,731
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * sd/SdBaseFile.h * * Arduino SdFat Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include "SdFatConfig.h" #include "SdVolume.h" #include <stdint.h> /** * \struct filepos_t * \brief internal type for istream * do not use in user apps */ struct filepos_t { uint32_t position; // stream byte position uint32_t cluster; // cluster of position filepos_t() : position(0), cluster(0) {} }; // use the gnu style oflag in open() uint8_t const O_READ = 0x01, // open() oflag for reading O_RDONLY = O_READ, // open() oflag - same as O_IN O_WRITE = 0x02, // open() oflag for write O_WRONLY = O_WRITE, // open() oflag - same as O_WRITE O_RDWR = (O_READ | O_WRITE), // open() oflag for reading and writing O_ACCMODE = (O_READ | O_WRITE), // open() oflag mask for access modes O_APPEND = 0x04, // The file offset shall be set to the end of the file prior to each write. O_SYNC = 0x08, // Synchronous writes - call sync() after each write O_TRUNC = 0x10, // Truncate the file to zero length O_AT_END = 0x20, // Set the initial position at the end of the file O_CREAT = 0x40, // Create the file if nonexistent O_EXCL = 0x80; // If O_CREAT and O_EXCL are set, open() shall fail if the file exists // SdBaseFile class static and const definitions // flags for ls() uint8_t const LS_DATE = 1, // ls() flag to print modify date LS_SIZE = 2, // ls() flag to print file size LS_R = 4; // ls() flag for recursive list of subdirectories // flags for timestamp uint8_t const T_ACCESS = 1, // Set the file's last access date T_CREATE = 2, // Set the file's creation date and time T_WRITE = 4; // Set the file's write date and time // values for type_ uint8_t const FAT_FILE_TYPE_CLOSED = 0, // This file has not been opened. FAT_FILE_TYPE_NORMAL = 1, // A normal file FAT_FILE_TYPE_ROOT_FIXED = 2, // A FAT12 or FAT16 root directory FAT_FILE_TYPE_ROOT32 = 3, // A FAT32 root directory FAT_FILE_TYPE_SUBDIR = 4, // A subdirectory file FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT_FIXED; // Test value for directory type /** * date field for FAT directory entry * \param[in] year [1980,2107] * \param[in] month [1,12] * \param[in] day [1,31] * * \return Packed date for dir_t entry. */ static inline uint16_t FAT_DATE(const uint16_t year, const uint8_t month, const uint8_t day) { return (year - 1980) << 9 | month << 5 | day; } /** * year part of FAT directory date field * \param[in] fatDate Date in packed dir format. * * \return Extracted year [1980,2107] */ static inline uint16_t FAT_YEAR(const uint16_t fatDate) { return 1980 + (fatDate >> 9); } /** * month part of FAT directory date field * \param[in] fatDate Date in packed dir format. * * \return Extracted month [1,12] */ static inline uint8_t FAT_MONTH(const uint16_t fatDate) { return (fatDate >> 5) & 0xF; } /** * day part of FAT directory date field * \param[in] fatDate Date in packed dir format. * * \return Extracted day [1,31] */ static inline uint8_t FAT_DAY(const uint16_t fatDate) { return fatDate & 0x1F; } /** * time field for FAT directory entry * \param[in] hour [0,23] * \param[in] minute [0,59] * \param[in] second [0,59] * * \return Packed time for dir_t entry. */ static inline uint16_t FAT_TIME(const uint8_t hour, const uint8_t minute, const uint8_t second) { return hour << 11 | minute << 5 | second >> 1; } /** * hour part of FAT directory time field * \param[in] fatTime Time in packed dir format. * * \return Extracted hour [0,23] */ static inline uint8_t FAT_HOUR(const uint16_t fatTime) { return fatTime >> 11; } /** * minute part of FAT directory time field * \param[in] fatTime Time in packed dir format. * * \return Extracted minute [0,59] */ static inline uint8_t FAT_MINUTE(const uint16_t fatTime) { return (fatTime >> 5) & 0x3F; } /** * second part of FAT directory time field * Note second/2 is stored in packed time. * * \param[in] fatTime Time in packed dir format. * * \return Extracted second [0,58] */ static inline uint8_t FAT_SECOND(const uint16_t fatTime) { return 2 * (fatTime & 0x1F); } // Default date for file timestamps is 1 Jan 2000 uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; // Default time for file timestamp is 1 am uint16_t const FAT_DEFAULT_TIME = (1 << 11); /** * \class SdBaseFile * \brief Base class for SdFile with Print and C++ streams. */ class SdBaseFile { public: SdBaseFile() : writeError(false), type_(FAT_FILE_TYPE_CLOSED) {} SdBaseFile(const char * const path, const uint8_t oflag); ~SdBaseFile() { if (isOpen()) close(); } /** * writeError is set to true if an error occurs during a write(). * Set writeError to false before calling print() and/or write() and check * for true after calls to print() and/or write(). */ bool writeError; // helpers for stream classes /** * get position for streams * \param[out] pos struct to receive position */ void getpos(filepos_t * const pos); /** * set position for streams * \param[out] pos struct with value for new position */ void setpos(filepos_t * const pos); bool close(); bool contiguousRange(uint32_t * const bgnBlock, uint32_t * const endBlock); bool createContiguous(SdBaseFile * const dirFile, const char * const path, const uint32_t size); /** * \return The current cluster number for a file or directory. */ uint32_t curCluster() const { return curCluster_; } /** * \return The current position for a file or directory. */ uint32_t curPosition() const { return curPosition_; } /** * \return Current working directory */ static SdBaseFile *cwd() { return cwd_; } /** * Set the date/time callback function * * \param[in] dateTime The user's call back function. The callback * function is of the form: * * \code * void dateTime(uint16_t *date, uint16_t *time) { * uint16_t year; * uint8_t month, day, hour, minute, second; * * // User gets date and time from GPS or real-time clock here * * // return date using FAT_DATE macro to format fields * *date = FAT_DATE(year, month, day); * * // return time using FAT_TIME macro to format fields * *time = FAT_TIME(hour, minute, second); * } * \endcode * * Sets the function that is called when a file is created or when * a file's directory entry is modified by sync(). All timestamps, * access, creation, and modify, are set when a file is created. * sync() maintains the last access date and last modify date/time. * * See the timestamp() function. */ static void dateTimeCallback( void (*dateTime)(uint16_t * const date, uint16_t * const time)) { dateTime_ = dateTime; } /** * Cancel the date/time callback function. */ static void dateTimeCallbackCancel() { dateTime_ = 0; } bool dirEntry(dir_t *dir); static void dirName(const dir_t& dir, char *name); bool exists(const char *name); int16_t fgets(char *str, int16_t num, char *delim=0); /** * \return The total number of bytes in a file or directory. */ uint32_t fileSize() const { return fileSize_; } /** * \return The first cluster number for a file or directory. */ uint32_t firstCluster() const { return firstCluster_; } /** * \return True if this is a directory else false. */ bool isDir() const { return type_ >= FAT_FILE_TYPE_MIN_DIR; } /** * \return True if this is a normal file else false. */ bool isFile() const { return type_ == FAT_FILE_TYPE_NORMAL; } /** * \return True if this is an open file/directory else false. */ bool isOpen() const { return type_ != FAT_FILE_TYPE_CLOSED; } /** * \return True if this is a subdirectory else false. */ bool isSubDir() const { return type_ == FAT_FILE_TYPE_SUBDIR; } /** * \return True if this is the root directory. */ bool isRoot() const { return type_ == FAT_FILE_TYPE_ROOT_FIXED || type_ == FAT_FILE_TYPE_ROOT32; } bool getDosName(char * const name); void ls(const uint8_t flags=0, const uint8_t indent=0); bool mkdir(SdBaseFile *parent, const char *path, const bool pFlag=true); bool open(SdBaseFile * const dirFile, uint16_t index, const uint8_t oflag); bool open(SdBaseFile * const dirFile, const char *path, const uint8_t oflag); bool open(const char * const path, const uint8_t oflag=O_READ); bool openNext(SdBaseFile * const dirFile, const uint8_t oflag); bool openRoot(SdVolume * const vol); int peek(); static void printFatDate(const uint16_t fatDate); static void printFatTime(const uint16_t fatTime); bool printName(); int16_t read(); int16_t read(void * const buf, uint16_t nbyte); int8_t readDir(dir_t * const dir, char * const longFilename); static bool remove(SdBaseFile * const dirFile, const char * const path); bool remove(); /** * Set the file's current position to zero. */ void rewind() { seekSet(0); } bool rename(SdBaseFile * const dirFile, const char * const newPath); bool rmdir(); bool rmRfStar(); /** * Set or clear DIR_ATT_HIDDEN attribute for directory entry */ bool hide(const bool hidden); /** * Set the files position to current position + \a pos. See seekSet(). * \param[in] offset The new position in bytes from the current position. * \return true for success or false for failure. */ bool seekCur(const int32_t offset) { return seekSet(curPosition_ + offset); } /** * Set the files position to end-of-file + \a offset. See seekSet(). * \param[in] offset The new position in bytes from end-of-file. * \return true for success or false for failure. */ bool seekEnd(const int32_t offset=0) { return seekSet(fileSize_ + offset); } bool seekSet(const uint32_t pos); bool sync(); bool timestamp(SdBaseFile * const file); bool timestamp(const uint8_t flag, const uint16_t year, const uint8_t month, const uint8_t day, const uint8_t hour, const uint8_t minute, const uint8_t second); /** * Type of file. Use isFile() or isDir() instead of type() if possible. * * \return The file or directory type. */ uint8_t type() const { return type_; } bool truncate(uint32_t size); /** * \return SdVolume that contains this file. */ SdVolume* volume() const { return vol_; } int16_t write(const void *buf, const uint16_t nbyte); private: friend class SdFat; // allow SdFat to set cwd_ static SdBaseFile *cwd_; // global pointer to cwd dir // data time callback function static void (*dateTime_)(uint16_t *date, uint16_t *time); // bits defined in flags_ static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC), // should be 0x0F F_FILE_DIR_DIRTY = 0x80; // sync of directory entry required // private data uint8_t flags_; // See above for definition of flags_ bits uint8_t fstate_; // error and eof indicator uint8_t type_; // type of file see above for values uint32_t curCluster_; // cluster for current file position uint32_t curPosition_; // current file position in bytes from beginning uint32_t dirBlock_; // block for this files directory entry uint8_t dirIndex_; // index of directory entry in dirBlock uint32_t fileSize_; // file size in bytes uint32_t firstCluster_; // first cluster of file SdVolume *vol_; // volume where file is located /** * EXPERIMENTAL - Don't use! */ //bool openParent(SdBaseFile *dir); // private functions bool addCluster(); bool addDirCluster(); dir_t* cacheDirEntry(const uint8_t action); int8_t lsPrintNext(const uint8_t flags, const uint8_t indent); static bool make83Name(const char *str, uint8_t * const name, const char **ptr); bool mkdir(SdBaseFile * const parent, const uint8_t dname[11] OPTARG(LONG_FILENAME_WRITE_SUPPORT, const uint8_t dlname[LONG_FILENAME_LENGTH]) ); bool open(SdBaseFile *dirFile, const uint8_t dname[11] OPTARG(LONG_FILENAME_WRITE_SUPPORT, const uint8_t dlname[LONG_FILENAME_LENGTH]) , const uint8_t oflag ); bool openCachedEntry(const uint8_t dirIndex, const uint8_t oflags); dir_t* readDirCache(); #if ENABLED(UTF_FILENAME_SUPPORT) uint8_t convertUtf16ToUtf8(char * const longFilename); #endif // Long Filename create/write support #if ENABLED(LONG_FILENAME_WRITE_SUPPORT) static bool isDirLFN(const dir_t* dir); static bool isDirNameLFN(const char * const dirname); static bool parsePath(const char *str, uint8_t * const name, uint8_t * const lname, const char **ptr); // Return the number of entries needed in the FAT for this LFN static uint8_t getLFNEntriesNum(const char * const lname) { return (strlen(lname) + 12) / 13; } static void getLFNName(vfat_t *vFatDir, char *lname, const uint8_t sequenceNumber); static void setLFNName(vfat_t *vFatDir, char *lname, const uint8_t sequenceNumber); #endif };
2301_81045437/Marlin
Marlin/src/sd/SdBaseFile.h
C++
agpl-3.0
14,479
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * sd/SdFatConfig.h * * Arduino SdFat Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include "../inc/MarlinConfig.h" /** * To use multiple SD cards set USE_MULTIPLE_CARDS nonzero. * * Using multiple cards costs 400 - 500 bytes of flash. * * Each card requires about 550 bytes of SRAM so use of a Mega is recommended. */ #define USE_MULTIPLE_CARDS 0 //TODO? ENABLED(MULTI_VOLUME) /** * Call flush for endl if ENDL_CALLS_FLUSH is nonzero * * The standard for iostreams is to call flush. This is very costly for * SdFat. Each call to flush causes 2048 bytes of I/O to the SD. * * SdFat has a single 512 byte buffer for SD I/O so it must write the current * data block to the SD, read the directory block from the SD, update the * directory entry, write the directory block to the SD and read the data * block back into the buffer. * * The SD flash memory controller is not designed for this many rewrites * so performance may be reduced by more than a factor of 100. * * If ENDL_CALLS_FLUSH is zero, you must call flush and/or close to force * all data to be written to the SD. */ #define ENDL_CALLS_FLUSH 0 /** * Allow FAT12 volumes if FAT12_SUPPORT is nonzero. * FAT12 has not been well tested. */ #define FAT12_SUPPORT 0 /** * SPI init rate for SD initialization commands. Must be 5 (F_CPU/64) * or 6 (F_CPU/128). */ #define SPI_SD_INIT_RATE 5 /** * Set the SS pin high for hardware SPI. If SS is chip select for another SPI * device this will disable that device during the SD init phase. */ #define SET_SPI_SS_HIGH 1 /** * Define MEGA_SOFT_SPI nonzero to use software SPI on Mega Arduinos. * Pins used are SS 10, MOSI 11, MISO 12, and SCK 13. * * MEGA_SOFT_SPI allows an unmodified Adafruit GPS Shield to be used * on Mega Arduinos. Software SPI works well with GPS Shield V1.1 * but many SD cards will fail with GPS Shield V1.0. */ #define MEGA_SOFT_SPI 0 // Set USE_SOFTWARE_SPI nonzero to ALWAYS use Software SPI. #define USE_SOFTWARE_SPI 0 /** * The __cxa_pure_virtual function is an error handler that is invoked when * a pure virtual function is called. */ #define USE_CXA_PURE_VIRTUAL 1 /** * Defines for 8.3 and long (vfat) filenames */ #define FILENAME_LENGTH 13 // Number of UTF-16 characters per entry // UTF-8 may use up to 3 bytes to represent single UTF-16 code point. // We discard 3-byte characters allowing only 2-bytes // or 1-byte if UTF_FILENAME_SUPPORT disabled. #define LONG_FILENAME_CHARSIZE TERN(UTF_FILENAME_SUPPORT, 2, 1) // Total bytes needed to store a single long filename #define LONG_FILENAME_LENGTH (FILENAME_LENGTH * LONG_FILENAME_CHARSIZE * VFAT_ENTRIES_LIMIT + 1)
2301_81045437/Marlin
Marlin/src/sd/SdFatConfig.h
C
agpl-3.0
3,606
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * sd/SdFatStructs.h * * Arduino SdFat Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include <stdint.h> #define PACKED __attribute__((__packed__)) /** * mostly from Microsoft document fatgen103.doc * https://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx */ uint8_t const BOOTSIG0 = 0x55, // Value for byte 510 of boot block or MBR BOOTSIG1 = 0xAA, // Value for byte 511 of boot block or MBR EXTENDED_BOOT_SIG = 0x29; // Value for bootSignature field int FAT/FAT32 boot sector /** * \struct partitionTable * \brief MBR partition table entry * * A partition table entry for a MBR formatted storage device. * The MBR partition table has four entries. */ struct partitionTable { /** * Boot Indicator . Indicates whether the volume is the active * partition. Legal values include: 0x00. Do not use for booting. * 0x80 Active partition. */ uint8_t boot; /** * Head part of Cylinder-head-sector address of the first block in * the partition. Legal values are 0-255. Only used in old PC BIOS. */ uint8_t beginHead; /** * Sector part of Cylinder-head-sector address of the first block in * the partition. Legal values are 1-63. Only used in old PC BIOS. */ uint8_t beginSector : 6; /** High bits cylinder for first block in partition. */ uint8_t beginCylinderHigh : 2; /** * Combine beginCylinderLow with beginCylinderHigh. Legal values * are 0-1023. Only used in old PC BIOS. */ uint8_t beginCylinderLow; /** * Partition type. See defines that begin with PART_TYPE_ for * some Microsoft partition types. */ uint8_t type; /** * head part of cylinder-head-sector address of the last sector in the * partition. Legal values are 0-255. Only used in old PC BIOS. */ uint8_t endHead; /** * Sector part of cylinder-head-sector address of the last sector in * the partition. Legal values are 1-63. Only used in old PC BIOS. */ uint8_t endSector : 6; /** High bits of end cylinder */ uint8_t endCylinderHigh : 2; /** * Combine endCylinderLow with endCylinderHigh. Legal values * are 0-1023. Only used in old PC BIOS. */ uint8_t endCylinderLow; uint32_t firstSector; // Logical block address of the first block in the partition. uint32_t totalSectors; // Length of the partition, in blocks. } PACKED; typedef struct partitionTable part_t; // Type name for partitionTable /** * \struct masterBootRecord * * \brief Master Boot Record * * The first block of a storage device that is formatted with a MBR. */ struct masterBootRecord { uint8_t codeArea[440]; // Code Area for master boot program. uint32_t diskSignature; // Optional Windows NT disk signature. May contain boot code. uint16_t usuallyZero; // Usually zero but may be more boot code. part_t part[4]; // Partition tables. uint8_t mbrSig0; // First MBR signature byte. Must be 0x55 uint8_t mbrSig1; // Second MBR signature byte. Must be 0xAA } PACKED; /** Type name for masterBootRecord */ typedef struct masterBootRecord mbr_t; /** * \struct fat_boot * * \brief Boot sector for a FAT12/FAT16 volume. */ struct fat_boot { /** * The first three bytes of the boot sector must be valid, * executable x 86-based CPU instructions. This includes a * jump instruction that skips the next nonexecutable bytes. */ uint8_t jump[3]; /** * This is typically a string of characters that identifies * the operating system that formatted the volume. */ char oemId[8]; /** * The size of a hardware sector. Valid decimal values for this * field are 512, 1024, 2048, and 4096. For most disks used in * the United States, the value of this field is 512. */ uint16_t bytesPerSector; /** * Number of sectors per allocation unit. This value must be a * power of 2 that is greater than 0. The legal values are * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. */ uint8_t sectorsPerCluster; /** * The number of sectors preceding the start of the first FAT, * including the boot sector. The value of this field is always 1. */ uint16_t reservedSectorCount; /** * The number of copies of the FAT on the volume. * The value of this field is always 2. */ uint8_t fatCount; /** * For FAT12 and FAT16 volumes, this field contains the count of * 32-byte directory entries in the root directory. For FAT32 volumes, * this field must be set to 0. For FAT12 and FAT16 volumes, this * value should always specify a count that when multiplied by 32 * results in a multiple of bytesPerSector. FAT16 volumes should * use the value 512. */ uint16_t rootDirEntryCount; /** * This field is the old 16-bit total count of sectors on the volume. * This count includes the count of all sectors in all four regions * of the volume. This field can be 0; if it is 0, then totalSectors32 * must be nonzero. For FAT32 volumes, this field must be 0. For * FAT12 and FAT16 volumes, this field contains the sector count, and * totalSectors32 is 0 if the total sector count fits * (is less than 0x10000). */ uint16_t totalSectors16; /** * This dates back to the old MS-DOS 1.x media determination and is * no longer usually used for anything. 0xF8 is the standard value * for fixed (nonremovable) media. For removable media, 0xF0 is * frequently used. Legal values are 0xF0 or 0xF8-0xFF. */ uint8_t mediaType; /** * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. * On FAT32 volumes this field must be 0, and sectorsPerFat32 * contains the FAT size count. */ uint16_t sectorsPerFat16; uint16_t sectorsPerTrack; // Sectors per track for interrupt 0x13. Not used otherwise. uint16_t headCount; // Number of heads for interrupt 0x13. Not used otherwise. /** * Count of hidden sectors preceding the partition that contains this * FAT volume. This field is generally only relevant for media * visible on interrupt 0x13. */ uint32_t hidddenSectors; /** * This field is the new 32-bit total count of sectors on the volume. * This count includes the count of all sectors in all four regions * of the volume. This field can be 0; if it is 0, then * totalSectors16 must be nonzero. */ uint32_t totalSectors32; /** * Related to the BIOS physical drive number. Floppy drives are * identified as 0x00 and physical hard disks are identified as * 0x80, regardless of the number of physical disk drives. * Typically, this value is set prior to issuing an INT 13h BIOS * call to specify the device to access. The value is only * relevant if the device is a boot device. */ uint8_t driveNumber; uint8_t reserved1; // used by Windows NT - should be zero for FAT uint8_t bootSignature; // 0x29 if next three fields are valid /** * A random serial number created when formatting a disk, * which helps to distinguish between disks. * Usually generated by combining date and time. */ uint32_t volumeSerialNumber; /** * A field once used to store the volume label. The volume label * is now stored as a special file in the root directory. */ char volumeLabel[11]; /** * A field with a value of either FAT, FAT12 or FAT16, * depending on the disk format. */ char fileSystemType[8]; uint8_t bootCode[448]; // X86 boot code uint8_t bootSectorSig0; // must be 0x55 uint8_t bootSectorSig1; // must be 0xAA } PACKED; typedef struct fat_boot fat_boot_t; // Type name for FAT Boot Sector /** * \struct fat32_boot * * \brief Boot sector for a FAT32 volume. */ struct fat32_boot { /** * The first three bytes of the boot sector must be valid, * executable x 86-based CPU instructions. This includes a * jump instruction that skips the next nonexecutable bytes. */ uint8_t jump[3]; /** * This is typically a string of characters that identifies * the operating system that formatted the volume. */ char oemId[8]; /** * The size of a hardware sector. Valid decimal values for this * field are 512, 1024, 2048, and 4096. For most disks used in * the United States, the value of this field is 512. */ uint16_t bytesPerSector; /** * Number of sectors per allocation unit. This value must be a * power of 2 that is greater than 0. The legal values are * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. */ uint8_t sectorsPerCluster; /** * The number of sectors preceding the start of the first FAT, * including the boot sector. Must not be zero */ uint16_t reservedSectorCount; /** * The number of copies of the FAT on the volume. * The value of this field is always 2. */ uint8_t fatCount; /** * FAT12/FAT16 only. For FAT32 volumes, this field must be set to 0. */ uint16_t rootDirEntryCount; /** * For FAT32 volumes, this field must be 0. */ uint16_t totalSectors16; /** * This dates back to the old MS-DOS 1.x media determination and is * no longer usually used for anything. 0xF8 is the standard value * for fixed (nonremovable) media. For removable media, 0xF0 is * frequently used. Legal values are 0xF0 or 0xF8-0xFF. */ uint8_t mediaType; /** * On FAT32 volumes this field must be 0, and sectorsPerFat32 * contains the FAT size count. */ uint16_t sectorsPerFat16; uint16_t sectorsPerTrack; // Sectors per track for interrupt 0x13. Not used otherwise. uint16_t headCount; // Number of heads for interrupt 0x13. Not used otherwise. /** * Count of hidden sectors preceding the partition that contains this * FAT volume. This field is generally only relevant for media * visible on interrupt 0x13. */ uint32_t hidddenSectors; /** * Contains the total number of sectors in the FAT32 volume. */ uint32_t totalSectors32; /** * Count of sectors occupied by one FAT on FAT32 volumes. */ uint32_t sectorsPerFat32; /** * This field is only defined for FAT32 media and does not exist on * FAT12 and FAT16 media. * Bits 0-3 -- Zero-based number of active FAT. * Only valid if mirroring is disabled. * Bits 4-6 -- Reserved. * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. * -- 1 means only one FAT is active; it is the one referenced * in bits 0-3. * Bits 8-15 -- Reserved. */ uint16_t fat32Flags; /** * FAT32 version. High byte is major revision number. * Low byte is minor revision number. Only 0.0 define. */ uint16_t fat32Version; /** * Cluster number of the first cluster of the root directory for FAT32. * This usually 2 but not required to be 2. */ uint32_t fat32RootCluster; /** * Sector number of FSINFO structure in the reserved area of the * FAT32 volume. Usually 1. */ uint16_t fat32FSInfo; /** * If nonzero, indicates the sector number in the reserved area * of the volume of a copy of the boot record. Usually 6. * No value other than 6 is recommended. */ uint16_t fat32BackBootBlock; /** * Reserved for future expansion. Code that formats FAT32 volumes * should always set all of the bytes of this field to 0. */ uint8_t fat32Reserved[12]; /** * Related to the BIOS physical drive number. Floppy drives are * identified as 0x00 and physical hard disks are identified as * 0x80, regardless of the number of physical disk drives. * Typically, this value is set prior to issuing an INT 13h BIOS * call to specify the device to access. The value is only * relevant if the device is a boot device. */ uint8_t driveNumber; uint8_t reserved1; // Used by Windows NT - should be zero for FAT uint8_t bootSignature; // 0x29 if next three fields are valid /** * A random serial number created when formatting a disk, * which helps to distinguish between disks. * Usually generated by combining date and time. */ uint32_t volumeSerialNumber; /** * A field once used to store the volume label. The volume label * is now stored as a special file in the root directory. */ char volumeLabel[11]; /** * A text field with a value of FAT32. */ char fileSystemType[8]; uint8_t bootCode[420]; // X86 boot code uint8_t bootSectorSig0; // must be 0x55 uint8_t bootSectorSig1; // must be 0xAA } PACKED; typedef struct fat32_boot fat32_boot_t; // Type name for FAT32 Boot Sector uint32_t const FSINFO_LEAD_SIG = 0x41615252, // 'AaRR' Lead signature for a FSINFO sector FSINFO_STRUCT_SIG = 0x61417272; // 'aArr' Struct signature for a FSINFO sector /** * \struct fat32_fsinfo * * \brief FSINFO sector for a FAT32 volume. */ struct fat32_fsinfo { uint32_t leadSignature; // must be 0x52, 0x52, 0x61, 0x41 'RRaA' uint8_t reserved1[480]; // must be zero uint32_t structSignature; // must be 0x72, 0x72, 0x41, 0x61 'rrAa' /** * Contains the last known free cluster count on the volume. * If the value is 0xFFFFFFFF, then the free count is unknown * and must be computed. Any other value can be used, but is * not necessarily correct. It should be range checked at least * to make sure it is <= volume cluster count. */ uint32_t freeCount; /** * This is a hint for the FAT driver. It indicates the cluster * number at which the driver should start looking for free clusters. * If the value is 0xFFFFFFFF, then there is no hint and the driver * should start looking at cluster 2. */ uint32_t nextFree; uint8_t reserved2[12]; // must be zero uint8_t tailSignature[4]; // must be 0x00, 0x00, 0x55, 0xAA } PACKED; typedef struct fat32_fsinfo fat32_fsinfo_t; // Type name for FAT32 FSINFO Sector // End Of Chain values for FAT entries uint16_t const FAT12EOC = 0xFFF, // FAT12 end of chain value used by Microsoft. FAT12EOC_MIN = 0xFF8, // Minimum value for FAT12 EOC. Use to test for EOC. FAT16EOC = 0xFFFF, // FAT16 end of chain value used by Microsoft. FAT16EOC_MIN = 0xFFF8; // Minimum value for FAT16 EOC. Use to test for EOC. uint32_t const FAT32EOC = 0x0FFFFFFF, // FAT32 end of chain value used by Microsoft. FAT32EOC_MIN = 0x0FFFFFF8, // Minimum value for FAT32 EOC. Use to test for EOC. FAT32MASK = 0x0FFFFFFF; // Mask a for FAT32 entry. Entries are 28 bits. /** * \struct directoryEntry * \brief FAT short directory entry * * Short means short 8.3 name, not the entry size. * * Date Format. A FAT directory entry date stamp is a 16-bit field that is * basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the * format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the * 16-bit word): * * Bits 9-15: Count of years from 1980, valid value range 0-127 * inclusive (1980-2107). * * Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. * * Bits 0-4: Day of month, valid value range 1-31 inclusive. * * Time Format. A FAT directory entry time stamp is a 16-bit field that has * a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the * 16-bit word, bit 15 is the MSB of the 16-bit word). * * Bits 11-15: Hours, valid value range 0-23 inclusive. * * Bits 5-10: Minutes, valid value range 0-59 inclusive. * * Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). * * The valid time range is from Midnight 00:00:00 to 23:59:58. */ struct directoryEntry { /** * Short 8.3 name. * * The first eight bytes contain the file name with blank fill. * The last three bytes contain the file extension with blank fill. */ uint8_t name[11]; /** * Entry attributes. * * The upper two bits of the attribute byte are reserved and should * always be set to 0 when a file is created and never modified or * looked at after that. See defines that begin with DIR_ATT_. */ uint8_t attributes; /** * Reserved for use by Windows NT. Set value to 0 when a file is * created and never modify or look at it after that. */ uint8_t reservedNT; /** * The granularity of the seconds part of creationTime is 2 seconds * so this field is a count of tenths of a second and it's valid * value range is 0-199 inclusive. (WHG note - seems to be hundredths) */ uint8_t creationTimeTenths; uint16_t creationTime; // Time file was created. uint16_t creationDate; // Date file was created. /** * Last access date. Note that there is no last access time, only * a date. This is the date of last read or write. In the case of * a write, this should be set to the same date as lastWriteDate. */ uint16_t lastAccessDate; /** * High word of this entry's first cluster number (always 0 for a * FAT12 or FAT16 volume). */ uint16_t firstClusterHigh; uint16_t lastWriteTime; // Time of last write. File creation is considered a write. uint16_t lastWriteDate; // Date of last write. File creation is considered a write. uint16_t firstClusterLow; // Low word of this entry's first cluster number. uint32_t fileSize; // 32-bit unsigned holding this file's size in bytes. } PACKED; /** * \struct directoryVFATEntry * \brief VFAT long filename directory entry * * directoryVFATEntries are found in the same list as normal directoryEntry. * But have the attribute field set to DIR_ATT_LONG_NAME. * * Long filenames are saved in multiple directoryVFATEntries. * Each entry containing 13 UTF-16 characters. */ struct directoryVFATEntry { /** * Sequence number. Consists of 2 parts: * bit 6: indicates first long filename block for the next file * bit 0-4: the position of this long filename block (first block is 1) */ uint8_t sequenceNumber; uint16_t name1[5]; // First set of UTF-16 characters uint8_t attributes; // attributes (at the same location as in directoryEntry), always 0x0F uint8_t reservedNT; // Reserved for use by Windows NT. Always 0. uint8_t checksum; // Checksum of the short 8.3 filename, can be used to checked if the file system as modified by a not-long-filename aware implementation. uint16_t name2[6]; // Second set of UTF-16 characters uint16_t firstClusterLow; // firstClusterLow is always zero for longFilenames uint16_t name3[2]; // Third set of UTF-16 characters } PACKED; // Definitions for directory entries // typedef struct directoryEntry dir_t; // Type name for directoryEntry typedef struct directoryVFATEntry vfat_t; // Type name for directoryVFATEntry uint8_t const DIR_NAME_0xE5 = 0x05, // escape for name[0] = 0xE5 DIR_NAME_DELETED = 0xE5, // name[0] value for entry that is free after being "deleted" DIR_NAME_FREE = 0x00, // name[0] value for entry that is free and no allocated entries follow DIR_ATT_READ_ONLY = 0x01, // file is read-only DIR_ATT_HIDDEN = 0x02, // File should hidden in directory listings DIR_ATT_SYSTEM = 0x04, // Entry is for a system file DIR_ATT_VOLUME_ID = 0x08, // Directory entry contains the volume label DIR_ATT_DIRECTORY = 0x10, // Entry is for a directory DIR_ATT_ARCHIVE = 0x20, // Old DOS archive bit for backup support DIR_ATT_LONG_NAME = 0x0F, // Test value for long name entry. Test is (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. DIR_ATT_LONG_NAME_MASK = 0x3F, // Test mask for long name entry DIR_ATT_DEFINED_BITS = 0x3F; // defined attribute bits /** * Directory entry is part of a long name * \param[in] dir Pointer to a directory entry. * * \return true if the entry is for part of a long name else false. */ static inline uint8_t DIR_IS_LONG_NAME(const dir_t *dir) { return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; } /** Mask for file/subdirectory tests */ uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); /** * Directory entry is for a file * \param[in] dir Pointer to a directory entry. * * \return true if the entry is for a normal file else false. */ static inline uint8_t DIR_IS_FILE(const dir_t *dir) { return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; } /** * Directory entry is for a subdirectory * \param[in] dir Pointer to a directory entry. * * \return true if the entry is for a subdirectory else false. */ static inline uint8_t DIR_IS_SUBDIR(const dir_t *dir) { return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; } /** * Directory entry is for a file or subdirectory * \param[in] dir Pointer to a directory entry. * * \return true if the entry is for a normal file or subdirectory else false. */ static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t *dir) { return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; }
2301_81045437/Marlin
Marlin/src/sd/SdFatStructs.h
C
agpl-3.0
22,240
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ /** * sd/SdFatUtil.cpp * * Arduino SdFat Library * Copyright (c) 2008 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include "../inc/MarlinConfig.h" #if HAS_MEDIA #include "SdFatUtil.h" #include <string.h> /** * Amount of free RAM * \return The number of free bytes. */ #ifdef __arm__ extern "C" char* sbrk(int incr); int SdFatUtil::FreeRam() { char top; return &top - reinterpret_cast<char*>(sbrk(0)); } #elif defined(__AVR__) extern char* __brkval; extern char __bss_end; int SdFatUtil::FreeRam() { char top; return __brkval ? &top - __brkval : &top - &__bss_end; } #endif #endif // HAS_MEDIA
2301_81045437/Marlin
Marlin/src/sd/SdFatUtil.cpp
C++
agpl-3.0
1,536
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * sd/SdFatUtil.h * * Arduino SdFat Library * Copyright (c) 2008 by William Greiman * * This file is part of the Arduino Sd2Card Library */ /** * \file * \brief Useful utility functions. */ namespace SdFatUtil { int FreeRam(); } using namespace SdFatUtil; // NOLINT
2301_81045437/Marlin
Marlin/src/sd/SdFatUtil.h
C++
agpl-3.0
1,161
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ /** * sd/SdFile.cpp * * Arduino SdFat Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include "../inc/MarlinConfig.h" #if HAS_MEDIA #include "SdFile.h" /** * Create a file object and open it in the current working directory. * * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. * * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t). */ SdFile::SdFile(const char * const path, const uint8_t oflag) : SdBaseFile(path, oflag) { } /** * Write data to an open file. * * \note Data is moved to the cache but may not be written to the * storage device until sync() is called. * * \param[in] buf Pointer to the location of the data to be written. * * \param[in] nbyte Number of bytes to write. * * \return For success write() returns the number of bytes written, always * \a nbyte. If an error occurs, write() returns -1. Possible errors * include write() is called before a file has been opened, write is called * for a read-only file, device is full, a corrupt file system or an I/O error. */ int16_t SdFile::write(const void * const buf, const uint16_t nbyte) { return SdBaseFile::write(buf, nbyte); } /** * Write a byte to a file. Required by the Arduino Print class. * \param[in] b the byte to be written. * Use writeError to check for errors. */ size_t SdFile::write(const uint8_t b) { return SdBaseFile::write(&b, 1); } /** * Write a string to a file. Used by the Arduino Print class. * \param[in] str Pointer to the string. * Use writeError to check for errors. */ void SdFile::write(const char * const str) { SdBaseFile::write(str, strlen(str)); } /** * Write a PROGMEM string to a file. * \param[in] str Pointer to the PROGMEM string. * Use writeError to check for errors. */ void SdFile::write_P(PGM_P str) { for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c); } /** * Write a PROGMEM string followed by CR/LF to a file. * \param[in] str Pointer to the PROGMEM string. * Use writeError to check for errors. */ void SdFile::writeln_P(PGM_P const str) { write_P(str); write_P(PSTR("\r\n")); } #endif // HAS_MEDIA
2301_81045437/Marlin
Marlin/src/sd/SdFile.cpp
C++
agpl-3.0
3,131
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * sd/SdFile.h * * Arduino SdFat Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include "SdBaseFile.h" #include <stdint.h> /** * \class SdFile * \brief SdBaseFile with Print. */ class SdFile : public SdBaseFile { public: SdFile() {} SdFile(const char * const name, const uint8_t oflag); size_t write(const uint8_t b); int16_t write(const void * const buf, const uint16_t nbyte); void write(const char * const str); void write_P(PGM_P str); void writeln_P(PGM_P const str); }; using MediaFile = SdFile;
2301_81045437/Marlin
Marlin/src/sd/SdFile.h
C++
agpl-3.0
1,468
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * Arduino Sd2Card Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include <stdint.h> // Based on the document: // // SD Specifications // Part 1 // Physical Layer // Simplified Specification // Version 3.01 // May 18, 2010 // // https://www.sdcard.org/downloads/pls/index.html // SD card commands uint8_t const CMD0 = 0x00, // GO_IDLE_STATE - init card in spi mode if CS low CMD8 = 0x08, // SEND_IF_COND - verify SD Memory Card interface operating condition CMD9 = 0x09, // SEND_CSD - read the Card Specific Data (CSD register) CMD10 = 0x0A, // SEND_CID - read the card identification information (CID register) CMD12 = 0x0C, // STOP_TRANSMISSION - end multiple block read sequence CMD13 = 0x0D, // SEND_STATUS - read the card status register CMD17 = 0x11, // READ_SINGLE_BLOCK - read a single data block from the card CMD18 = 0x12, // READ_MULTIPLE_BLOCK - read a multiple data blocks from the card CMD24 = 0x18, // WRITE_BLOCK - write a single data block to the card CMD25 = 0x19, // WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION CMD32 = 0x20, // ERASE_WR_BLK_START - sets the address of the first block to be erased CMD33 = 0x21, // ERASE_WR_BLK_END - sets the address of the last block of the continuous range to be erased CMD38 = 0x26, // ERASE - erase all previously selected blocks CMD55 = 0x37, // APP_CMD - escape for application specific command CMD58 = 0x3A, // READ_OCR - read the OCR register of a card CMD59 = 0x3B, // CRC_ON_OFF - enable or disable CRC checking ACMD23 = 0x17, // SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be pre-erased before writing ACMD41 = 0x29; // SD_SEND_OP_COMD - Sends host capacity support information and activates the card's initialization process /** status for card in the ready state */ uint8_t const R1_READY_STATE = 0x00; /** status for card in the idle state */ uint8_t const R1_IDLE_STATE = 0x01; /** status bit for illegal command */ uint8_t const R1_ILLEGAL_COMMAND = 0x04; /** start data token for read or write single block*/ uint8_t const DATA_START_BLOCK = 0xFE; /** stop token for write multiple blocks*/ uint8_t const STOP_TRAN_TOKEN = 0xFD; /** start data token for write multiple blocks*/ uint8_t const WRITE_MULTIPLE_TOKEN = 0xFC; /** mask for data response tokens after a write block operation */ uint8_t const DATA_RES_MASK = 0x1F; /** write data accepted token */ uint8_t const DATA_RES_ACCEPTED = 0x05; /** Card IDentification (CID) register */ typedef struct CID { // byte 0 /** Manufacturer ID */ unsigned char mid; // byte 1-2 /** OEM/Application ID */ char oid[2]; // byte 3-7 /** Product name */ char pnm[5]; // byte 8 /** Product revision least significant digit */ unsigned char prv_m : 4; /** Product revision most significant digit */ unsigned char prv_n : 4; // byte 9-12 /** Product serial number */ uint32_t psn; // byte 13 /** Manufacturing date year low digit */ unsigned char mdt_year_high : 4; /** not used */ unsigned char reserved : 4; // byte 14 /** Manufacturing date month */ unsigned char mdt_month : 4; /** Manufacturing date year low digit */ unsigned char mdt_year_low : 4; // byte 15 /** not used always 1 */ unsigned char always1 : 1; /** CRC7 checksum */ unsigned char crc : 7; } cid_t; /** CSD for version 1.00 cards */ typedef struct CSDV1 { // byte 0 unsigned char reserved1 : 6; unsigned char csd_ver : 2; // byte 1 unsigned char taac; // byte 2 unsigned char nsac; // byte 3 unsigned char tran_speed; // byte 4 unsigned char ccc_high; // byte 5 unsigned char read_bl_len : 4; unsigned char ccc_low : 4; // byte 6 unsigned char c_size_high : 2; unsigned char reserved2 : 2; unsigned char dsr_imp : 1; unsigned char read_blk_misalign : 1; unsigned char write_blk_misalign : 1; unsigned char read_bl_partial : 1; // byte 7 unsigned char c_size_mid; // byte 8 unsigned char vdd_r_curr_max : 3; unsigned char vdd_r_curr_min : 3; unsigned char c_size_low : 2; // byte 9 unsigned char c_size_mult_high : 2; unsigned char vdd_w_cur_max : 3; unsigned char vdd_w_curr_min : 3; // byte 10 unsigned char sector_size_high : 6; unsigned char erase_blk_en : 1; unsigned char c_size_mult_low : 1; // byte 11 unsigned char wp_grp_size : 7; unsigned char sector_size_low : 1; // byte 12 unsigned char write_bl_len_high : 2; unsigned char r2w_factor : 3; unsigned char reserved3 : 2; unsigned char wp_grp_enable : 1; // byte 13 unsigned char reserved4 : 5; unsigned char write_partial : 1; unsigned char write_bl_len_low : 2; // byte 14 unsigned char reserved5: 2; unsigned char file_format : 2; unsigned char tmp_write_protect : 1; unsigned char perm_write_protect : 1; unsigned char copy : 1; /** Indicates the file format on the card */ unsigned char file_format_grp : 1; // byte 15 unsigned char always1 : 1; unsigned char crc : 7; } csd1_t; /** CSD for version 2.00 cards */ typedef struct CSDV2 { // byte 0 unsigned char reserved1 : 6; unsigned char csd_ver : 2; // byte 1 /** fixed to 0x0E */ unsigned char taac; // byte 2 /** fixed to 0 */ unsigned char nsac; // byte 3 unsigned char tran_speed; // byte 4 unsigned char ccc_high; // byte 5 /** This field is fixed to 9h, which indicates READ_BL_LEN=512 Byte */ unsigned char read_bl_len : 4; unsigned char ccc_low : 4; // byte 6 /** not used */ unsigned char reserved2 : 4; unsigned char dsr_imp : 1; /** fixed to 0 */ unsigned char read_blk_misalign : 1; /** fixed to 0 */ unsigned char write_blk_misalign : 1; /** fixed to 0 - no partial read */ unsigned char read_bl_partial : 1; // byte 7 /** not used */ unsigned char reserved3 : 2; /** high part of card size */ unsigned char c_size_high : 6; // byte 8 /** middle part of card size */ unsigned char c_size_mid; // byte 9 /** low part of card size */ unsigned char c_size_low; // byte 10 /** sector size is fixed at 64 KB */ unsigned char sector_size_high : 6; /** fixed to 1 - erase single is supported */ unsigned char erase_blk_en : 1; /** not used */ unsigned char reserved4 : 1; // byte 11 unsigned char wp_grp_size : 7; /** sector size is fixed at 64 KB */ unsigned char sector_size_low : 1; // byte 12 /** write_bl_len fixed for 512 byte blocks */ unsigned char write_bl_len_high : 2; /** fixed value of 2 */ unsigned char r2w_factor : 3; /** not used */ unsigned char reserved5 : 2; /** fixed value of 0 - no write protect groups */ unsigned char wp_grp_enable : 1; // byte 13 unsigned char reserved6 : 5; /** always zero - no partial block read*/ unsigned char write_partial : 1; /** write_bl_len fixed for 512 byte blocks */ unsigned char write_bl_len_low : 2; // byte 14 unsigned char reserved7: 2; /** Do not use always 0 */ unsigned char file_format : 2; unsigned char tmp_write_protect : 1; unsigned char perm_write_protect : 1; unsigned char copy : 1; /** Do not use always 0 */ unsigned char file_format_grp : 1; // byte 15 /** not used always 1 */ unsigned char always1 : 1; /** checksum */ unsigned char crc : 7; } csd2_t; /** union of old and new style CSD register */ union csd_t { csd1_t v1; csd2_t v2; };
2301_81045437/Marlin
Marlin/src/sd/SdInfo.h
C
agpl-3.0
8,524
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ /** * sd/SdVolume.cpp * * Arduino SdFat Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include "../inc/MarlinConfig.h" #if HAS_MEDIA #include "SdVolume.h" #include "../MarlinCore.h" #if !USE_MULTIPLE_CARDS // raw block cache uint32_t SdVolume::cacheBlockNumber_; // current block number cache_t SdVolume::cacheBuffer_; // 512 byte cache for Sd2Card DiskIODriver *SdVolume::sdCard_; // pointer to SD card object bool SdVolume::cacheDirty_; // cacheFlush() will write block if true uint32_t SdVolume::cacheMirrorBlock_; // mirror block for second FAT #endif // find a contiguous group of clusters bool SdVolume::allocContiguous(const uint32_t count, uint32_t * const curCluster) { if (ENABLED(SDCARD_READONLY)) return false; // start of group uint32_t bgnCluster; // end of group uint32_t endCluster; // last cluster of FAT uint32_t fatEnd = clusterCount_ + 1; // flag to save place to start next search bool setStart; // set search start cluster if (*curCluster) { // try to make file contiguous bgnCluster = *curCluster + 1; // don't save new start location setStart = false; } else { // start at likely place for free cluster bgnCluster = allocSearchStart_; // save next search start if one cluster setStart = count == 1; } // end of group endCluster = bgnCluster; // search the FAT for free clusters for (uint32_t n = 0;; n++, endCluster++) { // can't find space checked all clusters if (n >= clusterCount_) return false; // past end - start from beginning of FAT if (endCluster > fatEnd) { bgnCluster = endCluster = 2; } uint32_t f; if (!fatGet(endCluster, &f)) return false; if (f != 0) { // cluster in use try next cluster as bgnCluster bgnCluster = endCluster + 1; } else if ((endCluster - bgnCluster + 1) == count) { // done - found space break; } } // mark end of chain if (!fatPutEOC(endCluster)) return false; // link clusters while (endCluster > bgnCluster) { if (!fatPut(endCluster - 1, endCluster)) return false; endCluster--; } if (*curCluster != 0) { // connect chains if (!fatPut(*curCluster, bgnCluster)) return false; } // return first cluster number to caller *curCluster = bgnCluster; // remember possible next free cluster if (setStart) allocSearchStart_ = bgnCluster + 1; return true; } bool SdVolume::cacheFlush() { #if DISABLED(SDCARD_READONLY) if (cacheDirty_) { if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data)) return false; // mirror FAT tables if (cacheMirrorBlock_) { if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data)) return false; cacheMirrorBlock_ = 0; } cacheDirty_ = 0; } #endif return true; } bool SdVolume::cacheRawBlock(const uint32_t blockNumber, const bool dirty) { if (cacheBlockNumber_ != blockNumber) { if (!cacheFlush()) return false; if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) return false; cacheBlockNumber_ = blockNumber; } if (dirty) cacheDirty_ = true; return true; } // return the size in bytes of a cluster chain bool SdVolume::chainSize(uint32_t cluster, uint32_t * const size) { uint32_t s = 0; do { if (!fatGet(cluster, &cluster)) return false; s += 512UL << clusterSizeShift_; } while (!isEOC(cluster)); *size = s; return true; } // Fetch a FAT entry bool SdVolume::fatGet(const uint32_t cluster, uint32_t * const value) { uint32_t lba; if (cluster > (clusterCount_ + 1)) return false; if (FAT12_SUPPORT && fatType_ == 12) { uint16_t index = cluster; index += index >> 1; lba = fatStartBlock_ + (index >> 9); if (!cacheRawBlock(lba, CACHE_FOR_READ)) return false; index &= 0x1FF; uint16_t tmp = cacheBuffer_.data[index]; index++; if (index == 512) { if (!cacheRawBlock(lba + 1, CACHE_FOR_READ)) return false; index = 0; } tmp |= cacheBuffer_.data[index] << 8; *value = cluster & 1 ? tmp >> 4 : tmp & 0xFFF; return true; } if (fatType_ == 16) lba = fatStartBlock_ + (cluster >> 8); else if (fatType_ == 32) lba = fatStartBlock_ + (cluster >> 7); else return false; if (lba != cacheBlockNumber_ && !cacheRawBlock(lba, CACHE_FOR_READ)) return false; *value = (fatType_ == 16) ? cacheBuffer_.fat16[cluster & 0xFF] : (cacheBuffer_.fat32[cluster & 0x7F] & FAT32MASK); return true; } // Store a FAT entry bool SdVolume::fatPut(const uint32_t cluster, const uint32_t value) { if (ENABLED(SDCARD_READONLY)) return false; uint32_t lba; // error if reserved cluster if (cluster < 2) return false; // error if not in FAT if (cluster > (clusterCount_ + 1)) return false; if (FAT12_SUPPORT && fatType_ == 12) { uint16_t index = cluster; index += index >> 1; lba = fatStartBlock_ + (index >> 9); if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return false; // mirror second FAT if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; index &= 0x1FF; uint8_t tmp = value; if (cluster & 1) { tmp = (cacheBuffer_.data[index] & 0xF) | tmp << 4; } cacheBuffer_.data[index] = tmp; index++; if (index == 512) { lba++; index = 0; if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return false; // mirror second FAT if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; } tmp = value >> 4; if (!(cluster & 1)) { tmp = ((cacheBuffer_.data[index] & 0xF0)) | tmp >> 4; } cacheBuffer_.data[index] = tmp; return true; } if (fatType_ == 16) lba = fatStartBlock_ + (cluster >> 8); else if (fatType_ == 32) lba = fatStartBlock_ + (cluster >> 7); else return false; if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return false; // store entry if (fatType_ == 16) cacheBuffer_.fat16[cluster & 0xFF] = value; else cacheBuffer_.fat32[cluster & 0x7F] = value; // mirror second FAT if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; return true; } // free a cluster chain bool SdVolume::freeChain(uint32_t cluster) { // clear free cluster location allocSearchStart_ = 2; do { uint32_t next; if (!fatGet(cluster, &next)) return false; // free cluster if (!fatPut(cluster, 0)) return false; cluster = next; } while (!isEOC(cluster)); return true; } /** Volume free space in clusters. * * \return Count of free clusters for success or -1 if an error occurs. */ int32_t SdVolume::freeClusterCount() { uint32_t free = 0; uint16_t n; uint32_t todo = clusterCount_ + 2; if (fatType_ == 16) n = 256; else if (fatType_ == 32) n = 128; else // put FAT12 here return -1; for (uint32_t lba = fatStartBlock_; todo; todo -= n, lba++) { if (!cacheRawBlock(lba, CACHE_FOR_READ)) return -1; NOMORE(n, todo); if (fatType_ == 16) { for (uint16_t i = 0; i < n; i++) if (cacheBuffer_.fat16[i] == 0) free++; } else { for (uint16_t i = 0; i < n; i++) if (cacheBuffer_.fat32[i] == 0) free++; } #ifdef ESP32 // Needed to reset the idle task watchdog timer on ESP32 as reading the complete FAT may easily // block for 10+ seconds. yield() is insufficient since it blocks lower prio tasks (e.g., idle). static millis_t nextTaskTime = 0; const millis_t ms = millis(); if (ELAPSED(ms, nextTaskTime)) { vTaskDelay(1); // delay 1 tick (Minimum. Usually 10 or 1 ms depending on skdconfig.h) nextTaskTime = ms + 1000; // tickle the task manager again in 1 second } #endif // ESP32 } return free; } /** Initialize a FAT volume. * * \param[in] dev The SD card where the volume is located. * * \param[in] part The partition to be used. Legal values for \a part are * 1-4 to use the corresponding partition on a device formatted with * a MBR, Master Boot Record, or zero if the device is formatted as * a super floppy with the FAT boot sector in block zero. * * \return true for success, false for failure. * Reasons for failure include not finding a valid partition, not finding a valid * FAT file system in the specified partition or an I/O error. */ bool SdVolume::init(DiskIODriver * const dev, const uint8_t part) { uint32_t totalBlocks, volumeStartBlock = 0; fat32_boot_t *fbs; sdCard_ = dev; fatType_ = 0; allocSearchStart_ = 2; cacheDirty_ = 0; // cacheFlush() will write block if true cacheMirrorBlock_ = 0; cacheBlockNumber_ = 0xFFFFFFFF; // if part == 0 assume super floppy with FAT boot sector in block zero // if part > 0 assume mbr volume with partition table if (part) { if (part > 4) return false; if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false; part_t *p = &cacheBuffer_.mbr.part[part - 1]; if ((p->boot & 0x7F) != 0 || p->totalSectors < 100 || p->firstSector == 0) return false; // not a valid partition volumeStartBlock = p->firstSector; } if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false; fbs = &cacheBuffer_.fbs32; if (fbs->bytesPerSector != 512 || fbs->fatCount == 0 || fbs->reservedSectorCount == 0 || fbs->sectorsPerCluster == 0) { // not valid FAT volume return false; } fatCount_ = fbs->fatCount; blocksPerCluster_ = fbs->sectorsPerCluster; // determine shift that is same as multiply by blocksPerCluster_ clusterSizeShift_ = 0; while (blocksPerCluster_ != _BV(clusterSizeShift_)) { // error if not power of 2 if (clusterSizeShift_++ > 7) return false; } blocksPerFat_ = fbs->sectorsPerFat16 ? fbs->sectorsPerFat16 : fbs->sectorsPerFat32; fatStartBlock_ = volumeStartBlock + fbs->reservedSectorCount; // count for FAT16 zero for FAT32 rootDirEntryCount_ = fbs->rootDirEntryCount; // directory start for FAT16 dataStart for FAT32 rootDirStart_ = fatStartBlock_ + fbs->fatCount * blocksPerFat_; // data start for FAT16 and FAT32 dataStartBlock_ = rootDirStart_ + ((32 * fbs->rootDirEntryCount + 511) / 512); // total blocks for FAT16 or FAT32 totalBlocks = fbs->totalSectors16 ? fbs->totalSectors16 : fbs->totalSectors32; // total data blocks clusterCount_ = totalBlocks - (dataStartBlock_ - volumeStartBlock); // divide by cluster size to get cluster count clusterCount_ >>= clusterSizeShift_; // FAT type is determined by cluster count if (clusterCount_ < 4085) { fatType_ = 12; if (!FAT12_SUPPORT) return false; } else if (clusterCount_ < 65525) fatType_ = 16; else { rootDirStart_ = fbs->fat32RootCluster; fatType_ = 32; } return true; } #endif // HAS_MEDIA
2301_81045437/Marlin
Marlin/src/sd/SdVolume.cpp
C++
agpl-3.0
11,736
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * sd/SdVolume.h * * Arduino SdFat Library * Copyright (c) 2009 by William Greiman * * This file is part of the Arduino Sd2Card Library */ #include <stdint.h> #include "../inc/MarlinConfigPre.h" #if ENABLED(USB_FLASH_DRIVE_SUPPORT) #include "usb_flashdrive/Sd2Card_FlashDrive.h" #endif #if NEED_SD2CARD_SDIO #include "Sd2Card_sdio.h" #elif NEED_SD2CARD_SPI #include "Sd2Card.h" #endif #include "SdFatConfig.h" #include "SdFatStructs.h" //============================================================================== // SdVolume class /** * \brief Cache for an SD data block */ union cache_t { uint8_t data[512]; // Used to access cached file data blocks. uint16_t fat16[256]; // Used to access cached FAT16 entries. uint32_t fat32[128]; // Used to access cached FAT32 entries. dir_t dir[16]; // Used to access cached directory entries. mbr_t mbr; // Used to access a cached Master Boot Record. fat_boot_t fbs; // Used to access to a cached FAT boot sector. fat32_boot_t fbs32; // Used to access to a cached FAT32 boot sector. fat32_fsinfo_t fsinfo; // Used to access to a cached FAT32 FSINFO sector. }; /** * \class SdVolume * \brief Access FAT16 and FAT32 volumes on SD and SDHC cards. */ class SdVolume { public: // Create an instance of SdVolume SdVolume() : fatType_(0) {} /** * Clear the cache and returns a pointer to the cache. Used by the WaveRP * recorder to do raw write to the SD card. Not for normal apps. * \return A pointer to the cache buffer or zero if an error occurs. */ cache_t* cacheClear() { if (!cacheFlush()) return 0; cacheBlockNumber_ = 0xFFFFFFFF; return &cacheBuffer_; } /** * Initialize a FAT volume. Try partition one first then try super * floppy format. * * \param[in] dev The DiskIODriver where the volume is located. * * \return true for success, false for failure. * Reasons for failure include not finding a valid partition, not finding * a valid FAT file system or an I/O error. */ bool init(DiskIODriver * const dev) { return init(dev, 1) || init(dev, 0); } bool init(DiskIODriver * const dev, const uint8_t part); // inline functions that return volume info uint8_t blocksPerCluster() const { return blocksPerCluster_; } //> \return The volume's cluster size in blocks. uint32_t blocksPerFat() const { return blocksPerFat_; } //> \return The number of blocks in one FAT. uint32_t clusterCount() const { return clusterCount_; } //> \return The total number of clusters in the volume. uint8_t clusterSizeShift() const { return clusterSizeShift_; } //> \return The shift count required to multiply by blocksPerCluster. uint32_t dataStartBlock() const { return dataStartBlock_; } //> \return The logical block number for the start of file data. uint8_t fatCount() const { return fatCount_; } //> \return The number of FAT structures on the volume. uint32_t fatStartBlock() const { return fatStartBlock_; } //> \return The logical block number for the start of the first FAT. uint8_t fatType() const { return fatType_; } //> \return The FAT type of the volume. Values are 12, 16 or 32. int32_t freeClusterCount(); uint32_t rootDirEntryCount() const { return rootDirEntryCount_; } /** \return The number of entries in the root directory for FAT16 volumes. */ /** * \return The logical block number for the start of the root directory * on FAT16 volumes or the first cluster number on FAT32 volumes. */ uint32_t rootDirStart() const { return rootDirStart_; } /** * DiskIODriver object for this volume * \return pointer to DiskIODriver object. */ DiskIODriver* sdCard() { return sdCard_; } /** * Debug access to FAT table * * \param[in] n cluster number. * \param[out] v value of entry * \return true for success or false for failure */ bool dbgFat(const uint32_t n, uint32_t * const v) { return fatGet(n, v); } private: // Allow SdBaseFile access to SdVolume private data. friend class SdBaseFile; // value for dirty argument in cacheRawBlock to indicate read from cache static bool const CACHE_FOR_READ = false; // value for dirty argument in cacheRawBlock to indicate write to cache static bool const CACHE_FOR_WRITE = true; #if USE_MULTIPLE_CARDS cache_t cacheBuffer_; // 512 byte cache for device blocks uint32_t cacheBlockNumber_; // Logical number of block in the cache DiskIODriver *sdCard_; // DiskIODriver object for cache bool cacheDirty_; // cacheFlush() will write block if true uint32_t cacheMirrorBlock_; // block number for mirror FAT #else static cache_t cacheBuffer_; // 512 byte cache for device blocks static uint32_t cacheBlockNumber_; // Logical number of block in the cache static DiskIODriver *sdCard_; // DiskIODriver object for cache static bool cacheDirty_; // cacheFlush() will write block if true static uint32_t cacheMirrorBlock_; // block number for mirror FAT #endif uint32_t allocSearchStart_; // start cluster for alloc search uint8_t blocksPerCluster_; // cluster size in blocks uint32_t blocksPerFat_; // FAT size in blocks uint32_t clusterCount_; // clusters in one FAT uint8_t clusterSizeShift_; // shift to convert cluster count to block count uint32_t dataStartBlock_; // first data block number uint8_t fatCount_; // number of FATs on volume uint32_t fatStartBlock_; // start block for first FAT uint8_t fatType_; // volume type (12, 16, OR 32) uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32 bool allocContiguous(const uint32_t count, uint32_t * const curCluster); uint8_t blockOfCluster(const uint32_t position) const { return (position >> 9) & (blocksPerCluster_ - 1); } uint32_t clusterStartBlock(const uint32_t cluster) const { return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_); } uint32_t blockNumber(const uint32_t cluster, const uint32_t position) const { return clusterStartBlock(cluster) + blockOfCluster(position); } cache_t* cache() { return &cacheBuffer_; } uint32_t cacheBlockNumber() const { return cacheBlockNumber_; } #if USE_MULTIPLE_CARDS bool cacheFlush(); bool cacheRawBlock(const uint32_t blockNumber, const bool dirty); #else static bool cacheFlush(); static bool cacheRawBlock(const uint32_t blockNumber, const bool dirty); #endif // used by SdBaseFile write to assign cache to SD location void cacheSetBlockNumber(uint32_t blockNumber, bool dirty) { cacheDirty_ = dirty; cacheBlockNumber_ = blockNumber; } void cacheSetDirty() { cacheDirty_ |= CACHE_FOR_WRITE; } bool chainSize(uint32_t cluster, uint32_t * const size); bool fatGet(const uint32_t cluster, uint32_t * const value); bool fatPut(const uint32_t cluster, const uint32_t value); bool fatPutEOC(const uint32_t cluster) { return fatPut(cluster, 0x0FFFFFFF); } bool freeChain(uint32_t cluster); bool isEOC(const uint32_t cluster) const { if (FAT12_SUPPORT && fatType_ == 12) return cluster >= FAT12EOC_MIN; if (fatType_ == 16) return cluster >= FAT16EOC_MIN; return cluster >= FAT32EOC_MIN; } bool readBlock(const uint32_t block, uint8_t * const dst) { return sdCard_->readBlock(block, dst); } bool writeBlock(const uint32_t block, const uint8_t * const dst) { return sdCard_->writeBlock(block, dst); } }; using MarlinVolume = SdVolume;
2301_81045437/Marlin
Marlin/src/sd/SdVolume.h
C++
agpl-3.0
8,582
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfig.h" #if HAS_MEDIA //#define DEBUG_CARDREADER #include "cardreader.h" #include "../MarlinCore.h" #include "../libs/hex_print.h" #include "../lcd/marlinui.h" #if ENABLED(DWIN_CREALITY_LCD) #include "../lcd/e3v2/creality/dwin.h" #endif #include "../module/planner.h" // for synchronize #include "../module/printcounter.h" #include "../gcode/queue.h" #include "../module/settings.h" #include "../module/stepper/indirection.h" #if ENABLED(EMERGENCY_PARSER) #include "../feature/e_parser.h" #endif #if ENABLED(POWER_LOSS_RECOVERY) #include "../feature/powerloss.h" #endif #if ENABLED(ADVANCED_PAUSE_FEATURE) #include "../feature/pause.h" #endif #if ENABLED(ONE_CLICK_PRINT) #include "../../src/lcd/menu/menu.h" #endif #define DEBUG_OUT ANY(DEBUG_CARDREADER, MARLIN_DEV_MODE) #include "../core/debug_out.h" #include "../libs/hex_print.h" // extern PGMSTR(M21_STR, "M21"); PGMSTR(M23_STR, "M23 %s"); PGMSTR(M24_STR, "M24"); // public: card_flags_t CardReader::flag; char CardReader::filename[FILENAME_LENGTH], CardReader::longFilename[LONG_FILENAME_LENGTH]; IF_DISABLED(NO_SD_AUTOSTART, uint8_t CardReader::autofile_index); // = 0 #if ENABLED(BINARY_FILE_TRANSFER) serial_index_t IF_DISABLED(HAS_MULTI_SERIAL, constexpr) CardReader::transfer_port_index; #endif // private: MediaFile CardReader::root, CardReader::workDir, CardReader::workDirParents[MAX_DIR_DEPTH]; uint8_t CardReader::workDirDepth; int16_t CardReader::nrItems = -1; #if ENABLED(SDCARD_SORT_ALPHA) int16_t CardReader::sort_count; #if ENABLED(SDSORT_GCODE) SortFlag CardReader::sort_alpha; int8_t CardReader::sort_folders; //bool CardReader::sort_reverse; #endif #if ENABLED(SDSORT_DYNAMIC_RAM) uint8_t *CardReader::sort_order; #else uint8_t CardReader::sort_order[SDSORT_LIMIT]; #endif #if ENABLED(SDSORT_USES_RAM) #if ENABLED(SDSORT_CACHE_NAMES) #if ENABLED(SDSORT_DYNAMIC_RAM) char **CardReader::sortshort, **CardReader::sortnames; #else char CardReader::sortshort[SDSORT_LIMIT][FILENAME_LENGTH]; char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE]; #endif #elif DISABLED(SDSORT_USES_STACK) char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE]; #endif #if HAS_FOLDER_SORTING #if ENABLED(SDSORT_DYNAMIC_RAM) uint8_t *CardReader::isDir; #elif ENABLED(SDSORT_CACHE_NAMES) || DISABLED(SDSORT_USES_STACK) uint8_t CardReader::isDir[(SDSORT_LIMIT+7)>>3]; #endif #define IS_DIR(n) TEST(isDir[(n) >> 3], (n) & 0x07) #endif #endif // SDSORT_USES_RAM #endif // SDCARD_SORT_ALPHA #if HAS_USB_FLASH_DRIVE DiskIODriver_USBFlash CardReader::media_driver_usbFlash; #endif #if NEED_SD2CARD_SDIO || NEED_SD2CARD_SPI CardReader::sdcard_driver_t CardReader::media_driver_sdcard; #endif DiskIODriver* CardReader::driver = nullptr; MarlinVolume CardReader::volume; MediaFile CardReader::file; #if HAS_MEDIA_SUBCALLS uint8_t CardReader::file_subcall_ctr; uint32_t CardReader::filespos[SD_PROCEDURE_DEPTH]; char CardReader::proc_filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH]; #endif uint32_t CardReader::filesize, CardReader::sdpos; CardReader::CardReader() { changeMedia(& #if HAS_USB_FLASH_DRIVE && !SHARED_VOLUME_IS(SD_ONBOARD) media_driver_usbFlash #else media_driver_sdcard #endif ); #if ENABLED(SDCARD_SORT_ALPHA) sort_count = 0; #if ENABLED(SDSORT_GCODE) sort_alpha = TERN(SDSORT_REVERSE, AS_REV, AS_FWD); sort_folders = SDSORT_FOLDERS; //sort_reverse = false; #endif #endif flag.sdprinting = flag.sdprintdone = flag.mounted = flag.saving = flag.logging = false; filesize = sdpos = 0; TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0); IF_DISABLED(NO_SD_AUTOSTART, autofile_cancel()); workDirDepth = 0; ZERO(workDirParents); #if ALL(HAS_MEDIA, HAS_SD_DETECT) SET_INPUT_PULLUP(SD_DETECT_PIN); #endif #if PIN_EXISTS(SDPOWER) OUT_WRITE(SDPOWER_PIN, HIGH); // Power the SD reader #endif } // // Get a DOS 8.3 filename in its useful form // char *createFilename(char * const buffer, const dir_t &p) { char *pos = buffer; for (uint8_t i = 0; i < 11; ++i) { if (p.name[i] == ' ') continue; if (i == 8) *pos++ = '.'; *pos++ = p.name[i]; } *pos++ = 0; return buffer; } // // Return 'true' if the item is a folder, G-code file or Binary file // bool CardReader::is_visible_entity(const dir_t &p OPTARG(CUSTOM_FIRMWARE_UPLOAD, const bool onlyBin/*=false*/)) { //uint8_t pn0 = p.name[0]; #if DISABLED(CUSTOM_FIRMWARE_UPLOAD) constexpr bool onlyBin = false; #endif if ( (p.attributes & DIR_ATT_HIDDEN) // Hidden by attribute // When readDir() > 0 these must be false: //|| pn0 == DIR_NAME_FREE || pn0 == DIR_NAME_DELETED // Clear or Deleted entry //|| pn0 == '.' || longFilename[0] == '.' // Hidden file //|| !DIR_IS_FILE_OR_SUBDIR(&p) // Not a File or Directory ) return false; flag.filenameIsDir = DIR_IS_SUBDIR(&p); // We know it's a File or Folder setBinFlag(p.name[8] == 'B' && // List .bin files (a firmware file for flashing) p.name[9] == 'I' && p.name[10]== 'N'); return ( flag.filenameIsDir // All Directories are ok || fileIsBinary() // BIN files are accepted || (!onlyBin && p.name[8] == 'G' && p.name[9] != '~') // Non-backup *.G* files are accepted ); } // // Get the number of (compliant) items in the folder // int16_t CardReader::countVisibleItems(MediaFile dir) { dir_t p; int16_t c = 0; dir.rewind(); while (dir.readDir(&p, longFilename) > 0) c += is_visible_entity(p); return c; } // // Get file/folder info for an item by index // void CardReader::selectByIndex(MediaFile dir, const int16_t index) { dir_t p; for (int16_t cnt = 0; dir.readDir(&p, longFilename) > 0;) { if (is_visible_entity(p)) { if (cnt == index) { createFilename(filename, p); return; // 0 based index } cnt++; } } } // // Get file/folder info for an item by name // void CardReader::selectByName(MediaFile dir, const char * const match) { dir_t p; for (uint8_t cnt = 0; dir.readDir(&p, longFilename) > 0; cnt++) { if (is_visible_entity(p)) { createFilename(filename, p); if (strcasecmp(match, filename) == 0) return; } } } /** * Recursive method to print all files within a folder in flat * DOS 8.3 format. This style of listing is the most compatible * with legacy hosts. * * This method recurses to unlimited depth and lists all G-code * files within the given parent. If the hierarchy is very deep * this can blow up the stack, so a 'depth' parameter would be a * good addition. */ void CardReader::printListing(MediaFile parent, const char * const prepend, const uint8_t lsflags OPTARG(LONG_FILENAME_HOST_SUPPORT, const char * const prependLong/*=nullptr*/) ) { const bool includeTime = TERN0(M20_TIMESTAMP_SUPPORT, TEST(lsflags, LS_TIMESTAMP)); #if ENABLED(LONG_FILENAME_HOST_SUPPORT) const bool includeLong = TEST(lsflags, LS_LONG_FILENAME); #endif #if ENABLED(CUSTOM_FIRMWARE_UPLOAD) const bool onlyBin = TEST(lsflags, LS_ONLY_BIN); #endif UNUSED(lsflags); dir_t p; while (parent.readDir(&p, longFilename) > 0) { if (DIR_IS_SUBDIR(&p)) { const size_t lenPrepend = prepend ? strlen(prepend) + 1 : 0; // Allocate enough stack space for the full path including / separator char path[lenPrepend + FILENAME_LENGTH]; if (prepend) { strcpy(path, prepend); path[lenPrepend - 1] = '/'; } char* dosFilename = path + lenPrepend; createFilename(dosFilename, p); // Get a new directory object using the full path // and dive recursively into it. MediaFile child; // child.close() in destructor if (child.open(&parent, dosFilename, O_READ)) { #if ENABLED(LONG_FILENAME_HOST_SUPPORT) if (includeLong) { const size_t lenPrependLong = prependLong ? strlen(prependLong) + 1 : 0; // Allocate enough stack space for the full long path including / separator char pathLong[lenPrependLong + strlen(longFilename) + 1]; if (prependLong) { strcpy(pathLong, prependLong); pathLong[lenPrependLong - 1] = '/'; } strcpy(pathLong + lenPrependLong, longFilename); printListing(child, path, lsflags, pathLong); continue; } #endif printListing(child, path, lsflags); } else { SERIAL_ECHO_MSG(STR_SD_CANT_OPEN_SUBDIR, dosFilename); return; } } else if (is_visible_entity(p OPTARG(CUSTOM_FIRMWARE_UPLOAD, onlyBin))) { if (prepend) { SERIAL_ECHO(prepend); SERIAL_CHAR('/'); } SERIAL_ECHO(createFilename(filename, p)); SERIAL_CHAR(' '); SERIAL_ECHO(p.fileSize); if (includeTime) { SERIAL_CHAR(' '); uint16_t crmodDate = p.lastWriteDate, crmodTime = p.lastWriteTime; if (crmodDate < p.creationDate || (crmodDate == p.creationDate && crmodTime < p.creationTime)) { crmodDate = p.creationDate; crmodTime = p.creationTime; } SERIAL_ECHOPGM("0x", hex_word(crmodDate)); print_hex_word(crmodTime); } #if ENABLED(LONG_FILENAME_HOST_SUPPORT) if (includeLong) { SERIAL_CHAR(' '); if (prependLong) { SERIAL_ECHO(prependLong); SERIAL_CHAR('/'); } SERIAL_ECHO(longFilename[0] ? longFilename : filename); } #endif SERIAL_EOL(); } } } // // List all files on the SD card // void CardReader::ls(const uint8_t lsflags/*=0*/) { if (flag.mounted) { root.rewind(); printListing(root, nullptr, lsflags); } } #if ENABLED(LONG_FILENAME_HOST_SUPPORT) // // Get a long pretty path based on a DOS 8.3 path // void CardReader::printLongPath(char * const path) { int i, pathLen = path ? strlen(path) : 0; // SERIAL_ECHOPGM("Full Path: "); SERIAL_ECHOLN(path); // Zero out slashes to make segments for (i = 0; i < pathLen; i++) if (path[i] == '/') path[i] = '\0'; MediaFile diveDir = root; // start from the root for segment 1 for (i = 0; i < pathLen;) { if (path[i] == '\0') i++; // move past a single nul char *segment = &path[i]; // The segment after most slashes // If a segment is empty (extra-slash) then exit if (!*segment) break; // Go to the next segment while (path[++i]) { } //SERIAL_ECHOLNPGM("Looking for segment: ", segment); // Find the item, setting the long filename diveDir.rewind(); selectByName(diveDir, segment); // Print /LongNamePart to serial output or the short name if not available SERIAL_CHAR('/'); SERIAL_ECHO(longFilename[0] ? longFilename : filename); // If the filename was printed then that's it if (!flag.filenameIsDir) break; // SERIAL_ECHOPGM("Opening dir: "); SERIAL_ECHOLN(segment); // Open the sub-item as the new dive parent MediaFile dir; if (!dir.open(&diveDir, segment, O_READ)) { SERIAL_EOL(); SERIAL_ECHO_START(); SERIAL_ECHOPGM(STR_SD_CANT_OPEN_SUBDIR, segment); break; } diveDir.close(); diveDir = dir; } // while i<pathLen SERIAL_EOL(); } void CardReader::getLongPath(char * const pathLong, char * const pathShort) { int i, pathLen = strlen(pathShort); char bufShort[FILENAME_LENGTH] = { '\0' }; strcpy_P(bufShort, pathShort); // Zero out slashes to make segments for (i = 0; i < pathLen; i++) if (bufShort[i] == '/') bufShort[i] = '\0'; SdFile diveDir = root; // start from the root for segment 1 for (i = 0; i < pathLen;) { if (bufShort[i] == '\0') i++; // move past a single nul char *segment = &bufShort[i]; // The segment after most slashes // If a segment is empty (extra-slash) then exit if (!*segment) break; //SERIAL_ECHOLNPGM("Looking for segment: ", segment); // Find the item, setting the long filename diveDir.rewind(); selectByName(diveDir, segment); diveDir.close(); if (longFilename[0]) { strlcpy_P(pathLong, longFilename, 64); break; } } } #endif // LONG_FILENAME_HOST_SUPPORT // // Echo the DOS 8.3 filename (and long filename, if any) // void CardReader::printSelectedFilename() { if (file.isOpen()) { char dosFilename[FILENAME_LENGTH]; file.getDosName(dosFilename); SERIAL_ECHO(dosFilename); #if ENABLED(LONG_FILENAME_HOST_SUPPORT) selectFileByName(dosFilename); if (longFilename[0]) { SERIAL_CHAR(' '); SERIAL_ECHO(longFilename); } #endif } else SERIAL_ECHOPGM("(no file)"); SERIAL_EOL(); } void CardReader::mount() { flag.mounted = false; nrItems = -1; if (root.isOpen()) root.close(); if (!driver->init(SD_SPI_SPEED, SDSS) #if defined(LCD_SDSS) && (LCD_SDSS != SDSS) && !driver->init(SD_SPI_SPEED, LCD_SDSS) #endif ) SERIAL_ECHO_MSG(STR_SD_INIT_FAIL); else if (!volume.init(driver)) SERIAL_WARN_MSG(STR_SD_VOL_INIT_FAIL); else if (!root.openRoot(&volume)) SERIAL_WARN_MSG(STR_SD_OPENROOT_FAIL); else { flag.mounted = true; SERIAL_ECHO_MSG(STR_SD_CARD_OK); } if (flag.mounted) cdroot(); else { #if ANY(HAS_SD_DETECT, USB_FLASH_DRIVE_SUPPORT) if (marlin_state != MF_INITIALIZING) LCD_ALERTMESSAGE(MSG_MEDIA_INIT_FAIL); #endif } ui.refresh(); } /** * Handle SD card events */ #if MB(FYSETC_CHEETAH, FYSETC_AIO_II) #include "../module/stepper.h" #endif void CardReader::manage_media() { static uint8_t prev_stat = 2; // At boot we don't know if media is present or not uint8_t stat = uint8_t(IS_SD_INSERTED()); if (stat == prev_stat) return; // Already checked and still no change? DEBUG_SECTION(cmm, "CardReader::manage_media()", true); DEBUG_ECHOLNPGM("Media present: ", prev_stat, " -> ", stat); if (!ui.detected()) { DEBUG_ECHOLNPGM("SD: No UI Detected."); return; } flag.workDirIsRoot = true; // Return to root on mount/release/init const uint8_t old_stat = prev_stat; prev_stat = stat; // Change now to prevent re-entry in safe_delay if (stat) { // Media Inserted safe_delay(500); // Some boards need a delay to get settled // Try to mount the media (only later with SD_IGNORE_AT_STARTUP) if (TERN1(SD_IGNORE_AT_STARTUP, old_stat != 2)) mount(); if (!isMounted()) stat = 0; // Not mounted? TERN_(RESET_STEPPERS_ON_MEDIA_INSERT, reset_stepper_drivers()); // Workaround for Cheetah bug } else { TERN_(HAS_SD_DETECT, release()); // Card is released } ui.media_changed(old_stat, stat); // Update the UI or flag an error if (!stat) return; // Exit if no media is present bool do_auto = true; UNUSED(do_auto); // First mount on boot? Load emulated EEPROM and look for PLR file. if (old_stat == 2) { DEBUG_ECHOLNPGM("First mount."); // Load settings the first time media is inserted (not just during init) TERN_(SDCARD_EEPROM_EMULATION, settings.first_load()); // Check for PLR file. Skip One-Click and auto#.g if found TERN_(POWER_LOSS_RECOVERY, if (recovery.check()) do_auto = false); } // Find the newest file and prompt to print it. TERN_(ONE_CLICK_PRINT, if (do_auto && one_click_check()) do_auto = false); // Also for the first mount run auto#.g for machine init. // (Skip if PLR or One-Click Print was invoked.) if (old_stat == 2) { // Look for auto0.g on the next idle() IF_DISABLED(NO_SD_AUTOSTART, if (do_auto) autofile_begin()); } } /** * "Release" the media by clearing the 'mounted' flag. * Used by M22, "Release Media", manage_media. */ void CardReader::release() { // Card removed while printing? Abort! if (IS_SD_PRINTING()) abortFilePrintSoon(); else endFilePrintNow(); flag.mounted = false; flag.workDirIsRoot = true; nrItems = -1; SERIAL_ECHO_MSG(STR_SD_CARD_RELEASED); TERN_(NO_SD_DETECT, ui.refresh()); } /** * Open a G-code file and set Marlin to start processing it. * Enqueues M23 and M24 commands to initiate a media print. */ void CardReader::openAndPrintFile(const char *name) { char cmd[4 + strlen(name) + 1 + 3 + 1]; // Room for "M23 ", filename, "\n", "M24", and null sprintf_P(cmd, M23_STR, name); for (char *c = &cmd[4]; *c; c++) *c = tolower(*c); strcat_P(cmd, PSTR("\nM24")); queue.inject(cmd); } /** * Start or resume a media print by setting the sdprinting flag. * The file browser pre-sort is also purged to free up memory, * since you cannot browse files during active printing. * Used by M24 and anywhere Start / Resume applies. */ void CardReader::startOrResumeFilePrinting() { if (isMounted()) { flag.sdprinting = true; flag.sdprintdone = false; TERN_(SD_RESORT, flush_presort()); } } // // Run tasks upon finishing or aborting a file print. // void CardReader::endFilePrintNow(TERN_(SD_RESORT, const bool re_sort/*=false*/)) { TERN_(ADVANCED_PAUSE_FEATURE, did_pause_print = 0); TERN_(DWIN_CREALITY_LCD, hmiFlag.print_finish = flag.sdprinting); flag.abort_sd_printing = false; if (isFileOpen()) file.close(); TERN_(SD_RESORT, if (re_sort) presort()); } void CardReader::abortFilePrintNow(TERN_(SD_RESORT, const bool re_sort/*=false*/)) { flag.sdprinting = flag.sdprintdone = false; endFilePrintNow(TERN_(SD_RESORT, re_sort)); } void CardReader::openLogFile(const char * const path) { flag.logging = DISABLED(SDCARD_READONLY); IF_DISABLED(SDCARD_READONLY, openFileWrite(path)); } // // Get the root-relative DOS path of the selected file // void CardReader::getAbsFilenameInCWD(char *dst) { *dst++ = '/'; uint8_t cnt = 1; auto appendAtom = [&](MediaFile &file) { file.getDosName(dst); while (*dst && cnt < MAXPATHNAMELENGTH) { dst++; cnt++; } if (cnt < MAXPATHNAMELENGTH) { *dst = '/'; dst++; cnt++; } }; for (uint8_t i = 0; i < workDirDepth; ++i) // Loop down to current work dir appendAtom(workDirParents[i]); if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH) - 1) { // Leave room for filename and nul appendAtom(file); --dst; } *dst = '\0'; } void openFailed(const char * const fname) { SERIAL_ECHOLNPGM(STR_SD_OPEN_FILE_FAIL, fname, "."); } void announceOpen(const uint8_t doing, const char * const path) { if (doing) { PORT_REDIRECT(SerialMask::All); SERIAL_ECHO_START(); SERIAL_ECHOLN(F("Now "), doing == 1 ? F("doing") : F("fresh"), F(" file: "), path); } } // // Open a file by DOS path for read // The 'subcall_type' flag indicates... // - 0 : Standard open from host or user interface. // - 1 : (file open) Opening a new sub-procedure. // - 1 : (no file open) Opening a macro (M98). // - 2 : Resuming from a sub-procedure // void CardReader::openFileRead(const char * const path, const uint8_t subcall_type/*=0*/) { if (!isMounted()) return openFailed(path); switch (subcall_type) { case 0: // Starting a new print. "Now fresh file: ..." announceOpen(2, path); TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0); break; #if HAS_MEDIA_SUBCALLS case 1: // Starting a sub-procedure // With no file is open it's a simple macro. "Now doing file: ..." if (!isFileOpen()) { announceOpen(1, path); break; } // Too deep? The firmware has to bail. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) { SERIAL_ERROR_MSG("Exceeded max SUBROUTINE depth:", SD_PROCEDURE_DEPTH); kill(GET_TEXT_F(MSG_KILL_SUBCALL_OVERFLOW)); return; } // Store current filename (based on workDirParents) and position getAbsFilenameInCWD(proc_filenames[file_subcall_ctr]); filespos[file_subcall_ctr] = sdpos; // For sub-procedures say 'SUBROUTINE CALL target: "..." parent: "..." pos12345' SERIAL_ECHO_MSG("SUBROUTINE CALL target:\"", path, "\" parent:\"", proc_filenames[file_subcall_ctr], "\" pos", sdpos); file_subcall_ctr++; break; case 2: // Resuming previous file after sub-procedure SERIAL_ECHO_MSG("END SUBROUTINE"); break; #endif } abortFilePrintNow(); MediaFile *diveDir; const char * const fname = diveToFile(true, diveDir, path); if (!fname) return openFailed(path); if (file.open(diveDir, fname, O_READ)) { filesize = file.fileSize(); sdpos = 0; { // Don't remove this block, as the PORT_REDIRECT is a RAII PORT_REDIRECT(SerialMask::All); SERIAL_ECHOLNPGM(STR_SD_FILE_OPENED, fname, STR_SD_SIZE, filesize); SERIAL_ECHOLNPGM(STR_SD_FILE_SELECTED); } selectFileByName(fname); ui.set_status(longFilename[0] ? longFilename : fname); } else openFailed(fname); } inline void echo_write_to_file(const char * const fname) { SERIAL_ECHOLNPGM(STR_SD_WRITE_TO_FILE, fname); } // // Open a file by DOS path for write // void CardReader::openFileWrite(const char * const path) { if (!isMounted()) return; announceOpen(2, path); TERN_(HAS_MEDIA_SUBCALLS, file_subcall_ctr = 0); abortFilePrintNow(); MediaFile *diveDir; const char * const fname = diveToFile(false, diveDir, path); if (!fname) return openFailed(path); #if DISABLED(SDCARD_READONLY) if (file.open(diveDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) { flag.saving = true; selectFileByName(fname); TERN_(EMERGENCY_PARSER, emergency_parser.disable()); echo_write_to_file(fname); ui.set_status(fname); return; } #endif openFailed(fname); } // // Check if a file exists by absolute or workDir-relative path // If the file exists, the long name can also be fetched. // bool CardReader::fileExists(const char * const path) { if (!isMounted()) return false; DEBUG_ECHOLNPGM("fileExists: ", path); // Dive to the file's directory and get the base name MediaFile *diveDir = nullptr; const char * const fname = diveToFile(false, diveDir, path); if (!fname) return false; // Get the longname of the checked file //diveDir->rewind(); //selectByName(*diveDir, fname); //diveDir->close(); // Try to open the file and return the result MediaFile tmpFile; const bool success = tmpFile.open(diveDir, fname, O_READ); if (success) tmpFile.close(); return success; } // // Delete a file by name in the working directory // void CardReader::removeFile(const char * const name) { if (!isMounted()) return; //abortFilePrintNow(); MediaFile *itsDirPtr; const char * const fname = diveToFile(false, itsDirPtr, name); if (!fname) return; #if ENABLED(SDCARD_READONLY) SERIAL_ECHOLNPGM("Deletion failed (read-only), File: ", fname, "."); #else if (file.remove(itsDirPtr, fname)) { SERIAL_ECHOLNPGM("File deleted:", fname); sdpos = 0; TERN_(SDCARD_SORT_ALPHA, presort()); } else SERIAL_ECHOLNPGM("Deletion failed, File: ", fname, "."); #endif } void CardReader::report_status() { if (isPrinting() || isPaused()) { SERIAL_ECHOPGM(STR_SD_PRINTING_BYTE, sdpos); SERIAL_CHAR('/'); SERIAL_ECHOLN(filesize); } else SERIAL_ECHOLNPGM(STR_SD_NOT_PRINTING); } void CardReader::write_command(char * const buf) { char *begin = buf, *npos = nullptr, *end = buf + strlen(buf) - 1; file.writeError = false; if ((npos = strchr(buf, 'N'))) { begin = strchr(npos, ' ') + 1; end = strchr(npos, '*') - 1; } end[1] = '\r'; end[2] = '\n'; end[3] = '\0'; file.write(begin); if (file.writeError) SERIAL_ERROR_MSG(STR_SD_ERR_WRITE_TO_FILE); } #if DISABLED(NO_SD_AUTOSTART) /** * Run all the auto#.g files. Called: * - On boot after successful card init. * - From the LCD command to Run Auto Files */ void CardReader::autofile_begin() { autofile_index = 1; (void)autofile_check(); } /** * Run the next auto#.g file. Called: * - On boot after successful card init * - After finishing the previous auto#.g file * - From the LCD command to begin the auto#.g files * * Return 'true' if an auto file was started */ bool CardReader::autofile_check() { if (!autofile_index) return false; if (!isMounted()) mount(); else if (ENABLED(SDCARD_EEPROM_EMULATION)) settings.first_load(); // Don't run auto#.g when a PLR file exists if (isMounted() && TERN1(POWER_LOSS_RECOVERY, !recovery.valid())) { char autoname[10]; sprintf_P(autoname, PSTR("/auto%c.g"), '0' + autofile_index - 1); if (fileExists(autoname)) { cdroot(); openAndPrintFile(autoname); autofile_index++; return true; } } autofile_cancel(); return false; } #endif #if ENABLED(ONE_CLICK_PRINT) /** * Select the newest file and ask the user if they want to print it. */ bool CardReader::one_click_check() { const bool found = selectNewestFile(); if (found) { //SERIAL_ECHO_MSG(" OCP File: ", longest_filename(), "\n"); //ui.init(); one_click_print(); } return found; } /** * Recurse the entire directory to find the newest file. * This may take a very long time so watch out for watchdog reset. * It may be best to only look at root for reasonable boot and mount times. */ void CardReader::diveToNewestFile(MediaFile parent, uint32_t &compareDateTime, MediaFile &outdir, char * const outname) { // Iterate the given parent dir parent.rewind(); for (dir_t p; parent.readDir(&p, longFilename) > 0;) { // If the item is a dir, recurse into it if (DIR_IS_SUBDIR(&p)) { // Get the name of the dir for opening char dirname[FILENAME_LENGTH]; createFilename(dirname, p); // Open the item in a new MediaFile MediaFile child; // child.close() in destructor if (child.open(&parent, dirname, O_READ)) diveToNewestFile(child, compareDateTime, outdir, outname); } else if (is_visible_entity(p)) { // Get the newer of the modified/created date and time const uint32_t modDateTime = uint32_t(p.lastWriteDate) << 16 | p.lastWriteTime, createDateTime = uint32_t(p.creationDate) << 16 | p.creationTime, newerDateTime = _MAX(modDateTime, createDateTime); // If a newer item is found overwrite the outdir and outname if (newerDateTime > compareDateTime) { compareDateTime = newerDateTime; outdir = parent; createFilename(outname, p); } } } } /** * Recurse the entire directory to find the newest file. * Make the found file the current selection. */ bool CardReader::selectNewestFile() { uint32_t dateTimeStorage = 0; MediaFile foundDir; char foundName[FILENAME_LENGTH]; foundName[0] = '\0'; diveToNewestFile(root, dateTimeStorage, foundDir, foundName); if (foundName[0]) { workDir = foundDir; workDir.rewind(); selectByName(workDir, foundName); //workDir.close(); // Not needed? return true; } return false; } #endif // ONE_CLICK_PRINT void CardReader::closefile(const bool store_location/*=false*/) { file.sync(); file.close(); flag.saving = flag.logging = false; sdpos = 0; TERN_(EMERGENCY_PARSER, emergency_parser.enable()); if (store_location) { //future: store printer state, filename and position for continuing a stopped print // so one can unplug the printer and continue printing the next day. } } // // Get info for a file in the working directory by index // void CardReader::selectFileByIndex(const int16_t nr) { #if ENABLED(SDSORT_CACHE_NAMES) if (nr < sort_count) { strcpy(filename, sortshort[nr]); strcpy(longFilename, sortnames[nr]); TERN_(HAS_FOLDER_SORTING, flag.filenameIsDir = IS_DIR(nr)); setBinFlag(strcmp_P(strrchr(filename, '.'), PSTR(".BIN")) == 0); return; } #endif workDir.rewind(); selectByIndex(workDir, nr); } // // Get info for a file in the working directory by DOS name // void CardReader::selectFileByName(const char * const match) { #if ENABLED(SDSORT_CACHE_NAMES) for (int16_t nr = 0; nr < sort_count; nr++) if (strcasecmp(match, sortshort[nr]) == 0) { strcpy(filename, sortshort[nr]); strcpy(longFilename, sortnames[nr]); TERN_(HAS_FOLDER_SORTING, flag.filenameIsDir = IS_DIR(nr)); setBinFlag(strcmp_P(strrchr(filename, '.'), PSTR(".BIN")) == 0); return; } #endif workDir.rewind(); selectByName(workDir, match); } /** * Dive to the given DOS 8.3 file path, with optional echo of the dive paths. * * On entry: * - The workDir points to the last-set navigation target by cd, cdup, cdroot, or diveToFile(true, ...) * * On exit: * - Your curDir pointer contains an MediaFile reference to the file's directory. * - If update_cwd was 'true' the workDir now points to the file's directory. * * Returns a pointer to the last segment (filename) of the given DOS 8.3 path. * On exit, inDirPtr contains an MediaFile reference to the file's directory. * * A nullptr result indicates an unrecoverable error. * * NOTE: End the path with a slash to dive to a folder. In this case the * returned filename will be blank (points to the end of the path). */ const char* CardReader::diveToFile(const bool update_cwd, MediaFile* &inDirPtr, const char * const path, const bool echo/*=false*/) { DEBUG_SECTION(est, "diveToFile", true); // Track both parent and subfolder static MediaFile newDir1, newDir2; MediaFile *sub = &newDir1, *startDirPtr; // Parsing the path string const char *atom_ptr = path; DEBUG_ECHOLNPGM(" path = '", path, "'"); if (path[0] == '/') { // Starting at the root directory? inDirPtr = &root; atom_ptr++; DEBUG_ECHOLNPGM(" CWD to root: ", hex_address((void*)inDirPtr)); if (update_cwd) workDirDepth = 0; // The cwd can be updated for the benefit of sub-programs } else inDirPtr = &workDir; // Dive from workDir (as set by the UI) startDirPtr = inDirPtr; DEBUG_ECHOLNPGM(" startDirPtr = ", hex_address((void*)startDirPtr)); while (atom_ptr) { // Find next subdirectory delimiter const char * const name_end = strchr(atom_ptr, '/'); // Last atom in the path? Item found. if (name_end <= atom_ptr) break; // Isolate the next subitem name const uint8_t len = name_end - atom_ptr; char dosSubdirname[len + 1]; strlcpy(dosSubdirname, atom_ptr, len + 1); if (echo) SERIAL_ECHOLN(dosSubdirname); DEBUG_ECHOLNPGM(" sub = ", hex_address((void*)sub)); // Open inDirPtr (closing first) sub->close(); if (!sub->open(inDirPtr, dosSubdirname, O_READ)) { openFailed(dosSubdirname); atom_ptr = nullptr; break; } // Close inDirPtr if not at starting-point if (inDirPtr != startDirPtr) { DEBUG_ECHOLNPGM(" closing inDirPtr: ", hex_address((void*)inDirPtr)); inDirPtr->close(); } // inDirPtr now subDir inDirPtr = sub; DEBUG_ECHOLNPGM(" inDirPtr = sub: ", hex_address((void*)inDirPtr)); // Update workDirParents and workDirDepth if (update_cwd) { DEBUG_ECHOLNPGM(" update_cwd"); if (workDirDepth < MAX_DIR_DEPTH) workDirParents[workDirDepth++] = *inDirPtr; } // Point sub at the other scratch object sub = (inDirPtr != &newDir1) ? &newDir1 : &newDir2; DEBUG_ECHOLNPGM(" swapping sub = ", hex_address((void*)sub)); // Next path atom address atom_ptr = name_end + 1; } if (update_cwd) { workDir = *inDirPtr; DEBUG_ECHOLNPGM(" final workDir = ", hex_address((void*)inDirPtr)); flag.workDirIsRoot = (workDirDepth == 0); TERN_(SDCARD_SORT_ALPHA, presort()); } DEBUG_ECHOLNPGM(" returning string ", atom_ptr ?: "nullptr"); return atom_ptr; } void CardReader::cd(const char * relpath) { MediaFile newDir, *parent = &getWorkDir(); if (newDir.open(parent, relpath, O_READ)) { workDir = newDir; flag.workDirIsRoot = false; if (workDirDepth < MAX_DIR_DEPTH) workDirParents[workDirDepth++] = workDir; nrItems = -1; TERN_(SDCARD_SORT_ALPHA, presort()); } else SERIAL_ECHO_MSG(STR_SD_CANT_ENTER_SUBDIR, relpath); } int8_t CardReader::cdup() { if (workDirDepth > 0) { // At least 1 dir has been saved nrItems = -1; workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none TERN_(SDCARD_SORT_ALPHA, presort()); } if (!workDirDepth) flag.workDirIsRoot = true; return workDirDepth; } void CardReader::cdroot() { workDir = root; flag.workDirIsRoot = true; workDirDepth = 0; nrItems = -1; TERN_(SDCARD_SORT_ALPHA, presort()); } #if ENABLED(SDCARD_SORT_ALPHA) /** * Get the name of a file in the working directory by sort-index */ void CardReader::selectFileByIndexSorted(const int16_t nr) { selectFileByIndex(SortFlag(TERN1(SDSORT_GCODE, sort_alpha != AS_OFF)) && (nr < sort_count) ? sort_order[nr] : nr); } #if ENABLED(SDSORT_USES_RAM) #if ENABLED(SDSORT_DYNAMIC_RAM) // Use dynamic method to copy long filename #define SET_SORTNAME(I) (sortnames[I] = strdup(longest_filename())) #if ENABLED(SDSORT_CACHE_NAMES) // When caching also store the short name, since // we're replacing the selectFileByIndex() behavior. #define SET_SORTSHORT(I) (sortshort[I] = strdup(filename)) #else #define SET_SORTSHORT(I) NOOP #endif #else // Copy filenames into the static array #define _SET_SORTNAME(I) strlcpy(sortnames[I], longest_filename(), sizeof(sortnames[I])) #if SORTED_LONGNAME_MAXLEN == LONG_FILENAME_LENGTH // Short name sorting always use LONG_FILENAME_LENGTH with no trailing nul #define SET_SORTNAME(I) _SET_SORTNAME(I) #else // Copy multiple name blocks. Add a nul for the longest case. #define SET_SORTNAME(I) do{ _SET_SORTNAME(I); sortnames[I][SORTED_LONGNAME_MAXLEN] = '\0'; }while(0) #endif #if ENABLED(SDSORT_CACHE_NAMES) #define SET_SORTSHORT(I) strcpy(sortshort[I], filename) #else #define SET_SORTSHORT(I) NOOP #endif #endif #endif /** * Read all the files and produce a sort key * * We can do this in 3 ways... * - Minimal RAM: Read two filenames at a time sorting along... * - Some RAM: Buffer the directory just for this sort * - Most RAM: Buffer the directory and return filenames from RAM */ void CardReader::presort() { // Throw away old sort index flush_presort(); int16_t fileCnt = get_num_items(); // Sorting may be turned off if (TERN0(SDSORT_GCODE, sort_alpha == AS_OFF)) return; // If there are files, sort up to the limit if (fileCnt > 0) { // Never sort more than the max allowed // If you use folders to organize, 20 may be enough NOMORE(fileCnt, int16_t(SDSORT_LIMIT)); // Sort order is always needed. May be static or dynamic. TERN_(SDSORT_DYNAMIC_RAM, sort_order = new uint8_t[fileCnt]); // Use RAM to store the entire directory during pre-sort. // SDSORT_LIMIT should be set to prevent over-allocation. #if ENABLED(SDSORT_USES_RAM) // If using dynamic ram for names, allocate on the heap. #if ENABLED(SDSORT_CACHE_NAMES) #if ENABLED(SDSORT_DYNAMIC_RAM) sortshort = new char*[fileCnt]; sortnames = new char*[fileCnt]; #endif #elif ENABLED(SDSORT_USES_STACK) char sortnames[fileCnt][SORTED_LONGNAME_STORAGE]; #endif // Folder sorting needs 1 bit per entry for flags. #if HAS_FOLDER_SORTING #if ENABLED(SDSORT_DYNAMIC_RAM) isDir = new uint8_t[(fileCnt + 7) >> 3]; // Allocate space with 'new' #elif ENABLED(SDSORT_USES_STACK) uint8_t isDir[(fileCnt + 7) >> 3]; // Use stack in this scope #endif #endif #else // !SDSORT_USES_RAM // By default re-read the names from SD for every compare // retaining only two filenames at a time. This is very // slow but is safest and uses minimal RAM. char name1[LONG_FILENAME_LENGTH]; #endif if (fileCnt > 1) { // Init sort order. for (int16_t i = 0; i < fileCnt; i++) { sort_order[i] = i; // If using RAM then read all filenames now. #if ENABLED(SDSORT_USES_RAM) selectFileByIndex(i); SET_SORTNAME(i); SET_SORTSHORT(i); //char out[30]; //sprintf_P(out, PSTR("---- %i %s %s"), i, flag.filenameIsDir ? "D" : " ", sortnames[i]); //SERIAL_ECHOLN(out); #if HAS_FOLDER_SORTING const uint16_t bit = i & 0x07, ind = i >> 3; if (bit == 0) isDir[ind] = 0x00; if (flag.filenameIsDir) SBI(isDir[ind], bit); #endif #endif } // Bubble Sort for (int16_t i = fileCnt; --i;) { bool didSwap = false; int16_t o1 = sort_order[0]; #if DISABLED(SDSORT_USES_RAM) selectFileByIndex(o1); // Pre-fetch the first entry and save it strcpy(name1, longest_filename()); // so the loop only needs one fetch #if HAS_FOLDER_SORTING bool dir1 = flag.filenameIsDir; #endif #endif for (int16_t j = 0; j < i; ++j) { const int16_t o2 = sort_order[j + 1]; // Compare names from the array or just the two buffered names auto _sort_cmp_file = [](char * const n1, char * const n2) -> bool { const bool sort = strcasecmp(n1, n2) > 0; return (TERN(SDSORT_GCODE, card.sort_alpha == AS_REV, ENABLED(SDSORT_REVERSE))) ? !sort : sort; }; #define _SORT_CMP_FILE() _sort_cmp_file(TERN(SDSORT_USES_RAM, sortnames[o1], name1), TERN(SDSORT_USES_RAM, sortnames[o2], name2)) #if HAS_FOLDER_SORTING #if ENABLED(SDSORT_USES_RAM) // Folder sorting needs an index and bit to test for folder-ness. #define _SORT_CMP_DIR(fs) (IS_DIR(o1) == IS_DIR(o2) ? _SORT_CMP_FILE() : IS_DIR(fs > 0 ? o1 : o2)) #else #define _SORT_CMP_DIR(fs) ((dir1 == flag.filenameIsDir) ? _SORT_CMP_FILE() : (fs > 0 ? dir1 : !dir1)) #endif #endif // The most economical method reads names as-needed // throughout the loop. Slow if there are many. #if DISABLED(SDSORT_USES_RAM) selectFileByIndex(o2); const bool dir2 = flag.filenameIsDir; char * const name2 = longest_filename(); // use the string in-place #endif // !SDSORT_USES_RAM // Sort the current pair according to settings. if ( #if HAS_FOLDER_SORTING #if ENABLED(SDSORT_GCODE) sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_FILE() #else _SORT_CMP_DIR(SDSORT_FOLDERS) #endif #else _SORT_CMP_FILE() #endif ) { // Reorder the index, indicate that sorting happened // Note that the next o1 will be the current o1. No new fetch needed. sort_order[j] = o2; sort_order[j + 1] = o1; didSwap = true; } else { // The next o1 is the current o2. No new fetch needed. o1 = o2; #if DISABLED(SDSORT_USES_RAM) TERN_(HAS_FOLDER_SORTING, dir1 = dir2); strcpy(name1, name2); #endif } } if (!didSwap) break; } // Using RAM but not keeping names around #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES) #if ENABLED(SDSORT_DYNAMIC_RAM) for (int16_t i = 0; i < fileCnt; ++i) free(sortnames[i]); TERN_(HAS_FOLDER_SORTING, delete [] isDir); #endif #endif } else { sort_order[0] = 0; #if ALL(SDSORT_USES_RAM, SDSORT_CACHE_NAMES) #if ENABLED(SDSORT_DYNAMIC_RAM) sortnames = new char*[1]; sortshort = new char*[1]; #endif selectFileByIndex(0); SET_SORTNAME(0); SET_SORTSHORT(0); #if ALL(HAS_FOLDER_SORTING, SDSORT_DYNAMIC_RAM) isDir = new uint8_t[1]; isDir[0] = flag.filenameIsDir; #endif #endif } sort_count = fileCnt; } } void CardReader::flush_presort() { if (sort_count > 0) { #if ENABLED(SDSORT_DYNAMIC_RAM) delete [] sort_order; #if ENABLED(SDSORT_CACHE_NAMES) for (uint8_t i = 0; i < sort_count; ++i) { free(sortshort[i]); // strdup free(sortnames[i]); // strdup } delete [] sortshort; delete [] sortnames; #endif #endif sort_count = 0; } } #endif // SDCARD_SORT_ALPHA int16_t CardReader::get_num_items() { if (!isMounted()) return 0; if (nrItems < 0) nrItems = countVisibleItems(workDir); return nrItems; } // // Return from procedure or close out the Print Job // void CardReader::fileHasFinished() { file.close(); #if HAS_MEDIA_SUBCALLS if (file_subcall_ctr > 0) { // Resume calling file after closing procedure file_subcall_ctr--; openFileRead(proc_filenames[file_subcall_ctr], 2); // 2 = Returning from sub-procedure setIndex(filespos[file_subcall_ctr]); startOrResumeFilePrinting(); return; } #endif endFilePrintNow(TERN_(SD_RESORT, true)); flag.sdprintdone = true; // Stop getting bytes from the SD card marlin_state = MF_SD_COMPLETE; // Tell Marlin to enqueue M1001 soon } #if ENABLED(AUTO_REPORT_SD_STATUS) AutoReporter<CardReader::AutoReportSD> CardReader::auto_reporter; #endif #if ENABLED(POWER_LOSS_RECOVERY) bool CardReader::jobRecoverFileExists() { const bool exists = recovery.file.open(&root, recovery.filename, O_READ); if (exists) recovery.file.close(); return exists; } void CardReader::openJobRecoveryFile(const bool read) { if (!isMounted()) return; if (recovery.file.isOpen()) return; if (!recovery.file.open(&root, recovery.filename, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC)) openFailed(recovery.filename); else if (!read) echo_write_to_file(recovery.filename); } // Removing the job recovery file currently requires closing // the file being printed, so during SD printing the file should // be zeroed and written instead of deleted. void CardReader::removeJobRecoveryFile() { if (jobRecoverFileExists()) { recovery.init(); removeFile(recovery.filename); #if ENABLED(DEBUG_POWER_LOSS_RECOVERY) SERIAL_ECHOLN(F("Power-loss file delete"), jobRecoverFileExists() ? F(" failed.") : F("d.")); #endif } } #endif // POWER_LOSS_RECOVERY #endif // HAS_MEDIA
2301_81045437/Marlin
Marlin/src/sd/cardreader.cpp
C++
agpl-3.0
44,603
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfig.h" #if HAS_MEDIA extern const char M23_STR[], M24_STR[]; #if ENABLED(SDCARD_SORT_ALPHA) #if ENABLED(SDSORT_DYNAMIC_RAM) #define SD_RESORT 1 #endif #ifndef SDSORT_FOLDERS #define SDSORT_FOLDERS 0 #endif #if SDSORT_FOLDERS || ENABLED(SDSORT_GCODE) #define HAS_FOLDER_SORTING 1 #endif #endif #define MAX_DIR_DEPTH 10 // Maximum folder depth #define MAXDIRNAMELENGTH 8 // DOS folder name size #define MAXPATHNAMELENGTH (1 + (MAXDIRNAMELENGTH + 1) * (MAX_DIR_DEPTH) + 1 + FILENAME_LENGTH) // "/" + N * ("ADIRNAME/") + "filename.ext" #include "SdFile.h" #include "disk_io_driver.h" #if ENABLED(USB_FLASH_DRIVE_SUPPORT) #include "usb_flashdrive/Sd2Card_FlashDrive.h" #endif #if NEED_SD2CARD_SDIO #include "Sd2Card_sdio.h" #elif NEED_SD2CARD_SPI #include "Sd2Card.h" #endif #if ENABLED(MULTI_VOLUME) #define SV_SD_ONBOARD 1 #define SV_USB_FLASH_DRIVE 2 #define _VOLUME_ID(N) _CAT(SV_, N) #define SHARED_VOLUME_IS(N) (DEFAULT_SHARED_VOLUME == _VOLUME_ID(N)) #if !SHARED_VOLUME_IS(SD_ONBOARD) && !SHARED_VOLUME_IS(USB_FLASH_DRIVE) #error "DEFAULT_SHARED_VOLUME must be either SD_ONBOARD or USB_FLASH_DRIVE." #endif #else #define SHARED_VOLUME_IS(...) 0 #endif typedef struct { bool saving:1, logging:1, sdprinting:1, sdprintdone:1, mounted:1, filenameIsDir:1, workDirIsRoot:1, abort_sd_printing:1 #if DO_LIST_BIN_FILES , filenameIsBin:1 #endif #if ENABLED(BINARY_FILE_TRANSFER) , binary_mode:1 #endif ; } card_flags_t; enum ListingFlags : uint8_t { LS_LONG_FILENAME, LS_ONLY_BIN, LS_TIMESTAMP }; enum SortFlag : int8_t { AS_REV = -1, AS_OFF, AS_FWD, AS_ALSO_REV }; #if ENABLED(AUTO_REPORT_SD_STATUS) #include "../libs/autoreport.h" #endif class CardReader { public: static card_flags_t flag; // Flags (above) static char filename[FILENAME_LENGTH], // DOS 8.3 filename of the selected item longFilename[LONG_FILENAME_LENGTH]; // Long name of the selected item // Fast! binary file transfer #if ENABLED(BINARY_FILE_TRANSFER) #if HAS_MULTI_SERIAL static serial_index_t transfer_port_index; #else static constexpr serial_index_t transfer_port_index = 0; #endif #endif CardReader(); static void changeMedia(DiskIODriver *_driver) { driver = _driver; } static MediaFile getroot() { return root; } static void mount(); static void release(); static bool isMounted() { return flag.mounted; } // Handle media insert/remove static void manage_media(); // SD Card Logging static void openLogFile(const char * const path); static void write_command(char * const buf); #if DISABLED(NO_SD_AUTOSTART) // Auto-Start auto#.g file handling static uint8_t autofile_index; // Next auto#.g index to run, plus one. Ignored by autofile_check when zero. static void autofile_begin(); // Begin check. Called automatically after boot-up. static bool autofile_check(); // Check for the next auto-start file and run it. static void autofile_cancel() { autofile_index = 0; } #endif #if ENABLED(ONE_CLICK_PRINT) static bool one_click_check(); // Check for the newest file and prompt to run it. static void diveToNewestFile(MediaFile parent, uint32_t &compareDateTime, MediaFile &outdir, char * const outname); static bool selectNewestFile(); #endif // Basic file ops static void openFileRead(const char * const path, const uint8_t subcall=0); static void openFileWrite(const char * const path); static void closefile(const bool store_location=false); static bool fileExists(const char * const name); static void removeFile(const char * const name); static char* longest_filename() { return longFilename[0] ? longFilename : filename; } #if ENABLED(LONG_FILENAME_HOST_SUPPORT) static void printLongPath(char * const path); // Used by M33 static void getLongPath(char * const pathLong, char * const pathShort); // Used by anycubic_vyper #endif // Working Directory for SD card menu static void cdroot(); static void cd(const char *relpath); static int8_t cdup(); static int16_t get_num_items(); // Select a file static void selectFileByIndex(const int16_t nr); static void selectFileByName(const char * const match); // (working directory only) // Print job static void report_status(); static void getAbsFilenameInCWD(char *dst); static void printSelectedFilename(); static void openAndPrintFile(const char *name); // (working directory or full path) static void startOrResumeFilePrinting(); static void endFilePrintNow(TERN_(SD_RESORT, const bool re_sort=false)); static void abortFilePrintNow(TERN_(SD_RESORT, const bool re_sort=false)); static void fileHasFinished(); static void abortFilePrintSoon() { flag.abort_sd_printing = isFileOpen(); } static void pauseSDPrint() { flag.sdprinting = false; } static bool isPrinting() { return flag.sdprinting; } static bool isPaused() { return isFileOpen() && !isPrinting(); } #if HAS_PRINT_PROGRESS_PERMYRIAD static uint16_t permyriadDone() { if (flag.sdprintdone) return 10000; if (isFileOpen() && filesize) return sdpos / ((filesize + 9999) / 10000); return 0; } #endif static uint8_t percentDone() { if (flag.sdprintdone) return 100; if (isFileOpen() && filesize) return sdpos / ((filesize + 99) / 100); return 0; } /** * Dive down to a relative or absolute path. * Relative paths apply to the workDir. * * update_cwd: Pass 'true' to update the workDir on success. * inDirPtr: On exit your pointer points to the target MediaFile. * A nullptr indicates failure. * path: Start with '/' for abs path. End with '/' to get a folder ref. * echo: Set 'true' to print the path throughout the loop. */ static const char* diveToFile(const bool update_cwd, MediaFile* &inDirPtr, const char * const path, const bool echo=false); #if ENABLED(SDCARD_SORT_ALPHA) static void presort(); static void selectFileByIndexSorted(const int16_t nr); #if ENABLED(SDSORT_GCODE) FORCE_INLINE static void setSortOn(const SortFlag f) { sort_alpha = (f == AS_ALSO_REV) ? AS_REV : f; presort(); } FORCE_INLINE static void setSortFolders(const int8_t i) { sort_folders = i; presort(); } //FORCE_INLINE static void setSortReverse(bool b) { sort_reverse = b; } #endif #else FORCE_INLINE static void selectFileByIndexSorted(const int16_t nr) { selectFileByIndex(TERN(SDCARD_RATHERRECENTFIRST, get_num_items() - 1 - nr, (nr))); } #endif static void ls(const uint8_t lsflags=0); #if ENABLED(POWER_LOSS_RECOVERY) static bool jobRecoverFileExists(); static void openJobRecoveryFile(const bool read); static void removeJobRecoveryFile(); #endif // Binary flag for the current file static bool fileIsBinary() { return TERN0(DO_LIST_BIN_FILES, flag.filenameIsBin); } static void setBinFlag(const bool bin) { TERN(DO_LIST_BIN_FILES, flag.filenameIsBin = bin, UNUSED(bin)); } // Current Working Dir - Set by cd, cdup, cdroot, and diveToFile(true, ...) static char* getWorkDirName() { workDir.getDosName(filename); return filename; } static MediaFile& getWorkDir() { return workDir.isOpen() ? workDir : root; } // Print File stats static uint32_t getFileSize() { return filesize; } static uint32_t getIndex() { return sdpos; } static bool isFileOpen() { return isMounted() && file.isOpen(); } static bool eof() { return getIndex() >= getFileSize(); } // File data operations static int16_t get() { int16_t out = (int16_t)file.read(); sdpos = file.curPosition(); return out; } static int16_t read(void *buf, uint16_t nbyte) { return file.isOpen() ? file.read(buf, nbyte) : -1; } static int16_t write(void *buf, uint16_t nbyte) { return file.isOpen() ? file.write(buf, nbyte) : -1; } static void setIndex(const uint32_t index) { file.seekSet((sdpos = index)); } // TODO: rename to diskIODriver() static DiskIODriver* diskIODriver() { return driver; } #if ENABLED(AUTO_REPORT_SD_STATUS) // // SD Auto Reporting // struct AutoReportSD { static void report() { report_status(); } }; static AutoReporter<AutoReportSD> auto_reporter; #endif #if SHARED_VOLUME_IS(USB_FLASH_DRIVE) || ENABLED(USB_FLASH_DRIVE_SUPPORT) #define HAS_USB_FLASH_DRIVE 1 static DiskIODriver_USBFlash media_driver_usbFlash; #endif #if NEED_SD2CARD_SDIO || NEED_SD2CARD_SPI typedef TERN(NEED_SD2CARD_SDIO, DiskIODriver_SDIO, DiskIODriver_SPI_SD) sdcard_driver_t; static sdcard_driver_t media_driver_sdcard; #endif private: // // Working directory and parents // static MediaFile root, workDir, workDirParents[MAX_DIR_DEPTH]; static uint8_t workDirDepth; static int16_t nrItems; // Cache the total count // // Alphabetical file and folder sorting // #if ENABLED(SDCARD_SORT_ALPHA) static int16_t sort_count; // Count of sorted items in the current directory #if ENABLED(SDSORT_GCODE) static SortFlag sort_alpha; // Sorting: REV, OFF, FWD static int8_t sort_folders; // Folder sorting before/none/after //static bool sort_reverse; // Flag to enable / disable reverse sorting #endif // By default the sort index is statically allocated #if ENABLED(SDSORT_DYNAMIC_RAM) static uint8_t *sort_order; #else static uint8_t sort_order[SDSORT_LIMIT]; #endif #if ALL(SDSORT_USES_RAM, SDSORT_CACHE_NAMES) && DISABLED(SDSORT_DYNAMIC_RAM) #define SORTED_LONGNAME_MAXLEN (SDSORT_CACHE_VFATS) * (FILENAME_LENGTH) #define SORTED_LONGNAME_STORAGE (SORTED_LONGNAME_MAXLEN + 1) #else #define SORTED_LONGNAME_MAXLEN LONG_FILENAME_LENGTH #define SORTED_LONGNAME_STORAGE SORTED_LONGNAME_MAXLEN #endif // Cache filenames to speed up SD menus. #if ENABLED(SDSORT_USES_RAM) // If using dynamic ram for names, allocate on the heap. #if ENABLED(SDSORT_CACHE_NAMES) #if ENABLED(SDSORT_DYNAMIC_RAM) static char **sortshort, **sortnames; #else static char sortshort[SDSORT_LIMIT][FILENAME_LENGTH]; #endif #endif #if (ENABLED(SDSORT_CACHE_NAMES) && DISABLED(SDSORT_DYNAMIC_RAM)) || NONE(SDSORT_CACHE_NAMES, SDSORT_USES_STACK) static char sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE]; #endif // Folder sorting uses an isDir array when caching items. #if HAS_FOLDER_SORTING #if ENABLED(SDSORT_DYNAMIC_RAM) static uint8_t *isDir; #elif ENABLED(SDSORT_CACHE_NAMES) || DISABLED(SDSORT_USES_STACK) static uint8_t isDir[(SDSORT_LIMIT + 7) >> 3]; #endif #endif #endif // SDSORT_USES_RAM #endif // SDCARD_SORT_ALPHA static DiskIODriver *driver; static MarlinVolume volume; static MediaFile file; static uint32_t filesize, // Total size of the current file, in bytes sdpos; // Index most recently read (one behind file.getPos) // // Procedure calls to other files // #if HAS_MEDIA_SUBCALLS static uint8_t file_subcall_ctr; static uint32_t filespos[SD_PROCEDURE_DEPTH]; static char proc_filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH]; #endif // // Directory items // static bool is_visible_entity(const dir_t &p OPTARG(CUSTOM_FIRMWARE_UPLOAD, const bool onlyBin=false)); static int16_t countVisibleItems(MediaFile dir); static void selectByIndex(MediaFile dir, const int16_t index); static void selectByName(MediaFile dir, const char * const match); static void printListing( MediaFile parent, const char * const prepend, const uint8_t lsflags OPTARG(LONG_FILENAME_HOST_SUPPORT, const char * const prependLong=nullptr) ); #if ENABLED(SDCARD_SORT_ALPHA) static void flush_presort(); #endif }; #if ENABLED(USB_FLASH_DRIVE_SUPPORT) #define IS_SD_INSERTED() DiskIODriver_USBFlash::isInserted() #elif HAS_SD_DETECT #define IS_SD_INSERTED() (READ(SD_DETECT_PIN) == SD_DETECT_STATE) #else // No card detect line? Assume the card is inserted. #define IS_SD_INSERTED() true #endif #define IS_SD_PRINTING() (card.flag.sdprinting && !card.flag.abort_sd_printing) #define IS_SD_FETCHING() (!card.flag.sdprintdone && IS_SD_PRINTING()) #define IS_SD_PAUSED() card.isPaused() #define IS_SD_FILE_OPEN() card.isFileOpen() extern CardReader card; #else // !HAS_MEDIA #define IS_SD_PRINTING() false #define IS_SD_FETCHING() false #define IS_SD_PAUSED() false #define IS_SD_FILE_OPEN() false #define LONG_FILENAME_LENGTH 0 #endif // !HAS_MEDIA
2301_81045437/Marlin
Marlin/src/sd/cardreader.h
C++
agpl-3.0
13,701
/** * Marlin 3D Printer Firmware * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once #include <stdint.h> #include "SdInfo.h" /** * DiskIO Interface * * Interface for low level disk io */ class DiskIODriver { public: /** * Initialize an SD flash memory card with default clock rate and chip * select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). * * \return true for success or false for failure. */ virtual bool init(const uint8_t sckRateID, const pin_t chipSelectPin) = 0; //TODO: only for SPI /** * Read a card's CSD register. The CSD contains Card-Specific Data that * provides information regarding access to the card's contents. * * \param[out] csd pointer to area for returned data. * * \return true for success or false for failure. */ virtual bool readCSD(csd_t * const csd) = 0; virtual bool readStart(const uint32_t block) = 0; virtual bool readData(uint8_t * const dst) = 0; virtual bool readStop() = 0; virtual bool writeStart(const uint32_t block, const uint32_t) = 0; virtual bool writeData(const uint8_t* src) = 0; virtual bool writeStop() = 0; virtual bool readBlock(const uint32_t block, uint8_t * const dst) = 0; virtual bool writeBlock(const uint32_t blockNumber, const uint8_t * const src) = 0; virtual uint32_t cardSize() = 0; virtual bool isReady() = 0; virtual void idle() = 0; };
2301_81045437/Marlin
Marlin/src/sd/disk_io_driver.h
C++
agpl-3.0
2,194
/** * Marlin 3D Printer Firmware * Copyright (c) 2023 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * Marlin Storage Architecture: * * DiskIODriver: * Do all low level IO with the underline hardware or block device: SPI, SDIO, OTG * * FilesystemDriver: * Handle the filesystem format / implementation. Uses the io driver to read and write data. * Sd2Card is the very first and current filesystem implementation on Marlin, supporting FAT. * FatFS - Work in progress. * * * Marlin Abstractions: * * Using this names allow us to isolate filesystem driver code, keeping all Marlin code agnostic. * * MediaFilesystem: * Abstraction of systemwide filesystem operation. * * MarlinVolume: * Abstraction of a filesystem volume. * * MediaFile: * Abstraction of a generic file. Using this name allow us to isolate filesystem driver code, * keeping all Marlin code agnostic. * * PrintFromStorage: * Class to handle printing from any attached storage. * */ /* Interface definition. Doesn't need to be compiled, as we use duck typing, allowing drivers to just use type alias. Class MarlinVolume { public: }; Class MediaFile { public: }; Class MediaFilesystem { public: static void init(); static MarlinVolume* openVolume(const char *); }; */
2301_81045437/Marlin
Marlin/src/sd/storage.h
C++
agpl-3.0
2,062
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #include "../../inc/MarlinConfigPre.h" /** * Adjust USB_DEBUG to select debugging verbosity. * 0 - no debug messages * 1 - basic insertion/removal messages * 2 - show USB state transitions * 3 - perform block range checking * 4 - print each block access */ #define USB_DEBUG 1 #define USB_STARTUP_DELAY 0 // uncomment to get 'printf' console debugging. NOT FOR UNO! //#define HOST_DEBUG(...) {char s[255]; sprintf(s,__VA_ARGS__); SERIAL_ECHOLNPGM("UHS:",s);} //#define BS_HOST_DEBUG(...) {char s[255]; sprintf(s,__VA_ARGS__); SERIAL_ECHOLNPGM("UHS:",s);} //#define MAX_HOST_DEBUG(...) {char s[255]; sprintf(s,__VA_ARGS__); SERIAL_ECHOLNPGM("UHS:",s);} #if ENABLED(USB_FLASH_DRIVE_SUPPORT) #include "../../MarlinCore.h" #include "../../core/serial.h" #include "../../module/temperature.h" #if DISABLED(USE_OTG_USB_HOST) && !PINS_EXIST(USB_CS, USB_INTR) #error "USB_FLASH_DRIVE_SUPPORT requires USB_CS_PIN and USB_INTR_PIN to be defined." #endif #if ENABLED(USE_UHS3_USB) #define NO_AUTO_SPEED #define UHS_MAX3421E_SPD 8000000 >> SD_SPI_SPEED #define UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE 1 #define UHS_HOST_MAX_INTERFACE_DRIVERS 2 #define MASS_MAX_SUPPORTED_LUN 1 #define USB_HOST_SERIAL MYSERIAL1 // Workaround for certain issues with UHS3 #define SKIP_PAGE3F // Required for IOGEAR media adapter #define USB_NO_TEST_UNIT_READY // Required for removable media adapter #define USB_HOST_MANUAL_POLL // Optimization to shut off IRQ automatically // Workarounds to keep Marlin's watchdog timer from barking... void marlin_yield() { thermalManager.task(); } #define SYSTEM_OR_SPECIAL_YIELD(...) marlin_yield(); #define delay(x) safe_delay(x) #define LOAD_USB_HOST_SYSTEM #define LOAD_USB_HOST_SHIELD #define LOAD_UHS_BULK_STORAGE #define MARLIN_UHS_WRITE_SS(v) WRITE(USB_CS_PIN, v) #define MARLIN_UHS_READ_IRQ() READ(USB_INTR_PIN) #include "lib-uhs3/UHS_host/UHS_host.h" MAX3421E_HOST usb(USB_CS_PIN, USB_INTR_PIN); UHS_Bulk_Storage bulk(&usb); #define UHS_START (usb.Init() == 0) #define UHS_STATE(state) UHS_USB_HOST_STATE_##state #elif ENABLED(USE_OTG_USB_HOST) #if HAS_SD_HOST_DRIVE #include HAL_PATH(../.., msc_sd.h) #endif #include HAL_PATH(../.., usb_host.h) #define UHS_START usb.start() #define rREVISION 0 #define UHS_STATE(state) USB_STATE_##state #else #include "lib-uhs2/Usb.h" #include "lib-uhs2/masstorage.h" USB usb; BulkOnly bulk(&usb); #define UHS_START usb.start() #define UHS_STATE(state) USB_STATE_##state #endif #include "Sd2Card_FlashDrive.h" #include "../../lcd/marlinui.h" static enum { UNINITIALIZED, DO_STARTUP, WAIT_FOR_DEVICE, WAIT_FOR_LUN, MEDIA_READY, MEDIA_ERROR } state; #if USB_DEBUG >= 3 uint32_t lun0_capacity; #endif bool DiskIODriver_USBFlash::usbStartup() { if (state <= DO_STARTUP) { SERIAL_ECHOPGM("Starting USB host..."); if (!UHS_START) { SERIAL_ECHOLNPGM(" failed."); LCD_MESSAGE(MSG_MEDIA_USB_FAILED); return false; } // SPI quick test - check revision register switch (usb.regRd(rREVISION)) { case 0x01: SERIAL_ECHOLNPGM("rev.01 started"); break; case 0x12: SERIAL_ECHOLNPGM("rev.02 started"); break; case 0x13: SERIAL_ECHOLNPGM("rev.03 started"); break; default: SERIAL_ECHOLNPGM("started. rev unknown."); break; } state = WAIT_FOR_DEVICE; } return true; } // The USB library needs to be called periodically to detect USB thumbdrive // insertion and removals. Call this idle() function periodically to allow // the USB library to monitor for such events. This function also takes care // of initializing the USB library for the first time. void DiskIODriver_USBFlash::idle() { usb.Task(); const uint8_t task_state = usb.getUsbTaskState(); #if USB_DEBUG >= 2 if (state > DO_STARTUP) { static uint8_t laststate = 232; if (task_state != laststate) { laststate = task_state; #define UHS_USB_DEBUG(x,y) case UHS_STATE(x): SERIAL_ECHOLNPGM(y); break switch (task_state) { UHS_USB_DEBUG(IDLE, "IDLE"); UHS_USB_DEBUG(RESET_DEVICE, "RESET_DEVICE"); UHS_USB_DEBUG(RESET_NOT_COMPLETE, "RESET_NOT_COMPLETE"); UHS_USB_DEBUG(DEBOUNCE, "DEBOUNCE"); UHS_USB_DEBUG(DEBOUNCE_NOT_COMPLETE, "DEBOUNCE_NOT_COMPLETE"); UHS_USB_DEBUG(WAIT_SOF, "WAIT_SOF"); UHS_USB_DEBUG(ERROR, "ERROR"); UHS_USB_DEBUG(CONFIGURING, "CONFIGURING"); UHS_USB_DEBUG(CONFIGURING_DONE, "CONFIGURING_DONE"); UHS_USB_DEBUG(RUNNING, "RUNNING"); default: SERIAL_ECHOLNPGM("UHS_USB_HOST_STATE: ", task_state); break; } } } #endif static millis_t next_state_ms = millis(); #define GOTO_STATE_AFTER_DELAY(STATE, DELAY) do{ state = STATE; next_state_ms = millis() + DELAY; }while(0) if (ELAPSED(millis(), next_state_ms)) { GOTO_STATE_AFTER_DELAY(state, 250); // Default delay switch (state) { case UNINITIALIZED: #ifndef MANUAL_USB_STARTUP GOTO_STATE_AFTER_DELAY( DO_STARTUP, USB_STARTUP_DELAY ); #endif break; case DO_STARTUP: usbStartup(); break; case WAIT_FOR_DEVICE: if (task_state == UHS_STATE(RUNNING)) { #if USB_DEBUG >= 1 SERIAL_ECHOLNPGM("USB device inserted"); #endif GOTO_STATE_AFTER_DELAY( WAIT_FOR_LUN, 250 ); } break; case WAIT_FOR_LUN: /* USB device is inserted, but if it is an SD card, * adapter it may not have an SD card in it yet. */ if (bulk.LUNIsGood(0)) { #if USB_DEBUG >= 1 SERIAL_ECHOLNPGM("LUN is good"); #endif GOTO_STATE_AFTER_DELAY( MEDIA_READY, 100 ); } else { #ifdef USB_HOST_MANUAL_POLL // Make sure we catch disconnect events usb.busprobe(); usb.VBUS_changed(); #endif #if USB_DEBUG >= 1 SERIAL_ECHOLNPGM("Waiting for media"); #endif LCD_MESSAGE(MSG_MEDIA_WAITING); GOTO_STATE_AFTER_DELAY(state, 2000); } break; case MEDIA_READY: break; case MEDIA_ERROR: break; } if (state > WAIT_FOR_DEVICE && task_state != UHS_STATE(RUNNING)) { // Handle device removal events #if USB_DEBUG >= 1 SERIAL_ECHOLNPGM("USB device removed"); #endif if (state != MEDIA_READY) LCD_MESSAGE(MSG_MEDIA_USB_REMOVED); GOTO_STATE_AFTER_DELAY(WAIT_FOR_DEVICE, 0); } else if (state > WAIT_FOR_LUN && !bulk.LUNIsGood(0)) { // Handle media removal events #if USB_DEBUG >= 1 SERIAL_ECHOLNPGM("Media removed"); #endif LCD_MESSAGE(MSG_MEDIA_REMOVED); GOTO_STATE_AFTER_DELAY(WAIT_FOR_DEVICE, 0); } else if (task_state == UHS_STATE(ERROR)) { LCD_MESSAGE(MSG_MEDIA_READ_ERROR); GOTO_STATE_AFTER_DELAY(MEDIA_ERROR, 0); } } } // Marlin calls this function to check whether an USB drive is inserted. // This is equivalent to polling the SD_DETECT when using SD cards. bool DiskIODriver_USBFlash::isInserted() { return state == MEDIA_READY; } bool DiskIODriver_USBFlash::isReady() { return state > DO_STARTUP && usb.getUsbTaskState() == UHS_STATE(RUNNING); } // Marlin calls this to initialize an SD card once it is inserted. bool DiskIODriver_USBFlash::init(const uint8_t, const pin_t) { if (!isInserted()) return false; #if USB_DEBUG >= 1 const uint32_t sectorSize = bulk.GetSectorSize(0); if (sectorSize != 512) { SERIAL_ECHOLNPGM("Expecting sector size of 512. Got: ", sectorSize); return false; } #endif #if USB_DEBUG >= 3 lun0_capacity = bulk.GetCapacity(0); SERIAL_ECHOLNPGM("LUN Capacity (in blocks): ", lun0_capacity); #endif return true; } // Returns the capacity of the card in blocks. uint32_t DiskIODriver_USBFlash::cardSize() { if (!isInserted()) return false; #if USB_DEBUG < 3 const uint32_t #endif lun0_capacity = bulk.GetCapacity(0); return lun0_capacity; } bool DiskIODriver_USBFlash::readBlock(uint32_t block, uint8_t *dst) { if (!isInserted()) return false; #if USB_DEBUG >= 3 if (block >= lun0_capacity) { SERIAL_ECHOLNPGM("Attempt to read past end of LUN: ", block); return false; } #if USB_DEBUG >= 4 SERIAL_ECHOLNPGM("Read block ", block); #endif #endif return bulk.Read(0, block, 512, 1, dst) == 0; } bool DiskIODriver_USBFlash::writeBlock(uint32_t block, const uint8_t *src) { if (!isInserted()) return false; #if USB_DEBUG >= 3 if (block >= lun0_capacity) { SERIAL_ECHOLNPGM("Attempt to write past end of LUN: ", block); return false; } #if USB_DEBUG >= 4 SERIAL_ECHOLNPGM("Write block ", block); #endif #endif return bulk.Write(0, block, 512, 1, src) == 0; } #endif // USB_FLASH_DRIVE_SUPPORT
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/Sd2Card_FlashDrive.cpp
C++
agpl-3.0
9,876
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once /** * \file * \brief Sd2Card class for USB Flash Drive */ #include "../SdFatConfig.h" #include "../SdInfo.h" #include "../disk_io_driver.h" #if DISABLED(USE_OTG_USB_HOST) /** * Define SOFTWARE_SPI to use bit-bang SPI */ #if ANY(MEGA_SOFT_SPI, USE_SOFTWARE_SPI) #define SOFTWARE_SPI #endif // SPI pin definitions - do not edit here - change in SdFatConfig.h #if ENABLED(SOFTWARE_SPI) #warning "Auto-assigning '10' as the SD_CHIP_SELECT_PIN." #define SD_CHIP_SELECT_PIN 10 // Software SPI chip select pin for the SD #else // hardware pin defs #define SD_CHIP_SELECT_PIN SD_SS_PIN // The default chip select pin for the SD card is SS. #endif #endif class DiskIODriver_USBFlash : public DiskIODriver { private: uint32_t pos; static void usbStateDebug(); public: static bool usbStartup(); static bool isInserted(); bool init(const uint8_t sckRateID=0, const pin_t chipSelectPin=TERN(USE_OTG_USB_HOST, 0, SD_CHIP_SELECT_PIN)) override; inline bool readCSD(csd_t*) override { return true; } inline bool readStart(const uint32_t block) override { pos = block; return isReady(); } inline bool readData(uint8_t *dst) override { return readBlock(pos++, dst); } inline bool readStop() override { return true; } inline bool writeStart(const uint32_t block, const uint32_t) override { pos = block; return isReady(); } inline bool writeData(const uint8_t *src) override { return writeBlock(pos++, src); } inline bool writeStop() override { return true; } bool readBlock(uint32_t block, uint8_t *dst) override; bool writeBlock(uint32_t blockNumber, const uint8_t *src) override; uint32_t cardSize() override; bool isReady() override; void idle() override; };
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/Sd2Card_FlashDrive.h
C++
agpl-3.0
2,842
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ // // USB functions supporting Flash Drive // #include "../../../inc/MarlinConfigPre.h" #if ENABLED(USB_FLASH_DRIVE_SUPPORT) && DISABLED(USE_UHS3_USB) #include "Usb.h" static uint8_t usb_error = 0; static uint8_t usb_task_state; /* constructor */ USB::USB() : bmHubPre(0) { usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; // Set up state machine init(); } /* Initialize data structures */ void USB::init() { //devConfigIndex = 0; bmHubPre = 0; } uint8_t USB::getUsbTaskState() { return usb_task_state; } void USB::setUsbTaskState(uint8_t state) { usb_task_state = state; } EpInfo* USB::getEpInfoEntry(uint8_t addr, uint8_t ep) { UsbDevice *p = addrPool.GetUsbDevicePtr(addr); if (!p || !p->epinfo) return nullptr; EpInfo *pep = p->epinfo; for (uint8_t i = 0; i < p->epcount; i++) { if ((pep)->epAddr == ep) return pep; pep++; } return nullptr; } /** * Set device table entry * Each device is different and has different number of endpoints. * This function plugs endpoint record structure, defined in application, to devtable */ uint8_t USB::setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo* eprecord_ptr) { if (!eprecord_ptr) return USB_ERROR_INVALID_ARGUMENT; UsbDevice *p = addrPool.GetUsbDevicePtr(addr); if (!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->address.devAddress = addr; p->epinfo = eprecord_ptr; p->epcount = epcount; return 0; } uint8_t USB::SetAddress(uint8_t addr, uint8_t ep, EpInfo **ppep, uint16_t *nak_limit) { UsbDevice *p = addrPool.GetUsbDevicePtr(addr); if (!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; if (!p->epinfo) return USB_ERROR_EPINFO_IS_NULL; *ppep = getEpInfoEntry(addr, ep); if (!*ppep) return USB_ERROR_EP_NOT_FOUND_IN_TBL; *nak_limit = (0x0001UL << (((*ppep)->bmNakPower > USB_NAK_MAX_POWER) ? USB_NAK_MAX_POWER : (*ppep)->bmNakPower)); (*nak_limit)--; /* USBTRACE2("\r\nAddress: ", addr); USBTRACE2(" EP: ", ep); USBTRACE2(" NAK Power: ",(*ppep)->bmNakPower); USBTRACE2(" NAK Limit: ", nak_limit); USBTRACE("\r\n"); */ regWr(rPERADDR, addr); // Set peripheral address uint8_t mode = regRd(rMODE); //Serial.print("\r\nMode: "); //Serial.println( mode, HEX); //Serial.print("\r\nLS: "); //Serial.println(p->lowspeed, HEX); // Set bmLOWSPEED and bmHUBPRE in case of low-speed device, reset them otherwise regWr(rMODE, (p->lowspeed) ? mode | bmLOWSPEED | bmHubPre : mode & ~(bmHUBPRE | bmLOWSPEED)); return 0; } /* Control transfer. Sets address, endpoint, fills control packet with necessary data, dispatches control packet, and initiates bulk IN transfer, */ /* depending on request. Actual requests are defined as inlines */ /* return codes: */ /* 00 = success */ /* 01-0f = non-zero HRSLT */ uint8_t USB::ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi, uint16_t wInd, uint16_t total, uint16_t nbytes, uint8_t *dataptr, USBReadParser *p) { bool direction = false; // Request direction, IN or OUT uint8_t rcode; SETUP_PKT setup_pkt; EpInfo *pep = nullptr; uint16_t nak_limit = 0; rcode = SetAddress(addr, ep, &pep, &nak_limit); if (rcode) return rcode; direction = ((bmReqType & 0x80) > 0); /* fill in setup packet */ setup_pkt.ReqType_u.bmRequestType = bmReqType; setup_pkt.bRequest = bRequest; setup_pkt.wVal_u.wValueLo = wValLo; setup_pkt.wVal_u.wValueHi = wValHi; setup_pkt.wIndex = wInd; setup_pkt.wLength = total; bytesWr(rSUDFIFO, 8, (uint8_t*) & setup_pkt); // Transfer to setup packet FIFO rcode = dispatchPkt(tokSETUP, ep, nak_limit); // Dispatch packet if (rcode) return rcode; // Return HRSLT if not zero if (dataptr) { // Data stage, if present if (direction) { // IN transfer uint16_t left = total; pep->bmRcvToggle = 1; // BmRCVTOG1; while (left) { // Bytes read into buffer uint16_t read = nbytes; //uint16_t read = (left<nbytes) ? left : nbytes; rcode = InTransfer(pep, nak_limit, &read, dataptr); if (rcode == hrTOGERR) { // Yes, we flip it wrong here so that next time it is actually correct! pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; continue; } if (rcode) return rcode; // Invoke callback function if inTransfer completed successfully and callback function pointer is specified if (!rcode && p) ((USBReadParser*)p)->Parse(read, dataptr, total - left); left -= read; if (read < nbytes) break; } } else { // OUT transfer pep->bmSndToggle = 1; // BmSNDTOG1; rcode = OutTransfer(pep, nak_limit, nbytes, dataptr); } if (rcode) return rcode; // Return error } // Status stage return dispatchPkt((direction) ? tokOUTHS : tokINHS, ep, nak_limit); // GET if direction } /** * IN transfer to arbitrary endpoint. Assumes PERADDR is set. Handles multiple packets if necessary. Transfers 'nbytes' bytes. * Keep sending INs and writes data to memory area pointed by 'data' * rcode 0 if no errors. rcode 01-0f is relayed from dispatchPkt(). Rcode f0 means RCVDAVIRQ error, fe = USB xfer timeout */ uint8_t USB::inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t *data, uint8_t bInterval/*=0*/) { EpInfo *pep = nullptr; uint16_t nak_limit = 0; uint8_t rcode = SetAddress(addr, ep, &pep, &nak_limit); if (rcode) { USBTRACE3("(USB::InTransfer) SetAddress Failed ", rcode, 0x81); USBTRACE3("(USB::InTransfer) addr requested ", addr, 0x81); USBTRACE3("(USB::InTransfer) ep requested ", ep, 0x81); return rcode; } return InTransfer(pep, nak_limit, nbytesptr, data, bInterval); } uint8_t USB::InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t *data, uint8_t bInterval/*=0*/) { uint8_t rcode = 0; uint8_t pktsize; uint16_t nbytes = *nbytesptr; //printf("Requesting %i bytes ", nbytes); uint8_t maxpktsize = pep->maxPktSize; *nbytesptr = 0; regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); // Set toggle value // Use a 'break' to exit this loop for (;;) { rcode = dispatchPkt(tokIN, pep->epAddr, nak_limit); // IN packet to EP-'endpoint'. Function takes care of NAKS. if (rcode == hrTOGERR) { // Yes, we flip it wrong here so that next time it is actually correct! pep->bmRcvToggle = (regRd(rHRSL) & bmRCVTOGRD) ? 0 : 1; regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); // Set toggle value continue; } if (rcode) { //printf(">>>>>>>> Problem! dispatchPkt %2.2x\r\n", rcode); break; // Should be 0, indicating ACK. Else return error code. } /* check for RCVDAVIRQ and generate error if not present */ /* the only case when absence of RCVDAVIRQ makes sense is when toggle error occurred. Need to add handling for that */ if ((regRd(rHIRQ) & bmRCVDAVIRQ) == 0) { //printf(">>>>>>>> Problem! NO RCVDAVIRQ!\r\n"); rcode = 0xF0; // Receive error break; } pktsize = regRd(rRCVBC); // Number of received bytes //printf("Got %i bytes \r\n", pktsize); // This would be OK, but... //assert(pktsize <= nbytes); if (pktsize > nbytes) { // This can happen. Use of assert on Arduino locks up the Arduino. // So I will trim the value, and hope for the best. //printf(">>>>>>>> Problem! Wanted %i bytes but got %i.\r\n", nbytes, pktsize); pktsize = nbytes; } int16_t mem_left = (int16_t)nbytes - *((int16_t*)nbytesptr); if (mem_left < 0) mem_left = 0; data = bytesRd(rRCVFIFO, ((pktsize > mem_left) ? mem_left : pktsize), data); regWr(rHIRQ, bmRCVDAVIRQ); // Clear the IRQ & free the buffer *nbytesptr += pktsize; // Add this packet's byte count to total transfer length /* The transfer is complete under two conditions: */ /* 1. The device sent a short packet (L.T. maxPacketSize) */ /* 2. 'nbytes' have been transferred. */ if (pktsize < maxpktsize || *nbytesptr >= nbytes) { // Transferred 'nbytes' bytes? // Save toggle value pep->bmRcvToggle = ((regRd(rHRSL) & bmRCVTOGRD)) ? 1 : 0; //printf("\r\n"); rcode = 0; break; } else if (bInterval > 0) delay(bInterval); // Delay according to polling interval } return rcode; } /** * OUT transfer to arbitrary endpoint. Handles multiple packets if necessary. Transfers 'nbytes' bytes. * Handles NAK bug per Maxim Application Note 4000 for single buffer transfer * rcode 0 if no errors. rcode 01-0f is relayed from HRSL */ uint8_t USB::outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *data) { EpInfo *pep = nullptr; uint16_t nak_limit = 0; uint8_t rcode = SetAddress(addr, ep, &pep, &nak_limit); if (rcode) return rcode; return OutTransfer(pep, nak_limit, nbytes, data); } uint8_t USB::OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data) { uint8_t rcode = hrSUCCESS, retry_count; uint8_t *data_p = data; // Local copy of the data pointer uint16_t bytes_tosend, nak_count; uint16_t bytes_left = nbytes; uint8_t maxpktsize = pep->maxPktSize; if (maxpktsize < 1 || maxpktsize > 64) return USB_ERROR_INVALID_MAX_PKT_SIZE; uint32_t timeout = (uint32_t)millis() + USB_XFER_TIMEOUT; regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); // Set toggle value while (bytes_left) { retry_count = 0; nak_count = 0; bytes_tosend = (bytes_left >= maxpktsize) ? maxpktsize : bytes_left; bytesWr(rSNDFIFO, bytes_tosend, data_p); // Filling output FIFO regWr(rSNDBC, bytes_tosend); // Set number of bytes regWr(rHXFR, (tokOUT | pep->epAddr)); // Dispatch packet while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); // Wait for the completion IRQ regWr(rHIRQ, bmHXFRDNIRQ); // Clear IRQ rcode = (regRd(rHRSL) & 0x0F); while (rcode && ((int32_t)((uint32_t)millis() - timeout) < 0L)) { switch (rcode) { case hrNAK: nak_count++; if (nak_limit && (nak_count == nak_limit)) goto breakout; //return rcode; break; case hrTIMEOUT: retry_count++; if (retry_count == USB_RETRY_LIMIT) goto breakout; //return rcode; break; case hrTOGERR: // Yes, we flip it wrong here so that next time it is actually correct! pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); // Set toggle value break; default: goto breakout; } /* process NAK according to Host out NAK bug */ regWr(rSNDBC, 0); regWr(rSNDFIFO, *data_p); regWr(rSNDBC, bytes_tosend); regWr(rHXFR, (tokOUT | pep->epAddr)); // Dispatch packet while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); // Wait for the completion IRQ regWr(rHIRQ, bmHXFRDNIRQ); // Clear IRQ rcode = (regRd(rHRSL) & 0x0F); } // While rcode && .... bytes_left -= bytes_tosend; data_p += bytes_tosend; } // While bytes_left... breakout: pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 1 : 0; // BmSNDTOG1 : bmSNDTOG0; // Update toggle return ( rcode); // Should be 0 in all cases } /** * Dispatch USB packet. Assumes peripheral address is set and relevant buffer is loaded/empty * If NAK, tries to re-send up to nak_limit times * If nak_limit == 0, do not count NAKs, exit after timeout * If bus timeout, re-sends up to USB_RETRY_LIMIT times * return codes 0x00-0x0F are HRSLT( 0x00 being success ), 0xFF means timeout */ uint8_t USB::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) { uint32_t timeout = (uint32_t)millis() + USB_XFER_TIMEOUT; uint8_t tmpdata; uint8_t rcode = hrSUCCESS; uint8_t retry_count = 0; uint16_t nak_count = 0; while ((int32_t)((uint32_t)millis() - timeout) < 0L) { #if defined(ESP8266) || defined(ESP32) yield(); // Needed in order to reset the watchdog timer on the ESP8266 #endif regWr(rHXFR, (token | ep)); // Launch the transfer rcode = USB_ERROR_TRANSFER_TIMEOUT; while ((int32_t)((uint32_t)millis() - timeout) < 0L) { // Wait for transfer completion #if defined(ESP8266) || defined(ESP32) yield(); // Needed to reset the watchdog timer on the ESP8266 #endif tmpdata = regRd(rHIRQ); if (tmpdata & bmHXFRDNIRQ) { regWr(rHIRQ, bmHXFRDNIRQ); // Clear the interrupt rcode = 0x00; break; } } // While millis() < timeout //if (rcode != 0x00) return rcode; // Exit if timeout rcode = (regRd(rHRSL) & 0x0F); // Analyze transfer result switch (rcode) { case hrNAK: nak_count++; if (nak_limit && (nak_count == nak_limit)) return (rcode); break; case hrTIMEOUT: retry_count++; if (retry_count == USB_RETRY_LIMIT) return (rcode); break; default: return (rcode); } } // While timeout > millis() return rcode; } // USB main task. Performs enumeration/cleanup void USB::Task() { // USB state machine uint8_t rcode; uint8_t tmpdata; static uint32_t delay = 0; //USB_FD_DEVICE_DESCRIPTOR buf; bool lowspeed = false; MAX3421E::Task(); tmpdata = getVbusState(); /* modify USB task state if Vbus changed */ switch (tmpdata) { case SE1: // Illegal state usb_task_state = USB_DETACHED_SUBSTATE_ILLEGAL; lowspeed = false; break; case SE0: // Disconnected if ((usb_task_state & USB_STATE_MASK) != USB_STATE_DETACHED) usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; lowspeed = false; break; case LSHOST: lowspeed = true; // Intentional fallthrough case FSHOST: // Attached if ((usb_task_state & USB_STATE_MASK) == USB_STATE_DETACHED) { delay = (uint32_t)millis() + USB_SETTLE_DELAY; usb_task_state = USB_ATTACHED_SUBSTATE_SETTLE; } break; } for (uint8_t i = 0; i < USB_NUMDEVICES; i++) if (devConfig[i]) rcode = devConfig[i]->Poll(); switch (usb_task_state) { case USB_DETACHED_SUBSTATE_INITIALIZE: init(); for (uint8_t i = 0; i < USB_NUMDEVICES; i++) if (devConfig[i]) rcode = devConfig[i]->Release(); usb_task_state = USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE; break; case USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE: // Just sit here break; case USB_DETACHED_SUBSTATE_ILLEGAL: // Just sit here break; case USB_ATTACHED_SUBSTATE_SETTLE: // Settle time for just attached device if ((int32_t)((uint32_t)millis() - delay) >= 0L) usb_task_state = USB_ATTACHED_SUBSTATE_RESET_DEVICE; else break; // Don't fall through case USB_ATTACHED_SUBSTATE_RESET_DEVICE: regWr(rHCTL, bmBUSRST); // Issue bus reset usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE; break; case USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE: if ((regRd(rHCTL) & bmBUSRST) == 0) { tmpdata = regRd(rMODE) | bmSOFKAENAB; // Start SOF generation regWr(rMODE, tmpdata); usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_SOF; //delay = (uint32_t)millis() + 20; // 20ms wait after reset per USB spec } break; case USB_ATTACHED_SUBSTATE_WAIT_SOF: // Todo: change check order if (regRd(rHIRQ) & bmFRAMEIRQ) { // When first SOF received _and_ 20ms has passed we can continue /* if (delay < (uint32_t)millis()) // 20ms passed usb_task_state = USB_STATE_CONFIGURING; */ usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET; delay = (uint32_t)millis() + 20; } break; case USB_ATTACHED_SUBSTATE_WAIT_RESET: if ((int32_t)((uint32_t)millis() - delay) >= 0L) usb_task_state = USB_STATE_CONFIGURING; else break; // Don't fall through case USB_STATE_CONFIGURING: //Serial.print("\r\nConf.LS: "); //Serial.println(lowspeed, HEX); rcode = Configuring(0, 0, lowspeed); if (!rcode) usb_task_state = USB_STATE_RUNNING; else if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) { usb_error = rcode; usb_task_state = USB_STATE_ERROR; } break; case USB_STATE_RUNNING: break; case USB_STATE_ERROR: //MAX3421E::Init(); break; } } uint8_t USB::DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed) { //uint8_t buf[12]; uint8_t rcode; UsbDevice *p0 = nullptr, *p = nullptr; // Get pointer to pseudo device with address 0 assigned p0 = addrPool.GetUsbDevicePtr(0); if (!p0) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; if (!p0->epinfo) return USB_ERROR_EPINFO_IS_NULL; p0->lowspeed = lowspeed; // Allocate new address according to device class uint8_t bAddress = addrPool.AllocAddress(parent, false, port); if (!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; p = addrPool.GetUsbDevicePtr(bAddress); if (!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; // Assign new address to the device rcode = setAddr(0, 0, bAddress); if (rcode) { addrPool.FreeAddress(bAddress); bAddress = 0; } return rcode; } uint8_t USB::AttemptConfig(uint8_t driver, uint8_t parent, uint8_t port, bool lowspeed) { //printf("AttemptConfig: parent = %i, port = %i\r\n", parent, port); uint8_t retries = 0; again: uint8_t rcode = devConfig[driver]->ConfigureDevice(parent, port, lowspeed); if (rcode == USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET) { if (parent == 0) { // Send a bus reset on the root interface. regWr(rHCTL, bmBUSRST); // Issue bus reset delay(102); // Delay 102ms, compensate for clock inaccuracy. } else { // Reset parent port devConfig[parent]->ResetHubPort(port); } } else if (rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works delay(100); retries++; goto again; } else if (rcode) return rcode; rcode = devConfig[driver]->Init(parent, port, lowspeed); if (rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works delay(100); retries++; goto again; } if (rcode) { // Issue a bus reset, because the device may be in a limbo state if (parent == 0) { // Send a bus reset on the root interface. regWr(rHCTL, bmBUSRST); // Issue bus reset delay(102); // Delay 102ms, compensate for clock inaccuracy. } else { // Reset parent port devConfig[parent]->ResetHubPort(port); } } return rcode; } /** * This is broken. It needs to enumerate differently. * It causes major problems with several devices if detected in an unexpected order. * * Oleg - I wouldn't do anything before the newly connected device is considered sane. * i.e.(delays are not indicated for brevity): * 1. reset * 2. GetDevDescr(); * 3a. If ACK, continue with allocating address, addressing, etc. * 3b. Else reset again, count resets, stop at some number (5?). * 4. When max.number of resets is reached, toggle power/fail * If desired, this could be modified by performing two resets with GetDevDescr() in the middle - however, from my experience, if a device answers to GDD() * it doesn't need to be reset again * New steps proposal: * 1: get address pool instance. exit on fail * 2: pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf). exit on fail. * 3: bus reset, 100ms delay * 4: set address * 5: pUsb->setEpInfoEntry(bAddress, 1, epInfo), exit on fail * 6: while (configurations) { * for (each configuration) { * for (each driver) { * 6a: Ask device if it likes configuration. Returns 0 on OK. * If successful, the driver configured device. * The driver now owns the endpoints, and takes over managing them. * The following will need codes: * Everything went well, instance consumed, exit with success. * Instance already in use, ignore it, try next driver. * Not a supported device, ignore it, try next driver. * Not a supported configuration for this device, ignore it, try next driver. * Could not configure device, fatal, exit with fail. * } * } * } * 7: for (each driver) { * 7a: Ask device if it knows this VID/PID. Acts exactly like 6a, but using VID/PID * 8: if we get here, no driver likes the device plugged in, so exit failure. */ uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) { //uint8_t bAddress = 0; //printf("Configuring: parent = %i, port = %i\r\n", parent, port); uint8_t devConfigIndex; uint8_t rcode = 0; uint8_t buf[sizeof (USB_FD_DEVICE_DESCRIPTOR)]; USB_FD_DEVICE_DESCRIPTOR *udd = reinterpret_cast<USB_FD_DEVICE_DESCRIPTOR *>(buf); UsbDevice *p = nullptr; EpInfo *oldep_ptr = nullptr; EpInfo epInfo; epInfo.epAddr = 0; epInfo.maxPktSize = 8; epInfo.bmSndToggle = 0; epInfo.bmRcvToggle = 0; epInfo.bmNakPower = USB_NAK_MAX_POWER; //delay(2000); AddressPool &addrPool = GetAddressPool(); // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); if (!p) { //printf("Configuring error: USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL\r\n"); return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } // Save old pointer to EP_RECORD of address 0 oldep_ptr = p->epinfo; // Temporary assign new pointer to epInfo to p->epinfo in order to // Avoid toggle inconsistence p->epinfo = &epInfo; p->lowspeed = lowspeed; // Get device descriptor rcode = getDevDescr(0, 0, sizeof (USB_FD_DEVICE_DESCRIPTOR), (uint8_t*)buf); // Restore p->epinfo p->epinfo = oldep_ptr; if (rcode) { //printf("Configuring error: Can't get USB_FD_DEVICE_DESCRIPTOR\r\n"); return rcode; } // To-do? // Allocate new address according to device class //bAddress = addrPool.AllocAddress(parent, false, port); uint16_t vid = udd->idVendor, pid = udd->idProduct; uint8_t klass = udd->bDeviceClass, subklass = udd->bDeviceSubClass; // Attempt to configure if VID/PID or device class matches with a driver // Qualify with subclass too. // // VID/PID & class tests default to false for drivers not yet ported // Subclass defaults to true, so you don't have to define it if you don't have to. // for (devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { if (!devConfig[devConfigIndex]) continue; // No driver if (devConfig[devConfigIndex]->GetAddress()) continue; // Consumed if (devConfig[devConfigIndex]->DEVSUBCLASSOK(subklass) && (devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass))) { rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed); if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED) break; } } if (devConfigIndex < USB_NUMDEVICES) return rcode; // Blindly attempt to configure for (devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { if (!devConfig[devConfigIndex]) continue; if (devConfig[devConfigIndex]->GetAddress()) continue; // Consumed if (devConfig[devConfigIndex]->DEVSUBCLASSOK(subklass) && (devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass))) continue; // If this is true it means it must have returned USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED above rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed); //printf("ERROR ENUMERATING %2.2x\r\n", rcode); if (!(rcode == USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED || rcode == USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE)) { // In case of an error dev_index should be reset to 0 // in order to start from the very beginning the // next time the program gets here //if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) //devConfigIndex = 0; return rcode; } } // Arriving here means the device class is unsupported by registered classes return DefaultAddressing(parent, port, lowspeed); } uint8_t USB::ReleaseDevice(uint8_t addr) { if (addr) { for (uint8_t i = 0; i < USB_NUMDEVICES; i++) { if (!devConfig[i]) continue; if (devConfig[i]->GetAddress() == addr) return devConfig[i]->Release(); } } return 0; } // Get device descriptor uint8_t USB::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *dataptr) { return ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, nbytes, dataptr, nullptr); } // Get configuration descriptor uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t *dataptr) { return ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, nbytes, dataptr, nullptr); } /** * Requests Configuration Descriptor. Sends two Get Conf Descr requests. * The first one gets the total length of all descriptors, then the second one requests this * total length. The length of the first request can be shorter (4 bytes), however, there are * devices which won't work unless this length is set to 9. */ uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint8_t conf, USBReadParser *p) { const uint8_t bufSize = 64; uint8_t buf[bufSize]; USB_FD_CONFIGURATION_DESCRIPTOR *ucd = reinterpret_cast<USB_FD_CONFIGURATION_DESCRIPTOR *>(buf); uint8_t ret = getConfDescr(addr, ep, 9, conf, buf); if (ret) return ret; uint16_t total = ucd->wTotalLength; //USBTRACE2("\r\ntotal conf.size:", total); return ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, total, bufSize, buf, p); } // Get string descriptor uint8_t USB::getStrDescr(uint8_t addr, uint8_t ep, uint16_t ns, uint8_t index, uint16_t langid, uint8_t *dataptr) { return ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, ns, ns, dataptr, nullptr); } // Set address uint8_t USB::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) { uint8_t rcode = ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, nullptr, nullptr); //delay(2); // Per USB 2.0 sect.9.2.6.3 delay(300); // Older spec says you should wait at least 200ms return rcode; //return ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, nullptr, nullptr); } // Set configuration uint8_t USB::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) { return ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, 0x0000, nullptr, nullptr); } #endif // USB_FLASH_DRIVE_SUPPORT
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/Usb.cpp
C++
agpl-3.0
28,117
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once /* USB functions */ #define _usb_h_ #include "../../../inc/MarlinConfigPre.h" // WARNING: Do not change the order of includes, or stuff will break! #include <inttypes.h> #include <stddef.h> #include <stdio.h> // None of these should ever be included by a driver, or a user's sketch. #include "settings.h" #include "printhex.h" #include "message.h" #include "hexdump.h" //#include "sink_parser.h" #include "max3421e.h" #include "address.h" //#include "avrpins.h" #include "usb_ch9.h" #include "usbhost.h" #include "UsbCore.h" #include "parsetools.h" #include "confdescparser.h" #undef _usb_h_
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/Usb.h
C
agpl-3.0
1,566
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #ifndef _usb_h_ #error "Never include UsbCore.h directly; include Usb.h instead" #endif #pragma once // Not used anymore? If anyone uses this, please let us know so that this may be // moved to the proper place, settings.h. //#define USB_METHODS_INLINE /* shield pins. First parameter - SS pin, second parameter - INT pin */ #ifdef __MARLIN_FIRMWARE__ typedef MAX3421e MAX3421E; // Marlin redefines this class in "../usb_host.h" #elif defined(BOARD_BLACK_WIDDOW) typedef MAX3421e<P6, P3> MAX3421E; // Black Widow #elif defined(CORE_TEENSY) && (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)) #if EXT_RAM typedef MAX3421e<P20, P7> MAX3421E; // Teensy++ 2.0 with XMEM2 #else typedef MAX3421e<P9, P8> MAX3421E; // Teensy++ 1.0 and 2.0 #endif #elif defined(BOARD_MEGA_ADK) typedef MAX3421e<P53, P54> MAX3421E; // Arduino Mega ADK #elif defined(ARDUINO_AVR_BALANDUINO) typedef MAX3421e<P20, P19> MAX3421E; // Balanduino #elif defined(__ARDUINO_X86__) && PLATFORM_ID == 0x06 typedef MAX3421e<P3, P2> MAX3421E; // The Intel Galileo supports much faster read and write speed at pin 2 and 3 #elif defined(ESP8266) typedef MAX3421e<P15, P5> MAX3421E; // ESP8266 boards #elif defined(ESP32) typedef MAX3421e<P5, P17> MAX3421E; // ESP32 boards #else typedef MAX3421e<P10, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x #endif /* Common setup data constant combinations */ #define bmREQ_GET_DESCR USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //get descriptor request type #define bmREQ_SET USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //set request type for all but 'set feature' and 'set interface' #define bmREQ_CL_GET_INTF USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE //get interface request type // D7 data transfer direction (0 - host-to-device, 1 - device-to-host) // D6-5 Type (0- standard, 1 - class, 2 - vendor, 3 - reserved) // D4-0 Recipient (0 - device, 1 - interface, 2 - endpoint, 3 - other, 4..31 - reserved) // USB Device Classes #define USB_CLASS_USE_CLASS_INFO 0x00 // Use Class Info in the Interface Descriptors #define USB_CLASS_AUDIO 0x01 // Audio #define USB_CLASS_COM_AND_CDC_CTRL 0x02 // Communications and CDC Control #define USB_CLASS_HID 0x03 // HID #define USB_CLASS_PHYSICAL 0x05 // Physical #define USB_CLASS_IMAGE 0x06 // Image #define USB_CLASS_PRINTER 0x07 // Printer #define USB_CLASS_MASS_STORAGE 0x08 // Mass Storage #define USB_CLASS_HUB 0x09 // Hub #define USB_CLASS_CDC_DATA 0x0A // CDC-Data #define USB_CLASS_SMART_CARD 0x0B // Smart-Card #define USB_CLASS_CONTENT_SECURITY 0x0D // Content Security #define USB_CLASS_VIDEO 0x0E // Video #define USB_CLASS_PERSONAL_HEALTH 0x0F // Personal Healthcare #define USB_CLASS_DIAGNOSTIC_DEVICE 0xDC // Diagnostic Device #define USB_CLASS_WIRELESS_CTRL 0xE0 // Wireless Controller #define USB_CLASS_MISC 0xEF // Miscellaneous #define USB_CLASS_APP_SPECIFIC 0xFE // Application Specific #define USB_CLASS_VENDOR_SPECIFIC 0xFF // Vendor Specific // Additional Error Codes #define USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED 0xD1 #define USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE 0xD2 #define USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS 0xD3 #define USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL 0xD4 #define USB_ERROR_HUB_ADDRESS_OVERFLOW 0xD5 #define USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL 0xD6 #define USB_ERROR_EPINFO_IS_NULL 0xD7 #define USB_ERROR_INVALID_ARGUMENT 0xD8 #define USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE 0xD9 #define USB_ERROR_INVALID_MAX_PKT_SIZE 0xDA #define USB_ERROR_EP_NOT_FOUND_IN_TBL 0xDB #define USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET 0xE0 #define USB_ERROR_FailGetDevDescr 0xE1 #define USB_ERROR_FailSetDevTblEntry 0xE2 #define USB_ERROR_FailGetConfDescr 0xE3 #define USB_ERROR_TRANSFER_TIMEOUT 0xFF #define USB_XFER_TIMEOUT 5000 // (5000) USB transfer timeout in milliseconds, per section 9.2.6.1 of USB 2.0 spec //#define USB_NAK_LIMIT 32000 // NAK limit for a transfer. 0 means NAKs are not counted #define USB_RETRY_LIMIT 3 // 3 retry limit for a transfer #define USB_SETTLE_DELAY 200 // settle delay in milliseconds #define USB_NUMDEVICES 16 //number of USB devices //#define HUB_MAX_HUBS 7 // maximum number of hubs that can be attached to the host controller #define HUB_PORT_RESET_DELAY 20 // hub port reset delay 10 ms recommended, can be up to 20 ms /* USB state machine states */ #define USB_STATE_MASK 0xF0 #define USB_STATE_DETACHED 0x10 #define USB_DETACHED_SUBSTATE_INITIALIZE 0x11 #define USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE 0x12 #define USB_DETACHED_SUBSTATE_ILLEGAL 0x13 #define USB_ATTACHED_SUBSTATE_SETTLE 0x20 #define USB_ATTACHED_SUBSTATE_RESET_DEVICE 0x30 #define USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE 0x40 #define USB_ATTACHED_SUBSTATE_WAIT_SOF 0x50 #define USB_ATTACHED_SUBSTATE_WAIT_RESET 0x51 #define USB_ATTACHED_SUBSTATE_GET_DEVICE_DESCRIPTOR_SIZE 0x60 #define USB_STATE_ADDRESSING 0x70 #define USB_STATE_CONFIGURING 0x80 #define USB_STATE_RUNNING 0x90 #define USB_STATE_ERROR 0xA0 class USBDeviceConfig { public: virtual uint8_t Init(uint8_t parent __attribute__((unused)), uint8_t port __attribute__((unused)), bool lowspeed __attribute__((unused))) { return 0; } virtual uint8_t ConfigureDevice(uint8_t parent __attribute__((unused)), uint8_t port __attribute__((unused)), bool lowspeed __attribute__((unused))) { return 0; } virtual uint8_t Release() { return 0; } virtual uint8_t Poll() { return 0; } virtual uint8_t GetAddress() { return 0; } virtual void ResetHubPort(uint8_t port __attribute__((unused))) { return; } // Note used for hubs only! virtual bool VIDPIDOK(uint16_t vid __attribute__((unused)), uint16_t pid __attribute__((unused))) { return false; } virtual bool DEVCLASSOK(uint8_t klass __attribute__((unused))) { return false; } virtual bool DEVSUBCLASSOK(uint8_t subklass __attribute__((unused))) { return true; } }; /* USB Setup Packet Structure */ typedef struct { union { // offset description uint8_t bmRequestType; // 0 Bit-map of request type struct { uint8_t recipient : 5; // Recipient of the request uint8_t type : 2; // Type of request uint8_t direction : 1; // Direction of data X-fer } __attribute__((packed)); } ReqType_u; uint8_t bRequest; // 1 Request union { uint16_t wValue; // 2 Depends on bRequest struct { uint8_t wValueLo; uint8_t wValueHi; } __attribute__((packed)); } wVal_u; uint16_t wIndex; // 4 Depends on bRequest uint16_t wLength; // 6 Depends on bRequest } __attribute__((packed)) SETUP_PKT, *PSETUP_PKT; // Base class for incoming data parser class USBReadParser { public: virtual void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset) = 0; }; class USB : public MAX3421E { AddressPoolImpl<USB_NUMDEVICES> addrPool; USBDeviceConfig* devConfig[USB_NUMDEVICES]; uint8_t bmHubPre; public: USB(); void SetHubPreMask() { bmHubPre |= bmHUBPRE; }; void ResetHubPreMask() { bmHubPre &= (~bmHUBPRE); }; AddressPool& GetAddressPool() { return (AddressPool&)addrPool; }; uint8_t RegisterDeviceClass(USBDeviceConfig *pdev) { for (uint8_t i = 0; i < USB_NUMDEVICES; i++) { if (!devConfig[i]) { devConfig[i] = pdev; return 0; } } return USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS; }; void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) { addrPool.ForEachUsbDevice(pfunc); }; uint8_t getUsbTaskState(); void setUsbTaskState(uint8_t state); EpInfo* getEpInfoEntry(uint8_t addr, uint8_t ep); uint8_t setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo* eprecord_ptr); /* Control requests */ uint8_t getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *dataptr); uint8_t getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t *dataptr); uint8_t getConfDescr(uint8_t addr, uint8_t ep, uint8_t conf, USBReadParser *p); uint8_t getStrDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t index, uint16_t langid, uint8_t *dataptr); uint8_t setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr); uint8_t setConf(uint8_t addr, uint8_t ep, uint8_t conf_value); /**/ uint8_t ctrlData(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *dataptr, bool direction); uint8_t ctrlStatus(uint8_t ep, bool direction, uint16_t nak_limit); uint8_t inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t *data, uint8_t bInterval = 0); uint8_t outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *data); uint8_t dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit); void Task(); uint8_t DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed); uint8_t Configuring(uint8_t parent, uint8_t port, bool lowspeed); uint8_t ReleaseDevice(uint8_t addr); uint8_t ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi, uint16_t wInd, uint16_t total, uint16_t nbytes, uint8_t *dataptr, USBReadParser *p); private: void init(); uint8_t SetAddress(uint8_t addr, uint8_t ep, EpInfo **ppep, uint16_t *nak_limit); uint8_t OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data); uint8_t InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t *data, uint8_t bInterval = 0); uint8_t AttemptConfig(uint8_t driver, uint8_t parent, uint8_t port, bool lowspeed); }; #if 0 //defined(USB_METHODS_INLINE) //get device descriptor inline uint8_t USB::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *dataptr) { return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, dataptr)); } //get configuration descriptor inline uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t *dataptr) { return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, dataptr)); } //get string descriptor inline uint8_t USB::getStrDescr(uint8_t addr, uint8_t ep, uint16_t nuint8_ts, uint8_t index, uint16_t langid, uint8_t *dataptr) { return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, nuint8_ts, dataptr)); } //set address inline uint8_t USB::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) { return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, nullptr)); } //set configuration inline uint8_t USB::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) { return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, nullptr)); } #endif // defined(USB_METHODS_INLINE)
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/UsbCore.h
C++
agpl-3.0
12,907
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once #ifndef _usb_h_ #error "Never include address.h directly; include Usb.h instead" #endif /* NAK powers. To save space in endpoint data structure, amount of retries before giving up and returning 0x4 is stored in */ /* bmNakPower as a power of 2. The actual nak_limit is then calculated as nak_limit = ( 2^bmNakPower - 1) */ #define USB_NAK_MAX_POWER 15 //NAK binary order maximum value #define USB_NAK_DEFAULT 14 //default 32K-1 NAKs before giving up #define USB_NAK_NOWAIT 1 //Single NAK stops transfer #define USB_NAK_NONAK 0 //Do not count NAKs, stop retrying after USB Timeout struct EpInfo { uint8_t epAddr; // Endpoint address uint8_t maxPktSize; // Maximum packet size union { uint8_t epAttribs; struct { uint8_t bmSndToggle : 1; // Send toggle, when zero bmSNDTOG0, bmSNDTOG1 otherwise uint8_t bmRcvToggle : 1; // Send toggle, when zero bmRCVTOG0, bmRCVTOG1 otherwise uint8_t bmNakPower : 6; // Binary order for NAK_LIMIT value } __attribute__((packed)); }; } __attribute__((packed)); // 7 6 5 4 3 2 1 0 // --------------------------------- // | | H | P | P | P | A | A | A | // --------------------------------- // // H - if 1 the address is a hub address // P - parent hub address // A - device address / port number in case of hub // struct UsbDeviceAddress { union { struct { uint8_t bmAddress : 3; // device address/port number uint8_t bmParent : 3; // parent hub address uint8_t bmHub : 1; // hub flag uint8_t bmReserved : 1; // reserved, must be zero } __attribute__((packed)); uint8_t devAddress; }; } __attribute__((packed)); #define bmUSB_DEV_ADDR_ADDRESS 0x07 #define bmUSB_DEV_ADDR_PARENT 0x38 #define bmUSB_DEV_ADDR_HUB 0x40 struct UsbDevice { EpInfo *epinfo; // endpoint info pointer UsbDeviceAddress address; uint8_t epcount; // number of endpoints bool lowspeed; // indicates if a device is the low speed one // uint8_t devclass; // device class } __attribute__((packed)); class AddressPool { public: virtual UsbDevice* GetUsbDevicePtr(uint8_t addr) = 0; virtual uint8_t AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 0) = 0; virtual void FreeAddress(uint8_t addr) = 0; }; typedef void (*UsbDeviceHandleFunc)(UsbDevice *pdev); #define ADDR_ERROR_INVALID_INDEX 0xFF #define ADDR_ERROR_INVALID_ADDRESS 0xFF template <const uint8_t MAX_DEVICES_ALLOWED> class AddressPoolImpl : public AddressPool { EpInfo dev0ep; //Endpoint data structure used during enumeration for uninitialized device uint8_t hubCounter; // hub counter is kept // in order to avoid hub address duplication UsbDevice thePool[MAX_DEVICES_ALLOWED]; // Initialize address pool entry void InitEntry(uint8_t index) { thePool[index].address.devAddress = 0; thePool[index].epcount = 1; thePool[index].lowspeed = 0; thePool[index].epinfo = &dev0ep; } // Return thePool index for a given address uint8_t FindAddressIndex(uint8_t address = 0) { for (uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) if (thePool[i].address.devAddress == address) return i; return 0; } // Return thePool child index for a given parent uint8_t FindChildIndex(UsbDeviceAddress addr, uint8_t start = 1) { for (uint8_t i = (start < 1 || start >= MAX_DEVICES_ALLOWED) ? 1 : start; i < MAX_DEVICES_ALLOWED; i++) { if (thePool[i].address.bmParent == addr.bmAddress) return i; } return 0; } // Frees address entry specified by index parameter void FreeAddressByIndex(uint8_t index) { // Zero field is reserved and should not be affected if (index == 0) return; UsbDeviceAddress uda = thePool[index].address; // If a hub was switched off all port addresses should be freed if (uda.bmHub == 1) { for (uint8_t i = 1; (i = FindChildIndex(uda, i));) FreeAddressByIndex(i); // If the hub had the last allocated address, hubCounter should be decremented if (hubCounter == uda.bmAddress) hubCounter--; } InitEntry(index); } // Initialize the whole address pool at once void InitAllAddresses() { for (uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) InitEntry(i); hubCounter = 0; } public: AddressPoolImpl() : hubCounter(0) { // Zero address is reserved InitEntry(0); thePool[0].address.devAddress = 0; thePool[0].epinfo = &dev0ep; dev0ep.epAddr = 0; dev0ep.maxPktSize = 8; dev0ep.bmSndToggle = 0; // Set DATA0/1 toggles to 0 dev0ep.bmRcvToggle = 0; dev0ep.bmNakPower = USB_NAK_MAX_POWER; InitAllAddresses(); } // Return a pointer to a specified address entry virtual UsbDevice* GetUsbDevicePtr(uint8_t addr) { if (!addr) return thePool; uint8_t index = FindAddressIndex(addr); return index ? thePool + index : nullptr; } // Perform an operation specified by pfunc for each addressed device void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) { if (pfunc) { for (uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) if (thePool[i].address.devAddress) pfunc(thePool + i); } } // Allocate new address virtual uint8_t AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 0) { /* if (parent != 0 && port == 0) USB_HOST_SERIAL.println("PRT:0"); */ UsbDeviceAddress _parent; _parent.devAddress = parent; if (_parent.bmReserved || port > 7) //if(parent > 127 || port > 7) return 0; if (is_hub && hubCounter == 7) return 0; // finds first empty address entry starting from one uint8_t index = FindAddressIndex(0); if (!index) return 0; // if empty entry is not found if (_parent.devAddress == 0) { if (is_hub) { thePool[index].address.devAddress = 0x41; hubCounter++; } else thePool[index].address.devAddress = 1; return thePool[index].address.devAddress; } UsbDeviceAddress addr; addr.devAddress = 0; // Ensure all bits are zero addr.bmParent = _parent.bmAddress; if (is_hub) { addr.bmHub = 1; addr.bmAddress = ++hubCounter; } else { addr.bmHub = 0; addr.bmAddress = port; } thePool[index].address = addr; /* USB_HOST_SERIAL.print("Addr:"); USB_HOST_SERIAL.print(addr.bmHub, HEX); USB_HOST_SERIAL.print("."); USB_HOST_SERIAL.print(addr.bmParent, HEX); USB_HOST_SERIAL.print("."); USB_HOST_SERIAL.println(addr.bmAddress, HEX); */ return thePool[index].address.devAddress; } // Empty the pool entry virtual void FreeAddress(uint8_t addr) { // if the root hub is disconnected all the addresses should be initialized if (addr == 0x41) { InitAllAddresses(); return; } FreeAddressByIndex(FindAddressIndex(addr)); } // Return number of hubs attached // It can be helpful to find out if hubs are attached when getting the exact number of hubs. //uint8_t GetNumHubs() { return hubCounter; } //uint8_t GetNumDevices() { // uint8_t counter = 0; // for (uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) // if (thePool[i].address != 0); counter++; // return counter; //} };
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/address.h
C++
agpl-3.0
8,378
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once #ifndef _usb_h_ #error "Never include confdescparser.h directly; include Usb.h instead" #endif class UsbConfigXtracter { public: //virtual void ConfigXtract(const USB_FD_CONFIGURATION_DESCRIPTOR *conf) = 0; //virtual void InterfaceXtract(uint8_t conf, const USB_FD_INTERFACE_DESCRIPTOR *iface) = 0; virtual void EndpointXtract(uint8_t conf __attribute__((unused)), uint8_t iface __attribute__((unused)), uint8_t alt __attribute__((unused)), uint8_t proto __attribute__((unused)), const USB_FD_ENDPOINT_DESCRIPTOR *ep __attribute__((unused))) { } }; #define CP_MASK_COMPARE_CLASS 1 #define CP_MASK_COMPARE_SUBCLASS 2 #define CP_MASK_COMPARE_PROTOCOL 4 #define CP_MASK_COMPARE_ALL 7 // Configuration Descriptor Parser Class Template template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK> class ConfigDescParser : public USBReadParser { UsbConfigXtracter *theXtractor; MultiValueBuffer theBuffer; MultiByteValueParser valParser; ByteSkipper theSkipper; uint8_t varBuffer[16 /*sizeof(USB_FD_CONFIGURATION_DESCRIPTOR)*/]; uint8_t stateParseDescr; // ParseDescriptor state uint8_t dscrLen; // Descriptor length uint8_t dscrType; // Descriptor type bool isGoodInterface; // Appropriate interface flag uint8_t confValue; // Configuration value uint8_t protoValue; // Protocol value uint8_t ifaceNumber; // Interface number uint8_t ifaceAltSet; // Interface alternate settings bool UseOr; bool ParseDescriptor(uint8_t **pp, uint16_t *pcntdn); void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc); public: void SetOR() { UseOr = true; } ConfigDescParser(UsbConfigXtracter *xtractor); void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset); }; template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK> ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::ConfigDescParser(UsbConfigXtracter *xtractor) : theXtractor(xtractor), stateParseDescr(0), dscrLen(0), dscrType(0), UseOr(false) { theBuffer.pValue = varBuffer; valParser.Initialize(&theBuffer); theSkipper.Initialize(&theBuffer); }; template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK> void ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset __attribute__((unused))) { uint16_t cntdn = (uint16_t)len; uint8_t *p = (uint8_t*)pbuf; while (cntdn) if (!ParseDescriptor(&p, &cntdn)) return; } /* Parser for the configuration descriptor. Takes values for class, subclass, protocol fields in interface descriptor and compare masks for them. When the match is found, calls EndpointXtract passing buffer containing endpoint descriptor */ template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK> bool ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::ParseDescriptor(uint8_t **pp, uint16_t *pcntdn) { USB_FD_CONFIGURATION_DESCRIPTOR* ucd = reinterpret_cast<USB_FD_CONFIGURATION_DESCRIPTOR*>(varBuffer); USB_FD_INTERFACE_DESCRIPTOR* uid = reinterpret_cast<USB_FD_INTERFACE_DESCRIPTOR*>(varBuffer); switch (stateParseDescr) { case 0: theBuffer.valueSize = 2; valParser.Initialize(&theBuffer); stateParseDescr = 1; case 1: if (!valParser.Parse(pp, pcntdn)) return false; dscrLen = *((uint8_t*)theBuffer.pValue); dscrType = *((uint8_t*)theBuffer.pValue + 1); stateParseDescr = 2; case 2: // This is a sort of hack. Assuming that two bytes are all ready in the buffer // the pointer is positioned two bytes ahead in order for the rest of descriptor // to be read right after the size and the type fields. // This should be used carefully. varBuffer should be used directly to handle data // in the buffer. theBuffer.pValue = varBuffer + 2; stateParseDescr = 3; case 3: switch (dscrType) { case USB_DESCRIPTOR_INTERFACE: isGoodInterface = false; break; case USB_DESCRIPTOR_CONFIGURATION: case USB_DESCRIPTOR_ENDPOINT: case HID_DESCRIPTOR_HID: break; } theBuffer.valueSize = dscrLen - 2; valParser.Initialize(&theBuffer); stateParseDescr = 4; case 4: switch (dscrType) { case USB_DESCRIPTOR_CONFIGURATION: if (!valParser.Parse(pp, pcntdn)) return false; confValue = ucd->bConfigurationValue; break; case USB_DESCRIPTOR_INTERFACE: if (!valParser.Parse(pp, pcntdn)) return false; if ((MASK & CP_MASK_COMPARE_CLASS) && uid->bInterfaceClass != CLASS_ID) break; if ((MASK & CP_MASK_COMPARE_SUBCLASS) && uid->bInterfaceSubClass != SUBCLASS_ID) break; if (UseOr) { if ((!((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol))) break; } else if ((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol != PROTOCOL_ID) break; isGoodInterface = true; ifaceNumber = uid->bInterfaceNumber; ifaceAltSet = uid->bAlternateSetting; protoValue = uid->bInterfaceProtocol; break; case USB_DESCRIPTOR_ENDPOINT: if (!valParser.Parse(pp, pcntdn)) return false; if (isGoodInterface && theXtractor) theXtractor->EndpointXtract(confValue, ifaceNumber, ifaceAltSet, protoValue, (USB_FD_ENDPOINT_DESCRIPTOR*)varBuffer); break; //case HID_DESCRIPTOR_HID: // if (!valParser.Parse(pp, pcntdn)) return false; // PrintHidDescriptor((const USB_HID_DESCRIPTOR*)varBuffer); // break; default: if (!theSkipper.Skip(pp, pcntdn, dscrLen - 2)) return false; } theBuffer.pValue = varBuffer; stateParseDescr = 0; } return true; } template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK> void ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc) { Notify(PSTR("\r\n\r\nHID Descriptor:\r\n"), 0x80); Notify(PSTR("bDescLength:\t\t"), 0x80); PrintHex<uint8_t > (pDesc->bLength, 0x80); Notify(PSTR("\r\nbDescriptorType:\t"), 0x80); PrintHex<uint8_t > (pDesc->bDescriptorType, 0x80); Notify(PSTR("\r\nbcdHID:\t\t\t"), 0x80); PrintHex<uint16_t > (pDesc->bcdHID, 0x80); Notify(PSTR("\r\nbCountryCode:\t\t"), 0x80); PrintHex<uint8_t > (pDesc->bCountryCode, 0x80); Notify(PSTR("\r\nbNumDescriptors:\t"), 0x80); PrintHex<uint8_t > (pDesc->bNumDescriptors, 0x80); for (uint8_t i = 0; i < pDesc->bNumDescriptors; i++) { HID_CLASS_DESCRIPTOR_LEN_AND_TYPE *pLT = (HID_CLASS_DESCRIPTOR_LEN_AND_TYPE*)&(pDesc->bDescrType); Notify(PSTR("\r\nbDescrType:\t\t"), 0x80); PrintHex<uint8_t > (pLT[i].bDescrType, 0x80); Notify(PSTR("\r\nwDescriptorLength:\t"), 0x80); PrintHex<uint16_t > (pLT[i].wDescriptorLength, 0x80); } Notify(PSTR("\r\n"), 0x80); }
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/confdescparser.h
C++
agpl-3.0
8,160
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once #ifndef _usb_h_ #error "Never include hexdump.h directly; include Usb.h instead" #endif extern int UsbDEBUGlvl; template <class BASE_CLASS, class LEN_TYPE, class OFFSET_TYPE> class HexDumper : public BASE_CLASS { uint8_t byteCount; OFFSET_TYPE byteTotal; public: HexDumper() : byteCount(0), byteTotal(0) { }; void Initialize() { byteCount = 0; byteTotal = 0; }; void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset); }; template <class BASE_CLASS, class LEN_TYPE, class OFFSET_TYPE> void HexDumper<BASE_CLASS, LEN_TYPE, OFFSET_TYPE>::Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset __attribute__((unused))) { if (UsbDEBUGlvl >= 0x80) { // Fully bypass this block of code if we do not debug. for (LEN_TYPE j = 0; j < len; j++, byteCount++, byteTotal++) { if (!byteCount) { PrintHex<OFFSET_TYPE > (byteTotal, 0x80); E_Notify(PSTR(": "), 0x80); } PrintHex<uint8_t > (pbuf[j], 0x80); E_Notify(PSTR(" "), 0x80); if (byteCount == 15) { E_Notify(PSTR("\r\n"), 0x80); byteCount = 0xFF; } } } }
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/hexdump.h
C++
agpl-3.0
2,117
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once #ifndef _usb_h_ #error "Never include macros.h directly; include Usb.h instead" #endif //////////////////////////////////////////////////////////////////////////////// // HANDY MACROS //////////////////////////////////////////////////////////////////////////////// #define VALUE_BETWEEN(v,l,h) (((v)>(l)) && ((v)<(h))) #define VALUE_WITHIN(v,l,h) (((v)>=(l)) && ((v)<=(h))) #define output_pgm_message(wa,fp,mp,el) wa = &mp, fp((char *)pgm_read_pointer(wa), el) #define output_if_between(v,l,h,wa,fp,mp,el) if (VALUE_BETWEEN(v,l,h)) output_pgm_message(wa,fp,mp[v-(l+1)],el); #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) #ifndef __BYTE_GRABBING_DEFINED__ #define __BYTE_GRABBING_DEFINED__ 1 #ifdef BROKEN_OPTIMIZER_LITTLE_ENDIAN // Note: Use this if your compiler generates horrible assembler! #define BGRAB0(__usi__) (((uint8_t *)&(__usi__))[0]) #define BGRAB1(__usi__) (((uint8_t *)&(__usi__))[1]) #define BGRAB2(__usi__) (((uint8_t *)&(__usi__))[2]) #define BGRAB3(__usi__) (((uint8_t *)&(__usi__))[3]) #define BGRAB4(__usi__) (((uint8_t *)&(__usi__))[4]) #define BGRAB5(__usi__) (((uint8_t *)&(__usi__))[5]) #define BGRAB6(__usi__) (((uint8_t *)&(__usi__))[6]) #define BGRAB7(__usi__) (((uint8_t *)&(__usi__))[7]) #else // Note: The cast alone to uint8_t is actually enough. // GCC throws out the "& 0xFF", and the size is no different. // Some compilers need it. #define BGRAB0(__usi__) ((uint8_t)((__usi__) & 0xFF )) #define BGRAB1(__usi__) ((uint8_t)(((__usi__) >> 8) & 0xFF)) #define BGRAB2(__usi__) ((uint8_t)(((__usi__) >> 16) & 0xFF)) #define BGRAB3(__usi__) ((uint8_t)(((__usi__) >> 24) & 0xFF)) #define BGRAB4(__usi__) ((uint8_t)(((__usi__) >> 32) & 0xFF)) #define BGRAB5(__usi__) ((uint8_t)(((__usi__) >> 40) & 0xFF)) #define BGRAB6(__usi__) ((uint8_t)(((__usi__) >> 48) & 0xFF)) #define BGRAB7(__usi__) ((uint8_t)(((__usi__) >> 56) & 0xFF)) #endif #define BOVER1(__usi__) ((uint16_t)(__usi__) << 8) #define BOVER2(__usi__) ((uint32_t)(__usi__) << 16) #define BOVER3(__usi__) ((uint32_t)(__usi__) << 24) #define BOVER4(__usi__) ((uint64_t)(__usi__) << 32) #define BOVER5(__usi__) ((uint64_t)(__usi__) << 40) #define BOVER6(__usi__) ((uint64_t)(__usi__) << 48) #define BOVER7(__usi__) ((uint64_t)(__usi__) << 56) // These are the smallest and fastest ways I have found so far in pure C/C++. #define BMAKE16(__usc1__,__usc0__) ((uint16_t)((uint16_t)(__usc0__) | (uint16_t)BOVER1(__usc1__))) #define BMAKE32(__usc3__,__usc2__,__usc1__,__usc0__) ((uint32_t)((uint32_t)(__usc0__) | (uint32_t)BOVER1(__usc1__) | (uint32_t)BOVER2(__usc2__) | (uint32_t)BOVER3(__usc3__))) #define BMAKE64(__usc7__,__usc6__,__usc5__,__usc4__,__usc3__,__usc2__,__usc1__,__usc0__) ((uint64_t)((uint64_t)__usc0__ | (uint64_t)BOVER1(__usc1__) | (uint64_t)BOVER2(__usc2__) | (uint64_t)BOVER3(__usc3__) | (uint64_t)BOVER4(__usc4__) | (uint64_t)BOVER5(__usc5__) | (uint64_t)BOVER6(__usc6__) | (uint64_t)BOVER1(__usc7__))) #endif /* * Debug macros: Strings are stored in progmem (flash) instead of RAM. */ #define USBTRACE(s) (Notify(PSTR(s), 0x80)) #define USBTRACE1(s,l) (Notify(PSTR(s), l)) #define USBTRACE2(s,r) (Notify(PSTR(s), 0x80), D_PrintHex((r), 0x80), Notify(PSTR("\r\n"), 0x80)) #define USBTRACE3(s,r,l) (Notify(PSTR(s), l), D_PrintHex((r), l), Notify(PSTR("\r\n"), l))
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/macros.h
C
agpl-3.0
4,279
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #include "../../../inc/MarlinConfigPre.h" #if ENABLED(USB_FLASH_DRIVE_SUPPORT) && DISABLED(USE_UHS3_USB) #include "masstorage.h" const uint8_t BulkOnly::epDataInIndex = 1; const uint8_t BulkOnly::epDataOutIndex = 2; const uint8_t BulkOnly::epInterruptInIndex = 3; //////////////////////////////////////////////////////////////////////////////// // Interface code //////////////////////////////////////////////////////////////////////////////// /** * Get the capacity of the media * * @param lun Logical Unit Number * @return media capacity */ uint32_t BulkOnly::GetCapacity(uint8_t lun) { return LUNOk[lun] ? CurrentCapacity[lun] : 0UL; } /** * Get the sector (block) size used on the media * * @param lun Logical Unit Number * @return media sector size */ uint16_t BulkOnly::GetSectorSize(uint8_t lun) { return LUNOk[lun] ? CurrentSectorSize[lun] : 0U; } /** * Test if LUN is ready for use * * @param lun Logical Unit Number * @return true if LUN is ready for use */ bool BulkOnly::LUNIsGood(uint8_t lun) { return LUNOk[lun]; } /** * Test if LUN is write protected * * @param lun Logical Unit Number * @return cached status of write protect switch */ bool BulkOnly::WriteProtected(uint8_t lun) { return WriteOk[lun]; } /** * Wrap and execute a SCSI CDB with length of 6 * * @param cdb CDB to execute * @param buf_size Size of expected transaction * @param buf Buffer * @param dir MASS_CMD_DIR_IN | MASS_CMD_DIR_OUT * @return */ uint8_t BulkOnly::SCSITransaction6(CDB6_t *cdb, uint16_t buf_size, void *buf, uint8_t dir) { // promote buf_size to 32bits. CommandBlockWrapper cbw = CommandBlockWrapper(++dCBWTag, (uint32_t)buf_size, cdb, dir); //SetCurLUN(cdb->LUN); return (HandleSCSIError(Transaction(&cbw, buf_size, buf))); } /** * Wrap and execute a SCSI CDB with length of 10 * * @param cdb CDB to execute * @param buf_size Size of expected transaction * @param buf Buffer * @param dir MASS_CMD_DIR_IN | MASS_CMD_DIR_OUT * @return */ uint8_t BulkOnly::SCSITransaction10(CDB10_t *cdb, uint16_t buf_size, void *buf, uint8_t dir) { // promote buf_size to 32bits. CommandBlockWrapper cbw = CommandBlockWrapper(++dCBWTag, (uint32_t)buf_size, cdb, dir); //SetCurLUN(cdb->LUN); return (HandleSCSIError(Transaction(&cbw, buf_size, buf))); } /** * Lock or Unlock the tray or door on device. * Caution: Some devices with buggy firmware will lock up. * * @param lun Logical Unit Number * @param lock 1 to lock, 0 to unlock * @return */ uint8_t BulkOnly::LockMedia(uint8_t lun, uint8_t lock) { Notify(PSTR("\r\nLockMedia\r\n"), 0x80); Notify(PSTR("---------\r\n"), 0x80); CDB6_t cdb = CDB6_t(SCSI_CMD_PREVENT_REMOVAL, lun, (uint8_t)0, lock); return SCSITransaction6(&cdb, (uint16_t)0, nullptr, (uint8_t)MASS_CMD_DIR_IN); } /** * Media control, for spindle motor and media tray or door. * This includes CDROM, TAPE and anything with a media loader. * * @param lun Logical Unit Number * @param ctl 0x00 Stop Motor, 0x01 Start Motor, 0x02 Eject Media, 0x03 Load Media * @return 0 on success */ uint8_t BulkOnly::MediaCTL(uint8_t lun, uint8_t ctl) { Notify(PSTR("\r\nMediaCTL\r\n"), 0x80); Notify(PSTR("-----------------\r\n"), 0x80); uint8_t rcode = MASS_ERR_UNIT_NOT_READY; if (bAddress) { CDB6_t cdb = CDB6_t(SCSI_CMD_START_STOP_UNIT, lun, ctl & 0x03, 0); rcode = SCSITransaction6(&cdb, (uint16_t)0, nullptr, (uint8_t)MASS_CMD_DIR_OUT); } else SetCurLUN(lun); return rcode; } /** * Read data from media * * @param lun Logical Unit Number * @param addr LBA address on media to read * @param bsize size of a block (we should probably use the cached size) * @param blocks how many blocks to read * @param buf memory that is able to hold the requested data * @return 0 on success */ uint8_t BulkOnly::Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, uint8_t *buf) { if (!LUNOk[lun]) return MASS_ERR_NO_MEDIA; Notify(PSTR("\r\nRead LUN:\t"), 0x80); D_PrintHex<uint8_t> (lun, 0x90); Notify(PSTR("\r\nLBA:\t\t"), 0x90); D_PrintHex<uint32_t> (addr, 0x90); Notify(PSTR("\r\nblocks:\t\t"), 0x90); D_PrintHex<uint8_t> (blocks, 0x90); Notify(PSTR("\r\nblock size:\t"), 0x90); D_PrintHex<uint16_t> (bsize, 0x90); Notify(PSTR("\r\n---------\r\n"), 0x80); CDB10_t cdb = CDB10_t(SCSI_CMD_READ_10, lun, blocks, addr); again: uint8_t er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), buf, (uint8_t)MASS_CMD_DIR_IN); if (er == MASS_ERR_STALL) { MediaCTL(lun, 1); delay(150); if (!TestUnitReady(lun)) goto again; } return er; } /** * Write data to media * * @param lun Logical Unit Number * @param addr LBA address on media to write * @param bsize size of a block (we should probably use the cached size) * @param blocks how many blocks to write * @param buf memory that contains the data to write * @return 0 on success */ uint8_t BulkOnly::Write(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, const uint8_t * buf) { if (!LUNOk[lun]) return MASS_ERR_NO_MEDIA; if (!WriteOk[lun]) return MASS_ERR_WRITE_PROTECTED; Notify(PSTR("\r\nWrite LUN:\t"), 0x80); D_PrintHex<uint8_t> (lun, 0x90); Notify(PSTR("\r\nLBA:\t\t"), 0x90); D_PrintHex<uint32_t> (addr, 0x90); Notify(PSTR("\r\nblocks:\t\t"), 0x90); D_PrintHex<uint8_t> (blocks, 0x90); Notify(PSTR("\r\nblock size:\t"), 0x90); D_PrintHex<uint16_t> (bsize, 0x90); Notify(PSTR("\r\n---------\r\n"), 0x80); CDB10_t cdb = CDB10_t(SCSI_CMD_WRITE_10, lun, blocks, addr); again: uint8_t er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), (void*)buf, (uint8_t)MASS_CMD_DIR_OUT); if (er == MASS_ERR_WRITE_STALL) { MediaCTL(lun, 1); delay(150); if (!TestUnitReady(lun)) goto again; } return er; } // End of user functions, the remaining code below is driver internals. // Only developer serviceable parts below! //////////////////////////////////////////////////////////////////////////////// // Main driver code //////////////////////////////////////////////////////////////////////////////// BulkOnly::BulkOnly(USB *p) : pUsb(p), bAddress(0), bIface(0), bNumEP(1), qNextPollTime(0), bPollEnable(false), //dCBWTag(0), bLastUsbError(0) { ClearAllEP(); dCBWTag = 0; if (pUsb) pUsb->RegisterDeviceClass(this); } /** * USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET == success * We need to standardize either the rcode, or change the API to return values * so a signal that additional actions are required can be produced. * Some of these codes do exist already. * * TECHNICAL: We could do most of this code elsewhere, with the exception of checking the class instance. * Doing so would save some program memory when using multiple drivers. * * @param parent USB address of parent * @param port address of port on parent * @param lowspeed true if device is low speed * @return */ uint8_t BulkOnly::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { const uint8_t constBufSize = sizeof (USB_FD_DEVICE_DESCRIPTOR); uint8_t buf[constBufSize]; USB_FD_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_FD_DEVICE_DESCRIPTOR*>(buf); uint8_t rcode; UsbDevice *p = nullptr; EpInfo *oldep_ptr = nullptr; USBTRACE("MS ConfigureDevice\r\n"); ClearAllEP(); AddressPool &addrPool = pUsb->GetAddressPool(); if (bAddress) return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; // <TECHNICAL> // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); if (!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; if (!p->epinfo) { USBTRACE("epinfo\r\n"); return USB_ERROR_EPINFO_IS_NULL; } // Save old pointer to EP_RECORD of address 0 oldep_ptr = p->epinfo; // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence p->epinfo = epInfo; p->lowspeed = lowspeed; // Get device descriptor rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf); // Restore p->epinfo p->epinfo = oldep_ptr; if (rcode) goto FailGetDevDescr; // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); if (!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Steal and abuse from epInfo structure to save on memory. epInfo[1].epAddr = udd->bNumConfigurations; // </TECHNICAL> return USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET; FailGetDevDescr: #ifdef DEBUG_USB_HOST NotifyFailGetDevDescr(rcode); #endif rcode = USB_ERROR_FailGetDevDescr; Release(); return rcode; } /** * @param parent (not used) * @param port (not used) * @param lowspeed true if device is low speed * @return 0 for success */ uint8_t BulkOnly::Init(uint8_t parent __attribute__((unused)), uint8_t port __attribute__((unused)), bool lowspeed) { uint8_t rcode; uint8_t num_of_conf = epInfo[1].epAddr; // number of configurations epInfo[1].epAddr = 0; USBTRACE("MS Init\r\n"); AddressPool &addrPool = pUsb->GetAddressPool(); UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); if (!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; // Assign new address to the device delay(2000); rcode = pUsb->setAddr(0, 0, bAddress); if (rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; USBTRACE2("setAddr:", rcode); return rcode; } USBTRACE2("Addr:", bAddress); p->lowspeed = false; p = addrPool.GetUsbDevicePtr(bAddress); if (!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); if (rcode) goto FailSetDevTblEntry; USBTRACE2("NC:", num_of_conf); for (uint8_t i = 0; i < num_of_conf; i++) { ConfigDescParser< USB_CLASS_MASS_STORAGE, MASS_SUBCLASS_SCSI, MASS_PROTO_BBB, CP_MASK_COMPARE_CLASS | CP_MASK_COMPARE_SUBCLASS | CP_MASK_COMPARE_PROTOCOL > BulkOnlyParser(this); rcode = pUsb->getConfDescr(bAddress, 0, i, &BulkOnlyParser); if (rcode) goto FailGetConfDescr; if (bNumEP > 1) break; } if (bNumEP < 3) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Assign epInfo to epinfo pointer pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); USBTRACE2("Conf:", bConfNum); // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); if (rcode) goto FailSetConfDescr; //Linux does a 1sec delay after this. delay(1000); rcode = GetMaxLUN(&bMaxLUN); if (rcode) goto FailGetMaxLUN; if (bMaxLUN >= MASS_MAX_SUPPORTED_LUN) bMaxLUN = MASS_MAX_SUPPORTED_LUN - 1; ErrorMessage<uint8_t> (PSTR("MaxLUN"), bMaxLUN); delay(1000); // Delay a bit for slow firmware. for (uint8_t lun = 0; lun <= bMaxLUN; lun++) { InquiryResponse response; rcode = Inquiry(lun, sizeof (InquiryResponse), (uint8_t*) & response); if (rcode) { ErrorMessage<uint8_t> (PSTR("Inquiry"), rcode); } else { #if 0 printf("LUN %i `", lun); uint8_t *buf = response.VendorID; for (int i = 0; i < 28; i++) printf("%c", buf[i]); printf("'\r\nQualifier %1.1X ", response.PeripheralQualifier); printf("Device type %2.2X ", response.DeviceType); printf("RMB %1.1X ", response.Removable); printf("SSCS %1.1X ", response.SCCS); uint8_t sv = response.Version; printf("SCSI version %2.2X\r\nDevice conforms to ", sv); switch (sv) { case 0: printf("No specific"); break; case 1: printf("ANSI X3.131-1986 (ANSI 1)"); break; case 2: printf("ANSI X3.131-1994 (ANSI 2)"); break; case 3: printf("ANSI INCITS 301-1997 (SPC)"); break; case 4: printf("ANSI INCITS 351-2001 (SPC-2)"); break; case 5: printf("ANSI INCITS 408-2005 (SPC-4)"); break; case 6: printf("T10/1731-D (SPC-4)"); break; default: printf("unknown"); } printf(" standards.\r\n"); #endif uint8_t tries = 0xF0; while ((rcode = TestUnitReady(lun))) { if (rcode == 0x08) break; // break on no media, this is OK to do. // try to lock media and spin up if (tries < 14) { LockMedia(lun, 1); MediaCTL(lun, 1); // I actually have a USB stick that needs this! } else delay(2 * (tries + 1)); tries++; if (!tries) break; } if (!rcode) { delay(1000); LUNOk[lun] = CheckLUN(lun); if (!LUNOk[lun]) LUNOk[lun] = CheckLUN(lun); } } } CheckMedia(); rcode = OnInit(); if (rcode) goto FailOnInit; #ifdef DEBUG_USB_HOST USBTRACE("MS configured\r\n\r\n"); #endif bPollEnable = true; //USBTRACE("Poll enabled\r\n"); return 0; FailSetConfDescr: #ifdef DEBUG_USB_HOST NotifyFailSetConfDescr(); goto Fail; #endif FailOnInit: #ifdef DEBUG_USB_HOST USBTRACE("OnInit:"); goto Fail; #endif FailGetMaxLUN: #ifdef DEBUG_USB_HOST USBTRACE("GetMaxLUN:"); goto Fail; #endif //#ifdef DEBUG_USB_HOST // FailInvalidSectorSize: // USBTRACE("Sector Size is NOT VALID: "); // goto Fail; //#endif FailSetDevTblEntry: #ifdef DEBUG_USB_HOST NotifyFailSetDevTblEntry(); goto Fail; #endif FailGetConfDescr: #ifdef DEBUG_USB_HOST NotifyFailGetConfDescr(); #endif #ifdef DEBUG_USB_HOST Fail: NotifyFail(rcode); #endif Release(); return rcode; } /** * For driver use only. * * @param conf * @param iface * @param alt * @param proto * @param pep */ void BulkOnly::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto __attribute__((unused)), const USB_FD_ENDPOINT_DESCRIPTOR * pep) { ErrorMessage<uint8_t> (PSTR("Conf.Val"), conf); ErrorMessage<uint8_t> (PSTR("Iface Num"), iface); ErrorMessage<uint8_t> (PSTR("Alt.Set"), alt); bConfNum = conf; uint8_t index; #if 1 if ((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_BULK) { index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; // Fill in the endpoint info structure epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F); epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize; epInfo[index].bmSndToggle = 0; epInfo[index].bmRcvToggle = 0; bNumEP++; PrintEndpointDescriptor(pep); } #else if ((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_INTERRUPT && (pep->bEndpointAddress & 0x80) == 0x80) index = epInterruptInIndex; else if ((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_BULK) index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; else return; // Fill in the endpoint info structure epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F); epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize; epInfo[index].bmSndToggle = 0; epInfo[index].bmRcvToggle = 0; bNumEP++; PrintEndpointDescriptor(pep); #endif } /** * For driver use only. * * @return */ uint8_t BulkOnly::Release() { ClearAllEP(); pUsb->GetAddressPool().FreeAddress(bAddress); return 0; } /** * For driver use only. * * @param lun Logical Unit Number * @return true if LUN is ready for use. */ bool BulkOnly::CheckLUN(uint8_t lun) { uint8_t rcode; Capacity capacity; for (uint8_t i = 0; i < 8; i++) capacity.data[i] = 0; rcode = ReadCapacity10(lun, (uint8_t*)capacity.data); if (rcode) { //printf(">>>>>>>>>>>>>>>>ReadCapacity returned %i\r\n", rcode); return false; } ErrorMessage<uint8_t> (PSTR(">>>>>>>>>>>>>>>>CAPACITY OK ON LUN"), lun); for (uint8_t i = 0; i < 8 /*sizeof (Capacity)*/; i++) D_PrintHex<uint8_t> (capacity.data[i], 0x80); Notify(PSTR("\r\n\r\n"), 0x80); // Only 512/1024/2048/4096 are valid values! uint32_t c = BMAKE32(capacity.data[4], capacity.data[5], capacity.data[6], capacity.data[7]); if (c != 0x0200UL && c != 0x0400UL && c != 0x0800UL && c != 0x1000UL) return false; // Store capacity information. CurrentSectorSize[lun] = (uint16_t)(c); // & 0xFFFF); CurrentCapacity[lun] = BMAKE32(capacity.data[0], capacity.data[1], capacity.data[2], capacity.data[3]) + 1; if (CurrentCapacity[lun] == /*0xFFFFFFFFUL */ 0x01UL || CurrentCapacity[lun] == 0x00UL) { // Buggy firmware will report 0xFFFFFFFF or 0 for no media if (CurrentCapacity[lun]) ErrorMessage<uint8_t> (PSTR(">>>>>>>>>>>>>>>>BUGGY FIRMWARE. CAPACITY FAIL ON LUN"), lun); return false; } delay(20); Page3F(lun); return !TestUnitReady(lun); } /** * For driver use only. * * Scan for media change on all LUNs */ void BulkOnly::CheckMedia() { for (uint8_t lun = 0; lun <= bMaxLUN; lun++) { if (TestUnitReady(lun)) { LUNOk[lun] = false; continue; } if (!LUNOk[lun]) LUNOk[lun] = CheckLUN(lun); } #if 0 printf("}}}}}}}}}}}}}}}}STATUS "); for (uint8_t lun = 0; lun <= bMaxLUN; lun++) printf(LUNOk[lun] ? "#" : "."); printf("\r\n"); #endif qNextPollTime = (uint32_t)millis() + 2000; } /** * For driver use only. * * @return */ uint8_t BulkOnly::Poll() { //uint8_t rcode = 0; if (!bPollEnable) return 0; if ((int32_t)((uint32_t)millis() - qNextPollTime) >= 0L) CheckMedia(); //rcode = 0; return 0; } //////////////////////////////////////////////////////////////////////////////// // SCSI code //////////////////////////////////////////////////////////////////////////////// /** * For driver use only. * * @param plun * @return */ uint8_t BulkOnly::GetMaxLUN(uint8_t *plun) { uint8_t ret = pUsb->ctrlReq(bAddress, 0, bmREQ_MASSIN, MASS_REQ_GET_MAX_LUN, 0, 0, bIface, 1, 1, plun, nullptr); if (ret == hrSTALL) *plun = 0; return 0; } /** * For driver use only. Used during Driver Init * * @param lun Logical Unit Number * @param bsize * @param buf * @return */ uint8_t BulkOnly::Inquiry(uint8_t lun, uint16_t bsize, uint8_t *buf) { Notify(PSTR("\r\nInquiry\r\n"), 0x80); Notify(PSTR("---------\r\n"), 0x80); CDB6_t cdb = CDB6_t(SCSI_CMD_INQUIRY, lun, 0UL, (uint8_t)bsize, 0); uint8_t rc = SCSITransaction6(&cdb, bsize, buf, (uint8_t)MASS_CMD_DIR_IN); return rc; } /** * For driver use only. * * @param lun Logical Unit Number * @return */ uint8_t BulkOnly::TestUnitReady(uint8_t lun) { //SetCurLUN(lun); if (!bAddress) return MASS_ERR_UNIT_NOT_READY; Notify(PSTR("\r\nTestUnitReady\r\n"), 0x80); Notify(PSTR("-----------------\r\n"), 0x80); CDB6_t cdb = CDB6_t(SCSI_CMD_TEST_UNIT_READY, lun, (uint8_t)0, 0); return SCSITransaction6(&cdb, 0, nullptr, (uint8_t)MASS_CMD_DIR_IN); } /** * For driver use only. * * @param lun Logical Unit Number * @param pc * @param page * @param subpage * @param len * @param pbuf * @return */ uint8_t BulkOnly::ModeSense6(uint8_t lun, uint8_t pc, uint8_t page, uint8_t subpage, uint8_t len, uint8_t * pbuf) { Notify(PSTR("\r\rModeSense\r\n"), 0x80); Notify(PSTR("------------\r\n"), 0x80); CDB6_t cdb = CDB6_t(SCSI_CMD_MODE_SENSE_6, lun, (uint32_t)((((pc << 6) | page) << 8) | subpage), len, 0); return SCSITransaction6(&cdb, len, pbuf, (uint8_t)MASS_CMD_DIR_IN); } /** * For driver use only. * * @param lun Logical Unit Number * @param bsize * @param buf * @return */ uint8_t BulkOnly::ReadCapacity10(uint8_t lun, uint8_t *buf) { Notify(PSTR("\r\nReadCapacity\r\n"), 0x80); Notify(PSTR("---------------\r\n"), 0x80); CDB10_t cdb = CDB10_t(SCSI_CMD_READ_CAPACITY_10, lun); return SCSITransaction10(&cdb, 8, buf, (uint8_t)MASS_CMD_DIR_IN); } /** * For driver use only. * * Page 3F contains write protect status. * * @param lun Logical Unit Number to test. * @return Write protect switch status. */ uint8_t BulkOnly::Page3F(uint8_t lun) { uint8_t buf[192]; for (int i = 0; i < 192; i++) { buf[i] = 0x00; } WriteOk[lun] = true; #ifdef SKIP_WRITE_PROTECT return 0; #endif uint8_t rc = ModeSense6(lun, 0, 0x3F, 0, 192, buf); if (!rc) { WriteOk[lun] = ((buf[2] & 0x80) == 0); Notify(PSTR("Mode Sense: "), 0x80); for (int i = 0; i < 4; i++) { D_PrintHex<uint8_t> (buf[i], 0x80); Notify(PSTR(" "), 0x80); } Notify(PSTR("\r\n"), 0x80); } return rc; } /** * For driver use only. * * @param lun Logical Unit Number * @param size * @param buf * @return */ uint8_t BulkOnly::RequestSense(uint8_t lun, uint16_t size, uint8_t *buf) { Notify(PSTR("\r\nRequestSense\r\n"), 0x80); Notify(PSTR("----------------\r\n"), 0x80); CDB6_t cdb = CDB6_t(SCSI_CMD_REQUEST_SENSE, lun, 0UL, (uint8_t)size, 0); CommandBlockWrapper cbw = CommandBlockWrapper(++dCBWTag, (uint32_t)size, &cdb, (uint8_t)MASS_CMD_DIR_IN); //SetCurLUN(lun); return Transaction(&cbw, size, buf); } //////////////////////////////////////////////////////////////////////////////// // USB code //////////////////////////////////////////////////////////////////////////////// /** * For driver use only. * * @param index * @return */ uint8_t BulkOnly::ClearEpHalt(uint8_t index) { if (index == 0) return 0; uint8_t ret = 0; while ((ret = (pUsb->ctrlReq(bAddress, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_STANDARD | USB_SETUP_RECIPIENT_ENDPOINT, USB_REQUEST_CLEAR_FEATURE, USB_FEATURE_ENDPOINT_HALT, 0, ((index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr), 0, 0, nullptr, nullptr)) == 0x01)) delay(6); if (ret) { ErrorMessage<uint8_t> (PSTR("ClearEpHalt"), ret); ErrorMessage<uint8_t> (PSTR("EP"), ((index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr)); return ret; } epInfo[index].bmSndToggle = 0; epInfo[index].bmRcvToggle = 0; return 0; } /** * For driver use only. */ void BulkOnly::Reset() { while (pUsb->ctrlReq(bAddress, 0, bmREQ_MASSOUT, MASS_REQ_BOMSR, 0, 0, bIface, 0, 0, nullptr, nullptr) == 0x01) delay(6); } /** * For driver use only. * * @return 0 if successful */ uint8_t BulkOnly::ResetRecovery() { Notify(PSTR("\r\nResetRecovery\r\n"), 0x80); Notify(PSTR("-----------------\r\n"), 0x80); delay(6); Reset(); delay(6); ClearEpHalt(epDataInIndex); delay(6); bLastUsbError = ClearEpHalt(epDataOutIndex); delay(6); return bLastUsbError; } /** * For driver use only. * * Clear all EP data and clear all LUN status */ void BulkOnly::ClearAllEP() { for (uint8_t i = 0; i < MASS_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].bmSndToggle = 0; epInfo[i].bmRcvToggle = 0; epInfo[i].bmNakPower = USB_NAK_DEFAULT; } for (uint8_t i = 0; i < MASS_MAX_SUPPORTED_LUN; i++) { LUNOk[i] = false; WriteOk[i] = false; CurrentCapacity[i] = 0UL; CurrentSectorSize[i] = 0; } bIface = 0; bNumEP = 1; bAddress = 0; qNextPollTime = 0; bPollEnable = false; bLastUsbError = 0; bMaxLUN = 0; bTheLUN = 0; } /** * For driver use only. * * @param pcsw * @param pcbw * @return */ bool BulkOnly::IsValidCSW(CommandStatusWrapper *pcsw, CommandBlockWrapperBase *pcbw) { if (pcsw->dCSWSignature != MASS_CSW_SIGNATURE) { Notify(PSTR("CSW:Sig error\r\n"), 0x80); return false; } if (pcsw->dCSWTag != pcbw->dCBWTag) { Notify(PSTR("CSW:Wrong tag\r\n"), 0x80); return false; } return true; } /** * For driver use only. * * @param error * @param index * @return */ uint8_t BulkOnly::HandleUsbError(uint8_t error, uint8_t index) { uint8_t count = 3; bLastUsbError = error; //if (error) //ClearEpHalt(index); while (error && count) { if (error != hrSUCCESS) { ErrorMessage<uint8_t> (PSTR("USB Error"), error); ErrorMessage<uint8_t> (PSTR("Index"), index); } switch (error) { // case hrWRONGPID: case hrSUCCESS: return MASS_ERR_SUCCESS; case hrBUSY: return MASS_ERR_UNIT_BUSY; // SIE is busy, just hang out and try again. case hrTIMEOUT: case hrJERR: return MASS_ERR_DEVICE_DISCONNECTED; case hrSTALL: if (index) { ClearEpHalt(index); return (index == epDataInIndex) ? MASS_ERR_STALL : MASS_ERR_WRITE_STALL; } return MASS_ERR_STALL; case hrNAK: return index ? MASS_ERR_UNIT_BUSY : MASS_ERR_UNIT_BUSY; case hrTOGERR: // Handle a super rare corner case, where toggles become de-synced. // I've only run into one device that has this firmware bug, and this is // the only clean way to get back into sync with the buggy device firmware. // --AJK if (bAddress && bConfNum) { error = pUsb->setConf(bAddress, 0, bConfNum); if (error) break; } return MASS_ERR_SUCCESS; default: ErrorMessage<uint8_t> (PSTR("\r\nUSB"), error); return MASS_ERR_GENERAL_USB_ERROR; } count--; } // while return ((error && !count) ? MASS_ERR_GENERAL_USB_ERROR : MASS_ERR_SUCCESS); } /** * For driver use only. * * @param pcbw * @param buf_size * @param buf * @param flags * @return */ uint8_t BulkOnly::Transaction(CommandBlockWrapper *pcbw, uint16_t buf_size, void *buf OPTARG(MS_WANT_PARSER, uint8_t flags/*=0*/) ) { #if MS_WANT_PARSER uint16_t bytes = (pcbw->dCBWDataTransferLength > buf_size) ? buf_size : pcbw->dCBWDataTransferLength; printf("Transfersize %i\r\n", bytes); delay(1000); bool callback = (flags & MASS_TRANS_FLG_CALLBACK) == MASS_TRANS_FLG_CALLBACK; #else uint16_t bytes = buf_size; #endif bool write = (pcbw->bmCBWFlags & MASS_CMD_DIR_IN) != MASS_CMD_DIR_IN; uint8_t ret = 0; uint8_t usberr; CommandStatusWrapper csw; // up here, we allocate ahead to save cpu cycles. SetCurLUN(pcbw->bmCBWLUN); ErrorMessage<uint32_t> (PSTR("CBW.dCBWTag"), pcbw->dCBWTag); while ((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, sizeof (CommandBlockWrapper), (uint8_t*)pcbw)) == hrBUSY) delay(1); ret = HandleUsbError(usberr, epDataOutIndex); //ret = HandleUsbError(pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, sizeof (CommandBlockWrapper), (uint8_t*)pcbw), epDataOutIndex); if (ret) ErrorMessage<uint8_t> (PSTR("============================ CBW"), ret); else { if (bytes) { if (!write) { #if MS_WANT_PARSER if (callback) { uint8_t rbuf[bytes]; while ((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, rbuf)) == hrBUSY) delay(1); if (usberr == hrSUCCESS) ((USBReadParser*)buf)->Parse(bytes, rbuf, 0); } else #endif { while ((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*)buf)) == hrBUSY) delay(1); } ret = HandleUsbError(usberr, epDataInIndex); } else { while ((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, bytes, (uint8_t*)buf)) == hrBUSY) delay(1); ret = HandleUsbError(usberr, epDataOutIndex); } if (ret) ErrorMessage<uint8_t> (PSTR("============================ DAT"), ret); } } bytes = sizeof (CommandStatusWrapper); int tries = 2; while (tries--) { while ((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*) & csw)) == hrBUSY) delay(1); if (!usberr) break; ClearEpHalt(epDataInIndex); if (tries) ResetRecovery(); } if (!ret) { Notify(PSTR("CBW:\t\tOK\r\n"), 0x80); Notify(PSTR("Data Stage:\tOK\r\n"), 0x80); } else { // Throw away csw, IT IS NOT OF ANY USE. ResetRecovery(); return ret; } ret = HandleUsbError(usberr, epDataInIndex); if (ret) ErrorMessage<uint8_t> (PSTR("============================ CSW"), ret); if (usberr == hrSUCCESS) { if (IsValidCSW(&csw, pcbw)) { //ErrorMessage<uint32_t> (PSTR("CSW.dCBWTag"), csw.dCSWTag); //ErrorMessage<uint8_t> (PSTR("bCSWStatus"), csw.bCSWStatus); //ErrorMessage<uint32_t> (PSTR("dCSWDataResidue"), csw.dCSWDataResidue); Notify(PSTR("CSW:\t\tOK\r\n\r\n"), 0x80); return csw.bCSWStatus; } else { // NOTE! Sometimes this is caused by the reported residue being wrong. // Get a different device. It isn't compliant, and should have never passed Q&A. // I own one... 05e3:0701 Genesys Logic, Inc. USB 2.0 IDE Adapter. // Other devices that exhibit this behavior exist in the wild too. // Be sure to check quirks in the Linux source code before reporting a bug. --xxxajk Notify(PSTR("Invalid CSW\r\n"), 0x80); ResetRecovery(); //return MASS_ERR_SUCCESS; return MASS_ERR_INVALID_CSW; } } return ret; } /** * For driver use only. * * @param lun Logical Unit Number * @return */ uint8_t BulkOnly::SetCurLUN(uint8_t lun) { if (lun > bMaxLUN) return MASS_ERR_INVALID_LUN; bTheLUN = lun; return MASS_ERR_SUCCESS; } /** * For driver use only. * * @param status * @return */ uint8_t BulkOnly::HandleSCSIError(uint8_t status) { uint8_t ret = 0; switch (status) { case 0: return MASS_ERR_SUCCESS; case 2: ErrorMessage<uint8_t> (PSTR("Phase Error"), status); ErrorMessage<uint8_t> (PSTR("LUN"), bTheLUN); ResetRecovery(); return MASS_ERR_GENERAL_SCSI_ERROR; case 1: ErrorMessage<uint8_t> (PSTR("SCSI Error"), status); ErrorMessage<uint8_t> (PSTR("LUN"), bTheLUN); RequestSenseResponce rsp; ret = RequestSense(bTheLUN, sizeof (RequestSenseResponce), (uint8_t*) & rsp); if (ret) return MASS_ERR_GENERAL_SCSI_ERROR; ErrorMessage<uint8_t> (PSTR("Response Code"), rsp.bResponseCode); if (rsp.bResponseCode & 0x80) { Notify(PSTR("Information field: "), 0x80); for (int i = 0; i < 4; i++) { D_PrintHex<uint8_t> (rsp.CmdSpecificInformation[i], 0x80); Notify(PSTR(" "), 0x80); } Notify(PSTR("\r\n"), 0x80); } ErrorMessage<uint8_t> (PSTR("Sense Key"), rsp.bmSenseKey); ErrorMessage<uint8_t> (PSTR("Add Sense Code"), rsp.bAdditionalSenseCode); ErrorMessage<uint8_t> (PSTR("Add Sense Qual"), rsp.bAdditionalSenseQualifier); // warning, this is not testing ASQ, only SK and ASC. switch (rsp.bmSenseKey) { case SCSI_S_UNIT_ATTENTION: switch (rsp.bAdditionalSenseCode) { case SCSI_ASC_MEDIA_CHANGED: return MASS_ERR_MEDIA_CHANGED; default: return MASS_ERR_UNIT_NOT_READY; } case SCSI_S_NOT_READY: switch (rsp.bAdditionalSenseCode) { case SCSI_ASC_MEDIUM_NOT_PRESENT: return MASS_ERR_NO_MEDIA; default: return MASS_ERR_UNIT_NOT_READY; } case SCSI_S_ILLEGAL_REQUEST: switch (rsp.bAdditionalSenseCode) { case SCSI_ASC_LBA_OUT_OF_RANGE: return MASS_ERR_BAD_LBA; default: return MASS_ERR_CMD_NOT_SUPPORTED; } default: return MASS_ERR_GENERAL_SCSI_ERROR; } // case 4: return MASS_ERR_UNIT_BUSY; // Busy means retry later. // case 0x05/0x14: we stalled out // case 0x15/0x16: we naked out. default: ErrorMessage<uint8_t> (PSTR("Gen SCSI Err"), status); ErrorMessage<uint8_t> (PSTR("LUN"), bTheLUN); return status; } // switch } //////////////////////////////////////////////////////////////////////////////// // Debugging code //////////////////////////////////////////////////////////////////////////////// /** * @param ep_ptr */ void BulkOnly::PrintEndpointDescriptor(const USB_FD_ENDPOINT_DESCRIPTOR * ep_ptr) { Notify(PSTR("Endpoint descriptor:"), 0x80); Notify(PSTR("\r\nLength:\t\t"), 0x80); D_PrintHex<uint8_t> (ep_ptr->bLength, 0x80); Notify(PSTR("\r\nType:\t\t"), 0x80); D_PrintHex<uint8_t> (ep_ptr->bDescriptorType, 0x80); Notify(PSTR("\r\nAddress:\t"), 0x80); D_PrintHex<uint8_t> (ep_ptr->bEndpointAddress, 0x80); Notify(PSTR("\r\nAttributes:\t"), 0x80); D_PrintHex<uint8_t> (ep_ptr->bmAttributes, 0x80); Notify(PSTR("\r\nMaxPktSize:\t"), 0x80); D_PrintHex<uint16_t> (ep_ptr->wMaxPacketSize, 0x80); Notify(PSTR("\r\nPoll Intrv:\t"), 0x80); D_PrintHex<uint8_t> (ep_ptr->bInterval, 0x80); Notify(PSTR("\r\n"), 0x80); } //////////////////////////////////////////////////////////////////////////////// // misc/to kill/to-do //////////////////////////////////////////////////////////////////////////////// /* We won't be needing this... */ uint8_t BulkOnly::Read(uint8_t lun __attribute__((unused)), uint32_t addr __attribute__((unused)), uint16_t bsize __attribute__((unused)), uint8_t blocks __attribute__((unused)), USBReadParser * prs __attribute__((unused))) { #if MS_WANT_PARSER if (!LUNOk[lun]) return MASS_ERR_NO_MEDIA; Notify(PSTR("\r\nRead (With parser)\r\n"), 0x80); Notify(PSTR("---------\r\n"), 0x80); CommandBlockWrapper cbw = CommandBlockWrapper(); cbw.dCBWSignature = MASS_CBW_SIGNATURE; cbw.dCBWTag = ++dCBWTag; cbw.dCBWDataTransferLength = ((uint32_t)bsize * blocks); cbw.bmCBWFlags = MASS_CMD_DIR_IN, cbw.bmCBWLUN = lun; cbw.bmCBWCBLength = 10; cbw.CBWCB[0] = SCSI_CMD_READ_10; cbw.CBWCB[8] = blocks; cbw.CBWCB[2] = ((addr >> 24) & 0xFF); cbw.CBWCB[3] = ((addr >> 16) & 0xFF); cbw.CBWCB[4] = ((addr >> 8) & 0xFF); cbw.CBWCB[5] = (addr & 0xFF); return HandleSCSIError(Transaction(&cbw, bsize, prs, 1)); #else return MASS_ERR_NOT_IMPLEMENTED; #endif } #endif // USB_FLASH_DRIVE_SUPPORT
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/masstorage.cpp
C++
agpl-3.0
35,419
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once // Cruft removal, makes driver smaller, faster. #ifndef MS_WANT_PARSER #define MS_WANT_PARSER 0 #endif #include "Usb.h" #define bmREQ_MASSOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE #define bmREQ_MASSIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE // Mass Storage Subclass Constants #define MASS_SUBCLASS_SCSI_NOT_REPORTED 0x00 // De facto use #define MASS_SUBCLASS_RBC 0x01 #define MASS_SUBCLASS_ATAPI 0x02 // MMC-5 (ATAPI) #define MASS_SUBCLASS_OBSOLETE1 0x03 // Was QIC-157 #define MASS_SUBCLASS_UFI 0x04 // Specifies how to interface Floppy Disk Drives to USB #define MASS_SUBCLASS_OBSOLETE2 0x05 // Was SFF-8070i #define MASS_SUBCLASS_SCSI 0x06 // SCSI Transparent Command Set #define MASS_SUBCLASS_LSDFS 0x07 // Specifies how host has to negotiate access before trying SCSI #define MASS_SUBCLASS_IEEE1667 0x08 // Mass Storage Class Protocols #define MASS_PROTO_CBI 0x00 // CBI (with command completion interrupt) #define MASS_PROTO_CBI_NO_INT 0x01 // CBI (without command completion interrupt) #define MASS_PROTO_OBSOLETE 0x02 #define MASS_PROTO_BBB 0x50 // Bulk Only Transport #define MASS_PROTO_UAS 0x62 // Request Codes #define MASS_REQ_ADSC 0x00 #define MASS_REQ_GET 0xFC #define MASS_REQ_PUT 0xFD #define MASS_REQ_GET_MAX_LUN 0xFE #define MASS_REQ_BOMSR 0xFF // Bulk-Only Mass Storage Reset #define MASS_CBW_SIGNATURE 0x43425355 #define MASS_CSW_SIGNATURE 0x53425355 #define MASS_CMD_DIR_OUT 0 // (0 << 7) #define MASS_CMD_DIR_IN 0x80 //(1 << 7) /* * Reference documents from T10 (https://www.t10.org) * SCSI Primary Commands - 3 (SPC-3) * SCSI Block Commands - 2 (SBC-2) * Multi-Media Commands - 5 (MMC-5) */ /* Group 1 commands (CDB's here are should all be 6-bytes) */ #define SCSI_CMD_TEST_UNIT_READY 0x00 #define SCSI_CMD_REQUEST_SENSE 0x03 #define SCSI_CMD_FORMAT_UNIT 0x04 #define SCSI_CMD_READ_6 0x08 #define SCSI_CMD_WRITE_6 0x0A #define SCSI_CMD_INQUIRY 0x12 #define SCSI_CMD_MODE_SELECT_6 0x15 #define SCSI_CMD_MODE_SENSE_6 0x1A #define SCSI_CMD_START_STOP_UNIT 0x1B #define SCSI_CMD_PREVENT_REMOVAL 0x1E /* Group 2 Commands (CDB's here are 10-bytes) */ #define SCSI_CMD_READ_FORMAT_CAPACITIES 0x23 #define SCSI_CMD_READ_CAPACITY_10 0x25 #define SCSI_CMD_READ_10 0x28 #define SCSI_CMD_WRITE_10 0x2A #define SCSI_CMD_SEEK_10 0x2B #define SCSI_CMD_ERASE_10 0x2C #define SCSI_CMD_WRITE_AND_VERIFY_10 0x2E #define SCSI_CMD_VERIFY_10 0x2F #define SCSI_CMD_SYNCHRONIZE_CACHE 0x35 #define SCSI_CMD_WRITE_BUFFER 0x3B #define SCSI_CMD_READ_BUFFER 0x3C #define SCSI_CMD_READ_SUBCHANNEL 0x42 #define SCSI_CMD_READ_TOC 0x43 #define SCSI_CMD_READ_HEADER 0x44 #define SCSI_CMD_PLAY_AUDIO_10 0x45 #define SCSI_CMD_GET_CONFIGURATION 0x46 #define SCSI_CMD_PLAY_AUDIO_MSF 0x47 #define SCSI_CMD_PLAY_AUDIO_TI 0x48 #define SCSI_CMD_PLAY_TRACK_REL_10 0x49 #define SCSI_CMD_GET_EVENT_STATUS 0x4A #define SCSI_CMD_PAUSE_RESUME 0x4B #define SCSI_CMD_READ_DISC_INFORMATION 0x51 #define SCSI_CMD_READ_TRACK_INFORMATION 0x52 #define SCSI_CMD_RESERVE_TRACK 0x53 #define SCSI_CMD_SEND_OPC_INFORMATION 0x54 #define SCSI_CMD_MODE_SELECT_10 0x55 #define SCSI_CMD_REPAIR_TRACK 0x58 #define SCSI_CMD_MODE_SENSE_10 0x5A #define SCSI_CMD_CLOSE_TRACK_SESSION 0x5B #define SCSI_CMD_READ_BUFFER_CAPACITY 0x5C #define SCSI_CMD_SEND_CUE_SHEET 0x5D /* Group 5 Commands (CDB's here are 12-bytes) */ #define SCSI_CMD_REPORT_LUNS 0xA0 #define SCSI_CMD_BLANK 0xA1 #define SCSI_CMD_SECURITY_PROTOCOL_IN 0xA2 #define SCSI_CMD_SEND_KEY 0xA3 #define SCSI_CMD_REPORT_KEY 0xA4 #define SCSI_CMD_PLAY_AUDIO_12 0xA5 #define SCSI_CMD_LOAD_UNLOAD 0xA6 #define SCSI_CMD_SET_READ_AHEAD 0xA7 #define SCSI_CMD_READ_12 0xA8 #define SCSI_CMD_PLAY_TRACK_REL_12 0xA9 #define SCSI_CMD_WRITE_12 0xAA #define SCSI_CMD_READ_MEDIA_SERIAL_12 0xAB #define SCSI_CMD_GET_PERFORMANCE 0xAC #define SCSI_CMD_READ_DVD_STRUCTURE 0xAD #define SCSI_CMD_SECURITY_PROTOCOL_OUT 0xB5 #define SCSI_CMD_SET_STREAMING 0xB6 #define SCSI_CMD_READ_MSF 0xB9 #define SCSI_CMD_SET_SPEED 0xBB #define SCSI_CMD_MECHANISM_STATUS 0xBD #define SCSI_CMD_READ_CD 0xBE #define SCSI_CMD_SEND_DISC_STRUCTURE 0xBF /* Vendor-unique Commands, included for completeness */ #define SCSI_CMD_CD_PLAYBACK_STATUS 0xC4 /* SONY unique */ #define SCSI_CMD_PLAYBACK_CONTROL 0xC9 /* SONY unique */ #define SCSI_CMD_READ_CDDA 0xD8 /* Vendor unique */ #define SCSI_CMD_READ_CDXA 0xDB /* Vendor unique */ #define SCSI_CMD_READ_ALL_SUBCODES 0xDF /* Vendor unique */ /* SCSI error codes */ #define SCSI_S_NOT_READY 0x02 #define SCSI_S_MEDIUM_ERROR 0x03 #define SCSI_S_ILLEGAL_REQUEST 0x05 #define SCSI_S_UNIT_ATTENTION 0x06 #define SCSI_ASC_LBA_OUT_OF_RANGE 0x21 #define SCSI_ASC_MEDIA_CHANGED 0x28 #define SCSI_ASC_MEDIUM_NOT_PRESENT 0x3A /* USB error codes */ #define MASS_ERR_SUCCESS 0x00 #define MASS_ERR_PHASE_ERROR 0x02 #define MASS_ERR_UNIT_NOT_READY 0x03 #define MASS_ERR_UNIT_BUSY 0x04 #define MASS_ERR_STALL 0x05 #define MASS_ERR_CMD_NOT_SUPPORTED 0x06 #define MASS_ERR_INVALID_CSW 0x07 #define MASS_ERR_NO_MEDIA 0x08 #define MASS_ERR_BAD_LBA 0x09 #define MASS_ERR_MEDIA_CHANGED 0x0A #define MASS_ERR_DEVICE_DISCONNECTED 0x11 #define MASS_ERR_UNABLE_TO_RECOVER 0x12 // Reset recovery error #define MASS_ERR_INVALID_LUN 0x13 #define MASS_ERR_WRITE_STALL 0x14 #define MASS_ERR_READ_NAKS 0x15 #define MASS_ERR_WRITE_NAKS 0x16 #define MASS_ERR_WRITE_PROTECTED 0x17 #define MASS_ERR_NOT_IMPLEMENTED 0xFD #define MASS_ERR_GENERAL_SCSI_ERROR 0xFE #define MASS_ERR_GENERAL_USB_ERROR 0xFF #define MASS_ERR_USER 0xA0 // For subclasses to define their own error codes #define MASS_TRANS_FLG_CALLBACK 0x01 // Callback is involved #define MASS_TRANS_FLG_NO_STALL_CHECK 0x02 // STALL condition is not checked #define MASS_TRANS_FLG_NO_PHASE_CHECK 0x04 // PHASE_ERROR is not checked #define MASS_MAX_ENDPOINTS 3 struct Capacity { uint8_t data[8]; //uint32_t dwBlockAddress; //uint32_t dwBlockLength; } __attribute__((packed)); struct BASICCDB { uint8_t Opcode; unsigned unused : 5; unsigned LUN : 3; uint8_t info[12]; } __attribute__((packed)); typedef BASICCDB BASICCDB_t; struct CDB6 { uint8_t Opcode; unsigned LBAMSB : 5; unsigned LUN : 3; uint8_t LBAHB; uint8_t LBALB; uint8_t AllocationLength; uint8_t Control; public: CDB6(uint8_t _Opcode, uint8_t _LUN, uint32_t LBA, uint8_t _AllocationLength, uint8_t _Control) : Opcode(_Opcode), LBAMSB(BGRAB2(LBA) & 0x1F), LUN(_LUN), LBAHB(BGRAB1(LBA)), LBALB(BGRAB0(LBA)), AllocationLength(_AllocationLength), Control(_Control) { } CDB6(uint8_t _Opcode, uint8_t _LUN, uint8_t _AllocationLength, uint8_t _Control) : Opcode(_Opcode), LBAMSB(0), LUN(_LUN), LBAHB(0), LBALB(0), AllocationLength(_AllocationLength), Control(_Control) { } } __attribute__((packed)); typedef CDB6 CDB6_t; struct CDB10 { uint8_t Opcode; unsigned Service_Action : 5; unsigned LUN : 3; uint8_t LBA_L_M_MB; uint8_t LBA_L_M_LB; uint8_t LBA_L_L_MB; uint8_t LBA_L_L_LB; uint8_t Misc2; uint8_t ALC_MB; uint8_t ALC_LB; uint8_t Control; public: CDB10(uint8_t _Opcode, uint8_t _LUN) : Opcode(_Opcode), Service_Action(0), LUN(_LUN), LBA_L_M_MB(0), LBA_L_M_LB(0), LBA_L_L_MB(0), LBA_L_L_LB(0), Misc2(0), ALC_MB(0), ALC_LB(0), Control(0) { } CDB10(uint8_t _Opcode, uint8_t _LUN, uint16_t xflen, uint32_t _LBA) : Opcode(_Opcode), Service_Action(0), LUN(_LUN), LBA_L_M_MB(BGRAB3(_LBA)), LBA_L_M_LB(BGRAB2(_LBA)), LBA_L_L_MB(BGRAB1(_LBA)), LBA_L_L_LB(BGRAB0(_LBA)), Misc2(0), ALC_MB(BGRAB1(xflen)), ALC_LB(BGRAB0(xflen)), Control(0) { } } __attribute__((packed)); typedef CDB10 CDB10_t; struct CDB12 { uint8_t Opcode; unsigned Service_Action : 5; unsigned Misc : 3; uint8_t LBA_L_M_LB; uint8_t LBA_L_L_MB; uint8_t LBA_L_L_LB; uint8_t ALC_M_LB; uint8_t ALC_L_MB; uint8_t ALC_L_LB; uint8_t Control; } __attribute__((packed)); typedef CDB12 CDB12_t; struct CDB_LBA32_16 { uint8_t Opcode; unsigned Service_Action : 5; unsigned Misc : 3; uint8_t LBA_L_M_MB; uint8_t LBA_L_M_LB; uint8_t LBA_L_L_MB; uint8_t LBA_L_L_LB; uint8_t A_M_M_MB; uint8_t A_M_M_LB; uint8_t A_M_L_MB; uint8_t A_M_L_LB; uint8_t ALC_M_MB; uint8_t ALC_M_LB; uint8_t ALC_L_MB; uint8_t ALC_L_LB; uint8_t Misc2; uint8_t Control; } __attribute__((packed)); struct CDB_LBA64_16 { uint8_t Opcode; uint8_t Misc; uint8_t LBA_M_M_MB; uint8_t LBA_M_M_LB; uint8_t LBA_M_L_MB; uint8_t LBA_M_L_LB; uint8_t LBA_L_M_MB; uint8_t LBA_L_M_LB; uint8_t LBA_L_L_MB; uint8_t LBA_L_L_LB; uint8_t ALC_M_MB; uint8_t ALC_M_LB; uint8_t ALC_L_MB; uint8_t ALC_L_LB; uint8_t Misc2; uint8_t Control; } __attribute__((packed)); struct InquiryResponse { uint8_t DeviceType : 5; uint8_t PeripheralQualifier : 3; unsigned Reserved : 7; unsigned Removable : 1; uint8_t Version; unsigned ResponseDataFormat : 4; unsigned HISUP : 1; unsigned NormACA : 1; unsigned TrmTsk : 1; unsigned AERC : 1; uint8_t AdditionalLength; //uint8_t Reserved3[2]; unsigned PROTECT : 1; unsigned Res : 2; unsigned ThreePC : 1; unsigned TPGS : 2; unsigned ACC : 1; unsigned SCCS : 1; unsigned ADDR16 : 1; unsigned R1 : 1; unsigned R2 : 1; unsigned MCHNGR : 1; unsigned MULTIP : 1; unsigned VS : 1; unsigned ENCSERV : 1; unsigned BQUE : 1; unsigned SoftReset : 1; unsigned CmdQue : 1; unsigned Reserved4 : 1; unsigned Linked : 1; unsigned Sync : 1; unsigned WideBus16Bit : 1; unsigned WideBus32Bit : 1; unsigned RelAddr : 1; uint8_t VendorID[8]; uint8_t ProductID[16]; uint8_t RevisionID[4]; } __attribute__((packed)); struct CommandBlockWrapperBase { uint32_t dCBWSignature; uint32_t dCBWTag; uint32_t dCBWDataTransferLength; uint8_t bmCBWFlags; public: CommandBlockWrapperBase() { } CommandBlockWrapperBase(uint32_t tag, uint32_t xflen, uint8_t flgs) : dCBWSignature(MASS_CBW_SIGNATURE), dCBWTag(tag), dCBWDataTransferLength(xflen), bmCBWFlags(flgs) { } } __attribute__((packed)); struct CommandBlockWrapper : public CommandBlockWrapperBase { struct { uint8_t bmCBWLUN : 4; uint8_t bmReserved1 : 4; }; struct { uint8_t bmCBWCBLength : 4; uint8_t bmReserved2 : 4; }; uint8_t CBWCB[16]; public: // All zeroed. CommandBlockWrapper() : CommandBlockWrapperBase(0, 0, 0), bmReserved1(0), bmReserved2(0) { for (int i = 0; i < 16; i++) CBWCB[i] = 0; } // Generic Wrap, CDB zeroed. CommandBlockWrapper(uint32_t tag, uint32_t xflen, uint8_t flgs, uint8_t lu, uint8_t cmdlen, uint8_t cmd) : CommandBlockWrapperBase(tag, xflen, flgs), bmCBWLUN(lu), bmReserved1(0), bmCBWCBLength(cmdlen), bmReserved2(0) { for (int i = 0; i < 16; i++) CBWCB[i] = 0; // Type punning can cause optimization problems and bugs. // Using reinterpret_cast to a dreinterpretifferent object is the proper way to do this. //(((BASICCDB_t *) CBWCB)->LUN) = cmd; BASICCDB_t *x = reinterpret_cast<BASICCDB_t *>(CBWCB); x->LUN = cmd; } // Wrap for CDB of 6 CommandBlockWrapper(uint32_t tag, uint32_t xflen, CDB6_t *cdb, uint8_t dir) : CommandBlockWrapperBase(tag, xflen, dir), bmCBWLUN(cdb->LUN), bmReserved1(0), bmCBWCBLength(6), bmReserved2(0) { memcpy(&CBWCB, cdb, 6); } // Wrap for CDB of 10 CommandBlockWrapper(uint32_t tag, uint32_t xflen, CDB10_t *cdb, uint8_t dir) : CommandBlockWrapperBase(tag, xflen, dir), bmCBWLUN(cdb->LUN), bmReserved1(0), bmCBWCBLength(10), bmReserved2(0) { memcpy(&CBWCB, cdb, 10); } } __attribute__((packed)); struct CommandStatusWrapper { uint32_t dCSWSignature; uint32_t dCSWTag; uint32_t dCSWDataResidue; uint8_t bCSWStatus; } __attribute__((packed)); struct RequestSenseResponce { uint8_t bResponseCode; uint8_t bSegmentNumber; uint8_t bmSenseKey : 4; uint8_t bmReserved : 1; uint8_t bmILI : 1; uint8_t bmEOM : 1; uint8_t bmFileMark : 1; uint8_t Information[4]; uint8_t bAdditionalLength; uint8_t CmdSpecificInformation[4]; uint8_t bAdditionalSenseCode; uint8_t bAdditionalSenseQualifier; uint8_t bFieldReplaceableUnitCode; uint8_t SenseKeySpecific[3]; } __attribute__((packed)); class BulkOnly : public USBDeviceConfig, public UsbConfigXtracter { protected: static const uint8_t epDataInIndex; // DataIn endpoint index static const uint8_t epDataOutIndex; // DataOUT endpoint index static const uint8_t epInterruptInIndex; // InterruptIN endpoint index USB *pUsb; uint8_t bAddress; uint8_t bConfNum; // configuration number uint8_t bIface; // interface value uint8_t bNumEP; // total number of EP in the configuration uint32_t qNextPollTime; // next poll time bool bPollEnable; // poll enable flag EpInfo epInfo[MASS_MAX_ENDPOINTS]; uint32_t dCBWTag; // Tag //uint32_t dCBWDataTransferLength; // Data Transfer Length uint8_t bLastUsbError; // Last USB error uint8_t bMaxLUN; // Max LUN uint8_t bTheLUN; // Active LUN uint32_t CurrentCapacity[MASS_MAX_SUPPORTED_LUN]; // Total sectors uint16_t CurrentSectorSize[MASS_MAX_SUPPORTED_LUN]; // Sector size, clipped to 16 bits bool LUNOk[MASS_MAX_SUPPORTED_LUN]; // use this to check for media changes. bool WriteOk[MASS_MAX_SUPPORTED_LUN]; void PrintEndpointDescriptor(const USB_FD_ENDPOINT_DESCRIPTOR* ep_ptr); // Additional Initialization Method for Subclasses virtual uint8_t OnInit() { return 0; } public: BulkOnly(USB *p); uint8_t GetLastUsbError() { return bLastUsbError; }; uint8_t GetbMaxLUN() { return bMaxLUN; } // Max LUN uint8_t GetbTheLUN() { return bTheLUN; } // Active LUN bool WriteProtected(uint8_t lun); uint8_t MediaCTL(uint8_t lun, uint8_t ctl); uint8_t Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, uint8_t *buf); uint8_t Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, USBReadParser *prs); uint8_t Write(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, const uint8_t *buf); uint8_t LockMedia(uint8_t lun, uint8_t lock); bool LUNIsGood(uint8_t lun); uint32_t GetCapacity(uint8_t lun); uint16_t GetSectorSize(uint8_t lun); // USBDeviceConfig implementation uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed); uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed); uint8_t Release(); uint8_t Poll(); virtual uint8_t GetAddress() { return bAddress; } // UsbConfigXtracter implementation void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_FD_ENDPOINT_DESCRIPTOR *ep); virtual bool DEVCLASSOK(uint8_t klass) { return klass == USB_CLASS_MASS_STORAGE; } uint8_t SCSITransaction6(CDB6_t *cdb, uint16_t buf_size, void *buf, uint8_t dir); uint8_t SCSITransaction10(CDB10_t *cdb, uint16_t buf_size, void *buf, uint8_t dir); private: uint8_t Inquiry(uint8_t lun, uint16_t size, uint8_t *buf); uint8_t TestUnitReady(uint8_t lun); uint8_t RequestSense(uint8_t lun, uint16_t size, uint8_t *buf); uint8_t ModeSense6(uint8_t lun, uint8_t pc, uint8_t page, uint8_t subpage, uint8_t len, uint8_t *buf); uint8_t GetMaxLUN(uint8_t *max_lun); uint8_t SetCurLUN(uint8_t lun); void Reset(); uint8_t ResetRecovery(); uint8_t ReadCapacity10(uint8_t lun, uint8_t *buf); void ClearAllEP(); void CheckMedia(); bool CheckLUN(uint8_t lun); uint8_t Page3F(uint8_t lun); bool IsValidCBW(uint8_t size, uint8_t *pcbw); bool IsMeaningfulCBW(uint8_t size, uint8_t *pcbw); bool IsValidCSW(CommandStatusWrapper *pcsw, CommandBlockWrapperBase *pcbw); uint8_t ClearEpHalt(uint8_t index); uint8_t Transaction(CommandBlockWrapper *cbw, uint16_t bsize, void *buf OPTARG(MS_WANT_PARSER, uint8_t flags=0)); uint8_t HandleUsbError(uint8_t error, uint8_t index); uint8_t HandleSCSIError(uint8_t status); };
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/masstorage.h
C++
agpl-3.0
17,953
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once #ifndef _usb_h_ #error "Never include max3421e.h directly; include Usb.h instead" #endif /* MAX3421E register/bit names and bitmasks */ /* Arduino pin definitions */ /* pin numbers to port numbers */ #define SE0 0 #define SE1 1 #define FSHOST 2 #define LSHOST 3 /* MAX3421E command byte format: rrrrr0wa where 'r' is register number */ // // MAX3421E Registers in HOST mode. // #define rRCVFIFO 0x08 //1<<3 #define rSNDFIFO 0x10 //2<<3 #define rSUDFIFO 0x20 //4<<3 #define rRCVBC 0x30 //6<<3 #define rSNDBC 0x38 //7<<3 #define rUSBIRQ 0x68 //13<<3 /* USBIRQ Bits */ #define bmVBUSIRQ 0x40 //b6 #define bmNOVBUSIRQ 0x20 //b5 #define bmOSCOKIRQ 0x01 //b0 #define rUSBIEN 0x70 //14<<3 /* USBIEN Bits */ #define bmVBUSIE 0x40 //b6 #define bmNOVBUSIE 0x20 //b5 #define bmOSCOKIE 0x01 //b0 #define rUSBCTL 0x78 //15<<3 /* USBCTL Bits */ #define bmCHIPRES 0x20 //b5 #define bmPWRDOWN 0x10 //b4 #define rCPUCTL 0x80 //16<<3 /* CPUCTL Bits */ #define bmPULSEWID1 0x80 //b7 #define bmPULSEWID0 0x40 //b6 #define bmIE 0x01 //b0 #define rPINCTL 0x88 //17<<3 /* PINCTL Bits */ #define bmFDUPSPI 0x10 //b4 #define bmINTLEVEL 0x08 //b3 #define bmPOSINT 0x04 //b2 #define bmGPXB 0x02 //b1 #define bmGPXA 0x01 //b0 // GPX pin selections #define GPX_OPERATE 0x00 #define GPX_VBDET 0x01 #define GPX_BUSACT 0x02 #define GPX_SOF 0x03 #define rREVISION 0x90 //18<<3 #define rIOPINS1 0xA0 //20<<3 /* IOPINS1 Bits */ #define bmGPOUT0 0x01 #define bmGPOUT1 0x02 #define bmGPOUT2 0x04 #define bmGPOUT3 0x08 #define bmGPIN0 0x10 #define bmGPIN1 0x20 #define bmGPIN2 0x40 #define bmGPIN3 0x80 #define rIOPINS2 0xA8 //21<<3 /* IOPINS2 Bits */ #define bmGPOUT4 0x01 #define bmGPOUT5 0x02 #define bmGPOUT6 0x04 #define bmGPOUT7 0x08 #define bmGPIN4 0x10 #define bmGPIN5 0x20 #define bmGPIN6 0x40 #define bmGPIN7 0x80 #define rGPINIRQ 0xB0 //22<<3 /* GPINIRQ Bits */ #define bmGPINIRQ0 0x01 #define bmGPINIRQ1 0x02 #define bmGPINIRQ2 0x04 #define bmGPINIRQ3 0x08 #define bmGPINIRQ4 0x10 #define bmGPINIRQ5 0x20 #define bmGPINIRQ6 0x40 #define bmGPINIRQ7 0x80 #define rGPINIEN 0xB8 //23<<3 /* GPINIEN Bits */ #define bmGPINIEN0 0x01 #define bmGPINIEN1 0x02 #define bmGPINIEN2 0x04 #define bmGPINIEN3 0x08 #define bmGPINIEN4 0x10 #define bmGPINIEN5 0x20 #define bmGPINIEN6 0x40 #define bmGPINIEN7 0x80 #define rGPINPOL 0xC0 //24<<3 /* GPINPOL Bits */ #define bmGPINPOL0 0x01 #define bmGPINPOL1 0x02 #define bmGPINPOL2 0x04 #define bmGPINPOL3 0x08 #define bmGPINPOL4 0x10 #define bmGPINPOL5 0x20 #define bmGPINPOL6 0x40 #define bmGPINPOL7 0x80 #define rHIRQ 0xC8 //25<<3 /* HIRQ Bits */ #define bmBUSEVENTIRQ 0x01 // indicates BUS Reset Done or BUS Resume #define bmRWUIRQ 0x02 #define bmRCVDAVIRQ 0x04 #define bmSNDBAVIRQ 0x08 #define bmSUSDNIRQ 0x10 #define bmCONDETIRQ 0x20 #define bmFRAMEIRQ 0x40 #define bmHXFRDNIRQ 0x80 #define rHIEN 0xD0 //26<<3 /* HIEN Bits */ #define bmBUSEVENTIE 0x01 #define bmRWUIE 0x02 #define bmRCVDAVIE 0x04 #define bmSNDBAVIE 0x08 #define bmSUSDNIE 0x10 #define bmCONDETIE 0x20 #define bmFRAMEIE 0x40 #define bmHXFRDNIE 0x80 #define rMODE 0xD8 //27<<3 /* MODE Bits */ #define bmHOST 0x01 #define bmLOWSPEED 0x02 #define bmHUBPRE 0x04 #define bmSOFKAENAB 0x08 #define bmSEPIRQ 0x10 #define bmDELAYISO 0x20 #define bmDMPULLDN 0x40 #define bmDPPULLDN 0x80 #define rPERADDR 0xE0 //28<<3 #define rHCTL 0xE8 //29<<3 /* HCTL Bits */ #define bmBUSRST 0x01 #define bmFRMRST 0x02 #define bmSAMPLEBUS 0x04 #define bmSIGRSM 0x08 #define bmRCVTOG0 0x10 #define bmRCVTOG1 0x20 #define bmSNDTOG0 0x40 #define bmSNDTOG1 0x80 #define rHXFR 0xF0 //30<<3 #undef tokSETUP #undef tokIN #undef tokOUT #undef tokINHS #undef tokOUTHS #undef tokISOIN #undef tokISOOUT /* Host transfer token values for writing the HXFR register (R30) */ /* OR this bit field with the endpoint number in bits 3:0 */ #define tokSETUP 0x10 // HS=0, ISO=0, OUTNIN=0, SETUP=1 #define tokIN 0x00 // HS=0, ISO=0, OUTNIN=0, SETUP=0 #define tokOUT 0x20 // HS=0, ISO=0, OUTNIN=1, SETUP=0 #define tokINHS 0x80 // HS=1, ISO=0, OUTNIN=0, SETUP=0 #define tokOUTHS 0xA0 // HS=1, ISO=0, OUTNIN=1, SETUP=0 #define tokISOIN 0x40 // HS=0, ISO=1, OUTNIN=0, SETUP=0 #define tokISOOUT 0x60 // HS=0, ISO=1, OUTNIN=1, SETUP=0 #define rHRSL 0xF8 //31<<3 /* HRSL Bits */ #define bmRCVTOGRD 0x10 #define bmSNDTOGRD 0x20 #define bmKSTATUS 0x40 #define bmJSTATUS 0x80 #define bmSE0 0x00 //SE0 - disconnect state #define bmSE1 0xC0 //SE1 - illegal state /* Host error result codes, the 4 LSB's in the HRSL register */ #define hrSUCCESS 0x00 #define hrBUSY 0x01 #define hrBADREQ 0x02 #define hrUNDEF 0x03 #define hrNAK 0x04 #define hrSTALL 0x05 #define hrTOGERR 0x06 #define hrWRONGPID 0x07 #define hrBADBC 0x08 #define hrPIDERR 0x09 #define hrPKTERR 0x0A #define hrCRCERR 0x0B #define hrKERR 0x0C #define hrJERR 0x0D #define hrTIMEOUT 0x0E #define hrBABBLE 0x0F #define MODE_FS_HOST (bmDPPULLDN|bmDMPULLDN|bmHOST|bmSOFKAENAB) #define MODE_LS_HOST (bmDPPULLDN|bmDMPULLDN|bmHOST|bmLOWSPEED|bmSOFKAENAB)
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/max3421e.h
C
agpl-3.0
6,560
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #include "../../../inc/MarlinConfigPre.h" #if ENABLED(USB_FLASH_DRIVE_SUPPORT) && DISABLED(USE_UHS3_USB) #include "Usb.h" // 0x80 is the default (i.e. trace) to turn off set this global to something lower. // this allows for 126 other debugging levels. // TO-DO: Allow assignment to a different serial port by software int UsbDEBUGlvl = 0x80; void E_Notifyc(char c, int lvl) { if (UsbDEBUGlvl < lvl) return; USB_HOST_SERIAL.print(c #if !defined(ARDUINO) && !defined(ARDUINO_ARCH_LPC176X) , BYTE #endif ); //USB_HOST_SERIAL.flush(); } void E_Notify(char const * msg, int lvl) { if (UsbDEBUGlvl < lvl) return; if (!msg) return; while (const char c = pgm_read_byte(msg++)) E_Notifyc(c, lvl); } void E_NotifyStr(char const * msg, int lvl) { if (UsbDEBUGlvl < lvl) return; if (!msg) return; while (const char c = *msg++) E_Notifyc(c, lvl); } void E_Notify(uint8_t b, int lvl) { if (UsbDEBUGlvl < lvl) return; USB_HOST_SERIAL.print(b #if !defined(ARDUINO) && !defined(ARDUINO_ARCH_LPC176X) , DEC #endif ); //USB_HOST_SERIAL.flush(); } void E_Notify(double d, int lvl) { if (UsbDEBUGlvl < lvl) return; USB_HOST_SERIAL.print(d); //USB_HOST_SERIAL.flush(); } #ifdef DEBUG_USB_HOST void NotifyFailGetDevDescr() { Notify(PSTR("\r\ngetDevDescr "), 0x80); } void NotifyFailSetDevTblEntry() { Notify(PSTR("\r\nsetDevTblEn "), 0x80); } void NotifyFailGetConfDescr() { Notify(PSTR("\r\ngetConf "), 0x80); } void NotifyFailSetConfDescr() { Notify(PSTR("\r\nsetConf "), 0x80); } void NotifyFailGetDevDescr(uint8_t reason) { NotifyFailGetDevDescr(); NotifyFail(reason); } void NotifyFailSetDevTblEntry(uint8_t reason) { NotifyFailSetDevTblEntry(); NotifyFail(reason); } void NotifyFailGetConfDescr(uint8_t reason) { NotifyFailGetConfDescr(); NotifyFail(reason); } void NotifyFailSetConfDescr(uint8_t reason) { NotifyFailSetConfDescr(); NotifyFail(reason); } void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID) { Notify(PSTR("\r\nUnknown Device Connected - VID: "), 0x80); D_PrintHex<uint16_t > (VID, 0x80); Notify(PSTR(" PID: "), 0x80); D_PrintHex<uint16_t > (PID, 0x80); } void NotifyFail(uint8_t rcode) { D_PrintHex<uint8_t > (rcode, 0x80); Notify(PSTR("\r\n"), 0x80); } #endif // DEBUG_USB_HOST #endif // USB_FLASH_DRIVE_SUPPORT
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/message.cpp
C++
agpl-3.0
3,370
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once #ifndef _usb_h_ #error "Never include message.h directly; include Usb.h instead" #endif extern int UsbDEBUGlvl; void E_Notify(char const * msg, int lvl); void E_Notify(uint8_t b, int lvl); void E_NotifyStr(char const * msg, int lvl); void E_Notifyc(char c, int lvl); #ifdef DEBUG_USB_HOST #define Notify E_Notify #define NotifyStr E_NotifyStr #define Notifyc E_Notifyc void NotifyFailGetDevDescr(uint8_t reason); void NotifyFailSetDevTblEntry(uint8_t reason); void NotifyFailGetConfDescr(uint8_t reason); void NotifyFailSetConfDescr(uint8_t reason); void NotifyFailGetDevDescr(); void NotifyFailSetDevTblEntry(); void NotifyFailGetConfDescr(); void NotifyFailSetConfDescr(); void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID); void NotifyFail(uint8_t rcode); #else #define Notify(...) ((void)0) #define NotifyStr(...) ((void)0) #define Notifyc(...) ((void)0) #define NotifyFailGetDevDescr(...) ((void)0) #define NotifyFailSetDevTblEntry(...) ((void)0) #define NotifyFailGetConfDescr(...) ((void)0) #define NotifyFailGetDevDescr(...) ((void)0) #define NotifyFailSetDevTblEntry(...) ((void)0) #define NotifyFailGetConfDescr(...) ((void)0) #define NotifyFailSetConfDescr(...) ((void)0) #define NotifyFailUnknownDevice(...) ((void)0) #define NotifyFail(...) ((void)0) #endif template <class ERROR_TYPE> void ErrorMessage(uint8_t level, char const * msg, ERROR_TYPE rcode = 0) { #ifdef DEBUG_USB_HOST Notify(msg, level); Notify(PSTR(": "), level); D_PrintHex<ERROR_TYPE > (rcode, level); Notify(PSTR("\r\n"), level); #endif } template <class ERROR_TYPE> void ErrorMessage(char const * msg __attribute__((unused)), ERROR_TYPE rcode __attribute__((unused)) = 0) { #ifdef DEBUG_USB_HOST Notify(msg, 0x80); Notify(PSTR(": "), 0x80); D_PrintHex<ERROR_TYPE > (rcode, 0x80); Notify(PSTR("\r\n"), 0x80); #endif }
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/message.h
C++
agpl-3.0
2,872
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #include "../../../inc/MarlinConfigPre.h" #if ENABLED(USB_FLASH_DRIVE_SUPPORT) && DISABLED(USE_UHS3_USB) #include "Usb.h" bool MultiByteValueParser::Parse(uint8_t **pp, uint16_t *pcntdn) { if (!pBuf) { Notify(PSTR("Buffer pointer is NULL!\r\n"), 0x80); return false; } for (; countDown && (*pcntdn); countDown--, (*pcntdn)--, (*pp)++) pBuf[valueSize - countDown] = (**pp); if (countDown) return false; countDown = valueSize; return true; } bool PTPListParser::Parse(uint8_t **pp, uint16_t *pcntdn, PTP_ARRAY_EL_FUNC pf, const void *me) { switch (nStage) { case 0: pBuf->valueSize = lenSize; theParser.Initialize(pBuf); nStage = 1; case 1: if (!theParser.Parse(pp, pcntdn)) return false; arLen = 0; arLen = (pBuf->valueSize >= 4) ? *((uint32_t*)pBuf->pValue) : (uint32_t)(*((uint16_t*)pBuf->pValue)); arLenCntdn = arLen; nStage = 2; case 2: pBuf->valueSize = valSize; theParser.Initialize(pBuf); nStage = 3; case 3: for (; arLenCntdn; arLenCntdn--) { if (!theParser.Parse(pp, pcntdn)) return false; if (pf) pf(pBuf, (arLen - arLenCntdn), me); } nStage = 0; } return true; } #endif // USB_FLASH_DRIVE_SUPPORT
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/parsetools.cpp
C++
agpl-3.0
2,221
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once #ifndef _usb_h_ #error "Never include parsetools.h directly; include Usb.h instead" #endif struct MultiValueBuffer { uint8_t valueSize; void *pValue; } __attribute__((packed)); class MultiByteValueParser { uint8_t * pBuf; uint8_t countDown; uint8_t valueSize; public: MultiByteValueParser() : pBuf(nullptr), countDown(0), valueSize(0) { }; const uint8_t* GetBuffer() { return pBuf; } void Initialize(MultiValueBuffer * const pbuf) { pBuf = (uint8_t*)pbuf->pValue; countDown = valueSize = pbuf->valueSize; } bool Parse(uint8_t **pp, uint16_t *pcntdn); }; class ByteSkipper { uint8_t *pBuf; uint8_t nStage; uint16_t countDown; public: ByteSkipper() : pBuf(nullptr), nStage(0), countDown(0) { } void Initialize(MultiValueBuffer *pbuf) { pBuf = (uint8_t*)pbuf->pValue; countDown = 0; } bool Skip(uint8_t **pp, uint16_t *pcntdn, uint16_t bytes_to_skip) { switch (nStage) { case 0: countDown = bytes_to_skip; nStage++; case 1: for (; countDown && (*pcntdn); countDown--, (*pp)++, (*pcntdn)--); if (!countDown) nStage = 0; } return (!countDown); } }; // Pointer to a callback function triggered for each element of PTP array when used with PTPArrayParser typedef void (*PTP_ARRAY_EL_FUNC)(const MultiValueBuffer * const p, uint32_t count, const void *me); class PTPListParser { public: enum ParseMode { modeArray, modeRange/*, modeEnum*/ }; private: uint8_t nStage; uint8_t enStage; uint32_t arLen; uint32_t arLenCntdn; uint8_t lenSize; // size of the array length field in bytes uint8_t valSize; // size of the array element in bytes MultiValueBuffer *pBuf; // The only parser for both size and array element parsing MultiByteValueParser theParser; uint8_t /*ParseMode*/ prsMode; public: PTPListParser() : nStage(0), enStage(0), arLen(0), arLenCntdn(0), lenSize(0), valSize(0), pBuf(nullptr), prsMode(modeArray) {} ; void Initialize(const uint8_t len_size, const uint8_t val_size, MultiValueBuffer * const p, const uint8_t mode = modeArray) { pBuf = p; lenSize = len_size; valSize = val_size; prsMode = mode; if (prsMode == modeRange) { arLenCntdn = arLen = 3; nStage = 2; } else { arLenCntdn = arLen = 0; nStage = 0; } enStage = 0; theParser.Initialize(p); } bool Parse(uint8_t **pp, uint16_t *pcntdn, PTP_ARRAY_EL_FUNC pf, const void *me=nullptr); };
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/parsetools.h
C++
agpl-3.0
3,501
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once #ifndef _usb_h_ #error "Never include printhex.h directly; include Usb.h instead" #endif void E_Notifyc(char c, int lvl); template <class T> void PrintHex(T val, int lvl) { int num_nybbles = sizeof (T) * 2; do { char v = 48 + (((val >> (num_nybbles - 1) * 4)) & 0x0F); if (v > 57) v += 7; E_Notifyc(v, lvl); } while (--num_nybbles); } template <class T> void PrintBin(T val, int lvl) { for (T mask = (((T)1) << ((sizeof (T) << 3) - 1)); mask; mask >>= 1) E_Notifyc(val & mask ? '1' : '0', lvl); } template <class T> void SerialPrintHex(T val) { int num_nybbles = sizeof (T) * 2; do { char v = 48 + (((val >> (num_nybbles - 1) * 4)) & 0x0F); if (v > 57) v += 7; USB_HOST_SERIAL.print(v); } while (--num_nybbles); } template <class T> void PrintHex2(Print *prn, T val) { T mask = (((T)1) << (((sizeof (T) << 1) - 1) << 2)); while (mask > 1) { if (val < mask) prn->print("0"); mask >>= 4; } prn->print((T)val, HEX); } template <class T> void D_PrintHex(T val __attribute__((unused)), int lvl __attribute__((unused))) { #ifdef DEBUG_USB_HOST PrintHex<T > (val, lvl); #endif } template <class T> void D_PrintBin(T val, int lvl) { #ifdef DEBUG_USB_HOST PrintBin<T > (val, lvl); #endif }
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/printhex.h
C++
agpl-3.0
2,233
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #pragma once #include "../../../inc/MarlinConfig.h" #include "macros.h" #if ENABLED(USB_FLASH_DRIVE_SUPPORT) //////////////////////////////////////////////////////////////////////////////// /* Added by Bill Greiman to speed up mass storage initialization with USB * flash drives and simple USB hard drives. * Disable this by defining DELAY(x) to be delay(x). */ #define delay(x) if ((x) < 200) safe_delay(x) /* Almost all USB flash drives and simple USB hard drives fail the write * protect test and add 20 - 30 seconds to USB init. Set SKIP_WRITE_PROTECT * to nonzero to skip the test and assume the drive is writable. */ #define SKIP_WRITE_PROTECT 1 /* Since Marlin only cares about USB flash drives, we only need one LUN. */ #define MASS_MAX_SUPPORTED_LUN 1 #endif //////////////////////////////////////////////////////////////////////////////// // SPI Configuration //////////////////////////////////////////////////////////////////////////////// #ifndef USB_SPI #define USB_SPI SPI //#define USB_SPI SPI1 #endif //////////////////////////////////////////////////////////////////////////////// // DEBUGGING //////////////////////////////////////////////////////////////////////////////// /* Set this to 1 to activate serial debugging */ #define ENABLE_UHS_DEBUGGING 0 /* This can be used to select which serial port to use for debugging if * multiple serial ports are available. * For example Serial3. */ #ifndef USB_HOST_SERIAL #if ENABLED(USB_FLASH_DRIVE_SUPPORT) #define USB_HOST_SERIAL MYSERIAL1 #else #define USB_HOST_SERIAL Serial #endif #endif //////////////////////////////////////////////////////////////////////////////// // Manual board activation //////////////////////////////////////////////////////////////////////////////// /* Set this to 1 if you are using an Arduino Mega ADK board with MAX3421e built-in */ #define USE_UHS_MEGA_ADK 0 // If you are using Arduino 1.5.5 or newer there is no need to do this manually /* Set this to 1 if you are using a Black Widdow */ #define USE_UHS_BLACK_WIDDOW 0 /* Set this to a one to use the xmem2 lock. This is needed for multitasking and threading */ #define USE_XMEM_SPI_LOCK 0 //////////////////////////////////////////////////////////////////////////////// // Wii IR camera //////////////////////////////////////////////////////////////////////////////// /* Set this to 1 to activate code for the Wii IR camera */ #define ENABLE_WII_IR_CAMERA 0 //////////////////////////////////////////////////////////////////////////////// // MASS STORAGE //////////////////////////////////////////////////////////////////////////////// // ******* IMPORTANT ******* // Set this to 1 to support single LUN devices, and save RAM. -- I.E. thumb drives. // Each LUN needs ~13 bytes to be able to track the state of each unit. #ifndef MASS_MAX_SUPPORTED_LUN #define MASS_MAX_SUPPORTED_LUN 8 #endif //////////////////////////////////////////////////////////////////////////////// // Set to 1 to use the faster spi4teensy3 driver. //////////////////////////////////////////////////////////////////////////////// #ifndef USE_SPI4TEENSY3 #define USE_SPI4TEENSY3 1 #endif // Disabled on the Teensy LC, as it is incompatible for now #ifdef __MKL26Z64__ #undef USE_SPI4TEENSY3 #define USE_SPI4TEENSY3 0 #endif //////////////////////////////////////////////////////////////////////////////// // AUTOMATIC Settings //////////////////////////////////////////////////////////////////////////////// // No user serviceable parts below this line. // DO NOT change anything below here unless you are a developer! //#include "version_helper.h" #if defined(__GNUC__) && defined(__AVR__) #ifndef GCC_VERSION #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif #if GCC_VERSION < 40602 // Test for GCC < 4.6.2 #ifdef PROGMEM #undef PROGMEM #define PROGMEM __attribute__((section(".progmem.data"))) // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734#c4 #ifdef PSTR #undef PSTR #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) // Copied from pgmspace.h in avr-libc source #endif #endif #endif #endif #if !defined(DEBUG_USB_HOST) && ENABLE_UHS_DEBUGGING #define DEBUG_USB_HOST #endif #if !defined(WIICAMERA) && ENABLE_WII_IR_CAMERA #define WIICAMERA #endif // To use some other locking (e.g. freertos), // define XMEM_ACQUIRE_SPI and XMEM_RELEASE_SPI to point to your lock and unlock. // NOTE: NO argument is passed. You have to do this within your routine for // whatever you are using to lock and unlock. #ifndef XMEM_ACQUIRE_SPI #if USE_XMEM_SPI_LOCK || defined(USE_MULTIPLE_APP_API) #include <xmem.h> #else #define XMEM_ACQUIRE_SPI() (void(0)) #define XMEM_RELEASE_SPI() (void(0)) #endif #endif #if !defined(EXT_RAM) && defined(EXT_RAM_STACK) || defined(EXT_RAM_HEAP) #include <xmem.h> #else #define EXT_RAM 0 #endif #if defined(CORE_TEENSY) && defined(KINETISK) #define USING_SPI4TEENSY3 USE_SPI4TEENSY3 #else #define USING_SPI4TEENSY3 0 #endif #if ((defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__)) || defined(__ARDUINO_X86__) || ARDUINO >= 10600) && !USING_SPI4TEENSY3 #include <SPI.h> // Use the Arduino SPI library for the Arduino Due, Intel Galileo 1 & 2, Intel Edison or if the SPI library with transaction is available #endif #ifdef RBL_NRF51822 #include <nrf_gpio.h> #include <SPI_Master.h> #define SPI SPI_Master #define MFK_CASTUINT8T (uint8_t) // RBLs return type for sizeof needs casting to uint8_t #endif #if defined(__PIC32MX__) || defined(__PIC32MZ__) #include <../../../../hardware/pic32/libraries/SPI/SPI.h> // Hack to use the SPI library #endif #if defined(ESP8266) || defined(ESP32) #define MFK_CASTUINT8T (uint8_t) // ESP return type for sizeof needs casting to uint8_t #endif #ifdef STM32F4 #include "stm32f4xx_hal.h" extern SPI_HandleTypeDef SPI_Handle; // Needed to be declared in your main.cpp #endif // Fix defines on Arduino Due #ifdef ARDUINO_SAM_DUE #ifdef tokSETUP #undef tokSETUP #endif #ifdef tokIN #undef tokIN #endif #ifdef tokOUT #undef tokOUT #endif #ifdef tokINHS #undef tokINHS #endif #ifdef tokOUTHS #undef tokOUTHS #endif #endif // Set defaults #ifndef MFK_CASTUINT8T #define MFK_CASTUINT8T #endif // Workaround issue: https://github.com/esp8266/Arduino/issues/2078 #ifdef ESP8266 #undef PROGMEM #define PROGMEM #undef PSTR #define PSTR(s) (s) #undef pgm_read_byte #define pgm_read_byte(addr) (*reinterpret_cast<const uint8_t*>(addr)) #undef pgm_read_word #define pgm_read_word(addr) (*reinterpret_cast<const uint16_t*>(addr)) #endif #ifdef ARDUINO_ESP8266_WIFIO #error "This board is currently not supported" #endif
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/settings.h
C
agpl-3.0
7,790
/** * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com */ #ifndef _usb_h_ #error "Never include usb_ch9.h directly; include Usb.h instead" #endif /* USB chapter 9 structures */ /* Misc.USB constants */ #define DEV_DESCR_LEN 18 //device descriptor length #define CONF_DESCR_LEN 9 //configuration descriptor length #define INTR_DESCR_LEN 9 //interface descriptor length #define EP_DESCR_LEN 7 //endpoint descriptor length /* Standard Device Requests */ #define USB_REQUEST_GET_STATUS 0 // Standard Device Request - GET STATUS #define USB_REQUEST_CLEAR_FEATURE 1 // Standard Device Request - CLEAR FEATURE #define USB_REQUEST_SET_FEATURE 3 // Standard Device Request - SET FEATURE #define USB_REQUEST_SET_ADDRESS 5 // Standard Device Request - SET ADDRESS #define USB_REQUEST_GET_DESCRIPTOR 6 // Standard Device Request - GET DESCRIPTOR #define USB_REQUEST_SET_DESCRIPTOR 7 // Standard Device Request - SET DESCRIPTOR #define USB_REQUEST_GET_CONFIGURATION 8 // Standard Device Request - GET CONFIGURATION #define USB_REQUEST_SET_CONFIGURATION 9 // Standard Device Request - SET CONFIGURATION #define USB_REQUEST_GET_INTERFACE 10 // Standard Device Request - GET INTERFACE #define USB_REQUEST_SET_INTERFACE 11 // Standard Device Request - SET INTERFACE #define USB_REQUEST_SYNCH_FRAME 12 // Standard Device Request - SYNCH FRAME #define USB_FEATURE_ENDPOINT_HALT 0 // CLEAR/SET FEATURE - Endpoint Halt #define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // CLEAR/SET FEATURE - Device remote wake-up #define USB_FEATURE_TEST_MODE 2 // CLEAR/SET FEATURE - Test mode /* Setup Data Constants */ #define USB_SETUP_HOST_TO_DEVICE 0x00 // Device Request bmRequestType transfer direction - host to device transfer #define USB_SETUP_DEVICE_TO_HOST 0x80 // Device Request bmRequestType transfer direction - device to host transfer #define USB_SETUP_TYPE_STANDARD 0x00 // Device Request bmRequestType type - standard #define USB_SETUP_TYPE_CLASS 0x20 // Device Request bmRequestType type - class #define USB_SETUP_TYPE_VENDOR 0x40 // Device Request bmRequestType type - vendor #define USB_SETUP_RECIPIENT_DEVICE 0x00 // Device Request bmRequestType recipient - device #define USB_SETUP_RECIPIENT_INTERFACE 0x01 // Device Request bmRequestType recipient - interface #define USB_SETUP_RECIPIENT_ENDPOINT 0x02 // Device Request bmRequestType recipient - endpoint #define USB_SETUP_RECIPIENT_OTHER 0x03 // Device Request bmRequestType recipient - other /* USB descriptors */ #define USB_DESCRIPTOR_DEVICE 0x01 // bDescriptorType for a Device Descriptor. #define USB_DESCRIPTOR_CONFIGURATION 0x02 // bDescriptorType for a Configuration Descriptor. #define USB_DESCRIPTOR_STRING 0x03 // bDescriptorType for a String Descriptor. #define USB_DESCRIPTOR_INTERFACE 0x04 // bDescriptorType for an Interface Descriptor. #define USB_DESCRIPTOR_ENDPOINT 0x05 // bDescriptorType for an Endpoint Descriptor. #define USB_DESCRIPTOR_DEVICE_QUALIFIER 0x06 // bDescriptorType for a Device Qualifier. #define USB_DESCRIPTOR_OTHER_SPEED 0x07 // bDescriptorType for a Other Speed Configuration. #define USB_DESCRIPTOR_INTERFACE_POWER 0x08 // bDescriptorType for Interface Power. #define USB_DESCRIPTOR_OTG 0x09 // bDescriptorType for an OTG Descriptor. #define HID_DESCRIPTOR_HID 0x21 /* OTG SET FEATURE Constants */ #define OTG_FEATURE_B_HNP_ENABLE 3 // SET FEATURE OTG - Enable B device to perform HNP #define OTG_FEATURE_A_HNP_SUPPORT 4 // SET FEATURE OTG - A device supports HNP #define OTG_FEATURE_A_ALT_HNP_SUPPORT 5 // SET FEATURE OTG - Another port on the A device supports HNP /* USB Endpoint Transfer Types */ #define USB_TRANSFER_TYPE_CONTROL 0x00 // Endpoint is a control endpoint. #define USB_TRANSFER_TYPE_ISOCHRONOUS 0x01 // Endpoint is an isochronous endpoint. #define USB_TRANSFER_TYPE_BULK 0x02 // Endpoint is a bulk endpoint. #define USB_TRANSFER_TYPE_INTERRUPT 0x03 // Endpoint is an interrupt endpoint. #define bmUSB_TRANSFER_TYPE 0x03 // bit mask to separate transfer type from ISO attributes /* Standard Feature Selectors for CLEAR_FEATURE Requests */ #define USB_FEATURE_ENDPOINT_STALL 0 // Endpoint recipient #define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // Device recipient #define USB_FEATURE_TEST_MODE 2 // Device recipient /* descriptor data structures */ /* Device descriptor structure */ typedef struct { uint8_t bLength; // Length of this descriptor. uint8_t bDescriptorType; // DEVICE descriptor type (USB_DESCRIPTOR_DEVICE). uint16_t bcdUSB; // USB Spec Release Number (BCD). uint8_t bDeviceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. uint8_t bDeviceSubClass; // Subclass code (assigned by the USB-IF). uint8_t bDeviceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. uint8_t bMaxPacketSize0; // Maximum packet size for endpoint 0. uint16_t idVendor; // Vendor ID (assigned by the USB-IF). uint16_t idProduct; // Product ID (assigned by the manufacturer). uint16_t bcdDevice; // Device release number (BCD). uint8_t iManufacturer; // Index of String Descriptor describing the manufacturer. uint8_t iProduct; // Index of String Descriptor describing the product. uint8_t iSerialNumber; // Index of String Descriptor with the device's serial number. uint8_t bNumConfigurations; // Number of possible configurations. } __attribute__((packed)) USB_FD_DEVICE_DESCRIPTOR; /* Configuration descriptor structure */ typedef struct { uint8_t bLength; // Length of this descriptor. uint8_t bDescriptorType; // CONFIGURATION descriptor type (USB_DESCRIPTOR_CONFIGURATION). uint16_t wTotalLength; // Total length of all descriptors for this configuration. uint8_t bNumInterfaces; // Number of interfaces in this configuration. uint8_t bConfigurationValue; // Value of this configuration (1 based). uint8_t iConfiguration; // Index of String Descriptor describing the configuration. uint8_t bmAttributes; // Configuration characteristics. uint8_t bMaxPower; // Maximum power consumed by this configuration. } __attribute__((packed)) USB_FD_CONFIGURATION_DESCRIPTOR; /* Interface descriptor structure */ typedef struct { uint8_t bLength; // Length of this descriptor. uint8_t bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE). uint8_t bInterfaceNumber; // Number of this interface (0 based). uint8_t bAlternateSetting; // Value of this alternate interface setting. uint8_t bNumEndpoints; // Number of endpoints in this interface. uint8_t bInterfaceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. uint8_t bInterfaceSubClass; // Subclass code (assigned by the USB-IF). uint8_t bInterfaceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. uint8_t iInterface; // Index of String Descriptor describing the interface. } __attribute__((packed)) USB_FD_INTERFACE_DESCRIPTOR; /* Endpoint descriptor structure */ typedef struct { uint8_t bLength; // Length of this descriptor. uint8_t bDescriptorType; // ENDPOINT descriptor type (USB_DESCRIPTOR_ENDPOINT). uint8_t bEndpointAddress; // Endpoint address. Bit 7 indicates direction (0=OUT, 1=IN). uint8_t bmAttributes; // Endpoint transfer type. uint16_t wMaxPacketSize; // Maximum packet size. uint8_t bInterval; // Polling interval in frames. } __attribute__((packed)) USB_FD_ENDPOINT_DESCRIPTOR; /* HID descriptor */ typedef struct { uint8_t bLength; uint8_t bDescriptorType; uint16_t bcdHID; // HID class specification release uint8_t bCountryCode; uint8_t bNumDescriptors; // Number of additional class specific descriptors uint8_t bDescrType; // Type of class descriptor uint16_t wDescriptorLength; // Total size of the Report descriptor } __attribute__((packed)) USB_HID_DESCRIPTOR; typedef struct { uint8_t bDescrType; // Type of class descriptor uint16_t wDescriptorLength; // Total size of the Report descriptor } __attribute__((packed)) HID_CLASS_DESCRIPTOR_LEN_AND_TYPE;
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/usb_ch9.h
C
agpl-3.0
9,945
/**************** * usb_host.cpp * ****************/ /**************************************************************************** * Written By Marcio Teixeira 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: <https://www.gnu.org/licenses/>. * ****************************************************************************/ /* What follows is a modified version of the MAX3421e originally defined in * lib/usbhost.c". This has been rewritten to use SPI routines from the * Marlin HAL */ #include "../../../inc/MarlinConfigPre.h" #if ENABLED(USB_FLASH_DRIVE_SUPPORT) && DISABLED(USE_UHS3_USB) #if !PINS_EXIST(USB_CS, USB_INTR) #error "USB_FLASH_DRIVE_SUPPORT requires USB_CS_PIN and USB_INTR_PIN to be defined." #endif #include "Usb.h" #include "usbhost.h" uint8_t MAX3421e::vbusState = 0; // constructor void MAX3421e::cs() { WRITE(USB_CS_PIN, LOW); } void MAX3421e::ncs() { WRITE(USB_CS_PIN, HIGH); } // write single byte into MAX3421 register void MAX3421e::regWr(uint8_t reg, uint8_t data) { cs(); spiSend(reg | 0x02); spiSend(data); ncs(); } // multiple-byte write // return a pointer to memory position after last written uint8_t* MAX3421e::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t *data_p) { cs(); spiSend(reg | 0x02); while (nbytes--) spiSend(*data_p++); ncs(); return data_p; } // GPIO write // GPIO byte is split between 2 registers, so two writes are needed to write one byte // GPOUT bits are in the low nybble. 0-3 in IOPINS1, 4-7 in IOPINS2 void MAX3421e::gpioWr(uint8_t data) { regWr(rIOPINS1, data); regWr(rIOPINS2, data >> 4); } // single host register read uint8_t MAX3421e::regRd(uint8_t reg) { cs(); spiSend(reg); uint8_t rv = spiRec(); ncs(); return rv; } // multiple-byte register read // return a pointer to a memory position after last read uint8_t* MAX3421e::bytesRd(uint8_t reg, uint8_t nbytes, uint8_t *data_p) { cs(); spiSend(reg); while (nbytes--) *data_p++ = spiRec(); ncs(); return data_p; } // GPIO read. See gpioWr for explanation // GPIN pins are in high nybbles of IOPINS1, IOPINS2 uint8_t MAX3421e::gpioRd() { return (regRd(rIOPINS2) & 0xF0) | // pins 4-7, clean lower nybble (regRd(rIOPINS1) >> 4); // shift low bits and OR with upper from previous operation. } // reset MAX3421e. Returns false if PLL failed to stabilize 1 second after reset bool MAX3421e::reset() { regWr(rUSBCTL, bmCHIPRES); regWr(rUSBCTL, 0x00); for (uint8_t i = 100; i--;) { if (regRd(rUSBIRQ) & bmOSCOKIRQ) return true; delay(10); } return false; } // initialize MAX3421e. Set Host mode, pullups, and stuff. Returns 0 if success, -1 if not bool MAX3421e::start() { // Initialize pins and SPI bus SET_OUTPUT(USB_CS_PIN); SET_INPUT_PULLUP(USB_INTR_PIN); ncs(); spiBegin(); spiInit(SD_SPI_SPEED); // MAX3421e - full-duplex, level interrupt, vbus off. regWr(rPINCTL, (bmFDUPSPI | bmINTLEVEL | GPX_VBDET)); const uint8_t revision = regRd(rREVISION); if (revision == 0x00 || revision == 0xFF) { SERIAL_ECHOLNPGM("Revision register appears incorrect on MAX3421e initialization. Got ", revision); return false; } if (!reset()) { SERIAL_ECHOLNPGM("OSCOKIRQ hasn't asserted in time"); return false; } // Delay a minimum of 1 second to ensure any capacitors are drained. // 1 second is required to make sure we do not smoke a Microdrive! delay(1000); regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST); // set pull-downs, Host regWr(rHIEN, bmCONDETIE | bmFRAMEIE); // connection detection // check if device is connected regWr(rHCTL, bmSAMPLEBUS); // sample USB bus while (!(regRd(rHCTL) & bmSAMPLEBUS)) delay(10); // wait for sample operation to finish busprobe(); // check if anything is connected regWr(rHIRQ, bmCONDETIRQ); // clear connection detect interrupt regWr(rCPUCTL, 0x01); // enable interrupt pin // GPX pin on. This is done here so that busprobe will fail if we have a switch connected. regWr(rPINCTL, bmFDUPSPI | bmINTLEVEL); return true; } // Probe bus to determine device presence and speed. Switch host to this speed. void MAX3421e::busprobe() { // Switch on just the J & K bits switch (regRd(rHRSL) & (bmJSTATUS | bmKSTATUS)) { case bmJSTATUS: if ((regRd(rMODE) & bmLOWSPEED) == 0) { regWr(rMODE, MODE_FS_HOST); // start full-speed host vbusState = FSHOST; } else { regWr(rMODE, MODE_LS_HOST); // start low-speed host vbusState = LSHOST; } break; case bmKSTATUS: if ((regRd(rMODE) & bmLOWSPEED) == 0) { regWr(rMODE, MODE_LS_HOST); // start low-speed host vbusState = LSHOST; } else { regWr(rMODE, MODE_FS_HOST); // start full-speed host vbusState = FSHOST; } break; case bmSE1: // illegal state vbusState = SE1; break; case bmSE0: // disconnected state regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST | bmSEPIRQ); vbusState = SE0; break; } } // MAX3421 state change task and interrupt handler uint8_t MAX3421e::Task() { return READ(USB_INTR_PIN) ? 0 : IntHandler(); } uint8_t MAX3421e::IntHandler() { uint8_t HIRQ = regRd(rHIRQ), // determine interrupt source HIRQ_sendback = 0x00; if (HIRQ & bmCONDETIRQ) { busprobe(); HIRQ_sendback |= bmCONDETIRQ; } // End HIRQ interrupts handling, clear serviced IRQs regWr(rHIRQ, HIRQ_sendback); return HIRQ_sendback; } #endif // USB_FLASH_DRIVE_SUPPORT
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/usbhost.cpp
C++
agpl-3.0
6,483
/************** * usb_host.h * **************/ /**************************************************************************** * Written By Marcio Teixeira 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: <https://www.gnu.org/licenses/>. * ****************************************************************************/ #pragma once /* This the following comes from "lib/usbhost.h", but has been rewritten * to use the SPI functions from Marlin's HAL */ class MAX3421e { private: static uint8_t vbusState; void cs(); void ncs(); uint8_t GpxHandler(); uint8_t IntHandler(); public: bool start(); void regWr(uint8_t reg, uint8_t data); uint8_t* bytesWr(uint8_t reg, uint8_t nbytes, uint8_t *data_p); void gpioWr(uint8_t data); uint8_t regRd(uint8_t reg); uint8_t* bytesRd(uint8_t reg, uint8_t nbytes, uint8_t *data_p); uint8_t gpioRd(); bool reset(); uint8_t getVbusState() {return vbusState;}; void busprobe(); uint8_t Task(); }; #define USE_MARLIN_MAX3421E #if defined(__SAM3X8E__) && !defined(ARDUINO_SAM_DUE) #define ARDUINO_SAM_DUE // Spoof the USB library that this is a DUE #endif
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs2/usbhost.h
C++
agpl-3.0
2,177
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #ifndef __UHS_BULK_STORAGE_H__ #define __UHS_BULK_STORAGE_H__ //////////////////////////////////////////////////////////////////////////////// // Define any of these options at the top of your sketch to override // the defaults contained herewith. Do NOT do modifications here. // Macro | Settings and notes | Default // -----------------------------------------+-----------------------+----------- // | 1 to 8 | // | Each LUN needs | // MASS_MAX_SUPPORTED_LUN | ~13 bytes to be able | 8 // | to track the state of | // | each unit. | // -----------------------------------------+-----------------------+----------- // | Just define to use. | // DEBUG_PRINTF_EXTRA_HUGE_UHS_BULK_STORAGE | works only if extra | // | huge debug is on too. | // -----------------------------------------^-----------------------^----------- #ifndef MASS_MAX_SUPPORTED_LUN #define MASS_MAX_SUPPORTED_LUN 8 #endif #include "UHS_SCSI.h" #define UHS_BULK_bmREQ_OUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE #define UHS_BULK_bmREQ_IN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE // Request Codes #define UHS_BULK_REQ_ADSC 0x00U #define UHS_BULK_REQ_GET 0xFCU #define UHS_BULK_REQ_PUT 0xFDU #define UHS_BULK_REQ_GET_MAX_LUN 0xFEU #define UHS_BULK_REQ_BOMSR 0xFFU // Mass Storage Reset #define UHS_BULK_CBW_SIGNATURE 0x43425355LU #define UHS_BULK_CSW_SIGNATURE 0x53425355LU #define UHS_BULK_CMD_DIR_OUT 0x00U #define UHS_BULK_CMD_DIR_IN 0x80U /* Bulk error codes */ #define UHS_BULK_ERR_SUCCESS UHS_HOST_ERROR_NONE #define UHS_BULK_ERR_PHASE_ERROR 0x22U #define UHS_BULK_ERR_UNIT_NOT_READY 0x23U #define UHS_BULK_ERR_UNIT_BUSY 0x24U #define UHS_BULK_ERR_STALL 0x25U #define UHS_BULK_ERR_CMD_NOT_SUPPORTED 0x26U #define UHS_BULK_ERR_INVALID_CSW 0x27U #define UHS_BULK_ERR_NO_MEDIA 0x28U #define UHS_BULK_ERR_BAD_LBA 0x29U #define UHS_BULK_ERR_MEDIA_CHANGED 0x2AU #define UHS_BULK_ERR_DEVICE_DISCONNECTED UHS_HOST_ERROR_UNPLUGGED #define UHS_BULK_ERR_UNABLE_TO_RECOVER 0x32U // Reset recovery error #define UHS_BULK_ERR_INVALID_LUN 0x33U #define UHS_BULK_ERR_WRITE_STALL 0x34U #define UHS_BULK_ERR_READ_NAKS 0x35U #define UHS_BULK_ERR_WRITE_NAKS 0x36U #define UHS_BULK_ERR_WRITE_PROTECTED 0x37U #define UHS_BULK_ERR_NOT_IMPLEMENTED 0xFDU #define UHS_BULK_ERR_GENERAL_SCSI_ERROR 0xF0U #define UHS_BULK_ERR_GENERAL_USB_ERROR 0xFFU #define UHS_BULK_ERR_USER 0xA0U // For subclasses to define their own error codes #define MASS_MAX_ENDPOINTS 3 struct UHS_BULK_CommandBlockWrapperBase { volatile uint32_t dCBWSignature; volatile uint32_t dCBWTag; volatile uint32_t dCBWDataTransferLength; volatile uint8_t bmCBWFlags; public: UHS_BULK_CommandBlockWrapperBase() { } UHS_BULK_CommandBlockWrapperBase(uint32_t tag, uint32_t xflen, uint8_t flgs) : dCBWSignature(UHS_BULK_CBW_SIGNATURE), dCBWTag(tag), dCBWDataTransferLength(xflen), bmCBWFlags(flgs) { } } __attribute__((packed)); struct UHS_BULK_CommandBlockWrapper : public UHS_BULK_CommandBlockWrapperBase { struct { uint8_t bmCBWLUN : 4; uint8_t bmReserved1 : 4; }; struct { uint8_t bmCBWCBLength : 4; uint8_t bmReserved2 : 4; }; uint8_t CBWCB[16]; public: // All zeroed. UHS_BULK_CommandBlockWrapper() : UHS_BULK_CommandBlockWrapperBase(0, 0, 0), bmReserved1(0), bmReserved2(0) { for(int i = 0; i < 16; i++) CBWCB[i] = 0; } // Generic Wrap, CDB zeroed. UHS_BULK_CommandBlockWrapper(uint32_t tag, uint32_t xflen, uint8_t flgs, uint8_t lu, uint8_t cmdlen, uint8_t cmd) : UHS_BULK_CommandBlockWrapperBase(tag, xflen, flgs), bmCBWLUN(lu), bmReserved1(0), bmCBWCBLength(cmdlen), bmReserved2(0) { for(int i = 0; i < 16; i++) CBWCB[i] = 0; SCSI_CDB_BASE_t *x = reinterpret_cast<SCSI_CDB_BASE_t *>(CBWCB); x->LUN = cmd; } // Wrap for CDB of 6 UHS_BULK_CommandBlockWrapper(uint32_t tag, uint32_t xflen, SCSI_CDB6_t *cdb, uint8_t dir) : UHS_BULK_CommandBlockWrapperBase(tag, xflen, dir), bmCBWLUN(cdb->LUN), bmReserved1(0), bmCBWCBLength(6), bmReserved2(0) { memcpy(&CBWCB, cdb, 6); } // Wrap for CDB of 10 UHS_BULK_CommandBlockWrapper(uint32_t tag, uint32_t xflen, SCSI_CDB10_t *cdb, uint8_t dir) : UHS_BULK_CommandBlockWrapperBase(tag, xflen, dir), bmCBWLUN(cdb->LUN), bmReserved1(0), bmCBWCBLength(10), bmReserved2(0) { memcpy(&CBWCB, cdb, 10); } } __attribute__((packed)); struct UHS_BULK_CommandStatusWrapper { uint32_t dCSWSignature; uint32_t dCSWTag; uint32_t dCSWDataResidue; uint8_t bCSWStatus; } __attribute__((packed)); class UHS_Bulk_Storage : public UHS_USBInterface { protected: static const uint8_t epDataInIndex = 1; // DataIn endpoint index static const uint8_t epDataOutIndex = 2; // DataOUT endpoint index static const uint8_t epInterruptInIndex = 3; // InterruptIN endpoint index uint8_t bMaxLUN; // Max LUN volatile uint32_t dCBWTag; // Tag volatile uint8_t bTheLUN; // Active LUN volatile uint32_t CurrentCapacity[MASS_MAX_SUPPORTED_LUN]; // Total sectors volatile uint16_t CurrentSectorSize[MASS_MAX_SUPPORTED_LUN]; // Sector size, clipped to 16 bits volatile bool LUNOk[MASS_MAX_SUPPORTED_LUN]; // use this to check for media changes. volatile bool WriteOk[MASS_MAX_SUPPORTED_LUN]; void PrintEndpointDescriptor(const USB_FD_ENDPOINT_DESCRIPTOR* ep_ptr); public: UHS_Bulk_Storage(UHS_USB_HOST_BASE *p); volatile UHS_EpInfo epInfo[MASS_MAX_ENDPOINTS]; uint8_t GetbMaxLUN() { return bMaxLUN; // Max LUN } uint8_t GetbTheLUN() { return bTheLUN; // Active LUN } bool WriteProtected(uint8_t lun); uint8_t MediaCTL(uint8_t lun, uint8_t ctl); uint8_t Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, uint8_t *buf); uint8_t Write(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, const uint8_t *buf); uint8_t LockMedia(uint8_t lun, uint8_t lock); bool LUNIsGood(uint8_t lun); uint32_t GetCapacity(uint8_t lun); uint16_t GetSectorSize(uint8_t lun); uint8_t SCSITransaction6(SCSI_CDB6_t *cdb, uint16_t buf_size, void *buf, uint8_t dir); uint8_t SCSITransaction10(SCSI_CDB10_t *cdb, uint16_t buf_size, void *buf, uint8_t dir); // Configure and internal methods, these should never be called by a user's sketch. uint8_t Start(); bool OKtoEnumerate(ENUMERATION_INFO *ei); uint8_t SetInterface(ENUMERATION_INFO *ei); uint8_t GetAddress() { return bAddress; }; void Poll(); void DriverDefaults(); private: void Reset(); void CheckMedia(); bool IsValidCBW(uint8_t size, uint8_t *pcbw); bool IsMeaningfulCBW(uint8_t size, uint8_t *pcbw); bool IsValidCSW(UHS_BULK_CommandStatusWrapper *pcsw, UHS_BULK_CommandBlockWrapperBase *pcbw); bool CheckLUN(uint8_t lun); uint8_t Inquiry(uint8_t lun, uint16_t size, uint8_t *buf); uint8_t TestUnitReady(uint8_t lun); uint8_t RequestSense(uint8_t lun, uint16_t size, uint8_t *buf); uint8_t ModeSense6(uint8_t lun, uint8_t pc, uint8_t page, uint8_t subpage, uint8_t len, uint8_t *buf); uint8_t GetMaxLUN(uint8_t *max_lun); uint8_t SetCurLUN(uint8_t lun); uint8_t ResetRecovery(); uint8_t ReadCapacity10(uint8_t lun, uint8_t *buf); uint8_t Page3F(uint8_t lun); uint8_t ClearEpHalt(uint8_t index); uint8_t Transaction(UHS_BULK_CommandBlockWrapper *cbw, uint16_t bsize, void *buf); uint8_t HandleUsbError(uint8_t error, uint8_t index); uint8_t HandleSCSIError(uint8_t status); }; #if defined(LOAD_UHS_BULK_STORAGE) && !defined(UHS_BULK_STORAGE_LOADED) #include "UHS_BULK_STORAGE_INLINE.h" #endif #endif // __MASSTORAGE_H__
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_BULK_STORAGE/UHS_BULK_STORAGE.h
C++
agpl-3.0
9,858
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if defined(LOAD_UHS_BULK_STORAGE) && defined(__UHS_BULK_STORAGE_H__) && !defined(UHS_BULK_STORAGE_LOADED) #define UHS_BULK_STORAGE_LOADED // uncomment to get 'printf' console debugging. NOT FOR UNO! //#define DEBUG_PRINTF_EXTRA_HUGE_UHS_BULK_STORAGE #if DEBUG_PRINTF_EXTRA_HUGE #ifdef DEBUG_PRINTF_EXTRA_HUGE_UHS_BULK_STORAGE #define BS_HOST_DEBUG(...) printf(__VA_ARGS__) #else #define BS_HOST_DEBUG(...) VOID0 #endif #else #define BS_HOST_DEBUG(...) VOID0 #endif //////////////////////////////////////////////////////////////////////////////// // Interface code //////////////////////////////////////////////////////////////////////////////// /** * Get the capacity of the media * * @param lun Logical Unit Number * @return media capacity */ uint32_t UHS_NI UHS_Bulk_Storage::GetCapacity(uint8_t lun) { uint32_t v = 0LU; pUsb->DisablePoll(); if(LUNOk[lun]) v = CurrentCapacity[lun]; pUsb->EnablePoll(); return v; } /** * Get the sector (block) size used on the media * * @param lun Logical Unit Number * @return media sector size */ uint16_t UHS_NI UHS_Bulk_Storage::GetSectorSize(uint8_t lun) { uint16_t v = 0U; pUsb->DisablePoll(); if(LUNOk[lun]) v = CurrentSectorSize[lun]; pUsb->EnablePoll(); return v; } /** * Test if LUN is ready for use * * @param lun Logical Unit Number * @return true if LUN is ready for use */ bool UHS_NI UHS_Bulk_Storage::LUNIsGood(uint8_t lun) { bool v; pUsb->DisablePoll(); v = LUNOk[lun]; pUsb->EnablePoll(); return v; } /** * Test if LUN is write protected * * @param lun Logical Unit Number * @return cached status of write protect switch */ bool UHS_NI UHS_Bulk_Storage::WriteProtected(uint8_t lun) { bool v; pUsb->DisablePoll(); v = WriteOk[lun]; pUsb->EnablePoll(); return v; } /** * Wrap and execute a SCSI CDB with length of 6 * * @param cdb CDB to execute * @param buf_size Size of expected transaction * @param buf Buffer * @param dir MASS_CMD_DIR_IN | MASS_CMD_DIR_OUT * @return */ uint8_t UHS_NI UHS_Bulk_Storage::SCSITransaction6(SCSI_CDB6_t *cdb, uint16_t buf_size, void *buf, uint8_t dir) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; pUsb->DisablePoll(); // promote buf_size to 32bits. UHS_BULK_CommandBlockWrapper cbw = UHS_BULK_CommandBlockWrapper(++dCBWTag, (uint32_t)buf_size, cdb, dir); #if 0 // Lets check the CBW here: printf("\r\n"); printf("\r\n"); uint8_t *dump = (uint8_t*)(&cbw); for(int i=0; i<(sizeof (UHS_BULK_CommandBlockWrapper)); i++) { printf("%02.2x ", *dump); dump++; } printf("\r\n"); printf("\r\n"); #endif uint8_t v = (HandleSCSIError(Transaction(&cbw, buf_size, buf))); pUsb->EnablePoll(); return v; } /** * Wrap and execute a SCSI CDB with length of 10 * * @param cdb CDB to execute * @param buf_size Size of expected transaction * @param buf Buffer * @param dir MASS_CMD_DIR_IN | MASS_CMD_DIR_OUT * @return */ uint8_t UHS_NI UHS_Bulk_Storage::SCSITransaction10(SCSI_CDB10_t *cdb, uint16_t buf_size, void *buf, uint8_t dir) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; pUsb->DisablePoll(); // promote buf_size to 32bits. UHS_BULK_CommandBlockWrapper cbw = UHS_BULK_CommandBlockWrapper(++dCBWTag, (uint32_t)buf_size, cdb, dir); //SetCurLUN(cdb->LUN); uint8_t v = (HandleSCSIError(Transaction(&cbw, buf_size, buf))); pUsb->EnablePoll(); return v; } /** * Lock or Unlock the tray or door on device. * Caution: Some devices with buggy firmware will lock up. * * @param lun Logical Unit Number * @param lock 1 to lock, 0 to unlock * @return */ uint8_t UHS_NI UHS_Bulk_Storage::LockMedia(uint8_t lun, uint8_t lock) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; pUsb->DisablePoll(); Notify(PSTR("\r\nLockMedia\r\n"), 0x80); Notify(PSTR("---------\r\n"), 0x80); SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_PREVENT_REMOVAL, lun, (uint8_t)0, lock); uint8_t v = SCSITransaction6(&cdb, (uint16_t)0, NULL, (uint8_t)UHS_BULK_CMD_DIR_IN); pUsb->EnablePoll(); return v; } /** * Media control, for spindle motor and media tray or door. * This includes CDROM, TAPE and anything with a media loader. * * @param lun Logical Unit Number * @param ctl 0x00 Stop Motor, 0x01 Start Motor, 0x02 Eject Media, 0x03 Load Media * @return 0 on success */ uint8_t UHS_NI UHS_Bulk_Storage::MediaCTL(uint8_t lun, uint8_t ctl) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; pUsb->DisablePoll(); Notify(PSTR("\r\nMediaCTL\r\n"), 0x80); Notify(PSTR("-----------------\r\n"), 0x80); uint8_t rcode = UHS_BULK_ERR_UNIT_NOT_READY; if(bAddress) { SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_START_STOP_UNIT, lun, ctl & 0x03, 0); rcode = SCSITransaction6(&cdb, (uint16_t)0, NULL, (uint8_t)UHS_BULK_CMD_DIR_OUT); } else { SetCurLUN(lun); } pUsb->EnablePoll(); return rcode; } /** * Read data from media * * @param lun Logical Unit Number * @param addr LBA address on media to read * @param bsize size of a block (we should probably use the cached size) * @param blocks how many blocks to read * @param buf memory that is able to hold the requested data * @return 0 on success */ uint8_t UHS_NI UHS_Bulk_Storage::Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, uint8_t *buf) { if(!bAddress) return UHS_BULK_ERR_NO_MEDIA; uint8_t er = UHS_BULK_ERR_NO_MEDIA; pUsb->DisablePoll(); if(LUNOk[lun]) { Notify(PSTR("\r\nRead LUN:\t"), 0x80); D_PrintHex<uint8_t > (lun, 0x90); Notify(PSTR("\r\nLBA:\t\t"), 0x90); D_PrintHex<uint32_t > (addr, 0x90); Notify(PSTR("\r\nblocks:\t\t"), 0x90); D_PrintHex<uint8_t > (blocks, 0x90); Notify(PSTR("\r\nblock size:\t"), 0x90); D_PrintHex<uint16_t > (bsize, 0x90); Notify(PSTR("\r\n---------\r\n"), 0x80); SCSI_CDB10_t cdb = SCSI_CDB10_t(SCSI_CMD_READ_10, lun, blocks, addr); again: er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), buf, (uint8_t)UHS_BULK_CMD_DIR_IN); if(er == UHS_BULK_ERR_STALL) { MediaCTL(lun, 1); if(UHS_SLEEP_MS(150)) { if(!TestUnitReady(lun)) goto again; } } } qNextPollTime = millis() + 100; pUsb->EnablePoll(); return er; } /** * Write data to media * * @param lun Logical Unit Number * @param addr LBA address on media to write * @param bsize size of a block (we should probably use the cached size) * @param blocks how many blocks to write * @param buf memory that contains the data to write * @return 0 on success */ uint8_t UHS_NI UHS_Bulk_Storage::Write(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, const uint8_t * buf) { if(!bAddress) return UHS_BULK_ERR_NO_MEDIA; uint8_t er = UHS_BULK_ERR_NO_MEDIA; pUsb->DisablePoll(); if(LUNOk[lun]) { if(!WriteOk[lun]) { er = UHS_BULK_ERR_WRITE_PROTECTED; } else { Notify(PSTR("\r\nWrite LUN:\t"), 0x80); D_PrintHex<uint8_t > (lun, 0x90); Notify(PSTR("\r\nLBA:\t\t"), 0x90); D_PrintHex<uint32_t > (addr, 0x90); Notify(PSTR("\r\nblocks:\t\t"), 0x90); D_PrintHex<uint8_t > (blocks, 0x90); Notify(PSTR("\r\nblock size:\t"), 0x90); D_PrintHex<uint16_t > (bsize, 0x90); Notify(PSTR("\r\n---------\r\n"), 0x80); SCSI_CDB10_t cdb = SCSI_CDB10_t(SCSI_CMD_WRITE_10, lun, blocks, addr); again: er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), (void*)buf, (uint8_t)UHS_BULK_CMD_DIR_OUT); if(er == UHS_BULK_ERR_WRITE_STALL) { MediaCTL(lun, 1); if(UHS_SLEEP_MS(150)) { if(!TestUnitReady(lun)) goto again; } } } } qNextPollTime = millis() + 100; pUsb->EnablePoll(); return er; } // End of user functions, the remaining code below is driver internals. // Only developer serviceable parts below! //////////////////////////////////////////////////////////////////////////////// // Main driver code //////////////////////////////////////////////////////////////////////////////// UHS_NI UHS_Bulk_Storage::UHS_Bulk_Storage(UHS_USB_HOST_BASE *p) { pUsb = p; dCBWTag = 0; if(pUsb) { DriverDefaults(); pUsb->RegisterDeviceClass(this); // Serial.print("Bulk Register to USB Host @ 0x"); // Serial.println((uint32_t)pUsb, HEX); // Serial.print("Bulk Register to USB Host Address Pool @ 0x"); // Serial.println((uint32_t)pUsb->GetAddressPool(), HEX); } } /** * @param ei Enumeration information * @return true if this interface driver can handle this interface description */ bool UHS_NI UHS_Bulk_Storage::OKtoEnumerate(ENUMERATION_INFO *ei) { BS_HOST_DEBUG("BulkOnly: checking numep %i, klass %2.2x, subklass %2.2x\r\n", ei->interface.numep, ei->klass, ei->subklass); BS_HOST_DEBUG("BulkOnly: checking protocol %2.2x, interface.klass %2.2x, interface.subklass %2.2x\r\n", ei->protocol, ei->interface.klass, ei->interface.subklass); BS_HOST_DEBUG("BulkOnly: checking interface.protocol %2.2x\r\n", ei->interface.protocol); // // TO-DO? // Check that we have 2 bulk endpoints, and one in each direction?? // e.g. (ei->interface.numep > 1) && // two or more endpoints AND check types // This will work with proper hardware though. // return ( ((ei->klass == UHS_USB_CLASS_MASS_STORAGE) || (ei->interface.klass == UHS_USB_CLASS_MASS_STORAGE)) && // mass storage class AND ((ei->subklass == UHS_BULK_SUBCLASS_SCSI) || (ei->interface.subklass == UHS_BULK_SUBCLASS_SCSI)) && // SCSI command set AND ((ei->protocol == UHS_STOR_PROTO_BBB) || (ei->interface.protocol == UHS_STOR_PROTO_BBB)) // Bulk Only transport ); } /** * @param ei Enumeration information * @return 0 always */ uint8_t UHS_NI UHS_Bulk_Storage::SetInterface(ENUMERATION_INFO *ei) { uint8_t index; bAddress = ei->address; BS_HOST_DEBUG("BS SetInterface\r\n"); // Fill in the endpoint info structure for(uint8_t ep = 0; ep < ei->interface.numep; ep++) { BS_HOST_DEBUG("ep: 0x%2.2x bmAttributes: 0x%2.2x ", ep, ei->interface.epInfo[ep].bmAttributes); if(ei->interface.epInfo[ep].bmAttributes == USB_TRANSFER_TYPE_BULK) { index = ((ei->interface.epInfo[ep].bEndpointAddress & USB_TRANSFER_DIRECTION_IN) == USB_TRANSFER_DIRECTION_IN) ? epDataInIndex : epDataOutIndex; epInfo[index].epAddr = (ei->interface.epInfo[ep].bEndpointAddress & 0x0F); epInfo[index].maxPktSize = ei->interface.epInfo[ep].wMaxPacketSize; epInfo[index].epAttribs = 0; epInfo[index].bmNakPower = UHS_USB_NAK_MAX_POWER; epInfo[index].bmSndToggle = 0; epInfo[index].bmRcvToggle = 0; epInfo[index].bIface=ei->interface.bInterfaceNumber; BS_HOST_DEBUG("index: %i\r\n", index); } BS_HOST_DEBUG("\r\n"); } bNumEP = 3; epInfo[0].epAddr = 0; epInfo[0].maxPktSize = ei->bMaxPacketSize0; epInfo[0].bmNakPower = UHS_USB_NAK_MAX_POWER; bIface = ei->interface.bInterfaceNumber; return 0; }; /** * @return 0 for success */ uint8_t UHS_NI UHS_Bulk_Storage::Start() { uint8_t rcode; // Serial.print("Bulk Start from USB Host @ 0x"); // Serial.println((uint32_t)pUsb, HEX); // Serial.print("Bulk Start USB Host Address Pool @ 0x"); // Serial.println((uint32_t)pUsb->GetAddressPool(), HEX); BS_HOST_DEBUG("BS Start, speed: %i\r\n", pUsb->GetAddressPool()->GetUsbDevicePtr(bAddress)->speed); BS_HOST_DEBUG("BS Start\r\n"); rcode = pUsb->setEpInfoEntry(bAddress, bIface, 3, epInfo); // Serial.println(rcode,HEX); if(rcode) goto FailOnInit; // Do a 1 second delay before LUN query if(!UHS_SLEEP_MS(1000)) goto FailUnPlug; rcode = GetMaxLUN(&bMaxLUN); BS_HOST_DEBUG("GetMaxLUN 0x%2.2x\r\n", rcode); if(rcode) { goto FailGetMaxLUN; } if(bMaxLUN >= MASS_MAX_SUPPORTED_LUN) bMaxLUN = MASS_MAX_SUPPORTED_LUN - 1; BS_HOST_DEBUG("MaxLUN %u\r\n", bMaxLUN); //ErrorMessage<uint8_t > (PSTR("MaxLUN"), bMaxLUN); if(!UHS_SLEEP_MS(150)) goto FailUnPlug; // Delay a bit for slow firmware. (again) for(uint8_t lun = 0; lun <= bMaxLUN; lun++) { if(!UHS_SLEEP_MS(3)) goto FailUnPlug; SCSI_Inquiry_Response response; rcode = Inquiry(lun, sizeof (SCSI_Inquiry_Response), (uint8_t*) & response); BS_HOST_DEBUG("Inquiry 0x%2.2x 0x%2.2x\r\n", sizeof (SCSI_Inquiry_Response), rcode); if(rcode) { goto FailInquiry; #if 0 } else { BS_HOST_DEBUG("LUN %i `", lun); uint8_t *buf = response.VendorID; for(int i = 0; i < 28; i++) BS_HOST_DEBUG("%c", buf[i]); BS_HOST_DEBUG("'\r\nQualifier %1.1X ", response.PeripheralQualifier); BS_HOST_DEBUG("Device type %2.2X ", response.DeviceType); BS_HOST_DEBUG("RMB %1.1X ", response.Removable); BS_HOST_DEBUG("SSCS %1.1X ", response.SCCS); uint8_t sv = response.Version; BS_HOST_DEBUG("SCSI version %2.2X\r\nDevice conforms to ", sv); switch(sv) { case 0: BS_HOST_DEBUG("No specific"); break; case 1: BS_HOST_DEBUG("ANSI X3.131-1986 (ANSI 1)"); break; case 2: BS_HOST_DEBUG("ANSI X3.131-1994 (ANSI 2)"); break; case 3: BS_HOST_DEBUG("ANSI INCITS 301-1997 (SPC)"); break; case 4: BS_HOST_DEBUG("ANSI INCITS 351-2001 (SPC-2)"); break; case 5: BS_HOST_DEBUG("ANSI INCITS 408-2005 (SPC-4)"); break; case 6: BS_HOST_DEBUG("T10/1731-D (SPC-4)"); break; default: BS_HOST_DEBUG("unknown"); } BS_HOST_DEBUG(" standards.\r\n"); #endif } } for(uint8_t lun = 0; lun <= bMaxLUN; lun++) { if(!UHS_SLEEP_MS(3)) goto FailUnPlug; #ifndef USB_NO_TEST_UNIT_READY uint8_t tries = 0xF0; while((rcode = TestUnitReady(lun))) { BS_HOST_DEBUG("\r\nTry %2.2x TestUnitReady %2.2x\r\n", tries - 0xF0, rcode); if(rcode == 0x08) break; // break on no media, this is OK to do. if(rcode == UHS_BULK_ERR_DEVICE_DISCONNECTED) goto FailUnPlug; if(rcode == UHS_BULK_ERR_INVALID_CSW) goto Fail; if(rcode != UHS_BULK_ERR_MEDIA_CHANGED) goto Fail; if(!UHS_SLEEP_MS(2 * (tries + 1))) goto FailUnPlug; tries++; if(!tries) break; } #else // Don't wait for the LUN to become ready, as this will // trigger Marlin's watchdog timer rcode = -1; #endif if(!UHS_SLEEP_MS(3)) goto FailUnPlug; LockMedia(lun, 1); if(rcode == 0x08) { if(!UHS_SLEEP_MS(3)) goto FailUnPlug; if(MediaCTL(lun, 1) == UHS_BULK_ERR_DEVICE_DISCONNECTED) goto FailUnPlug; // I actually have a USB stick that needs this! } BS_HOST_DEBUG("\r\nTry %2.2x TestUnitReady %2.2x\r\n", tries - 0xF0, rcode); if(!rcode) { if(!UHS_SLEEP_MS(3)) goto FailUnPlug; BS_HOST_DEBUG("CheckLUN...\r\n"); BS_HOST_DEBUG("%lu\r\n", millis()/1000); // Stalls on ***some*** devices, ***WHY***?! Device SAID it is READY!! LUNOk[lun] = CheckLUN(lun); BS_HOST_DEBUG("%lu\r\n", millis()/1000); if(!LUNOk[lun]) LUNOk[lun] = CheckLUN(lun); if(!UHS_SLEEP_MS(1)) goto FailUnPlug; BS_HOST_DEBUG("Checked LUN...\r\n"); } else { LUNOk[lun] = false; } } rcode = OnStart(); if(rcode) goto FailOnInit; #ifdef DEBUG_USB_HOST USBTRACE("BS configured\r\n\r\n"); #endif qNextPollTime = millis() + 100; bPollEnable = true; return 0; FailUnPlug: rcode = UHS_BULK_ERR_DEVICE_DISCONNECTED; goto Fail; FailOnInit: #ifdef DEBUG_USB_HOST USBTRACE("OnStart:"); goto Fail; #endif FailGetMaxLUN: #ifdef DEBUG_USB_HOST USBTRACE("GetMaxLUN:"); goto Fail; #endif FailInquiry: #ifdef DEBUG_USB_HOST USBTRACE("Inquiry:"); #endif Fail: #ifdef DEBUG_USB_HOST NotifyFail(rcode); #endif Release(); return rcode; } // Base class definition of Release() used. See UHS_USBInterface class definition for details /** * For driver use only. * * @return */ //void UHS_NI UHS_Bulk_Storage::Release() { // pUsb->DisablePoll(); // OnRelease(); // DriverDefaults(); // pUsb->EnablePoll(); // return; //} /** * For driver use only. * * @param lun Logical Unit Number * @return true if LUN is ready for use. */ bool UHS_NI UHS_Bulk_Storage::CheckLUN(uint8_t lun) { uint8_t rcode; SCSI_Capacity capacity; for(uint8_t i = 0; i < 8; i++) capacity.data[i] = 0; rcode = ReadCapacity10(lun, (uint8_t*)capacity.data); if(rcode) { BS_HOST_DEBUG(">>>>>>>>>>>>>>>>ReadCapacity returned %i\r\n", rcode); return false; } #ifdef DEBUG_USB_HOST ErrorMessage<uint8_t > (PSTR(">>>>>>>>>>>>>>>>CAPACITY OK ON LUN"), lun); for(uint8_t i = 0; i < 8 /*sizeof (Capacity)*/; i++) D_PrintHex<uint8_t > (capacity.data[i], 0x80); Notify(PSTR("\r\n\r\n"), 0x80); #endif // Only 512/1024/2048/4096 are valid values! uint32_t c = UHS_BYTES_TO_UINT32(capacity.data[4], capacity.data[5], capacity.data[6], capacity.data[7]); if(c != 0x0200LU && c != 0x0400LU && c != 0x0800LU && c != 0x1000LU) { return false; } // Store capacity information. CurrentSectorSize[lun] = (uint16_t)(c); // & 0xFFFF); CurrentCapacity[lun] = UHS_BYTES_TO_UINT32(capacity.data[0], capacity.data[1], capacity.data[2], capacity.data[3]) + 1; if(CurrentCapacity[lun] == /*0xffffffffLU */ 0x01LU || CurrentCapacity[lun] == 0x00LU) { // Buggy firmware will report 0xFFFFFFFF or 0 for no media #ifdef DEBUG_USB_HOST if(CurrentCapacity[lun]) ErrorMessage<uint8_t > (PSTR(">>>>>>>>>>>>>>>>BUGGY FIRMWARE. CAPACITY FAIL ON LUN"), lun); #endif return false; } if(!UHS_SLEEP_MS(20)) return false; #ifndef SKIP_PAGE3F Page3F(lun); #endif if(!TestUnitReady(lun)) return true; return false; } /** * For driver use only. * * Scan for media change on all LUNs */ void UHS_NI UHS_Bulk_Storage::CheckMedia() { if(!bAddress) return; for(uint8_t lun = 0; lun <= bMaxLUN; lun++) { if(TestUnitReady(lun)) { LUNOk[lun] = false; continue; } if(!LUNOk[lun]) LUNOk[lun] = CheckLUN(lun); } #if 0 BS_HOST_DEBUG("}}}}}}}}}}}}}}}}STATUS "); for(uint8_t lun = 0; lun <= bMaxLUN; lun++) { if(LUNOk[lun]) BS_HOST_DEBUG("#"); else BS_HOST_DEBUG("."); } BS_HOST_DEBUG("\r\n"); #endif OnPoll(); qNextPollTime = millis() + 100; } /** * For driver use only. */ void UHS_NI UHS_Bulk_Storage::Poll() { if((long)(millis() - qNextPollTime) >= 0L) { CheckMedia(); } return; } //////////////////////////////////////////////////////////////////////////////// // SCSI code //////////////////////////////////////////////////////////////////////////////// /** * For driver use only. * * @param plun * @return */ uint8_t UHS_NI UHS_Bulk_Storage::GetMaxLUN(uint8_t *plun) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; uint8_t ret = pUsb->ctrlReq(bAddress, mkSETUP_PKT16(UHS_BULK_bmREQ_IN, UHS_BULK_REQ_GET_MAX_LUN, 0x0000U, bIface, 1), 1, plun); if(ret == UHS_HOST_ERROR_STALL) { *plun = 0; Notify(PSTR("\r\nGetMaxLUN Stalled\r\n"), 0x80); } return 0; } /** * For driver use only. Used during Driver Start * * @param lun Logical Unit Number * @param bsize * @param buf * @return */ uint8_t UHS_NI UHS_Bulk_Storage::Inquiry(uint8_t lun, uint16_t bsize, uint8_t *buf) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; Notify(PSTR("\r\nInquiry\r\n"), 0x80); Notify(PSTR("---------\r\n"), 0x80); SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_INQUIRY, lun, 0LU, (uint8_t)bsize, 0); uint8_t rc = SCSITransaction6(&cdb, bsize, buf, (uint8_t)UHS_BULK_CMD_DIR_IN); return rc; } /** * For driver use only. * * @param lun Logical Unit Number * @return */ uint8_t UHS_NI UHS_Bulk_Storage::TestUnitReady(uint8_t lun) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; //SetCurLUN(lun); if(!bAddress) return UHS_BULK_ERR_UNIT_NOT_READY; Notify(PSTR("\r\nTestUnitReady\r\n"), 0x80); Notify(PSTR("-----------------\r\n"), 0x80); SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_TEST_UNIT_READY, lun, (uint8_t)0, 0); return SCSITransaction6(&cdb, 0, NULL, (uint8_t)UHS_BULK_CMD_DIR_IN); } /** * For driver use only. * * @param lun Logical Unit Number * @param pc * @param page * @param subpage * @param len * @param pbuf * @return */ uint8_t UHS_NI UHS_Bulk_Storage::ModeSense6(uint8_t lun, uint8_t pc, uint8_t page, uint8_t subpage, uint8_t len, uint8_t * pbuf) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; Notify(PSTR("\r\rModeSense\r\n"), 0x80); Notify(PSTR("------------\r\n"), 0x80); SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_MODE_SENSE_6, lun, (uint32_t)((((pc << 6) | page) << 8) | subpage), len, 0); return SCSITransaction6(&cdb, len, pbuf, (uint8_t)UHS_BULK_CMD_DIR_IN); } /** * For driver use only. * * @param lun Logical Unit Number * @param bsize * @param buf * @return */ uint8_t UHS_NI UHS_Bulk_Storage::ReadCapacity10(uint8_t lun, uint8_t *buf) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; Notify(PSTR("\r\nReadCapacity\r\n"), 0x80); Notify(PSTR("---------------\r\n"), 0x80); SCSI_CDB10_t cdb = SCSI_CDB10_t(SCSI_CMD_READ_CAPACITY_10, lun); return SCSITransaction10(&cdb, 8, buf, (uint8_t)UHS_BULK_CMD_DIR_IN); } /** * For driver use only. * * Page 3F contains write protect status. * * @param lun Logical Unit Number to test. * @return Write protect switch status. */ uint8_t UHS_NI UHS_Bulk_Storage::Page3F(uint8_t lun) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; uint8_t buf[192]; for(int i = 0; i < 192; i++) { buf[i] = 0x00; } WriteOk[lun] = true; uint8_t rc = ModeSense6(lun, 0, 0x3F, 0, 192, buf); if(!rc) { WriteOk[lun] = ((buf[2] & 0x80) == 0); #ifdef DEBUG_USB_HOST Notify(PSTR("Mode Sense: "), 0x80); for(int i = 0; i < 4; i++) { D_PrintHex<uint8_t > (buf[i], 0x80); Notify(PSTR(" "), 0x80); } Notify(PSTR("\r\n"), 0x80); #endif } return rc; } /** * For driver use only. * * @param lun Logical Unit Number * @param size * @param buf * @return */ uint8_t UHS_NI UHS_Bulk_Storage::RequestSense(uint8_t lun, uint16_t size, uint8_t *buf) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; pUsb->DisablePoll(); Notify(PSTR("\r\nRequestSense\r\n"), 0x80); Notify(PSTR("----------------\r\n"), 0x80); SCSI_CDB6_t cdb = SCSI_CDB6_t(SCSI_CMD_REQUEST_SENSE, lun, 0LU, (uint8_t)size, 0); UHS_BULK_CommandBlockWrapper cbw = UHS_BULK_CommandBlockWrapper(++dCBWTag, (uint32_t)size, &cdb, (uint8_t)UHS_BULK_CMD_DIR_IN); uint8_t v = Transaction(&cbw, size, buf); pUsb->EnablePoll(); return v; } //////////////////////////////////////////////////////////////////////////////// // USB code //////////////////////////////////////////////////////////////////////////////// /** * For driver use only. * * @param index * @return */ uint8_t UHS_NI UHS_Bulk_Storage::ClearEpHalt(uint8_t index) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; uint8_t ret = 0; if(index != 0) { uint8_t ep = (index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr; do { ret = pUsb->EPClearHalt(bAddress, ep); if(!UHS_SLEEP_MS(6)) break; } while(ret == 0x01); if(ret) { ErrorMessage<uint8_t > (PSTR("ClearEpHalt"), ret); ErrorMessage<uint8_t > (PSTR("EP"), ep); epInfo[index].bmSndToggle = 0; epInfo[index].bmRcvToggle = 0; return ret; } else { epInfo[index].bmSndToggle = 0; epInfo[index].bmRcvToggle = 0; } } return ret; } /** * For driver use only. */ void UHS_NI UHS_Bulk_Storage::Reset() { if(!bAddress) return; while(pUsb->ctrlReq(bAddress, mkSETUP_PKT16(UHS_BULK_bmREQ_OUT, UHS_BULK_REQ_BOMSR, 0x0000U, bIface, 0), 0, NULL) == 0x01) { if(!UHS_SLEEP_MS(6)) break; } if(!bAddress) return; UHS_SLEEP_MS(2500); } /** * For driver use only. * * @return 0 if successful */ uint8_t UHS_NI UHS_Bulk_Storage::ResetRecovery() { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; Notify(PSTR("\r\nResetRecovery\r\n"), 0x80); Notify(PSTR("-----------------\r\n"), 0x80); qNextPollTime = millis() + 90000; uint8_t bLastUsbError = UHS_HOST_ERROR_UNPLUGGED; if(UHS_SLEEP_MS(6)) { Reset(); if(UHS_SLEEP_MS(6)) { bLastUsbError = ClearEpHalt(epDataInIndex); if(UHS_SLEEP_MS(6)) { bLastUsbError = ClearEpHalt(epDataOutIndex); UHS_SLEEP_MS(6); } } } return bLastUsbError; } /** * For driver use only. * * Clear all EP data and clear all LUN status */ void UHS_NI UHS_Bulk_Storage::DriverDefaults() { pUsb->DeviceDefaults(MASS_MAX_ENDPOINTS, this); for(uint8_t i = 0; i < MASS_MAX_SUPPORTED_LUN; i++) { LUNOk[i] = false; WriteOk[i] = false; CurrentCapacity[i] = 0lu; CurrentSectorSize[i] = 0; } dCBWTag = 0; bMaxLUN = 0; bTheLUN = 0; } /** * For driver use only. * * @param pcsw * @param pcbw * @return */ bool UHS_NI UHS_Bulk_Storage::IsValidCSW(UHS_BULK_CommandStatusWrapper *pcsw, UHS_BULK_CommandBlockWrapperBase *pcbw) { if(!bAddress) return false; if(pcsw->dCSWSignature != UHS_BULK_CSW_SIGNATURE) { Notify(PSTR("CSW:Sig error\r\n"), 0x80); return false; } if(pcsw->dCSWTag != pcbw->dCBWTag) { Notify(PSTR("CSW:Wrong tag\r\n"), 0x80); ErrorMessage<uint32_t > (PSTR("dCSWTag"), pcsw->dCSWTag); ErrorMessage<uint32_t > (PSTR("dCBWTag"), pcbw->dCBWTag); return false; } return true; } /** * For driver use only. * * @param error * @param index * @return */ uint8_t UHS_NI UHS_Bulk_Storage::HandleUsbError(uint8_t error, uint8_t index) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; uint8_t count = 3; while(error && count) { if(error != UHS_HOST_ERROR_NONE) { ErrorMessage<uint8_t > (PSTR("USB Error"), error); ErrorMessage<uint8_t > (PSTR("Index"), index); } switch(error) { // case UHS_HOST_ERROR_WRONGPID: case UHS_HOST_ERROR_NONE: return UHS_BULK_ERR_SUCCESS; case UHS_HOST_ERROR_BUSY: // SIE is busy, just hang out and try again. return UHS_BULK_ERR_UNIT_BUSY; case UHS_HOST_ERROR_NAK: return UHS_BULK_ERR_UNIT_BUSY; case UHS_HOST_ERROR_UNPLUGGED: case UHS_HOST_ERROR_TIMEOUT: case UHS_HOST_ERROR_JERR: return UHS_BULK_ERR_DEVICE_DISCONNECTED; case UHS_HOST_ERROR_STALL: if(index == 0) return UHS_BULK_ERR_STALL; ClearEpHalt(index); if(index != epDataInIndex) return UHS_BULK_ERR_WRITE_STALL; return UHS_BULK_ERR_STALL; case UHS_HOST_ERROR_TOGERR: // Handle a very super rare corner case, where toggles become de-synched. // I have only ran into one device that has this firmware bug, and this is // the only clean way to get back into sync with the buggy device firmware. // --AJK if(bAddress && bConfNum) { error = pUsb->setConf(bAddress, bConfNum); if(error) break; } return UHS_BULK_ERR_SUCCESS; default: ErrorMessage<uint8_t > (PSTR("\r\nUSB"), error); return UHS_BULK_ERR_GENERAL_USB_ERROR; } count--; } // while return ((error && !count) ? UHS_BULK_ERR_GENERAL_USB_ERROR : UHS_BULK_ERR_SUCCESS); } /** * For driver use only. * * @param pcbw * @param buf_size * @param buf * @param flags * @return */ uint8_t UHS_NI UHS_Bulk_Storage::Transaction(UHS_BULK_CommandBlockWrapper *pcbw, uint16_t buf_size, void *buf) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; uint16_t bytes = buf_size; bool write = (pcbw->bmCBWFlags & UHS_BULK_CMD_DIR_IN) != UHS_BULK_CMD_DIR_IN; uint8_t ret = 0; uint8_t usberr; UHS_BULK_CommandStatusWrapper csw; // up here, we allocate ahead to save cpu cycles. SetCurLUN(pcbw->bmCBWLUN); ErrorMessage<uint32_t > (PSTR("CBW.dCBWTag"), pcbw->dCBWTag); while((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, sizeof (UHS_BULK_CommandBlockWrapper), (uint8_t*)pcbw)) == UHS_HOST_ERROR_BUSY) { if(!UHS_SLEEP_MS(1)) return UHS_BULK_ERR_DEVICE_DISCONNECTED; } ret = HandleUsbError(usberr, epDataOutIndex); if(ret) { ErrorMessage<uint8_t > (PSTR("============================ CBW"), ret); } else { if(bytes) { if(!write) { while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*)buf)) == UHS_HOST_ERROR_BUSY) { if(!UHS_SLEEP_MS(1)) return UHS_BULK_ERR_DEVICE_DISCONNECTED; } ret = HandleUsbError(usberr, epDataInIndex); } else { while((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, bytes, (uint8_t*)buf)) == UHS_HOST_ERROR_BUSY) { if(!UHS_SLEEP_MS(1)) return UHS_BULK_ERR_DEVICE_DISCONNECTED; } ret = HandleUsbError(usberr, epDataOutIndex); } if(ret) { ErrorMessage<uint8_t > (PSTR("============================ DAT"), ret); } } } { bytes = sizeof (UHS_BULK_CommandStatusWrapper); int tries = 2; while(tries--) { while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*) & csw)) == UHS_HOST_ERROR_BUSY) { if(!UHS_SLEEP_MS(1)) return UHS_BULK_ERR_DEVICE_DISCONNECTED; } if(!usberr) break; if(tries) { if(usberr == UHS_HOST_ERROR_STALL) { ResetRecovery(); } else { ClearEpHalt(epDataInIndex); } } } if(!ret) { Notify(PSTR("CBW:\t\tOK\r\n"), 0x80); Notify(PSTR("Data Stage:\tOK\r\n"), 0x80); } else { // Throw away csw, IT IS NOT OF ANY USE. ResetRecovery(); return ret; } ret = HandleUsbError(usberr, epDataInIndex); if(ret) { ErrorMessage<uint8_t > (PSTR("============================ CSW"), ret); } if(usberr == UHS_HOST_ERROR_NONE) { if(IsValidCSW(&csw, pcbw)) { //ErrorMessage<uint32_t > (PSTR("CSW.dCBWTag"), csw.dCSWTag); //ErrorMessage<uint8_t > (PSTR("bCSWStatus"), csw.bCSWStatus); //ErrorMessage<uint32_t > (PSTR("dCSWDataResidue"), csw.dCSWDataResidue); Notify(PSTR("CSW:\t\tOK\r\n\r\n"), 0x80); return csw.bCSWStatus; } else { // NOTE! Sometimes this is caused by the reported residue being wrong. // Get a different device. It isn't compliant, and should have never passed Q&A. // I own one... 05e3:0701 Genesys Logic, Inc. USB 2.0 IDE Adapter. // Other devices that exhibit this behavior exist in the wild too. // Be sure to check quirks in the Linux source code before reporting a bug. --xxxajk Notify(PSTR("Invalid CSW\r\n"), 0x80); Reset(); ResetRecovery(); return UHS_BULK_ERR_INVALID_CSW; } } } return ret; } /** * For driver use only. * * @param lun Logical Unit Number * @return */ uint8_t UHS_NI UHS_Bulk_Storage::SetCurLUN(uint8_t lun) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; if(lun > bMaxLUN) return UHS_BULK_ERR_INVALID_LUN; bTheLUN = lun; return UHS_BULK_ERR_SUCCESS; }; /** * For driver use only. * * @param status * @return */ uint8_t UHS_NI UHS_Bulk_Storage::HandleSCSIError(uint8_t status) { if(!bAddress) return UHS_BULK_ERR_DEVICE_DISCONNECTED; uint8_t ret = 0; switch(status) { case 0: return UHS_BULK_ERR_SUCCESS; case 2: ErrorMessage<uint8_t > (PSTR("Phase Error"), status); ErrorMessage<uint8_t > (PSTR("LUN"), bTheLUN); ResetRecovery(); return UHS_BULK_ERR_GENERAL_SCSI_ERROR; case 1: ErrorMessage<uint8_t > (PSTR("SCSI Error"), status); ErrorMessage<uint8_t > (PSTR("LUN"), bTheLUN); SCSI_Request_Sense_Response rsp; ret = RequestSense(bTheLUN, sizeof (SCSI_Request_Sense_Response), (uint8_t*) & rsp); if(ret) { if(ret == UHS_BULK_ERR_DEVICE_DISCONNECTED) return UHS_BULK_ERR_DEVICE_DISCONNECTED; return UHS_BULK_ERR_GENERAL_SCSI_ERROR; } #if ENABLE_UHS_DEBUGGING ErrorMessage<uint8_t > (PSTR("Response Code"), rsp.bResponseCode); if(rsp.bResponseCode & 0x80) { Notify(PSTR("Information field: "), 0x80); for(int i = 0; i < 4; i++) { D_PrintHex<uint8_t > (rsp.CmdSpecificInformation[i], 0x80); Notify(PSTR(" "), 0x80); } Notify(PSTR("\r\n"), 0x80); } ErrorMessage<uint8_t > (PSTR("Sense Key"), rsp.bmSenseKey); ErrorMessage<uint8_t > (PSTR("Add Sense Code"), rsp.bAdditionalSenseCode); ErrorMessage<uint8_t > (PSTR("Add Sense Qual"), rsp.bAdditionalSenseQualifier); #endif // warning, this is not testing ASQ, only SK and ASC. switch(rsp.bmSenseKey) { case SCSI_S_UNIT_ATTENTION: switch(rsp.bAdditionalSenseCode) { case SCSI_ASC_MEDIA_CHANGED: return UHS_BULK_ERR_MEDIA_CHANGED; default: return UHS_BULK_ERR_UNIT_NOT_READY; } case SCSI_S_NOT_READY: switch(rsp.bAdditionalSenseCode) { case SCSI_ASC_MEDIUM_NOT_PRESENT: return UHS_BULK_ERR_NO_MEDIA; default: return UHS_BULK_ERR_UNIT_NOT_READY; } case SCSI_S_ILLEGAL_REQUEST: switch(rsp.bAdditionalSenseCode) { case SCSI_ASC_LBA_OUT_OF_RANGE: return UHS_BULK_ERR_BAD_LBA; default: return UHS_BULK_ERR_CMD_NOT_SUPPORTED; } default: return UHS_BULK_ERR_GENERAL_SCSI_ERROR; } // case 4: return MASS_ERR_UNIT_BUSY; // Busy means retry later. // case 0x05/0x14: we stalled out // case 0x15/0x16: we naked out. default: ErrorMessage<uint8_t > (PSTR("Gen SCSI Err"), status); ErrorMessage<uint8_t > (PSTR("LUN"), bTheLUN); return status; } // switch } //////////////////////////////////////////////////////////////////////////////// // Debugging code //////////////////////////////////////////////////////////////////////////////// /** * @param ep_ptr */ void UHS_NI UHS_Bulk_Storage::PrintEndpointDescriptor(const USB_FD_ENDPOINT_DESCRIPTOR * ep_ptr) { Notify(PSTR("Endpoint descriptor:"), 0x80); Notify(PSTR("\r\nLength:\t\t"), 0x80); D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80); Notify(PSTR("\r\nType:\t\t"), 0x80); D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80); Notify(PSTR("\r\nAddress:\t"), 0x80); D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80); Notify(PSTR("\r\nAttributes:\t"), 0x80); D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80); Notify(PSTR("\r\nMaxPktSize:\t"), 0x80); D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80); Notify(PSTR("\r\nPoll Intrv:\t"), 0x80); D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80); Notify(PSTR("\r\n"), 0x80); } #else #error "Never include UHS_BULK_STORAGE_INLINE.h, include UHS_host.h instead" #endif
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_BULK_STORAGE/UHS_BULK_STORAGE_INLINE.h
C
agpl-3.0
44,636
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #ifndef UHS_SCSI_H #define UHS_SCSI_H /* * Reference documents from T10 (https://www.t10.org) * SCSI Primary Commands - 3 (SPC-3) * SCSI Block Commands - 2 (SBC-2) * Multi-Media Commands - 5 (MMC-5) */ /* Group 1 commands (CDB's here are should all be 6-bytes) */ #define SCSI_CMD_TEST_UNIT_READY 0x00U #define SCSI_CMD_REQUEST_SENSE 0x03U #define SCSI_CMD_FORMAT_UNIT 0x04U #define SCSI_CMD_READ_6 0x08U #define SCSI_CMD_WRITE_6 0x0AU #define SCSI_CMD_INQUIRY 0x12U #define SCSI_CMD_MODE_SELECT_6 0x15U #define SCSI_CMD_MODE_SENSE_6 0x1AU #define SCSI_CMD_START_STOP_UNIT 0x1BU #define SCSI_CMD_PREVENT_REMOVAL 0x1EU /* Group 2 Commands (CDB's here are 10-bytes) */ #define SCSI_CMD_READ_FORMAT_CAPACITIES 0x23U #define SCSI_CMD_READ_CAPACITY_10 0x25U #define SCSI_CMD_READ_10 0x28U #define SCSI_CMD_WRITE_10 0x2AU #define SCSI_CMD_SEEK_10 0x2BU #define SCSI_CMD_ERASE_10 0x2CU #define SCSI_CMD_WRITE_AND_VERIFY_10 0x2EU #define SCSI_CMD_VERIFY_10 0x2FU #define SCSI_CMD_SYNCHRONIZE_CACHE 0x35U #define SCSI_CMD_WRITE_BUFFER 0x3BU #define SCSI_CMD_READ_BUFFER 0x3CU #define SCSI_CMD_READ_SUBCHANNEL 0x42U #define SCSI_CMD_READ_TOC 0x43U #define SCSI_CMD_READ_HEADER 0x44U #define SCSI_CMD_PLAY_AUDIO_10 0x45U #define SCSI_CMD_GET_CONFIGURATION 0x46U #define SCSI_CMD_PLAY_AUDIO_MSF 0x47U #define SCSI_CMD_PLAY_AUDIO_TI 0x48U #define SCSI_CMD_PLAY_TRACK_REL_10 0x49U #define SCSI_CMD_GET_EVENT_STATUS 0x4AU #define SCSI_CMD_PAUSE_RESUME 0x4BU #define SCSI_CMD_READ_DISC_INFORMATION 0x51U #define SCSI_CMD_READ_TRACK_INFORMATION 0x52U #define SCSI_CMD_RESERVE_TRACK 0x53U #define SCSI_CMD_SEND_OPC_INFORMATION 0x54U #define SCSI_CMD_MODE_SELECT_10 0x55U #define SCSI_CMD_REPAIR_TRACK 0x58U #define SCSI_CMD_MODE_SENSE_10 0x5AU #define SCSI_CMD_CLOSE_TRACK_SESSION 0x5BU #define SCSI_CMD_READ_BUFFER_CAPACITY 0x5CU #define SCSI_CMD_SEND_CUE_SHEET 0x5DU /* Group 5 Commands (CDB's here are 12-bytes) */ #define SCSI_CMD_REPORT_LUNS 0xA0U #define SCSI_CMD_BLANK 0xA1U #define SCSI_CMD_SECURITY_PROTOCOL_IN 0xA2U #define SCSI_CMD_SEND_KEY 0xA3U #define SCSI_CMD_REPORT_KEY 0xA4U #define SCSI_CMD_PLAY_AUDIO_12 0xA5U #define SCSI_CMD_LOAD_UNLOAD 0xA6U #define SCSI_CMD_SET_READ_AHEAD 0xA7U #define SCSI_CMD_READ_12 0xA8U #define SCSI_CMD_PLAY_TRACK_REL_12 0xA9U #define SCSI_CMD_WRITE_12 0xAAU #define SCSI_CMD_READ_MEDIA_SERIAL_12 0xABU #define SCSI_CMD_GET_PERFORMANCE 0xACU #define SCSI_CMD_READ_DVD_STRUCTURE 0xADU #define SCSI_CMD_SECURITY_PROTOCOL_OUT 0xB5U #define SCSI_CMD_SET_STREAMING 0xB6U #define SCSI_CMD_READ_MSF 0xB9U #define SCSI_CMD_SET_SPEED 0xBBU #define SCSI_CMD_MECHANISM_STATUS 0xBDU #define SCSI_CMD_READ_CD 0xBEU #define SCSI_CMD_SEND_DISC_STRUCTURE 0xBFU /* Vendor-unique Commands, included for completeness */ #define SCSI_CMD_CD_PLAYBACK_STATUS 0xC4U /* SONY unique */ #define SCSI_CMD_PLAYBACK_CONTROL 0xC9U /* SONY unique */ #define SCSI_CMD_READ_CDDA 0xD8U /* Vendor unique */ #define SCSI_CMD_READ_CDXA 0xDBU /* Vendor unique */ #define SCSI_CMD_READ_ALL_SUBCODES 0xDFU /* Vendor unique */ /* SCSI error codes */ #define SCSI_S_NOT_READY 0x02U #define SCSI_S_MEDIUM_ERROR 0x03U #define SCSI_S_ILLEGAL_REQUEST 0x05U #define SCSI_S_UNIT_ATTENTION 0x06U #define SCSI_ASC_LBA_OUT_OF_RANGE 0x21U #define SCSI_ASC_MEDIA_CHANGED 0x28U #define SCSI_ASC_MEDIUM_NOT_PRESENT 0x3AU struct SCSI_Capacity { uint8_t data[8]; //uint32_t dwBlockAddress; //uint32_t dwBlockLength; } __attribute__((packed)); struct SCSI_CDB_BASE { uint8_t Opcode; unsigned unused : 5; unsigned LUN : 3; uint8_t info[12]; } __attribute__((packed)); typedef SCSI_CDB_BASE SCSI_CDB_BASE_t; struct SCSI_CDB6 { uint8_t Opcode; unsigned LBAMSB : 5; unsigned LUN : 3; uint8_t LBAHB; uint8_t LBALB; uint8_t AllocationLength; uint8_t Control; public: SCSI_CDB6(uint8_t _Opcode, uint8_t _LUN, uint32_t LBA, uint8_t _AllocationLength, uint8_t _Control) : Opcode(_Opcode), LBAMSB(UHS_UINT8_BYTE2(LBA) & 0x1F), LUN(_LUN), LBAHB(UHS_UINT8_BYTE1(LBA)), LBALB(UHS_UINT8_BYTE0(LBA)), AllocationLength(_AllocationLength), Control(_Control) { } SCSI_CDB6(uint8_t _Opcode, uint8_t _LUN, uint8_t _AllocationLength, uint8_t _Control) : Opcode(_Opcode), LBAMSB(0), LUN(_LUN), LBAHB(0), LBALB(0), AllocationLength(_AllocationLength), Control(_Control) { } } __attribute__((packed)); typedef SCSI_CDB6 SCSI_CDB6_t; struct SCSI_CDB10 { uint8_t Opcode; unsigned Service_Action : 5; unsigned LUN : 3; uint8_t LBA_L_M_MB; uint8_t LBA_L_M_LB; uint8_t LBA_L_L_MB; uint8_t LBA_L_L_LB; uint8_t Misc2; uint8_t ALC_MB; uint8_t ALC_LB; uint8_t Control; public: SCSI_CDB10(uint8_t _Opcode, uint8_t _LUN) : Opcode(_Opcode), Service_Action(0), LUN(_LUN), LBA_L_M_MB(0), LBA_L_M_LB(0), LBA_L_L_MB(0), LBA_L_L_LB(0), Misc2(0), ALC_MB(0), ALC_LB(0), Control(0) { } SCSI_CDB10(uint8_t _Opcode, uint8_t _LUN, uint16_t xflen, uint32_t _LBA) : Opcode(_Opcode), Service_Action(0), LUN(_LUN), LBA_L_M_MB(UHS_UINT8_BYTE3(_LBA)), LBA_L_M_LB(UHS_UINT8_BYTE2(_LBA)), LBA_L_L_MB(UHS_UINT8_BYTE1(_LBA)), LBA_L_L_LB(UHS_UINT8_BYTE0(_LBA)), Misc2(0), ALC_MB(UHS_UINT8_BYTE1(xflen)), ALC_LB(UHS_UINT8_BYTE0(xflen)), Control(0) { } } __attribute__((packed)); typedef SCSI_CDB10 SCSI_CDB10_t; struct SCSI_CDB12 { uint8_t Opcode; unsigned Service_Action : 5; unsigned Misc : 3; uint8_t LBA_L_M_LB; uint8_t LBA_L_L_MB; uint8_t LBA_L_L_LB; uint8_t ALC_M_LB; uint8_t ALC_L_MB; uint8_t ALC_L_LB; uint8_t Control; } __attribute__((packed)); typedef SCSI_CDB12 SCSI_CDB12_t; struct SCSI_CDB_LBA32_16 { uint8_t Opcode; unsigned Service_Action : 5; unsigned Misc : 3; uint8_t LBA_L_M_MB; uint8_t LBA_L_M_LB; uint8_t LBA_L_L_MB; uint8_t LBA_L_L_LB; uint8_t A_M_M_MB; uint8_t A_M_M_LB; uint8_t A_M_L_MB; uint8_t A_M_L_LB; uint8_t ALC_M_MB; uint8_t ALC_M_LB; uint8_t ALC_L_MB; uint8_t ALC_L_LB; uint8_t Misc2; uint8_t Control; } __attribute__((packed)); struct SCSI_CDB_LBA64_16 { uint8_t Opcode; uint8_t Misc; uint8_t LBA_M_M_MB; uint8_t LBA_M_M_LB; uint8_t LBA_M_L_MB; uint8_t LBA_M_L_LB; uint8_t LBA_L_M_MB; uint8_t LBA_L_M_LB; uint8_t LBA_L_L_MB; uint8_t LBA_L_L_LB; uint8_t ALC_M_MB; uint8_t ALC_M_LB; uint8_t ALC_L_MB; uint8_t ALC_L_LB; uint8_t Misc2; uint8_t Control; } __attribute__((packed)); struct SCSI_Inquiry_Response { uint8_t DeviceType : 5; uint8_t PeripheralQualifier : 3; unsigned Reserved : 7; unsigned Removable : 1; uint8_t Version; unsigned ResponseDataFormat : 4; unsigned HISUP : 1; unsigned NormACA : 1; unsigned TrmTsk : 1; unsigned AERC : 1; uint8_t AdditionalLength; unsigned PROTECT : 1; unsigned Res : 2; unsigned ThreePC : 1; unsigned TPGS : 2; unsigned ACC : 1; unsigned SCCS : 1; unsigned ADDR16 : 1; unsigned R1 : 1; unsigned R2 : 1; unsigned MCHNGR : 1; unsigned MULTIP : 1; unsigned VS : 1; unsigned ENCSERV : 1; unsigned BQUE : 1; unsigned SoftReset : 1; unsigned CmdQue : 1; unsigned Reserved4 : 1; unsigned Linked : 1; unsigned Sync : 1; unsigned WideBus16Bit : 1; unsigned WideBus32Bit : 1; unsigned RelAddr : 1; uint8_t VendorID[8]; uint8_t ProductID[16]; uint8_t RevisionID[4]; } __attribute__((packed)); struct SCSI_Request_Sense_Response { uint8_t bResponseCode; uint8_t bSegmentNumber; uint8_t bmSenseKey : 4; uint8_t bmReserved : 1; uint8_t bmILI : 1; uint8_t bmEOM : 1; uint8_t bmFileMark : 1; uint8_t Information[4]; uint8_t bAdditionalLength; uint8_t CmdSpecificInformation[4]; uint8_t bAdditionalSenseCode; uint8_t bAdditionalSenseQualifier; uint8_t bFieldReplaceableUnitCode; uint8_t SenseKeySpecific[3]; } __attribute__((packed)); #endif /* UHS_SCSI_H */
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_BULK_STORAGE/UHS_SCSI.h
C++
agpl-3.0
10,160
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #ifndef _UHS_UNOFFICIAL_IDs_h #define _UHS_UNOFFICIAL_IDs_h // Bogus unofficial and unregistered VIDs from cloners to be listed here. #define UHS_VID_UNOFFICIAL_JOYTECH 0x162EU // For unofficial Joytech controllers #endif
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_UNOFFICIAL_IDs.h
C
agpl-3.0
1,166
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if !defined(_UHS_host_h_) || defined(USBCORE_H) #error "Never include UHS_UsbCore.h directly; include UHS_Host.h instead" #else #define USBCORE_H #ifndef UHS_HOST_MAX_INTERFACE_DRIVERS #define UHS_HOST_MAX_INTERFACE_DRIVERS 0x10U // Default maximum number of USB interface drivers #endif #ifndef SYSTEM_OR_SPECIAL_YIELD #define SYSTEM_OR_SPECIAL_YIELD(...) VOID0 #endif #ifndef SYSTEM_OR_SPECIAL_YIELD_FROM_ISR #define SYSTEM_OR_SPECIAL_YIELD_FROM_ISR(...) SYSTEM_OR_SPECIAL_YIELD #endif // As we make extensions to a target interface add to UHS_HOST_MAX_INTERFACE_DRIVERS // This offset gets calculated for supporting wide subclasses, such as HID, BT, etc. #define UHS_HID_INDEX (UHS_HOST_MAX_INTERFACE_DRIVERS + 1) /* Common setup data constant combinations */ //get descriptor request type #define UHS_bmREQ_GET_DESCR (USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE) //set request type for all but 'set feature' and 'set interface' #define UHS_bmREQ_SET (USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE) //get interface request type #define UHS_bmREQ_CL_GET_INTF (USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE) // D7 data transfer direction (0 - host-to-device, 1 - device-to-host) // D6-5 Type (0- standard, 1 - class, 2 - vendor, 3 - reserved) // D4-0 Recipient (0 - device, 1 - interface, 2 - endpoint, 3 - other, 4..31 - reserved) // TO-DO: Use the python script to generate these. // TO-DO: Add _all_ subclasses here. // USB Device Classes, Subclasses and Protocols //////////////////////////////////////////////////////////////////////////////// // Use Class Info in the Interface Descriptors #define UHS_USB_CLASS_USE_CLASS_INFO 0x00U //////////////////////////////////////////////////////////////////////////////// // Audio #define UHS_USB_CLASS_AUDIO 0x01U // Subclasses #define UHS_USB_SUBCLASS_AUDIOCONTROL 0x01U #define UHS_USB_SUBCLASS_AUDIOSTREAMING 0x02U #define UHS_USB_SUBCLASS_MIDISTREAMING 0x03U //////////////////////////////////////////////////////////////////////////////// // Communications and CDC Control #define UHS_USB_CLASS_COM_AND_CDC_CTRL 0x02U //////////////////////////////////////////////////////////////////////////////// // HID #define UHS_USB_CLASS_HID 0x03U // Subclasses #define UHS_HID_BOOT_SUBCLASS 0x01U // Protocols #define UHS_HID_PROTOCOL_HIDBOOT_KEYBOARD 0x01U #define UHS_HID_PROTOCOL_HIDBOOT_MOUSE 0x02U //////////////////////////////////////////////////////////////////////////////// // Physical #define UHS_USB_CLASS_PHYSICAL 0x05U //////////////////////////////////////////////////////////////////////////////// // Image #define UHS_USB_CLASS_IMAGE 0x06U //////////////////////////////////////////////////////////////////////////////// // Printer #define UHS_USB_CLASS_PRINTER 0x07U //////////////////////////////////////////////////////////////////////////////// // Mass Storage #define UHS_USB_CLASS_MASS_STORAGE 0x08 // Subclasses #define UHS_BULK_SUBCLASS_SCSI_NOT_REPORTED 0x00U // De facto use #define UHS_BULK_SUBCLASS_RBC 0x01U #define UHS_BULK_SUBCLASS_ATAPI 0x02U // MMC-5 (ATAPI) #define UHS_BULK_SUBCLASS_OBSOLETE1 0x03U // Was QIC-157 #define UHS_BULK_SUBCLASS_UFI 0x04U // Specifies how to interface Floppy Disk Drives to USB #define UHS_BULK_SUBCLASS_OBSOLETE2 0x05U // Was SFF-8070i #define UHS_BULK_SUBCLASS_SCSI 0x06U // SCSI Transparent Command Set #define UHS_BULK_SUBCLASS_LSDFS 0x07U // Specifies how host has to negotiate access before trying SCSI #define UHS_BULK_SUBCLASS_IEEE1667 0x08U // Protocols #define UHS_STOR_PROTO_CBI 0x00U // CBI (with command completion interrupt) #define UHS_STOR_PROTO_CBI_NO_INT 0x01U // CBI (without command completion interrupt) #define UHS_STOR_PROTO_OBSOLETE 0x02U #define UHS_STOR_PROTO_BBB 0x50U // Bulk Only Transport #define UHS_STOR_PROTO_UAS 0x62U //////////////////////////////////////////////////////////////////////////////// // Hub #define UHS_USB_CLASS_HUB 0x09U //////////////////////////////////////////////////////////////////////////////// // CDC-Data #define UHS_USB_CLASS_CDC_DATA 0x0AU //////////////////////////////////////////////////////////////////////////////// // Smart-Card #define UHS_USB_CLASS_SMART_CARD 0x0BU //////////////////////////////////////////////////////////////////////////////// // Content Security #define UHS_USB_CLASS_CONTENT_SECURITY 0x0DU //////////////////////////////////////////////////////////////////////////////// // Video #define UHS_USB_CLASS_VIDEO 0x0EU //////////////////////////////////////////////////////////////////////////////// // Personal Healthcare #define UHS_USB_CLASS_PERSONAL_HEALTH 0x0FU //////////////////////////////////////////////////////////////////////////////// // Diagnostic Device #define UHS_USB_CLASS_DIAGNOSTIC_DEVICE 0xDCU //////////////////////////////////////////////////////////////////////////////// // Wireless Controller #define UHS_USB_CLASS_WIRELESS_CTRL 0xE0U //////////////////////////////////////////////////////////////////////////////// // Miscellaneous #define UHS_USB_CLASS_MISC 0xEFU //////////////////////////////////////////////////////////////////////////////// // Application Specific #define UHS_USB_CLASS_APP_SPECIFIC 0xFEU //////////////////////////////////////////////////////////////////////////////// // Vendor Specific #define UHS_USB_CLASS_VENDOR_SPECIFIC 0xFFU //////////////////////////////////////////////////////////////////////////////// /* USB state machine states */ #define UHS_USB_HOST_STATE_MASK 0xF0U // Configure states, MSN == 0 --------------------------V #define UHS_USB_HOST_STATE_DETACHED 0x00U #define UHS_USB_HOST_STATE_DEBOUNCE 0x01U #define UHS_USB_HOST_STATE_DEBOUNCE_NOT_COMPLETE 0x02U #define UHS_USB_HOST_STATE_RESET_NOT_COMPLETE 0x03U #define UHS_USB_HOST_STATE_WAIT_SOF 0x04U #define UHS_USB_HOST_STATE_WAIT_BUS_READY 0x05U #define UHS_USB_HOST_STATE_RESET_DEVICE 0x0AU #define UHS_USB_HOST_STATE_CONFIGURING 0x0CU // Looks like "CO"nfig (backwards) #define UHS_USB_HOST_STATE_CONFIGURING_DONE 0x0DU // Looks like "DO"one (backwards) #define UHS_USB_HOST_STATE_CHECK 0x0EU #define UHS_USB_HOST_STATE_ILLEGAL 0x0FU // Foo // Run states, MSN != 0 --------------------------------V #define UHS_USB_HOST_STATE_RUNNING 0x60U // Looks like "GO" #define UHS_USB_HOST_STATE_IDLE 0x1DU // Looks like "ID"le #define UHS_USB_HOST_STATE_ERROR 0xF0U // Looks like "FO"o #define UHS_USB_HOST_STATE_INITIALIZE 0x10U // Looks like "I"nit // Host SE result codes. // Common SE results are stored in the low nybble, all interface drivers understand these plus 0x1F. // Extended SE results are 0x10-0x1E. SE code only understands these internal to the hardware. // Values > 0x1F are driver or other internal error conditions. // Return these result codes from your host controller driver to match the error condition // ALL Non-zero values are errors. // Values not listed in this table are not handled in the base class, or any host driver. #define UHS_HOST_ERROR_NONE 0x00U // No error #define UHS_HOST_ERROR_BUSY 0x01U // transfer pending #define UHS_HOST_ERROR_BADREQ 0x02U // Transfer Launch Request was bad #define UHS_HOST_ERROR_DMA 0x03U // DMA was too short, or too long #define UHS_HOST_ERROR_NAK 0x04U // Peripheral returned NAK #define UHS_HOST_ERROR_STALL 0x05U // Peripheral returned STALL #define UHS_HOST_ERROR_TOGERR 0x06U // Toggle error/ISO over-underrun #define UHS_HOST_ERROR_WRONGPID 0x07U // Received wrong Packet ID #define UHS_HOST_ERROR_BADBC 0x08U // Byte count is bad #define UHS_HOST_ERROR_PIDERR 0x09U // Received Packet ID is corrupted #define UHS_HOST_ERROR_BADRQ 0x0AU // Packet error. Increase max packet. #define UHS_HOST_ERROR_CRC 0x0BU // USB CRC was incorrect #define UHS_HOST_ERROR_KERR 0x0CU // K-state instead of response, usually indicates wrong speed #define UHS_HOST_ERROR_JERR 0x0DU // J-state instead of response, usually indicates wrong speed #define UHS_HOST_ERROR_TIMEOUT 0x0EU // Device did not respond in time #define UHS_HOST_ERROR_BABBLE 0x0FU // Line noise/unexpected data #define UHS_HOST_ERROR_MEM_LAT 0x10U // Error caused by memory latency. #define UHS_HOST_ERROR_NYET 0x11U // OUT transfer accepted with NYET // Addressing error codes #define ADDR_ERROR_INVALID_INDEX 0xA0U #define ADDR_ERROR_INVALID_ADDRESS 0xA1U // Common Interface Driver error codes #define UHS_HOST_ERROR_DEVICE_NOT_SUPPORTED 0xD1U // Driver doesn't support the device or interfaces #define UHS_HOST_ERROR_DEVICE_INIT_INCOMPLETE 0xD2U // Init partially finished, but died. #define UHS_HOST_ERROR_CANT_REGISTER_DEVICE_CLASS 0xD3U // There was no driver for the interface requested. #define UHS_HOST_ERROR_ADDRESS_POOL_FULL 0xD4U // No addresses left in the address pool. #define UHS_HOST_ERROR_HUB_ADDRESS_OVERFLOW 0xD5U // No hub addresses left. The maximum is 7. #define UHS_HOST_ERROR_NO_ADDRESS_IN_POOL 0xD6U // Address was not allocated in the pool, thus not found. #define UHS_HOST_ERROR_NULL_EPINFO 0xD7U // The supplied endpoint was NULL, indicates a bug or other problem. #define UHS_HOST_ERROR_BAD_ARGUMENT 0xD8U // Indicates a range violation bug. #define UHS_HOST_ERROR_DEVICE_DRIVER_BUSY 0xD9U // The interface driver is busy or out buffer is full, try again later. #define UHS_HOST_ERROR_BAD_MAX_PACKET_SIZE 0xDAU // The maximum packet size was exceeded. Try again with smaller size. #define UHS_HOST_ERROR_NO_ENDPOINT_IN_TABLE 0xDBU // The endpoint could not be found in the endpoint table. #define UHS_HOST_ERROR_UNPLUGGED 0xDEU // Someone removed the USB device, or Vbus was turned off. #define UHS_HOST_ERROR_NOMEM 0xDFU // Out Of Memory. // Control request stream errors #define UHS_HOST_ERROR_FailGetDevDescr 0xE1U #define UHS_HOST_ERROR_FailSetDevTblEntry 0xE2U #define UHS_HOST_ERROR_FailGetConfDescr 0xE3U #define UHS_HOST_ERROR_END_OF_STREAM 0xEFU // Host base class specific Error codes #define UHS_HOST_ERROR_NOT_IMPLEMENTED 0xFEU #define UHS_HOST_ERROR_TRANSFER_TIMEOUT 0xFFU // SEI interaction defaults #define UHS_HOST_TRANSFER_MAX_MS 10000 // USB transfer timeout in ms, per section 9.2.6.1 of USB 2.0 spec #define UHS_HOST_TRANSFER_RETRY_MAXIMUM 3 // 3 retry limit for a transfer #define UHS_HOST_DEBOUNCE_DELAY_MS 500 // settle delay in milliseconds #define UHS_HUB_RESET_DELAY_MS 20 // hub port reset delay, 10ms recommended, but can be up to 20ms // // We only provide the minimum needed information for enumeration. // Interface drivers should be able to set up what is needed with nothing more. // A driver needs to know the following information: // 1: address on the USB network, parent and port (aka UsbDeviceAddress) // 2: endpoints // 3: vid:pid, class, subclass, protocol // struct ENDPOINT_INFO { uint8_t bEndpointAddress; // Endpoint address. Bit 7 indicates direction (0=OUT, 1=IN). uint8_t bmAttributes; // Endpoint transfer type. uint16_t wMaxPacketSize; // Maximum packet size. uint8_t bInterval; // Polling interval in frames. } __attribute__((packed)); struct INTERFACE_INFO { uint8_t bInterfaceNumber; uint8_t bAlternateSetting; uint8_t numep; uint8_t klass; uint8_t subklass; uint8_t protocol; ENDPOINT_INFO epInfo[16]; } __attribute__((packed)); struct ENUMERATION_INFO { uint16_t vid; uint16_t pid; uint16_t bcdDevice; uint8_t klass; uint8_t subklass; uint8_t protocol; uint8_t bMaxPacketSize0; uint8_t currentconfig; uint8_t parent; uint8_t port; uint8_t address; INTERFACE_INFO interface; } __attribute__((packed)); /* USB Setup Packet Structure */ typedef struct { // offset description // 0 Bit-map of request type union { uint8_t bmRequestType; struct { uint8_t recipient : 5; // Recipient of the request uint8_t type : 2; // Type of request uint8_t direction : 1; // Direction of data transfer } __attribute__((packed)); } ReqType_u; // 1 Request uint8_t bRequest; // 2 Depends on bRequest union { uint16_t wValue; struct { uint8_t wValueLo; uint8_t wValueHi; } __attribute__((packed)); } wVal_u; // 4 Depends on bRequest uint16_t wIndex; // 6 Depends on bRequest uint16_t wLength; // 8 bytes total } __attribute__((packed)) SETUP_PKT, *PSETUP_PKT; // little endian :-) 8 8 8 8 16 16 #define mkSETUP_PKT8(bmReqType, bRequest, wValLo, wValHi, wInd, total) ((uint64_t)(((uint64_t)(bmReqType)))|(((uint64_t)(bRequest))<<8)|(((uint64_t)(wValLo))<<16)|(((uint64_t)(wValHi))<<24)|(((uint64_t)(wInd))<<32)|(((uint64_t)(total)<<48))) #define mkSETUP_PKT16(bmReqType, bRequest, wVal, wInd, total) ((uint64_t)(((uint64_t)(bmReqType)))|(((uint64_t)(bRequest))<<8)|(((uint64_t)(wVal ))<<16) |(((uint64_t)(wInd))<<32)|(((uint64_t)(total)<<48))) // Big endian -- but we aren't able to use this :-/ //#define mkSETUP_PKT8(bmReqType, bRequest, wValLo, wValHi, wInd, total) ((uint64_t)(((uint64_t)(bmReqType))<<56)|(((uint64_t)(bRequest))<<48)|(((uint64_t)(wValLo))<<40)|(((uint64_t)(wValHi))<<32)|(((uint64_t)(wInd))<<16)|((uint64_t)(total))) //#define mkSETUP_PKT16(bmReqType, bRequest, wVal, wInd, total) ((uint64_t)(((uint64_t)(bmReqType))<<56)|(((uint64_t)(bRequest))<<48) |(((uint64_t)(wVal))<<32) |(((uint64_t)(wInd))<<16)|((uint64_t)(total))) #endif /* USBCORE_H */
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_UsbCore.h
C
agpl-3.0
16,995
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if !defined(_UHS_host_h_) || defined(__ADDRESS_H__) #error "Never include UHS_address.h directly; include UHS_Usb.h instead" #else #define __ADDRESS_H__ /* NAK powers. To save space in endpoint data structure, amount of retries before giving up and returning 0x4 is stored in */ /* bmNakPower as a power of 2. The actual nak_limit is then calculated as nak_limit = ( 2^bmNakPower - 1) */ #define UHS_USB_NAK_MAX_POWER 14 // NAK binary order maximum value #define UHS_USB_NAK_DEFAULT 13 // default 16K-1 NAKs before giving up #define UHS_USB_NAK_NOWAIT 1 // Single NAK stops transfer #define UHS_USB_NAK_NONAK 0 // Do not count NAKs, stop retrying after USB Timeout. Try not to use this. #define bmUSB_DEV_ADDR_PORT 0x07 #define bmUSB_DEV_ADDR_PARENT 0x78 #define bmUSB_DEV_ADDR_HUB 0x40 // TODO: embed parent? struct UHS_EpInfo { uint8_t epAddr; // Endpoint address uint8_t bIface; uint16_t maxPktSize; // Maximum packet size union { uint8_t epAttribs; struct { uint8_t bmSndToggle : 1; // Send toggle, when zero bmSNDTOG0, bmSNDTOG1 otherwise uint8_t bmRcvToggle : 1; // Send toggle, when zero bmRCVTOG0, bmRCVTOG1 otherwise uint8_t bmNeedPing : 1; // 1 == ping protocol needed for next out packet uint8_t bmNakPower : 5; // Binary order for NAK_LIMIT value } __attribute__((packed)); }; } __attribute__((packed)); // TODO: embed parent address and port into epinfo struct, // and nuke this address stupidity. // This is a compact scheme. Should also support full spec. // This produces a 7 hub limit, 49 devices + 7 hubs, 56 total. // // 7 6 5 4 3 2 1 0 // --------------------------------- // | | H | P | P | P | A | A | A | // --------------------------------- // // H - if 1 the address is a hub address // P - parent hub number // A - port number of parent // struct UHS_DeviceAddress { union { struct { uint8_t bmAddress : 3; // port number uint8_t bmParent : 3; // parent hub address uint8_t bmHub : 1; // hub flag uint8_t bmReserved : 1; // reserved, must be zero } __attribute__((packed)); uint8_t devAddress; }; } __attribute__((packed)); struct UHS_Device { volatile UHS_EpInfo *epinfo[UHS_HOST_MAX_INTERFACE_DRIVERS]; // endpoint info pointer UHS_DeviceAddress address; uint8_t epcount; // number of endpoints uint8_t speed; // indicates device speed } __attribute__((packed)); typedef void (*UsbDeviceHandleFunc)(UHS_Device *pdev); class AddressPool { UHS_EpInfo dev0ep; //Endpoint data structure used during enumeration for uninitialized device // In order to avoid hub address duplication, this should use bits uint8_t hubCounter; // hub counter UHS_Device thePool[UHS_HOST_MAX_INTERFACE_DRIVERS]; // Initializes address pool entry void UHS_NI InitEntry(uint8_t index) { thePool[index].address.devAddress = 0; thePool[index].epcount = 1; thePool[index].speed = 0; for(uint8_t i = 0; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) { thePool[index].epinfo[i] = &dev0ep; } }; // Returns thePool index for a given address uint8_t UHS_NI FindAddressIndex(uint8_t address = 0) { for(uint8_t i = 1; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) { if(thePool[i].address.devAddress == address) return i; } return 0; }; // Returns thePool child index for a given parent uint8_t UHS_NI FindChildIndex(UHS_DeviceAddress addr, uint8_t start = 1) { for(uint8_t i = (start < 1 || start >= UHS_HOST_MAX_INTERFACE_DRIVERS) ? 1 : start; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) { if(thePool[i].address.bmParent == addr.bmAddress) return i; } return 0; }; // Frees address entry specified by index parameter void UHS_NI FreeAddressByIndex(uint8_t index) { // Zero field is reserved and should not be affected if(index == 0) return; UHS_DeviceAddress uda = thePool[index].address; // If a hub was switched off all port addresses should be freed if(uda.bmHub == 1) { for(uint8_t i = 1; (i = FindChildIndex(uda, i));) FreeAddressByIndex(i); // FIXME: use BIT MASKS // If the hub had the last allocated address, hubCounter should be decremented if(hubCounter == uda.bmAddress) hubCounter--; } InitEntry(index); } void InitAllAddresses() { for(uint8_t i = 1; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) InitEntry(i); hubCounter = 0; }; public: AddressPool() { hubCounter = 0; // Zero address is reserved InitEntry(0); thePool[0].epinfo[0] = &dev0ep; dev0ep.epAddr = 0; #if UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE dev0ep.maxPktSize = 0x40; //starting at 0x40 and work down #else dev0ep.maxPktSize = 0x08; #endif dev0ep.epAttribs = 0; //set DATA0/1 toggles to 0 dev0ep.bmNakPower = UHS_USB_NAK_MAX_POWER; InitAllAddresses(); }; // Returns a pointer to a specified address entry UHS_Device* UHS_NI GetUsbDevicePtr(uint8_t addr) { if(!addr) return thePool; uint8_t index = FindAddressIndex(addr); return (!index) ? NULL : &thePool[index]; }; // Allocates new address uint8_t UHS_NI AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 1) { /* if (parent != 0 && port == 0) USB_HOST_SERIAL.println("PRT:0"); */ UHS_DeviceAddress _parent; _parent.devAddress = parent; if(_parent.bmReserved || port > 7) //if(parent > 127 || port > 7) return 0; // FIXME: use BIT MASKS if(is_hub && hubCounter == 7) return 0; // finds first empty address entry starting from one uint8_t index = FindAddressIndex(0); if(!index) // if empty entry is not found return 0; UHS_DeviceAddress addr; addr.devAddress = port; addr.bmParent = _parent.bmAddress; // FIXME: use BIT MASKS if(is_hub) { hubCounter++; addr.bmHub = 1; addr.bmAddress = hubCounter; } thePool[index].address = addr; #if DEBUG_PRINTF_EXTRA_HUGE #ifdef UHS_DEBUG_USB_ADDRESS printf("Address: %x (%x.%x.%x)\r\n", addr.devAddress, addr.bmHub, addr.bmParent, addr.bmAddress); #endif #endif return thePool[index].address.devAddress; }; void UHS_NI FreeAddress(uint8_t addr) { // if the root hub is disconnected all the addresses should be initialized if(addr == 0x41) { InitAllAddresses(); return; } uint8_t index = FindAddressIndex(addr); FreeAddressByIndex(index); }; }; #endif // __ADDRESS_H__
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_address.h
C++
agpl-3.0
9,144
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if !defined(_usb_h_) || defined(__HEXDUMP_H__) #error "Never include UHS_hexdump.h directly; include UHS_Usb.h instead" #else #define __HEXDUMP_H__ extern int UsbDEBUGlvl; template <class BASE_CLASS, class LEN_TYPE, class OFFSET_TYPE> class HexDumper : public BASE_CLASS { uint8_t byteCount; OFFSET_TYPE byteTotal; public: HexDumper() : byteCount(0), byteTotal(0) { }; void Initialize() { byteCount = 0; byteTotal = 0; }; virtual void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset); }; template <class BASE_CLASS, class LEN_TYPE, class OFFSET_TYPE> void HexDumper<BASE_CLASS, LEN_TYPE, OFFSET_TYPE>::Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) { if(UsbDEBUGlvl >= 0x80) { // Fully bypass this block of code if we do not debug. for(LEN_TYPE j = 0; j < len; j++, byteCount++, byteTotal++) { if(!byteCount) { PrintHex<OFFSET_TYPE > (byteTotal, 0x80); E_Notify(PSTR(": "), 0x80); } PrintHex<uint8_t > (pbuf[j], 0x80); E_Notify(PSTR(" "), 0x80); if(byteCount == 15) { E_Notify(PSTR("\r\n"), 0x80); byteCount = 0xFF; } } } } #endif // __HEXDUMP_H__
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_hexdump.h
C++
agpl-3.0
2,458
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ /* USB functions */ #ifndef _UHS_host_h_ #define _UHS_host_h_ // WARNING: Do not change the order of includes, or stuff will break! #include <inttypes.h> #include <stddef.h> #include <stdio.h> #include <stdint.h> #if DISABLED(USE_UHS3_USB) #include <ISR_safe_memory.h> #include <Wire.h> #include <SPI.h> #include <UHS_ByteBuffer.h> #endif #include "UHS_macros.h" // None of these should ever be directly included by a driver, or a user's sketch. #include "../dyn_SWI/dyn_SWI.h" #include "UHS_USB_IDs.h" #include "UHS_settings.h" #include "UHS_usb_ch9.h" #include "UHS_UsbCore.h" #include "UHS_address.h" #include "UHS_usbhost.h" #include "UHS_printhex.h" #include "UHS_message.h" // Load system components as required #if defined(LOAD_USB_HOST_SYSTEM) && !defined(USB_HOST_SYSTEM_LOADED) #include "UHS_util_INLINE.h" #include "UHS_host_INLINE.h" #include "UHS_printf_HELPER.h" #ifdef LOAD_USB_HOST_SHIELD #include "USB_HOST_SHIELD/USB_HOST_SHIELD.h" #endif #if defined(LOAD_UHS_KINETIS_FS_HOST) && !defined(UHS_KINETIS_FS_HOST_LOADED) #include "UHS_KINETIS_FS_HOST/UHS_KINETIS_FS_HOST.h" #endif #if defined(LOAD_UHS_KINETIS_EHCI) && !defined(UHS_KINETIS_EHCI_LOADED) #include "UHS_KINETIS_EHCI/UHS_KINETIS_EHCI.h" #endif // Load USB drivers and multiplexers #ifdef LOAD_UHS_HUB #include "UHS_HUB/UHS_HUB.h" #endif // HUB loaded #ifdef LOAD_UHS_BULK_STORAGE #include "UHS_BULK_STORAGE/UHS_BULK_STORAGE.h" #endif #ifdef LOAD_GENERIC_STORAGE #include "../UHS_FS/UHS_FS.h" #endif // Add BT and optionally HID if directed to do so #ifdef LOAD_UHS_BT #include "UHS_BT/UHS_BT.h" #endif // BT and optionally HID loaded // Add HID #ifdef LOAD_UHS_HID #include "UHS_HID/UHS_HID.h" #endif // HID loaded // Add CDC multiplexers (currently only ACM) #if defined(LOAD_UHS_CDC_ACM) || defined(LOAD_UHS_CDC_ACM_FTDI) || defined(LOAD_UHS_CDC_ACM_PROLIFIC) || defined(LOAD_UHS_CDC_ACM_XR21B1411) #include "UHS_CDC/UHS_CDC.h" #endif // CDC loaded #ifdef LOAD_UHS_ADK #include "UHS_ADK/UHS_ADK.h" #endif #ifdef LOAD_UHS_MIDI #include "UHS_MIDI/UHS_MIDI.h" #endif #endif // System code loaded #endif // _UHS_host_h_
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_host.h
C
agpl-3.0
3,052
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if defined(LOAD_USB_HOST_SYSTEM) && !defined(USB_HOST_SYSTEM_LOADED) #define USB_HOST_SYSTEM_LOADED #ifndef DEBUG_PRINTF_EXTRA_HUGE_UHS_HOST #define DEBUG_PRINTF_EXTRA_HUGE_UHS_HOST 0 #endif #if DEBUG_PRINTF_EXTRA_HUGE #if DEBUG_PRINTF_EXTRA_HUGE_UHS_HOST #define HOST_DEBUG(...) printf(__VA_ARGS__) #else #define HOST_DEBUG(...) VOID0 #endif #else #define HOST_DEBUG(...) VOID0 #endif UHS_EpInfo* UHS_USB_HOST_BASE::getEpInfoEntry(uint8_t addr, uint8_t ep) { UHS_Device *p = addrPool.GetUsbDevicePtr(addr); if(!p || !p->epinfo) return NULL; UHS_EpInfo *pep; for(uint8_t j = 0; j < UHS_HOST_MAX_INTERFACE_DRIVERS; j++) { pep = (UHS_EpInfo *)(p->epinfo[j]); for(uint8_t i = 0; i < p->epcount; i++) { if((pep)->epAddr == ep) { HOST_DEBUG("ep entry for interface %d ep %d max packet size = %d\r\n", pep->bIface, ep, pep->maxPktSize); return pep; } pep++; } } return NULL; } /** * Sets a device table entry for a device. * Each device is different and has different number of endpoints. * This function plugs endpoint record structure, defined in application, to devtable * * @param addr device address * @param epcount how many endpoints * @param eprecord pointer to the endpoint structure * @return Zero for success, or error code */ uint8_t UHS_USB_HOST_BASE::setEpInfoEntry(uint8_t addr, uint8_t iface, uint8_t epcount, volatile UHS_EpInfo* eprecord) { if(!eprecord) return UHS_HOST_ERROR_BAD_ARGUMENT; UHS_Device *p = addrPool.GetUsbDevicePtr(addr); if(!p) return UHS_HOST_ERROR_NO_ADDRESS_IN_POOL; p->address.devAddress = addr; p->epinfo[iface] = eprecord; p->epcount = epcount; return 0; } /** * sets all endpoint addresses to zero. * Sets all max packet sizes to defaults * Clears all endpoint attributes * Sets bmNakPower to USB_NAK_DEFAULT * Sets binterface to zero. * Sets bNumEP to zero. * Sets bAddress to zero. * Clears qNextPollTime and sets bPollEnable to false. * * @param maxep How many endpoints to initialize * @param device pointer to the device driver instance (this) */ void UHS_USB_HOST_BASE::DeviceDefaults(uint8_t maxep, UHS_USBInterface *interface) { for(uint8_t i = 0; i < maxep; i++) { interface->epInfo[i].epAddr = 0; interface->epInfo[i].maxPktSize = (i) ? 0 : 8; interface->epInfo[i].epAttribs = 0; interface->epInfo[i].bmNakPower = UHS_USB_NAK_DEFAULT; } interface->pUsb->GetAddressPool()->FreeAddress(interface->bAddress); interface->bIface = 0; interface->bNumEP = 1; interface->bAddress = 0; interface->qNextPollTime = 0; interface->bPollEnable = false; } /** * Perform a bus reset to the port of the connected device * * @param parent index to Parent * @param port what port on the parent * @param address address of the device * @return Zero for success, or error code */ uint8_t UHS_USB_HOST_BASE::doSoftReset(uint8_t parent, uint8_t port, uint8_t address) { uint8_t rcode = 0; if(parent == 0) { // Send a bus reset on the root interface. doHostReset(); } else { // reset parent port devConfig[parent]->ResetHubPort(port); } // // Many devices require a delay before setting the address here... // We loop upon fails for up to 2 seconds instead. // Most devices will be happy without a retry. // uint8_t retries = 0; if(address) { do { rcode = setAddr(0, address); if(!rcode) break; retries++; sof_delay(10); } while(retries < 200); HOST_DEBUG("%i retries.\r\n", retries); } else { #if DEBUG_PRINTF_EXTRA_HUGE printf("\r\ndoSoftReset called with address == 0.\r\n"); #endif } return rcode; } /* * Pseudo code so you may understand the code flow. * * reset; (happens at the lower level) * GetDevDescr(); * reset; * If there are no configuration descriptors { * // * // Note: I know of no device that does this. * // I suppose there could be one though. * // * try to enumerate. * } else { * last success count = 0 * best config = 0 * for each configuration descriptor { * for each interface descriptor { * get the endpoint descriptors for this interface. * Check to see if a driver can handle this interface. * If it can, add 1 to the success count. * } * if success count > last success count { * best config = current config * last success count = success count * } * } * set the device config to the best config * for each best config interface descriptor { * initialize driver that can handle this interface config * } * } * * NOTES: * 1: We do not need to save toggle states anymore and have not * needed to for some time, because the lower level driver * actually corrects wrong toggles on-the-fly for us. * * 2: We always do a second reset, since this stupid bug is * actually part of the specification documents that I * have found all over the net. Even Linux does it, and * many devices actually EXPECT this behavior. Some devices * will not enumerate without it. For devices that do not * need it, the additional reset is harmless. Here is an * example of one of these documents, see page Five: * https://www.ftdichip.com/Support/Documents/TechnicalNotes/TN_113_Simplified%20Description%20of%20USB%20Device%20Enumeration.pdf * */ /** * Enumerates interfaces on devices * * @param parent index to Parent * @param port what port on the parent * @param speed the speed of the device * @return Zero for success, or error code */ uint8_t UHS_USB_HOST_BASE::Configuring(uint8_t parent, uint8_t port, uint8_t speed) { //uint8_t bAddress = 0; HOST_DEBUG("\r\n\r\n\r\nConfiguring: parent = %i, port = %i, speed = %i\r\n", parent, port, speed); uint8_t rcode = 0; uint8_t retries = 0; uint8_t numinf = 0; uint8_t configs; UHS_Device *p = NULL; //EpInfo epInfo; // cap at 16, this should be fairly reasonable. ENUMERATION_INFO ei; uint8_t bestconf = 0; uint8_t bestsuccess = 0; uint8_t devConfigIndex; #if UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE const uint8_t biggest = 0x40; // wrap in {} to throw away the 64 byte buffer when we are done with it { uint8_t buf[biggest]; USB_FD_DEVICE_DESCRIPTOR *udd = reinterpret_cast<USB_FD_DEVICE_DESCRIPTOR *>(buf); #else const uint8_t biggest = 18; uint8_t buf[biggest]; USB_FD_DEVICE_DESCRIPTOR *udd = reinterpret_cast<USB_FD_DEVICE_DESCRIPTOR *>(buf); USB_FD_CONFIGURATION_DESCRIPTOR *ucd = reinterpret_cast<USB_FD_CONFIGURATION_DESCRIPTOR *>(buf); #endif //for(devConfigIndex = 0; devConfigIndex < UHS_HOST_MAX_INTERFACE_DRIVERS; devConfigIndex++) { // if((devConfig[devConfigIndex]->bAddress) && (!devConfig[devConfigIndex]->bPollEnable)) { // devConfig[devConfigIndex]->bAddress = 0; // } //} // Serial.print("HOST USB Host @ 0x"); // Serial.println((uint32_t)this, HEX); // Serial.print("HOST USB Host Address Pool @ 0x"); // Serial.println((uint32_t)GetAddressPool(), HEX); sof_delay(200); p = addrPool.GetUsbDevicePtr(0); if(!p) { HOST_DEBUG("Configuring error: USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL\r\n"); return UHS_HOST_ERROR_NO_ADDRESS_IN_POOL; } p->speed = speed; #if UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE p->epinfo[0][0].maxPktSize = 0x40; // Windows bug is expected. // poison data // udd->bMaxPacketSize0 = 0U; #else p->epinfo[0][0].maxPktSize = 0x08; // USB Spec, start small, work your way up. #endif again: memset((void *)buf, 0, biggest); HOST_DEBUG("\r\n\r\nConfiguring PktSize 0x%2.2x, rcode: 0x%2.2x, retries %i,\r\n", p->epinfo[0][0].maxPktSize, rcode, retries); rcode = getDevDescr(0, biggest, (uint8_t*)buf); #if UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE if(rcode || udd->bMaxPacketSize0 < 8) #else if(rcode) #endif { if(rcode == UHS_HOST_ERROR_JERR && retries < 4) { // // Some devices return JERR when plugged in. // Attempts to reinitialize the device usually works. // // I have a hub that will refuse to work and acts like // this unless external power is supplied. // So this may not always work, and you may be fooled. // sof_delay(100); retries++; goto again; #if UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE } else if(((rcode == UHS_HOST_ERROR_DMA || rcode == UHS_HOST_ERROR_MEM_LAT) && retries < 4) || (udd->bMaxPacketSize0 < 8 && !rcode)) { if(p->epinfo[0][0].maxPktSize > 8 && rcode == UHS_HOST_ERROR_DMA) p->epinfo[0][0].maxPktSize = p->epinfo[0][0].maxPktSize >> 1; #else } else if((rcode == UHS_HOST_ERROR_DMA || rcode == UHS_HOST_ERROR_MEM_LAT) && retries < 4) { if(p->epinfo[0][0].maxPktSize < 32) p->epinfo[0][0].maxPktSize = p->epinfo[0][0].maxPktSize << 1; #endif HOST_DEBUG("Configuring error: 0x%2.2x UHS_HOST_ERROR_DMA. Retry with maxPktSize: %i\r\n", rcode, p->epinfo[0][0].maxPktSize); doSoftReset(parent, port, 0); retries++; sof_delay(200); goto again; } HOST_DEBUG("Configuring error: 0x%2.2x Can't get USB_FD_DEVICE_DESCRIPTOR\r\n", rcode); return rcode; } #if UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE ei.address = addrPool.AllocAddress(parent, false, port); if(!ei.address) { return UHS_HOST_ERROR_ADDRESS_POOL_FULL; } p = addrPool.GetUsbDevicePtr(ei.address); // set to 1 if you suspect address table corruption. #if 0 if(!p) { return UHS_HOST_ERROR_NO_ADDRESS_IN_POOL; } #endif p->speed = speed; rcode = doSoftReset(parent, port, ei.address); if(rcode) { addrPool.FreeAddress(ei.address); HOST_DEBUG("Configuring error: %2.2x Can't set USB INTERFACE ADDRESS\r\n", rcode); return rcode; } { // the { } wrapper saves on stack. HOST_DEBUG("DevDescr 2nd poll, bMaxPacketSize0:%u\r\n", udd->bMaxPacketSize0); UHS_EpInfo dev1ep; dev1ep.maxPktSize = udd->bMaxPacketSize0; dev1ep.epAddr = 0; dev1ep.epAttribs = 0; dev1ep.bmNakPower = UHS_USB_NAK_MAX_POWER; p->address.devAddress = ei.address; p->epcount = 1; p->epinfo[0] = &dev1ep; sof_delay(10); memset((void *)buf, 0, biggest); rcode = getDevDescr(ei.address, 18, (uint8_t*)buf); if(rcode) HOST_DEBUG("getDevDescr err: 0x%x \r\n", rcode); addrPool.FreeAddress(ei.address); if(rcode && rcode != UHS_HOST_ERROR_DMA) { return rcode; } sof_delay(10); } #endif ei.vid = udd->idVendor; ei.pid = udd->idProduct; ei.bcdDevice = udd->bcdDevice; ei.klass = udd->bDeviceClass; ei.subklass = udd->bDeviceSubClass; ei.protocol = udd->bDeviceProtocol; ei.bMaxPacketSize0 = udd->bMaxPacketSize0; ei.currentconfig = 0; ei.parent = parent; ei.port = port; configs = udd->bNumConfigurations; #if UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE } // unwrapped, old large buf now invalid and discarded. uint8_t buf[18]; USB_FD_CONFIGURATION_DESCRIPTOR *ucd = reinterpret_cast<USB_FD_CONFIGURATION_DESCRIPTOR *>(buf); #endif ei.address = addrPool.AllocAddress(parent, IsHub(ei.klass), port); if(!ei.address) { return UHS_HOST_ERROR_ADDRESS_POOL_FULL; } p = addrPool.GetUsbDevicePtr(ei.address); // set to 1 if you suspect address table corruption. #if 0 if(!p) { return UHS_HOST_ERROR_NO_ADDRESS_IN_POOL; } #endif p->speed = speed; rcode = doSoftReset(parent, port, ei.address); if(rcode) { addrPool.FreeAddress(ei.address); HOST_DEBUG("Configuring error: %2.2x Can't set USB INTERFACE ADDRESS\r\n", rcode); return rcode; } if(configs < 1) { HOST_DEBUG("No interfaces?!\r\n"); addrPool.FreeAddress(ei.address); // rcode = TestInterface(&ei); // Not implemented (yet) rcode = UHS_HOST_ERROR_DEVICE_NOT_SUPPORTED; } else { HOST_DEBUG("configs: %i\r\n", configs); for(uint8_t conf = 0; (!rcode) && (conf < configs); conf++) { // read the config descriptor into a buffer. rcode = getConfDescr(ei.address, sizeof (USB_FD_CONFIGURATION_DESCRIPTOR), conf, buf); if(rcode) { HOST_DEBUG("Configuring error: %2.2x Can't get USB_FD_INTERFACE_DESCRIPTOR\r\n", rcode); rcode = UHS_HOST_ERROR_FailGetConfDescr; continue; } ei.currentconfig = conf; numinf = ucd->bNumInterfaces; // Does _not_ include alternates! HOST_DEBUG("CONFIGURATION: %i, bNumInterfaces %i, wTotalLength %i\r\n", conf, numinf, ucd->wTotalLength); uint8_t success = 0; uint16_t inf = 0; uint8_t data[ei.bMaxPacketSize0]; UHS_EpInfo *pep; pep = ctrlReqOpen(ei.address, mkSETUP_PKT8(UHS_bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, ei.currentconfig, USB_DESCRIPTOR_CONFIGURATION, 0x0000U, ucd->wTotalLength), data); if(!pep) { rcode = UHS_HOST_ERROR_NULL_EPINFO; continue; } uint16_t left; uint16_t read; uint8_t offset; rcode = initDescrStream(&ei, ucd, pep, data, &left, &read, &offset); if(rcode) { HOST_DEBUG("Configuring error: %2.2x Can't get USB_FD_INTERFACE_DESCRIPTOR stream.\r\n", rcode); break; } for(; (numinf) && (!rcode); inf++) { // iterate for each interface on this config rcode = getNextInterface(&ei, pep, data, &left, &read, &offset); if(rcode == UHS_HOST_ERROR_END_OF_STREAM) { HOST_DEBUG("USB_INTERFACE END OF STREAM\r\n"); ctrlReqClose(pep, UHS_bmREQ_GET_DESCR, left, ei.bMaxPacketSize0, data); rcode = 0; break; } if(rcode) { HOST_DEBUG("Configuring error: %2.2x Can't close USB_FD_INTERFACE_DESCRIPTOR stream.\r\n", rcode); continue; } rcode = TestInterface(&ei); if(!rcode) success++; rcode = 0; } if(!inf) { rcode = TestInterface(&ei); if(!rcode) success++; rcode = 0; } if(success > bestsuccess) { bestconf = conf; bestsuccess = success; } } if(!bestsuccess) rcode = UHS_HOST_ERROR_DEVICE_NOT_SUPPORTED; } if(!rcode) { rcode = getConfDescr(ei.address, sizeof (USB_FD_CONFIGURATION_DESCRIPTOR), bestconf, buf); if(rcode) { HOST_DEBUG("Configuring error: %2.2x Can't get USB_FD_INTERFACE_DESCRIPTOR\r\n", rcode); rcode = UHS_HOST_ERROR_FailGetConfDescr; } } if(!rcode) { bestconf++; ei.currentconfig = bestconf; numinf = ucd->bNumInterfaces; // Does _not_ include alternates! HOST_DEBUG("CONFIGURATION: %i, bNumInterfaces %i, wTotalLength %i\r\n", bestconf, numinf, ucd->wTotalLength); if(!rcode) { HOST_DEBUG("Best configuration is %i, enumerating interfaces.\r\n", bestconf); uint16_t inf = 0; uint8_t data[ei.bMaxPacketSize0]; UHS_EpInfo *pep; pep = ctrlReqOpen(ei.address, mkSETUP_PKT8(UHS_bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, ei.currentconfig - 1, USB_DESCRIPTOR_CONFIGURATION, 0x0000U, ucd->wTotalLength), data); if(!pep) { rcode = UHS_HOST_ERROR_NULL_EPINFO; } else { uint16_t left; uint16_t read; uint8_t offset; rcode = initDescrStream(&ei, ucd, pep, data, &left, &read, &offset); if(rcode) { HOST_DEBUG("Configuring error: %2.2x Can't get USB_FD_INTERFACE_DESCRIPTOR stream.\r\n", rcode); } else { for(; (numinf) && (!rcode); inf++) { // iterate for each interface on this config rcode = getNextInterface(&ei, pep, data, &left, &read, &offset); if(rcode == UHS_HOST_ERROR_END_OF_STREAM) { ctrlReqClose(pep, UHS_bmREQ_GET_DESCR, left, ei.bMaxPacketSize0, data); rcode = 0; break; } if(rcode) { HOST_DEBUG("Configuring error: %2.2x Can't close USB_FD_INTERFACE_DESCRIPTOR stream.\r\n", rcode); continue; } if(enumerateInterface(&ei) == UHS_HOST_MAX_INTERFACE_DRIVERS) { HOST_DEBUG("No interface driver for this interface."); } else { HOST_DEBUG("Interface Configured\r\n"); } } } } } else { HOST_DEBUG("Configuring error: %2.2x Can't set USB_INTERFACE_CONFIG stream.\r\n", rcode); } } if(!rcode) { rcode = setConf(ei.address, bestconf); if(rcode) { HOST_DEBUG("Configuring error: %2.2x Can't set Configuration.\r\n", rcode); addrPool.FreeAddress(ei.address); } else { for(devConfigIndex = 0; devConfigIndex < UHS_HOST_MAX_INTERFACE_DRIVERS; devConfigIndex++) { HOST_DEBUG("Driver %i ", devConfigIndex); if(!devConfig[devConfigIndex]) { HOST_DEBUG("no driver at this index.\r\n"); continue; // no driver } HOST_DEBUG("@ %2.2x ", devConfig[devConfigIndex]->bAddress); if(devConfig[devConfigIndex]->bAddress) { if(!devConfig[devConfigIndex]->bPollEnable) { HOST_DEBUG("Initialize\r\n"); rcode = devConfig[devConfigIndex]->Finalize(); rcode = devConfig[devConfigIndex]->Start(); if(!rcode) { HOST_DEBUG("Total endpoints = (%i)%i\r\n", p->epcount, devConfig[devConfigIndex]->bNumEP); } else { break; } } else { HOST_DEBUG("Already initialized.\r\n"); continue; // consumed } } else { HOST_DEBUG("Skipped\r\n"); } } #if 0 // defined(UHS_HID_LOADED) // Now do HID #endif } } else { addrPool.FreeAddress(ei.address); } return rcode; } /** * Removes a device from the tables * * @param addr address of the device * @return nothing */ void UHS_USB_HOST_BASE::ReleaseDevice(uint8_t addr) { if(addr) { #if 0 // defined(UHS_HID_LOADED) // Release any HID children UHS_HID_Release(this, addr); #endif for(uint8_t i = 0; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) { if(!devConfig[i]) continue; if(devConfig[i]->bAddress == addr) { devConfig[i]->Release(); break; } } } } /** * Gets the device descriptor, or part of it from endpoint Zero. * * @param addr Address of the device * @param nbytes how many bytes to return * @param dataptr pointer to the data to return * @return status of the request, zero is success. */ uint8_t UHS_USB_HOST_BASE::getDevDescr(uint8_t addr, uint16_t nbytes, uint8_t *dataptr) { return ( ctrlReq(addr, mkSETUP_PKT8(UHS_bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes), nbytes, dataptr)); } /** * Gets the config descriptor, or part of it from endpoint Zero. * * @param addr Address of the device * @param nbytes how many bytes to return * @param conf index to descriptor to return * @param dataptr ointer to the data to return * @return status of the request, zero is success. */ uint8_t UHS_USB_HOST_BASE::getConfDescr(uint8_t addr, uint16_t nbytes, uint8_t conf, uint8_t *dataptr) { return ( ctrlReq(addr, mkSETUP_PKT8(UHS_bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes), nbytes, dataptr)); } /** * Get the string descriptor from a device * * @param addr Address of the device * @param ns * @param index * @param langid language ID * @param dataptr pointer to the data to return * @return status of the request, zero is success. */ uint8_t UHS_USB_HOST_BASE::getStrDescr(uint8_t addr, uint16_t ns, uint8_t index, uint16_t langid, uint8_t *dataptr) { return ( ctrlReq(addr, mkSETUP_PKT8(UHS_bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, ns), ns, dataptr)); } // //set address // /** * Set the address of a device to a new address via endpoint Zero. * * @param oldaddr current address * @param newaddr new address * @return status of the request, zero is success. */ uint8_t UHS_USB_HOST_BASE::setAddr(uint8_t oldaddr, uint8_t newaddr) { uint8_t rcode = ctrlReq(oldaddr, mkSETUP_PKT8(UHS_bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000), 0x0000, NULL); sof_delay(300); // Older spec says you should wait at least 200ms return rcode; } // //set configuration // /** * Set the configuration for the device to use via endpoint Zero. * * @param addr Address of the device * @param conf_value configuration index value * @return status of the request, zero is success. */ uint8_t UHS_USB_HOST_BASE::setConf(uint8_t addr, uint8_t conf_value) { return ( ctrlReq(addr, mkSETUP_PKT8(UHS_bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000), 0x0000, NULL)); } /* rcode 0 if no errors. rcode 01-0f is relayed from HRSL */ /** * Writes data to an interface pipe * * @param addr Address of the device * @param ep Endpoint of the pipe * @param nbytes number of bytes to transfer * @param data pointer to buffer to hold transfer * @return zero for success or error code */ uint8_t UHS_USB_HOST_BASE::outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *data) { UHS_EpInfo *pep = NULL; uint16_t nak_limit = 0; HOST_DEBUG("outTransfer: addr: 0x%2.2x ep: 0x%2.2x nbytes: 0x%4.4x data: 0x%p\r\n", addr, ep, nbytes, data); uint8_t rcode = SetAddress(addr, ep, &pep, nak_limit); HOST_DEBUG("outTransfer: SetAddress 0x%2.2x\r\n", rcode); if(!rcode) rcode = OutTransfer(pep, nak_limit, nbytes, data); return rcode; }; /** * Reads data from an interface pipe * * @param addr Address of the device * @param ep Endpoint of the pipe * @param nbytesptr number of bytes to transfer * @param data pointer to buffer to hold transfer * @return zero for success or error code */ uint8_t UHS_USB_HOST_BASE::inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t *data) { UHS_EpInfo *pep = NULL; uint16_t nak_limit = 0; uint8_t rcode = SetAddress(addr, ep, &pep, nak_limit); // if(rcode) { // USBTRACE3("(USB::InTransfer) SetAddress Failed ", rcode, 0x81); // USBTRACE3("(USB::InTransfer) addr requested ", addr, 0x81); // USBTRACE3("(USB::InTransfer) ep requested ", ep, 0x81); // return rcode; // } if(!rcode) rcode = InTransfer(pep, nak_limit, nbytesptr, data); return rcode; } /** * Initialize the descriptor stream, works much like opening a file. * * @param ei * @param ucd * @param pep * @param data * @param left * @param read * @param offset * @return zero for success or error code */ uint8_t UHS_USB_HOST_BASE::initDescrStream(ENUMERATION_INFO *ei, USB_FD_CONFIGURATION_DESCRIPTOR *ucd, UHS_EpInfo *pep, uint8_t *data, uint16_t *left, uint16_t *read, uint8_t *offset) { if(!ei || !ucd) return UHS_HOST_ERROR_BAD_ARGUMENT; if(!pep) return UHS_HOST_ERROR_NULL_EPINFO; *left = ucd->wTotalLength; *read = 0; *offset = 1; uint8_t rcode; pep->maxPktSize = ei->bMaxPacketSize0; rcode = getone(pep, left, read, data, offset); return rcode; } uint8_t UHS_USB_HOST_BASE::getNextInterface(ENUMERATION_INFO *ei, UHS_EpInfo *pep, uint8_t data[], uint16_t *left, uint16_t *read, uint8_t *offset) { uint16_t remain; uint8_t ty; uint8_t rcode = UHS_HOST_ERROR_END_OF_STREAM; uint8_t *ptr; uint8_t epc = 0; ei->interface.numep = 0; ei->interface.klass = 0; ei->interface.subklass = 0; ei->interface.protocol = 0; while(*left + *read) { remain = data[*offset]; // bLength while(remain < 2) { rcode = getone(pep, left, read, data, offset); if(rcode) return rcode; remain = data[*offset]; } rcode = getone(pep, left, read, data, offset); if(rcode) return rcode; ty = data[*offset]; // bDescriptorType HOST_DEBUG("bLength: %i ", remain); HOST_DEBUG("bDescriptorType: %2.2x\r\n", ty); remain--; if(ty == USB_DESCRIPTOR_INTERFACE) { HOST_DEBUG("INTERFACE DESCRIPTOR FOUND\r\n"); ptr = (uint8_t *)(&(ei->interface.bInterfaceNumber)); for(int i = 0; i < 6; i++) { rcode = getone(pep, left, read, data, offset); if(rcode) return rcode; *ptr = data[*offset]; ptr++; } rcode = getone(pep, left, read, data, offset); if(rcode) return rcode; // Now at iInterface // Get endpoints. HOST_DEBUG("Getting %i endpoints\r\n", ei->interface.numep); while(epc < ei->interface.numep) { rcode = getone(pep, left, read, data, offset); if(rcode) { HOST_DEBUG("ENDPOINT DESCRIPTOR DIED WAY EARLY\r\n"); return rcode; } remain = data[*offset]; // bLength while(remain < 2) { rcode = getone(pep, left, read, data, offset); if(rcode) return rcode; remain = data[*offset]; } rcode = getone(pep, left, read, data, offset); if(rcode) { HOST_DEBUG("ENDPOINT DESCRIPTOR DIED EARLY\r\n"); return rcode; } ty = data[*offset]; // bDescriptorType HOST_DEBUG("bLength: %i ", remain); HOST_DEBUG("bDescriptorType: %2.2x\r\n", ty); remain -= 2; if(ty == USB_DESCRIPTOR_ENDPOINT) { HOST_DEBUG("ENDPOINT DESCRIPTOR: %i\r\n", epc); ptr = (uint8_t *)(&(ei->interface.epInfo[epc].bEndpointAddress)); for(unsigned int i = 0; i< sizeof (ENDPOINT_INFO); i++) { rcode = getone(pep, left, read, data, offset); if(rcode) { HOST_DEBUG("ENDPOINT DESCRIPTOR DIED LATE\r\n"); return rcode; } *ptr = data[*offset]; ptr++; remain--; } epc++; HOST_DEBUG("ENDPOINT DESCRIPTOR OK\r\n"); } rcode = eat(pep, left, read, data, offset, &remain); if(rcode) { HOST_DEBUG("ENDPOINT DESCRIPTOR DIED EATING\r\n"); return rcode; } remain = 0; } remain = 1; // queue ahead, but do not report if error. rcode = eat(pep, left, read, data, offset, &remain); if(!ei->interface.numep && rcode) { return rcode; } HOST_DEBUG("ENDPOINT DESCRIPTORS FILLED\r\n"); return 0; } else { rcode = eat(pep, left, read, data, offset, &remain); if(rcode) return rcode; } rcode = UHS_HOST_ERROR_END_OF_STREAM; } return rcode; } uint8_t UHS_USB_HOST_BASE::seekInterface(ENUMERATION_INFO *ei, uint16_t inf, USB_FD_CONFIGURATION_DESCRIPTOR *ucd) { if(!ei || !ucd) return UHS_HOST_ERROR_BAD_ARGUMENT; uint8_t data[ei->bMaxPacketSize0]; UHS_EpInfo *pep; pep = ctrlReqOpen(ei->address, mkSETUP_PKT8(UHS_bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, ei->currentconfig, USB_DESCRIPTOR_CONFIGURATION, 0x0000U, ucd->wTotalLength), data); if(!pep) return UHS_HOST_ERROR_NULL_EPINFO; uint16_t left = ucd->wTotalLength; uint8_t cinf = 0; uint8_t ty; uint8_t epc = 0; uint16_t remain = ucd->bLength; uint16_t read = 0; uint8_t offset = remain; uint8_t *ptr; uint8_t rcode; ei->interface.numep = 0; ei->interface.klass = 0; ei->interface.subklass = 0; ei->interface.protocol = 0; pep->maxPktSize = ei->bMaxPacketSize0; rcode = getone(pep, &left, &read, data, &offset); if(rcode) return rcode; HOST_DEBUG("\r\nGetting interface: %i\r\n", inf); inf++; while(cinf != inf && (left + read)) { //HOST_DEBUG("getInterface: cinf: %i inf: %i left: %i read: %i offset: %i remain %i\r\n", cinf, inf, left, read, offset, remain); // Go past current descriptor HOST_DEBUG("Skip: %i\r\n", remain); rcode = eat(pep, &left, &read, data, &offset, &remain); if(rcode) return rcode; remain = data[offset]; // bLength while(remain < 2) { rcode = getone(pep, &left, &read, data, &offset); if(rcode) return rcode; remain = data[offset]; } rcode = getone(pep, &left, &read, data, &offset); if(rcode) return rcode; ty = data[offset]; // bDescriptorType HOST_DEBUG("bLength: %i ", remain); HOST_DEBUG("bDescriptorType: %2.2x\r\n", ty); remain--; if(ty == USB_DESCRIPTOR_INTERFACE) { HOST_DEBUG("INTERFACE DESCRIPTOR: %i\r\n", cinf); cinf++; if(cinf == inf) { // Get the interface descriptor information. ptr = (uint8_t *)(&(ei->interface.bInterfaceNumber)); for(int i = 0; i < 6; i++) { rcode = getone(pep, &left, &read, data, &offset); if(rcode) return rcode; *ptr = data[offset]; ptr++; } rcode = getone(pep, &left, &read, data, &offset); if(rcode) return rcode; // Now at iInterface remain = 0; // Get endpoints. HOST_DEBUG("Getting %i endpoints\r\n", ei->interface.numep); while(epc < ei->interface.numep) { rcode = getone(pep, &left, &read, data, &offset); if(rcode) return rcode; remain = data[offset]; // bLength while(remain < 2) { rcode = getone(pep, &left, &read, data, &offset); if(rcode) return rcode; remain = data[offset]; } rcode = getone(pep, &left, &read, data, &offset); if(rcode) return rcode; ty = data[offset]; // bDescriptorType HOST_DEBUG("bLength: %i ", remain); HOST_DEBUG("bDescriptorType: %2.2x\r\n", ty); remain--; if(ty == USB_DESCRIPTOR_ENDPOINT) { HOST_DEBUG("ENDPOINT DESCRIPTOR: %i\r\n", epc); ptr = (uint8_t *)(&(ei->interface.epInfo[epc].bEndpointAddress)); for(unsigned int i = 0; i< sizeof (ENDPOINT_INFO); i++) { rcode = getone(pep, &left, &read, data, &offset); if(rcode) return rcode; *ptr = data[offset]; ptr++; } epc++; remain = 0; } else { rcode = eat(pep, &left, &read, data, &offset, &remain); if(rcode) return rcode; remain = 0; } } } } } return ctrlReqClose(pep, UHS_bmREQ_GET_DESCR, left, ei->bMaxPacketSize0, data); } uint8_t UHS_USB_HOST_BASE::getone(UHS_EpInfo *pep, uint16_t *left, uint16_t *read, uint8_t *dataptr, uint8_t *offset) { uint8_t rcode = 0; *offset += 1; if(*offset < *read) { return 0; } else if(*left > 0) { // uint16_t num = *left; uint16_t num = pep->maxPktSize; if(num > *left) num = *left; *offset = 0; rcode = ctrlReqRead(pep, left, read, num, dataptr); if(rcode == 0) { if(*read == 0) { rcode = UHS_HOST_ERROR_END_OF_STREAM; } else if(*read < num) *left = 0; } } else { rcode = UHS_HOST_ERROR_END_OF_STREAM; } return rcode; } uint8_t UHS_USB_HOST_BASE::eat(UHS_EpInfo *pep, uint16_t *left, uint16_t *read, uint8_t *dataptr, uint8_t *offset, uint16_t *yum) { uint8_t rcode = 0; HOST_DEBUG("eating %i\r\n", *yum); while(*yum) { *yum -= 1; rcode = getone(pep, left, read, dataptr, offset); if(rcode) break; } return rcode; } uint8_t UHS_USB_HOST_BASE::ctrlReq(uint8_t addr, uint64_t Request, uint16_t nbytes, uint8_t *dataptr) { //bool direction = bmReqType & 0x80; //request direction, IN or OUT uint8_t rcode = 0; //Serial.println(); UHS_EpInfo *pep = ctrlReqOpen(addr, Request, dataptr); if(!pep) { HOST_DEBUG("ctrlReq1: ERROR_NULL_EPINFO addr: %d\r\n", addr); return UHS_HOST_ERROR_NULL_EPINFO; } uint8_t rt = (uint8_t)(Request & 0xFFU); // Serial.println("Opened"); uint16_t left = (uint16_t)(Request >> 48) /*total*/; if(dataptr != NULL) { //data stage if((rt & 0x80) == 0x80) { //IN transfer while(left) { // Bytes read into buffer uint16_t read = nbytes; HOST_DEBUG("ctrlReq2: left: %i, read:%i, nbytes %i\r\n", left, read, nbytes); rcode = ctrlReqRead(pep, &left, &read, nbytes, dataptr); #if UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE HOST_DEBUG("RESULT: 0x%2.2x 0x%2.2x 0x%2.2x 0x%8.8lx%8.8lx\r\n", rcode, addr, read, (uint32_t)((Request>>32)&0xFFFFFFFFLU), (uint32_t)(Request&0xFFFFFFFFLU)); // Should only be used for GET_DESCRIPTOR USB_DESCRIPTOR_DEVICE constexpr uint32_t req_match = ((uint32_t)USB_DESCRIPTOR_DEVICE << 24) | ((uint32_t)USB_REQUEST_GET_DESCRIPTOR << 8); const uint32_t req_found = Request & 0xFF00FF00ul; if(!addr && read && (req_found == req_match)) { HOST_DEBUG("ctrlReq3: acceptBuffer sz %i nbytes %i left %i\n\r", read, nbytes, left); left = 0; rcode = UHS_HOST_ERROR_NONE; break; } #endif if(rcode) { return rcode; } } } else { // OUT transfer rcode = OutTransfer(pep, 0, nbytes, dataptr); } if(rcode) { //return error return ( rcode); } } // Serial.println("Close Phase"); // Serial.flush(); // Status stage rcode = ctrlReqClose(pep, rt, left, nbytes, dataptr); // Serial.println("Closed"); return rcode; } uint8_t UHS_USB_HOST_BASE::EPClearHalt(uint8_t addr, uint8_t ep) { return ctrlReq(addr, mkSETUP_PKT8(USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_STANDARD | USB_SETUP_RECIPIENT_ENDPOINT, USB_REQUEST_CLEAR_FEATURE, USB_FEATURE_ENDPOINT_HALT, 0, ep, 0), 0, NULL); } uint8_t UHS_USB_HOST_BASE::TestInterface(ENUMERATION_INFO *ei) { uint8_t devConfigIndex; uint8_t rcode = 0; HOST_DEBUG("TestInterface VID:%4.4x PID:%4.4x Class:%2.2x Subclass:%2.2x Protocol %2.2x\r\n", ei->vid, ei->pid, ei->klass, ei->subklass, ei->protocol); HOST_DEBUG("Interface data: Class:%2.2x Subclass:%2.2x Protocol %2.2x, number of endpoints %i\r\n", ei->interface.klass, ei->interface.subklass, ei->interface.subklass, ei->interface.numep); HOST_DEBUG("Parent: %2.2x, bAddress: %2.2x\r\n", ei->parent, ei->address); for(devConfigIndex = 0; devConfigIndex < UHS_HOST_MAX_INTERFACE_DRIVERS; devConfigIndex++) { if(!devConfig[devConfigIndex]) { HOST_DEBUG("No driver at index %i\r\n", devConfigIndex); continue; // no driver } if(devConfig[devConfigIndex]->bAddress) { HOST_DEBUG("Driver %i is already consumed @ %2.2x\r\n", devConfigIndex, devConfig[devConfigIndex]->bAddress); continue; // consumed } if(devConfig[devConfigIndex]->OKtoEnumerate(ei)) { HOST_DEBUG("Driver %i supports this interface\r\n", devConfigIndex); break; } } if(devConfigIndex == UHS_HOST_MAX_INTERFACE_DRIVERS) { rcode = UHS_HOST_ERROR_DEVICE_NOT_SUPPORTED; #if 0 // defined(UHS_HID_LOADED) // Check HID here, if it is, then lie if(ei->klass == UHS_USB_CLASS_HID) { devConfigIndex = UHS_HID_INDEX; // for debugging, otherwise this has no use. rcode = 0; } #endif } if(!rcode) HOST_DEBUG("Driver %i can be used for this interface\r\n", devConfigIndex); else HOST_DEBUG("No driver for this interface.\r\n"); return rcode; }; uint8_t UHS_USB_HOST_BASE::enumerateInterface(ENUMERATION_INFO *ei) { uint8_t devConfigIndex; HOST_DEBUG("AttemptConfig: parent = %i, port = %i\r\n", ei->parent, ei->port); #if 0 // defined(UHS_HID_LOADED) // Check HID here, if it is, then lie if(ei->klass == UHS_USB_CLASS_HID || ei->interface.klass == UHS_USB_CLASS_HID) { UHS_HID_SetUSBInterface(this, ENUMERATION_INFO * ei); devConfigIndex = UHS_HID_INDEX; } else #endif for(devConfigIndex = 0; devConfigIndex < UHS_HOST_MAX_INTERFACE_DRIVERS; devConfigIndex++) { if(!devConfig[devConfigIndex]) { HOST_DEBUG("No driver at index %i\r\n", devConfigIndex); continue; // no driver } if(devConfig[devConfigIndex]->bAddress) { HOST_DEBUG("Driver %i is already consumed @ %2.2x\r\n", devConfigIndex, devConfig[devConfigIndex]->bAddress); continue; // consumed } if(devConfig[devConfigIndex]->OKtoEnumerate(ei)) { HOST_DEBUG("Driver %i supports this interface\r\n", devConfigIndex); if(!devConfig[devConfigIndex]->SetInterface(ei)) break; else devConfigIndex = UHS_HOST_MAX_INTERFACE_DRIVERS; } } return devConfigIndex; }; //////////////////////////////////////////////////////////////////////////////// // Vendor Specific Interface Class //////////////////////////////////////////////////////////////////////////////// #if 0 /** * Might go away, depends on if it is useful, or not. * * @param ei Enumeration information * @return true if this interface driver can handle this interface description */ bool UHS_NI UHS_VSI::OKtoEnumerate(ENUMERATION_INFO *ei) { return ( (ei->subklass == UHS_USB_CLASS_VENDOR_SPECIFIC) || (ei->interface.subklass == UHS_USB_CLASS_VENDOR_SPECIFIC) ); } /** * Copy the entire ENUMERATION_INFO structure * @param ei Enumeration information * @return 0 */ uint8_t UHS_NI UHS_VSI::SetInterface(ENUMERATION_INFO *ei) { bNumEP = 1; bAddress = ei->address; eInfo.address = ei->address; eInfo.bMaxPacketSize0 = ei->bMaxPacketSize0; eInfo.currentconfig = ei->currentconfig; eInfo.interface.bAlternateSetting = ei->interface.bAlternateSetting; eInfo.interface.bInterfaceNumber = ei->interface.bInterfaceNumber; eInfo.interface.numep = ei->interface.numep; eInfo.interface.protocol = ei->interface.protocol; eInfo.interface.subklass = ei->interface.subklass; eInfo.klass = ei->klass; eInfo.parent = ei->parent; eInfo.pid = ei->pid; eInfo.port = ei->port; eInfo.protocol = ei->protocol; eInfo.subklass = ei->subklass; eInfo.vid = ei->vid; for(uint8_t i = 0; i < eInfo.interface.numep; i++) { eInfo.interface.epInfo[i].bEndpointAddress = ei->interface.epInfo[i].bEndpointAddress; eInfo.interface.epInfo[i].bInterval = ei->interface.epInfo[i].bInterval; eInfo.interface.epInfo[i].bmAttributes = ei->interface.epInfo[i].bmAttributes; eInfo.interface.epInfo[i].wMaxPacketSize = ei->interface.epInfo[i].wMaxPacketSize; } return 0; } #endif //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #if 0 /* TO-DO: Move this silliness to a NONE driver. * When we have a generic NONE driver we can: * o Extract ALL device information to help users with a new device. * o Use an unknown device from a sketch, kind of like usblib does. * This will aid in making more drivers in a faster way. */ uint8_t UHS_USB_HOST_BASE::DefaultAddressing(uint8_t parent, uint8_t port, uint8_t speed) { uint8_t rcode; UHS_Device *p0 = NULL, *p = NULL; // Get pointer to pseudo device with address 0 assigned p0 = addrPool.GetUsbDevicePtr(0); if(!p0) return UHS_HOST_ERROR_NO_ADDRESS_IN_POOL; if(!p0->epinfo) return UHS_HOST_ERROR_NULL_EPINFO; p0->speed = speed; // Allocate new address according to device class uint8_t bAddress = addrPool.AllocAddress(parent, false, port); if(!bAddress) return UHS_HOST_ERROR_ADDRESS_POOL_FULL; p = addrPool.GetUsbDevicePtr(bAddress); if(!p) return UHS_HOST_ERROR_NO_ADDRESS_IN_POOL; p->speed = speed; // Assign new address to the device rcode = setAddr(0, bAddress); if(rcode) { addrPool.FreeAddress(bAddress); bAddress = 0; return rcode; } return 0; } #endif #else #error "Never include UHS_host_INLINE.h, include UHS_host.h instead" #endif
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_host_INLINE.h
C++
agpl-3.0
54,238
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #ifndef MACROS_H #define MACROS_H #include "macro_logic.h" /* * Universal Arduino(tm) "IDE" fixups. */ // Just in case... #ifndef SERIAL_PORT_MONITOR #define SERIAL_PORT_MONITOR Serial #endif #ifndef INT16_MIN #define INT16_MIN -32768 #endif // require 10607+ #if defined(ARDUINO) && ARDUINO >=10607 // nop :-) #else #error "Arduino version too old, and must be at least 1.6.7" #endif // Nuke screwed up macro junk from the IDE. #ifdef __cplusplus #ifdef true #undef true #endif #ifdef false #undef false #endif #endif #ifndef UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE #ifndef UHS_BIG_FLASH #if defined(FLASHEND) && defined(FLASHSTART) #if (FLASHEND - FLASHSTART) > 0x0FFFFU #define UHS_BIG_FLASH 1 #else #define UHS_BIG_FLASH 0 #endif #elif defined(__PIC32_FLASH_SIZE) #if __PIC32_FLASH_SIZE > 511 #define UHS_BIG_FLASH 1 #else #define UHS_BIG_FLASH 0 #endif #elif defined(FLASHEND) && !defined(FLASHSTART) // Assumes flash starts at 0x00000, is this a safe assumption? // 192K + should be OK #if FLASHEND > 0x02FFFFU #define UHS_BIG_FLASH 1 #else #define UHS_BIG_FLASH 0 #endif #elif defined(IFLASH_SIZE) #if IFLASH_SIZE > 0x0FFFFU #define UHS_BIG_FLASH 1 #else #define UHS_BIG_FLASH 0 #endif #elif defined(ESP8266) #define UHS_BIG_FLASH 1 #define SYSTEM_OR_SPECIAL_YIELD(...) yield() #elif defined(__arm__) && defined(CORE_TEENSY) #define UHS_BIG_FLASH 1 #elif defined(ARDUINO_spresense_ast) #define UHS_BIG_FLASH 1 #else // safe default #warning Small flash? #define UHS_BIG_FLASH 0 #endif #endif #if UHS_BIG_FLASH #define UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE 1 #else #define UHS_DEVICE_WINDOWS_USB_SPEC_VIOLATION_DESCRIPTOR_DEVICE 0 #endif #endif #if defined(__arm__) && defined(CORE_TEENSY) #define UHS_PIN_WRITE(p, v) digitalWriteFast(p, v) #define UHS_PIN_READ(p) digitalReadFast(p) #endif // TODO: Fast inline code for AVR and SAM based microcontrollers // This can be done pretty easily. // For now, this will just work out-of-the-box. #ifndef UHS_PIN_WRITE #define UHS_PIN_WRITE(p, v) digitalWrite(p, v) #endif #ifndef UHS_PIN_READ #define UHS_PIN_READ(p) digitalRead(p) #endif #if defined( __PIC32MX__ ) && !defined(interrupts) // compiling with Microchip XC32 compiler #define interrupts() __builtin_enable_interrupts() #edfine noInterrupts() __builtin_disable_interrupts() #endif #ifndef ARDUINO_SAMD_ZERO #ifdef ARDUINO_AVR_ADK #define UHS_GET_DPI(x) (x == 54 ? 6 : digitalPinToInterrupt(x)) #else #define UHS_GET_DPI(x) digitalPinToInterrupt(x) #endif #else #define UHS_GET_DPI(x) (x) #endif #include "../../../../HAL/shared/progmem.h" //////////////////////////////////////////////////////////////////////////////// // HANDY MACROS //////////////////////////////////////////////////////////////////////////////// // Atomically set/clear single bits using bitbands. // Believe it or not, this boils down to a constant, // and is less code than using |= &= operators. // Bonus, it makes code easier to read too. // Bitbanding is a wonderful thing. #define BITNR(i) (i&0x1?0:i&0x2?1:i&0x4?2:i&0x8?3:i&0x10?4:i&0x20?5:i&0x40?6:i&0x80?7:i&0x100?8:i&0x200?9:i&0x400?10:i&0x800?11:i&0x1000?12:i&0x2000?13:i&0x4000?14:i&0x8000?15:i&0x10000?16:i&0x20000?17:i&0x40000?18:i&0x80000?19:i&0x100000?20:i&0x200000?21:i&0x400000?22:i&0x800000?23:i&0x1000000?24:i&0x2000000?25:i&0x4000000?26:i&0x8000000?27:i&0x10000000?28:i&0x20000000?29:i&0x40000000?30:i&0x80000000?31:32) #define UHS_KIO_BITBAND_ADDR(r, i) (((uint32_t)&(r) - 0x40000000) * 32 + (i) * 4 + 0x42000000) #define UHS_KIO_SETBIT_ATOMIC(r, m) (*(uint32_t *)UHS_KIO_BITBAND_ADDR((r), BITNR((m)))) = 1 #define UHS_KIO_CLRBIT_ATOMIC(r, m) (*(uint32_t *)UHS_KIO_BITBAND_ADDR((r), BITNR((m)))) = 0 #define VALUE_BETWEEN(v,l,h) (((v)>(l)) && ((v)<(h))) #define VALUE_WITHIN(v,l,h) (((v)>=(l)) && ((v)<=(h))) #define output_pgm_message(wa,fp,mp,el) wa = &mp, fp((char *)pgm_read_pointer(wa), el) #define output_if_between(v,l,h,wa,fp,mp,el) if(VALUE_BETWEEN(v,l,h)) output_pgm_message(wa,fp,mp[v-(l+1)],el); #define UHS_SWAP_VALUES(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) #ifndef __BYTE_GRABBING_DEFINED__ #define __BYTE_GRABBING_DEFINED__ 1 #ifdef BROKEN_OPTIMIZER_LITTLE_ENDIAN // Note: Use this if your compiler generates horrible assembler! #define UHS_UINT8_BYTE0(__usi__) (((uint8_t *)&(__usi__))[0]) #define UHS_UINT8_BYTE1(__usi__) (((uint8_t *)&(__usi__))[1]) #define UHS_UINT8_BYTE2(__usi__) (((uint8_t *)&(__usi__))[2]) #define UHS_UINT8_BYTE3(__usi__) (((uint8_t *)&(__usi__))[3]) #define UHS_UINT8_BYTE4(__usi__) (((uint8_t *)&(__usi__))[4]) #define UHS_UINT8_BYTE5(__usi__) (((uint8_t *)&(__usi__))[5]) #define UHS_UINT8_BYTE6(__usi__) (((uint8_t *)&(__usi__))[6]) #define UHS_UINT8_BYTE7(__usi__) (((uint8_t *)&(__usi__))[7]) #else // Note: The cast alone to uint8_t is actually enough. // GCC throws out the "& 0xFF", and the size is no different. // Some compilers need it. #define UHS_UINT8_BYTE0(__usi__) ((uint8_t)((__usi__) & 0xFF )) #define UHS_UINT8_BYTE1(__usi__) ((uint8_t)(((__usi__) >> 8) & 0xFF)) #define UHS_UINT8_BYTE2(__usi__) ((uint8_t)(((__usi__) >> 16) & 0xFF)) #define UHS_UINT8_BYTE3(__usi__) ((uint8_t)(((__usi__) >> 24) & 0xFF)) #define UHS_UINT8_BYTE4(__usi__) ((uint8_t)(((__usi__) >> 32) & 0xFF)) #define UHS_UINT8_BYTE5(__usi__) ((uint8_t)(((__usi__) >> 40) & 0xFF)) #define UHS_UINT8_BYTE6(__usi__) ((uint8_t)(((__usi__) >> 48) & 0xFF)) #define UHS_UINT8_BYTE7(__usi__) ((uint8_t)(((__usi__) >> 56) & 0xFF)) #endif #define UHS_UINT16_SET_BYTE1(__usi__) ((uint16_t)(__usi__) << 8) #define UHS_UINT32_SET_BYTE1(__usi__) ((uint32_t)(__usi__) << 8) #define UHS_UINT64_SET_BYTE1(__usi__) ((uint64_t)(__usi__) << 8) #define UHS_UINT32_SET_BYTE2(__usi__) ((uint32_t)(__usi__) << 16) #define UHS_UINT64_SET_BYTE2(__usi__) ((uint64_t)(__usi__) << 16) #define UHS_UINT32_SET_BYTE3(__usi__) ((uint32_t)(__usi__) << 24) #define UHS_UINT64_SET_BYTE3(__usi__) ((uint64_t)(__usi__) << 24) #define UHS_UINT64_SET_BYTE4(__usi__) ((uint64_t)(__usi__) << 32) #define UHS_UINT64_SET_BYTE5(__usi__) ((uint64_t)(__usi__) << 40) #define UHS_UINT64_SET_BYTE6(__usi__) ((uint64_t)(__usi__) << 48) #define UHS_UINT64_SET_BYTE7(__usi__) ((uint64_t)(__usi__) << 56) // These are the smallest and fastest ways I have found so far in pure C/C++. #define UHS_BYTES_TO_UINT16(__usc1__,__usc0__) ((uint16_t)((uint16_t)(__usc0__) | (uint16_t)UHS_UINT16_SET_BYTE1(__usc1__))) #define UHS_BYTES_TO_UINT32(__usc3__,__usc2__,__usc1__,__usc0__) ((uint32_t)((uint32_t)(__usc0__) | UHS_UINT32_SET_BYTE1(__usc1__) | UHS_UINT32_SET_BYTE2(__usc2__) | UHS_UINT32_SET_BYTE3(__usc3__))) #define UHS_BYTES_TO_UINT64(__usc7__,__usc6__,__usc5__,__usc4__,__usc3__,__usc2__,__usc1__,__usc0__) ((uint64_t)((uint64_t)__usc0__ | UHS_UINT64_SET_BYTE1(__usc1__) | UHS_UINT64_SET_BYTE2(__usc2__) | UHS_UINT64_SET_BYTE3(__usc3__) | UHS_UINT64_SET_BYTE4(__usc4__) | UHS_UINT64_SET_BYTE5(__usc5__) | UHS_UINT64_SET_BYTE6(__usc6__) | UHS_UINT64_SET_BYTE7(__usc7__))) #endif /* * Debug macros. * Useful when porting from UHS2. * Do not use these for any new code. * Change to better debugging after port is completed. * Strings are stored in progmem (flash) instead of RAM. */ #define USBTRACE1(s,l) (Notify(PSTR(s), l)) #define USBTRACE(s) (USBTRACE1((s), 0x80)); USB_HOST_SERIAL.flush() #define USBTRACE3(s,r,l) (Notify(PSTR(s), l), D_PrintHex((r), l), Notify(PSTR("\r\n"), l)) #define USBTRACE3X(s,r,l) (Notify(PSTR(s), l), D_PrintHex((r), l)) #define USBTRACE2(s,r) (USBTRACE3((s),(r),0x80)); USB_HOST_SERIAL.flush() #define USBTRACE2X(s,r) (USBTRACE3X((s),(r),0x80)); USB_HOST_SERIAL.flush() #define VOID0 ((void)0) #ifndef NOTUSED #define NOTUSED(...) __VA_ARGS__ __attribute__((unused)) #endif #endif /* MACROS_H */
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_macros.h
C
agpl-3.0
8,713
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if !defined(_UHS_host_h_) || defined(__MESSAGE_H__) #error "Never include UHS_message.h directly; include UHS_Usb.h instead" #else #define __MESSAGE_H__ extern int UsbDEBUGlvl; void E_Notify(char const * msg, int lvl); void E_Notify(uint8_t b, int lvl); void E_NotifyStr(char const * msg, int lvl); void E_Notifyc(char c, int lvl); #ifdef DEBUG_USB_HOST #define Notify E_Notify #define NotifyStr E_NotifyStr #define Notifyc E_Notifyc void NotifyFailGetDevDescr(uint8_t reason); void NotifyFailSetDevTblEntry(uint8_t reason); void NotifyFailGetConfDescr(uint8_t reason); void NotifyFailSetConfDescr(uint8_t reason); void NotifyFailGetDevDescr(); void NotifyFailSetDevTblEntry(); void NotifyFailGetConfDescr(); void NotifyFailSetConfDescr(); void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID); void NotifyFail(uint8_t rcode); #else #define Notify(...) VOID0 #define NotifyStr(...) VOID0 #define Notifyc(...) VOID0 #define NotifyFailGetDevDescr(...) VOID0 #define NotifyFailSetDevTblEntry(...) VOID0 #define NotifyFailGetConfDescr(...) VOID0 #define NotifyFailGetDevDescr(...) VOID0 #define NotifyFailSetDevTblEntry(...) VOID0 #define NotifyFailGetConfDescr(...) VOID0 #define NotifyFailSetConfDescr(...) VOID0 #define NotifyFailUnknownDevice(...) VOID0 #define NotifyFail(...) VOID0 #endif #ifdef DEBUG_USB_HOST template <class ERROR_TYPE> void ErrorMessage(uint8_t level, char const * msg, ERROR_TYPE rcode = 0) { Notify(msg, level); Notify(PSTR(": "), level); D_PrintHex<ERROR_TYPE > (rcode, level); Notify(PSTR("\r\n"), level); #else template <class ERROR_TYPE> void ErrorMessage(NOTUSED(uint8_t level), NOTUSED(char const * msg), ERROR_TYPE rcode = 0) { (void)rcode; #endif } #ifdef DEBUG_USB_HOST template <class ERROR_TYPE> void ErrorMessage(char const * msg, ERROR_TYPE rcode = 0) { Notify(msg, 0x80); Notify(PSTR(": "), 0x80); D_PrintHex<ERROR_TYPE > (rcode, 0x80); Notify(PSTR("\r\n"), 0x80); #else template <class ERROR_TYPE> void ErrorMessage(NOTUSED(char const * msg), ERROR_TYPE rcode = 0) { (void)rcode; #endif } #endif // __MESSAGE_H__
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_message.h
C++
agpl-3.0
3,082
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #ifndef UHS_PRINTF_HELPER_H #define UHS_PRINTF_HELPER_H #ifdef LOAD_UHS_PRINTF_HELPER #include <Arduino.h> #ifdef true #undef true #endif #ifdef false #undef false #endif #ifndef STDIO_IS_OK_TO_USE_AS_IS #if defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAM_DUE) || defined(ARDUINO_spresense_ast) // STDIO patching not required. #define STDIO_IS_OK_TO_USE_AS_IS #endif #endif #ifndef STDIO_IS_OK_TO_USE_AS_IS // We need to patch STDIO so it can be used. #ifndef SERIAL_PORT_MONITOR // Some don't define this. #define SERIAL_PORT_MONITOR Serial #endif #ifndef SERIAL_PORT_HARDWARE // Some don't define this. #define SERIAL_PORT_HARDWARE SERIAL_PORT_MONITOR #endif #ifndef USB_HOST_SERIAL #if defined(SERIAL_PORT_USBVIRTUAL) && defined(LOAD_UHS_KINETIS_FS_HOST) #define USB_HOST_SERIAL SERIAL_PORT_HARDWARE #else #define USB_HOST_SERIAL SERIAL_PORT_MONITOR #endif #endif #ifndef NOTUSED #define NOTUSED(...) __VA_ARGS__ __attribute__((unused)) #endif #ifndef __AVR__ #ifndef printf_P #define printf_P(...) printf(__VA_ARGS__) #endif #endif #ifdef ARDUINO_ARCH_PIC32 /* * For printf() output with pic32 Arduino */ extern "C" { void _mon_putc(char s) { USB_HOST_SERIAL.write(s); } int _mon_getc() { while(!USB_HOST_SERIAL.available()); return USB_HOST_SERIAL.read(); } } #elif defined(__AVR__) extern "C" { static FILE tty_stdio; static FILE tty_stderr; static int NOTUSED(tty_stderr_putc(char c, NOTUSED(FILE *t))); static int NOTUSED(tty_stderr_flush(NOTUSED(FILE *t))); static int NOTUSED(tty_std_putc(char c, NOTUSED(FILE *t))); static int NOTUSED(tty_std_getc(NOTUSED(FILE *t))); static int NOTUSED(tty_std_flush(NOTUSED(FILE *t))); static int tty_stderr_putc(char c, NOTUSED(FILE *t)) { USB_HOST_SERIAL.write(c); return 0; } static int tty_stderr_flush(NOTUSED(FILE *t)) { USB_HOST_SERIAL.flush(); return 0; } static int tty_std_putc(char c, NOTUSED(FILE *t)) { USB_HOST_SERIAL.write(c); return 0; } static int tty_std_getc(NOTUSED(FILE *t)) { while(!USB_HOST_SERIAL.available()); return USB_HOST_SERIAL.read(); } static int tty_std_flush(NOTUSED(FILE *t)) { USB_HOST_SERIAL.flush(); return 0; } } #elif defined(CORE_TEENSY) extern "C" { int _write(int fd, const char *ptr, int len) { int j; for(j = 0; j < len; j++) { if(fd == 1) USB_HOST_SERIAL.write(*ptr++); else if(fd == 2) USB_HOST_SERIAL.write(*ptr++); } return len; } int _read(int fd, char *ptr, int len) { if(len > 0 && fd == 0) { while(!USB_HOST_SERIAL.available()); *ptr = USB_HOST_SERIAL.read(); return 1; } return 0; } #include <sys/stat.h> int _fstat(int fd, struct stat *st) { memset(st, 0, sizeof (*st)); st->st_mode = S_IFCHR; st->st_blksize = 1024; return 0; } int _isatty(int fd) { return (fd < 3) ? 1 : 0; } } #else #error no STDIO #endif // defined(ARDUINO_ARCH_PIC32) #ifdef __AVR__ // The only wierdo in the bunch... void UHS_AVR_printf_HELPER_init() { // Set up stdio/stderr tty_stdio.put = tty_std_putc; tty_stdio.get = tty_std_getc; tty_stdio.flags = _FDEV_SETUP_RW; tty_stdio.udata = 0; tty_stderr.put = tty_stderr_putc; tty_stderr.get = NULL; tty_stderr.flags = _FDEV_SETUP_WRITE; tty_stderr.udata = 0; stdout = &tty_stdio; stdin = &tty_stdio; stderr = &tty_stderr; } #define UHS_printf_HELPER_init() UHS_AVR_printf_HELPER_init() #endif #endif /* STDIO_IS_OK_TO_USE_AS_IS */ #endif /* load.... */ #ifndef UHS_printf_HELPER_init #define UHS_printf_HELPER_init() (void(0)) #endif #endif /* UHS_PRINTF_HELPER_H */
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_printf_HELPER.h
C
agpl-3.0
5,280
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if !defined(_UHS_host_h_) || defined(__PRINTHEX_H__) #error "Never include UHS_printhex.h directly; include UHS_Usb.h instead" #else #define __PRINTHEX_H__ void E_Notifyc(char c, int lvl); template <class T> void PrintHex(T val, int lvl) { int num_nybbles = sizeof (T) * 2; do { char v = 48 + (((val >> (num_nybbles - 1) * 4)) & 0x0F); if(v > 57) v += 7; E_Notifyc(v, lvl); } while(--num_nybbles); } template <class T> void PrintBin(T val, int lvl) { for(T mask = (((T)1) << ((sizeof (T) << 3) - 1)); mask; mask >>= 1) if(val & mask) E_Notifyc('1', lvl); else E_Notifyc('0', lvl); } template <class T> void SerialPrintHex(T val) { int num_nybbles = sizeof (T) * 2; do { char v = 48 + (((val >> (num_nybbles - 1) * 4)) & 0x0F); if(v > 57) v += 7; USB_HOST_SERIAL.print(v); } while(--num_nybbles); } template <class T> void PrintHex2(Print *prn, T val) { T mask = (((T)1) << (((sizeof (T) << 1) - 1) << 2)); while(mask > 1) { if(val < mask) prn->print("0"); mask >>= 4; } prn->print((T)val, HEX); } #ifdef DEBUG_USB_HOST template <class T> void D_PrintHex(T val, int lvl) { PrintHex<T > (val, lvl); #else template <class T> void D_PrintHex(NOTUSED(T val), NOTUSED(int lvl)) { #endif } #ifdef DEBUG_USB_HOST template <class T> void D_PrintBin(T val, int lvl) { PrintBin<T > (val, lvl); #else template <class T> void D_PrintBin(NOTUSED(T val), NOTUSED(int lvl)) { #endif } #endif // __PRINTHEX_H__
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_printhex.h
C++
agpl-3.0
2,684
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #ifndef UHS_SETTINGS_H #define UHS_SETTINGS_H // TO-DO: Move specific settings to modules which use them. //////////////////////////////////////////////////////////////////////////////// // Define any of these options at the top of your sketch to override // the defaults contained herewith. Do NOT do modifications here. // Individual Components have their own settings. // // Macro | Settings and notes | Default // -----------------------------+-----------------------+----------------------- // | Any class that does | // USB_HOST_SERIAL | text streaming | SERIAL_PORT_MONITOR // | e.g. Serial2 | // -----------------------------+-----------------------+----------------------- // ENABLE_UHS_DEBUGGING | 0 = off, 1 = on | 0 // -----------------------------+-----------------------+----------------------- // | 0 = off, 1 = on | // | Caution! Can make | // DEBUG_PRINTF_EXTRA_HUGE | program too large! | 0 // | Other modules depend | // | on this setting. | // -----------------------------+-----------------------+----------------------- // USE_UHS_BLACK_WIDDOW | 0 = no, 1 = yes | 0 // -----------------------------+-----------------------+----------------------- // ENABLE_WII_IR_CAMERA | 0 = no, 1 = yes | 0 // -----------------------------^-----------------------^----------------------- // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // DEBUGGING //////////////////////////////////////////////////////////////////////////////// #ifndef USB_HOST_SERIAL #if defined(SERIAL_PORT_USBVIRTUAL) && defined(LOAD_UHS_KINETIS_FS_HOST) #define USB_HOST_SERIAL SERIAL_PORT_HARDWARE #else #define USB_HOST_SERIAL SERIAL_PORT_MONITOR #endif #endif #ifndef ENABLE_UHS_DEBUGGING #define ENABLE_UHS_DEBUGGING 0 #endif #ifndef DEBUG_PRINTF_EXTRA_HUGE #define DEBUG_PRINTF_EXTRA_HUGE 0 #endif //////////////////////////////////////////////////////////////////////////////// // Manual board activation //////////////////////////////////////////////////////////////////////////////// /* Set this to 1 if you are using a Black Widdow */ #ifndef USE_UHS_BLACK_WIDDOW #define USE_UHS_BLACK_WIDDOW 0 #endif //////////////////////////////////////////////////////////////////////////////// // Wii IR camera //////////////////////////////////////////////////////////////////////////////// /* Set this to 1 to activate code for the Wii IR camera */ #ifndef ENABLE_WII_IR_CAMERA #define ENABLE_WII_IR_CAMERA 0 #endif //////////////////////////////////////////////////////////////////////////////// // Set to 1 to use the faster spi4teensy3 driver. (not used yet)) //////////////////////////////////////////////////////////////////////////////// #ifndef USE_SPI4TEENSY3 #define USE_SPI4TEENSY3 0 #endif //////////////////////////////////////////////////////////////////////////////// // AUTOMATIC Settings //////////////////////////////////////////////////////////////////////////////// // No user serviceable parts below this line. // DO NOT change anything below here unless you are a developer! #if defined(__GNUC__) && defined(__AVR__) #ifndef GCC_VERSION #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif #if GCC_VERSION < 40602 // Test for GCC < 4.6.2 #ifdef PROGMEM #undef PROGMEM #define PROGMEM __attribute__((section(".progmem.data"))) // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734#c4 #ifdef PSTR #undef PSTR #define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) // Copied from pgmspace.h in avr-libc source #endif #endif #endif #endif #if !defined(DEBUG_USB_HOST) && ENABLE_UHS_DEBUGGING #define DEBUG_USB_HOST #endif #if !defined(WIICAMERA) && ENABLE_WII_IR_CAMERA #define WIICAMERA #endif #define UHS_SLEEP_MS(v) pUsb->sof_delay(v) #ifndef UHS_NI #define UHS_NI __attribute__((noinline)) #endif #endif /* SETTINGS_H */
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_settings.h
C
agpl-3.0
5,178
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if !defined(_UHS_host_h_) || defined(_UHS_ch9_h_) #error "Never include UHS_usb_ch9.h directly; include UHS_Usb.h instead" #else /* USB chapter 9 structures */ #define _UHS_ch9_h_ /* Misc.USB constants */ #define DEV_DESCR_LEN 18 //device descriptor length #define CONF_DESCR_LEN 9 //configuration descriptor length #define INTR_DESCR_LEN 9 //interface descriptor length #define EP_DESCR_LEN 7 //endpoint descriptor length /* Standard Device Requests */ #define USB_REQUEST_GET_STATUS 0 // Standard Device Request - GET STATUS #define USB_REQUEST_CLEAR_FEATURE 1 // Standard Device Request - CLEAR FEATURE #define USB_REQUEST_SET_FEATURE 3 // Standard Device Request - SET FEATURE #define USB_REQUEST_SET_ADDRESS 5 // Standard Device Request - SET ADDRESS #define USB_REQUEST_GET_DESCRIPTOR 6 // Standard Device Request - GET DESCRIPTOR #define USB_REQUEST_SET_DESCRIPTOR 7 // Standard Device Request - SET DESCRIPTOR #define USB_REQUEST_GET_CONFIGURATION 8 // Standard Device Request - GET CONFIGURATION #define USB_REQUEST_SET_CONFIGURATION 9 // Standard Device Request - SET CONFIGURATION #define USB_REQUEST_GET_INTERFACE 10 // Standard Device Request - GET INTERFACE #define USB_REQUEST_SET_INTERFACE 11 // Standard Device Request - SET INTERFACE #define USB_REQUEST_SYNCH_FRAME 12 // Standard Device Request - SYNCH FRAME /* Wireless USB Device Requests */ #define USB_REQ_SET_ENCRYPTION 0x0D #define USB_REQ_GET_ENCRYPTION 0x0E #define USB_REQ_RPIPE_ABORT 0x0E #define USB_REQ_SET_HANDSHAKE 0x0F #define USB_REQ_RPIPE_RESET 0x0F #define USB_REQ_GET_HANDSHAKE 0x10 #define USB_REQ_SET_CONNECTION 0x11 #define USB_REQ_SET_SECURITY_DATA 0x12 #define USB_REQ_GET_SECURITY_DATA 0x13 #define USB_REQ_SET_WUSB_DATA 0x14 #define USB_REQ_LOOPBACK_DATA_WRITE 0x15 #define USB_REQ_LOOPBACK_DATA_READ 0x16 #define USB_REQ_SET_INTERFACE_DS 0x17 /* USB feature flags */ #define USB_DEVICE_SELF_POWERED 0 /* (read only) */ #define USB_DEVICE_REMOTE_WAKEUP 1 /* dev may initiate wakeup */ #define USB_DEVICE_TEST_MODE 2 /* (wired high speed only) */ #define USB_DEVICE_BATTERY 2 /* (wireless) */ #define USB_DEVICE_B_HNP_ENABLE 3 /* (otg) dev may initiate HNP */ #define USB_DEVICE_WUSB_DEVICE 3 /* (wireless)*/ #define USB_DEVICE_A_HNP_SUPPORT 4 /* (otg) RH port supports HNP */ #define USB_DEVICE_A_ALT_HNP_SUPPORT 5 /* (otg) other RH port does */ #define USB_DEVICE_DEBUG_MODE 6 /* (special devices only) */ #define USB_FEATURE_ENDPOINT_HALT 0 // CLEAR/SET FEATURE - Endpoint Halt #define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // CLEAR/SET FEATURE - Device remote wake-up #define USB_FEATURE_TEST_MODE 2 // CLEAR/SET FEATURE - Test mode /* OTG SET FEATURE Constants */ #define OTG_FEATURE_B_HNP_ENABLE 3 // SET FEATURE OTG - Enable B device to perform HNP #define OTG_FEATURE_A_HNP_SUPPORT 4 // SET FEATURE OTG - A device supports HNP #define OTG_FEATURE_A_ALT_HNP_SUPPORT 5 // SET FEATURE OTG - Another port on the A device supports HNP /* Setup Data Constants */ #define USB_SETUP_HOST_TO_DEVICE 0x00 // Device Request bmRequestType transfer direction - host to device transfer #define USB_SETUP_DEVICE_TO_HOST 0x80 // Device Request bmRequestType transfer direction - device to host transfer #define USB_SETUP_TYPE_STANDARD 0x00 // Device Request bmRequestType type - standard #define USB_SETUP_TYPE_CLASS 0x20 // Device Request bmRequestType type - class #define USB_SETUP_TYPE_VENDOR 0x40 // Device Request bmRequestType type - vendor #define USB_SETUP_RECIPIENT_DEVICE 0x00 // Device Request bmRequestType recipient - device #define USB_SETUP_RECIPIENT_INTERFACE 0x01 // Device Request bmRequestType recipient - interface #define USB_SETUP_RECIPIENT_ENDPOINT 0x02 // Device Request bmRequestType recipient - endpoint #define USB_SETUP_RECIPIENT_OTHER 0x03 // Device Request bmRequestType recipient - other #define USB_SETUP_RECIPIENT_PORT 0x04 // Wireless USB 1.0 #define USB_SETUP_RECIPIENT_RPIPE 0x05 // Wireless USB 1.0 /* USB descriptors */ #define USB_DESCRIPTOR_DEVICE 0x01 // bDescriptorType for a Device Descriptor. #define USB_DESCRIPTOR_CONFIGURATION 0x02 // bDescriptorType for a Configuration Descriptor. #define USB_DESCRIPTOR_STRING 0x03 // bDescriptorType for a String Descriptor. #define USB_DESCRIPTOR_INTERFACE 0x04 // bDescriptorType for an Interface Descriptor. #define USB_DESCRIPTOR_ENDPOINT 0x05 // bDescriptorType for an Endpoint Descriptor. #define USB_DESCRIPTOR_DEVICE_QUALIFIER 0x06 // bDescriptorType for a Device Qualifier. #define USB_DESCRIPTOR_OTHER_SPEED 0x07 // bDescriptorType for a Other Speed Configuration. #define USB_DESCRIPTOR_INTERFACE_POWER 0x08 // bDescriptorType for Interface Power. #define USB_DESCRIPTOR_OTG 0x09 // bDescriptorType for an OTG Descriptor. #define USB_DESCRIPTOR_DEBUG 0x0A #define USB_DESCRIPTOR_INTERFACE_ASSOCIATION 0x0B #define USB_DESCRIPTOR_SECURITY 0x0C #define USB_DESCRIPTOR_KEY 0x0D #define USB_DESCRIPTOR_ENCRYPTION_TYPE 0x0E #define USB_DESCRIPTOR_BOS 0x0F #define USB_DESCRIPTOR_DEVICE_CAPABILITY 0x10 #define USB_DESCRIPTOR_WIRELESS_ENDPOINT_COMP 0x11 #define USB_DESCRIPTOR_WIRE_ADAPTER 0x21 #define USB_DESCRIPTOR_RPIPE 0x22 #define USB_DESCRIPTOR_CS_RADIO_CONTROL 0x23 #define USB_DESCRIPTOR_SS_ENDPOINT_COMP 0x30 #define USB_HID_DESCRIPTOR 0x21 // Conventional codes for class-specific descriptors. "Common Class" Spec (3.11) #define USB_DESCRIPTOR_CS_DEVICE 0x21 #define USB_DESCRIPTOR_CS_CONFIG 0x22 #define USB_DESCRIPTOR_CS_STRING 0x23 #define USB_DESCRIPTOR_CS_INTERFACE 0x24 #define USB_DESCRIPTOR_CS_ENDPOINT 0x25 /* USB Endpoint Transfer Types */ #define USB_TRANSFER_TYPE_CONTROL 0x00 // Endpoint is a control endpoint. #define USB_TRANSFER_TYPE_ISOCHRONOUS 0x01 // Endpoint is an isochronous endpoint. #define USB_TRANSFER_TYPE_BULK 0x02 // Endpoint is a bulk endpoint. #define USB_TRANSFER_TYPE_INTERRUPT 0x03 // Endpoint is an interrupt endpoint. #define bmUSB_TRANSFER_TYPE 0x03 // bit mask to separate transfer type from ISO attributes #define USB_TRANSFER_DIRECTION_IN 0x80 // Indicate direction is IN /* Standard Feature Selectors for CLEAR_FEATURE Requests */ #define USB_FEATURE_ENDPOINT_STALL 0 // Endpoint recipient #define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // Device recipient #define USB_FEATURE_TEST_MODE 2 // Device recipient /* descriptor data structures */ /* Device descriptor structure */ typedef struct { uint8_t bLength; // Length of this descriptor. uint8_t bDescriptorType; // DEVICE descriptor type (USB_DESCRIPTOR_DEVICE). uint16_t bcdUSB; // USB Spec Release Number (BCD). uint8_t bDeviceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. uint8_t bDeviceSubClass; // Subclass code (assigned by the USB-IF). uint8_t bDeviceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. uint8_t bMaxPacketSize0; // Maximum packet size for endpoint 0. uint16_t idVendor; // Vendor ID (assigned by the USB-IF). uint16_t idProduct; // Product ID (assigned by the manufacturer). uint16_t bcdDevice; // Device release number (BCD). uint8_t iManufacturer; // Index of String Descriptor describing the manufacturer. uint8_t iProduct; // Index of String Descriptor describing the product. uint8_t iSerialNumber; // Index of String Descriptor with the device's serial number. uint8_t bNumConfigurations; // Number of possible configurations. } __attribute__((packed)) USB_FD_DEVICE_DESCRIPTOR; /* Configuration descriptor structure */ typedef struct { uint8_t bLength; // Length of this descriptor. uint8_t bDescriptorType; // CONFIGURATION descriptor type (USB_DESCRIPTOR_CONFIGURATION). uint16_t wTotalLength; // Total length of all descriptors for this configuration. uint8_t bNumInterfaces; // Number of interfaces in this configuration. uint8_t bConfigurationValue; // Value of this configuration (1 based). uint8_t iConfiguration; // Index of String Descriptor describing the configuration. uint8_t bmAttributes; // Configuration characteristics. uint8_t bMaxPower; // Maximum power consumed by this configuration. } __attribute__((packed)) USB_FD_CONFIGURATION_DESCRIPTOR; /* Interface descriptor structure */ typedef struct { uint8_t bLength; // Length of this descriptor. uint8_t bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE). uint8_t bInterfaceNumber; // Number of this interface (0 based). uint8_t bAlternateSetting; // Value of this alternate interface setting. uint8_t bNumEndpoints; // Number of endpoints in this interface. uint8_t bInterfaceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. uint8_t bInterfaceSubClass; // Subclass code (assigned by the USB-IF). uint8_t bInterfaceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. uint8_t iInterface; // Index of String Descriptor describing the interface. } __attribute__((packed)) USB_FD_INTERFACE_DESCRIPTOR; /* Endpoint descriptor structure */ typedef struct { uint8_t bLength; // Length of this descriptor. uint8_t bDescriptorType; // ENDPOINT descriptor type (USB_DESCRIPTOR_ENDPOINT). uint8_t bEndpointAddress; // Endpoint address. Bit 7 indicates direction (0=OUT, 1=IN). uint8_t bmAttributes; // Endpoint transfer type. uint16_t wMaxPacketSize; // Maximum packet size. uint8_t bInterval; // Polling interval in frames. } __attribute__((packed)) USB_FD_ENDPOINT_DESCRIPTOR; /* HID descriptor */ /* typedef struct { uint8_t bLength; uint8_t bDescriptorType; uint16_t bcdHID; // HID class specification release uint8_t bCountryCode; uint8_t bNumDescriptors; // Number of additional class specific descriptors uint8_t bDescrType; // Type of class descriptor uint16_t wDescriptorLength; // Total size of the Report descriptor } __attribute__((packed)) USB_HID_DESCRIPTOR; */ typedef struct { uint8_t bDescrType; // Type of class descriptor uint16_t wDescriptorLength; // Total size of the Report descriptor } __attribute__((packed)) HID_CLASS_DESCRIPTOR_LEN_AND_TYPE; #endif // _ch9_h_
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_usb_ch9.h
C
agpl-3.0
12,781
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #ifndef _UHS_host_h_ #error "Never include UHS_usbhost.h directly; include UHS_host.h instead" #else #ifndef _USBHOST_H_ #define _USBHOST_H_ // Very early prototypes #ifdef UHS_LOAD_BT void UHS_BT_SetUSBInterface(UHS_USB_HOST_BASE *host, ENUMERATION_INFO *ei); void UHS_BT_ScanUninitialized(UHS_USB_HOST_BASE *host); void UHS_BT_Poll(UHS_USB_HOST_BASE *host); #endif #ifdef UHS_LOAD_HID void UHS_HID_SetUSBInterface(UHS_USB_HOST_BASE *host, ENUMERATION_INFO *ei); void UHS_HID_ScanUninitialized(UHS_USB_HOST_BASE *host); void UHS_HID_Poll(UHS_USB_HOST_BASE *host); #endif //#if defined(LOAD_UHS_CDC_ACM) || defined(LOAD_UHS_CDC_ACM_FTDI) || defined(LOAD_UHS_CDC_ACM_PROLIFIC) || defined(LOAD_UHS_CDC_ACM_XR21B1411) //void UHS_CDC_ACM_SetUSBInterface(UHS_USB_HOST_BASE *host, ENUMERATION_INFO *ei); //void UHS_CDC_ACM_ScanUninitialized(UHS_USB_HOST_BASE *host); //void UHS_CDC_ACM_Poll(UHS_USB_HOST_BASE *host); //#endif class UHS_USBInterface; // forward class declaration // enumerator to turn the VBUS on/off typedef enum { vbus_on = 0, vbus_off = 1 } VBUS_t; // All host SEI use this base class class UHS_USB_HOST_BASE { public: AddressPool addrPool; UHS_USBInterface* devConfig[UHS_HOST_MAX_INTERFACE_DRIVERS]; volatile uint8_t usb_error; volatile uint8_t usb_task_state; volatile uint8_t usb_task_polling_disabled; volatile uint8_t usb_host_speed; volatile uint8_t hub_present; UHS_USB_HOST_BASE() { for(uint16_t i = 0; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) { devConfig[i] = NULL; } usb_task_polling_disabled = 0; usb_task_state = UHS_USB_HOST_STATE_INITIALIZE; //set up state machine usb_host_speed = 0; usb_error = 0; }; ///////////////////////////////////////////// // // Virtual methods that interface to the SIE // Overriding each is mandatory. // ///////////////////////////////////////////// /** * Delay for x milliseconds * Override if your controller provides an SOF IRQ, which may involve * some sort of reentrant ISR or workaround with interrupts enabled. * * @param x how many milliseconds to delay * @return true if delay completed without a state change, false if delay aborted */ virtual bool UHS_NI sof_delay(uint16_t x) { if(!(usb_task_state & UHS_USB_HOST_STATE_MASK)) return false; uint8_t current_state = usb_task_state; while(current_state == usb_task_state && x--) { delay(1); } return (current_state == usb_task_state); }; virtual UHS_EpInfo * UHS_NI ctrlReqOpen(NOTUSED(uint8_t addr), NOTUSED(uint64_t Request), NOTUSED(uint8_t *dataptr)) { return NULL; }; virtual void UHS_NI vbusPower(NOTUSED(VBUS_t state)) { }; virtual void UHS_NI Task() { }; virtual uint8_t UHS_NI SetAddress(NOTUSED(uint8_t addr), NOTUSED(uint8_t ep), NOTUSED(UHS_EpInfo **ppep), NOTUSED(uint16_t &nak_limit)) { return UHS_HOST_ERROR_NOT_IMPLEMENTED; }; virtual uint8_t UHS_NI OutTransfer(NOTUSED(UHS_EpInfo *pep), NOTUSED(uint16_t nak_limit), NOTUSED(uint16_t nbytes), NOTUSED(uint8_t *data)) { return UHS_HOST_ERROR_NOT_IMPLEMENTED; }; virtual uint8_t UHS_NI InTransfer(NOTUSED(UHS_EpInfo *pep), NOTUSED(uint16_t nak_limit), NOTUSED(uint16_t *nbytesptr), NOTUSED(uint8_t *data)) { return UHS_HOST_ERROR_NOT_IMPLEMENTED; }; virtual uint8_t UHS_NI ctrlReqClose(NOTUSED(UHS_EpInfo *pep), NOTUSED(uint8_t bmReqType), NOTUSED(uint16_t left), NOTUSED(uint16_t nbytes), NOTUSED(uint8_t *dataptr)) { return UHS_HOST_ERROR_NOT_IMPLEMENTED; }; virtual uint8_t UHS_NI ctrlReqRead(NOTUSED(UHS_EpInfo *pep), NOTUSED(uint16_t *left), NOTUSED(uint16_t *read), NOTUSED(uint16_t nbytes), NOTUSED(uint8_t *dataptr)) { return UHS_HOST_ERROR_NOT_IMPLEMENTED; }; virtual uint8_t UHS_NI dispatchPkt(NOTUSED(uint8_t token), NOTUSED(uint8_t ep), NOTUSED(uint16_t nak_limit)) { return UHS_HOST_ERROR_NOT_IMPLEMENTED; }; virtual uint8_t UHS_NI init() { return 0; }; virtual void UHS_NI doHostReset() { }; virtual int16_t UHS_NI Init(NOTUSED(int16_t mseconds)) { return -1; }; virtual int16_t UHS_NI Init() { return Init(INT16_MIN); }; virtual uint8_t hwlPowerUp() { /* This is for machine specific support to enable/power up the USB HW to operate*/ return UHS_HOST_ERROR_NOT_IMPLEMENTED; }; virtual uint8_t hwPowerDown() { /* This is for machine specific support to disable/powerdown the USB Hw */ return UHS_HOST_ERROR_NOT_IMPLEMENTED; }; virtual bool IsHub(uint8_t klass) { return (klass == UHS_USB_CLASS_HUB); }; virtual void UHS_NI suspend_host() { // Used on MCU that lack control of IRQ priority (AVR). // Suspends ISRs, for critical code. IRQ will be serviced after it is resumed. // NOTE: you must track the state yourself! }; virtual void UHS_NI resume_host() { // Used on MCU that lack control of IRQ priority (AVR). // Resumes ISRs. // NOTE: you must track the state yourself! }; ///////////////////////////////////////////// // // Built-ins, No need to override // ///////////////////////////////////////////// // these two probably will go away, and won't be used, TBD inline void Poll_Others() { #ifdef UHS_LOAD_BT UHS_BT_Poll(this); #endif #ifdef UHS_LOAD_HID UHS_HID_Poll(this); #endif } inline void DisablePoll() { noInterrupts(); usb_task_polling_disabled++; DDSB(); interrupts(); } inline void EnablePoll() { noInterrupts(); usb_task_polling_disabled--; DDSB(); interrupts(); } uint8_t UHS_NI seekInterface(ENUMERATION_INFO *ei, uint16_t inf, USB_FD_CONFIGURATION_DESCRIPTOR *ucd); uint8_t UHS_NI setEpInfoEntry(uint8_t addr, uint8_t iface, uint8_t epcount, volatile UHS_EpInfo* eprecord_ptr); uint8_t UHS_NI EPClearHalt(uint8_t addr, uint8_t ep); uint8_t UHS_NI ctrlReq(uint8_t addr, uint64_t Request, uint16_t nbytes, uint8_t *dataptr); uint8_t UHS_NI getDevDescr(uint8_t addr, uint16_t nbytes, uint8_t *dataptr); uint8_t UHS_NI getConfDescr(uint8_t addr, uint16_t nbytes, uint8_t conf, uint8_t *dataptr); uint8_t UHS_NI setAddr(uint8_t oldaddr, uint8_t newaddr); uint8_t UHS_NI setConf(uint8_t addr, uint8_t conf_value); uint8_t UHS_NI getStrDescr(uint8_t addr, uint16_t nbytes, uint8_t index, uint16_t langid, uint8_t *dataptr); void UHS_NI ReleaseDevice(uint8_t addr); uint8_t UHS_NI Configuring(uint8_t parent, uint8_t port, uint8_t speed); void UHS_NI DeviceDefaults(uint8_t maxep, UHS_USBInterface *device); UHS_EpInfo* UHS_NI getEpInfoEntry(uint8_t addr, uint8_t ep); inline uint8_t getUsbTaskState() { return ( usb_task_state); }; inline AddressPool* GetAddressPool() { return &addrPool; }; int UHS_NI RegisterDeviceClass(UHS_USBInterface *pdev) { for(uint8_t i = 0; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) { if(!devConfig[i]) { devConfig[i] = pdev; return i; } } //return UHS_HOST_ERROR_CANT_REGISTER_DEVICE_CLASS; return -1; }; #if 0 inline void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) { addrPool.ForEachUsbDevice(pfunc); }; #endif uint8_t TestInterface(ENUMERATION_INFO *ei); uint8_t enumerateInterface(ENUMERATION_INFO *ei); uint8_t getNextInterface(ENUMERATION_INFO *ei, UHS_EpInfo *pep, uint8_t data[], uint16_t *left, uint16_t *read, uint8_t *offset); uint8_t initDescrStream(ENUMERATION_INFO *ei, USB_FD_CONFIGURATION_DESCRIPTOR *ucd, UHS_EpInfo *pep, uint8_t *data, uint16_t *left, uint16_t *read, uint8_t *offset); uint8_t outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *data); uint8_t inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t *data); uint8_t doSoftReset(uint8_t parent, uint8_t port, uint8_t address); uint8_t getone(UHS_EpInfo *pep, uint16_t *left, uint16_t *read, uint8_t *dataptr, uint8_t *offset); uint8_t eat(UHS_EpInfo *pep, uint16_t *left, uint16_t *read, uint8_t *dataptr, uint8_t *offset, uint16_t *yum); }; // All device interface drivers use this subclass class UHS_USBInterface { public: UHS_USB_HOST_BASE *pUsb; // Parent USB host volatile uint8_t bNumEP; // total number of EP in this interface volatile UHS_EpInfo epInfo[16]; // This is a stub, override in the driver. volatile uint8_t bAddress; // address of the device volatile uint8_t bConfNum; // configuration number volatile uint8_t bIface; // interface value volatile bool bPollEnable; // poll enable flag, operating status volatile uint32_t qNextPollTime; // next poll time /** * Resets interface driver to unused state. You should override this in * your driver if it requires extra class variable cleanup. */ virtual void DriverDefaults() { printf("Default driver defaults.\r\n"); pUsb->DeviceDefaults(bNumEP, this); }; /** * Checks if this interface is supported. * Executed called when new devices are connected. * * @param ei * @return true if the interface is supported */ virtual bool OKtoEnumerate(NOTUSED(ENUMERATION_INFO *ei)) { return false; }; /** * Configures any needed endpoint information for an interface. * You must provide this in your driver. * Executed when new devices are connected and OKtoEnumerate() * returned true. * * @param ei * @return zero on success */ virtual uint8_t SetInterface(NOTUSED(ENUMERATION_INFO *ei)) { return UHS_HOST_ERROR_NOT_IMPLEMENTED; }; /** * Interface specific additional setup and enumeration that * can't occur when the descriptor stream is open. * Also used for collection of unclaimed interfaces, to link to the master. * * @return zero on success */ virtual uint8_t Finalize() { return 0; }; /** * Executed after interface is finalized but, before polling has started. * * @return 0 on success */ virtual uint8_t OnStart() { return 0; }; /** * Start interface polling * @return */ virtual uint8_t Start() { uint8_t rcode = OnStart(); if(!rcode) bPollEnable = true; return rcode; }; /** * Executed before anything else in Release(). */ virtual void OnRelease() { return; }; /** * Release resources when device is disconnected. * Normally this does not need to be overridden. */ virtual void Release() { OnRelease(); DriverDefaults(); return; }; /** * Executed After driver polls. * Can be used when there is an important change detected during polling * and you want to handle it elsewhere. * Examples: * Media status change for bulk, e.g. ready, not-ready, media changed, door opened. * Button state/joystick position/etc changes on a HID device. * Flow control status change on a communication device, e.g. CTS on serial */ virtual void OnPoll() { return; }; /** * Poll interface driver. You should override this in your driver if you * require polling faster or slower than every 100 milliseconds, or your * driver requires special housekeeping. */ virtual void Poll() { OnPoll(); qNextPollTime = millis() + 100; }; virtual bool UHS_NI Polling() { return bPollEnable; } /** * This is only for a hub. * @param port */ virtual void ResetHubPort(NOTUSED(uint8_t port)) { return; }; #if 0 /** * @return true if this interface is Vendor Specific. */ virtual bool IsVSI() { return false; } #endif }; #if 0 /** * Vendor Specific interface class. * This is used by a partner interface. * It can also be used to force-enumerate an interface that * can use this interface directly. * You can also add an instance of this class within the interface constructor * if you expect the interface. * * If this is not needed, it may be removed. Nothing I have written needs this. * Let me know if it is not required, then IsVSI method can also be shit-canned. * -- AJK */ class UHS_VSI : public UHS_USBInterface { public: volatile UHS_EpInfo epInfo[1]; volatile ENUMERATION_INFO eInfo; UHS_VSI(UHS_USB_HOST_BASE *p); bool OKtoEnumerate(ENUMERATION_INFO *ei); uint8_t SetInterface(ENUMERATION_INFO *ei); virtual void DriverDefaults(); virtual void Release(); uint8_t GetAddress() { return bAddress; }; virtual bool IsVSI() { return true; } }; #endif #endif //_USBHOST_H_ #endif
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_usbhost.h
C++
agpl-3.0
15,536
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if defined(LOAD_USB_HOST_SYSTEM) && !defined(USB_HOST_SYSTEM_UTIL_LOADED) #define USB_HOST_SYSTEM_UTIL_LOADED // 0x80 is the default (i.e. trace) to turn off set this global to something lower. // this allows for 126 other debugging levels. // TO-DO: Allow assignment to a different serial port by software int UsbDEBUGlvl = 0x80; void E_Notifyc(char c, int lvl) { if(UsbDEBUGlvl < lvl) return; #if defined(ARDUINO) && ARDUINO >=100 USB_HOST_SERIAL.print(c); #else USB_HOST_SERIAL.print(c, BYTE); #endif //USB_HOST_SERIAL.flush(); } void E_Notify(char const * msg, int lvl) { if(UsbDEBUGlvl < lvl) return; if(!msg) return; char c; while((c = pgm_read_byte(msg++))) E_Notifyc(c, lvl); } void E_NotifyStr(char const * msg, int lvl) { if(UsbDEBUGlvl < lvl) return; if(!msg) return; char c; while((c = *msg++)) E_Notifyc(c, lvl); } void E_Notify(uint8_t b, int lvl) { if(UsbDEBUGlvl < lvl) return; #if defined(ARDUINO) && ARDUINO >=100 USB_HOST_SERIAL.print(b); #else USB_HOST_SERIAL.print(b, DEC); #endif } void E_Notify(double d, int lvl) { if(UsbDEBUGlvl < lvl) return; USB_HOST_SERIAL.print(d); } #ifdef DEBUG_USB_HOST void NotifyFailGetDevDescr() { Notify(PSTR("\r\ngetDevDescr "), 0x80); } void NotifyFailSetDevTblEntry() { Notify(PSTR("\r\nsetDevTblEn "), 0x80); } void NotifyFailGetConfDescr() { Notify(PSTR("\r\ngetConf "), 0x80); } void NotifyFailSetConfDescr() { Notify(PSTR("\r\nsetConf "), 0x80); } void NotifyFailGetDevDescr(uint8_t reason) { NotifyFailGetDevDescr(); NotifyFail(reason); } void NotifyFailSetDevTblEntry(uint8_t reason) { NotifyFailSetDevTblEntry(); NotifyFail(reason); } void NotifyFailGetConfDescr(uint8_t reason) { NotifyFailGetConfDescr(); NotifyFail(reason); } void NotifyFailSetConfDescr(uint8_t reason) { NotifyFailSetConfDescr(); NotifyFail(reason); } void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID) { Notify(PSTR("\r\nUnknown Device Connected - VID: "), 0x80); D_PrintHex<uint16_t > (VID, 0x80); Notify(PSTR(" PID: "), 0x80); D_PrintHex<uint16_t > (PID, 0x80); } void NotifyFail(uint8_t rcode) { D_PrintHex<uint8_t > (rcode, 0x80); Notify(PSTR("\r\n"), 0x80); } #endif #else #error "Never include UHS_util_INLINE.h, include UHS_host.h instead" #endif
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/UHS_util_INLINE.h
C
agpl-3.0
3,438
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. This software may be distributed and modified under the terms of the GNU General Public License version 2 (GPL2) as published by the Free Software Foundation and appearing in the file GPL2.TXT included in the packaging of this file. Please note that GPL2 Section 2[b] requires that all works based on this software must also be made publicly available under the terms of the GPL2 ("Copyleft"). Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if !defined(USB_HOST_SHIELD_H) || defined(_max3421e_h_) #error "Never include UHS_max3421e.h directly; include USB_HOST_SHIELD.h instead" #else #define _max3421e_h_ /* MAX3421E register/bit names and bitmasks */ #define SE0 0 #define SE1 1 #define FSHOST 2 #define LSHOST 3 /* MAX3421E command byte format: rrrrr0wa where 'r' is register number */ // // MAX3421E Registers in HOST mode. // #define rRCVFIFO 0x08 // Receive FIFO Register #define rSNDFIFO 0x10 // Send FIFO Register #define rSUDFIFO 0x20 // Set Up Data FIFO Register #define rRCVBC 0x30 // Receive FIFO Byte Count Register #define rSNDBC 0x38 // Send FIFO Byte Count Register // USB Interrupt Request Status (USBIRQ) #define rUSBIRQ 0x68 // USB Interrupt Request Register #define bmVBUSIRQ 0x40 // Vbus Present Interrupt Request #define bmNOVBUSIRQ 0x20 // Vbus Absent Interrupt Request #define bmOSCOKIRQ 0x01 // Oscillator OK Interrupt Request // USB Interrupt Request Control (USBIEN) #define rUSBIEN 0x70 // USB Interrupt Request Enable Register #define bmVBUSIE bmVBUSIRQ // Vbus Present Interrupt Request Enable #define bmNOVBUSIE bmNOVBUSIRQ // Vbus Absent Interrupt Request Enable #define bmOSCOKIE bmOSCOKIRQ // Oscillator OK Interrupt Request Enable // (USBCTL) #define rUSBCTL 0x78 //15<<3 #define bmCHIPRES 0x20 //b5 #define bmPWRDOWN 0x10 //b4 // (CPUCTL) #define rCPUCTL 0x80 //16<<3 #define bmPULSEWID1 0x80 //b7 #define bmPULSEWID0 0x40 //b6 #define bmIE 0x01 //b0 // bmPULSEWID1 bmPULSEWID0 Pulse width // 0 0 10.6uS // 0 1 5.3uS // 1 0 2.6uS // 1 1 1.3uS #define PULSEWIDTH10_6 (0) #define PULSEWIDTH5_3 (bmPULSEWID0) #define PULSEWIDTH2_6 (bmPULSEWID1) #define PULSEWIDTH1_3 (bmPULSEWID0 | bmPULSEWID1) // (PINCTL) #define rPINCTL 0x88 //17<<3 #define bmFDUPSPI 0x10 //b4 #define bmINTLEVEL 0x08 //b3 #define bmPOSINT 0x04 //b2 #define bmGPXB 0x02 //b1 #define bmGPXA 0x01 //b0 // GPX pin selections #define GPX_OPERATE 0x00 // #define GPX_VBDET 0x01 // #define GPX_BUSACT 0x02 // #define GPX_SOF 0x03 // #define rREVISION 0x90 //18<<3 // (IOPINS1) #define rIOPINS1 0xA0 //20<<3 #define bmGPOUT0 0x01 // #define bmGPOUT1 0x02 // #define bmGPOUT2 0x04 // #define bmGPOUT3 0x08 // #define bmGPIN0 0x10 // #define bmGPIN1 0x20 // #define bmGPIN2 0x40 // #define bmGPIN3 0x80 // // (IOPINS2) #define rIOPINS2 0xA8 //21<<3 #define bmGPOUT4 0x01 // #define bmGPOUT5 0x02 // #define bmGPOUT6 0x04 // #define bmGPOUT7 0x08 // #define bmGPIN4 0x10 // #define bmGPIN5 0x20 // #define bmGPIN6 0x40 // #define bmGPIN7 0x80 // // (GPINIRQ) #define rGPINIRQ 0xB0 //22<<3 #define bmGPINIRQ0 0x01 // #define bmGPINIRQ1 0x02 // #define bmGPINIRQ2 0x04 // #define bmGPINIRQ3 0x08 // #define bmGPINIRQ4 0x10 // #define bmGPINIRQ5 0x20 // #define bmGPINIRQ6 0x40 // #define bmGPINIRQ7 0x80 // // (GPINIEN) #define rGPINIEN 0xB8 //23<<3 #define bmGPINIEN0 0x01 // #define bmGPINIEN1 0x02 // #define bmGPINIEN2 0x04 // #define bmGPINIEN3 0x08 // #define bmGPINIEN4 0x10 // #define bmGPINIEN5 0x20 // #define bmGPINIEN6 0x40 // #define bmGPINIEN7 0x80 // // (GPINPOL) #define rGPINPOL 0xC0 //24<<3 #define bmGPINPOL0 0x01 // #define bmGPINPOL1 0x02 // #define bmGPINPOL2 0x04 // #define bmGPINPOL3 0x08 // #define bmGPINPOL4 0x10 // #define bmGPINPOL5 0x20 // #define bmGPINPOL6 0x40 // #define bmGPINPOL7 0x80 // // // If any data transfer errors occur, the HXFRDNIRQ asserts, while the RCVDAVIRQ does not. // // The CPU clears the SNDBAVIRQ by writing the SNDBC register. // The CPU should never directly clear the SNDBAVIRQ bit. // Host Interrupt Request Status (HIRQ) #define rHIRQ 0xC8 // Host Interrupt Request Register #define bmBUSEVENTIRQ 0x01 // BUS Reset Done or BUS Resume Interrupt Request #define bmRWUIRQ 0x02 // Remote Wakeup Interrupt Request #define bmRCVDAVIRQ 0x04 // Receive FIFO Data Available Interrupt Request #define bmSNDBAVIRQ 0x08 // Send Buffer Available Interrupt Request #define bmSUSDNIRQ 0x10 // Suspend operation Done Interrupt Request #define bmCONDETIRQ 0x20 // Peripheral Connect/Disconnect Interrupt Request #define bmFRAMEIRQ 0x40 // Frame Generator Interrupt Request #define bmHXFRDNIRQ 0x80 // Host Transfer Done Interrupt Request // IRQs that are OK for the CPU to clear #define ICLRALLBITS (bmBUSEVENTIRQ | bmRWUIRQ | bmRCVDAVIRQ | bmSUSDNIRQ | bmCONDETIRQ | bmFRAMEIRQ | bmHXFRDNIRQ) // Host Interrupt Request Control (HIEN) #define rHIEN 0xD0 // #define bmBUSEVENTIE bmBUSEVENTIRQ // BUS Reset Done or BUS Resume Interrupt Request Enable #define bmRWUIE bmRWUIRQ // Remote Wakeup Interrupt Request Enable #define bmRCVDAVIE bmRCVDAVIRQ // Receive FIFO Data Available Interrupt Request Enable #define bmSNDBAVIE bmSNDBAVIRQ // Send Buffer Available Interrupt Request Enable #define bmSUSDNIE bmSUSDNIRQ // Suspend operation Done Interrupt Request Enable #define bmCONDETIE bmCONDETIRQ // Peripheral Connect/Disconnect Interrupt Request Enable #define bmFRAMEIE bmFRAMEIRQ // Frame Generator Interrupt Request Enable #define bmHXFRDNIE bmHXFRDNIRQ // Host Transfer Done Interrupt Request Enable // (MODE)) #define rMODE 0xD8 //27<<3 #define bmHOST 0x01 // #define bmLOWSPEED 0x02 // #define bmHUBPRE 0x04 // #define bmSOFKAENAB 0x08 // #define bmSEPIRQ 0x10 // #define bmDELAYISO 0x20 // #define bmDMPULLDN 0x40 // #define bmDPPULLDN 0x80 // #define rPERADDR 0xE0 //28<<3 // (HCTL) #define rHCTL 0xE8 //29<<3 #define bmBUSRST 0x01 // #define bmFRMRST 0x02 // #define bmSAMPLEBUS 0x04 // #define bmSIGRSM 0x08 // #define bmRCVTOG0 0x10 // #define bmRCVTOG1 0x20 // #define bmSNDTOG0 0x40 // #define bmSNDTOG1 0x80 // // Host transfer (HXFR) #define rHXFR 0xF0 //30<<3 /* Host transfer token values for writing the HXFR register (R30) */ /* OR this bit field with the endpoint number in bits 3:0 */ #define MAX3421E_tokSETUP 0x10 // HS=0, ISO=0, OUTNIN=0, SETUP=1 #define MAX3421E_tokIN 0x00 // HS=0, ISO=0, OUTNIN=0, SETUP=0 #define MAX3421E_tokOUT 0x20 // HS=0, ISO=0, OUTNIN=1, SETUP=0 #define MAX3421E_tokINHS 0x80 // HS=1, ISO=0, OUTNIN=0, SETUP=0 #define MAX3421E_tokOUTHS 0xA0 // HS=1, ISO=0, OUTNIN=1, SETUP=0 #define MAX3421E_tokISOIN 0x40 // HS=0, ISO=1, OUTNIN=0, SETUP=0 #define MAX3421E_tokISOOUT 0x60 // HS=0, ISO=1, OUTNIN=1, SETUP=0 // (HRSL) #define rHRSL 0xF8 //31<<3 #define bmRCVTOGRD 0x10 // #define bmSNDTOGRD 0x20 // #define bmKSTATUS 0x40 // #define bmJSTATUS 0x80 // #define bmSE0 0x00 //SE0 - disconnect state #define bmSE1 0xC0 //SE1 - illegal state #define MODE_FS_HOST (bmDPPULLDN|bmDMPULLDN|bmHOST|bmSOFKAENAB) #define MODE_LS_HOST (bmDPPULLDN|bmDMPULLDN|bmHOST|bmLOWSPEED|bmSOFKAENAB) #endif //_max3421e_h_
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/USB_HOST_SHIELD/UHS_max3421e.h
C
agpl-3.0
9,449
/* Copyright (C) 2015-2016 Andrew J. Kroll and Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. This software may be distributed and modified under the terms of the GNU General Public License version 2 (GPL2) as published by the Free Software Foundation and appearing in the file GPL2.TXT included in the packaging of this file. Please note that GPL2 Section 2[b] requires that all works based on this software must also be made publicly available under the terms of the GPL2 ("Copyleft"). Contact information ------------------- Circuits At Home, LTD Web : https://www.circuitsathome.com e-mail : support@circuitsathome.com */ #ifndef USB_HOST_SHIELD_H #define USB_HOST_SHIELD_H // uncomment to get 'printf' console debugging. NOT FOR UNO! //#define DEBUG_PRINTF_EXTRA_HUGE_USB_HOST_SHIELD #ifdef LOAD_USB_HOST_SHIELD #include "UHS_max3421e.h" #include <SPI.h> #ifndef SPI_HAS_TRANSACTION #error "Your SPI library installation is too old." #else #ifndef SPI_ATOMIC_VERSION #warning "Your SPI library installation lacks 'SPI_ATOMIC_VERSION'. Please complain to the maintainer." #elif SPI_ATOMIC_VERSION < 1 #error "Your SPI library installation is too old." #endif #endif #if DEBUG_PRINTF_EXTRA_HUGE #ifdef DEBUG_PRINTF_EXTRA_HUGE_USB_HOST_SHIELD #define MAX_HOST_DEBUG(...) printf_P(__VA_ARGS__) #else #define MAX_HOST_DEBUG(...) VOID0 #endif #else #define MAX_HOST_DEBUG(...) VOID0 #endif #ifndef USB_HOST_SHIELD_USE_ISR #ifdef USE_MULTIPLE_APP_API #define USB_HOST_SHIELD_USE_ISR 0 #else #define USB_HOST_SHIELD_USE_ISR 1 #endif #else #define USB_HOST_SHIELD_USE_ISR 1 #endif #if !USB_HOST_SHIELD_USE_ISR #error NOISR Polled mode _NOT SUPPORTED YET_ // // Polled defaults // #ifdef BOARD_BLACK_WIDDOW #define UHS_MAX3421E_SS_ 6 #define UHS_MAX3421E_INT_ 3 #elif defined(CORE_TEENSY) && (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)) #if EXT_RAM // Teensy++ 2.0 with XMEM2 #define UHS_MAX3421E_SS_ 20 #define UHS_MAX3421E_INT_ 7 #else #define UHS_MAX3421E_SS_ 9 #define UHS_MAX3421E_INT_ 8 #endif #define UHS_MAX3421E_SPD #elif defined(ARDUINO_AVR_ADK) #define UHS_MAX3421E_SS_ 53 #define UHS_MAX3421E_INT_ 54 #elif defined(ARDUINO_AVR_BALANDUINO) #define UHS_MAX3421E_SS_ 20 #define UHS_MAX3421E_INT_ 19 #else #define UHS_MAX3421E_SS_ 10 #define UHS_MAX3421E_INT_ 9 #endif #else #ifdef ARDUINO_ARCH_PIC32 // PIC32 only allows edge interrupts, isn't that lovely? We'll emulate it... #if CHANGE < 2 #error core too old. #endif #define IRQ_IS_EDGE 0 #ifndef digitalPinToInterrupt // great, this isn't implemented. #warning digitalPinToInterrupt is not defined, complain here https://github.com/chipKIT32/chipKIT-core/issues/114 #if defined(_BOARD_UNO_) || defined(_BOARD_UC32_) #define digitalPinToInterrupt(p) ((p) == 2 ? 1 : ((p) == 7 ? 2 : ((p) == 8 ? 3 : ((p) == 35 ? 4 : ((p) == 38 ? 0 : NOT_AN_INTERRUPT))))) #warning digitalPinToInterrupt is now defined until this is taken care of. #else #error digitalPinToInterrupt not defined for your board, complain here https://github.com/chipKIT32/chipKIT-core/issues/114 #endif #endif #else #define IRQ_IS_EDGE 0 #endif // More stupidity from our friends @ Sony... #ifdef ARDUINO_spresense_ast #ifndef NOT_AN_INTERRUPT #define NOT_AN_INTERRUPT -1 #endif #endif // SAMD uses an enum for this instead of a define. Isn't that just dandy? #if !defined(NOT_AN_INTERRUPT) && !defined(ARDUINO_ARCH_SAMD) #warning NOT_AN_INTERRUPT not defined, possible problems ahead. #warning If NOT_AN_INTERRUPT is an enum or something else, complain to UHS30 developers on github. #warning Otherwise complain to your board core developer/maintainer. #define NOT_AN_INTERRUPT -1 #endif // // Interrupt defaults. Int0 or Int1 // #ifdef BOARD_BLACK_WIDDOW #error "HELP! Please send us an email, I don't know the values for Int0 and Int1 on the Black Widow board!" #elif defined(ARDUINO_AVR_ADK) #define UHS_MAX3421E_SS_ 53 #define UHS_MAX3421E_INT_ 54 #elif defined(ARDUINO_spresense_ast) #define UHS_MAX3421E_SS_ 21 #define UHS_MAX3421E_INT_ 20 #define SPIclass SPI5 //#define UHS_MAX3421E_SPD 100000 #elif defined(CORE_TEENSY) && (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)) // TO-DO! #if EXT_RAM // Teensy++ 2.0 with XMEM2 #define UHS_MAX3421E_SS_ 20 #define UHS_MAX3421E_INT_ 7 #else #define UHS_MAX3421E_SS_ 9 #define UHS_MAX3421E_INT_ 8 #endif #elif defined(ARDUINO_AVR_BALANDUINO) #error "ISR mode is currently not supported on the Balanduino. Please set USB_HOST_SHIELD_USE_ISR to 0." #else #define UHS_MAX3421E_SS_ 10 #ifdef __AVR__ #ifdef __AVR_ATmega32U4__ #define INT_FOR_PIN2 1 #define INT_FOR_PIN3 0 #else // Everybody else??? #define INT_FOR_PIN2 0 #define INT_FOR_PIN3 1 #endif #define UHS_MAX3421E_INT_ 3 #else // Non-avr #ifdef ARDUINO_ARCH_PIC32 // UNO32 External Interrupts: // Pin 38 (INT0), Pin 2 (INT1), Pin 7 (INT2), Pin 8 (INT3), Pin 35 (INT4) #define UHS_MAX3421E_INT_ 7 #else #define UHS_MAX3421E_INT_ 9 #endif #endif #endif #endif #ifdef NO_AUTO_SPEED // Ugly details section... // MAX3421E characteristics // SPI Serial - Clock Input. An external SPI master supplies SCLK with frequencies up to 26MHz. The // logic level is referenced to the voltage on VL. Data is clocked into the SPI slave inter face on the // rising edge of SCLK. Data is clocked out of the SPI slave interface on the falling edge of SCLK. // Serial Clock (SCLK) Period 38.4ns minimum. 17ns minimum pulse width. VL >2.5V // SCLK Fall to MISO Propagation Delay 14.2ns // SCLK Fall to MOSI Propagation Delay 14.2ns // SCLK Fall to MOSI Drive 3.5ns // Theoretical deadline for reply 17.7ns // 26MHz 38.4615ns period <-- MAX3421E theoretical maximum #ifndef UHS_MAX3421E_SPD #ifdef ARDUINO_SAMD_ZERO // Zero violates spec early, needs a long setup time, or doesn't like high latency. #define UHS_MAX3421E_SPD 10000000 #elif defined(ARDUINO_ARCH_PIC32) // PIC MX 5/6/7 characteristics // 25MHZ 40ns period <-- PIC MX 5/6/7 theoretical maximum // pulse width minimum Tsclk/2ns // Trise/fall 10ns maximum. 5ns is typical but not guaranteed. // Tsetup minimum for MISO 10ns. // We are in violation by 7.7ns @ 25MHz due to latency alone. // Even reading at end of data cycle, we only have a 2.3ns window. // This is too narrow to to compensate for capacitance, trace lengths, and noise. // 17.7ns + 10ns = 27.7ns // 18MHz fits and has enough slack time to compensate for capacitance, trace lengths, and noise. // For high speeds the SMP bit is recommended too, which samples at the end instead of the middle. // 20Mhz seems to work. #define UHS_MAX3421E_SPD 20000000 #else #define UHS_MAX3421E_SPD 25000000 #endif #endif #else // We start at 25MHz, and back down until hardware can take it. // Of course, SPI library can adjust this for us too. // Why not 26MHz? Because I have not found any MCU board that // can actually go that fast without problems. // Could be a shield limitation too. #ifndef UHS_MAX3421E_SPD #define UHS_MAX3421E_SPD 25000000 #endif #endif #ifndef UHS_MAX3421E_INT #define UHS_MAX3421E_INT UHS_MAX3421E_INT_ #endif #ifndef UHS_MAX3421E_SS #define UHS_MAX3421E_SS UHS_MAX3421E_SS_ #endif // NOTE: On the max3421e the irq enable and irq bits are in the same position. // IRQs used if CPU polls #define ENIBITSPOLLED (bmCONDETIE | bmBUSEVENTIE | bmFRAMEIE) // IRQs used if CPU is interrupted #define ENIBITSISR (bmCONDETIE | bmBUSEVENTIE | bmFRAMEIE /* | bmRCVDAVIRQ | bmSNDBAVIRQ | bmHXFRDNIRQ */ ) #if !USB_HOST_SHIELD_USE_ISR #define IRQ_CHECK_MASK (ENIBITSPOLLED & ICLRALLBITS) #define IRQ_IS_EDGE 0 #else #define IRQ_CHECK_MASK (ENIBITSISR & ICLRALLBITS) #endif #if IRQ_IS_EDGE // Note: UNO32 Interrupts can only be RISING, or FALLING. // This poses an interesting problem, since we want to use a LOW level. // The MAX3421E provides for pulse width control for an IRQ. // We do need to watch the timing on this, as a second IRQ could cause // a missed IRQ, since we read the level of the line to check if the IRQ // is actually for this chip. The only other alternative is to add a capacitor // and an NPN transistor, and use two lines. We can try this first, though. // Worse case, we can ignore reading the pin for verification on UNO32. // Too bad there is no minimum low width setting. // // Single Clear First Second Clear first Clear last // IRQ Single IRQ IRQ Second active pending IRQ // | | | | | | // V V V V V V // _____ _________ _ _ _______ // |______| |______| |______| |______________| // #define IRQ_SENSE FALLING #ifdef ARDUINO_ARCH_PIC32 //#define bmPULSEWIDTH PULSEWIDTH10_6 #define bmPULSEWIDTH 0 #define bmIRQ_SENSE 0 #else #define bmPULSEWIDTH PULSEWIDTH1_3 #define bmIRQ_SENSE 0 #endif #else #ifndef IRQ_SENSE #define IRQ_SENSE LOW #endif #ifndef bmPULSEWIDTH #define bmPULSEWIDTH 0 #endif #ifndef bmIRQ_SENSE #define bmIRQ_SENSE bmINTLEVEL #endif #endif class MAX3421E_HOST : public UHS_USB_HOST_BASE #ifdef SWI_IRQ_NUM , public dyn_SWI #endif { // TO-DO: move these into the parent class. volatile uint8_t vbusState; volatile uint16_t sof_countdown; // TO-DO: pack into a struct/union and use one byte volatile bool busevent; volatile bool sofevent; volatile bool counted; volatile bool condet; volatile bool doingreset; #ifdef USB_HOST_MANUAL_POLL volatile bool frame_irq_enabled = false; bool enable_frame_irq(bool enable) { const bool prev_state = frame_irq_enabled; if(prev_state != enable) { if(enable) regWr(rHIEN, regRd(rHIEN) | bmFRAMEIE); else regWr(rHIEN, regRd(rHIEN) & ~bmFRAMEIE); frame_irq_enabled = enable; } return prev_state; } #endif public: SPISettings MAX3421E_SPI_Settings; uint8_t ss_pin; uint8_t irq_pin; // Will use the defaults UHS_MAX3421E_SS, UHS_MAX3421E_INT and speed UHS_NI MAX3421E_HOST() { sof_countdown = 0; busevent = false; doingreset = false; sofevent = false; condet = false; ss_pin = UHS_MAX3421E_SS; irq_pin = UHS_MAX3421E_INT; MAX3421E_SPI_Settings = SPISettings(UHS_MAX3421E_SPD, MSBFIRST, SPI_MODE0); hub_present = 0; }; // Will use user supplied pins, and UHS_MAX3421E_SPD UHS_NI MAX3421E_HOST(uint8_t pss, uint8_t pirq) { sof_countdown = 0; busevent = false; doingreset = false; sofevent = false; condet = false; ss_pin = pss; irq_pin = pirq; MAX3421E_SPI_Settings = SPISettings(UHS_MAX3421E_SPD, MSBFIRST, SPI_MODE0); hub_present = 0; }; // Will use user supplied pins, and speed UHS_NI MAX3421E_HOST(uint8_t pss, uint8_t pirq, uint32_t pspd) { sof_countdown = 0; doingreset = false; busevent = false; sofevent = false; condet = false; ss_pin = pss; irq_pin = pirq; MAX3421E_SPI_Settings = SPISettings(pspd, MSBFIRST, SPI_MODE0); hub_present = 0; }; virtual bool UHS_NI sof_delay(uint16_t x) { #ifdef USB_HOST_MANUAL_POLL const bool saved_irq_state = enable_frame_irq(true); #endif sof_countdown = x; while((sof_countdown != 0) && !condet) { SYSTEM_OR_SPECIAL_YIELD(); #if !USB_HOST_SHIELD_USE_ISR Task(); #endif } #ifdef USB_HOST_MANUAL_POLL enable_frame_irq(saved_irq_state); #endif // Serial.println("...Wake"); return (!condet); }; virtual UHS_EpInfo *ctrlReqOpen(uint8_t addr, uint64_t Request, uint8_t *dataptr); virtual void UHS_NI vbusPower(VBUS_t state) { regWr(rPINCTL, (bmFDUPSPI | bmIRQ_SENSE) | (uint8_t)(state)); }; void UHS_NI Task(); virtual uint8_t SetAddress(uint8_t addr, uint8_t ep, UHS_EpInfo **ppep, uint16_t &nak_limit); virtual uint8_t OutTransfer(UHS_EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data); virtual uint8_t InTransfer(UHS_EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t *data); virtual uint8_t ctrlReqClose(UHS_EpInfo *pep, uint8_t bmReqType, uint16_t left, uint16_t nbytes, uint8_t *dataptr); virtual uint8_t ctrlReqRead(UHS_EpInfo *pep, uint16_t *left, uint16_t *read, uint16_t nbytes, uint8_t *dataptr); virtual uint8_t dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit); void UHS_NI ReleaseChildren() { for(uint8_t i = 0; i < UHS_HOST_MAX_INTERFACE_DRIVERS; i++) if(devConfig[i]) devConfig[i]->Release(); hub_present = 0; }; virtual bool IsHub(uint8_t klass) { if(klass == UHS_USB_CLASS_HUB) { hub_present = bmHUBPRE; return true; } return false; }; virtual void VBUS_changed(); virtual void UHS_NI doHostReset() { #if USB_HOST_SHIELD_USE_ISR // Enable interrupts noInterrupts(); #endif doingreset = true; busevent = true; regWr(rHIRQ, bmBUSEVENTIRQ); // see data sheet. regWr(rHCTL, bmBUSRST); //issue bus reset #if USB_HOST_SHIELD_USE_ISR DDSB(); // Enable interrupts interrupts(); #endif while(busevent) { DDSB(); SYSTEM_OR_SPECIAL_YIELD(); } #endif #if USB_HOST_SHIELD_USE_ISR // Enable interrupts noInterrupts(); #endif #ifdef USB_HOST_MANUAL_POLL enable_frame_irq(true); #endif sofevent = true; #if USB_HOST_SHIELD_USE_ISR DDSB(); // Enable interrupts interrupts(); #endif // Wait for SOF while(sofevent) { } #if USB_HOST_SHIELD_USE_ISR // Enable interrupts noInterrupts(); #endif doingreset = false; #if USB_HOST_SHIELD_USE_ISR DDSB(); // Enable interrupts interrupts(); }; int16_t UHS_NI Init(int16_t mseconds); int16_t UHS_NI Init() { return Init(INT16_MIN); }; void ISRTask(); void ISRbottom(); void busprobe(); uint16_t reset(); // MAX3421e specific void regWr(uint8_t reg, uint8_t data); void gpioWr(uint8_t data); uint8_t regRd(uint8_t reg); uint8_t gpioRd(); uint8_t* bytesWr(uint8_t reg, uint8_t nbytes, uint8_t *data_p); uint8_t* bytesRd(uint8_t reg, uint8_t nbytes, uint8_t *data_p); // ARM/NVIC specific, used to emulate reentrant ISR. #ifdef SWI_IRQ_NUM void dyn_SWISR() { ISRbottom(); }; #endif virtual void UHS_NI suspend_host() { // Used on MCU that lack control of IRQ priority (AVR). // Suspends ISRs, for critical code. IRQ will be serviced after it is resumed. // NOTE: you must track the state yourself! #ifdef __AVR__ noInterrupts(); detachInterrupt(UHS_GET_DPI(irq_pin)); interrupts(); #endif }; virtual void UHS_NI resume_host(); }; #ifndef SPIclass #define SPIclass SPI #endif #ifndef USB_HOST_SHIELD_LOADED #include "USB_HOST_SHIELD_INLINE.h" #endif #else #error "define LOAD_USB_HOST_SHIELD in your sketch, never include USB_HOST_SHIELD.h in a driver." #endif #endif /* USB_HOST_SHIELD_H */
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/USB_HOST_SHIELD/USB_HOST_SHIELD.h
C++
agpl-3.0
16,486
/* * Copyright (C) 2015-2016 Andrew J. Kroll * and * Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. * * This software may be distributed and modified under the terms of the GNU * General Public License version 2 (GPL2) as publishe7d by the Free Software * Foundation and appearing in the file GPL2.TXT included in the packaging of * this file. Please note that GPL2 Section 2[b] requires that all works based * on this software must also be made publicly available under the terms of * the GPL2 ("Copyleft"). * * Contact information * ------------------- * * Circuits At Home, LTD * Web : https://www.circuitsathome.com * e-mail : support@circuitsathome.com * */ #if defined(USB_HOST_SHIELD_H) && !defined(USB_HOST_SHIELD_LOADED) #define USB_HOST_SHIELD_LOADED #include <Arduino.h> #ifndef digitalPinToInterrupt #error digitalPinToInterrupt not defined, complain to your board maintainer. #endif #if USB_HOST_SHIELD_USE_ISR // allow two slots. this makes the maximum allowed shield count TWO // for AVRs this is limited to pins 2 and 3 ONLY // for all other boards, one odd and one even pin number is allowed. static MAX3421E_HOST *ISReven; static MAX3421E_HOST *ISRodd; static void UHS_NI call_ISReven() { ISReven->ISRTask(); } static void UHS_NI call_ISRodd() { UHS_PIN_WRITE(LED_BUILTIN, HIGH); ISRodd->ISRTask(); } #endif void UHS_NI MAX3421E_HOST::resume_host() { // Used on MCU that lack control of IRQ priority (AVR). // Resumes ISRs. // NOTE: you must track the state yourself! #ifdef __AVR__ noInterrupts(); if (irq_pin & 1) { ISRodd = this; attachInterrupt(UHS_GET_DPI(irq_pin), call_ISRodd, IRQ_SENSE); } else { ISReven = this; attachInterrupt(UHS_GET_DPI(irq_pin), call_ISReven, IRQ_SENSE); } interrupts(); #endif } /* write single byte into MAX3421e register */ void UHS_NI MAX3421E_HOST::regWr(uint8_t reg, uint8_t data) { SPIclass.beginTransaction(MAX3421E_SPI_Settings); MARLIN_UHS_WRITE_SS(LOW); SPIclass.transfer(reg | 0x02); SPIclass.transfer(data); MARLIN_UHS_WRITE_SS(HIGH); SPIclass.endTransaction(); } /* multiple-byte write */ /* returns a pointer to memory position after last written */ uint8_t* UHS_NI MAX3421E_HOST::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t *data_p) { SPIclass.beginTransaction(MAX3421E_SPI_Settings); MARLIN_UHS_WRITE_SS(LOW); SPIclass.transfer(reg | 0x02); //printf("%2.2x :", reg); while (nbytes) { SPIclass.transfer(*data_p); //printf("%2.2x ", *data_p); nbytes--; data_p++; // advance data pointer } MARLIN_UHS_WRITE_SS(HIGH); SPIclass.endTransaction(); //printf("\r\n"); return (data_p); } /* GPIO write */ /*GPIO byte is split between 2 registers, so two writes are needed to write one byte */ /* GPOUT bits are in the low nybble. 0-3 in IOPINS1, 4-7 in IOPINS2 */ void UHS_NI MAX3421E_HOST::gpioWr(uint8_t data) { regWr(rIOPINS1, data); data >>= 4; regWr(rIOPINS2, data); return; } /* single host register read */ uint8_t UHS_NI MAX3421E_HOST::regRd(uint8_t reg) { SPIclass.beginTransaction(MAX3421E_SPI_Settings); MARLIN_UHS_WRITE_SS(LOW); SPIclass.transfer(reg); uint8_t rv = SPIclass.transfer(0); MARLIN_UHS_WRITE_SS(HIGH); SPIclass.endTransaction(); return (rv); } /* multiple-byte register read */ /* returns a pointer to a memory position after last read */ uint8_t* UHS_NI MAX3421E_HOST::bytesRd(uint8_t reg, uint8_t nbytes, uint8_t *data_p) { SPIclass.beginTransaction(MAX3421E_SPI_Settings); MARLIN_UHS_WRITE_SS(LOW); SPIclass.transfer(reg); while (nbytes) { *data_p++ = SPIclass.transfer(0); nbytes--; } MARLIN_UHS_WRITE_SS(HIGH); SPIclass.endTransaction(); return ( data_p); } /* GPIO read. See gpioWr for explanation */ /* GPIN pins are in high nybbles of IOPINS1, IOPINS2 */ uint8_t UHS_NI MAX3421E_HOST::gpioRd() { uint8_t gpin = 0; gpin = regRd(rIOPINS2); // pins 4-7 gpin &= 0xF0; // clean lower nybble gpin |= (regRd(rIOPINS1) >> 4); // shift low bits and OR with upper from previous operation. return (gpin); } /* reset MAX3421E. Returns number of microseconds it took for PLL to stabilize after reset or zero if PLL haven't stabilized in 65535 cycles */ uint16_t UHS_NI MAX3421E_HOST::reset() { uint16_t i = 0; // Initiate chip reset regWr(rUSBCTL, bmCHIPRES); regWr(rUSBCTL, 0x00); int32_t now; uint32_t expires = micros() + 65535; // Enable full-duplex SPI so we can read rUSBIRQ regWr(rPINCTL, bmFDUPSPI); while ((int32_t)(micros() - expires) < 0L) { if ((regRd(rUSBIRQ) & bmOSCOKIRQ)) { break; } } now = (int32_t)(micros() - expires); if (now < 0L) { i = 65535 + now; // Note this subtracts, as now is negative } return (i); } void UHS_NI MAX3421E_HOST::VBUS_changed() { /* modify USB task state because Vbus changed or unknown */ uint8_t speed = 1; //printf("\r\n\r\n\r\n\r\nSTATE %2.2x -> ", usb_task_state); switch (vbusState) { case LSHOST: // Low speed speed = 0; // Intentional fall-through case FSHOST: // Full speed // Start device initialization if we are not initializing // Resets to the device cause an IRQ // usb_task_state == UHS_USB_HOST_STATE_RESET_NOT_COMPLETE; //if ((usb_task_state & UHS_USB_HOST_STATE_MASK) != UHS_USB_HOST_STATE_DETACHED) { ReleaseChildren(); if (!doingreset) { if (usb_task_state == UHS_USB_HOST_STATE_RESET_NOT_COMPLETE) { usb_task_state = UHS_USB_HOST_STATE_WAIT_BUS_READY; } else if (usb_task_state != UHS_USB_HOST_STATE_WAIT_BUS_READY) { usb_task_state = UHS_USB_HOST_STATE_DEBOUNCE; } } sof_countdown = 0; break; case SE1: // illegal state sof_countdown = 0; doingreset = false; ReleaseChildren(); usb_task_state = UHS_USB_HOST_STATE_ILLEGAL; break; case SE0: // disconnected default: sof_countdown = 0; doingreset = false; ReleaseChildren(); usb_task_state = UHS_USB_HOST_STATE_IDLE; break; } usb_host_speed = speed; //printf("0x%2.2x\r\n\r\n\r\n\r\n", usb_task_state); return; } /** * Probe bus to determine device presence and speed, * then switch host to detected speed. */ void UHS_NI MAX3421E_HOST::busprobe() { uint8_t bus_sample; uint8_t tmpdata; bus_sample = regRd(rHRSL); // Get J,K status bus_sample &= (bmJSTATUS | bmKSTATUS); // zero the rest of the byte switch (bus_sample) { // start full-speed or low-speed host case bmJSTATUS: // Serial.println("J"); if ((regRd(rMODE) & bmLOWSPEED) == 0) { regWr(rMODE, MODE_FS_HOST); // start full-speed host vbusState = FSHOST; } else { regWr(rMODE, MODE_LS_HOST); // start low-speed host vbusState = LSHOST; } #ifdef USB_HOST_MANUAL_POLL enable_frame_irq(true); #endif tmpdata = regRd(rMODE) | bmSOFKAENAB; // start SOF generation regWr(rHIRQ, bmFRAMEIRQ); // see data sheet. regWr(rMODE, tmpdata); break; case bmKSTATUS: // Serial.println("K"); if ((regRd(rMODE) & bmLOWSPEED) == 0) { regWr(rMODE, MODE_LS_HOST); // start low-speed host vbusState = LSHOST; } else { regWr(rMODE, MODE_FS_HOST); // start full-speed host vbusState = FSHOST; } #ifdef USB_HOST_MANUAL_POLL enable_frame_irq(true); #endif tmpdata = regRd(rMODE) | bmSOFKAENAB; // start SOF generation regWr(rHIRQ, bmFRAMEIRQ); // see data sheet. regWr(rMODE, tmpdata); break; case bmSE1: // illegal state // Serial.println("I"); regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST); vbusState = SE1; // sofevent = false; break; case bmSE0: // disconnected state // Serial.println("D"); regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST); vbusState = SE0; // sofevent = false; break; } // end switch ( bus_sample ) } /** * Initialize USB hardware, turn on VBUS * * @param mseconds Delay energizing VBUS after mseconds, A value of INT16_MIN means no delay. * @return 0 on success, -1 on error */ int16_t UHS_NI MAX3421E_HOST::Init(int16_t mseconds) { usb_task_state = UHS_USB_HOST_STATE_INITIALIZE; //set up state machine //Serial.print("MAX3421E 'this' USB Host @ 0x"); //Serial.println((uint32_t)this, HEX); //Serial.print("MAX3421E 'this' USB Host Address Pool @ 0x"); //Serial.println((uint32_t)GetAddressPool(), HEX); Init_dyn_SWI(); UHS_printf_HELPER_init(); noInterrupts(); #ifdef ARDUINO_AVR_ADK // For Mega ADK, which has a Max3421e on-board, // set MAX_RESET to output mode, and then set it to HIGH // PORTJ bit 2 if (irq_pin == 54) { DDRJ |= 0x04; // output PORTJ |= 0x04; // HIGH } #endif SPIclass.begin(); #ifdef ARDUINO_AVR_ADK if (irq_pin == 54) { DDRE &= ~0x20; // input PORTE |= 0x20; // pullup } else #endif pinMode(irq_pin, INPUT_PULLUP); //UHS_PIN_WRITE(irq_pin, HIGH); pinMode(ss_pin, OUTPUT); MARLIN_UHS_WRITE_SS(HIGH); #ifdef USB_HOST_SHIELD_TIMING_PIN pinMode(USB_HOST_SHIELD_TIMING_PIN, OUTPUT); // My counter/timer can't work on an inverted gate signal // so we gate using a high pulse -- AJK UHS_PIN_WRITE(USB_HOST_SHIELD_TIMING_PIN, LOW); #endif interrupts(); #if USB_HOST_SHIELD_USE_ISR int intr = digitalPinToInterrupt(irq_pin); if (intr == NOT_AN_INTERRUPT) { #ifdef ARDUINO_AVR_ADK if (irq_pin == 54) intr = 6; else #endif return (-2); } SPIclass.usingInterrupt(intr); #else SPIclass.usingInterrupt(255); #endif #ifndef NO_AUTO_SPEED // test to get to reset acceptance. uint32_t spd = UHS_MAX3421E_SPD; again: MAX3421E_SPI_Settings = SPISettings(spd, MSBFIRST, SPI_MODE0); if (reset() == 0) { MAX_HOST_DEBUG(PSTR("Fail SPI speed %lu\r\n"), spd); if (spd > 1999999) { spd -= 1000000; goto again; } return (-1); } else { // reset passes, does 64k? uint8_t sample_wr = 0; uint8_t sample_rd = 0; uint8_t gpinpol_copy = regRd(rGPINPOL); for (uint16_t j = 0; j < 65535; j++) { regWr(rGPINPOL, sample_wr); sample_rd = regRd(rGPINPOL); if (sample_rd != sample_wr) { MAX_HOST_DEBUG(PSTR("Fail SPI speed %lu\r\n"), spd); if (spd > 1999999) { spd -= 1000000; goto again; } return (-1); } sample_wr++; } regWr(rGPINPOL, gpinpol_copy); } MAX_HOST_DEBUG(PSTR("Pass SPI speed %lu\r\n"), spd); #endif if (reset() == 0) { // OSCOKIRQ hasn't asserted in time MAX_HOST_DEBUG(PSTR("OSCOKIRQ hasn't asserted in time")); return ( -1); } /* MAX3421E - full-duplex SPI, interrupt kind, vbus off */ regWr(rPINCTL, (bmFDUPSPI | bmIRQ_SENSE | GPX_VBDET)); // Delay a minimum of 1 second to ensure any capacitors are drained. // 1 second is required to make sure we do not smoke a Microdrive! if (mseconds != INT16_MIN) { if (mseconds < 1000) mseconds = 1000; delay(mseconds); // We can't depend on SOF timer here. } regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST); // set pull-downs, Host // Enable interrupts on the MAX3421e regWr(rHIEN, IRQ_CHECK_MASK); // Enable interrupt pin on the MAX3421e, set pulse width for edge regWr(rCPUCTL, (bmIE | bmPULSEWIDTH)); /* check if device is connected */ regWr(rHCTL, bmSAMPLEBUS); // sample USB bus while (!(regRd(rHCTL) & bmSAMPLEBUS)); // wait for sample operation to finish busprobe(); // check if anything is connected VBUS_changed(); // GPX pin on. This is done here so that a change is detected if we have a switch connected. /* MAX3421E - full-duplex SPI, interrupt kind, vbus on */ regWr(rPINCTL, (bmFDUPSPI | bmIRQ_SENSE)); regWr(rHIRQ, bmBUSEVENTIRQ); // see data sheet. regWr(rHCTL, bmBUSRST); // issue bus reset to force generate yet another possible IRQ #if USB_HOST_SHIELD_USE_ISR // Attach ISR to service IRQ from MAX3421e noInterrupts(); if (irq_pin & 1) { ISRodd = this; attachInterrupt(UHS_GET_DPI(irq_pin), call_ISRodd, IRQ_SENSE); } else { ISReven = this; attachInterrupt(UHS_GET_DPI(irq_pin), call_ISReven, IRQ_SENSE); } interrupts(); #endif //printf("\r\nrPINCTL 0x%2.2X\r\n", rPINCTL); //printf("rCPUCTL 0x%2.2X\r\n", rCPUCTL); //printf("rHIEN 0x%2.2X\r\n", rHIEN); //printf("irq_pin %i\r\n", irq_pin); return 0; } /** * Setup UHS_EpInfo structure * * @param addr USB device address * @param ep Endpoint * @param ppep pointer to the pointer to a valid UHS_EpInfo structure * @param nak_limit how many NAKs before aborting * @return 0 on success */ uint8_t UHS_NI MAX3421E_HOST::SetAddress(uint8_t addr, uint8_t ep, UHS_EpInfo **ppep, uint16_t &nak_limit) { UHS_Device *p = addrPool.GetUsbDevicePtr(addr); if (!p) return UHS_HOST_ERROR_NO_ADDRESS_IN_POOL; if (!p->epinfo) return UHS_HOST_ERROR_NULL_EPINFO; *ppep = getEpInfoEntry(addr, ep); if (!*ppep) return UHS_HOST_ERROR_NO_ENDPOINT_IN_TABLE; nak_limit = (0x0001UL << (((*ppep)->bmNakPower > UHS_USB_NAK_MAX_POWER) ? UHS_USB_NAK_MAX_POWER : (*ppep)->bmNakPower)); nak_limit--; /* USBTRACE2("\r\nAddress: ", addr); USBTRACE2(" EP: ", ep); USBTRACE2(" NAK Power: ",(*ppep)->bmNakPower); USBTRACE2(" NAK Limit: ", nak_limit); USBTRACE("\r\n"); */ regWr(rPERADDR, addr); // set peripheral address uint8_t mode = regRd(rMODE); //Serial.print("\r\nMode: "); //Serial.println( mode, HEX); //Serial.print("\r\nLS: "); //Serial.println(p->speed, HEX); // Set bmLOWSPEED and bmHUBPRE in case of low-speed device, reset them otherwise regWr(rMODE, (p->speed) ? mode & ~(bmHUBPRE | bmLOWSPEED) : mode | bmLOWSPEED | hub_present); return 0; } /** * Receive a packet * * @param pep pointer to a valid UHS_EpInfo structure * @param nak_limit how many NAKs before aborting * @param nbytesptr pointer to maximum number of bytes of data to receive * @param data pointer to data buffer * @return 0 on success */ uint8_t UHS_NI MAX3421E_HOST::InTransfer(UHS_EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t *data) { uint8_t rcode = 0; uint8_t pktsize; uint16_t nbytes = *nbytesptr; MAX_HOST_DEBUG(PSTR("Requesting %i bytes "), nbytes); uint8_t maxpktsize = pep->maxPktSize; *nbytesptr = 0; regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); // set toggle value // use a 'break' to exit this loop while (1) { rcode = dispatchPkt(MAX3421E_tokIN, pep->epAddr, nak_limit); // IN packet to EP-'endpoint'. Function takes care of NAKS. #if 0 // This issue should be resolved now. if (rcode == UHS_HOST_ERROR_TOGERR) { //MAX_HOST_DEBUG(PSTR("toggle wrong\r\n")); // yes, we flip it wrong here so that next time it is actually correct! pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); // set toggle value continue; } #endif if (rcode) { //MAX_HOST_DEBUG(PSTR(">>>>>>>> Problem! dispatchPkt %2.2x\r\n"), rcode); break; // should be 0, indicating ACK. Else return error code. } /* check for RCVDAVIRQ and generate error if not present */ /* the only case when absence of RCVDAVIRQ makes sense is when toggle error occurred. Need to add handling for that */ if ((regRd(rHIRQ) & bmRCVDAVIRQ) == 0) { //MAX_HOST_DEBUG(PSTR(">>>>>>>> Problem! NO RCVDAVIRQ!\r\n")); rcode = 0xF0; // receive error break; } pktsize = regRd(rRCVBC); // number of received bytes MAX_HOST_DEBUG(PSTR("Got %i bytes \r\n"), pktsize); if (pktsize > nbytes) { // certain devices send more than asked //MAX_HOST_DEBUG(PSTR(">>>>>>>> Warning: wanted %i bytes but got %i.\r\n"), nbytes, pktsize); pktsize = nbytes; } int16_t mem_left = (int16_t)nbytes - *((int16_t*)nbytesptr); if (mem_left < 0) mem_left = 0; data = bytesRd(rRCVFIFO, ((pktsize > mem_left) ? mem_left : pktsize), data); regWr(rHIRQ, bmRCVDAVIRQ); // Clear the IRQ & free the buffer *nbytesptr += pktsize; // add this packet's byte count to total transfer length /* The transfer is complete under two conditions: */ /* 1. The device sent a short packet (L.T. maxPacketSize) */ /* 2. 'nbytes' have been transferred. */ if ((pktsize < maxpktsize) || (*nbytesptr >= nbytes)) { // have we transferred 'nbytes' bytes? // Save toggle value pep->bmRcvToggle = ((regRd(rHRSL) & bmRCVTOGRD)) ? 1 : 0; //MAX_HOST_DEBUG(PSTR("\r\n")); rcode = 0; break; } // if } // while( 1 ) return (rcode); } /** * Transmit a packet * * @param pep pointer to a valid UHS_EpInfo structure * @param nak_limit how many NAKs before aborting * @param nbytes number of bytes of data to send * @param data pointer to data buffer * @return 0 on success */ uint8_t UHS_NI MAX3421E_HOST::OutTransfer(UHS_EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data) { uint8_t rcode = UHS_HOST_ERROR_NONE; uint8_t retry_count; uint8_t *data_p = data; // local copy of the data pointer uint16_t bytes_tosend; uint16_t nak_count; uint16_t bytes_left = nbytes; uint8_t maxpktsize = pep->maxPktSize; if (maxpktsize < 1 || maxpktsize > 64) return UHS_HOST_ERROR_BAD_MAX_PACKET_SIZE; unsigned long timeout = millis() + UHS_HOST_TRANSFER_MAX_MS; regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); // set toggle value while (bytes_left) { SYSTEM_OR_SPECIAL_YIELD(); retry_count = 0; nak_count = 0; bytes_tosend = (bytes_left >= maxpktsize) ? maxpktsize : bytes_left; bytesWr(rSNDFIFO, bytes_tosend, data_p); // filling output FIFO regWr(rSNDBC, bytes_tosend); // set number of bytes regWr(rHXFR, (MAX3421E_tokOUT | pep->epAddr)); // dispatch packet while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); // wait for the completion IRQ regWr(rHIRQ, bmHXFRDNIRQ); // clear IRQ rcode = (regRd(rHRSL) & 0x0F); while (rcode && ((long)(millis() - timeout) < 0L)) { switch (rcode) { case UHS_HOST_ERROR_NAK: nak_count++; if (nak_limit && (nak_count == nak_limit)) goto breakout; break; case UHS_HOST_ERROR_TIMEOUT: retry_count++; if (retry_count == UHS_HOST_TRANSFER_RETRY_MAXIMUM) goto breakout; break; case UHS_HOST_ERROR_TOGERR: // yes, we flip it wrong here so that next time it is actually correct! pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); // set toggle value break; default: goto breakout; } // switch (rcode /* process NAK according to Host out NAK bug */ regWr(rSNDBC, 0); regWr(rSNDFIFO, *data_p); regWr(rSNDBC, bytes_tosend); regWr(rHXFR, (MAX3421E_tokOUT | pep->epAddr)); // dispatch packet while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); // wait for the completion IRQ regWr(rHIRQ, bmHXFRDNIRQ); // clear IRQ rcode = (regRd(rHRSL) & 0x0F); SYSTEM_OR_SPECIAL_YIELD(); } // while (rcode && .... bytes_left -= bytes_tosend; data_p += bytes_tosend; } // while (bytes_left... breakout: pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 1 : 0; // bmSNDTOG1 : bmSNDTOG0; // update toggle return (rcode); // should be 0 in all cases } /** * Send the actual packet. * * @param token * @param ep Endpoint * @param nak_limit how many NAKs before aborting, 0 == exit after timeout * @return 0 on success, 0xFF indicates NAK timeout. @see */ /* Assumes peripheral address is set and relevant buffer is loaded/empty */ /* If NAK, tries to re-send up to nak_limit times */ /* If nak_limit == 0, do not count NAKs, exit after timeout */ /* If bus timeout, re-sends up to USB_RETRY_LIMIT times */ /* return codes 0x00-0x0F are HRSLT( 0x00 being success ), 0xFF means timeout */ uint8_t UHS_NI MAX3421E_HOST::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) { unsigned long timeout = millis() + UHS_HOST_TRANSFER_MAX_MS; uint8_t tmpdata; uint8_t rcode = UHS_HOST_ERROR_NONE; uint8_t retry_count = 0; uint16_t nak_count = 0; for (;;) { regWr(rHXFR, (token | ep)); // launch the transfer while (long(millis() - timeout) < 0L) { // wait for transfer completion SYSTEM_OR_SPECIAL_YIELD(); tmpdata = regRd(rHIRQ); if (tmpdata & bmHXFRDNIRQ) { regWr(rHIRQ, bmHXFRDNIRQ); // clear the interrupt //rcode = 0x00; break; } // if (tmpdata & bmHXFRDNIRQ } // while (millis() < timeout rcode = (regRd(rHRSL) & 0x0F); // analyze transfer result switch (rcode) { case UHS_HOST_ERROR_NAK: nak_count++; if (nak_limit && (nak_count == nak_limit)) return (rcode); delayMicroseconds(200); break; case UHS_HOST_ERROR_TIMEOUT: retry_count++; if (retry_count == UHS_HOST_TRANSFER_RETRY_MAXIMUM) return (rcode); break; default: return (rcode); } // switch (rcode) } } // // NULL is error, we don't need to know the reason. // UHS_EpInfo * UHS_NI MAX3421E_HOST::ctrlReqOpen(uint8_t addr, uint64_t Request, uint8_t *dataptr) { uint8_t rcode; UHS_EpInfo *pep = NULL; uint16_t nak_limit = 0; rcode = SetAddress(addr, 0, &pep, nak_limit); if (!rcode) { bytesWr(rSUDFIFO, 8, (uint8_t*)(&Request)); // transfer to setup packet FIFO rcode = dispatchPkt(MAX3421E_tokSETUP, 0, nak_limit); // dispatch packet if (!rcode) { if (dataptr != NULL) { if (((Request)/* bmReqType*/ & 0x80) == 0x80) { pep->bmRcvToggle = 1; //bmRCVTOG1; } else { pep->bmSndToggle = 1; //bmSNDTOG1; } } } else { pep = NULL; } } return pep; } uint8_t UHS_NI MAX3421E_HOST::ctrlReqRead(UHS_EpInfo *pep, uint16_t *left, uint16_t *read, uint16_t nbytes, uint8_t *dataptr) { *read = 0; uint16_t nak_limit = 0; MAX_HOST_DEBUG(PSTR("ctrlReqRead left: %i\r\n"), *left); if (*left) { again: *read = nbytes; uint8_t rcode = InTransfer(pep, nak_limit, read, dataptr); if (rcode == UHS_HOST_ERROR_TOGERR) { // yes, we flip it wrong here so that next time it is actually correct! pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; goto again; } if (rcode) { MAX_HOST_DEBUG(PSTR("ctrlReqRead ERROR: %2.2x, left: %i, read %i\r\n"), rcode, *left, *read); return rcode; } *left -= *read; MAX_HOST_DEBUG(PSTR("ctrlReqRead left: %i, read %i\r\n"), *left, *read); } return 0; } uint8_t UHS_NI MAX3421E_HOST::ctrlReqClose(UHS_EpInfo *pep, uint8_t bmReqType, uint16_t left, uint16_t nbytes, uint8_t *dataptr) { uint8_t rcode = 0; //MAX_HOST_DEBUG(PSTR("Closing")); if (((bmReqType & 0x80) == 0x80) && pep && left && dataptr) { MAX_HOST_DEBUG(PSTR("ctrlReqRead Sinking %i\r\n"), left); // If reading, sink the rest of the data. while (left) { uint16_t read = nbytes; rcode = InTransfer(pep, 0, &read, dataptr); if (rcode == UHS_HOST_ERROR_TOGERR) { // yes, we flip it wrong here so that next time it is actually correct! pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; continue; } if (rcode) break; left -= read; if (read < nbytes) break; } } if (!rcode) { //Serial.println("Dispatching"); rcode = dispatchPkt(((bmReqType & 0x80) == 0x80) ? MAX3421E_tokOUTHS : MAX3421E_tokINHS, 0, 0); //GET if direction //} else { //Serial.println("Bypassed Dispatch"); } return rcode; } /** * Bottom half of the ISR task */ void UHS_NI MAX3421E_HOST::ISRbottom() { uint8_t x; // Serial.print("Enter "); // Serial.print((uint32_t)this,HEX); // Serial.print(" "); // Serial.println(usb_task_state, HEX); DDSB(); if (condet) { VBUS_changed(); #if USB_HOST_SHIELD_USE_ISR noInterrupts(); #endif condet = false; #if USB_HOST_SHIELD_USE_ISR interrupts(); #endif } switch (usb_task_state) { case UHS_USB_HOST_STATE_INITIALIZE: // should never happen... MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_INITIALIZE\r\n")); busprobe(); VBUS_changed(); break; case UHS_USB_HOST_STATE_DEBOUNCE: MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_DEBOUNCE\r\n")); // This seems to not be needed. The host controller has debounce built in. sof_countdown = UHS_HOST_DEBOUNCE_DELAY_MS; usb_task_state = UHS_USB_HOST_STATE_DEBOUNCE_NOT_COMPLETE; break; case UHS_USB_HOST_STATE_DEBOUNCE_NOT_COMPLETE: MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_DEBOUNCE_NOT_COMPLETE\r\n")); if (!sof_countdown) usb_task_state = UHS_USB_HOST_STATE_RESET_DEVICE; break; case UHS_USB_HOST_STATE_RESET_DEVICE: MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_RESET_DEVICE\r\n")); busevent = true; usb_task_state = UHS_USB_HOST_STATE_RESET_NOT_COMPLETE; regWr(rHIRQ, bmBUSEVENTIRQ); // see data sheet. regWr(rHCTL, bmBUSRST); // issue bus reset break; case UHS_USB_HOST_STATE_RESET_NOT_COMPLETE: MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_RESET_NOT_COMPLETE\r\n")); if (!busevent) usb_task_state = UHS_USB_HOST_STATE_WAIT_BUS_READY; break; case UHS_USB_HOST_STATE_WAIT_BUS_READY: MAX_HOST_DEBUG(PSTR("UHS_USB_HOST_STATE_WAIT_BUS_READY\r\n")); usb_task_state = UHS_USB_HOST_STATE_CONFIGURING; break; // don't fall through case UHS_USB_HOST_STATE_CONFIGURING: usb_task_state = UHS_USB_HOST_STATE_CHECK; x = Configuring(0, 1, usb_host_speed); usb_error = x; if (usb_task_state == UHS_USB_HOST_STATE_CHECK) { if (x) { MAX_HOST_DEBUG(PSTR("Error 0x%2.2x"), x); if (x == UHS_HOST_ERROR_JERR) { usb_task_state = UHS_USB_HOST_STATE_IDLE; } else if (x != UHS_HOST_ERROR_DEVICE_INIT_INCOMPLETE) { usb_error = x; usb_task_state = UHS_USB_HOST_STATE_ERROR; } } else usb_task_state = UHS_USB_HOST_STATE_CONFIGURING_DONE; } break; case UHS_USB_HOST_STATE_CHECK: // Serial.println((uint32_t)__builtin_return_address(0), HEX); break; case UHS_USB_HOST_STATE_CONFIGURING_DONE: usb_task_state = UHS_USB_HOST_STATE_RUNNING; break; #ifdef USB_HOST_MANUAL_POLL case UHS_USB_HOST_STATE_RUNNING: case UHS_USB_HOST_STATE_ERROR: case UHS_USB_HOST_STATE_IDLE: case UHS_USB_HOST_STATE_ILLEGAL: enable_frame_irq(false); break; #else case UHS_USB_HOST_STATE_RUNNING: Poll_Others(); for (x = 0; (usb_task_state == UHS_USB_HOST_STATE_RUNNING) && (x < UHS_HOST_MAX_INTERFACE_DRIVERS); x++) { if (devConfig[x]) { if (devConfig[x]->bPollEnable) devConfig[x]->Poll(); } } // fall thru #endif default: // Do nothing break; } // switch ( usb_task_state ) DDSB(); #if USB_HOST_SHIELD_USE_ISR if (condet) { VBUS_changed(); noInterrupts(); condet = false; interrupts(); } #endif #ifdef USB_HOST_SHIELD_TIMING_PIN // My counter/timer can't work on an inverted gate signal // so we gate using a high pulse -- AJK UHS_PIN_WRITE(USB_HOST_SHIELD_TIMING_PIN, LOW); #endif //usb_task_polling_disabled--; EnablePoll(); DDSB(); } /* USB main task. Services the MAX3421e */ #if !USB_HOST_SHIELD_USE_ISR void UHS_NI MAX3421E_HOST::ISRTask() {} void UHS_NI MAX3421E_HOST::Task() #else void UHS_NI MAX3421E_HOST::Task() { #ifdef USB_HOST_MANUAL_POLL if (usb_task_state == UHS_USB_HOST_STATE_RUNNING) { noInterrupts(); for (uint8_t x = 0; x < UHS_HOST_MAX_INTERFACE_DRIVERS; x++) if (devConfig[x] && devConfig[x]->bPollEnable) devConfig[x]->Poll(); interrupts(); } #endif } void UHS_NI MAX3421E_HOST::ISRTask() #endif { DDSB(); #ifndef SWI_IRQ_NUM suspend_host(); #if USB_HOST_SHIELD_USE_ISR // Enable interrupts interrupts(); #endif #endif counted = false; if (!MARLIN_UHS_READ_IRQ()) { uint8_t HIRQALL = regRd(rHIRQ); // determine interrupt source uint8_t HIRQ = HIRQALL & IRQ_CHECK_MASK; uint8_t HIRQ_sendback = 0x00; if ((HIRQ & bmCONDETIRQ) || (HIRQ & bmBUSEVENTIRQ)) { MAX_HOST_DEBUG (PSTR("\r\nBEFORE CDIRQ %s BEIRQ %s resetting %s state 0x%2.2x\r\n"), (HIRQ & bmCONDETIRQ) ? "T" : "F", (HIRQ & bmBUSEVENTIRQ) ? "T" : "F", doingreset ? "T" : "F", usb_task_state ); } // ALWAYS happens BEFORE or WITH CONDETIRQ if (HIRQ & bmBUSEVENTIRQ) { HIRQ_sendback |= bmBUSEVENTIRQ; if (!doingreset) condet = true; busprobe(); busevent = false; } if (HIRQ & bmCONDETIRQ) { HIRQ_sendback |= bmCONDETIRQ; if (!doingreset) condet = true; busprobe(); } #if 1 if ((HIRQ & bmCONDETIRQ) || (HIRQ & bmBUSEVENTIRQ)) { MAX_HOST_DEBUG (PSTR("\r\nAFTER CDIRQ %s BEIRQ %s resetting %s state 0x%2.2x\r\n"), (HIRQ & bmCONDETIRQ) ? "T" : "F", (HIRQ & bmBUSEVENTIRQ) ? "T" : "F", doingreset ? "T" : "F", usb_task_state ); } #endif if (HIRQ & bmFRAMEIRQ) { HIRQ_sendback |= bmFRAMEIRQ; if (sof_countdown) { sof_countdown--; counted = true; } sofevent = false; } //MAX_HOST_DEBUG(PSTR("\r\n%s%s%s\r\n"), // sof_countdown ? "T" : "F", // counted ? "T" : "F", // usb_task_polling_disabled? "T" : "F"); DDSB(); regWr(rHIRQ, HIRQ_sendback); #ifndef SWI_IRQ_NUM resume_host(); #if USB_HOST_SHIELD_USE_ISR // Disable interrupts noInterrupts(); #endif #endif if (!sof_countdown && !counted && !usb_task_polling_disabled) { DisablePoll(); //usb_task_polling_disabled++; #ifdef USB_HOST_SHIELD_TIMING_PIN // My counter/timer can't work on an inverted gate signal // so we gate using a high pulse -- AJK UHS_PIN_WRITE(USB_HOST_SHIELD_TIMING_PIN, HIGH); #endif #ifdef SWI_IRQ_NUM //MAX_HOST_DEBUG(PSTR("--------------- Doing SWI ----------------")); exec_SWI(this); #else #if USB_HOST_SHIELD_USE_ISR // Enable interrupts interrupts(); #endif ISRbottom(); #endif /* SWI_IRQ_NUM */ } } } #if 0 DDSB(); #endif #else #error "Never include USB_HOST_SHIELD_INLINE.h, include UHS_host.h instead" #endif
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/USB_HOST_SHIELD/USB_HOST_SHIELD_INLINE.h
C
agpl-3.0
31,302
/* * File: macro_logic.h * Author: root * * Created on December 22, 2018, 4:49 AM * * To test: * gcc -DAJK_TEST_MACRO_LOGIC -E macro_logic.h */ #ifndef MACRO_LOGIC_H #define MACRO_LOGIC_H #define AJK_CAT(a, ...) AJK_PRIMITIVE_CAT(a, __VA_ARGS__) #define AJK_PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__ #define AJK_COMPL(b) AJK_PRIMITIVE_CAT(AJK_COMPL_, b) #define AJK_COMPL_0 1 #define AJK_COMPL_1 0 #define AJK_BITAND(x) AJK_PRIMITIVE_CAT(AJK_BITAND_, x) #define AJK_BITAND_0(y) 0 #define AJK_BITAND_1(y) y #define AJK_INC(x) AJK_PRIMITIVE_CAT(AJK_INC_, x) #define AJK_INC_0 1 #define AJK_INC_1 2 #define AJK_INC_2 3 #define AJK_INC_3 4 #define AJK_INC_4 5 #define AJK_INC_5 6 #define AJK_INC_6 7 #define AJK_INC_7 8 #define AJK_INC_8 9 #define AJK_INC_9 10 #define AJK_INC_10 10 #define AJK_DEC(x) AJK_PRIMITIVE_CAT(AJK_DEC_, x) #define AJK_DEC_0 0 #define AJK_DEC_1 0 #define AJK_DEC_2 1 #define AJK_DEC_3 2 #define AJK_DEC_4 3 #define AJK_DEC_5 4 #define AJK_DEC_6 5 #define AJK_DEC_7 6 #define AJK_DEC_8 7 #define AJK_DEC_9 8 #define AJK_DEC_10 9 #define AJK_CHECK_N(x, n, ...) n #define AJK_CHECK(...) AJK_CHECK_N(__VA_ARGS__, 0,) #define AJK_PROBE(x) x, 1, #define AJK_IS_PAREN(x) AJK_CHECK(AJK_IS_PAREN_PROBE x) #define AJK_IS_PAREN_PROBE(...) AJK_PROBE(~) #define AJK_NOT(x) AJK_CHECK(AJK_PRIMITIVE_CAT(AJK_NOT_, x)) #define AJK_NOT_0 AJK_PROBE(~) #define AJK_COMPL(b) AJK_PRIMITIVE_CAT(AJK_COMPL_, b) #define AJK_COMPL_0 1 #define AJK_COMPL_1 0 #define AJK_BOOL(x) AJK_COMPL(AJK_NOT(x)) #define AJK_IIF(c) AJK_PRIMITIVE_CAT(AJK_IIF_, c) #define AJK_IIF_0(t, ...) __VA_ARGS__ #define AJK_IIF_1(t, ...) t #define AJK_IF(c) AJK_IIF(AJK_BOOL(c)) #define AJK_EAT(...) #define AJK_EXPAND(...) __VA_ARGS__ #define AJK_WHEN(c) AJK_IF(c)(AJK_EXPAND, AJK_EAT) #define AJK_EMPTY() #define AJK_DEFER(id) id AJK_EMPTY() #define AJK_OBSTRUCT(id) id AJK_DEFER(AJK_EMPTY)() #define AJK_EVAL(...) AJK_EVAL1(AJK_EVAL1(AJK_EVAL1(__VA_ARGS__))) #define AJK_EVAL1(...) AJK_EVAL2(AJK_EVAL2(AJK_EVAL2(__VA_ARGS__))) #define AJK_EVAL2(...) AJK_EVAL3(AJK_EVAL3(AJK_EVAL3(__VA_ARGS__))) #define AJK_EVAL3(...) AJK_EVAL4(AJK_EVAL4(AJK_EVAL4(__VA_ARGS__))) #define AJK_EVAL4(...) AJK_EVAL5(AJK_EVAL5(AJK_EVAL5(__VA_ARGS__))) #define AJK_EVAL5(...) __VA_ARGS__ #define AJK_REPEAT(AJK_count, AJK_macro, ...) \ AJK_WHEN(AJK_count) \ ( \ AJK_OBSTRUCT(AJK_REPEAT_INDIRECT) () \ ( \ AJK_DEC(AJK_count), AJK_macro, __VA_ARGS__ \ ) \ AJK_OBSTRUCT(AJK_macro) \ ( \ AJK_DEC(AJK_count), __VA_ARGS__ \ ) \ ) #define AJK_REPEAT_INDIRECT() AJK_REPEAT #define AJK_WHILE(AJK_pred, AJK_op, ...) \ IF(AJK_pred(__VA_ARGS__)) \ ( \ AJK_OBSTRUCT(AJK_WHILE_INDIRECT) () \ ( \ AJK_pred, AJK_op, AJK_op(__VA_ARGS__) \ ), \ __VA_ARGS__ \ ) #define AJK_WHILE_INDIRECT() AJK_WHILE #define AJK_PRIMITIVE_COMPARE(x, y) AJK_IS_PAREN \ ( \ AJK_COMPARE_ ## x ( AJK_COMPARE_ ## y) (()) \ ) #define AJK_IS_COMPARABLE(x) AJK_IS_PAREN( AJK_CAT(AJK_COMPARE_, x) (()) ) #define AJK_NOT_EQUAL(x, y) \ AJK_IIF(AJK_BITAND(AJK_IS_COMPARABLE(x))(AJK_IS_COMPARABLE(y)) ) \ ( \ AJK_PRIMITIVE_COMPARE, \ 1 AJK_EAT \ )(x, y) #define AJK_EQUAL(x, y) AJK_COMPL(AJK_NOT_EQUAL(x, y)) #define AJK_COMMA() , #define AJK_COMMA_IF(n) AJK_IF(n)(AJK_COMMA, AJK_EAT)() #define AJK_COMMA_VAR(AJK_count, AJK_v) AJK_COMMA_IF(AJK_count) AJK_v ## AJK_count #define AJK_MAKE_LIST(AJK_v, AJK_count) AJK_EVAL(AJK_REPEAT(AJK_count, AJK_COMMA_VAR, AJK_v)) #define AJK_FUN(AJK_count, AJK_v, AJK_args, AJK_body) AJK_v ## AJK_count (AJK_args) { AJK_body(AJK_count) } #define AJK_MAKE_FUNS(AJK_v, AJK_args, AJK_count, AJK_body) AJK_EVAL(AJK_REPEAT(AJK_count, AJK_FUN, AJK_v, AJK_args, AJK_body)) #ifdef AJK_TEST_MACRO_LOGIC #define BODY(AJKindex) some(C, statement); containing(a, test[AJKindex]); #define ZERO_TIMES_TEST 0 #define THREE_TIMES_TEST 3 blank > AJK_MAKE_LIST(VARIABLE_, ZERO_TIMES_TEST) < because zero repeats Make 3 comma separated indexed variables : AJK_MAKE_LIST(VARIABLE_, THREE_TIMES_TEST) Make 3 bogus function bodies AJK_MAKE_FUNS(unsigned Cfunc,(arg1, arg2),3,BODY) #endif #endif /* MACRO_LOGIC_H */
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/UHS_host/macro_logic.h
C
agpl-3.0
4,220
/* * File: SWI_INLINE.h * Author: xxxajk@gmail.com * * Created on December 5, 2014, 9:40 AM * * This is the actual library. * There are no 'c' or 'cpp' files. * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef DYN_SWI_H #ifndef SWI_INLINE_H #define SWI_INLINE_H #ifndef SWI_MAXIMUM_ALLOWED #define SWI_MAXIMUM_ALLOWED 4 #endif #if defined(__arm__) || defined(ARDUINO_ARCH_PIC32) static char dyn_SWI_initied = 0; static dyn_SWI* dyn_SWI_LIST[SWI_MAXIMUM_ALLOWED]; static dyn_SWI* dyn_SWI_EXEC[SWI_MAXIMUM_ALLOWED]; #ifdef __arm__ #ifdef __USE_CMSIS_VECTORS__ extern "C" { void (*_VectorsRam[VECTORTABLE_SIZE])(void)__attribute__((aligned(VECTORTABLE_ALIGNMENT))); } #else __attribute__((always_inline)) static inline void __DSB() { __asm__ volatile ("dsb"); } #endif // defined(__USE_CMSIS_VECTORS__) #else // defined(__arm__) __attribute__((always_inline)) static inline void __DSB() { __asm__ volatile ("sync" : : : "memory"); } #endif // defined(__arm__) /** * Execute queued class ISR routines. */ #ifdef ARDUINO_ARCH_PIC32 static p32_regset *ifs = ((p32_regset *) & IFS0) + (SWI_IRQ_NUM / 32); //interrupt flag register set static p32_regset *iec = ((p32_regset *) & IEC0) + (SWI_IRQ_NUM / 32); //interrupt enable control reg set static uint32_t swibit = 1 << (SWI_IRQ_NUM % 32); void #ifdef __PIC32MZXX__ __attribute__((nomips16,at_vector(SWI_VECTOR),interrupt(SWI_IPL))) #else __attribute__((interrupt(),nomips16)) #endif softISR() { #else #ifdef ARDUINO_spresense_ast unsigned int softISR() { #else void softISR() { #endif #endif // // TO-DO: Perhaps limit to 8, and inline this? // // Make a working copy, while clearing the queue. noInterrupts(); #ifdef ARDUINO_ARCH_PIC32 //ifs->clr = swibit; #endif for(int i = 0; i < SWI_MAXIMUM_ALLOWED; i++) { dyn_SWI_EXEC[i] = dyn_SWI_LIST[i]; dyn_SWI_LIST[i] = NULL; } __DSB(); interrupts(); // Execute each class SWI for(int i = 0; i < SWI_MAXIMUM_ALLOWED; i++) { if(dyn_SWI_EXEC[i]) { #ifdef __DYN_SWI_DEBUG_LED__ digitalWrite(__DYN_SWI_DEBUG_LED__, HIGH); #endif dyn_SWI_EXEC[i]->dyn_SWISR(); #ifdef __DYN_SWI_DEBUG_LED__ digitalWrite(__DYN_SWI_DEBUG_LED__, LOW); #endif } } #ifdef ARDUINO_ARCH_PIC32 noInterrupts(); if(!dyn_SWI_EXEC[0]) ifs->clr = swibit; interrupts(); #endif #ifdef ARDUINO_spresense_ast return 0; #endif } #define DDSB() __DSB() #endif #ifdef __arm__ #ifndef interruptsStatus #define interruptsStatus() __interruptsStatus() static inline unsigned char __interruptsStatus() __attribute__((always_inline, unused)); static inline unsigned char __interruptsStatus() { unsigned int primask; asm volatile ("mrs %0, primask" : "=r" (primask)); if(primask) return 0; return 1; } #endif /** * Initialize the Dynamic (class) Software Interrupt */ static void Init_dyn_SWI() { if(!dyn_SWI_initied) { #ifdef __USE_CMSIS_VECTORS__ uint32_t *X_Vectors = (uint32_t*)SCB->VTOR; for(int i = 0; i < VECTORTABLE_SIZE; i++) { _VectorsRam[i] = reinterpret_cast<void (*)()>(X_Vectors[i]); /* copy vector table to RAM */ } /* relocate vector table */ noInterrupts(); SCB->VTOR = reinterpret_cast<uint32_t>(&_VectorsRam); DDSB(); interrupts(); #endif #ifndef ARDUINO_spresense_ast for(int i = 0; i < SWI_MAXIMUM_ALLOWED; i++) dyn_SWI_LIST[i] = NULL; noInterrupts(); _VectorsRam[SWI_IRQ_NUM + 16] = reinterpret_cast<void (*)()>(softISR); DDSB(); interrupts(); NVIC_SET_PRIORITY(SWI_IRQ_NUM, 255); NVIC_ENABLE_IRQ(SWI_IRQ_NUM); #endif #ifdef __DYN_SWI_DEBUG_LED__ pinMode(__DYN_SWI_DEBUG_LED__, OUTPUT); digitalWrite(__DYN_SWI_DEBUG_LED__, LOW); #endif dyn_SWI_initied = 1; } } /** * @param klass class that extends dyn_SWI * @return 0 on queue full, else returns queue position (ones based) */ int exec_SWI(const dyn_SWI* klass) { int rc = 0; uint8_t irestore = interruptsStatus(); // Allow use from inside a critical section... // ... and prevent races if also used inside an ISR noInterrupts(); for(int i = 0; i < SWI_MAXIMUM_ALLOWED; i++) { if(!dyn_SWI_LIST[i]) { rc = 1 + i; // Success! dyn_SWI_LIST[i] = (dyn_SWI*)klass; #ifndef ARDUINO_spresense_ast if(!NVIC_GET_PENDING(SWI_IRQ_NUM)) NVIC_SET_PENDING(SWI_IRQ_NUM); #else // Launch 1-shot timer as an emulated SWI // Hopefully the value of Zero is legal. // 1 microsecond latency would suck! attachTimerInterrupt(softISR, 100); #endif DDSB(); break; } } // Restore interrupts, if they were on. if(irestore) interrupts(); return rc; } #elif defined(ARDUINO_ARCH_PIC32) /** * Initialize the Dynamic (class) Software Interrupt */ static void Init_dyn_SWI() { if(!dyn_SWI_initied) { uint32_t sreg = disableInterrupts(); setIntVector(SWI_VECTOR, softISR); setIntPriority(SWI_VECTOR, 1, 1); // Lowest priority, ever. ifs->clr = swibit; iec->clr = swibit; iec->set = swibit; restoreInterrupts(sreg); #ifdef __DYN_SWI_DEBUG_LED__ pinMode(__DYN_SWI_DEBUG_LED__, OUTPUT); UHS_PIN_WRITE(__DYN_SWI_DEBUG_LED__, LOW); #endif } } /** * @param klass class that extends dyn_SWI * @return 0 on queue full, else returns queue position (ones based) */ int exec_SWI(const dyn_SWI* klass) { int rc = 0; uint32_t sreg = disableInterrupts(); for(int i = 0; i < SWI_MAXIMUM_ALLOWED; i++) { if(!dyn_SWI_LIST[i]) { rc = 1 + i; // Success! dyn_SWI_LIST[i] = (dyn_SWI*)klass; if(!(ifs->reg & swibit)) ifs->set = swibit; ; break; } } restoreInterrupts(sreg); return rc; } #endif /* defined(__arm__) */ #endif /* SWI_INLINE_H */ #else #error "Never include SWI_INLINE.h directly, include dyn_SWI.h instead" #endif
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/dyn_SWI/SWI_INLINE.h
C
agpl-3.0
7,469
/* * File: dyn_SWI.h * Author: xxxajk@gmail.com * * Created on December 5, 2014, 9:12 AM * * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef DYN_SWI_H #define DYN_SWI_H #if defined(__arm__) || defined(ARDUINO_ARCH_PIC32) #ifdef ARDUINO_ARCH_PIC32 #include <p32xxxx.h> #endif #ifdef __cplusplus #ifdef true #undef true #endif #ifdef false #undef false #endif #endif #ifdef ARDUINO_spresense_ast #define SWI_IRQ_NUM 666 // because this board is totally evil. #elif defined(ARDUINO_ARCH_PIC32) #ifndef SWI_IRQ_NUM #ifdef _DSPI0_IPL_ISR #define SWI_IPL _DSPI0_IPL_ISR #define SWI_VECTOR _DSPI0_ERR_IRQ #define SWI_IRQ_NUM _DSPI0_ERR_IRQ #elif defined(_PMP_ERROR_IRQ) #define SWI_IRQ_NUM _PMP_ERROR_IRQ #define SWI_VECTOR _PMP_VECTOR #else #error SWI_IRQ_NUM and SWI_VECTOR need a definition #endif #ifdef __cplusplus extern "C" { void #ifdef __PIC32MZXX__ __attribute__((nomips16,at_vector(SWI_VECTOR),interrupt(SWI_IPL))) #else __attribute__((interrupt(),nomips16)) #endif softISR(); } #endif #endif #elif !defined(NVIC_NUM_INTERRUPTS) // Assume CMSIS #define __USE_CMSIS_VECTORS__ #ifdef NUMBER_OF_INT_VECTORS #define NVIC_NUM_INTERRUPTS (NUMBER_OF_INT_VECTORS-16) #else #define NVIC_NUM_INTERRUPTS ((int)PERIPH_COUNT_IRQn) #endif #define VECTORTABLE_SIZE (NVIC_NUM_INTERRUPTS+16) #define VECTORTABLE_ALIGNMENT (0x100UL) #define NVIC_GET_ACTIVE(n) NVIC_GetActive((IRQn_Type)n) #define NVIC_GET_PENDING(n) NVIC_GetPendingIRQ((IRQn_Type)n) #define NVIC_SET_PENDING(n) NVIC_SetPendingIRQ((IRQn_Type)n) #define NVIC_ENABLE_IRQ(n) NVIC_EnableIRQ((IRQn_Type)n) #define NVIC_SET_PRIORITY(n ,p) NVIC_SetPriority((IRQn_Type)n, (uint32_t) p) //extern "C" { // extern uint32_t _VectorsRam[VECTORTABLE_SIZE] __attribute__((aligned(VECTORTABLE_ALIGNMENT))); //} #ifndef SWI_IRQ_NUM #if defined(__SAM3X8E__) && defined(_VARIANT_ARDUINO_DUE_X_) // DUE // Choices available: // HSMCI_IRQn Multimedia Card Interface (HSMCI) // EMAC_IRQn Ethernet MAC (EMAC) // EMAC is not broken out on the official DUE, but is on clones. // SPI0_IRQn Serial Peripheral Interface (SPI0) // SPI0_IRQn seems to be the best choice, as long as nobody uses an ISR based master #define SWI_IRQ_NUM SPI0_IRQn #elif defined(ARDUINO_SAMD_ZERO) // Just use sercom4's unused IRQ vector. #define SWI_IRQ_NUM I2S_IRQn //#define SWI_IRQ_NUM SERCOM4_IRQn #endif #endif #ifndef SWI_IRQ_NUM #error SWI_IRQ_NUM not defined (CMSIS) #endif #elif defined(CORE_TEENSY) #ifndef NVIC_GET_ACTIVE #define NVIC_GET_ACTIVE(n) (*((volatile uint32_t *)0xE000E300 + ((n) >> 5)) & (1 << ((n) & 31))) #endif #ifndef NVIC_GET_PENDING #define NVIC_GET_PENDING(n) (*((volatile uint32_t *)0xE000E200 + ((n) >> 5)) & (1 << ((n) & 31))) #ifndef SWI_IRQ_NUM #ifdef __MK20DX256__ #define SWI_IRQ_NUM 17 #elif defined(__MK20DX128__) #define SWI_IRQ_NUM 5 #elif defined(__MKL26Z64__) #define SWI_IRQ_NUM 4 #elif defined(__MK66FX1M0__) #define SWI_IRQ_NUM 30 #elif defined(__MK64FX512__) #define SWI_IRQ_NUM 30 #elif defined(__IMXRT1052__) || defined(__IMXRT1062__) #define SWI_IRQ_NUM 71 #else #error Do not know how to relocate IRQ vectors for this pjrc product #endif #endif #endif #else // Not CMSIS or PJRC CORE_TEENSY or PIC32 or SPRESENSE #error Do not know how to relocate IRQ vectors or perform SWI #endif // SWI_IRQ_NUM #ifndef SWI_IRQ_NUM #error SWI_IRQ_NUM not defined #else /** * Use this class to extend your class, in order to provide * a C++ context callable SWI. */ class dyn_SWI { public: /** * Override this method with your code. */ virtual void dyn_SWISR() { }; }; extern int exec_SWI(const dyn_SWI* klass); #include "SWI_INLINE.h" // IMPORTANT! Define this so that you do NOT end up with a NULL stub! #define SWI_NO_STUB #endif /* SWI_IRQ_NUM */ #endif /* __arm__ */ // if no SWI for CPU (e.g. AVR) make a void stub. #ifndef SWI_NO_STUB #define Init_dyn_SWI() (void(0)) #ifndef DDSB #define DDSB() (void(0)) #endif #endif #endif /* DYN_SWI_H */
2301_81045437/Marlin
Marlin/src/sd/usb_flashdrive/lib-uhs3/dyn_SWI/dyn_SWI.h
C++
agpl-3.0
4,693
/** * Marlin 3D Printer Firmware * Copyright (c) 2022 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfigPre.h" #if ENABLED(MARLIN_TEST_BUILD) #include "../module/endstops.h" #include "../module/motion.h" #include "../module/planner.h" #include "../module/settings.h" #include "../module/stepper.h" #include "../module/temperature.h" // Individual tests are localized in each module. // Each test produces its own report. // Startup tests are run at the end of setup() void runStartupTests() { // Call post-setup tests here to validate behaviors. } // Periodic tests are run from within loop() void runPeriodicTests() { // Call periodic tests here to validate behaviors. } #endif // MARLIN_TEST_BUILD
2301_81045437/Marlin
Marlin/src/tests/marlin_tests.cpp
C++
agpl-3.0
1,498
/** * Marlin 3D Printer Firmware * Copyright (c) 2022 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #pragma once void runStartupTests(); void runPeriodicTests();
2301_81045437/Marlin
Marlin/src/tests/marlin_tests.h
C
agpl-3.0
925
/** * Marlin 3D Printer Firmware * Copyright (c) 2024 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #include "../test/unit_tests.h" #include <src/core/macros.h> // These represent enabled and disabled configuration options for testing. // They will be used by multiple tests. #define OPTION_ENABLED 1 #define OPTION_DISABLED 0 MARLIN_TEST(macros_bitwise_8, TEST) { uint8_t odd_set = 0xAA; uint8_t even_set = 0x55; for (uint8_t b = 0; b < 8; ++b) { TEST_ASSERT_EQUAL((b % 2) != 0, TEST(odd_set, b)); TEST_ASSERT_EQUAL((b % 2) == 0, TEST(even_set, b)); } } MARLIN_TEST(macros_bitwise_8, SET_BIT_TO) { uint8_t n = 0x00; // Test LSB SET_BIT_TO(n, 0, true); TEST_ASSERT_EQUAL(0x01, n); SET_BIT_TO(n, 0, false); TEST_ASSERT_EQUAL(0x00, n); // Test MSB SET_BIT_TO(n, 7, true); TEST_ASSERT_EQUAL(0x80, n); SET_BIT_TO(n, 7, false); TEST_ASSERT_EQUAL(0x00, n); // Test a bit in the middle SET_BIT_TO(n, 3, true); TEST_ASSERT_EQUAL(0x08, n); SET_BIT_TO(n, 3, false); TEST_ASSERT_EQUAL(0x00, n); } MARLIN_TEST(macros_bitwise_8, SBI) { uint8_t n; // Test LSB n = 0x00; SBI(n, 0); TEST_ASSERT_EQUAL(0x01, n); // Test MSB n = 0x00; SBI(n, 7); TEST_ASSERT_EQUAL(0x80, n); // Test a bit in the middle n = 0x00; SBI(n, 3); TEST_ASSERT_EQUAL(0x08, n); } MARLIN_TEST(macros_bitwise_8, CBI) { uint8_t n; // Test LSB n = 0xFF; CBI(n, 0); TEST_ASSERT_EQUAL(0xFE, n); // Test MSB n = 0xFF; CBI(n, 7); TEST_ASSERT_EQUAL(0x7F, n); // Test a bit in the middle n = 0xFF; CBI(n, 3); TEST_ASSERT_EQUAL(0xF7, n); } MARLIN_TEST(macros_bitwise_8, TBI) { uint8_t n; // Test LSB n = 0xAA; TBI(n, 0); TEST_ASSERT_EQUAL(0xAB, n); // Test MSB n = 0xAA; TBI(n, 7); TEST_ASSERT_EQUAL(0x2A, n); // Test a bit in the middle n = 0xAA; TBI(n, 3); TEST_ASSERT_EQUAL(0xA2, n); } // 32-bit BIT operation tests // These verify the above macros, but specifically with the MSB of a uint32_t. // This ensures that the macros are not limited to 8-bit operations. MARLIN_TEST(macros_bitwise_32, TEST_32bit) { uint32_t odd_set = 0x80000000; uint32_t even_set = 0x00000000; TEST_ASSERT_EQUAL(true, TEST(odd_set, 31)); TEST_ASSERT_EQUAL(false, TEST(even_set, 31)); } MARLIN_TEST(macros_bitwise_32, SET_BIT_TO_32bit) { uint32_t n = 0x00000000; // Test MSB SET_BIT_TO(n, 31, true); TEST_ASSERT_EQUAL(0x80000000, n); SET_BIT_TO(n, 31, false); TEST_ASSERT_EQUAL(0x00000000, n); } MARLIN_TEST(macros_bitwise_32, SBI_32bit) { uint32_t n = 0x00000000; // Test MSB SBI(n, 31); TEST_ASSERT_EQUAL(0x80000000, n); } MARLIN_TEST(macros_bitwise_32, CBI_32bit) { uint32_t n = 0xFFFFFFFF; // Test MSB CBI(n, 31); TEST_ASSERT_EQUAL(0x7FFFFFFF, n); } MARLIN_TEST(macros_bitwise_32, TBI_32bit) { uint32_t n = 0x7FFFFFFF; // Test MSB TBI(n, 31); TEST_ASSERT_EQUAL(0xFFFFFFFF, n); } // Geometry macros MARLIN_TEST(macros_geometry, cu_int) { TEST_ASSERT_EQUAL(8, cu(2)); TEST_ASSERT_EQUAL(27, cu(3)); } MARLIN_TEST(macros_geometry, cu_float) { TEST_ASSERT_FLOAT_WITHIN(0.001f, 8.615f, cu(2.05f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 28.094f, cu(3.04f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 13.998f, cu(2.41f)); } MARLIN_TEST(macros_geometry, RADIANS) { TEST_ASSERT_FLOAT_WITHIN(0.001f, float(M_PI), RADIANS(180.0f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 0.0f, RADIANS(0.0f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, float(M_PI) / 4, RADIANS(45.0f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, float(M_PI) / 2, RADIANS(90.0f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 3 * float(M_PI) / 2, RADIANS(270.0f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 4 * float(M_PI), RADIANS(720.0f)); } MARLIN_TEST(macros_geometry, DEGREES) { TEST_ASSERT_FLOAT_WITHIN(0.001f, 180.0f, DEGREES(float(M_PI))); TEST_ASSERT_FLOAT_WITHIN(0.001f, 0.0f, DEGREES(0.0f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 45.0f, DEGREES(float(M_PI) / 4)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 90.0f, DEGREES(float(M_PI) / 2)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 270.0f, DEGREES(3 * float(M_PI) / 2)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 720.0f, DEGREES(4 * float(M_PI))); } MARLIN_TEST(macros_geometry, HYPOT2) { TEST_ASSERT_EQUAL(25, HYPOT2(3, 4)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 13.0f, HYPOT2(2.0f, 3.0f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 18.72f, HYPOT2(2.4f, 3.6f)); } MARLIN_TEST(macros_geometry, NORMSQ) { TEST_ASSERT_EQUAL(14, NORMSQ(1, 2, 3)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 14.0f, NORMSQ(1.0f, 2.0f, 3.0f)); TEST_ASSERT_FLOAT_WITHIN(0.001f, 20.16f, NORMSQ(1.2f, 2.4f, 3.6f)); } MARLIN_TEST(macros_geometry, CIRCLE_AREA) { TEST_ASSERT_EQUAL(float(M_PI) * 4, CIRCLE_AREA(2)); } MARLIN_TEST(macros_geometry, CIRCLE_CIRC) { TEST_ASSERT_EQUAL(2 * float(M_PI) * 3, CIRCLE_CIRC(3)); } MARLIN_TEST(macros_numeric, SIGN) { TEST_ASSERT_EQUAL(1, SIGN(100)); TEST_ASSERT_EQUAL(-1, SIGN(-100)); TEST_ASSERT_EQUAL(0, SIGN(0)); } MARLIN_TEST(macros_numeric, IS_POWER_OF_2) { TEST_ASSERT_EQUAL(false, IS_POWER_OF_2(0)); TEST_ASSERT_EQUAL(true, IS_POWER_OF_2(1)); TEST_ASSERT_EQUAL(true, IS_POWER_OF_2(4)); TEST_ASSERT_EQUAL(false, IS_POWER_OF_2(5)); TEST_ASSERT_EQUAL(false, IS_POWER_OF_2(0x80000001)); TEST_ASSERT_EQUAL(true, IS_POWER_OF_2(0x80000000)); } // Numeric constraints MARLIN_TEST(macros_numeric, NOLESS_int) { // Scenario 1: Input was already acceptable int a = 8; NOLESS(a, 5); TEST_ASSERT_EQUAL(8, a); // Original scenario: Input was less than the limit a = 5; NOLESS(a, 10); TEST_ASSERT_EQUAL(10, a); // Scenario 2: Input is negative, and coerces to a positive number a = -5; NOLESS(a, 0); TEST_ASSERT_EQUAL(0, a); // Scenario 3: Input is negative, and coerces to another negative number a = -10; NOLESS(a, -5); TEST_ASSERT_EQUAL(-5, a); } MARLIN_TEST(macros_numeric, NOLESS_uint) { // Scenario 1: Input was already acceptable unsigned int b = 8u; NOLESS(b, 5u); TEST_ASSERT_EQUAL(8u, b); // Original scenario: Input was less than the limit b = 5u; NOLESS(b, 10u); TEST_ASSERT_EQUAL(10u, b); } MARLIN_TEST(macros_numeric, NOLESS_float) { // Scenario 1: Input was already acceptable float c = 8.5f; NOLESS(c, 5.5f); TEST_ASSERT_EQUAL_FLOAT(8.5f, c); // Original scenario: Input was less than the limit c = 5.5f; NOLESS(c, 10.5f); TEST_ASSERT_EQUAL_FLOAT(10.5f, c); // Scenario 2: Input is negative, and coerces to a positive number c = -5.5f; NOLESS(c, 5.0f); TEST_ASSERT_EQUAL_FLOAT(5.0f, c); // Scenario 3: Input is negative, and coerces to another negative number c = -10.5f; NOLESS(c, -5.5f); TEST_ASSERT_EQUAL_FLOAT(-5.5f, c); c = -5.5f; NOLESS(c, -10.5f); TEST_ASSERT_EQUAL_FLOAT(-5.5f, c); } MARLIN_TEST(macros_numeric, NOMORE_int) { // Scenario 1: Input was already acceptable int a = 8; NOMORE(a, 10); TEST_ASSERT_EQUAL(8, a); // Original scenario: Input was more than the limit a = 15; NOMORE(a, 10); TEST_ASSERT_EQUAL(10, a); // Scenario 2: Input is positive, and coerces to a negative number a = 5; NOMORE(a, -2); TEST_ASSERT_EQUAL(-2, a); // Scenario 3: Input is negative, and coerces to another negative number a = -5; NOMORE(a, -10); TEST_ASSERT_EQUAL(-10, a); } MARLIN_TEST(macros_numeric, NOMORE_uint) { // Scenario 1: Input was already acceptable unsigned int b = 8u; NOMORE(b, 10u); TEST_ASSERT_EQUAL(8u, b); // Original scenario: Input was more than the limit b = 15u; NOMORE(b, 10u); TEST_ASSERT_EQUAL(10u, b); } MARLIN_TEST(macros_numeric, NOMORE_float) { // Scenario 1: Input was already acceptable float c = 8.5f; NOMORE(c, 10.5f); TEST_ASSERT_EQUAL_FLOAT(8.5f, c); // Original scenario: Input was more than the limit c = 15.5f; NOMORE(c, 10.5f); TEST_ASSERT_EQUAL_FLOAT(10.5f, c); // Scenario 2: Input is positive, and coerces to a negative number c = 5.5f; NOMORE(c, -1.7f); TEST_ASSERT_EQUAL_FLOAT(-1.7f, c); // Scenario 3: Input is negative, and coerces to another negative number c = -5.5f; NOMORE(c, -10.5f); TEST_ASSERT_EQUAL_FLOAT(-10.5f, c); } MARLIN_TEST(macros_numeric, LIMIT_int) { int a = 15; LIMIT(a, 10, 20); TEST_ASSERT_EQUAL(15, a); a = 5; LIMIT(a, 10, 20); TEST_ASSERT_EQUAL(10, a); a = 25; LIMIT(a, 10, 20); TEST_ASSERT_EQUAL(20, a); // Scenario: Range is [-10, -5] a = -8; LIMIT(a, -10, -5); TEST_ASSERT_EQUAL(-8, a); a = -12; LIMIT(a, -10, -5); TEST_ASSERT_EQUAL(-10, a); a = -3; LIMIT(a, -10, -5); TEST_ASSERT_EQUAL(-5, a); // Scenario: Range is [-10, 5] a = 0; LIMIT(a, -10, 5); TEST_ASSERT_EQUAL(0, a); a = -12; LIMIT(a, -10, 5); TEST_ASSERT_EQUAL(-10, a); a = 6; LIMIT(a, -10, 5); TEST_ASSERT_EQUAL(5, a); } MARLIN_TEST(macros_numeric, LIMIT_uint) { unsigned int b = 15u; LIMIT(b, 10u, 20u); TEST_ASSERT_EQUAL(15u, b); b = 5u; LIMIT(b, 10u, 20u); TEST_ASSERT_EQUAL(10u, b); b = 25u; LIMIT(b, 10u, 20u); TEST_ASSERT_EQUAL(20u, b); } MARLIN_TEST(macros_numeric, LIMIT_float) { float c = 15.5f; LIMIT(c, 10.5f, 20.5f); TEST_ASSERT_EQUAL_FLOAT(15.5f, c); c = 5.5f; LIMIT(c, 10.5f, 20.5f); TEST_ASSERT_EQUAL_FLOAT(10.5f, c); c = 25.5f; LIMIT(c, 10.5f, 20.5f); TEST_ASSERT_EQUAL_FLOAT(20.5f, c); // Scenario: Range is [-10.5, -5.5] c = -8.5f; LIMIT(c, -10.5f, -5.5f); TEST_ASSERT_EQUAL_FLOAT(-8.5f, c); c = -12.5f; LIMIT(c, -10.5f, -5.5f); TEST_ASSERT_EQUAL_FLOAT(-10.5f, c); c = -3.5f; LIMIT(c, -10.5f, -5.5f); TEST_ASSERT_EQUAL_FLOAT(-5.5f, c); // Scenario: Range is [-10.5, 5.5] c = 0.0f; LIMIT(c, -10.5f, 5.5f); TEST_ASSERT_EQUAL_FLOAT(0.0f, c); c = -12.5f; LIMIT(c, -10.5f, 5.5f); TEST_ASSERT_EQUAL_FLOAT(-10.5f, c); c = 6.5f; LIMIT(c, -10.5f, 5.5f); TEST_ASSERT_EQUAL_FLOAT(5.5f, c); } // Looping macros MARLIN_TEST(macros_looping, DO_macro) { #define _M_1(A) (A) int sum = DO(M, +, 1, 2, 3, 4, 5); TEST_ASSERT_EQUAL(15, sum); // Test with maximum number of arguments sum = DO(M, +, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40); TEST_ASSERT_EQUAL(820, sum); #undef _M_1 } // Configuration Options MARLIN_TEST(macros_options, ENABLED_DISABLED) { #define OPTION_A #define OPTION_B 1 #define OPTION_C true #define OPTION_D 0 #define OPTION_E false // #define OPTION_F // Test ENABLED macro TEST_ASSERT_TRUE(ENABLED(OPTION_A)); TEST_ASSERT_TRUE(ENABLED(OPTION_B)); TEST_ASSERT_TRUE(ENABLED(OPTION_C)); TEST_ASSERT_FALSE(ENABLED(OPTION_D)); TEST_ASSERT_FALSE(ENABLED(OPTION_E)); TEST_ASSERT_FALSE(ENABLED(OPTION_F)); // Test DISABLED macro TEST_ASSERT_FALSE(DISABLED(OPTION_A)); TEST_ASSERT_FALSE(DISABLED(OPTION_B)); TEST_ASSERT_FALSE(DISABLED(OPTION_C)); TEST_ASSERT_TRUE(DISABLED(OPTION_D)); TEST_ASSERT_TRUE(DISABLED(OPTION_E)); TEST_ASSERT_TRUE(DISABLED(OPTION_F)); #undef OPTION_A #undef OPTION_B #undef OPTION_C #undef OPTION_D #undef OPTION_E } MARLIN_TEST(macros_options, ANY) { TEST_ASSERT_TRUE(ANY(OPTION_DISABLED, OPTION_ENABLED, OPTION_DISABLED)); // Enabled option in the middle TEST_ASSERT_TRUE(ANY(OPTION_ENABLED, OPTION_DISABLED, OPTION_DISABLED)); // Enabled option at the beginning TEST_ASSERT_TRUE(ANY(OPTION_DISABLED, OPTION_DISABLED, OPTION_ENABLED)); // Enabled option at the end TEST_ASSERT_FALSE(ANY(OPTION_DISABLED, OPTION_DISABLED, OPTION_DISABLED)); // All options disabled } MARLIN_TEST(macros_options, ALL) { TEST_ASSERT_TRUE(ALL(OPTION_ENABLED, OPTION_ENABLED, OPTION_ENABLED)); // All options enabled TEST_ASSERT_FALSE(ALL(OPTION_ENABLED, OPTION_DISABLED, OPTION_ENABLED)); // Disabled option in the middle TEST_ASSERT_FALSE(ALL(OPTION_DISABLED, OPTION_ENABLED, OPTION_ENABLED)); // Disabled option at the beginning TEST_ASSERT_FALSE(ALL(OPTION_ENABLED, OPTION_ENABLED, OPTION_DISABLED)); // Disabled option at the end TEST_ASSERT_FALSE(ALL(OPTION_DISABLED, OPTION_DISABLED, OPTION_DISABLED)); // All options disabled } MARLIN_TEST(macros_options, NONE) { TEST_ASSERT_FALSE(NONE(OPTION_ENABLED, OPTION_ENABLED, OPTION_ENABLED)); // All options enabled TEST_ASSERT_FALSE(NONE(OPTION_ENABLED, OPTION_DISABLED, OPTION_ENABLED)); // Disabled option in the middle TEST_ASSERT_FALSE(NONE(OPTION_DISABLED, OPTION_ENABLED, OPTION_ENABLED)); // Disabled option at the beginning TEST_ASSERT_FALSE(NONE(OPTION_ENABLED, OPTION_ENABLED, OPTION_DISABLED)); // Disabled option at the end TEST_ASSERT_TRUE(NONE(OPTION_DISABLED, OPTION_DISABLED, OPTION_DISABLED)); // All options disabled } MARLIN_TEST(macros_options, COUNT_ENABLED) { TEST_ASSERT_EQUAL(3, COUNT_ENABLED(OPTION_ENABLED, OPTION_ENABLED, OPTION_ENABLED)); // All options enabled TEST_ASSERT_EQUAL(2, COUNT_ENABLED(OPTION_ENABLED, OPTION_DISABLED, OPTION_ENABLED)); // Disabled option in the middle TEST_ASSERT_EQUAL(2, COUNT_ENABLED(OPTION_DISABLED, OPTION_ENABLED, OPTION_ENABLED)); // Disabled option at the beginning TEST_ASSERT_EQUAL(2, COUNT_ENABLED(OPTION_ENABLED, OPTION_ENABLED, OPTION_DISABLED)); // Disabled option at the end TEST_ASSERT_EQUAL(0, COUNT_ENABLED(OPTION_DISABLED, OPTION_DISABLED, OPTION_DISABLED)); // All options disabled } MARLIN_TEST(macros_options, MANY) { TEST_ASSERT_FALSE(MANY(OPTION_ENABLED, OPTION_DISABLED, OPTION_DISABLED)); // Only one option enabled TEST_ASSERT_TRUE(MANY(OPTION_ENABLED, OPTION_ENABLED, OPTION_DISABLED)); // Two options enabled TEST_ASSERT_TRUE(MANY(OPTION_ENABLED, OPTION_ENABLED, OPTION_ENABLED)); // All options enabled TEST_ASSERT_FALSE(MANY(OPTION_DISABLED, OPTION_DISABLED, OPTION_DISABLED)); // No options enabled } // Ternary macros MARLIN_TEST(macros_options, TERN) { TEST_ASSERT_EQUAL(1, TERN(OPTION_ENABLED, 1, 0)); // OPTION_ENABLED is enabled, so it should return '1' TEST_ASSERT_EQUAL(0, TERN(OPTION_DISABLED, 1, 0)); // OPTION_DISABLED is disabled, so it should return '0' } MARLIN_TEST(macros_options, TERN0) { TEST_ASSERT_EQUAL(1, TERN0(OPTION_ENABLED, 1)); // OPTION_ENABLED is enabled, so it should return '1' TEST_ASSERT_EQUAL(0, TERN0(OPTION_DISABLED, 1)); // OPTION_DISABLED is disabled, so it should return '0' } MARLIN_TEST(macros_options, TERN1) { TEST_ASSERT_EQUAL(0, TERN1(OPTION_ENABLED, 0)); // OPTION_ENABLED is enabled, so it should return '0' TEST_ASSERT_EQUAL(1, TERN1(OPTION_DISABLED, 0)); // OPTION_DISABLED is disabled, so it should return '1' } MARLIN_TEST(macros_options, TERN_) { TEST_ASSERT_EQUAL(-1, TERN_(OPTION_ENABLED, -)1); // OPTION_ENABLED is enabled, so it should return '1' TEST_ASSERT_EQUAL(1, TERN_(OPTION_DISABLED, -)1); // OPTION_DISABLED is disabled, so it should return nothing } MARLIN_TEST(macros_options, IF_DISABLED) { TEST_ASSERT_EQUAL(1, IF_DISABLED(OPTION_ENABLED, -)1); // OPTION_ENABLED is enabled, so it should return nothing TEST_ASSERT_EQUAL(-1, IF_DISABLED(OPTION_DISABLED, -)1); // OPTION_DISABLED is disabled, so it should return '1' } MARLIN_TEST(macros_options, OPTITEM) { int enabledArray[] = {OPTITEM(OPTION_ENABLED, 1, 2)}; int disabledArray[] = {OPTITEM(OPTION_DISABLED, 1, 2)}; TEST_ASSERT_EQUAL(2, sizeof(enabledArray) / sizeof(int)); // OPTION_ENABLED is enabled, so it should return an array of size 2 TEST_ASSERT_EQUAL(0, sizeof(disabledArray) / sizeof(int)); // OPTION_DISABLED is disabled, so it should return an array of size 0 } MARLIN_TEST(macros_options, OPTARG) { int enabledArgs[] = {0 OPTARG(OPTION_ENABLED, 1, 2)}; int disabledArgs[] = {0 OPTARG(OPTION_DISABLED, 1, 2)}; int sumEnabledArgs = 0; for (const auto& arg : enabledArgs) { sumEnabledArgs += arg; } int sumDisabledArgs = 0; for (const auto& arg : disabledArgs) { sumDisabledArgs += arg; } TEST_ASSERT_EQUAL(3, sumEnabledArgs); // OPTION_ENABLED is enabled, so it should return 3 TEST_ASSERT_EQUAL(0, sumDisabledArgs); // OPTION_DISABLED is disabled, so it should return 0 } MARLIN_TEST(macros_options, OPTCODE) { int enabledCode = 0; OPTCODE(OPTION_ENABLED, enabledCode = 1); int disabledCode = 0; OPTCODE(OPTION_DISABLED, disabledCode = 1); TEST_ASSERT_EQUAL(1, enabledCode); // OPTION_ENABLED is enabled, so it should return 1 TEST_ASSERT_EQUAL(0, disabledCode); // OPTION_DISABLED is disabled, so it should return 0 } MARLIN_TEST(macros_optional_math, PLUS_TERN0) { int enabledPlus = 5 PLUS_TERN0(OPTION_ENABLED, 2); int disabledPlus = 5 PLUS_TERN0(OPTION_DISABLED, 2); TEST_ASSERT_EQUAL(7, enabledPlus); // OPTION_ENABLED is enabled, so it should return 7 TEST_ASSERT_EQUAL(5, disabledPlus); // OPTION_DISABLED is disabled, so it should return 5 } MARLIN_TEST(macros_optional_math, MINUS_TERN0) { int enabledMinus = 5 MINUS_TERN0(OPTION_ENABLED, 2); int disabledMinus = 5 MINUS_TERN0(OPTION_DISABLED, 2); TEST_ASSERT_EQUAL(3, enabledMinus); // OPTION_ENABLED is enabled, so it should return 3 TEST_ASSERT_EQUAL(5, disabledMinus); // OPTION_DISABLED is disabled, so it should return 5 } MARLIN_TEST(macros_optional_math, MUL_TERN1) { int enabledMul = 5 MUL_TERN1(OPTION_ENABLED, 2); int disabledMul = 5 MUL_TERN1(OPTION_DISABLED, 2); TEST_ASSERT_EQUAL(10, enabledMul); // OPTION_ENABLED is enabled, so it should return 10 TEST_ASSERT_EQUAL(5, disabledMul); // OPTION_DISABLED is disabled, so it should return 5 } MARLIN_TEST(macros_optional_math, DIV_TERN1) { int enabledDiv = 10 DIV_TERN1(OPTION_ENABLED, 2); int disabledDiv = 10 DIV_TERN1(OPTION_DISABLED, 2); TEST_ASSERT_EQUAL(5, enabledDiv); // OPTION_ENABLED is enabled, so it should return 5 TEST_ASSERT_EQUAL(10, disabledDiv); // OPTION_DISABLED is disabled, so it should return 10 } MARLIN_TEST(macros_optional_math, SUM_TERN) { int enabledSum = SUM_TERN(OPTION_ENABLED, 5, 2); int disabledSum = SUM_TERN(OPTION_DISABLED, 5, 2); TEST_ASSERT_EQUAL(7, enabledSum); // OPTION_ENABLED is enabled, so it should return 7 TEST_ASSERT_EQUAL(5, disabledSum); // OPTION_DISABLED is disabled, so it should return 5 } MARLIN_TEST(macros_optional_math, DIFF_TERN) { int enabledDiff = DIFF_TERN(OPTION_ENABLED, 5, 2); int disabledDiff = DIFF_TERN(OPTION_DISABLED, 5, 2); TEST_ASSERT_EQUAL(3, enabledDiff); // OPTION_ENABLED is enabled, so it should return 3 TEST_ASSERT_EQUAL(5, disabledDiff); // OPTION_DISABLED is disabled, so it should return 5 } MARLIN_TEST(macros_optional_math, MUL_TERN) { int enabledMul = MUL_TERN(OPTION_ENABLED, 5, 2); int disabledMul = MUL_TERN(OPTION_DISABLED, 5, 2); TEST_ASSERT_EQUAL(10, enabledMul); // OPTION_ENABLED is enabled, so it should return 10 TEST_ASSERT_EQUAL(5, disabledMul); // OPTION_DISABLED is disabled, so it should return 5 } MARLIN_TEST(macros_optional_math, DIV_TERN) { int enabledDiv = DIV_TERN(OPTION_ENABLED, 10, 2); int disabledDiv = DIV_TERN(OPTION_DISABLED, 10, 2); TEST_ASSERT_EQUAL(5, enabledDiv); // OPTION_ENABLED is enabled, so it should return 5 TEST_ASSERT_EQUAL(10, disabledDiv); // OPTION_DISABLED is disabled, so it should return 10 } // Mock pin definitions #define PIN1_PIN 1 #define PIN2_PIN 2 #define PIN3_PIN -1 MARLIN_TEST(macros_pins, PIN_EXISTS) { // Test PIN_EXISTS macro int pin1_exists, pin2_exists, pin3_exists, pin4_exists; #if PIN_EXISTS(PIN1) pin1_exists = 1; #else pin1_exists = 0; #endif #if PIN_EXISTS(PIN2) pin2_exists = 1; #else pin2_exists = 0; #endif #if PIN_EXISTS(PIN3) pin3_exists = 1; #else pin3_exists = 0; #endif #if PIN_EXISTS(PIN4) pin4_exists = 1; #else pin4_exists = 0; #endif TEST_ASSERT_TRUE(pin1_exists); TEST_ASSERT_TRUE(pin2_exists); TEST_ASSERT_FALSE(pin3_exists); TEST_ASSERT_FALSE(pin4_exists); } MARLIN_TEST(macros_pins, PINS_EXIST) { // Test PINS_EXIST macro int pins1_2_exist, pins1_3_exist; #if PINS_EXIST(PIN1, PIN2) pins1_2_exist = 1; #else pins1_2_exist = 0; #endif #if PINS_EXIST(PIN1, PIN3) pins1_3_exist = 1; #else pins1_3_exist = 0; #endif TEST_ASSERT_TRUE(pins1_2_exist); TEST_ASSERT_FALSE(pins1_3_exist); } MARLIN_TEST(macros_pins, ANY_PIN) { // Test ANY_PIN macro int any_pin1_3, any_pin3_4; #if ANY_PIN(PIN1, PIN3) any_pin1_3 = 1; #else any_pin1_3 = 0; #endif #if ANY_PIN(PIN3, PIN4) any_pin3_4 = 1; #else any_pin3_4 = 0; #endif TEST_ASSERT_TRUE(any_pin1_3); TEST_ASSERT_FALSE(any_pin3_4); } // Undefine mock pin definitions #undef PIN1_PIN #undef PIN2_PIN #undef PIN3_PIN // Mock button definitions #define BTN_BUTTON1 1 #define BTN_BUTTON2 2 #define BTN_BUTTON3 -1 MARLIN_TEST(macros_buttons, BUTTON_EXISTS) { // Test BUTTON_EXISTS macro int button1_exists, button2_exists, button3_exists, button4_exists; #if BUTTON_EXISTS(BUTTON1) button1_exists = 1; #else button1_exists = 0; #endif #if BUTTON_EXISTS(BUTTON2) button2_exists = 1; #else button2_exists = 0; #endif #if BUTTON_EXISTS(BUTTON3) button3_exists = 1; #else button3_exists = 0; #endif #if BUTTON_EXISTS(BUTTON4) button4_exists = 1; #else button4_exists = 0; #endif TEST_ASSERT_TRUE(button1_exists); TEST_ASSERT_TRUE(button2_exists); TEST_ASSERT_FALSE(button3_exists); TEST_ASSERT_FALSE(button4_exists); } MARLIN_TEST(macros_buttons, BUTTONS_EXIST) { // Test BUTTONS_EXIST macro int buttons1_2_exist, buttons1_3_exist; #if BUTTONS_EXIST(BUTTON1, BUTTON2) buttons1_2_exist = 1; #else buttons1_2_exist = 0; #endif #if BUTTONS_EXIST(BUTTON1, BUTTON3) buttons1_3_exist = 1; #else buttons1_3_exist = 0; #endif TEST_ASSERT_TRUE(buttons1_2_exist); TEST_ASSERT_FALSE(buttons1_3_exist); } MARLIN_TEST(macros_buttons, ANY_BUTTON) { // Test ANY_BUTTON macro int any_button1_3, any_button3_4; #if ANY_BUTTON(BUTTON1, BUTTON3) any_button1_3 = 1; #else any_button1_3 = 0; #endif #if ANY_BUTTON(BUTTON3, BUTTON4) any_button3_4 = 1; #else any_button3_4 = 0; #endif TEST_ASSERT_TRUE(any_button1_3); TEST_ASSERT_FALSE(any_button3_4); } // Undefine mock button definitions #undef BTN_BUTTON1 #undef BTN_BUTTON2 #undef BTN_BUTTON3 MARLIN_TEST(macros_value_functions, WITHIN) { // Test WITHIN macro TEST_ASSERT_TRUE(WITHIN(5, 1, 10)); // 5 is within 1 and 10 TEST_ASSERT_TRUE(WITHIN(1, 1, 10)); // Edge case: 1 is the lower limit TEST_ASSERT_TRUE(WITHIN(10, 1, 10)); // Edge case: 10 is the upper limit TEST_ASSERT_FALSE(WITHIN(0, 1, 10)); // Edge case: 0 is just below the lower limit TEST_ASSERT_FALSE(WITHIN(11, 1, 10)); // Edge case: 11 is just above the upper limit TEST_ASSERT_FALSE(WITHIN(15, 1, 10)); // 15 is not within 1 and 10 } MARLIN_TEST(macros_value_functions, ISEOL) { // Test ISEOL macro TEST_ASSERT_TRUE(ISEOL('\n')); // '\n' is an end-of-line character TEST_ASSERT_TRUE(ISEOL('\r')); // '\r' is an end-of-line character TEST_ASSERT_FALSE(ISEOL('a')); // 'a' is not an end-of-line character } MARLIN_TEST(macros_value_functions, NUMERIC) { // Test NUMERIC macro TEST_ASSERT_TRUE(NUMERIC('0')); // Edge case: '0' is the lowest numeric character TEST_ASSERT_TRUE(NUMERIC('5')); // '5' is a numeric character TEST_ASSERT_TRUE(NUMERIC('9')); // Edge case: '9' is the highest numeric character TEST_ASSERT_FALSE(NUMERIC('0' - 1)); // Edge case: '/' is just before '0' in ASCII TEST_ASSERT_FALSE(NUMERIC('9' + 1)); // Edge case: ':' is just after '9' in ASCII TEST_ASSERT_FALSE(NUMERIC('a')); // 'a' is not a numeric character } MARLIN_TEST(macros_value_functions, DECIMAL) { // Test DECIMAL macro TEST_ASSERT_TRUE(DECIMAL('0')); // Edge case: '0' is the lowest numeric character TEST_ASSERT_TRUE(DECIMAL('5')); // '5' is a numeric character TEST_ASSERT_TRUE(DECIMAL('9')); // Edge case: '9' is the highest numeric character TEST_ASSERT_TRUE(DECIMAL('.')); // '.' is a decimal character TEST_ASSERT_FALSE(DECIMAL('0' - 1)); // Edge case: '/' is just before '0' in ASCII TEST_ASSERT_FALSE(DECIMAL('9' + 1)); // Edge case: ':' is just after '9' in ASCII TEST_ASSERT_FALSE(DECIMAL('-')); // '-' is not a decimal character, but can appear in numbers TEST_ASSERT_FALSE(DECIMAL('+')); // '+' is not a decimal character, but can appear in numbers TEST_ASSERT_FALSE(DECIMAL('e')); // 'e' is not a decimal character, but can appear in scientific notation } MARLIN_TEST(macros_value_functions, HEXCHR) { // Test HEXCHR macro TEST_ASSERT_EQUAL(0, HEXCHR('0')); // Edge case: '0' is the lowest numeric character TEST_ASSERT_EQUAL(9, HEXCHR('9')); // Edge case: '9' is the highest numeric character TEST_ASSERT_EQUAL(10, HEXCHR('a')); // 'a' is a hex character with value 10 TEST_ASSERT_EQUAL(10, HEXCHR('A')); // 'A' is a hex character with value 10 TEST_ASSERT_EQUAL(15, HEXCHR('f')); // Edge case: 'f' is the highest lowercase hex character TEST_ASSERT_EQUAL(15, HEXCHR('F')); // Edge case: 'F' is the highest uppercase hex character TEST_ASSERT_EQUAL(-1, HEXCHR('g')); // 'g' is not a hex character } MARLIN_TEST(macros_value_functions, NUMERIC_SIGNED) { // Test NUMERIC_SIGNED macro TEST_ASSERT_TRUE(NUMERIC_SIGNED('0')); // Edge case: '0' is the lowest numeric character TEST_ASSERT_TRUE(NUMERIC_SIGNED('5')); // '5' is a numeric character TEST_ASSERT_TRUE(NUMERIC_SIGNED('9')); // Edge case: '9' is the highest numeric character TEST_ASSERT_TRUE(NUMERIC_SIGNED('-')); // '-' is not a numeric character, but can appear in signed numbers TEST_ASSERT_TRUE(NUMERIC_SIGNED('+')); // '+' is not a numeric character, but can appear in signed numbers TEST_ASSERT_FALSE(NUMERIC_SIGNED('.')); // '.' is not a numeric character TEST_ASSERT_FALSE(NUMERIC_SIGNED('0' - 1)); // Edge case: '/' is just before '0' in ASCII TEST_ASSERT_FALSE(NUMERIC_SIGNED('9' + 1)); // Edge case: ':' is just after '9' in ASCII TEST_ASSERT_FALSE(NUMERIC_SIGNED('e')); // 'e' is not a numeric character, but can appear in scientific notation } MARLIN_TEST(macros_value_functions, DECIMAL_SIGNED) { // Test DECIMAL_SIGNED macro TEST_ASSERT_TRUE(DECIMAL_SIGNED('0')); // Edge case: '0' is the lowest numeric character TEST_ASSERT_TRUE(DECIMAL_SIGNED('5')); // '5' is a decimal character TEST_ASSERT_TRUE(DECIMAL_SIGNED('9')); // Edge case: '9' is the highest numeric character TEST_ASSERT_TRUE(DECIMAL_SIGNED('-')); // '-' is not a numeric character, but can appear in signed numbers TEST_ASSERT_TRUE(DECIMAL_SIGNED('+')); // '+' is not a numeric character, but can appear in signed numbers TEST_ASSERT_TRUE(DECIMAL_SIGNED('.')); // '.' is a decimal character TEST_ASSERT_FALSE(DECIMAL_SIGNED('0' - 1)); // Edge case: '/' is just before '0' in ASCII TEST_ASSERT_FALSE(DECIMAL_SIGNED('9' + 1)); // Edge case: ':' is just after '9' in ASCII TEST_ASSERT_FALSE(DECIMAL_SIGNED('e')); // 'e' is not a decimal character, but can appear in scientific notation } MARLIN_TEST(macros_array, COUNT) { // Test COUNT macro int array[10]; TEST_ASSERT_EQUAL(10, COUNT(array)); // The array has 10 elements } MARLIN_TEST(macros_array, ZERO) { // Test ZERO macro int array[5] = {1, 2, 3, 4, 5}; ZERO(array); for (auto& element : array) { TEST_ASSERT_EQUAL(0, element); } } MARLIN_TEST(macros_array, COPY) { int array1[5] = {1, 2, 3, 4, 5}; int array2[5] = {0}; COPY(array2, array1); for (const auto& element : array1) { TEST_ASSERT_EQUAL(element, array2[&element - &array1[0]]); // All elements should be equal } } MARLIN_TEST(macros_expansion, CODE_N) { int a = 0; CODE_N(0, a+=1, a+=2, a+=3, a+=4, a+=5, a+=6, a+=7, a+=8, a+=9, a+=10, a+=11, a+=12, a+=13, a+=14, a+=15, a+=16); TEST_ASSERT_EQUAL(0, a); a = 0; CODE_N(1, a+=1, a+=2, a+=3, a+=4, a+=5, a+=6, a+=7, a+=8, a+=9, a+=10, a+=11, a+=12, a+=13, a+=14, a+=15, a+=16); TEST_ASSERT_EQUAL(1, a); a = 0; CODE_N(2, a+=1, a+=2, a+=3, a+=4, a+=5, a+=6, a+=7, a+=8, a+=9, a+=10, a+=11, a+=12, a+=13, a+=14, a+=15, a+=16); TEST_ASSERT_EQUAL(3, a); a = 0; CODE_N(16, a+=1, a+=2, a+=3, a+=4, a+=5, a+=6, a+=7, a+=8, a+=9, a+=10, a+=11, a+=12, a+=13, a+=14, a+=15, a+=16); TEST_ASSERT_EQUAL(136, a); // 16 is the highest number supported by the CODE_N macro } MARLIN_TEST(macros_expansion, GANG_N) { TEST_ASSERT_EQUAL(0, 0 GANG_N(0, +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, +13, +14, +15, +16)); TEST_ASSERT_EQUAL(1, 0 GANG_N(1, +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, +13, +14, +15, +16)); TEST_ASSERT_EQUAL(3, 0 GANG_N(2, +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, +13, +14, +15, +16)); TEST_ASSERT_EQUAL(136, 0 GANG_N(16, +1, +2, +3, +4, +5, +6, +7, +8, +9, +10, +11, +12, +13, +14, +15, +16)); // 16 is the highest number supported by the GANG_N macro } MARLIN_TEST(macros_expansion, GANG_N_1) { // Count by twos to be sure it can't bass by returning N TEST_ASSERT_EQUAL(0, 0 GANG_N_1(0, +2)); TEST_ASSERT_EQUAL(2, 0 GANG_N_1(1, +2)); TEST_ASSERT_EQUAL(4, 0 GANG_N_1(2, +2)); TEST_ASSERT_EQUAL(32, 0 GANG_N_1(16, +2)); } MARLIN_TEST(macros_expansion, LIST_N) { std::vector<int> expected, result; int compare_size; expected = {}; result = {LIST_N(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)}; TEST_ASSERT_EQUAL(expected.size(), result.size()); compare_size = _MIN(expected.size(), result.size()); for (int i = 0; i < compare_size; i++) { TEST_ASSERT_EQUAL(expected[i], result[i]); } expected = {1}; result = {LIST_N(1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)}; TEST_ASSERT_EQUAL(expected.size(), result.size()); compare_size = _MIN(expected.size(), result.size()); for (int i = 0; i < compare_size; i++) { TEST_ASSERT_EQUAL(expected[i], result[i]); } expected = {1, 2}; result = {LIST_N(2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)}; TEST_ASSERT_EQUAL(expected.size(), result.size()); compare_size = _MIN(expected.size(), result.size()); for (int i = 0; i < compare_size; i++) { TEST_ASSERT_EQUAL(expected[i], result[i]); } expected = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; result = {LIST_N(16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)}; TEST_ASSERT_EQUAL(expected.size(), result.size()); compare_size = _MIN(expected.size(), result.size()); for (int i = 0; i < compare_size; i++) { TEST_ASSERT_EQUAL(expected[i], result[i]); } } MARLIN_TEST(macros_expansion, LIST_N_1) { std::vector<int> expected, result; int compare_size; expected = {}; result = {LIST_N_1(0, 1)}; TEST_ASSERT_EQUAL(expected.size(), result.size()); compare_size = _MIN(expected.size(), result.size()); for (int i = 0; i < compare_size; i++) { TEST_ASSERT_EQUAL(expected[i], result[i]); } expected = {2}; result = {LIST_N_1(1, 2)}; TEST_ASSERT_EQUAL(expected.size(), result.size()); compare_size = _MIN(expected.size(), result.size()); for (int i = 0; i < compare_size; i++) { TEST_ASSERT_EQUAL(expected[i], result[i]); } expected = {1, 1}; result = {LIST_N_1(2, 1)}; TEST_ASSERT_EQUAL(expected.size(), result.size()); compare_size = _MIN(expected.size(), result.size()); for (int i = 0; i < compare_size; i++) { TEST_ASSERT_EQUAL(expected[i], result[i]); } expected = std::vector<int>(16, 1); result = {LIST_N_1(16, 1)}; TEST_ASSERT_EQUAL(expected.size(), result.size()); compare_size = _MIN(expected.size(), result.size()); for (int i = 0; i < compare_size; i++) { TEST_ASSERT_EQUAL(expected[i], result[i]); } } MARLIN_TEST(macros_expansion, ARRAY_N) { // Test ARRAY_N macro std::array<int, 5> expected = {1, 2, 3, 4, 5}; std::array<int, 5> result = ARRAY_N(5, 1, 2, 3, 4, 5); TEST_ASSERT_EQUAL(expected.size(), result.size()); std::array<int, 3> expected2 = {1, 2, 3}; std::array<int, 3> result2 = ARRAY_N(3, 1, 2, 3); TEST_ASSERT_EQUAL(expected2.size(), result2.size()); } MARLIN_TEST(macros_expansion, ARRAY_N_1) { // Test ARRAY_N_1 macro std::array<int, 5> expected = {2, 2, 2, 2, 2}; std::array<int, 5> result = ARRAY_N_1(5, 2); TEST_ASSERT_EQUAL(expected.size(), result.size()); std::array<int, 3> expected2 = {1, 1, 1}; std::array<int, 3> result2 = ARRAY_N_1(3, 1); TEST_ASSERT_EQUAL(expected2.size(), result2.size()); } MARLIN_TEST(macros_math, CEILING) { TEST_ASSERT_EQUAL(2, CEILING(3, 2)); TEST_ASSERT_EQUAL(5, CEILING(10, 2)); TEST_ASSERT_EQUAL(0, CEILING(0, 2)); } MARLIN_TEST(macros_math, ABS) { TEST_ASSERT_EQUAL(5, ABS(-5)); TEST_ASSERT_EQUAL(5, ABS(5)); TEST_ASSERT_EQUAL_FLOAT(5.5, ABS(-5.5)); TEST_ASSERT_EQUAL_FLOAT(5.5, ABS(5.5)); } MARLIN_TEST(macros_float, UNEAR_ZERO) { TEST_ASSERT_TRUE(UNEAR_ZERO(0.0000009f)); TEST_ASSERT_FALSE(UNEAR_ZERO(0.000001f)); } MARLIN_TEST(macros_float, NEAR_ZERO) { TEST_ASSERT_TRUE(NEAR_ZERO(0.0000001f)); TEST_ASSERT_TRUE(NEAR_ZERO(-0.0000001f)); TEST_ASSERT_FALSE(NEAR_ZERO(0.0000011f)); TEST_ASSERT_FALSE(NEAR_ZERO(-0.0000011f)); } MARLIN_TEST(macros_float, NEAR) { TEST_ASSERT_TRUE(NEAR(0.000001f, 0.000002f)); TEST_ASSERT_FALSE(NEAR(0.0000009f, 0.000002f)); } MARLIN_TEST(macros_float, RECIPROCAL) { TEST_ASSERT_EQUAL_FLOAT(1.0f, RECIPROCAL(1.0f)); TEST_ASSERT_EQUAL_FLOAT(0.0f, RECIPROCAL(0.0f)); TEST_ASSERT_EQUAL_FLOAT(2.0f, RECIPROCAL(0.5f)); TEST_ASSERT_EQUAL_FLOAT(-2.0f, RECIPROCAL(-0.5f)); TEST_ASSERT_EQUAL_FLOAT(0.0f, RECIPROCAL(0.0000001f)); TEST_ASSERT_EQUAL_FLOAT(0.0f, RECIPROCAL(-0.0000001f)); } MARLIN_TEST(macros_float, FIXFLOAT) { TEST_ASSERT_EQUAL(0.0000005f, FIXFLOAT(0.0f)); TEST_ASSERT_EQUAL(-0.0000005f, FIXFLOAT(-0.0f)); } MARLIN_TEST(macros_math, MATH_MACROS) { // Sanity check of macros typically mapped to compiler functions TEST_ASSERT_EQUAL_FLOAT(0.0f, ACOS(1.0f)); TEST_ASSERT_EQUAL_FLOAT(0.785398f, ATAN2(1.0f, 1.0f)); TEST_ASSERT_EQUAL_FLOAT(8.0f, POW(2.0f, 3.0f)); TEST_ASSERT_EQUAL_FLOAT(2.0f, SQRT(4.0f)); TEST_ASSERT_EQUAL_FLOAT(0.5f, RSQRT(4.0f)); TEST_ASSERT_EQUAL_FLOAT(2.0f, CEIL(1.5f)); TEST_ASSERT_EQUAL_FLOAT(1.0f, FLOOR(1.5f)); TEST_ASSERT_EQUAL_FLOAT(1.0f, TRUNC(1.5f)); TEST_ASSERT_EQUAL(2, LROUND(1.5f)); TEST_ASSERT_EQUAL_FLOAT(1.0f, FMOD(5.0f, 2.0f)); TEST_ASSERT_EQUAL_FLOAT(5.0f, HYPOT(3.0f, 4.0f)); } MARLIN_TEST(macros_math, MIN_MAX) { // _MIN tests TEST_ASSERT_EQUAL(-1, _MIN(-1, 0)); TEST_ASSERT_EQUAL(-1, _MIN(0, -1)); TEST_ASSERT_EQUAL(-1, _MIN(-1, 1)); TEST_ASSERT_EQUAL(-1, _MIN(1, -1)); TEST_ASSERT_EQUAL(-1, _MIN(-1, -1)); TEST_ASSERT_EQUAL(1, _MIN(1, 1)); TEST_ASSERT_EQUAL_FLOAT(-1.5f, _MIN(-1.5f, 0.5f)); TEST_ASSERT_EQUAL_FLOAT(-1.5f, _MIN(0.5f, -1.5f)); // _MAX tests TEST_ASSERT_EQUAL(0, _MAX(-1, 0)); TEST_ASSERT_EQUAL(0, _MAX(0, -1)); TEST_ASSERT_EQUAL(1, _MAX(-1, 1)); TEST_ASSERT_EQUAL(1, _MAX(1, -1)); TEST_ASSERT_EQUAL(-1, _MAX(-1, -1)); TEST_ASSERT_EQUAL(1, _MAX(1, 1)); TEST_ASSERT_EQUAL_FLOAT(0.5f, _MAX(-1.5f, 0.5f)); TEST_ASSERT_EQUAL_FLOAT(0.5f, _MAX(0.5f, -1.5f)); } MARLIN_TEST(macros_math, INCREMENT) { TEST_ASSERT_EQUAL(1, INCREMENT(0)); TEST_ASSERT_EQUAL(21, INCREMENT(20)); // 20 is the highest number supported by the INCREMENT macro } MARLIN_TEST(macros_math, ADD) { // Test smallest add TEST_ASSERT_EQUAL(0, ADD0(0)); TEST_ASSERT_EQUAL(10, ADD0(10)); // Test largest add TEST_ASSERT_EQUAL(10, ADD10(0)); TEST_ASSERT_EQUAL(20, ADD10(10)); } MARLIN_TEST(macros_math, SUM) { // Test smallest sum TEST_ASSERT_EQUAL(3, SUM(0, 3)); TEST_ASSERT_EQUAL(7, SUM(3, 4)); // Test largest sum TEST_ASSERT_EQUAL(15, SUM(10, 5)); TEST_ASSERT_EQUAL(19, SUM(9, 10)); } MARLIN_TEST(macros_math, DOUBLE) { // Test double TEST_ASSERT_EQUAL(0, DOUBLE(0)); TEST_ASSERT_EQUAL(2, DOUBLE(1)); TEST_ASSERT_EQUAL(4, DOUBLE(2)); TEST_ASSERT_EQUAL(20, DOUBLE(10)); } MARLIN_TEST(macros_math, DECREMENT) { TEST_ASSERT_EQUAL(0, DECREMENT(1)); TEST_ASSERT_EQUAL(14, DECREMENT(15)); } MARLIN_TEST(macros_math, SUB) { // Test smallest subtraction TEST_ASSERT_EQUAL(0, SUB0(0)); TEST_ASSERT_EQUAL(10, SUB0(10)); // Test subtracting 1 TEST_ASSERT_EQUAL(0, SUB1(1)); TEST_ASSERT_EQUAL(5, SUB1(6)); // Test largest subtraction TEST_ASSERT_EQUAL(0, SUB10(10)); TEST_ASSERT_EQUAL(5, SUB10(15)); } // Define a helper macro for testing #define TEST_OP(i) ++counter; #define TEST_OP2(i, j) counter += j; MARLIN_TEST(macros_repeat, REPEAT) { int counter = 0; REPEAT(5, TEST_OP); TEST_ASSERT_EQUAL(5, counter); } MARLIN_TEST(macros_repeat, REPEAT_1) { int counter = 0; REPEAT_1(5, TEST_OP); TEST_ASSERT_EQUAL(5, counter); } MARLIN_TEST(macros_repeat, REPEAT2) { int counter = 0; REPEAT2(5, TEST_OP2, 1); TEST_ASSERT_EQUAL(5, counter); } MARLIN_TEST(macros_repeat, RREPEAT) { int counter = 0; RREPEAT(5, TEST_OP); TEST_ASSERT_EQUAL(5, counter); } MARLIN_TEST(macros_repeat, RREPEAT_1) { int counter = 0; RREPEAT_1(5, TEST_OP); TEST_ASSERT_EQUAL(5, counter); } MARLIN_TEST(macros_repeat, RREPEAT2) { int counter = 0; RREPEAT2(5, TEST_OP2, 1); TEST_ASSERT_EQUAL(5, counter); }
2301_81045437/Marlin
Marlin/tests/core/test_macros.cpp
C++
agpl-3.0
37,728
/** * Marlin 3D Printer Firmware * Copyright (c) 2024 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #include "../test/unit_tests.h" #include "src/core/types.h" MARLIN_TEST(types, XYval_const_as_bools) { const XYval<int> xy_const_true = {1, 2}; TEST_ASSERT_TRUE(xy_const_true); const XYval<int> xy_const_false = {0, 0}; TEST_ASSERT_FALSE(xy_const_false); } MARLIN_TEST(types, XYval_non_const_as_bools) { XYval<int> xy_true = {1, 2}; TEST_ASSERT_TRUE(xy_true); XYval<int> xy_false = {0, 0}; TEST_ASSERT_FALSE(xy_false); } MARLIN_TEST(types, XYval_reset) { XYval<int> xy = {1, 2}; xy.reset(); TEST_ASSERT_EQUAL(0, xy.x); TEST_ASSERT_EQUAL(0, xy.y); } MARLIN_TEST(types, XYval_set) { XYval<int> xy; xy.set(3, 4); TEST_ASSERT_EQUAL(3, xy.x); TEST_ASSERT_EQUAL(4, xy.y); } MARLIN_TEST(types, XYval_magnitude) { XYval<int> xy; xy.set(3, 4); TEST_ASSERT_EQUAL(5, xy.magnitude()); xy.set(-3, -4); TEST_ASSERT_EQUAL(5, xy.magnitude()); xy.set(-3, 4); TEST_ASSERT_EQUAL(5, xy.magnitude()); xy.set(3, -4); TEST_ASSERT_EQUAL(5, xy.magnitude()); } MARLIN_TEST(types, XYval_small_large) { XYval<int> xy; xy.set(3, 4); TEST_ASSERT_EQUAL(3, xy.small()); TEST_ASSERT_EQUAL(4, xy.large()); xy.set(4, 3); TEST_ASSERT_EQUAL(3, xy.small()); TEST_ASSERT_EQUAL(4, xy.large()); // BUG?: Is this behavior actually correct? // Does small mean "less than", or should it mean // "closer to zero"? If the latter, then the following // tests are incorrect. xy.set(-3, -4); TEST_ASSERT_EQUAL(-4, xy.small()); TEST_ASSERT_EQUAL(-3, xy.large()); xy.set(-3, 2); TEST_ASSERT_EQUAL(-3, xy.small()); TEST_ASSERT_EQUAL(2, xy.large()); xy.set(2, -3); TEST_ASSERT_EQUAL(-3, xy.small()); TEST_ASSERT_EQUAL(2, xy.large()); } MARLIN_TEST(types, XYval_operators) { XYval<int> xy1 = {2, 3}, xy2 = {6, 12}; XYval<int> xy3 = xy1 + xy2; TEST_ASSERT_EQUAL(8, xy3.x); TEST_ASSERT_EQUAL(15, xy3.y); xy3 = xy1 - xy2; TEST_ASSERT_EQUAL(-4, xy3.x); TEST_ASSERT_EQUAL(-9, xy3.y); xy3 = xy1 * xy2; TEST_ASSERT_EQUAL(12, xy3.x); TEST_ASSERT_EQUAL(36, xy3.y); xy3 = xy2 / xy1; TEST_ASSERT_EQUAL(3, xy3.x); TEST_ASSERT_EQUAL(4, xy3.y); } MARLIN_TEST(types, XYval_ABS) { XYval<int> xy = {-3, -4}; XYval<int> xy_abs = xy.ABS(); TEST_ASSERT_EQUAL(3, xy_abs.x); TEST_ASSERT_EQUAL(4, xy_abs.y); } MARLIN_TEST(types, XYval_ROUNDL) { XYval<float> xy = {3.3f, 4.7f}; auto xy_round = xy.ROUNDL(); TEST_ASSERT_EQUAL(3, xy_round.x); TEST_ASSERT_EQUAL(5, xy_round.y); } MARLIN_TEST(types, XYval_reciprocal) { XYval<float> xy = {0.5f, 4.0f}; XYval<float> xy_reciprocal = xy.reciprocal(); TEST_ASSERT_EQUAL_FLOAT(2.0f, xy_reciprocal.x); TEST_ASSERT_EQUAL_FLOAT(0.25f, xy_reciprocal.y); } MARLIN_TEST(types, XYZval_const_as_bools) { const XYZval<int> xyz_const_true = {1, 2, 3}; TEST_ASSERT_TRUE(xyz_const_true); const XYZval<int> xyz_const_false = {0, 0, 0}; TEST_ASSERT_FALSE(xyz_const_false); } MARLIN_TEST(types, XYZval_non_const_as_bools) { XYZval<int> xyz_true = {1, 2, 3}; TEST_ASSERT_TRUE(xyz_true); XYZval<int> xyz_false = {0, 0, 0}; TEST_ASSERT_FALSE(xyz_false); } MARLIN_TEST(types, XYZval_reset) { XYZval<int> xyz = {1, 2, 3}; xyz.reset(); TEST_ASSERT_EQUAL(0, xyz.x); TEST_ASSERT_EQUAL(0, xyz.y); TEST_ASSERT_EQUAL(0, xyz.z); } MARLIN_TEST(types, XYZval_set) { XYZval<int> xyz; xyz.set(3, 4, 5); TEST_ASSERT_EQUAL(3, xyz.x); TEST_ASSERT_EQUAL(4, xyz.y); TEST_ASSERT_EQUAL(5, xyz.z); } MARLIN_TEST(types, XYZval_magnitude) { XYZval<float> xyz; xyz.set(3.0f, 4.0f, 5.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 7.071f, xyz.magnitude()); xyz.set(-3.0f, -4.0f, -5.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 7.071f, xyz.magnitude()); xyz.set(-3.0f, 4.0f, 5.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 7.071f, xyz.magnitude()); xyz.set(3.0f, -4.0f, 5.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 7.071f, xyz.magnitude()); xyz.set(3.0f, 4.0f, -5.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 7.071f, xyz.magnitude()); } MARLIN_TEST(types, XYZval_small_large) { XYZval<int> xyz; xyz.set(3, 4, 5); TEST_ASSERT_EQUAL(3, xyz.small()); TEST_ASSERT_EQUAL(5, xyz.large()); xyz.set(5, 4, 3); TEST_ASSERT_EQUAL(3, xyz.small()); TEST_ASSERT_EQUAL(5, xyz.large()); xyz.set(4, 3, 5); TEST_ASSERT_EQUAL(3, xyz.small()); TEST_ASSERT_EQUAL(5, xyz.large()); xyz.set(3, 5, 4); TEST_ASSERT_EQUAL(3, xyz.small()); TEST_ASSERT_EQUAL(5, xyz.large()); // Test with negative numbers xyz.set(-3, -4, -5); TEST_ASSERT_EQUAL(-5, xyz.small()); TEST_ASSERT_EQUAL(-3, xyz.large()); // Test with mixed negative/positive numbers xyz.set(-3, 4, 5); TEST_ASSERT_EQUAL(-3, xyz.small()); TEST_ASSERT_EQUAL(5, xyz.large()); xyz.set(3, -4, 5); TEST_ASSERT_EQUAL(-4, xyz.small()); TEST_ASSERT_EQUAL(5, xyz.large()); xyz.set(3, 4, -5); TEST_ASSERT_EQUAL(-5, xyz.small()); TEST_ASSERT_EQUAL(4, xyz.large()); } MARLIN_TEST(types, XYZval_operators) { XYZval<int> xyz1 = {2, 3, 4}, xyz2 = {6, 12, 24}; XYZval<int> xyz3 = xyz1 + xyz2; TEST_ASSERT_EQUAL(8, xyz3.x); TEST_ASSERT_EQUAL(15, xyz3.y); TEST_ASSERT_EQUAL(28, xyz3.z); xyz3 = xyz1 - xyz2; TEST_ASSERT_EQUAL(-4, xyz3.x); TEST_ASSERT_EQUAL(-9, xyz3.y); TEST_ASSERT_EQUAL(-20, xyz3.z); xyz3 = xyz1 * xyz2; TEST_ASSERT_EQUAL(12, xyz3.x); TEST_ASSERT_EQUAL(36, xyz3.y); TEST_ASSERT_EQUAL(96, xyz3.z); xyz3 = xyz2 / xyz1; TEST_ASSERT_EQUAL(3, xyz3.x); TEST_ASSERT_EQUAL(4, xyz3.y); TEST_ASSERT_EQUAL(6, xyz3.z); } MARLIN_TEST(types, XYZval_ABS) { XYZval<int> xyz = {-3, -4, -5}; XYZval<int> xyz_abs = xyz.ABS(); TEST_ASSERT_EQUAL(3, xyz_abs.x); TEST_ASSERT_EQUAL(4, xyz_abs.y); TEST_ASSERT_EQUAL(5, xyz_abs.z); } MARLIN_TEST(types, XYZval_ROUNDL) { XYZval<float> xyz = {3.3f, 4.7f, 5.5f}; XYZval<int> xyz_round = xyz.ROUNDL(); TEST_ASSERT_EQUAL(3, xyz_round.x); TEST_ASSERT_EQUAL(5, xyz_round.y); TEST_ASSERT_EQUAL(6, xyz_round.z); } MARLIN_TEST(types, XYZval_reciprocal) { XYZval<float> xyz = {0.5f, 2.0f, 0.33333f}; XYZval<float> xyz_reciprocal = xyz.reciprocal(); TEST_ASSERT_EQUAL_FLOAT(2.0f, xyz_reciprocal.x); TEST_ASSERT_EQUAL_FLOAT(0.5f, xyz_reciprocal.y); TEST_ASSERT_FLOAT_WITHIN(0.001f, 3.0f, xyz_reciprocal.z); } MARLIN_TEST(types, XYZEval_const_as_bools) { const XYZEval<int> xyze_const_true = {1, 2, 3, 4}; TEST_ASSERT_TRUE(xyze_const_true); const XYZEval<int> xyze_const_false = {0, 0, 0, 0}; TEST_ASSERT_FALSE(xyze_const_false); } MARLIN_TEST(types, XYZEval_non_const_as_bools) { XYZEval<int> xyze_true = {1, 2, 3, 4}; TEST_ASSERT_TRUE(xyze_true); XYZEval<int> xyze_false = {0, 0, 0, 0}; TEST_ASSERT_FALSE(xyze_false); } MARLIN_TEST(types, XYZEval_reset) { XYZEval<int> xyze = {1, 2, 3, 4}; xyze.reset(); TEST_ASSERT_EQUAL(0, xyze.x); TEST_ASSERT_EQUAL(0, xyze.y); TEST_ASSERT_EQUAL(0, xyze.z); TEST_ASSERT_EQUAL(0, xyze.e); } MARLIN_TEST(types, XYZEval_set) { XYZEval<int> xyze; xyze.set(3, 4, 5, 6); TEST_ASSERT_EQUAL(3, xyze.x); TEST_ASSERT_EQUAL(4, xyze.y); TEST_ASSERT_EQUAL(5, xyze.z); TEST_ASSERT_EQUAL(6, xyze.e); } MARLIN_TEST(types, XYZEval_magnitude) { XYZEval<float> xyze; xyze.set(3.0f, 4.0f, 5.0f, 6.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 9.274f, xyze.magnitude()); xyze.set(-3.0f, -4.0f, -5.0f, -6.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 9.274f, xyze.magnitude()); xyze.set(-3.0f, 4.0f, 5.0f, 6.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 9.274f, xyze.magnitude()); xyze.set(3.0f, -4.0f, 5.0f, 6.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 9.274f, xyze.magnitude()); xyze.set(3.0f, 4.0f, -5.0f, 6.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 9.274f, xyze.magnitude()); xyze.set(3.0f, 4.0f, 5.0f, -6.0f); TEST_ASSERT_FLOAT_WITHIN(0.001f, 9.274f, xyze.magnitude()); } MARLIN_TEST(types, XYZEval_small_large) { XYZEval<int> xyze; xyze.set(3, 4, 5, 6); TEST_ASSERT_EQUAL(3, xyze.small()); TEST_ASSERT_EQUAL(6, xyze.large()); xyze.set(6, 5, 4, 3); TEST_ASSERT_EQUAL(3, xyze.small()); TEST_ASSERT_EQUAL(6, xyze.large()); xyze.set(4, 3, 6, 5); TEST_ASSERT_EQUAL(3, xyze.small()); TEST_ASSERT_EQUAL(6, xyze.large()); xyze.set(3, 6, 5, 4); TEST_ASSERT_EQUAL(3, xyze.small()); TEST_ASSERT_EQUAL(6, xyze.large()); xyze.set(-3, -4, -5, -6); TEST_ASSERT_EQUAL(-6, xyze.small()); TEST_ASSERT_EQUAL(-3, xyze.large()); xyze.set(-3, 4, 5, 6); TEST_ASSERT_EQUAL(-3, xyze.small()); TEST_ASSERT_EQUAL(6, xyze.large()); xyze.set(3, -4, 5, 6); TEST_ASSERT_EQUAL(-4, xyze.small()); TEST_ASSERT_EQUAL(6, xyze.large()); xyze.set(3, 4, -5, 6); TEST_ASSERT_EQUAL(-5, xyze.small()); TEST_ASSERT_EQUAL(6, xyze.large()); xyze.set(3, 4, 5, -6); TEST_ASSERT_EQUAL(-6, xyze.small()); TEST_ASSERT_EQUAL(5, xyze.large()); } MARLIN_TEST(types, XYZEval_operators) { XYZEval<int> xyze1 = {2, 3, 4, 5}, xyze2 = {6, 12, 24, 48}; XYZEval<int> xyze3 = xyze1 + xyze2; TEST_ASSERT_EQUAL(8, xyze3.x); TEST_ASSERT_EQUAL(15, xyze3.y); TEST_ASSERT_EQUAL(28, xyze3.z); TEST_ASSERT_EQUAL(53, xyze3.e); xyze3 = xyze1 - xyze2; TEST_ASSERT_EQUAL(-4, xyze3.x); TEST_ASSERT_EQUAL(-9, xyze3.y); TEST_ASSERT_EQUAL(-20, xyze3.z); TEST_ASSERT_EQUAL(-43, xyze3.e); xyze3 = xyze1 * xyze2; TEST_ASSERT_EQUAL(12, xyze3.x); TEST_ASSERT_EQUAL(36, xyze3.y); TEST_ASSERT_EQUAL(96, xyze3.z); TEST_ASSERT_EQUAL(240, xyze3.e); xyze3 = xyze2 / xyze1; TEST_ASSERT_EQUAL(3, xyze3.x); TEST_ASSERT_EQUAL(4, xyze3.y); TEST_ASSERT_EQUAL(6, xyze3.z); TEST_ASSERT_EQUAL(9, xyze3.e); } MARLIN_TEST(types, XYZEval_ABS) { XYZEval<int> xyze = {-3, -4, -5, -6}; XYZEval<int> xyze_abs = xyze.ABS(); TEST_ASSERT_EQUAL(3, xyze_abs.x); TEST_ASSERT_EQUAL(4, xyze_abs.y); TEST_ASSERT_EQUAL(5, xyze_abs.z); TEST_ASSERT_EQUAL(6, xyze_abs.e); } MARLIN_TEST(types, XYZEval_ROUNDL) { XYZEval<float> xyze = {3.3f, 4.7f, 5.5f, 6.6f}; XYZEval<int> xyze_round = xyze.ROUNDL(); TEST_ASSERT_EQUAL(3, xyze_round.x); TEST_ASSERT_EQUAL(5, xyze_round.y); TEST_ASSERT_EQUAL(6, xyze_round.z); TEST_ASSERT_EQUAL(7, xyze_round.e); } MARLIN_TEST(types, XYZEval_reciprocal) { XYZEval<float> xyze = {0.5f, 2.0f, 0.33333f, 0.25f}; XYZEval<float> xyze_reciprocal = xyze.reciprocal(); TEST_ASSERT_EQUAL_FLOAT(2.0f, xyze_reciprocal.x); TEST_ASSERT_EQUAL_FLOAT(0.5f, xyze_reciprocal.y); TEST_ASSERT_FLOAT_WITHIN(0.001f, 3.0f, xyze_reciprocal.z); TEST_ASSERT_EQUAL_FLOAT(4.0f, xyze_reciprocal.e); } MARLIN_TEST(types, Flags_const_as_bools) { const Flags<32> flags_const_false = {0}; TEST_ASSERT_FALSE(flags_const_false); const Flags<32> flags_const_true = {1}; TEST_ASSERT_TRUE(flags_const_true); } MARLIN_TEST(types, Flags_non_const_as_bools) { Flags<32> flags_false = {0}; TEST_ASSERT_FALSE(flags_false); Flags<32> flags_true = {1}; TEST_ASSERT_TRUE(flags_true); } MARLIN_TEST(types, Flags_1) { Flags<1> flags; flags.set(0, true); TEST_ASSERT_EQUAL(1, flags.b); flags.reset(); TEST_ASSERT_EQUAL(0, flags.b); flags.set(0, true); flags.clear(0); TEST_ASSERT_EQUAL(0, flags.b); TEST_ASSERT_EQUAL(false, flags.test(0)); flags.set(0, true); TEST_ASSERT_EQUAL(true, flags.test(0)); TEST_ASSERT_EQUAL(true, flags[0]); flags.clear(0); TEST_ASSERT_EQUAL(false, flags[0]); TEST_ASSERT_EQUAL(1, flags.size()); } MARLIN_TEST(types, Flags_8) { Flags<8> flags; flags.reset(); TEST_ASSERT_EQUAL(0, flags.b); flags.set(3, true); TEST_ASSERT_EQUAL(8, flags.b); flags.clear(3); TEST_ASSERT_EQUAL(0, flags.b); flags.set(3, true); TEST_ASSERT_EQUAL(true, flags.test(3)); TEST_ASSERT_EQUAL(false, flags.test(2)); TEST_ASSERT_EQUAL(true, flags[3]); TEST_ASSERT_EQUAL(false, flags[2]); TEST_ASSERT_EQUAL(1, flags.size()); } MARLIN_TEST(types, Flags_16) { Flags<16> flags; flags.reset(); TEST_ASSERT_EQUAL(0, flags.b); flags.set(0, true); flags.set(15, true); TEST_ASSERT_EQUAL(32769, flags.b); flags.clear(0); TEST_ASSERT_EQUAL(32768, flags.b); flags.reset(); flags.set(7, true); flags.set(15, true); TEST_ASSERT_EQUAL(true, flags.test(7)); TEST_ASSERT_EQUAL(false, flags.test(8)); TEST_ASSERT_EQUAL(true, flags.test(15)); TEST_ASSERT_EQUAL(true, flags[7]); TEST_ASSERT_EQUAL(false, flags[8]); TEST_ASSERT_EQUAL(true, flags[15]); TEST_ASSERT_EQUAL(2, flags.size()); } MARLIN_TEST(types, Flags_32) { Flags<32> flags; flags.reset(); TEST_ASSERT_EQUAL(0, flags.b); flags.set(0, true); flags.set(31, true); TEST_ASSERT_EQUAL(2147483649, flags.b); flags.clear(0); flags.clear(31); TEST_ASSERT_EQUAL(0, flags.b); flags.set(0, true); flags.set(31, true); TEST_ASSERT_EQUAL(true, flags.test(0)); TEST_ASSERT_EQUAL(true, flags.test(31)); TEST_ASSERT_EQUAL(false, flags.test(1)); TEST_ASSERT_EQUAL(false, flags.test(30)); TEST_ASSERT_EQUAL(true, flags[0]); TEST_ASSERT_EQUAL(true, flags[31]); TEST_ASSERT_EQUAL(false, flags[1]); TEST_ASSERT_EQUAL(false, flags[30]); TEST_ASSERT_EQUAL(4, flags.size()); } MARLIN_TEST(types, AxisFlags_const_as_bools) { const AxisFlags axis_flags_const_false = {0}; TEST_ASSERT_FALSE(axis_flags_const_false); const AxisFlags axis_flags_const_true = {1}; TEST_ASSERT_TRUE(axis_flags_const_true); } MARLIN_TEST(types, AxisFlags_non_const_as_bools) { AxisFlags axis_flags_false = {0}; TEST_ASSERT_FALSE(axis_flags_false); AxisFlags axis_flags_true = {1}; TEST_ASSERT_TRUE(axis_flags_true); } MARLIN_TEST(types, AxisBits_const_as_bools) { const AxisBits axis_bits_const_false = {0}; TEST_ASSERT_FALSE(axis_bits_const_false); const AxisBits axis_bits_const_true = {1}; TEST_ASSERT_TRUE(axis_bits_const_true); } MARLIN_TEST(types, AxisBits_non_const_as_bools) { AxisBits axis_bits_false = {0}; TEST_ASSERT_FALSE(axis_bits_false); AxisBits axis_bits_true = {1}; TEST_ASSERT_TRUE(axis_bits_true); } MARLIN_TEST(types, MString1) { // String with cutoff at 20 chars: // "F-string, 1234.50, 2" MString<20> str20; str20 = F("F-string, "); str20.append(1234.5f).append(',').append(' ') .append(2345.67).append(',').append(' '); TEST_ASSERT_TRUE(strcmp_P(str20, PSTR("F-string, 1234.50, 2")) == 0); // Truncate to "F-string" str20.trunc(8); TEST_ASSERT_FALSE(strcmp_P(&str20, PSTR("F-string")) != 0); } MARLIN_TEST(types, MString2) { // 100 dashes, but chopped down to DEFAULT_MSTRING_SIZE (20) TEST_ASSERT_TRUE(TSS(repchr_t('-', 100)).length() == 20); } MARLIN_TEST(types, SString) { // Hello World!-123456------ < spaces!33 // ^ eol! ... 1234.50*2345.602 = 2895645.67 SString<100> str(F("Hello")); str.append(F(" World!")); str += '-'; str += uint8_t(123); str += F("456"); str += repchr_t('-', 6); str += Spaces(3); str += "< spaces!"; str += int8_t(33); str.eol(); str += "^ eol!"; str.append(" ... ", 1234.5f, '*', p_float_t(2345.602, 3), F(" = "), 1234.5 * 2345.602); TEST_ASSERT_TRUE(strcmp_P(str, PSTR("Hello World!-123456------ < spaces!33\n^ eol! ... 1234.50*2345.602 = 2895645.67")) == 0); }
2301_81045437/Marlin
Marlin/tests/core/test_types.cpp
C++
agpl-3.0
15,829
/** * Marlin 3D Printer Firmware * Copyright (c) 2024 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #include "../test/unit_tests.h" #if ENABLED(FILAMENT_RUNOUT_SENSOR) #include <src/feature/runout.h> MARLIN_TEST(runout, poll_runout_states) { FilamentSensorBase sensor; // Expected default value is one bit set for each extruder uint8_t expected = static_cast<uint8_t>(~(~0u << NUM_RUNOUT_SENSORS)); TEST_ASSERT_EQUAL(expected, sensor.poll_runout_states()); } #endif
2301_81045437/Marlin
Marlin/tests/feature/test_runout.cpp
C++
agpl-3.0
1,241
/** * Marlin 3D Printer Firmware * Copyright (c) 2024 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ #include "../test/unit_tests.h" #include <src/gcode/gcode.h> #include <src/gcode/parser.h> MARLIN_TEST(gcode, process_parsed_command) { GcodeSuite suite; parser.command_letter = 'G'; parser.codenum = 0; suite.process_parsed_command(false); } MARLIN_TEST(gcode, parse_g1_xz) { char current_command[] = "G0 X10 Z30"; parser.command_letter = -128; parser.codenum = -1; parser.parse(current_command); TEST_ASSERT_EQUAL('G', parser.command_letter); TEST_ASSERT_EQUAL(0, parser.codenum); TEST_ASSERT_TRUE(parser.seen('X')); TEST_ASSERT_FALSE(parser.seen('Y')); TEST_ASSERT_TRUE(parser.seen('Z')); TEST_ASSERT_FALSE(parser.seen('E')); } MARLIN_TEST(gcode, parse_g1_nxz) { char current_command[] = "N123 G0 X10 Z30"; parser.command_letter = -128; parser.codenum = -1; parser.parse(current_command); TEST_ASSERT_EQUAL('G', parser.command_letter); TEST_ASSERT_EQUAL(0, parser.codenum); TEST_ASSERT_TRUE(parser.seen('X')); TEST_ASSERT_FALSE(parser.seen('Y')); TEST_ASSERT_TRUE(parser.seen('Z')); TEST_ASSERT_FALSE(parser.seen('E')); }
2301_81045437/Marlin
Marlin/tests/gcode/test_gcode.cpp
C++
agpl-3.0
1,938
# # SAMD21_minitronics20.py # Customizations for env:SAMD21_minitronics20 # import pioutil if pioutil.is_pio_build(): from os.path import join, isfile import shutil Import("env") mf = env["MARLIN_FEATURES"] rxBuf = mf["RX_BUFFER_SIZE"] if "RX_BUFFER_SIZE" in mf else "0" txBuf = mf["TX_BUFFER_SIZE"] if "TX_BUFFER_SIZE" in mf else "0" serialBuf = str(max(int(rxBuf), int(txBuf), 350)) build_flags = env.get('BUILD_FLAGS') env.Replace(BUILD_FLAGS=build_flags)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/SAMD21_minitronics20.py
Python
agpl-3.0
499
# # SAMD51_grandcentral_m4.py # Customizations for env:SAMD51_grandcentral_m4 # import pioutil if pioutil.is_pio_build(): from os.path import join, isfile import shutil Import("env") mf = env["MARLIN_FEATURES"] rxBuf = mf["RX_BUFFER_SIZE"] if "RX_BUFFER_SIZE" in mf else "0" txBuf = mf["TX_BUFFER_SIZE"] if "TX_BUFFER_SIZE" in mf else "0" serialBuf = str(max(int(rxBuf), int(txBuf), 350)) build_flags = env.get('BUILD_FLAGS') build_flags.append("-DSERIAL_BUFFER_SIZE=" + serialBuf) env.Replace(BUILD_FLAGS=build_flags)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/SAMD51_grandcentral_m4.py
Python
agpl-3.0
563
# # STM32F103RC_MEEB_3DP.py # import pioutil if pioutil.is_pio_build(): Import("env", "projenv") flash_size = 0 vect_tab_addr = 0 for define in env['CPPDEFINES']: if define[0] == "VECT_TAB_ADDR": vect_tab_addr = define[1] if define[0] == "STM32_FLASH_SIZE": flash_size = define[1] print('Use the {0:s} address as the marlin app entry point.'.format(vect_tab_addr)) print('Use the {0:d}KB flash version of stm32f103rct6 chip.'.format(flash_size))
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/STM32F103RC_MEEB_3DP.py
Python
agpl-3.0
514
# # STM32F103RC_fysetc.py # import pioutil if pioutil.is_pio_build(): from os.path import join from os.path import expandvars Import("env") # Custom HEX from ELF env.AddPostAction( join("$BUILD_DIR", "${PROGNAME}.elf"), env.VerboseAction(" ".join([ "$OBJCOPY", "-O ihex", "$TARGET", "\"" + join("$BUILD_DIR", "${PROGNAME}.hex") + "\"", # Note: $BUILD_DIR is a full path ]), "Building $TARGET")) # In-line command with arguments UPLOAD_TOOL="stm32flash" platform = env.PioPlatform() if platform.get_package_dir("tool-stm32duino") != None: UPLOAD_TOOL=expandvars("\"" + join(platform.get_package_dir("tool-stm32duino"),"stm32flash","stm32flash") + "\"") env.Replace( UPLOADER=UPLOAD_TOOL, UPLOADCMD=expandvars(UPLOAD_TOOL + " -v -i rts,-dtr,dtr -R -b 115200 -g 0x8000000 -w \"" + join("$BUILD_DIR","${PROGNAME}.hex")+"\"" + " $UPLOAD_PORT") )
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/STM32F103RC_fysetc.py
Python
agpl-3.0
960
# # STM32F1_create_variant.py # import pioutil if pioutil.is_pio_build(): import shutil,marlin from pathlib import Path Import("env") platform = env.PioPlatform() board = env.BoardConfig() FRAMEWORK_DIR = Path(platform.get_package_dir("framework-arduinoststm32-maple")) assert FRAMEWORK_DIR.is_dir() source_root = Path("buildroot/share/PlatformIO/variants") assert source_root.is_dir() variant = board.get("build.variant") variant_dir = FRAMEWORK_DIR / "STM32F1/variants" / variant source_dir = source_root / variant assert source_dir.is_dir() if variant_dir.is_dir(): shutil.rmtree(variant_dir) if not variant_dir.is_dir(): variant_dir.mkdir() marlin.copytree(source_dir, variant_dir)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/STM32F1_create_variant.py
Python
agpl-3.0
774
# # add_nanolib.py # Import("env") env.Append(LINKFLAGS=["--specs=nano.specs"])
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/add_nanolib.py
Python
agpl-3.0
81
# # chitu_crypt.py # Customizations for Chitu boards # import pioutil if pioutil.is_pio_build(): import struct,uuid,marlin board = marlin.env.BoardConfig() def calculate_crc(contents, seed): accumulating_xor_value = seed for i in range(0, len(contents), 4): value = struct.unpack('<I', contents[ i : i + 4])[0] accumulating_xor_value = accumulating_xor_value ^ value return accumulating_xor_value def xor_block(r0, r1, block_number, block_size, file_key): # This is the loop counter loop_counter = 0x0 # This is the key length key_length = 0x18 # This is an initial seed xor_seed = 0x4BAD # This is the block counter block_number = xor_seed * block_number #load the xor key from the file r7 = file_key for loop_counter in range(0, block_size): # meant to make sure different bits of the key are used. xor_seed = int(loop_counter / key_length) # IP is a scratch register / R12 ip = loop_counter - (key_length * xor_seed) # xor_seed = (loop_counter * loop_counter) + block_number xor_seed = (loop_counter * loop_counter) + block_number # shift the xor_seed left by the bits in IP. xor_seed = xor_seed >> ip # load a byte into IP ip = r0[loop_counter] # XOR the seed with r7 xor_seed = xor_seed ^ r7 # and then with IP xor_seed = xor_seed ^ ip #Now store the byte back r1[loop_counter] = xor_seed & 0xFF #increment the loop_counter loop_counter = loop_counter + 1 def encrypt_file(input, output_file, file_length): input_file = bytearray(input.read()) block_size = 0x800 key_length = 0x18 uid_value = uuid.uuid4() file_key = int(uid_value.hex[0:8], 16) xor_crc = 0xEF3D4323 # the input file is exepcted to be in chunks of 0x800 # so round the size while len(input_file) % block_size != 0: input_file.extend(b'0x0') # write the file header output_file.write(struct.pack(">I", 0x443D2D3F)) # encrypt the contents using a known file header key # write the file_key output_file.write(struct.pack("<I", file_key)) #TODO - how to enforce that the firmware aligns to block boundaries? block_count = int(len(input_file) / block_size) print ("Block Count is ", block_count) for block_number in range(0, block_count): block_offset = (block_number * block_size) block_end = block_offset + block_size block_array = bytearray(input_file[block_offset: block_end]) xor_block(block_array, block_array, block_number, block_size, file_key) for n in range (0, block_size): input_file[block_offset + n] = block_array[n] # update the expected CRC value. xor_crc = calculate_crc(block_array, xor_crc) # write CRC output_file.write(struct.pack("<I", xor_crc)) # finally, append the encrypted results. output_file.write(input_file) return # Encrypt ${PROGNAME}.bin and save it as 'update.cbd' def encrypt(source, target, env): from pathlib import Path fwpath = Path(target[0].path) fwsize = fwpath.stat().st_size enname = board.get("build.crypt_chitu") enpath = Path(target[0].dir.path) fwfile = fwpath.open("rb") enfile = (enpath / enname).open("wb") print(f"Encrypting {fwpath} to {enname}") encrypt_file(fwfile, enfile, fwsize) fwfile.close() enfile.close() fwpath.unlink() marlin.relocate_firmware("0x08008800") marlin.add_post_action(encrypt)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/chitu_crypt.py
Python
agpl-3.0
3,935
# # collect-code-tests.py # Convenience script to collect all code tests. Used by env:linux_native_test in native.ini. # import pioutil if pioutil.is_pio_build(): import os, re Import("env") Import("projenv") os.environ['PATH'] = f"./buildroot/bin/:./buildroot/tests/:{os.environ['PATH']}" def collect_test_suites(): """Get all the test suites""" from pathlib import Path return sorted(list(Path("./test").glob("*.ini"))) def register_test_suites(): """Register all the test suites""" targets = [] test_suites = collect_test_suites() for path in test_suites: name = re.sub(r'^\d+-|\.ini$', '', path.name) targets += [name]; env.AddCustomTarget( name = f"marlin_{name}", dependencies = None, actions = [ f"echo ====== Configuring for marlin_{name} ======", "restore_configs", f"cp -f {path} ./Marlin/config.ini", "python ./buildroot/share/PlatformIO/scripts/configuration.py", f"platformio test -e linux_native_test -f {name}", "restore_configs", ], title = "Marlin: {}".format(name.lower().title().replace("_", " ")), description = ( f"Run a Marlin test suite, with the appropriate configuration, " f"that sits in {path}" ) ) env.AddCustomTarget( name = "test-marlin", dependencies = None, actions = [ f"platformio run -t marlin_{name} -e linux_native_test" for name in targets ], title = "Marlin: Test all code test suites", description = ( f"Run all Marlin code test suites ({len(targets)} found)." ), ) register_test_suites()
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/collect-code-tests.py
Python
agpl-3.0
1,989
# # common-cxxflags.py # Convenience script to apply customizations to CPP flags # import pioutil if pioutil.is_pio_build(): Import("env") cxxflags = [ # "-Wno-incompatible-pointer-types", # "-Wno-unused-const-variable", # "-Wno-maybe-uninitialized", # "-Wno-sign-compare" ] if "teensy" not in env["PIOENV"]: cxxflags += ["-Wno-register"] env.Append(CXXFLAGS=cxxflags) # # Add CPU frequency as a compile time constant instead of a runtime variable # def add_cpu_freq(): if "BOARD_F_CPU" in env: env["BUILD_FLAGS"].append("-DBOARD_F_CPU=" + env["BOARD_F_CPU"]) # Useful for JTAG debugging # # It will separate release and debug build folders. # It useful to keep two live versions: a debug version for debugging and another for # release, for flashing when upload is not done automatically by jlink/stlink. # Without this, PIO needs to recompile everything twice for any small change. if env.GetBuildType() == "debug" and env.get("UPLOAD_PROTOCOL") not in ["jlink", "stlink", "custom"]: env["BUILD_DIR"] = "$PROJECT_BUILD_DIR/$PIOENV/debug" def on_program_ready(source, target, env): import shutil shutil.copy(target[0].get_abspath(), env.subst("$PROJECT_BUILD_DIR/$PIOENV")) env.AddPostAction("$PROGPATH", on_program_ready) # On some platform, F_CPU is a runtime variable. Since it's used to convert from ns # to CPU cycles, this adds overhead preventing small delay (in the order of less than # 30 cycles) to be generated correctly. By using a compile time constant instead # the compiler will perform the computation and this overhead will be avoided add_cpu_freq()
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/common-cxxflags.py
Python
agpl-3.0
1,767
# # post:common-dependencies-post.py # Convenience script to add build flags for Marlin Enabled Features # import pioutil if pioutil.is_pio_build(): Import("env", "projenv") def apply_board_build_flags(): if not 'BOARD_CUSTOM_BUILD_FLAGS' in env['MARLIN_FEATURES']: return projenv.Append(CCFLAGS=env['MARLIN_FEATURES']['BOARD_CUSTOM_BUILD_FLAGS'].split()) # We need to add the board build flags in a post script # so the platform build script doesn't overwrite the custom CCFLAGS apply_board_build_flags()
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/common-dependencies-post.py
Python
agpl-3.0
556
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 <https://www.gnu.org/licenses/>. * */ /** * The purpose of this file is just include Marlin Configuration files, * to discover which FEATURES are enabled, without any HAL include. * Used by common-dependencies.py */ #include "../../../../Marlin/src/inc/MarlinConfig.h" // // Conditionals only used for [features] // #if ENABLED(SR_LCD_3W_NL) // Feature checks for SR_LCD_3W_NL #elif ANY(LCD_I2C_TYPE_MCP23017, LCD_I2C_TYPE_MCP23008) #define USES_LIQUIDTWI2 #elif ENABLED(LCD_I2C_TYPE_PCA8574) #define USES_LIQUIDCRYSTAL_I2C #elif ANY(HAS_MARLINUI_HD44780, LCD_I2C_TYPE_PCF8575, SR_LCD_2W_NL, LCM1602) #define USES_LIQUIDCRYSTAL #endif #if SAVED_POSITIONS #define HAS_SAVED_POSITIONS #endif #if ENABLED(DUET_SMART_EFFECTOR) && PIN_EXISTS(SMART_EFFECTOR_MOD) #define HAS_SMART_EFF_MOD #endif #if HAS_MARLINUI_MENU #if ENABLED(BACKLASH_GCODE) #define HAS_MENU_BACKLASH #endif #if ENABLED(LCD_BED_TRAMMING) #define HAS_MENU_BED_TRAMMING #endif #if ENABLED(CANCEL_OBJECTS) #define HAS_MENU_CANCELOBJECT #endif #if ANY(DELTA_CALIBRATION_MENU, DELTA_AUTO_CALIBRATION) #define HAS_MENU_DELTA_CALIBRATE #endif #if ANY(LED_CONTROL_MENU, CASE_LIGHT_MENU) #define HAS_MENU_LED #endif #if ENABLED(ADVANCED_PAUSE_FEATURE) #define HAS_MENU_FILAMENT #endif #if HAS_MEDIA #define HAS_MENU_MEDIA #endif #if ENABLED(MIXING_EXTRUDER) #define HAS_MENU_MIXER #endif #if ENABLED(POWER_LOSS_RECOVERY) #define HAS_MENU_JOB_RECOVERY #endif #if HAS_POWER_MONITOR #define HAS_MENU_POWER_MONITOR #endif #if HAS_CUTTER #define HAS_MENU_CUTTER #endif #if HAS_TEMPERATURE #define HAS_MENU_TEMPERATURE #endif #if ENABLED(MMU2_MENUS) #define HAS_MENU_MMU2 #endif #if ENABLED(PASSWORD_FEATURE) #define HAS_MENU_PASSWORD #endif #if HAS_TRINAMIC_CONFIG #define HAS_MENU_TMC #endif #if ENABLED(TOUCH_SCREEN_CALIBRATION) #define HAS_MENU_TOUCH_SCREEN #endif #if ENABLED(ASSISTED_TRAMMING_WIZARD) #define HAS_MENU_TRAMMING_WIZARD #endif #if ENABLED(AUTO_BED_LEVELING_UBL) #define HAS_MENU_UBL #endif #if ENABLED(ONE_CLICK_PRINT) #define HAS_MENU_ONE_CLICK_PRINT #endif #endif #if HAS_GRAPHICAL_TFT #include "../../../../Marlin/src/lcd/tft/fontdata/fontdata.h" #define UI_INCL_(W, H) STRINGIFY_(../../../../Marlin/src/lcd/tft/ui_##W##x##H.h) #define UI_INCL(W, H) UI_INCL_(W, H) #include UI_INCL(TFT_WIDTH, TFT_HEIGHT) #define Latin_Extended_A 1 #define Cyrillic 2 #define Greek 3 #define Katakana 4 #define Korean 5 #define Vietnamese 6 #define Simplified_Chinese 7 #define Traditional_Chinese 8 #if TFT_FONT == NOTOSANS #if FONT_SIZE == 14 #define TFT_FONT_NOTOSANS_14 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_NOTOSANS_14_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_NOTOSANS_14_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_NOTOSANS_14_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_NOTOSANS_14_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_NOTOSANS_14_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_NOTOSANS_14_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_NOTOSANS_14_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_NOTOSANS_14_ZH_TW #endif #elif FONT_SIZE == 16 #define TFT_FONT_NOTOSANS_16 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_NOTOSANS_16_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_NOTOSANS_16_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_NOTOSANS_16_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_NOTOSANS_16_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_NOTOSANS_16_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_NOTOSANS_16_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_NOTOSANS_16_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_NOTOSANS_16_ZH_TW #endif #elif FONT_SIZE == 19 #define TFT_FONT_NOTOSANS_19 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_NOTOSANS_19_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_NOTOSANS_19_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_NOTOSANS_19_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_NOTOSANS_19_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_NOTOSANS_19_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_NOTOSANS_19_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_NOTOSANS_19_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_NOTOSANS_19_ZH_TW #endif #elif FONT_SIZE == 26 #define TFT_FONT_NOTOSANS_26 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_NOTOSANS_26_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_NOTOSANS_26_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_NOTOSANS_26_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_NOTOSANS_26_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_NOTOSANS_26_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_NOTOSANS_26_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_NOTOSANS_26_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_NOTOSANS_26_ZH_TW #endif #elif FONT_SIZE == 27 #define TFT_FONT_NOTOSANS_27 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_NOTOSANS_27_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_NOTOSANS_27_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_NOTOSANS_27_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_NOTOSANS_27_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_NOTOSANS_27_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_NOTOSANS_27_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_NOTOSANS_27_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_NOTOSANS_27_ZH_TW #endif #elif FONT_SIZE == 28 #define TFT_FONT_NOTOSANS_28 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_NOTOSANS_28_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_NOTOSANS_28_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_NOTOSANS_28_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_NOTOSANS_28_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_NOTOSANS_28_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_NOTOSANS_28_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_NOTOSANS_28_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_NOTOSANS_28_ZH_TW #endif #elif FONT_SIZE == 29 #define TFT_FONT_NOTOSANS_29 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_NOTOSANS_29_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_NOTOSANS_29_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_NOTOSANS_29_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_NOTOSANS_29_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_NOTOSANS_29_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_NOTOSANS_29_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_NOTOSANS_29_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_NOTOSANS_29_ZH_TW #endif #endif #elif TFT_FONT == UNIFONT #if FONT_SIZE == 10 #define TFT_FONT_UNIFONT_10 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_UNIFONT_10_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_UNIFONT_10_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_UNIFONT_10_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_UNIFONT_10_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_UNIFONT_10_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_UNIFONT_10_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_UNIFONT_10_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_UNIFONT_10_ZH_TW #endif #elif FONT_SIZE == 20 #define TFT_FONT_UNIFONT_20 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_UNIFONT_20_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_UNIFONT_20_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_UNIFONT_20_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_UNIFONT_20_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_UNIFONT_20_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_UNIFONT_20_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_UNIFONT_20_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_UNIFONT_20_ZH_TW #endif #elif FONT_SIZE == 30 #define TFT_FONT_UNIFONT_30 #if FONT_EXTRA == Latin_Extended_A #define TFT_FONT_UNIFONT_30_LATIN #elif FONT_EXTRA == Cyrillic #define TFT_FONT_UNIFONT_30_CYRIL #elif FONT_EXTRA == Greek #define TFT_FONT_UNIFONT_30_GREEK #elif FONT_EXTRA == Katakana #define TFT_FONT_UNIFONT_30_KATA #elif FONT_EXTRA == Korean #define TFT_FONT_UNIFONT_30_KO #elif FONT_EXTRA == Vietnamese #define TFT_FONT_UNIFONT_30_VI #elif FONT_EXTRA == Simplified_Chinese #define TFT_FONT_UNIFONT_30_ZH_CN #elif FONT_EXTRA == Traditional_Chinese #define TFT_FONT_UNIFONT_30_ZH_TW #endif #endif #elif TFT_FONT == HELVETICA #if FONT_SIZE == 14 #define TFT_FONT_HELVETICA_14 #elif FONT_SIZE == 19 #define TFT_FONT_HELVETICA_19 #endif #endif #endif
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/common-dependencies.h
C
agpl-3.0
10,856
# # common-dependencies.py # Convenience script to check dependencies and add libs and sources for Marlin Enabled Features # import pioutil if pioutil.is_pio_build(): import subprocess,os,re,fnmatch,glob srcfilepattern = re.compile(r".*[.](cpp|c)$") marlinbasedir = os.path.join(os.getcwd(), "Marlin/") Import("env") from platformio.package.meta import PackageSpec from platformio.project.config import ProjectConfig verbose = 0 FEATURE_CONFIG = {} def validate_pio(): PIO_VERSION_MIN = (6, 0, 1) try: from platformio import VERSION as PIO_VERSION weights = (1000, 100, 1) version_min = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION_MIN)]) version_cur = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION)]) if version_cur < version_min: print() print("**************************************************") print("****** An update to PlatformIO is ******") print("****** required to build Marlin Firmware. ******") print("****** ******") print("****** Minimum version: ", PIO_VERSION_MIN, " ******") print("****** Current Version: ", PIO_VERSION, " ******") print("****** ******") print("****** Update PlatformIO and try again. ******") print("**************************************************") print() exit(1) except SystemExit: exit(1) except: print("Can't detect PlatformIO Version") def blab(str,level=1): if verbose >= level: print("[deps] %s" % str) def add_to_feat_cnf(feature, flines): try: feat = FEATURE_CONFIG[feature] except: FEATURE_CONFIG[feature] = {} # Get a reference to the FEATURE_CONFIG under construction feat = FEATURE_CONFIG[feature] # Split up passed lines on commas or newlines and iterate. # Take care to convert Windows '\' paths to Unix-style '/'. # Add common options to the features config under construction. # For lib_deps replace a previous instance of the same library. atoms = re.sub(r',\s*', '\n', flines.replace('\\', '/')).strip().split('\n') for line in atoms: parts = line.split('=') name = parts.pop(0) if name in ['build_flags', 'extra_scripts', 'build_src_filter', 'lib_ignore']: feat[name] = '='.join(parts) blab("[%s] %s=%s" % (feature, name, feat[name]), 3) else: for dep in re.split(r',\s*', line): lib_name = re.sub(r'@([~^]|[<>]=?)?[\d.]+', '', dep.strip()).split('=').pop(0) lib_re = re.compile('(?!^' + lib_name + '\\b)') if not 'lib_deps' in feat: feat['lib_deps'] = {} feat['lib_deps'] = list(filter(lib_re.match, feat['lib_deps'])) + [dep] blab("[%s] lib_deps = %s" % (feature, dep), 3) def load_features(): blab("========== Gather [features] entries...") for key in ProjectConfig().items('features'): feature = key[0].upper() if not feature in FEATURE_CONFIG: FEATURE_CONFIG[feature] = { 'lib_deps': [] } add_to_feat_cnf(feature, key[1]) # Add options matching custom_marlin.MY_OPTION to the pile blab("========== Gather custom_marlin entries...") for n in env.GetProjectOptions(): key = n[0] mat = re.match(r'custom_marlin\.(.+)', key) if mat: try: val = env.GetProjectOption(key) except: val = None if val: opt = mat[1].upper() blab("%s.custom_marlin.%s = '%s'" % ( env['PIOENV'], opt, val ), 2) add_to_feat_cnf(opt, val) def get_all_known_libs(): known_libs = [] for feature in FEATURE_CONFIG: feat = FEATURE_CONFIG[feature] if not 'lib_deps' in feat: continue for dep in feat['lib_deps']: known_libs.append(PackageSpec(dep).name) return known_libs def get_all_env_libs(): env_libs = [] lib_deps = env.GetProjectOption('lib_deps') for dep in lib_deps: env_libs.append(PackageSpec(dep).name) return env_libs def set_env_field(field, value): proj = env.GetProjectConfig() proj.set("env:" + env['PIOENV'], field, value) # All unused libs should be ignored so that if a library # exists in .pio/lib_deps it will not break compilation. def force_ignore_unused_libs(): env_libs = get_all_env_libs() known_libs = get_all_known_libs() diff = (list(set(known_libs) - set(env_libs))) lib_ignore = env.GetProjectOption('lib_ignore') + diff blab("Ignore libraries: %s" % lib_ignore) set_env_field('lib_ignore', lib_ignore) def apply_features_config(): load_features() blab("========== Apply enabled features...") build_filters = ' '.join(env.GetProjectOption('build_src_filter')) for feature in FEATURE_CONFIG: if not env.MarlinHas(feature): continue feat = FEATURE_CONFIG[feature] if 'lib_deps' in feat and len(feat['lib_deps']): blab("========== Adding lib_deps for %s... " % feature, 2) # feat to add deps_to_add = {} for dep in feat['lib_deps']: deps_to_add[PackageSpec(dep).name] = dep blab("==================== %s... " % dep, 2) # Does the env already have the dependency? deps = env.GetProjectOption('lib_deps') for dep in deps: name = PackageSpec(dep).name if name in deps_to_add: del deps_to_add[name] # Are there any libraries that should be ignored? lib_ignore = env.GetProjectOption('lib_ignore') for dep in deps: name = PackageSpec(dep).name if name in deps_to_add: del deps_to_add[name] # Is there anything left? if len(deps_to_add) > 0: # Only add the missing dependencies set_env_field('lib_deps', deps + list(deps_to_add.values())) if 'build_flags' in feat: f = feat['build_flags'] blab("========== Adding build_flags for %s: %s" % (feature, f), 2) new_flags = env.GetProjectOption('build_flags') + [ f ] env.Replace(BUILD_FLAGS=new_flags) if 'extra_scripts' in feat: blab("Running extra_scripts for %s... " % feature, 2) env.SConscript(feat['extra_scripts'], exports="env") if 'build_src_filter' in feat: blab("========== Adding build_src_filter for %s... " % feature, 2) build_filters = build_filters + ' ' + feat['build_src_filter'] # Just append the filter in the order that the build environment specifies. # Important here is the order of entries in the "features.ini" file. if 'lib_ignore' in feat: blab("========== Adding lib_ignore for %s... " % feature, 2) lib_ignore = env.GetProjectOption('lib_ignore') + [feat['lib_ignore']] set_env_field('lib_ignore', lib_ignore) build_src_filter = "" if True: # Build the actual equivalent build_src_filter list based on the inclusions by the features. # PlatformIO doesn't do it this way, but maybe in the future.... cur_srcs = set() # Remove the references to the same folder my_srcs = re.findall(r'([+-]<.*?>)', build_filters) for d in my_srcs: # Assume normalized relative paths plain = d[2:-1] if d[0] == '+': def addentry(fullpath, info=None): relp = os.path.relpath(fullpath, marlinbasedir) if srcfilepattern.match(relp): if info: blab("Added src file %s (%s)" % (relp, str(info)), 3) else: blab("Added src file %s " % relp, 3) cur_srcs.add(relp) # Special rule: If a direct folder is specified add all files within. fullplain = os.path.join(marlinbasedir, plain) if os.path.isdir(fullplain): blab("Directory content addition for %s " % plain, 3) gpattern = os.path.join(fullplain, "**") for fname in glob.glob(gpattern, recursive=True): addentry(fname, "dca") else: # Add all the things from the pattern by GLOB. def srepl(matchi): g0 = matchi.group(0) return r"**" + g0[1:] gpattern = re.sub(r'[*]($|[^*])', srepl, plain) gpattern = os.path.join(marlinbasedir, gpattern) for fname in glob.glob(gpattern, recursive=True): addentry(fname) else: # Special rule: If a direct folder is specified then remove all files within. def onremove(relp, info=None): if info: blab("Removed src file %s (%s)" % (relp, str(info)), 3) else: blab("Removed src file %s " % relp, 3) fullplain = os.path.join(marlinbasedir, plain) if os.path.isdir(fullplain): blab("Directory content removal for %s " % plain, 2) def filt(x): common = os.path.commonpath([plain, x]) if not common == os.path.normpath(plain): return True onremove(x, "dcr") return False cur_srcs = set(filter(filt, cur_srcs)) else: # Remove matching source entries. def filt(x): if not fnmatch.fnmatch(x, plain): return True onremove(x) return False cur_srcs = set(filter(filt, cur_srcs)) # Transform the resulting set into a string. for x in cur_srcs: if build_src_filter != "": build_src_filter += ' ' build_src_filter += "+<" + x + ">" #blab("Final build_src_filter: " + build_src_filter, 3) else: build_src_filter = build_filters # Update in PlatformIO set_env_field('build_src_filter', [build_src_filter]) env.Replace(SRC_FILTER=build_src_filter) # # Use the compiler to get a list of all enabled features # def load_marlin_features(): if 'MARLIN_FEATURES' in env: return # Process defines from preprocessor import run_preprocessor define_list = run_preprocessor(env) marlin_features = {} for define in define_list: feature = define[8:].strip().decode().split(' ') feature, definition = feature[0], ' '.join(feature[1:]) marlin_features[feature] = definition env['MARLIN_FEATURES'] = marlin_features # # Return True if a matching feature is enabled # def MarlinHas(env, feature): load_marlin_features() r = re.compile('^' + feature + '$', re.IGNORECASE) found = list(filter(r.match, env['MARLIN_FEATURES'])) # Defines could still be 'false' or '0', so check some_on = False if len(found): for f in found: val = env['MARLIN_FEATURES'][f] if val in [ '', '1', 'true' ]: some_on = True elif val in env['MARLIN_FEATURES']: some_on = env.MarlinHas(val) #blab("%s is %s" % (feature, str(some_on)), 2) return some_on validate_pio() try: verbose = int(env.GetProjectOption('custom_verbose')) except: pass # # Add a method for other PIO scripts to query enabled features # env.AddMethod(MarlinHas) # # Add dependencies for enabled Marlin features # apply_features_config() force_ignore_unused_libs() #print(env.Dump()) from signature import compute_build_signature compute_build_signature(env)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/common-dependencies.py
Python
agpl-3.0
13,385
#!/usr/bin/env python3 # # configuration.py # Apply options from config.ini to the existing Configuration headers # import re, shutil, configparser, datetime from pathlib import Path verbose = 0 def blab(str,level=1): if verbose >= level: print(f"[config] {str}") def config_path(cpath): return Path("Marlin", cpath, encoding='utf-8') # Apply a single name = on/off ; name = value ; etc. # TODO: Limit to the given (optional) configuration def apply_opt(name, val, conf=None): if name == "lcd": name, val = val, "on" # Create a regex to match the option and capture parts of the line # 1: Indentation # 2: Comment # 3: #define and whitespace # 4: Option name # 5: First space after name # 6: Remaining spaces between name and value # 7: Option value # 8: Whitespace after value # 9: End comment regex = re.compile(rf'^(\s*)(//\s*)?(#define\s+)({name}\b)(\s?)(\s*)(.*?)(\s*)(//.*)?$', re.IGNORECASE) # Find and enable and/or update all matches for file in ("Configuration.h", "Configuration_adv.h"): fullpath = config_path(file) lines = fullpath.read_text(encoding='utf-8').split('\n') found = False for i in range(len(lines)): line = lines[i] match = regex.match(line) if match and match[4].upper() == name.upper(): found = True # For boolean options un/comment the define if val in ("on", "", None): newline = re.sub(r'^(\s*)//+\s*(#define)(\s{1,3})?(\s*)', r'\1\2 \4', line) elif val == "off": # TODO: Comment more lines in a multi-line define with \ continuation newline = re.sub(r'^(\s*)(#define)(\s{1,3})?(\s*)', r'\1//\2 \4', line) else: # For options with values, enable and set the value addsp = '' if match[5] else ' ' newline = match[1] + match[3] + match[4] + match[5] + addsp + val + match[6] if match[9]: sp = match[8] if match[8] else ' ' newline += sp + match[9] lines[i] = newline blab(f"Set {name} to {val}") # If the option was found, write the modified lines if found: fullpath.write_text('\n'.join(lines), encoding='utf-8') break # If the option didn't appear in either config file, add it if not found: # OFF options are added as disabled items so they appear # in config dumps. Useful for custom settings. prefix = "" if val == "off": prefix, val = "//", "" # Item doesn't appear in config dump #val = "false" # Item appears in config dump # Uppercase the option unless already mixed/uppercase added = name.upper() if name.islower() else name # Add the provided value after the name if val != "on" and val != "" and val is not None: added += " " + val # Prepend the new option after the first set of #define lines fullpath = config_path("Configuration.h") with fullpath.open(encoding='utf-8') as f: lines = f.readlines() linenum = 0 gotdef = False for line in lines: isdef = line.startswith("#define") if not gotdef: gotdef = isdef elif not isdef: break linenum += 1 currtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") lines.insert(linenum, f"{prefix}#define {added:30} // Added by config.ini {currtime}\n") fullpath.write_text(''.join(lines), encoding='utf-8') # Disable all (most) defined options in the configuration files. # Everything in the named sections. Section hint for exceptions may be added. def disable_all_options(): # Create a regex to match the option and capture parts of the line regex = re.compile(r'^(\s*)(#define\s+)([A-Z0-9_]+\b)(\s?)(\s*)(.*?)(\s*)(//.*)?$', re.IGNORECASE) # Disable all enabled options in both Config files for file in ("Configuration.h", "Configuration_adv.h"): fullpath = config_path(file) lines = fullpath.read_text(encoding='utf-8').split('\n') found = False for i in range(len(lines)): line = lines[i] match = regex.match(line) if match: name = match[3].upper() if name in ('CONFIGURATION_H_VERSION', 'CONFIGURATION_ADV_H_VERSION'): continue if name.startswith('_'): continue found = True # Comment out the define # TODO: Comment more lines in a multi-line define with \ continuation lines[i] = re.sub(r'^(\s*)(#define)(\s{1,3})?(\s*)', r'\1//\2 \4', line) blab(f"Disable {name}") # If the option was found, write the modified lines if found: fullpath.write_text('\n'.join(lines), encoding='utf-8') # Fetch configuration files from GitHub given the path. # Return True if any files were fetched. def fetch_example(url): if url.endswith("/"): url = url[:-1] if not url.startswith('http'): brch = "bugfix-2.1.x" if '@' in url: url, brch = map(str.strip, url.split('@')) if url == 'examples/default': url = 'default' url = f"https://raw.githubusercontent.com/MarlinFirmware/Configurations/{brch}/config/{url}" url = url.replace("%", "%25").replace(" ", "%20") # Find a suitable fetch command if shutil.which("curl") is not None: fetch = "curl -L -s -S -f -o" elif shutil.which("wget") is not None: fetch = "wget -q -O" else: blab("Couldn't find curl or wget", -1) return False import os # Reset configurations to default os.system("git checkout HEAD Marlin/*.h") # Try to fetch the remote files gotfile = False for fn in ("Configuration.h", "Configuration_adv.h", "_Bootscreen.h", "_Statusscreen.h"): if os.system(f"{fetch} wgot {url}/{fn} >/dev/null 2>&1") == 0: shutil.move('wgot', config_path(fn)) gotfile = True if Path('wgot').exists(): shutil.rmtree('wgot') return gotfile def section_items(cp, sectkey): return cp.items(sectkey) if sectkey in cp.sections() else [] # Apply all items from a config section. Ignore ini_ items outside of config:base and config:root. def apply_ini_by_name(cp, sect): iniok = True if sect in ('config:base', 'config:root'): iniok = False items = section_items(cp, 'config:base') + section_items(cp, 'config:root') else: items = section_items(cp, sect) for item in items: if iniok or not item[0].startswith('ini_'): apply_opt(item[0], item[1]) # Apply all config sections from a parsed file def apply_all_sections(cp): for sect in cp.sections(): if sect.startswith('config:'): apply_ini_by_name(cp, sect) # Apply certain config sections from a parsed file def apply_sections(cp, ckey='all'): blab(f"Apply section key: {ckey}") if ckey == 'all': apply_all_sections(cp) else: # Apply the base/root config.ini settings after external files are done if ckey in ('base', 'root'): apply_ini_by_name(cp, 'config:base') # Apply historically 'Configuration.h' settings everywhere if ckey == 'basic': apply_ini_by_name(cp, 'config:basic') # Apply historically Configuration_adv.h settings everywhere # (Some of which rely on defines in 'Conditionals_LCD.h') elif ckey in ('adv', 'advanced'): apply_ini_by_name(cp, 'config:advanced') # Apply a specific config:<name> section directly elif ckey.startswith('config:'): apply_ini_by_name(cp, ckey) # Apply settings from a top level config.ini def apply_config_ini(cp): blab("=" * 20 + " Gather 'config.ini' entries...") # Pre-scan for ini_use_config to get config_keys base_items = section_items(cp, 'config:base') + section_items(cp, 'config:root') config_keys = ['base'] for ikey, ival in base_items: if ikey == 'ini_use_config': config_keys = map(str.strip, ival.split(',')) # For each ini_use_config item perform an action for ckey in config_keys: addbase = False # For a key ending in .ini load and parse another .ini file if ckey.endswith('.ini'): sect = 'base' if '@' in ckey: sect, ckey = map(str.strip, ckey.split('@')) cp2 = configparser.ConfigParser() cp2.read(config_path(ckey)) apply_sections(cp2, sect) ckey = 'base' # (Allow 'example/' as a shortcut for 'examples/') elif ckey.startswith('example/'): ckey = 'examples' + ckey[7:] # For 'examples/<path>' fetch an example set from GitHub. # For https?:// do a direct fetch of the URL. if ckey.startswith('examples/') or ckey.startswith('http'): fetch_example(ckey) ckey = 'base' # # [flatten] Write out Configuration.h and Configuration_adv.h files with # just the enabled options and all other content removed. # #if ckey == '[flatten]': # write_flat_configs() if ckey == '[disable]': disable_all_options() elif ckey == 'all': apply_sections(cp) else: # Apply keyed sections after external files are done apply_sections(cp, 'config:' + ckey) if __name__ == "__main__": # # From command line use the given file name # import sys args = sys.argv[1:] if len(args) > 0: if args[0].endswith('.ini'): ini_file = args[0] else: print("Usage: %s <.ini file>" % sys.argv[0]) else: ini_file = config_path('config.ini') if ini_file: user_ini = configparser.ConfigParser() user_ini.read(ini_file) apply_config_ini(user_ini) else: # # From within PlatformIO use the loaded INI file # import pioutil if pioutil.is_pio_build(): Import("env") try: verbose = int(env.GetProjectOption('custom_verbose')) except: pass from platformio.project.config import ProjectConfig apply_config_ini(ProjectConfig())
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/configuration.py
Python
agpl-3.0
10,609
# # custom_board.py # # - For build.address replace VECT_TAB_ADDR to relocate the firmware # - For build.ldscript use one of the linker scripts in buildroot/share/PlatformIO/ldscripts # import pioutil if pioutil.is_pio_build(): import marlin board = marlin.env.BoardConfig() address = board.get("build.address", "") if address: marlin.relocate_firmware(address) ldscript = board.get("build.ldscript", "") if ldscript: marlin.custom_ld_script(ldscript)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/custom_board.py
Python
agpl-3.0
494
# # download_mks_assets.py # Added by HAS_TFT_LVGL_UI to download assets from Makerbase repo # import pioutil if pioutil.is_pio_build(): Import("env") import requests,zipfile,tempfile,shutil from pathlib import Path url = "https://github.com/makerbase-mks/Mks-Robin-Nano-Marlin2.0-Firmware/archive/0263cdaccf.zip" deps_path = Path(env.Dictionary("PROJECT_LIBDEPS_DIR")) zip_path = deps_path / "mks-assets.zip" assets_path = Path(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets") def download_mks_assets(): print("Downloading MKS Assets for TFT_LVGL_UI") r = requests.get(url, stream=True) # the user may have a very clean workspace, # so create the PROJECT_LIBDEPS_DIR directory if not exits if not deps_path.exists(): deps_path.mkdir() with zip_path.open('wb') as fd: for chunk in r.iter_content(chunk_size=128): fd.write(chunk) def copy_mks_assets(): print("Copying MKS Assets for TFT_LVGL_UI") output_path = Path(tempfile.mkdtemp()) zip_obj = zipfile.ZipFile(zip_path, 'r') zip_obj.extractall(output_path) zip_obj.close() if assets_path.exists() and not assets_path.is_dir(): assets_path.unlink() if not assets_path.exists(): assets_path.mkdir() base_path = '' for filename in output_path.iterdir(): base_path = filename fw_path = (output_path / base_path / 'Firmware') font_path = fw_path / 'mks_font' for filename in font_path.iterdir(): shutil.copy(font_path / filename, assets_path) pic_path = fw_path / 'mks_pic' for filename in pic_path.iterdir(): shutil.copy(pic_path / filename, assets_path) shutil.rmtree(output_path, ignore_errors=True) if not zip_path.exists(): download_mks_assets() if not assets_path.exists(): copy_mks_assets()
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/download_mks_assets.py
Python
agpl-3.0
2,001
/* ***************************************************************************** * The MIT License * * Copyright (c) 2010 Perry Hung. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ****************************************************************************/ # On an exception, push a fake stack thread mode stack frame and redirect # thread execution to a thread mode error handler # From RM008: # The SP is decremented by eight words by the completion of the stack push. # Figure 5-1 shows the contents of the stack after an exception pre-empts the # current program flow. # # Old SP--> <previous> # xPSR # PC # LR # r12 # r3 # r2 # r1 # SP--> r0 .text .globl __exc_nmi .weak __exc_nmi .globl __exc_hardfault .weak __exc_hardfault .globl __exc_memmanage .weak __exc_memmanage .globl __exc_busfault .weak __exc_busfault .globl __exc_usagefault .weak __exc_usagefault .code 16 .thumb_func __exc_nmi: mov r0, #1 b __default_exc .thumb_func __exc_hardfault: mov r0, #2 b __default_exc .thumb_func __exc_memmanage: mov r0, #3 b __default_exc .thumb_func __exc_busfault: mov r0, #4 b __default_exc .thumb_func __exc_usagefault: mov r0, #5 b __default_exc .thumb_func __default_exc: ldr r2, NVIC_CCR @ Enable returning to thread mode even if there are mov r1 ,#1 @ pending exceptions. See flag NONEBASETHRDENA. str r1, [r2] cpsid i @ Disable global interrupts ldr r2, SYSTICK_CSR @ Disable systick handler mov r1, #0 str r1, [r2] ldr r1, CPSR_MASK @ Set default CPSR push {r1} ldr r1, TARGET_PC @ Set target pc push {r1} sub sp, sp, #24 @ Don't care ldr r1, EXC_RETURN @ Return to thread mode mov lr, r1 bx lr @ Exception exit .align 4 CPSR_MASK: .word 0x61000000 EXC_RETURN: .word 0xFFFFFFF9 TARGET_PC: .word __error NVIC_CCR: .word 0xE000ED14 @ NVIC configuration control register SYSTICK_CSR: .word 0xE000E010 @ Systick control register
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/exc.S
Unix Assembly
agpl-3.0
3,201
# # fix_framework_weakness.py # import pioutil if pioutil.is_pio_build(): import shutil from os.path import join, isfile from pprint import pprint Import("env") if env.MarlinHas("POSTMORTEM_DEBUGGING"): FRAMEWORK_DIR = env.PioPlatform().get_package_dir("framework-arduinoststm32-maple") patchflag_path = join(FRAMEWORK_DIR, ".exc-patching-done") # patch file only if we didn't do it before if not isfile(patchflag_path): print("Patching libmaple exception handlers") original_file = join(FRAMEWORK_DIR, "STM32F1", "cores", "maple", "libmaple", "exc.S") backup_file = join(FRAMEWORK_DIR, "STM32F1", "cores", "maple", "libmaple", "exc.S.bak") src_file = join("buildroot", "share", "PlatformIO", "scripts", "exc.S") assert isfile(original_file) and isfile(src_file) shutil.copyfile(original_file, backup_file) shutil.copyfile(src_file, original_file) def _touch(path): with open(path, "w") as fp: fp.write("") env.Execute(lambda *args, **kwargs: _touch(patchflag_path)) print("Done patching exception handler") print("Libmaple modified and ready for post mortem debugging")
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/fix_framework_weakness.py
Python
agpl-3.0
1,295
# # generic_create_variant.py # # Copy one of the variants from buildroot/platformio/variants into # the appropriate framework variants folder, so that its contents # will be picked up by PlatformIO just like any other variant. # import pioutil, re marlin_variant_pattern = re.compile("marlin_.*") if pioutil.is_pio_build(): import shutil,marlin from pathlib import Path # # Get the platform name from the 'platform_packages' option, # or look it up by the platform.class.name. # env = marlin.env platform = env.PioPlatform() from platformio.package.meta import PackageSpec platform_packages = env.GetProjectOption('platform_packages') # Remove all tool items from platform_packages platform_packages = [x for x in platform_packages if not x.startswith("platformio/tool-")] if len(platform_packages) == 0: framewords = { "Ststm32Platform": "framework-arduinoststm32", "AtmelavrPlatform": "framework-arduino-avr" } platform_name = framewords[platform.__class__.__name__] else: spec = PackageSpec(platform_packages[0]) if spec.uri and '@' in spec.uri: platform_name = re.sub(r'@.+', '', spec.uri) else: platform_name = spec.name FRAMEWORK_DIR = Path(platform.get_package_dir(platform_name)) assert FRAMEWORK_DIR.is_dir() board = env.BoardConfig() #mcu_type = board.get("build.mcu")[:-2] variant = board.get("build.variant") #series = mcu_type[:7].upper() + "xx" # Only prepare a new variant if the PlatformIO configuration provides it (board_build.variant). # This check is important to avoid deleting official board config variants. if marlin_variant_pattern.match(str(variant).lower()): # Prepare a new empty folder at the destination variant_dir = FRAMEWORK_DIR / "variants" / variant if variant_dir.is_dir(): shutil.rmtree(variant_dir) if not variant_dir.is_dir(): variant_dir.mkdir() # Source dir is a local variant sub-folder source_dir = Path("buildroot/share/PlatformIO/variants", variant) assert source_dir.is_dir() print("Copying variant " + str(variant) + " to framework directory...") marlin.copytree(source_dir, variant_dir)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/generic_create_variant.py
Python
agpl-3.0
2,331
# # jgaurora_a5s_a1_with_bootloader.py # Customizations for env:jgaurora_a5s_a1 # import pioutil if pioutil.is_pio_build(): # Append ${PROGNAME}.bin firmware after bootloader and save it as 'jgaurora_firmware.bin' def addboot(source, target, env): from pathlib import Path fw_path = Path(target[0].path) fwb_path = fw_path.parent / 'firmware_with_bootloader.bin' with fwb_path.open("wb") as fwb_file: bl_path = Path("buildroot/share/PlatformIO/scripts/jgaurora_bootloader.bin") bl_file = bl_path.open("rb") while True: b = bl_file.read(1) if b == b'': break else: fwb_file.write(b) with fw_path.open("rb") as fw_file: while True: b = fw_file.read(1) if b == b'': break else: fwb_file.write(b) fws_path = Path(target[0].dir.path, 'firmware_for_sd_upload.bin') if fws_path.exists(): fws_path.unlink() fw_path.rename(fws_path) import marlin marlin.add_post_action(addboot)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/jgaurora_a5s_a1_with_bootloader.py
Python
agpl-3.0
1,132
# # lerdge.py # Customizations for Lerdge build environments: # env:LERDGEX env:LERDGEX_usb_flash_drive # env:LERDGES env:LERDGES_usb_flash_drive # env:LERDGEK env:LERDGEK_usb_flash_drive # import pioutil if pioutil.is_pio_build(): import os,marlin board = marlin.env.BoardConfig() def encryptByte(byte): byte = 0xFF & ((byte << 6) | (byte >> 2)) i = 0x58 + byte j = 0x05 + byte + (i >> 8) byte = (0xF8 & i) | (0x07 & j) return byte def encrypt_file(input, output_file, file_length): input_file = bytearray(input.read()) for i in range(len(input_file)): input_file[i] = encryptByte(input_file[i]) output_file.write(input_file) # Encrypt ${PROGNAME}.bin and save it with the name given in build.crypt_lerdge def encrypt(source, target, env): fwpath = target[0].path enname = board.get("build.crypt_lerdge") print("Encrypting %s to %s" % (fwpath, enname)) fwfile = open(fwpath, "rb") enfile = open(target[0].dir.path + "/" + enname, "wb") length = os.path.getsize(fwpath) encrypt_file(fwfile, enfile, length) fwfile.close() enfile.close() os.remove(fwpath) if 'crypt_lerdge' in board.get("build").keys(): if board.get("build.crypt_lerdge") != "": marlin.add_post_action(encrypt) else: print("LERDGE builds require output file via board_build.crypt_lerdge = 'filename' parameter") exit(1)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/lerdge.py
Python
agpl-3.0
1,526
# # marlin.py # Helper module with some commonly-used functions # import shutil from pathlib import Path from SCons.Script import DefaultEnvironment env = DefaultEnvironment() def copytree(src, dst, symlinks=False, ignore=None): for item in src.iterdir(): if item.is_dir(): shutil.copytree(item, dst / item.name, symlinks, ignore) else: shutil.copy2(item, dst / item.name) def replace_define(field, value): envdefs = env['CPPDEFINES'].copy() for define in envdefs: if define[0] == field: env['CPPDEFINES'].remove(define) env['CPPDEFINES'].append((field, value)) # Relocate the firmware to a new address, such as "0x08005000" def relocate_firmware(address): replace_define("VECT_TAB_ADDR", address) # Relocate the vector table with a new offset def relocate_vtab(address): replace_define("VECT_TAB_OFFSET", address) # Replace the existing -Wl,-T with the given ldscript path def custom_ld_script(ldname): apath = str(Path("buildroot/share/PlatformIO/ldscripts", ldname).resolve()) for i, flag in enumerate(env["LINKFLAGS"]): if "-Wl,-T" in flag: env["LINKFLAGS"][i] = "-Wl,-T" + apath elif flag == "-T": env["LINKFLAGS"][i + 1] = apath # Encrypt ${PROGNAME}.bin and save it with a new name. This applies (mostly) to MKS boards # This PostAction is set up by offset_and_rename.py for envs with 'build.encrypt_mks'. def encrypt_mks(source, target, env, new_name): import sys key = [0xA3, 0xBD, 0xAD, 0x0D, 0x41, 0x11, 0xBB, 0x8D, 0xDC, 0x80, 0x2D, 0xD0, 0xD2, 0xC4, 0x9B, 0x1E, 0x26, 0xEB, 0xE3, 0x33, 0x4A, 0x15, 0xE4, 0x0A, 0xB3, 0xB1, 0x3C, 0x93, 0xBB, 0xAF, 0xF7, 0x3E] # If FIRMWARE_BIN is defined by config, override all mf = env["MARLIN_FEATURES"] if "FIRMWARE_BIN" in mf: new_name = mf["FIRMWARE_BIN"] fwpath = Path(target[0].path) fwfile = fwpath.open("rb") enfile = Path(target[0].dir.path, new_name).open("wb") length = fwpath.stat().st_size position = 0 try: while position < length: byte = fwfile.read(1) if 320 <= position < 31040: byte = chr(ord(byte) ^ key[position & 31]) if sys.version_info[0] > 2: byte = bytes(byte, 'latin1') enfile.write(byte) position += 1 finally: fwfile.close() enfile.close() fwpath.unlink() def add_post_action(action): env.AddPostAction(str(Path("$BUILD_DIR", "${PROGNAME}.bin")), action)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/marlin.py
Python
agpl-3.0
2,557
#!/usr/bin/env python # # Create a Configuration from marlin_config.json # import json import sys import shutil opt_output = '--opt' in sys.argv output_suffix = '.sh' if opt_output else '' if '--bare-output' in sys.argv else '.gen' try: with open('marlin_config.json', 'r') as infile: conf = json.load(infile) for key in conf: # We don't care about the hash when restoring here if key == '__INITIAL_HASH': continue if key == 'VERSION': for k, v in sorted(conf[key].items()): print(k + ': ' + v) continue # The key is the file name, so let's build it now outfile = open('Marlin/' + key + output_suffix, 'w') for k, v in sorted(conf[key].items()): # Make define line now if opt_output: if v != '': if '"' in v: v = "'%s'" % v elif ' ' in v: v = '"%s"' % v define = 'opt_set ' + k + ' ' + v + '\n' else: define = 'opt_enable ' + k + '\n' else: define = '#define ' + k + ' ' + v + '\n' outfile.write(define) outfile.close() # Try to apply changes to the actual configuration file (in order to keep useful comments) if output_suffix != '': # Move the existing configuration so it doesn't interfere shutil.move('Marlin/' + key, 'Marlin/' + key + '.orig') infile_lines = open('Marlin/' + key + '.orig', 'r').read().split('\n') outfile = open('Marlin/' + key, 'w') for line in infile_lines: sline = line.strip(" \t\n\r") if sline[:7] == "#define": # Extract the key here (we don't care about the value) kv = sline[8:].strip().split(' ') if kv[0] in conf[key]: outfile.write('#define ' + kv[0] + ' ' + conf[key][kv[0]] + '\n') # Remove the key from the dict, so we can still write all missing keys at the end of the file del conf[key][kv[0]] else: outfile.write(line + '\n') else: outfile.write(line + '\n') # Process any remaining defines here for k, v in sorted(conf[key].items()): define = '#define ' + k + ' ' + v + '\n' outfile.write(define) outfile.close() print('Output configuration written to: ' + 'Marlin/' + key + output_suffix) except: print('No marlin_config.json found.')
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/mc-apply.py
Python
agpl-3.0
2,929
# # offset_and_rename.py # # - If 'board_build.offset' is provided, either by JSON or by the environment... # - Set linker flag LD_FLASH_OFFSET and relocate the VTAB based on 'build.offset'. # - Set linker flag LD_MAX_DATA_SIZE based on 'build.maximum_ram_size'. # - Define STM32_FLASH_SIZE from 'upload.maximum_size' for use by Flash-based EEPROM emulation. # # - For 'board_build.rename' add a post-action to rename the firmware file. # import pioutil if pioutil.is_pio_build(): import marlin env = marlin.env board = env.BoardConfig() board_keys = board.get("build").keys() # # For build.offset define LD_FLASH_OFFSET, used by ldscript.ld # if 'offset' in board_keys: LD_FLASH_OFFSET = board.get("build.offset") marlin.relocate_vtab(LD_FLASH_OFFSET) # Flash size maximum_flash_size = int(board.get("upload.maximum_size") / 1024) marlin.replace_define('STM32_FLASH_SIZE', maximum_flash_size) # Get upload.maximum_ram_size (defined by /buildroot/share/PlatformIO/boards/VARIOUS.json) maximum_ram_size = board.get("upload.maximum_ram_size") for i, flag in enumerate(env["LINKFLAGS"]): if "-Wl,--defsym=LD_FLASH_OFFSET" in flag: env["LINKFLAGS"][i] = "-Wl,--defsym=LD_FLASH_OFFSET=" + LD_FLASH_OFFSET if "-Wl,--defsym=LD_MAX_DATA_SIZE" in flag: env["LINKFLAGS"][i] = "-Wl,--defsym=LD_MAX_DATA_SIZE=" + str(maximum_ram_size - 40) # # For build.encrypt_mks rename and encode the firmware file. # if 'encrypt_mks' in board_keys: # Encrypt ${PROGNAME}.bin and save it with the name given in build.encrypt_mks def encrypt(source, target, env): marlin.encrypt_mks(source, target, env, board.get("build.encrypt_mks")) if board.get("build.encrypt_mks") != "": marlin.add_post_action(encrypt) # # For build.rename simply rename the firmware file. # if 'rename' in board_keys: # If FIRMWARE_BIN is defined by config, override all mf = env["MARLIN_FEATURES"] if "FIRMWARE_BIN" in mf: new_name = mf["FIRMWARE_BIN"] else: new_name = board.get("build.rename") def rename_target(source, target, env): from pathlib import Path from datetime import datetime from os import path _newpath = Path(target[0].dir.path, datetime.now().strftime(new_name.replace('{date}', '%Y%m%d').replace('{time}', '%H%M%S'))) Path(target[0].path).replace(_newpath) env['PROGNAME'] = path.splitext(_newpath)[0] marlin.add_post_action(rename_target)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/offset_and_rename.py
Python
agpl-3.0
2,679
# # Convert the ELF to an SREC file suitable for some bootloaders # import pioutil if pioutil.is_pio_build(): from os.path import join Import("env") board = env.BoardConfig() board_keys = board.get("build").keys() if 'encode' in board_keys: env.AddPostAction( join("$BUILD_DIR", "${PROGNAME}.bin"), env.VerboseAction(" ".join([ "$OBJCOPY", "-O", "srec", "\"$BUILD_DIR/${PROGNAME}.elf\"", "\"" + join("$BUILD_DIR", board.get("build.encode")) + "\"" ]), "Building " + board.get("build.encode")) )
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/openblt.py
Python
agpl-3.0
601
# # pioutil.py # # Make sure 'vscode init' is not the current command def is_pio_build(): from SCons.Script import DefaultEnvironment env = DefaultEnvironment() if "IsCleanTarget" in dir(env) and env.IsCleanTarget(): return False return not env.IsIntegrationDump() def get_pio_version(): from platformio import util return util.pioversion_to_intstr()
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/pioutil.py
Python
agpl-3.0
377
# # preflight-checks.py # Check for common issues prior to compiling # import pioutil if pioutil.is_pio_build(): import re,sys from pathlib import Path Import("env") def get_envs_for_board(board): ppath = Path("Marlin/src/pins/pins.h") with ppath.open() as file: if sys.platform == 'win32': envregex = r"(?:env|win):" elif sys.platform == 'darwin': envregex = r"(?:env|mac|uni):" elif sys.platform == 'linux': envregex = r"(?:env|lin|uni):" else: envregex = r"(?:env):" r = re.compile(r"if\s+MB\((.+)\)") if board.startswith("BOARD_"): board = board[6:] for line in file: mbs = r.findall(line) if mbs and board in re.split(r",\s*", mbs[0]): line = file.readline() found_envs = re.match(r"\s*#include .+" + envregex, line) if found_envs: envlist = re.findall(envregex + r"(\w+)", line) return [ "env:"+s for s in envlist ] return [] def check_envs(build_env, board_envs, config): if build_env in board_envs: return True ext = config.get(build_env, 'extends', default=None) if ext: if isinstance(ext, str): return check_envs(ext, board_envs, config) elif isinstance(ext, list): for ext_env in ext: if check_envs(ext_env, board_envs, config): return True return False def sanity_check_target(): # Sanity checks: if 'PIOENV' not in env: raise SystemExit("Error: PIOENV is not defined. This script is intended to be used with PlatformIO") # Require PlatformIO 6.1.1 or later vers = pioutil.get_pio_version() if vers < [6, 1, 1]: raise SystemExit("Error: Marlin requires PlatformIO >= 6.1.1. Use 'pio upgrade' to get a newer version.") if 'MARLIN_FEATURES' not in env: raise SystemExit("Error: this script should be used after common Marlin scripts.") if len(env['MARLIN_FEATURES']) == 0: raise SystemExit("Error: Failed to parse Marlin features. See previous error messages.") build_env = env['PIOENV'] motherboard = env['MARLIN_FEATURES']['MOTHERBOARD'] board_envs = get_envs_for_board(motherboard) config = env.GetProjectConfig() result = check_envs("env:"+build_env, board_envs, config) # Make sure board is compatible with the build environment. Skip for _test, # since the board is manipulated as each unit test is executed. if not result and build_env != "linux_native_test": err = "Error: Build environment '%s' is incompatible with %s. Use one of these environments: %s" % \ ( build_env, motherboard, ", ".join([ e[4:] for e in board_envs if e.startswith("env:") ]) ) raise SystemExit(err) # # Check for Config files in two common incorrect places # epath = Path(env['PROJECT_DIR']) for p in [ epath, epath / "config" ]: for f in ("Configuration.h", "Configuration_adv.h"): if (p / f).is_file(): err = "ERROR: Config files found in directory %s. Please move them into the Marlin subfolder." % p raise SystemExit(err) # # Find the name.cpp.o or name.o and remove it # def rm_ofile(subdir, name): build_dir = Path(env['PROJECT_BUILD_DIR'], build_env) for outdir in (build_dir, build_dir / "debug"): for ext in (".cpp.o", ".o"): fpath = outdir / "src/src" / subdir / (name + ext) if fpath.exists(): fpath.unlink() # # Give warnings on every build # rm_ofile("inc", "Warnings") # # Rebuild 'settings.cpp' for EEPROM_INIT_NOW # if 'EEPROM_INIT_NOW' in env['MARLIN_FEATURES']: rm_ofile("module", "settings") # # Check for old files indicating an entangled Marlin (mixing old and new code) # mixedin = [] p = Path(env['PROJECT_DIR'], "Marlin/src/lcd/dogm") for f in [ "ultralcd_DOGM.cpp", "ultralcd_DOGM.h" ]: if (p / f).is_file(): mixedin += [ f ] p = Path(env['PROJECT_DIR'], "Marlin/src/feature/bedlevel/abl") for f in [ "abl.cpp", "abl.h" ]: if (p / f).is_file(): mixedin += [ f ] if mixedin: err = "ERROR: Old files fell into your Marlin folder. Remove %s and try again" % ", ".join(mixedin) raise SystemExit(err) # # Check FILAMENT_RUNOUT_SCRIPT has a %c parammeter when required # if 'FILAMENT_RUNOUT_SENSOR' in env['MARLIN_FEATURES'] and 'NUM_RUNOUT_SENSORS' in env['MARLIN_FEATURES']: if env['MARLIN_FEATURES']['NUM_RUNOUT_SENSORS'].isdigit() and int(env['MARLIN_FEATURES']['NUM_RUNOUT_SENSORS']) > 1: if 'FILAMENT_RUNOUT_SCRIPT' in env['MARLIN_FEATURES']: frs = env['MARLIN_FEATURES']['FILAMENT_RUNOUT_SCRIPT'] if "M600" in frs and "%c" not in frs: err = "ERROR: FILAMENT_RUNOUT_SCRIPT needs a %c parameter (e.g., \"M600 T%c\") when NUM_RUNOUT_SENSORS is > 1" raise SystemExit(err) sanity_check_target()
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/preflight-checks.py
Python
agpl-3.0
5,659
# # preprocessor.py # import subprocess nocache = 1 verbose = 0 def blab(str): if verbose: print(str) ################################################################################ # # Invoke GCC to run the preprocessor and extract enabled features # preprocessor_cache = {} def run_preprocessor(env, fn=None): filename = fn or 'buildroot/share/PlatformIO/scripts/common-dependencies.h' if filename in preprocessor_cache: return preprocessor_cache[filename] # Process defines build_flags = env.get('BUILD_FLAGS') build_flags = env.ParseFlagsExtended(build_flags) cxx = search_compiler(env) cmd = ['"' + cxx + '"'] # Build flags from board.json #if 'BOARD' in env: # cmd += [env.BoardConfig().get("build.extra_flags")] for s in build_flags['CPPDEFINES']: if isinstance(s, tuple): cmd += ['-D' + s[0] + '=' + str(s[1])] else: cmd += ['-D' + s] cmd += ['-D__MARLIN_DEPS__ -w -dM -E -x c++'] depcmd = cmd + [ filename ] cmd = ' '.join(depcmd) blab(cmd) try: define_list = subprocess.check_output(cmd, shell=True).splitlines() except: define_list = {} preprocessor_cache[filename] = define_list return define_list ################################################################################ # # Find a compiler, considering the OS # def search_compiler(env): from pathlib import Path, PurePath ENV_BUILD_PATH = Path(env['PROJECT_BUILD_DIR'], env['PIOENV']) GCC_PATH_CACHE = ENV_BUILD_PATH / ".gcc_path" try: gccpath = env.GetProjectOption('custom_gcc') blab("Getting compiler from env") return gccpath except: pass # Warning: The cached .gcc_path will obscure a newly-installed toolkit if not nocache and GCC_PATH_CACHE.exists(): blab("Getting g++ path from cache") return GCC_PATH_CACHE.read_text() # Use any item in $PATH corresponding to a platformio toolchain bin folder path_separator = ':' gcc_exe = '*g++' if env['PLATFORM'] == 'win32': path_separator = ';' gcc_exe += ".exe" # Search for the compiler in PATH for ppath in map(Path, env['ENV']['PATH'].split(path_separator)): if ppath.match(env['PROJECT_PACKAGES_DIR'] + "/**/bin"): for gpath in ppath.glob(gcc_exe): gccpath = str(gpath.resolve()) # Cache the g++ path to no search always if not nocache and ENV_BUILD_PATH.exists(): blab("Caching g++ for current env") GCC_PATH_CACHE.write_text(gccpath) return gccpath gccpath = env.get('CXX') blab("Couldn't find a compiler! Fallback to %s" % gccpath) return gccpath
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/preprocessor.py
Python
agpl-3.0
2,798
#!/usr/bin/env python3 # # schema.py # # Used by signature.py via common-dependencies.py to generate a schema file during the PlatformIO build # when CONFIG_EXPORT is defined in the configuration. # # This script can also be run standalone from within the Marlin repo to generate JSON and YAML schema files. # # This script is a companion to abm/js/schema.js in the MarlinFirmware/AutoBuildMarlin project, which has # been extended to evaluate conditions and can determine what options are actually enabled, not just which # options are uncommented. That will be migrated to this script for standalone migration. # import re,json from pathlib import Path def extend_dict(d:dict, k:tuple): if len(k) >= 1 and k[0] not in d: d[k[0]] = {} if len(k) >= 2 and k[1] not in d[k[0]]: d[k[0]][k[1]] = {} if len(k) >= 3 and k[2] not in d[k[0]][k[1]]: d[k[0]][k[1]][k[2]] = {} grouping_patterns = [ re.compile(r'^([XYZIJKUVW]|[XYZ]2|Z[34]|E[0-7])$'), re.compile(r'^AXIS\d$'), re.compile(r'^(MIN|MAX)$'), re.compile(r'^[0-8]$'), re.compile(r'^HOTEND[0-7]$'), re.compile(r'^(HOTENDS|BED|PROBE|COOLER)$'), re.compile(r'^[XYZIJKUVW]M(IN|AX)$') ] # If the indexed part of the option name matches a pattern # then add it to the dictionary. def find_grouping(gdict, filekey, sectkey, optkey, pindex): optparts = optkey.split('_') if 1 < len(optparts) > pindex: for patt in grouping_patterns: if patt.match(optparts[pindex]): subkey = optparts[pindex] modkey = '_'.join(optparts) optparts[pindex] = '*' wildkey = '_'.join(optparts) kkey = f'{filekey}|{sectkey}|{wildkey}' if kkey not in gdict: gdict[kkey] = [] gdict[kkey].append((subkey, modkey)) # Build a list of potential groups. Only those with multiple items will be grouped. def group_options(schema): for pindex in range(10, -1, -1): found_groups = {} for filekey, f in schema.items(): for sectkey, s in f.items(): for optkey in s: find_grouping(found_groups, filekey, sectkey, optkey, pindex) fkeys = [ k for k in found_groups.keys() ] for kkey in fkeys: items = found_groups[kkey] if len(items) > 1: f, s, w = kkey.split('|') extend_dict(schema, (f, s, w)) # Add wildcard group to schema for subkey, optkey in items: # Add all items to wildcard group schema[f][s][w][subkey] = schema[f][s][optkey] # Move non-wildcard item to wildcard group del schema[f][s][optkey] del found_groups[kkey] # Extract all board names from boards.h def load_boards(): bpath = Path("Marlin/src/core/boards.h") if bpath.is_file(): with bpath.open() as bfile: boards = [] for line in bfile: if line.startswith("#define BOARD_"): bname = line.split()[1] if bname != "BOARD_UNKNOWN": boards.append(bname) return "['" + "','".join(boards) + "']" return '' # # Extract the current configuration files in the form of a structured schema. # Contains the full schema for the configuration files, not just the enabled options, # Contains the current values of the options, not just data structure, so "schema" is a slight misnomer. # # The returned object is a nested dictionary with the following indexing: # # - schema[filekey][section][define_name] = define_info # # Where the define_info contains the following keyed fields: # - section = The @section the define is in # - name = The name of the define # - enabled = True if the define is enabled (not commented out) # - line = The line number of the define # - sid = A serial ID for the define # - value = The value of the define, if it has one # - type = The type of the define, if it has one # - requires = The conditions that must be met for the define to be enabled # - comment = The comment for the define, if it has one # - units = The units for the define, if it has one # - options = The options for the define, if it has one # def extract(): # Load board names from boards.h boards = load_boards() # Parsing states class Parse: NORMAL = 0 # No condition yet BLOCK_COMMENT = 1 # Looking for the end of the block comment EOL_COMMENT = 2 # EOL comment started, maybe add the next comment? SLASH_COMMENT = 3 # Block-like comment, starting with aligned // GET_SENSORS = 4 # Gathering temperature sensor options ERROR = 9 # Syntax error # List of files to process, with shorthand filekey = { 'Configuration.h':'basic', 'Configuration_adv.h':'advanced' } # A JSON object to store the data sch_out = { 'basic':{}, 'advanced':{} } # Regex for #define NAME [VALUE] [COMMENT] with sanitized line defgrep = re.compile(r'^(//)?\s*(#define)\s+([A-Za-z0-9_]+)\s*(.*?)\s*(//.+)?$') # Pattern to match a float value flt = r'[-+]?\s*(\d+\.|\d*\.\d+)([eE][-+]?\d+)?[fF]?' # Defines to ignore ignore = ('CONFIGURATION_H_VERSION', 'CONFIGURATION_ADV_H_VERSION', 'CONFIG_EXAMPLES_DIR', 'CONFIG_EXPORT') # Start with unknown state state = Parse.NORMAL # Serial ID sid = 0 # Loop through files and parse them line by line for fn, fk in filekey.items(): with Path("Marlin", fn).open() as fileobj: section = 'none' # Current Settings section line_number = 0 # Counter for the line number of the file conditions = [] # Create a condition stack for the current file comment_buff = [] # A temporary buffer for comments prev_comment = '' # Copy before reset for an EOL comment options_json = '' # A buffer for the most recent options JSON found eol_options = False # The options came from end of line, so only apply once join_line = False # A flag that the line should be joined with the previous one line = '' # A line buffer to handle \ continuation last_added_ref = None # Reference to the last added item # Loop through the lines in the file for the_line in fileobj.readlines(): line_number += 1 # Clean the line for easier parsing the_line = the_line.strip() if join_line: # A previous line is being made longer line += (' ' if line else '') + the_line else: # Otherwise, start the line anew line, line_start = the_line, line_number # If the resulting line ends with a \, don't process now. # Strip the end off. The next line will be joined with it. join_line = line.endswith("\\") if join_line: line = line[:-1].strip() continue else: line_end = line_number defmatch = defgrep.match(line) # Special handling for EOL comments after a #define. # At this point the #define is already digested and inserted, # so we have to extend it if state == Parse.EOL_COMMENT: # If the line is not a comment, we're done with the EOL comment if not defmatch and the_line.startswith('//'): comment_buff.append(the_line[2:].strip()) else: state = Parse.NORMAL cline = ' '.join(comment_buff) comment_buff = [] if cline != '': # A (block or slash) comment was already added cfield = 'notes' if 'comment' in last_added_ref else 'comment' last_added_ref[cfield] = cline def use_comment(c, opt, sec, bufref): if c.startswith(':'): # If the comment starts with : then it has magic JSON d = c[1:].strip() # Strip the leading : cbr = c.rindex('}') if d.startswith('{') else c.rindex(']') if d.startswith('[') else 0 if cbr: opt, cmt = c[1:cbr+1].strip(), c[cbr+1:].strip() if cmt != '': bufref.append(cmt) else: opt = c[1:].strip() elif c.startswith('@section'): # Start a new section sec = c[8:].strip() elif not c.startswith('========'): bufref.append(c) return opt, sec # For slash comments, capture consecutive slash comments. # The comment will be applied to the next #define. if state == Parse.SLASH_COMMENT: if not defmatch and the_line.startswith('//'): use_comment(the_line[2:].strip(), options_json, section, comment_buff) continue else: state = Parse.NORMAL # In a block comment, capture lines up to the end of the comment. # Assume nothing follows the comment closure. if state in (Parse.BLOCK_COMMENT, Parse.GET_SENSORS): endpos = line.find('*/') if endpos < 0: cline = line else: cline, line = line[:endpos].strip(), line[endpos+2:].strip() # Temperature sensors are done if state == Parse.GET_SENSORS: options_json = f'[ {options_json[:-2]} ]' state = Parse.NORMAL # Strip the leading '*' from block comments cline = re.sub(r'^\* ?', '', cline) # Collect temperature sensors if state == Parse.GET_SENSORS: sens = re.match(r'^(-?\d+)\s*:\s*(.+)$', cline) if sens: s2 = sens[2].replace("'","''") options_json += f"{sens[1]}:'{sens[1]} - {s2}', " elif state == Parse.BLOCK_COMMENT: # Look for temperature sensors if re.match(r'temperature sensors.*:', cline, re.IGNORECASE): state, cline = Parse.GET_SENSORS, "Temperature Sensors" options_json, section = use_comment(cline, options_json, section, comment_buff) # For the normal state we're looking for any non-blank line elif state == Parse.NORMAL: # Skip a commented define when evaluating comment opening st = 2 if re.match(r'^//\s*#define', line) else 0 cpos1 = line.find('/*') # Start a block comment on the line? cpos2 = line.find('//', st) # Start an end of line comment on the line? # Only the first comment starter gets evaluated cpos = -1 if cpos1 != -1 and (cpos1 < cpos2 or cpos2 == -1): cpos = cpos1 comment_buff = [] state = Parse.BLOCK_COMMENT eol_options = False elif cpos2 != -1 and (cpos2 < cpos1 or cpos1 == -1): cpos = cpos2 # Comment after a define may be continued on the following lines if defmatch != None and cpos > 10: state = Parse.EOL_COMMENT prev_comment = '\n'.join(comment_buff) comment_buff = [] else: state = Parse.SLASH_COMMENT # Process the start of a new comment if cpos != -1: comment_buff = [] cline, line = line[cpos+2:].strip(), line[:cpos].strip() if state == Parse.BLOCK_COMMENT: # Strip leading '*' from block comments cline = re.sub(r'^\* ?', '', cline) else: # Expire end-of-line options after first use if cline.startswith(':'): eol_options = True # Buffer a non-empty comment start if cline != '': options_json, section = use_comment(cline, options_json, section, comment_buff) # If the line has nothing before the comment, go to the next line if line == '': options_json = '' continue # Parenthesize the given expression if needed def atomize(s): if s == '' \ or re.match(r'^[A-Za-z0-9_]*(\([^)]+\))?$', s) \ or re.match(r'^[A-Za-z0-9_]+ == \d+?$', s): return s return f'({s})' # # The conditions stack is an array containing condition-arrays. # Each condition-array lists the conditions for the current block. # IF/N/DEF adds a new condition-array to the stack. # ELSE/ELIF/ENDIF pop the condition-array. # ELSE/ELIF negate the last item in the popped condition-array. # ELIF adds a new condition to the end of the array. # ELSE/ELIF re-push the condition-array. # cparts = line.split() iselif, iselse = cparts[0] == '#elif', cparts[0] == '#else' if iselif or iselse or cparts[0] == '#endif': if len(conditions) == 0: raise Exception(f'no #if block at line {line_number}') # Pop the last condition-array from the stack prev = conditions.pop() if iselif or iselse: prev[-1] = '!' + prev[-1] # Invert the last condition if iselif: prev.append(atomize(line[5:].strip())) conditions.append(prev) elif cparts[0] == '#if': conditions.append([ atomize(line[3:].strip()) ]) elif cparts[0] == '#ifdef': conditions.append([ f'defined({line[6:].strip()})' ]) elif cparts[0] == '#ifndef': conditions.append([ f'!defined({line[7:].strip()})' ]) # Handle a complete #define line elif defmatch != None: # Get the match groups into vars enabled, define_name, val = defmatch[1] == None, defmatch[3], defmatch[4] # Increment the serial ID sid += 1 # Create a new dictionary for the current #define define_info = { 'section': section, 'name': define_name, 'enabled': enabled, 'line': line_start, 'sid': sid } # Type is based on the value value_type = \ 'switch' if val == '' \ else 'bool' if re.match(r'^(true|false)$', val) \ else 'int' if re.match(r'^[-+]?\s*\d+$', val) \ else 'ints' if re.match(r'^([-+]?\s*\d+)(\s*,\s*[-+]?\s*\d+)+$', val) \ else 'floats' if re.match(rf'({flt}(\s*,\s*{flt})+)', val) \ else 'float' if re.match(f'^({flt})$', val) \ else 'string' if val[0] == '"' \ else 'char' if val[0] == "'" \ else 'state' if re.match(r'^(LOW|HIGH)$', val) \ else 'enum' if re.match(r'^[A-Za-z0-9_]{3,}$', val) \ else 'int[]' if re.match(r'^{\s*[-+]?\s*\d+(\s*,\s*[-+]?\s*\d+)*\s*}$', val) \ else 'float[]' if re.match(r'^{{\s*{flt}(\s*,\s*{flt})*\s*}}$', val) \ else 'array' if val[0] == '{' \ else '' val = (val == 'true') if value_type == 'bool' \ else int(val) if value_type == 'int' \ else val.replace('f','') if value_type == 'floats' \ else float(val.replace('f','')) if value_type == 'float' \ else val if val != '': define_info['value'] = val if value_type != '': define_info['type'] = value_type # Join up accumulated conditions with && if conditions: define_info['requires'] = '(' + ') && ('.join(sum(conditions, [])) + ')' # If the comment_buff is not empty, add the comment to the info if comment_buff: full_comment = '\n'.join(comment_buff) # An EOL comment will be added later # The handling could go here instead of above if state == Parse.EOL_COMMENT: define_info['comment'] = '' else: define_info['comment'] = full_comment comment_buff = [] # If the comment specifies units, add that to the info units = re.match(r'^\(([^)]+)\)', full_comment) if units: units = units[1] if units == 's' or units == 'sec': units = 'seconds' define_info['units'] = units # Set the options for the current #define if define_name == "MOTHERBOARD" and boards != '': define_info['options'] = boards elif options_json != '': define_info['options'] = options_json if eol_options: options_json = '' # Create section dict if it doesn't exist yet if section not in sch_out[fk]: sch_out[fk][section] = {} # If define has already been seen... if define_name in sch_out[fk][section]: info = sch_out[fk][section][define_name] if isinstance(info, dict): info = [ info ] # Convert a single dict into a list info.append(define_info) # Add to the list else: # Add the define dict with name as key sch_out[fk][section][define_name] = define_info if state == Parse.EOL_COMMENT: last_added_ref = define_info return sch_out def dump_json(schema:dict, jpath:Path): with jpath.open('w') as jfile: json.dump(schema, jfile, ensure_ascii=False, indent=2) def dump_yaml(schema:dict, ypath:Path): import yaml with ypath.open('w') as yfile: yaml.dump(schema, yfile, default_flow_style=False, width=120, indent=2) def main(): try: schema = extract() except Exception as exc: print("Error: " + str(exc)) schema = None if schema: # Get the command line arguments after the script name import sys args = sys.argv[1:] if len(args) == 0: args = ['some'] # Does the given array intersect at all with args? def inargs(c): return len(set(args) & set(c)) > 0 # Help / Unknown option unk = not inargs(['some','json','jsons','group','yml','yaml']) if (unk): print(f"Unknown option: '{args[0]}'") if inargs(['-h', '--help']) or unk: print("Usage: schema.py [some|json|jsons|group|yml|yaml]...") print(" some = json + yml") print(" jsons = json + group") return # JSON schema if inargs(['some', 'json', 'jsons']): print("Generating JSON ...") dump_json(schema, Path('schema.json')) # JSON schema (wildcard names) if inargs(['group', 'jsons']): group_options(schema) dump_json(schema, Path('schema_grouped.json')) # YAML if inargs(['some', 'yml', 'yaml']): try: import yaml except ImportError: print("Installing YAML module ...") import subprocess try: subprocess.run(['python3', '-m', 'pip', 'install', 'pyyaml']) import yaml except: print("Failed to install YAML module") return print("Generating YML ...") dump_yaml(schema, Path('schema.yml')) if __name__ == '__main__': main()
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/schema.py
Python
agpl-3.0
22,164
#!/usr/bin/env python3 # # signature.py # import schema import subprocess,re,json,hashlib from datetime import datetime from pathlib import Path def enabled_defines(filepath): ''' Return all enabled #define items from a given C header file in a dictionary. A "#define" in a multi-line comment could produce a false positive if it's not preceded by a non-space character (like * in a multi-line comment). Output: Each entry is a dictionary with a 'name' and a 'section' key. We end up with: { MOTHERBOARD: { name: "MOTHERBOARD", section: "hardware" }, ... } TODO: Drop the 'name' key as redundant. For now it's useful for debugging. This list is only used to filter config-defined options from those defined elsewhere. Because the option names are the keys, only the last occurrence is retained. This means the actual used value might not be reflected by this function. The Schema class does more complete parsing for a more accurate list of options. While the Schema class parses the configurations on its own, this script will get the preprocessor output and get the intersection of the enabled options from our crude scraping method and the actual compiler output. We end up with the actual configured state, better than what the config files say. You can then use the a decent reflection of all enabled options that (probably) came from resulting config.ini to produce more exact configuration files. ''' outdict = {} section = "user" spatt = re.compile(r".*@section +([-a-zA-Z0-9_\s]+)$") # must match @section ... f = open(filepath, encoding="utf8").read().split("\n") # Get the full contents of the file and remove all block comments. # This will avoid false positives from #defines in comments f = re.sub(r'/\*.*?\*/', '', '\n'.join(f), flags=re.DOTALL).split("\n") for line in f: sline = line.strip() m = re.match(spatt, sline) # @section ... if m: section = m.group(1).strip() ; continue if sline[:7] == "#define": # Extract the key here (we don't care about the value) kv = sline[8:].strip().split() outdict[kv[0]] = { 'name':kv[0], 'section': section } return outdict # Compute the SHA256 hash of a file def get_file_sha256sum(filepath): sha256_hash = hashlib.sha256() with open(filepath,"rb") as f: # Read and update hash string value in blocks of 4K for byte_block in iter(lambda: f.read(4096),b""): sha256_hash.update(byte_block) return sha256_hash.hexdigest() # # Compress a JSON file into a zip file # import zipfile def compress_file(filepath, storedname, outpath): with zipfile.ZipFile(outpath, 'w', compression=zipfile.ZIP_BZIP2, compresslevel=9) as zipf: zipf.write(filepath, arcname=storedname, compress_type=zipfile.ZIP_BZIP2, compresslevel=9) def compute_build_signature(env): ''' Compute the build signature by extracting all configuration settings and building a unique reversible signature that can be included in the binary. The signature can be reversed to get a 1:1 equivalent configuration file. Used by common-dependencies.py after filtering build files by feature. ''' if 'BUILD_SIGNATURE' in env: return env.Append(BUILD_SIGNATURE=1) build_path = Path(env['PROJECT_BUILD_DIR'], env['PIOENV']) marlin_json = build_path / 'marlin_config.json' marlin_zip = build_path / 'mc.zip' # Definitions from these files will be kept header_paths = [ 'Marlin/Configuration.h', 'Marlin/Configuration_adv.h' ] # Check if we can skip processing hashes = '' for header in header_paths: hashes += get_file_sha256sum(header)[0:10] # Read a previously exported JSON file # Same configuration, skip recomputing the build signature same_hash = False try: with marlin_json.open() as infile: conf = json.load(infile) same_hash = conf['__INITIAL_HASH'] == hashes if same_hash: compress_file(marlin_json, 'marlin_config.json', marlin_zip) except: pass # Extract "enabled" #define lines by scraping the configuration files. # This data also contains the @section for each option. conf_defines = {} conf_names = [] for hpath in header_paths: # Get defines in the form of { name: { name:..., section:... }, ... } defines = enabled_defines(hpath) # Get all unique define names into a flat array conf_names += defines.keys() # Remember which file these defines came from conf_defines[hpath.split('/')[-1]] = defines # Get enabled config options based on running GCC to preprocess the config files. # The result is a list of line strings, each starting with '#define'. from preprocessor import run_preprocessor build_output = run_preprocessor(env) # Dumb regex to filter out some dumb macros r = re.compile(r"\(+(\s*-*\s*_.*)\)+") # Extract all the #define lines in the build output as key/value pairs build_defines = {} for line in build_output: # Split the define from the value. key_val = line[8:].strip().decode().split(' ') key, value = key_val[0], ' '.join(key_val[1:]) # Ignore values starting with two underscore, since it's low level if len(key) > 2 and key[0:2] == "__": continue # Ignore values containing parentheses (likely a function macro) if '(' in key and ')' in key: continue # Then filter dumb values if r.match(value): continue build_defines[key] = value if len(value) else "" # # Continue to gather data for CONFIGURATION_EMBEDDING or CONFIG_EXPORT # if not ('CONFIGURATION_EMBEDDING' in build_defines or 'CONFIG_EXPORT' in build_defines): return # Filter out useless macros from the output cleaned_build_defines = {} for key in build_defines: # Remove all boards now if key.startswith("BOARD_") and key != "BOARD_INFO_NAME": continue # Remove all keys ending by "_T_DECLARED" as it's a copy of extraneous system stuff if key.endswith("_T_DECLARED"): continue # Remove keys that are not in the #define list in the Configuration list if key not in conf_names + [ 'DETAILED_BUILD_VERSION', 'STRING_DISTRIBUTION_DATE' ]: continue # Add to a new dictionary for simplicity cleaned_build_defines[key] = build_defines[key] # And we only care about defines that (most likely) came from the config files # Build a dictionary of dictionaries with keys: 'name', 'section', 'value' # { 'file1': { 'option': { 'name':'option', 'section':..., 'value':... }, ... }, 'file2': { ... } } real_config = {} for header in conf_defines: real_config[header] = {} for key in cleaned_build_defines: if key in conf_defines[header]: if key[0:2] == '__': continue val = cleaned_build_defines[key] real_config[header][key] = { 'file':header, 'name': key, 'value': val, 'section': conf_defines[header][key]['section']} def tryint(key): try: return int(build_defines[key]) except: return 0 # Get the CONFIG_EXPORT value and do an extended dump if > 100 # For example, CONFIG_EXPORT 102 will make a 'config.ini' with a [config:] group for each schema @section config_dump = tryint('CONFIG_EXPORT') extended_dump = config_dump > 100 if extended_dump: config_dump -= 100 # # Produce an INI file if CONFIG_EXPORT == 2 # if config_dump == 2: print("Generating config.ini ...") ini_fmt = '{0:40} = {1}' ext_fmt = '{0:40} {1}' ignore = ('CONFIGURATION_H_VERSION', 'CONFIGURATION_ADV_H_VERSION', 'CONFIG_EXPORT') if extended_dump: # Extended export will dump config options by section # We'll use Schema class to get the sections try: conf_schema = schema.extract() except Exception as exc: print("Error: " + str(exc)) exit(1) # Then group options by schema @section sections = {} for header in real_config: for name in real_config[header]: #print(f" name: {name}") if name not in ignore: ddict = real_config[header][name] #print(f" real_config[{header}][{name}]:", ddict) sect = ddict['section'] if sect not in sections: sections[sect] = {} sections[sect][name] = ddict # Get all sections as a list of strings, with spaces and dashes replaced by underscores long_list = [ re.sub(r'[- ]+', '_', x).lower() for x in sections.keys() ] # Make comma-separated lists of sections with 64 characters or less sec_lines = [] while len(long_list): line = long_list.pop(0) + ', ' while len(long_list) and len(line) + len(long_list[0]) < 64 - 1: line += long_list.pop(0) + ', ' sec_lines.append(line.strip()) sec_lines[-1] = sec_lines[-1][:-1] # Remove the last comma else: sec_lines = ['all'] # Build the ini_use_config item sec_list = ini_fmt.format('ini_use_config', sec_lines[0]) for line in sec_lines[1:]: sec_list += '\n' + ext_fmt.format('', line) config_ini = build_path / 'config.ini' with config_ini.open('w') as outfile: filegrp = { 'Configuration.h':'config:basic', 'Configuration_adv.h':'config:advanced' } vers = build_defines["CONFIGURATION_H_VERSION"] dt_string = datetime.now().strftime("%Y-%m-%d at %H:%M:%S") outfile.write( f'''# # Marlin Firmware # config.ini - Options to apply before the build # # Generated by Marlin build on {dt_string} # [config:base] # # ini_use_config - A comma-separated list of actions to apply to the Configuration files. # The actions will be applied in the listed order. # - none # Ignore this file and don't apply any configuration options # # - base # Just apply the options in config:base to the configuration # # - minimal # Just apply the options in config:minimal to the configuration # # - all # Apply all 'config:*' sections in this file to the configuration # # - another.ini # Load another INI file with a path relative to this config.ini file (i.e., within Marlin/) # # - https://me.myserver.com/path/to/configs # Fetch configurations from any URL. # # - example/Creality/Ender-5 Plus @ bugfix-2.1.x # Fetch example configuration files from the MarlinFirmware/Configurations repository # https://raw.githubusercontent.com/MarlinFirmware/Configurations/bugfix-2.1.x/config/examples/Creality/Ender-5%20Plus/ # # - example/default @ release-2.0.9.7 # Fetch default configuration files from the MarlinFirmware/Configurations repository # https://raw.githubusercontent.com/MarlinFirmware/Configurations/release-2.0.9.7/config/default/ # # - [disable] # Comment out all #defines in both Configuration.h and Configuration_adv.h. This is useful # to start with a clean slate before applying any config: options, so only the options explicitly # set in config.ini will be enabled in the configuration. # # - [flatten] (Not yet implemented) # Produce a flattened set of Configuration.h and Configuration_adv.h files with only the enabled # #defines and no comments. A clean look, but context-free. # {sec_list} {ini_fmt.format('ini_config_vers', vers)} ''' ) if extended_dump: # Loop through the sections for skey in sorted(sections): #print(f" skey: {skey}") sani = re.sub(r'[- ]+', '_', skey).lower() outfile.write(f"\n[config:{sani}]\n") opts = sections[skey] for name in sorted(opts): val = opts[name]['value'] if val == '': val = 'on' #print(f" {name} = {val}") outfile.write(ini_fmt.format(name.lower(), val) + '\n') else: # Standard export just dumps config:basic and config:advanced sections for header in real_config: outfile.write(f'\n[{filegrp[header]}]\n') for name in sorted(real_config[header]): if name not in ignore: val = real_config[header][name]['value'] if val == '': val = 'on' outfile.write(ini_fmt.format(name.lower(), val) + '\n') # # CONFIG_EXPORT 3 = schema.json, 4 = schema.yml # if config_dump >= 3: try: conf_schema = schema.extract() except Exception as exc: print("Error: " + str(exc)) conf_schema = None if conf_schema: # # 3 = schema.json # if config_dump in (3, 13): print("Generating schema.json ...") schema.dump_json(conf_schema, build_path / 'schema.json') if config_dump == 13: schema.group_options(conf_schema) schema.dump_json(conf_schema, build_path / 'schema_grouped.json') # # 4 = schema.yml # elif config_dump == 4: print("Generating schema.yml ...") try: import yaml except ImportError: env.Execute(env.VerboseAction( '$PYTHONEXE -m pip install "pyyaml"', "Installing YAML for schema.yml export", )) import yaml schema.dump_yaml(conf_schema, build_path / 'schema.yml') # # Produce a JSON file for CONFIGURATION_EMBEDDING or CONFIG_EXPORT == 1 # Skip if an identical JSON file was already present. # if not same_hash and (config_dump == 1 or 'CONFIGURATION_EMBEDDING' in build_defines): with marlin_json.open('w') as outfile: json_data = {} if extended_dump: print("Extended dump ...") for header in real_config: confs = real_config[header] json_data[header] = {} for name in confs: c = confs[name] s = c['section'] if s not in json_data[header]: json_data[header][s] = {} json_data[header][s][name] = c['value'] else: for header in real_config: conf = real_config[header] #print(f"real_config[{header}]", conf) for name in conf: json_data[name] = conf[name]['value'] json_data['__INITIAL_HASH'] = hashes # Append the source code version and date json_data['VERSION'] = { 'DETAILED_BUILD_VERSION': cleaned_build_defines['DETAILED_BUILD_VERSION'], 'STRING_DISTRIBUTION_DATE': cleaned_build_defines['STRING_DISTRIBUTION_DATE'] } try: curver = subprocess.check_output(["git", "describe", "--match=NeVeRmAtCh", "--always"]).strip() json_data['VERSION']['GIT_REF'] = curver.decode() except: pass json.dump(json_data, outfile, separators=(',', ':')) # # The rest only applies to CONFIGURATION_EMBEDDING # if not 'CONFIGURATION_EMBEDDING' in build_defines: (build_path / 'mc.zip').unlink(missing_ok=True) return # Compress the JSON file as much as we can if not same_hash: compress_file(marlin_json, 'marlin_config.json', marlin_zip) # Generate a C source file containing the entire ZIP file as an array with open('Marlin/src/mczip.h','wb') as result_file: result_file.write( b'#ifndef NO_CONFIGURATION_EMBEDDING_WARNING\n' + b' #warning "Generated file \'mc.zip\' is embedded (Define NO_CONFIGURATION_EMBEDDING_WARNING to suppress this warning.)"\n' + b'#endif\n' + b'const unsigned char mc_zip[] PROGMEM = {\n ' ) count = 0 for b in (build_path / 'mc.zip').open('rb').read(): result_file.write(b' 0x%02X,' % b) count += 1 if count % 16 == 0: result_file.write(b'\n ') if count % 16: result_file.write(b'\n') result_file.write(b'};\n') if __name__ == "__main__": # Build required. From command line just explain usage. print("Use schema.py to export JSON and YAML from the command-line.") print("Build Marlin with CONFIG_EXPORT 2 to export 'config.ini'.")
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/signature.py
Python
agpl-3.0
17,190
# # simulator.py # PlatformIO pre: script for simulator builds # import pioutil if pioutil.is_pio_build(): # Get the environment thus far for the build Import("env") #print(env.Dump()) # # Give the binary a distinctive name # env['PROGNAME'] = "MarlinSimulator" # # If Xcode is installed add the path to its Frameworks folder, # or if Mesa is installed try to use its GL/gl.h. # import sys if sys.platform == 'darwin': # # Silence half of the ranlib warnings. (No equivalent for 'ARFLAGS') # env['RANLIBFLAGS'] += [ "-no_warning_for_no_symbols" ] # Default paths for Xcode and a lucky GL/gl.h dropped by Mesa xcode_path = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks" mesa_path = "/opt/local/include/GL/gl.h" import os.path if os.path.exists(xcode_path): env['BUILD_FLAGS'] += [ "-F" + xcode_path ] print("Using OpenGL framework headers from Xcode.app") elif os.path.exists(mesa_path): env['BUILD_FLAGS'] += [ '-D__MESA__' ] print("Using OpenGL header from", mesa_path) else: print("\n\nNo OpenGL headers found. Install Xcode for matching headers, or use 'sudo port install mesa' to get a GL/gl.h.\n\n") # Break out of the PIO build immediately sys.exit(1)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/simulator.py
Python
agpl-3.0
1,474
# # stm32_serialbuffer.py # import pioutil if pioutil.is_pio_build(): Import("env") # Get a build flag's value or None def getBuildFlagValue(name): for flag in build_flags: if isinstance(flag, list) and flag[0] == name: return flag[1] return None # Get an overriding buffer size for RX or TX from the build flags def getInternalSize(side): return getBuildFlagValue(f"MF_{side}_BUFFER_SIZE") or \ getBuildFlagValue(f"SERIAL_{side}_BUFFER_SIZE") or \ getBuildFlagValue(f"USART_{side}_BUF_SIZE") # Get the largest defined buffer size for RX or TX def getBufferSize(side, default): # Get a build flag value or fall back to the given default internal = int(getInternalSize(side) or default) flag = side + "_BUFFER_SIZE" # Return the largest value return max(int(mf[flag]), internal) if flag in mf else internal # Add a build flag if it's not already defined def tryAddFlag(name, value): if getBuildFlagValue(name) is None: env.Append(BUILD_FLAGS=[f"-D{name}={value}"]) # Marlin uses the `RX_BUFFER_SIZE` \ `TX_BUFFER_SIZE` options to # configure buffer sizes for receiving \ transmitting serial data. # Stm32duino uses another set of defines for the same purpose, so this # script gets the values from the configuration and uses them to define # `SERIAL_RX_BUFFER_SIZE` and `SERIAL_TX_BUFFER_SIZE` as global build # flags so they are available for use by the platform. # # The script will set the value as the default one (64 bytes) # or the user-configured one, whichever is higher. # # Marlin's default buffer sizes are 128 for RX and 32 for TX. # The highest value is taken (128/64). # # If MF_*_BUFFER_SIZE, SERIAL_*_BUFFER_SIZE, USART_*_BUF_SIZE, are # defined, the first of these values will be used as the minimum. build_flags = env.ParseFlags(env.get('BUILD_FLAGS'))["CPPDEFINES"] mf = env["MARLIN_FEATURES"] # Get the largest defined buffer sizes for RX or TX, using defaults for undefined rxBuf = getBufferSize("RX", 128) txBuf = getBufferSize("TX", 64) # Provide serial buffer sizes to the stm32duino platform tryAddFlag("SERIAL_RX_BUFFER_SIZE", rxBuf) tryAddFlag("SERIAL_TX_BUFFER_SIZE", txBuf) tryAddFlag("USART_RX_BUF_SIZE", rxBuf) tryAddFlag("USART_TX_BUF_SIZE", txBuf)
2301_81045437/Marlin
buildroot/share/PlatformIO/scripts/stm32_serialbuffer.py
Python
agpl-3.0
2,470