; ***************************************************************************
; 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 VALUE packet.
;
; IN:
; - R16: destination address
; - R17: value id
; - R19:R18: value
; - R21:R20: denom (e.g. 100, meaning value must be divided by 100)
; - R22: value type
; OUT:
; - CFLAG: set if okay, clear otherwise
; MODIFIED REGS: R6, R7, R8, R9, R10, R11, R12, R16, R17, X, Y (R3, R4, R15, R16, R17, R18, R19, R20, R21)

CPRO_EnqueueValue:
  mov r6, r16
  mov r7, r17
  mov r8, r18
  mov r9, r19
  mov r10, r20
  mov r11, r21
  mov r12, r22

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

  push xh
    push xl
      mov r16, r6
      ldi r17, CPRO_PAYLOAD_FLAGS_UID | (6<<CPRO_PAYLOAD_FLAGS_SHIFT_NUM)
      ldi r18, CPRO_CMD_VALUE
      rcall cproBeginMsgWithVariablePayload  ; (R3, R4, R16, R17, R18, R19, R20, R21, X)
      st X+, r7                              ; 6: value id
      st X+, r12                             ; 7: value type
      st X+, r8                              ; 8: low value
      st X+, r9                              ; 9: high value
      st X+, r10                             ; 10: low denom
      st X+, r11                             ; 11: high denom
    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_EnqueueValue_error
  sec
  ret
CPRO_EnqueueValue_error:
  clc
  ret



