<commit_before>/* AFE Firmware for smart home devices
  LICENSE: https://github.com/tschaban/AFE-Firmware/blob/master/LICENSE
  DOC: http://smart-house.adrian.czabanowski.com/afe-firmware-pl/ */

#include "AFE-Web-Server.h"

AFEWebServer::AFEWebServer() {}

void AFEWebServer::begin() {
  httpUpdater.setup(&server);
  server.begin();
}

void AFEWebServer::listener() { server.handleClient(); }

boolean AFEWebServer::httpAPIlistener() { return receivedHTTPCommand; }

void AFEWebServer::publishHTML(String page) {
  server.send(200, "text/html", page);
}

void AFEWebServer::sendJSON(String json) {
  server.send(200, "application/json", json);
}

void AFEWebServer::handle(const char *uri,
                          ESP8266WebServer::THandlerFunction handler) {
  // Serial << endl << "INFO: Added url : " << uri << " for listening";
  server.on(uri, handler);
}

HTTPCOMMAND AFEWebServer::getHTTPCommand() {
  receivedHTTPCommand = false;
  return httpCommand;
}

void AFEWebServer::generate() {
  /* @TODO this method is not writen well */

  if (_refreshConfiguration) {
    _refreshConfiguration = false;
    Device.begin();
  }

  const String optionName = getOptionName();
  uint8_t command = getCommand();

  if (optionName == "language") {
    uint8_t data;
    if (command == SERVER_CMD_SAVE) {
      data = getLanguageData();
    }
    publishHTML(ConfigurationPanel.getLanguageConfigurationSite(
        optionName, getCommand(), data));

    if (command == SERVER_CMD_SAVE) {
      Device.reboot(Device.getMode());
    }
  } else if (optionName == "device") {
    DEVICE data;
    if (command == SERVER_CMD_SAVE) {
      data = getDeviceData();
    }
    publishHTML(ConfigurationPanel.getDeviceConfigurationSite(
        optionName, getCommand(), data));
  } else if (optionName == "network") {
    NETWORK data;
    if (command == SERVER_CMD_SAVE) {
      data = getNetworkData();
    }
    publishHTML(ConfigurationPanel.getNetworkConfigurationSite(
        optionName, getCommand(), data));

  } else if (optionName == "mqtt") {
    MQTT data;
    if (command == SERVER_CMD_SAVE) {
      data = getMQTTData();
    }
    publishHTML(ConfigurationPanel.getMQTTConfigurationSite(
        optionName, getCommand(), data));
  } else if (optionName == "domoticz") {
    DOMOTICZ data;
    if (command == SERVER_CMD_SAVE) {
      data = getDomoticzServerData();
    }
    publishHTML(ConfigurationPanel.getDomoticzServerConfigurationSite(
        optionName, getCommand(), data));
  } else if (optionName == "led") {
    LED data[sizeof(Device.configuration.isLED)] = {};
    uint8_t dataLedID;
    if (command == SERVER_CMD_SAVE) {
      for (uint8_t i = 0; i < sizeof(Device.configuration.isLED); i++) {
        data[i] = getLEDData(i);
      }
      dataLedID = getSystemLEDData();
    }
    publishHTML(ConfigurationPanel.getLEDConfigurationSite(
        optionName, getCommand(), data, dataLedID));
  } else if (optionName == "exit") {
    publishHTML(ConfigurationPanel.getSite(optionName, getCommand(), true));
    Device.reboot(MODE_NORMAL);
  } else if (optionName == "reset") {
    publishHTML(ConfigurationPanel.getSite(optionName, getCommand(), false));
    if (command == 1) {
      Device.setDevice();
      Device.reboot(MODE_ACCESS_POINT);
    }
  } else if (optionName == "help") {
    publishHTML(ConfigurationPanel.getSite(optionName, getCommand(),
                                           command == 0 ? false : true));
    if (command == 1) {
      Device.reboot(MODE_CONFIGURATION);
    } else if (command == 2) {
      Device.reboot(MODE_ACCESS_POINT);
    }
  } else {
    for (uint8_t i = 0; i < sizeof(Device.configuration.isRelay); i++) {
      if (Device.configuration.isRelay[i]) {
        if (optionName == "relay" + String(i)) {
          RELAY data = {};
          if (command == SERVER_CMD_SAVE) {
            data = getRelayData(i);
          }
          publishHTML(ConfigurationPanel.getRelayConfigurationSite(
              optionName, getCommand(), data, i));
        }
      } else {
        break;
      }
    }

    for (uint8_t i = 0; i < sizeof(Device.configuration.isSwitch); i++) {
      if (Device.configuration.isSwitch[i]) {
        if (optionName == "switch" + String(i)) {
          SWITCH data = {};
          if (command == SERVER_CMD_SAVE) {
            data = getSwitchData(i);
          }
          publishHTML(ConfigurationPanel.getSwitchConfigurationSite(
              optionName, getCommand(), data, i));
        }
      } else {
        break;
      }
    }
  }
}

String AFEWebServer::getOptionName() {

  if (Device.getMode() == MODE_NORMAL) {
    /* Recived HTTP API Command */
    if (server.hasArg("command")) {
      /* Constructing command */
      server.arg("command").toCharArray(httpCommand.command,
                                        sizeof(httpCommand.command));
      if (server.arg("device")) {
        server.arg("device").toCharArray(httpCommand.device,
                                         sizeof(httpCommand.device));
      } else {
        memset(httpCommand.device, 0, sizeof httpCommand.device);
      }
      if (server.arg("name")) {
        server.arg("name").toCharArray(httpCommand.name,
                                       sizeof(httpCommand.name));
      } else {
        memset(httpCommand.name, 0, sizeof httpCommand.name);
      }

      if (server.arg("source")) {
        server.arg("source").toCharArray(httpCommand.source,
                                         sizeof(httpCommand.source));
      } else {
        memset(httpCommand.source, 0, sizeof httpCommand.source);
      }
      /*
            Serial << endl
                   << "GET: Device=" << httpCommand.device
                   << " Name=" << httpCommand.name << " Source=" <<
         httpCommand.source
                   << " Command=" << httpCommand.command;
      */
      receivedHTTPCommand = true;
      return server.arg("command");

    } else {
      return "help";
    }
  } else {
    if (server.hasArg("option")) {
      return server.arg("option");
    } else {
      return "device";
    }
  }
}

uint8_t AFEWebServer::getCommand() {
  if (server.hasArg("cmd")) {
    return server.arg("cmd").toInt();
  }
}

DEVICE AFEWebServer::getDeviceData() {
  DEVICE data;

  _refreshConfiguration =
      true; // it will cause that device configuration will be refeshed

  if (server.arg("dn").length() > 0) {
    server.arg("dn").toCharArray(data.name, sizeof(data.name));
  } else {
    data.name[0] = '\0';
  }

  server.arg("h").length() > 0 ? data.httpAPI = true : data.httpAPI = false;

  server.arg("m").length() > 0 ? data.mqttAPI = true : data.mqttAPI = false;

  server.arg("d").length() > 0 ? data.domoticzAPI = true
                               : data.domoticzAPI = false;

  for (uint8_t i = 0; i < sizeof(Device.configuration.isLED); i++) {
    server.arg("hl").toInt() > i ? data.isLED[i] = true : data.isLED[i] = false;
  }

  for (uint8_t i = 0; i < sizeof(Device.configuration.isRelay); i++) {
    server.arg("hr").toInt() > i ? data.isRelay[i] = true
                                 : data.isRelay[i] = false;
  }

  for (uint8_t i = 0; i < sizeof(Device.configuration.isSwitch); i++) {
    server.arg("hs").toInt() > i ? data.isSwitch[i] = true
                                 : data.isSwitch[i] = false;
  }

  return data;
}

NETWORK AFEWebServer::getNetworkData() {
  NETWORK data;
  if (server.arg("s").length() > 0) {
    server.arg("s").toCharArray(data.ssid, sizeof(data.ssid) + 1);
  } else {
    data.ssid[0] = '\0';
  }

  if (server.arg("p").length() > 0) {
    server.arg("p").toCharArray(data.password, sizeof(data.password) + 1);
  } else {
    data.password[0] = '\0';
  }

  if (server.arg("d").length() > 0) {
    data.isDHCP = true;
  } else {
    data.isDHCP = false;
  }

  if (server.arg("d1").length() > 0 && server.arg("d2").length() > 0 &&
      server.arg("d3").length() > 0 && server.arg("d4").length() > 0) {

    data.ip = IPAddress(server.arg("d1").toInt(), server.arg("d2").toInt(),
                        server.arg("d3").toInt(), server.arg("d4").toInt());
  }
  if (server.arg("g1").length() > 0 && server.arg("g2").length() > 0 &&
      server.arg("g3").length() > 0 && server.arg("g4").length() > 0) {

    data.gateway =
        IPAddress(server.arg("g1").toInt(), server.arg("g2").toInt(),
                  server.arg("g3").toInt(), server.arg("g4").toInt());
  }
  if (server.arg("s1").length() > 0 && server.arg("s2").length() > 0 &&
      server.arg("s3").length() > 0 && server.arg("s4").length() > 0) {

    data.subnet = IPAddress(server.arg("s1").toInt(), server.arg("s2").toInt(),
                            server.arg("s3").toInt(), server.arg("s4").toInt());
  }
  if (server.arg("na").length() > 0) {
    data.noConnectionAttempts = server.arg("na").toInt();
  }
  if (server.arg("wc").length() > 0) {
    data.waitTimeConnections = server.arg("wc").toInt();
  }
  if (server.arg("ws").length() > 0) {
    data.waitTimeSeries = server.arg("ws").toInt();
  }

  return data;
}

MQTT AFEWebServer::getMQTTData() {
  MQTT data;
  if (server.arg("h").length() > 0) {
    server.arg("h").toCharArray(data.host, sizeof(data.host) + 1);
  } else {
    data.host[0] = '\0';
  }

  if (server.arg("m1").length() > 0 && server.arg("m2").length() > 0 &&
      server.arg("m3").length() > 0 && server.arg("m4").length() > 0) {

    data.ip = IPAddress(server.arg("m1").toInt(), server.arg("m2").toInt(),
                        server.arg("m3").toInt(), server.arg("m4").toInt());
  }

  if (server.arg("p").length() > 0) {
    data.port = server.arg("p").toInt();
  }

  if (server.arg("u").length() > 0) {
    server.arg("u").toCharArray(data.user, sizeof(data.user) + 1);
  } else {
    data.user[0] = '\0';
  }

  if (server.arg("s").length() > 0) {
    server.arg("s").toCharArray(data.password, sizeof(data.password) + 1);
  } else {
    data.password[0] = '\0';
  }

  if (server.arg("t").length() > 0) {
    server.arg("t").toCharArray(data.topic, sizeof(data.topic) + 1);
  } else {
    data.topic[0] = '\0';
  }

  return data;
}

DOMOTICZ AFEWebServer::getDomoticzServerData() {
  DOMOTICZ data;

  if (server.arg("t").length() > 0) {
    data.protocol = server.arg("t").toInt();
  }

  if (server.arg("h").length() > 0) {
    server.arg("h").toCharArray(data.host, sizeof(data.host) + 1);
  }

  if (server.arg("p").length() > 0) {
    data.port = server.arg("p").toInt();
  }

  if (server.arg("u").length() > 0) {
    server.arg("u").toCharArray(data.user, sizeof(data.user) + 1);
  } else {
    data.user[0] = '\0';
  }
  if (server.arg("s").length() > 0) {
    server.arg("s").toCharArray(data.password, sizeof(data.password) + 1);
  } else {
    data.password[0] = '\0';
  }

  return data;
}

