Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update socket io and manage reconnect #3

Merged
merged 3 commits into from
Nov 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ await ioBroker.ConnectAsync(TimeSpan.FromSeconds(5));
### Read value
```c#
var id = "deconz.0.Lights.13.level"; // the object id you want to read
var result = await ioBroker.GetStateAsync<int>(id, TimeSpan.FromSeconds(5)); // you receive a GetStateResult<T>
var result = await ioBroker.TryGetStateAsync<int>(id, TimeSpan.FromSeconds(5)); // you receive a GetStateResult<T>

// Check if reading was succesfull
if (result.Success)
Expand All @@ -45,14 +45,22 @@ else
### Write value
```c#
var id = "deconz.0.Lights.13.level"; // the object id you want to set
await ioBroker.SetStateAsync<int>(id, 55);
var result = await ioBroker.TrySetStateAsync<int>(id, 55); // you receive a SetStateResult<T>
// Check if writing was succesfull
if (result.Success)
{
Console.WriteLine($"Success with writing value: {result.ValueToWrite}");
}
else
{
Console.WriteLine($"Error while writing with Exception: {result.Error}");
}
```

### Subscribe for changes
```c#
var id = "deconz.0.Lights.13.level"; // the object id you want to get notifications if value changes
await ioBroker.SubscribeStateAsync<int>(id, LightLevelChangedHandler);

...

private static void LightLevelChangedHandler(int lightLevel)
Expand Down
57 changes: 43 additions & 14 deletions src/ioBroker.net/ConsoleTest/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,58 @@ static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
var ioBroker = new IoBrokerDotNet();
ioBroker.ConnectionString = @"http://ioBroker:8084";
ioBroker.ConnectionString = @"http://192.168.178.192:8084";
await ioBroker.ConnectAsync(TimeSpan.FromSeconds(5));


var tempCountId = "javascript.0.socketio.0.Test_12345";
var tempCount = ioBroker.TryGetStateAsync<bool>(tempCountId, TimeSpan.FromSeconds(5)).Result;
//var newValue = false;
//await ioBroker.SetStateAsync<bool>(tempCountId, newValue);

await ioBroker.ConnectAsync(TimeSpan.FromSeconds(5));
await ioBroker.SubscribeStateAsync<int>("linkeddevices.0.lights.GangOben.level", (value) => Console.WriteLine($"Received value: {value}"));
await ioBroker.SetStateAsync<int>("linkeddevices.0.lights.GangOben.level", 35);
//await ioBroker.SubscribeStateAsync<int>("linkeddevices.0.lights.GangOben.level", (value) => Console.WriteLine($"Received value: {value}"));
//await ioBroker.SetStateAsync<int>("linkeddevices.0.lights.GangOben.level", 35);

//var testread = await ioBroker.GetStateAsync<int>("linkeddevices.0.lights.fernsehlicht.level", TimeSpan.FromSeconds(5));
//if (testread.Success)
//{
// Console.WriteLine($"Success with value: {testread.Value}");
//}
//else
//{
// Console.WriteLine($"Error with Exception: {testread.Error}");
//}
////await ioBroker.CreateStateAsync<int>("javascript.0.toilett.flushes");

await TryWriteAndRead(ioBroker, tempCountId);
await TryWriteAndRead(ioBroker, tempCountId);

var testread = await ioBroker.GetStateAsync<int>("linkeddevices.0.lights.fernsehlicht.level", TimeSpan.FromSeconds(5));
if (testread.Success)
Console.ReadKey();
}

