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




; ---------------------------------------------------------------------------
; add checksum byte to buffer
;
; IN:
; - X  : pointer to packet buffer
; OUT:
; - CFLAG: set if okay, clear otherwise
; MODIFIED REGS: R16, R17, R18, R19, X

com2CalcAndAddChecksumByte:
  adiw xh:xl, COM2_MSG_OFFS_MSGLEN
  ld r18, X                           ; read msg len
  sbiw xh:xl, COM2_MSG_OFFS_MSGLEN
  inc r18                             ; account for dest address
  inc r18                             ; account for msg len byte
  rcall crc8Calc                      ; (R16, R17, R18, R20, X)
  st X, r16                           ; add checksum byte
  sec
  ret



; ---------------------------------------------------------------------------
; check message in buffer
;
; IN:
; - X  : pointer to packet buffer
; OUT:
; - CFLAG: set if okay, clear otherwise
; MODIFIED REGS: R16, R17, R18, R19, R20, X

com2CheckMessageInBuffer:
  adiw xh:xl, COM2_MSG_OFFS_MSGLEN
  ld r18, X                           ; read msg len
  sbiw xh:xl, COM2_MSG_OFFS_MSGLEN
  inc r18                             ; account for dest address
  inc r18                             ; account for msg len byte
  rcall crc8Calc                      ; (R16, R17, R18, R20, X)
  ld r17, X
  cp r16, r17                         ; should be equal
  brne com2CheckMessageInBuffer_error
  sec
  ret
com2CheckMessageInBuffer_error:
  clc
  ret


