; ***************************************************************************
; 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 TWI Bus Member packet.
;
; IN:
; - R16: destination address
; - R1 : Address of the bus member
; - R2 : availability (0=not available, 1=available)
; OUT:
; - CFLAG: set if okay, clear otherwise
; MODIFIED REGS: R16, R17, R20, X (R15, Y)

CPRO_EnqueueTwiBusMember:
  push r16
    rcall COM_AllocBufferAndGetXY ; (r16, r17, r21)
  pop r16
  brcc CPRO_EnqueueTwiBusMember_error
  clr r17                         ; r17: XOR byte
  ; write header (dest address, msg length)
  st X+, r16                      ; destination address
  eor r17, r16
  ldi r16, 4                      ; 4 bytes payload
  st X+, r16
  eor r17, r16
  ; write payload
  ldi r16, CPRO_CMD_TWIBUSMEMBER   ; send command
  st X+, r16
  eor r17, r16
  lds r16, comAddress             ; send source address
  st X+, r16
  eor r17, r16
  mov r16, r1                     ; send i2c bus member address
  st X+, r16
  eor r17, r16
  mov r16, r2                     ; send i2c bus member availability
  st X+, r16
  eor r17, r16
  ; store XOR byte
  st X+, r17
  ; mark buffer as enqueued with PRIO "info" (limited amount of retries)
  ldi r20, COM_BUFFER_PRIO_INFO
  rcall COM_EnqueuePacket      ; (R15, R16)
  brcc CPRO_EnqueueTwiBusMember_error
  sec
  ret
CPRO_EnqueueTwiBusMember_error:
  clc
  ret


