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

+135
View File
@@ -0,0 +1,135 @@
<?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;
use think\facade\Db;
use ywxapp\controller\FrontendBase;
/**
* IoT 插件前台展示页(免登录门面,对外介绍功能/能力/优势)
*
* GET /iot/index/index
*
* 遵循插件前台开发约定(与 articles/Index 同构):
* - 继承 FrontendBase:视图根自动切到 addon/iot/view/frontend/,
* noNeedLogin 默认 ['*'] 游客放行,fetch 叠加皮肤覆盖层;
* - 控制器放 controller/ 根(非 api/backend 子目录),
* 路由用字符串目标 'addon\iot\controller\Index@index'。
* 数据侧只读聚合指标,全部 try/catch 兜底 —— 任何一张表缺失/异常都
* 降级为 0,绝不 500(门面页的可用性 > 数据完整性)。
*/
class Index extends FrontendBase
{
/**
* 展示页
*/
public function index()
{
$this->assign('stats', $this->liveStats());
$this->assign('apiGroups', $this->apiCatalog());
$this->assign('now', date('Y-m-d H:i'));
return $this->fetch('index/index');
}
/**
* 实时聚合指标(每项独立兜底,缺表/异常返回 0)
*/
protected function liveStats(): array
{
$count = function (string $table, array $where = []): int {
try {
return (int) Db::name($table)->where($where)->count();
} catch (\Throwable $e) {
return 0;
}
};
// Broker 快照(iot_stats id=1,Broker 进程每 2s 写入)
$broker = ['uptime' => 0, 'clients_online' => 0, 'messages_received' => 0, 'retained' => 0];
try {
$row = Db::name('iot_stats')->where('id', 1)->find();
if ($row) {
$broker = array_merge($broker, array_intersect_key($row, $broker));
}
} catch (\Throwable $e) {
}
return [
'uptime' => $this->fmtUptime((int) $broker['uptime']),
'online' => (int) $broker['clients_online'],
'recv' => (int) $broker['messages_received'],
'retained' => (int) $broker['retained'],
'devices' => $count('iot_device'),
'points' => $count('iot_sensor_point'),
'alerts' => $count('iot_alert'),
'scenes' => $count('iot_scene'),
'shares' => $count('iot_share', ['status' => 1]),
'ota_pkgs' => $count('iot_ota'),
];
}
/** 供模板格式化运行时长(时:分:秒) */
protected function fmtUptime(int $s): string
{
return sprintf('%d:%02d:%02d', intdiv($s, 3600), intdiv($s % 3600, 60), $s % 60);
}
/**
* App API 能力域统计:从 route/app.php 自动解析(路由唯一真源)。
* 宣传页只展示功能域划分与接口数量——不输出任何端点路径 / 主题字符串
* (公开页面不做攻击者的侦察地图;详细契约见 docs/guide/iot_api_reference.md)。
*
* 解析约定:只匹配数组目标规则(本插件全部 App API 均为 [Xxx::class,'action'] 书写;
* backend/* 与前台页是字符串目标,天然不会被误收)。
* 同一 controller+action 只计首次出现:新域前缀 URL 注册在前、文件末尾的
* 旧 client/* 兼容别名在后,去重避免兼容别名把数量翻倍。
*/
protected function apiCatalog(): array
{
try {
$file = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'route' . DIRECTORY_SEPARATOR . 'app.php';
if (!is_file($file) || !preg_match_all(
"#Route::(get|post)\(\s*'([^']+)'\s*,\s*\[(\w+)::class\s*,\s*'(\w+)'\]#",
(string) @file_get_contents($file),
$ms,
PREG_SET_ORDER
)) {
return [];
}
} catch (\Throwable $e) {
return [];
}
$domains = [
'mqtt' => ['ico' => '📡', 'label' => 'Broker 运维', 'blurb' => '运行状态、指标快照与消息直发'],
'client' => ['ico' => '📱', 'label' => '设备与会员', 'blurb' => '绑定认领、共享授权、短时票据与命令下发'],
'monitor' => ['ico' => '📈', 'label' => '实时监测', 'blurb' => '历史曲线、分钟级聚合、告警与设备日志'],
'scene' => ['ico' => '⚡', 'label' => '场景联动', 'blurb' => '规则引擎、设备分组与批量控制'],
'ota' => ['ico' => '🚀', 'label' => '固件升级', 'blurb' => '升级包管理与分批推送进度跟踪'],
'_root' => ['ico' => '🔑', 'label' => '设备入云激活', 'blurb' => '出厂预置令牌换领一机一密凭证'],
];
$groups = [];
$seen = []; // "controller/action" => true:兼容别名去重
foreach ($ms as $m) {
[, , $rule, $ctrl, $action] = $m;
$key = $ctrl . '/' . $action;
if (isset($seen[$key])) {
continue;
}
$seen[$key] = true;
$domain = strpos($rule, '/') === false ? '_root' : strtok($rule, '/');
if (!isset($domains[$domain])) {
continue; // 未知前缀不入目录
}
$groups[$domain] = $groups[$domain] ?? ($domains[$domain] + ['count' => 0]);
$groups[$domain]['count']++;
}
return array_values($groups);
}
}
+390
View File
@@ -0,0 +1,390 @@
<?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\api;
use think\facade\Db;
use addon\iot\service\Store;
use addon\iot\service\DeviceService;
use addon\iot\service\ShareService;
use addon\iot\service\TicketService;
/**
* App 端设备域 API(需框架会员 JWT 登录)
* 路由前缀:/iot/api/client/...
*
* 2026-09-18 按功能域拆分后本控制器只保留「接入层」:连接/设备绑定/共享/
* 影子/命令 —— 全品类共用(品类无关)。传感器配置/曲线/日志/告警在 Monitor,
* 场景/分组在 Scene,OTA 在 Ota。共用会员取数在 ClientBase。
*/
class Client extends ClientBase
{
/** 免登录公开接口(设备侧调用,非会员) */
protected $noNeedLogin = ['deviceActivate'];
protected $noNeedVerify = ['deviceActivate'];
/**
* 我的设备 / 连接列表
* GET /iot/api/client/devices
*/
public function devices()
{
$account = $this->memberAccount();
if ($account === '') {
return $this->result->apiError('无法获取当前会员账号');
}
$list = Db::name('iot_connection')
->where('username', $account)
->order('update_at', 'desc')
->limit(200)
->field('client_id,username,ip,status,create_at,update_at')
->select()
->toArray();
return $this->result->setCount(count($list))->apiSuccess($list);
}
/**
* 我的订阅主题列表
* GET /iot/api/client/subscriptions
*/
public function subscriptions()
{
$account = $this->memberAccount();
if ($account === '') {
return $this->result->apiError('无法获取当前会员账号');
}
$clientIds = Db::name('iot_connection')
->where('username', $account)
->column('client_id');
$list = [];
if ($clientIds) {
$list = Db::name('iot_topic')
->whereIn('client_id', $clientIds)
->order('id', 'desc')
->field('client_id,topic,qos,create_at')
->select()
->toArray();
}
return $this->result->apiSuccess(['list' => $list, 'total' => count($list)]);
}
/**
* 发布消息(服务端代发,强制命名空间隔离)
* POST /iot/api/client/publish
* param: topic, payload, qos(0/1/2), retain(0/1)
*/
public function publish()
{
$account = $this->memberAccount();
if ($account === '') {
return $this->result->apiError('无法获取当前会员账号');
}
$topic = trim((string) $this->request->post('topic', ''));
$payload = (string) $this->request->post('payload', '');
$qos = (int) $this->request->post('qos', 0);
$retain = (int) $this->request->post('retain', 0);
if ($topic === '' || $topic[0] === '$') {
return $this->result->apiError('主题不能为空,且禁止发布到 $SYS 等系统主题');
}
// 命名空间隔离:topic 必须以 {username}/ 开头,避免越权发到他人主题
$prefix = $account . '/';
if (strncmp($topic, $prefix, strlen($prefix)) !== 0) {
return $this->result->apiError("主题必须以 {$prefix} 开头(命名空间隔离)");
}
if (!in_array($qos, [0, 1, 2], true)) {
$qos = 0;
}
$ok = Store::enqueueManual($topic, $payload, $qos, $retain, 'app');
if (!$ok) {
return $this->result->apiError('发布失败,请稍后重试');
}
return $this->result->apiSuccess(['topic' => $topic]);
}
/* ============================================================
* 智能设备绑定(华为式:激活与认领分离)
* 绑定与激活分离:设备先入云激活领凭证(deviceActivate,设备侧调),
* 用户再扫码 SN + 配对码绑定(bindDevice,认领归属)。
* 连接约定:设备 MQTT username=clientId=uuid,密码=激活时下发的 secret
* Topic:/devices/{uuid}/state(设备上报·影子) /devices/{uuid}/cmd(下发命令)
* ========================================================== */
/**
* 绑定设备(用户认领:扫码 SN + 配对码,华为式)
* 设备已激活(uuid+secret 已签发)→ 绑定仅建立归属,凭证不变;
* 设备未激活(无配对码的老设备)→ 兼容米家式:绑定即激活
* POST /iot/api/client/bindDevice
* param: sn(必填), pair_code(设备设置了配对码则必填), title, model, room
*/
public function bindDevice()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$sn = trim((string) $this->request->post('sn', ''));
$pairCode = trim((string) $this->request->post('pair_code', ''));
$title = trim((string) $this->request->post('title', ''));
$model = trim((string) $this->request->post('model', ''));
$room = trim((string) $this->request->post('room', ''));
try {
$res = DeviceService::bind($sn, $uid, $title, $model, $room, $pairCode);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess($res);
}
/**
* 设备入云激活(华为式,设备侧调用,无需会员登录)
* 设备出厂预置 sn + activate_token,首次联网调此接口领取正式连接凭证 uuid/secret(明文仅此一次返回)
* POST /iot/api/deviceActivate
* param: sn(必填), token(必填,后台预登记生成的激活令牌)
* 幂等:已激活设备重复调用返回激活状态但不再次下发 secret(如需换凭证走 resetSecret)
*/
public function deviceActivate()
{
$sn = trim((string) $this->request->post('sn', ''));
$token = trim((string) $this->request->post('token', ''));
try {
$res = DeviceService::activate($sn, $token);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess($res);
}
/**
* 我的设备列表(主人 + 共享给我,role 区分 owner/shared,含在线状态 + 影子,剔除密钥)
* GET /iot/api/client/myDevices
*/
public function myDevices()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$list = DeviceService::visibleDevices($uid);
return $this->result->setCount(count($list))->apiSuccess($list);
}
/**
* 共享设备给其他会员(仅主人可操作,华为式家庭授权)
* POST /iot/api/client/shareDevice
* param: device_id(必填), account(被共享者会员账号/手机号), perm(1只读 2可控制,默认2)
*/
public function shareDevice()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$deviceId = (int) $this->request->post('device_id', 0);
$account = trim((string) $this->request->post('account', ''));
$perm = (int) $this->request->post('perm', ShareService::PERM_CTRL);
if ($deviceId <= 0 || $account === '') {
return $this->result->apiError('设备与对方账号必填');
}
// 按账号查被共享会员(member_user 主键 uid)
$target = Db::name('member_user')->where('account', $account)->find();
if (!$target || empty($target['uid'])) {
return $this->result->apiError('对方账号不存在');
}
try {
$res = ShareService::share($deviceId, $uid, (int) $target['uid'], $perm);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess($res);
}
/**
* 撤销共享(仅主人可操作)
* POST /iot/api/client/revokeShare
* param: device_id, member_id
*/
public function revokeShare()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$deviceId = (int) $this->request->post('device_id', 0);
$memberId = (int) $this->request->post('member_id', 0);
if ($deviceId <= 0 || $memberId <= 0) {
return $this->result->apiError('参数无效');
}
try {
ShareService::revoke($deviceId, $uid, $memberId);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess('已撤销共享');
}
/**
* 某设备的共享成员列表(主人管理页)
* GET /iot/api/client/shareList?device_id=1
*/
public function shareList()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$deviceId = (int) $this->request->get('device_id', 0);
if ($deviceId <= 0) {
return $this->result->apiError('参数无效');
}
$dev = DeviceService::findById($deviceId);
if (!$dev || (int) $dev['member_id'] !== $uid) {
return $this->result->apiError('设备不存在或无权操作');
}
$list = ShareService::shareList($deviceId, $uid);
return $this->result->apiSuccess(['list' => $list, 'total' => count($list)]);
}
/**
* 解绑设备
* POST /iot/api/client/unbindDevice
* param: uuid
*/
public function unbindDevice()
{
$uid = $this->memberId();
$uuid = trim((string) $this->request->post('uuid', ''));
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
try {
DeviceService::unbind($uuid, $uid);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess('解绑成功,设备可被重新绑定(密钥将重置)');
}
/**
* 重置设备密钥(旧密钥立即作废,返回新明文一次)
* POST /iot/api/client/resetSecret
* param: uuid
*/
public function resetSecret()
{
$uid = $this->memberId();
$uuid = trim((string) $this->request->post('uuid', ''));
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
try {
$res = DeviceService::resetSecret($uuid, $uid);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess($res);
}
/**
* 换取 MQTT 一次性连接凭证(ticket)
* App 每次建立/重连 MQTT 前调用;连接时 username=会员账号(返回 account)、password=ticket。
* 凭证默认 60s 有效,过期失效;不直接使用会员明文密码,防反编译泄露。
* POST /iot/api/client/mqttTicket
*/
public function mqttTicket()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$account = $this->memberAccount();
if ($account === '') {
return $this->result->apiError('无法获取当前会员账号');
}
// ACL 自愈:ACL 是生成时快照,后来新增的自动规则(如 /status 在线态订阅)不会补到老设备上,
// 老用户升级 App 后会订阅被拒。换 ticket 是每次连接必经之路,在此顺手重建,幂等且代价极小。
try {
DeviceService::resyncMemberAcl($uid);
ShareService::resyncMember($uid);
} catch (\Throwable $e) {
}
$ticket = TicketService::issue($uid, $account);
return $this->result->apiSuccess([
'ticket' => $ticket,
'account' => $account,
'expire_in' => TicketService::TTL,
'expires_at' => time() + TicketService::TTL,
]);
}
/**
* 向绑定的设备下发命令
* POST /iot/api/client/sendCommand
* param: uuid, payload(JSON 字符串), qos(可选0/1/2)
*/
public function sendCommand()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$uuid = trim((string) $this->request->post('uuid', ''));
$payload = (string) $this->request->post('payload', '');
$qos = (int) $this->request->post('qos', 0);
if ($uuid === '') {
return $this->result->apiError('设备uuid不能为空');
}
if ($payload === '') {
return $this->result->apiError('命令内容不能为空');
}
$dev = DeviceService::findByUuid($uuid);
if (!$dev) {
return $this->result->apiError('设备不存在');
}
if (!ShareService::canAccess($uuid, $uid, ShareService::PERM_CTRL)) {
return $this->result->apiError('无权控制该设备');
}
if (!in_array($qos, [0, 1, 2], true)) {
$qos = 0;
}
$ok = Store::enqueueManual(sprintf(DeviceService::TOPIC_CMD, $uuid), $payload, $qos, 0, 'app');
if (!$ok) {
return $this->result->apiError('命令下发失败,请稍后重试');
}
return $this->result->apiSuccess(['uuid' => $uuid, 'topic' => sprintf(DeviceService::TOPIC_CMD, $uuid)]);
}
/**
* 读取设备状态(影子:最后上报的 retain 消息 + 在线状态)
* GET /iot/api/client/deviceState?uuid=xxx
*/
public function deviceState()
{
$uid = $this->memberId();
$uuid = trim((string) $this->request->get('uuid', ''));
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$dev = DeviceService::findByUuid($uuid);
if (!$dev) {
return $this->result->apiError('设备不存在');
}
if (!ShareService::canAccess($uuid, $uid, ShareService::PERM_VIEW)) {
return $this->result->apiError('无权查看该设备');
}
return $this->result->apiSuccess([
'uuid' => $uuid,
'online' => DeviceService::isOnline($uuid),
'shadow' => DeviceService::shadow($uuid),
]);
}
}
+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\api;
use ywxapp\controller\ApiBase;
/**
* App 端 client API 控制器公共基类
*
* 2026-09-18 Client.php 按功能域拆分(38 个方法 → 4 个控制器):
* Client 连接/设备绑定/共享/影子/命令(品类无关的接入层)
* Monitor 传感器配置/历史曲线/设备日志/告警(多路数值品类共用)
* Scene 场景联动 + 设备分组
* Ota 固件升级
*
* ⚠️ 拆分原则:**按功能域,不按设备品类**。接入层(myDevices/sendCommand/
* deviceState/config)全品类共用,将来开关/安防品类复用这些接口,不得
* 再按品类另起控制器。
* 路由 URL(/iot/api/client/*)保持不变,仅路由目标换成新控制器 ⇒ App 无感。
*/
abstract class ClientBase extends ApiBase
{
/**
* 当前会员ID
*/
protected function memberId(): int
{
return (int) ($this->auth->model->uid ?? 0);
}
/**
* 当前会员账号(Broker 连接用户名通常为 member.account)
*/
protected function memberAccount(): string
{
return (string) ($this->auth->model->account ?? '');
}
}
+331
View File
@@ -0,0 +1,331 @@
<?php
/*
* @Author: YwxApp <ywx@ywxapp.cn>
* @Date: 2026-09-18 01:39:38
* @LastEditors: YwxApp <ywx@ywxapp.cn>
* @LastEditTime: 2026-09-18 01:41:50
* @Description:
* @FilePath: \ywxapp_dev\addon\iot\controller\api\Monitor.php
* @CustomString: Copyright (c) 2026 YwxApp
*/
// +----------------------------------------------------------------------
// | 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\api;
use think\facade\Db;
use addon\iot\service\DeviceService;
use addon\iot\service\ShareService;
use addon\iot\service\AlertService;
use addon\iot\service\DeviceLogService;
use addon\iot\service\SensorConfigService;
use addon\iot\service\SensorPointService;
/**
* App 端监测域 API(需框架会员 JWT 登录)
* 路由前缀:/iot/api/monitor/...(监测域;旧 /iot/api/client/* 兼容别名迁移期保留)
*
* 覆盖:传感器位置配置(读写)· 历史曲线 · 设备日志 · 告警。
* 多路数值品类(温湿度/液位/气压等)共用本域,见 ClientBase 头注释的拆分原则。
*/
class Monitor extends ClientBase
{
/* ============================================================
* 传感器配置(配置真源在服务端:App 用它渲染面板骨架,state 只负责填值)
* ========================================================== */
/**
* 读取设备传感器配置
* GET /iot/api/monitor/deviceConfig?uuid=xxx
*
* 返回 {cfg_ver, sync_ver, sync_at, applied, pins, sensors:[{index,alias,probes,upper,lower,gap,enabled}]}
* - 设备离线时同样可用(这正是配置放服务端的核心原因)
* - applied=false 表示设备尚未回执生效(离线时改的配置,等它上线自动收到)
* - pins:总线 GPIO 表(下标 = 位置序号)。pin 是设备编译期常量,v1.7.0 起不在
* state 报文里逐条上报,改由设备上线时在 /status 报一次、服务端缓存后在此下发;
* 从没上报过(≤1.6.2 老固件)返回 [],App 此时靠 state 里的 pin 自行补
*/
public function deviceConfig()
{
$uid = $this->memberId();
$uuid = trim((string) $this->request->get('uuid', ''));
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
if (!DeviceService::findByUuid($uuid)) {
return $this->result->apiError('设备不存在');
}
if (!ShareService::canAccess($uuid, $uid, ShareService::PERM_VIEW)) {
return $this->result->apiError('无权查看该设备');
}
$cfg = SensorConfigService::get($uuid);
$cfg['uuid'] = $uuid;
/* 总线 GPIO 表(下标 = 位置序号):pin 是设备编译期常量,不再逐条进 state 报文,
由设备上线时在 /status 报一次 → DeviceService 缓存 → 这里下发给 App 显示。
没缓存过(≤1.6.2 老固件)返回 [],App 退回用 state 里带的 pin(老固件仍会带)。 */
$cfg['pins'] = DeviceService::getPins($uuid);
$this->result->apiSuccess($cfg);
}
/**
* 保存设备传感器配置(保存即下发 retained,设备在线秒级生效、离线则上线即生效)
* POST /iot/api/monitor/saveDeviceConfig
* param: uuid(必填), sensors(JSON 数组:{index,alias,probes,upper,lower,gap,enabled})
* ⚠️ 位置序号键统一 `index`;旧键 `i` 仍兼容(老 App 提交不会错位),别删兼容分支
*/
public function saveDeviceConfig()
{
$uid = $this->memberId();
$uuid = trim((string) $this->request->post('uuid', ''));
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
if (!ShareService::canAccess($uuid, $uid, ShareService::PERM_CTRL)) {
return $this->result->apiError('无权限修改该设备配置(只读共享)');
}
$sensors = $this->request->post('sensors', '');
if (is_string($sensors)) {
$sensors = json_decode($sensors, true);
}
if (!is_array($sensors)) {
return $this->result->apiError('sensors 参数须为数组或 JSON 数组字符串');
}
try {
$cfg = SensorConfigService::save($uuid, $sensors);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
$cfg['uuid'] = $uuid;
$this->result->apiSuccess($cfg, '配置已保存并下发(设备上线后自动生效)');
}
/**
* 传感器历史曲线(服务端结构化时序)
* GET /iot/api/monitor/sensorSeries?uuid=xxx&pos=0&from=1700000000&to=1700003600&limit=500
*
* 返回「稀疏点」(每条带 interval = 本条覆盖秒数);需要等间隔曲线时由客户端按
* ts → ts+interval 前向填充展开。不在服务端展开的原因:温变上报 10s~120s 一条,
* 展开会放大数倍且大量是重复值,纯浪费带宽。
*
* 每条形状**刻意沿用 HTTP 长名**(temp/temp_diff/probes[{id,temp}],null 即无读数)——
* 与 MQTT 上行报文的两字母键(t/df/pr)是两套:压字节只发生在设备↔服务端之间,
* 服务端往外(HTTP / App / 后台)一律用可读长名,换报文键名不必动 App 的 HTTP 链路。
* alert_mask 为云端复核告警位图(bit j = 槽位 j 越限,bit7 = 位置内温差超限),
* 供 App 标注异常区间。
*/
public function sensorSeries()
{
$uid = $this->memberId();
$uuid = trim((string) $this->request->get('uuid', ''));
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
if ($uuid === '' || !DeviceService::findByUuid($uuid)) {
return $this->result->apiError('设备不存在');
}
if (!ShareService::canAccess($uuid, $uid, ShareService::PERM_VIEW)) {
return $this->result->apiError('无权查看该设备');
}
$pos = (int) $this->request->get('pos', 0);
$from = (int) $this->request->get('from', 0);
$to = (int) $this->request->get('to', 0);
$limit = (int) $this->request->get('limit', 500);
$points = SensorPointService::series($uuid, $pos, $from, $to, $limit);
$data = [
'uuid' => $uuid,
'pos' => $pos,
'from' => $from,
'to' => $to,
'count' => count($points),
'points' => $points,
];
/* debug=1:附查询诊断(库名/表名/实际 SQL/各条件行数/最新原始行/异常原文)。
用于定位「接口 count=0 但直接跑 SQL 有数据」这类静默故障;正常调用不受影响。 */
if ((int) $this->request->get('debug', 0) === 1) {
$data['debug'] = SensorPointService::seriesDebug($uuid, $pos, $from, $to);
}
return $this->result->apiSuccess($data);
}
/**
* 传感器分钟级聚合曲线(时间加权平均)
* GET /iot/api/monitor/sensorAvg?uuid=xxx&pos=0&step=60&window=30&from=&to=&limit=720
*
* - step:桶大小(秒),默认 60 = 每分钟一点;可传 60/120/300/3600…,服务端钳到 [60, 86400]
* - window:查"最近 N 分钟",默认 30;**仅在未传 from 时生效**(from = now - window*60)
* —— 典型用法:最近 30 分钟每分钟一点(step=60&window=30)、最近 60 分钟每分钟一点(step=60&window=60)
* - from/to:显式时间戳(秒),传了优先于 window;to 缺省 = now
* - limit:最多返回桶数(默认 720,即 step=60 时最多覆盖 12 小时)
* - debug=1:附加查询诊断(库名/表名/实际 SQL/各条件行数/最新原始行/异常原文),
* 用于定位「直接跑 SQL 有数据、本接口却空」;正常调用不传即零开销
* - avg 为时间加权平均(SUM(t×秒)/SUM(秒)),min/max 为桶内极值,coverage_s 为桶内数据覆盖秒数
* (coverage_s < step 说明该分钟内有断档,App 可据此画"数据缺口")
* - ts 为桶起点(UTC 对齐),App 显示时按本地时区格式化
*
* 与 sensorSeries 的分工:sensorSeries 返回原始稀疏点(细粒度);本接口返回聚合桶(点数可控)。
*/
public function sensorAvg()
{
$uid = $this->memberId();
$uuid = trim((string) $this->request->get('uuid', ''));
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
if ($uuid === '' || !DeviceService::findByUuid($uuid)) {
return $this->result->apiError('设备不存在');
}
if (!ShareService::canAccess($uuid, $uid, ShareService::PERM_VIEW)) {
return $this->result->apiError('无权查看该设备');
}
$pos = (int) $this->request->get('pos', 0);
$from = (int) $this->request->get('from', 0);
$to = (int) $this->request->get('to', 0);
$step = (int) $this->request->get('step', 60);
$window = (int) $this->request->get('window', 30);
$limit = (int) $this->request->get('limit', 720);
if ($from <= 0 && $window > 0) {
$from = time() - $window * 60; // window 仅在未显式传 from 时生效
}
if ($to <= 0) {
$to = time();
}
$buckets = SensorPointService::seriesAvg($uuid, $pos, $step, $from, $to, $limit);
$data = [
'uuid' => $uuid,
'pos' => $pos,
'step' => $step,
'from' => $from,
'to' => $to,
'count' => count($buckets),
'points' => $buckets,
];
/* debug=1:与 sensorSeries 同一套诊断(库名/表名/实际 SQL/各条件行数/最新原始行/异常原文)。
「SQL 明明有数据、聚合接口却 count=0」时先看这里,不用再猜。 */
if ((int) $this->request->get('debug', 0) === 1) {
$data['debug'] = SensorPointService::seriesDebug($uuid, $pos, $from, $to);
}
return $this->result->apiSuccess($data);
}
/**
* 最近 N 分钟窗口平均(按位置汇总)
* GET /iot/api/monitor/recentAvg?uuid=xxx&window=10&pos=
*
* 与 sensorAvg 的分工:
* - sensorAvg 返回按 step 分桶的曲线序列(适合画趋势)
* - recentAvg 返回每个位置一条汇总值(首屏概览 / 阈值刷新 / 排障都够用)
*
* - window:最近多少分钟,默认 10,范围 [1, 1440](被服务端钳位)
* - pos:可选,只返回某个位置(>=0),默认 -1 = 全部位置
* - 每位置返回 {index, alias, avg, min, max, samples, coverage_s, last_ts, data_ok}
* 无样本的位置 avg=null 且 data_ok=false(前端可据此显示「无数据」而非「0 度」)
*
* 加权方式与 sensorAvg 一致:SUM(t×有效秒)/SUM(秒),避免温变期间简单 AVG 失真。
*/
public function recentAvg()
{
$uid = $this->memberId();
$uuid = trim((string) $this->request->get('uuid', ''));
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
if ($uuid === '' || !DeviceService::findByUuid($uuid)) {
return $this->result->apiError('设备不存在');
}
if (!ShareService::canAccess($uuid, $uid, ShareService::PERM_VIEW)) {
return $this->result->apiError('无权查看该设备');
}
$window = (int) $this->request->get('window', 10);
$pos = (int) $this->request->get('pos', -1);
$result = SensorPointService::recentAvg($uuid, $window, $pos);
$result['uuid'] = $uuid;
$result['window_min'] = $window;
return $this->result->apiSuccess($result);
}
/* ============================================================
* 设备日志 & 告警(P1:基础留痕与通知)
* ========================================================== */
/**
* 设备日志分页(设备维度留痕)
* GET /iot/api/monitor/deviceLogs?uuid=xxx&page=1&size=20&direction=in|out
*/
public function deviceLogs()
{
$uid = $this->memberId();
$uuid = trim((string) $this->request->get('uuid', ''));
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
if ($uuid === '') {
return $this->result->apiError('设备uuid不能为空');
}
$dev = DeviceService::findByUuid($uuid);
if (!$dev) {
return $this->result->apiError('设备不存在');
}
if (!ShareService::canAccess($uuid, $uid, ShareService::PERM_VIEW)) {
return $this->result->apiError('无权查看该设备');
}
$page = max(1, (int) $this->request->get('page', 1));
$size = min(100, max(1, (int) $this->request->get('size', 20)));
$direction = trim((string) $this->request->get('direction', ''));
$data = DeviceLogService::page($uuid, $page, $size, $direction);
return $this->result->apiSuccess($data);
}
/**
* 我的告警列表
* GET /iot/api/monitor/alertList?page=1&size=20&unread=0|1
*/
public function alertList()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$page = max(1, (int) $this->request->get('page', 1));
$size = min(100, max(1, (int) $this->request->get('size', 20)));
$onlyUnread = (int) $this->request->get('unread', 0) === 1;
$data = AlertService::page($uid, $page, $size, $onlyUnread);
return $this->result->apiSuccess($data);
}
/**
* 标记告警已读(空 ids=全部)
* POST /iot/api/monitor/readAlert
* param: ids[](可选)
*/
public function readAlert()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$ids = $this->request->post('ids/a', []);
$n = AlertService::markRead($uid, $ids);
return $this->result->apiSuccess(['affected' => $n]);
}
/**
* 未读告警数(App 角标轮询)
* GET /iot/api/monitor/alertUnread
*/
public function alertUnread()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$data = AlertService::page($uid, 1, 1, true);
return $this->result->apiSuccess(['unread' => $data['unread']]);
}
}
+64
View File
@@ -0,0 +1,64 @@
<?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\api;
use think\facade\Db;
use ywxapp\controller\ApiBase;
use addon\iot\model\Message;
/**
* Mqtt 类
*
* @author ywxapp <admin@ywxapp.cn>
*/
class Mqtt extends ApiBase
{
protected $noNeedLogin = [];
protected $noNeedVerify = ['*'];
/**
* 获取 Broker 运行状态
* GET /iot/api/mqtt/status
*/
public function status()
{
$data = [
'online' => Db::name('iot_connection')->where('status', 1)->count(),
'total' => Db::name('iot_connection')->count(),
'messages' => Message::count(),
'topics' => Db::name('iot_topic')->count(),
];
$this->result->success($data);
}
/**
* 发布消息
* POST /iot/api/mqtt/publish {topic, payload, qos}
*
* 零外部依赖:写入出站队列(DB),由常驻 Broker 进程消费后经内部路由投递,
* 不再依赖 workerman/mqtt 客户端连接本地 Broker。
*/
public function publish()
{
$topic = input('topic', '');
$payload = input('payload', '');
$qos = (int) input('qos', 0);
if (!$topic) {
$this->result->error('topic required');
}
$ok = \addon\iot\service\Store::enqueueManual($topic, $payload, $qos, 0, 'api');
if ($ok) {
$this->result->success('已加入发布队列,Broker 将投递给在线订阅者');
} else {
$this->result->error('发布失败:无法写入出站队列(请检查数据库)');
}
}
}
+95
View File
@@ -0,0 +1,95 @@
<?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\api;
use think\facade\Db;
use addon\iot\service\DeviceService;
use addon\iot\service\ShareService;
use addon\iot\service\OtaService;
/**
* App 端 OTA 域 API(需框架会员 JWT 登录)
* 路由前缀:/iot/api/ota/...(OTA 域;旧 /iot/api/client/* 兼容别名迁移期保留)
*
* 覆盖:固件查询与升级指令下发。
*/
class Ota extends ClientBase
{
/**
* 我的设备可用的固件
* GET /iot/api/ota/otaList?uuid=xxx(不传 uuid 返回全部设备)
* 返回:{ device, ota|null },App 端比对影子里的 version 判断是否有新版本
*/
public function otaList()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$uuid = trim((string) $this->request->get('uuid', ''));
// OTA 列表只用设备行(model 等),不需要位置配置:false 省掉 2 条 SQL 与响应体积
$devices = DeviceService::visibleDevices($uid, false);
if ($uuid !== '') {
$devices = array_values(array_filter($devices, fn($d) => $d['uuid'] === $uuid));
}
$cache = [];
$list = [];
foreach ($devices as $d) {
$model = (string) $d['model'];
if ($model === '') {
$list[] = ['device' => $d, 'ota' => null];
continue;
}
if (!isset($cache[$model])) {
$cache[$model] = Db::name('iot_ota')
->where('model', $model)->where('status', 1)
->order('id', 'desc')->find();
}
$list[] = ['device' => $d, 'ota' => $cache[$model] ?: null];
}
return $this->result->apiSuccess(['list' => $list, 'total' => count($list)]);
}
/**
* 我的设备 OTA 升级
* POST /iot/api/ota/publishOta
* param: ota_id, uuid
*/
public function publishOta()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$otaId = (int) $this->request->post('ota_id', 0);
$uuid = trim((string) $this->request->post('uuid', ''));
if (!$otaId) {
return $this->result->apiError('固件不能为空');
}
if ($uuid === '') {
return $this->result->apiError('设备uuid不能为空');
}
$dev = DeviceService::findByUuid($uuid);
if (!$dev) {
return $this->result->apiError('设备不存在');
}
if (!ShareService::canAccess($uuid, $uid, ShareService::PERM_CTRL)) {
return $this->result->apiError('无权控制该设备');
}
try {
$n = OtaService::publish($otaId, [$uuid]);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess(['affected' => $n, 'uuid' => $uuid]);
}
}
+304
View File
@@ -0,0 +1,304 @@
<?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\api;
use think\facade\Db;
use addon\iot\service\ShareService;
use addon\iot\service\SceneService;
use addon\iot\service\GroupService;
/**
* App 端联动域 API(需框架会员 JWT 登录)
* 路由前缀:/iot/api/scene/...(联动域;旧 /iot/api/client/* 兼容别名迁移期保留)
*
* 覆盖:场景联动(触发器/动作/执行/日志)+ 设备分组(房间/自定义)。
* 两者同属"用户组织设备的方式",合在一个控制器。
*/
class Scene extends ClientBase
{
/* ============================================================
* 场景联动(智慧生活自动化)
* ========================================================== */
/**
* 我的场景列表
* GET /iot/api/scene/sceneList
*/
public function sceneList()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$list = SceneService::list($uid);
return $this->result->apiSuccess(['list' => $list, 'total' => count($list)]);
}
/**
* 场景详情(含触发器/动作)
* GET /iot/api/scene/sceneDetail?id=1
*/
public function sceneDetail()
{
$uid = $this->memberId();
$id = (int) $this->request->get('id', 0);
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$scene = SceneService::findScene($id);
if (!$scene) {
return $this->result->apiError('场景不存在');
}
if ((int) $scene['member_id'] !== $uid) {
return $this->result->apiError('无权查看该场景');
}
return $this->result->apiSuccess($scene);
}
/**
* 新建/编辑场景
* POST /iot/api/scene/saveScene
* param: id?, title, icon, enabled, triggers(JSON数组), actions(JSON数组)
* triggers: [{"type":"device_state|schedule|manual","topic":"/devices/+/state",
* "condition_json":[{field,op,value,ref}],"cron":"0 8 * * *","enabled":1}]
* actions: [{"type":"send_cmd|http|notify","device_uuid":"...","payload_json":"...","topic":"..."}]
*/
public function saveScene()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
try {
$data = $this->request->post();
$data['member_id'] = $uid;
$triggers = json_decode((string) ($data['triggers'] ?? ''), true);
$actions = json_decode((string) ($data['actions'] ?? ''), true);
if (!is_array($triggers) && !is_array($actions)) {
return $this->result->apiError('触发器/动作格式错误');
}
$data['triggers'] = is_array($triggers) ? $triggers : [];
$data['actions'] = is_array($actions) ? $actions : [];
$id = SceneService::save($data);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess(['id' => $id]);
}
/**
* 删除场景
* POST /iot/api/scene/deleteScene
* param: id
*/
public function deleteScene()
{
$uid = $this->memberId();
$id = (int) $this->request->post('id', 0);
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$scene = SceneService::findScene($id);
if (!$scene || (int) $scene['member_id'] !== $uid) {
return $this->result->apiError('场景不存在或无权操作');
}
SceneService::remove($id, $uid);
return $this->result->apiSuccess('已删除');
}
/**
* 启用/停用场景
* POST /iot/api/scene/toggleScene
* param: id, enabled(0/1)
*/
public function toggleScene()
{
$uid = $this->memberId();
$id = (int) $this->request->post('id', 0);
$enabled = (int) $this->request->post('enabled', 0);
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$scene = SceneService::findScene($id);
if (!$scene || (int) $scene['member_id'] !== $uid) {
return $this->result->apiError('场景不存在或无权操作');
}
SceneService::toggle($id, $enabled, $uid);
return $this->result->apiSuccess('已更新');
}
/**
* 手动执行场景
* POST /iot/api/scene/runScene
* param: id
*/
public function runScene()
{
$uid = $this->memberId();
$id = (int) $this->request->post('id', 0);
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$scene = SceneService::findScene($id);
if (!$scene || (int) $scene['member_id'] !== $uid) {
return $this->result->apiError('场景不存在或无权操作');
}
$ok = SceneService::runScene($id, 'manual', 'App手动执行');
return $this->result->apiSuccess($ok ? '已触发执行' : '执行完成(无动作或场景停用)');
}
/**
* 场景执行日志
* GET /iot/api/scene/sceneLogs?id=1&page=1
*/
public function sceneLogs()
{
$uid = $this->memberId();
$id = (int) $this->request->get('id', 0);
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$scene = SceneService::findScene($id);
if (!$scene || (int) $scene['member_id'] !== $uid) {
return $this->result->apiError('场景不存在或无权操作');
}
$page = max(1, (int) $this->request->get('page', 1));
$size = min(100, max(1, (int) $this->request->get('size', 20)));
$data = SceneService::logs($id, $page, $size);
return $this->result->apiSuccess($data);
}
/* ============================================================
* 设备分组(智慧生活:房间/自定义)
* ========================================================== */
/**
* 我的分组列表(含设备数/在线数)
* GET /iot/api/scene/groupList
*/
public function groupList()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
$list = GroupService::groups($uid);
return $this->result->apiSuccess(['list' => $list, 'total' => count($list)]);
}
/**
* 新建/编辑分组
* POST /iot/api/scene/saveGroup
* param: id?, title, type(room/custom), sort?
*/
public function saveGroup()
{
$uid = $this->memberId();
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
try {
$data = $this->request->post();
$data['member_id'] = $uid;
$id = GroupService::save($data);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess(['id' => $id]);
}
/**
* 删除分组
* POST /iot/api/scene/deleteGroup
* param: id
*/
public function deleteGroup()
{
$uid = $this->memberId();
$id = (int) $this->request->post('id', 0);
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
try {
GroupService::remove($id, $uid);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess('已删除');
}
/**
* 设备加入分组
* POST /iot/api/scene/groupAddDevice
* param: group_id, device_id
*/
public function groupAddDevice()
{
$uid = $this->memberId();
$groupId = (int) $this->request->post('group_id', 0);
$deviceId = (int) $this->request->post('device_id', 0);
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
// 校验设备归属/共享权限
$dev = Db::name('iot_device')->where('id', $deviceId)->find();
if (!$dev || !ShareService::canAccess((string) $dev['uuid'], $uid, ShareService::PERM_VIEW)) {
return $this->result->apiError('设备不存在或无权操作');
}
try {
GroupService::addDevice($groupId, $deviceId, $uid);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess('已加入分组');
}
/**
* 设备移出分组
* POST /iot/api/scene/groupRemoveDevice
* param: group_id, device_id
*/
public function groupRemoveDevice()
{
$uid = $this->memberId();
$groupId = (int) $this->request->post('group_id', 0);
$deviceId = (int) $this->request->post('device_id', 0);
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
try {
GroupService::removeDevice($groupId, $deviceId, $uid);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess('已移出分组');
}
/**
* 组内设备列表
* GET /iot/api/scene/groupDevices?group_id=1
*/
public function groupDevices()
{
$uid = $this->memberId();
$groupId = (int) $this->request->get('group_id', 0);
if ($uid <= 0) {
return $this->result->apiError('未登录');
}
try {
$data = GroupService::devicesByGroup($groupId, $uid);
} catch (\Throwable $e) {
return $this->result->apiError($e->getMessage());
}
return $this->result->apiSuccess($data);
}
}
+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('保存成功');
}
}