/*------------------------------------------------------- 
 * PCMデータ生産者
 *   EEPROMからPCMデータを読み込む（一時的にバッファリング）
 *   順次PCMバッファに挿入
 *------------------------------------------------------- */
#include <xc.h>
#include <stdint.h>
#include "mcr.h"
#include "io.h"
#include "i2c-24fc1025.h"
#include "producer.h"
#include "buff.h"
#include "snd-eeprom.h"
#include "sw.h"

void producer(struct eeprom_index_s *h, uint8_t stop_by_sw)
{
  int8_t sw_state_prev = 1;
  int8_t sw_state_curr = sw_state_prev;
  /* サウンドデータを1バイトづつバッファに入れてゆく */
  uint32_t left_nbytes = left_nbytes = h->size;
  i2c_24fc1025_read_begin(0, h->addr, left_nbytes);
  for ( ; left_nbytes != 0; left_nbytes--) {
    CLRWDT();
    /* バッファに空きが出るのを待つ */
    while (buff_is_full()) {
      CLRWDT();
    }
    /* EEPROMより１バイト読んでデータをバッファに挿入 */
    buff_put(i2c_24fc1025_read_byte());
    /* SWによる再生中断(ONESHOT型再生時) */
    if (stop_by_sw == 1) {
      /* 一旦再生 SW が OFF となったのち、
       * 次に再生 SW が ON になれば, 再生を中断. */
      if (!sw_state_prev && sw_state_curr) {
        break;
      }
      sw_state_prev = sw_state_curr;
      sw_state_curr = sw_reader_get_play();
    }
  }
  i2c_24fc1025_read_done();
}
