This commit is contained in:
BlubbFish 2017-09-26 20:21:42 +02:00
parent e144bde202
commit 319ca0cbbb
194 changed files with 10149 additions and 0 deletions

76
.gitignore vendored
View File

@ -3,3 +3,79 @@
################################################################################
/.svn
/.vs
/CorrelationsAttacker
/flight hands
/Utils/Utils/obj
/Utils/Utils/bin/Debug
/Utils/Utils/bin/Release/Utils.pdb
/TT-Crawler
/TestUsb
/Testconsole
/testapp
/tconv
/SWP
/svnsync
/svgb
/Spielfeld
/SmallptGPU-v1.6
/Rollmorad
/Rock_C
/RailWorks_Joystick_API
/PowerSwitcher
/Plot
/PicoSopeReader
/OpenCLNet
/OpenCLImageFilter
/OpenCLFilter
/OpenCL
/netmonitor
/mwPS
/miranda
/Matomat
/MateBeweis
/MailServer
/LFSInsim
/Joystik-Test
/helloworld
/gspylogin
/GPSViewer
/GPGPU
/GoproControl
/Gcc-Proxy
/ebbits/.vs/ebbits/v15
/ebbits/AdvancedServo-simple/obj/Debug
/Mqtt-Dashboard/.vs/Dashboard/v15
/Mqtt-Dashboard/Mqtt-Dashboard/obj
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Debug
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/ca.pem
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/cert.key
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/cert.pem
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/Dashboard.exe.config
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/Dashboard.pdb
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/M2Mqtt.Net.pdb
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/OxyPlot.pdb
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/OxyPlot.WindowsForms.pdb
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/OxyPlot.WindowsForms.xml
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/OxyPlot.xml
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/sensor.ini
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/settings.ini
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/tracings.ini
/Mqtt-Dashboard/Mqtt-Dashboard/bin/Release/Utils.pdb
/Mqtt-Dashboard/packages
/Mqtt-SWB-Dashboard/.vs
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/Debug
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/ELE
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/SWB
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/Release/Mqtt-SWB-Dashboard.exe.config
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/Release/Mqtt-SWB-Dashboard.pdb
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/Release/OxyPlot.xml
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/Release/OxyPlot.Wpf.xml
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/Release/OxyPlot.Wpf.pdb
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/Release/OxyPlot.pdb
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/bin/Release/Utils.pdb
/Mqtt-SWB-Dashboard/Mqtt-SWB-Dashboard/obj
/Mqtt-SWB-Dashboard/packages
/TimeKeeper/Arduino/Zeit/Zeit-V2/Debug
/TimeKeeper/Arduino/Zeit/Zeit-V2/__vm
/TimeKeeper/lib/System.Data.SQLite.xml

20
Kinect/Demo1/Demo1.sln Normal file
View File

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Demo1", "Demo1\Demo1.csproj", "{1D0066B4-E5EE-4F76-97E4-0372F1EFAE1E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1D0066B4-E5EE-4F76-97E4-0372F1EFAE1E}.Debug|x86.ActiveCfg = Debug|x86
{1D0066B4-E5EE-4F76-97E4-0372F1EFAE1E}.Debug|x86.Build.0 = Debug|x86
{1D0066B4-E5EE-4F76-97E4-0372F1EFAE1E}.Release|x86.ActiveCfg = Release|x86
{1D0066B4-E5EE-4F76-97E4-0372F1EFAE1E}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

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

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
namespace Demo1
{
/// <summary>
/// Interaktionslogik für "App.xaml"
/// </summary>
public partial class App : Application
{
}
}

View File

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1D0066B4-E5EE-4F76-97E4-0372F1EFAE1E}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Demo1</RootNamespace>
<AssemblyName>Demo1</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Kinect, Version=1.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files\Microsoft SDKs\Kinect\v1.7\Assemblies\Microsoft.Kinect.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="SkeletalCommonExtensions.cs" />
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="DepthFrameConverter.cs" />
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<AppDesigner Include="Properties\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,137 @@
using Microsoft.Kinect;
using System.Drawing;
namespace KinectWorkshop
{
/*public class DepthFrameConverter
{
const int RED_IDX = 2;
const int GREEN_IDX = 1;
const int BLUE_IDX = 0;
byte[] depthFrame32 = new byte[320 * 240 * 4];
// Converts a 16-bit grayscale depth frame which includes player indexes into a 32-bit frame
// that displays different players in different colors
public byte[] ConvertDepthFrameWithUser(DepthImagePixel[] depthFrame, int width, int height)
{
Color c = Color.Empty;
byte[] ret = new byte[width * height * 4];
for (int x = 1; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int i = ((y * width) + x) * 4;
short depth = (depthFrame[x + y * width]).Depth;
c = Color.Empty;
if(depth > 0 && depth <= 4000)
{
int depthdist = (int)((depth / 4090f) * 255f);
c = System.Drawing.Color.FromArgb((int)(depthdist / 2f), depthdist, (int)(depthdist * 0.7f));
}
ret[i] = c.B;
ret[i] = c.G;
ret[i] = c.R;
ret[i] = 255;
}
}
/* for (int i16 = 0, i32 = 0; i16 < depthFrame16.Length && i32 < depthFrame32.Length; i16 += 2, i32 += 4)
{
int player = depthFrame16[i16] & 0x07;
//if ((y - 1) * 320 + x * 4 == i16)
//{
// player = 8;
//}
int realDepth = (depthFrame16[i16 + 1] << 5) | (depthFrame16[i16] >> 3);
// transform 13-bit depth information into an 8-bit intensity appropriate
// for display (we disregard information in most significant bit)
byte intensity = (byte)(255 - (255 * realDepth / 0x0fff));
depthFrame32[i32 + RED_IDX] = 0;
depthFrame32[i32 + GREEN_IDX] = 0;
depthFrame32[i32 + BLUE_IDX] = 0;
// choose different display colors based on player
switch (player)
{
case 0:
depthFrame32[i32 + RED_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity / 2);
break;
case 1:
depthFrame32[i32 + RED_IDX] = intensity;
break;
case 2:
depthFrame32[i32 + GREEN_IDX] = intensity;
break;
case 3:
depthFrame32[i32 + RED_IDX] = (byte)(intensity / 4);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
break;
case 4:
depthFrame32[i32 + RED_IDX] = (byte)(intensity);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity / 4);
break;
case 5:
depthFrame32[i32 + RED_IDX] = (byte)(intensity);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 4);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
break;
case 6:
depthFrame32[i32 + RED_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
break;
case 7:
depthFrame32[i32 + RED_IDX] = (byte)(255 - intensity);
depthFrame32[i32 + GREEN_IDX] = (byte)(255 - intensity);
depthFrame32[i32 + BLUE_IDX] = (byte)(255 - intensity);
break;
case 8:
depthFrame32[i32 + RED_IDX] = 255;
depthFrame32[i32 + GREEN_IDX] = 0;
depthFrame32[i32 + BLUE_IDX] = 0;
break;
}
}
return depthFrame32;*
return ret;
}
internal byte[] ConvertDepthFrame(byte[] depthFrame16)
{
for (int i16 = 0, i32 = 0; i16 < depthFrame16.Length && i32 < depthFrame32.Length; i16 += 2, i32 += 4)
{
int realDepth = (depthFrame16[i16+1] << 8)|(depthFrame16[i16]);
//byte r = (byte)(realDepth >> 8);
//byte b = (byte)realDepth;
byte intensity = (byte)(255 - (255 * realDepth / 0x0fff));
depthFrame32[i32 + RED_IDX] = (byte)((intensity * -1) + 255);// (byte)(intensity / 2);
depthFrame32[i32 + GREEN_IDX] = (byte)((intensity * -1) + 255);// (byte)(intensity / 2);
depthFrame32[i32 + BLUE_IDX] = (byte)((intensity * -1) + 255);// (byte)(intensity / 2);
}
return depthFrame32;
}
internal byte[] ConvertDepthFrameHiddenPlayer(byte[] depthFrame16)
{
for (int i16 = 0, i32 = 0; i16 < depthFrame16.Length && i32 < depthFrame32.Length; i16 += 2, i32 += 4)
{
int realDepth = (depthFrame16[i16 + 1] << 5) | (depthFrame16[i16] >> 3);
//byte r = (byte)(realDepth >> 8);
//byte b = (byte)realDepth;
byte intensity = (byte)(255 - (255 * realDepth / 0x0fff));
depthFrame32[i32 + RED_IDX] = (byte)((intensity * -1) + 255);// (byte)(intensity / 2);
depthFrame32[i32 + GREEN_IDX] = (byte)((intensity * -1) + 255);// (byte)(intensity / 2);
depthFrame32[i32 + BLUE_IDX] = (byte)((intensity * -1) + 255);// (byte)(intensity / 2);
}
return depthFrame32;
}
}*/
}

View File

@ -0,0 +1,14 @@
<Window x:Class="Demo1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="520" Width="660" Loaded="Window_Loaded" KeyUp="Window_KeyUp">
<Grid>
<Image Name="imgDepth" Width="640" Height="480" />
<!-- <StackPanel Orientation="Vertical">
<Image Name="imgRgb" Width="320" Height="240" />
<Image Name="imgDepthPlayer" Width="320" Height="240" />
</StackPanel> -->
<Canvas Name="MainCanvas"/>
</Grid>
</Window>

View File

