# This script configures OpenOCD for use with an ST-Link V2 programmer/debugger
# and an STM32L4S5 target microcontroller.
#
# To flash your firmware:
#
#    $ openocd -f openocd_stm32l4x6.cfg \
#        -c "stm_flash build-BOARD/firmware0.bin 0x08000000 build-BOARD/firmware1.bin 0x08004000"
#
# For a gdb server on port 3333:
#
#    $ openocd -f openocd_stm32l4x6.cfg


source [find interface/stlink.cfg]
transport select hla_swd
source [find target/stm32l4x.cfg]

# from <http://www.openstm32.org/forumthread7123>
#reset_config srst_only
reset_config none separate

init

proc stm_flash { BIN0 ADDR0 BIN1 ADDR1 } {
    reset halt
    sleep 100
    wait_halt 2
    flash write_image erase $BIN0 $ADDR0
    sleep 100
    verify_image $BIN0 $ADDR0
    sleep 100
    flash write_image erase $BIN1 $ADDR1
    sleep 100
    verify_image $BIN1 $ADDR1
    sleep 100
    reset run
    shutdown
}

proc stm_erase {} {
    reset halt
    sleep 100
    stm32l4x mass_erase 0
    sleep 100
    shutdown
}

proc dfu {} {
    # reset and get it started; doesn't work from "reset halt" nor "reset init"
    reset run
    halt

    # SYSCFG->MEMRMP setup for system flash @ 0x0
    # do __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH() 
    mww 0x40010000 0x1 

    # do "mdw 0x0 2" to learn these two values
    reg msp 0x20003560
    reg pc 0x1fff51db

    resume
    sleep 500
}
