Skip to content

Commit

Permalink
WS tailing / and Log Size
Browse files Browse the repository at this point in the history
WS tailing / and Log Size
  • Loading branch information
GamerClassN7 authored Jan 16, 2024
2 parents e0a62eb + cfaf02c commit be204a2
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 46 deletions.
2 changes: 1 addition & 1 deletion HA/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ public string GetRootDir()

public bool Start(bool sleepRecover = false)
{
Logger.init(appDir + "/log.log");
Logger.init();

string token = "";
string url = "";
Expand Down
19 changes: 15 additions & 4 deletions HA/Class/Helpers/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ namespace HA.Class.Helpers
public class Logger
{
private static bool initialized = false;
private static DateTime lastInit;
private static string path1;
private static string[] secreetsStrings = new string[] { };

Expand All @@ -36,13 +37,21 @@ public static void setSecreets(string[] strings)
secreetsStrings = strings.Where(x => !string.IsNullOrEmpty(x)).ToArray();
}

public static void init(string path = "./log.log")
public static void init()
{
path1 = Path.Combine(appDir, path).ToString();

path1 = Path.Combine(appDir, (DateTime.Now).ToString("MM_dd_yyyy_log.log")).ToString();
lastInit = DateTime.Now;
if (!File.Exists(path1))
{
File.WriteAllText(path1, getMessage("Initialization", 0 /*info*/), System.Text.Encoding.UTF8);
}

string pathToLogToDelete = Path.Combine(appDir, (DateTime.Now).AddDays(-3).ToString("MM_dd_yyyy_log.log")).ToString();
if (File.Exists(pathToLogToDelete))
{
File.Delete(pathToLogToDelete);
}
initialized = true;
}

Expand All @@ -55,7 +64,8 @@ public static void init(string path = "./log.log")

public static void write(string msg, int level = 0)
{
if (!initialized)
int initBeforeDays = (int)(DateTime.Now - lastInit).TotalDays;
if (!initialized || initBeforeDays >= 1)
{
init();
}
Expand All @@ -72,7 +82,8 @@ public static void write(string msg, int level = 0)

public static void write(object msg, int level = 0)
{
if (!initialized)
int initBeforeDays = (int)(DateTime.Now - lastInit).TotalDays;
if (!initialized || initBeforeDays >= 1)
{
init();
}
Expand Down
79 changes: 42 additions & 37 deletions HA/Class/HomeAssistant/HomeAssistantWS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public class HomeAssistantWS

public HomeAssistantWS(string apiUrl, string webhookId, string apiToken)
{
url = apiUrl;
url = apiUrl.TrimEnd('/');
token = apiToken;
webhook = webhookId;

Expand All @@ -58,8 +58,6 @@ public HomeAssistantWS(string apiUrl, string webhookId, string apiToken)
retryCount++;
registerAsync();
} catch (Exception ex) {


throw new Exception("unnable to connect to" + url);
}
}
Expand All @@ -70,7 +68,7 @@ public async Task registerAsync()
{
Logger.write("WS INITIALIZATION");

Uri wsAddress = new Uri(url + "api/websocket");
Uri wsAddress = new Uri(url + "/api/websocket");
var exitEvent = new ManualResetEvent(false);
socket.Options.KeepAliveInterval = TimeSpan.Zero;

Expand Down Expand Up @@ -118,9 +116,7 @@ public async Task registerAsync()

recieveLoopObject = ReceiveLoopAsync();

}
catch (Exception ex)
{
} catch (Exception ex) {
Logger.write("WS error " + ex.Message);
Logger.write("WS URL " + url);
Logger.write("WS State " + socket.State);
Expand Down Expand Up @@ -175,21 +171,27 @@ private async Task<JObject> RecieveAsync()

private async Task Send(dynamic payloadObj)
{
string JSONPayload = JsonConvert.SerializeObject(payloadObj, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }).ToString();
try {
string JSONPayload = JsonConvert.SerializeObject(payloadObj, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }).ToString();

Logger.write("SEND");
Logger.write(JSONPayload);
interactions = interactions + 1;
Logger.write("SEND");
Logger.write(JSONPayload);
interactions = interactions + 1;

ArraySegment<byte> BYTEPayload = new ArraySegment<byte>(Encoding.UTF8.GetBytes(JSONPayload));
ArraySegment<byte> BYTEPayload = new ArraySegment<byte>(Encoding.UTF8.GetBytes(JSONPayload));

socket.SendAsync(BYTEPayload, WebSocketMessageType.Text, true, CancellationToken.None).Wait();
socket.SendAsync(BYTEPayload, WebSocketMessageType.Text, true, CancellationToken.None).Wait();
} catch (Exception ex) {
Logger.write("SEND FAILED");
Logger.write(ex.Message);
}
}

public bool getConectionStatus()
{
return (isConnected && isSubscribed);
}

private async Task StartPingAsyncTask()
{
Logger.write("Initializing Ping");
Expand All @@ -206,41 +208,43 @@ private async void UpdatePingTick(object sender, EventArgs e)
HAWSPing pingObj = new HAWSPing { };
pingObj.type = "ping";
pingObj.id = interactions;
Logger.write("Ping");

await Send(pingObj);
}
}

