1
0
mirror of https://github.com/DarthAffe/RGB.NET-PicoPi.git synced 2025-12-12 13:28:34 +00:00

Added PicoPi config tool

This commit is contained in:
Darth Affe 2021-04-25 00:37:17 +02:00
parent f0062bffc1
commit 59bf1281a8
12 changed files with 822 additions and 1 deletions

255
.gitignore vendored
View File

@ -10,4 +10,257 @@ compile_commands.json
CTestTestfile.cmake
_deps
[Bb]uild/
.vscode
.vscode
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml

View File

@ -0,0 +1,39 @@
using System;
using System.Windows.Input;
namespace PicoPiConfig
{
public class ActionCommand : ICommand
{
private Action _action;
private Func<bool>? _canExecute;
public event EventHandler? CanExecuteChanged;
public ActionCommand(Action action, Func<bool>? canExecute = null)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object? parameter) => (_canExecute == null) || _canExecute();
public void Execute(object? parameter) => _action();
}
public class ActionCommand<T> : ICommand
{
private Action<T> _action;
private Func<bool>? _canExecute;
public event EventHandler? CanExecuteChanged;
public ActionCommand(Action<T> action, Func<bool>? canExecute = null)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object? parameter) => (_canExecute == null) || _canExecute();
public void Execute(object? parameter) => _action((T)parameter!);
}
}

4
PicoPiConfig/App.xaml Normal file
View File

@ -0,0 +1,4 @@
<Application x:Class="PicoPiConfig.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml" />

7
PicoPiConfig/App.xaml.cs Normal file
View File

@ -0,0 +1,7 @@
using System.Windows;
namespace PicoPiConfig
{
public partial class App : Application
{ }
}

View File

@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]

64
PicoPiConfig/Channel.cs Normal file
View File

@ -0,0 +1,64 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace PicoPiConfig
{
public class Channel : INotifyPropertyChanged
{
#region Properties & Fields
private int _index;
public int Index
{
get => _index;
set
{
_index = value;
OnPropertyChanged();
}
}
private int _pin;
public int Pin
{
get => _pin;
set
{
_pin = value;
OnPropertyChanged();
}
}
private int _ledCount;
public int LedCount
{
get => _ledCount;
set
{
_ledCount = value;
OnPropertyChanged();
}
}
#endregion
#region Constructors
public Channel(int index, int pin, int ledCount)
{
this.Index = index;
this.Pin = pin;
this.LedCount = ledCount;
}
#endregion
#region PropertyChanged
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
#endregion
}
}

View File

@ -0,0 +1,45 @@
<Window x:Class="PicoPiConfig.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PicoPiConfig"
mc:Ignorable="d"
Width="400" Height="440"
Title="RGB.NET PicoPi Configurator">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<DockPanel LastChildFill="True" Margin="16">
<Button DockPanel.Dock="Top" Content="Reload" Command="{Binding ReloadCommand}" />
<ComboBox DockPanel.Dock="Top" Margin="0,8" DisplayMemberPath="Id" SelectedItem="{Binding SelectedDevice}" ItemsSource="{Binding Devices}" />
<TextBlock DockPanel.Dock="Top" Text="{Binding SelectedDevice.Id, FallbackValue=-, StringFormat=SerialNumber: {0}}" />
<TextBlock DockPanel.Dock="Top" Margin="0,8" Text="{Binding SelectedDevice.Version, FallbackValue=-, StringFormat=Firmware version: {0}}" />
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Center">
<Button Padding="4,2" Margin="0,0,8,0" Content="Save pins" Command="{Binding SavePinsCommand}" />
<Button Padding="4,2" Content="Save led-counts" Command="{Binding SaveLedCountsCommand}" />
</StackPanel>
<TextBlock DockPanel.Dock="Bottom" Margin="0,8" TextWrapping="Wrap" Text="Please double check that the data above is valid (pin number exists on the device, led-count is in the range 0-255) before saving or you might corrupt the firmware of the device." />
<ItemsControl ItemsSource="{Binding Channels}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:Channel}">
<StackPanel Orientation="Horizontal">
<TextBlock Width="80" FontWeight="Bold" Text="{Binding Index, StringFormat=Channel {0}}" />
<TextBlock Text="Pin: " />
<TextBox Margin="0,0,16,0" Width="40" Text="{Binding Pin}" />
<TextBlock Text="Led-Count: " />
<TextBox Margin="0,0,16,0" Width="40" Text="{Binding LedCount}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DockPanel>
</Window>

View File