private static async Task TryWriteAndRead(IoBrokerDotNet ioBroker, string tempCountId)
{
Thread.Sleep(TimeSpan.FromSeconds(30));
var newValue = false;
var result = await ioBroker.TrySetStateAsync<bool>(tempCountId, newValue);
if (result.Success)
{
Console.WriteLine($"Success with value: {testread.Value}");
Console.WriteLine($"result: {result.Success}");
}
else
{
Console.WriteLine($"Error with Exception: {testread.Error}");
Console.WriteLine($"Error while writing: {result.Error}");
}

var resultWithoutConnection = ioBroker.TryGetStateAsync<bool>(tempCountId, TimeSpan.FromSeconds(5)).Result;
if (resultWithoutConnection.Success)
{
Console.WriteLine($"result: {resultWithoutConnection.Value}");
}
else
{
Console.WriteLine($"Error while Reading: {resultWithoutConnection.Error}");
}
//await ioBroker.CreateStateAsync<int>("javascript.0.toilett.flushes");

Thread.Sleep(5000000);
Console.ReadKey();
}


}
}
4 changes: 2 additions & 2 deletions src/ioBroker.net/ioBroker.net/IIoBrokerDotNet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ public interface IIoBrokerDotNet
{
string ConnectionString { get; set; }
Task ConnectAsync(TimeSpan timeout);
Task SetStateAsync<T>(string id, T value);
Task<GetStateResult<T>> GetStateAsync<T>(string id, TimeSpan timeout);
Task<SetStateResult<T>> TrySetStateAsync<T>(string id, T value);
Task<GetStateResult<T>> TryGetStateAsync<T>(string id, TimeSpan timeout);
Task SubscribeStateAsync<T>(string id, Action<T> callback);
}
}
73 changes: 54 additions & 19 deletions src/ioBroker.net/ioBroker.net/IoBrokerDotNet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace ioBroker.net
{
public class IoBrokerDotNet : IIoBrokerDotNet
{
private readonly SocketIO _socketIoClient;
private SocketIO _socketIoClient;
private EventWaitHandle _connectedWaitHandle;
private readonly Dictionary<string, List<Action<State>>> _subscriptions;

Expand All @@ -20,13 +20,6 @@ public class IoBrokerDotNet : IIoBrokerDotNet

public IoBrokerDotNet()
{
_socketIoClient = new SocketIO();
_socketIoClient.OnConnected += async (sender, eventArgs) => await SocketIoOnConnectedHandler(sender, eventArgs);
_socketIoClient.OnDisconnected += (sender, s) => { Console.WriteLine($"Disonnected from socket.io: {s}"); };
_socketIoClient.OnError += (sender, s) => { Console.WriteLine($"Error from socket.io: {s}"); };
_socketIoClient.OnReconnecting += (sender, i) => { Console.WriteLine($"Reconnecting: {i}"); };
_socketIoClient.OnReconnectFailed += (sender, exception) => { Console.WriteLine($"Reconnect failed: {exception}"); };

_subscriptions = new Dictionary<string, List<Action<State>>>();
}

Expand All @@ -35,36 +28,78 @@ public IoBrokerDotNet(string connectionString) : this()
ConnectionString = connectionString;
}

private void CreateSocketIoClient()
{
var connectionUri = new Uri(ConnectionString);
//_socketIoClient.ServerUri = connectionUri;

_socketIoClient = new SocketIO(connectionUri, new SocketIOOptions() { EIO = 3, ConnectionTimeout = TimeSpan.FromDays(1) });
_socketIoClient.OnConnected += async (sender, eventArgs) => await SocketIoOnConnectedHandler(sender, eventArgs);
_socketIoClient.OnDisconnected += (sender, s) => { Console.WriteLine($"Disonnected from socket.io: {s}"); };
_socketIoClient.OnError += (sender, s) => { Console.WriteLine($"Error from socket.io: {s}"); };
_socketIoClient.OnReconnectAttempt += (sender, i) => { Console.WriteLine($"Reconnecting: {i}"); };
_socketIoClient.OnReconnectFailed += (sender, exception) => { Console.WriteLine($"Reconnect failed: {exception}"); };
}

public string ConnectionString { get; set; }

public async Task ConnectAsync(TimeSpan timeout)
{
var connectionUri = new Uri(ConnectionString);
_socketIoClient.ServerUri = connectionUri;
CreateSocketIoClient();

_connectedWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
await _socketIoClient.ConnectAsync();

_connectedWaitHandle.WaitOne(timeout);
}

public async Task SetStateAsync<T>(string id, T value)
public async Task<SetStateResult<T>> TrySetStateAsync<T>(string id, T value)
{
await _socketIoClient.EmitAsync("setState", id, new { val = value, ack = false });
var result = new SetStateResult<T>() { Success = true, ValueToWrite = value };
try
{
if (_socketIoClient.Connected)
{
await _socketIoClient.EmitAsync("setState", id, new { val = value, ack = false });
}
else
{
result.Success = false;
result.Error = new Exception($"Not connected to socket io server {ConnectionString}");
}
}
catch(Exception exception)
{
Console.WriteLine(exception);
result.Success = false;
result.Error = exception;
}

return result;
}

public async Task<GetStateResult<T>> GetStateAsync<T>(string id, TimeSpan timeout)
public async Task<GetStateResult<T>> TryGetStateAsync<T>(string id, TimeSpan timeout)
{
var retVal = new GetStateResult<T>();
var stateReceivedWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
await _socketIoClient.EmitAsync("getState", (response) => GetStateResponse<T>(response, stateReceivedWaitHandle, retVal, id), id);

if (!stateReceivedWaitHandle.WaitOne(timeout))
try
{
await _socketIoClient.EmitAsync("getState", (response) => GetStateResponse<T>(response, stateReceivedWaitHandle, retVal, id), id);
if (!stateReceivedWaitHandle.WaitOne(timeout))
{
retVal.Success = false;
retVal.Error = new TimeoutException($"Timeout for reading state of id: \"{id}\"");
}
}
catch (Exception exception)
{
retVal.Success = false;
retVal.Error = new TimeoutException($"Timeout for reading state of id: \"{id}\"");
retVal.Error = exception;
}
finally
{
stateReceivedWaitHandle.Dispose();
}
stateReceivedWaitHandle.Dispose();

return retVal;
}
Expand Down Expand Up @@ -129,7 +164,7 @@ private void GetStateResponse<T>(SocketIOResponse response, EventWaitHandle stat
{
try
{
stateResult.Value= JsonSerializer.Deserialize<T>(obj.Val.ToString());
stateResult.Value= JsonSerializer.Deserialize<T>(obj.Val.ToString().ToLower());
stateResult.Success = true;
}
catch (Exception e)
Expand Down
13 changes: 13 additions & 0 deletions src/ioBroker.net/ioBroker.net/SetStateResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;

namespace ioBroker.net
{
public class SetStateResult<T>
{
public bool Success { get; set; }

public Exception Error { get; set; }

public T ValueToWrite { get; set; }
}
}
2 changes: 1 addition & 1 deletion src/ioBroker.net/ioBroker.net/ioBroker.net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="SocketIOClient" Version="2.2.0" />
<PackageReference Include="SocketIOClient" Version="3.0.3" />
</ItemGroup>

<ItemGroup>
Expand Down