; ***************************************************************************
; 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_MODULES_NETWORK_MSG_MEMSTATS_W_ASM
#define AQH_AVR_MODULES_NETWORK_MSG_MEMSTATS_W_ASM



; ---------------------------------------------------------------------------
; @routine NETMSG_MemStats_Write @global
;
; @param Y pointer to device to write msg for
; @param X pointer to buffer to write to
; @clobbers R16, R17, R18, R19, R20, R21

NETMSG_MemStats_Write:
  ldi r16, 0xff
  st X+, r16                          ; dest address
  ldi r16, (NETMSG_MEMSTATS_SIZE-2)
  st X+, r16                          ; msg len
  ldi r16, NETMSG_CMD_MEMSTATS
  st X+, r16                          ; msg code
  ldd r16, Y+NET_IFACE_OFFS_ADDRESS
  st X+, r16                          ; src address

  ; uid
  bigcall NETMSG_Common_AddUidToBuffer  ; (R16, R18, R19, R20, R21)
  ; timestamp
#ifdef MODULES_CLOCK
  lds r16, clockModuleCounterHours
  st X+, r16
  lds r16, clockModuleCounterMins
  st X+, r16
  lds r16, clockModuleCounterSecs
  st X+, r16
  lds r16, clockModuleTickCounter
  st X+, r16
#else
  clr r16
  st X+, r16
  st X+, r16
  st X+, r16
  st X+, r16
#endif
  ; stack used
  ldi r20, LOW(RAMEND)
  ldi r21, HIGH(RAMEND)
  in r17, SPL
  sub r20, r17
  st X+, r20
  in r17, SPH
  sbc r21, r17
  st X+, r21
  ; current buffers used
  lds r16, netBuffersUsed
  st X+, r16
  ; max buffers used
  lds r16, netBuffersMaxUsed
  st X+, r16
  ; no buffer errors
  ldd r16, Y+NET_IFACE_OFFS_ERR_NOBUF_LOW
  st X+, r16
  ldd r16, Y+NET_IFACE_OFFS_ERR_NOBUF_HIGH
  st X+, r16

; heap
#ifdef MODULES_HEAP
    ; heap used
    lds r20, heapUsed
    lds r21, heapUsed+1
    st X+, r20
    st X+, r21
    ; heap free
    lds r20, heapFree
    lds r21, heapFree+1
    st X+, r20
    st X+, r21
#else
  clr r16
  st X+, r16
  st X+, r16
  st X+, r16
  st X+, r16
#endif

; XRAM
#ifdef MODULES_XRAM
  lds r20, xramLastAddress
  lds r21, xramLastAddress+1
  st X+, r20
  st X+, r21
#else
  clr r16
  st X+, r16
  st X+, r16
#endif

  sbiw xh:xl, NETMSG_MEMSTATS_SIZE      ; go back to beginning of message
  bigcall NETMSG_CalcAndAddChecksumByte ; (R16, R17, R18, R19, R20, X)
  sbiw xh:xl, (NETMSG_MEMSTATS_SIZE+1)  ; go back to beginning of message
  ret
; @end



#endif


