Skip to content

Add script to auto-set local time on reboot/daily with timedatectl #6

@jezdez

Description

@jezdez

Hey, so maybe I'm doing this wrong, but I wondered how to use the RV3028 to have my Raspi auto-set the time on boot using the RTC and also handle the case in which it doesn't have network connection to an optionally configured NTP server.

Here's the script I use for this (via /etc/crontab), does that make any sense?

#!/usr/bin/env python3
"""
A script to run on reboot to automatically set the system time to
the RTC time. Will disable Automatic time synchronization while running
(if enabled) and re-enable it again. This is to ensure that setting from RTC
works without network connection.

Add to the system crontab:

$ sudo nano /etc/crontab

And then add:

@daily root python3 /path/to/timedatectl-set-time-from-rtc.py

(c) Jannis Leidel 2019
"""
import time
from subprocess import run

import rv3028

TIMEDATECTL = "/usr/bin/timedatectl"

# Create RV3028 instance
rtc = rv3028.RV3028()

# Switches RTC to backup battery if VCC goes below 2V
# Other settings: 'switchover_disabled', 'direct_switching_mode', 'standby_mode'
rtc.set_battery_switchover('level_switching_mode')

rtc_time = rtc.get_time_and_date()
iso_rtc_time = rtc_time.isoformat(" ")
print("The RTC time is: {}".format(iso_rtc_time))

# Disabling NTP now so we can set the time manually
# in case network connection isn't there right now
timedatectl_output = run([TIMEDATECTL], capture_output=True)
ntp_enabled = b"NTP service: active" in timedatectl_output.stdout
if ntp_enabled:
    run([TIMEDATECTL, "set-ntp", "false"])

time.sleep(1)

try:
    # run timedatectl set-time with the time returned from the RTC
    # The time may be specified in the format "2012-10-30 18:17:16".
    run([TIMEDATECTL, "set-time", iso_rtc_time])
finally:
    print("Successfully set local time using the RV3028.")
    # definitely re-enable NTP in case something goes wrong with setting
    # the time.
    if ntp_enabled:
        run([TIMEDATECTL, "set-ntp", "true"])

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions