feat: implement LAN multi-device synchronization and dedicated sync server
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
*.db
|
||||
.DS_Store
|
||||
.atom/
|
||||
.build/
|
||||
|
||||
@@ -9,6 +9,8 @@ import 'session_screen.dart';
|
||||
import 'history_screen.dart';
|
||||
import 'settings_screen.dart';
|
||||
import 'plan_config_screen.dart';
|
||||
import 'lan_sync_screen.dart';
|
||||
import '../services/sync_service.dart';
|
||||
|
||||
class HomeScreen extends StatefulWidget {
|
||||
final StorageService storageService;
|
||||
@@ -30,6 +32,10 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadData();
|
||||
// 局域网静默尝试同步拉取最新状态
|
||||
SyncService(widget.storageService).syncSilently().then((_) {
|
||||
if (mounted) _loadData();
|
||||
});
|
||||
}
|
||||
|
||||
void _loadData() {
|
||||
@@ -73,6 +79,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
);
|
||||
if (result == true) {
|
||||
_loadData();
|
||||
SyncService(widget.storageService).syncSilently();
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
@@ -133,6 +140,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
await widget.storageService.deductSessionDoses(deductions);
|
||||
await widget.storageService.addRecord(record);
|
||||
_loadData();
|
||||
SyncService(widget.storageService).syncSilently();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +177,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
await widget.storageService.deductSessionDoses({canister.id: 1});
|
||||
await widget.storageService.addRecord(record);
|
||||
_loadData();
|
||||
SyncService(widget.storageService).syncSilently();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,6 +200,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
if (confirmed == true) {
|
||||
await widget.storageService.resetCanisterDoses(canister.id, canister.totalDoses);
|
||||
_loadData();
|
||||
SyncService(widget.storageService).syncSilently();
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('已成功将 ${canister.name.split(" ")[0]} 重置为满瓶!')),
|
||||
@@ -232,7 +242,19 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.tune, color: Color(0xFF2563EB)),
|
||||
icon: const Icon(Icons.sync, color: Color(0xFF2563EB)),
|
||||
tooltip: '局域网同步',
|
||||
onPressed: () async {
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => LanSyncScreen(storageService: widget.storageService),
|
||||
),
|
||||
);
|
||||
_loadData();
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.tune, color: Color(0xFF475569)),
|
||||
tooltip: '配置用药方案',
|
||||
onPressed: _openPlanConfig,
|
||||
),
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../services/sync_service.dart';
|
||||
|
||||
class LanSyncScreen extends StatefulWidget {
|
||||
final StorageService storageService;
|
||||
|
||||
const LanSyncScreen({super.key, required this.storageService});
|
||||
|
||||
@override
|
||||
State<LanSyncScreen> createState() => _LanSyncScreenState();
|
||||
}
|
||||
|
||||
class _LanSyncScreenState extends State<LanSyncScreen> {
|
||||
late TextEditingController _urlController;
|
||||
late TextEditingController _deviceNameController;
|
||||
|
||||
bool _isTesting = false;
|
||||
bool _autoSync = true;
|
||||
String? _statusMessage;
|
||||
bool? _isOnline;
|
||||
int? _latencyMs;
|
||||
DateTime? _lastSyncTime;
|
||||
|
||||
late SyncService _syncService;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_syncService = SyncService(widget.storageService);
|
||||
_urlController = TextEditingController();
|
||||
_deviceNameController = TextEditingController();
|
||||
_loadConfig();
|
||||
}
|
||||
|
||||
Future<void> _loadConfig() async {
|
||||
final url = await SyncService.getServerUrl();
|
||||
final name = await SyncService.getDeviceName();
|
||||
final auto = await SyncService.getAutoSyncEnabled();
|
||||
final lastTime = await SyncService.getLastSyncTime();
|
||||
|
||||
setState(() {
|
||||
_urlController.text = url;
|
||||
_deviceNameController.text = name;
|
||||
_autoSync = auto;
|
||||
_lastSyncTime = lastTime;
|
||||
});
|
||||
|
||||
_testConnection(autoPingOnly: true);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_urlController.dispose();
|
||||
_deviceNameController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _saveConfig() async {
|
||||
await SyncService.setServerUrl(_urlController.text);
|
||||
await SyncService.setDeviceName(_deviceNameController.text);
|
||||
await SyncService.setAutoSyncEnabled(_autoSync);
|
||||
}
|
||||
|
||||
Future<void> _testConnection({bool autoPingOnly = false}) async {
|
||||
final url = _urlController.text.trim();
|
||||
if (url.isEmpty) return;
|
||||
|
||||
setState(() {
|
||||
_isTesting = true;
|
||||
_statusMessage = null;
|
||||
});
|
||||
|
||||
await _saveConfig();
|
||||
|
||||
if (autoPingOnly) {
|
||||
final latency = await SyncService.pingServer(url);
|
||||
setState(() {
|
||||
_isTesting = false;
|
||||
_isOnline = latency != null;
|
||||
_latencyMs = latency;
|
||||
if (latency != null) {
|
||||
_statusMessage = '局域网主机在线 (响应 $latency ms)';
|
||||
} else {
|
||||
_statusMessage = '当前未连通局域网服务器 (回家连 Wi-Fi 即可自动连上)';
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 执行完整同步
|
||||
final result = await _syncService.performSync(customUrl: url);
|
||||
final lastTime = await SyncService.getLastSyncTime();
|
||||
|
||||
setState(() {
|
||||
_isTesting = false;
|
||||
_isOnline = result.success;
|
||||
_latencyMs = result.latencyMs;
|
||||
_statusMessage = result.message;
|
||||
_lastSyncTime = lastTime;
|
||||
});
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(result.message),
|
||||
backgroundColor: result.success ? const Color(0xFF10B981) : const Color(0xFFEF4444),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final lastSyncStr = _lastSyncTime != null
|
||||
? DateFormat('yyyy-MM-dd HH:mm:ss').format(_lastSyncTime!)
|
||||
: '尚未同步';
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFFF8FAFC),
|
||||
appBar: AppBar(
|
||||
title: const Text('局域网多设备同步', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
|
||||
backgroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
foregroundColor: const Color(0xFF0F172A),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
// 状态卡片
|
||||
Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
border: Border.all(
|
||||
color: _isOnline == true ? const Color(0xFF86EFAC) : const Color(0xFFCBD5E1),
|
||||
width: _isOnline == true ? 1.5 : 1,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(color: Colors.black.withValues(alpha: 0.02), blurRadius: 8, offset: const Offset(0, 2)),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 44,
|
||||
height: 44,
|
||||
decoration: BoxDecoration(
|
||||
color: _isOnline == true ? const Color(0xFFECFDF5) : const Color(0xFFF1F5F9),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
_isOnline == true ? Icons.cloud_done : Icons.cloud_off,
|
||||
color: _isOnline == true ? const Color(0xFF10B981) : Colors.grey,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
_isOnline == true
|
||||
? (_latencyMs != null ? '局域网主机已连接 (延迟 ${_latencyMs}ms)' : '局域网主机已连接')
|
||||
: '局域网离线 / 待连接',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 15,
|
||||
color: _isOnline == true ? const Color(0xFF065F46) : const Color(0xFF334155),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
_statusMessage ?? '正在检测局域网服务器连通性...',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: _isOnline == true ? const Color(0xFF059669) : Colors.grey,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text('最近成功同步:$lastSyncStr', style: const TextStyle(fontSize: 11, color: Color(0xFF94A3B8))),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 配置表单
|
||||
const Text('局域网服务器连接配置', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: Colors.grey)),
|
||||
const SizedBox(height: 10),
|
||||
|
||||
Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
border: Border.all(color: const Color(0xFFE2E8F0)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text('局域网同步服务器地址 (IP + 端口)', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _urlController,
|
||||
decoration: InputDecoration(
|
||||
hintText: '例如: http://192.168.21.200:8090',
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
prefixIcon: const Icon(Icons.dns, size: 20, color: Color(0xFF2563EB)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// 快捷预设按钮
|
||||
Row(
|
||||
children: [
|
||||
ActionChip(
|
||||
label: const Text('填入 192.168.21.200:8090', style: TextStyle(fontSize: 11)),
|
||||
onPressed: () => setState(() => _urlController.text = 'http://192.168.21.200:8090'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ActionChip(
|
||||
label: const Text('填入 localhost:8090', style: TextStyle(fontSize: 11)),
|
||||
onPressed: () => setState(() => _urlController.text = 'http://localhost:8090'),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: 18),
|
||||
|
||||
const Text('本机设备标识名称 (用于全家记录署名)', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _deviceNameController,
|
||||
decoration: InputDecoration(
|
||||
hintText: '例如: 妈妈的手机 / 家中 iPad / 爷爷手机',
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
prefixIcon: const Icon(Icons.devices, size: 20, color: Color(0xFF2563EB)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// 自动同步开关
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFE2E8F0)),
|
||||
),
|
||||
child: SwitchListTile(
|
||||
title: const Text('打卡后自动静默同步', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
|
||||
subtitle: const Text('只要连着家庭 Wi-Fi,每次吸入完成自动同步到所有设备', style: TextStyle(fontSize: 12)),
|
||||
value: _autoSync,
|
||||
activeTrackColor: const Color(0xFF2563EB),
|
||||
onChanged: (val) {
|
||||
setState(() => _autoSync = val);
|
||||
_saveConfig();
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 立即同步按钮
|
||||
ElevatedButton.icon(
|
||||
onPressed: _isTesting ? null : () => _testConnection(autoPingOnly: false),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF2563EB),
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
),
|
||||
icon: _isTesting
|
||||
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
|
||||
: const Icon(Icons.sync),
|
||||
label: Text(_isTesting ? '正在同步数据...' : '测试连接并立即同步', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15)),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 架构原理说明
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFEFF6FF),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: const Color(0xFFBFDBFE)),
|
||||
),
|
||||
child: const Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.shield_outlined, color: Color(0xFF2563EB), size: 18),
|
||||
SizedBox(width: 8),
|
||||
Text('家庭私有化保障说明', style: TextStyle(color: Color(0xFF1E3A8A), fontWeight: FontWeight.bold, fontSize: 13)),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
'• 数据完全保存在您的私有服务器 (192.168.21.200),不上任何公有云,隐私绝对安全。\n'
|
||||
'• 离开家时:手机照常在本地打卡计时,不受断网影响。\n'
|
||||
'• 回家连上 Wi-Fi:系统无感将离线记录合并至服务器,并校准辅舒酮 60 喷剩余数。',
|
||||
style: TextStyle(fontSize: 12, color: Color(0xFF1E40AF), height: 1.5),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import '../models/app_settings.dart';
|
||||
import '../models/dose_record.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../services/tts_service.dart';
|
||||
import '../services/sync_service.dart';
|
||||
|
||||
enum StepType {
|
||||
inhale, // 正在吸入某药某喷
|
||||
@@ -242,6 +243,7 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
|
||||
await widget.storageService.deductSessionDoses(deductions);
|
||||
await widget.storageService.addRecord(record);
|
||||
SyncService(widget.storageService).syncSilently();
|
||||
|
||||
if (mounted) {
|
||||
Navigator.of(context).pop(true);
|
||||
|
||||
@@ -3,6 +3,7 @@ import '../models/app_settings.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../services/tts_service.dart';
|
||||
import 'plan_config_screen.dart';
|
||||
import 'lan_sync_screen.dart';
|
||||
|
||||
class SettingsScreen extends StatefulWidget {
|
||||
final StorageService storageService;
|
||||
@@ -137,6 +138,33 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// 局域网多设备同步入口卡
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFBFDBFE)),
|
||||
boxShadow: [
|
||||
BoxShadow(color: Colors.black.withValues(alpha: 0.02), blurRadius: 6, offset: const Offset(0, 2)),
|
||||
],
|
||||
),
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.sync, color: Color(0xFF2563EB), size: 26),
|
||||
title: const Text('局域网多设备同步', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
|
||||
subtitle: const Text('家庭私有化同步 • 离开家离线打卡,回家自动合并', style: TextStyle(fontSize: 11, color: Colors.grey)),
|
||||
trailing: const Icon(Icons.chevron_right, color: Colors.grey),
|
||||
onTap: () async {
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => LanSyncScreen(storageService: widget.storageService),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 模块 2:提醒偏好
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import '../models/canister.dart';
|
||||
import '../models/dose_record.dart';
|
||||
import 'storage_service.dart';
|
||||
|
||||
class SyncResult {
|
||||
final bool success;
|
||||
final String message;
|
||||
final int? latencyMs;
|
||||
final int newRecordsCount;
|
||||
|
||||
SyncResult({
|
||||
required this.success,
|
||||
required this.message,
|
||||
this.latencyMs,
|
||||
this.newRecordsCount = 0,
|
||||
});
|
||||
}
|
||||
|
||||
class SyncService {
|
||||
static const String _keyServerUrl = 'aerotrack_lan_server_url';
|
||||
static const String _keyDeviceName = 'aerotrack_device_name';
|
||||
static const String _keyDeviceId = 'aerotrack_device_id';
|
||||
static const String _keyLastSync = 'aerotrack_last_sync_time';
|
||||
static const String _keyAutoSync = 'aerotrack_auto_sync';
|
||||
|
||||
// 默认局域网地址推荐(契合私有服务器 192.168.21.200)
|
||||
static const String defaultServerUrl = 'http://192.168.21.200:8090';
|
||||
|
||||
final StorageService storageService;
|
||||
|
||||
SyncService(this.storageService);
|
||||
|
||||
static Future<String> getDeviceId() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
String? id = prefs.getString(_keyDeviceId);
|
||||
if (id == null) {
|
||||
id = const Uuid().v4();
|
||||
await prefs.setString(_keyDeviceId, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
static Future<String> getServerUrl() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyServerUrl) ?? defaultServerUrl;
|
||||
}
|
||||
|
||||
static Future<void> setServerUrl(String url) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyServerUrl, url.trim());
|
||||
}
|
||||
|
||||
static Future<String> getDeviceName() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyDeviceName) ?? '家人手机';
|
||||
}
|
||||
|
||||
static Future<void> setDeviceName(String name) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyDeviceName, name.trim());
|
||||
}
|
||||
|
||||
static Future<bool> getAutoSyncEnabled() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_keyAutoSync) ?? true;
|
||||
}
|
||||
|
||||
static Future<void> setAutoSyncEnabled(bool enabled) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_keyAutoSync, enabled);
|
||||
}
|
||||
|
||||
static Future<DateTime?> getLastSyncTime() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final str = prefs.getString(_keyLastSync);
|
||||
return str != null ? DateTime.tryParse(str) : null;
|
||||
}
|
||||
|
||||
/// 测试与局域网服务器连通性
|
||||
static Future<int?> pingServer(String serverUrl) async {
|
||||
try {
|
||||
final cleanUrl = serverUrl.trim().replaceAll(RegExp(r'/+$'), '');
|
||||
final uri = Uri.parse('$cleanUrl/api/v1/ping');
|
||||
final stopwatch = Stopwatch()..start();
|
||||
|
||||
final res = await http.get(uri).timeout(const Duration(seconds: 3));
|
||||
stopwatch.stop();
|
||||
|
||||
if (res.statusCode == 200) {
|
||||
return stopwatch.elapsedMilliseconds;
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('Ping server error: $e');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 执行完整双向增量同步
|
||||
Future<SyncResult> performSync({String? customUrl}) async {
|
||||
final baseUrl = (customUrl ?? await getServerUrl()).replaceAll(RegExp(r'/+$'), '');
|
||||
final deviceName = await getDeviceName();
|
||||
final deviceId = await getDeviceId();
|
||||
|
||||
final pingMs = await pingServer(baseUrl);
|
||||
if (pingMs == null) {
|
||||
return SyncResult(
|
||||
success: false,
|
||||
message: '无法连接局域网服务器 ($baseUrl),请检查 Wi-Fi 或 IP 地址',
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
final localRecords = storageService.getRecords();
|
||||
final localCanisters = storageService.getCanisters();
|
||||
final lastSync = await getLastSyncTime();
|
||||
|
||||
final body = json.encode({
|
||||
'device_name': deviceName,
|
||||
'device_id': deviceId,
|
||||
'last_sync_time': lastSync?.toIso8601String(),
|
||||
'records': localRecords.map((r) => r.toMap()).toList(),
|
||||
'canisters': localCanisters.map((c) => c.toMap()).toList(),
|
||||
});
|
||||
|
||||
final syncUri = Uri.parse('$baseUrl/api/v1/sync');
|
||||
final res = await http.post(
|
||||
syncUri,
|
||||
headers: {'Content-Type': 'application/json; charset=utf-8'},
|
||||
body: body,
|
||||
).timeout(const Duration(seconds: 6));
|
||||
|
||||
if (res.statusCode == 200) {
|
||||
final data = json.decode(utf8.decode(res.bodyBytes)) as Map<String, dynamic>;
|
||||
|
||||
// 1. 合并远端记录到本地
|
||||
final remoteRecordsRaw = data['records'] as List<dynamic>? ?? [];
|
||||
final remoteRecords = remoteRecordsRaw
|
||||
.map((item) => DoseRecord.fromMap(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
final existingIds = localRecords.map((r) => r.id).toSet();
|
||||
int newCount = 0;
|
||||
|
||||
for (var r in remoteRecords) {
|
||||
if (!existingIds.contains(r.id)) {
|
||||
await storageService.addRecord(r);
|
||||
newCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 合并远端药瓶状态到本地
|
||||
final remoteCanistersRaw = data['canisters'] as List<dynamic>? ?? [];
|
||||
final remoteCanisters = remoteCanistersRaw
|
||||
.map((item) => Canister.fromMap(item as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
if (remoteCanisters.isNotEmpty) {
|
||||
await storageService.saveCanisters(remoteCanisters);
|
||||
}
|
||||
|
||||
// 3. 更新同步时间
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyLastSync, DateTime.now().toIso8601String());
|
||||
|
||||
return SyncResult(
|
||||
success: true,
|
||||
message: '同步成功!拉取到 $newCount 条新记录',
|
||||
latencyMs: pingMs,
|
||||
newRecordsCount: newCount,
|
||||
);
|
||||
} else {
|
||||
return SyncResult(
|
||||
success: false,
|
||||
message: '服务器返回错误 HTTP ${res.statusCode}',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
return SyncResult(
|
||||
success: false,
|
||||
message: '同步中断: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 默默在后台尝试同步(失败不弹窗干扰用户)
|
||||
Future<void> syncSilently() async {
|
||||
final enabled = await getAutoSyncEnabled();
|
||||
if (!enabled) return;
|
||||
try {
|
||||
await performSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,22 @@ packages:
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
http:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: http
|
||||
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.6.0"
|
||||
http_parser:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http_parser
|
||||
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.2"
|
||||
intl:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -341,6 +357,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.10"
|
||||
typed_data:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: typed_data
|
||||
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
uuid:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
|
||||
@@ -38,6 +38,7 @@ dependencies:
|
||||
shared_preferences: ^2.5.6
|
||||
uuid: ^4.6.0
|
||||
flutter_tts: ^4.2.5
|
||||
http: ^1.6.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
Executable
+394
@@ -0,0 +1,394 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AeroTrack LAN Sync Server (AeroTrack 局域网多设备同步服务端)
|
||||
- 零第三方依赖,纯 Python 标准库 (Python 3.8+)
|
||||
- 自动管理 SQLite 数据库
|
||||
- 支持高并发多线程与完整 CORS
|
||||
- 提供局域网设备数据同步接口与 Web 状态看板
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
import sqlite3
|
||||
import datetime
|
||||
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||
from socketserver import ThreadingMixIn
|
||||
|
||||
DB_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'aerotrack.db')
|
||||
|
||||
def get_db():
|
||||
conn = sqlite3.connect(DB_FILE, check_same_thread=False)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
def init_db():
|
||||
conn = get_db()
|
||||
with conn:
|
||||
# 药瓶状态表
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS canisters (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
total_doses INTEGER NOT NULL,
|
||||
remaining_doses INTEGER NOT NULL,
|
||||
opened_at TEXT,
|
||||
is_enabled INTEGER DEFAULT 1,
|
||||
puffs_per_session INTEGER DEFAULT 2,
|
||||
inhalation_seconds INTEGER DEFAULT 15,
|
||||
is_steroid INTEGER DEFAULT 1,
|
||||
sort_order INTEGER DEFAULT 1,
|
||||
note TEXT,
|
||||
updated_at TEXT
|
||||
)
|
||||
''')
|
||||
|
||||
# 吸入流水日志表 (UUID 主键,天然支持并发防重)
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS dose_records (
|
||||
id TEXT PRIMARY KEY,
|
||||
start_time TEXT NOT NULL,
|
||||
end_time TEXT NOT NULL,
|
||||
flixotide_puffs INTEGER DEFAULT 0,
|
||||
ventolin_puffs INTEGER DEFAULT 0,
|
||||
rinsed_mouth INTEGER DEFAULT 1,
|
||||
washed_face INTEGER DEFAULT 1,
|
||||
is_prime INTEGER DEFAULT 0,
|
||||
note TEXT,
|
||||
operator_name TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
# 局域网同步设备列表
|
||||
conn.execute('''
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id TEXT PRIMARY KEY,
|
||||
device_name TEXT NOT NULL,
|
||||
last_seen TEXT NOT NULL,
|
||||
ip_address TEXT
|
||||
)
|
||||
''')
|
||||
conn.close()
|
||||
|
||||
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
|
||||
daemon_threads = True
|
||||
|
||||
class SyncHandler(BaseHTTPRequestHandler):
|
||||
def _send_cors_headers(self):
|
||||
self.send_header('Access-Control-Allow-Origin', '*')
|
||||
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
||||
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With')
|
||||
|
||||
def do_OPTIONS(self):
|
||||
self.send_response(200)
|
||||
self._send_cors_headers()
|
||||
self.end_headers()
|
||||
|
||||
def _send_json(self, status_code, data):
|
||||
payload = json.dumps(data, ensure_ascii=False).encode('utf-8')
|
||||
self.send_response(status_code)
|
||||
self._send_cors_headers()
|
||||
self.send_header('Content-Type', 'application/json; charset=utf-8')
|
||||
self.send_header('Content-Length', str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def do_GET(self):
|
||||
# 1. Ping / 延迟测试
|
||||
if self.path == '/api/v1/ping':
|
||||
self._send_json(200, {
|
||||
'status': 'ok',
|
||||
'service': 'AeroTrack LAN Sync Server',
|
||||
'timestamp': datetime.datetime.utcnow().isoformat() + 'Z'
|
||||
})
|
||||
return
|
||||
|
||||
# 2. 状态查询
|
||||
if self.path == '/api/v1/sync/status':
|
||||
conn = get_db()
|
||||
total_records = conn.execute('SELECT COUNT(*) as c FROM dose_records').fetchone()['c']
|
||||
devices = [dict(r) for r in conn.execute('SELECT * FROM devices ORDER BY last_seen DESC').fetchall()]
|
||||
canisters = [dict(r) for r in conn.execute('SELECT * FROM canisters ORDER BY sort_order ASC').fetchall()]
|
||||
conn.close()
|
||||
|
||||
self._send_json(200, {
|
||||
'status': 'online',
|
||||
'total_records': total_records,
|
||||
'devices': devices,
|
||||
'canisters': canisters,
|
||||
'server_time': datetime.datetime.utcnow().isoformat() + 'Z'
|
||||
})
|
||||
return
|
||||
|
||||
# 3. 根路径:漂亮的局域网 Web 监控面板
|
||||
if self.path == '/' or self.path == '/index.html':
|
||||
self._render_dashboard()
|
||||
return
|
||||
|
||||
self.send_error(404, "Not Found")
|
||||
|
||||
def do_POST(self):
|
||||
if self.path == '/api/v1/sync':
|
||||
content_length = int(self.headers.get('Content-Length', 0))
|
||||
body = self.rfile.read(content_length)
|
||||
try:
|
||||
payload = json.loads(body.decode('utf-8'))
|
||||
except Exception as e:
|
||||
self._send_json(400, {'error': f'Invalid JSON: {str(e)}'})
|
||||
return
|
||||
|
||||
self._handle_sync(payload)
|
||||
return
|
||||
|
||||
self.send_error(404, "Not Found")
|
||||
|
||||
def _handle_sync(self, payload):
|
||||
device_name = payload.get('device_name', '未知设备')
|
||||
device_id = payload.get('device_id', 'unknown')
|
||||
client_ip = self.client_address[0]
|
||||
now_str = datetime.datetime.utcnow().isoformat() + 'Z'
|
||||
|
||||
conn = get_db()
|
||||
with conn:
|
||||
# 记录设备心跳
|
||||
conn.execute('''
|
||||
INSERT INTO devices (device_id, device_name, last_seen, ip_address)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(device_id) DO UPDATE SET
|
||||
device_name = excluded.device_name,
|
||||
last_seen = excluded.last_seen,
|
||||
ip_address = excluded.ip_address
|
||||
''', (device_id, device_name, now_str, client_ip))
|
||||
|
||||
# 1. 接收客户端推上来的新用药记录 (以 UUID 防重幂等入库)
|
||||
incoming_records = payload.get('records', [])
|
||||
for r in incoming_records:
|
||||
rec_id = r.get('id')
|
||||
if not rec_id:
|
||||
continue
|
||||
conn.execute('''
|
||||
INSERT OR IGNORE INTO dose_records
|
||||
(id, start_time, end_time, flixotide_puffs, ventolin_puffs, rinsed_mouth, washed_face, is_prime, note, operator_name, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (
|
||||
rec_id,
|
||||
r.get('startTime', now_str),
|
||||
r.get('endTime', now_str),
|
||||
r.get('flixotidePuffs', 0),
|
||||
r.get('ventolinPuffs', 0),
|
||||
1 if r.get('rinsedMouth', True) else 0,
|
||||
1 if r.get('washedFace', True) else 0,
|
||||
1 if r.get('isPrime', False) else 0,
|
||||
r.get('note', ''),
|
||||
device_name,
|
||||
now_str
|
||||
))
|
||||
|
||||
# 2. 接收客户端同步上来的药瓶设置或更新
|
||||
incoming_canisters = payload.get('canisters', [])
|
||||
for c in incoming_canisters:
|
||||
cid = c.get('id')
|
||||
if not cid:
|
||||
continue
|
||||
conn.execute('''
|
||||
INSERT INTO canisters
|
||||
(id, name, total_doses, remaining_doses, opened_at, is_enabled, puffs_per_session, inhalation_seconds, is_steroid, sort_order, note, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
remaining_doses = excluded.remaining_doses,
|
||||
is_enabled = excluded.is_enabled,
|
||||
puffs_per_session = excluded.puffs_per_session,
|
||||
inhalation_seconds = excluded.inhalation_seconds,
|
||||
updated_at = excluded.updated_at
|
||||
''', (
|
||||
cid,
|
||||
c.get('name', ''),
|
||||
c.get('totalDoses', 60),
|
||||
c.get('remainingDoses', 60),
|
||||
c.get('openedAt', now_str),
|
||||
1 if c.get('isEnabled', True) else 0,
|
||||
c.get('puffsPerSession', 2),
|
||||
c.get('inhalationSeconds', 15),
|
||||
1 if c.get('isSteroid', True) else 0,
|
||||
c.get('sortOrder', 1),
|
||||
c.get('note', ''),
|
||||
now_str
|
||||
))
|
||||
|
||||
# 3. 汇总拉取全量最新记录并返回给客户端
|
||||
all_records = []
|
||||
for row in conn.execute('SELECT * FROM dose_records ORDER BY start_time DESC LIMIT 200'):
|
||||
all_records.append({
|
||||
'id': row['id'],
|
||||
'startTime': row['start_time'],
|
||||
'endTime': row['end_time'],
|
||||
'flixotidePuffs': row['flixotide_puffs'],
|
||||
'ventolinPuffs': row['ventolin_puffs'],
|
||||
'rinsedMouth': bool(row['rinsed_mouth']),
|
||||
'washedFace': bool(row['washed_face']),
|
||||
'isPrime': bool(row['is_prime']),
|
||||
'note': row['note'],
|
||||
'operatorName': row['operator_name']
|
||||
})
|
||||
|
||||
# 4. 汇总各药瓶当前最新信息
|
||||
all_canisters = []
|
||||
for row in conn.execute('SELECT * FROM canisters ORDER BY sort_order ASC'):
|
||||
all_canisters.append({
|
||||
'id': row['id'],
|
||||
'name': row['name'],
|
||||
'totalDoses': row['total_doses'],
|
||||
'remainingDoses': row['remaining_doses'],
|
||||
'openedAt': row['opened_at'],
|
||||
'isEnabled': bool(row['is_enabled']),
|
||||
'puffsPerSession': row['puffs_per_session'],
|
||||
'inhalationSeconds': row['inhalation_seconds'],
|
||||
'isSteroid': bool(row['is_steroid']),
|
||||
'sortOrder': row['sort_order'],
|
||||
'note': row['note']
|
||||
})
|
||||
|
||||
conn.close()
|
||||
|
||||
self._send_json(200, {
|
||||
'success': True,
|
||||
'server_time': now_str,
|
||||
'records': all_records,
|
||||
'canisters': all_canisters
|
||||
})
|
||||
|
||||
def _render_dashboard(self):
|
||||
conn = get_db()
|
||||
records = conn.execute('SELECT * FROM dose_records ORDER BY start_time DESC LIMIT 20').fetchall()
|
||||
devices = conn.execute('SELECT * FROM devices ORDER BY last_seen DESC').fetchall()
|
||||
canisters = conn.execute('SELECT * FROM canisters ORDER BY sort_order ASC').fetchall()
|
||||
total_count = conn.execute('SELECT COUNT(*) as c FROM dose_records').fetchone()['c']
|
||||
conn.close()
|
||||
|
||||
canister_list = []
|
||||
for c in canisters:
|
||||
status_badge = '<span style="color:#059669;font-weight:bold;">启用</span>' if c['is_enabled'] else '<span style="color:#94a3b8;">未启用</span>'
|
||||
canister_list.append(
|
||||
f"<tr style='border-bottom:1px solid #e2e8f0;'>"
|
||||
f"<td style='padding:10px 14px;'><strong>{c['name']}</strong></td>"
|
||||
f"<td style='padding:10px 14px;color:#2563eb;font-weight:bold;'>{c['remaining_doses']} / {c['total_doses']} 喷</td>"
|
||||
f"<td style='padding:10px 14px;'>{c['puffs_per_session']} 喷</td>"
|
||||
f"<td style='padding:10px 14px;'>{status_badge}</td>"
|
||||
f"</tr>"
|
||||
)
|
||||
canister_rows = "".join(canister_list) or "<tr><td colspan='4' style='padding:12px;color:#94a3b8;'>暂无同步的药瓶数据</td></tr>"
|
||||
|
||||
device_list = []
|
||||
for d in devices:
|
||||
device_list.append(
|
||||
f"<tr style='border-bottom:1px solid #e2e8f0;'>"
|
||||
f"<td style='padding:10px 14px;'><strong>📱 {d['device_name']}</strong></td>"
|
||||
f"<td style='padding:10px 14px;font-family:monospace;'>{d['ip_address']}</td>"
|
||||
f"<td style='padding:10px 14px;color:#64748b;'>{d['last_seen'][:19].replace('T', ' ')}</td>"
|
||||
f"</tr>"
|
||||
)
|
||||
device_rows = "".join(device_list) or "<tr><td colspan='3' style='padding:12px;color:#94a3b8;'>暂无在线设备连接</td></tr>"
|
||||
|
||||
record_list = []
|
||||
for r in records:
|
||||
detail = '试喷 -1' if r['is_prime'] else f"万{r['ventolin_puffs']}喷 + 辅{r['flixotide_puffs']}喷"
|
||||
clean_status = '已漱口/洗脸' if r['rinsed_mouth'] and r['washed_face'] else '未清洁'
|
||||
op_name = r['operator_name'] or '未知'
|
||||
record_list.append(
|
||||
f"<tr style='border-bottom:1px solid #f1f5f9;'>"
|
||||
f"<td style='padding:8px 12px;color:#1e293b;'>{r['start_time'][:16].replace('T', ' ')}</td>"
|
||||
f"<td style='padding:8px 12px;'><strong>{op_name}</strong></td>"
|
||||
f"<td style='padding:8px 12px;color:#059669;'>{detail}</td>"
|
||||
f"<td style='padding:8px 12px;color:#64748b;'>{clean_status}</td>"
|
||||
f"</tr>"
|
||||
)
|
||||
record_rows = "".join(record_list) or "<tr><td colspan='4' style='padding:12px;color:#94a3b8;'>暂无吸入记录</td></tr>"
|
||||
|
||||
html = f"""<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>AeroTrack 局域网同步服务器</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<style>
|
||||
body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f8fafc; color: #1e293b; margin: 0; padding: 24px; }}
|
||||
.container {{ max-width: 900px; margin: 0 auto; }}
|
||||
.header {{ background: #2563eb; color: #fff; padding: 24px; border-radius: 16px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; }}
|
||||
.card {{ background: #fff; border-radius: 14px; border: 1px solid #e2e8f0; padding: 20px; margin-bottom: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }}
|
||||
h2 {{ margin-top: 0; font-size: 16px; color: #0f172a; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px; }}
|
||||
table {{ width: 100%; border-collapse: collapse; font-size: 13px; }}
|
||||
th {{ background: #f8fafc; text-align: left; padding: 10px 14px; font-weight: 600; color: #64748b; }}
|
||||
.tag {{ display: inline-block; padding: 2px 8px; border-radius: 6px; font-size: 11px; font-weight: bold; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div>
|
||||
<h1 style="margin:0;font-size:22px;">AeroTrack 局域网多设备同步服务器</h1>
|
||||
<p style="margin:4px 0 0;font-size:13px;opacity:0.85;">数据安全保存在局域网私有主机,已记录 {total_count} 条雾化流水</p>
|
||||
</div>
|
||||
<div style="background:rgba(255,255,255,0.2);padding:8px 16px;border-radius:12px;font-size:12px;font-weight:bold;">
|
||||
🟢 服务运行中
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>当前药瓶余量监控 (各设备统一账本)</h2>
|
||||
<table>
|
||||
<thead><tr><th>药名</th><th>当前剩余喷数</th><th>每次用量</th><th>方案状态</th></tr></thead>
|
||||
<tbody>{canister_rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>已连接局域网设备</h2>
|
||||
<table>
|
||||
<thead><tr><th>设备名称</th><th>IP 地址</th><th>最后同步时间</th></tr></thead>
|
||||
<tbody>{device_rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>最近雾化时间流水 (前20条)</h2>
|
||||
<table>
|
||||
<thead><tr><th>时间</th><th>操作人</th><th>喷数明细</th><th>收尾防护</th></tr></thead>
|
||||
<tbody>{record_rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>"""
|
||||
encoded = html.encode('utf-8')
|
||||
self.send_response(200)
|
||||
self._send_cors_headers()
|
||||
self.send_header('Content-Type', 'text/html; charset=utf-8')
|
||||
self.send_header('Content-Length', str(len(encoded)))
|
||||
self.end_headers()
|
||||
self.wfile.write(encoded)
|
||||
|
||||
def main():
|
||||
port = 8090
|
||||
if len(sys.argv) > 1:
|
||||
try:
|
||||
port = int(sys.argv[1])
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
init_db()
|
||||
server_address = ('0.0.0.0', port)
|
||||
httpd = ThreadedHTTPServer(server_address, SyncHandler)
|
||||
print(f"=====================================================")
|
||||
print(f"🚀 AeroTrack 局域网同步服务器已启动!")
|
||||
print(f"📡 监听端口: {port}")
|
||||
print(f"🌐 局域网访问地址: http://0.0.0.0:{port}")
|
||||
print(f"💾 数据存储路径: {DB_FILE}")
|
||||
print(f"=====================================================")
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
print("\n服务已停止")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
# AeroTrack 局域网同步服务器启动脚本
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
PORT=${1:-8090}
|
||||
|
||||
echo "启动 AeroTrack 局域网多设备同步服务器..."
|
||||
echo "端口: $PORT"
|
||||
echo "数据库: $DIR/aerotrack.db"
|
||||
|
||||
python3 "$DIR/server.py" "$PORT"
|
||||
Reference in New Issue
Block a user