Windows下USB钱箱设备路径查找及Laravel按钮触发打开问题咨询
USB钱箱集成Laravel POS系统问题(Windows 10环境)
问题描述
正在使用Laravel开发POS系统,需集成USB钱箱。目前在Windows 10系统下无法找到USB钱箱的设备路径,也不清楚如何通过按钮点击触发打开钱箱。具体问题:
- 如何在Windows 10中查找USB钱箱的设备路径?
- 获取设备路径后,如何调整Laravel控制器实现按钮点击打开钱箱?
已知Windows设备通常分配至COM端口(如COM3),但不确定如何在PHP脚本中正确识别和使用。已编写的代码如下:
控制器代码
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class CashDrawerController extends Controller { public function open() { $device = "/dev/ttyUSB0"; // Adjust based on your actual device path $command = chr(27) . chr(112) . chr(0) . chr(25) . chr(250); // Example command if (file_exists($device)) { $fp = fopen($device, 'w'); if ($fp) { fwrite($fp, $command); fclose($fp); return response()->json(['message' => 'Cash drawer opened.']); } else { return response()->json(['message' => 'Failed to open device.'], 500); } } else { return response()->json(['message' => 'Device not found.'], 404); } } }
路由定义
Route::get('/open-cash-drawer', [CashDrawerController::class, 'open'])->name('open-cash-drawer');
按钮点击JavaScript代码
<script> $(document).ready(function(){ $('#openDrawerBtn').click(function(){ $.ajax({ url: '{{ route('open-cash-drawer') }}', method: 'GET', success: function(response) { alert(response.message); }, error: function(xhr) { alert(xhr.responseJSON.message); } }); }); }); </script>
解决方案
1. Windows 10中查找USB钱箱的设备路径
- 打开设备管理器:右键点击开始菜单,选择「设备管理器」
- 展开「端口(COM和LPT)」分类,找到对应USB钱箱的COM端口(通常名称会包含钱箱品牌或“USB Serial Port”字样)
- 若找不到,检查钱箱是否正确连接,或尝试更新USB驱动;部分钱箱通过打印机端口触发,可查看「打印机队列」中的打印机端口
2. 调整Laravel控制器实现按钮触发打开钱箱
Windows系统下COM端口路径格式为COMX(如COM3),而非Linux的/dev/ttyUSB0,同时PHP访问COM端口需注意权限和路径格式,调整后的控制器代码如下:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class CashDrawerController extends Controller { public function open() { // 替换为实际找到的COM端口 $device = "COM3"; // 钱箱触发指令,不同品牌可能有差异,需参考官方手册调整 $command = chr(27) . chr(112) . chr(0) . chr(25) . chr(250); // 验证COM端口是否有效 $portCheck = exec("mode {$device} 2>&1"); if(strpos($portCheck, 'Invalid') === false){ // Windows下访问COM端口需使用转义路径 $fp = fopen("\\\\.\\{$device}", 'w'); if ($fp) { fwrite($fp, $command); fclose($fp); return response()->json(['message' => '钱箱已打开。']); } else { return response()->json(['message' => '无法打开设备,请检查权限或端口占用。'], 500); } } else { return response()->json(['message' => '设备未找到,请检查端口是否正确。'], 404); } } }
关键调整说明
- 设备路径改为Windows格式
COMX,访问时需使用\\\\.\\COMX(转义后的路径,避免路径解析问题) - 增加端口有效性检查:通过
exec("mode COMx")命令判断端口是否存在 - 权限配置:确保运行Laravel的Web服务器(如IIS、XAMPP)有访问COM端口的权限,可右键服务器进程选择「属性」-「安全」,添加当前用户并赋予读写权限,或用管理员权限启动服务器
- 指令适配:不同品牌钱箱的触发指令可能不同,需参考钱箱官方手册修改
$command参数
内容的提问来源于stack exchange,提问作者dcodax
相关产品推荐
相关产品推荐

