; ***************************************************************************
; 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 FLASH DATA packet.
;
; IN:
; - X  : buffer containing the message
; OUT:
; - CFLAG: set if message is for us, cleared otherwise
; REGS: R0, R1, R15, R16, R17, R18, R19, R20, R21, R24, R25, X, Z

flashHandleFlashData:
  adiw xh:xl, FLASH_MSG_OFFS_MSGLEN
  ld r18, X                           ; length (subtract 6
  cpi r18, 6                          ; cmd(1), src(1), addr(4)
  brcs flashHandleFlashData_badData
  subi r18, 6                         ; remaining length
  adiw xh:xl, FLASH_PACKET_DATA_OFFS_ADDR-FLASH_MSG_OFFS_MSGLEN
  ld zl, X+                           ; address (low)
  ld zh, X+                           ; address (high)
  adiw xh:xl, 2                       ; ignore high bytes, points to first data byte now

;  rcall Flash_StartPage               ; (R0, R1, R16, R20, R24, R25)
  push zl
    push zh
flashHandleFlashData_loop:
        ld r0, X+
        ld r1, X+
        rcall Flash_WriteIntoPage     ; (R15, R16, Z+)
        subi r18, 2
      brne flashHandleFlashData_loop
    pop zh
  pop zl
  rcall Flash_FinishPage              ; (R15, R16, R20)
  clr r16
  rjmp flashHandleFlashData_sendResponse
flashHandleFlashData_badData:
  ldi r16, FLASH_ERROR_MSGERROR
flashHandleFlashData_sendResponse:
  rcall flashSendFlashResponse        ; (R15, R16, R17, R18, R19, R20, R21, R22, X)
  sec
  ret



