/** Start the thread that periodically updates the metadata. */
  public void startUpdating() {
    if (update == true) {
      return;
    }

    final Sink metadataSink = new Sink();
    try {
      metadataSink.OpenRBNBConnection(rbnbController.getRBNBConnectionString(), rbnbSinkName);
    } catch (SAPIException e) {
      log.error("Failed to connect to RBNB server: " + e.getMessage());
      e.printStackTrace();
      return;
    }

    updateMetadata(metadataSink);

    updateThread =
        new Thread("MetadataManager") {
          public void run() {
            log.info("RBNB Metadata thread is starting.");

            updateMetadataThread(metadataSink);

            metadataSink.CloseRBNBConnection();

            channels.clear();
            ctree = null;

            log.info("RBNB Metadata thread is stopping.");
          }
        };
    update = true;
    updateThread.start();
  }
Exemple #2
0
 /** Connect to the RBNB * */
 public void connect() {
   if (connected) return;
   try {
     // Create a source and connect:
     if (archiveSize > 0) source = new Source(cacheSize, "append", archiveSize);
     else source = new Source(cacheSize, "append", 0);
     System.out.println(getServer());
     // source.OpenRBNBConnection(getServer(),rbnbSourceName);
     source.OpenRBNBConnection("128.180.53.5:3333", rbnbSourceName);
     connected = true;
     System.out.println(
         "Connecting to SCRAMNetSource with..."
             + "\n RBNB Server = "
             + getServer()
             + "\n RBNB Cache Size = "
             + cacheSize
             + "\n RBNB Archive Size = "
             + archiveSize
             + "\n RBNB Source name = "
             + rbnbSourceName
             + "\n Number of channels = "
             + rbnbChannelNames.length
             + "\n Delay between frames = "
             + ((float) delay / 1000F)
             + "s"
             + "\n RBNB Frame Size = "
             + (rbnbChannelNames.length * 4 * 1000 / delay)
             + " bytes");
   } catch (SAPIException se) {
     se.printStackTrace();
   }
 }
 public void connect() {
   try {
     // Create a sink and connect:
     sink = new Sink();
     sink.OpenRBNBConnection(getServer(), "ChannelListRequest");
     connected = true;
     System.out.println(
         "ChannelList: Connection made to server = " + getServer() + " requesting channel list.");
   } catch (SAPIException se) {
     se.printStackTrace();
   }
 }
 private void testConnect() {
   try {
     // test the connection to the server
     Sink sink = new Sink();
     sink.OpenRBNBConnection(getServer(), sinkName);
     connected = true;
     System.out.println(
         "DataVideoGather: Test connection made to server = "
             + getServer()
             + " as "
             + sinkName
             + ".");
     sink.CloseRBNBConnection();
   } catch (SAPIException se) {
     se.printStackTrace();
   }
 }
  private ChannelTree getChannelTree(String pattern) {

    ChannelTree tr = null;

    try {
      sMap = new ChannelMap();
      if ((pattern != null) && (pattern.length() > 0)) sMap.Add(pattern);
      sink.RequestRegistration(sMap);
      sMap = sink.Fetch(-1, sMap);
      tr = ChannelTree.createFromChannelMap(sMap);

    } catch (SAPIException se) {
      se.printStackTrace();
    }

    return tr;
  }
  public void appendChannelListFromPattern() {
    try {
      // Create a sink and connect:
      Sink sink = new Sink();
      sink.OpenRBNBConnection(getServer(), sinkName);

      // get all the channel paths that match the pattern
      ChannelMap sMap = new ChannelMap();
      sink.RequestRegistration();
      sMap = sink.Fetch(-1, sMap);
      ChannelTree tree = ChannelTree.createFromChannelMap(sMap);

      Pattern p = Pattern.compile(channelPathPattern);
      // for each channel path, check match, collect matches...

      Iterator nodes = tree.iterator();
      while (nodes.hasNext()) {
        ChannelTree.Node n = (ChannelTree.Node) nodes.next();
        // System.out.println("Checking " + n.getFullName() + ";" + n.getName());
        if (!includeHidden && n.getFullName().startsWith("_")) continue;
        if (n.getType() != ChannelTree.CHANNEL) continue;
        String name = n.getFullName();
        Matcher m = p.matcher(name);
        if (m.matches()) {
          //					System.out.println("Matches");
          boolean isSource = false;
          ChannelTree.Node upNode = n.getParent();
          while ((!isSource) || (upNode != null)) {
            if (upNode.getType() == ChannelTree.SOURCE) isSource = true;
            upNode = upNode.getParent();
          }
          if (isSource) {
            // System.out.println("... and is a source.");
            channelPathList.add(n);
          } else {
            // System.out.println("... and is NOT a source.");
          }
        }
      }

    } catch (SAPIException se) {
      se.printStackTrace();
    }
  } // appendChannelListFromPattern
  public void appendChannelListFromString() {
    try {
      StringTokenizer st = new StringTokenizer(channelPathListString, ",");

      // Create a sink and connect:
      Sink sink = new Sink();
      sink.OpenRBNBConnection(getServer(), sinkName);

      // get all the channel paths that match the pattern
      ChannelMap sMap = new ChannelMap();
      sink.RequestRegistration();
      sMap = sink.Fetch(-1, sMap);
      ChannelTree tree = ChannelTree.createFromChannelMap(sMap);

      Pattern p = Pattern.compile(channelPathPattern);
      // for each channel path, check match, collect matches...

      while (st.hasMoreTokens()) {
        String path = st.nextToken();
        //				System.out.println("Checking " + path);

        ChannelTree.Node n = tree.findNode(path);
        if (n == null) continue;
        if (n.getType() != ChannelTree.CHANNEL) continue;
        String name = n.getFullName();
        //				System.out.println("Found it...");
        boolean isSource = false;
        ChannelTree.Node upNode = n.getParent();
        while ((!isSource) || (upNode != null)) {
          if (upNode.getType() == ChannelTree.SOURCE) isSource = true;
          upNode = upNode.getParent();
        }
        if (isSource) {
          //					System.out.println("... and is a source.");
          channelPathList.add(n);
        } else {
          //					System.out.println("... and is NOT a source.");
        }
      } // while next token
    } catch (SAPIException se) {
      se.printStackTrace();
    }
  } // appendChannelListFromString
  /**
   * Updates the metadata and posts it to listeners. It also notifies all threads waiting on this
   * object.
   *
   * @param metadataSink the RBNB sink to use for the server connection
   */
  private synchronized void updateMetadata(Sink metadataSink) {
    // log.info("Updating channel listing at " + DataViewer.formatDate(System.currentTimeMillis
    // ()));

    Map<String, Channel> newChannels = new HashMap<String, Channel>();

    ChannelTree channelTree;
    try {
      // create metadata channel tree
      channelTree = getChannelTree(metadataSink, newChannels);
    } catch (SAPIException e) {
      log.error("Failed to update metadata: " + e.getMessage() + ".");

      if (!metadataSink.VerifyConnection()) {
        log.error(
            "Metadata RBNB connection is severed, try to reconnect to "
                + rbnbController.getRBNBConnectionString()
                + ".");
        metadataSink.CloseRBNBConnection();
        try {
          metadataSink.OpenRBNBConnection(rbnbController.getRBNBConnectionString(), "RDVMetadata");
        } catch (SAPIException error) {
          log.error("Failed to connect to RBNB server: " + error.getMessage());
          error.printStackTrace();
        }
      }

      return;
    }

    if (LocalChannelManager.getInstance().hasChannels()) {
      ChannelTree localChannelTree = getLocalChannelTree(newChannels, channelTree);
      ctree = localChannelTree.merge(channelTree);
    } else {
      ctree = channelTree;
    }

    channels = newChannels;

    // notify metadata listeners
    fireMetadataUpdated(ctree);
  }
  /** @param args the command line arguments */
  @SuppressWarnings("static-access")
  public static void main(String[] args) {
    String hostname = "localhost:3333";
    String portName = "/dev/tty.KeySerial1";
    String srcName = "ADXL-RBNB Accelerometer";
    String[] chanNames = {"X", "Y"};
    int[] chanIdx = {0, 1};
    double[] vals = {0, 0};
    String unitsMetadata = "units=G,scale=1,offset=0";
    Source source;
    ChannelMap cmap;
    int cacheSize = 10240; // ! @todo parse from command line
    int archiveSize = cacheSize * 10; // ! @todo parse from command line
    int idx;
    int chanCount = 2;
    ADXL chip;

    // Setup interrupt handler
    DoHook();

    System.out.println("Opening serial port");
    chip = new ADXL();
    if (chip.initialize(portName) == 0) {
      portConnected = true;
      System.out.println("Serial port initialized OK");
    } else {
      System.out.println("Error opening serial port");
      return;
    }

    // RBNB connection setup
    try {
      System.out.println("Opening connection to RBNB on " + hostname);
      // Create both a source and a sink, connect both:
      source = new Source(cacheSize, "append", archiveSize);
      source.OpenRBNBConnection(hostname, srcName);
      DTconnected = true;

      System.out.println("OK.");

      // Setup channel map - names of channels, units
      cmap = new ChannelMap();
      for (idx = 0; idx < chanCount; idx++) {
        chanIdx[idx] = cmap.Add(chanNames[idx]);

        // Hardwired units (G) for all three sources
        cmap.PutUserInfo(chanIdx[idx], unitsMetadata);

        // Not sure if we still need the MIME type or not
        cmap.PutMime(chanIdx[idx], "application/octet-stream");
      }
      source.Register(cmap);
      source.Flush(cmap);
    } // We don't distinguish between errors in setup phase, just bail out
    catch (SAPIException se) {
      System.out.println("Error on Turbine - not connected");
      DTconnected = false;
      return;
    }

    // ********************************************************************
    // Main data loop: read, scale, write.
    try {
      System.out.println("Turbine connected, running. Press control-c to end");

      // Loop - runs until control-c or error.
      do {
        for (idx = 0; idx < chanCount; idx++) chanIdx[idx] = cmap.Add(chanNames[idx]);

        // Read the data from the accelerometer
        vals = chip.chipRead();

        // Timestamp all channels with client-side time
        cmap.PutTimeAuto("timeofday");

        for (idx = 0; idx < chanCount; idx++) {
          double valBuf[] = {vals[idx]};
          cmap.PutDataAsFloat64(cmap.GetIndex(chanNames[idx]), valBuf);
        }

        source.Flush(cmap);

        cmap.Clear();

        Thread.sleep(20);
      } while (!ctrlC);
    } catch (SAPIException mse) {
      System.out.println("Error saving data!");
      mse.printStackTrace();
    } catch (InterruptedException ie) {
      System.out.println("Interrupted, exiting.");
    }

    // Shutdown and exit
    if (portConnected) {
      chip.closePort(chip.serialPort);
    }
    if (DTconnected) {
      System.out.println("Closing RBNB connection");

      // Tell RBNB to keep the data once we close
      source.Detach();

      source.CloseRBNBConnection();
    }
    System.out.println("Done, exiting.");

    return;
  }
Exemple #10
0
  /** Main data push from SCRAMNet */
  private boolean execute() {
    if (!connected) return false;

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    // Connect to SCRAMNet
    ScramNetIO scr = new ScramNetIO();
    scr.initScramnet();

    // Create a new Channel map
    ChannelMap cmap = new ChannelMap();

    // Gather all the channels
    int channelId[] = new int[rbnbChannelNames.length];
    for (int i = 0; i < rbnbChannelNames.length; i++) {
      try {
        // add the channels
        channelId[i] = cmap.Add(rbnbChannelNames[i]);
      } catch (SAPIException e) {
        System.err.println(
            "Failed to add SCRAMNet channel to channel map; name = " + rbnbChannelNames[i]);
        disconnect();
        return false;
      }

      try {
        cmap.PutUserInfo(channelId[i], "Channel_Name=" + rbnbChannelNames[i]);
      } catch (SAPIException e) {
        System.err.println("Failed to register SCRAMnet channel metadata.");
      }
    }

    try {
      source.Register(cmap);
    } catch (SAPIException e) {
      System.err.println("Failed to register SCRAMnet channel metadata.");
    }

    while (true) {
      // Read SCRAMNet channel depending on if its DAQ or other
      for (int i = 0; i < rbnbChannelNames.length; i++) {
        float scrdata[] = new float[1];

        if (xml.getxPCReadisDAQ(i).equals("true")) {
          scrdata[0] =
              (float)
                  scr.readDAQ(
                      xml.getxPCReadLocation(i),
                      xml.getxPCReadGain(i),
                      xml.getxPCReadVoffset(i),
                      xml.getxPCReadVslope(i),
                      xml.getxPCReadEUoffset(i),
                      xml.getxPCReadEUslope(i));
        } else {
          scrdata[0] =
              scr.readFloat(Integer.parseInt(xml.getxPCReadLocation(i)))
                  * (float) xml.getxPCReadGain(i);
        }

        // Push data to turbine
        try {
          cmap.PutTimeAuto("timeofday");
          cmap.PutDataAsFloat32(channelId[i], scrdata);
        } catch (SAPIException e) {
          System.err.println("Failed to put SCRAMNet data into channel map.");
          scr.unmapScramnet();
          return false;
        }
      }

      // Flush output
      try {
        source.Flush(cmap, true);
      } catch (SAPIException e) {
        e.printStackTrace();
        System.err.println("Failed to flush channel output data to server.");
        scr.unmapScramnet();
        return false;
      }

      try {
        // Delay between
        Thread.sleep(delay);
      } catch (InterruptedException e) {
      }
    }
  }