Java не работает usb

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Operation not supported or unimplemented on this platform #11

Operation not supported or unimplemented on this platform #11

Comments

First of all thank you for coming back to update this project. API for USB with java is lame.

I’m using the usb4java-javax-examples examples. But the DumpNames class informs me the following errors:

Ignoring problematic device: javax.usb.UsbPlatformException: USB error 12: Can not open device Bus 002 Device 002: ID 045e: 02e6: Operation not supported or unimplemented on this platform
Ignoring problematic device: javax.usb.UsbPlatformException: USB error 8: Unable to get string descriptor languages: Overflow
Ignoring problematic device: javax.usb.UsbPlatformException: USB error 12: Can not open device Bus 002 Device 014: ID 04e8: 6860: Operation not supported or unimplemented on this platform

Читайте также:  Php creating a button

How to solve or really my platform is not supported?

windows 10 64 bit / java 8

The text was updated successfully, but these errors were encountered:

Источник

How to access USB ports in java [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

I’m trying to write a java application that accesses the usb ports to read from and write to a device connected through usb. The problem I face is that I don’t know what exactly to use in java to do such a thing. I searched online and found something called JUSB but all the posts seem fairly old. Currently I’m using the RXTX libraries but I sometimes run into some sync error. When I use C# to do the equivalent it requires far less code and I don’t face any of the same sync error. My question is, is there anything built into the latest version of the JRE I can use to access the usb ports (that is just as easy as the equivalent C# code)?

6 Answers 6

Been using usb4java for a year on cross platfom (Linux and Windows) and it works great.

They are very active and have a very good javax USB front.

There is nothing equivalent to C#’s USB support in Java. Both jUSB and Java-USB are severely out-of-date and likely unusable for any serious application development.

If you want to implement a cross-platform USB application, really your best bet is to write an abstract JNI interface that talks to Linux, Mac and Windows native libraries that you’ll have to write yourself. I’d look at LibUSB to handle Mac and Linux. Windows, as you’ve seen, is pretty straightforward. I just came off a year-long project that did just this, and unfortunately this is the only serious cross-platform solution. If you don’t have to implement on Windows and your needs are limited, you may get by with one of the older Java libs (jUSB or Java-USB). Anything that needs to deploy on Win32/Win64 will need a native component.

You might want to have a look at usb4java — http://usb4java.org/index.html it appears to support Windows, Linux and Mac OS’s and appears to be reasonably current at the time of posting. Is unfortunately under the LGPL so may not be suitable for commercial development.

Linking with LGPL libraries should not be an issue, if you are going to only use their APIs in your code (and you have a non LGPL license). GPL licensed libraries are copyleft licenses, forcing your code’s license also to be GPL license, regardless of what license you have used.

Источник

Как получить доступ к USB-портам в Java

Я пытаюсь написать приложение Java, которое обращается к портам USB для чтения и записи на устройство, подключенное через USB. Проблема, с которой я сталкиваюсь, заключается в том, что я не знаю, что именно использовать в java, чтобы делать такую ​​вещь. Я искал в Интернете и нашел что-то под названием JUSB , но все сообщения выглядят довольно старыми. В настоящее время я использую библиотеки RXTX , но иногда сталкиваюсь с некоторой ошибкой синхронизации. Когда я использую С# для выполнения эквивалента, он требует гораздо меньше кода, и я не сталкиваюсь с какой-либо одной ошибкой синхронизации. Мой вопрос: есть ли что-нибудь встроенное в последнюю версию JRE, которую я могу использовать для доступа к портам usb (это так же просто, как эквивалентный код С#)?

6 ответов

Ничего не эквивалентно поддержке С# USB в Java. Как jUSB, так и Java-USB сильно устарели и, вероятно, непригодны для любой серьезной разработки приложений. Если вы хотите внедрить кросс-платформенное приложение USB, действительно лучше всего написать абстрактный интерфейс JNI, который говорит с Linux, Mac и Windows, которые вам придется писать самостоятельно. Я бы посмотрел LibUSB для работы с Mac и Linux. Windows, как вы видели, довольно проста. Я только что закончил годичный проект, который сделал именно это, и, к сожалению, это единственное серьезное кросс-платформенное решение. Если вам не нужно реализовывать в Windows и ваши потребности ограничены, вы можете пройти с одной из старых Java-библиотек (jUSB или Java-USB). Все, что требуется для развертывания на Win32/Win64, будет иметь собственный компонент.

Источник

How to communicate with a USB device under Windows and Java?

I’d like to communicate with a USB device under Windows and Java but I can’t find a good library to do so. I don’t want the user to have to install any extra hardware or device drivers to make this work. That is, I want to be able to interact with USB just like other Windows applications do. I am familiar with jUSB and JSR 80 but both seem to be dead projects (at least for Windows).

I just found this at cafe.elharo.com/blogroll/what-java-still-cant-do/#comment-69109 «[. ] on Windows, you cant just list connected devices and start talking to them, which is what the Java USB API is for.» I don’t fully understand his comment but it sounds rather discouraging 🙁

4 Answers 4

libusb-win32 requires you to install their generic driver, which then makes a USB device available to you. I’m not sure that it’s possible to do driver-less access of an USB device unless the device belongs to one of several standard classes (storage and HID, in particular).

There is a Java wrapper for libusb-win32 which might work for you. I haven’t used it myself, though.

Don’t all USB devices ship with on-board drivers which get installed automatically when you plug the device in? Or is this just for «standard» devices? Is it at least possible to communicate with «standard» devices using Java without drivers?

No, on-board drivers are an exception. Standard devices, such as storage and HID (keyboards, mouses etc.) would probably work with the above mentioned libusb-win32. Windows includes standard drivers for them.

I have been looking for a simple way to interact with a custom USB device that didn’t involve emulating a comm port, Thanks

I did quite a bit of research on this some time ago, and the unfortunate fact was that all the useful free USB+Windows+Java projects were dead. There is commercial and expensive (price $39.99 is not per developer, but per copy of your software sold!) JCommUSB library which probably works, although I have no experience of it; we had to build our own custom C wrappers to the USB drivers and communicate with them through JNI.

The fastest and easiest way is to hack some native code 🙂 I wrote a small wrapper for HID devices that enabled my Java applications to read data from CalComp digitizers, so it’s definitely doable and not too hard. The bad thing is that my work is still proprietary code owned by my former employer, so for legal reasons I can’t release that as open-source — yet.

The good thing is that you can get a flying start with the HID example code from the Microsoft DDK 🙂

An example is conducted for a Freescale microcontroller

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

usb4java: не удается получить передачу данных на работу

Я пытаюсь использовать usb4java (низкоуровневый API) для связи с научным прибором, связанным с USB, настроенным как HID-устройство в Windows (как x86, так и x86_64). Существует очень старое приложение C++, которое отлично работает, но я пытаюсь заменить его чистой Java по разным причинам.

Я могу получить дескрипторы устройств и определить интерфейс/конечную точку, но асинхронные передачи никогда не происходят (проверяется Device Monitoring Studio), и обратные вызовы никогда не вызываются. Никакие исключения не выбрасываются usb4java и не знают, могу ли я получить доступ к любым журналам на уровне libusb (если это возможно). Я полный новичок в общении с оборудованием, поэтому вполне может быть что-то действительно основное, что мне не хватает.

Существует только одна конечная точка, и я не уверен, как код C++ управлял двунаправленной связью. В коде нет явного упоминания о типах передачи, поскольку все детали зарыты в стороннюю библиотеку.

Я установил драйвер libusbK, и я попытался выполнить высокоуровневую реализацию (javax-usb). Переводы все еще не проходят.

Ниже приведен вывод с дампа дескриптора конечной точки, а также сокращенную версию кода.

 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 3 Transfer Type Interrupt Synch Type None Usage Type Data wMaxPacketSize 8 bInterval 100 extralen 0 extra: 
import java.nio.*; import java.util.*; import org.usb4java.*; /** * This class is intended to test USB communication using usb4java * */ public class Test < private static final String vendorId = "VVV"; private static final String productId = "PPP"; private Context context; private Device device; private Handle handle; static volatile boolean exit = false; Object synchObj = new Object(); boolean readCompleted = false; private static final int BUFFER_SIZE = 8; private final byte[] idQuery = new byte[]< 0x1d, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 >; public Test() < initialize(); if (device == null)< System.out.println("No target devices found"); System.exit(0); >boolean loop = true; //claim interface 0 int result = LibUsb.claimInterface(handle, 0); if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to claim interface", result); //this code doesn't get executed because the transfer never completes correctly final TransferCallback readCallback = new TransferCallback() < public void processTransfer(Transfer transfer)< System.out.println(transfer.actualLength() + " bytes sent"); //read the response here synchronized (synchObj)< readCompleted = true; synchObj.notify(); >> >; //initial request writing the device identification query write(handle, idQuery, readCallback); //waiting for the write/response to complete while (loop) < synchronized (synchObj)< while (!readCompleted)< try< synchObj.wait(); >catch (InterruptedException ex) < ex.printStackTrace(); >> > readCompleted = false; loop = false; System.out.println("Completed reading"); > result = LibUsb.releaseInterface(handle, 0); LibUsb.close(handle); > private void initialize() < try< context = new Context(); int result = LibUsb.init(context); if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to initialize libusb.", result); DeviceList deviceList = new DeviceList(); result = LibUsb.getDeviceList(context, deviceList); if (result < 0) throw new LibUsbException("Unable to get device list.", result); for (int i = 0; i < deviceList.getSize(); i++)< Device dev = deviceList.get(i); DeviceHandle h = new DeviceHandle(); int res = LibUsb.open(dev, h); if (res != LibUsb.SUCCESS) continue; DeviceDescriptor descriptor = new DeviceDescriptor(); result = LibUsb.getDeviceDescriptor(dev, descriptor); if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to read device descriptor", result); String dump = descriptor.dump(h); if (dump.indexOf("PPP") >-1) < device = dev; handle = h; System.out.println("Found target device"); break; >> > catch (Exception ex) < ex.printStackTrace(); >> public static void write(DeviceHandle handle, byte[] data, TransferCallback callback) < ByteBuffer buffer = BufferUtils.allocateByteBuffer(data.length); buffer.put(data); Transfer transfer = LibUsb.allocTransfer(); LibUsb.fillInterruptTransfer(transfer, handle, (byte)0x81, buffer, callback, null, 1000); System.out.println("Sending " + data.length + " bytes to device"); int result = LibUsb.submitTransfer(transfer); if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to submit transfer", result); >public static void main(String[] args) < Test app = new Test(); >> 

Спасибо заранее за любые предложения.

Первое: если вы не участвуете в возиться и вмешиваться, я предлагаю вам лучше жить с уже предоставленным программным обеспечением. Theres гора работы впереди, и поскольку это научное устройство, это может испортить ваши чтения.

Теперь, почему это не может работать: Интересно, что эта деталь bEndpointAddress 0x81 EP 1 IN . То, что он говорит нам, заключается в том, что есть конечная точка, которая может отправлять данные на хост. Да, вы не можете написать эту конечную точку. Это будет ждать, пока устройство не получит данные для отправки и просто перезапишет ваши данные в указанном вами буфере.

Почему это так: вы имеете дело с HID. Лучше прочитайте об этом, потому что вы не получите просто ASCII-буферы, а специально отформатированные массивы байтов, которые должны интерпретироваться в соответствии с HID-протоколом.

Единственный способ отправить данные на это устройство – использовать передачу управления в конечной точке 0x00.

Самый простой способ начать работу – использовать программное обеспечение c++ с помощью usb-сниффера и пытаться понять данные, идущие туда и обратно.

Источник

Оцените статью