/*
  03c_Keypad_SetAllRows

  Keypad entry of a date and time on each of the three rows
  Arduino Uno R3, 4x4 keypad, three HT16K33 display rows at 0x70-0x72

  Wiring:
    D0-D3  keypad rows 1-4
    D4-D7  keypad columns 1-4
    A4     display SDA
    A5     display SCL
    5V     display power
    GND    display ground
  SDA and SCL are also on the two pins at the end of the header by the USB
  socket; the very end pin is SCL.

  Press A (red), B (green) or C (yellow), then type:
  month (01-12), day, year (4 digits),
  hour (01-12), minute (00-59), then 1 = AM or 2 = PM.
  The position waiting for input flashes. An invalid key is ignored and the
  whole row flashes. * cancels and restores the previous value. A, B or C
  during entry abandons it and starts that row instead.

  Values are held in RAM, so they are lost on reset or power off.

  TCDSegments.h is a copy of lib/TCDDisplay/TCDSegments.h.

  D0 and D1 are also the USB serial pins, so Serial is only switched on
  while logging (9600 baud). Don't hold a key down while uploading.
*/

#include <Wire.h>
#include "TCDSegments.h"

const uint8_t ROW_COUNT = 3;            // red, green, yellow
const uint8_t ADDRESS[ROW_COUNT] = {0x70, 0x71, 0x72};   // keys A, B, C
const uint8_t BRIGHTNESS = 8;           // 0-15

// Keypad wiring and key layout, as printed on the pad.
const uint8_t ROW_PINS[] = {0, 1, 2, 3};
const uint8_t COL_PINS[] = {4, 5, 6, 7};
const char KEYS[4][4] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

const unsigned long BAUD = 9600;       // slow enough to ignore scan pulses on D1
const uint8_t DEBOUNCE_MS = 20;        // a key must be steady this long
const uint16_t BLINK_MS = 350;         // on and off time of the flashing cursor

// One entry step per key press, in the order the row is filled.
enum : uint8_t {
  ST_MONTH1, ST_MONTH2,
  ST_DAY1, ST_DAY2,
  ST_YEAR1, ST_YEAR2, ST_YEAR3, ST_YEAR4,
  ST_HOUR1, ST_HOUR2,
  ST_MIN1, ST_MIN2,
  ST_AMPM,                 // 1 = AM, 2 = PM
  STEPS
};

// Buffer slot for each step. Month and AM/PM are drawn separately.
const uint8_t NO_SLOT = 0xFF;
const uint8_t STEP_SLOT[STEPS] = {
  NO_SLOT, NO_SLOT,
  TCD_DAY_TENS, TCD_DAY_ONES,
  TCD_YEAR_THOU, TCD_YEAR_HUND, TCD_YEAR_TENS, TCD_YEAR_ONES,
  TCD_HOUR_TENS, TCD_HOUR_ONES,
  TCD_MIN_TENS, TCD_MIN_ONES,
  NO_SLOT,
};

const uint8_t DASH_7 = 0x40;            // segment g

uint8_t saved[ROW_COUNT][STEPS];        // last completed entry per row
uint8_t entry[STEPS];                   // entry in progress
bool haveValue[ROW_COUNT];
bool editing = false;
uint8_t step = 0;
uint8_t editRow = 0;                    // row being entered

bool blinkOn = true;
unsigned long blinkAt = 0;
uint8_t shown[ROW_COUNT][16];
bool displayOk[ROW_COUNT];

// ---- Serial log -----------------------------------------------------------

void rowsAsInputs() {
  for (uint8_t r = 0; r < 4; ++r) pinMode(ROW_PINS[r], INPUT_PULLUP);
}

// Print one line (text plus an optional character), then release D0/D1.
void logLine(const __FlashStringHelper *text, char key = 0) {
  Serial.begin(BAUD);
  Serial.print(text);
  if (key) Serial.print(key);
  Serial.println();
  Serial.flush();
  Serial.end();
  rowsAsInputs();
}

// ---- Display --------------------------------------------------------------

uint8_t sendBytes(uint8_t row, const uint8_t *data, uint8_t count) {
  Wire.beginTransmission(ADDRESS[row]);
  Wire.write(data, count);
  return Wire.endTransmission();
}

// Send a single-byte HT16K33 command.
uint8_t sendCommand(uint8_t row, uint8_t command) {
  return sendBytes(row, &command, 1);
}

// Start a display: it stays dark until the oscillator is switched on.
bool initDisplay(uint8_t row) {
  uint8_t errors = sendCommand(row, 0x21);          // oscillator on
  errors |= sendCommand(row, 0x81);                 // display on, no blink
  errors |= sendCommand(row, 0xE0 | BRIGHTNESS);
  return errors == 0;
}

// Copy a 16-byte frame to display RAM, remember it, and log when a row
// appears or disappears.
void writeDisplay(uint8_t row, const uint8_t *buf) {
  uint8_t out[17];
  out[0] = 0x00;                               // RAM address
  memcpy(out + 1, buf, 16);
  bool ok = sendBytes(row, out, 17) == 0;
  if (ok != displayOk[row]) {
    displayOk[row] = ok;
    logLine(ok ? F("Display responding, row ") : F("No response from row "),
            'A' + row);
  }
  memcpy(shown[row], buf, 16);
}

// A 7-segment style digit drawn on a 14-segment month character.
void putMonthDigit(uint8_t *buf, uint8_t slot, uint8_t v) {
  uint8_t g = TCD_FONT_DIGIT[v];
  buf[slot] = g;                               // a-f, g -> G1
  if (g & DASH_7) buf[slot + 1] |= 0x01;       // g -> G2
}

// A dash on a month character: both halves of the middle bar.
void putMonthDash(uint8_t *buf, uint8_t slot) {
  buf[slot] = DASH_7;
  buf[slot + 1] |= 0x01;
}

// Build a row's frame from its saved value, or from the entry in progress,
// including the flashing cursor. Writes only when changed, unless forced.
void render(uint8_t row, bool force = false) {
  bool active = editing && row == editRow;
  uint8_t buf[16] = {0};
  const uint8_t *d = active ? entry : saved[row];
  uint8_t filled = active ? step : (haveValue[row] ? STEPS : 0);
  bool cursor = active && blinkOn;

  // Month: dashes, then the first digit in the middle, then the name.
  if (filled > ST_MONTH2) {
    tcdPutLabel(buf, TCD_MONTH_NAME[d[ST_MONTH1] * 10 + d[ST_MONTH2]]);
  } else if (active && step == ST_MONTH1) {
    if (cursor) {
      putMonthDash(buf, TCD_MON1);
      putMonthDash(buf, TCD_MON2);
      putMonthDash(buf, TCD_MON3);
    }
  } else if (active && step == ST_MONTH2) {
    putMonthDigit(buf, TCD_MON2, d[ST_MONTH1]);
    if (cursor) putMonthDash(buf, TCD_MON3);
  }

  for (uint8_t s = 0; s < STEPS; ++s) {
    uint8_t slot = STEP_SLOT[s];
    if (slot == NO_SLOT) continue;
    if (s < filled) tcdPutDigit(buf, slot, d[s]);
    else if (cursor && s == step) buf[slot] = DASH_7;
  }

  if (filled > ST_AMPM) {
    tcdSetIndicator(buf, d[ST_AMPM] == 1 ? TCD_AM_BYTE : TCD_PM_BYTE, true);
  } else if (cursor && step == ST_AMPM) {
    tcdSetIndicator(buf, TCD_AM_BYTE, true);
    tcdSetIndicator(buf, TCD_PM_BYTE, true);
  }

  tcdSetIndicator(buf, TCD_COLON_BYTE, !active && haveValue[row]);

  if (force || memcmp(buf, shown[row], 16) != 0) writeDisplay(row, buf);
}

// Redraw all three rows.
void renderAll(bool force = false) {
  for (uint8_t row = 0; row < ROW_COUNT; ++row) render(row, force);
}

// Signal a rejected key: blink every segment of the row three times.
void flashRow() {
  uint8_t on[16];
  uint8_t off[16] = {0};
  memset(on, 0xFF, sizeof(on));
  for (uint8_t i = 0; i < 3; ++i) {
    writeDisplay(editRow, on);
    delay(120);
    writeDisplay(editRow, off);
    delay(120);
  }
}

// ---- Entry ----------------------------------------------------------------

uint8_t daysInMonth() {
  static const uint8_t DAYS[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  return DAYS[entry[ST_MONTH1] * 10 + entry[ST_MONTH2] - 1];
}

// Is v acceptable as the digit for the current step?
bool isValid(uint8_t v) {
  switch (step) {
    case ST_MONTH1: return v <= 1;
    case ST_MONTH2: {
      uint8_t month = entry[ST_MONTH1] * 10 + v;
      return month >= 1 && month <= 12;
    }
    case ST_DAY1:   return v * 10 <= daysInMonth();
    case ST_DAY2: {
      uint8_t day = entry[ST_DAY1] * 10 + v;
      return day >= 1 && day <= daysInMonth();
    }
    case ST_AMPM:   return v == 1 || v == 2;
    case ST_HOUR1:  return v <= 1;
    case ST_HOUR2: {
      uint8_t hour = entry[ST_HOUR1] * 10 + v;
      return hour >= 1 && hour <= 12;
    }
    case ST_MIN1:   return v <= 5;
    default:        return true;               // year and last minute digit
  }
}

// Act on one key press: start, cancel, accept or reject.
void handleKey(char key) {
  logLine(F("Key: "), key);

  if (key >= 'A' && key <= 'C') {            // A, B, C pick the row
    editRow = key - 'A';
    editing = true;
    step = 0;
  } else if (!editing) {
    return;
  } else if (key == '*') {
    editing = false;
    logLine(F("Cancelled"));
  } else if (key >= '0' && key <= '9' && isValid(key - '0')) {
    entry[step++] = key - '0';
    if (step == STEPS) {
      memcpy(saved[editRow], entry, STEPS);
      haveValue[editRow] = true;
      editing = false;
      logLine(F("Row set: "), 'A' + editRow);
    }
  } else {
    logLine(F("Invalid, ignored"));
    flashRow();
  }

  blinkOn = true;
  blinkAt = millis();
  renderAll(true);
}

// ---- Keypad ---------------------------------------------------------------

// Returns the first pressed key, or 0. Columns float except while scanned.
char scanKeypad() {
  char found = 0;
  for (uint8_t c = 0; c < 4 && !found; ++c) {
    digitalWrite(COL_PINS[c], LOW);
    pinMode(COL_PINS[c], OUTPUT);
    delayMicroseconds(5);
    for (uint8_t r = 0; r < 4; ++r) {
      if (digitalRead(ROW_PINS[r]) == LOW) {
        found = KEYS[r][c];
        break;
      }
    }
    pinMode(COL_PINS[c], INPUT);
  }
  return found;
}

// Returns a key once, when it is first pressed (debounced).
char newKeyPress() {
  static char lastRaw = 0;
  static char stable = 0;
  static unsigned long changedAt = 0;

  char raw = scanKeypad();
  if (raw != lastRaw) {
    lastRaw = raw;
    changedAt = millis();
  } else if (raw != stable && millis() - changedAt >= DEBOUNCE_MS) {
    stable = raw;
    return stable;
  }
  return 0;
}

// ---------------------------------------------------------------------------

void setup() {
  rowsAsInputs();
  for (uint8_t c = 0; c < 4; ++c) pinMode(COL_PINS[c], INPUT);

  Wire.begin();
  Wire.setWireTimeout(25000, true);            // don't hang on a stuck bus
  for (uint8_t row = 0; row < ROW_COUNT; ++row) {
    displayOk[row] = initDisplay(row);
    logLine(displayOk[row] ? F("Display found, row ") : F("No response from row "),
            'A' + row);
  }
  logLine(F("Press A, B or C."));
  renderAll(true);
}

// Poll the keypad and keep the flashing cursor going, without blocking.
void loop() {
  char key = newKeyPress();
  if (key) handleKey(key);

  if (millis() - blinkAt >= BLINK_MS) {
    blinkAt = millis();
    blinkOn = !blinkOn;
    for (uint8_t row = 0; row < ROW_COUNT; ++row) {
      bool lost = !displayOk[row];
      if (lost) initDisplay(row);             // recovers a late connection
      render(row, lost);
    }
  }
}
