; ***************************************************************************
; copyright   : (C) 2025 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 AQH_AVR_NETWORK_MSG_DEBUG_ASM
#define AQH_AVR_NETWORK_MSG_DEBUG_ASM



; ---------------------------------------------------------------------------
; @routine NETMSG_Debug_Write @global
;
; @param Y pointer to device to write msg for
; @param X pointer to buffer to write to
; @param r0-14 value 1-15
; @clobbers R16, R17, R18, R19, R20, R21

NETMSG_Debug_Write:
  ldi r16, 0xff
  st X+, r16                          ; dest address
  ldi r16, 17                         ; msg code+src address+15 payload bytes
  st X+, r16                          ; msg len
  ldi r16, NETMSG_CMD_DEBUG
  st X+, r16                          ; msg code
  ldd r16, Y+NET_IFACE_OFFS_ADDRESS
  st X+, r16                          ; src address

  st X+, r0                           ; 5th byte
  st X+, r1
  st X+, r2
  st X+, r3
  st X+, r4
  st X+, r5
  st X+, r6
  st X+, r7
  st X+, r8
  st X+, r9
  st X+, r10
  st X+, r11
  st X+, r12
  st X+, r13
  st X+, r14

  sbiw xh:xl, 19 ; go back to beginning of message (1 byte dst addr, 1 byte length, 17 bytes payload)
  rcall NETMSG_CalcAndAddChecksumByte ; (R16, R17, R18, R19, R20, X)
  sbiw xh:xl, 20 ; go back to beginning of message (1 byte dst addr, 1 byte length, 17 bytes payload, 1 byte crc)
  ret
; @end



; ---------------------------------------------------------------------------
; @routine NETMSG_Debug_Write2 @global
;
; @param Y pointer to device to write msg for
; @param X pointer to buffer to write to
; @param Z source pointer (in RAM)
; @clobbers R16, R17, R18, R19, R20, R21

NETMSG_Debug_Write2:
  push xl
    push xh
      ldi r16, 0xff
      st X+, r16                          ; dest address
      mov r16, r20
      ldi r17, 2
      add r16, r17                        ; msg code+src address+n payload bytes
      st X+, r16                          ; msg len
      ldi r16, NETMSG_CMD_DEBUG
      st X+, r16                          ; msg code
      ldd r16, Y+NET_IFACE_OFFS_ADDRESS
      st X+, r16                          ; src address
      mov r17, r20
NETMSG_Debug_Write2_loop:
        ld r16, Z+
        st X+, r16
        dec r17
      brne NETMSG_Debug_Write2_loop
    pop xh
  pop xl
  push xl
    push xh
      rcall NETMSG_CalcAndAddChecksumByte ; (R16, R17, R18, R19, R20, X)
    pop xh
  pop xl
  ret
; @end



#endif

