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