// +---------------------------------------------------------------------- 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('已删除'); } }