RELAY AFEWebServer::getRelayData(uint8_t id) {
  RELAY data;

  if (server.arg("g" + String(id)).length() > 0) {
    data.gpio = server.arg("g" + String(id)).toInt();
  }

  if (server.arg("ot" + String(id)).length() > 0) {
    data.timeToOff = server.arg("ot" + String(id)).toFloat();
  }

  if (server.arg("pr" + String(id)).length() > 0) {
    data.statePowerOn = server.arg("pr" + String(id)).toInt();
  }

  if (server.arg("n" + String(id)).length() > 0) {
    server.arg("n" + String(id)).toCharArray(data.name, sizeof(data.name) + 1);
  }

  if (server.arg("mc" + String(id)).length() > 0) {
    data.stateMQTTConnected = server.arg("mc" + String(id)).toInt();
  }

  if (server.arg("l" + String(id)).length() > 0) {
    data.ledID = server.arg("l" + String(id)).toInt();
  }

  if (server.arg("x" + String(id)).length() > 0) {
    data.idx = server.arg("x" + String(id)).toInt();
  }

  return data;
}

SWITCH AFEWebServer::getSwitchData(uint8_t id) {
  SWITCH data;

  if (server.arg("t" + String(id)).length() > 0) {
    data.type = server.arg("t" + String(id)).toInt();
  }

  if (server.arg("s" + String(id)).length() > 0) {
    data.sensitiveness = server.arg("s" + String(id)).toInt();
  }

  if (server.arg("f" + String(id)).length() > 0) {
    data.functionality = server.arg("f" + String(id)).toInt();
  }

  if (server.arg("g" + String(id)).length() > 0) {
    data.gpio = server.arg("g" + String(id)).toInt();
  }

  if (server.arg("r" + String(id)).length() > 0) {
    data.relayID = server.arg("r" + String(id)).toInt();
  }

  return data;
}

LED AFEWebServer::getLEDData(uint8_t id) {
  LED data;
  if (server.arg("g" + String(id)).length() > 0) {
    data.gpio = server.arg("g" + String(id)).toInt();
  }

  server.arg("o" + String(id)).length() > 0
      ? data.changeToOppositeValue = true
      : data.changeToOppositeValue = false;

  return data;
}

uint8_t AFEWebServer::getSystemLEDData() {
  uint8_t data;

  if (server.arg("i").length() > 0) {
    data = server.arg("i").toInt();
  }

  return data;
}

uint8_t AFEWebServer::getLanguageData() {
  return server.arg("l").length() > 0 ? server.arg("l").toInt() : 1;
}
<commit_msg>replaced getCommand() with command<commit_after>/* AFE Firmware for smart home devices
  LICENSE: https://github.com/tschaban/AFE-Firmware/blob/master/LICENSE
  DOC: http://smart-house.adrian.czabanowski.com/afe-firmware-pl/ */

#include "AFE-Web-Server.h"

AFEWebServer::AFEWebServer() {}

void AFEWebServer::begin() {
  httpUpdater.setup(&server);
  server.begin();
}

void AFEWebServer::listener() { server.handleClient(); }

boolean AFEWebServer::httpAPIlistener() { return receivedHTTPCommand; }

void AFEWebServer::publishHTML(String page) {
  server.send(200, "text/html", page);
}

void AFEWebServer::sendJSON(String json) {
  server.send(200, "application/json", json);
}

void AFEWebServer::handle(const char *uri,
                          ESP8266WebServer::THandlerFunction handler) {
  // Serial << endl << "INFO: Added url : " << uri << " for listening";
  server.on(uri, handler);
}

HTTPCOMMAND AFEWebServer::getHTTPCommand() {
  receivedHTTPCommand = false;
  return httpCommand;
}

void AFEWebServer::generate() {
  /* @TODO this method is not writen well */

  if (_refreshConfiguration) {
    _refreshConfiguration = false;
    Device.begin();
  }

  const String optionName = getOptionName();
  uint8_t command = getCommand();

  if (optionName == "language") {
    uint8_t data;
    if (command == SERVER_CMD_SAVE) {
      data = getLanguageData();
    }
    publishHTML(ConfigurationPanel.getLanguageConfigurationSite(optionName,
                                                                command, data));

    if (command == SERVER_CMD_SAVE) {
      Device.reboot(Device.getMode());
    }
  } else if (optionName == "device") {
    DEVICE data;
    if (command == SERVER_CMD_SAVE) {
      data = getDeviceData();
    }
    publishHTML(ConfigurationPanel.getDeviceConfigurationSite(optionName,
                                                              command, data));
  } else if (optionName == "network") {
    NETWORK data;
    if (command == SERVER_CMD_SAVE) {
      data = getNetworkData();
    }
    publishHTML(ConfigurationPanel.getNetworkConfigurationSite(optionName,
                                                               command, data));

  } else if (optionName == "mqtt") {
    MQTT data;
    if (command == SERVER_CMD_SAVE) {
      data = getMQTTData();
    }
    publishHTML(
        ConfigurationPanel.getMQTTConfigurationSite(optionName, command, data));
  } else if (optionName == "domoticz") {
    DOMOTICZ data;
    if (command == SERVER_CMD_SAVE) {
      data = getDomoticzServerData();
    }
    publishHTML(ConfigurationPanel.getDomoticzServerConfigurationSite(
        optionName, command, data));
  } else if (optionName == "led") {
    LED data[sizeof(Device.configuration.isLED)] = {};
    uint8_t dataLedID;
    if (command == SERVER_CMD_SAVE) {
      for (uint8_t i = 0; i < sizeof(Device.configuration.isLED); i++) {
        data[i] = getLEDData(i);
      }
      dataLedID = getSystemLEDData();
    }
    publishHTML(ConfigurationPanel.getLEDConfigurationSite(optionName, command,
                                                           data, dataLedID));
  } else if (optionName == "exit") {
    publishHTML(ConfigurationPanel.getSite(optionName, command, true));
    Device.reboot(MODE_NORMAL);
  } else if (optionName == "reset") {
    publishHTML(ConfigurationPanel.getSite(optionName, command, false));
    if (command == 1) {
      Device.setDevice();
      Device.reboot(MODE_ACCESS_POINT);
    }
  } else if (optionName == "help") {
    publishHTML(ConfigurationPanel.getSite(optionName, command,
                                           command == 0 ? false : true));
    if (command == 1) {
      Device.reboot(MODE_CONFIGURATION);
    } else if (command == 2) {
      Device.reboot(MODE_ACCESS_POINT);
    }
  } else {
    for (uint8_t i = 0; i < sizeof(Device.configuration.isRelay); i++) {
      if (Device.configuration.isRelay[i]) {
        if (optionName == "relay" + String(i)) {
          RELAY data = {};
          if (command == SERVER_CMD_SAVE) {
            data = getRelayData(i);
          }
          publishHTML(ConfigurationPanel.getRelayConfigurationSite(
              optionName, command, data, i));
        }
      } else {
        break;
      }
    }

    for (uint8_t i = 0; i < sizeof(Device.configuration.isSwitch); i++) {
      if (Device.configuration.isSwitch[i]) {
        if (optionName == "switch" + String(i)) {
          SWITCH data = {};
          if (command == SERVER_CMD_SAVE) {
            data = getSwitchData(i);
          }
          publishHTML(ConfigurationPanel.getSwitchConfigurationSite(
              optionName, command, data, i));
        }
      } else {
        break;
      }
    }
  }
}

String AFEWebServer::getOptionName() {

  if (Device.getMode() == MODE_NORMAL) {
    /* Recived HTTP API Command */
    if (server.hasArg("command")) {
      /* Constructing command */
      server.arg("command").toCharArray(httpCommand.command,
                                        sizeof(httpCommand.command));
      if (server.arg("device")) {
        server.arg("device").toCharArray(httpCommand.device,
                                         sizeof(httpCommand.device));
      } else {
        memset(httpCommand.device, 0, sizeof httpCommand.device);
      }
      if (server.arg("name")) {
        server.arg("name").toCharArray(httpCommand.name,
                                       sizeof(httpCommand.name));
      } else {
        memset(httpCommand.name, 0, sizeof httpCommand.name);
      }

      if (server.arg("source")) {
        server.arg("source").toCharArray(httpCommand.source,
                                         sizeof(httpCommand.source));
      } else {
        memset(httpCommand.source, 0, sizeof httpCommand.source);
      }
      /*
            Serial << endl
                   << "GET: Device=" << httpCommand.device
                   << " Name=" << httpCommand.name << " Source=" <<
         httpCommand.source
                   << " Command=" << httpCommand.command;
      */
      receivedHTTPCommand = true;
      return server.arg("command");

    } else {
      return "help";
    }
  } else {
    if (server.hasArg("option")) {
      return server.arg("option");
    } else {
      return "device";
    }
  }
}

uint8_t AFEWebServer::getCommand() {
  if (server.hasArg("cmd")) {
    return server.arg("cmd").toInt();
  }
}

DEVICE AFEWebServer::getDeviceData() {
  DEVICE data;

  _refreshConfiguration =
      true; // it will cause that device configuration will be refeshed

  if (server.arg("dn").length() > 0) {
    server.arg("dn").toCharArray(data.name, sizeof(data.name));
  } else {
    data.name[0] = '\0';
  }

  server.arg("h").length() > 0 ? data.httpAPI = true : data.httpAPI = false;

  server.arg("m").length() > 0 ? data.mqttAPI = true : data.mqttAPI = false;

  server.arg("d").length() > 0 ? data.domoticzAPI = true
                               : data.domoticzAPI = false;

  for (uint8_t i = 0; i < sizeof(Device.configuration.isLED); i++) {
    server.arg("hl").toInt() > i ? data.isLED[i] = true : data.isLED[i] = false;
  }

  for (uint8_t i = 0; i < sizeof(Device.configuration.isRelay); i++) {
    server.arg("hr").toInt() > i ? data.isRelay[i] = true
                                 : data.isRelay[i] = false;
  }

  for (uint8_t i = 0; i < sizeof(Device.configuration.isSwitch); i++) {
    server.arg("hs").toInt() > i ? data.isSwitch[i] = true
                                 : data.isSwitch[i] = false;
  }

  return data;
}

NETWORK AFEWebServer::getNetworkData() {
  NETWORK data;
  if (server.arg("s").length() > 0) {
    server.arg("s").toCharArray(data.ssid, sizeof(data.ssid) + 1);
  } else {
    data.ssid[0] = '\0';
  }

  if (server.arg("p").length() > 0) {
    server.arg("p").toCharArray(data.password, sizeof(data.password) + 1);
  } else {
    data.password[0] = '\0';
  }

  if (server.arg("d").length() > 0) {
    data.isDHCP = true;
  } else {
    data.isDHCP = false;
  }

  if (server.arg("d1").length() > 0 && server.arg("d2").length() > 0 &&
      server.arg("d3").length() > 0 && server.arg("d4").length() > 0) {

    data.ip = IPAddress(server.arg("d1").toInt(), server.arg("d2").toInt(),
                        server.arg("d3").toInt(), server.arg("d4").toInt());
  }
  if (server.arg("g1").length() > 0 && server.arg("g2").length() > 0 &&
      server.arg("g3").length() > 0 && server.arg("g4").length() > 0) {

    data.gateway =
        IPAddress(server.arg("g1").toInt(), server.arg("g2").toInt(),
                  server.arg("g3").toInt(), server.arg("g4").toInt());
  }
  if (server.arg("s1").length() > 0 && server.arg("s2").length() > 0 &&
      server.arg("s3").length() > 0 && server.arg("s4").length() > 0) {

    data.subnet = IPAddress(server.arg("s1").toInt(), server.arg("s2").toInt(),
                            server.arg("s3").toInt(), server.arg("s4").toInt());
  }
  if (server.arg("na").length() > 0) {
    data.noConnectionAttempts = server.arg("na").toInt();
  }
  if (server.arg("wc").length() > 0) {
    data.waitTimeConnections = server.arg("wc").toInt();
  }
  if (server.arg("ws").length() > 0) {
    data.waitTimeSeries = server.arg("ws").toInt();
  }

  return data;
}

