You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
yudao/RFIDSocketNBDDemo.java

364 lines
13 KiB
Java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* 南北达 UHF RFID 读写器盘存演示(独立可运行,无任何第三方依赖)。
*
* <p>直接运行: {@code java RFIDSocketNBDDemo.java [host] [port]}
*
* <p>协议要点(V3.8):
* <pre>
* 帧格式:Head(0xA0) | Len | Address | Cmd | Data(N) | Check
* Len = Address + Cmd + Data + Check 的字节数
* Check = (~sum + 1) & 0xFF (除 Check 外所有字节的校验和)
* </pre>
*/
public class RFIDSocketNBDDemo {
private static final int HEAD = 0xA0;
private static final int DEFAULT_ADDRESS = 0xFF; // 广播地址,任何读写器都会响应
private static final int READ_BUFFER_SIZE = 1024;
private static final int MAX_FRAME_LEN = 1024;
// 命令码
private static final int CMD_GET_FIRMWARE_VERSION = 0x72; // 读取固件版本(诊断用)
private static final int CMD_INVENTORY_6C = 0x80; // 6C 盘存(缓存模式)
private static final int CMD_REAL_TIME_INVENTORY_6C = 0x89; // 6C 实时盘存
private static final int CMD_SESSION_INVENTORY_6C = 0x8B; // 6C session 盘存
private static final int CMD_INVENTORY_6B = 0xB0; // 6B 盘存
private static final int CMD_GET_INVENTORY_BUFFER = 0x90; // 提取缓存
private static final int CMD_GET_AND_RESET_BUFFER = 0x91; // 提取并清空缓存
private final Socket socket;
private final OutputStream out;
private final InputStream in;
private final Set<String> tagSet = ConcurrentHashMap.newKeySet();
private final AtomicBoolean running = new AtomicBoolean(false);
private Thread readerThread;
public RFIDSocketNBDDemo(String host, int port) throws IOException {
this.socket = new Socket();
this.socket.connect(new InetSocketAddress(host, port), 3000);
this.socket.setTcpNoDelay(true);
this.out = socket.getOutputStream();
this.in = socket.getInputStream();
System.out.println("[INFO] 已连接 " + host + ":" + port);
}
// ------------------------------------------------------------------
// 编解码
// ------------------------------------------------------------------
private static byte checksum(byte[] data, int offset, int length) {
int sum = 0;
for (int i = offset; i < offset + length; i++) {
sum += (data[i] & 0xFF);
}
return (byte) (((~sum) + 1) & 0xFF);
}
private synchronized void send(int cmd, byte... data) throws IOException {
int dataLen = data == null ? 0 : data.length;
int len = 1 + 1 + dataLen + 1; // Address + Cmd + Data + Check
byte[] frame = new byte[2 + len];
frame[0] = (byte) HEAD;
frame[1] = (byte) len;
frame[2] = (byte) DEFAULT_ADDRESS;
frame[3] = (byte) cmd;
if (dataLen > 0) {
System.arraycopy(data, 0, frame, 4, dataLen);
}
frame[frame.length - 1] = checksum(frame, 0, frame.length - 1);
out.write(frame);
out.flush();
System.out.println("[TX] " + toHex(frame));
}
// ------------------------------------------------------------------
// 盘存命令
// ------------------------------------------------------------------
/**
* 查询固件版本(0x72),用于诊断通信链路是否正常。
* 该命令无参数且必然返回,是判断"地址是否正确 / 连接是否正常"的最佳手段。
*/
public synchronized void getFirmwareVersion() throws IOException {
send(CMD_GET_FIRMWARE_VERSION);
}
public synchronized void inventory6B() throws IOException {
send(CMD_INVENTORY_6B);
}
public synchronized void inventory6C(int repeat) throws IOException {
send(CMD_INVENTORY_6C, (byte) repeat);
}
public synchronized void inventory6CSession(int session, int target, int repeat) throws IOException {
send(CMD_SESSION_INVENTORY_6C, (byte) session, (byte) target, (byte) repeat);
}
public synchronized void inventory6CRealTime(int repeat) throws IOException {
send(CMD_REAL_TIME_INVENTORY_6C, (byte) repeat);
}
public synchronized void fetchInventoryBuffer(boolean andReset) throws IOException {
send(andReset ? CMD_GET_AND_RESET_BUFFER : CMD_GET_INVENTORY_BUFFER);
}
// ------------------------------------------------------------------
// 读线程与解析
// ------------------------------------------------------------------
public void start() {
if (!running.compareAndSet(false, true)) {
return;
}
readerThread = new Thread(this::readLoop, "rfid-reader");
readerThread.setDaemon(true);
readerThread.start();
}
private void readLoop() {
byte[] buf = new byte[READ_BUFFER_SIZE];
List<Byte> frame = new ArrayList<>(64);
while (running.get()) {
int n;
try {
n = in.read(buf);
} catch (IOException e) {
System.out.println("[INFO] 连接断开,读线程退出");
break;
}
if (n == -1) {
System.out.println("[INFO] 连接关闭(EOF)");
break;
}
for (int i = 0; i < n; i++) {
int ub = buf[i] & 0xFF;
if (frame.isEmpty()) {
if (ub == HEAD) {
frame.add(buf[i]);
}
continue;
}
frame.add(buf[i]);
if (frame.size() >= 2) {
int len = frame.get(1) & 0xFF;
if (len < 3 || len > MAX_FRAME_LEN) {
frame.clear();
continue;
}
int total = 2 + len;
if (frame.size() >= total) {
byte[] bytes = new byte[total];
for (int k = 0; k < total; k++) {
bytes[k] = frame.get(k);
}
frame.subList(0, total).clear();
handleFrame(bytes);
}
}
}
}
running.set(false);
}
private void handleFrame(byte[] frame) {
byte expected = checksum(frame, 0, frame.length - 1);
if (expected != frame[frame.length - 1]) {
System.out.println("[RX] 校验失败: " + toHex(frame));
return;
}
System.out.println("[RX] " + toHex(frame));
int cmd = frame[3] & 0xFF;
byte[] data = Arrays.copyOfRange(frame, 4, frame.length - 1);
switch (cmd) {
case CMD_GET_FIRMWARE_VERSION:
// 返回:Major(1) + Minor(1),即固件主版本号 + 次版本号
if (data.length >= 2) {
System.out.println(" [固件版本] v" + (data[0] & 0xFF) + "." + (data[1] & 0xFF));
} else {
System.out.println(" [固件版本] 返回数据异常: " + toHex(data));
}
break;
case CMD_INVENTORY_6B:
parse6B(data);
break;
case CMD_INVENTORY_6C:
case CMD_GET_INVENTORY_BUFFER:
case CMD_GET_AND_RESET_BUFFER:
parse6CBuffer(data);
break;
case CMD_REAL_TIME_INVENTORY_6C:
case CMD_SESSION_INVENTORY_6C:
parse6CRealTime(data);
break;
default:
// 忽略其它帧(如错误响应、汇总帧)
}
}
private void parse6B(byte[] data) {
// 6B 盘存:AntID(1) + UID(8),命令完成帧为 AntID(1) + TagFound(1)
for (int i = 0; i + 9 <= data.length; i += 9) {
String uid = toHex(data, i + 1, 8);
tagSet.add(uid);
System.out.println(" [6B] UID = " + uid);
}
}
private void parse6CBuffer(byte[] data) {
// 缓存提取:TagCount(2) + [DataLen(2) + Data(N)]* 多组
// 盘存:AntID(1) + TagCount(2) + ReadRate(2) + TotalRead(4)
scanEpc(data);
}
private void parse6CRealTime(byte[] data) {
// 实时盘存:FreqAnt(1) + PC(2) + EPC(N) + RSSI(1)
scanEpc(data);
}
private void scanEpc(byte[] data) {
int i = 0;
while (i + 3 < data.length) {
int pc = data[i + 1] & 0xFF;
int epcWords = (pc >> 3) & 0x1F;
int epcBytes = epcWords * 2;
if (epcBytes <= 0 || epcBytes > 62) {
i++;
continue;
}
int blockLen = 1 + 2 + epcBytes + 1;
if (i + blockLen > data.length) {
break;
}
String epc = toHex(data, i + 3, epcBytes);
tagSet.add(epc);
System.out.println(" [6C] EPC = " + epc);
i += blockLen;
}
}
// ------------------------------------------------------------------
// 工具
// ------------------------------------------------------------------
private static String toHex(byte[] data) {
return toHex(data, 0, data.length);
}
private static String toHex(byte[] data, int offset, int length) {
StringBuilder sb = new StringBuilder(length * 2);
for (int i = offset; i < offset + length; i++) {
sb.append(String.format("%02X", data[i] & 0xFF));
}
return sb.toString();
}
public void close() {
running.set(false);
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
// ignore
}
if (readerThread != null) {
readerThread.interrupt();
}
}
// ------------------------------------------------------------------
// main
// ------------------------------------------------------------------
public static void main(String[] args) throws Exception {
String host = args.length > 0 ? args[0] : "10.43.26.128";
int port = args.length > 1 ? Integer.parseInt(args[1]) : 4001;
RFIDSocketNBDDemo rfid = new RFIDSocketNBDDemo(host, port);
rfid.start();
Scanner scanner = new Scanner(System.in);
printMenu();
while (true) {
System.out.print("> ");
String line = scanner.nextLine().trim();
if (line.isEmpty()) {
continue;
}
switch (line) {
case "0":
System.out.println("查询固件版本(诊断链路)...");
rfid.getFirmwareVersion();
break;
case "1":
System.out.println("盘存 6B 标签 ...");
rfid.inventory6B();
break;
case "2":
System.out.println("盘存 6C 标签(session 模式)...");
rfid.inventory6CSession(1, 0, 0xFF);
break;
case "3":
System.out.println("盘存 6C 标签(实时模式)...");
rfid.inventory6CRealTime(0xFF);
break;
case "4":
System.out.println("盘存 6C 标签(缓存模式)...");
rfid.inventory6C(0xFF);
break;
case "5":
System.out.println("提取缓存标签 ...");
rfid.fetchInventoryBuffer(true);
break;
case "s":
System.out.println("已读到标签(去重,共 " + rfid.tagSet.size() + " 张):");
for (String t : rfid.tagSet) {
System.out.println(" " + t);
}
break;
case "c":
rfid.tagSet.clear();
System.out.println("已清空标签缓存");
break;
case "q":
rfid.close();
System.out.println("退出");
return;
default:
printMenu();
}
}
}
private static void printMenu() {
System.out.println("========================================");
System.out.println(" 0 - 查询固件版本(诊断链路是否正常)");
System.out.println(" 1 - 盘存 6B 标签");
System.out.println(" 2 - 盘存 6C 标签(session 模式,推荐)");
System.out.println(" 3 - 盘存 6C 标签(实时模式)");
System.out.println(" 4 - 盘存 6C 标签(缓存模式)");
System.out.println(" 5 - 提取缓存标签");
System.out.println(" s - 查看已读到标签");
System.out.println(" c - 清空标签缓存");
System.out.println(" q - 退出");
System.out.println("========================================");
}
}