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

+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);
}
}