/*
 * srm32sprog.h
 *
 *  Created on: Apr 12, 2016
 *      Author: jesstr
 */

#ifndef SRM32SPROG_H_
#define SRM32SPROG_H_

#include "stm32f4xx_usart.h"
#include "gpio_io.h"

#include "serial.h"
#include "sys/types.h"

#define MAX_CONNECT_RETRIES	3

#define DEFAULT_BAUD 57600

#define MAX_BLOCK_SIZE 256


static const uint8_t ACK = 0x79;
typedef enum {
    CMD_GET_VERSION = 0x00,
    CMD_GET_READ_STATUS = 0x01,
    CMD_GET_ID = 0x02,
    CMD_READ_MEM = 0x11,
    CMD_GO = 0x21,
    CMD_WRITE_MEM = 0x31,
    CMD_ERASE = 0x43,
    CMD_EXTENDED_ERASE = 0x44,
    CMD_WRITE_PROTECT = 0x63,
    CMD_WRITE_UNPROTECT = 0x73,
    CMD_READ_PROTECT = 0x82,
    CMD_READ_UNPROTECT = 0x92
} Command;
#define NUM_COMMANDS_KNOWN 12

enum {
    ID_LOW_DENSITY = 0x0412,
    ID_MED_DENSITY = 0x0410,
    ID_HI_DENSITY = 0x0414,
    ID_CONNECTIVITY = 0x0418,
    ID_VALUE = 0x0420,
    ID_HI_DENSITY_VALUE = 0x0428,
    ID_XL_DENSITY = 0x0430,
    ID_MED_DENSITY_ULTRA_LOW_POWER = 0x0436,
    ID_HI_DENSITY_ULTRA_LOW_POWER = 0x0416
};

typedef struct {
    uint8_t bootloaderVer;
    bool commands[NUM_COMMANDS_KNOWN];
    uint32_t flashBeginAddr;
    uint32_t flashEndAddr;
    int flashPagesPerSector;
    size_t flashPageSize;
    useconds_t eraseDelay;
    useconds_t writeDelay;
} DeviceParameters;

int stm32sprog_test(void);
void usleep(uint32_t us);
void stmRebootForFlash(void);
void stmReboot(void);
uint32_t stmCalcFlashCrc(void (* periodic_handler)(uint8_t));
uint32_t stmReadFlashCrc(void);
bool stmConnect(void);
bool stmGetDevParams(void);
bool stmEraseFlash(void);
bool stmEraseFW(void);
bool stmWriteBlock(uint32_t addr, const uint8_t *buff, size_t size);
void stmProg( uint32_t* addr, uint8_t * ptr, uint32_t len);


#endif /* SRM32SPROG_H_ */
