SBD-DL22 / Libraries / RTC_handler / RTC_handler.cpp
RTC_handler.cpp
Raw
/*
RTC_handler.cpp - Library for handling the RTC (Real-Time Clock) module
Created by JHU SBD-DL22, 10/07/2021
*/

// Include necessary libraries
#include "Energia.h" // Energia is an open-source electronics prototyping platform 
#include "RTC_handler.h" // The header file for this RTC_handler class
#include <Wire.h> // Allows for communication over I2C/TWI (Inter-Integrated Circuit/Two Wire Interface) bus
#include <config.h> // User-defined file, typically used to contain project configuration information

// Check if CONFIG_UNIXTIME is not defined, then define it
#ifndef CONFIG_UNIXTIME
#define CONFIG_UNIXTIME
#endif

// A struct "ts" is declared to hold the time and date information.
struct ts t;

// Constructor for the RTC_handler class, starts the Wire (I2C communication) library.
RTC_handler::RTC_handler()
{
	Wire.begin();
}

// Function to return the current Unix time (seconds since 01-01-1970)
int64_t RTC_handler::get_unix_time()
{
	DS3231_get(&t); // Fetches current time and stores it in the ts struct
	return t.unixtime; // Returns the unix time from the ts struct
}

// Function to get the current date and time as a string.
unsigned int RTC_handler::get_datetime(char* str, unsigned int str_size)
{
	DS3231_get(&t); // Fetches current time and stores it in the ts struct
	// Formats the fetched date and time as a string and returns the size of the formatted string
	return snprintf(str, str_size, "%02d/%02d/%04d-%02d:%02d:%02d", t.mon, t.mday, t.year, t.hour, t.min, t.sec);
}

// Function to get the current time and stores it in the provided ts struct.
void RTC_handler::get_time_s(struct ts* t)
{
	DS3231_get(t); // Fetches current time and stores it in the provided ts struct
}

// Function to get the current date and time as a string, taking a ts struct as a parameter.
unsigned int RTC_handler::get_datetime_s(char* str, unsigned int str_size, struct ts& t)
{
	// Formats the date and time from the provided ts struct as a string and returns the size of the formatted string
	return snprintf(str, str_size, "%02d/%02d/%04d-%02d:%02d:%02d", t.mon, t.mday, t.year, t.hour, t.min, t.sec);
}