如何实现多个扫码枪和多个耳机匹配输出信息

Zhang99996666 Zhang99996666 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

需求:根据扫码枪获得条码信息,在数据库中匹配到相关信息后通过耳机输出,已实现一对一,希望实现多对多,不同的操作人员使用4-6个扫码枪扫码并能分别获得需要的信息。

已有一对一代码,输入是通过输入焦点实现,程序需保持在前台运行,耳机是蓝牙耳机默认输出 。

关于扫码枪我选择的是USB HID的,公司安全部不允许用带系统的,只能用这种,关于多对多的想法是输入端通过VID和PID区分设备。

耳机之前考虑过蓝牙耳机,但蓝牙耳机只能安装一个适配器,同时只能有一个耳机进行输出。

后来考虑通过软件直接解码成数字信号直接输出到USB设备,但是不是很清楚音频播放是不是必须通过windows,能不能实现数字信号直接发送到USB设备。

或者通过混音器将各个耳机设定为不同的声道,将音频通过各个声道播放。

学习python刚一个多月,只做过一个小项目,这方面真没什么了解,希望大家能给个建议。

import pandas as pd
import sqlite3
import datetime
import schedule
import time
import threading
import os
import traceback
import pygame
import re

def find_and_mark_data(audio_directory, query):
    conn = sqlite3.connect('test_requests.db')
    c = conn.cursor()
    c.execute("SELECT * FROM test_requests WHERE Barcode=? LIMIT 1", (query,))
    row = c.fetchone()
    if row:
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        c.execute("UPDATE test_requests SET Note=? WHERE Barcode=?", (f"{today}已挑", query))
        print(f"Updated row with Request_Code {row[0]}")
        conn.commit()
        request_text = f"{row[0]},{row[4]}"
        print(request_text)
        # 播放 request_text
        play_request_text(audio_directory, request_text)
        return request_text
    else:
        return None

def play_request_text(audio_directory, request_text):
    pygame.mixer.init()
    volume = 0.8
    pygame.mixer.music.set_volume(volume)
    gap_between_audios = 0
    for char in request_text:
        file_name = f"{char}.mp3"
        file_path = os.path.join(audio_directory, file_name)
        if os.path.isfile(file_path):
            while pygame.mixer.music.get_busy():
                pygame.time.Clock().tick(10)
            pygame.mixer.music.load(file_path)
            pygame.mixer.music.play()
            while pygame.mixer.music.get_busy():
                pygame.time.Clock().tick(10)
            time.sleep(gap_between_audios)
        else:
            print(f"No audio file found for character '{char}'")

def update_and_export(folder_path):
    try:
        excel_path = os.path.join(folder_path, 'test request.xlsx')
        try:
            df_excel = pd.read_excel(excel_path, header=None)
        except PermissionError:
            print(f"输入文件 {excel_path} 正在被占用,结束本次更新。")
            return
        except Exception as e:
            print(f"读取 Excel 文件时发生错误:{e}")
            return

        mapping_dict = pd.read_excel(excel_path, sheet_name='Sheet2', header=None, index_col=0)[1].astype(str).to_dict()

        def process_test_list(test_list_str):
            parts = re.split(',\s*', test_list_str)
            new_parts = []
            for part in parts:
                new_part = mapping_dict.get(part, part)
                # 将返回值转换为字符串类型
                new_part = str(new_part)
                new_parts.append(new_part)
            return ','.join(new_parts)

        df_excel.iloc[:, 4] = df_excel.iloc[:, 4].apply(process_test_list)
        
        conn = sqlite3.connect('test_requests.db')
        c = conn.cursor()

        try:
            c.execute("SELECT Request_Code, Identifier FROM test_requests")
            database_data = c.fetchall()
            database_df = pd.DataFrame(database_data, columns=['Request_Code', 'Identifier'])
        except Exception as e:
            print(f"从数据库读取数据时发生错误:{e}")
            conn.close()
            return

        new_rows = df_excel[~df_excel.iloc[:, 0].isin(database_df['Request_Code']) & ~df_excel.iloc[:, 6].isin(database_df['Identifier'])]
        
        new_rows.iloc[:, 4] = new_rows.iloc[:, 4].apply(process_test_list)

        # 使用批量插入
        values = [tuple(row) for _, row in new_rows.iterrows()]
        if values:
            c.executemany('''
            INSERT INTO test_requests (
                Request_Code, Size, Tread, Spec, Test_list, IPCode, Identifier,
                Barcode, Requester
            ) VALUES (?,?,?,?,?,?,?,?,?)
            ''', values)
            conn.commit()
        conn.close()

        # 执行导出操作
        try:
            output_path = os.path.join(folder_path, 'output.xlsx')
            # 如果文件存在,先清空文件内容
            if os.path.exists(output_path):
                with open(output_path, 'w') as f:
                    f.write('')

            # 从数据库读取所有列数据,包括 Note 列
            conn = sqlite3.connect('test_requests.db')
            df_export = pd.read_sql_query("SELECT * FROM test_requests", conn)
            conn.close()
            
            df_export.to_excel(output_path, index=False)
        except PermissionError:
            print(f"输出文件 {output_path} 正在被占用,结束本次导出。")
            return
        except sqlite3.OperationalError as e:
            if "no such table: test_requests" in str(e):
                print('test_requests.db none')
            else:
                raise e
    except Exception as e:
        traceback.print_exc()