MQTT AFEWebServer::getMQTTData() {
  MQTT data;
  if (server.arg("h").length() > 0) {
    server.arg("h").toCharArray(data.host, sizeof(data.host) + 1);
  } else {
    data.host[0] = '\0';
  }

  if (server.arg("m1").length() > 0 && server.arg("m2").length() > 0 &&
      server.arg("m3").length() > 0 && server.arg("m4").length() > 0) {

    data.ip = IPAddress(server.arg("m1").toInt(), server.arg("m2").toInt(),
                        server.arg("m3").toInt(), server.arg("m4").toInt());
  }

  if (server.arg("p").length() > 0) {
    data.port = server.arg("p").toInt();
  }

  if (server.arg("u").length() > 0) {
    server.arg("u").toCharArray(data.user, sizeof(data.user) + 1);
  } else {
    data.user[0] = '\0';
  }

  if (server.arg("s").length() > 0) {
    server.arg("s").toCharArray(data.password, sizeof(data.password) + 1);
  } else {
    data.password[0] = '\0';
  }

  if (server.arg("t").length() > 0) {
    server.arg("t").toCharArray(data.topic, sizeof(data.topic) + 1);
  } else {
    data.topic[0] = '\0';
  }

  return data;
}

DOMOTICZ AFEWebServer::getDomoticzServerData() {
  DOMOTICZ data;

  if (server.arg("t").length() > 0) {
    data.protocol = server.arg("t").toInt();
  }

  if (server.arg("h").length() > 0) {
    server.arg("h").toCharArray(data.host, sizeof(data.host) + 1);
  }

  if (server.arg("p").length() > 0) {
    data.port = server.arg("p").toInt();
  }

  if (server.arg("u").length() > 0) {
    server.arg("u").toCharArray(data.user, sizeof(data.user) + 1);
  } else {
    data.user[0] = '\0';
  }
  if (server.arg("s").length() > 0) {
    server.arg("s").toCharArray(data.password, sizeof(data.password) + 1);
  } else {
    data.password[0] = '\0';
  }

  return data;
}

RELAY AFEWebServer::getRelayData(uint8_t id) {
  RELAY data;

  if (server.arg("g" + String(id)).length() > 0) {
    data.gpio = server.arg("g" + String(id)).toInt();
  }

  if (server.arg("ot" + String(id)).length() > 0) {
    data.timeToOff = server.arg("ot" + String(id)).toFloat();
  }

  if (server.arg("pr" + String(id)).length() > 0) {
    data.statePowerOn = server.arg("pr" + String(id)).toInt();
  }

  if (server.arg("n" + String(id)).length() > 0) {
    server.arg("n" + String(id)).toCharArray(data.name, sizeof(data.name) + 1);
  }

  if (server.arg("mc" + String(id)).length() > 0) {
    data.stateMQTTConnected = server.arg("mc" + String(id)).toInt();
  }

  if (server.arg("l" + String(id)).length() > 0) {
    data.ledID = server.arg("l" + String(id)).toInt();
  }

  if (server.arg("x" + String(id)).length() > 0) {
    data.idx = server.arg("x" + String(id)).toInt();
  }

  return data;
}

SWITCH AFEWebServer::getSwitchData(uint8_t id) {
  SWITCH data;

  if (server.arg("t" + String(id)).length() > 0) {
    data.type = server.arg("t" + String(id)).toInt();
  }

  if (server.arg("s" + String(id)).length() > 0) {
    data.sensitiveness = server.arg("s" + String(id)).toInt();
  }

  if (server.arg("f" + String(id)).length() > 0) {
    data.functionality = server.arg("f" + String(id)).toInt();
  }

  if (server.arg("g" + String(id)).length() > 0) {
    data.gpio = server.arg("g" + String(id)).toInt();
  }

  if (server.arg("r" + String(id)).length() > 0) {
    data.relayID = server.arg("r" + String(id)).toInt();
  }

  return data;
}

LED AFEWebServer::getLEDData(uint8_t id) {
  LED data;
  if (server.arg("g" + String(id)).length() > 0) {
    data.gpio = server.arg("g" + String(id)).toInt();
  }

  server.arg("o" + String(id)).length() > 0
      ? data.changeToOppositeValue = true
      : data.changeToOppositeValue = false;

  return data;
}

uint8_t AFEWebServer::getSystemLEDData() {
  uint8_t data;

  if (server.arg("i").length() > 0) {
    data = server.arg("i").toInt();
  }

  return data;
}

uint8_t AFEWebServer::getLanguageData() {
  return server.arg("l").length() > 0 ? server.arg("l").toInt() : 1;
}
<|endoftext|>


<commit_before>#include <osrm/coordinate.hpp>

#include <boost/test/unit_test.hpp>

// Regression test for bug captured in #1347
BOOST_AUTO_TEST_CASE(regression_test_1347)
{
    FixedPointCoordinate u(10 * COORDINATE_PRECISION, -100 * COORDINATE_PRECISION);
    FixedPointCoordinate v(10.001 * COORDINATE_PRECISION, -100.002 * COORDINATE_PRECISION);
    FixedPointCoordinate q(10.002 * COORDINATE_PRECISION, -100.001 * COORDINATE_PRECISION);

    float d1 = FixedPointCoordinate::ComputePerpendicularDistance(u, v, q);

    float ratio;
    FixedPointCoordinate nearest_location;
    float d2 = FixedPointCoordinate::ComputePerpendicularDistance(u, v, q, nearest_location, ratio);

    BOOST_CHECK_LE(std::abs(d1 - d2), 0.01);
}

<commit_msg>make floating point number literal a float<commit_after>#include <osrm/coordinate.hpp>

#include <boost/test/unit_test.hpp>

// Regression test for bug captured in #1347
BOOST_AUTO_TEST_CASE(regression_test_1347)
{
    FixedPointCoordinate u(10 * COORDINATE_PRECISION, -100 * COORDINATE_PRECISION);
    FixedPointCoordinate v(10.001 * COORDINATE_PRECISION, -100.002 * COORDINATE_PRECISION);
    FixedPointCoordinate q(10.002 * COORDINATE_PRECISION, -100.001 * COORDINATE_PRECISION);

    float d1 = FixedPointCoordinate::ComputePerpendicularDistance(u, v, q);

    float ratio;
    FixedPointCoordinate nearest_location;
    float d2 = FixedPointCoordinate::ComputePerpendicularDistance(u, v, q, nearest_location, ratio);

    BOOST_CHECK_LE(std::abs(d1 - d2), 0.01f);
}

<|endoftext|>


<commit_before>#pragma once

#include "kernel.hh"
#include "refcache.hh"
#include "chainhash.hh"
#include "radix_array.hh"
#include "page_info.hh"
#include "kalloc.hh"
#include "fs.h"

class mdir;
class mfile;
class mdev;
class msock;

class mnode : public refcache::weak_referenced
{
public:
  struct types {
    enum {
      dir = 1,
      file,
      dev,
      sock,
    };
  };

  static sref<mnode> get(u64 n);
  static sref<mnode> alloc(u8 type);

  void cache_pin(bool flag);
  u8 type() const;

  mdir* as_dir();
  const mdir* as_dir() const;
  mfile* as_file();
  const mfile* as_file() const;
  mdev* as_dev();
  const mdev* as_dev() const;
  msock* as_sock();
  const msock* as_sock() const;

  class linkcount : public refcache::referenced {
  public:
    linkcount() : refcache::referenced(0) {};
    void onzero() override;
  };

  const u64 inum_;
  linkcount nlink_;

protected:
  mnode(u64 inum);

private:
  void onzero() override;

  std::atomic<bool> cache_pin_;
  std::atomic<bool> dirty_;
  std::atomic<bool> valid_;
};

/*
 * An mlinkref represents a link count reference on an mnode.
 * The caller must ensure that mlinkref::acquire() is not called
 * after mnode::nlink_ reaches stable zero, perhaps by blocking
 * refcache epochs using cli when looking up the inode number in
 * a directory.
 *
 * Each mlinkref holds a reference to the mnode as well, to ensure
 * that the memory used to store the nlink_ count is not evicted
 * before all of the refcache deltas are flushed.  Otherwise this
 * would just be an sref<linkcount>.
 */
class mlinkref {
public:
  mlinkref() {}
  mlinkref(sref<mnode> mref) : m_(mref) {}

  sref<mnode> mn() {
    return m_;
  }

  bool held() {
    return !!l_;
  }

  /*
   * Increment the link count on the mnode.
   */
  void acquire() {
    assert(m_ && !l_);
    l_ = sref<mnode::linkcount>::newref(&m_->nlink_);
  }

  /*
   * Transfer an existing link count on the mnode to this mlinkref.
   */
  void transfer() {
    assert(m_ && !l_);
    l_ = sref<mnode::linkcount>::transfer(&m_->nlink_);
  }

private:
  /*
   * The order is important due to C++ constructor/destructor
   * rules: we must hold the mnode reference while manipulating
   * the linkcount reference.
   */
  sref<mnode> m_;
  sref<mnode::linkcount> l_;
};

class mdir : public mnode {
private:
  mdir(u64 inum) : mnode(inum), map_(257) {}
  NEW_DELETE_OPS(mdir);
  friend sref<mnode> mnode::get(u64);

  class filecount : public refcache::referenced {
  public:
    filecount() : refcache::referenced(0) {};
    void onzero() override {};
  };

  chainhash<strbuf<DIRSIZ>, u64> map_;

public:
  bool insert(const strbuf<DIRSIZ>& name, mlinkref* ilink) {
    if (name == ".")
      return false;
    if (!map_.insert(name, ilink->mn()->inum_))
      return false;
    assert(ilink->held());
    ilink->mn()->nlink_.inc();
    return true;
  }

  bool remove(const strbuf<DIRSIZ>& name, sref<mnode> m) {
    if (!map_.remove(name, m->inum_))
      return false;
    m->nlink_.dec();
    return true;
  }

  bool replace(const strbuf<DIRSIZ>& name, sref<mnode> mold, mlinkref* ilinknew) {
    if (!map_.replace(name, mold->inum_, ilinknew->mn()->inum_))
      return false;
    assert(ilinknew->held());
    ilinknew->mn()->nlink_.inc();
    mold->nlink_.dec();
    return true;
  }

  sref<mnode> lookup(const strbuf<DIRSIZ>& name) const {
    if (name == ".")
      return mnode::get(inum_);

    u64 iprev = -1;
    for (;;) {
      u64 inum;
      if (!map_.lookup(name, &inum))
        return sref<mnode>();

      sref<mnode> m = mnode::get(inum);
      if (m)
        return m;

      /*
       * The inode was GCed between the lookup and mnode::get().
       * Retry the lookup.  Crash if we repeatedly can't find
       * the same inode (to make such bugs easier to track down).
       */
      assert(inum != iprev);
      iprev = inum;
    }
  }

  mlinkref lookup_link(const strbuf<DIRSIZ>& name) const {
    if (name == ".")
      /*
       * We cannot convert the name "." to a link count on the mnode,
       * because "." does not hold a link count of its own.
       */
      return mlinkref();

    for (;;) {
      sref<mnode> m = lookup(name);
      if (!m)
        return mlinkref();

      scoped_cli cli;
      /*
       * Retry the lookup, now that we have an sref<mnode>, since
       * we don't want to do lookup's mnode::get() under cli.
       */
      u64 inum;
      if (!map_.lookup(name, &inum) || inum != m->inum_)
        /*
         * The name has either been unlinked or changed to point
         * to another inode.  Retry.
         */
        continue;

      mlinkref ilink(m);

      /*
       * At this point, we know the inode had a non-zero link
       * count prior to the second lookup.  Since we are holding
       * cli, refcache cannot advance its epoch, and will not
       * garbage-collect the inode until after we release cli.
       *
       * Mild POSIX violation: an inode can appear to have a
       * zero link count, according to fstat, but get a positive
       * link counter later, because the fstat occurs after the
       * last name has been unlinked, but before we increment
       * the link count here.
       */

      ilink.acquire();

      /*
       * Mild POSIX violation: an inode can appear to have a
       * link count, according to fstat, that is higher than
       * the number of all its names.  For instance, sys_link()
       * first grabs a mlinkref on the existing name, and then
       * drops it if the new name already exists.
       */

      return ilink;
    }
  }

