inoChannel.cpp 1.83 KB
#include "inoChannel.h"
#include "heisenwave.h"

void inoChannel::setup(string device) {
  this->device = device;
}

void inoChannel::exit() {
  serial.close();
}

void inoChannel::identify() {
  inoCommand cmd;

  cmd.resize(17, 0);

  cmd[0] = HW_HELO;
  for(int i = 0; i < 16 && i < device.size(); i++) {
    cmd[i+1] = device[i];
  }
  commands.push(cmd);
}

void inoChannel::startStream() {
  inoCommand cmd;
  cmd.push_back(HW_START_STREAM);
  commands.push(cmd);
}

void inoChannel::stopStream() {
  inoCommand cmd;
  cmd.push_back(HW_STOP_STREAM);
  commands.push(cmd);
}

bool inoChannel::checkSystem() {
  while(isThreadRunning() && !(serial.available() >= 4));
  if(serial.available() >= 4) {
    unsigned char buf[4];
    serial.readBytes(buf, 4);
    if(buf[0] != 'H' || buf[1] != 'W') {
      // Serial Port is invalid
      string status("Invalid");
      ofNotifyEvent(statusChange, status, this);
      return false;
    }
    string status("Connected");
    ofNotifyEvent(statusChange, status, this);
    return true;
  }
  return false;
}

void inoChannel::threadedFunction() {
  serial.setup(device, 115200);
  serial.flush();
  if(!checkSystem()) {
    ofLogError() << "Invalid System";
  }
  identify();
  while(isThreadRunning()) {
    if(serial.available() >= 1) {
      switch(serial.readByte()) {
        case HW_NEW_FRAME:
          {
            while(serial.available() < 256) {
              if(!isThreadRunning()) return;
            }

            // serial.readBytes(buffer, 256);

            break;
          }
        default:
          // no idea what could go wrong
          break;
      }
    }
    if(commands.size() > 1) {
      inoCommand cmd = commands.front();
      if(serial.writeBytes(cmd.data(), cmd.size())) {
        commands.pop();
      } else {
        ofLogError() << "Unable to send command";
      }
    }
  }
}