feat: 上线前安全加固与发布工程化;appmall 由插件迁移为独立应用

安全(P0)
- 发布包签名:新增 scripts/package_keygen.php、scripts/package_verify.php、
  ywxapp\service\PackageVerifier;FrameworkService::apply() 解压前强制验签
  (ywxapp.framework_package_verify,默认开启)
- JWT 收紧:config/jwt.php 移除公开默认密钥,JwtService::assertStrongSecret()
  校验非空 / 长度≥32 / 已知弱值;.env.production.example 键名由 JWT_SECRET_KEY 修正为 JWT_SECRET
- /api/v1/Article:免登录白名单收窄为只读接口,写操作字段白名单 + assertOwner() 越权校验
- 开发者令牌:查找接口不再回显明文、统一失败文案 + 限流
- TemplateInstaller:文件名白名单 + realpath 归一化 + 目录内断言,修复 Zip Slip;补 use ZipArchive
- 后台登录:接入验证码、失败锁定与登录限流(config/ratelimit.php)
- 缓存 / Session 驱动可由 .env 覆盖(CACHE_DRIVER / SESSION_TYPE),集群部署改 redis
- paycenter 支付日志开关改为 PAY_LOG,不再跟随 APP_DEBUG

工程化 / 交付
- 新增 CHANGELOG.md 与 .env.production.example;composer.lock 入库锁定依赖版本
- 插件离线安装 CLI 增加 --uid,后台上传安装透传 uid,付费插件授权校验可通过
- 授权拒绝文案区分「未携带 uid」与「未找到有效授权」,便于排障
- .gitignore 放行 .env.production.example / .env.addon.example / .gitattributes / public/.htaccess

