; ***************************************************************************
; copyright   : (C) 2023 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



; ---------------------------------------------------------------------------
; Handle reboot request
;
; IN:
; - X  : buffer containing the received packet
; OUT:
; - nothing
; REGS: 

cproHandleReboot:
  adiw xh:xl, CPRO_PACKET_REBOOTREQ_OFFS_UID
  rcall cproCheckUidInMsg
  brcc cproHandleReboot_notHandled
  sbiw xh:xl, CPRO_PACKET_REBOOTREQ_OFFS_UID+4
  adiw xh:xl, COM2_MSG_OFFS_SRCADDR
  ld r16, x
  cpi r16, 0xff
  breq cproHandleReboot_notHandled    ; dont handle src address 255
cproHandleReboot_loop1:
  push r16
    ldi xl, LOW(com2SendBuffer)
    ldi xh, HIGH(com2SendBuffer)
    rcall CPRO_WriteRebootResponse
    rcall COM2_SendPacket
  pop r16
  brcc cproHandleReboot_loop1

  ; directly call bootloader
  cli
  rcall systemSetBootSpeed    ; reset speed if necessary (TODO: let bootloader set its speed)
  rjmp BOOTLOADER_ADDR
cproHandleReboot_notHandled:
  clc
  ret



; ---------------------------------------------------------------------------
; Write a Reboot Response packet.
;
; IN:
; - R16: destination address
; - X  : buffer to write to
; OUT:
; - nothing
; REGS: R3, R4, R16, R17, R18, X (R19, R20, R21)

CPRO_WriteRebootResponse:
  ldi r18, CPRO_CMD_REBOOT_RESPONSE
  rjmp COM2_WriteMsgWithCmdAndSrcAddr  ; R3, R4, R15, R16, R17, R18, R19, R20, R21, X



