Skip to content

Commit

Permalink
add some try catch and cover more edge cases
Browse files Browse the repository at this point in the history
  • Loading branch information
franco-giordano committed Nov 22, 2021
1 parent 7a2f357 commit 8a7af48
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 44 deletions.
117 changes: 87 additions & 30 deletions App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
using Forms = System.Windows.Forms;
using CloudFlightMonitor.model;
using System.Timers;
using System.Drawing;


namespace CloudFlightMonitor
{

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
Expand All @@ -15,8 +18,8 @@ public partial class App : Application
private System.Drawing.Icon[] chargeIcons;
private CloudFlightHeadset headset = null;
private Timer updateTimer;
private const int UPDATE_TIMER_MS = 5000; // 5 mins = 300000 ms

private const int UPDATE_TIMER_MS = 60000; // 5 mins = 300000 ms
private const string BASE_ICON_TEXT = "Cloud Flight Monitor";

private Forms.ToolStripLabel batLabel;
Expand All @@ -28,18 +31,18 @@ public App()

protected override void OnStartup(StartupEventArgs e)
{
this.InitIcons();
this.InitHIDDev();
this.OnUpdate(null, null); // force update first time
InitIcons();
InitHIDDev();
OnUpdate(null, null); // force update first time

base.OnStartup(e);
Console.WriteLine("Started!");

// Start update Timer
this.updateTimer = new Timer(UPDATE_TIMER_MS);
this.updateTimer.Elapsed += this.OnUpdate;
this.updateTimer.AutoReset = true;
this.updateTimer.Enabled = true;
updateTimer = new Timer(UPDATE_TIMER_MS);
updateTimer.Elapsed += OnUpdate;
updateTimer.AutoReset = true;
updateTimer.Enabled = true;
}

protected override void OnExit(ExitEventArgs e)
Expand All @@ -48,37 +51,79 @@ protected override void OnExit(ExitEventArgs e)
base.OnExit(e);
}

private void OnUpdate(Object source, ElapsedEventArgs e)
private void OnUpdate(Object source, ElapsedEventArgs _)
{
//Get current batteryCharge
int batteryCharge = this.headset.ReadBattery();
try
{
//Get current batteryCharge
int batteryCharge = headset.ReadBattery();

string text = "Battery: " + batteryCharge + "%";
batLabel.Text = text;
notifyIcon.Text = BASE_ICON_TEXT + "\n" + text;
if (batteryCharge <= 100)
{
string text = "Battery: " + batteryCharge + "%";
batLabel.Text = text;
notifyIcon.Text = BASE_ICON_TEXT + "\n" + text;

//Update Tray Icon
notifyIcon.Icon = chargeIcons[batteryCharge];
}
else if (batteryCharge == 199)
{
// headset is charging
string text = "Headset Charging";
batLabel.Text = text;
notifyIcon.Text = BASE_ICON_TEXT + "\n" + text;

//Update Tray Icon
notifyIcon.Icon = chargeIcons[100];
}
else
{
// headset returned a strange/unknown value...
string text = "Unknown Status";
batLabel.Text = text;
notifyIcon.Text = BASE_ICON_TEXT + "\n" + text;

//Update Tray Icon
notifyIcon.Icon = chargeIcons[101];
}

}
catch (Exception e)
{
Console.WriteLine("Error while updating battery charge, message: ", e.Message);
const string txt = "Couldn't connect to headset";
batLabel.Text = txt;
notifyIcon.Text = BASE_ICON_TEXT + "\n" + txt;

//Update Tray Icon
notifyIcon.Icon = chargeIcons[0];

// Reset connection...
InitHIDDev();
}

//Update Tray Icon
this.notifyIcon.Icon = this.chargeIcons[batteryCharge];
}

private void InitIcons()
{
this.chargeIcons = new System.Drawing.Icon[101];
chargeIcons = new Icon[102];
for (int i = 0; i <= 100; i++)
{
try
{
this.chargeIcons[i] = new System.Drawing.Icon("icos\\" + i + ".ico");
chargeIcons[i] = LoadIcon("icos\\" + i + ".ico");
}
catch (Exception)
{
/*exit = true;*/
Console.WriteLine("At least one Icon was not found (" + i + ".ico). Process exiting.");
return;
ExitProgram();
}
}

this.notifyIcon.Text = BASE_ICON_TEXT;
chargeIcons[101] = LoadIcon("icos\\Headset.ico");

notifyIcon.Text = BASE_ICON_TEXT + "\n" + "Waiting for connection...";

Forms.ContextMenuStrip trayMenu = new Forms.ContextMenuStrip();

Expand All @@ -87,30 +132,42 @@ private void InitIcons()

Forms.ToolStripMenuItem exitItem = new Forms.ToolStripMenuItem();
exitItem.Text = "Exit";
exitItem.Click += new System.EventHandler(ExitProgram);
exitItem.Click += new EventHandler(ExitProgram);
trayMenu.Items.Add(exitItem);

this.notifyIcon.ContextMenuStrip = trayMenu;
notifyIcon.ContextMenuStrip = trayMenu;

this.notifyIcon.Icon = this.chargeIcons[0];
notifyIcon.Icon = chargeIcons[0];

this.notifyIcon.Visible = true;
notifyIcon.Visible = true;
}

