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

Increased Rm2Pro Rf learning stability #8

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 0 additions & 4 deletions ConsoleTest/ConsoleTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Xb.Core" Version="1.0.13" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\SharpBroadlink\SharpBroadlink.csproj" />
</ItemGroup>
Expand Down
73 changes: 46 additions & 27 deletions ConsoleTest/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
Expand Down Expand Up @@ -28,10 +29,6 @@ static void Main(string[] args)
// .GetAwaiter()
// .GetResult();

//Program.RmTest()
// .GetAwaiter()
// .GetResult();

//Program.RmTemperatureTest()
// .GetAwaiter()
// .GetResult();
Expand All @@ -49,6 +46,8 @@ static void Main(string[] args)
Program.RmRfSignalTest()
.GetAwaiter()
.GetResult();

//TestIrLearning().Wait();
}
catch(Exception e)
{
Expand All @@ -64,6 +63,32 @@ static void Main(string[] args)

#region "TestOK"

private static async Task TestIrLearning()
{
Console.WriteLine("Searching for Rm2Pro devices...");
var devs = await Broadlink.Discover(1);
var rm = (Rm2Pro)devs.FirstOrDefault(d => d.DeviceType == DeviceType.Rm2Pro);

if (rm == null)
throw new Exception("Rm2Pro Not Found");
else Console.WriteLine($"Rm2Pro found at {rm.Host}");

if (!await rm.Auth())
throw new Exception("Auth Failure");

Console.WriteLine("Learning command, press remote now");
var command = await rm.LearnIRCommnad(CancellationToken.None);
if (command == null || command.Length == 0)
throw new Exception("Failed to learn command");

Console.WriteLine("Command learned, press any key to send the command now...");
Console.ReadKey();

Console.WriteLine("Sending IR command");
await rm.SendData(command);
Console.WriteLine("IR command sent");
}

private static async Task<bool> RmRfSignalTest()
{
Console.WriteLine("Searching for Rm2Pro devices...");
Expand All @@ -87,13 +112,27 @@ private static async Task<bool> RmRfSignalTest()
byte[] command = null;
try
{
command = await rm.LearnRfCommand(cancellationSource.Token, () =>
Action<Rm2Pro.LearnInstructions> learnInstructionHandler = (instructions) =>
{
//Get description from the enum - any other text will do
var msg = instructions.GetType().GetField(instructions.ToString())
?.GetCustomAttributes(typeof(DescriptionAttribute), true)
.OfType<DescriptionAttribute>()
.FirstOrDefault()
?.Description
?? instructions.ToString();

Console.WriteLine(msg);
Console.ReadKey(true);
};

command = await rm.LearnRfCommand(learnInstructionHandler, cancellationSource.Token, () =>
{
Console.Write('.');
});

if (command == null || command.Length == 0)
throw new InvalidOperationException("Failed to learn RF command");
throw new InvalidOperationException("Failed to learn RF command");
}
catch(TaskCanceledException)
{
Expand All @@ -108,7 +147,7 @@ private static async Task<bool> RmRfSignalTest()
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
Console.Write("Sending RF command... ");
await rm.SendRfData(command);
await rm.SendData(command);
Console.WriteLine("RF command sent");
}

Expand Down Expand Up @@ -138,26 +177,6 @@ private static async Task<bool> AuthTest()
return true;
}

private static async Task<bool> RmTest()
{
var devs = await Broadlink.Discover();

var rm = (Rm)devs[0];

if (!await rm.Auth())
throw new Exception("Auth Failure");

await rm.EnterLearning();

var data1 = await rm.CheckData();

var data2 = await rm.CheckData();

await rm.SendData(data2);

return true;
}

private static async Task<bool> RmTemperatureTest()
{
var devs = await Broadlink.Discover();
Expand Down
60 changes: 40 additions & 20 deletions SharpBroadlink/Broadlink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace SharpBroadlink
Expand All @@ -18,16 +19,33 @@ public enum WifiSecurityMode
WPA12 = 4
}

public static async Task<List<Devices.IDevice>> Discover(int timeout = 0)
{
var result = new List<Devices.IDevice>();
if (timeout == 0)
{
await Discover(result);
}
else
{
using (var cancellationSource = new CancellationTokenSource(TimeSpan.FromSeconds(timeout)))
await Discover(result, null, cancellationSource.Token);
}

return result;
}

/// <summary>
/// Find devices on the LAN.
/// </summary>
/// <param name="timeout"></param>
/// <param name="devices">Devices result collection</param>
/// <param name="cancellationToken">Optional Cancellation Token. If not provided the method will exit after discovering at least one device or after a timeout</param>
/// <param name="localIpAddress"></param>
/// <returns></returns>
/// <remarks>
/// https://github.com/mjg59/python-broadlink/blob/56b2ac36e5a2359272f4af8a49cfaf3e1891733a/broadlink/__init__.py#L61-L138
/// </remarks>
public static async Task<Devices.IDevice[]> Discover(int timeout = 0, IPAddress localIpAddress = null)
public static async Task Discover(ICollection<Devices.IDevice> devices, IPAddress localIpAddress = null, CancellationToken cancellationToken = default)
{
if (localIpAddress == null)
localIpAddress = IPAddress.Any;
Expand All @@ -45,7 +63,6 @@ public enum WifiSecurityMode
{
var port = cs.LocalPort;
var startTime = DateTime.Now;
var devices = new List<Devices.IDevice>();
var timezone = (int)((System.TimeZoneInfo.Local).BaseUtcOffset.TotalSeconds / -3600);
var year = startTime.Year;
var subYear = year % 100;
Expand Down Expand Up @@ -95,13 +112,14 @@ public enum WifiSecurityMode
packet[0x20] = (byte)(checksum & 0xff);
packet[0x21] = (byte)(checksum >> 8);

var isRecievedOnce = false;
var isReceivedOnce = false;
cs.OnRecieved += (object sender, Xb.Net.RemoteData rdata) =>
{
// Get mac
// 0x3a-0x3f, Little Endian
var mac = new byte[6];
Array.Copy(rdata.Bytes, 0x3a, mac, 0, 6);
Array.Reverse(mac);

// Get IP address
byte[] addr;
Expand Down Expand Up @@ -176,29 +194,31 @@ public enum WifiSecurityMode
var devType = (rdata.Bytes[0x34] | rdata.Bytes[0x35] << 8);
devices.Add(Devices.Factory.GenDevice(devType, host, mac));

isRecievedOnce = true;
isReceivedOnce = true;
};

await cs.SendToAsync(packet, IPAddress.Broadcast, 80);

await Task.Run(() =>
try
{
while (true)
await Task.Run(async () =>
{
if ((timeout <= 0 && isRecievedOnce)
|| (timeout > 0
&& (DateTime.Now - startTime).TotalSeconds > timeout)
)
break;

Task.Delay(100)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
}
});
while (true)
{
if ((cancellationToken.Equals(CancellationToken.None) && (isReceivedOnce || (DateTime.Now - startTime).TotalSeconds > 10))
|| cancellationToken.IsCancellationRequested)
break;

return devices.ToArray();
await Task.Delay(100).ConfigureAwait(false);
}
});
}
catch (TaskCanceledException)
{
}
catch (OperationCanceledException)
{
}
}
}

Expand Down
14 changes: 14 additions & 0 deletions SharpBroadlink/Devices/LearnInstructions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.ComponentModel;

namespace SharpBroadlink.Devices
{
public enum LearnInstructions
{
[Description("Press and hold the remote button")]
PressAndHoldRemotedButton,
[Description("Release the remote button")]
ReleaseRemoteButton,
[Description("Press shortly the remote button you want to learn")]
PressRemoteButtonShortly,
}
}
Loading