Mbed Clock application using an NTP connection to get internet time and a terminal interface to send commands

Dependencies:   4DGL-uLCD-SE EthernetInterface NTPClient mbed-rtos mbed SDFileSystem wavfile

Clock.cpp

Committer:
dudanian
Date:
2014-12-08
Revision:
2:c939d0501184
Parent:
0:4e6ae21cbd31

File content as of revision 2:c939d0501184:

#include "Clock.h"


Clock::Clock() : timezone(UTC) {
    set_time(1388534400);
}

void Clock::setAlarmThread(Thread *aThread) {
    alarmThread = aThread;
}

/**
 * Sets the time and stores it in UTC time
 */
void Clock::setTime(int hour, int minute, int period) {
    time_t rawtime = time(NULL);
    struct tm *timeinfo = localtime(&rawtime);
    if (hour == 12)
        hour = 0;
    timeinfo->tm_hour = (((period == AM) ? hour : (hour + 12)) - timezone) % 24;
    timeinfo->tm_min = minute;
    timeinfo->tm_sec = 0;
    set_time(mktime(timeinfo));
}

/**
 * Sets the timezone. Since the time is stored in UTC, the system time 
 * is not modified
 */
void Clock::setTimezone(int timezone) {
    
    this->timezone = timezone;
}

/**
 * Uses an NTP Client to set the time to UTC
 */
int Clock::syncTime() {
    NTPClient ntp;
    return ntp.setTime("0.pool.ntp.org");
}

void Clock::setAlarm(int hour, int minute, int period) {
    time_t currentTime = getTime();
    struct tm *timeinfo = localtime(&currentTime);
    if (hour == 12)
        hour = 0;
    hour = ((period == AM) ? hour : (hour + 12)) % 24;
    if (hour <= timeinfo->tm_hour && minute <= timeinfo->tm_hour) {
        (timeinfo->tm_mday)++;
    }
    timeinfo->tm_hour = hour;
    timeinfo->tm_min = minute;
    timeinfo->tm_sec = 0;
    time_t alarmTime = mktime(timeinfo);
    alarmTicker.attach(this, &Clock::signalAlarm, difftime(alarmTime, currentTime));
    aSet = true;
}

bool Clock::alarmSet() {
    return aSet;
}

void Clock::setTimer(int hours, int minutes) {
    alarmTicker.attach(this, &Clock::signalAlarm, hours * 3600 + minutes * 60);
    aSet = true;
}

void Clock::deleteAlarm() {
    alarmTicker.detach();
    aSet = false;
}

/**
 * Gets the system time in UTC and converts it according to the given timezone
 */
time_t Clock::getTime() {
    time_t rawtime = time(NULL);
    struct tm *timeinfo = localtime(&rawtime);
    timeinfo->tm_hour = (timeinfo->tm_hour + timezone) % 24;
    return mktime(timeinfo);
}

int Clock::getTimezone() {
    return timezone;
}

void Clock::signalAlarm() {
    alarmThread->signal_set(0x1);
    alarmTicker.detach();
    aSet = false;
}