def input_thread_function(audio_directory):
    while True:
        barcode = input('请输入 Barcode:')
        if barcode.lower() == 'exit':
            break
        find_and_mark_data(audio_directory, barcode)

def main():
    # 设置音频文件所在的目录
    audio_directory = input(r'请输入audio文件夹路径:')

    # 连接到SQLite数据库,创建表结构
    conn = sqlite3.connect('test_requests.db')
    cursor = conn.cursor()
    print("正在尝试删除可能存在的旧表...")
    cursor.execute("DROP TABLE IF EXISTS test_requests;")
    print("正在创建test_requests表...")
    cursor.execute("CREATE TABLE test_requests (Request_Code TEXT, Size TEXT, Tread TEXT, Spec TEXT, Test_list TEXT, IPCode TEXT, Identifier TEXT, Barcode TEXT, Requester TEXT, Note TEXT);")
    conn.commit()
    conn.close()

    folder_path = input(r'请输入test request文件夹路径:')
    # 定时执行更新和导出操作
    schedule.every(10).seconds.do(lambda: update_and_export(folder_path))

    # 启动一个线程来处理用户输入
    input_thread = threading.Thread(target=input_thread_function, args=(audio_directory,))
    input_thread.start()

    # 运行定时任务
    while True:
        schedule.run_pending()
        time.sleep(1)

if __name__ == "__main__":
    main()  

 

...全文

相关推荐

C#实现简单获取扫码枪信息代码

- 多线程管理:如果有多个连接,应妥善管理这些线程,防止资源耗尽。总的来说,C#实现获取扫码枪信息的核心在于建立一个TCP服务器,监听指定端口,接收扫码枪发送的条形码数据,并进行解析。

weixin_38633897

C#无焦点后台读取扫码枪信息

通过阅读和理解这些代码,你可以了解到如何在C#项目中实现后台无焦点读取扫码枪信息的具体步骤。总的来说,无焦点后台读取扫码枪信息是提高应用效率和用户体验的重要技术,而C#为此提供了丰富的工具和API。

netrain911

c#实现USB扫码枪监听读取数据 完整代码 可以直接运行

此外,可能还需要根据实际的扫码枪输出格式和数据处理需求对代码进行调整,例如,如果扫码枪发送的是连续的多个字符,可能需要跟踪并组合这些字符以形成完整的条形码字符串。

柳絮因风起-

Labview串口读取扫码枪信息_labview_gun_扫码枪_labview扫码枪_labview扫码枪

在LabVIEW中,串口通信是通过“串口”节点或者“串口读写”VI来实现的。这个"串口扫码.vi"可能就是一个完成该功能的虚拟仪器。以下是一些关于LabVIEW串口读取扫码枪信息的关键知识点:1.

心梓

中科蓝讯蓝牙测试盒产线高效测试全攻略

本文详细解析中科蓝讯蓝牙测试盒在产线高效测试中的应用,涵盖硬件搭建、软件配置及常见问题排查。通过双通道并行架构,测试盒将单体测试时间从15分钟压缩至4秒,显著提升生产效率。文章还提供产线优化方案,帮助解决配对效率低、误测率高等痛点,实现日均2万+耳机的全项检测。

代码浣熊
评论
收藏 已收藏
分享
返回顶部
Zhang99996666
疑难问题 22,298 成员 121,727 内容