Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/ClusterM/ibutton_client.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlexey 'Cluster' Avdyukhin <clusterrr@clusterrr.com>2014-01-22 23:11:09 +0400
committerAlexey 'Cluster' Avdyukhin <clusterrr@clusterrr.com>2014-01-22 23:11:09 +0400
commit0aeadfe2a098559ea0e647745adccbaf3dfc0168 (patch)
treeeab3edb8913fe2c6b605d2d9857964c23b81f09e
parent5f911b2c0be7807c27cc823038308b983730111d (diff)
First commit
-rw-r--r--iButonManager/App.config18
-rw-r--r--iButonManager/FormIButtonManager.Designer.cs408
-rw-r--r--iButonManager/FormIButtonManager.cs350
-rw-r--r--iButonManager/FormIButtonManager.resx171
-rw-r--r--iButonManager/Program.cs22
-rw-r--r--iButonManager/Properties/AssemblyInfo.cs36
-rw-r--r--iButonManager/Properties/Resources.Designer.cs63
-rw-r--r--iButonManager/Properties/Resources.resx117
-rw-r--r--iButonManager/Properties/Settings.Designer.cs38
-rw-r--r--iButonManager/Properties/Settings.settings9
-rw-r--r--iButonManager/iButtonManager.csproj121
-rw-r--r--iButonManager/ibutton.icobin0 -> 766 bytes
-rw-r--r--iButton.sln34
-rw-r--r--iButtonLib/HIDDevice.cs234
-rw-r--r--iButtonLib/Properties/AssemblyInfo.cs36
-rw-r--r--iButtonLib/Win32Usb.cs288
-rw-r--r--iButtonLib/iButtonConnection.cs147
-rw-r--r--iButtonLib/iButtonConnectionUsb.cs100
-rw-r--r--iButtonLib/iButtonKey.cs92
-rw-r--r--iButtonLib/iButtonLib.csproj75
20 files changed, 2359 insertions, 0 deletions
diff --git a/iButonManager/App.config b/iButonManager/App.config
new file mode 100644
index 0000000..71e6ee5
--- /dev/null
+++ b/iButonManager/App.config
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+ <configSections>
+ <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
+ <section name="iButonManager.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
+ </sectionGroup>
+ </configSections>
+ <startup>
+ <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
+ </startup>
+ <userSettings>
+ <iButonManager.Properties.Settings>
+ <setting name="Port" serializeAs="String">
+ <value>COM4</value>
+ </setting>
+ </iButonManager.Properties.Settings>
+ </userSettings>
+</configuration> \ No newline at end of file
diff --git a/iButonManager/FormIButtonManager.Designer.cs b/iButonManager/FormIButtonManager.Designer.cs
new file mode 100644
index 0000000..c8a33e4
--- /dev/null
+++ b/iButonManager/FormIButtonManager.Designer.cs
@@ -0,0 +1,408 @@
+namespace Cluster.iButtonManager
+{
+ partial class FormIButtonManager
+ {
+ /// <summary>
+ /// Требуется переменная конструктора.
+ /// </summary>
+ private System.ComponentModel.IContainer components = null;
+
+ /// <summary>
+ /// Освободить все используемые ресурсы.
+ /// </summary>
+ /// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (components != null))
+ {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Код, автоматически созданный конструктором форм Windows
+
+ /// <summary>
+ /// Обязательный метод для поддержки конструктора - не изменяйте
+ /// содержимое данного метода при помощи редактора кода.
+ /// </summary>
+ private void InitializeComponent()
+ {
+ System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
+ System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
+ System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormIButtonManager));
+ this.dataGridViewDatabase = new System.Windows.Forms.DataGridView();
+ this.buttonRead = new System.Windows.Forms.Button();
+ this.dataGridViewKey = new System.Windows.Forms.DataGridView();
+ this.buttonDeleteFromKey = new System.Windows.Forms.Button();
+ this.buttonUpKey = new System.Windows.Forms.Button();
+ this.buttonDownKey = new System.Windows.Forms.Button();
+ this.buttonWrite = new System.Windows.Forms.Button();
+ this.label1 = new System.Windows.Forms.Label();
+ this.label2 = new System.Windows.Forms.Label();
+ this.buttonDown = new System.Windows.Forms.Button();
+ this.buttonUp = new System.Windows.Forms.Button();
+ this.buttonDelete = new System.Windows.Forms.Button();
+ this.buttonAddToDevice = new System.Windows.Forms.Button();
+ this.menuStrip = new System.Windows.Forms.MenuStrip();
+ this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.определитьПортToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.перезагрузитьУстройствоToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.colNum = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.colType = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.colKey = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.colCRC = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.colDescription = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.colNumK = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.colTypeK = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.colKeyK = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.colCRCK = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ this.colDescriptionK = new System.Windows.Forms.DataGridViewTextBoxColumn();
+ ((System.ComponentModel.ISupportInitialize)(this.dataGridViewDatabase)).BeginInit();
+ ((System.ComponentModel.ISupportInitialize)(this.dataGridViewKey)).BeginInit();
+ this.menuStrip.SuspendLayout();
+ this.SuspendLayout();
+ //
+ // dataGridViewDatabase
+ //
+ this.dataGridViewDatabase.AllowUserToAddRows = false;
+ this.dataGridViewDatabase.AllowUserToDeleteRows = false;
+ this.dataGridViewDatabase.AllowUserToResizeRows = false;
+ this.dataGridViewDatabase.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.dataGridViewDatabase.BackgroundColor = System.Drawing.SystemColors.ButtonFace;
+ this.dataGridViewDatabase.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
+ this.dataGridViewDatabase.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
+ this.colNum,
+ this.colType,
+ this.colKey,
+ this.colCRC,
+ this.colDescription});
+ this.dataGridViewDatabase.Location = new System.Drawing.Point(12, 40);
+ this.dataGridViewDatabase.MultiSelect = false;
+ this.dataGridViewDatabase.Name = "dataGridViewDatabase";
+ this.dataGridViewDatabase.RowHeadersVisible = false;
+ this.dataGridViewDatabase.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
+ this.dataGridViewDatabase.Size = new System.Drawing.Size(704, 247);
+ this.dataGridViewDatabase.TabIndex = 0;
+ this.dataGridViewDatabase.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewDatabase_CellDoubleClick);
+ this.dataGridViewDatabase.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewDatabase_CellEndEdit);
+ this.dataGridViewDatabase.Sorted += new System.EventHandler(this.dataGridViewDatabase_Sorted);
+ //
+ // buttonRead
+ //
+ this.buttonRead.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
+ this.buttonRead.Location = new System.Drawing.Point(12, 567);
+ this.buttonRead.Name = "buttonRead";
+ this.buttonRead.Size = new System.Drawing.Size(179, 23);
+ this.buttonRead.TabIndex = 6;
+ this.buttonRead.Text = "Прочитать ключи";
+ this.buttonRead.UseVisualStyleBackColor = true;
+ this.buttonRead.Click += new System.EventHandler(this.buttonRead_Click);
+ //
+ // dataGridViewKey
+ //
+ this.dataGridViewKey.AllowUserToAddRows = false;
+ this.dataGridViewKey.AllowUserToDeleteRows = false;
+ this.dataGridViewKey.AllowUserToResizeRows = false;
+ this.dataGridViewKey.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.dataGridViewKey.BackgroundColor = System.Drawing.SystemColors.ButtonFace;
+ this.dataGridViewKey.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
+ this.dataGridViewKey.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
+ this.colNumK,
+ this.colTypeK,
+ this.colKeyK,
+ this.colCRCK,
+ this.colDescriptionK});
+ this.dataGridViewKey.Location = new System.Drawing.Point(12, 351);
+ this.dataGridViewKey.MultiSelect = false;
+ this.dataGridViewKey.Name = "dataGridViewKey";
+ this.dataGridViewKey.RowHeadersVisible = false;
+ this.dataGridViewKey.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
+ this.dataGridViewKey.Size = new System.Drawing.Size(704, 198);
+ this.dataGridViewKey.TabIndex = 5;
+ this.dataGridViewKey.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewKey_CellEndEdit);
+ this.dataGridViewKey.Sorted += new System.EventHandler(this.dataGridViewKey_Sorted);
+ //
+ // buttonDeleteFromKey
+ //
+ this.buttonDeleteFromKey.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
+ this.buttonDeleteFromKey.Location = new System.Drawing.Point(408, 567);
+ this.buttonDeleteFromKey.Name = "buttonDeleteFromKey";
+ this.buttonDeleteFromKey.Size = new System.Drawing.Size(75, 23);
+ this.buttonDeleteFromKey.TabIndex = 9;
+ this.buttonDeleteFromKey.Text = "Удалить";
+ this.buttonDeleteFromKey.UseVisualStyleBackColor = true;
+ this.buttonDeleteFromKey.Click += new System.EventHandler(this.buttonDeleteFromKey_Click);
+ //
+ // buttonUpKey
+ //
+ this.buttonUpKey.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
+ this.buttonUpKey.Location = new System.Drawing.Point(246, 567);
+ this.buttonUpKey.Name = "buttonUpKey";
+ this.buttonUpKey.Size = new System.Drawing.Size(75, 23);
+ this.buttonUpKey.TabIndex = 7;
+ this.buttonUpKey.Text = "Вверх";
+ this.buttonUpKey.UseVisualStyleBackColor = true;
+ this.buttonUpKey.Click += new System.EventHandler(this.buttonUpKey_Click);
+ //
+ // buttonDownKey
+ //
+ this.buttonDownKey.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
+ this.buttonDownKey.Location = new System.Drawing.Point(327, 567);
+ this.buttonDownKey.Name = "buttonDownKey";
+ this.buttonDownKey.Size = new System.Drawing.Size(75, 23);
+ this.buttonDownKey.TabIndex = 8;
+ this.buttonDownKey.Text = "Вниз";
+ this.buttonDownKey.UseVisualStyleBackColor = true;
+ this.buttonDownKey.Click += new System.EventHandler(this.buttonDownKey_Click);
+ //
+ // buttonWrite
+ //
+ this.buttonWrite.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
+ this.buttonWrite.Location = new System.Drawing.Point(537, 567);
+ this.buttonWrite.Name = "buttonWrite";
+ this.buttonWrite.Size = new System.Drawing.Size(179, 23);
+ this.buttonWrite.TabIndex = 10;
+ this.buttonWrite.Text = "Записать ключи";
+ this.buttonWrite.UseVisualStyleBackColor = true;
+ this.buttonWrite.Click += new System.EventHandler(this.buttonWrite_Click);
+ //
+ // label1
+ //
+ this.label1.AutoSize = true;
+ this.label1.Location = new System.Drawing.Point(12, 24);
+ this.label1.Name = "label1";
+ this.label1.Size = new System.Drawing.Size(78, 13);
+ this.label1.TabIndex = 8;
+ this.label1.Text = "Ключи в базе:";
+ //
+ // label2
+ //
+ this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
+ this.label2.AutoSize = true;
+ this.label2.Location = new System.Drawing.Point(12, 335);
+ this.label2.Name = "label2";
+ this.label2.Size = new System.Drawing.Size(111, 13);
+ this.label2.TabIndex = 9;
+ this.label2.Text = "Ключи в устройстве:";
+ //
+ // buttonDown
+ //
+ this.buttonDown.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
+ this.buttonDown.Location = new System.Drawing.Point(327, 293);
+ this.buttonDown.Name = "buttonDown";
+ this.buttonDown.Size = new System.Drawing.Size(75, 23);
+ this.buttonDown.TabIndex = 2;
+ this.buttonDown.Text = "Вниз";
+ this.buttonDown.UseVisualStyleBackColor = true;
+ this.buttonDown.Click += new System.EventHandler(this.buttonDown_Click);
+ //
+ // buttonUp
+ //
+ this.buttonUp.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
+ this.buttonUp.Location = new System.Drawing.Point(246, 293);
+ this.buttonUp.Name = "buttonUp";
+ this.buttonUp.Size = new System.Drawing.Size(75, 23);
+ this.buttonUp.TabIndex = 1;
+ this.buttonUp.Text = "Вверх";
+ this.buttonUp.UseVisualStyleBackColor = true;
+ this.buttonUp.Click += new System.EventHandler(this.buttonUp_Click);
+ //
+ // buttonDelete
+ //
+ this.buttonDelete.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
+ this.buttonDelete.Location = new System.Drawing.Point(408, 293);
+ this.buttonDelete.Name = "buttonDelete";
+ this.buttonDelete.Size = new System.Drawing.Size(75, 23);
+ this.buttonDelete.TabIndex = 3;
+ this.buttonDelete.Text = "Удалить";
+ this.buttonDelete.UseVisualStyleBackColor = true;
+ this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click);
+ //
+ // buttonAddToDevice
+ //
+ this.buttonAddToDevice.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
+ this.buttonAddToDevice.Location = new System.Drawing.Point(537, 293);
+ this.buttonAddToDevice.Name = "buttonAddToDevice";
+ this.buttonAddToDevice.Size = new System.Drawing.Size(179, 23);
+ this.buttonAddToDevice.TabIndex = 4;
+ this.buttonAddToDevice.Text = "Добавить в устройство";
+ this.buttonAddToDevice.UseVisualStyleBackColor = true;
+ this.buttonAddToDevice.Click += new System.EventHandler(this.buttonAddToDevice_Click);
+ //
+ // menuStrip
+ //
+ this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
+ this.файлToolStripMenuItem});
+ this.menuStrip.Location = new System.Drawing.Point(0, 0);
+ this.menuStrip.Name = "menuStrip";
+ this.menuStrip.Size = new System.Drawing.Size(728, 24);
+ this.menuStrip.TabIndex = 14;
+ this.menuStrip.Text = "menuStrip";
+ //
+ // файлToolStripMenuItem
+ //
+ this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
+ this.определитьПортToolStripMenuItem,
+ this.перезагрузитьУстройствоToolStripMenuItem});
+ this.файлToolStripMenuItem.Name = "файлToolStripMenuItem";
+ this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
+ this.файлToolStripMenuItem.Text = "Файл";
+ //
+ // определитьПортToolStripMenuItem
+ //
+ this.определитьПортToolStripMenuItem.Name = "определитьПортToolStripMenuItem";
+ this.определитьПортToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
+ this.определитьПортToolStripMenuItem.Text = "Определить порт";
+ this.определитьПортToolStripMenuItem.Click += new System.EventHandler(this.определитьПортToolStripMenuItem_Click);
+ //
+ // перезагрузитьУстройствоToolStripMenuItem
+ //
+ this.перезагрузитьУстройствоToolStripMenuItem.Name = "перезагрузитьУстройствоToolStripMenuItem";
+ this.перезагрузитьУстройствоToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
+ this.перезагрузитьУстройствоToolStripMenuItem.Text = "Перезагрузить устройство";
+ this.перезагрузитьУстройствоToolStripMenuItem.Click += new System.EventHandler(this.перезагрузитьУстройствоToolStripMenuItem_Click);
+ //
+ // colNum
+ //
+ this.colNum.HeaderText = "№";
+ this.colNum.Name = "colNum";
+ this.colNum.ReadOnly = true;
+ this.colNum.Width = 30;
+ //
+ // colType
+ //
+ this.colType.HeaderText = "Тип";
+ this.colType.Name = "colType";
+ this.colType.ReadOnly = true;
+ this.colType.Width = 70;
+ //
+ // colKey
+ //
+ dataGridViewCellStyle1.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
+ this.colKey.DefaultCellStyle = dataGridViewCellStyle1;
+ this.colKey.HeaderText = "Серийник";
+ this.colKey.Name = "colKey";
+ this.colKey.ReadOnly = true;
+ this.colKey.Width = 200;
+ //
+ // colCRC
+ //
+ this.colCRC.HeaderText = "CRC";
+ this.colCRC.Name = "colCRC";
+ this.colCRC.ReadOnly = true;
+ this.colCRC.Width = 50;
+ //
+ // colDescription
+ //
+ this.colDescription.HeaderText = "Описание";
+ this.colDescription.Name = "colDescription";
+ this.colDescription.Width = 350;
+ //
+ // colNumK
+ //
+ this.colNumK.HeaderText = "№";
+ this.colNumK.Name = "colNumK";
+ this.colNumK.ReadOnly = true;
+ this.colNumK.Width = 30;
+ //
+ // colTypeK
+ //
+ this.colTypeK.HeaderText = "Тип";
+ this.colTypeK.Name = "colTypeK";
+ this.colTypeK.ReadOnly = true;
+ this.colTypeK.Width = 70;
+ //
+ // colKeyK
+ //
+ dataGridViewCellStyle2.Font = new System.Drawing.Font("Courier New", 9F);
+ this.colKeyK.DefaultCellStyle = dataGridViewCellStyle2;
+ this.colKeyK.HeaderText = "Серийник";
+ this.colKeyK.Name = "colKeyK";
+ this.colKeyK.ReadOnly = true;
+ this.colKeyK.Width = 200;
+ //
+ // colCRCK
+ //
+ this.colCRCK.HeaderText = "CRC";
+ this.colCRCK.Name = "colCRCK";
+ this.colCRCK.ReadOnly = true;
+ this.colCRCK.Width = 50;
+ //
+ // colDescriptionK
+ //
+ this.colDescriptionK.HeaderText = "Описание";
+ this.colDescriptionK.Name = "colDescriptionK";
+ this.colDescriptionK.Width = 350;
+ //
+ // FormIButtonManager
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+ this.ClientSize = new System.Drawing.Size(728, 602);
+ this.Controls.Add(this.buttonDown);
+ this.Controls.Add(this.buttonUp);
+ this.Controls.Add(this.buttonDelete);
+ this.Controls.Add(this.buttonAddToDevice);
+ this.Controls.Add(this.label2);
+ this.Controls.Add(this.label1);
+ this.Controls.Add(this.buttonWrite);
+ this.Controls.Add(this.buttonDownKey);
+ this.Controls.Add(this.buttonUpKey);
+ this.Controls.Add(this.buttonDeleteFromKey);
+ this.Controls.Add(this.dataGridViewKey);
+ this.Controls.Add(this.buttonRead);
+ this.Controls.Add(this.dataGridViewDatabase);
+ this.Controls.Add(this.menuStrip);
+ this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
+ this.MainMenuStrip = this.menuStrip;
+ this.MinimumSize = new System.Drawing.Size(684, 641);
+ this.Name = "FormIButtonManager";
+ this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
+ this.Text = "iButton Manager";
+ this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormIButtonManager_FormClosing);
+ this.Load += new System.EventHandler(this.FormIButtonManager_Load);
+ ((System.ComponentModel.ISupportInitialize)(this.dataGridViewDatabase)).EndInit();
+ ((System.ComponentModel.ISupportInitialize)(this.dataGridViewKey)).EndInit();
+ this.menuStrip.ResumeLayout(false);
+ this.menuStrip.PerformLayout();
+ this.ResumeLayout(false);
+ this.PerformLayout();
+
+ }
+
+ #endregion
+
+ private System.Windows.Forms.DataGridView dataGridViewDatabase;
+ private System.Windows.Forms.Button buttonRead;
+ private System.Windows.Forms.DataGridView dataGridViewKey;
+ private System.Windows.Forms.Button buttonDeleteFromKey;
+ private System.Windows.Forms.Button buttonUpKey;
+ private System.Windows.Forms.Button buttonDownKey;
+ private System.Windows.Forms.Button buttonWrite;
+ private System.Windows.Forms.Label label1;
+ private System.Windows.Forms.Label label2;
+ private System.Windows.Forms.Button buttonDown;
+ private System.Windows.Forms.Button buttonUp;
+ private System.Windows.Forms.Button buttonDelete;
+ private System.Windows.Forms.Button buttonAddToDevice;
+ private System.Windows.Forms.MenuStrip menuStrip;
+ private System.Windows.Forms.ToolStripMenuItem файлToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem определитьПортToolStripMenuItem;
+ private System.Windows.Forms.ToolStripMenuItem перезагрузитьУстройствоToolStripMenuItem;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colNum;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colType;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colKey;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colCRC;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colDescription;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colNumK;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colTypeK;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colKeyK;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colCRCK;
+ private System.Windows.Forms.DataGridViewTextBoxColumn colDescriptionK;
+ }
+}
+
diff --git a/iButonManager/FormIButtonManager.cs b/iButonManager/FormIButtonManager.cs
new file mode 100644
index 0000000..5d54010
--- /dev/null
+++ b/iButonManager/FormIButtonManager.cs
@@ -0,0 +1,350 @@
+using Cluster.iButtonManager.Properties;
+using Cluster.iButtonLib;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Data;
+using System.Drawing;
+using System.IO;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+
+namespace Cluster.iButtonManager
+{
+ public partial class FormIButtonManager : Form
+ {
+ public FormIButtonManager()
+ {
+ InitializeComponent();
+ }
+
+ private string KeyType(byte type)
+ {
+ switch (type)
+ {
+ case 0xFF: return "Cyfral";
+ case 0xFE: return "Metacom";
+ default: return string.Format("{0:X2}", type);
+ }
+ }
+
+ private void buttonRead_Click(object sender, EventArgs e)
+ {
+ try
+ {
+ var connection = new iButtonConnection(Settings.Default.Port);
+ var keys = connection.ReadKeys();
+ dataGridViewKey.Rows.Clear();
+ dataGridViewKey.RowCount = keys.Length;
+ for (int i = 0; i < keys.Length; i++)
+ {
+ dataGridViewKey.Rows[i].Tag = keys[i];
+ dataGridViewKey.Rows[i].Cells["colTypeK"].Value = KeyType(keys[i].Type);
+ dataGridViewKey.Rows[i].Cells["colKeyK"].Value = keys[i].Key;
+ dataGridViewKey.Rows[i].Cells["colCRCK"].Value = (keys[i].Type != 0xFF ? string.Format("{0:X2}", keys[i].CRC) : "--");
+ bool found = false;
+ foreach (DataGridViewRow keyInDB in dataGridViewDatabase.Rows)
+ {
+ if (((iButtonKey)keyInDB.Tag).ToString() == keys[i].ToString())
+ {
+ found = true;
+ dataGridViewKey.Rows[i].Cells["colDescriptionK"].Value = keyInDB.Cells["colDescription"].Value;
+ }
+ }
+ if (!found)
+ {
+ var newRow = dataGridViewDatabase.Rows.Add();
+ dataGridViewDatabase.Rows[newRow].Tag = keys[i];
+ dataGridViewDatabase.Rows[newRow].Cells["colType"].Value = KeyType(keys[i].Type);
+ dataGridViewDatabase.Rows[newRow].Cells["colKey"].Value = keys[i].Key;
+ dataGridViewDatabase.Rows[newRow].Cells["colCRC"].Value = (keys[i].Type != 0xFF ? string.Format("{0:X2}", keys[i].CRC) : "--");
+ dataGridViewKey.Rows[i].Cells["colDescriptionK"].Value =
+ dataGridViewDatabase.Rows[newRow].Cells["colDescription"].Value = "Добавлен " + DateTime.Now.ToString();
+ }
+ }
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ dataGridViewDatabase.Rows[i].Cells["colNum"].Value = i + 1;
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ dataGridViewKey.Rows[i].Cells["colNumK"].Value = i + 1;
+ SaveDatabase();
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show(this, ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+
+ private void buttonWrite_Click(object sender, EventArgs e)
+ {
+ if (MessageBox.Show(this, "Уверен?", "Записать?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
+ != System.Windows.Forms.DialogResult.Yes) return;
+ try
+ {
+ var connection = new iButtonConnection(Settings.Default.Port);
+ connection.Erase();
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ connection.Write(((iButtonKey)dataGridViewKey.Rows[i].Tag));
+ MessageBox.Show(this, "Готово!", "Запись ключей", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show(this, ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+
+ private void buttonDeleteFromKey_Click(object sender, EventArgs e)
+ {
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ {
+ if (dataGridViewKey.Rows[i].Selected &&
+ MessageBox.Show(this, "Уверен?", "Удалить?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
+ == System.Windows.Forms.DialogResult.Yes)
+ {
+ dataGridViewKey.Rows.RemoveAt(i);
+ break;
+ }
+ }
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ dataGridViewKey.Rows[i].Cells["colNumK"].Value = i + 1;
+ }
+
+ private void dataGridViewDatabase_CellEndEdit(object sender, DataGridViewCellEventArgs e)
+ {
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ {
+ if (dataGridViewDatabase.Rows[e.RowIndex].Tag.ToString() == dataGridViewKey.Rows[i].Tag.ToString())
+ {
+ dataGridViewKey.Rows[i].Cells["colDescriptionK"].Value = dataGridViewDatabase.Rows[e.RowIndex].Cells["colDescription"].Value;
+ }
+ }
+ }
+
+ private void dataGridViewKey_CellEndEdit(object sender, DataGridViewCellEventArgs e)
+ {
+ var newDescription = dataGridViewKey.Rows[e.RowIndex].Cells["colDescriptionK"].Value;
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ {
+ if (dataGridViewDatabase.Rows[i].Tag.ToString() == dataGridViewKey.Rows[e.RowIndex].Tag.ToString())
+ {
+ dataGridViewDatabase.Rows[i].Cells["colDescription"].Value = newDescription;
+ }
+ }
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ {
+ if (dataGridViewKey.Rows[i].Tag.ToString() == dataGridViewKey.Rows[e.RowIndex].Tag.ToString())
+ {
+ dataGridViewKey.Rows[i].Cells["colDescriptionK"].Value = newDescription;
+ }
+ }
+ }
+
+ private void dataGridViewDatabase_Sorted(object sender, EventArgs e)
+ {
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ dataGridViewDatabase.Rows[i].Cells["colNum"].Value = i + 1;
+ }
+
+ private void dataGridViewKey_Sorted(object sender, EventArgs e)
+ {
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ dataGridViewKey.Rows[i].Cells["colNumK"].Value = i + 1;
+ }
+
+ void AddToDeviceSelectedRow()
+ {
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ {
+ if (dataGridViewDatabase.Rows[i].Selected)
+ {
+ var newRow = dataGridViewKey.Rows.Add();
+ dataGridViewKey.Rows[newRow].Tag = dataGridViewDatabase.Rows[i].Tag;
+ dataGridViewKey.Rows[newRow].Cells["colTypeK"].Value = dataGridViewDatabase.Rows[i].Cells["colType"].Value;
+ dataGridViewKey.Rows[newRow].Cells["colKeyK"].Value = dataGridViewDatabase.Rows[i].Cells["colKey"].Value;
+ dataGridViewKey.Rows[newRow].Cells["colCRCK"].Value = dataGridViewDatabase.Rows[i].Cells["colCRC"].Value;
+ dataGridViewKey.Rows[newRow].Cells["colDescriptionK"].Value = dataGridViewDatabase.Rows[i].Cells["colDescription"].Value;
+ }
+ }
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ dataGridViewKey.Rows[i].Cells["colNumK"].Value = i + 1;
+ }
+
+ private void buttonAddToDevice_Click(object sender, EventArgs e)
+ {
+ AddToDeviceSelectedRow();
+ }
+
+ private void dataGridViewDatabase_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
+ {
+ if (dataGridViewDatabase.Columns[e.ColumnIndex].Name != "colDescription")
+ AddToDeviceSelectedRow();
+ }
+
+ private void buttonUpKey_Click(object sender, EventArgs e)
+ {
+ for (int i = 1; i < dataGridViewKey.RowCount; i++)
+ {
+ if (dataGridViewKey.Rows[i].Selected)
+ {
+ var row1 = dataGridViewKey.Rows[i - 1];
+ var row2 = dataGridViewKey.Rows[i];
+ dataGridViewKey.Rows.RemoveAt(i - 1);
+ dataGridViewKey.Rows.RemoveAt(i - 1);
+ dataGridViewKey.Rows.Insert(i - 1, row2);
+ dataGridViewKey.Rows.Insert(i, row1);
+ dataGridViewKey.Rows[i - 1].Selected = true;
+ break;
+ }
+ }
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ dataGridViewKey.Rows[i].Cells["colNumK"].Value = i + 1;
+ }
+
+ private void buttonDownKey_Click(object sender, EventArgs e)
+ {
+ for (int i = 0; i < dataGridViewKey.RowCount - 1; i++)
+ {
+ if (dataGridViewKey.Rows[i].Selected)
+ {
+ var row1 = dataGridViewKey.Rows[i];
+ var row2 = dataGridViewKey.Rows[i + 1];
+ dataGridViewKey.Rows.RemoveAt(i);
+ dataGridViewKey.Rows.RemoveAt(i);
+ dataGridViewKey.Rows.Insert(i, row1);
+ dataGridViewKey.Rows.Insert(i, row2);
+ dataGridViewKey.Rows[i + 1].Selected = true;
+ break;
+ }
+ }
+ for (int i = 0; i < dataGridViewKey.RowCount; i++)
+ dataGridViewKey.Rows[i].Cells["colNumK"].Value = i + 1;
+ }
+
+ private void buttonUp_Click(object sender, EventArgs e)
+ {
+ for (int i = 1; i < dataGridViewDatabase.RowCount; i++)
+ {
+ if (dataGridViewDatabase.Rows[i].Selected)
+ {
+ var row1 = dataGridViewDatabase.Rows[i - 1];
+ var row2 = dataGridViewDatabase.Rows[i];
+ dataGridViewDatabase.Rows.RemoveAt(i - 1);
+ dataGridViewDatabase.Rows.RemoveAt(i - 1);
+ dataGridViewDatabase.Rows.Insert(i - 1, row2);
+ dataGridViewDatabase.Rows.Insert(i, row1);
+ dataGridViewDatabase.Rows[i - 1].Selected = true;
+ break;
+ }
+ }
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ dataGridViewDatabase.Rows[i].Cells["colNum"].Value = i + 1;
+ }
+
+ private void buttonDown_Click(object sender, EventArgs e)
+ {
+ for (int i = 0; i < dataGridViewDatabase.RowCount - 1; i++)
+ {
+ if (dataGridViewDatabase.Rows[i].Selected)
+ {
+ var row1 = dataGridViewDatabase.Rows[i];
+ var row2 = dataGridViewDatabase.Rows[i + 1];
+ dataGridViewDatabase.Rows.RemoveAt(i);
+ dataGridViewDatabase.Rows.RemoveAt(i);
+ dataGridViewDatabase.Rows.Insert(i, row1);
+ dataGridViewDatabase.Rows.Insert(i, row2);
+ dataGridViewDatabase.Rows[i + 1].Selected = true;
+ break;
+ }
+ }
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ dataGridViewDatabase.Rows[i].Cells["colNum"].Value = i + 1;
+ }
+
+ private void buttonDelete_Click(object sender, EventArgs e)
+ {
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ {
+ if (dataGridViewDatabase.Rows[i].Selected &&
+ MessageBox.Show(this, "Уверен?", "Удалить?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
+ == System.Windows.Forms.DialogResult.Yes)
+ {
+ dataGridViewDatabase.Rows.RemoveAt(i);
+ break;
+ }
+ }
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ dataGridViewDatabase.Rows[i].Cells["colNum"].Value = i + 1;
+ }
+
+ private void SaveDatabase()
+ {
+ var database = new List<string>();
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ {
+ database.Add(dataGridViewDatabase.Rows[i].Tag.ToString() + ";" + dataGridViewDatabase.Rows[i].Cells["colDescription"].Value);
+ }
+ File.WriteAllLines(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "keys.dat"), database);
+ }
+
+ private void FormIButtonManager_FormClosing(object sender, FormClosingEventArgs e)
+ {
+ SaveDatabase();
+ }
+
+ private void FormIButtonManager_Load(object sender, EventArgs e)
+ {
+ try
+ {
+ var database = File.ReadAllLines(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "keys.dat"));
+ dataGridViewDatabase.RowCount = database.Length;
+ for (int i = 0; i < database.Length; i++)
+ {
+ var line = database[i];
+ int d = line.IndexOf(";");
+ var key = new iButtonKey(line.Substring(0, d));
+ var description = line.Substring(d + 1);
+ dataGridViewDatabase.Rows[i].Tag = key;
+ dataGridViewDatabase.Rows[i].Cells["colType"].Value = KeyType(key.Type);
+ dataGridViewDatabase.Rows[i].Cells["colKey"].Value = key.Key;
+ dataGridViewDatabase.Rows[i].Cells["colCRC"].Value = (key.Type != 0xFF ? string.Format("{0:X2}", key.CRC) : "--");
+ dataGridViewDatabase.Rows[i].Cells["colDescription"].Value = description;
+ }
+ for (int i = 0; i < dataGridViewDatabase.RowCount; i++)
+ dataGridViewDatabase.Rows[i].Cells["colNum"].Value = i + 1;
+ }
+ catch { }
+ }
+
+ private void определитьПортToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ var ports = SerialPort.GetPortNames();
+ foreach (var port in ports)
+ {
+ if (new iButtonConnection(port).Test())
+ {
+ Settings.Default.Port = port;
+ Settings.Default.Save();
+ MessageBox.Show(this, "Порт определён: " + port, "Определение порта", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ return;
+ }
+ }
+ MessageBox.Show(this, "Не определён", "Определение порта", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+
+ private void перезагрузитьУстройствоToolStripMenuItem_Click(object sender, EventArgs e)
+ {
+ var connection = new iButtonConnection(Settings.Default.Port);
+ try
+ {
+ connection.Reboot();
+ MessageBox.Show(this, "Готово", "Перезагрузка", MessageBoxButtons.OK, MessageBoxIcon.Information);
+ }
+ catch (Exception ex)
+ {
+ MessageBox.Show(this, ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
+ }
+ }
+}
diff --git a/iButonManager/FormIButtonManager.resx b/iButonManager/FormIButtonManager.resx
new file mode 100644
index 0000000..45b9669
--- /dev/null
+++ b/iButonManager/FormIButtonManager.resx
@@ -0,0 +1,171 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <metadata name="colNum.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="colType.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="colKey.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="colCRC.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="colDescription.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="colNumK.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="colTypeK.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="colKeyK.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="colCRCK.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="colDescriptionK.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <value>True</value>
+ </metadata>
+ <metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+ <value>17, 17</value>
+ </metadata>
+ <assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+ <data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>
+ AAABAAEAICAQAAAAAADoAgAAFgAAACgAAAAgAAAAQAAAAAEABAAAAAAAgAIAAAAAAAAAAAAAAAAAAAAA
+ AAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAgICAAMDAwAAAAP8AAP8AAAD//wD/AAAA/wD/AP//
+ AAD///8AAAAAAAAAAP//AAAAAAAAAAAAAAAA//AAAA//AAAAAAAAAAAA/wAA//8AAP8AAAAAAAAADwD/
+ //////8A8AAAAAAAD/AP////////8A/wAAAAAPAP///////////w/wAAAADw/////////////w8AAAAP
+ D////3iHiHiP///w8AAA8A////+G+G+G////8A8AAPD/////iIiIiI////8PAA8P////////////////
+ 8PAPD/////////////////DwDw/////////////////w8PAP////////////////8P/w////////////
+ //////8P8P//eDSDSDSDSDSDSHj/D/D///ePePePePePePeP/w/w//+HeHeHeHeHeHeHf/8P8A//f4b4
+ b4b4b4b4b4jw/w8P////////////////8PAPD/////////////////DwDw/////////////////w8ADw
+ //////eIeI//////DwAA8A/////4b4b/////8A8AAA8P////+IiIj/////DwAAAA8P////////////8P
+ AAAAAPAP///////////w/wAAAAAP8A/////////wD/AAAAAAAA8A////////APAAAAAAAAAA/wAA//8A
+ AP8AAAAAAAAAAAD/8AAAD/8AAAAAAAAAAAAAAAD//wAAAAAAAAD//D///8AD//8AAP/+AAB/+AAAH/AA
+ AA/wAAAP4AAAB8AAAAPAAAADgAAAAYAAAAGAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAYAA
+ AAGAAAABwAAAA8AAAAPgAAAH8AAAD/AAAA/4AAAf/gAAf/8AAP//wAP///w//w==
+</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/iButonManager/Program.cs b/iButonManager/Program.cs
new file mode 100644
index 0000000..570c91e
--- /dev/null
+++ b/iButonManager/Program.cs
@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+
+namespace Cluster.iButtonManager
+{
+ static class Program
+ {
+ /// <summary>
+ /// Главная точка входа для приложения.
+ /// </summary>
+ [STAThread]
+ static void Main()
+ {
+ Application.EnableVisualStyles();
+ Application.SetCompatibleTextRenderingDefault(false);
+ Application.Run(new FormIButtonManager());
+ }
+ }
+}
diff --git a/iButonManager/Properties/AssemblyInfo.cs b/iButonManager/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..d28b5a9
--- /dev/null
+++ b/iButonManager/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// Управление общими сведениями о сборке осуществляется с помощью
+// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("iButonManager")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("iButonManager")]
+[assembly: AssemblyCopyright("Copyright © 2013")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
+// для COM-компонентов. Если требуется обратиться к типу в этой сборке через
+// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
+[assembly: ComVisible(false)]
+
+// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
+[assembly: Guid("8ffdb493-ceb6-45e7-b348-1cd91247fc59")]
+
+// Сведения о версии сборки состоят из следующих четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер построения
+// Редакция
+//
+// Можно задать все значения или принять номер построения и номер редакции по умолчанию,
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/iButonManager/Properties/Resources.Designer.cs b/iButonManager/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..9d060b4
--- /dev/null
+++ b/iButonManager/Properties/Resources.Designer.cs
@@ -0,0 +1,63 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// Этот код создан программой.
+// Исполняемая версия:4.0.30319.18010
+//
+// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
+// повторной генерации кода.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace Cluster.iButtonManager.Properties {
+ using System;
+
+
+ /// <summary>
+ /// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
+ /// </summary>
+ // Этот класс создан автоматически классом StronglyTypedResourceBuilder
+ // с помощью такого средства, как ResGen или Visual Studio.
+ // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
+ // с параметром /str или перестройте свой проект VS.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources() {
+ }
+
+ /// <summary>
+ /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Cluster.iButtonManager.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Перезаписывает свойство CurrentUICulture текущего потока для всех
+ /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/iButonManager/Properties/Resources.resx b/iButonManager/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/iButonManager/Properties/Resources.resx
@@ -0,0 +1,117 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+</root> \ No newline at end of file
diff --git a/iButonManager/Properties/Settings.Designer.cs b/iButonManager/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..500592a
--- /dev/null
+++ b/iButonManager/Properties/Settings.Designer.cs
@@ -0,0 +1,38 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// Этот код создан программой.
+// Исполняемая версия:4.0.30319.18010
+//
+// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
+// повторной генерации кода.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace Cluster.iButtonManager.Properties {
+
+
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default {
+ get {
+ return defaultInstance;
+ }
+ }
+
+ [global::System.Configuration.UserScopedSettingAttribute()]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Configuration.DefaultSettingValueAttribute("COM4")]
+ public string Port {
+ get {
+ return ((string)(this["Port"]));
+ }
+ set {
+ this["Port"] = value;
+ }
+ }
+ }
+}
diff --git a/iButonManager/Properties/Settings.settings b/iButonManager/Properties/Settings.settings
new file mode 100644
index 0000000..004f1b0
--- /dev/null
+++ b/iButonManager/Properties/Settings.settings
@@ -0,0 +1,9 @@
+<?xml version='1.0' encoding='utf-8'?>
+<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="iButonManager.Properties" GeneratedClassName="Settings">
+ <Profiles />
+ <Settings>
+ <Setting Name="Port" Type="System.String" Scope="User">
+ <Value Profile="(Default)">COM4</Value>
+ </Setting>
+ </Settings>
+</SettingsFile> \ No newline at end of file
diff --git a/iButonManager/iButtonManager.csproj b/iButonManager/iButtonManager.csproj
new file mode 100644
index 0000000..26af67b
--- /dev/null
+++ b/iButonManager/iButtonManager.csproj
@@ -0,0 +1,121 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProjectGuid>{D63C743C-2D8E-421B-801C-12BF1FD6D59C}</ProjectGuid>
+ <OutputType>WinExe</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Cluster.iButtonManager</RootNamespace>
+ <AssemblyName>iButton Manager</AssemblyName>
+ <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <PlatformTarget>AnyCPU</PlatformTarget>
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <PlatformTarget>AnyCPU</PlatformTarget>
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>..\..\..\..\..\Soft\Soft\iButtonManager\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup>
+ <ApplicationIcon>ibutton.ico</ApplicationIcon>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
+ <DebugSymbols>true</DebugSymbols>
+ <OutputPath>bin\x86\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <DebugType>full</DebugType>
+ <PlatformTarget>x86</PlatformTarget>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
+ <OutputPath>bin\x86\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <Optimize>true</Optimize>
+ <DebugType>pdbonly</DebugType>
+ <PlatformTarget>x86</PlatformTarget>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
+ <Prefer32Bit>true</Prefer32Bit>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Xml.Linq" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Deployment" />
+ <Reference Include="System.Drawing" />
+ <Reference Include="System.Windows.Forms" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="FormIButtonManager.cs">
+ <SubType>Form</SubType>
+ </Compile>
+ <Compile Include="FormIButtonManager.Designer.cs">
+ <DependentUpon>FormIButtonManager.cs</DependentUpon>
+ </Compile>
+ <Compile Include="Program.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <EmbeddedResource Include="FormIButtonManager.resx">
+ <DependentUpon>FormIButtonManager.cs</DependentUpon>
+ </EmbeddedResource>
+ <EmbeddedResource Include="Properties\Resources.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>Resources.Designer.cs</LastGenOutput>
+ <SubType>Designer</SubType>
+ </EmbeddedResource>
+ <Compile Include="Properties\Resources.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DependentUpon>Resources.resx</DependentUpon>
+ <DesignTime>True</DesignTime>
+ </Compile>
+ <None Include="Properties\Settings.settings">
+ <Generator>SettingsSingleFileGenerator</Generator>
+ <LastGenOutput>Settings.Designer.cs</LastGenOutput>
+ </None>
+ <Compile Include="Properties\Settings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DependentUpon>Settings.settings</DependentUpon>
+ <DesignTimeSharedInput>True</DesignTimeSharedInput>
+ </Compile>
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="App.config" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\iButtonLib\iButtonLib.csproj">
+ <Project>{152746d8-f182-40fc-a4a3-c69ae584ddd2}</Project>
+ <Name>iButtonLib</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="ibutton.ico" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project> \ No newline at end of file
diff --git a/iButonManager/ibutton.ico b/iButonManager/ibutton.ico
new file mode 100644
index 0000000..00324c3
--- /dev/null
+++ b/iButonManager/ibutton.ico
Binary files differ
diff --git a/iButton.sln b/iButton.sln
new file mode 100644
index 0000000..9484d46
--- /dev/null
+++ b/iButton.sln
@@ -0,0 +1,34 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2012
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "iButtonLib", "iButtonLib\iButtonLib.csproj", "{152746D8-F182-40FC-A4A3-C69AE584DDD2}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "iButtonManager", "iButonManager\iButtonManager.csproj", "{D63C743C-2D8E-421B-801C-12BF1FD6D59C}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Debug|x86 = Debug|x86
+ Release|Any CPU = Release|Any CPU
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {152746D8-F182-40FC-A4A3-C69AE584DDD2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {152746D8-F182-40FC-A4A3-C69AE584DDD2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {152746D8-F182-40FC-A4A3-C69AE584DDD2}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {152746D8-F182-40FC-A4A3-C69AE584DDD2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {152746D8-F182-40FC-A4A3-C69AE584DDD2}.Release|Any CPU.Build.0 = Release|Any CPU
+ {152746D8-F182-40FC-A4A3-C69AE584DDD2}.Release|x86.ActiveCfg = Release|x86
+ {152746D8-F182-40FC-A4A3-C69AE584DDD2}.Release|x86.Build.0 = Release|x86
+ {D63C743C-2D8E-421B-801C-12BF1FD6D59C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {D63C743C-2D8E-421B-801C-12BF1FD6D59C}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {D63C743C-2D8E-421B-801C-12BF1FD6D59C}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {D63C743C-2D8E-421B-801C-12BF1FD6D59C}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D63C743C-2D8E-421B-801C-12BF1FD6D59C}.Release|Any CPU.Build.0 = Release|Any CPU
+ {D63C743C-2D8E-421B-801C-12BF1FD6D59C}.Release|x86.ActiveCfg = Release|x86
+ {D63C743C-2D8E-421B-801C-12BF1FD6D59C}.Release|x86.Build.0 = Release|x86
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/iButtonLib/HIDDevice.cs b/iButtonLib/HIDDevice.cs
new file mode 100644
index 0000000..ae30a85
--- /dev/null
+++ b/iButtonLib/HIDDevice.cs
@@ -0,0 +1,234 @@
+using System;
+using System.IO;
+using System.Text;
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+namespace UsbLibrary
+{
+ #region Custom exception
+ /// <summary>
+ /// Generic HID device exception
+ /// </summary>
+ public class HIDDeviceException : ApplicationException
+ {
+ public HIDDeviceException(string strMessage) : base(strMessage) { }
+
+ public static HIDDeviceException GenerateWithWinError(string strMessage)
+ {
+ return new HIDDeviceException(string.Format("Msg:{0} WinEr:{1:X8}", strMessage, Marshal.GetLastWin32Error()));
+ }
+
+ public static HIDDeviceException GenerateError(string strMessage)
+ {
+ return new HIDDeviceException(string.Format("Msg:{0}", strMessage));
+ }
+ }
+ #endregion
+
+ public class HIDDevice : Win32Usb, IDisposable
+ {
+ #region Privates variables
+ /// <summary>Filestream we can use to read/write from</summary>
+ private FileStream m_oFile;
+ /// <summary>Length of input report : device gives us this</summary>
+ private int m_nInputReportLength;
+ /// <summary>Length if output report : device gives us this</summary>
+ private int m_nOutputReportLength;
+ /// <summary>Handle to the device</summary>
+ private IntPtr m_hHandle;
+ #endregion
+
+ #region IDisposable Members
+ /// <summary>
+ /// Dispose method
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+ /// <summary>
+ /// Disposer called by both dispose and finalise
+ /// </summary>
+ /// <param name="bDisposing">True if disposing</param>
+ protected virtual void Dispose(bool bDisposing)
+ {
+ try
+ {
+ if (bDisposing) // if we are disposing, need to close the managed resources
+ {
+ if (m_oFile != null)
+ {
+ m_oFile.Close();
+ m_oFile = null;
+ }
+ }
+ if (m_hHandle != IntPtr.Zero) // Dispose and finalize, get rid of unmanaged resources
+ {
+
+ CloseHandle(m_hHandle);
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine(ex.ToString());
+ }
+ }
+ #endregion
+
+ #region Privates/protected
+ /// <summary>
+ /// Initialises the device
+ /// </summary>
+ /// <param name="strPath">Path to the device</param>
+ private void Initialise(string strPath)
+ {
+ // Create the file from the device path
+ m_hHandle = CreateFile(strPath, GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);
+
+ if ( m_hHandle != InvalidHandleValue || m_hHandle == null) // if the open worked...
+ {
+ IntPtr lpData;
+ if (HidD_GetPreparsedData(m_hHandle, out lpData)) // get windows to read the device data into an internal buffer
+ {
+ try
+ {
+ HidCaps oCaps;
+ HidP_GetCaps(lpData, out oCaps); // extract the device capabilities from the internal buffer
+ m_nInputReportLength = oCaps.InputReportByteLength; // get the input...
+ m_nOutputReportLength = oCaps.OutputReportByteLength; // ... and output report lengths
+
+ //m_oFile = new FileStream(m_hHandle, FileAccess.Read | FileAccess.Write, true, m_nInputReportLength, true);
+ m_oFile = new FileStream(new SafeFileHandle(m_hHandle, false), FileAccess.Read | FileAccess.Write, m_nInputReportLength, true);
+
+// BeginAsyncRead(); // kick off the first asynchronous read
+ }
+ catch (Exception)
+ {
+ throw HIDDeviceException.GenerateWithWinError("Failed to get the detailed data from the hid.");
+ }
+ finally
+ {
+ HidD_FreePreparsedData(ref lpData); // before we quit the funtion, we must free the internal buffer reserved in GetPreparsedData
+ }
+ }
+ else // GetPreparsedData failed? Chuck an exception
+ {
+ throw HIDDeviceException.GenerateWithWinError("GetPreparsedData failed");
+ }
+ }
+ else // File open failed? Chuck an exception
+ {
+ m_hHandle = IntPtr.Zero;
+ throw HIDDeviceException.GenerateWithWinError("Failed to create device file");
+ }
+ }
+
+ /// <summary>
+ /// Helper method to return the device path given a DeviceInterfaceData structure and an InfoSet handle.
+ /// Used in 'FindDevice' so check that method out to see how to get an InfoSet handle and a DeviceInterfaceData.
+ /// </summary>
+ /// <param name="hInfoSet">Handle to the InfoSet</param>
+ /// <param name="oInterface">DeviceInterfaceData structure</param>
+ /// <returns>The device path or null if there was some problem</returns>
+ private static string GetDevicePath(IntPtr hInfoSet, ref DeviceInterfaceData oInterface)
+ {
+ uint nRequiredSize = 0;
+ // Get the device interface details
+ if (!SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))
+ {
+ DeviceInterfaceDetailData oDetail = new DeviceInterfaceDetailData();
+ oDetail.Size = 5; // hardcoded to 5! Sorry, but this works and trying more future proof versions by setting the size to the struct sizeof failed miserably. If you manage to sort it, mail me! Thx
+ if (SetupDiGetDeviceInterfaceDetail(hInfoSet, ref oInterface, ref oDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero))
+ {
+ return oDetail.DevicePath;
+ }
+ }
+ return null;
+ }
+ #endregion
+
+ #region Public static
+ /// <summary>
+ /// Finds a device given its PID and VID
+ /// </summary>
+ /// <param name="nVid">Vendor id for device (VID)</param>
+ /// <param name="nPid">Product id for device (PID)</param>
+ /// <param name="oType">Type of device class to create</param>
+ /// <returns>A new device class of the given type or null</returns>
+ public static HIDDevice FindDevice(int nVid, int nPid)
+ {
+ string strPath = string.Empty;
+ string strSearch = string.Format("vid_{0:x4}&pid_{1:x4}", nVid, nPid); // first, build the path search string
+ Guid gHid = HIDGuid;
+ //HidD_GetHidGuid(out gHid); // next, get the GUID from Windows that it uses to represent the HID USB interface
+ IntPtr hInfoSet = SetupDiGetClassDevs(ref gHid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT); // this gets a list of all HID devices currently connected to the computer (InfoSet)
+ try
+ {
+ DeviceInterfaceData oInterface = new DeviceInterfaceData(); // build up a device interface data block
+ oInterface.Size = Marshal.SizeOf(oInterface);
+ // Now iterate through the InfoSet memory block assigned within Windows in the call to SetupDiGetClassDevs
+ // to get device details for each device connected
+ int nIndex = 0;
+ while (SetupDiEnumDeviceInterfaces(hInfoSet, 0, ref gHid, (uint)nIndex, ref oInterface)) // this gets the device interface information for a device at index 'nIndex' in the memory block
+ {
+ string strDevicePath = GetDevicePath(hInfoSet, ref oInterface); // get the device path (see helper method 'GetDevicePath')
+ if (strDevicePath.IndexOf(strSearch) >= 0) // do a string search, if we find the VID/PID string then we found our device!
+ {
+ HIDDevice oNewDevice = new HIDDevice();
+ oNewDevice.Initialise(strDevicePath); // initialise it with the device path
+ return oNewDevice; // and return it
+ }
+ nIndex++; // if we get here, we didn't find our device. So move on to the next one.
+ }
+ }
+ catch(Exception ex)
+ {
+ throw HIDDeviceException.GenerateError(ex.ToString());
+ //Console.WriteLine(ex.ToString());
+ }
+ finally
+ {
+ // Before we go, we have to free up the InfoSet memory reserved by SetupDiGetClassDevs
+ SetupDiDestroyDeviceInfoList(hInfoSet);
+ }
+ return null; // oops, didn't find our device
+ }
+ #endregion
+
+ #region Publics
+ /// <summary>
+ /// Accessor for output report length
+ /// </summary>
+ public int OutputReportLength
+ {
+ get
+ {
+ return m_nOutputReportLength;
+ }
+ }
+ /// <summary>
+ /// Accessor for input report length
+ /// </summary>
+ public int InputReportLength
+ {
+ get
+ {
+ return m_nInputReportLength;
+ }
+ }
+
+ public void Read(byte[] array, int offset, int count)
+ {
+ m_oFile.Read(array, offset, count);
+ }
+
+ public void Write(byte[] array, int offset, int count)
+ {
+ m_oFile.Write(array, offset, count);
+ }
+
+ #endregion
+ }
+}
diff --git a/iButtonLib/Properties/AssemblyInfo.cs b/iButtonLib/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..823a74e
--- /dev/null
+++ b/iButtonLib/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// Управление общими сведениями о сборке осуществляется с помощью
+// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("iButtonLib")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("iButtonLib")]
+[assembly: AssemblyCopyright("Copyright © 2013")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
+// для COM-компонентов. Если требуется обратиться к типу в этой сборке через
+// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
+[assembly: ComVisible(false)]
+
+// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
+[assembly: Guid("39dabeda-d032-43bc-a9ef-80856a062441")]
+
+// Сведения о версии сборки состоят из следующих четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер построения
+// Редакция
+//
+// Можно задать все значения или принять номер построения и номер редакции по умолчанию,
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/iButtonLib/Win32Usb.cs b/iButtonLib/Win32Usb.cs
new file mode 100644
index 0000000..b55cdf0
--- /dev/null
+++ b/iButtonLib/Win32Usb.cs
@@ -0,0 +1,288 @@
+using System;
+using System.Text;
+using System.Runtime.InteropServices;
+
+namespace UsbLibrary
+{
+ /// <summary>
+ /// Class that wraps USB API calls and structures.
+ /// </summary>
+ public class Win32Usb
+ {
+ #region Structures
+ /// <summary>
+ /// An overlapped structure used for overlapped IO operations. The structure is
+ /// only used by the OS to keep state on pending operations. You don't need to fill anything in if you
+ /// unless you want a Windows event to fire when the operation is complete.
+ /// </summary>
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ protected struct Overlapped
+ {
+ public uint Internal;
+ public uint InternalHigh;
+ public uint Offset;
+ public uint OffsetHigh;
+ public IntPtr Event;
+ }
+ /// <summary>
+ /// Provides details about a single USB device
+ /// </summary>
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ protected struct DeviceInterfaceData
+ {
+ public int Size;
+ public Guid InterfaceClassGuid;
+ public int Flags;
+ public int Reserved;
+ }
+ /// <summary>
+ /// Provides the capabilities of a HID device
+ /// </summary>
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ protected struct HidCaps
+ {
+ public short Usage;
+ public short UsagePage;
+ public short InputReportByteLength;
+ public short OutputReportByteLength;
+ public short FeatureReportByteLength;
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)]
+ public short[] Reserved;
+ public short NumberLinkCollectionNodes;
+ public short NumberInputButtonCaps;
+ public short NumberInputValueCaps;
+ public short NumberInputDataIndices;
+ public short NumberOutputButtonCaps;
+ public short NumberOutputValueCaps;
+ public short NumberOutputDataIndices;
+ public short NumberFeatureButtonCaps;
+ public short NumberFeatureValueCaps;
+ public short NumberFeatureDataIndices;
+ }
+ /// <summary>
+ /// Access to the path for a device
+ /// </summary>
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ public struct DeviceInterfaceDetailData
+ {
+ public int Size;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
+ public string DevicePath;
+ }
+ /// <summary>
+ /// Used when registering a window to receive messages about devices added or removed from the system.
+ /// </summary>
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
+ public class DeviceBroadcastInterface
+ {
+ public int Size;
+ public int DeviceType;
+ public int Reserved;
+ public Guid ClassGuid;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
+ public string Name;
+ }
+ #endregion
+
+ #region Constants
+ /// <summary>Windows message sent when a device is inserted or removed</summary>
+ public const int WM_DEVICECHANGE = 0x0219;
+ /// <summary>WParam for above : A device was inserted</summary>
+ public const int DEVICE_ARRIVAL = 0x8000;
+ /// <summary>WParam for above : A device was removed</summary>
+ public const int DEVICE_REMOVECOMPLETE = 0x8004;
+ /// <summary>Used in SetupDiClassDevs to get devices present in the system</summary>
+ protected const int DIGCF_PRESENT = 0x02;
+ /// <summary>Used in SetupDiClassDevs to get device interface details</summary>
+ protected const int DIGCF_DEVICEINTERFACE = 0x10;
+ /// <summary>Used when registering for device insert/remove messages : specifies the type of device</summary>
+ protected const int DEVTYP_DEVICEINTERFACE = 0x05;
+ /// <summary>Used when registering for device insert/remove messages : we're giving the API call a window handle</summary>
+ protected const int DEVICE_NOTIFY_WINDOW_HANDLE = 0;
+ /// <summary>Purges Win32 transmit buffer by aborting the current transmission.</summary>
+ protected const uint PURGE_TXABORT = 0x01;
+ /// <summary>Purges Win32 receive buffer by aborting the current receive.</summary>
+ protected const uint PURGE_RXABORT = 0x02;
+ /// <summary>Purges Win32 transmit buffer by clearing it.</summary>
+ protected const uint PURGE_TXCLEAR = 0x04;
+ /// <summary>Purges Win32 receive buffer by clearing it.</summary>
+ protected const uint PURGE_RXCLEAR = 0x08;
+ /// <summary>CreateFile : Open file for read</summary>
+ protected const uint GENERIC_READ = 0x80000000;
+ /// <summary>CreateFile : Open file for write</summary>
+ protected const uint GENERIC_WRITE = 0x40000000;
+ /// <summary>CreateFile : file share for write</summary>
+ protected const uint FILE_SHARE_WRITE = 0x2;
+ /// <summary>CreateFile : file share for read</summary>
+ protected const uint FILE_SHARE_READ = 0x1;
+ /// <summary>CreateFile : Open handle for overlapped operations</summary>
+ protected const uint FILE_FLAG_OVERLAPPED = 0x40000000;
+ /// <summary>CreateFile : Resource to be "created" must exist</summary>
+ protected const uint OPEN_EXISTING = 3;
+ /// <summary>CreateFile : Resource will be "created" or existing will be used</summary>
+ protected const uint OPEN_ALWAYS = 4;
+ /// <summary>ReadFile/WriteFile : Overlapped operation is incomplete.</summary>
+ protected const uint ERROR_IO_PENDING = 997;
+ /// <summary>Infinite timeout</summary>
+ protected const uint INFINITE = 0xFFFFFFFF;
+ /// <summary>Simple representation of a null handle : a closed stream will get this handle. Note it is public for comparison by higher level classes.</summary>
+ public static IntPtr NullHandle = IntPtr.Zero;
+ /// <summary>Simple representation of the handle returned when CreateFile fails.</summary>
+ protected static IntPtr InvalidHandleValue = new IntPtr(-1);
+ #endregion
+
+ #region P/Invoke
+ /// <summary>
+ /// Gets the GUID that Windows uses to represent HID class devices
+ /// </summary>
+ /// <param name="gHid">An out parameter to take the Guid</param>
+ [DllImport("hid.dll", SetLastError = true)] protected static extern void HidD_GetHidGuid(out Guid gHid);
+ /// <summary>
+ /// Allocates an InfoSet memory block within Windows that contains details of devices.
+ /// </summary>
+ /// <param name="gClass">Class guid (e.g. HID guid)</param>
+ /// <param name="strEnumerator">Not used</param>
+ /// <param name="hParent">Not used</param>
+ /// <param name="nFlags">Type of device details required (DIGCF_ constants)</param>
+ /// <returns>A reference to the InfoSet</returns>
+ [DllImport("setupapi.dll", SetLastError = true)] protected static extern IntPtr SetupDiGetClassDevs(ref Guid gClass, [MarshalAs(UnmanagedType.LPStr)] string strEnumerator, IntPtr hParent, uint nFlags);
+ /// <summary>
+ /// Frees InfoSet allocated in call to above.
+ /// </summary>
+ /// <param name="lpInfoSet">Reference to InfoSet</param>
+ /// <returns>true if successful</returns>
+ [DllImport("setupapi.dll", SetLastError = true)] protected static extern int SetupDiDestroyDeviceInfoList(IntPtr lpInfoSet);
+ /// <summary>
+ /// Gets the DeviceInterfaceData for a device from an InfoSet.
+ /// </summary>
+ /// <param name="lpDeviceInfoSet">InfoSet to access</param>
+ /// <param name="nDeviceInfoData">Not used</param>
+ /// <param name="gClass">Device class guid</param>
+ /// <param name="nIndex">Index into InfoSet for device</param>
+ /// <param name="oInterfaceData">DeviceInterfaceData to fill with data</param>
+ /// <returns>True if successful, false if not (e.g. when index is passed end of InfoSet)</returns>
+ [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, uint nDeviceInfoData, ref Guid gClass, uint nIndex, ref DeviceInterfaceData oInterfaceData);
+ /// <summary>
+ /// SetupDiGetDeviceInterfaceDetail
+ /// Gets the interface detail from a DeviceInterfaceData. This is pretty much the device path.
+ /// You call this twice, once to get the size of the struct you need to send (nDeviceInterfaceDetailDataSize=0)
+ /// and once again when you've allocated the required space.
+ /// </summary>
+ /// <param name="lpDeviceInfoSet">InfoSet to access</param>
+ /// <param name="oInterfaceData">DeviceInterfaceData to use</param>
+ /// <param name="lpDeviceInterfaceDetailData">DeviceInterfaceDetailData to fill with data</param>
+ /// <param name="nDeviceInterfaceDetailDataSize">The size of the above</param>
+ /// <param name="nRequiredSize">The required size of the above when above is set as zero</param>
+ /// <param name="lpDeviceInfoData">Not used</param>
+ /// <returns></returns>
+ [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);
+ /// <summary>
+ /// SetupDiGetDeviceInterfaceDetail
+ /// Gets the interface detail from a DeviceInterfaceData. This is pretty much the device path.
+ /// You call this twice, once to get the size of the struct you need to send (nDeviceInterfaceDetailDataSize=0)
+ /// and once again when you've allocated the required space.
+ /// </summary>
+ /// <param name="lpDeviceInfoSet">InfoSet to access</param>
+ /// <param name="oInterfaceData">DeviceInterfaceData to use</param>
+ /// <param name="oDetailData">DeviceInterfaceDetailData to fill with data</param>
+ /// <param name="nDeviceInterfaceDetailDataSize">The size of the above</param>
+ /// <param name="nRequiredSize">The required size of the above when above is set as zero</param>
+ /// <param name="lpDeviceInfoData">Not used</param>
+ /// <returns></returns>
+ [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, ref DeviceInterfaceDetailData oDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);
+ /// <summary>
+ /// Registers a window for device insert/remove messages
+ /// </summary>
+ /// <param name="hwnd">Handle to the window that will receive the messages</param>
+ /// <param name="oInterface">DeviceBroadcastInterrface structure</param>
+ /// <param name="nFlags">set to DEVICE_NOTIFY_WINDOW_HANDLE</param>
+ /// <returns>A handle used when unregistering</returns>
+ [DllImport("user32.dll", SetLastError = true)] protected static extern IntPtr RegisterDeviceNotification(IntPtr hwnd, DeviceBroadcastInterface oInterface, uint nFlags);
+ /// <summary>
+ /// Unregister from above.
+ /// </summary>
+ /// <param name="hHandle">Handle returned in call to RegisterDeviceNotification</param>
+ /// <returns>True if success</returns>
+ [DllImport("user32.dll", SetLastError = true)] protected static extern bool UnregisterDeviceNotification(IntPtr hHandle);
+ /// <summary>
+ /// Gets details from an open device. Reserves a block of memory which must be freed.
+ /// </summary>
+ /// <param name="hFile">Device file handle</param>
+ /// <param name="lpData">Reference to the preparsed data block</param>
+ /// <returns></returns>
+ [DllImport("hid.dll", SetLastError = true)] protected static extern bool HidD_GetPreparsedData(IntPtr hFile, out IntPtr lpData);
+ /// <summary>
+ /// Frees the memory block reserved above.
+ /// </summary>
+ /// <param name="pData">Reference to preparsed data returned in call to GetPreparsedData</param>
+ /// <returns></returns>
+ [DllImport("hid.dll", SetLastError = true)] protected static extern bool HidD_FreePreparsedData(ref IntPtr pData);
+ /// <summary>
+ /// Gets a device's capabilities from the preparsed data.
+ /// </summary>
+ /// <param name="lpData">Preparsed data reference</param>
+ /// <param name="oCaps">HidCaps structure to receive the capabilities</param>
+ /// <returns>True if successful</returns>
+ [DllImport("hid.dll", SetLastError = true)] protected static extern int HidP_GetCaps(IntPtr lpData, out HidCaps oCaps);
+ /// <summary>
+ /// Creates/opens a file, serial port, USB device... etc
+ /// </summary>
+ /// <param name="strName">Path to object to open</param>
+ /// <param name="nAccess">Access mode. e.g. Read, write</param>
+ /// <param name="nShareMode">Sharing mode</param>
+ /// <param name="lpSecurity">Security details (can be null)</param>
+ /// <param name="nCreationFlags">Specifies if the file is created or opened</param>
+ /// <param name="nAttributes">Any extra attributes? e.g. open overlapped</param>
+ /// <param name="lpTemplate">Not used</param>
+ /// <returns></returns>
+ [DllImport("kernel32.dll", SetLastError = true)] protected static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)] string strName, uint nAccess, uint nShareMode, IntPtr lpSecurity, uint nCreationFlags, uint nAttributes, IntPtr lpTemplate);
+ /// <summary>
+ /// Closes a window handle. File handles, event handles, mutex handles... etc
+ /// </summary>
+ /// <param name="hFile">Handle to close</param>
+ /// <returns>True if successful.</returns>
+ [DllImport("kernel32.dll", SetLastError = true)] protected static extern int CloseHandle(IntPtr hFile);
+ #endregion
+
+ #region Public methods
+ /// <summary>
+ /// Registers a window to receive windows messages when a device is inserted/removed. Need to call this
+ /// from a form when its handle has been created, not in the form constructor. Use form's OnHandleCreated override.
+ /// </summary>
+ /// <param name="hWnd">Handle to window that will receive messages</param>
+ /// <param name="gClass">Class of devices to get messages for</param>
+ /// <returns>A handle used when unregistering</returns>
+ public static IntPtr RegisterForUsbEvents(IntPtr hWnd, Guid gClass)
+ {
+ DeviceBroadcastInterface oInterfaceIn = new DeviceBroadcastInterface();
+ oInterfaceIn.Size = Marshal.SizeOf(oInterfaceIn);
+ oInterfaceIn.ClassGuid = gClass;
+ oInterfaceIn.DeviceType = DEVTYP_DEVICEINTERFACE;
+ oInterfaceIn.Reserved = 0;
+ return RegisterDeviceNotification(hWnd, oInterfaceIn, DEVICE_NOTIFY_WINDOW_HANDLE);
+ }
+ /// <summary>
+ /// Unregisters notifications. Can be used in form dispose
+ /// </summary>
+ /// <param name="hHandle">Handle returned from RegisterForUSBEvents</param>
+ /// <returns>True if successful</returns>
+ public static bool UnregisterForUsbEvents(IntPtr hHandle)
+ {
+ return UnregisterDeviceNotification(hHandle);
+ }
+ /// <summary>
+ /// Helper to get the HID guid.
+ /// </summary>
+ public static Guid HIDGuid
+ {
+ get
+ {
+ Guid gHid;
+ HidD_GetHidGuid(out gHid);
+ return gHid;
+ //return new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); //gHid;
+ }
+ }
+ #endregion
+ }
+}
diff --git a/iButtonLib/iButtonConnection.cs b/iButtonLib/iButtonConnection.cs
new file mode 100644
index 0000000..ca6aa2e
--- /dev/null
+++ b/iButtonLib/iButtonConnection.cs
@@ -0,0 +1,147 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Cluster.iButtonLib
+{
+ public class iButtonConnection
+ {
+ public string Port { get; set; }
+
+ public iButtonConnection(string port)
+ {
+ Port = port;
+ }
+
+ private SerialPort OpenPort()
+ {
+ SerialPort sPort;
+ sPort = new SerialPort();
+ sPort.PortName = Port;
+ sPort.WriteTimeout = 500; sPort.ReadTimeout = 3000;
+ sPort.BaudRate = 19200;
+ sPort.Parity = Parity.None;
+ sPort.DataBits = 8;
+ sPort.StopBits = StopBits.One;
+ sPort.Handshake = Handshake.None;
+ sPort.DtrEnable = false;
+ sPort.RtsEnable = false;
+ sPort.NewLine = System.Environment.NewLine;
+ sPort.Open();
+ return sPort;
+ }
+
+ public bool Test()
+ {
+ bool result = false;
+ SerialPort port = null;
+ try
+ {
+ port = OpenPort();
+ port.Write("\r\nname\r\n");
+ while (true)
+ {
+ var line = port.ReadLine().Trim();
+ if (line.Contains("iButton"))
+ {
+ result = true;
+ }
+ }
+ }
+ catch { }
+ finally
+ {
+ if (port != null)
+ port.Close();
+ }
+ return result;
+ }
+
+ public iButtonKey[] ReadKeys()
+ {
+ var port = OpenPort();
+ try
+ {
+ var result = new List<iButtonKey>();
+ port.Write("\r\nread\r\n");
+ int keyCount = 1;
+ do
+ {
+ var line = port.ReadLine().Trim();
+ if (line.StartsWith("Count: "))
+ {
+ keyCount = byte.Parse(line.Substring(7), NumberStyles.AllowHexSpecifier);
+ }
+ else if (line.StartsWith("Key: "))
+ {
+ string keyLine = line.Substring(8);
+ result.Add(new iButtonKey(keyLine));
+ }
+ } while (result.Count < keyCount);
+ return result.ToArray();
+ }
+ finally
+ {
+ port.Close();
+ }
+ }
+
+ public void Erase()
+ {
+ var port = OpenPort();
+ try
+ {
+ port.Write("\r\nerase\r\n");
+ while (true)
+ {
+ var line = port.ReadLine().Trim();
+ if (line == "Done.") return;
+ }
+ }
+ finally
+ {
+ port.Close();
+ }
+ }
+
+ public void Write(iButtonKey key)
+ {
+ var port = OpenPort();
+ try
+ {
+ port.Write("\r\nwrite " + key.ToString() + "\r\n");
+ while (true)
+ {
+ var line = port.ReadLine().Trim();
+ if (line == "Done.") return;
+ }
+ }
+ finally
+ {
+ port.Close();
+ }
+ }
+
+ public void Reboot()
+ {
+ var port = OpenPort();
+ try
+ {
+ port.Write("\r\nreboot\r\n");
+ while (true)
+ {
+ var line = port.ReadLine().Trim();
+ if (line == "OK.") return;
+ }
+ }
+ finally
+ {
+ port.Close();
+ }
+ }
+ }
+}
diff --git a/iButtonLib/iButtonConnectionUsb.cs b/iButtonLib/iButtonConnectionUsb.cs
new file mode 100644
index 0000000..578d6d3
--- /dev/null
+++ b/iButtonLib/iButtonConnectionUsb.cs
@@ -0,0 +1,100 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO.Ports;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading.Tasks;
+using UsbLibrary;
+
+namespace Cluster.iButtonLib
+{
+ public class iButtonConnectionUsb
+ {
+ const int VID = 0x0C16;
+ const int PID = 0xDF05;
+
+ public iButtonConnectionUsb()
+ {
+ }
+
+ private HIDDevice OpenDevice()
+ {
+ return HIDDevice.FindDevice(VID, PID);
+ }
+
+ public bool IsPresent()
+ {
+ var device = OpenDevice();
+ var present = device != null;
+ if (present)
+ device.Dispose();
+ return present;
+ }
+
+ public iButtonKey[] ReadKeys()
+ {
+ var device = OpenDevice();
+ byte[] buffer = new byte[9];
+ try
+ {
+ var result = new List<iButtonKey>();
+ int keyCount = 0;
+ bool initPacket;
+ do
+ {
+ initPacket = true;
+ device.Read(buffer, 0, 9);
+ for (int i = 2; i < 8; i++)
+ {
+ if (buffer[i] != 0xFF) initPacket = false;
+ }
+ } while (!initPacket) ;
+ keyCount = buffer[1];
+ for (int key = 0; key < keyCount; key++)
+ {
+ device.Read(buffer, 0, 9);
+ result.Add(new iButtonKey(buffer, 1));
+ }
+ return result.ToArray();
+ }
+ finally
+ {
+ device.Dispose();
+ }
+ }
+
+ public void Erase()
+ {
+ var device = OpenDevice();
+ try
+ {
+ byte[] buffer = new byte[9] { 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
+ device.Write(buffer, 0, 9);
+ }
+ finally
+ {
+ device.Dispose();
+ }
+ }
+
+ public void Write(iButtonKey key)
+ {
+ var device = OpenDevice();
+ try
+ {
+ byte[] buffer = new byte[9];
+ buffer[0] = 0;
+ var keyBuffer = key.ToArray();
+ for (int i = 1; i <= 8; i++)
+ buffer[i] = keyBuffer[i - 1];
+ device.Write(buffer, 0, 9);
+ }
+ finally
+ {
+ device.Dispose();
+ }
+ }
+ }
+}
diff --git a/iButtonLib/iButtonKey.cs b/iButtonLib/iButtonKey.cs
new file mode 100644
index 0000000..b28656c
--- /dev/null
+++ b/iButtonLib/iButtonKey.cs
@@ -0,0 +1,92 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Cluster.iButtonLib
+{
+ public class iButtonKey
+ {
+ public byte Type { get; private set; }
+ public string Key { get; private set; }
+ public byte CRC { get; private set; }
+ //public string Raw { get; private set; }
+
+ public iButtonKey(string data)
+ {
+ Type = byte.Parse(data.Substring(0, 2), NumberStyles.AllowHexSpecifier);
+ if (Type == 0xFF)
+ {
+ Key = data.Substring(2, 2) + "-" + data.Substring(4, 2);
+ CRC = 0;
+ }
+ else if (Type == 0xFE)
+ {
+ Key = data.Substring(2, 2) + "-" + data.Substring(4, 2) + "-" + data.Substring(6, 2) + "-" + data.Substring(8, 2);
+ CRC = 0;
+ }
+ else
+ {
+ Key = data.Substring(12, 2) + "-" + data.Substring(10, 2) + "-" + data.Substring(8, 2) +
+ "-" + data.Substring(6, 2) + "-" + data.Substring(4, 2) + "-" + data.Substring(2, 2);
+ CRC = byte.Parse(data.Substring(14, 2), NumberStyles.AllowHexSpecifier);
+ }
+ }
+ public iButtonKey(byte[] data, int offset)
+ {
+ Type = data[offset];
+ if (Type == 0xFF)
+ {
+ Key = string.Format("{0:X2}{1:X2}", data[1 + offset], data[2 + offset]);
+ CRC = 0;
+ }
+ else if (Type == 0xFE)
+ {
+ Key = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}", data[1 + offset], data[2 + offset] + data[3 + offset] + data[4 + offset]);
+ CRC = 0;
+ }
+ else
+ {
+ Key = string.Format("{5:X2}-{4:X2}-{3:X2}-{2:X2}-{1:X2}-{0:X2}", data[1 + offset], data[2 + offset], data[3 + offset],
+ data[4 + offset], data[5 + offset], data[6 + offset]);
+ CRC = data[7 + offset];
+ }
+ }
+ public iButtonKey(byte type, string key, byte crc)
+ {
+ Type = type;
+ Key = key;
+ CRC = crc;
+ }
+ public override string ToString()
+ {
+ var key = Key.Replace("-", "");
+ if (Type == 0xFF)
+ {
+ return string.Format("{0:X2}{1}", Type, key);
+ }
+ if (Type == 0xFE)
+ {
+ return string.Format("{0:X2}{1}{2}{3}{4}", Type, key.Substring(0, 2), key.Substring(2, 2), key.Substring(4, 2), key.Substring(6, 2));
+ }
+ else
+ {
+ return string.Format("{0:X2}{6}{5}{4}{3}{2}{1}{7:X2}", Type, key.Substring(0, 2), key.Substring(2, 2), key.Substring(4, 2), key.Substring(6, 2), key.Substring(8, 2), key.Substring(10, 2), CRC);
+ }
+ }
+ public byte[] ToArray()
+ {
+ byte[] result = new byte[8];
+ var str = ToString().Replace("-", "");
+ for (int i = 0; i < 8; i++)
+ {
+ if (i * 2 <= str.Length - 2)
+ result[i] = byte.Parse(str.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier);
+ else result[i] = 0;
+ }
+ return result;
+ }
+ }
+}
diff --git a/iButtonLib/iButtonLib.csproj b/iButtonLib/iButtonLib.csproj
new file mode 100644
index 0000000..9231618
--- /dev/null
+++ b/iButtonLib/iButtonLib.csproj
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProjectGuid>{152746D8-F182-40FC-A4A3-C69AE584DDD2}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Cluster.iButtonLib</RootNamespace>
+ <AssemblyName>iButtonLib</AssemblyName>
+ <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
+ <DebugSymbols>true</DebugSymbols>
+ <OutputPath>bin\x86\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <DebugType>full</DebugType>
+ <PlatformTarget>x86</PlatformTarget>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
+ <OutputPath>bin\x86\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <Optimize>true</Optimize>
+ <DebugType>pdbonly</DebugType>
+ <PlatformTarget>x86</PlatformTarget>
+ <ErrorReport>prompt</ErrorReport>
+ <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Xml.Linq" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="HIDDevice.cs" />
+ <Compile Include="iButtonConnection.cs" />
+ <Compile Include="iButtonKey.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="iButtonConnectionUsb.cs" />
+ <Compile Include="Win32Usb.cs" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project> \ No newline at end of file