; ***************************************************************************
; 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 (points behind checksum upon return)
; OUT:
; - CFLAG: set if okay, clear otherwise
; - X  : points behind checksum byte pos upon return
; MODIFIED REGS: R16, R17, R18, R19, X

com2CalcAndAddChecksumByte:
  rcall com2CalcMsgChecksum
  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:
  rcall com2CalcMsgChecksum           ; (R16, R17, R18, R19, R20, X)
  ld r17, X
  cp r16, r17                         ; should be equal
  brne com2CheckMessageInBuffer_error
  sec
  ret
com2CheckMessageInBuffer_error:
  clc
  ret



; ---------------------------------------------------------------------------
; @routine com2CalcMsgChecksum
;
; calc checksum from msg buffer (except crc byte)
;
; @return r16 crc8 checksum
; @return X   points to position of checksum byte
; @param X  pointer to packet buffer (points to checksum byte upon return)
; @clobbers R16, R18 (R17, R19, R20, X)

com2CalcMsgChecksum:
  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
  rjmp com2CrcCalc                       ; (R16, R17, R18, R20, X)
; @end



; ---------------------------------------------------------------------------
; @routine com2CrcCalc @global
; calc checksum using given polynomial
;
; @return r16 calculated checksum
; @return X   points directly after last checked byte
; @param X    pointer to data to calc crc8 for
; @param r18  number of bytes to calc crc8 for
; @clobbers: R16, R17, R18, R19, R20, X

com2CrcCalc:
  ldi r16, 0xff                 ; start crc
  ldi r19, COM2_CRC8_POLYNOMIAL ; polynomial
  
com2CrcCalc_loop1:
    ld r17, X+                  ; running var
    eor r16, r17
    ldi r20, 8                  ; counter for loop2
com2CrcCalc_loop2:
      lsl r16
      brcc com2CrcCalc_l1
      eor r16, r19
com2CrcCalc_l1:
      dec r20
    brne com2CrcCalc_loop2
    dec r18
  brne com2CrcCalc_loop1
  ret
; @end




