diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index c32e44b..b065d7c 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -74,24 +74,21 @@ MySensor::MySensor(MyTransport &_radio, MyHw &_hw #ifdef MY_OTA_FIRMWARE_FEATURE -// do a crc16 on the whole received firmware -bool MySensor::isValidFirmware() { - void* ptr = 0; - uint16_t crc = ~0; - int j; +// do a crc16 on the whole received firmware +bool MySensor::isValidFirmware() { + // init crc + uint16_t crc = ~0; for (uint16_t i = 0; i < fc.blocks * FIRMWARE_BLOCK_SIZE; ++i) { - uint8_t a = flash.readByte((uint16_t) ptr + i + FIRMWARE_START_OFFSET); - crc ^= a; - for (j = 0; j < 8; ++j) - { + crc ^= flash.readByte(i + FIRMWARE_START_OFFSET); + for (int8_t j = 0; j < 8; ++j) { if (crc & 1) crc = (crc >> 1) ^ 0xA001; else crc = (crc >> 1); } - } - return crc == fc.crc; + } + return crc == fc.crc; } #endif @@ -722,46 +719,61 @@ boolean MySensor::process() { // compare with current node configuration, if they differ, start fw fetch process if (memcmp(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig))) { debug(PSTR("fw update\n")); - fwUpdateOngoing = true; - fwBlock = fc.blocks; // copy new FW config memcpy(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig)); // Init flash if (!flash.initialize()) { debug(PSTR("flash init fail\n")); + fwUpdateOngoing = false; + } else { + // erase lower 32K -> max flash size for ATMEGA328 + flash.blockErase32K(0); + // wait until flash erased + while ( flash.busy() ); + fwBlock = fc.blocks; + fwUpdateOngoing = true; + // reset flags + fwRetry = MY_OTA_RETRY+1; + fwLastRequestTime = 0; } - - } + return false; + } else debug(PSTR("fw update skipped\n")); } else if (type == ST_FIRMWARE_RESPONSE) { - // Save block to eeprom + // Save block to flash debug(PSTR("fw block %d\n"), fwBlock); - + // extract FW block ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data; // write to flash - flash.writeBytes(((fwBlock-1)*FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); + flash.writeBytes( ((fwBlock - 1) * FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); + // wait until flash written + while ( flash.busy() ); fwBlock--; - if (fwBlock == 0) { + if (!fwBlock) { // We're finished! Do a checksum and reboot. if (isValidFirmware()) { debug(PSTR("fw checksum ok\n")); // All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it) - uint16_t fwsize = FIRMWARE_BLOCK_SIZE*fc.blocks; flash.writeBytes(0, "FLXIMG:", 7); + // FW size in flash + uint16_t fwsize = FIRMWARE_BLOCK_SIZE * fc.blocks; flash.writeByte(7, fwsize >> 8); flash.writeByte(8, fwsize); + // end of header flash.writeByte(9, ':'); // Write the new firmware config to eeprom hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); hw_reboot(); } else { debug(PSTR("fw checksum fail\n")); + fwUpdateOngoing = false; } } + // reset flags + fwRetry = MY_OTA_RETRY+1; + fwLastRequestTime = 0; + return false; } - // Make sure packet request occurs next time process() is called by timing out requestTime. - fwRetry = MY_OTA_RETRY+1; - fwLastRequestTime = 0; - return false; + } #endif // Call incoming message callback if available diff --git a/libraries/MySensors/utility/SPIFlash.cpp b/libraries/MySensors/utility/SPIFlash.cpp index ee6e1b0..e250c17 100644 --- a/libraries/MySensors/utility/SPIFlash.cpp +++ b/libraries/MySensors/utility/SPIFlash.cpp @@ -1,20 +1,40 @@ -/* - * Copyright (c) 2013 by Felix Rusu - * SPI Flash memory library for arduino/moteino. - * This works with 256byte/page SPI flash memory - * For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) - * Minimal modifications should allow chips that have different page size but modifications - * DEPENDS ON: Arduino SPI library - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ +// Copyright (c) 2013-2015 by Felix Rusu, LowPowerLab.com +// SPI Flash memory library for arduino/moteino. +// This works with 256byte/page SPI flash memory +// For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) +// Minimal modifications should allow chips that have different page size but modifications +// DEPENDS ON: Arduino SPI library +// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment. +// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above) +// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4 +// ********************************************************************************** +// License +// ********************************************************************************** +// 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 . +// +// Licence can be viewed at +// http://www.gnu.org/licenses/gpl-3.0.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code #include -byte SPIFlash::UNIQUEID[8]; +uint8_t SPIFlash::UNIQUEID[8]; /// IMPORTANT: NAND FLASH memory requires erase before write, because /// it can only transition from 1s to 0s and only the erase command can reset all 0s to 1s @@ -32,15 +52,22 @@ SPIFlash::SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID) { /// Select the flash chip void SPIFlash::select() { - noInterrupts(); //save current SPI settings +#ifndef SPI_HAS_TRANSACTION + noInterrupts(); +#endif _SPCR = SPCR; _SPSR = SPSR; - //set FLASH chip SPI settings + +#ifdef SPI_HAS_TRANSACTION + SPI.beginTransaction(_settings); +#else + // set FLASH SPI settings SPI.setDataMode(SPI_MODE0); SPI.setBitOrder(MSBFIRST); SPI.setClockDivider(SPI_CLOCK_DIV4); //decided to slow down from DIV2 after SPI stalling in some instances, especially visible on mega1284p when RFM69 and FLASH chip both present SPI.begin(); +#endif digitalWrite(_slaveSelectPin, LOW); } @@ -48,18 +75,25 @@ void SPIFlash::select() { void SPIFlash::unselect() { digitalWrite(_slaveSelectPin, HIGH); //restore SPI settings to what they were before talking to the FLASH chip +#ifdef SPI_HAS_TRANSACTION + SPI.endTransaction(); +#else + interrupts(); +#endif SPCR = _SPCR; SPSR = _SPSR; - interrupts(); } /// setup SPI, read device ID etc... boolean SPIFlash::initialize() { - SPI.begin(); _SPCR = SPCR; _SPSR = SPSR; pinMode(_slaveSelectPin, OUTPUT); +#ifdef SPI_HAS_TRANSACTION + _settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); +#endif + unselect(); wakeup(); @@ -73,7 +107,7 @@ boolean SPIFlash::initialize() } /// Get the manufacturer and device ID bytes (as a short word) -word SPIFlash::readDeviceId() +uint16_t SPIFlash::readDeviceId() { #if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo command(SPIFLASH_IDREAD); // Read JEDEC ID @@ -81,7 +115,7 @@ word SPIFlash::readDeviceId() select(); SPI.transfer(SPIFLASH_IDREAD); #endif - word jedecid = SPI.transfer(0) << 8; + uint16_t jedecid = SPI.transfer(0) << 8; jedecid |= SPI.transfer(0); unselect(); return jedecid; @@ -90,47 +124,47 @@ word SPIFlash::readDeviceId() /// Get the 64 bit unique identifier, stores it in UNIQUEID[8]. Only needs to be called once, ie after initialize /// Returns the byte pointer to the UNIQUEID byte array /// Read UNIQUEID like this: -/// flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); } +/// flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); } /// or like this: -/// flash.readUniqueId(); byte* MAC = flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); } -byte* SPIFlash::readUniqueId() +/// flash.readUniqueId(); uint8_t* MAC = flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); } +uint8_t* SPIFlash::readUniqueId() { command(SPIFLASH_MACREAD); SPI.transfer(0); SPI.transfer(0); SPI.transfer(0); SPI.transfer(0); - for (byte i=0;i<8;i++) + for (uint8_t i=0;i<8;i++) UNIQUEID[i] = SPI.transfer(0); unselect(); return UNIQUEID; } /// read 1 byte from flash memory -byte SPIFlash::readByte(long addr) { +uint8_t SPIFlash::readByte(uint32_t addr) { command(SPIFLASH_ARRAYREADLOWFREQ); SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); SPI.transfer(addr); - byte result = SPI.transfer(0); + uint8_t result = SPI.transfer(0); unselect(); return result; } /// read unlimited # of bytes -void SPIFlash::readBytes(long addr, void* buf, word len) { +void SPIFlash::readBytes(uint32_t addr, void* buf, uint16_t len) { command(SPIFLASH_ARRAYREAD); SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); SPI.transfer(addr); SPI.transfer(0); //"dont care" - for (word i = 0; i < len; ++i) - ((byte*) buf)[i] = SPI.transfer(0); + for (uint16_t i = 0; i < len; ++i) + ((uint8_t*) buf)[i] = SPI.transfer(0); unselect(); } /// Send a command to the flash chip, pass TRUE for isWrite when its a write command -void SPIFlash::command(byte cmd, boolean isWrite){ +void SPIFlash::command(uint8_t cmd, boolean isWrite){ #if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo DDRB |= B00000001; // Make sure the SS pin (PB0 - used by RFM12B on MoteinoLeo R1) is set as output HIGH! PORTB |= B00000001; @@ -156,7 +190,7 @@ boolean SPIFlash::busy() /* select(); SPI.transfer(SPIFLASH_STATUSREAD); - byte status = SPI.transfer(0); + uint8_t status = SPI.transfer(0); unselect(); return status & 1; */ @@ -164,11 +198,11 @@ boolean SPIFlash::busy() } /// return the STATUS register -byte SPIFlash::readStatus() +uint8_t SPIFlash::readStatus() { select(); SPI.transfer(SPIFLASH_STATUSREAD); - byte status = SPI.transfer(0); + uint8_t status = SPI.transfer(0); unselect(); return status; } @@ -177,7 +211,7 @@ byte SPIFlash::readStatus() /// Write 1 byte to flash memory /// WARNING: you can only write to previously erased memory locations (see datasheet) /// use the block erase commands to first clear memory (write 0xFFs) -void SPIFlash::writeByte(long addr, uint8_t byt) { +void SPIFlash::writeByte(uint32_t addr, uint8_t byt) { command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); @@ -186,20 +220,32 @@ void SPIFlash::writeByte(long addr, uint8_t byt) { unselect(); } -/// write 1-256 bytes to flash memory +/// write multiple bytes to flash memory (up to 64K) /// WARNING: you can only write to previously erased memory locations (see datasheet) /// use the block erase commands to first clear memory (write 0xFFs) -/// WARNING: if you write beyond a page boundary (or more than 256bytes), -/// the bytes will wrap around and start overwriting at the beginning of that same page -/// see datasheet for more details -void SPIFlash::writeBytes(long addr, const void* buf, uint16_t len) { - command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program - SPI.transfer(addr >> 16); - SPI.transfer(addr >> 8); - SPI.transfer(addr); - for (uint16_t i = 0; i < len; i++) - SPI.transfer(((byte*) buf)[i]); - unselect(); +/// This version handles both page alignment and data blocks larger than 256 bytes. +/// +void SPIFlash::writeBytes(uint32_t addr, const void* buf, uint16_t len) { + uint16_t n; + uint16_t maxBytes = 256-(addr%256); // force the first set of bytes to stay within the first page + uint16_t offset = 0; + while (len>0) + { + n = (len<=maxBytes) ? len : maxBytes; + command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program + SPI.transfer(addr >> 16); + SPI.transfer(addr >> 8); + SPI.transfer(addr); + + for (uint16_t i = 0; i < n; i++) + SPI.transfer(((uint8_t*) buf)[offset + i]); + unselect(); + + addr+=n; // adjust the addresses and remaining bytes by what we've just transferred. + offset +=n; + len -= n; + maxBytes = 256; // now we can do up to 256 bytes per loop + } } /// erase entire flash memory array @@ -214,7 +260,7 @@ void SPIFlash::chipErase() { } /// erase a 4Kbyte block -void SPIFlash::blockErase4K(long addr) { +void SPIFlash::blockErase4K(uint32_t addr) { command(SPIFLASH_BLOCKERASE_4K, true); // Block Erase SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); @@ -223,7 +269,7 @@ void SPIFlash::blockErase4K(long addr) { } /// erase a 32Kbyte block -void SPIFlash::blockErase32K(long addr) { +void SPIFlash::blockErase32K(uint32_t addr) { command(SPIFLASH_BLOCKERASE_32K, true); // Block Erase SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); diff --git a/libraries/MySensors/utility/SPIFlash.h b/libraries/MySensors/utility/SPIFlash.h index f0c071a..a308760 100644 --- a/libraries/MySensors/utility/SPIFlash.h +++ b/libraries/MySensors/utility/SPIFlash.h @@ -1,16 +1,36 @@ -/* - * Copyright (c) 2013 by Felix Rusu - * SPI Flash memory library for arduino/moteino. - * This works with 256byte/page SPI flash memory - * For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) - * Minimal modifications should allow chips that have different page size but modifications - * DEPENDS ON: Arduino SPI library - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ +// Copyright (c) 2013-2015 by Felix Rusu, LowPowerLab.com +// SPI Flash memory library for arduino/moteino. +// This works with 256byte/page SPI flash memory +// For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) +// Minimal modifications should allow chips that have different page size but modifications +// DEPENDS ON: Arduino SPI library +// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment. +// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above) +// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4 +// ********************************************************************************** +// License +// ********************************************************************************** +// 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 . +// +// Licence can be viewed at +// http://www.gnu.org/licenses/gpl-3.0.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code #ifndef _SPIFLASH_H_ #define _SPIFLASH_H_ @@ -33,19 +53,19 @@ /// Assuming the WP pin is pulled up (to disable hardware write protection) /// To use any write commands the WEL bit in the status register must be set to 1. /// This is accomplished by sending a 0x06 command before any such write/erase command. -/// The WEL bit in the status register resets to the logical “0” state after a -/// device power-up or reset. In addition, the WEL bit will be reset to the logical “0” state automatically under the following conditions: -/// • Write Disable operation completes successfully -/// • Write Status Register operation completes successfully or aborts -/// • Protect Sector operation completes successfully or aborts -/// • Unprotect Sector operation completes successfully or aborts -/// • Byte/Page Program operation completes successfully or aborts -/// • Sequential Program Mode reaches highest unprotected memory location -/// • Sequential Program Mode reaches the end of the memory array -/// • Sequential Program Mode aborts -/// • Block Erase operation completes successfully or aborts -/// • Chip Erase operation completes successfully or aborts -/// • Hold condition aborts +/// The WEL bit in the status register resets to the logical ?0? state after a +/// device power-up or reset. In addition, the WEL bit will be reset to the logical ?0? state automatically under the following conditions: +/// ? Write Disable operation completes successfully +/// ? Write Status Register operation completes successfully or aborts +/// ? Protect Sector operation completes successfully or aborts +/// ? Unprotect Sector operation completes successfully or aborts +/// ? Byte/Page Program operation completes successfully or aborts +/// ? Sequential Program Mode reaches highest unprotected memory location +/// ? Sequential Program Mode reaches the end of the memory array +/// ? Sequential Program Mode aborts +/// ? Block Erase operation completes successfully or aborts +/// ? Chip Erase operation completes successfully or aborts +/// ? Hold condition aborts #define SPIFLASH_WRITEENABLE 0x06 // write enable #define SPIFLASH_WRITEDISABLE 0x04 // write disable @@ -69,21 +89,21 @@ class SPIFlash { public: - static byte UNIQUEID[8]; - SPIFlash(byte slaveSelectPin, uint16_t jedecID=0); + static uint8_t UNIQUEID[8]; + SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID=0); boolean initialize(); - void command(byte cmd, boolean isWrite=false); - byte readStatus(); - byte readByte(long addr); - void readBytes(long addr, void* buf, word len); - void writeByte(long addr, byte byt); - void writeBytes(long addr, const void* buf, uint16_t len); + void command(uint8_t cmd, boolean isWrite=false); + uint8_t readStatus(); + uint8_t readByte(uint32_t addr); + void readBytes(uint32_t addr, void* buf, uint16_t len); + void writeByte(uint32_t addr, uint8_t byt); + void writeBytes(uint32_t addr, const void* buf, uint16_t len); boolean busy(); void chipErase(); - void blockErase4K(long address); - void blockErase32K(long address); - word readDeviceId(); - byte* readUniqueId(); + void blockErase4K(uint32_t address); + void blockErase32K(uint32_t address); + uint16_t readDeviceId(); + uint8_t* readUniqueId(); void sleep(); void wakeup(); @@ -91,10 +111,13 @@ public: protected: void select(); void unselect(); - byte _slaveSelectPin; + uint8_t _slaveSelectPin; uint16_t _jedecID; - byte _SPCR; - byte _SPSR; + uint8_t _SPCR; + uint8_t _SPSR; +#ifdef SPI_HAS_TRANSACTION + SPISettings _settings; +#endif }; #endif \ No newline at end of file