public static void main(String[] args) {

    LoggingFactory.getInstance().configure();
    LoggingFactory.getInstance().setLevel(Level.DEBUG);

    try {
      // FIXME !!! - don't use Adafruit's library - do your own stepper control through "pure"
      // MRLComm.ino
      AdafruitMotorShield fruity =
          (AdafruitMotorShield) Runtime.createAndStart("fruity", "AdafruitMotorShield");
      Runtime.createAndStart("gui01", "GUIService");

      fruity.connect("COM3");

      Motor motor1 = fruity.createDCMotor(4);
      motor1.move(0.4f);

      // create a 200 step stepper on adafruitsheild port 1
      Stepper stepper1 = fruity.createStepper(200, 1);

      // FIXME - needs to be cleaned up - tear down
      fruity.releaseStepper(stepper1.getName());

      // Runtime.createAndStart("python", "Python");
    } catch (Exception e) {
      Logging.logError(e);
    }
  }
  public Integer update(Object[] data) {
    String result = "0";
    try {

      if (System.currentTimeMillis() - lastUpdate < intervalSeconds * 1000) {
        log.debug(String.format("not ready for posting - must be >= %d seconds", intervalSeconds));
        return 0;
      }

      if (data.length > 8) {
        log.warn("data array is larger than 8 - post will be truncated");
      }

      StringBuffer url = new StringBuffer();
      url.append(String.format("%s?key=%s", updateURL, writeKey));

      for (int i = 0; i < data.length && i < 8; ++i) {
        Object o = data[i];
        url.append(String.format("&field%d=%s", i + 1, o.toString()));
      }

      HTTPRequest request = new HTTPRequest(url.toString());
      result = request.getString();
      log.info(String.format("ThingSpeak returned %s", result));

    } catch (IOException e) {
      Logging.logError(e);
    }

    Integer ret = Integer.parseInt(result);
    if (ret > 0) {
      lastUpdate = System.currentTimeMillis();
    }
    return ret;
  }
Exemple #3
0
  public String talkToSelf(String input) {
    try {

      ChatterBot bot1 = factory.create(ChatterBotType.CLEVERBOT);
      ChatterBotSession bot1session = bot1.createSession();

      ChatterBot bot2 = factory.create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
      ChatterBotSession bot2session = bot2.createSession();

      while (continueToTalkToSelf) {

        System.out.println("bot1> " + input);

        input = bot2session.think(input);
        log.info(input);
        System.out.println("bot2> " + input);
        log.info(input);

        input = bot1session.think(input);
      }
    } catch (Exception e) {
      Logging.logException(e);
    }

    return input;
  }
Exemple #4
0
 public void write(byte[] command) {
   // iterate through the byte array sending each one to the serial port.
   for (int i = 0; i < command.length; i++) {
     try {
       serial.write(command[i]);
     } catch (IOException e) {
       Logging.logException(e);
     }
   }
 }
Exemple #5
0
  public String chat(String toSay) {

    try {
      return session.think(toSay);
    } catch (Exception e) {
      Logging.logException(e);
    }

    return null;
  }
 public void displayClear() {
   try {
     device.write(0x00, new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0, 16);
     device.write(0x00, new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0, 16);
     device.write(0x00, new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0, 16);
     device.write(0x00, new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0, 16);
   } catch (Exception e) {
     Logging.logException(e);
   }
 }
Exemple #7
0
 public boolean init() {
   try {
     factory = new ChatterBotFactory();
     // chatterbot = factory.create(type);
     chatterbot = factory.create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
     session = chatterbot.createSession();
   } catch (Exception e) {
     Logging.logException(e);
   }
   return true;
 }
  public byte[] writeDisplay(byte[] data) {
    if (device == null) {
      log.error("device is null");
      return data;
    }

    try {
      device.write(0x00, data, 0, 16);
    } catch (Exception e) {
      Logging.logException(e);
    }

    return data;
  }
Exemple #9
0
  public static void main(String[] args) throws ClassNotFoundException {
    // Logger root = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    Logging logging = LoggingFactory.getInstance();
    logging.configure();
    logging.setLevel(Level.INFO);
    // LoggingFactory.getInstance().setLevel(Level.INFO);

    int test = 35;
    log.info("{}", test);

    log.debug("hello");
    log.trace("trace");
    log.error("error");
    log.info("info");

    PID pid = new PID("pid");
    pid.startService();
    pid.setPID(2.0, 5.0, 1.0);
    pid.setControllerDirection(DIRECTION_DIRECT);
    pid.setMode(MODE_AUTOMATIC);
    pid.setOutputRange(0, 255);
    pid.setSetpoint(100);
    pid.setSampleTime(40);

    GUIService gui = new GUIService("gui");
    gui.startService();

    for (int i = 0; i < 200; ++i) {
      pid.setInput(i);
      Service.sleep(30);
      if (pid.compute()) {
        log.info(String.format("%d %f", i, pid.getOutput()));
      } else {
        log.warn("not ready");
      }
    }
  }
  public boolean init7SegmentDisplay() {
    try {
      if (device == null) {
        log.error("device is null");
        return false;
      }

      device.write(0x21, (byte) 0x00);
      device.write(0x81, (byte) 0x00);
      device.write(0xEF, (byte) 0x00);
      device.write(0x00, new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0, 16);

    } catch (Exception e) {
      Logging.logException(e);
    }

    return true;
  }
  public static void main(String[] args) {
    LoggingFactory.getInstance().configure();
    LoggingFactory.getInstance().setLevel(Level.DEBUG);

    try {
      // BasicConfigurator.

      log.info("hello");

      ThingSpeak thingSpeak = new ThingSpeak("thingSpeak");
      thingSpeak.update(33);
      thingSpeak.startService();

      /*
       * GUIService gui = new GUIService("gui"); gui.startService();
       */
    } catch (Exception e) {
      Logging.logError(e);
    }
  }
Exemple #12
0
  public static void main(String[] args) {
    LoggingFactory.getInstance().configure();
    LoggingFactory.getInstance().setLevel(Level.WARN);

    try {

      LIDAR template = new LIDAR("Lidar");
      template.startService();

      //            LIDAR lidar01 = (LIDAR) Runtime.createAndStart("lidar01", "LIDAR");
      // creates and runs a serial service
      //			lidar01.connect("dev/lidar01");
      // send a command
      // this sets the mode to a spread of 180 degrees with readings every
      // 0.5
      // degrees
      //			lidar01.setMode(180, 0.5f);
      // this setMode command catches the reply from the LMS in the
      // listener
      // within the
      // LIDAR service and returns a bool stating if it was successful or
      // not.

      // an array of floats holding ranges (after the LDIAR service strips
      // and
      // parses the data.
      //			lidar01.singleScan();

      Python python = new Python("python");
      python.startService();

      Runtime.createAndStart("gui", "GUIService");
      /*
       * GUIService gui = new GUIService("gui"); gui.startService();
       *
       */

    } catch (Exception e) {
      Logging.logException(e);
    }
  }
  @Override
  public void run() {
    try {
      // Keep a socket open to listen to all the UDP trafic that is
      // destined for this port
      socket = new DatagramSocket(8888, InetAddress.getByName("0.0.0.0"));
      socket.setBroadcast(true);

      while (true) {
        log.info("server >>>Ready to receive broadcast packets! on 0.0.0.0:8888");

        // Receive a packet
        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        socket.receive(packet);

        // Packet received
        log.info(
            "server >>>Discovery packet received from: " + packet.getAddress().getHostAddress());
        log.info("server >>>Packet received; data: " + new String(packet.getData()));

        // See if the packet holds the right command (message)
        String message = new String(packet.getData()).trim();
        if (message.equals("DISCOVER_FUIFSERVER_REQUEST")) {
          byte[] sendData = "DISCOVER_FUIFSERVER_RESPONSE".getBytes();

          // Send a response
          DatagramPacket sendPacket =
              new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
          socket.send(sendPacket);

          log.info("server >>>Sent packet to: " + sendPacket.getAddress().getHostAddress());
        }
      }
    } catch (Exception e) {
      Logging.logException(e);
    }
  }
  public static void main(String[] args) {
    LoggingFactory.getInstance().configure();
    LoggingFactory.getInstance().setLevel(Level.INFO);

    try {

      MyoThalmic myo = (MyoThalmic) Runtime.start("myo", "MyoThalmic");
      myo.test();

      Hub hub = new Hub("com.example.hello-myo");

      System.out.println("Attempting to find a Myo...");
      log.info("Attempting to find a Myo");

      Myo myodevice = hub.waitForMyo(10000);

      if (myodevice == null) {
        throw new RuntimeException("Unable to find a Myo!");
      }

      System.out.println("Connected to a Myo armband!");
      log.info("Connected to a Myo armband");
      DataCollector dataCollector = new DataCollector();
      hub.addListener(dataCollector);

      while (true) {
        hub.run(1000 / 20);
        // System.out.print(dataCollector);
        System.out.println("yaw is " + dataCollector.getYaw());
        System.out.println("roll is " + dataCollector.getRoll());
        System.out.println("pitch is " + dataCollector.getPitch());

        Runtime.start("gui", "GUIService");
      }
    } catch (Exception e) {
      Logging.logError(e);
    }
  }
  public ArrayList<InetAddress> ping() {
    ArrayList<InetAddress> ret = new ArrayList<InetAddress>();
    // Find the server using UDP broadcast
    try {
      // Open a random port to send the package
      DatagramSocket c = new DatagramSocket();
      c.setBroadcast(true);

      byte[] sendData = "DISCOVER_FUIFSERVER_REQUEST".getBytes();

      // Try the 255.255.255.255 first
      try {
        log.info("client >>> sending request packet to: 255.255.255.255:8888 (DEFAULT)");
        DatagramPacket sendPacket =
            new DatagramPacket(
                sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 8888);
        c.send(sendPacket);
        byte[] recvBuf = new byte[15000];
        DatagramPacket pong = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(pong);
        log.info("client >>> recieved PONG");
      } catch (Exception e) {
      }

      // Broadcast the message over all the network interfaces
      Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

        if (networkInterface.isLoopback() || !networkInterface.isUp()) {
          continue; // Don't want to broadcast to the loopback
          // interface
        }

        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
          InetAddress broadcast = interfaceAddress.getBroadcast();
          if (broadcast == null) {
            continue;
          }

          // Send the broadcast package!
          try {
            log.info("client >>> sending request packet to: 255.255.255.255:8888 (DEFAULT)");
            DatagramPacket sendPacket =
                new DatagramPacket(sendData, sendData.length, broadcast, 8888);
            c.send(sendPacket);
          } catch (Exception e) {
          }

          log.info(
              "client >>> Request packet sent to: "
                  + broadcast.getHostAddress()
                  + "; Interface: "
                  + networkInterface.getDisplayName());
        }
      }

      log.info(">>> Done looping over all network interfaces. Now waiting for a reply!");

      // Wait for a response
      byte[] recvBuf = new byte[15000];
      DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
      c.receive(receivePacket);

      // We have a response
      log.info(
          ">>> Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

      // Check if the message is correct
      String message = new String(receivePacket.getData()).trim();
      if (message.equals("DISCOVER_FUIFSERVER_RESPONSE")) {
        // DO SOMETHING WITH THE SERVER'S IP (for example, store it in
        // your controller)
        // Controller_Base.setServerIp(receivePacket.getAddress());
        ret.add(receivePacket.getAddress());
      }

      // Close the port!
      c.close();
    } catch (IOException e) {
      Logging.logException(e);
    }

    return ret;
  }
  // FIXME - normalize further
  public Response serveFile(
      String uri,
      Map<String, String> header,
      File homeDir,
      boolean allowDirectoryListing,
      boolean isCustomFile) {

    String username;
    String password;

    //
    if (webgui.requiresSecurity()) { // && !authorized) {
      try {
        if (header.containsKey("authorization")) {
          String up = header.get("authorization");
          int pos = up.indexOf("Basic ");
          if (pos != -1) {
            up = up.substring(pos + 6);
          }
          // FIXME - depends on commons !!!!
          String usernameAndPassword = new String(Base64.decode(up)); // SHWEET
          // CURRENTLY
          // USING
          // WEBSOCKETS
          // VERSION
          // !!!
          // :P
          username = usernameAndPassword.substring(0, usernameAndPassword.lastIndexOf(":"));
          password = usernameAndPassword.substring(usernameAndPassword.lastIndexOf(":") + 1);
          String token = BasicSecurity.authenticate(username, password);

          if (token != null) {
            // authorized = true;
          } else {
            throw new Exception(String.format("no token for user %s", username));
          }
          log.info(usernameAndPassword);
        } else {
          throw new Exception("no authorization in header");
        }

      } catch (Exception e) {
        Logging.logException(e);
        Response r = new Response(e.getMessage());
        r.setStatus(Response.Status.FORBIDDEN);
        r.addHeader("WWW-Authenticate", "Basic realm=\"MyRobotLab\"");
        return r;
      }
    }

    // Remove URL arguments
    uri = uri.trim().replace(File.separatorChar, '/');
    if (uri.indexOf('?') >= 0) {
      uri = uri.substring(0, uri.indexOf('?'));
    }

    // Prohibit getting out of current directory
    if (uri.startsWith("..") || uri.endsWith("..") || uri.indexOf("../") >= 0) {
      return new Response(
          Response.Status.FORBIDDEN,
          WSServer.MIME_PLAINTEXT,
          "FORBIDDEN: Won't serve ../ for security reasons.");
    }

    File f;
    if (!isCustomFile) {
      // ---- begin resource ----------------
      // TODO ? hard coded /resource - are they going to pull up
      // WebGUI.class how useful is that ??
      String resoucePath = String.format("/resource%s", uri);
      InputStream fis = null;
      if (resoucePath.endsWith("/")) {
        // ends with a slash .. might be a directory - try index.html
        String documentIndex = String.format("%sindex.html", resoucePath);
        fis = FileIO.class.getResourceAsStream(documentIndex);
        if (fis == null) { // couldn't find document index try directory
          // listing, if allowed
          fis = FileIO.class.getResourceAsStream(resoucePath);
        } else {
          uri = documentIndex;
        }
      } else {
        fis = FileIO.class.getResourceAsStream(resoucePath);
      }

      if (fis == null)
        return new Response(
            Response.Status.NOT_FOUND, WSServer.MIME_PLAINTEXT, "Error 404, file not found.");

      try {
        // Get MIME type from file name extension, if possible
        String mime = null;
        int dot = uri.lastIndexOf('.');
        if (dot >= 0) {
          mime = (String) NanoHTTPD.theMimeTypes.get(uri.substring(dot + 1).toLowerCase());
        }
        if (mime == null) {
          // mime = NanoHTTPD.MIME_DEFAULT_BINARY;
          mime = WSServer.MIME_PLAINTEXT;
        }

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int nRead;
        byte[] data = new byte[16384];

        while ((nRead = fis.read(data, 0, data.length)) != -1) {
          buffer.write(data, 0, nRead);
        }

        fis.close();
        buffer.flush();

        byte[] content = null;

        // if ("/resource/WebGUI/myrobotlab.html".equals(uri)) {
        if (uri.endsWith(".mrl")) {
          content = filter(new String(buffer.toByteArray()), header);
          mime = NanoHTTPD.MIME_HTML;
        } else {
          content = buffer.toByteArray();
        }

        Response r = new Response(Response.Status.OK, mime, new ByteArrayInputStream(content));

        r.addHeader("Content-length", "" + content.length);
        return r;
      } catch (IOException ioe) {
        return new Response(
            Response.Status.FORBIDDEN, WSServer.MIME_PLAINTEXT, "FORBIDDEN: Reading file failed.");
      }
      // ---- end resource -------------------
    } else {
      // ---- begin file -----------------------
      f = new File(homeDir, uri);
      if (!f.exists())
        return new Response(
            Response.Status.NOT_FOUND, WSServer.MIME_PLAINTEXT, "Error 404, file not found.");

      // List the directory, if necessary
      if (f.isDirectory()) {
        // Browsers get confused without '/' after the
        // directory, send a redirect.
        if (!uri.endsWith("/")) {
          uri += "/";
          Response r =
              new Response(
                  Response.Status.REDIRECT,
                  NanoHTTPD.MIME_HTML,
                  "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>");
          r.addHeader("Location", uri);
          return r;
        }

        // First try index.html and index.htm
        if (new File(f, "index.html").exists()) f = new File(homeDir, uri + "/index.html");
        else if (new File(f, "index.htm").exists()) f = new File(homeDir, uri + "/index.htm");

        // No index file, list the directory
        else if (allowDirectoryListing) {
          String[] files = f.list();
          String msg = "<html><body><h1>Directory " + uri + "</h1><br/>";

          if (uri.length() > 1) {
            String u = uri.substring(0, uri.length() - 1);
            int slash = u.lastIndexOf('/');
            if (slash >= 0 && slash < u.length())
              msg += "<b><a href=\"" + uri.substring(0, slash + 1) + "\">..</a></b><br/>";
          }

          for (int i = 0; i < files.length; ++i) {
            File curFile = new File(f, files[i]);
            boolean dir = curFile.isDirectory();
            if (dir) {
              msg += "<b>";
              files[i] += "/";
            }

            msg += "<a href=\"" + NanoHTTPD.encodeUri(uri + files[i]) + "\">" + files[i] + "</a>";

            // Show file size
            if (curFile.isFile()) {
              long len = curFile.length();
              msg += " &nbsp;<font size=2>(";
              if (len < 1024) msg += curFile.length() + " bytes";
              else if (len < 1024 * 1024)
                msg += curFile.length() / 1024 + "." + (curFile.length() % 1024 / 10 % 100) + " KB";
              else
                msg +=
                    curFile.length() / (1024 * 1024)
                        + "."
                        + curFile.length() % (1024 * 1024) / 10 % 100
                        + " MB";

              msg += ")</font>";
            }
            msg += "<br/>";
            if (dir) msg += "</b>";
          }
          return new Response(Response.Status.OK, NanoHTTPD.MIME_HTML, msg);
        } else {
          return new Response(
              Response.Status.FORBIDDEN,
              WSServer.MIME_PLAINTEXT,
              "FORBIDDEN: No directory listing.");
        }
      }

      // ----- end file ------------------------
    }
    // }
    try {
      // Get MIME type from file name extension, if possible
      String mime = null;
      // int dot = f.getCanonicalPath().lastIndexOf('.');
      int dot = uri.lastIndexOf('.');
      if (dot >= 0) {
        mime = (String) NanoHTTPD.theMimeTypes.get(uri.substring(dot + 1).toLowerCase());
      }
      if (mime == null) {
        mime = WSServer.MIME_PLAINTEXT;
      }

      // Support (simple) skipping:
      long startFrom = 0;
      String range = header.get("Range");
      if (range != null) {
        if (range.startsWith("bytes=")) {
          range = range.substring("bytes=".length());
          int minus = range.indexOf('-');
          if (minus > 0) range = range.substring(0, minus);
          try {
            startFrom = Long.parseLong(range);
          } catch (NumberFormatException nfe) {
          }
        }
      }

      InputStream fis;
      if (!isCustomFile) {
        fis = FileIO.class.getResourceAsStream(uri);
        if (fis == null) {
          return new Response(
              Response.Status.NOT_FOUND, WSServer.MIME_PLAINTEXT, "Error 404, file not found.");
        }

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int nRead;
        byte[] data = new byte[16384];

        while ((nRead = fis.read(data, 0, data.length)) != -1) {
          buffer.write(data, 0, nRead);
        }

        fis.close();
        buffer.flush();

        byte[] content = null;
        // FIXME - this is not normalized - because the code around it
        // is
        // not normalized
        if (uri.endsWith(".mrl")) {
          content = filter(new String(buffer.toByteArray()), header);
          mime = NanoHTTPD.MIME_HTML;
        } else {
          content = buffer.toByteArray();
        }

        Response r = new Response(Response.Status.OK, mime, new ByteArrayInputStream(content));

        r.addHeader("Content-length", "" + content.length);
        return r;
      } else {
        fis = new FileInputStream(f);
        // fis.skip(startFrom); // TODO support skip in the future
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int nRead;
        byte[] data = new byte[16384];

        while ((nRead = fis.read(data, 0, data.length)) != -1) {
          buffer.write(data, 0, nRead);
        }

        fis.close();
        buffer.flush();

        byte[] content = null;
        // FIXME - this is not normalized - because the code around it
        // is
        // not normalized

        if (uri.endsWith(".mrl")) {
          content = filter(new String(buffer.toByteArray()), header);
          mime = NanoHTTPD.MIME_HTML;
        } else {
          content = buffer.toByteArray();
        }

        Response r = new Response(Response.Status.OK, mime, new ByteArrayInputStream(content));
        r.addHeader("Content-length", "" + content.length);
        // r.addHeader("Content-length", "" + (f.length() - startFrom));
        // r.addHeader("Content-range", "" + startFrom + "-" +
        // (f.length() - 1) + "/" + f.length());
        return r;
      }

    } catch (IOException ioe) {
      return new Response(
          Response.Status.FORBIDDEN, WSServer.MIME_PLAINTEXT, "FORBIDDEN: Reading file failed.");
    }
  }