; ***************************************************************************
; copyright   : (C) 2026 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.   *
; ***************************************************************************

#ifndef AVR_MODULES_COM2W2_MSGWRITE_H
#define AVR_MODULES_COM2W2_MSGWRITE_H


.cseg



; ---------------------------------------------------------------------------
; @routine com2w2SendMsg
;
; @param X pointer to bytes to send
; @param Y pointer to interface data in SRAM
; @return CFLAG set if message sent, cleared otherwise
; @clobbers R16, R18 (R20, R22, R24, R25, X)

com2w2SendMsg:
  ldi r20, 6                           ; wait for about 60us for clock low
  rcall com2w2WaitForClockLowMulti10Us  ; (R16, R20, R22)
  brcs com2w2SendMsg_busy               ; CLK got low while waiting, so line is busy
  push r15
    in r15, SREG
    cli                                 ; atomic disable irq and set CLK low
    rcall com2w2DisableClkIrq            ; (none)
    rcall com2w2ClkSetLow                ; reserve bus (none)
    out SREG, r15
  pop r15
  adiw xh:xl, NETMSG_OFFS_MSGLEN
  ld r18, X
  sbiw xh:xl, NETMSG_OFFS_MSGLEN
  inc r18                               ; adjust for DESTADDR
  inc r18                               ; adjust for MSGLEN
  inc r18                               ; adjust for CRCBYTE
  rcall com2w2WaitTime1                  ; longer wait period (R22)
  rcall com2w2SendBytes                  ; (r16, r17, r18, r22, X)
  rcall com2w2ClkSetHigh                 ; make sure bus is released
  rcall com2w2DataSetHigh

  rcall com2w2EnableClkIrq               ; (none)
  ldi r16, NET_IFACE_OFFS_PACKETSOUT_LOW
  rcall NET_Interface_IncCounter16       ; (R24, R25)
  sec
  ret
com2w2SendMsg_busy:
  ldi r16, NET_IFACE_OFFS_ERR_BUSY_LOW
  rcall NET_Interface_IncCounter16       ; (R24, R25)
  clc
  ret
; @end




#endif


