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



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


.cseg



; ---------------------------------------------------------------------------
; @routine DevUid_Read

; Read UID from EEPROM.
;
; @return r21:r20:r19:r18 UID
; @clobbers R16, X

DevUid_ReadFromEeprom:
  ldi xl, LOW(EEPROM_OFFS_UUID)
  ldi xh, HIGH(EEPROM_OFFS_UUID)
  rcall Eeprom_ReadByte          ; r16=byte read (none)
  brcc DevUid_ReadFromEeprom_ret
  mov r18, r16
  adiw xh:xl, 1

  rcall Eeprom_ReadByte          ; r16=byte read (none)
  brcc DevUid_ReadFromEeprom_ret
  mov r19, r16
  adiw xh:xl, 1

  rcall Eeprom_ReadByte          ; r16=byte read (none)
  brcc DevUid_ReadFromEeprom_ret
  mov r20, r16
  adiw xh:xl, 1

  rcall Eeprom_ReadByte          ; r16=byte read (none)
  brcc DevUid_ReadFromEeprom_ret
  mov r21, r16

DevUid_ReadFromEeprom_ret:
  ret
; @end



; ---------------------------------------------------------------------------
; @routine DevUid_Setup @global
;
; Reads UID from EEPROM. If not set generate a new one and store it in EEPROM.
;
; @return CFLAG set if new generated, cleared if there already was one.
; @clobbers R16, R18, R19, R20, R21, X (R17)

DevUid_Setup:
    rcall DevUid_ReadFromEeprom        ; (R16, X)
    cp r18, r19                     ; all the same?
    brne DevUid_Setup_uidOkay     ; different, jmp
    cp r18, r20
    brne DevUid_Setup_uidOkay     ; different, jmp
    cp r18, r21
    brne DevUid_Setup_uidOkay     ; different, jmp

    ldi xl, LOW(EEPROM_OFFS_UUID)   ; all the same, generate new uid
    ldi xh, HIGH(EEPROM_OFFS_UUID)
    rcall RAND_PseudoRandom         ; byte 0 (R16, R17, R18, R19)
    inc r16
    rcall Eeprom_WriteByteIfChanged ; (r17)
    brcc DevUid_Setup_ret
    adiw xh:xl, 1

    rcall RAND_PseudoRandom         ; byte 1
    rcall Eeprom_WriteByteIfChanged ; (r17)
    brcc DevUid_Setup_ret
    adiw xh:xl, 1

    rcall RAND_PseudoRandom         ; byte 2
    rcall Eeprom_WriteByteIfChanged ; (r17)
    brcc DevUid_Setup_ret
    adiw xh:xl, 1

    rcall RAND_PseudoRandom         ; byte 3
    rcall Eeprom_WriteByteIfChanged ; (r17)
    brcc DevUid_Setup_ret
  
    rcall RAND_UpdateSeedInEeprom ; (R16, R17, R18, R19, X)
  
DevUid_Setup_uidOkay:
  sec
DevUid_Setup_ret:
  ret
; @end






#endif

