; ***************************************************************************
; 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.   *
; ***************************************************************************


; ***************************************************************************
; defines

.equ STATS_POS_MAX    = 5
.equ STATS_POS_DEVICE = 5
.equ STATS_POS_SEND   = 4
.equ STATS_POS_RECV   = 3
.equ STATS_POS_SYS    = 2
.equ STATS_POS_MEM    = 1


; ***************************************************************************
; data

.dseg


statsDataBegin:
  statsRemaining:    .byte 1
statsDataEnd:

statsSendTimer:      .byte 2 ; intentionally outside zeroed out are


; ***************************************************************************
; code

.cseg



Stats_Init:
  ; preset SRAM data area
  ldi xh, HIGH(statsDataBegin)
  ldi xl, LOW(statsDataBegin)
  clr r16
  ldi r17, (statsDataEnd-statsDataBegin)
  rcall Utils_FillSram
  sec
  ret



Stats_Run:
  in r15, SREG
  push r15
    cli
    
    lds r17, statsRemaining
    tst r17                       ; some left?
    breq Stats_Run_done           ; nope, jump to end

    ldi xl, LOW(com2SendBuffer)
    ldi xh, HIGH(com2SendBuffer)
    ldi r16, 0xff                 ; broadcast
    
    cpi r17, STATS_POS_RECV
    brne Stats_Run_l1
    rcall CPRO_WriteComRecvStats
    rjmp Stats_Run_SendPacket
Stats_Run_l1:
    cpi r17, STATS_POS_SYS
    brne Stats_Run_l2
    rcall CPRO_WriteSysStats
    rjmp Stats_Run_SendPacket
Stats_Run_l2:
    cpi r17, STATS_POS_MEM
    brne Stats_Run_l3
    rcall CPRO_WriteMemStats
    rjmp Stats_Run_SendPacket
Stats_Run_l3:
    cpi r17, STATS_POS_SEND
    brne Stats_Run_l4
    rcall CPRO_WriteComSendStats
    rjmp Stats_Run_SendPacket
Stats_Run_l4:
    cpi r17, STATS_POS_DEVICE
    brne Stats_Run_l5
    rcall CPRO_WriteDevice
    rjmp Stats_Run_SendPacket
Stats_Run_l5:
    ; add more stats here
    rjmp Stats_Run_done
Stats_Run_SendPacket:
    rcall COM2_SendPacket
    brcc Stats_Run_done         ; only decrement counter if message successfully sent
    lds r16, statsRemaining
    dec r16
    sts statsRemaining, r16
Stats_Run_done:
  pop r15
  out SREG, r15
  clc
  ret




Stats_Timer:
  ldi r16, STATS_POS_MAX ; RECV, SYS
  sts statsRemaining, r16
  ret


  
