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

#ifndef AVR_MODULES_COM2W2_MSGREAD_H
#define AVR_MODULES_COM2W2_MSGREAD_H


.cseg


; ---------------------------------------------------------------------------
; @routine com2w2RecvMsg
;
; Receive a packet into buffer pointed to by X.
; Expects interrupts to be disabled.
;
; @param R19 max buffer size
; @param X   buffer to receive to
; @return CFLAG set if msg received, cleared on error (see R16)
; @return R16   if CFLAG cleared: 0=message not for this node, otherwise error
; @clobbers r16, r17, r18, r19, r20, r22, r24, r25, X

com2w2RecvMsg:
  ; check buffer size
  subi r19, 2
  brcs com2w2RecvMsg_eBadSize
  ; read destination address
  rcall com2w2RecvByte                    ; (r17, r18, r20, r22)
  brcc com2w2RecvMsg_eIo
  st X+, r16
  ; read remaining msg size
  rcall com2w2RecvByte                    ; (r17, r18, r20, r22)
  brcc com2w2RecvMsg_eIo
  st X+, r16
  inc r16                                 ; account for CRC byte
  sub r19, r16
  brcs com2w2RecvMsg_eBadSize
  mov r19, r16
com2w2RecvMsg_loop:
    rcall com2w2RecvByte                  ; (r17, r18, r20, r22)
    brcc com2w2RecvMsg_eIo
    st X+, r16
    dec r19
  brne com2w2RecvMsg_loop
  sec
  rjmp com2w2RecvMsg_end
com2w2RecvMsg_eBadSize:
  ldi r16, NET_IFACE_OFFS_ERR_MSGSIZE_LOW
  rjmp com2w2RecvMsg_incCounterRet
com2w2RecvMsg_eIo:
  ldi r16, NET_IFACE_OFFS_ERR_IO_LOW
com2w2RecvMsg_incCounterRet:
  rcall NET_Interface_IncCounter16         ; (R24, R25)
  rcall com2w2RecvByteWaitForQuietClk      ; (r18, r20, r22)
com2w2RecvMsg_clcRet:
  clc
com2w2RecvMsg_end:
  ret
; @end




#endif

