Skip to content

Commit

Permalink
improved logging and added manual connection
Browse files Browse the repository at this point in the history
  • Loading branch information
hedihadi committed Nov 9, 2024
1 parent 8046296 commit b1bf354
Show file tree
Hide file tree
Showing 17 changed files with 278 additions and 116 deletions.
20 changes: 11 additions & 9 deletions local_server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,27 @@ const server = http.createServer((req, res) => {
const io = socketIo(server);

// Track the number of connected clients
let clientCount = 0;
let clients = [];

io.on('connection', (socket) => {
console.log("user connected");
// Increment the client count
clientCount++;
io.on('connect', (socket) => {
console.log(`user connected, ${clients.length}`);
// add client to the list of clients
let client = { 'name': socket.handshake.query.name, 'type': socket.handshake.query.type, 'id': socket.id }
clients.push(client)
// Broadcast the updated client count
io.emit('room_clients', clientCount);
io.emit('room_clients', clients);

// Relay any event received to all clients except the sender
socket.onAny((event, ...args) => {
socket.broadcast.emit(event, ...args);
});

socket.on('disconnect', () => {
// Decrement the client count
clientCount--;
console.log(`user disconnected, ${clients.length}`);
// remove the disconnected client
clients = clients.filter(client => client.id !== socket.id);
// Broadcast the updated client count
io.emit('room_clients', clientCount);
io.emit('room_clients', clients);
});
});

Expand Down
11 changes: 4 additions & 7 deletions zal_app/lib/Functions/models.dart
Original file line number Diff line number Diff line change
Expand Up @@ -546,17 +546,14 @@ class ProgramTime {
class SocketObject {
late Socket socket;
Timer? timer;
SocketObject(String? localSocketAddress, String? uid, String? idToken) {
SocketObject(String localSocketAddress, {Map<String, dynamic> extraQueries = const {}}) {
socket = io(
localSocketAddress ?? (dotenv.env['SERVER'] == 'production' ? 'https://api.zalapp.com' : 'http://192.168.0.120:5000'),
localSocketAddress,
<String, dynamic>{
'transports': ['websocket'],
'query': {
'EIO': '3',
'uid': uid,
'idToken': idToken,
'type': 1,
'version': 1,
...extraQueries,
'EIO': '4',
},
},
);
Expand Down
16 changes: 8 additions & 8 deletions zal_app/lib/Screens/FpsScreen/Widgets/fps_screen_pc_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -219,12 +219,12 @@ class FpsScreenPcWidget extends ConsumerWidget {
text: "core speed",
value: "${gpu.coreSpeed.round()}Mhz",
icon: FontAwesomeIcons.gauge,
maxValue: "${data.highestValues['gpu.coreSpeed']?.round()}Mhz"),
maxValue: "${data.highestValues['gpu.coreSpeed']?.round() ?? 0}Mhz"),
FpsPcStatWidget(
text: "mem speed",
value: "${gpu.memorySpeed.round()}Mhz",
icon: Icons.memory,
maxValue: "${data.highestValues['gpu.memorySpeed']?.round()}Mhz"),
maxValue: "${data.highestValues['gpu.memorySpeed']?.round() ?? 0}Mhz"),
FpsPcStatWidget(
text: "mem usage",
value: (gpu.dedicatedMemoryUsed * 1000 * 1000).toSize(),
Expand All @@ -234,18 +234,18 @@ class FpsScreenPcWidget extends ConsumerWidget {
text: "power",
value: "${gpu.power.round()}W",
icon: Icons.memory,
maxValue: "${data.highestValues['gpu.power']?.round()}W",
maxValue: "${data.highestValues['gpu.power']?.round() ?? 0}W",
),
FpsPcStatWidget(
text: "voltage",
value: "${gpu.voltage.round()}V",
icon: Icons.memory,
maxValue: "${data.highestValues['gpu.voltage']?.round()}V"),
maxValue: "${data.highestValues['gpu.voltage']?.round() ?? 0}V"),
FpsPcStatWidget(
text: "fan Speed",
value: "${gpu.fanSpeedPercentage.round()}%",
icon: Icons.memory,
maxValue: "${data.highestValues['gpu.fanSpeedPercentage']?.round()}%"),
maxValue: "${data.highestValues['gpu.fanSpeedPercentage']?.round() ?? 0}%"),
FpsPcStatWidget(
text: "temperature",
value: getTemperatureText(gpu.temperature, ref),
Expand All @@ -255,7 +255,7 @@ class FpsScreenPcWidget extends ConsumerWidget {
text: "load",
value: "${gpu.corePercentage.round()}%",
icon: Icons.memory,
maxValue: "${data.highestValues['gpu.corePercentage']?.round()}%"),
maxValue: "${data.highestValues['gpu.corePercentage']?.round() ?? 0}%"),
],
),
],
Expand Down Expand Up @@ -316,13 +316,13 @@ class FpsScreenPcWidget extends ConsumerWidget {
),
Expanded(
child: Text(
'${coreInfo.clock?.round()}MHZ',
'${coreInfo.clock?.round() ?? 0}MHZ',
style: Theme.of(context).textTheme.labelMedium,
textAlign: TextAlign.center,
),
),
Text(
'${coreInfo.load?.round()}%',
'${coreInfo.load?.round() ?? 0}%',
style: Theme.of(context).textTheme.labelMedium,
textAlign: TextAlign.end,
),
Expand Down
4 changes: 2 additions & 2 deletions zal_app/lib/Screens/FpsScreen/fps_screen_providers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ final fpsTimeElapsedProvider = AsyncNotifierProvider.autoDispose<FpsTimeElapsedN
return FpsTimeElapsedNotifier();
});

final gpuProcessesProvider = FutureProvider<List<GpuProcess>>((ref) {
final gpuProcessesProvider = FutureProvider<List<GpuProcess>>((ref) async {
final sub = ref.listen(socketStreamProvider, (prev, cur) {
if (cur.valueOrNull?.type == SocketDataType.gpuProcesses) {
final parsedData = Map<String, dynamic>.from(jsonDecode(cur.valueOrNull!.data));
Expand All @@ -148,7 +148,7 @@ final gpuProcessesProvider = FutureProvider<List<GpuProcess>>((ref) {
}
});
ref.onDispose(() => sub.close());
return ref.future;
return ref.future.timeout(const Duration(seconds: 2), onTimeout: () => []);
});

final selectedGpuProcessProvider = StateProvider.autoDispose<GpuProcess?>((ref) => null);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:sizer/sizer.dart';
import 'package:zal/Functions/utils.dart';
import 'package:zal/Screens/MainScreen/main_screen_providers.dart';
import 'package:zal/Screens/StorageScreen/Widgets/storage_information_widget.dart';

class ConnectManuallyWidget extends ConsumerWidget {
ConnectManuallyWidget({super.key});
TextEditingController addressController = TextEditingController(text: "192.168.");
@override
Widget build(BuildContext context, WidgetRef ref) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
const Text("Computer Address:"),
IconButton(
onPressed: () {
showInformationDialog(null, "You can find this address by opening Zal on your Computer, and check the bottom left corner.", context);
},
icon: Icon(
FontAwesomeIcons.question,
size: 2.h,
),
),
],
),
const SizedBox(height: 4),
TextField(
controller: addressController,
),
const SizedBox(height: 8),
Align(
alignment: Alignment.bottomRight,
child: ElevatedButton(
onPressed: () {
ref.read(socketProvider.notifier).connect(null, manualAddress: addressController.text, forceConnect: true);
Navigator.pop(context);
},
child: const Text("Connect"))),
],
);
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:sizer/sizer.dart';
import 'package:zal/Functions/models.dart';
import 'package:zal/Functions/theme.dart';
import 'package:zal/Screens/ConnectedScreen/connected_screen.dart';
import 'package:zal/Screens/InitialConnectionScreen/Widgets/choose_computer_widget.dart';
import 'package:zal/Screens/InitialConnectionScreen/Widgets/connect_manually_widget.dart';
import 'package:zal/Screens/InitialConnectionScreen/Widgets/initial_connection_settings_screen.dart';
import 'package:zal/Screens/InitialConnectionScreen/initial_connection_screen_providers.dart';
import 'package:zal/Screens/MainScreen/SettingsScreen/settings_providers.dart';
Expand Down Expand Up @@ -85,7 +88,7 @@ class InitialConnectionScreen extends ConsumerWidget {
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
ref.read(socketProvider.notifier).connect(computers[index]);
ref.read(socketProvider.notifier).connect(computers[index], forceConnect: true);
},
child: const Text("Connect"),
),
Expand All @@ -97,6 +100,22 @@ class InitialConnectionScreen extends ConsumerWidget {
);
},
),
ElevatedButton(
onPressed: () {
AlertDialog alert = AlertDialog(
title: Text("Connect manually", style: GoogleFonts.bebasNeueTextTheme(AppTheme.darkTheme.textTheme).displayLarge),
content: ConnectManuallyWidget(),
);

// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
},
child: const Text("Connect Manually")),
const Spacer(),
const Divider(),
Wrap(
Expand Down
49 changes: 41 additions & 8 deletions zal_app/lib/Screens/MainScreen/main_screen_providers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
Expand Down Expand Up @@ -54,17 +55,38 @@ final contextProvider = StateProvider<BuildContext?>((ref) => null);

class SocketObjectNotifier extends AsyncNotifier<SocketObject?> {
ComputerAddress? currentAddress;
String mobileName = 'Default Mobile Name';

Future<void> setMobileName() async {
if (Platform.isAndroid) {
final info = (await DeviceInfoPlugin().androidInfo);
mobileName = info.model;
}
if (Platform.isIOS) {
final info = (await DeviceInfoPlugin().iosInfo);
mobileName = info.model;
}
}

@override
Future<SocketObject?> build() async {
await setMobileName();
return null;
}

connect(ComputerAddress address) {
if (currentAddress == address) return;
connect(ComputerAddress? address, {String? manualAddress, bool forceConnect = false}) {
if (!forceConnect) {
if (currentAddress == address) return;
}
if (state.valueOrNull != null) {
state.valueOrNull!.socket.disconnect();
state.valueOrNull!.socket.dispose();
}
currentAddress = address;
ref.read(settingsProvider.notifier).updateSettings('address', address.toJson());

state = AsyncData(SocketObject(address.ip, null, null));
if (address != null) {
ref.read(settingsProvider.notifier).updateSettings('address', address.toJson());
}
state = AsyncData(SocketObject(address?.ip ?? "http://$manualAddress/", extraQueries: {'name': mobileName, 'type': 'mobile'}));
}

sendMessage(String key, dynamic value) {
Expand All @@ -73,6 +95,7 @@ class SocketObjectNotifier extends AsyncNotifier<SocketObject?> {

disconnect() {
currentAddress = null;
state.valueOrNull?.socket.disconnect();
state.valueOrNull?.socket.dispose();
ref.invalidateSelf();
}
Expand All @@ -93,8 +116,10 @@ final socketStreamProvider = StreamProvider<SocketData>((ref) async* {
if (socket != null) {
socket.socket.onConnect((data) {
ref.read(isConnectedToServerProvider.notifier).state = true;

//showSnackbarLocal("Server Connected");
showSnackbarLocal("Server Connected");
});
socket.socket.onConnectError((a) {
showSnackbarLocal("Connection error:${a.toString()}");
});
socket.socket.onDisconnect((data) {
ref.read(isConnectedToServerProvider.notifier).state = false;
Expand All @@ -105,7 +130,15 @@ final socketStreamProvider = StreamProvider<SocketData>((ref) async* {
// ref.read(webrtcProvider.notifier).messageReceived(RTCDataChannelMessage(data));
});
socket.socket.on("room_clients", (data) {
ref.read(isConnectedToServerProvider.notifier).state = (data as int) > 1;
for (Map<String, dynamic> client in data) {
if (client['type'] == 'computer') {
showSnackbarLocal("Connected to ${client['name']}!");

ref.read(isConnectedToServerProvider.notifier).state = true;
return;
}
}
showSnackbarLocal("Connected to Server, but no PC is online!");
// stream.add(SocketData(type: SocketDataType.roomClients, data: data != 0 ? [0, 1] : [1]));
});
socket.socket.on('pc_data', (data) {
Expand Down
10 changes: 5 additions & 5 deletions zal_app/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -207,21 +207,21 @@ packages:
source: hosted
version: "4.1.1"
device_info_plus:
dependency: transitive
dependency: "direct main"
description:
name: device_info_plus
sha256: "77f757b789ff68e4eaf9c56d1752309bd9f7ad557cb105b938a7f8eb89e59110"
sha256: f545ffbadee826f26f2e1a0f0cbd667ae9a6011cc0f77c0f8f00a969655e6e95
url: "https://pub.dev"
source: hosted
version: "9.1.2"
version: "11.1.1"
device_info_plus_platform_interface:
dependency: transitive
description:
name: device_info_plus_platform_interface
sha256: d3b01d5868b50ae571cd1dc6e502fc94d956b665756180f7b16ead09e836fd64
sha256: "282d3cf731045a2feb66abfe61bbc40870ae50a3ed10a4d3d217556c35c8c2ba"
url: "https://pub.dev"
source: hosted
version: "7.0.0"
version: "7.0.1"
dio:
dependency: transitive
description:
Expand Down
1 change: 1 addition & 0 deletions zal_app/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ dependencies:
hive: ^2.2.3
hive_flutter: ^1.1.0
flutter_gemini: ^2.0.3
device_info_plus: ^11.1.1

dev_dependencies:
flutter_lints: ^4.0.0
Expand Down
20 changes: 16 additions & 4 deletions zal_program/Zal/Backend/HelperFunctions/FpsDataGetter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,30 @@ public void disposeIt()
public void stopPresentmon()
{
Logger.Log("stopping presentmon");
foreach (var process in Process.GetProcessesByName("presentmon"))
try
{
process.Kill();
Logger.Log("presentmon killed");
foreach (var process in Process.GetProcessesByName("presentmon"))
{
process.Kill();
Logger.Log("presentmon killed");
}
foreach (var process in Process.GetProcessesByName("PresentMon-x64"))
{
process.Kill();
Logger.Log("presentmon killed");
}
}
catch (Exception ex)
{
Logger.LogError("error killing presentmon", ex);
}
}

public async void startPresentmon(int processId, bool logFps)
{
shouldLog = logFps;
//startFpsTimer();
//kill any presentmon process that might be running
stopPresentmon();
var filePath = GlobalClass.Instance.getFilepathFromResources("presentmon.exe");
var startInfo = new ProcessStartInfo
{
Expand Down
Loading

0 comments on commit b1bf354

Please sign in to comment.