; ***************************************************************************
; copyright   : (C) 2025 by Martin Preuss
; email       : martin@libchipcard.de
;
; ***************************************************************************
; * This file is part of the project "AqHome".                              *
; * Please see toplevel file COPYING of that project for license details.   *
; ***************************************************************************



; ***************************************************************************
; code

.cseg



BOOTLOADER_BEGIN:




bootLoader:
  cli
  ; setup stack
  .ifdef SPH               ; if SPH is defined
    ldi r16, High(RAMEND)
    out SPH, r16           ; init MSB stack pointer
  .endif
  ldi r16, Low(RAMEND)
  out SPL, r16             ; init LSB stack pointer

  ; start by setting all ports as inputs and enable internal pull-up resistors
  ldi r16, 0xff
  clr r17
.ifdef PORTA
  out DDRA, r17  ; all input
  out PORTA, r16 ; enable pull-up on all
.endif

.ifdef PORTB
  out DDRB, r17  ; all input
  out PORTB, r16 ; enable pull-up on all
.endif

.ifdef PORTC
  out DDRC, r17  ; all input
  out PORTC, r16 ; enable pull-up on all
.endif

  rcall systemSetSpeed
;  rcall watchdogOff        ; turn off watchdog timer (sometimes it stays on after reboot)

  sbi LED_DDR, LED_PINNUM  ; out
  sbi LED_PORT, LED_PINNUM ; off

  ldi r19, 10 ; loop count
  ldi r20, 2  ; on time
  ldi r21, 2  ; off time
  rcall bootLoaderBlinkLed

  rcall checkFlash                          ; (r16, r17, r18, r19, r20, r22, x, y, z)
  brcc bootLoader_startFirmware             ; no flash process, try to start installed firmware
  rcall flashProcess                        ; received a FLASH START msg, handle flashing
  brcc bootLoader_waitAndRestartBootLoader
  ; try to start firmware
bootLoader_startFirmware:
  ldi r19, 6  ; loop count
  ldi r20, 4  ; on time
  ldi r21, 1  ; off time
  rcall bootLoaderBlinkLed
  bigjmp firmwareStart

bootLoader_waitAndRestartBootLoader:
  ldi r19, 3  ; loop count
  ldi r20, 1  ; on time
  ldi r21, 8  ; off time
  rcall bootLoaderBlinkLed
  rjmp bootLoader



; @param r19 loop count
; @param r20 on time
; @param r21 off time
; @clobbers (R16, R18, R22, R24, R25)

bootLoaderBlinkLed:
    cbi LED_PORT, LED_PINNUM ; on
    mov r16, r20
    rcall flashWaitForMulti100ms  ; (R16, R18, R22, R24, R25)
    sbi LED_PORT, LED_PINNUM ; on
    mov r16, r21
    rcall flashWaitForMulti100ms  ; (R16, R18, R22, R24, R25)
    dec r19
  brne bootLoaderBlinkLed  
  ret


bootClcRet:
  clc
bootRet:
  ret

bootSecRet:
  sec
  ret






BOOTLOADER_END:
.equ MODULE_SIZE_BOOTLOADER = BOOTLOADER_END-BOOTLOADER_BEGIN