  bool enumerate(const strbuf<DIRSIZ>* prev, strbuf<DIRSIZ>* name) const {
    if (!prev) {
      *name = ".";
      return true;
    }

    if (*prev == ".")
      prev = nullptr;

    return map_.enumerate(prev, name);
  }

  bool kill(sref<mnode> parent) {
    if (!map_.remove_and_kill("..", parent->inum_))
      return false;

    parent->nlink_.dec();
    return true;
  }

  bool killed() const {
    return map_.killed();
  }
};

inline mdir*
mnode::as_dir()
{
  assert(type() == types::dir);
  return static_cast<mdir*>(this);
}

inline const mdir*
mnode::as_dir() const
{
  assert(type() == types::dir);
  return static_cast<const mdir*>(this);
}

class mfile : public mnode {
private:
  mfile(u64 inum) : mnode(inum), size_(0) {}
  NEW_DELETE_OPS(mfile);
  friend sref<mnode> mnode::get(u64);

  struct page_state {
    enum {
      FLAG_LOCK_BIT = 0,
      FLAG_LOCK = 1 << FLAG_LOCK_BIT,
      FLAG_SET = 1 << 1,
    };

    page_state() : flags(0) {}
    page_state(sref<page_info> p) : flags(FLAG_SET), pg(p) {}

    bool is_set() const {
      return flags & FLAG_SET;
    }

    bit_spinlock get_lock() {
      return bit_spinlock(&flags, FLAG_LOCK_BIT);
    }

    u64 flags;
    sref<page_info> pg;
  };

  enum { maxidx = __SIZE_MAX__ / PGSIZE + 1 };
  radix_array<page_state, maxidx, PGSIZE,
              kalloc_allocator<page_state>> pages_;

  spinlock resize_lock_;
  seqcount<u32> size_seq_;
  u64 size_;

public:
  class resizer : public lock_guard<spinlock>,
                  public seq_writer {
  private:
    resizer(mfile* mf) : lock_guard<spinlock>(&mf->resize_lock_),
                         seq_writer(&mf->size_seq_),
                         mf_(mf) {}
    mfile* mf_;
    friend class mfile;

  public:
    resizer() : mf_(nullptr) {}
    explicit operator bool () const { return !!mf_; }
    u64 read_size() { return mf_->size_; }
    void resize_nogrow(u64 size);
    void resize_append(u64 size, sref<page_info> pi);
  };

  resizer write_size() {
    return resizer(this);
  }

  seq_reader<u64> read_size() {
    return seq_reader<u64>(&size_, &size_seq_);
  }

  sref<page_info> get_page(u64 pageidx);
};

inline mfile*
mnode::as_file()
{
  assert(type() == types::file);
  return static_cast<mfile*>(this);
}

inline const mfile*
mnode::as_file() const
{
  assert(type() == types::file);
  return static_cast<const mfile*>(this);
}

class mdev : public mnode {
private:
  mdev(u64 inum) : mnode(inum), major_(0), minor_(0) {}
  NEW_DELETE_OPS(mdev);
  friend sref<mnode> mnode::get(u64);

  u16 major_;
  u16 minor_;

public:
  u16 major() const { return major_; }
  u16 minor() const { return minor_; }

  void init(u16 major, u16 minor) {
    assert(!major_ && !minor_);
    major_ = major;
    minor_ = minor;
  }
};

inline mdev*
mnode::as_dev()
{
  assert(type() == types::dev);
  return static_cast<mdev*>(this);
}

inline const mdev*
mnode::as_dev() const
{
  assert(type() == types::dev);
  return static_cast<const mdev*>(this);
}

class msock : public mnode {
private:
  msock(u64 inum) : mnode(inum), localsock_(nullptr) {}
  NEW_DELETE_OPS(msock);
  friend sref<mnode> mnode::get(u64);

  localsock* localsock_;

public:
  localsock* get_sock() const { return localsock_; }

  void init(localsock* ls) {
    assert(!localsock_);
    localsock_ = ls;
  }
};

inline msock*
mnode::as_sock()
{
  assert(type() == types::sock);
  return static_cast<msock*>(this);
}

inline const msock*
mnode::as_sock() const
{
  assert(type() == types::sock);
  return static_cast<const msock*>(this);
}
<commit_msg>filecount no longer needed<commit_after>#pragma once

#include "kernel.hh"
#include "refcache.hh"
#include "chainhash.hh"
#include "radix_array.hh"
#include "page_info.hh"
#include "kalloc.hh"
#include "fs.h"

class mdir;
class mfile;
class mdev;
class msock;

class mnode : public refcache::weak_referenced
{
public:
  struct types {
    enum {
      dir = 1,
      file,
      dev,
      sock,
    };
  };

  static sref<mnode> get(u64 n);
  static sref<mnode> alloc(u8 type);

  void cache_pin(bool flag);
  u8 type() const;

  mdir* as_dir();
  const mdir* as_dir() const;
  mfile* as_file();
  const mfile* as_file() const;
  mdev* as_dev();
  const mdev* as_dev() const;
  msock* as_sock();
  const msock* as_sock() const;

  class linkcount : public refcache::referenced {
  public:
    linkcount() : refcache::referenced(0) {};
    void onzero() override;
  };

  const u64 inum_;
  linkcount nlink_;

protected:
  mnode(u64 inum);

private:
  void onzero() override;

  std::atomic<bool> cache_pin_;
  std::atomic<bool> dirty_;
  std::atomic<bool> valid_;
};

/*
 * An mlinkref represents a link count reference on an mnode.
 * The caller must ensure that mlinkref::acquire() is not called
 * after mnode::nlink_ reaches stable zero, perhaps by blocking
 * refcache epochs using cli when looking up the inode number in
 * a directory.
 *
 * Each mlinkref holds a reference to the mnode as well, to ensure
 * that the memory used to store the nlink_ count is not evicted
 * before all of the refcache deltas are flushed.  Otherwise this
 * would just be an sref<linkcount>.
 */
class mlinkref {
public:
  mlinkref() {}
  mlinkref(sref<mnode> mref) : m_(mref) {}

  sref<mnode> mn() {
    return m_;
  }

  bool held() {
    return !!l_;
  }

  /*
   * Increment the link count on the mnode.
   */
  void acquire() {
    assert(m_ && !l_);
    l_ = sref<mnode::linkcount>::newref(&m_->nlink_);
  }

  /*
   * Transfer an existing link count on the mnode to this mlinkref.
   */
  void transfer() {
    assert(m_ && !l_);
    l_ = sref<mnode::linkcount>::transfer(&m_->nlink_);
  }

private:
  /*
   * The order is important due to C++ constructor/destructor
   * rules: we must hold the mnode reference while manipulating
   * the linkcount reference.
   */
  sref<mnode> m_;
  sref<mnode::linkcount> l_;
};

class mdir : public mnode {
private:
  mdir(u64 inum) : mnode(inum), map_(257) {}
  NEW_DELETE_OPS(mdir);
  friend sref<mnode> mnode::get(u64);

  chainhash<strbuf<DIRSIZ>, u64> map_;

public:
  bool insert(const strbuf<DIRSIZ>& name, mlinkref* ilink) {
    if (name == ".")
      return false;
    if (!map_.insert(name, ilink->mn()->inum_))
      return false;
    assert(ilink->held());
    ilink->mn()->nlink_.inc();
    return true;
  }

  bool remove(const strbuf<DIRSIZ>& name, sref<mnode> m) {
    if (!map_.remove(name, m->inum_))
      return false;
    m->nlink_.dec();
    return true;
  }

  bool replace(const strbuf<DIRSIZ>& name, sref<mnode> mold, mlinkref* ilinknew) {
    if (!map_.replace(name, mold->inum_, ilinknew->mn()->inum_))
      return false;
    assert(ilinknew->held());
    ilinknew->mn()->nlink_.inc();
    mold->nlink_.dec();
    return true;
  }

  sref<mnode> lookup(const strbuf<DIRSIZ>& name) const {
    if (name == ".")
      return mnode::get(inum_);

    u64 iprev = -1;
    for (;;) {
      u64 inum;
      if (!map_.lookup(name, &inum))
        return sref<mnode>();

      sref<mnode> m = mnode::get(inum);
      if (m)
        return m;

      /*
       * The inode was GCed between the lookup and mnode::get().
       * Retry the lookup.  Crash if we repeatedly can't find
       * the same inode (to make such bugs easier to track down).
       */
      assert(inum != iprev);
      iprev = inum;
    }
  }

  mlinkref lookup_link(const strbuf<DIRSIZ>& name) const {
    if (name == ".")
      /*
       * We cannot convert the name "." to a link count on the mnode,
       * because "." does not hold a link count of its own.
       */
      return mlinkref();

    for (;;) {
      sref<mnode> m = lookup(name);
      if (!m)
        return mlinkref();

      scoped_cli cli;
      /*
       * Retry the lookup, now that we have an sref<mnode>, since
       * we don't want to do lookup's mnode::get() under cli.
       */
      u64 inum;
      if (!map_.lookup(name, &inum) || inum != m->inum_)
        /*
         * The name has either been unlinked or changed to point
         * to another inode.  Retry.
         */
        continue;

      mlinkref ilink(m);

      /*
       * At this point, we know the inode had a non-zero link
       * count prior to the second lookup.  Since we are holding
       * cli, refcache cannot advance its epoch, and will not
       * garbage-collect the inode until after we release cli.
       *
       * Mild POSIX violation: an inode can appear to have a
       * zero link count, according to fstat, but get a positive
       * link counter later, because the fstat occurs after the
       * last name has been unlinked, but before we increment
       * the link count here.
       */

      ilink.acquire();

      /*
       * Mild POSIX violation: an inode can appear to have a
       * link count, according to fstat, that is higher than
       * the number of all its names.  For instance, sys_link()
       * first grabs a mlinkref on the existing name, and then
       * drops it if the new name already exists.
       */

      return ilink;
    }
  }

  bool enumerate(const strbuf<DIRSIZ>* prev, strbuf<DIRSIZ>* name) const {
    if (!prev) {
      *name = ".";
      return true;
    }

    if (*prev == ".")
      prev = nullptr;

    return map_.enumerate(prev, name);
  }

  bool kill(sref<mnode> parent) {
    if (!map_.remove_and_kill("..", parent->inum_))
      return false;

    parent->nlink_.dec();
    return true;
  }

  bool killed() const {
    return map_.killed();
  }
};

inline mdir*
mnode::as_dir()
{
  assert(type() == types::dir);
  return static_cast<mdir*>(this);
}

inline const mdir*
mnode::as_dir() const
{
  assert(type() == types::dir);
  return static_cast<const mdir*>(this);
}

class mfile : public mnode {
private:
  mfile(u64 inum) : mnode(inum), size_(0) {}
  NEW_DELETE_OPS(mfile);
  friend sref<mnode> mnode::get(u64);

  struct page_state {
    enum {
      FLAG_LOCK_BIT = 0,
      FLAG_LOCK = 1 << FLAG_LOCK_BIT,
      FLAG_SET = 1 << 1,
    };

    page_state() : flags(0) {}
    page_state(sref<page_info> p) : flags(FLAG_SET), pg(p) {}

    bool is_set() const {
      return flags & FLAG_SET;
    }

    bit_spinlock get_lock() {
      return bit_spinlock(&flags, FLAG_LOCK_BIT);
    }

    u64 flags;
    sref<page_info> pg;
  };

