Я пытаюсь прочитать данные из чтения карт RFID, подключенного к последовательному порту, используя веб -серийный API JavaScript. Я смог подключиться к считыванию карт, но регистрация данных, похоже, не из моих журналов консоли. Как получить эти данные.
Serial Data Reader
body {
font-family: Arial, sans-serif;
}
#status {
font-size: 16px;
}
#serial-data {
font-size: 18px;
font-weight: bold;
color: green;
}
Serial Data from COM Port
Connect to Device
Not connected
Waiting for data...
let port;
let reader;
let writer;
let inputDone;
let inputStream;
let outputStream;
const statusElement = document.getElementById('status');
const serialDataElement = document.getElementById('serial-data');
const connectButton = document.getElementById('connectBtn');
// Request permission to access the serial device and open it
async function connectToDevice() {
try {
port = await navigator.serial.requestPort(); // Request the user to select a serial port
console.log("Port selected:", port); // Log port information
await port.open({ baudRate: 9600 }); // Open the serial port (adjust baud rate if needed)
// Setup the input and output streams
inputStream = port.readable;
outputStream = port.writable;
inputDone = inputStream.getReader();
statusElement.textContent = `Connected to ${port.getInfo().usbVendorId}:${port.getInfo().usbProductId}`;
// Start reading data from the device
readSerialData();
} catch (err) {
console.error('Error accessing serial port:', err);
statusElement.textContent = 'Error: Could not connect to device';
}
}
// Read data from the serial port
async function readSerialData() {
try {
// Continuously read data from the device
while (true) {
const { value, done } = await inputDone.read(); // Read the data
if (done) {
console.log("Stream done");
break;
}
// Log the raw data for debugging
console.log("Raw data received:", value);
// Check if the value is valid, and decode if it's a valid Uint8Array
if (value && value.length > 0) {
const receivedData = new TextDecoder().decode(value); // Decode the data
console.log("Decoded data:", receivedData); // Log the decoded data
serialDataElement.textContent = receivedData.trim(); // Show the data in the frontend
} else {
console.warn("Empty data received");
}
}
} catch (err) {
console.error('Error reading from the serial port:', err);
statusElement.textContent = 'Error: Failed to read data';
}
}
// Set up the button to connect to the device
connectButton.addEventListener('click', () => {
statusElement.textContent = 'Connecting to device...';
connectToDevice();
});
< /code>
output: < /p>
select port < /p>
Данные из чтения карты < /p>
Заигрываемые данные, по -видимому, отличаются от данных, которые я искал. Когда я сканирую карту, данные, которые регистрируются на другом веб -сайте, - «12561111915» (номер карты), но в моей консоли он регистрируется как «733994570».
Подробнее здесь: https://stackoverflow.com/questions/795 ... erial-port
Считать данные от чтения карт RFID, подключенного к последовательному порту ⇐ Javascript
Форум по Javascript
1743570598
Anonymous
Я пытаюсь прочитать данные из чтения карт RFID, подключенного к последовательному порту, используя веб -серийный API JavaScript. Я смог подключиться к считыванию карт, но регистрация данных, похоже, не из моих журналов консоли. Как получить эти данные.
Serial Data Reader
body {
font-family: Arial, sans-serif;
}
#status {
font-size: 16px;
}
#serial-data {
font-size: 18px;
font-weight: bold;
color: green;
}
Serial Data from COM Port
Connect to Device
Not connected
Waiting for data...
let port;
let reader;
let writer;
let inputDone;
let inputStream;
let outputStream;
const statusElement = document.getElementById('status');
const serialDataElement = document.getElementById('serial-data');
const connectButton = document.getElementById('connectBtn');
// Request permission to access the serial device and open it
async function connectToDevice() {
try {
port = await navigator.serial.requestPort(); // Request the user to select a serial port
console.log("Port selected:", port); // Log port information
await port.open({ baudRate: 9600 }); // Open the serial port (adjust baud rate if needed)
// Setup the input and output streams
inputStream = port.readable;
outputStream = port.writable;
inputDone = inputStream.getReader();
statusElement.textContent = `Connected to ${port.getInfo().usbVendorId}:${port.getInfo().usbProductId}`;
// Start reading data from the device
readSerialData();
} catch (err) {
console.error('Error accessing serial port:', err);
statusElement.textContent = 'Error: Could not connect to device';
}
}
// Read data from the serial port
async function readSerialData() {
try {
// Continuously read data from the device
while (true) {
const { value, done } = await inputDone.read(); // Read the data
if (done) {
console.log("Stream done");
break;
}
// Log the raw data for debugging
console.log("Raw data received:", value);
// Check if the value is valid, and decode if it's a valid Uint8Array
if (value && value.length > 0) {
const receivedData = new TextDecoder().decode(value); // Decode the data
console.log("Decoded data:", receivedData); // Log the decoded data
serialDataElement.textContent = receivedData.trim(); // Show the data in the frontend
} else {
console.warn("Empty data received");
}
}
} catch (err) {
console.error('Error reading from the serial port:', err);
statusElement.textContent = 'Error: Failed to read data';
}
}
// Set up the button to connect to the device
connectButton.addEventListener('click', () => {
statusElement.textContent = 'Connecting to device...';
connectToDevice();
});
< /code>
output: < /p>
select port < /p>
Данные из чтения карты < /p>
Заигрываемые данные, по -видимому, отличаются от данных, которые я искал. Когда я сканирую карту, данные, которые регистрируются на другом веб -сайте, - «12561111915» (номер карты), но в моей консоли он регистрируется как «733994570».
Подробнее здесь: [url]https://stackoverflow.com/questions/79549671/read-data-from-rfid-card-reader-connected-to-serial-port[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия