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




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

.cseg


; ---------------------------------------------------------------------------
; Enqueue a DEVICE packet.
;
; IN:
; - R16: destination address
; OUT:
; - CFLAG: set if okay, clear otherwise
; MODIFIED REGS: R6, R16, R17, R18, R20 (R3, R4, R15, R19, R21, X)

CPRO_EnqueueDevice:
  mov r6, r16

  rcall COM_AllocBufferAndGetXY ; (r16, r17, r21)
  brcc CPRO_EnqueueDevice_error

  push xh
    push xl
      mov r16, r6
      ldi r17, CPRO_PAYLOAD_FLAGS_UID | (6<<CPRO_PAYLOAD_FLAGS_SHIFT_NUM)
      ldi r18, CPRO_CMD_DEVICE
      rcall cproBeginMsgWithVariablePayload  ; (R3, R4, R16, R17, R18, R19, R20, R21, X)
      ldi r17, LOW(FW_TYPE)
      st X+, r17                             ; 6: firmware type low
      ldi r17, HIGH(FW_TYPE)
      st X+, r17                             ; 7: firmware type high
      ldi r17, FW_MAIN_VERSION_LOW
      st X+, r17                             ; 8: version low
      ldi r17, FW_MAIN_VERSION_HIGH
      st X+, r17                             ; 9: version high
      ldi r17, LOW(MODULES_MASK)
      st X+, r17                             ; 10: modules mask low
      ldi r17, HIGH(MODULES_MASK)
      st X+, r17                             ; 11: modules mask low
    pop xl
  pop xh
  rcall comCalcAndAddChecksumByte            ; (R16, R17, R18, R19, X)

  ; mark buffer as enqueued with PRIO "normal" (slightly limited number of retries)
  ldi r20, COM_BUFFER_PRIO_NORMAL
  rcall COM_EnqueuePacket      ; (R15, R16)
  brcc CPRO_EnqueueDevice_error
  sec
  ret
CPRO_EnqueueDevice_error:
  clc
  ret



