/* LUFA Library Copyright (C) Dean Camera, 2011. dean [at] fourwalledcubicle [dot] com www.lufa-lib.org */ /* Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /** \file * * Main source file for the TemperatureDataLogger project. This file contains the main tasks of * the project and is responsible for the initial application hardware configuration. */ #include "TempDataLogger.h" /** LUFA Mass Storage Class driver interface configuration and state information. This structure is * passed to all Mass Storage Class driver functions, so that multiple instances of the same class * within a device can be differentiated from one another. */ USB_ClassInfo_MS_Device_t Disk_MS_Interface = { .Config = { .InterfaceNumber = 0, .DataINEndpointNumber = MASS_STORAGE_IN_EPNUM, .DataINEndpointSize = MASS_STORAGE_IO_EPSIZE, .DataINEndpointDoubleBank = false, .DataOUTEndpointNumber = MASS_STORAGE_OUT_EPNUM, .DataOUTEndpointSize = MASS_STORAGE_IO_EPSIZE, .DataOUTEndpointDoubleBank = false, .TotalLUNs = 1, }, }; /** Buffer to hold the previously generated HID report, for comparison purposes inside the HID class driver. */ static uint8_t PrevHIDReportBuffer[GENERIC_REPORT_SIZE]; /** LUFA HID Class driver interface configuration and state information. This structure is * passed to all HID Class driver functions, so that multiple instances of the same class * within a device can be differentiated from one another. */ USB_ClassInfo_HID_Device_t Generic_HID_Interface = { .Config = { .InterfaceNumber = 1, .ReportINEndpointNumber = GENERIC_IN_EPNUM, .ReportINEndpointSize = GENERIC_EPSIZE, .ReportINEndpointDoubleBank = false, .PrevReportINBuffer = PrevHIDReportBuffer, .PrevReportINBufferSize = sizeof(PrevHIDReportBuffer), }, }; /** Non-volatile Logging Interval value in EEPROM, stored as a number of 500ms ticks */ static uint8_t EEMEM LoggingInterval500MS_EEPROM = DEFAULT_LOG_INTERVAL; /** SRAM Logging Interval value fetched from EEPROM, stored as a number of 500ms ticks */ static uint8_t LoggingInterval500MS_SRAM; /** Total number of 500ms logging ticks elapsed since the last log value was recorded */ static uint16_t CurrentLoggingTicks; /** FAT Fs structure to hold the internal state of the FAT driver for the Dataflash contents. */ static FATFS DiskFATState; /** FAT Fs structure to hold a FAT file handle for the log data write destination. */ static FIL TempLogFile; /** ISR to handle the 500ms ticks for sampling and data logging */ ISR(TIMER1_COMPA_vect, ISR_BLOCK) { uint8_t LEDMask = LEDs_GetLEDs(); /* Check to see if the logging interval has expired */ if (CurrentLoggingTicks++ < LoggingInterval500MS_SRAM) return; /* Reset log tick counter to prepare for next logging interval */ CurrentLoggingTicks = 0; LEDs_SetAllLEDs(LEDMASK_USB_BUSY); /* Only log when not connected to a USB host */ if (USB_DeviceState == DEVICE_STATE_Unattached) { TimeDate_t CurrentTimeDate; DS1307_GetTimeDate(&CurrentTimeDate); char LineBuffer[100]; uint16_t BytesWritten; BytesWritten = sprintf(LineBuffer, "%02d/%02d/20%02d, %02d:%02d:%02d, %d Degrees\r\n", CurrentTimeDate.Day, CurrentTimeDate.Month, CurrentTimeDate.Year, CurrentTimeDate.Hour, CurrentTimeDate.Minute, CurrentTimeDate.Second, Temperature_GetTemperature()); f_write(&TempLogFile, LineBuffer, BytesWritten, &BytesWritten); f_sync(&TempLogFile); } LEDs_SetAllLEDs(LEDMask); } /** Main program entry point. This routine contains the overall program flow, including initial * setup of all components and the main program loop. */ int main(void) { SetupHardware(); /* Fetch logging interval from EEPROM */ LoggingInterval500MS_SRAM = eeprom_read_byte(&LoggingInterval500MS_EEPROM); /* Check if the logging interval is invalid (0xFF) indicating that the EEPROM is blank */ if (LoggingInterval500MS_SRAM == 0xFF) LoggingInterval500MS_SRAM = DEFAULT_LOG_INTERVAL; /* Mount and open the log file on the Dataflash FAT partition */ OpenLogFile(); LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY); sei(); for (;;) { MS_Device_USBTask(&Disk_MS_Interface); HID_Device_USBTask(&Generic_HID_Interface); USB_USBTask(); } } /** Opens the log file on the Dataflash's FAT formatted partition according to the current date */ void OpenLogFile(void) { char LogFileName[12]; /* Get the current date for the filename as "DDMMYY.csv" */ TimeDate_t CurrentTimeDate; DS1307_GetTimeDate(&CurrentTimeDate); sprintf(LogFileName, "%02d%02d%02d.csv", CurrentTimeDate.Day, CurrentTimeDate.Month, CurrentTimeDate.Year); /* Mount the storage device, open the file */ f_mount(0, &DiskFATState); f_open(&TempLogFile, LogFileName, FA_OPEN_ALWAYS | FA_WRITE); f_lseek(&TempLogFile, TempLogFile.fsize); } /** Closes the open data log file on the Dataflash's FAT formatted partition */ void CloseLogFile(void) { /* Sync any data waiting to be written, unmount the storage device */ f_sync(&TempLogFile); f_close(&TempLogFile); } /** Configures the board hardware and chip peripherals for the demo's functionality. */ void SetupHardware(void) { /* Disable watchdog if enabled by bootloader/fuses */ MCUSR &= ~(1 << WDRF); wdt_disable(); /* Disable clock division */ clock_prescale_set(clock_div_1); /* Hardware Initialization */ LEDs_Init(); SPI_Init(SPI_SPEED_FCPU_DIV_2 | SPI_SCK_LEAD_FALLING | SPI_SAMPLE_TRAILING | SPI_MODE_MASTER); ADC_Init(ADC_FREE_RUNNING | ADC_PRESCALE_128); Temperature_Init(); Dataflash_Init(); USB_Init(); TWI_Init(TWI_BIT_PRESCALE_4, (F_CPU / 4 / 50000) / 2); /* 500ms logging interval timer configuration */ OCR1A = (((F_CPU / 1024) / 2) - 1); TCCR1B = (1 << WGM12) | (1 << CS12) | (1 << CS10); TIMSK1 = (1 << OCIE1A); /* Clear Dataflash sector protections, if enabled */ DataflashManager_ResetDataflashProtections(); } /** Event handler for the library USB Connection event. */ void EVENT_USB_Device_Connect(void) { LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING); /* Close the log file so that the host has exclusive filesystem access */ CloseLogFile(); } /** Event handler for the library USB Disconnection event. */ void EVENT_USB_Device_Disconnect(void) { LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY); /* Mount and open the log file on the Dataflash FAT partition */ OpenLogFile(); } /** Event handler for the library USB Configuration Changed event. */ void EVENT_USB_Device_ConfigurationChanged(void) { bool ConfigSuccess = true; ConfigSuccess &= HID_Device_ConfigureEndpoints(&Generic_HID_Interface); ConfigSuccess &= MS_Device_ConfigureEndpoint
/*
 * MIT License
 *
 * Copyright (c) 2023 Christian Chapman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "calc.h"
#include "calc_fns.h"

#define CALC_NAN (0.0/0.0)

/* calc_init 
 * Initialize calculator
 */