private async Task ReceiveLoopAsync()
{
try
{
try {
Logger.write("WS RECEEVE LOOP STARTED");
var localBuffer = new ArraySegment<byte>(new byte[2048]);
do
{
WebSocketReceiveResult localResult;
using (var ms = new MemoryStream())
{
do
{
localResult = await socket.ReceiveAsync(localBuffer, CancellationToken.None);
ms.Write(localBuffer.Array, localBuffer.Offset, localResult.Count);
} while (!localResult.EndOfMessage);

if (localResult.MessageType == WebSocketMessageType.Close)
break;

ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
string jsonPayload = await reader.ReadToEndAsync();
Logger.write("WS RECEEVED");
Logger.write(JObject.Parse(jsonPayload).ToString());
HandleEvent(JObject.Parse(jsonPayload));
bool error = false;
do {
try {
WebSocketReceiveResult localResult;
using (var ms = new MemoryStream()) {
do {
localResult = await socket.ReceiveAsync(localBuffer, CancellationToken.None);
ms.Write(localBuffer.Array, localBuffer.Offset, localResult.Count);
} while (!localResult.EndOfMessage);

if (localResult.MessageType == WebSocketMessageType.Close)
break;

ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms, Encoding.UTF8)) {
string jsonPayload = await reader.ReadToEndAsync();
Logger.write("WS RECEEVED");
Logger.write(JObject.Parse(jsonPayload).ToString());
HandleEvent(JObject.Parse(jsonPayload));
}
}
} catch (Exception ex) {
error = true;
Logger.write("WS RECEEVE ERROR" + ex.Message);
}
} while (true);
} while (!error);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -305,6 +309,7 @@ public bool Close()
isSubscribed = false;
isPingEnabled = false;
isConnected = false;

Logger.write("WS state " + socket.State);

updatePingTimer.Stop();
Expand Down
4 changes: 2 additions & 2 deletions HA/HA.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
<UseWindowsForms>true</UseWindowsForms>
<PackageIcon>ha_logo.ico</PackageIcon>
<ApplicationIcon>ha_logo.ico</ApplicationIcon>
<AssemblyVersion>0.0.12.0</AssemblyVersion>
<FileVersion>0.0.12.0</FileVersion>
<AssemblyVersion>0.0.12.1</AssemblyVersion>
<FileVersion>0.0.12.1</FileVersion>
</PropertyGroup>
<ItemGroup>
<None Remove="Resources\ha_loading.gif" />
Expand Down
2 changes: 1 addition & 1 deletion HA/class/HomeAssistant/HomeAssistantAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public HomeAssistantAPI(string apiRootUrl, string apiToken)
throw new Exception("unnabůle to connect to" + apiRootUrl);
}

url = apiRootUrl;
url = apiRootUrl.TrimEnd('/');
token = apiToken;
}

Expand Down
2 changes: 1 addition & 1 deletion HA/meta.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<item>
<version>0.0.11.0</version>
<version>0.0.12.1</version>
<url>https://github.com/GamerClassN7/HA_Desktop_Companion/releases/latest/download/HA_Self_Contained.zip</url>
<changelog>https://github.com/GamerClassN7/HA_Desktop_Companion/releases/latest</changelog>
<mandatory>false</mandatory>
Expand Down

0 comments on commit be204a2

Please sign in to comment.