Friday, April 27, 2012

Android CNC App

I got the whole toolchain working today!  Android app to tgFX, to TinyG, to JGRO CNC.  See the video for a sense of how it currently works.  I hope to have the configuration settings exposed to the UI tonight, so that you don't have to edit the code to change the link to the server.

While the current version relies on tgFX to talk to the hardware (TinyG), that isn't strictly necessary.  I put together a simple serial to network java program which will serve a similar purpose.  I may put that up on github soon too.

Once I get the basics working fairly well, I'll move on to phase 2, which is using my ICS tablet to talk directly to the TinyG vis host USB support.  That will be very nice, and will get me to my main goal - use of the CNC system without a PC being required.

The write code is fairly pedestrian, but the read code from the network took a little work to sort out.  I'm using an AsyncTask to do the blocking reads, and after each line it parses the JSON and updates the necessary state info. 
private class ListenerTask extends AsyncTask {

  @Override
  protected Void doInBackground(InputStream... params) {
    byte[] buffer = new byte[1024];
    InputStream is = params[0];
    int b;
    int idx=0;
    try {
      while (!isCancelled()) {
        if ((b = is.read()) == -1) {
          break;
        }
      buffer[idx++] = (byte) b;
      if (b == '\n') {
        publishProgress(new String(buffer,0,idx));
        idx = 0;
      }
    }
   } catch (IOException e) {
     Log.e(TAG, "listener read: " + e.getMessage());
   }
   return null;
  }

  @Override
  protected void onProgressUpdate(String... values) {
    if (values.length > 0) {
      Log.i(TAG, "onProgressUpdate: " + values[0].length() + " bytes received.");
      if (machine.processJSON(values[0])) {
        ((TextView)findViewById(R.id.xloc)).setText(Double.toString(machine.getX()));
        ((TextView)findViewById(R.id.yloc)).setText(Double.toString(machine.getY()));
        ((TextView)findViewById(R.id.zloc)).setText(Double.toString(machine.getZ()));
      }
    }
  }

  @Override
  protected void onCancelled() {
    Log.i(TAG, "ListenerTask cancelled");
    mConnect.setVisibility(View.VISIBLE);
  }
}

No comments:

Post a Comment