This is a library for managing the mbed real time clock, including functions for setting and getting the rtc in text format, getting and setting the timezone offset, and getting and setting the calibration register, both directly, and by using an adjustment API to automatically set the calibration value.

Dependents:   mbed_escm2000

TimeUtilities.cpp

Committer:
WiredHome
Date:
2011-05-29
Revision:
0:108436d3cea9
Child:
1:6d3d16f4b27c

File content as of revision 0:108436d3cea9:

/// @file TimeUtilities.cpp contains a real time clock interface for the mbed
///
/// APIs for showing the time from the RTC, or from a passed in value.
/// Also supports setting the clock, timezone offsets and calibration
/// of the RTC subsystem.
///
/// @note Copyright © 2011 by Smartware Computing, all rights reserved.
/// @author David Smart
///
#ifndef WIN32
// embedded build
#include "mbed.h"
#endif

#include "TimeUtilities.h"
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#ifdef WIN32
// Fake it out for Win32
struct LPC {
	unsigned long GPREG0;
	unsigned long CALIBRATION;
};
struct LPC X;
struct LPC * LPC_RTC = &X;
#define set_time(x) (void)x
#endif

static int tzOffsetHr = 0;       ///!< time zone offset hours to print time in local time
static int tzOffsetMin = 0;      ///!< time zone offset minutes to print time in local time

static int SignOf(const int i) {
    return (i >= 0) ? 1 : -1;
}

RealTimeClock::RealTimeClock() {
	GetTimeOffsetStore();
}

RealTimeClock::~RealTimeClock() {
}

void RealTimeClock::GetTimeString(char *buf, time_t tValue) {
    GetTimeOffsetStore();       // Load the time zone offset values from the battery ram
    GetTimeString(buf, tValue, tzOffsetHr, tzOffsetMin);
}

void RealTimeClock::GetTimeString(char *buf, int hOffset, int mOffset) {
    GetTimeString(buf, 0, hOffset, mOffset);
}

void RealTimeClock::GetTimeString(char *buf, time_t tValue, int hOffset, int mOffset) {
    time_t ctTime;

    if (tValue == 0)
        tValue = time(NULL);
    ctTime = tValue + hOffset * 3600 + SignOf(hOffset) * mOffset * 60;
    strcpy(buf, ctime(&ctTime));
    buf[strlen(buf)-1] = '\0';   // remove the \n
    sprintf(buf + strlen(buf), " (tzo: %2i:%02i)", hOffset, mOffset);
}

int32_t RealTimeClock::GetTimeCalibration() {
    int32_t calvalue = LPC_RTC->CALIBRATION & 0x3FFFF;

    if (calvalue & 0x20000) {
        calvalue = -(calvalue & 0x1FFFF);
    }    
    return calvalue;
}

void RealTimeClock::SetTimeCalibration(int32_t calibration) {
    if (calibration < 0) {
        calibration = (-calibration & 0x1FFFF) | 0x20000;
    }
    LPC_RTC->CALIBRATION = calibration;
}

void RealTimeClock::SetTimeOffset(int offsetHour, int offsetMinute) {
    tzOffsetHr = offsetHour;
    tzOffsetMin = offsetMinute;
    SetTimeOffsetStore();
}

void RealTimeClock::SetTimeOffsetStore() {
    LPC_RTC->GPREG0 = tzOffsetHr * 256 + tzOffsetMin;
}

void RealTimeClock::GetTimeOffsetStore() {
    tzOffsetHr = (int32_t)LPC_RTC->GPREG0 / 256;
    tzOffsetMin = (LPC_RTC->GPREG0 & 0xFF);
}