结构
- appmall 由 addon/appmall 迁移为独立应用 app/appmall(市场 / 开发者中心 / 审核 / 分润)
This commit is contained in:
yangwx committed 2026-10-22 00:53:39 +08:00
1 parent 1d49e6f5ee
commit 18101cf11a
636 files changed
+58517 -9519

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\Db;
use think\facade\View;
use ywxapp\controller\BackendBase;
/**
* ACL 规则控制器
*/
class Acl extends BackendBase
{
/**
* ACL 规则页(layui.table 前端拉取)
*/
public function acl()
{
return View::fetch('admin/acl');
}
/**
* ACL 列表(layui.table 分页 JSON,按 sort 升序)
*/
public function aclTable()
{
$page = max(1, (int) input('get.page', 1));
$limit = (int) input('get.limit', 20);
if ($limit < 1 || $limit > 100) {
$limit = 20;
}
$q = Db::name('iot_acl')->order('sort', 'asc')->order('id', 'asc');
$count = (int) (clone $q)->count();
$rows = $q->page($page, $limit)->select()->toArray();
$this->result->success(['list' => $rows, 'count' => $count]);
}
public function saveAcl()
{
$id = (int) input('post.id', 0);
$data = [
'target_type' => (string) input('post.target_type', 'all'),
'target' => (string) input('post.target', ''),
'topic' => (string) input('post.topic', ''),
'access' => (int) input('post.access', 3),
'allow' => (int) input('post.allow', 1),
'sort' => (int) input('post.sort', 0),
'remark' => (string) input('post.remark', ''),
];
if ($data['topic'] === '') {
$this->result->error('主题过滤器不能为空');
}
try {
if ($id > 0) {
Db::name('iot_acl')->where('id', $id)->update($data);
} else {
$data['create_at'] = time();
Db::name('iot_acl')->insert($data);
}
} catch (\Throwable $e) {
$this->result->error('保存失败:' . $e->getMessage());
}
$this->result->success('保存成功(最长 30s 后在 Broker 生效)');
}
public function deleteAcl()
{
$id = (int) input('post.id', 0);
Db::name('iot_acl')->where('id', $id)->delete();
$this->result->success('已删除');
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\Db;
use think\facade\View;
use ywxapp\controller\BackendBase;
use addon\iot\service\AlertService;
/**
* 告警中心控制器(后台查全部会员告警)
*/
class Alerts extends BackendBase
{
/**
* 告警中心页(layui.table 前端拉取)
*/
public function alertsPage()
{
return View::fetch('admin/alerts');
}
/**
* 告警列表(layui.table 分页 JSON,支持只看未读)
*/
public function alerts()
{
$page = max(1, (int) input('get.page', 1));
// layui.table 传 limit,兼容原手工分页的 size 命名
$size = max(1, (int) input('get.limit', (int) input('get.size', 20)));
$size = min(100, $size);
$only = (int) input('get.unread', 0) === 1;
$data = AlertService::pageAll($page, $size, $only);
// 兼容 layui.table parseData:count 字段
$this->result->success(['list' => $data['list'], 'count' => (int) $data['total']]);
}
/** 后台:标记告警已读(ids 空=全部) */
public function readAlertAll()
{
$ids = input('post.ids/a', []);
$n = 0;
try {
$q = Db::name('iot_alert')->where('is_read', 0);
if ($ids) {
$q->whereIn('id', array_map('intval', $ids));
}
$n = (int) $q->update(['is_read' => 1]);
} catch (\Throwable $e) {
$this->result->error('操作失败:' . $e->getMessage());
}
$this->result->success(['affected' => $n]);
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\Db;
use think\facade\View;
use ywxapp\controller\BackendBase;
/**
* 认证账号控制器
*
* 注意:本类名为 Auth,与 service\Auth 同名,
* 内部引用密码哈希等需使用全限定名 \addon\iot\service\Auth::hashPassword()。
*/
class Auth extends BackendBase
{
/**
* 认证账号页(layui.table 前端拉取)
*/
public function auth()
{
return View::fetch('admin/auth');
}
/**
* 账号列表(layui.table 分页 JSON)
*/
public function authTable()
{
$page = max(1, (int) input('get.page', 1));
$limit = (int) input('get.limit', 20);
if ($limit < 1 || $limit > 100) {
$limit = 20;
}
$q = Db::name('iot_auth')->order('id', 'desc');
$count = (int) (clone $q)->count();
$rows = $q->page($page, $limit)->select()->toArray();
// 密文不返回前端
foreach ($rows as &$r) {
unset($r['password']);
}
unset($r);
$this->result->success(['list' => $rows, 'count' => $count]);
}
public function saveAuth()
{
$id = (int) input('post.id', 0);
$username = trim((string) input('post.username', ''));
$password = (string) input('post.password', '');
$isSuper = (int) input('post.is_superuser', 0);
$status = (int) input('post.status', 1);
$remark = (string) input('post.remark', '');
if ($username === '') {
$this->result->error('用户名不能为空');
}
$data = [
'username' => $username,
'is_superuser' => $isSuper ? 1 : 0,
'status' => $status ? 1 : 0,
'remark' => $remark,
'update_at' => time(),
];
// 仅当填写了密码才更新(编辑时留空表示不改)
if ($password !== '') {
$data['password'] = \addon\iot\service\Auth::hashPassword($password);
}
try {
if ($id > 0) {
Db::name('iot_auth')->where('id', $id)->update($data);
} else {
if ($password === '') {
$this->result->error('新增账号必须设置密码');
}
$data['create_at'] = time();
Db::name('iot_auth')->insert($data);
}
} catch (\Throwable $e) {
$this->result->error('保存失败:' . $e->getMessage());
}
$this->result->success('保存成功');
}
public function deleteAuth()
{
$id = (int) input('post.id', 0);
Db::name('iot_auth')->where('id', $id)->delete();
$this->result->success('已删除');
}
}
@@ -0,0 +1,45 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\View;
use ywxapp\controller\BackendBase;
use addon\iot\model\Connection;
/**
* 客户端连接控制器
*/
class Connections extends BackendBase
{
/**
* 连接列表页(layui.table 前端拉取)
*/
public function connections()
{
return View::fetch('admin/connections');
}
/**
* 连接列表(layui.table 分页 JSON)
*/
public function connectionsTable()
{
$page = max(1, (int) input('get.page', 1));
$limit = (int) input('get.limit', 20);
if ($limit < 1 || $limit > 100) {
$limit = 20;
}
$q = Connection::order('id', 'desc');
$count = (int) (clone $q)->count();
$rows = $q->page($page, $limit)->select()->toArray();
$this->result->success(['list' => $rows, 'count' => $count]);
}
}
+190
View File
@@ -0,0 +1,190 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\Db;
use think\facade\View;
use ywxapp\controller\BackendBase;
use addon\iot\service\DeviceService;
use addon\iot\service\DeviceLogService;
use addon\iot\service\SensorConfigService;
/**
* 智能设备控制器(绑定表,预登记 SN → App 扫码绑定激活)
*/
class Devices extends BackendBase
{
/**
* 设备管理页(layui.table 前端拉取)
*/
public function device()
{
return View::fetch('admin/device');
}
/**
* 设备列表(layui.table 分页 JSON,支持关键词过滤)
*/
public function deviceTable()
{
$kw = trim((string) input('get.kw', ''));
$page = max(1, (int) input('get.page', 1));
$limit = (int) input('get.limit', 20);
if ($limit < 1 || $limit > 100) {
$limit = 20;
}
$q = Db::name('iot_device');
if ($kw !== '') {
$q->where(function ($query) use ($kw) {
$query->whereLike('sn', "%{$kw}%")
->whereOr('title', 'like', "%{$kw}%")
->whereOr('uuid', 'like', "%{$kw}%");
});
}
$count = (int) (clone $q)->count();
$rows = $q->order('id', 'desc')->page($page, $limit)->select()->toArray();
foreach ($rows as &$d) {
$d['online'] = DeviceService::isOnline((string) $d['uuid']);
$d['member_account'] = (int) $d['member_id'] > 0
? DeviceService::memberAccount((int) $d['member_id'])
: '';
unset($d['secret']);
}
unset($d);
$this->result->success(['list' => $rows, 'count' => $count]);
}
/**
* 登记/编辑设备(华为式:新增=预登记SN,自动生成配对码+激活令牌,绑定激活由设备/App 完成)
*/
public function saveDevice()
{
$id = (int) input('post.id', 0);
$sn = trim((string) input('post.sn', ''));
$title = trim((string) input('post.title', ''));
$model = trim((string) input('post.model', ''));
$room = trim((string) input('post.room', ''));
$status = (int) input('post.status', 1);
$pairCode = trim((string) input('post.pair_code', ''));
if ($title === '') {
$this->result->error('设备名称不能为空');
}
try {
if ($id > 0) {
$update = [
'title' => $title, 'model' => $model, 'room' => $room,
'status' => $status ? 1 : 0, 'update_at' => time(),
];
if ($pairCode !== '') {
$update['pair_code'] = $pairCode;
}
Db::name('iot_device')->where('id', $id)->update($update);
} else {
$res = DeviceService::register($sn, $title, $model, $room, $pairCode);
$this->result->success($res, '登记成功');
}
} catch (\Throwable $e) {
$this->result->error('保存失败:' . $e->getMessage());
}
$this->result->success('保存成功(预登记设备由设备激活/App 扫码绑定)');
}
/**
* 重置设备密钥(返回新明文,前端展示一次)
*/
public function resetDeviceSecret()
{
$uuid = trim((string) input('post.uuid', ''));
try {
$res = DeviceService::resetSecret($uuid);
} catch (\Throwable $e) {
$this->result->error($e->getMessage());
}
$this->result->success($res);
}
/**
* 重新生成激活令牌(仅未激活设备,按 SN 定位;已激活设备如需换凭证走 resetDeviceSecret)
*/
public function resetActivateToken()
{
$sn = trim((string) input('post.sn', ''));
try {
$res = DeviceService::resetActivateToken($sn);
} catch (\Throwable $e) {
$this->result->error($e->getMessage());
}
$this->result->success($res);
}
/**
* 删除设备(含 MQTT账号/ACL/影子/订阅/离线队列)
*/
public function deleteDevice()
{
$uuid = trim((string) input('post.uuid', ''));
DeviceService::remove($uuid);
$this->result->success('已删除(含MQTT账号/ACL/影子/订阅)');
}
/**
* 读取设备传感器配置(配置真源在服务端:后台编辑 → retained 下发设备 + App 共用同一份)
*/
public function deviceConfig()
{
$uuid = trim((string) input('get.uuid', ''));
if ($uuid === '' || !DeviceService::findByUuid($uuid)) {
$this->result->error('设备不存在或未激活(未分配 uuid)');
}
$cfg = SensorConfigService::get($uuid);
$cfg['uuid'] = $uuid;
$this->result->success($cfg);
}
/**
* 保存设备传感器配置(保存即生效:立即入 retained 下发队列,设备在线秒级生效、离线上线即生效)
* param: uuid(必填), sensors(JSON 数组:{index,alias,probes,upper,lower,gap,enabled})
* 位置序号键统一 `index`(旧键 `i` 仍兼容)
*/
public function saveDeviceConfig()
{
$uuid = trim((string) input('post.uuid', ''));
if ($uuid === '' || !DeviceService::findByUuid($uuid)) {
$this->result->error('设备不存在或未激活(未分配 uuid)');
}
$sensors = input('post.sensors', '');
if (is_string($sensors)) {
$sensors = json_decode($sensors, true);
}
if (!is_array($sensors)) {
$this->result->error('sensors 参数须为 JSON 数组');
}
try {
$cfg = SensorConfigService::save($uuid, $sensors);
} catch (\Throwable $e) {
$this->result->error($e->getMessage());
}
$cfg['uuid'] = $uuid;
$this->result->success($cfg, '配置已保存并下发(设备离线则上线后自动生效)');
}
/**
* 设备日志(JSON,按设备 uuid 分页)
*/
public function deviceLogs()
{
$uuid = trim((string) input('get.uuid', ''));
$page = max(1, (int) input('get.page', 1));
$size = min(100, max(1, (int) input('get.size', 20)));
$data = $uuid !== '' ? DeviceLogService::page($uuid, $page, $size) : ['list' => [], 'total' => 0];
$this->result->success($data);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\View;
use ywxapp\controller\BackendBase;
use addon\iot\service\GroupService;
/**
* 设备分组控制器(后台全局分组管理)
*/
class Groups extends BackendBase
{
/**
* 分组列表页(分组数据以 JSON 注入,前端 layui.table 本地渲染)
*/
public function group()
{
$list = GroupService::groups(0);
View::assign('groupsJson', (string) json_encode($list, JSON_UNESCAPED_UNICODE
| JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT));
return View::fetch('admin/group');
}
public function saveGroup()
{
try {
$data = $this->request->post();
$data['member_id'] = 0; // 后台全局分组
GroupService::save($data);
} catch (\Throwable $e) {
$this->result->error('保存失败:' . $e->getMessage());
}
$this->result->success('保存成功');
}
public function deleteGroup()
{
$id = (int) input('post.id', 0);
try {
GroupService::remove($id, 0);
} catch (\Throwable $e) {
$this->result->error($e->getMessage());
}
$this->result->success('已删除');
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\View;
use ywxapp\controller\BackendBase;
use addon\iot\model\Message;
/**
* 消息日志控制器
*/
class Messages extends BackendBase
{
/**
* 消息日志页(layui.table 前端拉取)
*/
public function messages()
{
return View::fetch('admin/messages');
}
/**
* 消息列表(layui.table 分页 JSON,支持主题过滤)
*/
public function messagesTable()
{
$topic = trim((string) input('get.topic', ''));
$page = max(1, (int) input('get.page', 1));
$limit = (int) input('get.limit', 20);
if ($limit < 1 || $limit > 100) {
$limit = 20;
}
$q = Message::order('id', 'desc');
if ($topic !== '') {
$q->where('topic', 'like', "%{$topic}%");
}
$count = (int) (clone $q)->count();
$rows = $q->page($page, $limit)->select()->toArray();
$this->result->success(['list' => $rows, 'count' => $count]);
}
}
+178
View File
@@ -0,0 +1,178 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\Db;
use think\facade\View;
use ywxapp\controller\BackendBase;
use addon\iot\service\OtaService;
/**
* OTA 固件控制器(P4:固件上传 / 下发升级指令 / 进度上报)
*/
class Ota extends BackendBase
{
/**
* OTA 管理页(固件列表 + 设备多选下发)
*/
public function ota()
{
$devices = Db::name('iot_device')
->field('uuid,title,model')->order('id', 'desc')->select()->toArray();
// 先做 JSON_HEX_* 转义(<>&'"→\uXXXX)再注入模板,避免模板默认 htmlentities
// 对 json 中的引号做二次转义导致 JS 字面量失效(SyntaxError: Unexpected token '&')
View::assign('devicesJson', (string) json_encode($devices, JSON_UNESCAPED_UNICODE
| JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT));
return View::fetch('admin/ota');
}
/**
* 固件列表(JSON,支持按型号过滤)
*/
public function otaList()
{
$model = trim((string) input('get.model', ''));
$this->result->success(['list' => OtaService::list($model)]);
}
/**
* 固件列表(layui.table 分页版,按型号过滤)
*/
public function otaTable()
{
$model = trim((string) input('get.model', ''));
$page = max(1, (int) input('get.page', 1));
$limit = (int) input('get.limit', 10);
if ($limit < 1 || $limit > 100) {
$limit = 10;
}
OtaService::ensureTable();
$q = Db::name('iot_ota');
if ($model !== '') {
$q->where('model', $model);
}
$count = (clone $q)->count();
$rows = $q->order('id', 'desc')->page($page, $limit)->select()->toArray();
$this->result->success(['list' => $rows, 'count' => $count]);
}
/**
* 上传并登记固件(保存到 public/upload/ota,自动计算 SHA256)
*/
public function saveOta()
{
$model = trim((string) input('post.model', ''));
$version = trim((string) input('post.version', ''));
$remark = trim((string) input('post.remark', ''));
$status = (int) input('post.status', 1);
if ($model === '' || $version === '') {
$this->result->error('设备型号与版本号必填');
}
$file = $this->request->file('file');
if (empty($file)) {
// 常见原因:文件超过 php upload_max_filesize / post_max_size 时 $_FILES 为空或仅有错误码
$this->result->error('未收到固件文件(请确认文件未超过服务器上传大小限制)');
}
$ext = strtolower((string) pathinfo($file->getOriginalName(), PATHINFO_EXTENSION));
if (!in_array($ext, ['bin', 'zip', 'hex'], true)) {
$this->result->error('仅支持 bin / zip / hex 格式固件');
}
$hash = hash_file('sha256', $file->getRealPath());
if (!$hash) {
$this->result->error('固件文件读取失败');
}
$dir = root_path() . 'public' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . 'ota';
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}
$saveName = substr($hash, 0, 16) . '_' . preg_replace('/[^\w.\-]+/', '_', $version)
. '_' . preg_replace('/[^\w.\-]+/', '_', $file->getOriginalName());
try {
$file->move($dir, $saveName);
} catch (\Throwable $e) {
$this->result->error('固件保存失败:' . $e->getMessage()
. '(若提示超限,请调大 upload_max_filesize / post_max_size)');
}
$abs = realpath($dir . DIRECTORY_SEPARATOR . $saveName);
if (!$abs || !is_file($abs)) {
$this->result->error('固件保存失败');
}
try {
$id = OtaService::add([
'model' => $model,
'version' => $version,
'filename' => $file->getOriginalName(),
'file_hash' => hash_file('sha256', $abs),
'size' => (int) filesize($abs),
'url' => rtrim((string) $this->request->domain(), '/') . '/upload/ota/' . rawurlencode($saveName),
'remark' => $remark,
'status' => $status,
]);
} catch (\Throwable $e) {
@unlink($abs);
$this->result->error('登记失败:' . $e->getMessage());
}
$this->result->success(['id' => $id]);
}
/**
* 删除固件(连带删除本地上传文件)
*/
public function deleteOta()
{
$id = (int) input('post.id', 0);
$ota = Db::name('iot_ota')->where('id', $id)->find();
if ($ota) {
OtaService::remove($id);
if (preg_match('#/upload/ota/([^/]+)$#', (string) $ota['url'], $m)) {
$abs = root_path() . 'public' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . 'ota'
. DIRECTORY_SEPARATOR . rawurldecode($m[1]);
if (is_file($abs)) {
@unlink($abs);
}
}
}
$this->result->success('已删除');
}
/**
* 启停固件(停用后不可再下发)
*/
public function toggleOta()
{
$id = (int) input('post.id', 0);
$enabled = (int) input('post.enabled', 1);
Db::name('iot_ota')->where('id', $id)->update(['status' => $enabled ? 1 : 0]);
$this->result->success('已更新');
}
/**
* 向选中的设备下发升级指令(离线设备待上线后由 outbox 补发)
*/
public function publishOta()
{
$otaId = (int) input('post.ota_id', 0);
$uuids = input('post.uuids/a', []);
if (!$otaId) {
$this->result->error('固件不能为空');
}
$uuids = array_values(array_filter((array) $uuids, fn($v) => trim((string) $v) !== ''));
if (!$uuids) {
$this->result->error('请选择目标设备');
}
try {
$n = OtaService::publish($otaId, $uuids);
} catch (\Throwable $e) {
$this->result->error($e->getMessage());
}
$this->result->success("已向 {$n} 台设备下发升级指令(离线设备上线后自动补发)");
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\Db;
use think\facade\View;
use ywxapp\controller\BackendBase;
use addon\iot\model\Connection;
use addon\iot\model\Message;
/**
* 概览控制器(实时运行仪表盘 + 最近消息)
*
* 实时指标由页面轮询 statsData 接口获取,此处仅取最近消息;
* 原独立的 stats 实时监控页已并入概览页。
*/
class Overview extends BackendBase
{
/**
* 概览页
*/
public function index()
{
$recent = Message::order('id', 'desc')->limit(10)->select()->toArray();
// JSON_HEX_* 转义后由模板 {$recentJson|raw} 输出,供前端 layui.table 本地渲染
View::assign('recentJson', (string) json_encode($recent, JSON_UNESCAPED_UNICODE
| JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT));
return View::fetch('admin/index');
}
/**
* 运行监控数据接口(供概览页轮询实时指标)
*/
public function statsData()
{
$row = Db::name('iot_stats')->where('id', 1)->find();
if (!$row) {
$row = [
'uptime' => 0, 'clients_online' => 0, 'clients_total' => 0,
'subscriptions' => 0, 'messages_received' => 0, 'messages_sent' => 0,
'retained' => 0, 'timestamp' => time(),
];
}
// 以连接表的实时在线数补全(更贴近 DB 视角的在线状态)
try {
$row['db_online'] = Connection::where('status', 1)->count();
} catch (\Throwable $e) {
$row['db_online'] = $row['clients_online'] ?? 0;
}
$this->result->success($row);
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\View;
use ywxapp\controller\BackendBase;
use addon\iot\service\Store;
/**
* 发布消息控制器
*/
class Publish extends BackendBase
{
/**
* 发布表单页
*/
public function publish()
{
return View::fetch('admin/publish');
}
/**
* 执行发布(零外部依赖:写入出站队列,由常驻 Broker 消费后经内部路由投递)
*/
public function doPublish()
{
$topic = input('post.topic', '');
$payload = input('post.payload', '');
$qos = (int) input('post.qos', 0);
if (!$topic) {
$this->result->error('主题不能为空');
}
$ok = Store::enqueueManual($topic, $payload, $qos, 0, 'backend');
if ($ok) {
$this->result->success('已加入发布队列,Broker 将投递给在线订阅者');
}
$this->result->error('发布失败:无法写入出站队列');
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\Db;
use think\facade\View;
use ywxapp\controller\BackendBase;
/**
* 转发规则控制器(规则引擎 / 桥接到 EMQX)
*/
class Rules extends BackendBase
{
/**
* 转发规则页(layui.table 前端拉取)
*/
public function rule()
{
return View::fetch('admin/rule');
}
/**
* 规则列表(layui.table 分页 JSON)
*/
public function ruleTable()
{
$page = max(1, (int) input('get.page', 1));
$limit = (int) input('get.limit', 20);
if ($limit < 1 || $limit > 100) {
$limit = 20;
}
$q = Db::name('iot_rule')->order('id', 'desc');
$count = (int) (clone $q)->count();
$rows = $q->page($page, $limit)->select()->toArray();
$this->result->success(['list' => $rows, 'count' => $count]);
}
public function saveRule()
{
$id = (int) input('post.id', 0);
$data = [
'name' => (string) input('post.name', ''),
'source_filter' => (string) input('post.source_filter', ''),
'target_type' => (string) input('post.target_type', 'mqtt'),
'target_broker' => (string) input('post.target_broker', ''),
'target_clientid' => (string) input('post.target_clientid', ''),
'target_username' => (string) input('post.target_username', ''),
'target_password' => (string) input('post.target_password', ''),
'target_topic' => (string) input('post.target_topic', ''),
'target_qos' => (int) input('post.target_qos', 0),
'enabled' => (int) input('post.enabled', 1),
'remark' => (string) input('post.remark', ''),
];
if ($data['name'] === '' || $data['source_filter'] === '') {
$this->result->error('规则名称与源主题过滤器必填');
}
if ($data['target_broker'] === '') {
$this->result->error('目标 Broker 地址必填');
}
try {
if ($id > 0) {
Db::name('iot_rule')->where('id', $id)->update($data);
} else {
$data['create_at'] = time();
Db::name('iot_rule')->insert($data);
}
} catch (\Throwable $e) {
$this->result->error('保存失败:' . $e->getMessage());
}
$this->result->success('保存成功(最多 30s 后在 Broker 生效)');
}
public function deleteRule()
{
$id = (int) input('post.id', 0);
Db::name('iot_rule')->where('id', $id)->delete();
$this->result->success('已删除');
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\Db;
use think\facade\View;
use ywxapp\controller\BackendBase;
use addon\iot\service\SceneService;
/**
* 场景联动控制器(智慧生活自动化:设备状态/定时/手动 → 动作组)
*/
class Scenes extends BackendBase
{
/**
* 场景列表页(场景与设备数据以 JSON 注入,前端 layui.table 本地渲染)
*/
public function scene()
{
$list = SceneService::list(0);
$devs = Db::name('iot_device')
->field('uuid,title,model')->order('id', 'desc')->select()->toArray();
// 与 ota() 同理:JSON_HEX_* 转义防模板 htmlentities 二次转义破坏 JS 字面量
$flags = JSON_UNESCAPED_UNICODE
| JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
View::assign('scenesJson', (string) json_encode($list, $flags));
View::assign('devicesJson', (string) json_encode($devs, $flags));
return View::fetch('admin/scene');
}
/**
* 场景详情(JSON,含 triggers/actions,供编辑弹层初始化)
*/
public function sceneDetail()
{
$id = (int) input('get.id', 0);
$row = SceneService::findScene($id);
if (!$row) {
$this->result->error('场景不存在');
}
$this->result->success($row);
}
public function saveScene()
{
try {
$data = $this->request->post();
$data['member_id'] = 0; // 后台全局场景
// 前端将 triggers/actions 以 JSON 字符串提交,Service 按数组遍历
foreach (['triggers', 'actions'] as $k) {
if (isset($data[$k]) && is_string($data[$k]) && $data[$k] !== '') {
$decoded = json_decode($data[$k], true);
$data[$k] = is_array($decoded) ? $decoded : [];
} elseif (!isset($data[$k])) {
$data[$k] = [];
}
}
SceneService::save($data);
} catch (\Throwable $e) {
$this->result->error('保存失败:' . $e->getMessage());
}
$this->result->success('保存成功(约 30s 内在 Broker 生效)');
}
public function deleteScene()
{
$id = (int) input('post.id', 0);
SceneService::remove($id, 0);
$this->result->success('已删除');
}
public function toggleScene()
{
$id = (int) input('post.id', 0);
$enabled = (int) input('post.enabled', 0);
SceneService::toggle($id, $enabled, 0);
$this->result->success('已更新');
}
public function runScene()
{
$id = (int) input('post.id', 0);
SceneService::runScene($id, 'manual', '后台手动执行');
$this->result->success('已触发执行');
}
public function sceneLogs()
{
$id = (int) input('get.id', 0);
$page = max(1, (int) input('get.page', 1));
$data = SceneService::logs($id, $page, 20);
$this->result->success($data);
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace addon\iot\controller\backend;
use think\facade\View;
use ywxapp\controller\BackendBase;
use ywxapp\service\AddonService;
/**
* 服务设置控制器
*/
class Setting extends BackendBase
{
/**
* 服务设置页
*/
public function setting()
{
$def = include ADDON_PATH . 'iot' . DIRECTORY_SEPARATOR . 'config.php';
$saved = AddonService::config('iot');
View::assign('def', $def);
View::assign('saved', $saved ?: []);
return View::fetch('admin/setting');
}
/**
* 保存设置
*/
public function saveSetting()
{
$data = input('post.');
AddonService::config('iot', $data);
$this->result->success('保存成功');
}
}