@ -0,0 +1,257 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;
namespace Demo1
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private KinectWorkshop.DepthFrameConverter cv = new KinectWorkshop.DepthFrameConverter();
private KinectSensor r;
//private DepthImagePixel[] depthPixels;
//private byte[] colorPixels;
//private DepthImageFormat DepthFormat = DepthImageFormat.Resolution320x240Fps30;
//private ColorImageFormat ColorFormat = ColorImageFormat.RgbResolution640x480Fps30;
//private ColorImagePoint[] colorCoordinates;
//private bool init = false;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (KinectSensor.KinectSensors.Count == 0)
{
MessageBox.Show("Keine Kinect");
return;
}
try
{
r = KinectSensor.KinectSensors[0];
r.Start();
//r.Initialize(RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseDepthAndPlayerIndex);
//r.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(r_VideoFrameReady);
//r.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
//r.DepthFrameReady += r_DepthFrameReady;
//r.DepthStream.Enable();
//r.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex);
//r.SkeletonFrameReady += r_SkeletonFrameReady;
r.SkeletonStream.Enable(new TransformSmoothParameters() { Smoothing = 0.1f });
//r.SkeletonEngine.TransformSmooth = true;
//r.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(r_SkeletonFrameReady);
//_cam = r.NuiCamera;
//r.AllFramesReady += R_AllFramesReady;
r.SkeletonFrameReady += this.r_SkeletonFrameReady;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
/*private void R_AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
if(r == null)
{
return;
}
bool depthReceived = false;
bool colorReceived = false;
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (null != depthFrame)
{
// Copy the pixel data from the image to a temporary array
depthFrame.CopyDepthImagePixelDataTo(this.depthPixels);
depthReceived = true;
if(!init) {
this.colorCoordinates = new ColorImagePoint[r.DepthStream.FramePixelDataLength];
init = true;
}
}
}
using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
{
if (null != colorFrame)
{
// Copy the pixel data from the image to a temporary array
colorFrame.CopyPixelDataTo(this.colorPixels);
colorReceived = true;
}
}
if (true == depthReceived)
{
r.CoordinateMapper.MapDepthFrameToColorFrame(
DepthFormat,
this.depthPixels,
ColorFormat,
this.colorCoordinates);
// ...
int depthIndex = x + (y * this.depthWidth);
DepthImagePixel depthPixel = this.depthPixels[depthIndex];
// scale color coordinates to depth resolution
int X = colorImagePoint.X / this.colorToDepthDivisor;
int Y = colorImagePoint.Y / this.colorToDepthDivisor;
// depthPixel is the depth for the (X,Y) pixel in the color frame
}
}*/
void r_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
SkeletonFrame skf = e.OpenSkeletonFrame();
if(skf == null)
{
return;
}
Skeleton[] sks = new Skeleton[skf.SkeletonArrayLength];
skf.CopySkeletonDataTo(sks);
this.MainCanvas.Children.Clear();
foreach (Skeleton sk in sks)
{
if (sk.TrackingState == SkeletonTrackingState.Tracked)
{
this.drawPlayer(sk);
}
}
}
private void drawPlayer(Skeleton sk)
{
this.SetPoints(sk);
this.SetLines(sk);
}
private void SetLines(Skeleton sk)
{
JointType[,] id = {
{ JointType.Head, JointType.ShoulderCenter },
{ JointType.ShoulderCenter, JointType.ShoulderLeft },
{ JointType.ShoulderCenter, JointType.ShoulderRight },
{ JointType.ShoulderLeft, JointType.ElbowLeft },
{ JointType.ShoulderRight, JointType.ElbowRight },
{ JointType.ElbowLeft, JointType.WristLeft },
{ JointType.ElbowRight, JointType.WristRight },
{ JointType.WristLeft, JointType.HandLeft },
{ JointType.WristRight, JointType.HandRight },
{ JointType.ShoulderCenter, JointType.Spine },
{ JointType.Spine, JointType.HipCenter },
{ JointType.HipCenter, JointType.HipLeft },
{ JointType.HipCenter, JointType.HipRight },
{ JointType.HipLeft, JointType.KneeLeft },
{ JointType.HipRight, JointType.KneeRight },
{ JointType.KneeLeft, JointType.AnkleLeft },
{ JointType.KneeRight, JointType.AnkleRight },
{ JointType.AnkleLeft, JointType.FootLeft },
{ JointType.AnkleRight, JointType.FootRight }
};
for (int i = 0; i < id.Length / 2; i++)
{
Joint r1 = sk.Joints[id[i, 0]].ScaleTo(640, 480);
Joint r2 = sk.Joints[id[i, 1]].ScaleTo(640, 480);
/**** */
Line l = new Line();
l.Stroke = Brushes.Blue;
l.StrokeThickness = 5.0;
l.Y1 = r1.Position.Y;
l.X1 = r1.Position.X;
l.Y2 = r2.Position.Y;
l.X2 = r2.Position.X;
/**** */
this.MainCanvas.Children.Add(l);
}
}
private void SetPoints(Skeleton sk)
{
foreach (Joint joint in sk.Joints)
{
Joint p = joint.ScaleTo(640, 480);
Ellipse e = new Ellipse();
e.Fill = Brushes.Red;
e.Stroke = Brushes.Black;
e.Height = 10;
e.Width = 10;
Canvas.SetLeft(e, p.Position.X - e.Width / 2);
Canvas.SetTop(e, p.Position.Y - e.Height / 2);
this.MainCanvas.Children.Add(e);
}
}
/*void r_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
{
//PlanarImage img = e.ImageFrame.Image;
DepthImageFrame img = e.OpenDepthImageFrame();
if(img == null)
{
return;
}
DepthImagePixel[] bs = new DepthImagePixel[img.PixelDataLength];
img.CopyDepthImagePixelDataTo(bs);
byte[] bh = cv.ConvertDepthFrameWithUser(bs, img.Width, img.Height);
imgDepth.Source = BitmapSource.Create(img.Width, img.Height, 96, 96, PixelFormats.Bgr32, null, bh, img.Width * 4);
//bh = cv.ConvertDepthFrameHiddenPlayer(img.Bits);
//byte[] bh = cv.ConvertDepthFrame(img.Bits);
//imgDepthPlayer.Source = BitmapSource.Create(img.Width, img.Height,
// 96, 96, PixelFormats.Bgr32, null,
// bh, img.Width * 4);
}*/
private void Window_KeyUp(object sender, KeyEventArgs e)
{
try
{
if (e.Key == Key.Up)
{
int k = r.ElevationAngle;
k++;
r.ElevationAngle = k;
}
if (e.Key == Key.Down)
r.ElevationAngle -= 1;
}
catch (ArgumentOutOfRangeException outOfRangeException)
{
MessageBox.Show(outOfRangeException.Message);
}
catch (Exception) { }
}
/*void r_VideoFrameReady(object sender, ImageFrameReadyEventArgs e)
{
PlanarImage img = e.ImageFrame.Image;
imgRgb.Source = BitmapSource.Create(img.Width, img.Height,
96, 96, PixelFormats.Bgr32, null,
img.Bits, img.Width * img.BytesPerPixel);
}*/
}
}

View File