// MM/DD/YYYY HH:MM:SS [(+/-hh:mm)]
bool RealTimeClock::SetTime(char * timestring) {
    bool success = false;
    char * p;
    time_t seconds = time(NULL);
    struct tm *t = localtime(&seconds);
    int _oH, _oM;
    
    p = strtok(timestring," /");
    if (p != NULL) {
        t->tm_mon = atoi(p) - 1;
        p = strtok(NULL, " /");
        if (p != NULL) {
            t->tm_mday = atoi(p);
            p = strtok(NULL, " /");
            if (p != NULL) {
                t->tm_year = atoi(p) - 1900;
                p = strtok(NULL, " :");
                if (p != NULL) {
                    t->tm_hour = atoi(p);
                    p = strtok(NULL, " :");
                    if (p != NULL) {
						t->tm_min = atoi(p);
						p = strtok(NULL, " (:");
						if (p != NULL) {
							t->tm_sec = atoi(p);
							success = true;         // if we get to here, we're good
							p = strtok(NULL, " (:");
							if (p != NULL) {
								success = false;    // but can't accept a partial tzo
								_oH = atoi(p);
								p = strtok(NULL, " (:)");
								if (p != NULL) {
									_oM = atoi(p);
									success = true; // but a whole tzo is ok
									SetTimeOffset(_oH, _oM);
								}   
							}
							seconds = mktime(t);
							seconds = seconds - (time_t)(tzOffsetHr * 3600 + tzOffsetMin * 60);
							set_time(seconds);
						}
					}
                }
            }
        }
    }
    return success;
}

#if 0
// GetNumber will get from the user a number using the
/// specified number of digits.
///
/// They can enter a number from 0 to 10^(digits-1)
///
/// @param digits is the number of digits to enter
/// @param pValue is a pointer to where to store the result
/// @returns true if a number was entered
/// @returns false if they entered a non-digit
///
int GetNumber(int digits, int * pValue) {
    int tempValue = 0;
    int i;

    while (digits--) {
        while (!pc.readable())
            wdt.Service();
        i = pc.getc();
        if (i == ' ') i = '0';      // special case for leading blank
        if (i >= '0' && i <= '9') {
            pc.putc(i);
            tempValue = tempValue * 10 + (i - '0');
        } else
            return false;
    }
    *pValue = tempValue;
    return true;
}

/// RTC_Set will interactively set the Real Time Clock
///
/// It will allow you to enter the date and time information
/// and then create a timestamp. After this, it will set
/// the RTC to that timestamp.
///
void RTC_Set(void) {
    time_t seconds = time(NULL);
    struct tm *t = localtime(&seconds);

    pc.printf("RTC Set:\r\n");
    GetTimeString(seconds, tzOffsetHr, tzOffsetMin);
    pc.printf("    Enter the time MM/DD/YYYY HH:MM:SS\r\n");
    while (1) {
        int _m, _d, _y, _H, _M, _S;
        printf("                 > ");
        if (GetNumber(2, &_m)) {
            pc.putc('/');
            if (!GetNumber(2, &_d))
                continue;
            pc.putc('/');
            if (!GetNumber(4, &_y))
                continue;
            t->tm_mon = _m - 1;
            t->tm_mday = _d;
            t->tm_year = _y - 1900;
        } else {
            pc.printf("%02d/%02d/%04d", t->tm_mon+1, t->tm_mday, t->tm_year+1900);
        }
        pc.putc(' ');
        if (GetNumber(2, &_H)) {
            pc.putc(':');
            if (!GetNumber(2, &_M))
                continue;
            pc.putc(':');
            if (!GetNumber(2, &_S))
                continue;
            t->tm_hour = _H;
            t->tm_min = _M;
            t->tm_sec = _S;
            pc.printf("\r\n");
            pc.printf("%02d/%02d/%04d ", t->tm_mon+1, t->tm_mday, t->tm_year+1900);
            pc.printf("%02d:%02d:%02d\r\n", t->tm_hour, t->tm_min, t->tm_sec);
            // convert to timestamp and display (1256729737)
            time_t seconds = mktime(t);
            seconds = seconds - (time_t)(tzOffsetHr * 3600 + tzOffsetMin * 60);
            set_time(seconds);
            break;
        } else {
            pc.printf("%02d:%02d:%02d\r\n", t->tm_hour, t->tm_min, t->tm_sec);
            break;          // they can bail here
        }
    }
}
#endif