int calc_init(calc_state_t *cs) {    
    memset(cs->stack, CALC_NAN, N_STACK*sizeof(cs->stack[0]));
    cs->s = 0; 
    cs->mem = 0.0;
    return 0;
}

/* calc_input_function
 * Try to execute the token as a calculator function
 */
int calc_input_function(calc_state_t *cs, char *token) {
    for(uint8_t idx=0; idx<sizeof(calc_dict)/sizeof(calc_dict[0]); idx++) {
        for(uint8_t idxn=0; idxn<calc_dict[idx].n_names; idxn++) {
            if(0 == strcmp(calc_dict[idx].names[idxn], token)) { // Found a match
                return (*calc_dict[idx].fn)(cs); // Run calculator function
            }
        }
    }
    return -1; // Unrecognized function name
}

/* calc_input_float
 * Read the token as a float.
 * For convenience, numerals can be written in binary:
 * 0     1    2    3    4    5    6    7    8    9
 * .     -    -.   --   -..  -.-  --.  ---  -... -..-
 * e     t    n    m    d    k    g    o    b    x
 * 
 * Exponent signs must be entered as "p".
 * Decimal place "." can be entered as "h" (code ....)
 * Sign "-" can be entered as "Ch digraph" (code ----)
 * 
 * e.g. "4.2e-3" can be entered directly or as "4h2pC3"
 * similarly, "0.0042" can be "eheedn"
 */ 
#define REPCHAR(X,Y) for(idx=0; idx<strlen(token); idx++) \
    if(X==token[idx]) token[idx] = Y
int calc_input_float(calc_state_t *cs, char *token) {
    uint8_t idx;
    REPCHAR('e', '0');
    REPCHAR('t', '1');
    REPCHAR('n', '2');
    REPCHAR('m', '3');
    REPCHAR('d', '4');
    REPCHAR('k', '5');
    REPCHAR('g', '6');
    REPCHAR('o', '7');
    REPCHAR('b', '8');
    REPCHAR('x', '9');
    REPCHAR('h', '.');
    REPCHAR('C', '-');
    REPCHAR('p', 'E');
    
    char *endptr;
    double d = calc_strtof(token, &endptr);
    if(!endptr || (uint8_t)(endptr-token)<strlen(token)) return -1; // Bad format
    if(cs->s >= N_STACK) return -2; // Stack full
    cs->stack[cs->s++] = d;
    return 0;
}

/* calc_input
 * Manipulate the stack using the entered token.
 * If the token isn't a calculator function, try to convert it to a number and
 * add it to the stack.
 *
 * Return values: 
 *  0 if function completed successfully.
 * -1 if token isn't a calculator function and couldn't convert to float.
 * -2 if stack is too full or too empty
 * -3 for something else
 */
int calc_input(calc_state_t *cs, char *token) {
    int retval = calc_input_function(cs, token);
    if(-1 == retval) retval = calc_input_float(cs, token);
    return retval;
}