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

.include "common/divide8.asm"



; ---------------------------------------------------------------------------
; @routine netMsgTimeRead @global
; Write a packet (including the checksum byte).
;
; @return r22     source address
; @return r23     command
; @return r25:r24 message id
; @param  X       buffer to read from
; @param  Z       pointer to buffer for RTC DS3231 format of time

netMsgTimeRead:
  adiw xh:xl, NETMSG_OFFS_MSGDATA  ; skip DEST, LEN     0
  ld r23, X+     ; command            2
  ld r22, X+     ; src address        3
  adiw xh:xl, 4  ; skip uid
  ld r24, X+     ; msg id
  ld r25, X+

  ; X=payload
  adiw zh:zl, 7  ; point to one byte behind year

  ; read year (only last two digits)
  ld r16, X+
  ld r17, X+
  ldi r18, LOW(2000)
  ldi r19, HIGH(2000)
  sub r16, r18
  sbc r17, r19
  rcall toBcd
  st -Z, r16
  ; read month
  ld r16, X+
  rcall toBcd
  st -Z, r16
  ; read day of month
  ld r16, X+
  rcall toBcd
  st -Z, r16
  ; read day of week
  ld r16, X+
  rcall toBcd
  st -Z, r16
  ; read hours
  ld r16, X+
  rcall toBcd
  st -Z, r16
  ; read minutes
  ld r16, X+
  rcall toBcd
  st -Z, r16
  ; read seconds
  ld r16, X+
  rcall toBcd
  st -Z, r16

  sbiw xh:xl, NETMSG_TIME_SIZE                    ; go back to beginning of message
  sec
  ret
; @end



; ---------------------------------------------------------------------------
; @routine toBcd
;
; Write a packet (including the checksum byte).
;
; @param r16 bin value
; @return r16 BCD value
; @clobbers r17, r18

toBcd:
  mov r18, r16
  ldi r19, 10
  bigcall Utils_Divu8_8_8  ; r16=result, r17=remainder (R25)
  lsl r16
  lsl r16
  lsl r16
  lsl r16
  add r16, r17
  ret
; @end




#endif

