错误:类型错误 [ERR_INVALID_ARG_TYPE]:“size”参数必须是数字类型。收到 Buffer 的实例

问题描述 投票:0回答:1

我尝试在连接 USB 时读取数据。我有一个已成功连接的读卡器,但是当我尝试执行读取功能时,它给出错误: TypeError [ERR_INVALID_ARG_TYPE]:“size”参数必须是数字类型。收到 Buffer 的实例

这是我尝试过的片段

const express = require('express');
const usb = require('usb');
const cors = require('cors');
const app = express();
const port = 3001;

app.use(cors());
app.use(express.json());

// Function to list all available USB devices
function listUSBDevices() {
  const devices = usb.getDeviceList();
  // Return a list of USB devices
  return devices.map((device, index) => ({
    id: index + 1,
    descriptor: device.deviceDescriptor,
    manufacturer: device.deviceDescriptor.iManufacturer,
    product: device.deviceDescriptor.iProduct,
  }));
}

// Function to connect to a specific USB device
function connectToUSBDevice(targetVendorId, targetProductId) {
  const devices = usb.getDeviceList();
  const targetDevice = devices.find((device) => {
    return (
      device.deviceDescriptor.idVendor === targetVendorId &&
      device.deviceDescriptor.idProduct === targetProductId
    );
  });

  return targetDevice;
}

// Function to read data from the USB device
function readDataFromUSBDevice(vendorId, productId, blockNum, callback) {
  const targetDevice = connectToUSBDevice(vendorId, productId);

  if (!targetDevice) {
    callback('USB device not found.');
    return;
  }

  try {
    targetDevice.open();

    const interface = targetDevice.interfaces[0];
    const endpoint = interface.endpoints[0];

    const bufferSize = 64; // Set the buffer size to your desired size in bytes
    const buffer = Buffer.alloc(bufferSize); // Create a buffer to hold the read data

    // Send a read command (modify this part according to your device's protocol)
    buffer[0] = 0x04;
    buffer[1] = 0x21;
    buffer[2] = 0x02;
    buffer[3] = blockNum; // Replace with the desired block number
    // Add other necessary modifications to the buffer based on your protocol

    endpoint.transfer(buffer, (error, actualLength) => {
      if (error) {
        console.error('Error sending command to USB device:', error);
        targetDevice.close();
        callback('Error reading from USB device.');
      } else {
        // Process the received data and send it to the callback function
        const data = buffer.slice(0, actualLength).toString('utf8');
        targetDevice.close();
        callback(null, data);
      }
    });
  } catch (error) {
    console.error('Error reading from USB device:', error);
    callback('Error reading from USB device.');
  }
}


// Handle requests to the root URL
app.get('/', (req, res) => {
  res.send('Hello, this is your server response!');
});

app.get('/listUSBDevices', (req, res) => {
  const usbDevices = listUSBDevices();
  res.json(usbDevices);
});

// Add a new route for reading data
app.post('/communicateWithDevice', (req, res) => {
  const { vendorId, productId, action, data, blockNum } = req.body;

  if (action === 'read') {
    readDataFromUSBDevice(vendorId, productId, blockNum, (error, result) => {
      if (error) {
        res.json({ message: error });
      } else {
        res.json({ message: result });
      }
    });
  } else if (action === 'write') {
    const result = writeToUSBDevice(targetDevice, data);
    res.json({ message: result });
  } else if (action === 'connectToDevice') { // Corrected action name
    const targetDevice = connectToUSBDevice(vendorId, productId);
    const result = targetDevice ? 'Connected to USB device successfully.' : 'USB device not found.';
    res.json({ message: result });
  } else {
    res.json({ message: 'Invalid action specified.' });
  }
});


app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
javascript css reactjs node.js usb
1个回答
0
投票

我发现的问题(我刚刚在代码中遇到了这个错误)是

endpoint.transfer
是我的问题。

尝试这样写...

endpoint.transfer(64, (error, data) => {
                if (error) {
                    console.error('Error transferring data:', error);
                } else {
                    const receivedData = data || dataBuffer;
                    console.log('Data sent successfully', dataBuffer);
                }
            });

我将对传输方法的调用调整为与上面的示例类似的内容,并且不再看到此错误。

参考 - https://github.com/node-usb/node-usb/blob/ae4baaf417bd9a4226476733e74a3a001b07f259/tsc/usb/endpoint.ts#L79

© www.soinside.com 2019 - 2024. All rights reserved.