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






; ***************************************************************************
; data

.dseg


cproDataBegin:
  cproMode:                .byte 1
cproDataEnd:



; ***************************************************************************
; code

.cseg


CPRO_BEGIN:


CPRO_Init:
  ; preset SRAM data area
  ldi xh, HIGH(cproDataBegin)
  ldi xl, LOW(cproDataBegin)
  clr r16
  ldi r17, (cproDataEnd-cproDataBegin)
  rcall Utils_FillSram
  
#ifdef MODULES_COM_WITH_ADDR_PROTO
  rcall CPRO_Address_Init
#endif
  
  sec
  ret



; ---------------------------------------------------------------------------
; CPRO_OnPacketReceived:
;
; Try to handle the given packet.
;
; IN:
; - X  : pointer to received buffer
; OUT:
; - CFLAG: set if handled, cleared otherwise
; USED: depending on called routines

CPRO_OnPacketReceived:
  adiw xh:xl, COM2_MSG_OFFS_CMD
  ld r16, x
  sbiw xh:xl, COM2_MSG_OFFS_CMD
  cpi r16, CPRO_CMD_PING
  brne CPRO_OnPacketReceived_l1
  rjmp cproHandlePing

CPRO_OnPacketReceived_l1:
#ifndef BASE_SYSTEM
  cpi r16, CPRO_CMD_REBOOT_REQUEST
  brne CPRO_OnPacketReceived_l2
  rjmp cproHandleReboot
#endif

CPRO_OnPacketReceived_l2:
#ifdef MODULES_COM_WITH_ADDR_PROTO
  rjmp CPRO_Address_OnPacketReceived
#else
  clc
  ret
#endif



cproHandlePing:
  adiw xh:xl, COM2_MSG_OFFS_SRCADDR
  ld r16, x
  tst r16                             ; dont handle src address 0
  breq cproHandlePing_notHandled
  inc r16
  breq cproHandlePing_notHandled      ; dont handle src address 255
  dec r16
  ldi xl, LOW(com2SendBuffer)
  ldi xh, HIGH(com2SendBuffer)
  rcall CPRO_WritePong
  rjmp COM2_SendPacket                ; use carry flag from this routine
cproHandlePing_notHandled:
  clc
  ret


; ---------------------------------------------------------------------------
; Compare the UID from a message against out own UID.
;
;IN:
; - X: pointer to UID in a message to compare against out own uid
; OUT:
; - CFLAG set if matches, cleared otherwise
; REGS: r16, r18, r19, r20, r21, X

cproCheckUidInMsg:
  push xl
    push xh
      rcall Utils_ReadUid
    pop xh
  pop xl
  ld r16, X+
  cp r16, r18
  brne cproCheckUidInMsg_notMe
  ld r16, X+
  cp r16, r19
  brne cproCheckUidInMsg_notMe
  ld r16, X+
  cp r16, r20
  brne cproCheckUidInMsg_notMe
  ld r16, X+
  cp r16, r21
  brne cproCheckUidInMsg_notMe
  sec
  ret
cproCheckUidInMsg_notMe:
  clc
  ret


CPRO_END:
.equ MODULE_SIZE_CPRO = CPRO_END-CPRO_BEGIN



