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


; Counts seconds, minutes and hours
;
; calls onEverySecond, onEveryMinute, onEveryHour and onEveryDay
;



; ***************************************************************************
; defs





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

.dseg

clockModuleData:
clockModuleTickCounter:      .byte 1
clockModuleCounterSecs:      .byte 1
clockModuleCounterMins:      .byte 1
clockModuleCounterHours:     .byte 1
clockModuleData_end:




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

.cseg

CLOCK_BEGIN:



; ---------------------------------------------------------------------------
; @routine Clock_Init
;
; @clobbers r16, r17, x

Clock_Init:
  ; reset data in SDRAM
  ldi xh, HIGH(clockModuleData)
  ldi xl, LOW(clockModuleData)
  clr r16
  ldi r17, (clockModuleData_end-clockModuleData)
  bigcall Utils_FillSram                ; (R17, X)
  sec
  ret
; @end



; ---------------------------------------------------------------------------
; @routine Clock_Fini
;

Clock_Fini:
  ret
; @end



; ---------------------------------------------------------------------------
; @routine Clock_Every100ms
;

Clock_Every100ms:
  lds r16, clockModuleTickCounter
  inc r16
  cpi r16, 10
  brcc Clock_Every100ms_inc1s
  sts clockModuleTickCounter, r16
  ret
Clock_Every100ms_inc1s:
  clr r16
  sts clockModuleTickCounter, r16
  rcall sysOnEverySecond
  lds r16, clockModuleCounterSecs
  inc r16
  cpi r16, 60
  brcc Clock_Every100ms_inc1m
  sts clockModuleCounterSecs, r16
  ret
Clock_Every100ms_inc1m:
  clr r16
  sts clockModuleCounterSecs, r16
  rcall sysOnEveryMinute
  lds r16, clockModuleCounterMins
  inc r16
  cpi r16, 60
  brcc Clock_Every100ms_inc1h
  sts clockModuleCounterMins, r16
  ret
Clock_Every100ms_inc1h:
  clr r16
  sts clockModuleCounterMins, r16
  rcall sysOnEveryHour
  lds r16, clockModuleCounterHours
  inc r16
  cpi r16, 24
  brcc Clock_Every100ms_1d
  sts clockModuleCounterHours, r16
  ret
Clock_Every100ms_1d:
  clr r16
  sts clockModuleCounterHours, r16
  rcall sysOnEveryDay
  ret
; @end





CLOCK_END:
.equ MODULE_SIZE_CLOCK = CLOCK_END-CLOCK_BEGIN


