/* ****************************************************************************
 * File:      beep.h
 * Date:      26 Dec 2024
 * Author:    Andrew Levido
 *
 * Copyright 2025 Imbrius Pty Ltd - All Rights Reserved
 *
 *****************************************************************************/
#ifndef _beep_H
#define _beep_H

#ifdef __cplusplus
extern "C" {
#endif

/* Description -----------------------------------------------------------------
 * Plays a single tone on the audio transducer.   
 */

/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Defines -------------------------------------------------------------------*/
extern TIM_HandleTypeDef htim15;

#define BEEP_TIMER      &htim15
#define BEEP_PWM_CHAN   TIM_CHANNEL_2

#define BEEP_BLIP        10         // Blip, 10ms
#define BEEP_SHORT       100        // Short beep, 100ms
#define BEEP_MEDIUM      300        // Medium beep, 300ms
#define BEEP_LONG        1000       // Long beep, 1s
#define BEEP_FOREVER     0xffff     // Beep forever

/* Typedefs & Enumerations ---------------------------------------------------*/
typedef enum { 
  C3  =  131, CS3 =  139, D3  =  147, DS3 =  156, E3  =  165, F3 =  175, 
  FS3 =  185, G3  =  196, GS3 =  208, A3  =  220, AS3 =  466, B3 =  247,
  C4  =  262, CS4 =  277, D4  =  294, DS4 =  311, E4  =  330, F4 =  349,
  FS4 =  370, G4  =  392, GS4 =  415, A4  =  440, AS4 =  466, B4 =  494,
  C5  =  523, CS5 =  554, D5  =  587, DS5 =  622, E5  =  659, F5 =  698, 
  FS5 =  740, G5  =  784, GS5 =  831, A5  =  880, AS5 =  932, B5 =  988,  
  C6  = 1047, CS6 = 1109, D6  = 1175, DS6 = 1245, E6  = 1319, F6 = 1397, 
  FS6 = 1480, G6  = 1568, GS6 = 1661, A6  = 1760
} note_t;

/* Public Functions Declarations ---------------------------------------------*/

/** Play one tone for a defined period of time
 * Plays a single tone for a defined period (or indefinitley if BEEP_FOREVER
 * is specified). Continues until terminated by beep_stop() or the
 * start of another note. Any currently playing note is terminated by 
 * calling this function.
 * 
 * @param note          Enumerated note frequency
 * @param time          Time in ms (0 to 65,534) or BEEP_FOREVER
 */
void beep(note_t note, uint16_t time);

/* Stop current beep 
 * Terminates the currently playng note or tune
 */
void beep_stop(void);

/* Interrupt Service Routine Declarations ------------------------------------*/
/**  Beeper 1 ms tick function
 * Must be called from the system tick interrupt handler every 1 millisecond
 * to manage beep timing
 */
void beep_1ms_tick(void);

#ifdef __cplusplus
}
#endif

#endif

/* End beep */