  enum { maxidx = __SIZE_MAX__ / PGSIZE + 1 };
  radix_array<page_state, maxidx, PGSIZE,
              kalloc_allocator<page_state>> pages_;

  spinlock resize_lock_;
  seqcount<u32> size_seq_;
  u64 size_;

public:
  class resizer : public lock_guard<spinlock>,
                  public seq_writer {
  private:
    resizer(mfile* mf) : lock_guard<spinlock>(&mf->resize_lock_),
                         seq_writer(&mf->size_seq_),
                         mf_(mf) {}
    mfile* mf_;
    friend class mfile;

  public:
    resizer() : mf_(nullptr) {}
    explicit operator bool () const { return !!mf_; }
    u64 read_size() { return mf_->size_; }
    void resize_nogrow(u64 size);
    void resize_append(u64 size, sref<page_info> pi);
  };

  resizer write_size() {
    return resizer(this);
  }

  seq_reader<u64> read_size() {
    return seq_reader<u64>(&size_, &size_seq_);
  }

  sref<page_info> get_page(u64 pageidx);
};

inline mfile*
mnode::as_file()
{
  assert(type() == types::file);
  return static_cast<mfile*>(this);
}

inline const mfile*
mnode::as_file() const
{
  assert(type() == types::file);
  return static_cast<const mfile*>(this);
}

class mdev : public mnode {
private:
  mdev(u64 inum) : mnode(inum), major_(0), minor_(0) {}
  NEW_DELETE_OPS(mdev);
  friend sref<mnode> mnode::get(u64);

  u16 major_;
  u16 minor_;

public:
  u16 major() const { return major_; }
  u16 minor() const { return minor_; }

  void init(u16 major, u16 minor) {
    assert(!major_ && !minor_);
    major_ = major;
    minor_ = minor;
  }
};

inline mdev*
mnode::as_dev()
{
  assert(type() == types::dev);
  return static_cast<mdev*>(this);
}

inline const mdev*
mnode::as_dev() const
{
  assert(type() == types::dev);
  return static_cast<const mdev*>(this);
}

class msock : public mnode {
private:
  msock(u64 inum) : mnode(inum), localsock_(nullptr) {}
  NEW_DELETE_OPS(msock);
  friend sref<mnode> mnode::get(u64);

  localsock* localsock_;

public:
  localsock* get_sock() const { return localsock_; }

  void init(localsock* ls) {
    assert(!localsock_);
    localsock_ = ls;
  }
};

inline msock*
mnode::as_sock()
{
  assert(type() == types::sock);
  return static_cast<msock*>(this);
}

inline const msock*
mnode::as_sock() const
{
  assert(type() == types::sock);
  return static_cast<const msock*>(this);
}
<|endoftext|>


<commit_before>#include <cv.h>
#include <highgui.h>
#include <iostream>

using namespace cv;
using namespace std;

void help(){
    cout << "This is Crative Commons work, do what you like... " << endl;
    cout << "Usage: ./binary <image_name> " << endl;
    cout << "Hot keys: \n"
                "\tr/R toggle croping \n"
                "\tc/C toggle camera \n"
                "\ts/S toggle taking screenshoot\n"
                "\th/H toggle Hough Transform on screenshot\n"
                "\te/E toggle edge detetction \n"
                "\tt/T toggle template matching\n";
    }

void canny_edge();
void cannyTreshold( int, void* );
void cannyTreshold2( int, void* );
void init_camera();
void onMouse( int event, int x, int y, int flags, void* param );
void draw_box( Mat& img, Rect rect );
void crop_image( Mat& img, Rect rect );
void match_template_on_crop( int match_method, Mat& templ );
void getPoints( int event, int x, int y, int flags, void* param );
void savePoint( int x, int y );
void callHoughTransform( Mat& img, Rect rect );

Mat temp, mat_image, gray_image, frame, ss;
Mat templ, result, imgRoi, imgRoi2;
Mat dst, detected_edges;

Point pt1, pt2, pt3, pt4;
int n;
Rect box, box2;
bool drawing_box = false;
char ** global_argv;
int match_method = 0;
int lowThreshold;
int ratio = 3;
int const max_lowThreshold = 100;

int main(int argc, char** argv) {
    help();
    global_argv = argv;

    if (argc < 2) {
        cout << " Usage: "<< argv[0] <<" <image> " << endl;
        return -1;
    }

    char* imageName = argv[1];
    mat_image = imread( imageName, CV_LOAD_IMAGE_COLOR);

    if( !mat_image.data ) {
        cout << " Could not open or find the image" << endl;
        return -1;
    }

    while ( 1 ){
        namedWindow( imageName, CV_WINDOW_AUTOSIZE );
        imshow( imageName, mat_image );

        char c = waitKey(10);
        switch( c )
        {
            case 27:
                cout << "Exiting ... \n ";
                return 0;
            case 'e':
                canny_edge();
                break;
            case 'E':
                destroyWindow("canny edge");
                break;
            case 'r':
                cout << "Setting callback, calling crop_image  ...\n";
                setMouseCallback( imageName, onMouse, (void*)&mat_image );
                break;
            case 'R':
                destroyWindow( "ImgROI" );
                break;
            case 'c':
                init_camera();
                break;
            case 't':
                match_template_on_crop( 2, imgRoi );
                break;
            case 'T':
                destroyWindow( "source" );
                destroyWindow( "result" );
                break;
            case 'S':
                destroyWindow( "snapshot" );
                break;
            case 'h':
                callHoughTransform( ss, box2 );
                break;
        }
    }

    return 0;
}

void onMouse( int event, int x, int y, int flags, void* param ) {
    Mat& image = *(Mat*) param;
    switch( event )
    {
        case CV_EVENT_LBUTTONDOWN:
            drawing_box = true;
            box = Rect(x, y, 0, 0);
            break;
        case CV_EVENT_MOUSEMOVE:
            if( drawing_box ) {
                box.width = x-box.x;
                box.height = y-box.y;
            }
            break;
        case CV_EVENT_LBUTTONUP:
            drawing_box = false;
            if( box.width<0 ) {
                box.x+=box.width;
                box.width *= -1;
            }
            if( box.height<0 ) {
                box.y+=box.height;
                box.height*=-1;
            }
            cout << "box coordinates \n"
                << "x\t y\t height\t width\n"
                << box.x << "\t" << box.y << "\t"
                << box.height << "\t" << box.width << "\n";
            crop_image( image, box);
            draw_box( image, box );
            break;
    }
}

void draw_box( Mat& img, Rect rect ){
    rectangle( img, rect.tl(), rect.br(), Scalar(0,0,255));
}

void crop_image( Mat& img, Rect rect ){
    imgRoi = img( rect );
    namedWindow( "ImgROI", CV_WINDOW_AUTOSIZE );
    imshow( "ImgROI", imgRoi );
    /* gornji kod kopira samo header u imgRoi
     * ako treba kopirat i sliku moze se ovako:
    imgRoi.copyTo(temp);
    namedWindow( "temp", CV_WINDOW_AUTOSIZE );
    imshow( "temp", temp );
    */
}

void canny_edge(){
    cout << "calling canny... \n";
    cvtColor( mat_image, gray_image, CV_RGB2GRAY);
    namedWindow( "canny edge", CV_WINDOW_AUTOSIZE);
    createTrackbar( "Min Treshold: ", "canny edge", &lowThreshold, max_lowThreshold, cannyTreshold );
}

void cannyTreshold( int, void* ){
    Canny( gray_image, detected_edges, lowThreshold, lowThreshold*ratio, 3 );
    dst = Scalar::all(0);
    gray_image.copyTo( dst, detected_edges);
    imshow( "canny edge", dst);
}

void init_camera(){
    cout << "Starting camera mode... \n";
    VideoCapture cap(0);
    if( !cap.isOpened() ){
        cerr << "fail preko default camere \n";
        cout << "isprobavam argv2 "
            << global_argv[2] << endl;
        cap.open( global_argv[2] );
        if( !cap.isOpened() ){
            cerr << "fail i preko argv[2] \n";
        }
    }
    while( 1 ){
        cap >> frame;
        if(!frame.data) break;
        namedWindow( "camera", CV_WINDOW_AUTOSIZE );
        imshow( "camera", frame );
        char c = waitKey(10);
        if( c == 'C' ){
            destroyWindow("camera");
            break;
        }
        switch ( c ) {
            case 's':
                frame.copyTo( ss );
                namedWindow( "snapshot", CV_WINDOW_AUTOSIZE );
                imshow( "snapshot", ss );
                cout << " Setting MouseCallback getPoints " << endl;
                setMouseCallback( "snapshot", getPoints, 0 );
                break;
        }
    }
}

void match_template_on_crop( int match_method, Mat& templ ){
    /// Source image to display
    Mat img_display;
    mat_image.copyTo( img_display );

    /// Create the result matrix
    int result_cols =  mat_image.cols - templ.cols + 1;
    int result_rows = mat_image.rows - templ.rows + 1;

    result.create( result_cols, result_rows, CV_32FC1 );

    /// Do the Matching and Normalize
    matchTemplate( mat_image, templ, result, match_method );
    normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

    /// Localizing the best match with minMaxLoc
    double minVal; double maxVal; Point minLoc; Point maxLoc;
    Point matchLoc;

    minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

    /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
    if( match_method  == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
    else
    { matchLoc = maxLoc; }

    /// Show me what you got
    rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
    rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );

    namedWindow( "source", CV_WINDOW_AUTOSIZE );
    namedWindow( "result", CV_WINDOW_AUTOSIZE );
    imshow( "source", img_display );
    imshow( "result", result );
}

void savePoint( int x, int y ){
    n++;
    if ( n == 1 ){
        pt1.x = x;
        pt1.y = y;
        cout << pt1.x << " " << pt1.y << endl;
    }
    if ( n == 2 ){
        pt2.x = x;
        pt2.y = y;
        cout << pt2.x << " " << pt2.y << endl;
    }
    if ( n == 3 ){
        pt3.x = x;
        pt3.y = y;
        cout << pt3.x << " " << pt3.y << endl;
    }
    if ( n == 4 ){
        pt4.x = x;
        pt4.y = y;
        box2.x = pt1.x;
        box2.y = pt1.y;
        box2.width = pt4.x - box2.x;
        box2.height = pt4.y - box2.y;
        cout << pt4.x << " " << pt4.y << endl;
        cout << box2.width << " " << box2.height << endl;
    }
}

void getPoints( int event, int x, int y, int flags, void* param ) {
    switch( event ) {
        case CV_EVENT_LBUTTONDOWN:
                break;
        case CV_EVENT_LBUTTONUP:
                savePoint( x, y );
                break;
         }
}
void cannyTreshold2( int, void* ){
    Canny( temp, detected_edges, lowThreshold, lowThreshold*ratio, 3 );
    dst = Scalar::all(0);
    imgRoi2.copyTo( dst, detected_edges);
    imshow( "imageRoi2", dst);
}

