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 设备,是的。

找到解决方案!==> 这是我的 Linux,除了经典存储密钥外,没有看到其他 USB 设备。所以现在它开始工作了!

我现在有第二个问题,在这段代码中我从来没有通过

 int n = dev.read(buf);

而这条线对于取得好成绩至关重要。字节操作对我来说并不容易......

找到解决方案 n°2!==> 我只需要在写入和读取之前添加以下行:

dev.disableBlocking();

我认为的最后一个问题:我这样做时没有读取任何字节:

int n = dev.read(buf);

n 始终等于 0...

4

0 回答 0