@ -0,0 +1,55 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("Demo1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Demo1")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
//Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie
//<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei
//in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch
//(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung
//des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile,
//sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher
//(wird verwendet, wenn eine Ressource auf der Seite
// oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.)
ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs
//(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem
// designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.)
)]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.239
//
// Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn
// der Code neu generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Demo1.Properties
{
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder-Klasse
// über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der Option /str erneut aus, oder erstellen Sie Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Demo1.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenlookups, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.239
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Demo1.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,41 @@
using Microsoft.Kinect;
using System.Windows;
namespace Demo1
{
internal static class SkeletalCommonExtensions
{
public static Joint ScaleTo(this Joint joint, int width, int height, float skeletonMaxX, float skeletonMaxY)
{
SkeletonPoint pos = new SkeletonPoint()
{
X = Scale(width, skeletonMaxX, joint.Position.X),
Y = Scale(height, skeletonMaxY, -joint.Position.Y),
Z = joint.Position.Z
};
Joint j = new Joint()
{
TrackingState = joint.TrackingState,
Position = pos
};
return j;
}
public static Joint ScaleTo(this Joint joint, int width, int height)
{
return ScaleTo(joint, width, height, 1.0f, 1.0f);
}
private static float Scale(int maxPixel, float maxSkeleton, float position)
{
float value = ((((maxPixel / maxSkeleton) / 2) * position) + (maxPixel / 2));
if (value > maxPixel)
return maxPixel;
if (value < 0)
return 0;
return value;
}
}
}

20
Kinect/Demo2/Demo2.sln Normal file
View File

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Demo2", "Demo2\Demo2.csproj", "{12018BA3-A02D-488C-83F6-1799D344C1C3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{12018BA3-A02D-488C-83F6-1799D344C1C3}.Debug|x86.ActiveCfg = Debug|x86
{12018BA3-A02D-488C-83F6-1799D344C1C3}.Debug|x86.Build.0 = Debug|x86
{12018BA3-A02D-488C-83F6-1799D344C1C3}.Release|x86.ActiveCfg = Release|x86
{12018BA3-A02D-488C-83F6-1799D344C1C3}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{12018BA3-A02D-488C-83F6-1799D344C1C3}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Demo2</RootNamespace>
<AssemblyName>Demo2</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Research.Kinect, Version=1.0.0.45, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Kinect.Nui;
namespace Demo2
{
class Program
{
static void Main(string[] args)
{
if (Runtime.Kinects.Count == 0)
{
Console.WriteLine("KEine Kinect");
return;
}
Runtime r = Runtime.Kinects[0];
r.Initialize(RuntimeOptions.UseSkeletalTracking);
r.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(r_SkeletonFrameReady);
r.SkeletonEngine.TransformSmooth = true;
Console.ReadLine();
r.Uninitialize();
}
static void r_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
foreach (SkeletonData sk in e.SkeletonFrame.Skeletons)
{
if (sk.TrackingState == SkeletonTrackingState.Tracked)
{
Joint l = sk.Joints[JointID.HandLeft];
Joint r = sk.Joints[JointID.HandRight];
Console.WriteLine("Left Hand: X:{0}, Y:{1}, Z:{2}", l.Position.X, l.Position.Y, l.Position.Z);
Console.WriteLine("Right Hand: X:{0}, Y:{1}, Z:{2}", r.Position.X, r.Position.Y, r.Position.Z);
}
}
Console.WriteLine();
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("Demo2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Demo2")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("c0c8b6f9-5275-4f3b-a622-0a78d2a3a3dd")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

20
Kinect/Demo3/Demo3.sln Normal file
View File

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Demo3", "Demo3\Demo3.csproj", "{33D30437-2141-4BEE-B4DE-FBF5B01F7A8C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{33D30437-2141-4BEE-B4DE-FBF5B01F7A8C}.Debug|x86.ActiveCfg = Debug|x86
{33D30437-2141-4BEE-B4DE-FBF5B01F7A8C}.Debug|x86.Build.0 = Debug|x86
{33D30437-2141-4BEE-B4DE-FBF5B01F7A8C}.Release|x86.ActiveCfg = Release|x86
{33D30437-2141-4BEE-B4DE-FBF5B01F7A8C}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{33D30437-2141-4BEE-B4DE-FBF5B01F7A8C}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Demo3</RootNamespace>
<AssemblyName>Demo3</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Research.Kinect, Version=1.0.0.45, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="Microsoft.Speech, Version=10.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files\Microsoft Speech Platform SDK\Assembly\Microsoft.Speech.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SpeechToText.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo3
{
class Program
{
static void Main(string[] args)
{
KinectWorkshop.SpeechToText stt = new KinectWorkshop.SpeechToText();
stt.TextRecognized += new EventHandler<KinectWorkshop.SpeechToText.TextRecognizedArgs>(stt_TextRecognized);
stt.Start();
Console.ReadLine();
stt.Stop();
}
static void stt_TextRecognized(object sender, KinectWorkshop.SpeechToText.TextRecognizedArgs e)
{
Console.WriteLine(e.Verb);
switch (e.Verb)
{
case KinectWorkshop.SpeechToText.Verbs.None:
break;
case KinectWorkshop.SpeechToText.Verbs.PreviousSlide:
break;
case KinectWorkshop.SpeechToText.Verbs.NextSlide:
break;
default:
break;
}
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("Demo3")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Demo3")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("1fd608c9-3dd2-4d4b-b7a0-c368ff56a377")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.Research.Kinect.Audio;
using Microsoft.Speech.AudioFormat;
using Microsoft.Speech.Recognition;
namespace KinectWorkshop
{
public class SpeechToText
{
public enum Verbs
{
None = 0,
PreviousSlide,
NextSlide
};
Dictionary<string, Verbs> SinglePhrases = new Dictionary<string, Verbs>()
{
{"previous slide", Verbs.PreviousSlide},
{"next slide", Verbs.NextSlide}
};
public class TextRecognizedArgs : EventArgs
{
public Verbs Verb { get; set; }
public string Phrase { get; set; }
public string Matched {get; set; }
}
public event EventHandler<TextRecognizedArgs> TextRecognized;
private KinectAudioSource kinectSource;
private SpeechRecognitionEngine sre;
private const string RecognizerId = "SR_MS_en-US_Kinect_10.0";
public SpeechToText()
{
RecognizerInfo ri = SpeechRecognitionEngine.InstalledRecognizers().Where(r => r.Id == RecognizerId).FirstOrDefault();
if (ri == null)
return;
sre = new SpeechRecognitionEngine(ri.Id);
var singlePhrases = new Choices();
foreach (var phrase in SinglePhrases)
singlePhrases.Add(phrase.Key);
var g = new Grammar(new GrammarBuilder(singlePhrases));
sre.LoadGrammar(g);
sre.SpeechRecognized += sre_SpeechRecognized;
sre.SpeechRecognitionRejected += new EventHandler<SpeechRecognitionRejectedEventArgs>(sre_SpeechRecognitionRejected);
}
private void StartSST()
{
kinectSource = new KinectAudioSource();
kinectSource.SystemMode = SystemMode.OptibeamArrayOnly;
kinectSource.FeatureMode = true;
kinectSource.AutomaticGainControl = false;
kinectSource.MicArrayMode = MicArrayMode.MicArrayAdaptiveBeam;
var kinectStream = kinectSource.Start();
sre.SetInputToAudioStream(kinectStream, new SpeechAudioFormatInfo(
EncodingFormat.Pcm, 16000, 16, 1,
32000, 2, null));
sre.RecognizeAsync(RecognizeMode.Multiple);
//const double alpha = 0.35;
//double angle = 0.0;
//while (true)
//{
// if (kinectSource.SoundSourcePositionConfidence > 0.5)
// {
// double a = alpha*kinectSource.SoundSourcePositionConfidence;
// angle = (1 - a) * angle + a * kinectSource.SoundSourcePosition;
// Console.WriteLine(angle + ":" + kinectSource.MicArrayBeamAngle);
// }
// System.Threading.Thread.Sleep(50);
//}
}
public void Start()
{
var t = new Thread(StartSST);
t.Start();
}
public void Stop()
{
if (sre != null)
{
sre.RecognizeAsyncCancel();
sre.RecognizeAsyncStop();
kinectSource.Dispose();
}
}
void sre_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
var said = new TextRecognizedArgs();
said.Verb = Verbs.None;
said.Matched = "?";
TextRecognized(new object(), said);
Console.WriteLine("\nSpeech Rejected");
}
void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (TextRecognized == null)
return;
var said = new TextRecognizedArgs();
said.Verb = Verbs.None;
said.Phrase = e.Result.Text;
bool found = false;
foreach (var phrase in SinglePhrases)
{
if (e.Result.Text.Contains(phrase.Key))
{
said.Verb = phrase.Value;
found = true;
break;
}
}
if (!found)
return;
TextRecognized(new object(), said);
}
}
}

20
Kinect/Demo4/Demo4.sln Normal file
View File

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Demo4", "Demo4\Demo4.csproj", "{FBF0FD4F-54D6-4077-AE63-F98C1FD10FBC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FBF0FD4F-54D6-4077-AE63-F98C1FD10FBC}.Debug|x86.ActiveCfg = Debug|x86
{FBF0FD4F-54D6-4077-AE63-F98C1FD10FBC}.Debug|x86.Build.0 = Debug|x86
{FBF0FD4F-54D6-4077-AE63-F98C1FD10FBC}.Release|x86.ActiveCfg = Release|x86
{FBF0FD4F-54D6-4077-AE63-F98C1FD10FBC}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{FBF0FD4F-54D6-4077-AE63-F98C1FD10FBC}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Demo4</RootNamespace>
<AssemblyName>Demo4</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Research.Kinect, Version=1.0.0.45, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="KeySender.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WindowFinder.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace KinectWorkshop
{
public enum VirtualKey : ushort
{
SHIFT = 0x10,
CONTROL = 0x11,
MENU = 0x12,
ESCAPE = 0x1B,
BACK = 0x08,
TAB = 0x09,
RETURN = 0x0D,
PRIOR = 0x21,
NEXT = 0x22,
END = 0x23,
HOME = 0x24,
LEFT = 0x25,
UP = 0x26,
RIGHT = 0x27,
DOWN = 0x28,
SELECT = 0x29,
PRINT = 0x2A,
EXECUTE = 0x2B,
SNAPSHOT = 0x2C,
INSERT = 0x2D,
DELETE = 0x2E,
HELP = 0x2F,
NUMPAD0 = 0x60,
NUMPAD1 = 0x61,
NUMPAD2 = 0x62,
NUMPAD3 = 0x63,
NUMPAD4 = 0x64,
NUMPAD5 = 0x65,
NUMPAD6 = 0x66,
NUMPAD7 = 0x67,
NUMPAD8 = 0x68,
NUMPAD9 = 0x69,
MULTIPLY = 0x6A,
ADD = 0x6B,
SEPARATOR = 0x6C,
SUBTRACT = 0x6D,
DECIMAL = 0x6E,
DIVIDE = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
OEM_1 = 0xBA, // ',:' for US
OEM_PLUS = 0xBB, // '+' any country
OEM_COMMA = 0xBC, // ',' any country
OEM_MINUS = 0xBD, // '-' any country
OEM_PERIOD = 0xBE, // '.' any country
OEM_2 = 0xBF, // '/?' for US
OEM_3 = 0xC0, // '`~' for US
MEDIA_NEXT_TRACK = 0xB0,
MEDIA_PREV_TRACK = 0xB1,
MEDIA_STOP = 0xB2,
MEDIA_PLAY_PAUSE = 0xB3,
LWIN =0x5B,
RWIN =0x5C
}
class KeySender
{
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
public struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public long time;
public uint dwExtraInfo;
}
[StructLayout(LayoutKind.Explicit, Size = 28)]
public struct INPUT
{
[FieldOffset(0)]
public uint type;
[FieldOffset(4)]
public KEYBDINPUT ki;
}
public enum Win32Consts : int
{
INPUT_MOUSE = 0,
INPUT_KEYBOARD = 1,
INPUT_HARDWARE = 2,
}
public static void Send(VirtualKey key)
{
INPUT structInput = new INPUT();
structInput.type = (uint)Win32Consts.INPUT_KEYBOARD;
structInput.ki.wVk = (ushort)key;
SendInput(1, ref structInput, Marshal.SizeOf(structInput));
}
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Kinect.Nui;
namespace Demo4
{
class Program
{
private static DateTime lastTimeHit;
static void Main(string[] args)
{
if (Runtime.Kinects.Count == 0)
{
Console.WriteLine("Keine Kinect");
return;
}
Runtime r = Runtime.Kinects[0];
r.Initialize(RuntimeOptions.UseSkeletalTracking);
r.SkeletonEngine.TransformSmooth = true;
r.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(r_SkeletonFrameReady);
Console.ReadLine();
r.Uninitialize();
}
static void r_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
if ((DateTime.Now - lastTimeHit).Seconds < 5)
{
return;
}
foreach (SkeletonData s in e.SkeletonFrame.Skeletons)
{
if (s.TrackingState == SkeletonTrackingState.Tracked)
{
Joint rh = s.Joints[JointID.HandRight];
Joint h = s.Joints[JointID.Head];
if (rh.Position.Y > h.Position.Y)
{
lastTimeHit = DateTime.Now;
Console.WriteLine("Hand über kopf");
IntPtr hwnd = KinectWorkshop.WindowFinder.StartingWith("Unbenannt");
KinectWorkshop.WindowFinder.SetFocusOn(hwnd);
KinectWorkshop.KeySender.Send(KinectWorkshop.VirtualKey.NEXT);
}
}
}
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("Demo4")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Demo4")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("aa436451-b12f-49c9-aa04-728a278274ee")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace KinectWorkshop
{
class WindowFinder
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.Dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, [MarshalAsAttribute(UnmanagedType.Struct)] ref SearchData data);
private delegate bool EnumWindowsProc(IntPtr hWnd, ref SearchData data);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);
struct SearchData
{
public string TitlePrefix;
public IntPtr hWnd;
}
static bool EnumProc(IntPtr hWnd, ref SearchData data)
{
StringBuilder sb = new StringBuilder(1024);
GetWindowText(hWnd, sb, sb.Capacity);
if (sb.ToString().StartsWith(data.TitlePrefix))
{
data.hWnd = hWnd;
return false;
}
return true;
}
public static IntPtr StartingWith(string prefix)
{
SearchData sd = new SearchData { TitlePrefix = prefix };
EnumWindows(new EnumWindowsProc(EnumProc), ref sd);
return sd.hWnd;
}
public static void SetFocusOn(IntPtr hwnd)
{
SetFocus(hwnd);
}
}
}

20
Kinect/Demo5/Demo5.sln Normal file
View File

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Demo5", "Demo5\Demo5.csproj", "{CF078AB1-B658-48F7-89C1-45610E317B3D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CF078AB1-B658-48F7-89C1-45610E317B3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CF078AB1-B658-48F7-89C1-45610E317B3D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF078AB1-B658-48F7-89C1-45610E317B3D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF078AB1-B658-48F7-89C1-45610E317B3D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo5
{
public class Class1
{
}
}

View File

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{CF078AB1-B658-48F7-89C1-45610E317B3D}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Demo5</RootNamespace>
<AssemblyName>Demo5</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<RegisterForComInterop>true</RegisterForComInterop>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>KinectDemo5.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Research.Kinect, Version=1.0.0.45, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Class1.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="KinectControl.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="KinectControl.Designer.cs">
<DependentUpon>KinectControl.cs</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="KinectControl.resx">
<DependentUpon>KinectControl.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="KinectDemo5.snk" />
</ItemGroup>
<ItemGroup>
<Content Include="TextFile1.txt" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,72 @@
namespace Demo5
{
partial class KinectControl
{
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Komponenten-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.lbHandLeft = new System.Windows.Forms.Label();
this.lbHandRight = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lbHandLeft
//
this.lbHandLeft.AutoSize = true;
this.lbHandLeft.Location = new System.Drawing.Point(3, 15);
this.lbHandLeft.Name = "lbHandLeft";
this.lbHandLeft.Size = new System.Drawing.Size(59, 13);
this.lbHandLeft.TabIndex = 0;
this.lbHandLeft.Text = "lbHandLeft";
//
// lbHandRight
//
this.lbHandRight.AutoSize = true;
this.lbHandRight.Location = new System.Drawing.Point(84, 15);
this.lbHandRight.Name = "lbHandRight";
this.lbHandRight.Size = new System.Drawing.Size(66, 13);
this.lbHandRight.TabIndex = 1;
this.lbHandRight.Text = "lbHandRight";
//
// KinectControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.lbHandRight);
this.Controls.Add(this.lbHandLeft);
this.Name = "KinectControl";
this.Size = new System.Drawing.Size(150, 46);
this.Load += new System.EventHandler(this.KinectControl_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lbHandLeft;
private System.Windows.Forms.Label lbHandRight;
}
}

View File

@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Reflection;
using Microsoft.Research.Kinect.Nui;
namespace Demo5
{
[ProgId("Demo5.KinectControl")]
[Guid("577410DD-1FC4-4B28-A0FE-9D0F78CEEDB5")]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public partial class KinectControl : UserControl
{
private string text;
[ComRegisterFunction()]
public static void RegisterClass(string key)
{
StringBuilder sb = new StringBuilder(key);
sb.Replace(@"HKEY_CLASSES_ROOT\", "");
RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(), true);
RegistryKey ctrl = k.CreateSubKey("Control");
ctrl.Close();
RegistryKey inprocServer32 = k.OpenSubKey("InprocServer32", true);
inprocServer32.SetValue("CodeBase", Assembly.GetExecutingAssembly().CodeBase);
inprocServer32.Close();
k.Close();
}
[ComUnregisterFunction()]
public static void UnregisterClass(string key)
{
StringBuilder sb = new StringBuilder(key);
sb.Replace(@"HKEY_CLASSES_ROOT\", "");
RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(), true);
k.DeleteSubKey("Control", false);
RegistryKey inprocServer32 = k.OpenSubKey("InprocServer32", true);
inprocServer32.DeleteSubKey("CodeBase", false);
inprocServer32.Close();
k.Close();
}
public KinectControl()
{
InitializeComponent();
}
private void KinectControl_Load(object sender, EventArgs e)
{
Runtime r = Runtime.Kinects[0];
r.Initialize(RuntimeOptions.UseSkeletalTracking);
r.SkeletonEngine.TransformSmooth = true;
r.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(r_SkeletonFrameReady);
}
void r_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
foreach (SkeletonData s in e.SkeletonFrame.Skeletons)
{
if (s.TrackingState == SkeletonTrackingState.Tracked)
{
Joint lh = s.Joints[JointID.HandLeft];
this.text = String.Format("X: {0}, Y: {1}", lh.Position.X, lh.Position.Y);
this.Invoke(new CallMe(SetText));
}
}
}
void SetText()
{
lbHandLeft.Text = this.text;
}
delegate void CallMe();
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

Binary file not shown.

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("Demo5")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Demo5")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("75922dfb-1c32-4750-9af7-48d92b2c969d")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,2 @@
regasm demo.dll
regasm /u demo.dll

20
Kinect/Demo6/Demo6.sln Normal file
View File

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Demo6", "Demo6\Demo6.csproj", "{9775B675-99C5-4DAD-8F6E-757002AE51D4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9775B675-99C5-4DAD-8F6E-757002AE51D4}.Debug|x86.ActiveCfg = Debug|x86
{9775B675-99C5-4DAD-8F6E-757002AE51D4}.Debug|x86.Build.0 = Debug|x86
{9775B675-99C5-4DAD-8F6E-757002AE51D4}.Release|x86.ActiveCfg = Release|x86
{9775B675-99C5-4DAD-8F6E-757002AE51D4}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

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

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
namespace Demo6
{
/// <summary>
/// Interaktionslogik für "App.xaml"
/// </summary>
public partial class App : Application
{
}
}

View File

@ -0,0 +1,104 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{9775B675-99C5-4DAD-8F6E-757002AE51D4}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Demo6</RootNamespace>
<AssemblyName>Demo6</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Research.Kinect, Version=1.0.0.45, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<AppDesigner Include="Properties\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,8 @@
<Window x:Class="Demo6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="250" Width="330" Loaded="Window_Loaded">
<StackPanel Orientation="Horizontal">
<Image Name="imgDepth" Width="320" Height="240" />
</StackPanel>
</Window>

View File

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Research.Kinect.Nui;
namespace Demo6
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (Runtime.Kinects.Count == 0)
{
MessageBox.Show("Keine Kinect");
return;
}
Runtime r = Runtime.Kinects[0];
r.Initialize(RuntimeOptions.UseDepth);
r.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.Depth);
r.DepthFrameReady += new EventHandler<ImageFrameReadyEventArgs>(r_DepthFrameReady);
}
void r_DepthFrameReady(object sender, ImageFrameReadyEventArgs e)
{
PlanarImage img = e.ImageFrame.Image;
//byte[] b = cv.ConvertDepthFrame(img.Bits);
imgDepth.Source = BitmapSource.Create(img.Width, img.Height,
96, 96, PixelFormats.Bgr32, null,
b, img.Width * img.BytesPerPixel);
}
}
}

View File

@ -0,0 +1,55 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("Demo6")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Demo6")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
//Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie
//<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei
//in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch
//(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung
//des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile,
//sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher
//(wird verwendet, wenn eine Ressource auf der Seite
// oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.)
ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs
//(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem
// designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.)
)]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.239
//
// Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn
// der Code neu generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Demo6.Properties
{
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder-Klasse
// über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der Option /str erneut aus, oder erstellen Sie Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Demo6.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenlookups, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.239
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Demo6.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dashboard", "Mqtt-Dashboard\Dashboard.csproj", "{16AC0F61-0B60-4A1D-A827-B3BFDBA9AAC7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils", "..\Utils\Utils\Utils.csproj", "{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{16AC0F61-0B60-4A1D-A827-B3BFDBA9AAC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{16AC0F61-0B60-4A1D-A827-B3BFDBA9AAC7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{16AC0F61-0B60-4A1D-A827-B3BFDBA9AAC7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{16AC0F61-0B60-4A1D-A827-B3BFDBA9AAC7}.Release|Any CPU.Build.0 = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>

View File

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
namespace Dashboard.Connector {
public abstract class ADataBackend {
public abstract event MqttMessage MessageIncomming;
public abstract event MqttMessage MessageSending;
public delegate void MqttMessage(Object sender, MqttEventArgs e);
public static ADataBackend GetInstance(Dictionary<String, String> dictionary) {
String object_sensor = "Dashboard.Connector." + Char.ToUpper(dictionary["type"][0]) + dictionary["type"].Substring(1).ToLower();
Type t = null;
try {
t = Type.GetType(object_sensor, true);
} catch (TypeLoadException) {
throw new ArgumentException("settings.ini: " + dictionary["type"] + " is not a Connector");
}
return (ADataBackend)t.GetConstructor(new Type[] { typeof(Dictionary<String, String>) }).Invoke(new Object[] { dictionary });
}
public abstract void Send(String topic, String data);
public abstract void Dispose();
}
public class MqttEventArgs : EventArgs {
public MqttEventArgs() : base() { }
public MqttEventArgs(String message, String topic) {
this.Topic = topic;
this.Message = message;
this.Date = DateTime.Now;
}
public String Topic { get; private set; }
public String Message { get; private set; }
public DateTime Date { get; private set; }
}
}

View File

@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace Dashboard.Connector {
class Mosquitto : ADataBackend, IDisposable {
private Process p;
private String message;
public override event MqttMessage MessageIncomming;
public override event MqttMessage MessageSending;
public Mosquitto(Dictionary<String, String> mqtt_settings) {
this.settings = mqtt_settings;
//mosquitto_sub --cafile ca.pem --cert cert.pem --key cert.key -h swb.broker.flex4grid.eu -p 8883 -t "#" -v -d
this.message = "";
this.p = new Process();
this.p.StartInfo.FileName = "mosquitto_sub";
String args = "-h " + this.settings["server"]+" ";
if(this.settings.ContainsKey("port")) {
args += "-p "+ this.settings["port"]+" ";
}
if (this.settings.ContainsKey("cafile")) {
args += "--cafile " + this.settings["cafile"] + " ";
}
if (this.settings.ContainsKey("cert")) {
args += "--cert " + this.settings["cert"] + " ";
}
if (this.settings.ContainsKey("key")) {
args += "--key " + this.settings["key"] + " ";
}
this.p.StartInfo.Arguments = args+"-t \"#\" -v -d";
this.p.StartInfo.CreateNoWindow = true;
this.p.StartInfo.UseShellExecute = false;
this.p.StartInfo.RedirectStandardOutput = true;
this.p.StartInfo.RedirectStandardError = true;
this.p.OutputDataReceived += this.P_OutputDataReceived;
this.p.ErrorDataReceived += this.P_ErrorDataReceived;
this.p.Start();
this.p.BeginOutputReadLine();
}
public override void Send(String topic, String data) {
Process send = new Process();
send.StartInfo.FileName = "mosquitto_pub";
String args = "-h " + this.settings["server"] + " ";
if (this.settings.ContainsKey("port")) {
args += "-p " + this.settings["port"] + " ";
}
if (this.settings.ContainsKey("cafile")) {
args += "--cafile " + this.settings["cafile"] + " ";
}
if (this.settings.ContainsKey("cert")) {
args += "--cert " + this.settings["cert"] + " ";
}
if (this.settings.ContainsKey("key")) {
args += "--key " + this.settings["key"] + " ";
}
send.StartInfo.Arguments = args + "-m \""+data.Replace("\"","\\\"")+"\" -t \""+topic+"\" -d";
send.StartInfo.CreateNoWindow = true;
send.StartInfo.UseShellExecute = false;
send.StartInfo.RedirectStandardOutput = true;
send.StartInfo.RedirectStandardError = true;
send.Start();
send.WaitForExit();
MessageSending?.Invoke(this, new MqttEventArgs(data, topic));
}
private void P_ErrorDataReceived(Object sender, DataReceivedEventArgs e) {
if (e.Data != null) {
throw new NotImplementedException(e.Data);
}
}
private void P_OutputDataReceived(Object sender, DataReceivedEventArgs e) {
if (e.Data != null) {
if (e.Data.StartsWith("Client mosqsub")) {
if (this.message != "" && this.message.IndexOf(" received PUBLISH ") > 0) {
MatchCollection matches = (new Regex("^Client mosqsub[\\|/].*received PUBLISH \\(.*,.*,.*,.*, '(.*)'.*\\)\\)\n[^ ]* (.*)$", RegexOptions.IgnoreCase | RegexOptions.Singleline)).Matches(this.message);
String topic = matches[0].Groups[1].Value;
String message = matches[0].Groups[2].Value.Trim();
this.MessageIncomming?.Invoke(this, new MqttEventArgs(message, topic));
}
this.message = e.Data + "\n";
} else {
this.message += e.Data + "\n";
}
}
}
#region IDisposable Support
private Boolean disposedValue = false; // Dient zur Erkennung redundanter Aufrufe.
private readonly Dictionary<String, String> settings;
protected virtual void Dispose(Boolean disposing) {
if (!this.disposedValue) {
if (disposing) {
this.p.CancelOutputRead();
if (!this.p.HasExited) {
this.p.Kill();
}
this.p.Close();
}
this.p = null;
this.disposedValue = true;
}
}
~Mosquitto() {
Dispose(false);
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}

View File

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Text;
using BlubbFish.Utils;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace Dashboard.Connector {
class Mqtt : ADataBackend, IDisposable {
private MqttClient client;
public override event MqttMessage MessageIncomming;
public override event MqttMessage MessageSending;
public Mqtt(Dictionary<String, String> settings) {
if(settings.ContainsKey("port")) {
this.client = new MqttClient(settings["server"], Int32.Parse(settings["port"]), false, null, null, MqttSslProtocols.None);
} else {
this.client = new MqttClient(settings["server"]);
}
Connect();
}
private void Connect() {
this.client.MqttMsgPublishReceived += this.Client_MqttMsgPublishReceived;
this.client.Connect(Guid.NewGuid().ToString());
this.client.Subscribe(new String[] { "#" }, new Byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
}
private void Client_MqttMsgPublishReceived(Object sender, MqttMsgPublishEventArgs e) {
this.MessageIncomming?.Invoke(this, new MqttEventArgs(Encoding.UTF8.GetString(e.Message), e.Topic));
}
public override void Send(String topic, String data) {
this.client.Publish(topic, Encoding.UTF8.GetBytes(data));
this.MessageSending?.Invoke(this, new MqttEventArgs(data, topic));
}
#region IDisposable Support
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if(!this.disposedValue) {
if(disposing) {
this.client.MqttMsgPublishReceived -= this.Client_MqttMsgPublishReceived;
this.client.Unsubscribe(new String[] { "#" });
this.client.Disconnect();
}
this.client = null;
this.disposedValue = true;
}
}
~Mqtt() {
Dispose(false);
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}

View File

@ -0,0 +1,54 @@
using BlubbFish.Utils;
using System;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types;
namespace MqttToTelegram {
class Telegram {
private static Telegram instance;
private TelegramBotClient bot;
private ChatId chat;
public delegate void TelegramMessage(Object sender, Message e);
public event TelegramMessage MessageIncomming;
public event TelegramMessage MessageSending;
private Telegram() {
bot = new TelegramBotClient(InIReader.GetInstance("settings.ini").GetValue("general", "telegram-key"));
bot.OnMessage += Bot_OnMessage;
this.Connect();
}
private void Bot_OnMessage(Object sender, MessageEventArgs e) {
this.MessageIncomming?.Invoke(this, e.Message);
}
public static Telegram Instance {
get {
if(instance == null) {
instance = new Telegram();
}
return instance;
}
}
private void Connect() {
bot.StartReceiving();
this.chat = new ChatId(InIReader.GetInstance("settings.ini").GetValue("general", "chatid"));
}
public async void Send(String text) {
try {
Message x = await this.bot.SendTextMessageAsync(this.chat, text);
this.MessageSending?.Invoke(this, x);
} catch(ApiRequestException e) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message+" "+e.ErrorCode+" "+e.Parameters);
Console.ForegroundColor = ConsoleColor.White;
}
}
}
}

View File

@ -0,0 +1,149 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{16AC0F61-0B60-4A1D-A827-B3BFDBA9AAC7}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>Dashboard</RootNamespace>
<AssemblyName>Dashboard</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="LitJson, Version=0.9.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\LitJson.0.9.0\lib\LitJson.dll</HintPath>
</Reference>
<Reference Include="M2Mqtt.Net, Version=4.3.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\M2Mqtt.4.3.0.0\lib\net45\M2Mqtt.Net.dll</HintPath>
</Reference>
<Reference Include="OxyPlot, Version=1.0.0.0, Culture=neutral, PublicKeyToken=638079a8f0bd61e9, processorArchitecture=MSIL">
<HintPath>..\packages\OxyPlot.Core.1.0.0\lib\net45\OxyPlot.dll</HintPath>
</Reference>
<Reference Include="OxyPlot.WindowsForms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=245eacd6b5d2d338, processorArchitecture=MSIL">
<HintPath>..\packages\OxyPlot.WindowsForms.1.0.0\lib\net45\OxyPlot.WindowsForms.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Windows.Forms.DataVisualization" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Connector\ADataBackend.cs" />
<Compile Include="Connector\Mosquitto.cs" />
<Compile Include="Connector\Mqtt.cs" />
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Sensor\ASensor.cs" />
<Compile Include="Sensor\Flex4GridPower.cs" />
<Compile Include="Sensor\Power.cs" />
<Compile Include="Sensor\Flex4GridSwitch.cs" />
<Compile Include="Sensor\Switch.cs" />
<Compile Include="Tracings\ATracings.cs" />
<Compile Include="Tracings\Graph.cs" />
<Compile Include="Tracings\Meter.cs" />
<Compile Include="Tracings\PowerMeter.cs" />
<Compile Include="Tracings\Switcher.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<None Include="sensor.ini.example" />
<None Include="settings.ini.example" />
<None Include="tracings.ini.example" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Utils\Utils\Utils.csproj">
<Project>{fac8ce64-bf13-4ece-8097-aeb5dd060098}</Project>
<Name>Utils</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5.2 %28x86 und x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<StartArguments>-debug</StartArguments>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<StartArguments>-debug</StartArguments>
</PropertyGroup>
<PropertyGroup>
<PublishUrlHistory />
<InstallUrlHistory />
<SupportUrlHistory />
<UpdateUrlHistory />
<BootstrapperUrlHistory />
<ErrorReportUrlHistory />
<FallbackCulture>de-DE</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,65 @@
namespace Dashboard {
partial class Dashboard {
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent() {
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel();
this.SuspendLayout();
//
// statusStrip1
//
this.statusStrip1.Location = new System.Drawing.Point(0, 490);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(1247, 22);
this.statusStrip1.TabIndex = 0;
this.statusStrip1.Text = "statusStrip1";
//
// flowLayoutPanel2
//
this.flowLayoutPanel2.Location = new System.Drawing.Point(12, 12);
this.flowLayoutPanel2.Name = "flowLayoutPanel2";
this.flowLayoutPanel2.Size = new System.Drawing.Size(1223, 475);
this.flowLayoutPanel2.TabIndex = 3;
//
// Dashboard
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1247, 512);
this.Controls.Add(this.flowLayoutPanel2);
this.Controls.Add(this.statusStrip1);
this.Name = "Dashboard";
this.Text = "Dashboard";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2;
}
}

View File

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using BlubbFish.Utils;
using Dashboard.Connector;
using Dashboard.Sensor;
using Dashboard.Tracings;
namespace Dashboard {
public partial class Dashboard : Form {
private Dictionary<String, ASensor> sensors = new Dictionary<String, ASensor>();
private ADataBackend mqtt;
public Dashboard(Boolean debug) {
InitializeComponent();
this.mqtt = ADataBackend.GetInstance(InIReader.GetInstance("settings.ini").GetSection("mqtt"));
this.GenerateSensors();
this.GenerateForms();
this.FormClosed += this.Dashboard_FormClosed;
this.SizeChanged += this.Dashboard_SizeChanged;
if (debug) {
this.mqtt.MessageIncomming += this.Instance_MessageIncomming;
this.mqtt.MessageSending += this.Instance_MessageSending;
}
}
private void Dashboard_SizeChanged(Object sender, EventArgs e) {
this.flowLayoutPanel2.Size = new System.Drawing.Size(this.Size.Width - 40, this.Size.Width - 76);
}
private void GenerateSensors() {
InIReader ini = InIReader.GetInstance("sensor.ini");
List<String> sensorini = ini.GetSections(false);
foreach(String sensor in sensorini) {
this.sensors.Add(sensor.ToLower(), ASensor.GetInstance(this.mqtt, ini.GetSection(sensor), sensor));
}
}
private void GenerateForms() {
InIReader ini = InIReader.GetInstance("tracings.ini");
List<String> tracingini = ini.GetSections();
foreach(String tracing in tracingini) {
this.flowLayoutPanel2.Controls.Add(ATracings.GetInstance(ini.GetValue(tracing, "type").ToLower(), this.sensors, ini.GetSection(tracing)).GetPanel());
}
}
private void Dashboard_FormClosed(Object sender, FormClosedEventArgs e) {
this.Dispose();
}
private new void Dispose() {
foreach (KeyValuePair<String, ASensor> item in this.sensors) {
item.Value.Dispose();
}
this.sensors.Clear();
this.mqtt.MessageIncomming -= this.Instance_MessageIncomming;
this.mqtt.MessageSending -= this.Instance_MessageSending;
this.mqtt.Dispose();
this.Dispose(true);
}
private void Instance_MessageIncomming(Object sender, MqttEventArgs e) {
Console.WriteLine("Received = " + e.Message + " on topic " + e.Topic+" at "+DateTime.Now.ToUniversalTime());
}
private void Instance_MessageSending(Object sender, MqttEventArgs e) {
Console.WriteLine("Sended = " + e.Message + " on topic " + e.Topic + " at " + DateTime.Now.ToUniversalTime());
}
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="statusStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using BlubbFish.Utils;
namespace Dashboard {
static class Program {
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main(String[] args) {
CmdArgs.Instance.SetArguments(new Dictionary<String, CmdArgs.VaildArguments> {
{ "-debug", new CmdArgs.VaildArguments(CmdArgs.ArgLength.Single) }
}, args);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Boolean debug = false;
if(CmdArgs.Instance.HasArgumentType("-debug")) {
debug = true;
}
Application.Run(new Dashboard(debug));
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("Mqtt-Dashboard")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mqtt-Dashboard")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("16ac0f61-0b60-4a1d-a827-b3bfdba9aac7")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Dashboard.Properties {
using System;
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
// -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Dashboard.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Dashboard.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,121 @@
using Dashboard.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text.RegularExpressions;
namespace Dashboard.Sensor {
public abstract class ASensor : IDisposable {
protected String topic;
protected Int32 pollcount;
private Dictionary<String, String> settings;
protected ADataBackend backend;
private Thread updateThread;
private Boolean pollEnabled = false;
public ASensor(Dictionary<String, String> settings, String name, ADataBackend backend) {
this.GetBool = true;
this.GetFloat = 0.0f;
this.GetInt = 0;
this.topic = (settings.Keys.Contains("topic")) ? settings["topic"] : "";
this.settings = settings;
this.Title = (settings.Keys.Contains("title")) ? settings["title"] : "";
this.Name = name;
this.backend = backend;
this.backend.MessageIncomming += this.IncommingMqttMessage;
if (settings.Keys.Contains("polling")) {
this.pollEnabled = true;
this.Polling = Int32.Parse(settings["polling"]);
this.pollcount = this.Polling;
this.updateThread = new Thread(this.SensorPolling);
this.updateThread.Start();
}
}
private void SensorPolling() {
while(this.pollEnabled) {
Thread.Sleep(1000);
this.Poll();
}
}
private void IncommingMqttMessage(Object sender, MqttEventArgs e) {
if(Regex.Match(e.Topic, this.topic).Success) {
if (this.UpdateValue(e)) {
this.Timestamp = DateTime.Now;
this.Update?.Invoke(this, e);
}
}
}
internal static ASensor GetInstance(ADataBackend backend, Dictionary<String, String> dictionary, String name) {
String object_sensor = "Dashboard.Sensor." + Char.ToUpper(dictionary["type"][0]) + dictionary["type"].Substring(1).ToLower();
Type t = null;
try {
t = Type.GetType(object_sensor, true);
} catch(TypeLoadException) {
throw new ArgumentException("sensor.ini: " + dictionary["type"] + " is not a Sensor");
}
return (ASensor)t.GetConstructor(new Type[] { typeof(Dictionary<String, String>), typeof(String), typeof(ADataBackend) }).Invoke(new Object[] { dictionary, name, backend });
}
protected virtual void Poll() {
if(this.pollcount++ >= this.Polling) {
this.pollcount = 1;
this.backend.Send(this.topic + "/status","");
}
}
internal virtual void SetBool(Boolean v) {
this.backend.Send(this.topic + "/set", v ? "on" : "off");
}
protected abstract Boolean UpdateValue(MqttEventArgs e);
public Single GetFloat { get; protected set; }
public Boolean GetBool { get; protected set; }
public Int32 GetInt { get; protected set; }
public Types Datatypes { get; protected set; }
public DateTime Timestamp { get; protected set; }
public Int32 Polling { get; private set; }
public String Title { get; protected set; }
public String Name { get; internal set; }
public enum Types {
Bool,
Int,
Float
}
public delegate void UpdatedValue(ASensor sender, EventArgs e);
public event UpdatedValue Update;
#region IDisposable Support
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if(!this.disposedValue) {
if(disposing) {
this.pollEnabled = false;
if (this.updateThread != null && this.updateThread.ThreadState == ThreadState.Running) {
this.updateThread.Abort();
while (this.updateThread.ThreadState != ThreadState.Aborted) { }
}
this.backend.MessageIncomming -= this.IncommingMqttMessage;
}
this.settings = null;
this.updateThread = null;
this.disposedValue = true;
}
}
~ASensor() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using Dashboard.Connector;
using LitJson;
namespace Dashboard.Sensor {
class Flex4gridswitch : ASensor {
private String id;
public Flex4gridswitch(Dictionary<String, String> settings, String name, ADataBackend backend) : base(settings, name, backend) {
this.Datatypes = Types.Bool;
this.id = settings["id"];
}
protected override Boolean UpdateValue(MqttEventArgs e) {
CultureInfo info = new CultureInfo("de-DE");
info.NumberFormat.NumberDecimalSeparator = ".";
CultureInfo.DefaultThreadCurrentCulture = info;
CultureInfo.DefaultThreadCurrentUICulture = info;
System.Threading.Thread.CurrentThread.CurrentCulture = info;
System.Threading.Thread.CurrentThread.CurrentUICulture = info;
try {
JsonData data = JsonMapper.ToObject(e.Message);
if (data.Keys.Contains("id") && data["id"].ToString() == this.id) {
this.GetBool = data["status"].ToString() == "active" ? true : false;
return true;
}
if(data.Keys.Contains(this.id)) {
this.GetBool = data[this.id].ToString() == "active" ? true : false;
return true;
}
} catch (Exception) {
}
return false;
}
protected override void Poll() {
if (this.pollcount++ >= this.Polling) {
this.pollcount = 1;
String hid = Regex.Match(this.topic, "/flex4grid/v1/households/([^/]*)/device/state").Groups[1].Value;
this.backend.Send("/flex4grid/v1/households/" + hid + "/devices/state/request", "{\"timestamp\": \"" + DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffff'Z'") + "\"}");
}
}
internal override void SetBool(Boolean v) {
String hid = Regex.Match(this.topic, "/flex4grid/v1/households/([^/]*)/device/state").Groups[1].Value;
this.backend.Send("/flex4grid/v1/households/" + hid + "/device/actuate", "{\"command\":\""+(v ? "ON" : "OFF") + "\",\"deviceId\":\""+ this.id + "\",\"timestamp\":\"" + DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffff'Z'") + "\"}");
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Dashboard.Connector;
using LitJson;
namespace Dashboard.Sensor {
class Flex4gridpower : ASensor {
private String id;
public Flex4gridpower(Dictionary<String, String> settings, String name, ADataBackend backend) : base(settings, name, backend) {
this.Datatypes = Types.Float;
this.id = settings["id"];
}
protected override Boolean UpdateValue(MqttEventArgs e) {
CultureInfo info = new CultureInfo("de-DE");
info.NumberFormat.NumberDecimalSeparator = ".";
CultureInfo.DefaultThreadCurrentCulture = info;
CultureInfo.DefaultThreadCurrentUICulture = info;
System.Threading.Thread.CurrentThread.CurrentCulture = info;
System.Threading.Thread.CurrentThread.CurrentUICulture = info;
try {
JsonData data = JsonMapper.ToObject(e.Message);
if(data["id"].ToString() == this.id) {
this.GetFloat = Single.Parse(data["power"].ToString());
return true;
}
} catch (Exception) {
}
return false;
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace Dashboard.Sensor {
class Luminanz : ASensor {
public Luminanz(Dictionary<String, String> settings) : base(settings) {
this.GetBool = true;
this.GetFloat = 0.0f;
this.GetInt = 0;
this.Datatypes = Types.Int;
}
protected override void UpdateValue(MqttMsgPublishEventArgs e) {
this.GetInt = Int32.Parse(Encoding.UTF8.GetString(e.Message), new CultureInfo("en-US"));
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Text;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace Dashboard.Sensor {
class Pir : ASensor {
public Pir(Dictionary<String, String> settings) : base(settings) {
this.Datatypes = Types.Bool;
}
protected override void UpdateValue(MqttMsgPublishEventArgs e) {
this.GetBool = (Encoding.UTF8.GetString(e.Message).ToLower() == "on") ? true : false;
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Dashboard.Connector;
namespace Dashboard.Sensor {
class Power : ASensor {
public Power(Dictionary<String, String> settings, String name, ADataBackend backend) : base(settings, name, backend) {
this.GetBool = true;
this.GetFloat = 0.0f;
this.GetInt = 0;
this.Datatypes = Types.Float;
}
protected override Boolean UpdateValue(MqttEventArgs e) {
this.GetFloat = Single.Parse(e.Message, new CultureInfo("en-US"));
return true;
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using Dashboard.Connector;
namespace Dashboard.Sensor {
class Switch : ASensor {
public Switch(Dictionary<System.String, System.String> settings, String name, ADataBackend backend) : base(settings, name, backend) {
this.Datatypes = Types.Bool;
}
protected override Boolean UpdateValue(MqttEventArgs e) {
this.GetBool = (e.Message.ToLower() == "on") ? true : false;
return true;
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace Dashboard.Sensor {
class Temperatur : ASensor {
public Temperatur(Dictionary<String, String> settings) : base(settings) {
this.GetBool = true;
this.GetFloat = 0.0f;
this.GetInt = 0;
this.Datatypes = Types.Float;
}
protected override void UpdateValue(MqttMsgPublishEventArgs e) {
this.GetFloat = Single.Parse(Encoding.UTF8.GetString(e.Message), new CultureInfo("en-US"));
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Dashboard.Sensor;
namespace Dashboard.Tracings {
public abstract class ATracings {
protected ASensor sensor;
protected Dictionary<String, String> settings;
protected Dictionary<String, ASensor> sensors;
public ATracings(ASensor sensor, Dictionary<String, String> settings) {
this.sensor = sensor;
this.sensor.Update += this.SensorUpdate;
this.settings = settings;
}
public ATracings(Dictionary<String, ASensor> sensors, Dictionary<String, String> settings) {
this.sensors = sensors;
foreach(KeyValuePair<String, ASensor> sensor in this.sensors) {
sensor.Value.Update += this.SensorsUpdate;
}
this.settings = settings;
}
protected abstract void SensorsUpdate(ASensor sender, EventArgs e);
protected abstract void SensorUpdate(ASensor sender, EventArgs e);
public abstract Panel GetPanel();
internal static ATracings GetInstance(String v, Dictionary<String, ASensor> sensorList, Dictionary<String, String> dictionary) {
String object_sensor = "Dashboard.Tracings." + Char.ToUpper(v[0]) + v.Substring(1);
Type t = null;
try {
t = Type.GetType(object_sensor, true);
} catch (TypeLoadException) {
throw new ArgumentException("tracings.ini: " + v + " is not a Tracing");
}
if (dictionary["sensor"].Contains(",")) {
Dictionary<String, ASensor> sensors = new Dictionary<String, ASensor>();
String[] sensors_name = dictionary["sensor"].Split(',');
foreach (String item in sensors_name) {
sensors.Add(item, sensorList[item.ToLower()]);
}
return (ATracings)t.GetConstructor(new Type[] { typeof(Dictionary<String, ASensor>), typeof(Dictionary<String, String>) }).Invoke(new Object[] { sensors, dictionary });
} else {
return (ATracings)t.GetConstructor(new Type[] { typeof(ASensor), typeof(Dictionary<String, String>) }).Invoke(new Object[] { sensorList[dictionary["sensor"].ToLower()], dictionary });
}
}
}
}

View File

@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Dashboard.Sensor;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using OxyPlot.WindowsForms;
namespace Dashboard.Tracings {
class Graph : ATracings, IDisposable {
private Queue<Tuple<DateTime, Single>> hist = new Queue<Tuple<DateTime, Single>>();
private Dictionary<String, Queue<Tuple<DateTime, Single>>> hists = new Dictionary<String, Queue<Tuple<DateTime, Single>>>();
private Dictionary<String, Single> hists_last = new Dictionary<String, Single>();
private Int32 Chart_Items;
private PlotView plot = new PlotView { BackColor = System.Drawing.Color.White };
private PlotModel Model = new PlotModel();
private Boolean multi;
private Single MaximumDrawn = 1;
private String[] colors = { "255,255,0,0","255,230,230,0", "255,0,128,0", "255,0,0,255", "255,255,0,255", "255,255,128,0", "255,0,255,255", "255,158,255,128", "255,0,128,255", "255,0,0,0" };
public Graph(ASensor sensor, Dictionary<String, String> settings) : base(sensor, settings) {
this.Chart_Items = (settings.Keys.Contains("items")) ? Int32.Parse(settings["items"]) : 1000;
this.multi = false;
}
public Graph(Dictionary<String, ASensor> sensors, Dictionary<String, String> settings) : base(sensors, settings) {
this.Chart_Items = (settings.Keys.Contains("items")) ? Int32.Parse(settings["items"]) : 1000;
this.multi = true;
}
public override Panel GetPanel() {
Panel panel = new Panel { BorderStyle = BorderStyle.FixedSingle };
this.Model.Axes.Add(new DateTimeAxis { Position = AxisPosition.Bottom, AbsoluteMinimum = DateTimeAxis.ToDouble(DateTime.Now), AbsoluteMaximum = DateTimeAxis.ToDouble(DateTime.Now.AddMinutes(1)), IsZoomEnabled = false });
this.Model.Axes.Add(new LinearAxis { Position = AxisPosition.Left, AbsoluteMinimum = 0, Minimum = 0, AbsoluteMaximum = 1, IsZoomEnabled = false });
if (this.multi) {
Int32 i = 0;
foreach (KeyValuePair<String, ASensor> item in this.sensors) {
LineSeries l = new LineSeries { Color = OxyColor.Parse(this.colors[i++ % this.colors.Length]), TrackerKey = item.Value.Name };
if (item.Value.Title != "") {
l.Title = item.Value.Title;
}
this.Model.Series.Add(l);
}
} else {
LineSeries l = new LineSeries { Color = OxyColor.FromRgb(0, 0, 255) };
l.CanTrackerInterpolatePoints = true;
if (this.sensor.Title != "") {
l.Title = this.sensor.Title;
}
this.Model.Series.Add(l);
}
Int32 fieldWidth = 200;
if(this.multi) {
fieldWidth = (this.sensors.Count * 200) + (this.sensors.Count-1)*6;
}
this.plot.Location = new System.Drawing.Point(0, 0);
this.plot.Size = new System.Drawing.Size(fieldWidth, 200);
this.plot.Dock = DockStyle.Fill;
this.plot.Model = this.Model;
panel.Controls.Add(this.plot);
panel.Size = new System.Drawing.Size(fieldWidth, 200);
return panel;
}
protected override void SensorUpdate(ASensor sender, EventArgs e) {
Single v = 0;
switch (sender.Datatypes) {
case ASensor.Types.Bool: v = sender.GetBool ? 1 : 0; break;
case ASensor.Types.Int: v = sender.GetInt; break;
case ASensor.Types.Float: v = sender.GetFloat; break;
}
this.hist.Enqueue(new Tuple<DateTime, Single>(sender.Timestamp, v));
if (this.MaximumDrawn < v) {
this.MaximumDrawn = v;
}
if (this.hist.Count > this.Chart_Items) {
this.hist.Dequeue();
}
if (this.Model.Series.Count != 0) {
this.plot.BeginInvoke((MethodInvoker)delegate {
this.Model.Axes[1].Maximum = this.MaximumDrawn * 1.1;
this.Model.Axes[1].AbsoluteMaximum = this.MaximumDrawn * 1.1;
this.Model.Axes[0].AbsoluteMaximum = DateTimeAxis.ToDouble(sender.Timestamp);
((LineSeries)this.Model.Series[0]).Points.Clear();
try {
foreach(Tuple<DateTime, Single> temp in this.hist) {
((LineSeries)this.Model.Series[0]).Points.Add(new DataPoint(DateTimeAxis.ToDouble(temp.Item1),temp.Item2));
}
this.Model.InvalidatePlot(true);
} catch(Exception) { };
});
}
}
protected override void SensorsUpdate(ASensor sender, EventArgs e) {
Single v = 0;
if (!this.hists.ContainsKey(sender.Name)) {
this.hists.Add(sender.Name, new Queue<Tuple<DateTime, Single>>());
this.hists_last.Add(sender.Name, 0);
}
switch (sender.Datatypes) {
case ASensor.Types.Bool:
v = sender.GetBool ? 1 : 0;
break;
case ASensor.Types.Int:
v = sender.GetInt;
break;
case ASensor.Types.Float:
v = sender.GetFloat;
break;
}
this.hists_last[sender.Name] = v;
foreach (KeyValuePair<String, Queue<Tuple<DateTime, Single>>> item in this.hists) {
item.Value.Enqueue(new Tuple<DateTime, Single>(sender.Timestamp, this.hists_last[item.Key]));
if (this.MaximumDrawn < this.hists_last[item.Key]) {
this.MaximumDrawn = this.hists_last[item.Key];
}
if (item.Value.Count > this.Chart_Items) {
item.Value.Dequeue();
}
}
foreach (Series item in this.Model.Series) {
if (this.hists.ContainsKey(item.TrackerKey)) {
this.plot.BeginInvoke((MethodInvoker)delegate {
try {
this.Model.Axes[1].Maximum = this.MaximumDrawn * 1.1;
this.Model.Axes[1].AbsoluteMaximum = this.MaximumDrawn * 1.1;
this.Model.Axes[0].AbsoluteMaximum = DateTimeAxis.ToDouble(sender.Timestamp);
((LineSeries)item).Points.Clear();
foreach (Tuple<DateTime, Single> temp in this.hists[item.TrackerKey]) {
((LineSeries)item).Points.Add(new DataPoint(DateTimeAxis.ToDouble(temp.Item1), temp.Item2));
}
this.Model.InvalidatePlot(true);
} catch (Exception) { };
});
}
}
}
public void Dispose() {
((LineSeries)this.Model.Series[0]).Points.Clear();
this.Model = null;
this.hist.Clear();
this.hist = null;
this.plot.Dispose();
}
}
}

View File

@ -0,0 +1,71 @@
using System.Collections.Generic;
using Dashboard.Sensor;
using System;
using System.Windows.Forms;
using System.Linq;
using System.Globalization;
namespace Dashboard.Tracings {
class Meter : ATracings {
protected Int32 DisplayItems;
protected Queue<Single> DisplayAverage = new Queue<Single>();
protected Label label1;
protected Label label2;
public Meter(ASensor sensor, Dictionary<String, String> settings) : base(sensor, settings) {
this.DisplayItems = (settings.Keys.Contains("items")) ? Int32.Parse(settings["items"]) : 1000;
this.label1 = new Label();
this.label2 = new Label();
}
public override Panel GetPanel() {
Panel panel = new Panel() {
BorderStyle = BorderStyle.FixedSingle,
Size = new System.Drawing.Size(200, 100)
};
this.label1 = new Label() {
Font = new System.Drawing.Font("Lucida Sans Typewriter", 27.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((Byte)(0))),
Location = new System.Drawing.Point(0, 0),
Size = new System.Drawing.Size(200, 43),
Text = "",
TextAlign = System.Drawing.ContentAlignment.TopCenter
};
panel.Controls.Add(this.label1);
this.label2 = new Label() {
AutoSize = true,
Location = new System.Drawing.Point(0, 50),
Size = new System.Drawing.Size(96, 13),
Text = ""
};
panel.Controls.Add(this.label2);
return panel;
}
protected override void SensorsUpdate(ASensor sender, EventArgs e) {
throw new NotImplementedException();
}
protected override void SensorUpdate(ASensor sender, EventArgs e) {
String value = "";
switch(sender.Datatypes) {
case ASensor.Types.Bool: this.DisplayAverage.Enqueue((sender.GetBool) ? 1 : 0); value = sender.GetBool.ToString(new CultureInfo("de-DE")); break;
case ASensor.Types.Int: this.DisplayAverage.Enqueue(sender.GetInt); value = sender.GetInt.ToString(); break;
case ASensor.Types.Float: this.DisplayAverage.Enqueue(sender.GetFloat); value = sender.GetFloat.ToString(new CultureInfo("de-DE")); break;
}
if(this.DisplayAverage.Count > this.DisplayItems) {
this.DisplayAverage.Dequeue();
}
Single average = this.DisplayAverage.Sum() / this.DisplayAverage.Count();
this.label1.BeginInvoke((MethodInvoker)delegate {
this.label1.Text = value;
});
this.label2.BeginInvoke((MethodInvoker)delegate {
this.label2.Text = "Durchschnitt: " + Math.Round(average, 2);
});
}
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using Dashboard.Sensor;
namespace Dashboard.Tracings {
class Powermeter : Meter {
public Powermeter(ASensor sensor, Dictionary<String, String> settings) : base(sensor, settings) {
}
protected override void SensorUpdate(ASensor sender, EventArgs e) {
String value = "";
switch (sender.Datatypes) {
case ASensor.Types.Bool:
this.DisplayAverage.Enqueue((sender.GetBool) ? 1 : 0);
value = sender.GetBool.ToString(new CultureInfo("de-DE"));
break;
case ASensor.Types.Int:
this.DisplayAverage.Enqueue(sender.GetInt);
value = sender.GetInt.ToString();
break;
case ASensor.Types.Float:
this.DisplayAverage.Enqueue(sender.GetFloat);
value = sender.GetFloat.ToString(new CultureInfo("de-DE"));
break;
}
if (this.DisplayAverage.Count > this.DisplayItems) {
this.DisplayAverage.Dequeue();
}
Single average = this.DisplayAverage.Sum() / this.DisplayAverage.Count();
try {
this.label1.BeginInvoke((MethodInvoker)delegate {
this.label1.Text = value + " W";
});
this.label2.BeginInvoke((MethodInvoker)delegate {
this.label2.Text = "Durchschnitt: " + Math.Round(average, 2) + " W";
});
} catch (Exception) { }
}
}
}

View File

@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using Dashboard.Connector;
using Dashboard.Sensor;
namespace Dashboard.Tracings {
class Switcher : ATracings {
private Label label;
private Button button1;
private Button button2;
public Switcher(ASensor sensor, Dictionary<System.String, System.String> settings) : base(sensor, settings) {
this.label = new Label();
this.button1 = new Button();
this.button2 = new Button();
}
public override Panel GetPanel() {
Panel panel = new Panel() {
BorderStyle = BorderStyle.FixedSingle,
Size = new System.Drawing.Size(200, 100)
};
this.label = new Label() {
AutoSize = true,
Location = new System.Drawing.Point(69, 16),
Size = new System.Drawing.Size(35, 13),
Text = ""
};
panel.Controls.Add(this.label);
this.button1 = new Button() {
BackColor = System.Drawing.Color.FromArgb(0, 192, 0),
Location = new System.Drawing.Point(94, 67),
Name = "on",
Size = new System.Drawing.Size(45, 23),
Text = "ON",
UseVisualStyleBackColor = false
};
this.button1.Click += this.ButtonClicker;
panel.Controls.Add(this.button1);
this.button2 = new Button() {
BackColor = System.Drawing.Color.Red,
Location = new System.Drawing.Point(145, 67),
Name = "off",
Size = new System.Drawing.Size(45, 23),
Text = "OFF",
UseVisualStyleBackColor = false
};
this.button2.Click += this.ButtonClicker;
panel.Controls.Add(this.button2);
return panel;
}
private void ButtonClicker(Object sender, EventArgs e) {
Button b = (Button)sender;
if (b.Name == "on") {
this.sensor.SetBool(true);
} else if(b.Name == "off") {
this.sensor.SetBool(false);
}
}
protected override void SensorUpdate(ASensor sender, EventArgs e) {
this.label.BeginInvoke((MethodInvoker)delegate {
this.label.Text = sender.GetBool?"Eingeschaltet":"Ausgeschaltet";
});
this.button1.BeginInvoke((MethodInvoker)delegate {
this.button1.Enabled = !sender.GetBool;
});
this.button2.BeginInvoke((MethodInvoker)delegate {
this.button2.Enabled = sender.GetBool;
});
}
protected override void SensorsUpdate(ASensor sender, EventArgs e) {
throw new NotImplementedException();
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="LitJson" version="0.9.0" targetFramework="net452" />
<package id="M2Mqtt" version="4.3.0.0" targetFramework="net452" />
<package id="OxyPlot.Core" version="1.0.0" targetFramework="net452" />
<package id="OxyPlot.WindowsForms" version="1.0.0" targetFramework="net452" />
</packages>

View File

@ -0,0 +1,24 @@
[Thinkpad]
topic=zway/wohnzimmer/thinkpad/power
type=Power
polling=10
[Tv]
topic=zway/wohnzimmer/tV/power
type=Power
polling=10
[Kühlschrank]
topic=zway/küche/kuehlschrank/power
type=Power
polling=10
[TvSW]
topic=zway/wohnzimmer/tV/switch
type=switch
polling=10
;[Ventilator]
;topic=zway/power/test/wVentilator
;type=Power
;polling=10

View File

@ -0,0 +1,3 @@
[mqtt]
type=mqtt
server=localhost

View File

@ -0,0 +1,45 @@
[ThinkpadMeter]
sensor=Thinkpad
type=PowerMeter
items=100
[TvMeter]
sensor=Tv
type=PowerMeter
items=100
[KühlschrankrMeter]
sensor=Kühlschrank
type=PowerMeter
items=100
[ThinkpadGraph]
sensor=Thinkpad
type=Graph
items=100
[TvGraph]
sensor=Tv
type=Graph
items=100
[KühlschrankGraph]
sensor=Kühlschrank
type=Graph
items=100
[TvSWMeter]
sensor=TvSW
type=Switcher
items=100
;[VentilatorGraph]
;sensor=Ventilator
;type=Graph
;items=100
;[VentilatorMeter]
;sensor=Ventilator
;type=Meter
;unit=W
;items=100

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mqtt-SWB-Dashboard", "Mqtt-SWB-Dashboard\Mqtt-SWB-Dashboard.csproj", "{324B2308-7C6E-4F16-8764-7C2F8C342B6A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils", "..\Utils\Utils\Utils.csproj", "{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{324B2308-7C6E-4F16-8764-7C2F8C342B6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{324B2308-7C6E-4F16-8764-7C2F8C342B6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{324B2308-7C6E-4F16-8764-7C2F8C342B6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{324B2308-7C6E-4F16-8764-7C2F8C342B6A}.Release|Any CPU.Build.0 = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8640C2B5-61E7-4C20-8E37-28A9543423B7}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>

View File

@ -0,0 +1,9 @@
<Application x:Class="Mqtt_SWB_Dashboard.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Mqtt_SWB_Dashboard"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Mqtt_SWB_Dashboard {
/// <summary>
/// Interaktionslogik für "App.xaml"
/// </summary>
public partial class App : Application {
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Globalization;
using LitJson;
namespace Mqtt_SWB_Dashboard.Helper {
class Device {
public enum DevType {
State,
Consumption,
Production
}
public Device(JsonData data, DevType type) {
this.TimeStamp = new DateTime();
this.Power = 0;
this.Comul = 0;
this.Status = false;
this.Production = 0;
this.Type = type;
this.Update(data, type);
}
public Device(JsonData data) {
this.TimeStamp = DateTime.Parse(data["TimeStamp"].ToString(), new CultureInfo("en-US"));
this.Status = data["Status"].ToString() == "true" ? true : false;
this.Production = Double.Parse(data["Production"].ToString());
this.Type = (DevType)Int32.Parse(data["Type"].ToString());
this.Power = Double.Parse(data["Power"].ToString());
this.Comul = Double.Parse(data["Comul"].ToString());
}
public DateTime TimeStamp { get; private set; }
public Boolean Status { get; private set; }
public Double Production { get; private set; }
public DevType Type { get; private set; }
public Double Power { get; private set; }
public Double Comul { get; private set; }
internal void Update(JsonData data, DevType type) {
this.TimeStamp = DateTime.Parse(data["timestamp"].ToString());
if (type == DevType.State) {
this.Status = data["status"].ToString() == "active" ? true : false;
}
if (type == DevType.Consumption) {
this.Power = Double.Parse(data["power"].ToString());
this.Comul = Double.Parse(data["energyCumul"].ToString());
}
if (type == DevType.Production) {
this.Power = Double.Parse(data["power"].ToString());
this.Comul = Double.Parse(data["energyCumulative"].ToString());
this.Production = Double.Parse(data["productionCumulative"].ToString());
}
}
}
}

View File

@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using LitJson;
namespace Mqtt_SWB_Dashboard.Helper {
class Household {
public SortedDictionary<String, Device> Devices { get; private set; }
public DateTime Active { get; private set; }
public Boolean Connected { get; private set; }
public Household(String did, Device device) {
this.Active = DateTime.Now;
this.Devices = new SortedDictionary<String, Device> {
{ did, device }
};
}
public Household(JsonData data) {
this.Devices = new SortedDictionary<String, Device>();
if (data.Keys.Contains("Devices")) {
foreach (KeyValuePair<String, JsonData> item in data["Devices"]) {
this.Devices.Add(item.Key, new Device(item.Value));
}
}
if(data.Keys.Contains("Connected")) {
this.Connected = Boolean.Parse(data["Connected"].ToString());
if (this.Connected) {
this.Active = DateTime.Now;
}
}
if(data.Keys.Contains("Active")) {
this.Active = DateTime.Parse(data["Active"].ToString(), new CultureInfo("en-US"));
}
}
public void PutDevice(String did, JsonData data, Device.DevType dtype) {
this.Active = DateTime.Now;
if (this.Devices.Keys.Contains(did)) {
this.Devices[did].Update(data, dtype);
} else {
this.Devices.Add(did, new Device(data, dtype));
}
}
internal Int32 GetActive() {
Int32 ret = 0;
foreach (KeyValuePair<String, Device> item in this.Devices) {
if (item.Value.TimeStamp > DateTime.Now.AddMinutes(-10)) {
ret++;
}
}
return ret;
}
internal Double GetPower() {
Double ret = 0;
foreach (KeyValuePair<String, Device> item in this.Devices) {
if (item.Value.TimeStamp > DateTime.Now.AddMinutes(-10) && item.Value.Type != Device.DevType.Production) {
ret += item.Value.Power;
}
}
return ret;
}
internal Double GetAllPower() {
Double ret = 0;
foreach (KeyValuePair<String, Device> item in this.Devices) {
if (item.Value.Type != Device.DevType.Production) {
ret += item.Value.Power;
}
}
return ret;
}
internal Double GetColum() {
Double ret = 0;
foreach (KeyValuePair<String, Device> item in this.Devices) {
if (item.Value.TimeStamp > DateTime.Now.AddMinutes(-10) && item.Value.Type != Device.DevType.Production) {
ret += item.Value.Comul;
}
}
return ret;
}
internal Double GetAllColum() {
Double ret = 0;
foreach (KeyValuePair<String, Device> item in this.Devices) {
if (item.Value.Type != Device.DevType.Production) {
ret += item.Value.Comul;
}
}
return ret;
}
internal void PutConnection(JsonData data) {
this.Connected = Boolean.Parse(data["Connected"].ToString());
if(this.Connected) {
this.Active = DateTime.Now;
}
}
}
}

View File

@ -0,0 +1,35 @@
using System;
using LitJson;
namespace Mqtt_SWB_Dashboard.Helper {
class Raspi {
public Raspi(JsonData data) {
PutStatus(data);
if(data.Keys.Contains("Connected")) {
this.Connected = Boolean.Parse(data["Connected"].ToString());
}
if (data.Keys.Contains("Uptime")) {
this.Uptime = Double.Parse(data["Uptime"].ToString());
}
}
public Boolean Connected { get; private set; }
public Double Uptime { get; private set; }
internal void PutStatus(JsonData data) {
if (data.Keys.Contains("message")) {
if (data["message"].Keys.Contains("status")) {
this.Connected = (data["message"]["status"].ToString() == "disconnected") ? false : true;
if (!this.Connected) {
this.Uptime = 0;
}
}
if (data["message"].Keys.Contains("uptime")) {
this.Uptime = Double.Parse(data["message"]["uptime"].ToString());
this.Connected = true;
}
}
}
}
}

View File

@ -0,0 +1,34 @@
<Window x:Class="Mqtt_SWB_Dashboard.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:oxy="clr-namespace:OxyPlot.Wpf;assembly=OxyPlot.Wpf"
xmlns:models="clr-namespace:Mqtt_SWB_Dashboard.Models"
xmlns:local="clr-namespace:Mqtt_SWB_Dashboard"
mc:Ignorable="d"
Title="Flex4Grid-Debugger" Height="400" Width="525" Closed="OnClosed">
<Window.DataContext>
<models:PowerChartModel />
</Window.DataContext>
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="10,55,0,0" TextWrapping="Wrap" Text="Haushalte" VerticalAlignment="Top" Width="70" TextAlignment="Center"/>
<TextBlock HorizontalAlignment="Left" Margin="85,55,0,0" TextWrapping="Wrap" Text="Geräte" VerticalAlignment="Top" Width="62" TextAlignment="Center"/>
<TextBlock HorizontalAlignment="Left" Margin="10,139,0,0" TextWrapping="Wrap" Text="Power" VerticalAlignment="Top" Width="202" TextAlignment="Center"/>
<TextBlock HorizontalAlignment="Left" Margin="10,97,0,0" TextWrapping="Wrap" Text="Verbrauch" VerticalAlignment="Top" Width="202" TextAlignment="Center"/>
<TextBlock HorizontalAlignment="Left" Margin="152,55,0,0" TextWrapping="Wrap" Text="Raspis" VerticalAlignment="Top" Width="60" TextAlignment="Center"/>
<TextBlock HorizontalAlignment="Left" Margin="217,55,0,0" TextWrapping="Wrap" Text="Most Uptime" VerticalAlignment="Top" Width="195" TextAlignment="Center"/>
<TextBlock HorizontalAlignment="Left" Margin="417,55,0,0" TextWrapping="Wrap" Text="Avg Uptime" VerticalAlignment="Top" Width="90" TextAlignment="Center"/>
<TextBlock x:Name="connectedTo" HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Text="Connected to: *.broker.flex4grid.eu" VerticalAlignment="Top" Width="497" TextAlignment="Center"/>
<TextBlock x:Name="countHouses" HorizontalAlignment="Left" Margin="10,76,0,0" TextWrapping="Wrap" Text="0 / 0 / 0" VerticalAlignment="Top" Width="70" TextAlignment="Center"/>
<TextBlock x:Name="countDevices" HorizontalAlignment="Left" Margin="85,76,0,0" TextWrapping="Wrap" Text="0 / 0" VerticalAlignment="Top" Width="62" TextAlignment="Center"/>
<TextBlock x:Name="countPower" HorizontalAlignment="Left" Margin="10,160,0,0" TextWrapping="Wrap" Text="0W / 0W" VerticalAlignment="Top" Width="202" TextAlignment="Center"/>
<TextBlock x:Name="countColum" HorizontalAlignment="Left" Margin="10,118,0,0" TextWrapping="Wrap" Text="0kW / 0kW" VerticalAlignment="Top" Width="202" TextAlignment="Center"/>
<TextBlock x:Name="countRaspis" HorizontalAlignment="Left" Margin="152,76,0,0" TextWrapping="Wrap" Text="0 / 0" VerticalAlignment="Top" Width="60" TextAlignment="Center"/>
<TextBlock x:Name="maxRaspi" HorizontalAlignment="Left" Margin="217,76,0,0" TextWrapping="Wrap" Text="- / 0" VerticalAlignment="Top" Width="195" TextAlignment="Center"/>
<TextBlock x:Name="avgUptime" HorizontalAlignment="Left" Margin="417,76,0,0" TextWrapping="Wrap" Text="0t 00:00:00" VerticalAlignment="Top" Width="90" TextAlignment="Center"/>
<TextBlock HorizontalAlignment="Right" Margin="0,160,10,0" TextWrapping="Wrap" Text="{Binding TotalNumberOfPoints, StringFormat='Total number of data points in Diagram: {0}'}" VerticalAlignment="Top"/>
<oxy:PlotView Margin="10,181,10,10" Model="{Binding Model}" />
</Grid>
</Window>

View File

@ -0,0 +1,56 @@
using BlubbFish.Utils;
using System;
using System.Globalization;
using System.Windows;
namespace Mqtt_SWB_Dashboard {
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
private Stats s;
public MainWindow() {
InitializeComponent();
CultureInfo info = new CultureInfo("de-DE");
info.NumberFormat.NumberDecimalSeparator = ".";
CultureInfo.DefaultThreadCurrentCulture = info;
CultureInfo.DefaultThreadCurrentUICulture = info;
System.Threading.Thread.CurrentThread.CurrentCulture = info;
System.Threading.Thread.CurrentThread.CurrentUICulture = info;
LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(System.Windows.Markup.XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
try {
String broker = InIReader.GetInstance("settings.ini").GetValue("general", "broker");
this.Dispatcher.BeginInvoke((Action)(() => {
this.connectedTo.Text = "Connected to: " + broker;
}));
this.s = new Stats(new Mosquitto(broker));
this.s.UpdatedConsumption += this.S_UpdatedConsumption;
this.S_UpdatedConsumption(this.s, null);
} catch(Exception e) {
MessageBox.Show(e.Message+"\n"+e.StackTrace, "Some Shit goes fucking wrong!");
Application.Current.Shutdown(1);
}
}
private void S_UpdatedConsumption(Stats sender, EventArgs e) {
this.Dispatcher.BeginInvoke((Action)(() => {
this.countHouses.Text = sender.GetNumberHouseholds();
this.countDevices.Text = sender.GetNumberDevices();
this.countRaspis.Text = sender.GetNumberRaspis();
this.maxRaspi.Text = sender.GetMostRaspiUptime();
this.avgUptime.Text = sender.GetAvgRaspiUptime();
Tuple<Double, Double> power = sender.GetCurrentPower();
this.countPower.Text = power.Item1 + "W / " + power.Item2 + "W";
Tuple<Double, Double> colum = sender.GetCurrentColum();
this.countColum.Text = colum.Item1.ToString("F1") + "kW / " + colum.Item2.ToString("F1") + "kW";
((Models.PowerChartModel)this.DataContext).AddPower(power, colum);
}));
}
private void OnClosed(Object sender, EventArgs e) {
this.s.Dispose();
}
}
}

View File

@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
namespace Mqtt_SWB_Dashboard.Models {
public class PowerChartModel : INotifyPropertyChanged {
private Double MaximumDrawnL = 5;
private Double MaximumDrawnR = 5;
public event PropertyChangedEventHandler PropertyChanged;
public PowerChartModel() {
Instance = this;
this.Model = new PlotModel { Title = "Stromverbrauch" };
this.Model.Axes.Add(new DateTimeAxis { Position = AxisPosition.Bottom, AbsoluteMinimum = DateTimeAxis.ToDouble(DateTime.Now), AbsoluteMaximum = DateTimeAxis.ToDouble(DateTime.Now.AddMinutes(1)), IsZoomEnabled = false });
this.Model.Axes.Add(new LinearAxis { Position = AxisPosition.Left, AbsoluteMinimum = 0, Minimum = 0, AbsoluteMaximum = 1, IsZoomEnabled = false });
this.Model.Axes.Add(new LinearAxis { Position = AxisPosition.Right, AbsoluteMinimum = 0, Minimum = 0, AbsoluteMaximum = 1, IsZoomEnabled = false, Key = "Right" });
this.Model.Series.Add(new LineSeries { Title = "Active [W]", Color = OxyColor.FromRgb(0, 150, 0) });
this.Model.Series.Add(new LineSeries { Title = "Seen [W]", Color = OxyColor.FromRgb(0, 255, 0) });
this.Model.Series.Add(new LineSeries { Title = "Active [kW]", Color = OxyColor.FromRgb(0, 0, 150), YAxisKey= "Right" });
this.Model.Series.Add(new LineSeries { Title = "Seen [kW]", Color = OxyColor.FromRgb(0, 0, 255), YAxisKey = "Right" });
this.RaisePropertyChanged("Model");
}
internal void AddPower(Tuple<Double, Double> power, Tuple<Double, Double> colum) {
if((power.Item1 == 0 && power.Item2 == 0) || (colum.Item1 == 0 && colum.Item2 == 0)) {
return;
}
((LineSeries)this.Model.Series[0]).Points.Add(new DataPoint(DateTimeAxis.ToDouble(DateTime.Now), power.Item1));
((LineSeries)this.Model.Series[1]).Points.Add(new DataPoint(DateTimeAxis.ToDouble(DateTime.Now), power.Item2));
((LineSeries)this.Model.Series[2]).Points.Add(new DataPoint(DateTimeAxis.ToDouble(DateTime.Now), colum.Item1));
((LineSeries)this.Model.Series[3]).Points.Add(new DataPoint(DateTimeAxis.ToDouble(DateTime.Now), colum.Item2));
if (this.MaximumDrawnL < power.Item1) {
this.MaximumDrawnL = power.Item1;
}
if (this.MaximumDrawnL < power.Item2) {
this.MaximumDrawnL = power.Item2;
}
if (this.MaximumDrawnR < colum.Item1) {
this.MaximumDrawnR = colum.Item1;
}
if (this.MaximumDrawnR < colum.Item2) {
this.MaximumDrawnR = colum.Item2;
}
//this.Model.Axes[1].Minimum = 0;
//this.Model.Axes[2].Minimum = 0;
this.Model.Axes[1].Maximum = this.MaximumDrawnL * 1.1;
this.Model.Axes[1].AbsoluteMaximum = this.MaximumDrawnL * 1.1;
this.Model.Axes[2].Maximum = this.MaximumDrawnR * 1.05;
this.Model.Axes[2].AbsoluteMaximum = this.MaximumDrawnR * 1.05;
this.Model.Axes[0].AbsoluteMaximum = DateTimeAxis.ToDouble(DateTime.Now);
this.TotalNumberOfPoints++;
this.RaisePropertyChanged("TotalNumberOfPoints");
this.Model.InvalidatePlot(true);
}
protected void RaisePropertyChanged(String property) {
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
public PlotModel Model { get; private set; }
public Int32 TotalNumberOfPoints { get; private set; }
public static PowerChartModel Instance { get; private set; }
}
}

View File

@ -0,0 +1,88 @@
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace Mqtt_SWB_Dashboard {
class Mosquitto : IDisposable {
private Process p;
private String message;
public delegate void MqttMessage(Object sender, MqttEventArgs e);
public event MqttMessage MessageIncomming;
public Mosquitto(String broker) {
//mosquitto_sub --cafile ca.pem --cert cert.pem --key cert.key -h swb.broker.flex4grid.eu -p 8883 -t /# -v
this.message = "";
this.p = new Process();
this.p.StartInfo.FileName = "mosquitto_sub.exe";
this.p.StartInfo.Arguments = "--cafile ca.pem --cert cert.pem --key cert.key -h "+broker+" -p 8883 -t /# -v -d";
this.p.StartInfo.CreateNoWindow = true;
this.p.StartInfo.UseShellExecute = false;
this.p.StartInfo.RedirectStandardOutput = true;
this.p.StartInfo.RedirectStandardError = true;
this.p.OutputDataReceived += this.P_OutputDataReceived;
this.p.ErrorDataReceived += this.P_ErrorDataReceived;
this.p.Start();
this.p.BeginOutputReadLine();
}
private void P_ErrorDataReceived(Object sender, DataReceivedEventArgs e) {
if (e.Data != null) {
throw new NotImplementedException(e.Data);
}
}
private void P_OutputDataReceived(Object sender, DataReceivedEventArgs e) {
if (e.Data != null) {
if (e.Data.StartsWith("Client mosqsub")) {
if (this.message != "" && this.message.IndexOf(" received PUBLISH ") > 0) {
MatchCollection matches = (new Regex("^Client mosqsub\\|.*received PUBLISH \\(.*,.*,.*,.*, '(.*)'.*\\)\\)\n[^ ]* (.*)$", RegexOptions.IgnoreCase | RegexOptions.Singleline)).Matches(this.message);
String topic = matches[0].Groups[1].Value;
String message = matches[0].Groups[2].Value.Trim();
this.MessageIncomming?.Invoke(this, new MqttEventArgs(message, topic));
}
this.message = e.Data + "\n";
} else {
this.message += e.Data + "\n";
}
}
}
#region IDisposable Support
private Boolean disposedValue = false; // Dient zur Erkennung redundanter Aufrufe.
protected virtual void Dispose(Boolean disposing) {
if (!this.disposedValue) {
if (disposing) {
this.p.CancelOutputRead();
this.p.Kill();
this.p.Close();
}
this.p = null;
this.disposedValue = true;
}
}
~Mosquitto() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
class MqttEventArgs : EventArgs {
public MqttEventArgs() : base() { }
public MqttEventArgs(String message, String topic) {
this.Topic = topic;
this.Message = message;
this.Date = DateTime.Now;
}
public String Topic { get; private set; }
public String Message { get; private set; }
public DateTime Date { get; private set; }
}
}

Some files were not shown because too many files have changed in this diff Show More