├── AForge_libs
├── AForge.dll
├── License.txt
├── Copyright.txt
├── Release notes.txt
├── AForge.Imaging.dll
├── lgpl-3.0.txt
└── gpl-3.0.txt
├── TestSeek
├── palette
│ ├── Gray.png
│ ├── Iron.png
│ └── Rain.png
├── App.config
├── Properties
│ ├── Settings.settings
│ ├── Settings.Designer.cs
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ └── Resources.resx
├── Program.cs
├── SeekThermal.cs
├── Form1.resx
├── TestSeek.csproj
├── Form1.cs
├── Form1.Designer.cs
├── NativeMethods.cs
└── WinUSBDevice.cs
├── SeekOFix.sln
├── .gitattributes
└── .gitignore
/AForge_libs/AForge.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frenkinet/SeekOFix/HEAD/AForge_libs/AForge.dll
--------------------------------------------------------------------------------
/AForge_libs/License.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frenkinet/SeekOFix/HEAD/AForge_libs/License.txt
--------------------------------------------------------------------------------
/AForge_libs/Copyright.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frenkinet/SeekOFix/HEAD/AForge_libs/Copyright.txt
--------------------------------------------------------------------------------
/TestSeek/palette/Gray.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frenkinet/SeekOFix/HEAD/TestSeek/palette/Gray.png
--------------------------------------------------------------------------------
/TestSeek/palette/Iron.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frenkinet/SeekOFix/HEAD/TestSeek/palette/Iron.png
--------------------------------------------------------------------------------
/TestSeek/palette/Rain.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frenkinet/SeekOFix/HEAD/TestSeek/palette/Rain.png
--------------------------------------------------------------------------------
/AForge_libs/Release notes.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frenkinet/SeekOFix/HEAD/AForge_libs/Release notes.txt
--------------------------------------------------------------------------------
/AForge_libs/AForge.Imaging.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/frenkinet/SeekOFix/HEAD/AForge_libs/AForge.Imaging.dll
--------------------------------------------------------------------------------
/TestSeek/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/TestSeek/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/TestSeek/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using System.Windows.Forms;
6 |
7 | namespace TestSeek
8 | {
9 | static class Program
10 | {
11 | ///
12 | /// The main entry point for the application.
13 | ///
14 | [STAThread]
15 | static void Main()
16 | {
17 | Application.EnableVisualStyles();
18 | Application.SetCompatibleTextRenderingDefault(false);
19 | Application.Run(new Form1());
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/SeekOFix.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.25123.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestSeek", "TestSeek\TestSeek.csproj", "{012D3FDD-9622-4018-8A29-9A4A35BC1B37}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {012D3FDD-9622-4018-8A29-9A4A35BC1B37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {012D3FDD-9622-4018-8A29-9A4A35BC1B37}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {012D3FDD-9622-4018-8A29-9A4A35BC1B37}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {012D3FDD-9622-4018-8A29-9A4A35BC1B37}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/TestSeek/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.34014
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace TestSeek.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/TestSeek/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("TestSeek")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("TestSeek")]
13 | [assembly: AssemblyCopyright("Copyright © 2014")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("b0f23e83-8a9d-4c71-a037-dd57abb06f90")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/TestSeek/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.34209
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace TestSeek.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// Returns the cached ResourceManager instance used by this class.
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TestSeek.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// Overrides the current thread's CurrentUICulture property for all
51 | /// resource lookups using this strongly typed resource class.
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | build/
21 | bld/
22 | [Bb]in/
23 | [Oo]bj/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 |
28 | # MSTest test Results
29 | [Tt]est[Rr]esult*/
30 | [Bb]uild[Ll]og.*
31 |
32 | # NUNIT
33 | *.VisualState.xml
34 | TestResult.xml
35 |
36 | # Build Results of an ATL Project
37 | [Dd]ebugPS/
38 | [Rr]eleasePS/
39 | dlldata.c
40 |
41 | # DNX
42 | project.lock.json
43 | artifacts/
44 |
45 | *_i.c
46 | *_p.c
47 | *_i.h
48 | *.ilk
49 | *.meta
50 | *.obj
51 | *.pch
52 | *.pdb
53 | *.pgc
54 | *.pgd
55 | *.rsp
56 | *.sbr
57 | *.tlb
58 | *.tli
59 | *.tlh
60 | *.tmp
61 | *.tmp_proj
62 | *.log
63 | *.vspscc
64 | *.vssscc
65 | .builds
66 | *.pidb
67 | *.svclog
68 | *.scc
69 |
70 | # Chutzpah Test files
71 | _Chutzpah*
72 |
73 | # Visual C++ cache files
74 | ipch/
75 | *.aps
76 | *.ncb
77 | *.opensdf
78 | *.sdf
79 | *.cachefile
80 |
81 | # Visual Studio profiler
82 | *.psess
83 | *.vsp
84 | *.vspx
85 |
86 | # TFS 2012 Local Workspace
87 | $tf/
88 |
89 | # Guidance Automation Toolkit
90 | *.gpState
91 |
92 | # ReSharper is a .NET coding add-in
93 | _ReSharper*/
94 | *.[Rr]e[Ss]harper
95 | *.DotSettings.user
96 |
97 | # JustCode is a .NET coding add-in
98 | .JustCode
99 |
100 | # TeamCity is a build add-in
101 | _TeamCity*
102 |
103 | # DotCover is a Code Coverage Tool
104 | *.dotCover
105 |
106 | # NCrunch
107 | _NCrunch_*
108 | .*crunch*.local.xml
109 |
110 | # MightyMoose
111 | *.mm.*
112 | AutoTest.Net/
113 |
114 | # Web workbench (sass)
115 | .sass-cache/
116 |
117 | # Installshield output folder
118 | [Ee]xpress/
119 |
120 | # DocProject is a documentation generator add-in
121 | DocProject/buildhelp/
122 | DocProject/Help/*.HxT
123 | DocProject/Help/*.HxC
124 | DocProject/Help/*.hhc
125 | DocProject/Help/*.hhk
126 | DocProject/Help/*.hhp
127 | DocProject/Help/Html2
128 | DocProject/Help/html
129 |
130 | # Click-Once directory
131 | publish/
132 |
133 | # Publish Web Output
134 | *.[Pp]ublish.xml
135 | *.azurePubxml
136 | ## TODO: Comment the next line if you want to checkin your
137 | ## web deploy settings but do note that will include unencrypted
138 | ## passwords
139 | #*.pubxml
140 |
141 | *.publishproj
142 |
143 | # NuGet Packages
144 | *.nupkg
145 | # The packages folder can be ignored because of Package Restore
146 | **/packages/*
147 | # except build/, which is used as an MSBuild target.
148 | !**/packages/build/
149 | # Uncomment if necessary however generally it will be regenerated when needed
150 | #!**/packages/repositories.config
151 |
152 | # Windows Azure Build Output
153 | csx/
154 | *.build.csdef
155 |
156 | # Windows Store app package directory
157 | AppPackages/
158 |
159 | # Visual Studio cache files
160 | # files ending in .cache can be ignored
161 | *.[Cc]ache
162 | # but keep track of directories ending in .cache
163 | !*.[Cc]ache/
164 |
165 | # Others
166 | ClientBin/
167 | [Ss]tyle[Cc]op.*
168 | ~$*
169 | *~
170 | *.dbmdl
171 | *.dbproj.schemaview
172 | *.pfx
173 | *.publishsettings
174 | node_modules/
175 | orleans.codegen.cs
176 |
177 | # RIA/Silverlight projects
178 | Generated_Code/
179 |
180 | # Backup & report files from converting an old project file
181 | # to a newer Visual Studio version. Backup files are not needed,
182 | # because we have git ;-)
183 | _UpgradeReport_Files/
184 | Backup*/
185 | UpgradeLog*.XML
186 | UpgradeLog*.htm
187 |
188 | # SQL Server files
189 | *.mdf
190 | *.ldf
191 |
192 | # Business Intelligence projects
193 | *.rdl.data
194 | *.bim.layout
195 | *.bim_*.settings
196 |
197 | # Microsoft Fakes
198 | FakesAssemblies/
199 |
200 | # Node.js Tools for Visual Studio
201 | .ntvs_analysis.dat
202 |
203 | # Visual Studio 6 build log
204 | *.plg
205 |
206 | # Visual Studio 6 workspace options file
207 | *.opt
208 |
209 | # LightSwitch generated files
210 | GeneratedArtifacts/
211 | _Pvt_Extensions/
212 | ModelManifest.xml
213 |
--------------------------------------------------------------------------------
/TestSeek/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 |
--------------------------------------------------------------------------------
/TestSeek/SeekThermal.cs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2014 Stephen Stair (sgstair@akkit.org)
3 | Additional code Miguel Parra (miguelvp@msn.com)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 | */
23 |
24 | using System;
25 | using System.Collections.Generic;
26 | using System.Linq;
27 | using System.Text;
28 | using System.Threading;
29 | using System.Threading.Tasks;
30 |
31 | using winusbdotnet;
32 |
33 | namespace winusbdotnet.UsbDevices
34 | {
35 | /*public class CalibratedThermalFrame
36 | {
37 | public readonly int Width, Height;
38 | public readonly UInt16[] PixelData;
39 | public UInt16 MinValue;
40 | public UInt16 MaxValue;
41 | }*/
42 |
43 | public class ThermalFrame
44 | {
45 | public readonly int Width, Height;
46 | public readonly byte[] RawData;
47 | public readonly UInt16[] RawDataU16;
48 | public readonly bool IsCalibrationFrame;
49 | public readonly bool IsUsableFrame;
50 | public readonly byte StatusByte;
51 | public readonly UInt16 StatusWord;
52 | public readonly UInt16 AvgValue;
53 |
54 | internal ThermalFrame(Byte[] data)
55 | {
56 | Width = 208;
57 | Height = 156;
58 | RawData = data;
59 | StatusByte = data[20];
60 |
61 | IsCalibrationFrame = StatusByte == 1;
62 | IsUsableFrame = StatusByte == 3;
63 |
64 | // Convert to 16 bit as well for easier manipulation of data.
65 | RawDataU16 = new UInt16[data.Length / 2];
66 |
67 | for (int i = 0; i < (data.Length / 2); i++)
68 | {
69 | UInt16 v = (UInt16)BitConverter.ToInt16(data, i * 2);
70 | RawDataU16[i] = v;
71 | }
72 |
73 | }
74 | }
75 |
76 | public class SeekThermal
77 | {
78 | public static IEnumerable Enumerate()
79 | {
80 | foreach (WinUSBEnumeratedDevice dev in WinUSBDevice.EnumerateAllDevices())
81 | {
82 | // Seek Thermal "iAP Interface" device - Use Zadig to install winusb driver on it.
83 | if (dev.VendorID == 0x289D && dev.ProductID == 0x0010 && dev.UsbInterface == 0)
84 | {
85 | yield return dev;
86 | }
87 | }
88 | }
89 |
90 | WinUSBDevice device;
91 |
92 | public SeekThermal(WinUSBEnumeratedDevice dev)
93 | {
94 | device = new WinUSBDevice(dev);
95 |
96 | // device setup sequence
97 | try
98 | {
99 | device.ControlTransferOut(0x41, 0x54, 0, 0, new byte[] { 0x01 });
100 | }
101 | catch
102 | {
103 | // Try deinit device and repeat.
104 | Deinit();
105 | device.ControlTransferOut(0x41, 0x54, 0, 0, new byte[] { 0x01 });
106 | }
107 |
108 | device.ControlTransferOut(0x41, 0x3c, 0, 0, new byte[] { 0x00, 0x00 });
109 |
110 | byte[] data1 = device.ControlTransferIn(0xC1, 0x4e, 0, 0, 4);
111 |
112 | byte[] data2 = device.ControlTransferIn(0xC1, 0x36, 0, 0, 12);
113 |
114 | // Analysis of 0x56 payload:
115 | // First byte seems to be half the size of the output data.
116 | // It seems like this command may be retriving some sensor data?
117 | device.ControlTransferOut(0x41, 0x56, 0, 0, new byte[] { 0x20, 0x00, 0x30, 0x00, 0x00, 0x00 });
118 |
119 | byte[] data3 = device.ControlTransferIn(0xC1, 0x58, 0, 0, 0x40);
120 |
121 | device.ControlTransferOut(0x41, 0x56, 0, 0, new byte[] { 0x20, 0x00, 0x50, 0x00, 0x00, 0x00 });
122 |
123 | byte[] data4 = device.ControlTransferIn(0xC1, 0x58, 0, 0, 0x40);
124 |
125 | device.ControlTransferOut(0x41, 0x56, 0, 0, new byte[] { 0x0C, 0x00, 0x70, 0x00, 0x00, 0x00 });
126 |
127 | byte[] data5 = device.ControlTransferIn(0xC1, 0x58, 0, 0, 0x18);
128 |
129 | device.ControlTransferOut(0x41, 0x56, 0, 0, new byte[] { 0x06, 0x00, 0x08, 0x00, 0x00, 0x00 });
130 |
131 | byte[] data6 = device.ControlTransferIn(0xC1, 0x58, 0, 0, 0x0c);
132 |
133 |
134 | device.ControlTransferOut(0x41, 0x3E, 0, 0, new byte[] { 0x08, 0x00 });
135 |
136 | byte[] data7 = device.ControlTransferIn(0xC1, 0x3D, 0, 0, 2);
137 |
138 | device.ControlTransferOut(0x41, 0x3E, 0, 0, new byte[] { 0x08, 0x00 });
139 |
140 | device.ControlTransferOut(0x41, 0x3C, 0, 0, new byte[] { 0x01, 0x00 });
141 |
142 | byte[] data8 = device.ControlTransferIn(0xC1, 0x3D, 0, 0, 2);
143 |
144 | }
145 |
146 | //
147 | public void Deinit()
148 | {
149 | device.ControlTransferOut(0x41, 0x3C, 0, 0, new byte[] { 0x00, 0x00 });
150 | device.ControlTransferOut(0x41, 0x3C, 0, 0, new byte[] { 0x00, 0x00 });
151 | device.ControlTransferOut(0x41, 0x3C, 0, 0, new byte[] { 0x00, 0x00 });
152 | }
153 |
154 | public ThermalFrame GetFrameBlocking()
155 | {
156 | // Request frame (vendor interface request 0x53; data "C0 7e 00 00" which is half the size of the return data)
157 | device.ControlTransferOut(0x41, 0x53, 0, 0, new byte[] { 0xc0, 0x7e, 0, 0 });
158 |
159 | // Read data from IN 1 pipe
160 | return new ThermalFrame(device.ReadExactPipe(0x81, 0x7ec0 * 2));
161 | }
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/TestSeek/Form1.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | 114, 17
122 |
123 |
124 | 17, 17
125 |
126 |
127 | 17, 17
128 |
129 |
130 | 114, 17
131 |
132 |
133 | True
134 |
135 |
136 | True
137 |
138 |
139 | 25
140 |
141 |
--------------------------------------------------------------------------------
/TestSeek/TestSeek.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {012D3FDD-9622-4018-8A29-9A4A35BC1B37}
8 | WinExe
9 | Properties
10 | TestSeek
11 | TestSeek
12 | v4.5
13 | 512
14 | false
15 | C:\temp\seek\published\
16 | true
17 | Disk
18 | false
19 | Foreground
20 | 7
21 | Days
22 | false
23 | false
24 | true
25 | 1
26 | 1.0.0.%2a
27 | false
28 | true
29 | true
30 |
31 |
32 | AnyCPU
33 | true
34 | full
35 | false
36 | bin\Debug\
37 | DEBUG;TRACE
38 | prompt
39 | 4
40 | true
41 |
42 |
43 | AnyCPU
44 | pdbonly
45 | true
46 | bin\Release\
47 | TRACE
48 | prompt
49 | 4
50 |
51 |
52 | true
53 | bin\x64\Debug\
54 | DEBUG;TRACE
55 | true
56 | full
57 | x64
58 | prompt
59 | MinimumRecommendedRules.ruleset
60 | true
61 |
62 |
63 | bin\x64\Release\
64 | TRACE
65 | true
66 | pdbonly
67 | x64
68 | prompt
69 | MinimumRecommendedRules.ruleset
70 | true
71 |
72 |
73 | 553B4D59E1D48A3B3915155A9074402C2CBA7C1E
74 |
75 |
76 | TestSeek_TemporaryKey.pfx
77 |
78 |
79 | true
80 |
81 |
82 | true
83 |
84 |
85 |
86 | ..\AForge_libs\AForge.dll
87 |
88 |
89 | ..\AForge_libs\AForge.Imaging.dll
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 | Form
105 |
106 |
107 | Form1.cs
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 | Form1.cs
116 |
117 |
118 | ResXFileCodeGenerator
119 | Resources.Designer.cs
120 | Designer
121 |
122 |
123 | True
124 | Resources.resx
125 | True
126 |
127 |
128 | SettingsSingleFileGenerator
129 | Settings.Designer.cs
130 |
131 |
132 | True
133 | Settings.settings
134 | True
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 | False
143 | Microsoft .NET Framework 4.5 %28x86 and x64%29
144 | true
145 |
146 |
147 | False
148 | .NET Framework 3.5 SP1 Client Profile
149 | false
150 |
151 |
152 | False
153 | .NET Framework 3.5 SP1
154 | false
155 |
156 |
157 |
158 |
159 | PreserveNewest
160 |
161 |
162 | PreserveNewest
163 |
164 |
165 | PreserveNewest
166 |
167 |
168 |
169 |
170 |
177 |
--------------------------------------------------------------------------------
/AForge_libs/lgpl-3.0.txt:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 |
5 | Copyright (C) 2007 Free Software Foundation, Inc.
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 |
10 | This version of the GNU Lesser General Public License incorporates
11 | the terms and conditions of version 3 of the GNU General Public
12 | License, supplemented by the additional permissions listed below.
13 |
14 | 0. Additional Definitions.
15 |
16 | As used herein, "this License" refers to version 3 of the GNU Lesser
17 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
18 | General Public License.
19 |
20 | "The Library" refers to a covered work governed by this License,
21 | other than an Application or a Combined Work as defined below.
22 |
23 | An "Application" is any work that makes use of an interface provided
24 | by the Library, but which is not otherwise based on the Library.
25 | Defining a subclass of a class defined by the Library is deemed a mode
26 | of using an interface provided by the Library.
27 |
28 | A "Combined Work" is a work produced by combining or linking an
29 | Application with the Library. The particular version of the Library
30 | with which the Combined Work was made is also called the "Linked
31 | Version".
32 |
33 | The "Minimal Corresponding Source" for a Combined Work means the
34 | Corresponding Source for the Combined Work, excluding any source code
35 | for portions of the Combined Work that, considered in isolation, are
36 | based on the Application, and not on the Linked Version.
37 |
38 | The "Corresponding Application Code" for a Combined Work means the
39 | object code and/or source code for the Application, including any data
40 | and utility programs needed for reproducing the Combined Work from the
41 | Application, but excluding the System Libraries of the Combined Work.
42 |
43 | 1. Exception to Section 3 of the GNU GPL.
44 |
45 | You may convey a covered work under sections 3 and 4 of this License
46 | without being bound by section 3 of the GNU GPL.
47 |
48 | 2. Conveying Modified Versions.
49 |
50 | If you modify a copy of the Library, and, in your modifications, a
51 | facility refers to a function or data to be supplied by an Application
52 | that uses the facility (other than as an argument passed when the
53 | facility is invoked), then you may convey a copy of the modified
54 | version:
55 |
56 | a) under this License, provided that you make a good faith effort to
57 | ensure that, in the event an Application does not supply the
58 | function or data, the facility still operates, and performs
59 | whatever part of its purpose remains meaningful, or
60 |
61 | b) under the GNU GPL, with none of the additional permissions of
62 | this License applicable to that copy.
63 |
64 | 3. Object Code Incorporating Material from Library Header Files.
65 |
66 | The object code form of an Application may incorporate material from
67 | a header file that is part of the Library. You may convey such object
68 | code under terms of your choice, provided that, if the incorporated
69 | material is not limited to numerical parameters, data structure
70 | layouts and accessors, or small macros, inline functions and templates
71 | (ten or fewer lines in length), you do both of the following:
72 |
73 | a) Give prominent notice with each copy of the object code that the
74 | Library is used in it and that the Library and its use are
75 | covered by this License.
76 |
77 | b) Accompany the object code with a copy of the GNU GPL and this license
78 | document.
79 |
80 | 4. Combined Works.
81 |
82 | You may convey a Combined Work under terms of your choice that,
83 | taken together, effectively do not restrict modification of the
84 | portions of the Library contained in the Combined Work and reverse
85 | engineering for debugging such modifications, if you also do each of
86 | the following:
87 |
88 | a) Give prominent notice with each copy of the Combined Work that
89 | the Library is used in it and that the Library and its use are
90 | covered by this License.
91 |
92 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
93 | document.
94 |
95 | c) For a Combined Work that displays copyright notices during
96 | execution, include the copyright notice for the Library among
97 | these notices, as well as a reference directing the user to the
98 | copies of the GNU GPL and this license document.
99 |
100 | d) Do one of the following:
101 |
102 | 0) Convey the Minimal Corresponding Source under the terms of this
103 | License, and the Corresponding Application Code in a form
104 | suitable for, and under terms that permit, the user to
105 | recombine or relink the Application with a modified version of
106 | the Linked Version to produce a modified Combined Work, in the
107 | manner specified by section 6 of the GNU GPL for conveying
108 | Corresponding Source.
109 |
110 | 1) Use a suitable shared library mechanism for linking with the
111 | Library. A suitable mechanism is one that (a) uses at run time
112 | a copy of the Library already present on the user's computer
113 | system, and (b) will operate properly with a modified version
114 | of the Library that is interface-compatible with the Linked
115 | Version.
116 |
117 | e) Provide Installation Information, but only if you would otherwise
118 | be required to provide such information under section 6 of the
119 | GNU GPL, and only to the extent that such information is
120 | necessary to install and execute a modified version of the
121 | Combined Work produced by recombining or relinking the
122 | Application with a modified version of the Linked Version. (If
123 | you use option 4d0, the Installation Information must accompany
124 | the Minimal Corresponding Source and Corresponding Application
125 | Code. If you use option 4d1, you must provide the Installation
126 | Information in the manner specified by section 6 of the GNU GPL
127 | for conveying Corresponding Source.)
128 |
129 | 5. Combined Libraries.
130 |
131 | You may place library facilities that are a work based on the
132 | Library side by side in a single library together with other library
133 | facilities that are not Applications and are not covered by this
134 | License, and convey such a combined library under terms of your
135 | choice, if you do both of the following:
136 |
137 | a) Accompany the combined library with a copy of the same work based
138 | on the Library, uncombined with any other library facilities,
139 | conveyed under the terms of this License.
140 |
141 | b) Give prominent notice with the combined library that part of it
142 | is a work based on the Library, and explaining where to find the
143 | accompanying uncombined form of the same work.
144 |
145 | 6. Revised Versions of the GNU Lesser General Public License.
146 |
147 | The Free Software Foundation may publish revised and/or new versions
148 | of the GNU Lesser General Public License from time to time. Such new
149 | versions will be similar in spirit to the present version, but may
150 | differ in detail to address new problems or concerns.
151 |
152 | Each version is given a distinguishing version number. If the
153 | Library as you received it specifies that a certain numbered version
154 | of the GNU Lesser General Public License "or any later version"
155 | applies to it, you have the option of following the terms and
156 | conditions either of that published version or of any later version
157 | published by the Free Software Foundation. If the Library as you
158 | received it does not specify a version number of the GNU Lesser
159 | General Public License, you may choose any version of the GNU Lesser
160 | General Public License ever published by the Free Software Foundation.
161 |
162 | If the Library as you received it specifies that a proxy can decide
163 | whether future versions of the GNU Lesser General Public License shall
164 | apply, that proxy's public statement of acceptance of any version is
165 | permanent authorization for you to choose that version for the
166 | Library.
167 |
--------------------------------------------------------------------------------
/TestSeek/Form1.cs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2014 Stephen Stair (sgstair@akkit.org)
3 | Additional code Miguel Parra (miguelvp@msn.com)
4 | Additional code by Franci Kapel: http://html-color-codes.info/Contact/
5 | (Franci Kapel: A lot of my code was influenced by JadeW's work: https://github.com/rzva/ThermalView)
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy
8 | of this software and associated documentation files (the "Software"), to deal
9 | in the Software without restriction, including without limitation the rights
10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 | copies of the Software, and to permit persons to whom the Software is
12 | furnished to do so, subject to the following conditions:
13 |
14 | The above copyright notice and this permission notice shall be included in
15 | all copies or substantial portions of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 | THE SOFTWARE.
24 | */
25 |
26 | using System;
27 | using System.Drawing;
28 | using System.Linq;
29 | using System.Threading;
30 | using System.Windows.Forms;
31 | using System.IO;
32 | using winusbdotnet.UsbDevices;
33 | using AForge.Imaging.Filters;
34 | using System.Drawing.Imaging;
35 | using System.Runtime.InteropServices;
36 | using System.Globalization;
37 |
38 | namespace TestSeek
39 | {
40 | public partial class Form1 : Form
41 | {
42 | SeekThermal thermal;
43 | Thread thermalThread;
44 | ThermalFrame currentFrame, lastUsableFrame;
45 |
46 | bool stopThread;
47 | bool grabExternalReference = false;
48 | bool firstAfterCal = false;
49 | bool usignExternalCal = false;
50 | bool autoSaveImg = false;
51 | bool autoRange = true;
52 | bool dynSliders = false;
53 | bool SharpenImage = false;
54 | bool isRunning = true;
55 |
56 | string localPath;
57 | string tempUnit;
58 |
59 | ushort[] arrID4 = new ushort[32448];
60 | ushort[] arrID1 = new ushort[32448];
61 | ushort[] arrID3 = new ushort[32448];
62 |
63 | bool[] badPixelArr = new bool[32448];
64 |
65 | ushort[] gMode = new ushort[1000];
66 |
67 | ushort[,] palleteArr = new ushort[1001,3];//-> ushort
68 |
69 | byte[] imgBuffer = new byte[97344];
70 |
71 | ushort gModePeakIx = 0;
72 | ushort gModePeakCnt = 0;
73 | ushort gModeLeft = 0;
74 | ushort gModeRight = 0;
75 | ushort gModeLeftManual = 0;
76 | ushort gModeRightManual = 0;
77 | ushort avgID4 = 0;
78 | ushort avgID1 = 0;
79 | ushort maxTempRaw = 0;
80 |
81 | double[] gainCalArr = new double[32448];
82 |
83 | Bitmap bitmap = new Bitmap(208, 156, PixelFormat.Format24bppRgb);
84 | Bitmap croppedBitmap = new Bitmap(206, 156, PixelFormat.Format24bppRgb);
85 | Bitmap bigBitmap = new Bitmap(412, 312, PixelFormat.Format24bppRgb);
86 | BitmapData bitmap_data;
87 |
88 | //ResizeBicubic bicubicResize = new ResizeBicubic(412, 312);
89 | ResizeBilinear bilinearResize = new ResizeBilinear(412, 312);
90 | Crop cropFilter = new Crop(new Rectangle(0, 0, 206, 156));
91 | Sharpen sfilter = new Sharpen();
92 |
93 | public Form1()
94 | {
95 | InitializeComponent();
96 |
97 | localPath = Directory.GetCurrentDirectory().ToString();
98 | Directory.CreateDirectory(localPath+@"\export");
99 |
100 | rbUnitsK.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
101 | rbUnitsC.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
102 | rbUnitsF.CheckedChanged += new EventHandler(radioButtons_CheckedChanged);
103 |
104 | var device = SeekThermal.Enumerate().FirstOrDefault();
105 | if(device == null)
106 | {
107 | MessageBox.Show("No Seek Thermal devices found.");
108 | return;
109 | }
110 | thermal = new SeekThermal(device);
111 |
112 | thermalThread = new Thread(ThermalThreadProc);
113 | thermalThread.IsBackground = true;
114 | thermalThread.Start();
115 | }
116 |
117 | void ThermalThreadProc()
118 | {
119 | while (!stopThread && thermal != null)
120 | {
121 | bool progress = false;
122 |
123 | currentFrame = thermal.GetFrameBlocking();
124 |
125 | switch (currentFrame.StatusByte)
126 | {
127 | case 4://gain calibration
128 | frame4stuff();
129 | break;
130 |
131 | case 1://shutter calibration
132 | markBadPixels();
133 | if (!usignExternalCal) frame1stuff();
134 | firstAfterCal = true;
135 | break;
136 |
137 | case 3://image frame
138 | markBadPixels();
139 | if (grabExternalReference)//use this image as reference
140 | {
141 | grabExternalReference = false;
142 | usignExternalCal = true;
143 | frame1stuff();
144 | }
145 | else
146 | {
147 | frame3stuff();
148 | lastUsableFrame = currentFrame;
149 | progress = true;
150 | }
151 | break;
152 |
153 | default:
154 | break;
155 | }
156 |
157 | if(progress)
158 | {
159 | Invalidate();//redraw form
160 | }
161 | }
162 | }
163 |
164 | private void frame4stuff()
165 | {
166 | arrID4 = currentFrame.RawDataU16;
167 | avgID4 = GetMode(arrID4);
168 |
169 | for (int i = 0; i < 32448; i++)
170 | {
171 | if (arrID4[i] > 2000 && arrID4[i] < 8000) {
172 | gainCalArr[i] = avgID4 / (double)arrID4[i];
173 | }
174 | else {
175 | gainCalArr[i] = 1;
176 | badPixelArr[i] = true;
177 | }
178 | }
179 | }
180 |
181 | private void frame1stuff()
182 | {
183 | arrID1 = currentFrame.RawDataU16;
184 | //avgID1 = GetMode(arrID1);
185 | }
186 |
187 | private void frame3stuff()
188 | {
189 | arrID3 = currentFrame.RawDataU16;
190 |
191 | for (int i = 0; i < 32448; i++)
192 | {
193 | if (arrID3[i] > 2000)
194 | {
195 | arrID3[i] = (ushort)((arrID3[i] - arrID1[i]) * gainCalArr[i] + 7500);
196 | }
197 | else
198 | {
199 | arrID3[i] = 0;
200 | badPixelArr[i] = true;
201 | }
202 | }
203 |
204 | fixBadPixels();
205 | removeNoise();
206 | getHistogram();
207 | fillImgBuffer();
208 | }
209 |
210 | private void fillImgBuffer()
211 | {
212 | ushort v = 0;
213 | ushort loc = 0;
214 |
215 | double iScaler;
216 | iScaler = (double)(gModeRight - gModeLeft) / 1000;
217 |
218 | for (int i = 0; i < 32448; i++)
219 | {
220 | v = arrID3[i];
221 | if (v < gModeLeft) v = gModeLeft;
222 | if (v > gModeRight) v = gModeRight;
223 | v = (ushort)(v - gModeLeft);
224 | loc = (ushort)(v / iScaler);
225 |
226 | imgBuffer[i*3] = (byte)palleteArr[loc, 2];
227 | imgBuffer[i*3+1] = (byte)palleteArr[loc, 1];
228 | imgBuffer[i*3+2] = (byte)palleteArr[loc, 0];
229 | }
230 | }
231 |
232 | private void markBadPixels()
233 | {
234 | ushort[] RawDataArr = currentFrame.RawDataU16;
235 |
236 | for (int i = 0; i < RawDataArr.Length; i++)
237 | {
238 | if (RawDataArr[i] < 2000 || RawDataArr[i] > 22000)
239 | {
240 | badPixelArr[i] = true;
241 | }
242 | }
243 | }
244 |
245 | private void fixBadPixels()
246 | {
247 | ushort x = 0;
248 | ushort y = 0;
249 | ushort i = 0;
250 | ushort nr = 0;
251 | ushort val = 0;
252 |
253 | for (y = 0; y < 156; y++)
254 | {
255 | for (x = 0; x < 208; x++, i++)
256 | {
257 | if (badPixelArr[i] && x < 206) {
258 |
259 | val = 0;
260 | nr = 0;
261 |
262 | if (y > 0 && !badPixelArr[i - 208]) //top pixel
263 | {
264 | val += arrID3[i - 208];
265 | ++nr;
266 | }
267 |
268 | if (y < 155 && !badPixelArr[i + 208]) // bottom pixel
269 | {
270 | val += arrID3[i + 208];
271 | ++nr;
272 | }
273 |
274 | if (x > 0 && !badPixelArr[i - 1]) //Left pixel
275 | {
276 | val += arrID3[i - 1];
277 | ++nr;
278 | }
279 |
280 | if (x < 205 && !badPixelArr[i + 1]) //Right pixel
281 | {
282 | val += arrID3[i + 1];
283 | ++nr;
284 | }
285 |
286 | if (nr>0)
287 | {
288 | val /= nr;
289 | arrID3[i] = val;
290 | }
291 | }
292 | }
293 | }
294 | }
295 |
296 | private void removeNoise()
297 | {
298 | ushort x = 0;
299 | ushort y = 0;
300 | ushort i = 0;
301 | ushort val = 0;
302 | ushort[] arrColor = new ushort[4];
303 |
304 | for (y = 0; y < 156; y++)
305 | {
306 | for (x = 0; x < 208; x++)
307 | {
308 | if (x > 0 && x < 206 && y > 0 && y < 155)
309 | {
310 | arrColor[0] = arrID3[i - 208];//top
311 | arrColor[1] = arrID3[i + 208];//bottom
312 | arrColor[2] = arrID3[i - 1];//left
313 | arrColor[3] = arrID3[i + 1];//right
314 |
315 | val = (ushort)((arrColor[0] + arrColor[1] + arrColor[2] + arrColor[3] - Highest(arrColor) - Lowest(arrColor))/2);
316 |
317 | if (Math.Abs(val - arrID3[i]) > 100 && val != 0)
318 | {
319 | arrID3[i] = val;
320 | }
321 | }
322 | i++;
323 | }
324 | }
325 |
326 | }
327 |
328 | private ushort Highest(ushort[] numbers)
329 | {
330 | ushort highest = 0;
331 |
332 | for (ushort i = 0; i < 4; i++)
333 | {
334 | if (numbers[i] > highest)
335 | highest = numbers[i];
336 | }
337 |
338 | return highest;
339 | }
340 |
341 | private ushort Lowest(ushort[] numbers)
342 | {
343 | ushort lowest = 30000;
344 |
345 | for (ushort i = 0; i < 4; i++)
346 | {
347 | if (numbers[i] < lowest)
348 | lowest = numbers[i];
349 | }
350 |
351 | return lowest;
352 | }
353 |
354 | private void Form1_FormClosing(object sender, FormClosingEventArgs e)
355 | {
356 | stopThread = true;
357 | if (thermal != null)
358 | {
359 | thermalThread.Join(500);
360 | thermal.Deinit();
361 | }
362 | }
363 |
364 | // Button to capture external reference or switch to internal shutter.
365 | private void button1_Click(object sender, EventArgs e)
366 | {
367 | grabExternalReference = true;
368 | }
369 |
370 | // Button to toggle between automatic ranging or manual.
371 | private void button2_Click(object sender, EventArgs e)
372 | {
373 | autoRange = !autoRange;
374 | if (autoRange) {
375 | button2.Text = "Switch to manual range";
376 | cbDynSlidres.Checked = false;
377 | cbDynSlidres.Visible = false;
378 | }
379 | else {
380 | button2.Text = "Switch to auto range";
381 | cbDynSlidres.Visible = true;
382 | }
383 | }
384 |
385 | private void trackBar1_Scroll(object sender, EventArgs e)
386 | {
387 | if (!autoRange)
388 | {
389 | if (trackBar1.Value > trackBar2.Value + 10)
390 | {
391 | gModeRightManual = (ushort)trackBar1.Value;
392 | }
393 | else
394 | {
395 | trackBar1.Value = trackBar2.Value + 10;
396 | }
397 | }
398 | }
399 |
400 | private void trackBar2_Scroll(object sender, EventArgs e)
401 | {
402 | if (!autoRange)
403 | {
404 | if (trackBar2.Value < trackBar1.Value - 10)
405 | {
406 | gModeLeftManual = (ushort)trackBar2.Value;
407 | }
408 | else
409 | {
410 | trackBar2.Value = trackBar1.Value - 10;
411 | }
412 | }
413 | }
414 |
415 | private void cbAutoSave_CheckedChanged(object sender, EventArgs e)
416 | {
417 | autoSaveImg = !autoSaveImg;
418 | }
419 |
420 | private void cbDynSlidres_CheckedChanged(object sender, EventArgs e)
421 | {
422 | dynSliders = !dynSliders;
423 |
424 | int currentLeftPos = trackBar2.Value;
425 | int currentRightPos = trackBar1.Value;
426 | int currentDiff = currentRightPos - currentLeftPos;
427 |
428 | if (dynSliders)
429 | {
430 | if (currentLeftPos - currentDiff > 4000) trackBar2.Minimum = currentLeftPos - currentDiff;//left min
431 | else trackBar2.Minimum = 4000;
432 |
433 | if (currentLeftPos + currentDiff * 2 < 20000) trackBar2.Maximum = currentLeftPos + currentDiff * 2;//left max
434 | else trackBar2.Maximum = 20000;
435 |
436 | if (currentRightPos - currentDiff * 2 > 4000) trackBar1.Minimum = currentRightPos - currentDiff * 2;//right min
437 | else trackBar1.Minimum = 4000;
438 |
439 | if (currentRightPos + currentDiff < 20000) trackBar1.Maximum = currentRightPos + currentDiff;//right max
440 | else trackBar1.Maximum = 20000;
441 | }
442 | else
443 | {
444 | trackBar1.Minimum = 4000;
445 | trackBar2.Minimum = 4000;
446 | trackBar1.Maximum = 20000;
447 | trackBar2.Maximum = 20000;
448 | }
449 | }
450 |
451 | private void checkBox2_CheckedChanged(object sender, EventArgs e)
452 | {
453 | SharpenImage = !SharpenImage;
454 | }
455 |
456 | private void Form1_Load(object sender, EventArgs e)
457 | {
458 | var pngFiles = new DirectoryInfo(Directory.GetCurrentDirectory()+"\\palette").GetFiles("*.png");
459 |
460 | foreach (FileInfo file in pngFiles)
461 | {
462 | cbPal.Items.Add(new ComboItem(file.FullName, file.Name.Replace(".png", "")));
463 | }
464 | cbPal.SelectedIndex = 1;
465 | }
466 |
467 | private void cbPal_SelectedIndexChanged(object sender, EventArgs e)
468 | {
469 | ComboItem newPal = (ComboItem)cbPal.SelectedItem;
470 | Bitmap paletteImg = new Bitmap(newPal.Key);
471 | Color picColor;
472 |
473 | for (int i = 0; i < 1001; i++)
474 | {
475 | picColor = paletteImg.GetPixel(i, 0);
476 | palleteArr[i, 0] = picColor.R;
477 | palleteArr[i, 1] = picColor.G;
478 | palleteArr[i, 2] = picColor.B;
479 | }
480 |
481 | paletteImg.RotateFlip(RotateFlipType.Rotate270FlipNone);
482 | pictureBox4.Image = paletteImg;
483 | }
484 |
485 | class ComboItem
486 | {
487 | public string Key { get; set; }
488 | public string Value { get; set; }
489 | public ComboItem(string key, string value)
490 | {
491 | Key = key; Value = value;
492 | }
493 | public override string ToString()
494 | {
495 | return Value;
496 | }
497 | }
498 |
499 | public ushort GetMode(ushort[] arr)
500 | {
501 | ushort[] arrMode = new ushort[320];
502 | ushort topPos = 0;
503 | for (ushort i = 0; i < 32448; i++)
504 | {
505 | if ((arr[i] > 1000) && (arr[i] / 100 != 0)) arrMode[(arr[i]) / 100]++;
506 | }
507 |
508 | topPos = (ushort)Array.IndexOf(arrMode, arrMode.Max());
509 |
510 | return (ushort)(topPos * 100);
511 | }
512 |
513 | public void getHistogram()
514 | {
515 | maxTempRaw = arrID3.Max();
516 | ushort[] arrMode = new ushort[2100];
517 | ushort topPos = 0;
518 | for (ushort i = 0; i < 32448; i++)
519 | {
520 | if ((arrID3[i] > 1000) && (arrID3[i] / 10 != 0) && !badPixelArr[i]) arrMode[(arrID3[i]) / 10]++;
521 | }
522 |
523 | topPos = (ushort)Array.IndexOf(arrMode, arrMode.Max());
524 |
525 | gMode = arrMode;
526 | gModePeakCnt = arrMode.Max();
527 | gModePeakIx = (ushort)(topPos * 10);
528 |
529 | //lower it to 100px;
530 | for (ushort i = 0; i < 2100; i++)
531 | {
532 | gMode[i] = (ushort)((double)arrMode[i] / gModePeakCnt * 100);
533 | }
534 |
535 | if (autoRange)
536 | {
537 | gModeLeft = gModePeakIx;
538 | gModeRight = gModePeakIx;
539 | //find left border:
540 | for (ushort i = 0; i < topPos; i++)
541 | {
542 | if (arrMode[i] > arrMode[topPos] * 0.01)
543 | {
544 | gModeLeft = (ushort)(i * 10);
545 | break;
546 | }
547 | }
548 |
549 | //find right border:
550 | for (ushort i = 2099; i > topPos; i--)
551 | {
552 | if (arrMode[i] > arrMode[topPos] * 0.01)
553 | {
554 | gModeRight = (ushort)(i * 10);
555 | break;
556 | }
557 | }
558 | gModeLeftManual = gModeLeft;
559 | gModeRightManual = gModeRight;
560 | }
561 | else {
562 | gModeLeft = gModeLeftManual;
563 | gModeRight = gModeRightManual;
564 | }
565 | }
566 |
567 | public void DrawHistogram()
568 | {
569 | int imgWidth = (gModeRight - gModeLeft)/10;
570 | int leftBorder = gModeLeft / 10;
571 | var hist = new Bitmap(imgWidth, 100, PixelFormat.Format24bppRgb);
572 | Pen blackPen = new Pen(Color.Black, 1);
573 |
574 | using (var g = Graphics.FromImage(hist))
575 | {
576 | g.FillRectangle(new SolidBrush(Color.White), 0, 0, imgWidth, 100);
577 |
578 | for (int i = 0; i < imgWidth; i++)
579 | {
580 | g.DrawLine(blackPen, i, 0, i, gMode[leftBorder + i]);
581 | }
582 | }
583 |
584 | hist.RotateFlip(RotateFlipType.Rotate180FlipX);
585 | hist = new Bitmap(hist, new Size(200, 100));
586 |
587 | pictureBox2.Image = hist;
588 | }
589 |
590 | private void button3_Click(object sender, EventArgs e)
591 | {
592 | if (isRunning)
593 | {
594 | thermalThread.Suspend();
595 | button3.Text = "START";
596 | }
597 | else
598 | {
599 | thermalThread.Resume();
600 | button3.Text = "STOP";
601 | }
602 | isRunning = !isRunning;
603 | }
604 |
605 | private string rawToTemp(int val)
606 | {
607 | double tempVal = 0;
608 |
609 | tempVal = (double)(val - 5950) / 40 + 273.15;//K
610 |
611 | switch (tempUnit)
612 | {
613 | case "C":
614 | tempVal = tempVal - 273.15;//C
615 | break;
616 | case "F":
617 | tempVal = tempVal * 9 / 5 - 459.67;//F
618 | break;
619 | }
620 |
621 | return tempVal.ToString("F1", CultureInfo.InvariantCulture);
622 | }
623 |
624 | private void button4_Click(object sender, EventArgs e)
625 | {
626 | usignExternalCal = false;
627 | }
628 |
629 | private void radioButtons_CheckedChanged(object sender, EventArgs e)
630 | {
631 | if (rbUnitsK.Checked) tempUnit = "K";
632 | if (rbUnitsC.Checked) tempUnit = "C";
633 | if (rbUnitsF.Checked) tempUnit = "F";
634 | }
635 |
636 | private void Form1_Paint(object sender, PaintEventArgs e)
637 | {
638 | if (lastUsableFrame != null)
639 | {
640 | string minTemp = rawToTemp(gModeLeft);
641 | string maxTemp = rawToTemp(gModeRight);
642 |
643 | lblSliderMin.Text = minTemp;
644 | lblSliderMax.Text = maxTemp;
645 | lblMinTemp.Text = minTemp;
646 | lblMaxTemp.Text = maxTemp;
647 |
648 | lblLeft.Text = gModeLeft.ToString();
649 | lblRight.Text = gModeRight.ToString();
650 | label2.Text = maxTempRaw.ToString();
651 |
652 | if (autoRange)//set sliders position
653 | {
654 | trackBar2.Value = gModeLeft;
655 | trackBar1.Value = gModeRight;
656 | }
657 |
658 | bitmap_data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
659 | Marshal.Copy(imgBuffer, 0, bitmap_data.Scan0, imgBuffer.Length);
660 | bitmap.UnlockBits(bitmap_data);
661 |
662 | //crop image to 206x156
663 | croppedBitmap = cropFilter.Apply(bitmap);
664 |
665 | //upscale 200 %
666 | bigBitmap = bilinearResize.Apply(croppedBitmap);
667 |
668 | //sharpen image
669 | if (SharpenImage) sfilter.ApplyInPlace(bigBitmap);
670 |
671 | pictureBox3.Image = bigBitmap;
672 |
673 | if (firstAfterCal)
674 | {
675 | firstAfterCal = false;
676 | pictureBox5.Image = bigBitmap;
677 | if (autoSaveImg) bigBitmap.Save(localPath + @"\export\seek_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss_fff") + ".png");
678 | }
679 |
680 | DrawHistogram();
681 | }
682 |
683 | }
684 |
685 | }
686 | }
687 |
--------------------------------------------------------------------------------
/TestSeek/Form1.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace TestSeek
2 | {
3 | partial class Form1
4 | {
5 | ///
6 | /// Required designer variable.
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// Clean up any resources being used.
12 | ///
13 | /// true if managed resources should be disposed; otherwise, false.
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Windows Form Designer generated code
24 |
25 | ///
26 | /// Required method for Designer support - do not modify
27 | /// the contents of this method with the code editor.
28 | ///
29 | private void InitializeComponent()
30 | {
31 | this.components = new System.ComponentModel.Container();
32 | this.button1 = new System.Windows.Forms.Button();
33 | this.label5 = new System.Windows.Forms.Label();
34 | this.trackBar1 = new System.Windows.Forms.TrackBar();
35 | this.trackBar2 = new System.Windows.Forms.TrackBar();
36 | this.button2 = new System.Windows.Forms.Button();
37 | this.cbAutoSave = new System.Windows.Forms.CheckBox();
38 | this.pictureBox1 = new System.Windows.Forms.PictureBox();
39 | this.cbDynSlidres = new System.Windows.Forms.CheckBox();
40 | this.label6 = new System.Windows.Forms.Label();
41 | this.label7 = new System.Windows.Forms.Label();
42 | this.checkBox2 = new System.Windows.Forms.CheckBox();
43 | this.lblSliderMin = new System.Windows.Forms.Label();
44 | this.lblSliderMax = new System.Windows.Forms.Label();
45 | this.button3 = new System.Windows.Forms.Button();
46 | this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
47 | this.toolTip2 = new System.Windows.Forms.ToolTip(this.components);
48 | this.panel1 = new System.Windows.Forms.Panel();
49 | this.label3 = new System.Windows.Forms.Label();
50 | this.rbUnitsF = new System.Windows.Forms.RadioButton();
51 | this.pictureBox2 = new System.Windows.Forms.PictureBox();
52 | this.rbUnitsK = new System.Windows.Forms.RadioButton();
53 | this.rbUnitsC = new System.Windows.Forms.RadioButton();
54 | this.cbPal = new System.Windows.Forms.ComboBox();
55 | this.label13 = new System.Windows.Forms.Label();
56 | this.panel2 = new System.Windows.Forms.Panel();
57 | this.pictureBox3 = new System.Windows.Forms.PictureBox();
58 | this.lblLeft = new System.Windows.Forms.Label();
59 | this.lblRight = new System.Windows.Forms.Label();
60 | this.pictureBox4 = new System.Windows.Forms.PictureBox();
61 | this.pictureBox5 = new System.Windows.Forms.PictureBox();
62 | this.label2 = new System.Windows.Forms.Label();
63 | this.lblMaxTemp = new System.Windows.Forms.Label();
64 | this.lblMinTemp = new System.Windows.Forms.Label();
65 | this.button4 = new System.Windows.Forms.Button();
66 | ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
67 | ((System.ComponentModel.ISupportInitialize)(this.trackBar2)).BeginInit();
68 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
69 | this.panel1.SuspendLayout();
70 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
71 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
72 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).BeginInit();
73 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).BeginInit();
74 | this.SuspendLayout();
75 | //
76 | // button1
77 | //
78 | this.button1.Location = new System.Drawing.Point(151, 6);
79 | this.button1.Name = "button1";
80 | this.button1.Size = new System.Drawing.Size(60, 25);
81 | this.button1.TabIndex = 0;
82 | this.button1.Text = "EXT Cal";
83 | this.toolTip2.SetToolTip(this.button1, "Do external calibration");
84 | this.button1.UseVisualStyleBackColor = true;
85 | this.button1.Click += new System.EventHandler(this.button1_Click);
86 | //
87 | // label5
88 | //
89 | this.label5.AutoSize = true;
90 | this.label5.Location = new System.Drawing.Point(480, 166);
91 | this.label5.Name = "label5";
92 | this.label5.Size = new System.Drawing.Size(0, 13);
93 | this.label5.TabIndex = 7;
94 | //
95 | // trackBar1
96 | //
97 | this.trackBar1.CausesValidation = false;
98 | this.trackBar1.LargeChange = 100;
99 | this.trackBar1.Location = new System.Drawing.Point(12, 396);
100 | this.trackBar1.Maximum = 20000;
101 | this.trackBar1.Minimum = 4000;
102 | this.trackBar1.Name = "trackBar1";
103 | this.trackBar1.Size = new System.Drawing.Size(1102, 45);
104 | this.trackBar1.SmallChange = 10;
105 | this.trackBar1.TabIndex = 11;
106 | this.trackBar1.TickStyle = System.Windows.Forms.TickStyle.TopLeft;
107 | this.trackBar1.Value = 4000;
108 | this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
109 | //
110 | // trackBar2
111 | //
112 | this.trackBar2.CausesValidation = false;
113 | this.trackBar2.LargeChange = 100;
114 | this.trackBar2.Location = new System.Drawing.Point(12, 370);
115 | this.trackBar2.Maximum = 20000;
116 | this.trackBar2.Minimum = 4000;
117 | this.trackBar2.Name = "trackBar2";
118 | this.trackBar2.Size = new System.Drawing.Size(1102, 45);
119 | this.trackBar2.SmallChange = 10;
120 | this.trackBar2.TabIndex = 12;
121 | this.trackBar2.TickFrequency = 100;
122 | this.trackBar2.TickStyle = System.Windows.Forms.TickStyle.None;
123 | this.trackBar2.Value = 4000;
124 | this.trackBar2.Scroll += new System.EventHandler(this.trackBar2_Scroll);
125 | //
126 | // button2
127 | //
128 | this.button2.Location = new System.Drawing.Point(11, 264);
129 | this.button2.Name = "button2";
130 | this.button2.Size = new System.Drawing.Size(200, 35);
131 | this.button2.TabIndex = 13;
132 | this.button2.Text = "Switch to manual range";
133 | this.button2.UseVisualStyleBackColor = true;
134 | this.button2.Click += new System.EventHandler(this.button2_Click);
135 | //
136 | // cbAutoSave
137 | //
138 | this.cbAutoSave.AutoSize = true;
139 | this.cbAutoSave.Location = new System.Drawing.Point(11, 94);
140 | this.cbAutoSave.Name = "cbAutoSave";
141 | this.cbAutoSave.Size = new System.Drawing.Size(73, 17);
142 | this.cbAutoSave.TabIndex = 14;
143 | this.cbAutoSave.Text = "AutoSave";
144 | this.cbAutoSave.UseVisualStyleBackColor = true;
145 | this.cbAutoSave.CheckedChanged += new System.EventHandler(this.cbAutoSave_CheckedChanged);
146 | //
147 | // pictureBox1
148 | //
149 | this.pictureBox1.Location = new System.Drawing.Point(23, 802);
150 | this.pictureBox1.Name = "pictureBox1";
151 | this.pictureBox1.Size = new System.Drawing.Size(1001, 1);
152 | this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
153 | this.pictureBox1.TabIndex = 15;
154 | this.pictureBox1.TabStop = false;
155 | //
156 | // cbDynSlidres
157 | //
158 | this.cbDynSlidres.AutoSize = true;
159 | this.cbDynSlidres.Location = new System.Drawing.Point(11, 305);
160 | this.cbDynSlidres.Name = "cbDynSlidres";
161 | this.cbDynSlidres.Size = new System.Drawing.Size(128, 17);
162 | this.cbDynSlidres.TabIndex = 16;
163 | this.cbDynSlidres.Text = "Enable relative sliders";
164 | this.cbDynSlidres.UseVisualStyleBackColor = true;
165 | this.cbDynSlidres.Visible = false;
166 | this.cbDynSlidres.CheckedChanged += new System.EventHandler(this.cbDynSlidres_CheckedChanged);
167 | //
168 | // label6
169 | //
170 | this.label6.AutoSize = true;
171 | this.label6.Location = new System.Drawing.Point(9, 5);
172 | this.label6.Name = "label6";
173 | this.label6.Size = new System.Drawing.Size(30, 13);
174 | this.label6.TabIndex = 17;
175 | this.label6.Text = "Live:";
176 | //
177 | // label7
178 | //
179 | this.label7.AutoSize = true;
180 | this.label7.Location = new System.Drawing.Point(699, 5);
181 | this.label7.Name = "label7";
182 | this.label7.Size = new System.Drawing.Size(70, 13);
183 | this.label7.TabIndex = 18;
184 | this.label7.Text = "First after cal:";
185 | //
186 | // checkBox2
187 | //
188 | this.checkBox2.AutoSize = true;
189 | this.checkBox2.Location = new System.Drawing.Point(11, 117);
190 | this.checkBox2.Name = "checkBox2";
191 | this.checkBox2.Size = new System.Drawing.Size(117, 17);
192 | this.checkBox2.TabIndex = 20;
193 | this.checkBox2.Text = "Apply Sharpen filter";
194 | this.checkBox2.UseVisualStyleBackColor = true;
195 | this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged);
196 | //
197 | // lblSliderMin
198 | //
199 | this.lblSliderMin.AutoSize = true;
200 | this.lblSliderMin.Location = new System.Drawing.Point(16, 354);
201 | this.lblSliderMin.Name = "lblSliderMin";
202 | this.lblSliderMin.Size = new System.Drawing.Size(27, 13);
203 | this.lblSliderMin.TabIndex = 22;
204 | this.lblSliderMin.Text = "MIN";
205 | this.lblSliderMin.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
206 | //
207 | // lblSliderMax
208 | //
209 | this.lblSliderMax.AutoSize = true;
210 | this.lblSliderMax.Location = new System.Drawing.Point(1084, 425);
211 | this.lblSliderMax.Name = "lblSliderMax";
212 | this.lblSliderMax.Size = new System.Drawing.Size(30, 13);
213 | this.lblSliderMax.TabIndex = 23;
214 | this.lblSliderMax.Text = "MAX";
215 | this.lblSliderMax.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
216 | //
217 | // button3
218 | //
219 | this.button3.Location = new System.Drawing.Point(10, 6);
220 | this.button3.Name = "button3";
221 | this.button3.Size = new System.Drawing.Size(60, 25);
222 | this.button3.TabIndex = 27;
223 | this.button3.Text = "STOP";
224 | this.toolTip1.SetToolTip(this.button3, "Start / Stop Streaming");
225 | this.button3.UseVisualStyleBackColor = true;
226 | this.button3.Click += new System.EventHandler(this.button3_Click);
227 | //
228 | // panel1
229 | //
230 | this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
231 | this.panel1.Controls.Add(this.button4);
232 | this.panel1.Controls.Add(this.label3);
233 | this.panel1.Controls.Add(this.rbUnitsF);
234 | this.panel1.Controls.Add(this.pictureBox2);
235 | this.panel1.Controls.Add(this.rbUnitsK);
236 | this.panel1.Controls.Add(this.rbUnitsC);
237 | this.panel1.Controls.Add(this.cbPal);
238 | this.panel1.Controls.Add(this.label13);
239 | this.panel1.Controls.Add(this.cbAutoSave);
240 | this.panel1.Controls.Add(this.button3);
241 | this.panel1.Controls.Add(this.checkBox2);
242 | this.panel1.Controls.Add(this.button2);
243 | this.panel1.Controls.Add(this.cbDynSlidres);
244 | this.panel1.Controls.Add(this.button1);
245 | this.panel1.Location = new System.Drawing.Point(471, 5);
246 | this.panel1.Name = "panel1";
247 | this.panel1.Size = new System.Drawing.Size(225, 327);
248 | this.panel1.TabIndex = 28;
249 | //
250 | // label3
251 | //
252 | this.label3.AutoSize = true;
253 | this.label3.Location = new System.Drawing.Point(8, 73);
254 | this.label3.Name = "label3";
255 | this.label3.Size = new System.Drawing.Size(62, 13);
256 | this.label3.TabIndex = 33;
257 | this.label3.Text = "Temp units:";
258 | //
259 | // rbUnitsF
260 | //
261 | this.rbUnitsF.AutoSize = true;
262 | this.rbUnitsF.Location = new System.Drawing.Point(154, 71);
263 | this.rbUnitsF.Name = "rbUnitsF";
264 | this.rbUnitsF.Size = new System.Drawing.Size(35, 17);
265 | this.rbUnitsF.TabIndex = 26;
266 | this.rbUnitsF.Text = "°F";
267 | this.rbUnitsF.UseVisualStyleBackColor = true;
268 | //
269 | // pictureBox2
270 | //
271 | this.pictureBox2.BackColor = System.Drawing.SystemColors.ControlLightLight;
272 | this.pictureBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
273 | this.pictureBox2.Location = new System.Drawing.Point(10, 140);
274 | this.pictureBox2.Name = "pictureBox2";
275 | this.pictureBox2.Size = new System.Drawing.Size(200, 100);
276 | this.pictureBox2.TabIndex = 40;
277 | this.pictureBox2.TabStop = false;
278 | //
279 | // rbUnitsK
280 | //
281 | this.rbUnitsK.AutoSize = true;
282 | this.rbUnitsK.Checked = true;
283 | this.rbUnitsK.Location = new System.Drawing.Point(76, 71);
284 | this.rbUnitsK.Name = "rbUnitsK";
285 | this.rbUnitsK.Size = new System.Drawing.Size(32, 17);
286 | this.rbUnitsK.TabIndex = 32;
287 | this.rbUnitsK.TabStop = true;
288 | this.rbUnitsK.Text = "K";
289 | this.rbUnitsK.UseVisualStyleBackColor = true;
290 | //
291 | // rbUnitsC
292 | //
293 | this.rbUnitsC.AutoSize = true;
294 | this.rbUnitsC.Location = new System.Drawing.Point(114, 71);
295 | this.rbUnitsC.Name = "rbUnitsC";
296 | this.rbUnitsC.Size = new System.Drawing.Size(36, 17);
297 | this.rbUnitsC.TabIndex = 25;
298 | this.rbUnitsC.Text = "°C";
299 | this.rbUnitsC.UseVisualStyleBackColor = true;
300 | //
301 | // cbPal
302 | //
303 | this.cbPal.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
304 | this.cbPal.FormattingEnabled = true;
305 | this.cbPal.Location = new System.Drawing.Point(57, 35);
306 | this.cbPal.Name = "cbPal";
307 | this.cbPal.Size = new System.Drawing.Size(154, 21);
308 | this.cbPal.TabIndex = 31;
309 | this.cbPal.SelectedIndexChanged += new System.EventHandler(this.cbPal_SelectedIndexChanged);
310 | //
311 | // label13
312 | //
313 | this.label13.AutoSize = true;
314 | this.label13.Location = new System.Drawing.Point(8, 38);
315 | this.label13.Name = "label13";
316 | this.label13.Size = new System.Drawing.Size(43, 13);
317 | this.label13.TabIndex = 30;
318 | this.label13.Text = "Palette:";
319 | //
320 | // panel2
321 | //
322 | this.panel2.Location = new System.Drawing.Point(19, 393);
323 | this.panel2.Name = "panel2";
324 | this.panel2.Size = new System.Drawing.Size(1095, 12);
325 | this.panel2.TabIndex = 33;
326 | //
327 | // pictureBox3
328 | //
329 | this.pictureBox3.Location = new System.Drawing.Point(12, 20);
330 | this.pictureBox3.Name = "pictureBox3";
331 | this.pictureBox3.Size = new System.Drawing.Size(412, 312);
332 | this.pictureBox3.TabIndex = 34;
333 | this.pictureBox3.TabStop = false;
334 | //
335 | // lblLeft
336 | //
337 | this.lblLeft.AutoSize = true;
338 | this.lblLeft.Location = new System.Drawing.Point(315, 454);
339 | this.lblLeft.Name = "lblLeft";
340 | this.lblLeft.Size = new System.Drawing.Size(41, 13);
341 | this.lblLeft.TabIndex = 35;
342 | this.lblLeft.Text = "label14";
343 | //
344 | // lblRight
345 | //
346 | this.lblRight.AutoSize = true;
347 | this.lblRight.Location = new System.Drawing.Point(815, 454);
348 | this.lblRight.Name = "lblRight";
349 | this.lblRight.Size = new System.Drawing.Size(41, 13);
350 | this.lblRight.TabIndex = 36;
351 | this.lblRight.Text = "label15";
352 | //
353 | // pictureBox4
354 | //
355 | this.pictureBox4.Location = new System.Drawing.Point(432, 20);
356 | this.pictureBox4.Name = "pictureBox4";
357 | this.pictureBox4.Size = new System.Drawing.Size(33, 312);
358 | this.pictureBox4.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
359 | this.pictureBox4.TabIndex = 37;
360 | this.pictureBox4.TabStop = false;
361 | //
362 | // pictureBox5
363 | //
364 | this.pictureBox5.Location = new System.Drawing.Point(702, 20);
365 | this.pictureBox5.Name = "pictureBox5";
366 | this.pictureBox5.Size = new System.Drawing.Size(412, 312);
367 | this.pictureBox5.TabIndex = 38;
368 | this.pictureBox5.TabStop = false;
369 | //
370 | // label2
371 | //
372 | this.label2.AutoSize = true;
373 | this.label2.Location = new System.Drawing.Point(570, 454);
374 | this.label2.Name = "label2";
375 | this.label2.Size = new System.Drawing.Size(41, 13);
376 | this.label2.TabIndex = 39;
377 | this.label2.Text = "label15";
378 | //
379 | // lblMaxTemp
380 | //
381 | this.lblMaxTemp.AutoSize = true;
382 | this.lblMaxTemp.Location = new System.Drawing.Point(429, 5);
383 | this.lblMaxTemp.Name = "lblMaxTemp";
384 | this.lblMaxTemp.Size = new System.Drawing.Size(28, 13);
385 | this.lblMaxTemp.TabIndex = 41;
386 | this.lblMaxTemp.Text = "30.5";
387 | //
388 | // lblMinTemp
389 | //
390 | this.lblMinTemp.AutoSize = true;
391 | this.lblMinTemp.Location = new System.Drawing.Point(429, 335);
392 | this.lblMinTemp.Name = "lblMinTemp";
393 | this.lblMinTemp.Size = new System.Drawing.Size(28, 13);
394 | this.lblMinTemp.TabIndex = 42;
395 | this.lblMinTemp.Text = "20.5";
396 | //
397 | // button4
398 | //
399 | this.button4.Location = new System.Drawing.Point(80, 6);
400 | this.button4.Name = "button4";
401 | this.button4.Size = new System.Drawing.Size(60, 25);
402 | this.button4.TabIndex = 43;
403 | this.button4.Text = "INT Cal";
404 | this.toolTip2.SetToolTip(this.button4, "Do external calibration");
405 | this.button4.UseVisualStyleBackColor = true;
406 | this.button4.Click += new System.EventHandler(this.button4_Click);
407 | //
408 | // Form1
409 | //
410 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
411 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
412 | this.BackColor = System.Drawing.SystemColors.Control;
413 | this.ClientSize = new System.Drawing.Size(1131, 447);
414 | this.Controls.Add(this.lblMinTemp);
415 | this.Controls.Add(this.lblMaxTemp);
416 | this.Controls.Add(this.label2);
417 | this.Controls.Add(this.pictureBox5);
418 | this.Controls.Add(this.pictureBox4);
419 | this.Controls.Add(this.lblRight);
420 | this.Controls.Add(this.lblLeft);
421 | this.Controls.Add(this.pictureBox3);
422 | this.Controls.Add(this.panel2);
423 | this.Controls.Add(this.lblSliderMax);
424 | this.Controls.Add(this.lblSliderMin);
425 | this.Controls.Add(this.trackBar1);
426 | this.Controls.Add(this.label7);
427 | this.Controls.Add(this.label6);
428 | this.Controls.Add(this.pictureBox1);
429 | this.Controls.Add(this.trackBar2);
430 | this.Controls.Add(this.label5);
431 | this.Controls.Add(this.panel1);
432 | this.Name = "Form1";
433 | this.Text = "SeekOFix v0.4";
434 | this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
435 | this.Load += new System.EventHandler(this.Form1_Load);
436 | this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
437 | ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
438 | ((System.ComponentModel.ISupportInitialize)(this.trackBar2)).EndInit();
439 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
440 | this.panel1.ResumeLayout(false);
441 | this.panel1.PerformLayout();
442 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
443 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
444 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).EndInit();
445 | ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).EndInit();
446 | this.ResumeLayout(false);
447 | this.PerformLayout();
448 |
449 | }
450 |
451 | #endregion
452 |
453 | private System.Windows.Forms.Button button1;
454 | private System.Windows.Forms.Label label5;
455 | private System.Windows.Forms.TrackBar trackBar1;
456 | private System.Windows.Forms.TrackBar trackBar2;
457 | private System.Windows.Forms.Button button2;
458 | private System.Windows.Forms.CheckBox cbAutoSave;
459 | private System.Windows.Forms.PictureBox pictureBox1;
460 | private System.Windows.Forms.CheckBox cbDynSlidres;
461 | private System.Windows.Forms.Label label6;
462 | private System.Windows.Forms.Label label7;
463 | private System.Windows.Forms.CheckBox checkBox2;
464 | private System.Windows.Forms.Label lblSliderMin;
465 | private System.Windows.Forms.Label lblSliderMax;
466 | private System.Windows.Forms.Button button3;
467 | private System.Windows.Forms.ToolTip toolTip1;
468 | private System.Windows.Forms.ToolTip toolTip2;
469 | private System.Windows.Forms.Panel panel1;
470 | private System.Windows.Forms.Label label13;
471 | private System.Windows.Forms.ComboBox cbPal;
472 | private System.Windows.Forms.Panel panel2;
473 | private System.Windows.Forms.PictureBox pictureBox3;
474 | private System.Windows.Forms.Label lblLeft;
475 | private System.Windows.Forms.Label lblRight;
476 | private System.Windows.Forms.PictureBox pictureBox4;
477 | private System.Windows.Forms.PictureBox pictureBox5;
478 | private System.Windows.Forms.Label label2;
479 | private System.Windows.Forms.PictureBox pictureBox2;
480 | private System.Windows.Forms.Label lblMaxTemp;
481 | private System.Windows.Forms.Label lblMinTemp;
482 | private System.Windows.Forms.Label label3;
483 | private System.Windows.Forms.RadioButton rbUnitsF;
484 | private System.Windows.Forms.RadioButton rbUnitsK;
485 | private System.Windows.Forms.RadioButton rbUnitsC;
486 | private System.Windows.Forms.Button button4;
487 | }
488 | }
489 |
490 |
--------------------------------------------------------------------------------
/TestSeek/NativeMethods.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Linq;
5 | using System.Runtime.InteropServices;
6 | using System.Text;
7 | using System.Threading;
8 | using System.Threading.Tasks;
9 | using Microsoft.Win32.SafeHandles;
10 |
11 | namespace winusbdotnet
12 | {
13 |
14 | internal class EnumeratedDevice
15 | {
16 | public string DevicePath { get; set; }
17 | public Guid InterfaceGuid { get; set; }
18 | public string DeviceDescription { get; set; }
19 | public string Manufacturer { get; set; }
20 | public string FriendlyName { get; set; }
21 | }
22 |
23 | internal class NativeMethods
24 | {
25 |
26 | private struct SP_DEVINFO_DATA
27 | {
28 | public UInt32 cbSize;
29 | public Guid classGuid;
30 | public UInt32 devInst;
31 | public IntPtr reserved;
32 | }
33 |
34 | private struct SP_DEVICE_INTERFACE_DATA
35 | {
36 | public UInt32 cbSize;
37 | public Guid interfaceClassGuid;
38 | public UInt32 flags;
39 | public IntPtr reserved;
40 | }
41 |
42 | private struct DEVPROPKEY
43 | {
44 | public Guid fmtId;
45 | public UInt32 pId;
46 |
47 |
48 | //DEFINE_DEVPROPKEY(DEVPKEY_Device_DeviceDesc, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 2); // DEVPROP_TYPE_STRING
49 | //DEFINE_DEVPROPKEY(DEVPKEY_Device_Manufacturer, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 13); // DEVPROP_TYPE_STRING
50 | //DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14); // DEVPROP_TYPE_STRING
51 |
52 | public static DEVPROPKEY Device_DeviceDesc { get { return new DEVPROPKEY() { fmtId = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pId = 2 }; } }
53 | public static DEVPROPKEY Device_Manufacturer { get { return new DEVPROPKEY() { fmtId = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pId = 13 }; } }
54 | public static DEVPROPKEY Device_FriendlyName { get { return new DEVPROPKEY() { fmtId = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pId = 14 }; } }
55 | }
56 |
57 | private const UInt32 DIGCF_PRESENT = 2;
58 | private const UInt32 DIGCF_ALLCLASSES = 4;
59 | private const UInt32 DIGCF_DEVICEINTERFACE = 0x10;
60 |
61 | private static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
62 |
63 | private const int ERROR_NOT_FOUND = 1168;
64 | private const int ERROR_FILE_NOT_FOUND = 2;
65 | private const int ERROR_NO_MORE_ITEMS = 259;
66 | private const int ERROR_INSUFFICIENT_BUFFER = 122;
67 | private const int ERROR_MORE_DATA = 234;
68 |
69 | public const int ERROR_SEM_TIMEOUT = 121;
70 | public const int ERROR_IO_PENDING = 997;
71 |
72 | private const int DICS_FLAG_GLOBAL = 1;
73 | private const int DICS_FLAG_CONFIGSPECIFIC = 2;
74 |
75 | private const int DIREG_DEV = 1;
76 | private const int DIREG_DRV = 2;
77 |
78 | private const int KEY_READ = 0x20019; // Registry SAM value.
79 |
80 | private const int RRF_RT_REG_SZ = 2;
81 | private const int RRF_RT_REG_MULTI_SZ = 0x20;
82 |
83 |
84 | ///
85 | /// Retrieve device paths that can be opened from a specific device interface guid.
86 | /// todo: Make this friendlier & query some more data about the devices being returned.
87 | ///
88 | /// Guid uniquely identifying the interface to search for
89 | /// List of device paths that can be opened with CreateFile
90 | public static EnumeratedDevice[] EnumerateDevicesByInterface(Guid deviceInterface)
91 | {
92 | // Horribe horrible things have to be done with SetupDI here. These travesties must never leave this class.
93 | List outputPaths = new List();
94 |
95 | IntPtr devInfo = SetupDiGetClassDevs(ref deviceInterface, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
96 | if(devInfo == INVALID_HANDLE_VALUE)
97 | {
98 | throw new Exception("SetupDiGetClassDevs failed. " + (new Win32Exception()).ToString());
99 | }
100 |
101 | try
102 | {
103 | uint deviceIndex = 0;
104 | SP_DEVICE_INTERFACE_DATA interfaceData = new SP_DEVICE_INTERFACE_DATA();
105 |
106 | bool success = true;
107 | for (deviceIndex = 0; ; deviceIndex++)
108 | {
109 | interfaceData.cbSize = (uint)Marshal.SizeOf(interfaceData);
110 | success = SetupDiEnumDeviceInterfaces(devInfo, IntPtr.Zero, ref deviceInterface, deviceIndex, ref interfaceData);
111 | if (!success)
112 | {
113 | if (Marshal.GetLastWin32Error() != ERROR_NO_MORE_ITEMS)
114 | {
115 | throw new Exception("SetupDiEnumDeviceInterfaces failed " + (new Win32Exception()).ToString());
116 | }
117 | // We have reached the end of the list of devices.
118 | break;
119 | }
120 |
121 | // This is a valid interface, retrieve its path
122 | EnumeratedDevice dev = new EnumeratedDevice() { DevicePath = RetrieveDeviceInstancePath(devInfo, interfaceData), InterfaceGuid = deviceInterface };
123 |
124 |
125 | // Todo: debug. Not working correctly.
126 | /*
127 | dev.DeviceDescription = RetrieveDeviceInstancePropertyString(devInfo, interfaceData, DEVPROPKEY.Device_DeviceDesc);
128 | dev.Manufacturer = RetrieveDeviceInstancePropertyString(devInfo, interfaceData, DEVPROPKEY.Device_Manufacturer);
129 | dev.FriendlyName = RetrieveDeviceInstancePropertyString(devInfo, interfaceData, DEVPROPKEY.Device_FriendlyName);
130 | */
131 |
132 | outputPaths.Add(dev);
133 | }
134 | }
135 | finally
136 | {
137 | SetupDiDestroyDeviceInfoList(devInfo);
138 | }
139 |
140 | return outputPaths.ToArray();
141 | }
142 |
143 | public static EnumeratedDevice[] EnumerateAllWinUsbDevices()
144 | {
145 | List outputDevices = new List();
146 | string[] guids = EnumerateAllWinUsbGuids();
147 | foreach (string guid in guids)
148 | {
149 | try
150 | {
151 | Guid g = new Guid(guid);
152 | outputDevices.AddRange(EnumerateDevicesByInterface(g));
153 | }
154 | catch
155 | {
156 | // Ignore failing guid conversions.
157 | }
158 | }
159 | return outputDevices.ToArray();
160 | }
161 |
162 | public static string[] EnumerateAllWinUsbGuids()
163 | {
164 | // Horribe horrible things have to be done with SetupDI here. These travesties must never leave this class.
165 | List outputGuids = new List();
166 |
167 | IntPtr devInfo = SetupDiGetClassDevs(IntPtr.Zero, null, IntPtr.Zero, DIGCF_ALLCLASSES | DIGCF_PRESENT);
168 | if (devInfo == INVALID_HANDLE_VALUE)
169 | {
170 | throw new Exception("SetupDiGetClassDevs failed. " + (new Win32Exception()).ToString());
171 | }
172 |
173 | try
174 | {
175 | uint deviceIndex = 0;
176 | SP_DEVINFO_DATA devInfoData = new SP_DEVINFO_DATA();
177 |
178 | bool success = true;
179 | for (deviceIndex = 0; ; deviceIndex++)
180 | {
181 | devInfoData.cbSize = (uint)Marshal.SizeOf(devInfoData);
182 | success = SetupDiEnumDeviceInfo(devInfo, deviceIndex, ref devInfoData);
183 | if (!success)
184 | {
185 | if (Marshal.GetLastWin32Error() != ERROR_NO_MORE_ITEMS)
186 | {
187 | throw new Exception("SetupDiEnumDeviceInfo failed " + (new Win32Exception()).ToString());
188 | }
189 | // We have reached the end of the list of devices.
190 | break;
191 | }
192 |
193 | // Enumerate the WinUSB Interface Guids (if present) by looking at the registry.
194 | //DebugEnumRegistryValues(devInfo, devInfoData);
195 | string guid = RetrieveDeviceProperty(devInfo, devInfoData, "DeviceInterfaceGUIDs");
196 | if(guid == null)
197 | {
198 | guid = RetrieveDeviceProperty(devInfo, devInfoData, "DeviceInterfaceGUID");
199 | }
200 |
201 | if (guid != null)
202 | {
203 | outputGuids.Add(guid);
204 | }
205 | }
206 | }
207 | finally
208 | {
209 | SetupDiDestroyDeviceInfoList(devInfo);
210 | }
211 |
212 | return outputGuids.Distinct().ToArray();
213 | }
214 |
215 | static void DebugEnumRegistryValues(IntPtr devInfo, SP_DEVINFO_DATA devInfoData)
216 | {
217 | System.Console.WriteLine("DebugEnumRegistryValues");
218 | IntPtr hKey = SetupDiOpenDevRegKey(devInfo, ref devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
219 | if (hKey == INVALID_HANDLE_VALUE)
220 | {
221 | System.Console.WriteLine("Failed");
222 | return;
223 | throw new Exception("SetupDiGetClassDevs failed. " + (new Win32Exception()).ToString());
224 | }
225 |
226 | try
227 | {
228 |
229 | IntPtr memValue = Marshal.AllocHGlobal(16384);
230 | try
231 | {
232 | IntPtr memData = Marshal.AllocHGlobal(65536);
233 | try
234 | {
235 |
236 | for (int i = 0; ; i++)
237 | {
238 | UInt32 outValueLen = 16384;
239 | UInt32 outDataLen = 65536;
240 | UInt32 outType;
241 | long output = RegEnumValue(hKey, (uint)i, memValue, ref outValueLen, IntPtr.Zero, out outType, memData, ref outDataLen);
242 | if((int)output == ERROR_NO_MORE_ITEMS)
243 | {
244 | break;
245 | }
246 | if (output != 0)
247 | {
248 | throw new Exception("RegEnumValue failed " + (new Win32Exception((int)output)).ToString());
249 | }
250 |
251 | string value = ReadAsciiString(memValue, (int)outValueLen);
252 | string data = ReadAsciiString(memData, (int)outDataLen);
253 |
254 | Console.WriteLine("Enum: '{0}' - {2} '{1}'", value, data, outType);
255 |
256 | }
257 |
258 | }
259 | finally
260 | {
261 | Marshal.FreeHGlobal(memData);
262 | }
263 | }
264 | finally
265 | {
266 | Marshal.FreeHGlobal(memValue);
267 | }
268 |
269 | }
270 | finally
271 | {
272 | RegCloseKey(hKey);
273 | }
274 | }
275 |
276 |
277 |
278 |
279 | static string RetrieveDeviceProperty(IntPtr devInfo, SP_DEVINFO_DATA devInfoData, string deviceProperty)
280 | {
281 | IntPtr hKey = SetupDiOpenDevRegKey(devInfo, ref devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
282 | if (hKey == INVALID_HANDLE_VALUE)
283 | {
284 | return null; // Ignore failures, probably the key doesn't exist.
285 | }
286 |
287 | try
288 | {
289 | UInt32 outType;
290 | UInt32 outLength = 0;
291 | long output = RegGetValue(hKey, null, deviceProperty, RRF_RT_REG_SZ | RRF_RT_REG_MULTI_SZ, out outType, IntPtr.Zero, ref outLength);
292 | if(output == ERROR_FILE_NOT_FOUND)
293 | {
294 | return null; // Key not present, don't continue.
295 | }
296 | if (output != 0)
297 | {
298 | throw new Exception("RegGetValue failed (determining length) " + (new Win32Exception((int)output)).ToString());
299 | }
300 |
301 | IntPtr mem = Marshal.AllocHGlobal((int)outLength);
302 | try
303 | {
304 |
305 | UInt32 actualLength = outLength;
306 | output = RegGetValue(hKey, null, deviceProperty, RRF_RT_REG_SZ | RRF_RT_REG_MULTI_SZ, out outType, mem, ref actualLength);
307 | if (output != 0)
308 | {
309 | throw new Exception("RegGetValue failed (retrieving data) " + (new Win32Exception((int)output)).ToString());
310 | }
311 |
312 | // Convert TCHAR string into chars.
313 | if (actualLength > outLength)
314 | {
315 | throw new Exception("Consistency issue: Actual length should not be larger than buffer size.");
316 | }
317 |
318 | return ReadAsciiString(mem, (int)((actualLength)));
319 | }
320 | finally
321 | {
322 | Marshal.FreeHGlobal(mem);
323 | }
324 |
325 | }
326 | finally
327 | {
328 | RegCloseKey(hKey);
329 | }
330 | }
331 |
332 | static string RetrieveDeviceInstancePath(IntPtr devInfo, SP_DEVICE_INTERFACE_DATA interfaceData)
333 | {
334 | // This is a valid interface, retrieve its path
335 | UInt32 requiredLength = 0;
336 |
337 | if (!SetupDiGetDeviceInterfaceDetail(devInfo, ref interfaceData, IntPtr.Zero, 0, ref requiredLength, IntPtr.Zero))
338 | {
339 | int err = Marshal.GetLastWin32Error();
340 |
341 | if (err != ERROR_INSUFFICIENT_BUFFER)
342 | {
343 | throw new Exception("SetupDiGetDeviceInterfaceDetail failed (determining length) " + (new Win32Exception()).ToString());
344 | }
345 | }
346 |
347 | UInt32 actualLength = requiredLength;
348 | Int32 structLen = 6;
349 | if (IntPtr.Size == 8) structLen = 8; // Compensate for 64bit struct packing.
350 |
351 | if (requiredLength < structLen)
352 | {
353 | throw new Exception("Consistency issue: Required memory size should be larger");
354 | }
355 |
356 | IntPtr mem = Marshal.AllocHGlobal((int)requiredLength);
357 |
358 | try
359 | {
360 | Marshal.WriteInt32(mem, structLen); // set fake size in fake structure
361 |
362 | if (!SetupDiGetDeviceInterfaceDetail(devInfo, ref interfaceData, mem, requiredLength, ref actualLength, IntPtr.Zero))
363 | {
364 | throw new Exception("SetupDiGetDeviceInterfaceDetail failed (retrieving data) " + (new Win32Exception()).ToString());
365 | }
366 |
367 | // Convert TCHAR string into chars.
368 | if (actualLength > requiredLength)
369 | {
370 | throw new Exception("Consistency issue: Actual length should not be larger than buffer size.");
371 | }
372 |
373 | return ReadString(mem, (int)((actualLength - 4) / 2), 4);
374 | }
375 | finally
376 | {
377 | Marshal.FreeHGlobal(mem);
378 | }
379 | }
380 |
381 | static string RetrieveDeviceInstancePropertyString(IntPtr devInfo, SP_DEVICE_INTERFACE_DATA interfaceData, DEVPROPKEY property)
382 | {
383 | // This is a valid interface, retrieve its path
384 | UInt32 requiredLength = 0;
385 | UInt32 propertyType;
386 |
387 | if (!SetupDiGetDeviceInterfaceProperty(devInfo, ref interfaceData, ref property, out propertyType, IntPtr.Zero, 0, out requiredLength, 0))
388 | {
389 | int err = Marshal.GetLastWin32Error();
390 | if (err == ERROR_NOT_FOUND)
391 | {
392 | return null;
393 | }
394 |
395 | if (err != ERROR_INSUFFICIENT_BUFFER)
396 | {
397 | throw new Exception("SetupDiGetDeviceInterfaceProperty failed (determining length) " + (new Win32Exception()).ToString());
398 | }
399 |
400 | }
401 |
402 | UInt32 actualLength = requiredLength;
403 |
404 |
405 | IntPtr mem = Marshal.AllocHGlobal((int)requiredLength);
406 | try
407 | {
408 | Marshal.WriteInt32(mem, 6); // set fake size in fake structure
409 |
410 | if (!SetupDiGetDeviceInterfaceProperty(devInfo, ref interfaceData, ref property, out propertyType, mem, requiredLength, out actualLength, 0))
411 | {
412 | throw new Exception("SetupDiGetDeviceInterfaceProperty failed (retrieving data) " + (new Win32Exception()).ToString());
413 | }
414 |
415 | // Convert TCHAR string into chars.
416 | if (actualLength > requiredLength)
417 | {
418 | throw new Exception("Consistency issue: Actual length should not be larger than buffer size.");
419 | }
420 |
421 | return ReadString(mem, (int)((actualLength) / 2));
422 | }
423 | finally
424 | {
425 | Marshal.FreeHGlobal(mem);
426 | }
427 | }
428 |
429 |
430 | static string ReadString(IntPtr source, int length, int offset = 0)
431 | {
432 | char[] stringChars = new char[length];
433 | for (int i = 0; i < length; i++)
434 | {
435 | stringChars[i] = (char)Marshal.ReadInt16(source, i * 2 + offset);
436 | if (stringChars[i] == 0) { length = i; break; }
437 | }
438 | return new string(stringChars, 0, length);
439 | }
440 |
441 |
442 | static string ReadAsciiString(IntPtr source, int length, int offset = 0)
443 | {
444 | char[] stringChars = new char[length];
445 | for (int i = 0; i < length; i++)
446 | {
447 | stringChars[i] = (char)Marshal.ReadByte(source, i + offset);
448 | if (stringChars[i] == 0) { length = i; break; }
449 | }
450 | return new string(stringChars, 0, length);
451 | }
452 |
453 |
454 | /*
455 | HDEVINFO SetupDiGetClassDevs(
456 | _In_opt_ const GUID *ClassGuid,
457 | _In_opt_ PCTSTR Enumerator,
458 | _In_opt_ HWND hwndParent,
459 | _In_ DWORD Flags
460 | );
461 | */
462 | [DllImport("setupapi.dll", SetLastError = true)]
463 | private extern static IntPtr SetupDiGetClassDevs(ref Guid classGuid, string enumerator, IntPtr hwndParent, UInt32 flags);
464 | [DllImport("setupapi.dll", SetLastError = true)]
465 | private extern static IntPtr SetupDiGetClassDevs(IntPtr classGuid, string enumerator, IntPtr hwndParent, UInt32 flags);
466 |
467 | /*
468 | BOOL SetupDiEnumDeviceInterfaces(
469 | _In_ HDEVINFO DeviceInfoSet,
470 | _In_opt_ PSP_DEVINFO_DATA DeviceInfoData,
471 | _In_ const GUID *InterfaceClassGuid,
472 | _In_ DWORD MemberIndex,
473 | _Out_ PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData
474 | );
475 | */
476 | [DllImport("setupapi.dll", SetLastError = true)]
477 | private extern static bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, IntPtr optDeviceInfoData, ref Guid interfaceClassGuid, UInt32 memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
478 | [DllImport("setupapi.dll", SetLastError = true)]
479 | private extern static bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, IntPtr optDeviceInfoData, IntPtr interfaceClassGuid, UInt32 memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
480 | [DllImport("setupapi.dll", SetLastError = true)]
481 | private extern static bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref Guid interfaceClassGuid, UInt32 memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
482 | [DllImport("setupapi.dll", SetLastError = true)]
483 | private extern static bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, IntPtr interfaceClassGuid, UInt32 memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
484 |
485 |
486 | /*
487 | BOOL SetupDiEnumDeviceInfo(
488 | _In_ HDEVINFO DeviceInfoSet,
489 | _In_ DWORD MemberIndex,
490 | _Out_ PSP_DEVINFO_DATA DeviceInfoData
491 | );
492 | */
493 | [DllImport("setupapi.dll", SetLastError = true)]
494 | private extern static bool SetupDiEnumDeviceInfo(IntPtr deviceInfoSet, UInt32 memberIndex, ref SP_DEVINFO_DATA deviceInfoData);
495 |
496 | /*
497 | HKEY SetupDiOpenDevRegKey(
498 | _In_ HDEVINFO DeviceInfoSet,
499 | _In_ PSP_DEVINFO_DATA DeviceInfoData,
500 | _In_ DWORD Scope,
501 | _In_ DWORD HwProfile,
502 | _In_ DWORD KeyType,
503 | _In_ REGSAM samDesired
504 | );
505 | */
506 | [DllImport("setupapi.dll", SetLastError = true)]
507 | private extern static IntPtr SetupDiOpenDevRegKey(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, UInt32 scope, UInt32 hwProfile, UInt32 keyType, UInt32 samDesired);
508 |
509 | /*
510 | BOOL SetupDiGetDeviceInterfaceProperty(
511 | _In_ HDEVINFO DeviceInfoSet,
512 | _In_ PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData,
513 | _In_ const DEVPROPKEY *PropertyKey,
514 | _Out_ DEVPROPTYPE *PropertyType,
515 | _Out_ PBYTE PropertyBuffer,
516 | _In_ DWORD PropertyBufferSize,
517 | _Out_opt_ PDWORD RequiredSize,
518 | _In_ DWORD Flags
519 | );
520 | */
521 | [DllImport("setupapi.dll", SetLastError = true, CharSet=CharSet.Unicode, EntryPoint="SetupDiGetDeviceInterfacePropertyW")]
522 | private extern static bool SetupDiGetDeviceInterfaceProperty(IntPtr deviceInfoSet, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceDataa, ref DEVPROPKEY propertyKey, out UInt32 propertyType, IntPtr outPropertyData, UInt32 dataBufferLength, out UInt32 requredBufferLength, UInt32 flags);
523 |
524 |
525 | /*
526 | BOOL SetupDiGetDevicePropertyKeys(
527 | _In_ HDEVINFO DeviceInfoSet,
528 | _In_ PSP_DEVINFO_DATA DeviceInfoData,
529 | _Out_opt_ DEVPROPKEY *PropertyKeyArray,
530 | _In_ DWORD PropertyKeyCount,
531 | _Out_opt_ PDWORD RequiredPropertyKeyCount,
532 | _In_ DWORD Flags
533 | );
534 | */
535 |
536 | /*
537 | LONG WINAPI RegCloseKey(
538 | _In_ HKEY hKey
539 | );
540 | */
541 | [DllImport("advapi32.dll", SetLastError = false)]
542 | private extern static int RegCloseKey(IntPtr hKey);
543 |
544 |
545 | /*
546 | LONG WINAPI RegGetValue(
547 | _In_ HKEY hkey,
548 | _In_opt_ LPCTSTR lpSubKey,
549 | _In_opt_ LPCTSTR lpValue,
550 | _In_opt_ DWORD dwFlags,
551 | _Out_opt_ LPDWORD pdwType,
552 | _Out_opt_ PVOID pvData,
553 | _Inout_opt_ LPDWORD pcbData
554 | );
555 | */
556 | [DllImport("advapi32.dll", SetLastError = false)]
557 | private extern static int RegGetValue(IntPtr hKey, string lpSubKey, string lpValue, UInt32 flags, out UInt32 outType, IntPtr outData, ref UInt32 dataLength);
558 |
559 | /*
560 | LONG WINAPI RegEnumValue(
561 | _In_ HKEY hKey,
562 | _In_ DWORD dwIndex,
563 | _Out_ LPTSTR lpValueName,
564 | _Inout_ LPDWORD lpcchValueName,
565 | _Reserved_ LPDWORD lpReserved,
566 | _Out_opt_ LPDWORD lpType,
567 | _Out_opt_ LPBYTE lpData,
568 | _Inout_opt_ LPDWORD lpcbData
569 | );
570 | */
571 | [DllImport("advapi32.dll", SetLastError = false)]
572 | private extern static int RegEnumValue(IntPtr hKey, UInt32 index, IntPtr outValue, ref UInt32 valueLen, IntPtr reserved, out UInt32 outType, IntPtr outData, ref UInt32 dataLength);
573 |
574 | /*
575 | BOOL SetupDiDestroyDeviceInfoList(
576 | _In_ HDEVINFO DeviceInfoSet
577 | );
578 | */
579 | [DllImport("setupapi.dll", SetLastError = true)]
580 | private extern static bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);
581 |
582 |
583 | /*
584 | BOOL SetupDiGetDeviceInterfaceDetail(
585 | _In_ HDEVINFO DeviceInfoSet,
586 | _In_ PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData,
587 | _Out_opt_ PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData,
588 | _In_ DWORD DeviceInterfaceDetailDataSize,
589 | _Out_opt_ PDWORD RequiredSize,
590 | _Out_opt_ PSP_DEVINFO_DATA DeviceInfoData
591 | );
592 | */
593 | [DllImport("setupapi.dll", SetLastError = true, CharSet=CharSet.Unicode)]
594 | private extern static bool SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, [In] ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
595 | IntPtr deviceInterfaceDetailData, UInt32 deviceInterfaceDetailSize, ref UInt32 requiredSize, IntPtr deviceInfoData );
596 |
597 |
598 | /*
599 | HANDLE WINAPI CreateFile(
600 | _In_ LPCTSTR lpFileName,
601 | _In_ DWORD dwDesiredAccess,
602 | _In_ DWORD dwShareMode,
603 | _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
604 | _In_ DWORD dwCreationDisposition,
605 | _In_ DWORD dwFlagsAndAttributes,
606 | _In_opt_ HANDLE hTemplateFile
607 | );
608 | */
609 | [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
610 | public extern static SafeFileHandle CreateFile(string lpFileName, UInt32 dwDesiredAccess,
611 | UInt32 dwShareMode, IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition, UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);
612 |
613 | public const uint FILE_ATTRIBUTE_NORMAL = 0x80;
614 | public const uint FILE_FLAG_OVERLAPPED = 0x40000000;
615 | public const uint GENERIC_READ = 0x80000000;
616 | public const uint GENERIC_WRITE = 0x40000000;
617 | public const uint CREATE_NEW = 1;
618 | public const uint CREATE_ALWAYS = 2;
619 | public const uint OPEN_EXISTING = 3;
620 | public const uint FILE_SHARE_READ = 1;
621 | public const uint FILE_SHARE_WRITE = 2;
622 |
623 |
624 |
625 |
626 | public struct WINUSB_SETUP_PACKET
627 | {
628 | public byte RequestType;
629 | public byte Request;
630 | public UInt16 Value;
631 | public UInt16 Index;
632 | public UInt16 Length;
633 | }
634 |
635 |
636 | /*
637 | BOOL __stdcall WinUsb_Initialize(
638 | _In_ HANDLE DeviceHandle,
639 | _Out_ PWINUSB_INTERFACE_HANDLE InterfaceHandle
640 | );
641 | */
642 | [DllImport("winusb.dll", SetLastError = true)]
643 | public extern static bool WinUsb_Initialize(SafeFileHandle deviceHandle, out IntPtr interfaceHandle);
644 |
645 | /*
646 | BOOL __stdcall WinUsb_Free(
647 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle
648 | );
649 | */
650 |
651 | [DllImport("winusb.dll", SetLastError = true)]
652 | public extern static bool WinUsb_Free(IntPtr interfaceHandle);
653 |
654 | /*
655 | BOOL __stdcall WinUsb_ControlTransfer(
656 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
657 | _In_ WINUSB_SETUP_PACKET SetupPacket,
658 | _Out_ PUCHAR Buffer,
659 | _In_ ULONG BufferLength,
660 | _Out_opt_ PULONG LengthTransferred,
661 | _In_opt_ LPOVERLAPPED Overlapped
662 | );
663 | */
664 | [DllImport("winusb.dll", SetLastError = true)]
665 | public extern static bool WinUsb_ControlTransfer(IntPtr interfaceHandle, WINUSB_SETUP_PACKET setupPacket, byte[] buffer, uint bufferLength, out UInt32 lengthTransferred, IntPtr overlapped);
666 |
667 |
668 |
669 |
670 | /*
671 | BOOL __stdcall WinUsb_ReadPipe(
672 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
673 | _In_ UCHAR PipeID,
674 | _Out_ PUCHAR Buffer,
675 | _In_ ULONG BufferLength,
676 | _Out_opt_ PULONG LengthTransferred,
677 | _In_opt_ LPOVERLAPPED Overlapped
678 | );
679 | */
680 |
681 | [DllImport("winusb.dll", SetLastError = true)]
682 | public extern static bool WinUsb_ReadPipe(IntPtr interfaceHandle, byte pipeId, IntPtr buffer, uint bufferLength, IntPtr lengthTransferred, IntPtr overlapped);
683 | [DllImport("winusb.dll", SetLastError = true)]
684 | public extern static bool WinUsb_ReadPipe(IntPtr interfaceHandle, byte pipeId, [Out] byte[] buffer, uint bufferLength, ref UInt32 lengthTransferred, IntPtr overlapped);
685 |
686 | /*
687 | BOOL __stdcall WinUsb_WritePipe(
688 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
689 | _In_ UCHAR PipeID,
690 | _In_ PUCHAR Buffer,
691 | _In_ ULONG BufferLength,
692 | _Out_opt_ PULONG LengthTransferred,
693 | _In_opt_ LPOVERLAPPED Overlapped
694 | );
695 | */
696 |
697 | [DllImport("winusb.dll", SetLastError = true)]
698 | public extern static bool WinUsb_WritePipe(IntPtr interfaceHandle, byte pipeId, [In] byte[] buffer, uint bufferLength, IntPtr lengthTransferred, ref NativeOverlapped overlapped);
699 | [DllImport("winusb.dll", SetLastError = true)]
700 | public extern static bool WinUsb_WritePipe(IntPtr interfaceHandle, byte pipeId, [In] byte[] buffer, uint bufferLength, ref UInt32 lengthTransferred, IntPtr overlapped);
701 |
702 |
703 | /*
704 | BOOL __stdcall WinUsb_GetOverlappedResult(
705 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
706 | _In_ LPOVERLAPPED lpOverlapped,
707 | _Out_ LPDWORD lpNumberOfBytesTransferred,
708 | _In_ BOOL bWait
709 | );
710 | */
711 |
712 | [DllImport("winusb.dll", SetLastError = true)]
713 | public extern static bool WinUsb_GetOverlappedResult(IntPtr interfaceHandle, IntPtr overlapped, out UInt32 numberOfBytesTransferred, bool wait);
714 |
715 |
716 | /*
717 | BOOL __stdcall WinUsb_SetPipePolicy(
718 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
719 | _In_ UCHAR PipeID,
720 | _In_ ULONG PolicyType,
721 | _In_ ULONG ValueLength,
722 | _In_ PVOID Value
723 | );
724 | */
725 |
726 | [DllImport("winusb.dll", SetLastError = true)]
727 | public extern static bool WinUsb_SetPipePolicy(IntPtr interfaceHandle, byte pipeId, UInt32 policyType, UInt32 valueLength, UInt32[] value);
728 |
729 | /*
730 | BOOL __stdcall WinUsb_GetPipePolicy(
731 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
732 | _In_ UCHAR PipeID,
733 | _In_ ULONG PolicyType,
734 | _Inout_ PULONG ValueLength,
735 | _Out_ PVOID Value
736 | );
737 | */
738 |
739 | [DllImport("winusb.dll", SetLastError = true)]
740 | public extern static bool WinUsb_GetPipePolicy(IntPtr interfaceHandle, byte pipeId, UInt32 policyType, ref UInt32 valueLength, UInt32[] value);
741 |
742 |
743 | /*
744 | BOOL __stdcall WinUsb_FlushPipe(
745 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
746 | _In_ UCHAR PipeID
747 | );
748 | */
749 |
750 | [DllImport("winusb.dll", SetLastError = true)]
751 | public extern static bool WinUsb_FlushPipe(IntPtr interfaceHandle, byte pipeId);
752 |
753 |
754 | /*
755 | BOOL __stdcall WinUsb_GetDescriptor(
756 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
757 | _In_ UCHAR DescriptorType,
758 | _In_ UCHAR Index,
759 | _In_ USHORT LanguageID,
760 | _Out_ PUCHAR Buffer,
761 | _In_ ULONG BufferLength,
762 | _Out_ PULONG LengthTransferred
763 | );
764 | */
765 |
766 |
767 | /*
768 | BOOL __stdcall WinUsb_QueryInterfaceSettings(
769 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
770 | _In_ UCHAR AlternateSettingNumber,
771 | _Out_ PUSB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor
772 | );
773 | */
774 |
775 | /*
776 | BOOL __stdcall WinUsb_GetCurrentAlternateSetting(
777 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
778 | _Out_ PUCHAR AlternateSetting
779 | );
780 | */
781 | [DllImport("winusb.dll", SetLastError = true)]
782 | public extern static bool WinUsb_GetCurrentAlternateSetting(IntPtr interfaceHandle, out byte alternateSetting);
783 |
784 |
785 | /*
786 | BOOL __stdcall WinUsb_SetCurrentAlternateSetting(
787 | _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,
788 | _In_ UCHAR AlternateSetting
789 | );
790 | */
791 | [DllImport("winusb.dll", SetLastError = true)]
792 | public extern static bool WinUsb_SetCurrentAlternateSetting(IntPtr interfaceHandle, byte alternateSetting);
793 |
794 |
795 |
796 |
797 |
798 |
799 | }
800 |
801 | public struct NativeOverlapped
802 | {
803 | public IntPtr Internal;
804 | public IntPtr InternalHigh;
805 | public long Pointer; // On 32bit systems this is 32bit, but it's merged with an "Offset" field which is 64bit.
806 | public IntPtr Event;
807 | }
808 |
809 | public class Overlapped : IDisposable
810 | {
811 | public Overlapped()
812 | {
813 | WaitEvent = new ManualResetEvent(false);
814 | OverlappedStructShadow = new NativeOverlapped();
815 | OverlappedStructShadow.Event = WaitEvent.SafeWaitHandle.DangerousGetHandle();
816 |
817 | OverlappedStruct = Marshal.AllocHGlobal(Marshal.SizeOf(OverlappedStructShadow));
818 | Marshal.StructureToPtr(OverlappedStructShadow, OverlappedStruct, false);
819 | }
820 | public void Dispose()
821 | {
822 | Marshal.FreeCoTaskMem(OverlappedStruct);
823 | WaitEvent.Dispose();
824 | GC.SuppressFinalize(this);
825 | }
826 |
827 | public ManualResetEvent WaitEvent;
828 | public NativeOverlapped OverlappedStructShadow;
829 | public IntPtr OverlappedStruct;
830 | }
831 |
832 | public enum WinUsbPipePolicy
833 | {
834 | SHORT_PACKET_TERMINATE = 1,
835 | AUTO_CLEAR_STALL = 2,
836 | PIPE_TRANSFER_TIMEOUT = 3,
837 | IGNORE_SHORT_PACKETS = 4,
838 | ALLOW_PARTIAL_READS = 5,
839 | AUTO_FLUSH = 6,
840 | RAW_IO = 7,
841 | MAXIMUM_TRANSFER_SIZE = 8,
842 | RESET_PIPE_ON_RESUME = 9
843 | }
844 |
845 |
846 |
847 | }
848 |
--------------------------------------------------------------------------------
/TestSeek/WinUSBDevice.cs:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2014 Stephen Stair (sgstair@akkit.org)
3 | Additional code Miguel Parra (miguelvp@msn.com)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 | */
23 |
24 | using System;
25 | using System.Collections.Generic;
26 | using System.Linq;
27 | using System.Runtime.InteropServices;
28 | using System.Text;
29 | using System.Text.RegularExpressions;
30 | using System.Threading;
31 | using System.Threading.Tasks;
32 | using Microsoft.Win32.SafeHandles;
33 | using System.ComponentModel;
34 |
35 | namespace winusbdotnet
36 | {
37 |
38 | public class WinUSBEnumeratedDevice
39 | {
40 | internal string DevicePath;
41 | internal EnumeratedDevice EnumeratedData;
42 | internal WinUSBEnumeratedDevice(EnumeratedDevice enumDev)
43 | {
44 | DevicePath = enumDev.DevicePath;
45 | EnumeratedData = enumDev;
46 | Match m = Regex.Match(DevicePath, @"vid_([\da-f]{4})");
47 | if (m.Success) { VendorID = Convert.ToUInt16(m.Groups[1].Value, 16); }
48 | m = Regex.Match(DevicePath, @"pid_([\da-f]{4})");
49 | if (m.Success) { ProductID = Convert.ToUInt16(m.Groups[1].Value, 16); }
50 | m = Regex.Match(DevicePath, @"mi_([\da-f]{2})");
51 | if (m.Success) { UsbInterface = Convert.ToByte(m.Groups[1].Value, 16); }
52 | }
53 |
54 | public string Path { get { return DevicePath; } }
55 | public UInt16 VendorID { get; private set; }
56 | public UInt16 ProductID { get; private set; }
57 | public Byte UsbInterface { get; private set; }
58 | public Guid InterfaceGuid { get { return EnumeratedData.InterfaceGuid; } }
59 |
60 |
61 | public override string ToString()
62 | {
63 | return string.Format("WinUSBEnumeratedDevice({0},{1})", DevicePath, InterfaceGuid);
64 | }
65 | }
66 |
67 | public class WinUSBDevice : IDisposable
68 | {
69 | public static IEnumerable EnumerateDevices(Guid deviceInterfaceGuid)
70 | {
71 | foreach (EnumeratedDevice devicePath in NativeMethods.EnumerateDevicesByInterface(deviceInterfaceGuid))
72 | {
73 | yield return new WinUSBEnumeratedDevice(devicePath);
74 | }
75 | }
76 |
77 | public static IEnumerable EnumerateAllDevices()
78 | {
79 | foreach (EnumeratedDevice devicePath in NativeMethods.EnumerateAllWinUsbDevices())
80 | {
81 | yield return new WinUSBEnumeratedDevice(devicePath);
82 | }
83 | }
84 | public delegate void NewDataCallback();
85 |
86 | string myDevicePath;
87 | SafeFileHandle deviceHandle;
88 | IntPtr WinusbHandle;
89 |
90 | internal bool Stopping = false;
91 |
92 | public WinUSBDevice(WinUSBEnumeratedDevice deviceInfo)
93 | {
94 | myDevicePath = deviceInfo.DevicePath;
95 |
96 | deviceHandle = NativeMethods.CreateFile(myDevicePath, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE,
97 | NativeMethods.FILE_SHARE_READ | NativeMethods.FILE_SHARE_WRITE, IntPtr.Zero, NativeMethods.OPEN_EXISTING,
98 | NativeMethods.FILE_ATTRIBUTE_NORMAL | NativeMethods.FILE_FLAG_OVERLAPPED, IntPtr.Zero);
99 |
100 | if (deviceHandle.IsInvalid)
101 | {
102 | throw new Exception("Could not create file. " + (new Win32Exception()).ToString());
103 | }
104 |
105 | if (!NativeMethods.WinUsb_Initialize(deviceHandle, out WinusbHandle))
106 | {
107 | WinusbHandle = IntPtr.Zero;
108 | throw new Exception("Could not Initialize WinUSB. " + (new Win32Exception()).ToString());
109 | }
110 |
111 |
112 | }
113 |
114 |
115 | public byte AlternateSetting
116 | {
117 | get
118 | {
119 | byte alt;
120 | if (!NativeMethods.WinUsb_GetCurrentAlternateSetting(WinusbHandle, out alt))
121 | {
122 | throw new Exception("GetCurrentAlternateSetting failed. " + (new Win32Exception()).ToString());
123 | }
124 | return alt;
125 | }
126 | set
127 | {
128 | if (!NativeMethods.WinUsb_SetCurrentAlternateSetting(WinusbHandle, value))
129 | {
130 | throw new Exception("SetCurrentAlternateSetting failed. " + (new Win32Exception()).ToString());
131 | }
132 | }
133 | }
134 |
135 |
136 | public void Dispose()
137 | {
138 | Stopping = true;
139 |
140 | // Close handles which will cause background theads to stop working & exit.
141 | if (WinusbHandle != IntPtr.Zero)
142 | {
143 | NativeMethods.WinUsb_Free(WinusbHandle);
144 | WinusbHandle = IntPtr.Zero;
145 | }
146 | deviceHandle.Close();
147 |
148 | // Wait for pipe threads to quit
149 | foreach (BufferedPipeThread th in bufferedPipes.Values)
150 | {
151 | while (!th.Stopped) Thread.Sleep(5);
152 | }
153 |
154 | GC.SuppressFinalize(this);
155 | }
156 |
157 | public void Close()
158 | {
159 | Dispose();
160 | }
161 |
162 | public void FlushPipe(byte pipeId)
163 | {
164 | if (!NativeMethods.WinUsb_FlushPipe(WinusbHandle, pipeId))
165 | {
166 | throw new Exception("FlushPipe failed. " + (new Win32Exception()).ToString());
167 | }
168 | }
169 |
170 | public UInt32 GetPipePolicy(byte pipeId, WinUsbPipePolicy policyType)
171 | {
172 | UInt32[] data = new UInt32[1];
173 | UInt32 length = 4;
174 |
175 | if (!NativeMethods.WinUsb_GetPipePolicy(WinusbHandle, pipeId, (uint)policyType, ref length, data))
176 | {
177 | throw new Exception("GetPipePolicy failed. " + (new Win32Exception()).ToString());
178 | }
179 |
180 | return data[0];
181 | }
182 |
183 | public void SetPipePolicy(byte pipeId, WinUsbPipePolicy policyType, UInt32 newValue)
184 | {
185 | UInt32[] data = new UInt32[1];
186 | UInt32 length = 4;
187 | data[0] = newValue;
188 |
189 | if (!NativeMethods.WinUsb_SetPipePolicy(WinusbHandle, pipeId, (uint)policyType, length, data))
190 | {
191 | throw new Exception("SetPipePolicy failed. " + (new Win32Exception()).ToString());
192 | }
193 | }
194 |
195 | Dictionary bufferedPipes = new Dictionary();
196 | public void EnableBufferedRead(byte pipeId, int bufferCount = 4, int multiPacketCount = 1)
197 | {
198 | if (!bufferedPipes.ContainsKey(pipeId))
199 | {
200 | bufferedPipes.Add(pipeId, new BufferedPipeThread(this, pipeId, bufferCount, multiPacketCount));
201 | }
202 | }
203 |
204 | public void StopBufferedRead(byte pipeId)
205 | {
206 |
207 | }
208 |
209 | public void BufferedReadNotifyPipe(byte pipeId, NewDataCallback callback)
210 | {
211 | if (!bufferedPipes.ContainsKey(pipeId))
212 | {
213 | throw new Exception("Pipe not enabled for buffered reads!");
214 | }
215 | bufferedPipes[pipeId].NewDataEvent += callback;
216 | }
217 |
218 | BufferedPipeThread GetInterface(byte pipeId, bool packetInterface)
219 | {
220 | if (!bufferedPipes.ContainsKey(pipeId))
221 | {
222 | throw new Exception("Pipe not enabled for buffered reads!");
223 | }
224 | BufferedPipeThread th = bufferedPipes[pipeId];
225 | if (!th.InterfaceBound)
226 | {
227 | th.InterfaceBound = true;
228 | th.PacketInterface = packetInterface;
229 | }
230 | else
231 | {
232 | if (th.PacketInterface != packetInterface)
233 | {
234 | string message = string.Format("Pipe is already bound as a {0} interface - cannot bind to both Packet and Byte interfaces",
235 | packetInterface ? "Byte" : "Packet");
236 | throw new Exception(message);
237 | }
238 | }
239 | return th;
240 | }
241 | public IPipeByteReader BufferedGetByteInterface(byte pipeId)
242 | {
243 | return GetInterface(pipeId, false);
244 | }
245 |
246 | public IPipePacketReader BufferedGetPacketInterface(byte pipeId)
247 | {
248 | return GetInterface(pipeId, true);
249 | }
250 |
251 |
252 |
253 | public byte[] BufferedReadPipe(byte pipeId, int byteCount)
254 | {
255 | return BufferedGetByteInterface(pipeId).ReceiveBytes(byteCount);
256 | }
257 |
258 | public byte[] BufferedPeekPipe(byte pipeId, int byteCount)
259 | {
260 | return BufferedGetByteInterface(pipeId).PeekBytes(byteCount);
261 | }
262 |
263 | public void BufferedSkipBytesPipe(byte pipeId, int byteCount)
264 | {
265 | BufferedGetByteInterface(pipeId).SkipBytes(byteCount);
266 | }
267 |
268 | public byte[] BufferedReadExactPipe(byte pipeId, int byteCount)
269 | {
270 | return BufferedGetByteInterface(pipeId).ReceiveExactBytes(byteCount);
271 | }
272 |
273 | public int BufferedByteCountPipe(byte pipeId)
274 | {
275 | return BufferedGetByteInterface(pipeId).QueuedDataLength;
276 | }
277 |
278 | public UInt16[] ReadExactPipeU16(byte pipeId, int count)
279 | {
280 | int read = 0;
281 | UInt16[] accumulate = null;
282 | while (read < count)
283 | {
284 | UInt16[] data = ReadPipeU16(pipeId, count - read);
285 | if (data.Length == 0)
286 | {
287 | // Timeout happened in ReadPipeU16.
288 | throw new Exception("Timed out while trying to read data.");
289 | }
290 | if (data.Length == count) return data;
291 | if (accumulate == null)
292 | {
293 | accumulate = new UInt16[count];
294 | }
295 | Array.Copy(data, 0, accumulate, read, data.Length);
296 | read += data.Length;
297 | }
298 | return accumulate;
299 | }
300 |
301 | public byte[] ReadExactPipe(byte pipeId, int byteCount)
302 | {
303 | int read = 0;
304 | byte[] accumulate = null;
305 | while (read < byteCount)
306 | {
307 | byte[] data = ReadPipe(pipeId, byteCount - read);
308 | if (data.Length == 0)
309 | {
310 | // Timeout happened in ReadPipe.
311 | throw new Exception("Timed out while trying to read data.");
312 | }
313 | if (data.Length == byteCount) return data;
314 | if (accumulate == null)
315 | {
316 | accumulate = new byte[byteCount];
317 | }
318 | Array.Copy(data, 0, accumulate, read, data.Length);
319 | read += data.Length;
320 | }
321 | return accumulate;
322 | }
323 |
324 | // basic synchronous read
325 | public UInt16[] ReadPipeU16(byte pipeId, int count)
326 | {
327 |
328 | byte[] data = new byte[count*2];
329 |
330 | UInt32 transferSize = 0;
331 | if (!NativeMethods.WinUsb_ReadPipe(WinusbHandle, pipeId, data, (uint)count*2, ref transferSize, IntPtr.Zero))
332 | {
333 | if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_SEM_TIMEOUT)
334 | {
335 | // This was a pipe timeout. Return an empty byte array to indicate this case.
336 | return new UInt16[0];
337 | }
338 | throw new Exception("ReadPipe failed. " + (new Win32Exception()).ToString());
339 | }
340 |
341 | UInt16[] newdata = new UInt16[transferSize / 2];
342 | for (int i = 0; i < (transferSize / 2); i++)
343 | {
344 | int v = BitConverter.ToInt16(data, i * 2);
345 | newdata[i] = (UInt16)v;
346 | }
347 | return newdata;
348 |
349 | }
350 |
351 | // basic synchronous read
352 | public byte[] ReadPipe(byte pipeId, int byteCount)
353 | {
354 |
355 | byte[] data = new byte[byteCount];
356 |
357 | UInt32 transferSize = 0;
358 | if (!NativeMethods.WinUsb_ReadPipe(WinusbHandle, pipeId, data, (uint)byteCount, ref transferSize, IntPtr.Zero))
359 | {
360 | if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_SEM_TIMEOUT)
361 | {
362 | // This was a pipe timeout. Return an empty byte array to indicate this case.
363 | return new byte[0];
364 | }
365 | throw new Exception("ReadPipe failed. " + (new Win32Exception()).ToString());
366 | }
367 |
368 | byte[] newdata = new byte[transferSize];
369 | Array.Copy(data, newdata, transferSize);
370 | return newdata;
371 |
372 | }
373 |
374 | // Asynchronous read bits, only for use with buffered reader for now.
375 | internal void BeginReadPipe(byte pipeId, QueuedBuffer buffer)
376 | {
377 | buffer.Overlapped.WaitEvent.Reset();
378 |
379 | if (!NativeMethods.WinUsb_ReadPipe(WinusbHandle, pipeId, buffer.PinnedBuffer, (uint)buffer.BufferSize, IntPtr.Zero, buffer.Overlapped.OverlappedStruct))
380 | {
381 | if (Marshal.GetLastWin32Error() != NativeMethods.ERROR_IO_PENDING)
382 | {
383 | throw new Exception("ReadPipe failed. " + (new Win32Exception()).ToString());
384 | }
385 | }
386 | }
387 |
388 | internal byte[] EndReadPipe(QueuedBuffer buf)
389 | {
390 | UInt32 transferSize;
391 |
392 | if (!NativeMethods.WinUsb_GetOverlappedResult(WinusbHandle, buf.Overlapped.OverlappedStruct, out transferSize, true))
393 | {
394 | if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_SEM_TIMEOUT)
395 | {
396 | // This was a pipe timeout. Return an empty byte array to indicate this case.
397 | //System.Diagnostics.Debug.WriteLine("Timed out");
398 | return null;
399 | }
400 | throw new Exception("ReadPipe's overlapped result failed. " + (new Win32Exception()).ToString());
401 | }
402 |
403 | byte[] data = new byte[transferSize];
404 | Marshal.Copy(buf.PinnedBuffer, data, 0, (int)transferSize);
405 | return data;
406 | }
407 |
408 |
409 | // basic synchronous send.
410 | public void WritePipe(byte pipeId, byte[] pipeData)
411 | {
412 |
413 | int remainingbytes = pipeData.Length;
414 | while (remainingbytes > 0)
415 | {
416 |
417 | UInt32 transferSize = 0;
418 | if (!NativeMethods.WinUsb_WritePipe(WinusbHandle, pipeId, pipeData, (uint)pipeData.Length, ref transferSize, IntPtr.Zero))
419 | {
420 | throw new Exception("WritePipe failed. " + (new Win32Exception()).ToString());
421 | }
422 | if (transferSize == pipeData.Length) return;
423 |
424 | remainingbytes -= (int)transferSize;
425 |
426 | // Need to retry. Copy the remaining data to a new buffer.
427 | byte[] data = new byte[remainingbytes];
428 | Array.Copy(pipeData, transferSize, data, 0, remainingbytes);
429 |
430 | pipeData = data;
431 | }
432 | }
433 |
434 |
435 |
436 | public void ControlTransferOut(byte requestType, byte request, UInt16 value, UInt16 index, byte[] data)
437 | {
438 | NativeMethods.WINUSB_SETUP_PACKET setupPacket = new NativeMethods.WINUSB_SETUP_PACKET();
439 | setupPacket.RequestType = (byte)(requestType | ControlDirectionOut);
440 | setupPacket.Request = request;
441 | setupPacket.Value = value;
442 | setupPacket.Index = index;
443 | if (data != null)
444 | {
445 | setupPacket.Length = (ushort)data.Length;
446 | }
447 |
448 | UInt32 actualLength = 0;
449 |
450 | if (!NativeMethods.WinUsb_ControlTransfer(WinusbHandle, setupPacket, data, setupPacket.Length, out actualLength, IntPtr.Zero))
451 | {
452 | throw new Exception("ControlTransfer failed. " + (new Win32Exception()).ToString());
453 | }
454 |
455 | if (data != null && actualLength != data.Length)
456 | {
457 | throw new Exception("Not all data transferred");
458 | }
459 | }
460 |
461 | public byte[] ControlTransferIn(byte requestType, byte request, UInt16 value, UInt16 index, UInt16 length)
462 | {
463 | NativeMethods.WINUSB_SETUP_PACKET setupPacket = new NativeMethods.WINUSB_SETUP_PACKET();
464 | setupPacket.RequestType = (byte)(requestType | ControlDirectionIn);
465 | setupPacket.Request = request;
466 | setupPacket.Value = value;
467 | setupPacket.Index = index;
468 | setupPacket.Length = length;
469 |
470 | byte[] output = new byte[length];
471 | UInt32 actualLength = 0;
472 |
473 | if(!NativeMethods.WinUsb_ControlTransfer(WinusbHandle, setupPacket, output, (uint)output.Length, out actualLength, IntPtr.Zero))
474 | {
475 | throw new Exception("ControlTransfer failed. " + (new Win32Exception()).ToString());
476 | }
477 |
478 | if(actualLength != output.Length)
479 | {
480 | byte[] copyTo = new byte[actualLength];
481 | Array.Copy(output, copyTo, actualLength);
482 | output = copyTo;
483 | }
484 | return output;
485 | }
486 |
487 | const byte ControlDirectionOut = 0x00;
488 | const byte ControlDirectionIn = 0x80;
489 |
490 | public const byte ControlTypeStandard = 0x00;
491 | public const byte ControlTypeClass = 0x20;
492 | public const byte ControlTypeVendor = 0x40;
493 |
494 | public const byte ControlRecipientDevice = 0;
495 | public const byte ControlRecipientInterface = 1;
496 | public const byte ControlRecipientEndpoint = 2;
497 | public const byte ControlRecipientOther = 3;
498 |
499 |
500 | }
501 |
502 |
503 | internal class QueuedBuffer : IDisposable
504 | {
505 | public readonly int BufferSize;
506 | public Overlapped Overlapped;
507 | public IntPtr PinnedBuffer;
508 | public QueuedBuffer(int bufferSizeBytes)
509 | {
510 | BufferSize = bufferSizeBytes;
511 | Overlapped = new Overlapped();
512 | PinnedBuffer = Marshal.AllocHGlobal(BufferSize);
513 | }
514 |
515 | public void Dispose()
516 | {
517 | Overlapped.Dispose();
518 | Marshal.FreeHGlobal(PinnedBuffer);
519 | GC.SuppressFinalize(this);
520 | }
521 |
522 | public void Wait()
523 | {
524 | Overlapped.WaitEvent.WaitOne();
525 | }
526 |
527 | public bool Ready
528 | {
529 | get
530 | {
531 | return Overlapped.WaitEvent.WaitOne(0);
532 | }
533 | }
534 |
535 | }
536 |
537 |
538 |
539 | public interface IPipeByteReader
540 | {
541 | ///
542 | /// Receive a number of bytes from the incoming data stream.
543 | /// If there are not enough bytes available, only the available bytes will be returned.
544 | /// Returns immediately.
545 | ///
546 | /// Number of bytes to request
547 | /// Byte data from the USB pipe
548 | byte[] ReceiveBytes(int count);
549 |
550 | ///
551 | /// Receive a number of bytes from the incoming data stream, but don't remove them from the queue.
552 | /// If there are not enough bytes available, only the available bytes will be returned.
553 | /// Returns immediately.
554 | ///
555 | /// Number of bytes to request
556 | /// Byte data from the USB pipe
557 | byte[] PeekBytes(int count);
558 |
559 | ///
560 | /// Receive a specific number of bytes from the incoming data stream.
561 | /// This call will block until the requested bytes are available, or will eventually throw on timeout.
562 | ///
563 | /// Number of bytes to request
564 | /// Byte data from the USB pipe
565 | byte[] ReceiveExactBytes(int count);
566 |
567 | ///
568 | /// Drop bytes from the incoming data stream without reading them.
569 | /// If you try to drop more bytes than are available, the buffer will be cleared.
570 | /// Returns immediately.
571 | ///
572 | /// Number of bytes to drop.
573 | void SkipBytes(int count);
574 |
575 | ///
576 | /// Current number of bytes that are queued and available to read.
577 | ///
578 | int QueuedDataLength { get; }
579 | }
580 |
581 | public interface IPipePacketReader
582 | {
583 | ///
584 | /// Number of received packets that can be read.
585 | ///
586 | int QueuedPackets { get; }
587 |
588 | ///
589 | /// Retrieve the next packet, but do not remove it from the buffer.
590 | /// Warning: If you modify the returned array, the modifications will be present in future calls to Peek/Dequeue for this pacekt.
591 | ///
592 | /// The contents of the next packet in the receive queue
593 | byte[] PeekPacket();
594 |
595 | ///
596 | /// Retrieve the next packet from the receive queue
597 | ///
598 | /// The contents of the next packet in the receive queue
599 | byte[] DequeuePacket();
600 | }
601 |
602 |
603 | // Background thread to receive data from pipes.
604 | // Provides two data access mechanisms which are mutually exclusive: Packet level and byte level.
605 | internal class BufferedPipeThread : IPipeByteReader, IPipePacketReader
606 | {
607 | // Logic to enforce interface exclucivity is in WinUSBDevice
608 | public bool InterfaceBound; // Has the interface been bound?
609 | public bool PacketInterface; // Are we using the packet reader interface?
610 |
611 |
612 | Thread PipeThread;
613 | WinUSBDevice Device;
614 | byte DevicePipeId;
615 |
616 | private long TotalReceived;
617 |
618 | private int QueuedLength;
619 | private Queue ReceivedData;
620 | private int SkipFirstBytes;
621 | public bool Stopped = false;
622 |
623 | ManualResetEvent ReceiveTick;
624 |
625 | QueuedBuffer[] BufferList;
626 | Queue PendingBuffers;
627 |
628 | public BufferedPipeThread(WinUSBDevice dev, byte pipeId, int bufferCount, int multiPacketCount)
629 | {
630 | int maxTransferSize = (int)dev.GetPipePolicy(pipeId, WinUsbPipePolicy.MAXIMUM_TRANSFER_SIZE);
631 |
632 | int pipeSize = 512; // Todo: query pipe transfer size for 1:1 mapping to packets.
633 | int bufferSize = pipeSize * multiPacketCount;
634 | if (bufferSize > maxTransferSize) { bufferSize = maxTransferSize; }
635 |
636 | PendingBuffers = new Queue(bufferCount);
637 | BufferList = new QueuedBuffer[bufferCount];
638 | for (int i = 0; i < bufferCount;i++)
639 | {
640 | BufferList[i] = new QueuedBuffer(bufferSize);
641 | }
642 |
643 | EventConcurrency = new Semaphore(3, 3);
644 | Device = dev;
645 | DevicePipeId = pipeId;
646 | QueuedLength = 0;
647 | ReceivedData = new Queue();
648 | ReceiveTick = new ManualResetEvent(false);
649 | PipeThread = new Thread(ThreadFunc);
650 | PipeThread.IsBackground = true;
651 |
652 | //dev.SetPipePolicy(pipeId, WinUsbPipePolicy.PIPE_TRANSFER_TIMEOUT, 1000);
653 |
654 | // Start reading on all the buffers.
655 | foreach(QueuedBuffer qb in BufferList)
656 | {
657 | dev.BeginReadPipe(pipeId, qb);
658 | PendingBuffers.Enqueue(qb);
659 | }
660 |
661 | //dev.SetPipePolicy(pipeId, WinUsbPipePolicy.RAW_IO, 1);
662 |
663 | PipeThread.Start();
664 | }
665 |
666 | public long TotalReceivedBytes { get { return TotalReceived; } }
667 |
668 | //
669 | // Packet Reader members
670 | //
671 |
672 | public int QueuedPackets { get { lock (this) { return ReceivedData.Count; } } }
673 |
674 | public byte[] PeekPacket()
675 | {
676 | lock (this)
677 | {
678 | return ReceivedData.Peek();
679 | }
680 | }
681 |
682 | public byte[] DequeuePacket()
683 | {
684 | lock (this)
685 | {
686 | return ReceivedData.Dequeue();
687 | }
688 | }
689 |
690 | //
691 | // Byte Reader members
692 | //
693 |
694 | public int QueuedDataLength { get { return QueuedLength; } }
695 |
696 | // Only returns as many as it can.
697 | public byte[] ReceiveBytes(int count)
698 | {
699 | int queue = QueuedDataLength;
700 | if (queue < count)
701 | count = queue;
702 |
703 | byte[] output = new byte[count];
704 | lock (this)
705 | {
706 | CopyReceiveBytes(output, 0, count);
707 | }
708 | return output;
709 | }
710 |
711 | // Only returns as many as it can.
712 | public byte[] PeekBytes(int count)
713 | {
714 | int queue = QueuedDataLength;
715 | if (queue < count)
716 | count = queue;
717 |
718 | byte[] output = new byte[count];
719 | lock (this)
720 | {
721 | CopyPeekBytes(output, 0, count);
722 | }
723 | return output;
724 | }
725 |
726 | public byte[] ReceiveExactBytes(int count)
727 | {
728 | byte[] output = new byte[count];
729 | if (QueuedDataLength >= count)
730 | {
731 | lock (this)
732 | {
733 | CopyReceiveBytes(output, 0, count);
734 | }
735 | return output;
736 | }
737 | int failedcount = 0;
738 | int haveBytes = 0;
739 | while (haveBytes < count)
740 | {
741 | ReceiveTick.Reset();
742 | lock (this)
743 | {
744 | int thisBytes = QueuedLength;
745 |
746 | if(thisBytes == 0)
747 | {
748 | failedcount++;
749 | if(failedcount > 3)
750 | {
751 | throw new Exception("Timed out waiting to receive bytes");
752 | }
753 | }
754 | else
755 | {
756 | failedcount = 0;
757 | if (thisBytes + haveBytes > count) thisBytes = count - haveBytes;
758 | CopyReceiveBytes(output, haveBytes, thisBytes);
759 | }
760 | haveBytes += (int)thisBytes;
761 | }
762 | if(haveBytes < count)
763 | {
764 | if (Stopped) throw new Exception("Not going to have enough bytes to complete request.");
765 | ReceiveTick.WaitOne();
766 | }
767 | }
768 | return output;
769 | }
770 |
771 | public void SkipBytes(int count)
772 | {
773 | lock (this)
774 | {
775 | int queue = QueuedLength;
776 | if (queue < count)
777 | throw new ArgumentException("count must be less than the data length");
778 |
779 | int copied = 0;
780 | while (copied < count)
781 | {
782 | byte[] firstData = ReceivedData.Peek();
783 | int available = firstData.Length - SkipFirstBytes;
784 | int toCopy = count - copied;
785 | if (toCopy > available) toCopy = available;
786 |
787 | if (toCopy == available)
788 | {
789 | ReceivedData.Dequeue();
790 | SkipFirstBytes = 0;
791 | }
792 | else
793 | {
794 | SkipFirstBytes += toCopy;
795 | }
796 |
797 | copied += toCopy;
798 | QueuedLength -= toCopy;
799 | }
800 | }
801 | }
802 |
803 | //
804 | // Internal functionality
805 | //
806 |
807 | // Must be called under lock with enough bytes in the buffer.
808 | void CopyReceiveBytes(byte[] target, int start, int count)
809 | {
810 | int copied = 0;
811 | while(copied < count)
812 | {
813 | byte[] firstData = ReceivedData.Peek();
814 | int available = firstData.Length - SkipFirstBytes;
815 | int toCopy = count - copied;
816 | if (toCopy > available) toCopy = available;
817 |
818 | Array.Copy(firstData, SkipFirstBytes, target, start, toCopy);
819 |
820 | if(toCopy == available)
821 | {
822 | ReceivedData.Dequeue();
823 | SkipFirstBytes = 0;
824 | }
825 | else
826 | {
827 | SkipFirstBytes += toCopy;
828 | }
829 |
830 | copied += toCopy;
831 | start += toCopy;
832 | QueuedLength -= toCopy;
833 | }
834 | }
835 |
836 | // Must be called under lock with enough bytes in the buffer.
837 | void CopyPeekBytes(byte[] target, int start, int count)
838 | {
839 | int copied = 0;
840 | int skipBytes = SkipFirstBytes;
841 |
842 | foreach(byte[] firstData in ReceivedData)
843 | {
844 | int available = firstData.Length - skipBytes;
845 | int toCopy = count - copied;
846 | if (toCopy > available) toCopy = available;
847 |
848 | Array.Copy(firstData, skipBytes, target, start, toCopy);
849 |
850 | skipBytes = 0;
851 |
852 | copied += toCopy;
853 | start += toCopy;
854 |
855 | if (copied >= count)
856 | {
857 | break;
858 | }
859 | }
860 | }
861 |
862 |
863 |
864 |
865 | void ThreadFunc(object context)
866 | {
867 | Queue receivedData = new Queue(BufferList.Length);
868 |
869 | while(true)
870 | {
871 | if (Device.Stopping)
872 | break;
873 |
874 | try
875 | {
876 | PendingBuffers.Peek().Wait();
877 | // Process a large group of received buffers in a batch, if available.
878 | int n = 0;
879 | try
880 | {
881 | while (n < BufferList.Length)
882 | {
883 | QueuedBuffer buf = PendingBuffers.Peek();
884 | if (n == 0 || buf.Ready)
885 | {
886 | byte[] data = Device.EndReadPipe(buf);
887 | PendingBuffers.Dequeue();
888 | if (data != null)
889 | { // null is a timeout condition.
890 | receivedData.Enqueue(data);
891 | }
892 | Device.BeginReadPipe(DevicePipeId, buf);
893 | // Todo: If this operation fails during normal operation, the buffer is lost from rotation.
894 | // Should never happen during normal operation, but should confirm and mitigate if it's possible.
895 | PendingBuffers.Enqueue(buf);
896 |
897 | }
898 | n++;
899 | }
900 | }
901 | finally
902 | {
903 | // Unless we're exiting, ensure we always indicate the data, even if some operation failed.
904 | if(!Device.Stopping && receivedData.Count > 0)
905 | {
906 | lock (this)
907 | {
908 | foreach (byte[] data in receivedData)
909 | {
910 | ReceivedData.Enqueue(data);
911 | QueuedLength += data.Length;
912 | TotalReceived += data.Length;
913 | }
914 | }
915 | ThreadPool.QueueUserWorkItem(RaiseNewData);
916 | receivedData.Clear();
917 | }
918 | }
919 | }
920 | catch(Exception ex)
921 | {
922 | System.Diagnostics.Debug.Print("Should not happen: Exception in background thread. {0}", ex.ToString());
923 | Thread.Sleep(15);
924 | }
925 |
926 | ReceiveTick.Set();
927 |
928 | }
929 | Stopped = true;
930 | }
931 |
932 | public event WinUSBDevice.NewDataCallback NewDataEvent;
933 |
934 | Semaphore EventConcurrency;
935 |
936 | void RaiseNewData(object context)
937 | {
938 | WinUSBDevice.NewDataCallback cb = NewDataEvent;
939 | if (cb != null)
940 | {
941 | if(EventConcurrency.WaitOne(0)) // Prevent requests from stacking up; Don't issue new events if there are several in flight
942 | {
943 | try
944 | {
945 | cb();
946 | }
947 | finally
948 | {
949 | EventConcurrency.Release();
950 | }
951 |
952 | }
953 | }
954 | }
955 |
956 | }
957 |
958 | }
959 |
--------------------------------------------------------------------------------
/AForge_libs/gpl-3.0.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------