private Icon LoadIcon(string path)
{
try
{
return new Icon(path);
}
catch (Exception)
{
Console.WriteLine("At least one Icon was not found ({0}). Process exiting.", path);
ExitProgram();
return null; // unreachable
}
}

private void InitHIDDev()
{
try
{
this.headset = new CloudFlightHeadset();
headset = new CloudFlightHeadset();
}
catch (Exception e)
{
Console.WriteLine("Cloud Flight Device not found! Msg: " + e.Message);
/*exit = true;*/
Console.WriteLine("Cloud Flight Device not found! Message: " + e.Message);
}
}
private void ExitProgram(object sender, EventArgs e)
private void ExitProgram(object sender = null, EventArgs e = null)
{
Application.Current.Shutdown();
}
Expand Down
2 changes: 1 addition & 1 deletion CloudFlightMonitor.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

<PropertyGroup>
<OutputType>Exe</OutputType>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
<ApplicationIcon />
Expand Down
46 changes: 33 additions & 13 deletions model/CloudFlightHeadset.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CloudFlightMonitor.model
{
Expand All @@ -12,22 +11,46 @@ class CloudFlightHeadset

public CloudFlightHeadset()
{
var devs = HIDBrowse.Browse().FindAll(x => x.Pid == 5923 && x.Vid == 2385);
List<HIDInfo> allDevs = HIDBrowse.Browse();
allDevs.ForEach(x => Console.WriteLine("{0} - {1} - {2} - {3} - {4} - {5}", x.Manufacturer, x.Path, x.Product, x.SerialNumber, x.Pid, x.Vid));
Console.WriteLine("CONSTRUCTOR: Scanning matching devices...");
List<HIDInfo> devs = allDevs.FindAll(x => x.Pid == 5923 && x.Vid == 2385);
List<HIDInfo> chargingDevs = allDevs.FindAll(x => x.Pid == 5925 && x.Vid == 2385);

if (chargingDevs.Count != 0)
{
Console.WriteLine("CONSTRUCTOR: Cloud Flight Device Charging!");
MakeConnection(chargingDevs, 1);
return;
}

if (devs.Count == 0)
{
Console.WriteLine("CONSTRUCTOR: Cloud Flight Device not found!");
throw new Exception("Device not found");
}

this.dev = new HIDDev();
dev.Open(devs.ElementAt(0));
MakeConnection(devs, 2);
}

private void MakeConnection(List<HIDInfo> devs, int index)
{
Console.WriteLine("CONSTRUCTOR: Found devices. Count: {0}", devs.Count);

dev = new HIDDev();
bool res = dev.Open(devs.ElementAt(index));
Console.WriteLine("CONSTRUCTOR: Open connection result is {0}", res);

if (!res)
{
throw new Exception("Device found, but couldn't connect");
}
}

public int ReadBattery()
{
// get report
byte[] reportIn = this.GetReport();
byte[] reportIn = GetReport();

Console.WriteLine(string.Join("\t", reportIn));

Expand All @@ -36,12 +59,11 @@ public int ReadBattery()
Int32 chargeState = reportIn[3];
Int32 magicValue = reportIn[4] != 0 ? reportIn[4] : chargeState;

Int32 percentage = calculatePercentage(chargeState, magicValue);
Int32 percentage = CalculatePercentage(chargeState, magicValue);

Console.WriteLine("Charge: " + chargeState + " - MV: " + magicValue + " - Percentage: " + percentage);

return percentage;

}

private byte[] GetReport()
Expand All @@ -52,24 +74,22 @@ private byte[] GetReport()
report[2] = 0x05;

// Send request
this.dev.Write(report);
dev.Write(report);

// Prepare buffer for answer
byte[] reportIn = new byte[20]; //neeed 31 (by testing)
byte[] reportIn = new byte[20];

// Read answer
this.dev.Read(reportIn);
dev.Read(reportIn);

return reportIn;
}

private int calculatePercentage(int chargeState, int magicValue)
private int CalculatePercentage(int chargeState, int magicValue)
{

if (chargeState == 0x10)
{
//emitter.emit('charging', magicValue >= 20)

if (magicValue <= 11)
{
return 200; // full?
Expand Down

0 comments on commit 8a7af48

Please sign in to comment.