void callHoughTransform( Mat& img, Rect rect ){
    imgRoi2 = img( rect );
    cvtColor( imgRoi2, temp, CV_RGB2GRAY);
    namedWindow( "imageRoi2", CV_WINDOW_AUTOSIZE);
    createTrackbar( "Min Treshold: ", "imageRoi2", &lowThreshold, max_lowThreshold, cannyTreshold2 );

/*    cvtColor( imgRoi2, temp, CV_RGB2GRAY );
    Canny( temp, temp, 50, 100, 3 );
    namedWindow( "ImgRoi2", CV_WINDOW_AUTOSIZE );
    imshow( "ImgRoi2", temp ); */
    vector<Vec2f> lines;
    HoughLines(temp, lines, 1, CV_PI/180, 100, 0, 0 );
    /*
    temp: Output of the edge detector.
    lines: A vector that will store the parameters (r,\theta) of the detected lines
    rho : The resolution of the parameter r in pixels. We use 1 pixel.
    theta: The resolution of the parameter \theta in radians. We use 1 degree (CV_PI/180)
    threshold: The minimum number of intersections to “detect” a line
    srn and stn: Default parameters to zero. Check OpenCV reference for more info.
    */
    // izvuci prvu linija, koja bi trebala vektor od dva elementa
    // ro'' i theta
    // prebacit ro u k.s. slike a ne ROI ro=ro'' +pt1.x*cos theta +
    //                                          +pt1.y*sin theta
    // findExtrinsci, predat xml, vraca R koji treba konvertirit u 3*3 pogledi rodrigez,
    // pomonzit R i P(iz xml, camera matrix) jedanko A
    // pomnozit t i P dobijemo B
    // dobijemo lamde
    //
    //
/*    Mat cdst;
    imgRoi2.copyTo( cdst );
    for( size_t i = 0; i < lines.size(); i++ )
    {
        float rho2 = lines[i][0], theta = lines[i][1];
        Point pt1, pt2;
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho2, y0 = b*rho2;
        pt1.x = cvRound(x0 + 1000*(-b));
        pt1.y = cvRound(y0 + 1000*(a));
        pt2.x = cvRound(x0 - 1000*(-b));
        pt2.y = cvRound(y0 - 1000*(a));
        line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
    }
    imshow("detected lines", cdst);
/*
    float rho_crtano = lines[0][0], theta = lines[0][1];
    float rho;
    rho = rho_crtano + pt1.x * cos( theta ) + pt1.y * sin( theta );

    FileStorage fs("calib/cam.xml", FileStorage::READ);
    cout << "procitao " << endl;
    Mat intrinsics, distortion;
    fs["camera_matrix"] >> intrinsics; //3*3
    fs["distortion_coefficients"] >> distortion; //4*1, kod mene 5*1
*/

}
<commit_msg>dodani object i image points<commit_after>#include <cv.h>
#include <highgui.h>
#include <iostream>

using namespace cv;
using namespace std;

void help(){
    cout << "This is Crative Commons work, do what you like... " << endl;
    cout << "Usage: ./binary <image_name> " << endl;
    cout << "Hot keys: \n"
                "\tr/R toggle croping \n"
                "\tc/C toggle camera \n"
                "\ts/S toggle taking screenshoot\n"
                "\th/H toggle Hough Transform on screenshot\n"
                "\te/E toggle edge detetction \n"
                "\tt/T toggle template matching\n";
    }

void canny_edge();
void cannyTreshold( int, void* );
void cannyTreshold2( int, void* );
void init_camera();
void onMouse( int event, int x, int y, int flags, void* param );
void draw_box( Mat& img, Rect rect );
void crop_image( Mat& img, Rect rect );
void match_template_on_crop( int match_method, Mat& templ );
void getPoints( int event, int x, int y, int flags, void* param );
void savePoint( int x, int y );
void callHoughTransform( );
void cannyForHT( Mat& img, Rect rect );

Mat temp, mat_image, gray_image, frame, ss;
Mat templ, result, imgRoi, imgRoi2;
Mat dst, detected_edges;

Point pt1, pt2, pt3, pt4;
vector<Point2f> imagePoints(4);
int n;
Rect box, box2;
bool drawing_box = false;
char ** global_argv;
int match_method = 0;
int lowThreshold;
int ratio = 3;
int const max_lowThreshold = 100;

int main(int argc, char** argv) {
    help();
    global_argv = argv;

    if (argc < 2) {
        cout << " Usage: "<< argv[0] <<" <image> " << endl;
        return -1;
    }

    char* imageName = argv[1];
    mat_image = imread( imageName, CV_LOAD_IMAGE_COLOR);

    if( !mat_image.data ) {
        cout << " Could not open or find the image" << endl;
        return -1;
    }

    while ( 1 ){
        namedWindow( imageName, CV_WINDOW_AUTOSIZE );
        imshow( imageName, mat_image );

        char c = waitKey(10);
        switch( c )
        {
            case 27:
                cout << "Exiting ... \n ";
                return 0;
            case 'e':
                canny_edge();
                break;
            case 'E':
                destroyWindow("canny edge");
                break;
            case 'r':
                cout << "Setting callback, calling crop_image  ...\n";
                setMouseCallback( imageName, onMouse, (void*)&mat_image );
                break;
            case 'R':
                destroyWindow( "ImgROI" );
                break;
            case 'c':
                init_camera();
                break;
            case 't':
                match_template_on_crop( 2, imgRoi );
                break;
            case 'T':
                destroyWindow( "source" );
                destroyWindow( "result" );
                break;
            case 'S':
                destroyWindow( "snapshot" );
                break;
            case 'h':
                cannyForHT( ss, box2 );
                //callHoughTransform( ss, box2 );
                break;
            case 'H':
                callHoughTransform( );
                break;
        }
    }

    return 0;
}

void onMouse( int event, int x, int y, int flags, void* param ) {
    Mat& image = *(Mat*) param;
    switch( event )
    {
        case CV_EVENT_LBUTTONDOWN:
            drawing_box = true;
            box = Rect(x, y, 0, 0);
            break;
        case CV_EVENT_MOUSEMOVE:
            if( drawing_box ) {
                box.width = x-box.x;
                box.height = y-box.y;
            }
            break;
        case CV_EVENT_LBUTTONUP:
            drawing_box = false;
            if( box.width<0 ) {
                box.x+=box.width;
                box.width *= -1;
            }
            if( box.height<0 ) {
                box.y+=box.height;
                box.height*=-1;
            }
            cout << "box coordinates \n"
                << "x\t y\t height\t width\n"
                << box.x << "\t" << box.y << "\t"
                << box.height << "\t" << box.width << "\n";
            crop_image( image, box);
            draw_box( image, box );
            break;
    }
}

void draw_box( Mat& img, Rect rect ){
    rectangle( img, rect.tl(), rect.br(), Scalar(0,0,255));
}

void crop_image( Mat& img, Rect rect ){
    imgRoi = img( rect );
    namedWindow( "ImgROI", CV_WINDOW_AUTOSIZE );
    imshow( "ImgROI", imgRoi );
    /* gornji kod kopira samo header u imgRoi
     * ako treba kopirat i sliku moze se ovako:
    imgRoi.copyTo(temp);
    namedWindow( "temp", CV_WINDOW_AUTOSIZE );
    imshow( "temp", temp );
    */
}

void canny_edge(){
    cout << "calling canny... \n";
    cvtColor( mat_image, gray_image, CV_RGB2GRAY);
    namedWindow( "canny edge", CV_WINDOW_AUTOSIZE);
    createTrackbar( "Min Treshold: ", "canny edge", &lowThreshold, max_lowThreshold, cannyTreshold );
}

void cannyTreshold( int, void* ){
    Canny( gray_image, detected_edges, lowThreshold, lowThreshold*ratio, 3 );
    dst = Scalar::all(0);
    gray_image.copyTo( dst, detected_edges);
    imshow( "canny edge", dst);
}

void init_camera(){
    cout << "Starting camera mode... \n";
    VideoCapture cap(0);
    if( !cap.isOpened() ){
        cerr << "fail preko default camere \n";
        cout << "isprobavam argv2 "
            << global_argv[2] << endl;
        cap.open( global_argv[2] );
        if( !cap.isOpened() ){
            cerr << "fail i preko argv[2] \n";
        }
    }
    while( 1 ){
        cap >> frame;
        if(!frame.data) break;
        namedWindow( "camera", CV_WINDOW_AUTOSIZE );
        imshow( "camera", frame );
        char c = waitKey(10);
        if( c == 'C' ){
            destroyWindow("camera");
            break;
        }
        switch ( c ) {
            case 's':
                frame.copyTo( ss );
                namedWindow( "snapshot", CV_WINDOW_AUTOSIZE );
                imshow( "snapshot", ss );
                cout << " Setting MouseCallback getPoints " << endl;
                setMouseCallback( "snapshot", getPoints, 0 );
                break;
        }
    }
}

void match_template_on_crop( int match_method, Mat& templ ){
    /// Source image to display
    Mat img_display;
    mat_image.copyTo( img_display );

    /// Create the result matrix
    int result_cols =  mat_image.cols - templ.cols + 1;
    int result_rows = mat_image.rows - templ.rows + 1;

    result.create( result_cols, result_rows, CV_32FC1 );

    /// Do the Matching and Normalize
    matchTemplate( mat_image, templ, result, match_method );
    normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

    /// Localizing the best match with minMaxLoc
    double minVal; double maxVal; Point minLoc; Point maxLoc;
    Point matchLoc;

    minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

    /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
    if( match_method  == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
    else
    { matchLoc = maxLoc; }

    /// Show me what you got
    rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
    rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );

    namedWindow( "source", CV_WINDOW_AUTOSIZE );
    namedWindow( "result", CV_WINDOW_AUTOSIZE );
    imshow( "source", img_display );
    imshow( "result", result );
}

void savePoint( int x, int y ){
    n++;
    if ( n == 1 ){
        pt1.x = x;
        pt1.y = y;
        imagePoints[0] = Point2f( x, y );
        cout << pt1.x << " " << pt1.y << endl;
    }
    if ( n == 2 ){
        pt2.x = x;
        pt2.y = y;
        imagePoints[1] = Point2f( x, y );
        cout << pt2.x << " " << pt2.y << endl;
    }
    if ( n == 3 ){
        pt3.x = x;
        pt3.y = y;
        imagePoints[2] = Point2f( x, y );
        cout << pt3.x << " " << pt3.y << endl;
    }
    if ( n == 4 ){
        pt4.x = x;
        pt4.y = y;
        imagePoints[3] = Point2f( x, y );
        box2.x = pt1.x;
        box2.y = pt1.y;
        box2.width = pt4.x - box2.x;
        box2.height = pt4.y - box2.y;
        cout << pt4.x << " " << pt4.y << endl;
        cout << box2.width << " " << box2.height << endl;
    }
}

void getPoints( int event, int x, int y, int flags, void* param ) {
    switch( event ) {
        case CV_EVENT_LBUTTONDOWN:
                break;
        case CV_EVENT_LBUTTONUP:
                savePoint( x, y );
                break;
         }
}
void cannyTreshold2( int, void* ){
    Canny( temp, detected_edges, lowThreshold, lowThreshold*ratio, 3 );
    dst = Scalar::all(0);
    temp.copyTo( dst, detected_edges);
    imshow( "imageRoi2", dst);
}

void cannyForHT( Mat& img, Rect rect ){
    imgRoi2 = img( rect );
    cvtColor( imgRoi2, temp, CV_RGB2GRAY);
    namedWindow( "imageRoi2", CV_WINDOW_AUTOSIZE);
    createTrackbar( "Min Treshold: ", "imageRoi2", &lowThreshold, max_lowThreshold, cannyTreshold2 );
}

void callHoughTransform( ){
    vector<Vec2f> lines;
    HoughLines( temp, lines, 1, CV_PI/180, 100, 0, 0 );
    // temp nije output edge detectora, treba izmjeniti
    /*
    temp: Output of the edge detector.
    lines: A vector that will store the parameters (r,\theta) of the detected lines
    */
    // izvuci prvu linija, koja bi trebala vektor od dva elementa
    // ro'' i theta
    // prebacit ro u k.s. slike a ne ROI ro=ro'' +pt1.x*cos theta +
    //                                          +pt1.y*sin theta
    // findExtrinsci, predat xml, vraca R koji treba konvertirit u 3*3 pogledi rodrigez,
    // pomonzit R i P(iz xml, camera matrix) jedanko A
    // pomnozit t i P dobijemo B
    // dobijemo lamde
    //
    float rho, rho_roi, theta;
    rho_roi= lines[0][0];
    theta = lines[0][1];
    // prebacivanje u k.s. slike
    rho = rho_roi + pt1.x * cos( theta ) + pt1.y * sin( theta );

    // ucitavanje
    FileStorage fs("calib/cam.xml", FileStorage::READ);
    cout << "procitao " << rho << " " << theta << endl;
    Mat intrinsics, distortion;
    fs["camera_matrix"] >> intrinsics; //3*3
    fs["distortion_coefficients"] >> distortion; //4*1, kod mene 5*1
    cout << "idemo dalj" << endl;

    vector<Point3f> objectPoints(4);
    objectPoints[0] = Point3f( 0, 0, 0 );
    objectPoints[1] = Point3f( 0, 0, 0 );
    objectPoints[2] = Point3f( 0, 0, 0 );
    objectPoints[3] = Point3f( 0, 0, 0 );
    cout << "A vector of 3D Object Points = " << objectPoints << endl << endl;
    cout << "A vector of 2D Image Points = " << imagePoints << endl << endl;

    //cvFindExtrinsicCameraParams2() je zamjenjen s solvePnP()
    //solvePnP(Mat(objectPoints), Mat(imagePoints), intrinsics, distortion, rvec, tvec, false);

}
<|endoftext|>


