Commit cdddd8f0 by luotx

0

parents

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27703.2035
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JmpDehumidifier", "JmpDehumidifier\JmpDehumidifier.csproj", "{07C4B9DB-3E1C-48D6-A47E-631D658BAC04}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JmpDehumidifierLib", "JmpDehumidifierLib\JmpDehumidifierLib.csproj", "{1CBDFA1B-8309-458A-9F44-3B741D022A7F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{07C4B9DB-3E1C-48D6-A47E-631D658BAC04}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{07C4B9DB-3E1C-48D6-A47E-631D658BAC04}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07C4B9DB-3E1C-48D6-A47E-631D658BAC04}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07C4B9DB-3E1C-48D6-A47E-631D658BAC04}.Release|Any CPU.Build.0 = Release|Any CPU
{1CBDFA1B-8309-458A-9F44-3B741D022A7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1CBDFA1B-8309-458A-9F44-3B741D022A7F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1CBDFA1B-8309-458A-9F44-3B741D022A7F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1CBDFA1B-8309-458A-9F44-3B741D022A7F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {09041FEB-4723-43E2-B95D-BB6C31D43082}
EndGlobalSection
EndGlobal
namespace JmpDehumidifier
{
partial class Demo
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.tb_Temp = new System.Windows.Forms.TextBox();
this.tb_Humid = new System.Windows.Forms.TextBox();
this.tb_SetHumid = new System.Windows.Forms.TextBox();
this.btn_OpenClose = new System.Windows.Forms.Button();
this.btn_SetHumid = new System.Windows.Forms.Button();
this.tb_ErrorCode = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 25);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 12);
this.label1.TabIndex = 0;
this.label1.Text = "室内温度";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 12);
this.label2.TabIndex = 1;
this.label2.Text = "室内湿度";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 104);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(53, 12);
this.label3.TabIndex = 2;
this.label3.Text = "目标湿度";
//
// tb_Temp
//
this.tb_Temp.Location = new System.Drawing.Point(82, 22);
this.tb_Temp.Name = "tb_Temp";
this.tb_Temp.Size = new System.Drawing.Size(100, 21);
this.tb_Temp.TabIndex = 3;
this.tb_Temp.Text = "100";
//
// tb_Humid
//
this.tb_Humid.Location = new System.Drawing.Point(82, 61);
this.tb_Humid.Name = "tb_Humid";
this.tb_Humid.Size = new System.Drawing.Size(100, 21);
this.tb_Humid.TabIndex = 4;
this.tb_Humid.Text = "100";
//
// tb_SetHumid
//
this.tb_SetHumid.Location = new System.Drawing.Point(82, 101);
this.tb_SetHumid.Name = "tb_SetHumid";
this.tb_SetHumid.Size = new System.Drawing.Size(100, 21);
this.tb_SetHumid.TabIndex = 5;
this.tb_SetHumid.Text = "100";
//
// btn_OpenClose
//
this.btn_OpenClose.Location = new System.Drawing.Point(233, 22);
this.btn_OpenClose.Name = "btn_OpenClose";
this.btn_OpenClose.Size = new System.Drawing.Size(73, 23);
this.btn_OpenClose.TabIndex = 6;
this.btn_OpenClose.Text = "Open";
this.btn_OpenClose.UseVisualStyleBackColor = true;
this.btn_OpenClose.Click += new System.EventHandler(this.btn_OpenClose_Click);
//
// btn_SetHumid
//
this.btn_SetHumid.Location = new System.Drawing.Point(233, 99);
this.btn_SetHumid.Name = "btn_SetHumid";
this.btn_SetHumid.Size = new System.Drawing.Size(73, 23);
this.btn_SetHumid.TabIndex = 7;
this.btn_SetHumid.Text = "Set";
this.btn_SetHumid.UseVisualStyleBackColor = true;
this.btn_SetHumid.Click += new System.EventHandler(this.btn_SetHumid_Click);
//
// tb_ErrorCode
//
this.tb_ErrorCode.Location = new System.Drawing.Point(82, 137);
this.tb_ErrorCode.Name = "tb_ErrorCode";
this.tb_ErrorCode.Size = new System.Drawing.Size(100, 21);
this.tb_ErrorCode.TabIndex = 9;
this.tb_ErrorCode.Text = "0";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(12, 140);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(41, 12);
this.label4.TabIndex = 8;
this.label4.Text = "错误码";
//
// Demo
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(334, 170);
this.Controls.Add(this.tb_ErrorCode);
this.Controls.Add(this.label4);
this.Controls.Add(this.btn_SetHumid);
this.Controls.Add(this.btn_OpenClose);
this.Controls.Add(this.tb_SetHumid);
this.Controls.Add(this.tb_Humid);
this.Controls.Add(this.tb_Temp);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "Demo";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "除湿机DEMO";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox tb_Temp;
private System.Windows.Forms.TextBox tb_Humid;
private System.Windows.Forms.TextBox tb_SetHumid;
private System.Windows.Forms.Button btn_OpenClose;
private System.Windows.Forms.Button btn_SetHumid;
private System.Windows.Forms.TextBox tb_ErrorCode;
private System.Windows.Forms.Label label4;
}
}
using JmpDehumidifierLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace JmpDehumidifier
{
public partial class Demo : Form
{
private Dehumidifier dev = null;
public Demo()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dev = new Dehumidifier(Properties.Settings.Default.IP,Properties.Settings.Default.port);
if(dev.Open())
{
dev.OnStatusChanged += new Dehumidifier.StatusChanged(OnStatusChanged);
}
}
private void btn_SetHumid_Click(object sender, EventArgs e)
{
if (dev.SetHumid(Convert.ToByte(tb_SetHumid.Text)))
{
MessageBox.Show("成功!");
}
else
{
MessageBox.Show("失败!");
}
}
private void btn_OpenClose_Click(object sender, EventArgs e)
{
if (dev.OpenMachine(btn_OpenClose.Text == "Open"))
{
MessageBox.Show("成功!");
}
else
{
MessageBox.Show("失败!");
}
if(btn_OpenClose.Text == "Open")
{
btn_OpenClose.Text = "Close";
}
else
{
btn_OpenClose.Text = "Open";
}
}
public delegate void StatusChangedDeleg(MachineStatus args);
private void OnStatusChanged(MachineStatus args)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new StatusChangedDeleg(OnStatusChanged), new object[] { args });
return;
}
tb_Temp.Text = args.Temp.ToString();
tb_Humid.Text = args.Humid.ToString();
tb_ErrorCode.Text = args.ErrorCode.ToString();
tb_SetHumid.Text = args.SetHumid.ToString();
if(args.IsWorking)
{
btn_OpenClose.Text = "Close";
}
else
{
btn_OpenClose.Text = "Open";
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{07C4B9DB-3E1C-48D6-A47E-631D658BAC04}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>JmpDehumidifier</RootNamespace>
<AssemblyName>JmpDehumidifier</AssemblyName>
<TargetFrameworkVersion>v4.0</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>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</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="Demo.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Demo.Designer.cs">
<DependentUpon>Demo.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Demo.resx">
<DependentUpon>Demo.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>
</Compile>
<None Include="app.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JmpDehumidifierLib\JmpDehumidifierLib.csproj">
<Project>{1cbdfa1b-8309-458a-9f44-3b741d022a7f}</Project>
<Name>JmpDehumidifierLib</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace JmpDehumidifier
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Demo());
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JmpDehumidifier")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JmpDehumidifier")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("07c4b9db-3e1c-48d6-a47e-631d658bac04")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace JmpDehumidifier.Properties
{
/// <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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JmpDehumidifier.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;
}
}
}
}
<?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
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace JmpDehumidifier.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.7.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("172.16.10.66")]
public string IP {
get {
return ((string)(this["IP"]));
}
set {
this["IP"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("8234")]
public int port {
get {
return ((int)(this["port"]));
}
set {
this["port"] = value;
}
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="JmpDehumidifier.Properties" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="IP" Type="System.String" Scope="User">
<Value Profile="(Default)">172.16.10.66</Value>
</Setting>
<Setting Name="port" Type="System.Int32" Scope="User">
<Value Profile="(Default)">8234</Value>
</Setting>
</Settings>
</SettingsFile>
\ No newline at end of file
<?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="JmpDehumidifier.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<JmpDehumidifier.Properties.Settings>
<setting name="IP" serializeAs="String">
<value>172.16.10.66</value>
</setting>
<setting name="port" serializeAs="String">
<value>8234</value>
</setting>
</JmpDehumidifier.Properties.Settings>
</userSettings>
</configuration>
\ No newline at end of file
<?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="JmpDehumidifier.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<JmpDehumidifier.Properties.Settings>
<setting name="IP" serializeAs="String">
<value>172.16.10.66</value>
</setting>
<setting name="port" serializeAs="String">
<value>8234</value>
</setting>
</JmpDehumidifier.Properties.Settings>
</userSettings>
</configuration>
\ No newline at end of file
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.0", FrameworkDisplayName = ".NET Framework 4")]
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\bin\Debug\JmpDehumidifier.exe
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\bin\Debug\JmpDehumidifier.pdb
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\bin\Debug\JmpDehumidifierLib.dll
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\bin\Debug\JmpDehumidifierLib.pdb
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\obj\Debug\JmpDehumidifier.Demo.resources
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\obj\Debug\JmpDehumidifier.Properties.Resources.resources
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\obj\Debug\JmpDehumidifier.csproj.GenerateResource.cache
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\obj\Debug\JmpDehumidifier.csproj.CoreCompileInputs.cache
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\obj\Debug\JmpDehumidifier.csproj.CopyComplete
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\obj\Debug\JmpDehumidifier.exe
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\obj\Debug\JmpDehumidifier.pdb
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\bin\Debug\JmpDehumidifier.exe.config
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifier\obj\Debug\JmpDehumidifier.csproj.AssemblyReference.cache
using System;
using System.Text;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace JmpDehumidifierLib
{
public class Common
{
public Common() { }
#region Convert
public static byte[] ToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
{
hexString = hexString + " ";
}
byte[] buffer = new byte[hexString.Length / 2];
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 0x10);
}
return buffer;
}
public static string ToHexString(byte[] bytes)
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
}
/// <summary>
/// 数组大小端转换
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static byte[] ReserveBytes(byte[] bytes, UInt16 len)
{
byte[] ret = new byte[len];
for(int i =0; i < len; i++)
{
ret[len - i - 1] = bytes[i];
}
return ret;
}
/// <summary>
/// 数组转字符串
/// </summary>
/// <param name="bytes"></param>
/// <param name="offset"></param>
/// <param name="lenth"></param>
/// <returns></returns>
public static string ToHexString(byte[] bytes, int offset, int lenth)
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();
for (int i = offset; i < lenth + offset; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
}
internal static bool ValidateHex_uint(string input, out uint value)
{
if (!uint.TryParse(input, NumberStyles.AllowHexSpecifier, null, out value))
{
return false;
}
return true;
}
internal static bool ValidateHex_ushort(string input, out ushort value)
{
if (!ushort.TryParse(input, NumberStyles.AllowHexSpecifier, (IFormatProvider)null, out value))
{
return false;
}
return true;
}
/// <summary>
/// 是否为十进制字符串
/// </summary>
/// <param name="strIn"></param>
/// <returns></returns>
internal static bool IsInteger(string strIn)
{
bool rtn = true;
if (strIn != "")
{
foreach (char ch in strIn)
{
if (Char.IsNumber(ch))
{
continue;
}
else
{
rtn = false;
}
}
}
else
{
rtn = false;
}
return rtn;
}
/// <summary>
/// 是否为16进制字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsHex(string str)
{
const string pattern = @"[A-Fa-f0-9]+$";
return System.Text.RegularExpressions.Regex.IsMatch(str, pattern);
}
#endregion
/// <summary>
/// 验证是否为数字
/// </summary>
/// <param name="number">要验证的数字</param>
public static bool IsNumber(string number)
{
try
{
//如果为空,认为验证不合格
if (number == null || number == string.Empty)
{
return false;
}
//清除要验证字符串中的空格
number = number.Trim();
//模式字符串
string pattern = @"^(-)?[0-9]+[0-9]*[.]?[0-9]*$";
//验证
return Regex.IsMatch(number, pattern, RegexOptions.IgnoreCase);
}
catch (System.Exception)
{
return false;
}
}
/// <summary>
/// 获取枚举的描述
/// </summary>
/// <param name="enumValue">枚举变量</param>
/// <returns>描述</returns>
public static string GetEnumDescription(Enum enumValue)
{
string str = enumValue.ToString();
System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);
object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (objs == null || objs.Length == 0) return str;
System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
return da.Description;
}
/// <summary>
/// 返回两个时间差(毫秒数)
/// </summary>
/// <param name="DateTime1"></param>
/// <param name="DateTime2"></param>
/// <returns></returns>
public static double DateDiffMillSecond(DateTime DateTime1, DateTime DateTime2)
{
return new TimeSpan(DateTime1.Ticks).Subtract(new TimeSpan(DateTime2.Ticks)).Duration().TotalMilliseconds;
}
#region 转换
/// <summary>
/// byte to ushort
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static UInt64 BytesToUInt64(byte[] bytes, byte pos)
{
UInt64 rtn = 0;
if (bytes != null)
{
for (int i = pos; i < pos + 8; i++)
{
rtn = rtn << 8 | bytes[i];
}
return rtn;
}
return rtn;
}
/// <summary>
/// byte to int
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static Int32 BytesToInt32(byte[] bytes, byte pos)
{
Int32 rtn = 0;
if (bytes != null)
{
for (int i = pos; i < pos + 4; i++)
{
rtn = rtn << 8 | bytes[i];
}
return rtn;
}
return rtn;
}
/// <summary>
/// byte to ushort
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static Int16 BytesToInt16(byte[] bytes, byte pos)
{
Int16 rtn = 0;
if (bytes != null)
{
for (int i = pos; i < pos + 2; i++)
{
rtn = (Int16)(rtn << 8 | bytes[i]);
}
}
return rtn;
}
/// <summary>
/// byte to int
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static UInt32 BytesToUInt32(byte[] bytes, byte pos)
{
UInt32 rtn = 0;
if (bytes != null)
{
for (int i = pos; i < pos + 4; i++)
{
rtn = rtn << 8 | bytes[i];
}
}
return rtn;
}
/// <summary>
/// byte to ushort
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static UInt16 BytesToUInt16(byte[] bytes, byte pos)
{
UInt16 rtn = 0;
if (bytes != null)
{
for (int i = pos; i < pos + 2; i++)
{
rtn = (UInt16)(rtn << 8 | bytes[i]);
}
}
return rtn;
}
/// <summary>
/// IP int to string
/// </summary>
/// <param name="ipInt"></param>
/// <returns></returns>
public static string IntToIp(long ipInt)
{
StringBuilder sb = new StringBuilder();
sb.Append((ipInt >> 24) & 0xFF).Append(".");
sb.Append((ipInt >> 16) & 0xFF).Append(".");
sb.Append((ipInt >> 8) & 0xFF).Append(".");
sb.Append(ipInt & 0xFF);
return sb.ToString();
}
/// <summary>
/// ip string to int
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static byte[] IpToBytes(string ip)
{
byte[] ipAddr = new byte[4] { 0, 0, 0, 0 };
char[] separator = new char[] { '.' };
string[] items = ip.Split(separator);
ipAddr[0] = Byte.Parse(items[0]);
ipAddr[1] = Byte.Parse(items[1]);
ipAddr[2] = Byte.Parse(items[2]);
ipAddr[3] = Byte.Parse(items[3]);
return ipAddr;
}
public static byte[] UInt32ToBytes(UInt32 val)
{
if(val > 0x10000)
{
byte[] rtn = new byte[4];
rtn[0] = (byte)(val >> 24);
rtn[1] = (byte)(val >> 16);
rtn[2] = (byte)(val >> 8);
rtn[3] = (byte)(val);
return rtn;
}
else
{
byte[] rtn = new byte[2];
rtn[0] = (byte)(val >> 8);
rtn[1] = (byte)(val);
return rtn;
}
}
#endregion
/// <summary>
/// 获取MD5密文
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string GetCiper(string input)
{
// Use input string to calculate MD5 hash
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
public static class TransExpV2<TIn, TOut>
{
private static readonly Func<TIn, TOut> cache = GetFunc();
public static Func<TIn, TOut> GetFunc()
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
List<MemberBinding> memberBindingList = new List<MemberBinding>();
foreach (var item in typeof(TOut).GetProperties())
{
if (!item.CanWrite)
continue;
MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
MemberBinding memberBinding = Expression.Bind(item, property);
memberBindingList.Add(memberBinding);
}
MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
return lambda.Compile();
}
public static TOut Trans(TIn tIn)
{
return cache(tIn);
}
}
}
namespace JmpDehumidifierLib
{
internal class Controller
{
internal IDevice device;
internal Controller(IDevice dev)
{
this.device = dev;
device.MsgRcvEvent +=new MessageReceivedDeleg(Device_MsgRcvEvent);
}
internal bool Open()
{
return device.Open();
}
internal bool Close()
{
return device.Close();
}
internal bool Send(byte[] command)
{
return device.Send(command);
}
/// <summary>
/// 接收并发送解析后的消息
/// </summary>
/// <param name="msg"></param>
/// <param name="len"></param>
internal void Device_MsgRcvEvent(byte[] msg)
{
OnMsgRcv(msg);
}
internal event MessageReceivedDeleg MsgRcvEvent;
internal void OnMsgRcv(byte[] msg)
{
MsgRcvEvent?.Invoke(msg);
}
}
}
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
namespace JmpDehumidifierLib
{
public class MachineStatus
{
public byte Temp = 0; // 室内温度
public byte Humid = 0; // 室内湿度
public byte SetHumid = 80; // 控制湿度
public bool IsWorking = false; // 是否正在工作
public byte ErrorCode = 0; // 1 设置失败
public string ip = "";
public int port = 0;
}
public enum CurrentCmd
{
Idle = 0,
GetWSD = 0x01, // 获取温湿度
GetWorkState = 0x02, // 获取工作状态
GetSetHumid = 0x03, // 获取设置的湿度值
OpenMachine = 0x11, // 打开或关闭设备
SetHumid = 0x12 // 设置湿度
}
public class Dehumidifier
{
private Controller controller;
#region DevDef
private bool bSending = false;
private bool isOpen = false;
private readonly byte DevId = 0;
private CurrentCmd currentCmd = CurrentCmd.Idle;
private MachineStatus Status = new MachineStatus();
private MachineStatus lastStatusHashcode = new MachineStatus();
#endregion
#region Base
public Dehumidifier(string comPort = "COM3", byte devId = 1)
{
DevId = devId;
controller = new Controller(new Serial(comPort.ToUpper()));
}
public Dehumidifier(string ip, int port, byte devId = 1)
{
if (IsIp(ip))
{
DevId = devId;
ip = ip.Trim();
Status.ip = ip;
Status.port = port;
controller = new Controller(new JpSocket(ip, port));
}
}
private bool IsIp(string ip)
{
if (string.IsNullOrEmpty(ip))
{
return false;
}
string pattern = @"^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])(\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)){3}$";
return Regex.IsMatch(ip, pattern);
}
private bool isClosed = true;
/// <summary>
/// 打开设备
/// </summary>
public bool Open()
{
//controller
isOpen = controller.Open();
if (isOpen)
{
if (controller.GetType().GetProperty("MsgRcvEvent", BindingFlags.Instance | BindingFlags.NonPublic) == null)
{
controller.MsgRcvEvent += new MessageReceivedDeleg(Controller_MsgRcvEvent);
}
if(isClosed)
{
Thread thr_Status = new Thread(CheckStatus)
{
IsBackground = true
};
thr_Status.Start();
}
isClosed = false;
return true;
}
else
{
isClosed = true;
return false;
}
}
/// <summary>
/// 关闭
/// </summary>
/// <returns></returns>
public bool Close()
{
if(controller.Close())
{
controller.MsgRcvEvent -= new MessageReceivedDeleg(Controller_MsgRcvEvent);
isOpen = false;
return true;
}
else
{
return false;
}
}
/// <summary>
/// 判断设备是否打开
/// </summary>
/// <returns></returns>
public bool IsOpen()
{
return isOpen;
}
private bool Send(byte[] data)
{
if (bSending)
{
Console.WriteLine("命令正在处理中,不接收新命令!");
return false;
}
bSending = true;
Status.ErrorCode = 1;
// 计算CRC
var crc = Crc16_ModBus(data, data.Length - 2);
data[data.Length - 1] = (byte)((crc >> 8) & 0xff);
data[data.Length - 2] = (byte)(crc & 0xff);
var rtn = controller.Send(data);
return rtn;
}
/// <summary>
/// 接收消息并处理
/// </summary>
/// <param name="msg"></param>
/// <param name="len"></param>
private void Controller_MsgRcvEvent(byte[] msg)
{
// 如果消息为空,则不处理
if (msg == null || msg.Length == 0)
{
return;
}
DealData(msg);
}
#endregion
#region App
private void CheckStatus()
{
while (isOpen)
{
GetWSD();
IsMachineWorking();
GetSetHumid();
CheckStatusChanged();
Thread.Sleep(10000);
}
}
/// <summary>
/// 获取温湿度
/// </summary>
/// <param name="args">参数</param>
/// <returns></returns>
private bool GetWSD()
{
currentCmd = CurrentCmd.GetWSD;
byte[] cmd = new byte[8];
cmd[0] = DevId;
cmd[1] = 0x04; // 读数据
cmd[2] = 0;
cmd[3] = 0x21;
cmd[4] = 0;
cmd[5] = 2; // 0x21 温度, 0X22 湿度
Send(cmd);
ReqSuccessed();
return Status.ErrorCode == 0;
}
/// <summary>
/// 设备是否开机
/// </summary>
/// <returns></returns>
private bool IsMachineWorking()
{
currentCmd = CurrentCmd.GetWorkState;
byte[] cmd = new byte[8];
cmd[0] = DevId;
cmd[1] = 0x04; // 读数据
cmd[2] = 0;
cmd[3] = 0x13;
cmd[4] = 0;
cmd[5] = 1;
Send(cmd);
ReqSuccessed();
return Status.ErrorCode == 0;
}
/// <summary>
/// 设置抽湿启动湿度
/// </summary>
/// <returns></returns>
public bool SetHumid(byte humid)
{
ReqSuccessed();
currentCmd = CurrentCmd.SetHumid;
byte[] cmd = new byte[8];
cmd[0] = DevId;
cmd[1] = 0x06; // 读数据
cmd[2] = 0;
cmd[3] = 0x14;
cmd[4] = 0;
cmd[5] = humid;
Send(cmd);
ReqSuccessed();
return Status.ErrorCode == 0;
}
public bool GetSetHumid()
{
ReqSuccessed();
currentCmd = CurrentCmd.GetSetHumid;
byte[] cmd = new byte[8];
cmd[0] = DevId;
cmd[1] = 0x04; // 读数据
cmd[2] = 0;
cmd[3] = 0x14;
cmd[4] = 0;
cmd[5] = 1;
Send(cmd);
ReqSuccessed();
return Status.ErrorCode == 0;
}
/// <summary>
/// 是否打开除湿机
/// </summary>
/// <param name="IsOpen"></param>
/// <returns></returns>
public bool OpenMachine(bool IsOpen)
{
ReqSuccessed();
currentCmd = CurrentCmd.OpenMachine;
byte[] cmd = new byte[8];
cmd[0] = DevId;
cmd[1] = 0x06; // 读数据
cmd[2] = 0;
cmd[3] = 0x13;
cmd[4] = 0;
cmd[5] = (byte)(IsOpen ? 0xFF : 0);
Send(cmd);
ReqSuccessed();
return Status.ErrorCode == 0;
}
#endregion
/// <summary>
/// 读写器发过来的数据处理
/// </summary>
/// <param name="data"></param>
/// <param name="len"></param>
private void DealData(byte[] msg)
{
try
{
// 设备号不一致
if (msg[0] != DevId)
return;
// CRC校验
var crc = Crc16_ModBus(msg, msg.Length-2);
if((msg[msg.Length-1] != ((crc >> 8) & 0xff)) || (msg[msg.Length - 2] != (crc & 0xff)))
{
return;
}
switch (msg[1])
{
case 0x04: // 读寄存器
ReadReg(msg);
break;
case 0x06: // 写寄存器
WriteReg(msg);
break;
default:
break;
}
bSending = false;
currentCmd = CurrentCmd.Idle;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void ReadReg(byte[] msg)
{
switch (currentCmd)
{
case CurrentCmd.GetWSD:
if (msg[2] == 4)
{
Status.Temp = msg[4];
Status.Humid = msg[6];
Status.ErrorCode = 0;
}
break;
case CurrentCmd.GetWorkState:
if (msg[2] == 2)
{
Status.IsWorking = (msg[4] == 0xff);
Status.ErrorCode = 0;
}
break;
case CurrentCmd.GetSetHumid:
if (msg[2] == 2)
{
Status.SetHumid = msg[4];
Status.ErrorCode = 0;
}
break;
}
}
private void WriteReg(byte[] msg)
{
Status.ErrorCode = 0;
}
#region Common
/// <summary>
/// 阻塞式接收
/// </summary>
private void ReqSuccessed()
{
int timeout = 100;
while (bSending)
{
Thread.Sleep(10);
if (timeout-- < 0)
{
bSending = false;
currentCmd = CurrentCmd.Idle;
break;
}
}
}
private void ReqSuccessed(int timeout)
{
timeout += 100;
while (bSending)
{
Thread.Sleep(10);
if (timeout-- < 0)
{
bSending = false;
currentCmd = CurrentCmd.Idle;
break;
}
}
}
#endregion
/// <summary>
/// MODBUS-CRC运算
/// </summary>
/// <param name="data"></param>
/// <param name="len">必须是偶数</param>
/// <returns></returns>
public static UInt16 Crc16_ModBus(byte[] data, int lenth)
{
ushort crc = 0xffff;
for (int i = 0; i < lenth; i++)
{
crc = (ushort)(data[i] ^ crc);
for (int j = 0; j < 8; j++)
{
if ((crc & 0x01) == 0x01)
{
crc = (ushort)(crc >> 1);
crc = (ushort)(crc ^ 0xa001);
}
else
{
crc = (ushort)(crc >> 1);
}
}
}
return crc;
}
#region Event
private void CheckStatusChanged()
{
//var currentHashcode = Status.GetHashCode();
if(!Status.Equals(lastStatusHashcode))
{
lastStatusHashcode.Humid = Status.Humid;
lastStatusHashcode.Temp = Status.Temp;
lastStatusHashcode.IsWorking = Status.IsWorking;
lastStatusHashcode.SetHumid = Status.SetHumid;
lastStatusHashcode.ErrorCode = Status.ErrorCode;
OnStatusChanged(Status);
}
}
// GPI事件
public delegate void StatusChanged(MachineStatus args);
public event StatusChanged OnStatusChanged;
#endregion
}
}
namespace JmpDehumidifierLib
{
internal interface IDevice
{
bool Open();
bool Close();
bool Send(byte[] command);
// read事件
event MessageReceivedDeleg MsgRcvEvent;
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{1CBDFA1B-8309-458A-9F44-3B741D022A7F}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>JmpDehumidifierLib</RootNamespace>
<AssemblyName>JmpDehumidifierLib</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</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>
<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="Common.cs" />
<Compile Include="Controller.cs" />
<Compile Include="InterfaceDevice.cs" />
<Compile Include="JpSocket.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Dehumidifier.cs" />
<Compile Include="Serial.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace JmpDehumidifierLib
{
internal class JpSocket : IDevice
{
private readonly string SrvIp = "127.0.0.1";
private readonly int SrvPort = 7890;
private Thread threadClient = null; // 创建用于接收服务端消息的 线程;
private Socket sockClient = null;
private bool sockClientEnable = false;
private Queue<byte[]> queMsg = new Queue<byte[]>();
public JpSocket(string ip, int port)
{
SrvIp = ip;
SrvPort = port;
}
/// <summary>
/// 关闭
/// </summary>
/// <param name="comPort"></param>
/// <returns></returns>
public bool Close()
{
try
{
// 停止接收线程
sockClientEnable = false;
// 关闭SOCKET
if (sockClient != null && sockClient.Connected)
{
sockClient.Close();
}
return true;
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
/// <summary>
/// 打开
/// </summary>
/// <param name="comPort"></param>
/// <returns></returns>
public bool Open()
{
try
{
IPAddress ip = IPAddress.Parse(SrvIp);
IPEndPoint endPoint = new IPEndPoint(ip, SrvPort);
sockClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sockClient.Connect(endPoint);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
return false;
}
if (sockClientEnable == false)
{
sockClientEnable = true;
threadClient = new Thread(RecMsg)
{
IsBackground = true
};
threadClient.Start();
Thread thr = new Thread(DealMsgs)
{
IsBackground = true
};
thr.Start();
}
return true;
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
void RecMsg()
{
while (sockClientEnable)
{
// 定义一个2M的缓存区;
byte[] arrMsgRec = new byte[4096];
// 将接受到的数据存入到输入 arrMsgRec中;
int len = -1;
try
{
len = sockClient.Receive(arrMsgRec); // 接收数据,并返回数据的长度;
if (len > 0)
{
byte[] buf = new byte[len];
Array.Copy(arrMsgRec, buf, len);
lock (queMsg)
{
queMsg.Enqueue(buf);
}
}
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
return;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return;
}
}
}
private void DealMsgs()
{
while (sockClientEnable)
{
while (queMsg.Count > 0)
{
byte[] msg = null;
lock (queMsg)
{
msg = queMsg.Dequeue();
}
OnMsgRcv(msg);
}
Thread.Sleep(10);
}
}
/// <summary>
/// Send
/// </summary>
/// <param name="command"></param>
/// <param name="len"></param>
/// <returns></returns>
public bool Send(byte[] msg)
{
try
{
if (sockClient != null && sockClient.Connected)
{
// 组包
if (msg != null && msg.Length >= 8)
{
// 发送
sockClient.Send(msg, 0, msg.Length, SocketFlags.None);
return true;
}
Console.WriteLine("发送失败!");
return false;
}
Console.WriteLine("网络未打开!");
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
public event MessageReceivedDeleg MsgRcvEvent;
public void OnMsgRcv(byte[] msg)
{
MsgRcvEvent?.Invoke(msg);
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JmpDehumidifierLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JmpDehumidifierLib")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("1cbdfa1b-8309-458a-9f44-3b741d022a7f")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Threading;
namespace JmpDehumidifierLib
{
internal delegate void MessageReceivedDeleg(byte[] msg);
internal class Serial : IDevice
{
private SerialPort port1;
private readonly string SerialName = "COM1";
private Queue<byte[]> queMsg = new Queue<byte[]>();
public Serial(string name)
{
SerialName = name;
}
/// <summary>
/// 关闭
/// </summary>
/// <param name="comPort"></param>
/// <returns></returns>
public bool Close()
{
try
{
port1.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(this.OnDataReceived);
if (port1.IsOpen == true && port1.PortName == SerialName)
{
port1.Close();
port1.Dispose();
return true;
}
else
{
port1.Dispose();
return false;
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
/// <summary>
/// 打开
/// </summary>
/// <param name="comPort"></param>
/// <returns></returns>
public bool Open()
{
try
{
// 打开前已存在,则关闭
if (port1 != null)
{
port1.Dispose();
Thread.Sleep(50);
}
// 判断串口是否存在, 如果不存在,则打开失败
if (!SerialPort.GetPortNames().Contains(SerialName))
{
Console.WriteLine("串口不存在!");
return false;
}
port1 = new SerialPort(SerialName, 9600, Parity.None, 8, StopBits.One);
port1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.OnDataReceived);
port1.Open();
if (port1.IsOpen == true)
{
port1.DiscardInBuffer();
port1.DiscardOutBuffer();
Thread thr = new Thread(DealMsgs)
{
IsBackground = true
};
thr.Start();
return true;
}
else
{
port1.Dispose();
return false;
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
/// <summary>
/// Send
/// </summary>
/// <param name="command"></param>
/// <param name="len"></param>
/// <returns></returns>
public bool Send(byte[] msg)
{
try
{
if (port1.IsOpen)
{
if (msg != null && msg.Length >= 8)
{
// 发送
port1.Write(msg, 0, msg.Length);
return true;
}
Console.WriteLine("发送失败!");
return false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return false;
}
private readonly object _lock_ = new object();
/// <summary>
/// Recerive
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
lock (_lock_)
{
var len = port1.BytesToRead;
byte[] buf = new byte[len];
port1.Read(buf, 0, len);
if (len > 0)
{
lock (queMsg)
{
queMsg.Enqueue(buf);
}
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void DealMsgs()
{
while(port1.IsOpen)
{
while(queMsg.Count > 0)
{
byte[] msg = null;
lock(queMsg)
{
msg = queMsg.Dequeue();
}
OnMsgRcv(msg);
}
Thread.Sleep(10);
}
}
public event MessageReceivedDeleg MsgRcvEvent;
public void OnMsgRcv(byte[] msg)
{
MsgRcvEvent?.Invoke(msg);
}
}
}
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.0", FrameworkDisplayName = ".NET Framework 4")]
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifierLib\bin\Debug\JmpDehumidifierLib.dll
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifierLib\bin\Debug\JmpDehumidifierLib.pdb
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifierLib\obj\Debug\JmpDehumidifierLib.csproj.CoreCompileInputs.cache
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifierLib\obj\Debug\JmpDehumidifierLib.dll
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifierLib\obj\Debug\JmpDehumidifierLib.pdb
D:\project\JP200017JYZB\JmpDehumidifier\JmpDehumidifier\JmpDehumidifierLib\obj\Debug\JmpDehumidifierLib.csproj.AssemblyReference.cache
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论