@ -0,0 +1,12 @@
using System.Windows;
namespace PicoPiConfig
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using HidSharp;
using RGB.NET.Devices.PicoPi;
namespace PicoPiConfig
{
public class MainWindowViewModel : INotifyPropertyChanged
{
#region Properties & Fields
private List<PicoPiSDK>? _devices;
public List<PicoPiSDK>? Devices
{
get => _devices;
set
{
_devices = value;
OnPropertyChanged();
}
}
private PicoPiSDK? _selectedDevice;
public PicoPiSDK? SelectedDevice
{
get => _selectedDevice;
set
{
_selectedDevice = value;
OnPropertyChanged();
ReloadChannels();
}
}
private List<Channel>? _channels;
public List<Channel>? Channels
{
get => _channels;
set
{
_channels = value;
OnPropertyChanged();
}
}
#endregion
#region Commands
private ActionCommand? _reloadCommand;
public ActionCommand ReloadCommand => _reloadCommand ??= new ActionCommand(Reload);
private ActionCommand? _savePinsCommand;
public ActionCommand SavePinsCommand => _savePinsCommand ??= new ActionCommand(SavePins);
private ActionCommand? _saveLedCountsCommand;
public ActionCommand SaveLedCountsCommand => _saveLedCountsCommand ??= new ActionCommand(SaveLedCounts);
#endregion
#region Constructors
public MainWindowViewModel()
{
Reload();
}
#endregion
#region Methods
private void Reload()
{
if (Devices != null)
foreach (PicoPiSDK sdk in Devices) sdk.Dispose();
Devices = DeviceList.Local.GetHidDevices(PicoPiSDK.VENDOR_ID, PicoPiSDK.HID_BULK_CONTROLLER_PID).Select(d => new PicoPiSDK(d)).ToList();
SelectedDevice = Devices.FirstOrDefault();
}
private void ReloadChannels()
{
Channels = SelectedDevice?.Channels.Select(c => new Channel(c.channel, c.pin, c.ledCount)).ToList();
}
private void SavePins()
{
if (Channels == null) return;
try
{
SelectedDevice?.SetPins(Channels.Select(c => (c.Index, c.Pin)).ToArray());
MessageBox.Show("Pins saved!\r\nRestart/Reconnect the device for the changes to take effect.", "Pins", MessageBoxButton.OK);
}
catch (Exception ex)
{
MessageBox.Show($"Failed saving pins:\r\n{ex.StackTrace}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void SaveLedCounts()
{
if (Channels == null) return;
try
{
SelectedDevice?.SetLedCounts(Channels.Select(c => (c.Index, c.LedCount)).ToArray());
MessageBox.Show("Led-counts saved!", "Led-counts", MessageBoxButton.OK);
}
catch (Exception ex)
{
MessageBox.Show($"Failed saving led-counts:\r\n{ex.StackTrace}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
#endregion
#region PropertyChanged
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
#endregion
}
}

View File

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<OutputPath>..\build\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'">
<DefineConstants>$(DefineConstants);TRACE;DEBUG</DefineConstants>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<NoWarn>$(NoWarn);CS1591;CS1572;CS1573</NoWarn>
<DefineConstants>$(DefineConstants);RELEASE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="HidSharp" Version="2.1.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31025.194
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PicoPiConfig", "PicoPiConfig.csproj", "{EF9724FB-E2EE-4590-B3D2-3FE683DCA0D6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{EF9724FB-E2EE-4590-B3D2-3FE683DCA0D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EF9724FB-E2EE-4590-B3D2-3FE683DCA0D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EF9724FB-E2EE-4590-B3D2-3FE683DCA0D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EF9724FB-E2EE-4590-B3D2-3FE683DCA0D6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {62E26A26-66C1-4416-A1E5-F53902E13E17}
EndGlobalSection
EndGlobal

201
PicoPiConfig/PicoPiSDK.cs Normal file
View File

@ -0,0 +1,201 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using HidSharp;
//TODO DarthAffe 24.04.2021: Replace with RGB.NET PicoPiSDK once it's merged to main
namespace RGB.NET.Devices.PicoPi
{
public class PicoPiSDK : IDisposable
{
#region Constants
public const int VENDOR_ID = 0x1209;
public const int HID_BULK_CONTROLLER_PID = 0x2812;
private const byte COMMAND_CHANNEL_COUNT = 0x01;
private const byte COMMAND_LEDCOUNTS = 0x0A;
private const byte COMMAND_PINS = 0x0B;
private const byte COMMAND_ID = 0x0E;
private const byte COMMAND_VERSION = 0x0F;
private const byte COMMAND_UPDATE = 0x01;
private const byte COMMAND_UPDATE_BULK = 0x02;
#endregion
#region Properties & Fields
private readonly HidDevice _hidDevice;
private readonly HidStream _hidStream;
private readonly byte[] _hidSendBuffer;
private readonly byte[] _bulkSendBuffer;
private int _bulkTransferLength = 0;
public string Id { get; }
public int Version { get; }
public IReadOnlyList<(int channel, int ledCount, int pin)> Channels { get; }
#endregion
#region Constructors
public PicoPiSDK(HidDevice device)
{
this._hidDevice = device;
_hidSendBuffer = new byte[_hidDevice.GetMaxOutputReportLength() - 1];
_hidStream = _hidDevice.Open();
Id = GetId();
Version = GetVersion();
Channels = new ReadOnlyCollection<(int channel, int ledCount, int pin)>(GetChannels().ToList());
_bulkSendBuffer = new byte[(Channels.Sum(c => c.ledCount + 1) * 3) + 5];
}
#endregion
#region Methods
public void SetLedCounts(params (int channel, int ledCount)[] ledCounts)
{
byte[] data = new byte[Channels.Count + 2];
data[1] = COMMAND_LEDCOUNTS;
foreach ((int channel, int ledCount, _) in Channels)
data[channel + 1] = (byte)ledCount;
foreach ((int channel, int ledCount) in ledCounts)
data[channel + 1] = (byte)ledCount;
SendHID(data);
}
public void SetPins(params (int channel, int pin)[] pins)
{
byte[] data = new byte[Channels.Count + 2];
data[1] = COMMAND_PINS;
foreach ((int channel, _, int pin) in Channels)
data[channel + 1] = (byte)pin;
foreach ((int channel, int pin) in pins)
data[channel + 1] = (byte)pin;
SendHID(data);
}
private string GetId()
{
SendHID(0x00, COMMAND_ID);
return ConversionHelper.ToHex(Read().Skip(1).Take(8).ToArray());
}
private int GetVersion()
{
SendHID(0x00, COMMAND_VERSION);
return Read()[1];
}
private IEnumerable<(int channel, int ledCount, int pin)> GetChannels()
{
SendHID(0x00, COMMAND_CHANNEL_COUNT);
int channelCount = Read()[1];
for (int i = 1; i <= channelCount; i++)
{
SendHID(0x00, (byte)((i << 4) | COMMAND_LEDCOUNTS));
int ledCount = Read()[1];
SendHID(0x00, (byte)((i << 4) | COMMAND_PINS));
int pin = Read()[1];
yield return (i, ledCount, pin);
}
}
public void SendHidUpdate(in Span<byte> data, int channel, int chunk, bool update)
{
if (data.Length == 0) return;
Span<byte> sendBuffer = _hidSendBuffer;
sendBuffer[0] = 0x00;
sendBuffer[1] = (byte)((channel << 4) | COMMAND_UPDATE);
sendBuffer[2] = update ? (byte)1 : (byte)0;
sendBuffer[3] = (byte)chunk;
data.CopyTo(sendBuffer.Slice(4, data.Length));
SendHID(_hidSendBuffer);
}
private void SendHID(params byte[] data) => _hidStream.Write(data);
private byte[] Read() => _hidStream.Read();
public void Dispose()
{
_hidStream.Dispose();
}
#endregion
}
/// <summary>
/// Contains helper methods for converting things.
/// </summary>
public static class ConversionHelper
{
#region Methods
// Source: https://web.archive.org/web/20180224104425/https://stackoverflow.com/questions/623104/byte-to-hex-string/3974535
/// <summary>
/// Converts an array of bytes to a HEX-representation.
/// </summary>
/// <param name="bytes">The array of bytes.</param>
/// <returns>The HEX-representation of the provided bytes.</returns>
public static string ToHex(params byte[] bytes)
{
char[] c = new char[bytes.Length * 2];
for (int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
{
byte b = ((byte)(bytes[bx] >> 4));
c[cx] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(bytes[bx] & 0x0F));
c[++cx] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
return new string(c);
}
// Source: https://web.archive.org/web/20180224104425/https://stackoverflow.com/questions/623104/byte-to-hex-string/3974535
/// <summary>
/// Converts the HEX-representation of a byte array to that array.
/// </summary>
/// <param name="hexString">The HEX-string to convert.</param>
/// <returns>The correspondending byte array.</returns>
public static byte[] HexToBytes(ReadOnlySpan<char> hexString)
{
if ((hexString.Length == 0) || ((hexString.Length % 2) != 0))
return Array.Empty<byte>();
byte[] buffer = new byte[hexString.Length / 2];
for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
{
// Convert first half of byte
char c = hexString[sx];
buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? ((c - 'a') + 10) : ((c - 'A') + 10)) : (c - '0')) << 4);
// Convert second half of byte
c = hexString[++sx];
buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? ((c - 'a') + 10) : ((c - 'A') + 10)) : (c - '0'));
}
return buffer;
}
#endregion
}
}