<commit_before>#include "connection_manager.hpp"
#include "karabiner_version.h"
#include "logger.hpp"

int main(int argc, const char* argv[]) {
  signal(SIGUSR1, SIG_IGN);
  signal(SIGUSR2, SIG_IGN);

  logger::get_logger().info("version {0}", karabiner_version);

  connection_manager manager;

  CFRunLoopRun();
  return 0;
}
<commit_msg>create configuration directory at launch<commit_after>#include "connection_manager.hpp"
#include "karabiner_version.h"
#include "logger.hpp"
#include "constants.hpp"

int main(int argc, const char* argv[]) {
  signal(SIGUSR1, SIG_IGN);
  signal(SIGUSR2, SIG_IGN);

  logger::get_logger().info("version {0}", karabiner_version);

  mkdir(constants::get_configuration_directory(), 0700);

  connection_manager manager;

  CFRunLoopRun();
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <utils/LibCvTools/random_generator.hpp>
#include <vector>
#include <set>

namespace files {

inline bool create_on_check(const std::string &path)
{
    if(!boost::filesystem3::exists(path)) {
        std::cout << "Directory is not existing, therefore creating it as sub dir!" << std::endl;
        if(!boost::filesystem3::create_directories(path)) {
            std::cerr << "Cannot create directory '" << path << "' !" << std::endl;
            return false;
        }
    }
    return true;
}

inline bool read_yml_img(const std::string &path, std::vector<std::string> &imgs, std::vector<std::string> &ymls)
{
    boost::regex e_yaml(".*\\.(yml)");
    boost::regex e_jpg(".*\\.(jpg)");
    if(boost::filesystem3::is_directory(path)) {
        boost::filesystem3::directory_iterator end_iter;
        for(boost::filesystem3::directory_iterator dir_itr( path ); dir_itr != end_iter; ++dir_itr) {
            try {
                boost::cmatch what;
                if (boost::filesystem3::is_regular_file( dir_itr->status())) {
                    std::string current = dir_itr->path().string();
                    if(boost::regex_match(current.c_str(), what, e_yaml) && what[0].matched) {
                        ymls.push_back(current);
                    }
                    if(boost::regex_match(current.c_str(), what, e_jpg) && what[0].matched) {
                        imgs.push_back(current);
                    }
                }
            }
            catch ( const std::exception & ex ){
                std::cerr << dir_itr->path().filename() << " " << ex.what() << std::endl;
            }
        }
    }

    return imgs.size() > 0 && imgs.size() == ymls.size();
}

}

int main(int argc, char *argv[])
{
    std::string path = boost::filesystem3::current_path().string();

    if(argc < 3 ) {
        std::cout << "Arguments : [<src path>] <train set> <validation set>" << std::endl;
        return 1;
    }

    std::string path_train = argv[1];
    std::string path_valid = argv[2];
    if(argc == 4) {
        path        = argv[1];
        path_train  = argv[2];
        path_valid  = argv[3];
    }

    if(path_train == "" || path_valid == "") {
        std::cerr << "Path length was 0 !" << std::endl;
        return 1;
    }

    if(path_train[path_train.length() - 1] != '/')
        path_train += '/';

    if(path_valid[path_valid.length() - 1] != '/')
        path_valid += '/';

    if(!files::create_on_check(path_train))
        return 1;
    if(!files::create_on_check(path_valid))
        return 1;

    std::vector<std::string> img_paths;
    std::vector<std::string> yml_paths;
    if(!files::read_yml_img(path, img_paths, yml_paths) || yml_paths.size() == 0 || img_paths.size() == 0) {
        std::cerr << "Directory not readable, no files given or the amount of .yml and .img files is not matching!" << std::endl;
        if(yml_paths.size() == 0) {
            std::cerr << "No yml paths found !" << std::endl;
        }

        if(img_paths.size() == 0) {
            std::cout << "No images where found!" << std::endl;
        }
        return 1;
    }

    std::sort(yml_paths.begin(), yml_paths.end());
    std::sort(img_paths.begin(), img_paths.end());

    /// SAMPLE 30% TRAIN DATA AND 70% VALIDATION DATA

    std::set<int>  sample_indeces;
    int sample_elements = .3 * img_paths.size();
    RandomGeneratorInt         generator(0, img_paths.size() - 1);
    while(sample_indeces.size() < sample_elements) {
        sample_indeces.insert(generator.generate());
    }

    std::vector<std::string> train_images;
    for(std::set<int>::iterator it = sample_indeces.begin() ; it != sample_indeces.end() ; ++it) {
        train_images.push_back(img_paths[*it]);
     }

    for(std::set<int>::iterator it = sample_indeces.begin() ; it != sample_indeces.end() ; ++it) {
        img_paths.erase(img_paths.begin() + *it);
        yml_paths.erase(yml_paths.begin() + *it);
    }

    /// DO THE COPY STUFF
    /// TRAIN
    for(std::vector<std::string>::iterator it = train_images.begin() ; it != train_images.end() ; ++it) {
        boost::filesystem3::path src(*it);
        boost::filesystem3::path dst(path_train + src.filename().string());
        boost::filesystem3::copy_file(src, dst, boost::filesystem3::copy_option::overwrite_if_exists);
    }

    for(int i = 0 ; i < img_paths.size() ; ++i) {
        boost::filesystem3::path src_img(img_paths[i]);
        boost::filesystem3::path src_yml(yml_paths[i]);
        boost::filesystem3::path dst_img(path_valid + src_img.filename().string());
        boost::filesystem3::path dst_yml(path_valid + src_yml.filename().string());
        boost::filesystem3::copy_file(src_img, dst_img, boost::filesystem3::copy_option::overwrite_if_exists);
        boost::filesystem3::copy_file(src_yml, dst_yml, boost::filesystem3::copy_option::overwrite_if_exists);

    }

    std::cout << "Sets were generated!" << std::endl;
    return 0;
}

<commit_msg>fix<commit_after>#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <utils/LibCvTools/random_generator.hpp>
#include <vector>
#include <set>

namespace files {

inline bool create_on_check(const std::string &path)
{
    if(!boost::filesystem3::exists(path)) {
        std::cout << "Directory is not existing, therefore creating it as sub dir!" << std::endl;
        if(!boost::filesystem3::create_directories(path)) {
            std::cerr << "Cannot create directory '" << path << "' !" << std::endl;
            return false;
        }
    }
    return true;
}

inline bool read_yml_img(const std::string &path, std::vector<std::string> &imgs, std::vector<std::string> &ymls)
{
    boost::regex e_yaml(".*\\.(yml)");
    boost::regex e_jpg(".*\\.(jpg)");
    if(boost::filesystem3::is_directory(path)) {
        boost::filesystem3::directory_iterator end_iter;
        for(boost::filesystem3::directory_iterator dir_itr( path ); dir_itr != end_iter; ++dir_itr) {
            try {
                boost::cmatch what;
                if (boost::filesystem3::is_regular_file( dir_itr->status())) {
                    std::string current = dir_itr->path().string();
                    if(boost::regex_match(current.c_str(), what, e_yaml) && what[0].matched) {
                        ymls.push_back(current);
                    }
                    if(boost::regex_match(current.c_str(), what, e_jpg) && what[0].matched) {
                        imgs.push_back(current);
                    }
                }
            }
            catch ( const std::exception & ex ){
                std::cerr << dir_itr->path().filename() << " " << ex.what() << std::endl;
            }
        }
    }

    return imgs.size() > 0 && imgs.size() == ymls.size();
}

}

int main(int argc, char *argv[])
{
    std::string path = boost::filesystem3::current_path().string();

    if(argc < 3 ) {
        std::cout << "Arguments : [<src path>] <train set> <validation set>" << std::endl;
        return 1;
    }

    std::string path_train = argv[1];
    std::string path_valid = argv[2];
    if(argc == 4) {
        path        = argv[1];
        path_train  = argv[2];
        path_valid  = argv[3];
    }

    if(path_train == "" || path_valid == "") {
        std::cerr << "Path length was 0 !" << std::endl;
        return 1;
    }

    if(path_train[path_train.length() - 1] != '/')
        path_train += '/';

    if(path_valid[path_valid.length() - 1] != '/')
        path_valid += '/';

    if(!files::create_on_check(path_train))
        return 1;
    if(!files::create_on_check(path_valid))
        return 1;

    std::vector<std::string> img_paths;
    std::vector<std::string> yml_paths;
    if(!files::read_yml_img(path, img_paths, yml_paths) || yml_paths.size() == 0 || img_paths.size() == 0) {
        std::cerr << "Directory not readable, no files given or the amount of .yml and .img files is not matching!" << std::endl;
        if(yml_paths.size() == 0) {
            std::cerr << "No yml paths found !" << std::endl;
        }

        if(img_paths.size() == 0) {
            std::cout << "No images where found!" << std::endl;
        }
        return 1;
    }

    std::sort(yml_paths.begin(), yml_paths.end());
    std::sort(img_paths.begin(), img_paths.end());

    /// SAMPLE 70% TRAIN DATA AND 30% VALIDATION DATA

    std::set<int>  sample_indeces;
    int sample_elements = .3 * img_paths.size();
    RandomGeneratorInt         generator(0, img_paths.size() - 1);
    while(sample_indeces.size() < sample_elements) {
        sample_indeces.insert(generator.generate());
    }

    std::vector<std::string> train_images;
    for(std::set<int>::iterator it = sample_indeces.begin() ; it != sample_indeces.end() ; ++it) {
        train_images.push_back(img_paths[*it]);
     }

    for(std::set<int>::iterator it = sample_indeces.begin() ; it != sample_indeces.end() ; ++it) {
        img_paths.erase(img_paths.begin() + *it);
        yml_paths.erase(yml_paths.begin() + *it);
    }

    /// DO THE COPY STUFF
    /// TRAIN
    for(std::vector<std::string>::iterator it = train_images.begin() ; it != train_images.end() ; ++it) {
        boost::filesystem3::path src(*it);
        boost::filesystem3::path dst(path_train + src.filename().string());
        boost::filesystem3::copy_file(src, dst, boost::filesystem3::copy_option::overwrite_if_exists);
    }

    for(int i = 0 ; i < img_paths.size() ; ++i) {
        boost::filesystem3::path src_img(img_paths[i]);
        boost::filesystem3::path src_yml(yml_paths[i]);
        boost::filesystem3::path dst_img(path_valid + src_img.filename().string());
        boost::filesystem3::path dst_yml(path_valid + src_yml.filename().string());
        boost::filesystem3::copy_file(src_img, dst_img, boost::filesystem3::copy_option::overwrite_if_exists);
        boost::filesystem3::copy_file(src_yml, dst_yml, boost::filesystem3::copy_option::overwrite_if_exists);

    }

    std::cout << "Sets were generated!" << std::endl;
    return 0;
}

<|endoftext|>


<commit_before>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the X86 specific subclass of TargetMachine.
//
//===----------------------------------------------------------------------===//

#include "X86TargetMachine.h"
#include "X86.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;

X86VectorEnum llvm::X86Vector = NoSSE;

/// X86TargetMachineModule - Note that this is used on hosts that cannot link
/// in a library unless there are references into the library.  In particular,
/// it seems that it is not possible to get things to work on Win32 without
/// this.  Though it is unused, do not remove it.
extern "C" int X86TargetMachineModule;
int X86TargetMachineModule = 0;

namespace {
  cl::opt<bool> NoSSAPeephole("disable-ssa-peephole", cl::init(true),
                        cl::desc("Disable the ssa-based peephole optimizer "
                                 "(defaults to disabled)"));
  cl::opt<bool> DisableOutput("disable-x86-llc-output", cl::Hidden,
                              cl::desc("Disable the X86 asm printer, for use "
                                       "when profiling the code generator."));

#if 0
  // FIXME: This should eventually be handled with target triples and
  // subtarget support!
  cl::opt<X86VectorEnum, true>
  SSEArg(
    cl::desc("Enable SSE support in the X86 target:"),
    cl::values(
       clEnumValN(SSE,  "sse", "  Enable SSE support"),
       clEnumValN(SSE2, "sse2", "  Enable SSE and SSE2 support"),
       clEnumValN(SSE3, "sse3", "  Enable SSE, SSE2, and SSE3 support"),
       clEnumValEnd),
    cl::location(X86Vector), cl::init(NoSSE));
#endif

  // Register the target.
  RegisterTarget<X86TargetMachine> X("x86", "  IA-32 (Pentium and above)");
}

unsigned X86TargetMachine::getJITMatchQuality() {
#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)
  return 10;
#else
  return 0;
#endif
}

unsigned X86TargetMachine::getModuleMatchQuality(const Module &M) {
  // We strongly match "i[3-9]86-*".
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
      TT[4] == '-' && TT[1] - '3' < 6)
    return 20;

  if (M.getEndianness()  == Module::LittleEndian &&
      M.getPointerSize() == Module::Pointer32)
    return 10;                                   // Weak match
  else if (M.getEndianness() != Module::AnyEndianness ||
           M.getPointerSize() != Module::AnyPointerSize)
    return 0;                                    // Match for some other target

  return getJITMatchQuality()/2;
}

