58 lines
1.5 KiB
Python
58 lines
1.5 KiB
Python
'''
|
|
Script to read time from RTC module
|
|
I2C connection
|
|
Address 0x68
|
|
/usr/bin/python3 /var/www/nebuleair_pro_4g/RTC/read.py
|
|
'''
|
|
import smbus2
|
|
import time
|
|
import json
|
|
from datetime import datetime
|
|
|
|
|
|
# DS3231 I2C address
|
|
DS3231_ADDR = 0x68
|
|
|
|
# Registers for DS3231
|
|
REG_TIME = 0x00
|
|
|
|
def bcd_to_dec(bcd):
|
|
return (bcd // 16 * 10) + (bcd % 16)
|
|
|
|
def read_time(bus):
|
|
data = bus.read_i2c_block_data(DS3231_ADDR, REG_TIME, 7)
|
|
seconds = bcd_to_dec(data[0] & 0x7F)
|
|
minutes = bcd_to_dec(data[1])
|
|
hours = bcd_to_dec(data[2] & 0x3F)
|
|
day = bcd_to_dec(data[4])
|
|
month = bcd_to_dec(data[5])
|
|
year = bcd_to_dec(data[6]) + 2000
|
|
return (year, month, day, hours, minutes, seconds)
|
|
|
|
def main():
|
|
# Read RTC time
|
|
bus = smbus2.SMBus(1)
|
|
year, month, day, hours, minutes, seconds = read_time(bus)
|
|
rtc_time = datetime(year, month, day, hours, minutes, seconds)
|
|
|
|
# Get current system time
|
|
system_time = datetime.now() #local
|
|
utc_time = datetime.utcnow() #UTC
|
|
|
|
# Print both times
|
|
#print(f"RTC module Time: {rtc_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
#print(f"Sys local Time: {system_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
#print(f"Sys UTC Time: {utc_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
|
|
# Create JSON output
|
|
time_data = {
|
|
"rtc_module_time": rtc_time.strftime('%Y-%m-%d %H:%M:%S'),
|
|
"system_local_time": system_time.strftime('%Y-%m-%d %H:%M:%S'),
|
|
"system_utc_time": utc_time.strftime('%Y-%m-%d %H:%M:%S')
|
|
}
|
|
|
|
print(json.dumps(time_data, indent=4))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |