; ***************************************************************************
; 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.   *
; ***************************************************************************

#ifndef AQH_AVR_NETWORK_MSG_COMMON_ASM
#define AQH_AVR_NETWORK_MSG_COMMON_ASM

;
; ---------------------------------------------------------------------------
; @routine NETMSG_Common_AddUidToBuffer @global
;
; @return X points directly behind the UID in buffer
; @param X current buffer position to write UID to
; @clobbers R16, R18, R19, R20, R21

NETMSG_Common_AddUidToBuffer:
  push xh
    push xl
      bigcall DevUid_ReadFromEeprom       ; (R16, X)
    pop xl
  pop xh
  st X+, r18
  st X+, r19
  st X+, r20
  st X+, r21
  ret
; @end



; ---------------------------------------------------------------------------
; @routine NETMSG_AddNextMsgIdToBuffer @global
;
; Write next message id (2 bytes) into buffer given by X, advance X.
;
; @return X   points to behind written message id
; @param  X   pointer to packet buffer
; @param  Y   pointer to network interface data
; @clobbers: r16, r17, r18

NETMSG_AddNextMsgIdToBuffer:
  ldi r18, 1
  ldd r16, Y+NET_IFACE_OFFS_LASTMSGID_LOW
  ldd r17, Y+NET_IFACE_OFFS_LASTMSGID_HIGH
  add r16, r18
  dec r18
  adc r17, r18
  std Y+NET_IFACE_OFFS_LASTMSGID_LOW, r16
  std Y+NET_IFACE_OFFS_LASTMSGID_HIGH, r17
  st X+, r16
  st X+, r17
  ret
; @end



; ---------------------------------------------------------------------------
; @routine NETMSG_CheckUidInMsg
;
; Compare the UID from a message against our own UID.
;
; @param  X     pointer to UID in a message to compare against out own uid
; @return CFLAG set if matches, cleared otherwise
; @clobbers r16, r18, r19, r20, r21, X

NETMSG_CheckUidInMsg:
  push xl
    push xh
      bigcall DevUid_ReadFromEeprom
    pop xh
  pop xl
  ld r16, X+
  cp r16, r18
  brne NETMSG_CheckUidInMsg_notMe
  ld r16, X+
  cp r16, r19
  brne NETMSG_CheckUidInMsg_notMe
  ld r16, X+
  cp r16, r20
  brne NETMSG_CheckUidInMsg_notMe
  ld r16, X+
  cp r16, r21
  brne NETMSG_CheckUidInMsg_notMe
  sec
  ret
NETMSG_CheckUidInMsg_notMe:
  clc
  ret
; @end



#endif

