#ifndef PHONY_BL_H_
#define PHONY_BL_H_
//----------------------------------------------------------------------------
///
/// \brief   Phony bootloader
///
///          Fake it
///          https://www.st.com/resource/en/application_note/an3155-usart-protocol-used-in-the-stm32-bootloader-stmicroelectronics.pdf
///
/// \date   20221112
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//----------------------------------------------------------------------------


//---Includes-----------------------------------------------------------------


//---Own------------------------------

#include <biwak/iostream.h>


//---Declaration--------------------------------------------------------------


void readFlashData(int addr, void *dest, size_t size);
void writeFlashData(int addr, void *src, size_t size);
void eraseFlash();

class CPhonyBL
{
   private:
      CIOStream &m_io;
      static constexpr char ACK  =0x79;
      static constexpr char NACK =0x1F;

      struct SFunction
      {
         uint8_t  ch1;
         uint8_t  ch2;
         void (CPhonyBL::*func)(void);
         const char *name;
      };
      static SFunction functions[];
      uint8_t m_pages[0x101];
      uint8_t m_data[0x101];

   public:
      CSignal <void, int> writeSignal;
      CPhonyBL(CIOStream &io)
         :m_io(io)
      {};

      void eventLoop();
      int getInput();

      // BL functions
      void info( void );
      void version( void );
      void readMemory( void );
      void eraseMemory( void );
      void writeMemory( void );
      void extEraseMemory( void );
      void specialCommand( void );
      void ack( void );
      void nack( void );
      static bool checkXor( char start, const char *buf, int size, char targetXor );
};


//---fin----------------------------------------------------------------------
#endif // ? ! PHONY_BL_H_
