checkDeviceStatus static method

Future<void> checkDeviceStatus(
  1. BuildContext context,
  2. NearbyHttpService nearbyHttpService
)

Implementation

static Future<void> checkDeviceStatus(BuildContext context, NearbyHttpService nearbyHttpService) async {

  final Battery battery = Battery();
  final batteryLevel = await battery.batteryLevel;

  final Directory tempDir = await getTemporaryDirectory();
  final Directory appDir = await getApplicationDocumentsDirectory();
  final int totalStorage = tempDir.statSync().size + appDir.statSync().size;
  final int availableStorage = tempDir.statSync().size;
  final double storageAvailable = (availableStorage / totalStorage) * 100;

  final connectivityResult = await Connectivity().checkConnectivity();
  final bool hasInternet = connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi;
  final DeviceRole role = hasInternet ? DeviceRole.advertiser : DeviceRole.browser;

  final devId = nearbyHttpService.devInfo;

  reputationsByDevice.clear();


  final sent = nearbyHttpService.sentPacketsPerDevice[devId] ?? 0;
  final failed = nearbyHttpService.failedPacketsPerDevice[devId] ?? 0;
  final delivered = sent - failed;

  final delaysList = nearbyHttpService.delaysPerDevice[devId] ?? [];
  final avgLatency = delaysList.isEmpty
      ? 0.0
      : delaysList.map((e) => e.toDouble()).reduce((a, b) => a + b) / delaysList.length;

  final node = NodeReputation(
    timestamp: DateTime.now().toIso8601String(),
    deviceId: devId,
    battery: batteryLevel.toDouble(),
    storage: storageAvailable,
    successfulInteractions: delivered,
    totalInteractions: sent,
    requestedPackets: sent,
    deliveredPackets: delivered,
    avgLatency: avgLatency,
    diversity: nearbyHttpService.discoveredDevices.length,
    daysSinceLastInteraction: 1,
    weights: [0.28, 0.14, 0.22, 0.20, 0.16],
  );

  await node.init();
  await node.calculateReputation();

  final history = await node.readHistory();
  history.sort((a, b) => DateTime.parse(b['timestamp']).compareTo(DateTime.parse(a['timestamp'])));
  reputationsByDevice.clear();
  for (var item in history) {
    final histKey = '${devId}_hist_${item["timestamp"]}';
    reputationsByDevice[histKey] = NodeReputation.fromMap(item);
  }

  if (!node.canCooperate()) {
    final threshold = node.hasHistory ? node.pl : node.sl;

    final details = '''
🧠 Cooperation Evaluation:
History available: ${node.hasHistory} → Threshold = ${threshold.toStringAsFixed(2)}
Battery: ${node.battery.toStringAsFixed(1)}%, Storage: ${node.storage.toStringAsFixed(1)}%
❌ Cooperation denied: reputation = ${node.reputation.toStringAsFixed(3)} < threshold = ${threshold.toStringAsFixed(2)}
''';


    if (!context.mounted) return;

    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: const Text("Warning"),
        content: Text(details),
        actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text("OK"))],
      ),
    );

    if (role == DeviceRole.advertiser) {
      await nearbyService.stopAdvertisingPeer();
    } else {
      await nearbyService.stopBrowsingForPeers();
    }
  }
}