1

USB デバイス TEMPer から温度の値を回復する必要があり、このブログ投稿でコードを見つけまし

import java.io.IOException;

import org.apache.log4j.Logger;

import com.codeminders.hidapi.HIDDevice;
import com.codeminders.hidapi.HIDManager;


public class Foo {
 static final int VENDOR_ID = 3141;
 static final int PRODUCT_ID = 29697;
 static final int BUFSIZE = 2048;
 static final long READ_UPDATE_DELAY_MS = 1000;
 public static String myTemperature = "0.00";
 private static Logger log = Logger.getLogger(Foo.class.getName());

static float raw_to_c(final int rawtemp) {
 final float temp_c = rawtemp * (125.f / 32000.f);
 return temp_c;
}

static float c_to_u(final float deg_c, final char unit) {
  if (unit == 'F') {
    return (deg_c * 1.8f) + 32.f;
  } else if (unit == 'K') {
    return (deg_c + 273.15f);
  } else {
    return deg_c;
  }
}

public static void readDevice(final int vendorId, final int productId) {

  System.out.println("In readDevice");
  final HIDDevice dev;

  try {
    final HIDManager hid_mgr = HIDManager.getInstance();
    log.debug("vendorId =" +vendorId + " productID =" + productId);
    dev = hid_mgr.openById(vendorId, productId, null);      



    final byte[] temp = new byte[] { (byte) 0x01, (byte) 0x80, (byte) 0x33, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };

    final int res = dev.write(temp);

    try {
      final byte[] buf = new byte[BUFSIZE];
      final int n = dev.read(buf);

      int rawtemp = (buf[3] & (byte) 0xFF) + (buf[2] << 8);
      if ((buf[2] & 0x80) != 0) {
      /* return the negative of magnitude of the temperature */
      rawtemp = -((rawtemp ^ 0xffff) + 1);
      }

      System.out.println("temp = " + c_to_u(raw_to_c(rawtemp), 'C'));
      myTemperature = Float.toString( c_to_u(raw_to_c(rawtemp), 'C'));

      try {
        Thread.sleep(READ_UPDATE_DELAY_MS);
      } catch (final InterruptedException e) {
        e.printStackTrace();
      }
    } finally {
      dev.close();
      hid_mgr.release();
    }
  } catch (final IOException e) {
    e.printStackTrace();
  }

}

}

私のクラスはこのエラーコードを返します:

com.codeminders.hidapi.HIDDeviceNotFoundException at com.codeminders.hidapi.HIDManager.openById(HIDManager.java:114) at Foo.readTemperature(Foo.java:44) at StartApplication.main(StartApplication.java:96)

USB プローブが HID デバイスかどうかを確認しましたが、そうです。

解決策が見つかりました!==> クラシック ストレージ キー以外の USB デバイスが表示されないのは、私の Linux です。だから今それは働いています!

私は今、2番目の問題を抱えています.このコードでは、

 int n = dev.read(buf);

そして、このラインは良い結果を得るために不可欠です。そして、バイトを使った操作は私にとって本当に簡単ではありません...

ソリューション n°2 が見つかりました! ==>必要なのは、書き込みと読み取りの前に次の行を追加することだけです:

dev.disableBlocking();

私が思う最後の問題:これを行うときにバイトを読み取らない:

int n = dev.read(buf);

n は常に 0 です...

4

0 に答える 0