|
| 1 | +package com.pi4j.drivers.sensor.geospatial.mcp7941x; |
| 2 | + |
| 3 | +import java.time.LocalDateTime; |
| 4 | + |
| 5 | +import com.pi4j.io.i2c.I2C; |
| 6 | + |
| 7 | +import org.slf4j.Logger; |
| 8 | +import org.slf4j.LoggerFactory; |
| 9 | + |
| 10 | +public class Mcp7941xDriver { |
| 11 | + private static Logger log = LoggerFactory.getLogger(Mcp7941xDriver.class); |
| 12 | + |
| 13 | + private static final int START_OSCILLATOR = 0x80; |
| 14 | + |
| 15 | + private static final int SECONDS = 0x00; |
| 16 | + private static final int MINUTES = 0x01; |
| 17 | + private static final int HOURS = 0x02; |
| 18 | + private static final int DAY_OF_WEEK = 0x03; |
| 19 | + private static final int DAY = 0x04; |
| 20 | + private static final int MONTH = 0x05; |
| 21 | + private static final int YEAR = 0x06; |
| 22 | + |
| 23 | + private final I2C i2c; |
| 24 | + |
| 25 | + public Mcp7941xDriver(I2C i2c) { |
| 26 | + |
| 27 | + this.i2c = i2c; |
| 28 | + } |
| 29 | + |
| 30 | + public LocalDateTime getDateTime() { |
| 31 | + |
| 32 | + int year = bcdToDec(i2c.readRegister(YEAR)) + 2000; |
| 33 | + int month = bcdToDec(i2c.readRegister(MONTH)); |
| 34 | + int day = bcdToDec(i2c.readRegister(DAY)); |
| 35 | + |
| 36 | + int hour = bcdToDec(i2c.readRegister(HOURS)); |
| 37 | + int minute = bcdToDec(i2c.readRegister(MINUTES)); |
| 38 | + int seconds = bcdToDec(i2c.readRegister(SECONDS) & 0x7F); |
| 39 | + |
| 40 | + return LocalDateTime.of(year, month, day, hour, minute, seconds); |
| 41 | + } |
| 42 | + |
| 43 | + public void setDateTime(LocalDateTime localDateTime) { |
| 44 | + |
| 45 | + log.trace("setting dateTime: " + localDateTime); |
| 46 | + |
| 47 | + i2c.writeRegister(SECONDS, (byte) decToBcd(localDateTime.getSecond()) | START_OSCILLATOR); |
| 48 | + i2c.writeRegister(MINUTES, (byte) decToBcd(localDateTime.getMinute())); |
| 49 | + i2c.writeRegister(HOURS, (byte) decToBcd(localDateTime.getHour())); |
| 50 | + |
| 51 | + i2c.writeRegister(DAY, (byte) decToBcd(localDateTime.getDayOfMonth())); |
| 52 | + i2c.writeRegister(MONTH, (byte) decToBcd(localDateTime.getMonthValue())); |
| 53 | + i2c.writeRegister(YEAR, (byte) decToBcd(localDateTime.getYear() - 2000)); |
| 54 | + } |
| 55 | + |
| 56 | + // limited to 2 digits ( 0..99 ) |
| 57 | + private static int bcdToDec(int bcd) { |
| 58 | + return ((bcd >> 4) * 10) + (bcd & 0x0F); |
| 59 | + } |
| 60 | + |
| 61 | + // limited to 2 digits ( 0..99 ) |
| 62 | + private static int decToBcd(int val) { |
| 63 | + |
| 64 | + if (val < 0) { |
| 65 | + throw new IllegalArgumentException(); |
| 66 | + } |
| 67 | + |
| 68 | + int result = ((val / 10) << 4) | (val % 10); |
| 69 | + log.trace("decToBcd in: {} out: {}", val, result); |
| 70 | + return result; |
| 71 | + } |
| 72 | +} |
0 commit comments