/// X86TargetMachine ctor - Create an ILP32 architecture model
///
X86TargetMachine::X86TargetMachine(const Module &M, IntrinsicLowering *IL)
  : TargetMachine("X86", IL, true, 4, 4, 4, 4, 4),
    FrameInfo(TargetFrameInfo::StackGrowsDown, 8, -4),
    JITInfo(*this) {
}

// addPassesToEmitAssembly - We currently use all of the same passes as the JIT
// does to emit statically compiled machine code.
bool X86TargetMachine::addPassesToEmitAssembly(PassManager &PM,
					       std::ostream &Out) {
  // FIXME: Implement efficient support for garbage collection intrinsics.
  PM.add(createLowerGCPass());

  // FIXME: Implement the invoke/unwind instructions!
  PM.add(createLowerInvokePass());

  // FIXME: Implement the switch instruction in the instruction selector!
  PM.add(createLowerSwitchPass());

  // Make sure that no unreachable blocks are instruction selected.
  PM.add(createUnreachableBlockEliminationPass());

  PM.add(createX86SimpleInstructionSelector(*this));

  // Run optional SSA-based machine code optimizations next...
  if (!NoSSAPeephole)
    PM.add(createX86SSAPeepholeOptimizerPass());

  // Print the instruction selected machine code...
  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  // Perform register allocation to convert to a concrete x86 representation
  PM.add(createRegisterAllocator());

  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  PM.add(createX86FloatingPointStackifierPass());

  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  // Insert prolog/epilog code.  Eliminate abstract frame index references...
  PM.add(createPrologEpilogCodeInserter());

  PM.add(createX86PeepholeOptimizerPass());

  if (PrintMachineCode)  // Print the register-allocated code
    PM.add(createX86CodePrinterPass(std::cerr, *this));

  if (!DisableOutput)
    PM.add(createX86CodePrinterPass(Out, *this));

  // Delete machine code for this function
  PM.add(createMachineCodeDeleter());

  return false; // success!
}

/// addPassesToJITCompile - Add passes to the specified pass manager to
/// implement a fast dynamic compiler for this target.  Return true if this is
/// not supported for this target.
///
void X86JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {
  // FIXME: Implement efficient support for garbage collection intrinsics.
  PM.add(createLowerGCPass());

  // FIXME: Implement the invoke/unwind instructions!
  PM.add(createLowerInvokePass());

  // FIXME: Implement the switch instruction in the instruction selector!
  PM.add(createLowerSwitchPass());

  // Make sure that no unreachable blocks are instruction selected.
  PM.add(createUnreachableBlockEliminationPass());

  PM.add(createX86SimpleInstructionSelector(TM));

  // Run optional SSA-based machine code optimizations next...
  if (!NoSSAPeephole)
    PM.add(createX86SSAPeepholeOptimizerPass());

  // FIXME: Add SSA based peephole optimizer here.

  // Print the instruction selected machine code...
  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  // Perform register allocation to convert to a concrete x86 representation
  PM.add(createRegisterAllocator());

  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  PM.add(createX86FloatingPointStackifierPass());

  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  // Insert prolog/epilog code.  Eliminate abstract frame index references...
  PM.add(createPrologEpilogCodeInserter());

  PM.add(createX86PeepholeOptimizerPass());

  if (PrintMachineCode)  // Print the register-allocated code
    PM.add(createX86CodePrinterPass(std::cerr, TM));
}

<commit_msg>Allow the selection-dag based selector to be diabled with -disable-pattern-isel.<commit_after>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the X86 specific subclass of TargetMachine.
//
//===----------------------------------------------------------------------===//

#include "X86TargetMachine.h"
#include "X86.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;

X86VectorEnum llvm::X86Vector = NoSSE;

/// X86TargetMachineModule - Note that this is used on hosts that cannot link
/// in a library unless there are references into the library.  In particular,
/// it seems that it is not possible to get things to work on Win32 without
/// this.  Though it is unused, do not remove it.
extern "C" int X86TargetMachineModule;
int X86TargetMachineModule = 0;

namespace {
  cl::opt<bool> NoSSAPeephole("disable-ssa-peephole", cl::init(true),
                        cl::desc("Disable the ssa-based peephole optimizer "
                                 "(defaults to disabled)"));
  cl::opt<bool> DisableOutput("disable-x86-llc-output", cl::Hidden,
                              cl::desc("Disable the X86 asm printer, for use "
                                       "when profiling the code generator."));
  cl::opt<bool> DisablePatternISel("disable-pattern-isel", cl::Hidden,
                                 cl::desc("Disable the pattern isel XXX FIXME"),
                                   cl::init(true));

#if 0
  // FIXME: This should eventually be handled with target triples and
  // subtarget support!
  cl::opt<X86VectorEnum, true>
  SSEArg(
    cl::desc("Enable SSE support in the X86 target:"),
    cl::values(
       clEnumValN(SSE,  "sse", "  Enable SSE support"),
       clEnumValN(SSE2, "sse2", "  Enable SSE and SSE2 support"),
       clEnumValN(SSE3, "sse3", "  Enable SSE, SSE2, and SSE3 support"),
       clEnumValEnd),
    cl::location(X86Vector), cl::init(NoSSE));
#endif

  // Register the target.
  RegisterTarget<X86TargetMachine> X("x86", "  IA-32 (Pentium and above)");
}

unsigned X86TargetMachine::getJITMatchQuality() {
#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)
  return 10;
#else
  return 0;
#endif
}

unsigned X86TargetMachine::getModuleMatchQuality(const Module &M) {
  // We strongly match "i[3-9]86-*".
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
      TT[4] == '-' && TT[1] - '3' < 6)
    return 20;

  if (M.getEndianness()  == Module::LittleEndian &&
      M.getPointerSize() == Module::Pointer32)
    return 10;                                   // Weak match
  else if (M.getEndianness() != Module::AnyEndianness ||
           M.getPointerSize() != Module::AnyPointerSize)
    return 0;                                    // Match for some other target

  return getJITMatchQuality()/2;
}

/// X86TargetMachine ctor - Create an ILP32 architecture model
///
X86TargetMachine::X86TargetMachine(const Module &M, IntrinsicLowering *IL)
  : TargetMachine("X86", IL, true, 4, 4, 4, 4, 4),
    FrameInfo(TargetFrameInfo::StackGrowsDown, 8, -4),
    JITInfo(*this) {
}

// addPassesToEmitAssembly - We currently use all of the same passes as the JIT
// does to emit statically compiled machine code.
bool X86TargetMachine::addPassesToEmitAssembly(PassManager &PM,
					       std::ostream &Out) {
  // FIXME: Implement efficient support for garbage collection intrinsics.
  PM.add(createLowerGCPass());

  // FIXME: Implement the invoke/unwind instructions!
  PM.add(createLowerInvokePass());

  // FIXME: Implement the switch instruction in the instruction selector!
  PM.add(createLowerSwitchPass());

  // Make sure that no unreachable blocks are instruction selected.
  PM.add(createUnreachableBlockEliminationPass());

  if (DisablePatternISel)
    PM.add(createX86SimpleInstructionSelector(*this));
  else
    PM.add(createX86PatternInstructionSelector(*this));

  // Run optional SSA-based machine code optimizations next...
  if (!NoSSAPeephole)
    PM.add(createX86SSAPeepholeOptimizerPass());

  // Print the instruction selected machine code...
  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  // Perform register allocation to convert to a concrete x86 representation
  PM.add(createRegisterAllocator());

  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  PM.add(createX86FloatingPointStackifierPass());

  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  // Insert prolog/epilog code.  Eliminate abstract frame index references...
  PM.add(createPrologEpilogCodeInserter());

  PM.add(createX86PeepholeOptimizerPass());

  if (PrintMachineCode)  // Print the register-allocated code
    PM.add(createX86CodePrinterPass(std::cerr, *this));

  if (!DisableOutput)
    PM.add(createX86CodePrinterPass(Out, *this));

  // Delete machine code for this function
  PM.add(createMachineCodeDeleter());

  return false; // success!
}

/// addPassesToJITCompile - Add passes to the specified pass manager to
/// implement a fast dynamic compiler for this target.  Return true if this is
/// not supported for this target.
///
void X86JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {
  // FIXME: Implement efficient support for garbage collection intrinsics.
  PM.add(createLowerGCPass());

  // FIXME: Implement the invoke/unwind instructions!
  PM.add(createLowerInvokePass());

  // FIXME: Implement the switch instruction in the instruction selector!
  PM.add(createLowerSwitchPass());

  // Make sure that no unreachable blocks are instruction selected.
  PM.add(createUnreachableBlockEliminationPass());

  if (DisablePatternISel)
    PM.add(createX86SimpleInstructionSelector(TM));
  else
    PM.add(createX86PatternInstructionSelector(TM));

  // Run optional SSA-based machine code optimizations next...
  if (!NoSSAPeephole)
    PM.add(createX86SSAPeepholeOptimizerPass());

  // FIXME: Add SSA based peephole optimizer here.

  // Print the instruction selected machine code...
  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  // Perform register allocation to convert to a concrete x86 representation
  PM.add(createRegisterAllocator());

  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  PM.add(createX86FloatingPointStackifierPass());

  if (PrintMachineCode)
    PM.add(createMachineFunctionPrinterPass(&std::cerr));

  // Insert prolog/epilog code.  Eliminate abstract frame index references...
  PM.add(createPrologEpilogCodeInserter());

  PM.add(createX86PeepholeOptimizerPass());

  if (PrintMachineCode)  // Print the register-allocated code
    PM.add(createX86CodePrinterPass(std::cerr, TM));
}

<|endoftext|>