Skip to content

Instantly share code, notes, and snippets.

@bryanjhv
Last active February 15, 2022 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanjhv/91a4d519ca4550bd51fbdc921e030fb5 to your computer and use it in GitHub Desktop.
Save bryanjhv/91a4d519ca4550bd51fbdc921e030fb5 to your computer and use it in GitHub Desktop.
if __name__ == "__main__":
from datetime import datetime, timedelta
from smbus import SMBus
from sys import argv
from time import sleep
argc = len(argv)
bus = SMBus(1 if argc < 2 else int(argv[1]))
rop = "r" if argc < 3 else argv[2].lower()[0:1]
bcd2bin = lambda n: n - 6 * (n >> 4)
if rop == "r":
print(bus.read_i2c_block_data(0x68, 0x00, 7))
if rop == "w":
now = datetime.utcnow()
print(now)
sleep(1 - now.microsecond / 1e6) # TODO: review!!!
now += timedelta(0, 1)
print(now)
bus.write_i2c_block_data(
0x68,
0x00,
[
n + 6 * (n // 10)
for n in (
now.second,
now.minute,
now.hour,
now.isoweekday(),
now.day,
now.month,
now.year - 2000,
)
],
)
#!/bin/sh
# shellcheck enable=all disable=SC2046,SC2086,SC2250
do_read() {
! res=$(i2cget -y $bus 0x68 0x00 i 7 2>/dev/null) && exit 2
set -- $(for v in $res; do printf '%d ' $((v - 6 * (v >> 4))); done)
fmt='%F %T %z'
date --date="$6/$5/20$7 $3:$2:$1 Z" +"$fmt" # TODO: don't assume 2k
date +"$fmt"
}
do_write() {
# TODO: wait until next second
res=$(date -u +'%-S %-M %-H %u %-d %-m %-y' 2>/dev/null) # TODO: avoid GNU
set -- $(for v in $res; do printf '0x%02x ' $((v + 6 * (v / 10))); done)
! i2cset -y $bus 0x68 0x00 $1 $2 $3 $4 $5 $6 $7 i 2>/dev/null && exit 3
}
do_sync() {
do_write
do_read
}
main() {
bus=${1:-1}
case ${2:-r} in
r*) do_read ;;
w*) do_write ;;
s*) do_sync ;;
*) exit 1 ;;
esac
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment