Exemplo n.º 1
0
  /**
   * Method main
   *
   * @param args
   * @throws OneWireException
   * @throws OneWireIOException
   */
  public static void main(String[] args) throws OneWireIOException, OneWireException {
    boolean show_history = false;
    boolean show_log = false;
    boolean show_histogram = false;
    boolean pre_kill = false;
    boolean post_kill = false;
    boolean usedefault = false;
    DSPortAdapter access = null;
    String adapter_name = null;
    String port_name = null;

    if ((args == null) || (args.length < 1) || (args[0].indexOf("_") == -1)) {
      try {
        access = OneWireAccessProvider.getDefaultAdapter();

        if (access == null) throw new Exception();
      } catch (Exception e) {
        System.out.println("Couldn't get default adapter!");
        printUsageString();

        return;
      }

      usedefault = true;
    }

    if ((args != null) && (args.length > 0) && (usedefault)) {
      String arg = args[0];

      if (arg.indexOf("a") != -1) show_history = true;

      if (arg.indexOf("l") != -1) show_log = true;

      if (arg.indexOf("h") != -1) show_histogram = true;

      if (arg.indexOf("k") != -1) pre_kill = true;

      if (arg.indexOf("s") != -1) post_kill = true;
    }

    if (!usedefault) {
      StringTokenizer st = new StringTokenizer(args[0], "_");

      if (st.countTokens() != 2) {
        printUsageString();

        return;
      }

      if (args.length > 1) {
        String arg = args[1];

        if (arg.indexOf("a") != -1) show_history = true;

        if (arg.indexOf("l") != -1) show_log = true;

        if (arg.indexOf("h") != -1) show_histogram = true;

        if (arg.indexOf("k") != -1) pre_kill = true;

        if (arg.indexOf("s") != -1) post_kill = true;
      }

      adapter_name = st.nextToken();
      port_name = st.nextToken();

      System.out.println("Adapter Name: " + adapter_name);
      System.out.println("Port Name: " + port_name);
    }

    if (access == null) {
      try {
        access = OneWireAccessProvider.getAdapter(adapter_name, port_name);
      } catch (Exception e) {
        System.out.println("That is not a valid adapter/port combination.");

        Enumeration en = OneWireAccessProvider.enumerateAllAdapters();

        while (en.hasMoreElements()) {
          DSPortAdapter temp = (DSPortAdapter) en.nextElement();

          System.out.println("Adapter: " + temp.getAdapterName());

          Enumeration f = temp.getPortNames();

          while (f.hasMoreElements()) {
            System.out.println("   Port name : " + ((String) f.nextElement()));
          }
        }

        return;
      }
    }

    access.adapterDetected();
    access.targetFamily(0x21);
    access.beginExclusive(true);
    access.reset();
    access.setSearchAllDevices();

    boolean next = access.findFirstDevice();

    if (!next) {
      System.out.println("Could not find any DS1921 Thermocrons!");

      return;
    }

    OneWireContainer21 owc = new OneWireContainer21();

    owc.setupContainer(access, access.getAddressAsLong());

    // put the part into overdrive...make it sizzle!
    owc.setSpeed(access.SPEED_OVERDRIVE, true);

    // let's gather our information here...
    long t1 = System.currentTimeMillis();

    if (pre_kill) {
      try {
        owc.disableMission();
      } catch (Exception e) {
        System.out.println("Couldn't end mission before reading: " + e.toString());
      }
    }

    boolean mission_in_progress = owc.getFlag(owc.STATUS_REGISTER, owc.MISSION_IN_PROGRESS_FLAG);
    byte[] state;

    Calendar cal = Calendar.getInstance();

    // first, check to make sure that the thermochron isn't
    // sampling, or at least that a sample isn't about to occur.
    boolean isSampling = false;
    do {
      state = owc.readDevice();
      cal.setTime(new Date(owc.getClock(state)));

      isSampling =
          mission_in_progress
              && (owc.getFlag(owc.STATUS_REGISTER, owc.SAMPLE_IN_PROGRESS_FLAG, state)
                  || (cal.get(Calendar.SECOND) > 55));

      if (isSampling) {
        // wait for current sample to finish
        try {
          Thread.sleep(1000);
        } catch (InterruptedException ie) {;
        }
      }
    } while (isSampling);

    int mission_count = owc.getMissionSamplesCounter(state);
    int device_count = owc.getDeviceSamplesCounter(state);
    long rtc = owc.getClock(state);
    long next_alarm = owc.getClockAlarm(state);
    Calendar time_stamp = owc.getMissionTimeStamp(state);
    int sample_rate = owc.getSampleRate(state);
    double high_alarm = owc.getTemperatureAlarm(owc.ALARM_HIGH, state);
    double low_alarm = owc.getTemperatureAlarm(owc.ALARM_LOW, state);
    int[] histogram = owc.getTemperatureHistogram();
    byte[] log = owc.getTemperatureLog(state);
    byte[] high_history = owc.getAlarmHistory(owc.TEMPERATURE_HIGH_ALARM);
    byte[] low_history = owc.getAlarmHistory(owc.TEMPERATURE_LOW_ALARM);
    long t2 = System.currentTimeMillis();
    boolean clock_enabled = owc.isClockRunning(state);
    boolean alarm_enabled = owc.isClockAlarmEnabled(state);
    boolean clock_alarm = owc.isClockAlarming(state);
    boolean rollover = owc.getFlag(owc.CONTROL_REGISTER, owc.ROLLOVER_ENABLE_FLAG, state);
    double current_temp = 0;
    String mission_in_progress_string;

    if (!mission_in_progress) {
      owc.doTemperatureConvert(state);

      current_temp = owc.getTemperature(state);
      mission_in_progress_string = "- NO MISSION IN PROGRESS AT THIS TIME";
    } else mission_in_progress_string = "- MISSION IS CURRENTLY RUNNING";

    // spew all this data
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Dallas Semiconductor DS1921 Thermocron Mission Summary Demo");
    System.out.println("-----------------------------------------------------------");
    System.out.println("- Device ID : " + owc.getAddressAsString());
    System.out.println(mission_in_progress_string);

    if (!mission_in_progress) {
      System.out.println("- Current Temperature : " + current_temp);
    } else System.out.println("- Cannot read current temperature with mission in progress");

    System.out.println("-----------------------------------------------------------");
    System.out.println("- Number of mission samples: " + mission_count);
    System.out.println("- Total number of samples  : " + device_count);
    System.out.println("- Real Time Clock          : " + (clock_enabled ? "ENABLED" : "DISABLED"));
    System.out.println("- Real Time Clock Value    : " + (new Date(rtc)));
    System.out.println("- Clock Alarm              : " + (alarm_enabled ? "ENABLED" : "DISABLED"));

    if (alarm_enabled) {
      System.out.println(
          "- Clock Alarm Status       : " + (clock_alarm ? "ALARMING" : "NOT ALARMING"));
      System.out.println("- Next alarm occurs at     : " + (new Date(next_alarm)));
    }

    System.out.println("- Last mission started     : " + time_stamp.getTime());
    System.out.println("- Sample rate              : Every " + sample_rate + " minutes");
    System.out.println("- High temperature alarm   : " + high_alarm);
    System.out.println("- Low temperature alarm    : " + low_alarm);
    System.out.println("- Rollover enabled         : " + (rollover ? "YES" : "NO"));
    System.out.println("- Time to read Thermocron  : " + (t2 - t1) + " milliseconds");
    System.out.println("-----------------------------------------------------------");

    if (show_history) {
      int start_offset, violation_count;

      System.out.println("-");
      System.out.println("-                   ALARM HISTORY");

      if (low_history.length == 0) {
        System.out.println("- No violations against the low temperature alarm.");
        System.out.println("-");
      }

      for (int i = 0; i < low_history.length / 4; i++) {
        start_offset =
            (low_history[i * 4] & 0x0ff)
                | ((low_history[i * 4 + 1] << 8) & 0x0ff00)
                | ((low_history[i * 4 + 2] << 16) & 0x0ff0000);
        violation_count = 0x0ff & low_history[i * 4 + 3];

        System.out.println("- Low alarm started at     : " + (start_offset * sample_rate));
        System.out.println(
            "-                          : Lasted " + (violation_count * sample_rate) + " minutes");
      }

      if (high_history.length == 0) {
        System.out.println("- No violations against the high temperature alarm.");
        System.out.println("-");
      }

      for (int i = 0; i < high_history.length / 4; i++) {
        start_offset =
            (high_history[i * 4] & 0x0ff)
                | ((high_history[i * 4 + 1] << 8) & 0x0ff00)
                | ((high_history[i * 4 + 2] << 16) & 0x0ff0000);
        violation_count = 0x0ff & high_history[i * 4 + 3];

        System.out.println("- High alarm started at    : " + (start_offset * sample_rate));
        System.out.println(
            "-                          : Lasted " + (violation_count * sample_rate) + " minutes");
      }

      System.out.println("-----------------------------------------------------------");
    }

    if (show_log) {
      long time = time_stamp.getTime().getTime() + owc.getFirstLogOffset(state);

      System.out.println("-");
      System.out.println("-                   TEMPERATURE LOG");

      GregorianCalendar gc = new GregorianCalendar();
      for (int i = 0; i < log.length; i++) {
        gc.setTime(new Date(time));
        System.out.println("- Temperature recorded at  : " + (gc.getTime()));
        System.out.println("-                     was  : " + owc.decodeTemperature(log[i]) + " C");

        time += sample_rate * 60 * 1000;
      }

      System.out.println("-----------------------------------------------------------");
    }

    if (show_histogram) {
      double resolution = owc.getTemperatureResolution();
      double histBinWidth = owc.getHistogramBinWidth();
      double start = owc.getHistogramLowTemperature();

      System.out.println("-");
      System.out.println("-                   TEMPERATURE HISTOGRAM");

      for (int i = 0; i < histogram.length; i++) {
        System.out.println(
            "- Histogram entry          : "
                + histogram[i]
                + " at temperature "
                + start
                + " to "
                + (start + (histBinWidth - resolution))
                + " C");

        start += histBinWidth;
      }
    }

    if (post_kill) {
      try {
        owc.disableMission();
      } catch (Exception e) {
        System.out.println("Couldn't end mission after reading: " + e.toString());
      }
    }

    access.endExclusive();
    access.freePort();
    access = null;
    System.out.println("Finished.");
  }
Exemplo n.º 2
0
  /** Load the configuration properties and register e new service */
  private void initialize() throws Exception {

    if (context == null) return;

    // Get the Config-Location value from the manifest

    String configLocation = null;
    Dictionary dict = context.getBundle().getHeaders();
    Enumeration enum1 = dict.keys();
    while (enum1.hasMoreElements()) {
      Object nextKey = enum1.nextElement();
      Object nextElem = dict.get(nextKey);
      if (nextKey.equals("Config-Location")) {
        configLocation = nextElem.toString();
        break;
      }
    }
    if (configLocation == null) {
      configLocation = CONFIGFILE;
    }

    // Load properties from configLocation file
    InputStream is = getClass().getResourceAsStream(configLocation);
    Properties props = Configuration.loadProperties(is);

    String ptraceout = props.getProperty("traceout");
    PrintStream traceout = null;
    if (ptraceout != null) {
      if (ptraceout.equals("System.out")) {
        traceout = System.out;
      } else if (ptraceout.equals("System.err")) {
        traceout = System.err;
      } else {
        // TODO instanciante the class with the name
        System.err.println("custom trace is not implemented !");
      }
    } else {
      traceout = null;
    }

    // Get the properties
    String adapter_name = props.getProperty("adapterName");
    String port_name = props.getProperty("portName");
    traceln("Configured Adapter:" + adapter_name + " on port:" + port_name);

    String poll_interval = props.getProperty("pollInterval");
    int pollInterval = 1000; // default 1000 millisec
    if (poll_interval != null) {
      pollInterval = Integer.parseInt(poll_interval);
    }

    try {
      if (adapter_name == null || port_name == null) {
        // get the default adapter
        adapter = OneWireAccessProvider.getDefaultAdapter();
      } else {
        adapter = OneWireAccessProvider.getAdapter(adapter_name, port_name);
      }

      traceln("Found adapter: " + adapter.getAdapterName() + " on port: " + adapter.getPortName());

    } catch (Exception e) {
      traceln("That is not a valid adapter/port combination.");

      Enumeration en = OneWireAccessProvider.enumerateAllAdapters();
      while (en.hasMoreElements()) {

        DSPortAdapter temp = (DSPortAdapter) en.nextElement();

        traceln("Adapter: " + temp.getAdapterName());

        Enumeration f = temp.getPortNames();

        while (f.hasMoreElements()) {
          traceln("   Port name : " + ((String) f.nextElement()));
        }
      }

      return;
    }

    traceln("Adapter: " + adapter.getAdapterName() + " Port: " + adapter.getPortName());

    // clear any previous search restrictions
    adapter.setSearchAllDevices();
    adapter.targetAllFamilies();
    adapter.setSpeed(DSPortAdapter.SPEED_REGULAR);
    // SPEED_OVERDRIVE, SPEED_HYPERDRIVE, SPEED_FLEX

    // create a network monitor
    dm = new DeviceMonitor(adapter);

    eventProducer = new EventProducer(context, traceout);
    oneWireProducerRegister = new OneWireProducerRegister(context, pollInterval, traceout);

    // add this to the event listers
    dm.addDeviceMonitorEventListener(eventProducer);
    dm.addDeviceMonitorEventListener(oneWireProducerRegister);

    // start the monitor
    // start the monitor
    Thread thread = new Thread(dm);
    thread.setName(DeviceMonitor.class.getName());
    thread.start();
  }