لماذا تعود القيمة الى 0 اريد ان تظهر ويتم عمل محاكاة… · The Chat Archive
Explore لماذا تعود القيمة الى 0 اريد ان تظهر ويتم عمل محاكاة للتوقيت عبر دالة fetchUptime للعلم… Save Share Download ▾ Reportلماذا تعود القيمة الى 0 اريد ان تظهر ويتم عمل محاكاة للتوقيت عبر دالة
_fetchUptime
للعلم الكود
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:router_os_client/router_os_client.dart';
import 'Login.dart';
import 'hotspotUserList.dart';
import 'AddHotspotUser.dart';
class RouterDetailsPage extends StatefulWidget {
final RouterOSClient client;
const RouterDetailsPage({super.key, required this.client});
@override
State createState() => _RouterDetailsPageState();
}
class _RouterDetailsPageState extends State {
final _routerInfoNotifier = ValueNotifier<Map<String, dynamic>>({});
final _activeHotspotUsersCountNotifier = ValueNotifier(0);
final _connectedDevicesCountNotifier = ValueNotifier(0);
final _isLoadingNotifier = ValueNotifier(false);
final _hasErrorNotifier = ValueNotifier(false);
Timer? _uptimeTimer, _cpuTimer, _memoryTimer, _usersTimer, _devicesTimer;
bool _isFetchingUsers = false;
bool _isFetchingDevices = false;
int _lastKnownUserCount = 0;
int _currentIndex = 0;
Color _primaryColor = const Color(0xFF3B82F6);
Color _backgroundColor = const Color(0xFF0A192F);
Color _cardColor = const Color(0xFF172A46);
Color _textColor = Colors.white;
@override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 1), _startTimers);
}
@override
void dispose() {
widget.client.close();
_routerInfoNotifier.dispose();
_activeHotspotUsersCountNotifier.dispose();
_connectedDevicesCountNotifier.dispose();
_isLoadingNotifier.dispose();
_hasErrorNotifier.dispose();
super.dispose();
}
void _cancelAllTimers() {
_uptimeTimer?.cancel();
_uptimeTimer = null;
_cpuTimer?.cancel();
_cpuTimer = null;
_memoryTimer?.cancel();
_memoryTimer = null;
_usersTimer?.cancel();
_usersTimer = null;
_devicesTimer?.cancel();
_devicesTimer = null;
print('stoped');
}
void _startTimers() {
cpuTimer = Timer.periodic(Duration(milliseconds: 2100), ( ) {
_fetchCpu();
print('router_cpu');
});
usersTimer = Timer.periodic(Duration(seconds: 10), ( ) {
_fetchActiveHotspotUsers();
print('router_Active');
});
_fetchAllData();
}
Future _fetchAllData() async {
await Future.wait([
_fetchUptime(),
Future.delayed(Duration(milliseconds: 450), () => _fetchCpu()),
_fetchMemory(),
Future.delayed(Duration(seconds: 1), () => _fetchActiveHotspotUsers()),
Future.delayed(
Duration(milliseconds: 1200),
() => _fetchConnectedDevices(),
),
]);
print('first_fetch');
}
Future _fetchResourceData(List properties) async {
try {
final response = await widget.client.talk(['/system/resource/print']);
if (response.isNotEmpty && response[0] is Map) {
final data = Map<String, dynamic>.from(
response[0] as Map<dynamic, dynamic>,
);
final newData = Map<String, dynamic>.from(_routerInfoNotifier.value);
for (var prop in properties) {
if (data.containsKey(prop)) {
newData[prop] = data[prop];
}
}
_routerInfoNotifier.value = newData;
}
} catch (e) {
if (mounted) {
_handleError(e);
}
}
}
Assistant2025-06-26 14:18 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Jun 26, 2025
Added to archive Nov 16, 2026
ID 01m7h42wp5md5hs53mawe2ysexSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 94718a8310326a3fbfc373d299292e88
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
int _initialUptimeSeconds = 0;
DateTime? _lastUptimeFetchTime;
Future _fetchUptime() async {
// جلب القيمة الحقيقية مرة واحدة فقط
if (_initialUptimeSeconds == 0 || _lastUptimeFetchTime == null) {
try {
final response = await widget.client.talk(['/system/resource/print']);
if (response.isNotEmpty && response[0] is Map) {
final data = Map<String, dynamic>.from(
response[0] as Map<dynamic, dynamic>,
);
_initialUptimeSeconds =
int.tryParse(data['uptime']?.toString() ?? '0') ?? 0;
_lastUptimeFetchTime = DateTime.now();
// تحديث القيمة في الـ notifier
final newData = Map<String, dynamic>.from(_routerInfoNotifier.value);
newData['uptime'] = _initialUptimeSeconds.toString();
newData['identity'] = data['identity'];
_routerInfoNotifier.value = newData;
}
} catch (e) {
if (mounted) _handleError(e);
}
} else {
// محاكاة الوقت التزايدي بناءً على الوقت الفعلي المنقضي
final now = DateTime.now();
final elapsedSeconds = now.difference(_lastUptimeFetchTime!).inSeconds;
final currentUptime = _initialUptimeSeconds + elapsedSeconds;
// تحديث القيمة في الـ notifier
final newData = Map<String, dynamic>.from(_routerInfoNotifier.value);
newData['uptime'] = currentUptime.toString();
_routerInfoNotifier.value = newData;
}
Future _fetchCpu() async => _fetchResourceData(['cpu-load']);
Future _fetchMemory() async =>
_fetchResourceData(['total-memory', 'free-memory']);
Future _fetchActiveHotspotUsers() async {
if (_isFetchingUsers) return;
_isFetchingUsers = true;
try {
final response = await widget.client.talk([
'/ip/hotspot/active/print',
'=.proplist=user',
]);
if (response.isEmpty) {
_activeHotspotUsersCountNotifier.value = 0;
return;
}
int activeUsersCount = 0;
for (var item in response) {
if (item is Map && item.containsKey('user')) {
activeUsersCount++;
}
}
if (_lastKnownUserCount != activeUsersCount) {
_lastKnownUserCount = activeUsersCount;
_activeHotspotUsersCountNotifier.value = activeUsersCount;
}
} catch (e) {
if (mounted) _handleError(e);
} finally {
_isFetchingUsers = false;
}
Future _fetchConnectedDevices() async {
if (_isFetchingDevices) return;
_isFetchingDevices = true;
try {
final response = await widget.client.talk(['/ip/neighbor/print']);
final devices = response.where((device) => device is Map).toList();
_connectedDevicesCountNotifier.value = devices.length;
} catch (e) {
if (mounted) _handleError(e);
} finally {
_isFetchingDevices = false;
}
}
void _handleError(dynamic e) {
if (!mounted) return;
_hasErrorNotifier.value = true;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('خطأ في جلب البيانات: ${e.toString()}'),
backgroundColor: Colors.red,
),
);
}
void _onItemTapped(int index) {
setState(() {
_currentIndex = index;
});
switch (index) {
case 0:
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => RouterDetailsPage(client: widget.client),
),
);
break;
case 1:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UsersPage(client: widget.client),
),
);
break;
case 2:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddHotspotCardsPage(client: widget.client),
),
);
break;
case 3:
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Login()),
);
break;
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > 800) {
return _buildDesktopLayout(context);
} else {
return _buildMobileLayout(context);
}
},
),
);
}
Widget _buildDesktopLayout(BuildContext context) {
return Scaffold(
backgroundColor: _backgroundColor,
body: Row(
children: [
Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.05),
border: Border(
right: BorderSide(color: Colors.white.withOpacity(0.1)),
),
), // <== هذا القوس كان مفقوداً
child: Column(
children: [
const SizedBox(height: 40),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
Icon(Icons.router, color: _primaryColor, size: 28),
const SizedBox(width: 10),
Text(
'لوحة تحكم الراوتر',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
],
),
),
const SizedBox(height: 30),
_buildDesktopNavigation(),
],
),
),
Expanded(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
_backgroundColor.withOpacity(0.9),
_backgroundColor.withOpacity(0.7),
],
),
),
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildAdaptiveStatsCard(),
const SizedBox(height: 20),
Row(
children: [
Expanded(child: _buildCpuUsageCard()),
const SizedBox(width: 20),
Expanded(child: _buildMemoryUsageCard()),
],
),
],
),
),
),
),
],
),
);
}
Widget _buildDesktopNavigation() {
return Column(
children: [
_buildNavItem(
icon: Icons.dashboard,
title: 'الرئيسية',
isActive: true,
onTap: () {},
),
_buildNavItem(
icon: Icons.people,
title: 'المستخدمون',
isActive: false,
onTap: () {
_cancelAllTimers();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UsersPage(client: widget.client),
),
).then((value) {
_startTimers();
});
},
),
_buildNavItem(
icon: Icons.person_add,
title: 'إضافة مستخدم',
isActive: false,
onTap: () {
_cancelAllTimers();
Navigator.push(
context,
MaterialPageRoute(
builder:
(context) => AddHotspotCardsPage(client: widget.client),
),
).then((value) {
_startTimers();
});
},
),
const SizedBox(height: 20),
const Divider(color: Colors.white24, height: 1),
const SizedBox(height: 20),
_buildNavItem(
icon: Icons.settings,
title: 'الإعدادات',
isActive: false,
onTap: () {},
),
_buildNavItem(
icon: Icons.logout,
title: 'تسجيل خروج',
isActive: false,
onTap: () {
_cancelAllTimers();
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Login()),
).then((value) {
_startTimers();
});
},
),
],
);
}
Widget _buildNavItem({
required IconData icon,
required String title,
required bool isActive,
required VoidCallback onTap,
}) {
return InkWell(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 16),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: isActive ? _primaryColor.withOpacity(0.2) : Colors.transparent,
borderRadius: BorderRadius.circular(8),
border:
isActive
? Border.all(color: _primaryColor.withOpacity(0.5), width: 1)
: null,
),
child: Row(
children: [
Icon(
icon,
color: isActive ? _primaryColor : Colors.white.withOpacity(0.7),
size: 24,
),
const SizedBox(width: 12),
Text(
title,
style: TextStyle(
color: isActive ? Colors.white : Colors.white.withOpacity(0.7),
fontSize: 16,
fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
),
),
if (isActive) const Spacer(),
if (isActive)
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: _primaryColor,
shape: BoxShape.circle,
),
),
],
),
),
);
}
Widget _buildMobileLayout(BuildContext context) {
return Scaffold(
backgroundColor: _backgroundColor,
appBar: AppBar(
title: Text(
'لوحة تحكم الراوتر',
style: TextStyle(color: _textColor, fontSize: 20),
),
centerTitle: true,
backgroundColor: _backgroundColor,
elevation: 0,
iconTheme: IconThemeData(color: _textColor),
),
drawer: _buildMobileDrawer(),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
_backgroundColor.withOpacity(0.9),
_backgroundColor.withOpacity(0.7),
],
),
),
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildAdaptiveStatsCard(),
const SizedBox(height: 20),
_buildCpuUsageCard(),
const SizedBox(height: 20),
_buildMemoryUsageCard(),
],
),
),
),
);
}
Widget _buildMobileDrawer() {
return Drawer(
backgroundColor: _backgroundColor,
child: ListView(
padding: EdgeInsets.zero,
children: [
DrawerHeader(
decoration: BoxDecoration(
color: _primaryColor.withOpacity(0.1),
border: Border(
bottom: BorderSide(color: Colors.white.withOpacity(0.1)),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.router, size: 40, color: _primaryColor),
const SizedBox(height: 10),
ValueListenableBuilder(
valueListenable: _routerInfoNotifier,
builder:
(context, value, _) => Text(
value['identity'] ?? 'RouterOS',
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 5),
ValueListenableBuilder(
valueListenable: _routerInfoNotifier,
builder: (context, value, _) {
return Text(
'وقت التشغيل: ${_formatUptime(value['uptime'])}',
style: TextStyle(color: Colors.white.withOpacity(0.8)),
);
},
),
],
),
),
_buildDrawerItem(
icon: Icons.dashboard,
title: 'الرئيسية',
onTap: () {},
),
_buildDrawerItem(
icon: Icons.people,
title: 'المستخدمون',
onTap: () {
_cancelAllTimers();
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UsersPage(client: widget.client),
),
).then((value) {
_startTimers();
});
},
),
_buildDrawerItem(
icon: Icons.person_add,
title: 'إضافة مستخدم',
onTap: () {
_cancelAllTimers();
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder:
(context) => AddHotspotCardsPage(client: widget.client),
),
).then((value) {
_startTimers();
});
},
),
const Divider(color: Colors.white24),
_buildDrawerItem(
icon: Icons.settings,
title: 'الإعدادات',
onTap: () {},
),
_buildDrawerItem(
icon: Icons.logout,
title: 'تسجيل خروج',
color: Colors.red,
onTap: () {
_cancelAllTimers();
Navigator.pop(context);
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Login()),
);
},
),
],
),
);
}
Widget _buildDrawerItem({
required IconData icon,
required String title,
Color color = Colors.white,
required VoidCallback onTap,
}) {
return ListTile(
leading: Icon(icon, color: color),
title: Text(title, style: TextStyle(color: color)),
onTap: onTap,
);
}
Widget _buildAdaptiveStatsCard() {
// ارتفاع ثابت لجميع الشاشات
const double fixedHeight = 130.0;
// أحجام ثابتة مع ضبطها لتكون متناسبة مع الارتفاع الثابت
const double iconSize = 28.0;
const double valueSize = 22.0;
const double titleSize = 14.0;
return Container(
height: fixedHeight, // استخدام الارتفاع الثابت هنا
decoration: BoxDecoration(
color: _cardColor,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 10,
spreadRadius: 2,
),
],
),
child: Padding(
padding: const EdgeInsets.all(8),
child: ValueListenableBuilder(
valueListenable: _routerInfoNotifier,
builder: (context, routerInfo, _) {
return Row(
children: [
Expanded(
child: _buildStatItem(
icon: Icons.people_alt_outlined,
value: _activeHotspotUsersCountNotifier.value.toString(),
title: 'المستخدمون النشطون',
color: Colors.green,
iconSize: iconSize,
valueSize: valueSize,
titleSize: titleSize,
),
),
Container(
width: 1,
height: 60,
margin: EdgeInsets.symmetric(vertical: 12),
color: Colors.white.withOpacity(0.15),
),
Expanded(
child: _buildStatItem(
icon: Icons.devices_other,
value: _connectedDevicesCountNotifier.value.toString(),
title: 'الأجهزة المتصلة',
color: Colors.blueAccent,
iconSize: iconSize,
valueSize: valueSize,
titleSize: titleSize,
),
),
Container(
width: 1,
height: 60,
margin: EdgeInsets.symmetric(vertical: 12),
color: Colors.white.withOpacity(0.15),
),
Expanded(
child: _buildStatItem(
icon: Icons.health_and_safety,
value: _getSystemStatusFromMap(routerInfo),
title: 'حالة النظام',
color: _getSystemStatusColorFromMap(routerInfo),
iconSize: iconSize,
valueSize: valueSize,
titleSize: titleSize,
),
),
],
);
},
),
),
);
Widget _buildStatItem({
required IconData icon,
required String value,
required String title,
required Color color,
required double iconSize,
required double valueSize,
required double titleSize,
}) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: iconSize, color: color),
SizedBox(height: 6),
Text(
value,
style: TextStyle(
fontSize: valueSize,
fontWeight: FontWeight.bold,
color: color,
),
),
SizedBox(height: 4),
Text(
title,
style: TextStyle(
color: Colors.white.withOpacity(0.9),
fontSize: titleSize,
),
),
],
);
}
Widget _buildHorizontalStatsLayout({
required double iconSize,
required double valueSize,
required double titleSize,
required double spacing,
required Map<String, dynamic> routerInfo,
}) {
return Container(
width: double.infinity,
margin: EdgeInsets.symmetric(horizontal: 8), // هامش جانبي صغير
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: _cardColor,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
blurRadius: 12,
spreadRadius: 3,
),
],
),
child: Padding(
padding: EdgeInsets.all(8),
child: Row(
children: [
// بطاقة المستخدمين النشطين
Expanded(
child: _buildEnhancedStatItem(
icon: Icons.people_alt_outlined,
value: _activeHotspotUsersCountNotifier.value.toString(),
title: 'المستخدمون النشطون',
color: Colors.green,
iconSize: 28,
valueSize: 24,
titleSize: 16,
spacing: 8,
),
),
// فاصل عمودي
Container(
width: 1,
height: 60,
margin: EdgeInsets.symmetric(vertical: 12),
color: Colors.white.withOpacity(0.15),
),
// بطاقة الأجهزة المتصلة
Expanded(
child: _buildEnhancedStatItem(
icon: Icons.devices_other,
value: _connectedDevicesCountNotifier.value.toString(),
title: 'الأجهزة المتصلة',
color: Colors.blueAccent,
iconSize: 28,
valueSize: 24,
titleSize: 16,
spacing: 8,
),
),
// فاصل عمودي
Container(
width: 1,
height: 60,
margin: EdgeInsets.symmetric(vertical: 12),
color: Colors.white.withOpacity(0.15),
),
// بطاقة حالة النظام
Expanded(
child: _buildEnhancedStatItem(
icon: Icons.health_and_safety,
value: _getSystemStatusFromMap(routerInfo),
title: 'حالة النظام',
color: _getSystemStatusColorFromMap(routerInfo),
iconSize: 28,
valueSize: 24,
titleSize: 16,
spacing: 8,
),
),
],
),
),
);
Widget _buildEnhancedStatItem({
required IconData icon,
required String value,
required String title,
required Color color,
required double iconSize,
required double valueSize,
required double titleSize,
required double spacing,
}) {
return Container(
padding: EdgeInsets.symmetric(vertical: 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: iconSize, color: color),
SizedBox(width: 8),
Text(
value,
style: TextStyle(
fontSize: valueSize,
fontWeight: FontWeight.bold,
color: color,
),
),
],
),
SizedBox(height: spacing),
Text(
title,
style: TextStyle(
color: Colors.white.withOpacity(0.9),
fontSize: titleSize,
),
),
],
),
);
}
Widget _buildModernStatCard({
required IconData icon,
required String value,
required String title,
required Color color,
required Gradient gradient,
bool isSmall = false,
}) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 2), // تقليل الهوامش
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8), // تقليل نصف القطر
gradient: gradient,
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min, // مهم للتحكم في الارتفاع
children: [
Container(
padding: const EdgeInsets.all(6), // تصغير حجم الأيقونة
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2),
shape: BoxShape.circle,
),
child: Icon(
icon,
size: isSmall ? 18 : 22, // ضبط حجم الأيقونة
color: Colors.white,
),
),
SizedBox(height: 4),
Text(
value,
style: TextStyle(
fontSize: isSmall ? 16 : 20, // ضبط حجم النص
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
SizedBox(height: 2),
Text(
title,
style: TextStyle(
color: Colors.white.withOpacity(0.9),
fontSize: isSmall ? 10 : 12, // ضبط حجم النص
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
maxLines: 1, // منع التقسيم إلى سطور متعددة
overflow: TextOverflow.ellipsis, // إضافة ... إذا طال النص
),
],
),
),
);
}
Widget _buildVerticalStatsLayout({
required double iconSize,
required double valueSize,
required double titleSize,
required double spacing,
required Map<String, dynamic> routerInfo,
}) {
return Container(
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: _cardColor,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 10,
spreadRadius: 2,
),
],
),
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
// جعل كل جزء يأخذ نفس المساحة
Expanded(
flex: 1,
child: _buildModernStatCard(
icon: Icons.people_alt_outlined,
value: _activeHotspotUsersCountNotifier.value.toString(),
title: 'المستخدمون النشطون',
color: Colors.green,
gradient: LinearGradient(
colors: [Colors.green.shade400, Colors.green.shade700],
),
isSmall: true,
),
),
Container(
height: 40,
width: 1,
margin: EdgeInsets.symmetric(vertical: 12),
color: Colors.white.withOpacity(0.2),
),
Expanded(
flex: 1,
child: _buildModernStatCard(
icon: Icons.devices_other,
value: _connectedDevicesCountNotifier.value.toString(),
title: 'الأجهزة المتصلة',
color: Colors.blueAccent,
gradient: LinearGradient(
colors: [
Colors.blueAccent.shade400,
Colors.blueAccent.shade700,
],
),
isSmall: true,
),
),
Container(
height: 40,
width: 1,
margin: EdgeInsets.symmetric(vertical: 12),
color: Colors.white.withOpacity(0.2),
),
Expanded(
flex: 1,
child: _buildModernStatCard(
icon: Icons.health_and_safety,
value: _getSystemStatusFromMap(routerInfo),
title: 'حالة النظام',
color: _getSystemStatusColorFromMap(routerInfo),
gradient: LinearGradient(
colors: [
_getSystemStatusColorFromMap(routerInfo).withOpacity(0.8),
_getSystemStatusColorFromMap(routerInfo),
],
),
isSmall: true,
),
),
],
),
),
);
}
Widget _buildAdaptiveStatItem({
required IconData icon,
required String value,
required String title,
required Color color,
required double iconSize,
required double valueSize,
required double titleSize,
required double spacing,
}) {
return Flexible(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: iconSize, color: color),
SizedBox(height: spacing),
Text(
value,
style: TextStyle(
fontSize: valueSize,
fontWeight: FontWeight.bold,
color: color,
),
),
SizedBox(height: spacing / 2),
Text(
title,
style: TextStyle(
color: Colors.white.withOpacity(0.7),
fontSize: titleSize,
),
),
],
),
);
}
Widget _buildStatCard({
required String title,
required ValueNotifier value,
required IconData icon,
required Color color,
bool isSystemStatus = false,
}) {
return Container(
decoration: BoxDecoration(
color: _cardColor,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 6,
spreadRadius: 2,
),
],
),
child: Padding(
padding: const EdgeInsets.all(16),
child: ValueListenableBuilder(
valueListenable: value,
builder:
(context, val, _) => Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
shape: BoxShape.circle,
),
child: Icon(icon, size: 24, color: color),
),
const SizedBox(height: 10),
Text(
isSystemStatus
? _getSystemStatusFromMap(val as Map<String, dynamic>)
: val.toString(),
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color:
isSystemStatus
? _getSystemStatusColorFromMap(val)
: color,
),
),
const SizedBox(height: 5),
Text(
title,
style: TextStyle(
color: Colors.white.withOpacity(0.7),
fontSize: 14,
),
),
],
),
),
),
);
}
Widget _buildCpuUsageCard() {
return Container(
height: 320,
decoration: BoxDecoration(
color: _cardColor,
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.speed, color: Colors.blue),
const SizedBox(width: 8),
Text(
'استخدام المعالج',
style: TextStyle(
color: _textColor,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 20),
ValueListenableBuilder(
valueListenable: _routerInfoNotifier,
builder: (context, value, _) {
final cpuLoad =
double.tryParse(value['cpu-load']?.toString() ?? '0') ?? 0;
return Column(
children: [
Stack(
alignment: Alignment.center,
children: [
SizedBox(
width: 180,
height: 180,
child: CircularProgressIndicator(
value: cpuLoad / 100,
strokeWidth: 12,
backgroundColor: Colors.grey.withOpacity(0.2),
valueColor: AlwaysStoppedAnimation(
_getCpuColor(cpuLoad),
),
),
),
Column(
children: [
Text(
'$cpuLoad%',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.bold,
color: _getCpuColor(cpuLoad),
),
),
Text(
'حمل المعالج',
style: TextStyle(
color: Colors.white.withOpacity(0.7),
),
),
],
),
],
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildStatusIndicator(
'طبيعي',
Colors.green,
cpuLoad <= 70,
),
const SizedBox(width: 16),
_buildStatusIndicator(
'تحذير',
Colors.orange,
cpuLoad > 70 && cpuLoad <= 90,
),
const SizedBox(width: 16),
_buildStatusIndicator('حرج', Colors.red, cpuLoad > 90),
],
),
],
);
},
),
],
),
);
}
Widget _buildMemoryUsageCard() {
return Container(
height: 320,
decoration: BoxDecoration(
color: _cardColor,
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.memory, color: Colors.purple),
const SizedBox(width: 8),
Text(
'استخدام الذاكرة',
style: TextStyle(
color: _textColor,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 20),
ValueListenableBuilder(
valueListenable: _routerInfoNotifier,
builder: (context, value, _) {
final freeMem =
double.tryParse(value['free-memory']?.toString() ?? '0') ?? 0;
final totalMem =
double.tryParse(value['total-memory']?.toString() ?? '1') ??
1;
final usedPercent = ((totalMem - freeMem) / totalMem * 100)
.toStringAsFixed(1);
final usedValue = (totalMem - freeMem) / totalMem;
return Column(
children: [
Stack(
alignment: Alignment.center,
children: [
SizedBox(
width: 180,
height: 180,
child: CircularProgressIndicator(
value: usedValue,
strokeWidth: 12,
backgroundColor: Colors.grey.withOpacity(0.2),
valueColor: AlwaysStoppedAnimation<Color>(
_getMemoryColor(usedValue * 100),
),
),
),
Column(
children: [
Text(
'$usedPercent%',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.bold,
color: _getMemoryColor(usedValue * 100),
),
),
Text(
'الذاكرة المستخدمة',
style: TextStyle(
color: Colors.white.withOpacity(0.7),
),
),
],
),
],
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildMemoryDetail('الإجمالي', _formatBytes(totalMem)),
_buildMemoryDetail(
'المستخدم',
_formatBytes(totalMem - freeMem),
),
_buildMemoryDetail('المتاح', _formatBytes(freeMem)),
],
),
],
);
},
),
],
),
);
Widget _buildStatusIndicator(String label, Color color, bool isActive) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 12,
height: 12,
decoration: BoxDecoration(
color: isActive ? color : Colors.grey.withOpacity(0.3),
shape: BoxShape.circle,
),
),
const SizedBox(width: 4),
Text(
label,
style: TextStyle(color: isActive ? color : Colors.grey, fontSize: 14),
),
],
);
}
Widget _buildMemoryDetail(String title, String value) {
return Column(
children: [
Text(
title,
style: TextStyle(color: Colors.white.withOpacity(0.7), fontSize: 12),
),
const SizedBox(height: 4),
Text(
value,
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
],
);
}
Color _getCpuColor(double value) {
if (value > 90) return Colors.red;
if (value > 70) return Colors.orange;
return Colors.green;
}
Color _getMemoryColor(double value) {
if (value > 90) return Colors.red;
if (value > 70) return Colors.orange;
return Colors.blue;
}
String _getSystemStatusFromMap(Map<String, dynamic> info) {
final cpuLoad = double.tryParse(info['cpu-load']?.toString() ?? '0') ?? 0;
if (cpuLoad > 90) return 'حرج';
if (cpuLoad > 70) return 'تحذير';
return 'طبيعي';
}
Color _getSystemStatusColorFromMap(Map<String, dynamic> info) {
switch (_getSystemStatusFromMap(info)) {
case 'حرج':
return Colors.red;
case 'تحذير':
return Colors.orange;
default:
return Colors.green;
}
}
String _formatUptime(String? uptime) {
if (uptime == null) return 'غير معروف';
try {
final seconds = int.parse(uptime);
final days = seconds ~/ (24 * 3600);
final hours = (seconds % (24 * 3600)) ~/ 3600;
final minutes = (seconds % 3600) ~/ 60;
if (days > 0) return 'd a y s يوم {days} يوم d a y s يوم {hours} ساعة';
if (hours > 0) return 'h o u r s ساعة {hours} ساعة h o u r s ساعة {minutes} دقيقة';
return '${minutes} دقيقة';
} catch (e) {
return uptime;
}
}
String _formatBytes(double bytes) {
if (bytes < 1024) return 'b y t e s . t o S t r i n g A s F i x e d ( 0 ) B ′ ; i f ( b y t e s < 1024 ∗ 1024 ) r e t u r n ′ {bytes.toStringAsFixed(0)} B';
if (bytes < 1024 * 1024) return ' b y t es . t o S t r in g A s F i x e d ( 0 ) B ′ ; i f ( b y t es < 1024 ∗ 1024 ) r e t u r n ′ {(bytes / 1024).toStringAsFixed(1)} KB';
if (bytes < 1024 * 1024 * 1024)
return '( b y t e s / ( 1024 ∗ 1024 ) ) . t o S t r i n g A s F i x e d ( 1 ) M B ′ ; r e t u r n ′ {(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
return ' ( b y t es / ( 1024 ∗ 1024 )) . t o S t r in g A s F i x e d ( 1 ) {(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
}
}
ملاحظة اعطيني الجزء السابق والجزء المراد استبدالة بة
بناءً على كودك، سبب رجوع قيمة الـ uptime إلى 0 أو عدم تحديثها بشكل صحيح يعود إلى أن دالة _fetchUptime() يتم استدعاؤها مرة واحدة فقط لإحضار القيمة الحقيقية، وبعدها تعتمد على الحسابات المحلية لإظهار الوقت المتزايد (الـ simulation).
لكن في كودك الحالي، يبدو أن دالة _fetchUptime() لا يتم استدعاؤها بشكل دوري لتحديث الوقت مع مرور الثواني بحيث تتزايد القيمة. مشاكل محتملة:
لم يتم إنشاء Timer يقوم بتحديث قيمة uptime باستدعاء _fetchUptime() باستمرار.
أو تم استدعاء _fetchUptime() مرة واحدة فقط عند الجلب الأولي (عند تهيئة الصفحة أو بداية التشغيل)، وبالتالي لا تحدث القيمة لاحقًا.
الحل:
يجب إضافة Timer ليحدث القيمة بشكل دوري (مثلاً كل ثانية) عن طريق تحديث القيمة من محاكاة الوقت حسب _initialUptimeSeconds و _lastUptimeFetchTime.
الجزء السابق في كودك (في initState و startTimers):
@override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 1), _startTimers);
}
void _startTimers() {
_cpuTimer = Timer.periodic(Duration(milliseconds: 2100), (_) {
_fetchCpu();
print('router_cpu');
});
_usersTimer = Timer.periodic(Duration(seconds: 10), (_) {
_fetchActiveHotspotUsers();
print('router_Active');
});
_fetchAllData();
}
الجزء المراد استبداله بـ:
@override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 1), _startTimers);
}
void _startTimers() {
_cpuTimer = Timer.periodic(Duration(milliseconds: 2100), (_) {
_fetchCpu();
print('router_cpu');
});
_usersTimer = Timer.periodic(Duration(seconds: 10), (_) {
_fetchActiveHotspotUsers();
print('router_Active');
});
// أضف تايمر لتحديث uptime بشكل دوري كل ثانية
_uptimeTimer = Timer.periodic(Duration(seconds: 1), (_) {
_fetchUptime();
});
_fetchAllData();
}
@override
void dispose() {
_cancelAllTimers(); // ألغِ كل التايمرات هنا أيضاً لتجنب التسريبات
widget.client.close();
_routerInfoNotifier.dispose();
_activeHotspotUsersCountNotifier.dispose();
_connectedDevicesCountNotifier.dispose();
_isLoadingNotifier.dispose();
_hasErrorNotifier.dispose();
super.dispose();
}
void _cancelAllTimers() {
_uptimeTimer?.cancel();
_uptimeTimer = null;
_cpuTimer?.cancel();
_cpuTimer = null;
_memoryTimer?.cancel();
_memoryTimer = null;
_usersTimer?.cancel();
_usersTimer = null;
_devicesTimer?.cancel();
_devicesTimer = null;
print('Stopped all timers');
}
شرح:
أضفت _uptimeTimer ليجري تحديث قيمة uptime كل ثانية بحساب الوقت وفقًا لما لديك في _fetchUptime().
هذا سيجعل الواجهة تعرض قيمة uptime متزايدة وليست ثابتة أو 0.
أيضا حرصت على إلغاء التايمر في dispose ومن خلال الدالة _cancelAllTimers التي تستخدمها في التنقل وإغلاق الصفحة لتفادي تشغيل عدة Timers في نفس الوقت.
إذا أردت التحقق من صحة الحساب أو طباعة القيم أثناء تحديث uptime لمزيد من التتبع، يمكنك إضافة طبعات للوقت الحالي والقيمة المحسوبة داخل _fetchUptime().
ملاحظة إضافية:
إذا عند استدعاء /system/resource/print من الراوتر يتم جلب uptime بصيغة مختلفة (مثلاً نص يحتوي على أيام وساعات بدلاً من ثانية واحدة)، تأكد من تحويله إلى عدد ثوانٍ بشكل صحيح.
مثلاً: إذا data['uptime'] عبارة عن نص بتنسيق مثل 1d23:59:59 يجب معالجته لتحويله لعدد ثواني.
إذا كان لديك تنسيق مختلف أو تريد مساعدة في تحويل نص uptime لعدد ثواني، أعطني مثال لتنسيق القيمة data['uptime'] وسأساعدك عليها.
Copy first response
Not yet included in a published release.
M
B ′
;
r
e
t
u
r
n ′