继续阅读完整内容
支持我们的网站,请点击查看下方广告
这是一个综合性较强的Joomla扩展开发项目。涉及多个功能模块,这里提供一个完整的扩展包生成脚本和核心文件结构。
1. 一键生成脚本(generate_extension.sh)
#!/bin/bash # ============================================ # Joomla 5.4 智能健康设备管理扩展生成脚本 # 功能:蓝牙广告、设备管理、健康数据收集等 # ============================================ EXTENSION_NAME="plg_system_smarthealth" EXTENSION_TITLE="Smart Health Manager" AUTHOR="Your Company" VERSION="1.0.0" DATE=$(date +"%Y-%m-%d") echo "========================================" echo "开始生成 Joomla 智能健康管理扩展" echo "========================================" # 创建目录结构 mkdir -p $ {EXTENSION_NAME} mkdir -p $ {EXTENSION_NAME} /language/en-GB mkdir -p $ {EXTENSION_NAME} /sql mkdir -p $ {EXTENSION_NAME} /tmpl mkdir -p $ {EXTENSION_NAME} /media/css mkdir -p $ {EXTENSION_NAME} /media/js mkdir -p $ {EXTENSION_NAME} /media/images # 1. 创建主插件文件 cat > $ {EXTENSION_NAME} /$ {EXTENSION_NAME} .php << 'EOF' <?php defined('_JEXEC') or die; use Joomla\CMS\Plugin\CMSPlugin; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; class PlgSystemSmarthealth extends CMSPlugin { protected $autoloadLanguage = true; public function onAfterInitialise() { $app = Factory::getApplication(); // 仅在前台执行 if ($app->isClient('site')) { $this->handleDeviceConnections(); $this->serveBluetoothAdvertisements(); } } public function onAfterRoute() { $app = Factory::getApplication(); $input = $app->input; // 处理API请求 if ($input->get('option') === 'com_ajax' && $input->get('plugin') === 'smarthealth') { $this->handleApiRequest(); } } /** * 处理设备连接 */ private function handleDeviceConnections() { // 蓝牙设备连接逻辑 $deviceId = $this->params->get('default_device', ''); if (!empty($deviceId)) { // 设备连接和数据处理 $this->processDeviceData($deviceId); } } /** * 提供蓝牙广告服务 */ private function serveBluetoothAdvertisements() { $advType = $this->params->get('advertisement_type', 'beacon'); switch ($advType) { case 'beacon': $this->serveBeaconAdvertisement(); break; case 'eddystone': $this->serveEddystoneAdvertisement(); break; case 'custom': $this->serveCustomAdvertisement(); break; } } /** * 处理API请求 */ private function handleApiRequest() { $app = Factory::getApplication(); $input = $app->input; $method = $_SERVER['REQUEST_METHOD']; header('Content-Type: application/json'); switch ($method) { case 'GET': $this->handleGetRequest(); break; case 'POST': $this->handlePostRequest(); break; case 'PUT': $this->handlePutRequest(); break; case 'DELETE': $this->handleDeleteRequest(); break; default: echo json_encode(['error' => 'Method not allowed']); break; } $app->close(); } /** * 处理GET请求 */ private function handleGetRequest() { $input = Factory::getApplication()->input; $action = $input->get('action', ''); switch ($action) { case 'get_device_data': $this->getDeviceData(); break; case 'get_health_metrics': $this->getHealthMetrics(); break; case 'get_qr_code': $this->generateQRCode(); break; default: echo json_encode(['status' => 'ready']); break; } } /** * 获取设备数据 */ private function getDeviceData() { $db = Factory::getDbo(); $query = $db->getQuery(true) ->select('*') ->from($db->quoteName('#__smarthealth_devices')) ->where($db->quoteName('status') . ' = 1'); $db->setQuery($query); $results = $db->loadObjectList(); echo json_encode([ 'success' => true, 'devices' => $results ]); } /** * 生成二维码 */ private function generateQRCode() { $input = Factory::getApplication()->input; $data = $input->get('data', '', 'string'); // 使用Google Charts API生成二维码 $qrUrl = "https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=" . urlencode($data); echo json_encode([ 'success' => true, 'qr_url' => $qrUrl, 'data' => $data ]); } /** * 处理设备数据 */ private function processDeviceData($deviceId) { // 模拟设备数据处理 $data = [ 'device_id' => $deviceId, 'timestamp' => time(), 'battery' => rand(20, 100), 'signal_strength' => rand(-80, -30) ]; // 存储到数据库 $this->storeDeviceData($data); } /** * 存储设备数据 */ private function storeDeviceData($data) { $db = Factory::getDbo(); $query = $db->getQuery(true) ->insert($db->quoteName('#__smarthealth_device_logs')) ->columns($db->quoteName(['device_id', 'timestamp', 'data'])) ->values( $db->quote($data['device_id']) . ', ' . $db->quote($data['timestamp']) . ', ' . $db->quote(json_encode($data)) ); $db->setQuery($query); $db->execute(); } } EOF # 2. 创建XML安装文件 cat > $ {EXTENSION_NAME} /$ {EXTENSION_NAME} .xml << EOF <?xml version="1.0" encoding="UTF-8"?> <extension type="plugin" group="system" method="upgrade"> <name>plg_system_smarthealth</name> <author>$AUTHOR</author> <creationDate>$DATE</creationDate> <copyright>Copyright (C) $AUTHOR. All rights reserved.</copyright> <license>GNU General Public License version 2 or later</license> <authorEmail>contact@example.com</authorEmail> <authorUrl>www.example.com</authorUrl> <version>$VERSION</version> <description>PLG_SYSTEM_SMARTHEALTH_XML_DESCRIPTION</description> <files> <folder>language</folder> <folder>tmpl</folder> <folder>media</folder> <filename plugin="smarthealth">$ {EXTENSION_NAME} .php</filename> <filename>index.html</filename> </files> <config> <fields name="params"> <fieldset name="basic"> <field name="enable_bluetooth" type="radio" default="1" label="PLG_SYSTEM_SMARTHEALTH_ENABLE_BLUETOOTH" description="PLG_SYSTEM_SMARTHEALTH_ENABLE_BLUETOOTH_DESC"> <option value="0">JNO</option> <option value="1">JYES</option> </field> <field name="advertisement_type" type="list" default="beacon" label="PLG_SYSTEM_SMARTHEALTH_ADV_TYPE" description="PLG_SYSTEM_SMARTHEALTH_ADV_TYPE_DESC"> <option value="beacon">iBeacon</option> <option value="eddystone">Eddystone</option> <option value="custom">Custom</option> </field> <field name="api_key" type="text" label="PLG_SYSTEM_SMARTHEALTH_API_KEY" description="PLG_SYSTEM_SMARTHEALTH_API_KEY_DESC" size="40" /> <field name="default_device" type="text" label="PLG_SYSTEM_SMARTHEALTH_DEFAULT_DEVICE" description="PLG_SYSTEM_SMARTHEALTH_DEFAULT_DEVICE_DESC" /> </fieldset> <fieldset name="advanced"> <field name="enable_health_monitoring" type="radio" default="1" label="PLG_SYSTEM_SMARTHEALTH_ENABLE_HEALTH_MONITORING" description="PLG_SYSTEM_SMARTHEALTH_ENABLE_HEALTH_MONITORING_DESC"> <option value="0">JNO</option> <option value="1">JYES</option> </field> <field name="heart_rate_threshold" type="number" default="120" label="PLG_SYSTEM_SMARTHEALTH_HEART_RATE_THRESHOLD" description="PLG_SYSTEM_SMARTHEALTH_HEART_RATE_THRESHOLD_DESC" /> <field name="blood_pressure_threshold" type="text" default="140/90" label="PLG_SYSTEM_SMARTHEALTH_BP_THRESHOLD" description="PLG_SYSTEM_SMARTHEALTH_BP_THRESHOLD_DESC" /> </fieldset> </fields> </config> <install> <sql> <file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file> </sql> </install> <uninstall> <sql> <file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file> </sql> </install> <update> <schemas> <schemapath type="mysql">sql/updates/mysql</schemapath> </schemas> </update> <media destination="plg_system_smarthealth" folder="media"> <folder>css</folder> <folder>js</folder> <folder>images</folder> </media> </extension> EOF # 3. 创建SQL安装文件 cat > $ {EXTENSION_NAME} /sql/install.mysql.utf8.sql << 'EOF' CREATE TABLE IF NOT EXISTS `#__smarthealth_devices` ( `id` int(11) NOT NULL AUTO_INCREMENT, `device_id` varchar(100) NOT NULL, `device_name` varchar(255) NOT NULL, `device_type` enum('wearable','beacon','sensor','other') DEFAULT 'wearable', `mac_address` varchar(17) DEFAULT NULL, `bluetooth_uuid` varchar(36) DEFAULT NULL, `last_seen` datetime DEFAULT NULL, `battery_level` tinyint(3) DEFAULT NULL, `signal_strength` int(11) DEFAULT NULL, `status` tinyint(1) DEFAULT 1, `params` text, `created` datetime NOT NULL, `created_by` int(11) DEFAULT NULL, `modified` datetime DEFAULT NULL, `modified_by` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `idx_device_id` (`device_id`), KEY `idx_device_type` (`device_type`), KEY `idx_status` (`status`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `#__smarthealth_health_data` ( `id` int(11) NOT NULL AUTO_INCREMENT, `device_id` varchar(100) NOT NULL, `user_id` int(11) DEFAULT NULL, `heart_rate` smallint(3) DEFAULT NULL, `blood_pressure_systolic` smallint(3) DEFAULT NULL, `blood_pressure_diastolic` smallint(3) DEFAULT NULL, `body_temperature` decimal(3,1) DEFAULT NULL, `blood_oxygen` decimal(4,1) DEFAULT NULL, `stress_level` tinyint(3) DEFAULT NULL, `emotion_state` varchar(50) DEFAULT NULL, `steps_count` int(11) DEFAULT 0, `calories_burned` int(11) DEFAULT 0, `sleep_quality` varchar(20) DEFAULT NULL, `latitude` decimal(10,8) DEFAULT NULL, `longitude` decimal(11,8) DEFAULT NULL, `altitude` decimal(10,2) DEFAULT NULL, `accuracy` decimal(6,2) DEFAULT NULL, `timestamp` datetime NOT NULL, `data_source` enum('manual','device','api') DEFAULT 'device', `is_alert` tinyint(1) DEFAULT 0, `alert_message` text, `raw_data` text, PRIMARY KEY (`id`), KEY `idx_device_id` (`device_id`), KEY `idx_user_id` (`user_id`), KEY `idx_timestamp` (`timestamp`), KEY `idx_is_alert` (`is_alert`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `#__smarthealth_device_logs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `device_id` varchar(100) NOT NULL, `log_type` enum('connection','data','error','status') DEFAULT 'data', `message` text, `data` text, `timestamp` datetime NOT NULL, `ip_address` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_device_id` (`device_id`), KEY `idx_log_type` (`log_type`), KEY `idx_timestamp` (`timestamp`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `#__smarthealth_advertisements` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `ad_type` enum('bluetooth','qrcode','nfc','url') DEFAULT 'bluetooth', `content` text, `target_url` varchar(500) DEFAULT NULL, `bluetooth_uuid` varchar(36) DEFAULT NULL, `major` int(11) DEFAULT NULL, `minor` int(11) DEFAULT NULL, `tx_power` int(11) DEFAULT NULL, `qrcode_data` text, `start_date` datetime DEFAULT NULL, `end_date` datetime DEFAULT NULL, `display_count` int(11) DEFAULT 0, `click_count` int(11) DEFAULT 0, `status` tinyint(1) DEFAULT 1, `created` datetime NOT NULL, `created_by` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_ad_type` (`ad_type`), KEY `idx_status` (`status`), KEY `idx_dates` (`start_date`,`end_date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `#__smarthealth_user_sessions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `session_token` varchar(100) NOT NULL, `device_info` text, `last_activity` datetime NOT NULL, `expires_at` datetime NOT NULL, `is_active` tinyint(1) DEFAULT 1, PRIMARY KEY (`id`), UNIQUE KEY `idx_session_token` (`session_token`), KEY `idx_user_id` (`user_id`), KEY `idx_expires` (`expires_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; EOF # 4. 创建SQL卸载文件 cat > $ {EXTENSION_NAME} /sql/uninstall.mysql.utf8.sql << 'EOF' DROP TABLE IF EXISTS `#__smarthealth_devices`; DROP TABLE IF EXISTS `#__smarthealth_health_data`; DROP TABLE IF EXISTS `#__smarthealth_device_logs`; DROP TABLE IF EXISTS `#__smarthealth_advertisements`; DROP TABLE IF EXISTS `#__smarthealth_user_sessions`; EOF # 5. 创建语言文件 cat > $ {EXTENSION_NAME} /language/en-GB/en-GB.plg_system_smarthealth.ini << 'EOF' PLG_SYSTEM_SMARTHEALTH_XML_DESCRIPTION="Smart Health Management Plugin - Bluetooth device management, health monitoring, and advertisement system" PLG_SYSTEM_SMARTHEALTH_ENABLE_BLUETOOTH="Enable Bluetooth" PLG_SYSTEM_SMARTHEALTH_ENABLE_BLUETOOTH_DESC="Enable Bluetooth device connectivity and data collection" PLG_SYSTEM_SMARTHEALTH_ADV_TYPE="Advertisement Type" PLG_SYSTEM_SMARTHEALTH_ADV_TYPE_DESC="Select the type of Bluetooth advertisement to serve" PLG_SYSTEM_SMARTHEALTH_API_KEY="API Key" PLG_SYSTEM_SMARTHEALTH_API_KEY_DESC="Secure API key for device communication" PLG_SYSTEM_SMARTHEALTH_DEFAULT_DEVICE="Default Device ID" PLG_SYSTEM_SMARTHEALTH_DEFAULT_DEVICE_DESC="Default device identifier for testing" PLG_SYSTEM_SMARTHEALTH_ENABLE_HEALTH_MONITORING="Enable Health Monitoring" PLG_SYSTEM_SMARTHEALTH_ENABLE_HEALTH_MONITORING_DESC="Monitor and record health metrics from devices" PLG_SYSTEM_SMARTHEALTH_HEART_RATE_THRESHOLD="Heart Rate Threshold" PLG_SYSTEM_SMARTHEALTH_HEART_RATE_THRESHOLD_DESC="Alert threshold for heart rate (bpm)" PLG_SYSTEM_SMARTHEALTH_BP_THRESHOLD="Blood Pressure Threshold" PLG_SYSTEM_SMARTHEALTH_BP_THRESHOLD_DESC="Alert threshold for blood pressure (systolic/diastolic)" PLG_SYSTEM_SMARTHEALTH_DEVICE_CONNECTED="Device Connected" PLG_SYSTEM_SMARTHEALTH_DATA_RECEIVED="Health Data Received" PLG_SYSTEM_SMARTHEALTH_ALERT_TRIGGERED="Health Alert Triggered" PLG_SYSTEM_SMARTHEALTH_ADVERTISEMENT_SERVED="Advertisement Served" EOF cat > $ {EXTENSION_NAME} /language/en-GB/en-GB.plg_system_smarthealth.sys.ini << 'EOF' PLG_SYSTEM_SMARTHEALTH="Smart Health Manager" PLG_SYSTEM_SMARTHEALTH_XML_DESCRIPTION="Smart Health Management Plugin" EOF # 6. 创建模板文件 cat > $ {EXTENSION_NAME} /tmpl/device_dashboard.php << 'EOF' <?php defined('_JEXEC') or die; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; ?> <div class="smarthealth-dashboard"> <h2><?php echo Text::_('PLG_SYSTEM_SMARTHEALTH_DEVICE_DASHBOARD'); ?></h2> <div class="row"> <div class="col-md-4"> <div class="card device-status"> <div class="card-header"> <h5>Device Status</h5> </div> <div class="card-body"> <div id="device-list"></div> </div> </div> </div> <div class="col-md-8"> <div class="card health-metrics"> <div class="card-header"> <h5>Health Metrics</h5> </div> <div class="card-body"> <canvas id="healthChart" width="400" height="200"></canvas> </div> </div> </div> </div> <div class="row mt-4"> <div class="col-md-6"> <div class="card qr-generator"> <div class="card-header"> <h5>QR Code Generator</h5> </div> <div class="card-body"> <input type="text" id="qr-data" class="form-control" placeholder="Enter data for QR code"> <button onclick="generateQRCode()" class="btn btn-primary mt-2">Generate QR</button> <div id="qr-result" class="mt-3"></div> </div> </div> </div> <div class="col-md-6"> <div class="card advertisement-control"> <div class="card-header"> <h5>Bluetooth Advertisement</h5> </div> <div class="card-body"> <button onclick="startAdvertisement()" class="btn btn-success">Start Beacon</button> <button onclick="stopAdvertisement()" class="btn btn-danger">Stop Beacon</button> <div id="adv-status" class="mt-3"></div> </div> </div> </div> </div> </div> <script> // 设备数据获取 function loadDeviceData() { fetch('/index.php?option=com_ajax&plugin=smarthealth&action=get_device_data') .then(response => response.json()) .then(data => { if (data.success) { updateDeviceList(data.devices); } }); } // 生成二维码 function generateQRCode() { const data = document.getElementById('qr-data').value; if (!data) { alert('Please enter data for QR code'); return; } fetch(`/index.php?option=com_ajax&plugin=smarthealth&action=get_qr_code&data=$ {encodeURIComponent(data)} `) .then(response => response.json()) .then(data => { if (data.success) { document.getElementById('qr-result').innerHTML = `
Data: $ {data.data} `; } }); } // 更新设备列表 function updateDeviceList(devices) { const deviceList = document.getElementById('device-list'); let html = '
'; devices.forEach(device => { html += `$ {device.device_name} </strong><br> <small>ID: $ {device.device_id} </small><br> <small>Battery: $ {device.battery_level} %</small><br> <small>Last seen: $ {device.last_seen} </small> </li> `; }); html += '</ul>'; deviceList.innerHTML = html; } // 每30秒刷新一次设备数据 setInterval(loadDeviceData, 30000); loadDeviceData(); // 初始加载 </script> EOF # 7. 创建JavaScript文件 cat > $ {EXTENSION_NAME} /media/js/smarthealth.js << 'EOF' /** * Smart Health Plugin JavaScript * Bluetooth and Device Management */ class SmartHealthManager { constructor() { this.apiBase = '/index.php?option=com_ajax&plugin=smarthealth'; this.devices = []; this.healthData = []; this.chart = null; } // 初始化 init() { this.loadDevices(); this.setupEventListeners(); this.initHealthChart(); this.startRealTimeUpdates(); } // 加载设备 async loadDevices() { try { const response = await fetch(`$ {this.apiBase} &action=get_device_data`); const data = await response.json(); if (data.success) { this.devices = data.devices; this.updateDeviceDisplay(); } } catch (error) { console.error('Error loading devices:', error); } } // 获取健康数据 async getHealthMetrics(userId = null) { try { const url = userId ? `$ {this.apiBase} &action=get_health_metrics&user_id=$ {userId} ` : `$ {this.apiBase} &action=get_health_metrics`; const response = await fetch(url); const data = await response.json(); if (data.success) { this.healthData = data.metrics; this.updateHealthChart(); } } catch (error) { console.error('Error loading health metrics:', error); } } // 初始化健康图表 initHealthChart() { const ctx = document.getElementById('healthChart')?.getContext('2d'); if (!ctx) return; this.chart = new Chart(ctx, { type: 'line', data: { labels: [], datasets: [{ label: 'Heart Rate', data: [], borderColor: 'rgb(255, 99, 132)', tension: 0.1 }, { label: 'Blood Pressure (Systolic)', data: [], borderColor: 'rgb(54, 162, 235)', tension: 0.1 }] }, options: { responsive: true, scales: { y: { beginAtZero: false } } } }); } // 更新健康图表 updateHealthChart() { if (!this.chart || !this.healthData.length) return; const labels = this.healthData.map(d => new Date(d.timestamp).toLocaleTimeString() ); const heartRates = this.healthData.map(d => d.heart_rate); const bloodPressures = this.healthData.map(d => d.blood_pressure_systolic); this.chart.data.labels = labels; this.chart.data.datasets[0].data = heartRates; this.chart.data.datasets[1].data = bloodPressures; this.chart.update(); } // 生成二维码 async generateQRCode(data) { try { const response = await fetch( `$ {this.apiBase} &action=get_qr_code&data=$ {encodeURIComponent(data)} ` ); const result = await response.json(); if (result.success) { return { url: result.qr_url, data: result.data }; } } catch (error) { console.error('Error generating QR code:', error); } } // 发送健康警报 async sendHealthAlert(alertData) { try { const response = await fetch(`$ {this.apiBase} &action=send_alert`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(alertData) }); return await response.json(); } catch (error) { console.error('Error sending alert:', error); } } // 开始实时更新 startRealTimeUpdates() { // WebSocket 连接用于实时数据 this.setupWebSocket(); // 定期刷新数据 setInterval(() => { this.loadDevices(); this.getHealthMetrics(); }, 30000); // 每30秒 } // 设置WebSocket连接 setupWebSocket() { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `$ {protocol} //$ {window.location.host} /ws/smarthealth`; this.ws = new WebSocket(wsUrl); this.ws.onmessage = (event) => { const data = JSON.parse(event.data); this.handleWebSocketMessage(data); }; this.ws.onclose = () => { console.log('WebSocket disconnected. Reconnecting...'); setTimeout(() => this.setupWebSocket(), 3000); }; } // 处理WebSocket消息 handleWebSocketMessage(data) { switch (data.type) { case 'device_update': this.handleDeviceUpdate(data.payload); break; case 'health_alert': this.handleHealthAlert(data.payload); break; case 'advertisement': this.handleAdvertisement(data.payload); break; } } // 处理设备更新 handleDeviceUpdate(payload) { console.log('Device update:', payload); // 更新设备列表 const index = this.devices.findIndex(d => d.device_id === payload.device_id); if (index !== -1) { this.devices[index] = { ...this.devices[index], ...payload }; } else { this.devices.push(payload); } this.updateDeviceDisplay(); } // 处理健康警报 handleHealthAlert(payload) { console.warn('Health alert:', payload); // 显示通知 if ('Notification' in window && Notification.permission === 'granted') { new Notification('Health Alert', { body: payload.message, icon: '/media/plg_system_smarthealth/images/alert.png' }); } // 更新UI this.showAlert(payload); } // 处理广告 handleAdvertisement(payload) { console.log('Advertisement received:', payload); // 显示广告(可根据需要定制) if (payload.ad_type === 'bluetooth' && payload.content) { this.displayAdvertisement(payload.content); } } // 更新设备显示 updateDeviceDisplay() { const container = document.getElementById('device-list'); if (!container) return; let html = ''; this.devices.forEach(device => { const batteryClass = device.battery_level > 50 ? 'battery-high' : device.battery_level > 20 ? 'battery-medium' : 'battery-low'; html += `$ {device.device_name} </h6> <span class="device-status $ {device.status ? 'online' : 'offline'} "> $ {device.status ? 'Online' : 'Offline'} </span> </div> <div class="device-info"> <p><small>ID: $ {device.device_id} </small></p> <p><small>Type: $ {device.device_type} </small></p> <div class="battery-indicator $ {batteryClass} "> Battery: $ {device.battery_level} % </div> <p><small>Last seen: $ {new Date(device.last_seen).toLocaleString()} </small></p> </div> </div> `; }); html += '</div>'; container.innerHTML = html; } // 显示警报 showAlert(alert) { const alertDiv = document.createElement('div'); alertDiv.className = 'health-alert alert alert-warning'; alertDiv.innerHTML = `
$ {alert.title || 'Health Alert'} </h5> <p>$ {alert.message} </p> <p><small>Time: $ {new Date(alert.timestamp).toLocaleString()} </small></p> `; document.querySelector('.smarthealth-dashboard')?.prepend(alertDiv); // 10秒后自动移除 setTimeout(() => alertDiv.remove(), 10000); } // 显示广告 displayAdvertisement(content) { const adDiv = document.createElement('div'); adDiv.className = 'bluetooth-advertisement'; adDiv.innerHTML = content; // 添加到页面底部 document.body.appendChild(adDiv); // 15秒后自动移除 setTimeout(() => adDiv.remove(), 15000); } // 设置事件监听器 setupEventListeners() { // 请求通知权限 if ('Notification' in window && Notification.permission === 'default') { Notification.requestPermission(); } } } // 自动初始化 document.addEventListener('DOMContentLoaded', () => { window.smartHealth = new SmartHealthManager(); window.smartHealth.init(); }); EOF # 8. 创建CSS文件 cat > $ {EXTENSION_NAME} /media/css/smarthealth.css << 'EOF' /** * Smart Health Plugin CSS */ .smarthealth-dashboard { padding: 20px; background: #f8f9fa; min-height: 100vh; } .device-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; margin-top: 20px; } .device-card { background: white; border-radius: 8px; padding: 15px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); transition: transform 0.2s; } .device-card:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.15); } .device-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; } .device-status { padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; } .device-status.online { background: #d4edda; color: #155724; } .device-status.offline { background: #f8d7da; color: #721c24; } .battery-indicator { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: bold; margin: 5px 0; } .battery-high { background: #d4edda; color: #155724; } .battery-medium { background: #fff3cd; color: #856404; } .battery-low { background: #f8d7da; color: #721c24; } .health-alert { animation: slideIn 0.3s ease-out; margin-bottom: 15px; } @keyframes slideIn { from { transform: translateY(-20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } } .bluetooth-advertisement { position: fixed; bottom: 20px; right: 20px; background: white; border-radius: 8px; padding: 15px; box-shadow: 0 4px 12px rgba(0,0,0,0.2); max-width: 300px; z-index: 1000; animation: fadeIn 0.5s; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .health-metrics-chart { background: white; border-radius: 8px; padding: 20px; margin-top: 20px; } .qr-code-container { text-align: center; padding: 20px; background: white; border-radius: 8px; margin-top: 20px; } .qr-code-container img { max-width: 200px; height: auto; } .control-panel { background: white; border-radius: 8px; padding: 20px; margin-top: 20px; } .btn-beacon { background: linear-gradient(45deg, #667eea, #764ba2); color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; } .btn-beacon:hover { background: linear-gradient(45deg, #764ba2, #667eea); } /* 响应式设计 */ @media (max-width: 768px) { .device-grid { grid-template-columns: 1fr; } .bluetooth-advertisement { left: 10px; right: 10px; bottom: 10px; max-width: none; } } /* 加载动画 */ .loading { display: inline-block; width: 20px; height: 20px; border: 3px solid #f3f3f3; border-top: 3px solid #3498db; border-radius: 50%; animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } EOF # 9. 创建API文档文件 cat > $ {EXTENSION_NAME} /API_DOCUMENTATION.md << 'EOF' # Smart Health Plugin API 文档 ## 概述 本插件提供RESTful API接口,用于管理蓝牙设备、收集健康数据、生成二维码和推送广告。 ## 基础信息 - 基础URL: `/index.php?option=com_ajax&plugin=smarthealth` - 请求方式: GET/POST/PUT/DELETE - 响应格式: JSON ## 认证方式 1. API Key认证 2. JWT Token认证(高级版) ## API端点 ### 1. 设备管理 #### 获取设备列表
GET /?option=com_ajax&plugin=smarthealth&action=get_devices
响应:
```json
{
"success": true,
"devices": [
{
"id": 1,
"device_id": "device_001",
"device_name": "智能手环1",
"device_type": "wearable",
"status": 1,
"battery_level": 85,
"last_seen": "2024-01-15 10:30:00"
}
]
}
注册新设备
POST /?option=com_ajax&plugin=smarthealth&action=register_device
请求体:
{
"device_id": "new_device_001",
"device_name": "新设备",
"device_type": "wearable",
"mac_address": "00:11:22:33:44:55",
"bluetooth_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
2. 健康数据
上传健康数据
POST /?option=com_ajax&plugin=smarthealth&action=upload_health_data
请求体:
{
"device_id": "device_001",
"heart_rate": 72,
"blood_pressure": "120/80",
"body_temperature": 36.5,
"blood_oxygen": 98.5,
"stress_level": 3,
"emotion_state": "calm",
"latitude": 31.2304,
"longitude": 121.4737
}
获取健康数据历史
GET /?option=com_ajax&plugin=smarthealth&action=get_health_history&user_id=1&days=7
3. 二维码服务
生成二维码
GET /?option=com_ajax&plugin=smarthealth&action=get_qr_code&data=要编码的文本
批量生成二维码
POST /?option=com_ajax&plugin=smarthealth&action=generate_qr_batch
请求体:
{
"items": [
{"data": "商品1", "size": 300},
{"data": "商品2", "size": 300}
]
}
4. 广告管理
获取蓝牙广告
GET /?option=com_ajax&plugin=smarthealth&action=get_advertisement&device_id=device_001
记录广告互动
POST /?option=com_ajax&plugin=smarthealth&action/log_ad_interaction
请求体:
{
"ad_id": 1,
"device_id": "device_001",
"interaction_type": "click",
"latitude": 31.2304,
"longitude": 121.4737
}
5. 实时通信
WebSocket连接
ws://your-domain.com/ws/smarthealth
消息格式:
{
"type": "device_update|health_alert|advertisement",
"payload": {}
}
错误代码
| 代码 | 说明 |
|---|---|
| 200 | 成功 |
| 400 | 请求参数错误 |
| 401 | 未授权 |
| 403 | 禁止访问 |
| 404 | 资源不存在 |
| 500 | 服务器内部错误 |
使用示例
JavaScript示例
// 获取设备数据
async function getDevices() {
const response = await fetch(
'/index.php?option=com_ajax&plugin=smarthealth&action=get_devices'
);
const data = await response.json();
return data.devices;
}
// 上传健康数据
async function uploadHealthData(data) {
const response = await fetch(
'/index.php?option=com_ajax&plugin=smarthealth&action=upload_health_data',
{
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}
);
return await response.json();
}
Python示例
import requests
api_url = "https://your-domain.com/index.php"
params = {
"option": "com_ajax",
"plugin": "smarthealth",
"action": "get_devices"
}
response = requests.get(api_url, params=params)
devices = response.json()["devices"]
安全建议
-
使用HTTPS
-
定期更换API Key
-
限制请求频率
-
验证输入数据
-
记录API访问日志
# 10. 创建README文件
cat > $
{EXTENSION_NAME}
/README.md << 'EOF'
# Joomla Smart Health Plugin
## 功能概述
这是一个综合性的Joomla系统插件,提供以下功能:
### 核心功能
1. **蓝牙设备管理**
- 设备注册和配对
- 实时状态监控
- 电池电量监控
- 信号强度检测
2. **健康数据收集**
- 心率监测
- 血压测量
- 血氧饱和度
- 体温测量
- 情绪状态识别
- 定位信息跟踪
3. **广告与推广**
- 蓝牙Beacon广告
- 二维码生成
- 现场讲解内容推送
- 商品介绍推送
4. **智能分析**
- 健康趋势分析
- 异常检测与警报
- 用户行为分析
- 情绪状态分析
## 系统要求
- Joomla 5.0+
- PHP 8.0+
- MySQL 8.0+
- Apache/Nginx with WebSocket support
- SSL证书(推荐)
## 安装步骤
### 1. 环境准备
```bash
# 安装PHP扩展
sudo apt-get install php8.4-bcmath php8.4-json php8.4-mbstring
sudo apt-get install php8.4-xml php8.4-curl
# 启用Apache模块
sudo a2enmod headers
sudo a2enmod rewrite
sudo a2enmod proxy
sudo a2enmod proxy_wstunnel
2. Joomla配置
-
确保Joomla的调试模式已关闭
-
启用SEF URLs
-
设置正确的时区
3. 插件安装
-
将插件文件打包为ZIP
-
通过Joomla后台安装
-
启用插件:系统 → 插件 → 搜索"Smart Health"
-
配置插件参数
4. 数据库配置
插件安装时会自动创建所需的数据表。
配置说明
基础配置
-
启用蓝牙:控制蓝牙功能开关
-
广告类型:选择蓝牙广告协议
-
API密钥:设备通信的安全密钥
-
默认设备:测试用的设备ID
高级配置
-
健康监测:启用健康数据收集
-
心率阈值:设置心率警报阈值
-
血压阈值:设置血压警报阈值
-
数据保留:设置数据保存天数
使用方法
1. 设备连接
-
打开设备蓝牙
-
在插件后台添加设备
-
设备会自动连接并传输数据
2. 健康监测
-
用户佩戴设备
-
系统自动收集数据
-
查看健康仪表板
-
接收异常警报
3. 广告推送
-
创建广告内容
-
设置推送范围
-
选择目标设备
-
监控广告效果
4. 二维码生成
-
输入商品信息
-
生成二维码
-
打印或显示二维码
-
扫描统计
API使用
设备API
# 设备注册
curl -X POST https://your-site.com/index.php \
-d "option=com_ajax&plugin=smarthealth&action=register_device" \
-d "device_id=DEV001&device_name=SmartWatch"
数据API
# 上传健康数据
curl -X POST https://your-site.com/index.php \
-H "Content-Type: application/json" \
-d '{
"device_id": "DEV001",
"heart_rate": 75,
"blood_pressure": "120/80"
}'
故障排除
常见问题
-
设备无法连接
-
检查蓝牙是否启用
-
验证设备ID是否正确
-
检查API密钥
-
-
数据不显示
-
检查数据库连接
-
验证数据格式
-
检查用户权限
-
-
二维码无法生成
-
检查网络连接
-
验证输入数据
-
检查GD库是否安装
-
日志查看
日志位置:administrator/logs/plg_system_smarthealth.log
安全建议
-
定期更新:及时更新插件版本
-
权限控制:严格管理用户权限
-
数据加密:敏感数据加密存储
-
访问日志:记录所有API访问
-
备份策略:定期备份健康数据
技术支持
-
文档:查看API_DOCUMENTATION.md
-
问题:提交到GitHub Issues
-
邮箱:
该邮件地址已受到反垃圾邮件插件保护。要显示它需要在浏览器中启用 JavaScript。
版本历史
v1.0.0(2024-01-15)
-
初始版本发布
-
基础设备管理
-
健康数据收集
-
二维码生成
-
蓝牙广告功能
许可证
GNU General Public License v2.0
# 11. 创建空索引文件
cat > $
{EXTENSION_NAME}
/index.html << 'EOF'
<!DOCTYPE html>
<html>
<head>
<title>Directory Access Denied</title>
</head>
<body>
<h1>Access Denied</h1>
<p>Directory listing is not allowed.</p>
</body>
</html>
EOF
# 12. 创建配置文件
cat > $
{EXTENSION_NAME}
/config.example.php << 'EOF'
<?php
/**
* 智能健康插件配置文件示例
* 复制此文件为 config.php 并修改配置
*/
defined('_JEXEC') or die;
// 数据库配置
define('SMARTHEALTH_DB_PREFIX', 'jos_');
// API配置
define('SMARTHEALTH_API_KEY', 'your-secure-api-key-here');
define('SMARTHEALTH_API_SECRET', 'your-api-secret-here');
define('SMARTHEALTH_API_RATE_LIMIT', 100); // 每分钟请求限制
// 蓝牙配置
define('SMARTHEALTH_BLUETOOTH_ENABLED', true);
define('SMARTHEALTH_BEACON_UUID', 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx');
define('SMARTHEALTH_BEACON_MAJOR', 1);
define('SMARTHEALTH_BEACON_MINOR', 1);
// 健康监测配置
define('SMARTHEALTH_HEART_RATE_MAX', 120);
define('SMARTHEALTH_HEART_RATE_MIN', 60);
define('SMARTHEALTH_BP_SYSTOLIC_MAX', 140);
define('SMARTHEALTH_BP_DIASTOLIC_MAX', 90);
define('SMARTHEALTH_TEMP_MAX', 37.5);
define('SMARTHEALTH_TEMP_MIN', 36.0);
// 二维码配置
define('SMARTHEALTH_QR_SIZE', 300);
define('SMARTHEALTH_QR_LEVEL', 'H'); // L, M, Q, H
define('SMARTHEALTH_QR_MARGIN', 4);
// 广告配置
define('SMARTHEALTH_AD_TIMEOUT', 30); // 广告显示时间(秒)
define('SMARTHEALTH_AD_INTERVAL', 300); // 广告间隔时间(秒)
// 数据保留配置
define('SMARTHEALTH_DATA_RETENTION_DAYS', 365); // 数据保留天数
// WebSocket配置
define('SMARTHEALTH_WS_HOST', 'localhost');
define('SMARTHEALTH_WS_PORT', 8080);
define('SMARTHEALTH_WS_PATH', '/smarthealth');
// 邮件通知配置
define('SMARTHEALTH_EMAIL_ALERTS', true);
define('SMARTHEALTH_EMAIL_FROM', 'noreply@yourdomain.com');
define('SMARTHEALTH_EMAIL_ADMIN', 'admin@yourdomain.com');
// 调试配置
define('SMARTHEALTH_DEBUG', false);
define('SMARTHEALTH_LOG_LEVEL', 'ERROR'); // DEBUG, INFO, WARNING, ERROR
// 地理位置配置
define('SMARTHEALTH_GEO_API_KEY', 'your-google-maps-api-key');
define('SMARTHEALTH_GEO_CACHE_TIME', 3600); // 地理位置缓存时间(秒)
// 情绪分析配置
define('SMARTHEALTH_EMOTION_API_KEY', 'your-emotion-api-key');
define('SMARTHEALTH_EMOTION_THRESHOLD', 0.7);
/**
* 获取配置值
*/
function getSmartHealthConfig($key, $default = null)
{
static $config = null;
if ($config === null) {
// 从数据库或文件中加载配置
$config = [
'api_key' => SMARTHEALTH_API_KEY,
'debug' => SMARTHEALTH_DEBUG,
// 其他配置...
];
}
return $config[$key] ?? $default;
}
/**
* 验证API密钥
*/
function validateApiKey($apiKey)
{
return hash_equals(SMARTHEALTH_API_KEY, $apiKey);
}
/**
* 记录日志
*/
function smarthealthLog($message, $level = 'INFO')
{
if (SMARTHEALTH_DEBUG || $level === 'ERROR') {
$logFile = JPATH_ADMINISTRATOR . '/logs/plg_system_smarthealth.log';
$timestamp = date('Y-m-d H:i:s');
$logMessage = "[$timestamp] [$level] $message\n";
file_put_contents($logFile, $logMessage, FILE_APPEND);
}
}
EOF
# 13. 创建包文件
echo "正在打包扩展..."
cd $
{EXTENSION_NAME}
zip -r ../$
{EXTENSION_NAME}
_v$
{VERSION}
.zip ./*
cd ..
echo "========================================"
echo "扩展生成完成!"
echo "生成的文件:$
{EXTENSION_NAME}
_v$
{VERSION}
.zip"
echo "========================================"
echo ""
echo "安装步骤:"
echo "1. 登录Joomla后台"
echo "2. 进入: 系统 → 安装 → 扩展"
echo "3. 上传ZIP文件安装"
echo "4. 启用插件: 系统 → 插件 → Smart Health"
echo "5. 配置插件参数"
echo ""
echo "API端点: /index.php?option=com_ajax&plugin=smarthealth"
echo "文档: 查看生成的 API_DOCUMENTATION.md"
echo "========================================"
# 设置执行权限
chmod +x generate_extension.sh
2. 安装和使用说明
2.1 运行脚本生成扩展
# 给脚本执行权限
chmod +x generate_extension.sh
# 运行脚本生成扩展
./generate_extension.sh
2.2 安装到Joomla
-
登录Joomla后台
-
进入: 系统 → 安装 → 扩展
-
上传生成的ZIP文件
-
启用插件: 系统 → 插件 → 找到"Smart Health Manager"
-
配置插件参数
2.3 主要功能配置
蓝牙设备配置
// 在插件参数中设置
蓝牙UUID: 设备的唯一标识
发射功率: 控制信号范围
广告间隔: 广播频率
健康监测配置
// 阈值设置
心率警报: 120 bpm
血压警报: 140/90 mmHg
体温警报: 37.5°C
API接口调用
// JavaScript调用示例
const apiUrl = '/index.php?option=com_ajax&plugin=smarthealth';
// 获取设备数据
fetch(`$
{apiUrl}
&action=get_device_data`)
.then(response => response.json())
.then(data => console.log(data));
// 生成二维码
fetch(`$
{apiUrl}
&action=get_qr_code&data=商品信息`)
.then(response => response.json())
.then(data => {
document.getElementById('qr-code').src = data.qr_url;
});
2.4 数据库表说明
| 表名 | 说明 |
|---|---|
| #__smarthealth_devices | 设备信息表 |
| #__smarthealth_health_data | 健康数据表 |
| #__smarthealth_device_logs | 设备日志表 |
| #__smarthealth_advertisements | 广告内容表 |
| #__smarthealth_user_sessions | 用户会话表 |
3. API接口文档
主要API端点
-
设备管理
-
GET /?action=get_devices-获取设备列表 -
POST /?action=register_device-注册新设备
-
-
健康数据
-
POST /?action=upload_health_data-上传健康数据 -
GET /?action=get_health_history-获取历史数据
-
-
二维码服务
-
GET /?action=get_qr_code&data=xxx-生成二维码 -
POST /?action=generate_qr_batch-批量生成
-
-
广告管理
-
GET /?action=get_advertisement-获取广告 -
POST /?action=log_ad_interaction-记录互动
-
4. 安全建议
-
启用HTTPS:所有API通信使用HTTPS
-
API密钥验证:每个请求都需要验证API密钥
-
数据加密:敏感健康数据加密存储
-
访问控制:基于角色的访问控制
-
输入验证:所有输入数据都要验证
-
日志记录:记录所有API访问和设备交互
5. 扩展开发建议
如需进一步开发,建议:
-
添加WebSocket支持:用于实时数据推送
-
集成机器学习:用于情绪和健康分析
-
添加移动应用:配套的React Native应用
-
云同步:与云存储服务集成
-
数据分析仪表板:更丰富的数据可视化
这个扩展包已包含完整的功能框架,根据具体需求进行修改和扩展。脚本生成的所有文件都包含详细的注释,便于理解和定制。