/* Copyright 2025 by COG9 Enterprises LLC
 * All rights reserved.
 * Title: led.ino
 * Author: Jed Marti KI7NNP
 * Description: Blink big LED to indicate status.
 * Created: Sat Oct 11 09:25:19 2025
 * Revision History:
 */

#include <stdint.h>
#include "powerard.h"
#include "led.h"

// What the led is supposed to be doing.
static uint8_t  ledState;

// How long to be on in milliseconds.
static uint32_t onTime;

// How long to be off in milliseconds.
static uint32_t offTime;

// The time of the last change.
static uint32_t lastChange;


void ledInit(void)
/*     Set big beautiful red LED on D19 (i.e. PC3) to output, turn it off, set state.
 * Parameters: none
 * External References:
 *   BRED: constant (see led.h) is pin for big red led.
 *   ledState: What the led is supposed to be doing.
 *   ledOFF: i.e. off! (constant)
 * Returned values: none.
 * Errors detected: none
 */
{
  pinMode(BRED, OUTPUT);
  digitalWrite(BRED, LOW);
  ledState = ledOFF;
} 



void ledCheck(void)
/*    Check what the LED is doing and update appropriately.
 * Parameters: none
 * External References:
 *   BRED: constant (see led.h) is pin for big red led.
 *   ledState: What the led is supposed to be doing.
 *   led...: One of the 4 led states (constant)
 *   lastChange: The time in milliseconds of the last change.
 * Returned values: none
 * Errors detected: none
 */
{
  uint32_t ct;
  
  switch (ledState) {

  // Off or on, just ignore, already set correctly by ledBlink.
  case ledOFF:
  case ledON:
    break;

  // LED is on, if time, turn it off, change state.
  case ledBlinkON:
    ct = millis();
    if ((ct - lastChange) >= onTime)
    {
      lastChange = ct;
      digitalWrite(BRED, LOW);
      ledState = ledBlinkOFF;
    }
    break;

  // LED is off, if time, turn it on, change state.
  case ledBlinkOFF:
    ct = millis();
    if ((ct - lastChange) >= offTime)
    {
      lastChange = ct;
      digitalWrite(BRED, HIGH);
      ledState = ledBlinkON;
    }
    break;
  }
}



void ledBlink(uint16_t ont, uint16_t offt)
/*     Set the led to blink or on or off.
 * Parameters:
 *   ont: How long to be on. 0 means off, 0xFFFF means on, others blink on for that many
 *     milliseconds.
 *   offt: How many milliseconds to be off.
 * External References:
 *   ledState: What the led is supposed to be doing.
 *   led...: One of the 4 led states.
 * Returned values: none
 * Errors detected: none
 */
{
  // on time is 0? Turn it off and set state.
  if (ont == 0)
  {
    digitalWrite(BRED, LOW);
    ledState = ledOFF;
    return;
  }

  // Max time on (65 or so seconds) then turn on and set state.
  else if (ont == 0xFFFF)
  {
    digitalWrite(BRED, HIGH);
    ledState = ledON;
    return;
  }

  // Set timnes, turn LED on.
  onTime = (uint32_t) ont,
    offTime = (uint32_t) offt;
  lastChange = millis();
  ledState = ledBlinkON,
    digitalWrite(BRED, HIGH);
}





// EOF
