feat: 多系统新增扫码中间件与 AGV 对接,优化拧紧与退库流程
新增扫码中间件支持网络型扫码枪键盘注入,AGV 对接从 WMS 迁至 MES 统一管理;新增拧紧不合格人工处置与 PLC 对账机制,优化退库单关联与工位终端功能,同时清理旧 AGV 任务表,完善数据库与配置项。
This commit is contained in:
@@ -0,0 +1,629 @@
|
||||
package scanbridge
|
||||
|
||||
// 扫码中间件(键盘 HID 注入):在单个 TCP 端口上同时接收两类网络型扫码设备的数据,
|
||||
// 按内容自动判别帧格式、解析出扫码文本,并用「模拟键盘 HID」注入到当前光标窗口。
|
||||
//
|
||||
// 两类设备都是 TCP 客户端连到本机 7757,长连接常驻、扫码时才推数据。虽然帧格式不同,
|
||||
// 本中间件【按收到的字节内容自动分流】,同一端口同时兼容:
|
||||
//
|
||||
// A) iData PAD —— 二进制长度前缀帧:
|
||||
// [4 字节头 00 03][2 字节大端长度 L][L 字节载荷]
|
||||
// 载荷文本形如 "barcode <主条码A> <次条码B>",B 段按字节做了 \uXX 转义需还原。
|
||||
// 每收一帧回 ASCII ACK(0x06)。
|
||||
//
|
||||
// B) 新大陆手机端 —— 长度+校验帧:
|
||||
// [1 字节 总长度 N][1 字节 校验和][N-2 字节 载荷(ASCII 原文)]
|
||||
// 校验和 = 载荷所有字节之和 & 0xFF。载荷即扫码原文,整段注入。
|
||||
// 默认不回包(设备只推不收)。
|
||||
//
|
||||
// C) HTTP 客户端 —— GET 回状态页不注入;POST/PUT 取 body 提取扫码值注入,回 200。
|
||||
//
|
||||
// 判别依据(三者互斥、无歧义):首字节 0x00 且次字节 0x03 → PAD;首字节=N(总长,≥3)
|
||||
// → 手机端(总长至少 3,首字节不可能为 0x00);以 GET/POST/PUT… 开头 → HTTP。
|
||||
//
|
||||
// 三种模式解码后都统一走「模拟键盘 HID 注入」,把文本敲进当前光标所在窗口
|
||||
// (微信 / 浏览器 / 记事本 / 任意输入框等),末尾不回车 —— 电脑端对设备型号完全无感。
|
||||
//
|
||||
// 服务常驻监听,因空闲永不主动断开连接。解码结论写入 captures/analysis.log,
|
||||
// 原始字节存 captures/raw_*.bin。
|
||||
//
|
||||
// 端口容错:7757 绑不上(官网工具占用 / 同机两进程同开 / 其它程序占用)时仅记一行日志、
|
||||
// 不退出、不影响主进程;谁先绑谁监听,后到的只记日志。
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
const sep = "================================================================"
|
||||
|
||||
// Options 扫码中间件运行参数。零值字段由 Start 填充默认值(端口 :7757 / 空闲 3s / 字符间隔 2ms)。
|
||||
type Options struct {
|
||||
Addrs []string // 监听地址列表(默认 [":7757"])
|
||||
Idle time.Duration // 空闲超时:仅用于切分帧,永不因空闲断开连接
|
||||
KbdDelay time.Duration // 键盘注入字符间隔(模拟真实 HID 速率,默认 2ms)
|
||||
NoKbd bool // true=仅日志、不模拟键盘注入(调试用)
|
||||
Nlak bool // true=给新大陆手机端也回 ASCII ACK(0x06)(默认不回)
|
||||
}
|
||||
|
||||
// 运行期参数(单进程单实例,由 Start 注入)。
|
||||
var (
|
||||
kbdDelay time.Duration
|
||||
noKbd bool
|
||||
nlak bool
|
||||
)
|
||||
|
||||
// unescapeRe 预编译一次,避免每帧重复编译。
|
||||
var unescapeRe = regexp.MustCompile(`\\u([0-9A-Fa-f]{2})`)
|
||||
|
||||
// 三种帧模式
|
||||
type frameMode int
|
||||
|
||||
const (
|
||||
modeUnknown frameMode = iota
|
||||
modePAD // iData PAD:00 03 + 大端长度
|
||||
modeNewland // 新大陆手机:总长 + 校验和
|
||||
modeHTTP // HTTP 请求
|
||||
)
|
||||
|
||||
// Start 启动扫码中间件:按 Options 监听端口,接收 iData PAD / 新大陆手机两类设备数据,
|
||||
// 解析后模拟键盘 HID 注入当前光标窗口。任一端口被占用仅记日志、不影响主进程;所有端口都失败返回 error(仍非致命)。
|
||||
// ctx 取消时优雅关闭所有监听器。
|
||||
func Start(ctx context.Context, opts Options) error {
|
||||
if len(opts.Addrs) == 0 {
|
||||
opts.Addrs = []string{":7757"}
|
||||
}
|
||||
if opts.Idle <= 0 {
|
||||
opts.Idle = 3 * time.Second
|
||||
}
|
||||
if opts.KbdDelay <= 0 {
|
||||
opts.KbdDelay = 2 * time.Millisecond
|
||||
}
|
||||
kbdDelay = opts.KbdDelay
|
||||
noKbd = opts.NoKbd
|
||||
nlak = opts.Nlak
|
||||
|
||||
if err := os.MkdirAll(capturesDir(), 0o755); err != nil {
|
||||
log.Printf("⚠️ 扫码中间件创建 captures 目录失败(仅影响落盘,监听与注入不受影响): %v", err)
|
||||
}
|
||||
|
||||
kbdMode := fmt.Sprintf("键盘HID注入(开,不回车,字符间隔=%v)", kbdDelay)
|
||||
if noKbd {
|
||||
kbdMode = "键盘HID注入(关,仅日志)"
|
||||
}
|
||||
|
||||
okCount := 0
|
||||
for _, a := range opts.Addrs {
|
||||
a = strings.TrimSpace(a)
|
||||
if a == "" {
|
||||
continue
|
||||
}
|
||||
ln, err := net.Listen("tcp", a)
|
||||
if err != nil {
|
||||
log.Printf("⚠️ 7757 被占用,扫码监听未启动,主程序不受影响: %v", err)
|
||||
continue
|
||||
}
|
||||
okCount++
|
||||
log.Printf("✅ 扫码中间件正在监听 %s | %s", a, kbdMode)
|
||||
go acceptLoop(ln, a, opts.Idle, ctx)
|
||||
}
|
||||
|
||||
if okCount == 0 {
|
||||
log.Printf("⚠️ 扫码监听:没有任何端口监听成功(7757 被占用/被拦截),扫码功能不可用,主程序继续正常运行")
|
||||
return fmt.Errorf("scanbridge: no listener bound")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func acceptLoop(ln net.Listener, port string, idle time.Duration, ctx context.Context) {
|
||||
// ctx 取消时关闭监听器,使阻塞的 Accept 返回,干净退出(避免泄漏 goroutine)。
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
_ = ln.Close()
|
||||
}()
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
log.Printf("accept %s 错误: %v", port, err)
|
||||
continue
|
||||
}
|
||||
go handleConn(conn, port, idle)
|
||||
}
|
||||
}
|
||||
|
||||
// handleConn 处理一条 TCP 连接:常驻读取,按内容自动识别帧模式;空闲仅用于切分帧,绝不主动断开。
|
||||
func handleConn(conn net.Conn, port string, idle time.Duration) {
|
||||
defer func() { _ = conn.Close() }()
|
||||
remote := conn.RemoteAddr().String()
|
||||
log.Printf("🔌 [%s] 新连接: %s", port, remote)
|
||||
|
||||
var buf []byte
|
||||
tmp := make([]byte, 8192)
|
||||
mode := modeUnknown
|
||||
|
||||
for {
|
||||
_ = conn.SetReadDeadline(time.Now().Add(idle))
|
||||
n, err := conn.Read(tmp)
|
||||
if n > 0 {
|
||||
buf = append(buf, tmp[:n]...)
|
||||
}
|
||||
|
||||
// ---- 首次数据到达时判定帧模式 ----
|
||||
if mode == modeUnknown && len(buf) > 0 {
|
||||
switch {
|
||||
case buf[0] == 0x00:
|
||||
// 首字节 0x00:只可能是 PAD(00 03 头)。手机端首字节=总长(≥3),永不为 0x00。
|
||||
// 若 TCP 把 4 字节头拆包、暂时只有 1 字节,则保持 unknown 等下一批,避免误判。
|
||||
if len(buf) >= 2 {
|
||||
if buf[1] == 0x03 {
|
||||
mode = modePAD
|
||||
log.Printf("🔧 [%s] %s → iData PAD 二进制帧模式(头=%s)", port, remote, hex2(buf[:min(4, len(buf))]))
|
||||
} else {
|
||||
// 首字节 0x00 但次字节非 0x03:按手机端兜底(其解析会丢弃非法长度字节重新对齐)
|
||||
mode = modeNewland
|
||||
log.Printf("📱 [%s] %s → 新大陆手机端「长度+校验」帧模式(首字节 00 非 PAD 头)", port, remote)
|
||||
}
|
||||
}
|
||||
case looksLikeHTTP(buf):
|
||||
mode = modeHTTP
|
||||
log.Printf("🌐 [%s] %s → HTTP 模式", port, remote)
|
||||
default:
|
||||
mode = modeNewland
|
||||
log.Printf("📱 [%s] %s → 新大陆手机端「长度+校验」帧模式", port, remote)
|
||||
}
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case modePAD:
|
||||
buf = parsePADFrames(conn, remote, buf)
|
||||
case modeNewland:
|
||||
buf = parseNewlandFrames(conn, remote, buf)
|
||||
case modeHTTP:
|
||||
if req, rest, ok := trySplitHTTP(buf); ok {
|
||||
processHTTP(conn, remote, req)
|
||||
buf = rest
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if ne, ok := err.(net.Error); ok && ne.Timeout() {
|
||||
// 空闲超时:仅表示"当前没有新数据",连接保持不动
|
||||
if mode == modeUnknown && len(buf) > 0 && buf[0] != 0x00 {
|
||||
// 攒到了可判定的数据却判不出模式(罕见),兜底记录
|
||||
processRaw(conn, remote, buf)
|
||||
buf = buf[:0]
|
||||
}
|
||||
// 若 buf[0]==0x00(疑似 PAD 头碎片),继续等剩余字节,不兜底、不丢弃
|
||||
continue
|
||||
}
|
||||
if len(buf) > 0 {
|
||||
log.Printf("⚠️ [%s] 连接关闭时残留 %d 字节,按裸数据兜底处理", port, len(buf))
|
||||
processRaw(conn, remote, buf)
|
||||
}
|
||||
log.Printf("🔌 [%s] 连接结束: %s", port, remote)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// A) iData PAD: [00 03][2字节大端长度 L][L 字节载荷]
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// parsePADFrames 解析 PAD 帧:头异常/尾部 NUL 等非法字节丢弃 1 字节重新对齐;
|
||||
// 帧未收全则缓存等下次。
|
||||
func parsePADFrames(conn net.Conn, remote string, buf []byte) []byte {
|
||||
for len(buf) >= 4 {
|
||||
length := int(buf[2])<<8 | int(buf[3])
|
||||
if length <= 0 || length > 16*1024*1024 {
|
||||
// 头异常(含帧间残留的尾随 NUL 等),丢弃 1 字节重新对齐
|
||||
buf = buf[1:]
|
||||
continue
|
||||
}
|
||||
if len(buf) < 4+length {
|
||||
break // 帧未收全
|
||||
}
|
||||
hdr := buf[:4]
|
||||
payload := buf[4 : 4+length]
|
||||
buf = buf[4+length:]
|
||||
processPADFrame(conn, remote, hdr, payload)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
func processPADFrame(conn net.Conn, remote string, hdr, payload []byte) {
|
||||
ts := time.Now().Format("20060102_150405.000")
|
||||
raw := append(append([]byte{}, hdr...), payload...)
|
||||
text := unescapeUnicode(payload)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("\n" + sep + "\n")
|
||||
b.WriteString(fmt.Sprintf("📥 [PAD iData 帧] 时间=%s | 来源=%s | 头=%s | 载荷=%d字节\n", ts, remote, hex2(hdr), len(payload)))
|
||||
b.WriteString(sep + "\n")
|
||||
b.WriteString(fmt.Sprintf("\n[原始字节 HEX] %s\n", hex2(payload)))
|
||||
b.WriteString(fmt.Sprintf("[解码内容] %s\n", text))
|
||||
|
||||
fields := strings.Fields(text)
|
||||
if len(fields) >= 1 && strings.HasPrefix(fields[0], "barcode") {
|
||||
b.WriteString("\n[结构化]\n")
|
||||
if len(fields) >= 2 {
|
||||
b.WriteString(fmt.Sprintf(" 主条码(A) = %s\n", fields[1]))
|
||||
}
|
||||
if len(fields) >= 3 {
|
||||
b.WriteString(fmt.Sprintf(" 次条码(B) = %s\n", fields[2]))
|
||||
}
|
||||
}
|
||||
b.WriteString(sep + "\n")
|
||||
|
||||
inject := extractInjectText(text)
|
||||
b.WriteString(fmt.Sprintf("[注入内容] %s\n", describeInject(inject)))
|
||||
b.WriteString(sep + "\n")
|
||||
|
||||
// 优先注入(用户感知路径),再做落盘/打印等 I/O —— 避免文件写阻塞拖慢注入
|
||||
injectText(inject, "PAD")
|
||||
sendAck(conn)
|
||||
|
||||
fmt.Print(b.String())
|
||||
appendToLog(b.String())
|
||||
saveRaw(ts, remote, raw)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// B) 新大陆手机端: [1字节 总长度 N][1字节 载荷校验和][N-2 字节 载荷]
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func parseNewlandFrames(conn net.Conn, remote string, buf []byte) []byte {
|
||||
for len(buf) >= 2 {
|
||||
n := int(buf[0])
|
||||
if n < 3 || n > 255 {
|
||||
// 长度非法,丢 1 字节重新对齐
|
||||
buf = buf[1:]
|
||||
continue
|
||||
}
|
||||
if len(buf) < n {
|
||||
break // 帧未收全
|
||||
}
|
||||
frame := buf[:n]
|
||||
buf = buf[n:]
|
||||
payload := frame[2:]
|
||||
sum := 0
|
||||
for _, c := range payload {
|
||||
sum += int(c)
|
||||
}
|
||||
chkOK := byte(sum&0xFF) == frame[1]
|
||||
processNewlandFrame(conn, remote, frame, payload, chkOK)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
func processNewlandFrame(conn net.Conn, remote string, frame, payload []byte, chkOK bool) {
|
||||
ts := time.Now().Format("20060102_150405.000")
|
||||
text := string(payload)
|
||||
|
||||
chkMark := "校验通过"
|
||||
if !chkOK {
|
||||
chkMark = "⚠️ 校验不符(仍按原文处理)"
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("\n" + sep + "\n")
|
||||
b.WriteString(fmt.Sprintf("📥 [手机 新大陆帧] 时间=%s | 来源=%s | 总长=%d | 校验=0x%02X(%s) | 载荷=%d字节\n",
|
||||
ts, remote, len(frame), frame[1], chkMark, len(payload)))
|
||||
b.WriteString(sep + "\n")
|
||||
b.WriteString(fmt.Sprintf("\n[原始字节 HEX] %s\n", hex2(frame)))
|
||||
b.WriteString(fmt.Sprintf("[解码内容] %s\n", text))
|
||||
|
||||
inject := strings.TrimSpace(text)
|
||||
if !looksLikeText(inject) {
|
||||
inject = ""
|
||||
}
|
||||
b.WriteString(fmt.Sprintf("[注入内容] %s\n", describeInject(inject)))
|
||||
b.WriteString(sep + "\n")
|
||||
|
||||
// 优先注入,再做落盘/打印等 I/O
|
||||
injectText(inject, "手机")
|
||||
if nlak {
|
||||
sendAck(conn)
|
||||
}
|
||||
|
||||
fmt.Print(b.String())
|
||||
appendToLog(b.String())
|
||||
saveRaw(ts, remote, frame)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// C) HTTP
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func processHTTP(conn net.Conn, remote string, data []byte) {
|
||||
ts := time.Now().Format("20060102_150405.000")
|
||||
var b strings.Builder
|
||||
b.WriteString("\n" + sep + "\n")
|
||||
b.WriteString(fmt.Sprintf("📥 [HTTP 请求] 时间=%s | 来源=%s | %d字节\n", ts, remote, len(data)))
|
||||
b.WriteString(sep + "\n")
|
||||
b.WriteString(fmt.Sprintf("\n[原始字节 HEX] %s\n", hex2(data)))
|
||||
b.WriteString(fmt.Sprintf("[解码内容] %s\n", string(data)))
|
||||
b.WriteString(sep + "\n")
|
||||
|
||||
// 浏览器 GET / 或健康检查:回状态页,不注入(避免往光标打一堆 HTTP 头)
|
||||
if bytes.HasPrefix(data, []byte("GET ")) {
|
||||
log.Printf("🌐 收到 HTTP GET(浏览器/健康检查),回状态页,不注入")
|
||||
sendHTTPPage(conn)
|
||||
fmt.Print(b.String())
|
||||
appendToLog(b.String())
|
||||
saveRaw(ts, remote, data)
|
||||
return
|
||||
}
|
||||
|
||||
injectSrc := data
|
||||
if idx := bytes.Index(data, []byte("\r\n\r\n")); idx >= 0 {
|
||||
injectSrc = data[idx+4:]
|
||||
}
|
||||
inject := extractInjectText(string(injectSrc))
|
||||
if inject != "" {
|
||||
b.WriteString(fmt.Sprintf("[注入内容] %s\n%s\n", describeInject(inject), sep))
|
||||
}
|
||||
|
||||
// 优先注入,再做落盘/打印等 I/O
|
||||
injectText(inject, "HTTP")
|
||||
sendHTTPOK(conn)
|
||||
|
||||
fmt.Print(b.String())
|
||||
appendToLog(b.String())
|
||||
saveRaw(ts, remote, data)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 兜底:无法判定模式的数据
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func processRaw(conn net.Conn, remote string, data []byte) {
|
||||
ts := time.Now().Format("20060102_150405.000")
|
||||
var b strings.Builder
|
||||
b.WriteString("\n" + sep + "\n")
|
||||
b.WriteString(fmt.Sprintf("📥 [裸数据] 时间=%s | 来源=%s | %d字节\n", ts, remote, len(data)))
|
||||
b.WriteString(sep + "\n")
|
||||
b.WriteString(fmt.Sprintf("\n[原始字节 HEX] %s\n", hex2(data)))
|
||||
b.WriteString(fmt.Sprintf("[解码内容] %s\n", string(data)))
|
||||
b.WriteString(sep + "\n")
|
||||
|
||||
// 优先注入,再做落盘/打印等 I/O
|
||||
injectText(extractInjectText(string(data)), "裸数据")
|
||||
sendAck(conn)
|
||||
|
||||
fmt.Print(b.String())
|
||||
appendToLog(b.String())
|
||||
saveRaw(ts, remote, data)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 键盘注入 / 文本处理
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// injectText 统一走键盘 HID 注入(不回车),并记录耗时以便核对节流生效。
|
||||
func injectText(s, tag string) {
|
||||
if s == "" || noKbd {
|
||||
return
|
||||
}
|
||||
t0 := time.Now()
|
||||
if err := sendStringAsKeyboard(s); err != nil {
|
||||
log.Printf("⚠️ 键盘注入失败: %v", err)
|
||||
} else {
|
||||
log.Printf("⌨️ 已模拟键盘输入(%s, %d字符, 耗时%dms): %s",
|
||||
tag, len([]rune(s)), time.Since(t0).Milliseconds(), s)
|
||||
}
|
||||
}
|
||||
|
||||
func describeInject(s string) string {
|
||||
if s == "" {
|
||||
return "(无可注入内容)"
|
||||
}
|
||||
if noKbd {
|
||||
return s + " [已禁用注入]"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// extractInjectText 统一提取要注入光标的文本:
|
||||
// - PAD 的 "barcode <A> <B>" 格式 → 返回次条码 B
|
||||
// - JSON(如 {"code":"..."})→ 返回常见扫码字段值
|
||||
// - 其它可读文本(手机端等)→ 返回整段
|
||||
// - 不可读/空 → 返回空(不注入)
|
||||
func extractInjectText(text string) string {
|
||||
fields := strings.Fields(text)
|
||||
if len(fields) >= 3 && strings.HasPrefix(fields[0], "barcode") {
|
||||
return fields[2]
|
||||
}
|
||||
if strings.Contains(text, "{") && strings.Contains(text, "}") {
|
||||
if v := extractJSONScanValue(text); v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
t := strings.TrimSpace(text)
|
||||
if t != "" && looksLikeText(t) {
|
||||
return t
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// extractJSONScanValue 从 JSON 文本中提取常见扫码字段的值。
|
||||
func extractJSONScanValue(s string) string {
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(s), &m); err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, key := range []string{"code", "scan", "scancode", "barcode", "qr", "qrcode", "data", "value", "result", "content", "text", "sn", "id"} {
|
||||
if v, ok := m[key]; ok {
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
if val != "" {
|
||||
return val
|
||||
}
|
||||
case float64:
|
||||
return strconv.FormatFloat(val, 'f', -1, 64)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// unescapeRe 包级预编译一次(见 unescapeRe 定义)。unescapeUnicode 把载荷里的 \uXX(2 位十六进制)
|
||||
// 还原成对应字符。
|
||||
func unescapeUnicode(b []byte) string {
|
||||
return unescapeRe.ReplaceAllStringFunc(string(b), func(s string) string {
|
||||
m := unescapeRe.FindStringSubmatch(s)
|
||||
if m == nil {
|
||||
return s
|
||||
}
|
||||
c, err := strconv.ParseUint(m[1], 16, 8)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
return string(rune(c))
|
||||
})
|
||||
}
|
||||
|
||||
// looksLikeText 判断是否为可打印文本(允许 \r\n\t,其余必须 IsPrint)。
|
||||
func looksLikeText(s string) bool {
|
||||
for _, r := range s {
|
||||
if r == '\r' || r == '\n' || r == '\t' {
|
||||
continue
|
||||
}
|
||||
if !unicode.IsPrint(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// looksLikeHTTP 判断数据是否像 HTTP 请求。
|
||||
func looksLikeHTTP(b []byte) bool {
|
||||
for _, p := range [][]byte{[]byte("POST "), []byte("GET "), []byte("PUT "), []byte("DELETE "), []byte("HEAD "), []byte("OPTIONS ")} {
|
||||
if bytes.HasPrefix(b, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return bytes.Contains(b, []byte("\r\nHost:")) || bytes.Contains(b, []byte("\r\nContent-Type:"))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 应答
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// sendAck 回一个 ASCII ACK(0x06),确认已收到(PAD 需要,否则会反复重连)。
|
||||
func sendAck(conn net.Conn) {
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(3 * time.Second))
|
||||
_, _ = conn.Write([]byte{0x06})
|
||||
}
|
||||
|
||||
// sendHTTPOK 给 HTTP 客户端回 200。
|
||||
func sendHTTPOK(conn net.Conn) {
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(3 * time.Second))
|
||||
_, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK"))
|
||||
}
|
||||
|
||||
// sendHTTPPage 给浏览器 GET / 回一个状态页。
|
||||
func sendHTTPPage(conn net.Conn) {
|
||||
html := `<!doctype html><html><head><meta charset="utf-8"><title>扫码接收服务</title></head>` +
|
||||
`<body style="font-family:sans-serif;padding:24px"><h2>扫码统一接收服务运行中</h2>` +
|
||||
`<p>本机监听 <b>7757</b>:iData PAD 与新大陆手机端共用该端口,按内容自动识别两种帧格式。</p>` +
|
||||
`<p>扫码数据会自动解析,并模拟键盘注入当前光标所在的窗口(微信 / 浏览器 / 记事本等)。</p></body></html>`
|
||||
body := []byte(html)
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(3 * time.Second))
|
||||
_, _ = conn.Write([]byte(fmt.Sprintf(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\nConnection: close\r\n\r\n",
|
||||
len(body))))
|
||||
_, _ = conn.Write(body)
|
||||
}
|
||||
|
||||
// trySplitHTTP 尝试从 buf 中切出一条完整 HTTP 请求(按 Content-Length 判定 body 边界)。
|
||||
func trySplitHTTP(buf []byte) (req, rest []byte, ok bool) {
|
||||
if !looksLikeHTTP(buf) {
|
||||
return nil, nil, false
|
||||
}
|
||||
idx := bytes.Index(buf, []byte("\r\n\r\n"))
|
||||
if idx < 0 {
|
||||
return nil, nil, false
|
||||
}
|
||||
bodyStart := idx + 4
|
||||
cl := httpContentLength(buf[:bodyStart])
|
||||
if len(buf) < bodyStart+cl {
|
||||
return nil, nil, false
|
||||
}
|
||||
end := bodyStart + cl
|
||||
return buf[:end], buf[end:], true
|
||||
}
|
||||
|
||||
func httpContentLength(header []byte) int {
|
||||
s := strings.ToLower(string(header))
|
||||
i := strings.Index(s, "content-length:")
|
||||
if i < 0 {
|
||||
return 0
|
||||
}
|
||||
rest := s[i+len("content-length:"):]
|
||||
if j := strings.Index(rest, "\r\n"); j >= 0 {
|
||||
rest = rest[:j]
|
||||
}
|
||||
n, err := strconv.Atoi(strings.TrimSpace(rest))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 工具函数
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func hex2(b []byte) string { return strings.ToUpper(hex.EncodeToString(b)) }
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func saveRaw(ts, remote string, data []byte) {
|
||||
name := filepath.Join(capturesDir(), fmt.Sprintf("raw_%s_%s.bin", ts, sanitize(remote)))
|
||||
if err := os.WriteFile(name, data, 0o644); err == nil {
|
||||
log.Printf("💾 原始字节已保存: %s (%d bytes)", name, len(data))
|
||||
}
|
||||
}
|
||||
|
||||
func appendToLog(report string) {
|
||||
f, err := os.OpenFile(filepath.Join(capturesDir(), "analysis.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
_, _ = f.WriteString(report)
|
||||
}
|
||||
|
||||
func sanitize(s string) string {
|
||||
return strings.NewReplacer(":", "_", "[", "", "]", "", " ", "").Replace(s)
|
||||
}
|
||||
|
||||
func capturesDir() string {
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
return filepath.Join(filepath.Dir(exe), "captures")
|
||||
}
|
||||
return "captures"
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !windows
|
||||
|
||||
package scanbridge
|
||||
|
||||
import "log"
|
||||
|
||||
// 非 Windows 平台的占位实现:仅记录,不注入键盘。
|
||||
// 编译期即确定(build tag),生产环境(Windows 工位终端 / WMS / MES 服务器)走 keyboard_windows.go。
|
||||
func sendStringAsKeyboard(s string) error {
|
||||
log.Printf("⌨️ [非Windows] 跳过键盘注入: %s", s)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//go:build windows
|
||||
|
||||
package scanbridge
|
||||
|
||||
// 用 Windows user32.SendInput 以 Unicode 方式模拟键盘输入(HID 模式),
|
||||
// 把文本注入到「当前前台窗口 + 当前光标」位置,不受键盘布局影响。
|
||||
//
|
||||
// 关键优化:
|
||||
// 1. 逐字符节流(kbdDelay,默认 2ms):模仿真实 HID 扫码枪的固定输出速率。
|
||||
// 原本把整串按键「瞬时一次性」灌进去,会灌爆前台程序的消息队列,
|
||||
// 导致「一个字一个字往外蹦 / 卡顿 / 甚至掉字」——节流正是为此。
|
||||
// 2. 完整 UTF-16 处理:先转 UTF-16 code unit,非 BMP 字符(>0xFFFF,如 emoji)
|
||||
// 会正确拆成代理对,不再被 uint16(r) 截断。
|
||||
// 3. 最后一个字符后不再多余 sleep;kbdDelay=0 时回退为整串一次发出。
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var procSendInput = syscall.NewLazyDLL("user32.dll").NewProc("SendInput")
|
||||
|
||||
const (
|
||||
inputKeyboard = 1
|
||||
keyeventfUnicode = 0x0004
|
||||
keyeventfKeyup = 0x0002
|
||||
)
|
||||
|
||||
// input 精确对齐 Windows INPUT 结构(64 位下 40 字节:DWORD type + 4 填充 + KEYBDINPUT(24) + 8 填充到 union 尺寸)。
|
||||
type input struct {
|
||||
typ uint32
|
||||
_pad0 uint32
|
||||
wVk uint16
|
||||
wScan uint16
|
||||
dwFlags uint32
|
||||
time uint32
|
||||
dwExtraInfo uintptr
|
||||
_pad1 [8]byte
|
||||
}
|
||||
|
||||
// sendStringAsKeyboard 模拟键盘逐字符输入字符串(纯文本,不追加回车)。
|
||||
//
|
||||
// 字符之间按包级 kbdDelay 节流:
|
||||
// - kbdDelay > 0 :每个 UTF-16 码元单独投递一对 按下/抬起 事件,之间 sleep kbdDelay,
|
||||
// 观感"快速顺滑地滑出",且不会掉字;
|
||||
// - kbdDelay <= 0:整串事件一次 SendInput 发出(最快,但部分程序可能卡顿/掉字)。
|
||||
func sendStringAsKeyboard(s string) error {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
// Windows 的 KEYEVENTF_UNICODE 是按 UTF-16 code unit 投递的,
|
||||
// 先做 UTF-8 → UTF-16 转换,非 BMP 字符会在此正确拆成一对代理码元。
|
||||
units := utf16.Encode([]rune(s))
|
||||
|
||||
if kbdDelay <= 0 {
|
||||
inputs := make([]input, 0, len(units)*2)
|
||||
for _, u := range units {
|
||||
inputs = append(inputs, input{typ: inputKeyboard, wScan: u, dwFlags: keyeventfUnicode})
|
||||
inputs = append(inputs, input{typ: inputKeyboard, wScan: u, dwFlags: keyeventfUnicode | keyeventfKeyup})
|
||||
}
|
||||
return sendInputs(inputs)
|
||||
}
|
||||
|
||||
for i, u := range units {
|
||||
pair := [2]input{
|
||||
{typ: inputKeyboard, wScan: u, dwFlags: keyeventfUnicode},
|
||||
{typ: inputKeyboard, wScan: u, dwFlags: keyeventfUnicode | keyeventfKeyup},
|
||||
}
|
||||
if err := sendInputs(pair[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if i < len(units)-1 {
|
||||
time.Sleep(kbdDelay)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendInputs 调用 SendInput 投递一批键盘事件,并校验返回的事件数。
|
||||
func sendInputs(inputs []input) error {
|
||||
if len(inputs) == 0 {
|
||||
return nil
|
||||
}
|
||||
ret, _, err := procSendInput.Call(
|
||||
uintptr(len(inputs)),
|
||||
uintptr(unsafe.Pointer(&inputs[0])),
|
||||
uintptr(unsafe.Sizeof(inputs[0])),
|
||||
)
|
||||
if int(ret) != len(inputs) {
|
||||
if err == nil {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user