Commit 819bd750 authored by shaxuezheng's avatar shaxuezheng

修改控制定时处理

parent b5267af2
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections;
using System.Data.Common;
namespace ModbusDemo
{
//JSON转换类
public class ConvertJson
{
#region 私有方法
/// <summary>
/// 过滤特殊字符
/// </summary>
private static string String2Json(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s.ToCharArray()[i];
switch (c)
{
case '\"':
sb.Append("\\\""); break;
case '\\':
sb.Append("\\\\"); break;
case '/':
sb.Append("\\/"); break;
case '\b':
sb.Append("\\b"); break;
case '\f':
sb.Append("\\f"); break;
case '\n':
sb.Append("\\n"); break;
case '\r':
sb.Append("\\r"); break;
case '\t':
sb.Append("\\t"); break;
default:
sb.Append(c); break;
}
}
return sb.ToString();
}
/// <summary>
/// 格式化字符型、日期型、布尔型
/// </summary>
private static string StringFormat(string str, Type type)
{
if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
else if (type != typeof(string) && string.IsNullOrEmpty(str))
{
str = "\"" + str + "\"";
}
return str;
}
#endregion
#region List转换成Json
/// <summary>
/// List转换成Json
/// </summary>
public static string ListToJson<T>(IList<T> list)
{
object obj = list[0];
return ListToJson<T>(list, obj.GetType().Name);
}
/// <summary>
/// List转换成Json
/// </summary>
public static string ListToJson<T>(IList<T> list, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
Json.Append("{\"" + jsonName + "\":[");
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].GetValue(list[i], null).GetType();
Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < list.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
#endregion
#region 对象转换为Json
/// <summary>
/// 对象转换为Json
/// </summary>
/// <param name="jsonObject">对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(object jsonObject)
{
string jsonString = "{";
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = 0; i < propertyInfo.Length; i++)
{
object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
string value = string.Empty;
if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
{
value = "'" + objectValue.ToString() + "'";
}
else if (objectValue is string)
{
value = "'" + ToJson(objectValue.ToString()) + "'";
}
else if (objectValue is IEnumerable)
{
value = ToJson((IEnumerable)objectValue);
}
else
{
value = ToJson(objectValue.ToString());
}
jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "}";
}
#endregion
#region 对象集合转换Json
/// <summary>
/// 对象集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString += ToJson(item) + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "]";
}
#endregion
#region 普通集合转换Json
/// <summary>
/// 普通集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToArrayString(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString = ToJson(item.ToString()) + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "]";
}
#endregion
#region DataSet转换为Json
/// <summary>
/// DataSet转换为Json
/// </summary>
/// <param name="dataSet">DataSet对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataSet dataSet)
{
string jsonString = "{";
foreach (DataTable table in dataSet.Tables)
{
jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
}
jsonString = jsonString.TrimEnd(',');
return jsonString + "}";
}
#endregion
#region Datatable转换为Json
/// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name="table">Datatable对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < dt.Columns.Count - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}
/// <summary>
/// DataTable转换为Json
/// </summary>
public static string ToJson(DataTable dt, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;
Json.Append("{\"" + jsonName + "\":[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
Type type = dt.Rows[i][j].GetType();
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
#endregion
#region DataReader转换为Json
/// <summary>
/// DataReader转换为Json
/// </summary>
/// <param name="dataReader">DataReader对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DbDataReader dataReader)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
while (dataReader.Read())
{
jsonString.Append("{");
for (int i = 0; i < dataReader.FieldCount; i++)
{
Type type = dataReader.GetFieldType(i);
string strKey = dataReader.GetName(i);
string strValue = dataReader[i].ToString();
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (i < dataReader.FieldCount - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
dataReader.Close();
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}
#endregion
}
}
\ No newline at end of file
...@@ -6,8 +6,14 @@ using System.Threading.Tasks; ...@@ -6,8 +6,14 @@ using System.Threading.Tasks;
namespace ModbusDemo namespace ModbusDemo
{ {
class startAddress
class WTDR18X {
private ushort address;
private ushort num;
public ushort Address { get => address; set => address = value; }
public ushort Num { get => num; set => num = value; }
}
class WTDR18X
{ {
public string addr { get; set; } public string addr { get; set; }
public double d0 { get; set; } public double d0 { get; set; }
...@@ -33,7 +39,7 @@ namespace ModbusDemo ...@@ -33,7 +39,7 @@ namespace ModbusDemo
this.ts = ts; this.ts = ts;
} }
} }
class WTDR14P class WTDR14P
{ {
public string addr { get; set; } public string addr { get; set; }
public double d0 { get; set; } public double d0 { get; set; }
...@@ -51,7 +57,7 @@ namespace ModbusDemo ...@@ -51,7 +57,7 @@ namespace ModbusDemo
this.ts = ts; this.ts = ts;
} }
} }
class WTDR66C class WTDR66C
{ {
public string addr { get; set; } public string addr { get; set; }
public int d0 { get; set; } public int d0 { get; set; }
...@@ -75,4 +81,110 @@ namespace ModbusDemo ...@@ -75,4 +81,110 @@ namespace ModbusDemo
} }
} }
public class Ctrl
{
public string taskId;
public void settaskId(string taskId)
{
this.taskId = taskId;
}
public string gettaskId()
{
return taskId;
}
public List<Ss> ss { get; set; }
}
public class Op
{
public int duration;
public long startTime;
public int d0
{
get => D0;
set => D0 = value;
}
public int d1
{
get => D1;
set => D1 = value;
}
public int d2
{
get => D2;
set => D2 = value;
}
public int d3
{
get => D3;
set => D3 = value;
}
public int d4
{
get => D4;
set => D4 = value;
}
public int d5
{
get => D5;
set => D5 = value;
}
public long ts
{
get => Ts;
set => Ts = value;
}
private int D0;
private int D1;
private int D2;
private int D3;
private int D4;
private int D5;
private long Ts;
public void setDuration(int duration)
{
this.duration = duration;
}
public int getDuration()
{
return duration;
}
public void setStartTime(long startTime)
{
this.startTime = startTime;
}
public long getStartTime()
{
return startTime;
}
}
public class Ss
{
public byte addr;
public Op op;
public void setAddr(byte addr)
{
this.addr = addr;
}
public byte getAddr()
{
return addr;
}
public void setOp(Op op)
{
this.op = op;
}
public Op getOp()
{
return op;
}
}
} }
...@@ -11,6 +11,8 @@ ...@@ -11,6 +11,8 @@
<AssemblyName>WTG93UG</AssemblyName> <AssemblyName>WTG93UG</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<IsWebBootstrapper>false</IsWebBootstrapper>
<TargetFrameworkProfile />
<PublishUrl>publish\</PublishUrl> <PublishUrl>publish\</PublishUrl>
<Install>true</Install> <Install>true</Install>
<InstallFrom>Disk</InstallFrom> <InstallFrom>Disk</InstallFrom>
...@@ -23,10 +25,8 @@ ...@@ -23,10 +25,8 @@
<MapFileExtensions>true</MapFileExtensions> <MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision> <ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion> <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust> <UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled> <BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
...@@ -81,37 +81,29 @@ ...@@ -81,37 +81,29 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="414P.cs" /> <Compile Include="application\Pond.cs" />
<Compile Include="478C.cs" /> <Compile Include="Modular\414P.cs" />
<Compile Include="418X.cs" /> <Compile Include="Modular\478C.cs" />
<Compile Include="Modular\418X.cs" />
<Compile Include="Common\Modbuslib.cs" /> <Compile Include="Common\Modbuslib.cs" />
<Compile Include="ConvertJson.cs" />
<Compile Include="windows\Form1.cs"> <Compile Include="windows\Form1.cs">
<SubType>Form</SubType> <SubType>Form</SubType>
</Compile> </Compile>
<Compile Include="windows\Form1.Designer.cs"> <Compile Include="windows\Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon> <DependentUpon>Form1.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="mqttpacke.cs" /> <Compile Include="MessageFormat\mqttpacke.cs" />
<Compile Include="RData.cs" /> <Compile Include="MessageFormat\RData.cs" />
<Compile Include="UData.cs" /> <Compile Include="MessageFormat\UData.cs" />
<Compile Include="Common\ModSearch.cs" /> <Compile Include="Common\ModSearch.cs" />
<Compile Include="Common\WTModbus.cs" /> <Compile Include="Common\WTModbus.cs" />
<Compile Include="windows\frmInputValue.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="windows\frmInputValue.designer.cs">
<DependentUpon>frmInputValue.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Totxt.cs" /> <Compile Include="Common\Totxt.cs" />
<Compile Include="application\TransferPool.cs" />
<EmbeddedResource Include="windows\Form1.resx"> <EmbeddedResource Include="windows\Form1.resx">
<DependentUpon>Form1.cs</DependentUpon> <DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource> </EmbeddedResource>
<EmbeddedResource Include="windows\frmInputValue.resx">
<DependentUpon>frmInputValue.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx"> <EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator> <Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput> <LastGenOutput>Resources.Designer.cs</LastGenOutput>
......
...@@ -54,86 +54,79 @@ namespace ModbusDemo ...@@ -54,86 +54,79 @@ namespace ModbusDemo
public string[] Value(ushort[] typeData, ushort[] Inputtype) public string[] Value(ushort[] typeData, ushort[] Inputtype)
{ {
string[] Valuepass = new string[MAX_AN_CH_NUM]; string[] Valuepass = new string[MAX_AN_CH_NUM];
if (typeData != null || Inputtype != null) /********************/
{ users.UserId = 0;//通道
/********************/ users.Data = typeData[0];//数据
users.UserId = 0;//通道 users.UserCompany = Strcom[Inputtype[0]];//通道类型
users.Data = typeData[0];//数据 users.UserModel = Inputtype[0];//确定计算公式
users.UserCompany = Strcom[Inputtype[0]];//通道类型 /********************/
users.UserModel = Inputtype[0];//确定计算公式 users1.UserId = 1;//通道
/********************/ users1.Data = typeData[1];//数据
users1.UserId = 1;//通道 users1.UserCompany = Strcom[Inputtype[1]];//通道类型
users1.Data = typeData[1];//数据 users1.UserModel = Inputtype[1];//确定计算公式
users1.UserCompany = Strcom[Inputtype[1]];//通道类型 /********************/
users1.UserModel = Inputtype[1];//确定计算公式 users2.UserId = 2;//通道
/********************/ users2.Data = typeData[2];//数据
users2.UserId = 2;//通道 users2.UserCompany = Strcom[Inputtype[2]];//通道类型
users2.Data = typeData[2];//数据 users2.UserModel = Inputtype[2];//确定计算公式
users2.UserCompany = Strcom[Inputtype[2]];//通道类型 /********************/
users2.UserModel = Inputtype[2];//确定计算公式 users3.UserId = 3;//通道
/********************/ users3.Data = typeData[3];//数据
users3.UserId = 3;//通道 users3.UserCompany = Strcom[Inputtype[3]];//通道类型
users3.Data = typeData[3];//数据 users3.UserModel = Inputtype[3];//确定计算公式
users3.UserCompany = Strcom[Inputtype[3]];//通道类型 /********************/
users3.UserModel = Inputtype[3];//确定计算公式 users4.UserId = 4;//通道
/********************/ users4.Data = typeData[4];//数据
users4.UserId = 4;//通道 users4.UserCompany = Strcom[Inputtype[4]];//通道类型
users4.Data = typeData[4];//数据 users4.UserModel = Inputtype[4];//确定计算公式
users4.UserCompany = Strcom[Inputtype[4]];//通道类型 /********************/
users4.UserModel = Inputtype[4];//确定计算公式 users5.UserId = 5;//通道
/********************/ users5.Data = typeData[5];//数据
users5.UserId = 5;//通道 users5.UserCompany = Strcom[Inputtype[5]];//通道类型
users5.Data = typeData[5];//数据 users5.UserModel = Inputtype[5];//确定计算公式
users5.UserCompany = Strcom[Inputtype[5]];//通道类型 /********************/
users5.UserModel = Inputtype[5];//确定计算公式 users6.UserId = 6;//通道
/********************/ users6.Data = typeData[6];//数据
users6.UserId = 6;//通道 users6.UserCompany = Strcom[Inputtype[6]];//通道类型
users6.Data = typeData[6];//数据 users6.UserModel = Inputtype[6];//确定计算公式
users6.UserCompany = Strcom[Inputtype[6]];//通道类型 /********************/
users6.UserModel = Inputtype[6];//确定计算公式 users7.UserId = 7;//通道
/********************/ users7.Data = typeData[7];//数据
users7.UserId = 7;//通道 users7.UserCompany = Strcom[Inputtype[7]];//通道类型
users7.Data = typeData[7];//数据 users7.UserModel = Inputtype[7];//确定计算公式
users7.UserCompany = Strcom[Inputtype[7]];//通道类型
users7.UserModel = Inputtype[7];//确定计算公式
//////输入格式为:NegMin NegMax PosMin PosMax usMin usMax //////输入格式为:NegMin NegMax PosMin PosMax usMin usMax
Valuepass[0] = current(users.NegMin[users.UserModel], users.NegMax[users.UserModel], users.PosMin[users.UserModel], Valuepass[0] = current(users.NegMin[users.UserModel], users.NegMax[users.UserModel], users.PosMin[users.UserModel],
users.PosMax[users.UserModel], users.usMin[users.UserModel], users.usMax[users.UserModel], users.PosMax[users.UserModel], users.usMin[users.UserModel], users.usMax[users.UserModel],
users.Data); //处理函数 users.Data); //处理函数
Valuepass[1] = current(users1.NegMin[users1.UserModel], users1.NegMax[users1.UserModel], users1.PosMin[users1.UserModel], Valuepass[1] = current(users1.NegMin[users1.UserModel], users1.NegMax[users1.UserModel], users1.PosMin[users1.UserModel],
users1.PosMax[users1.UserModel], users1.usMin[users1.UserModel], users1.usMax[users1.UserModel], users1.PosMax[users1.UserModel], users1.usMin[users1.UserModel], users1.usMax[users1.UserModel],
users1.Data); //处理函数 users1.Data); //处理函数
Valuepass[2] = current(users2.NegMin[users2.UserModel], users2.NegMax[users2.UserModel], users2.PosMin[users2.UserModel], Valuepass[2] = current(users2.NegMin[users2.UserModel], users2.NegMax[users2.UserModel], users2.PosMin[users2.UserModel],
users2.PosMax[users2.UserModel], users2.usMin[users2.UserModel], users2.usMax[users2.UserModel], users2.PosMax[users2.UserModel], users2.usMin[users2.UserModel], users2.usMax[users2.UserModel],
users2.Data); //处理函数 users2.Data); //处理函数
Valuepass[3] = current(users3.NegMin[users3.UserModel], users3.NegMax[users3.UserModel], users3.PosMin[users3.UserModel], Valuepass[3] = current(users3.NegMin[users3.UserModel], users3.NegMax[users3.UserModel], users3.PosMin[users3.UserModel],
users3.PosMax[users3.UserModel], users3.usMin[users3.UserModel], users3.usMax[users3.UserModel], users3.PosMax[users3.UserModel], users3.usMin[users3.UserModel], users3.usMax[users3.UserModel],
users3.Data); //处理函数 users3.Data); //处理函数
Valuepass[4] = current(users4.NegMin[users4.UserModel], users4.NegMax[users4.UserModel], users4.PosMin[users4.UserModel], Valuepass[4] = current(users4.NegMin[users4.UserModel], users4.NegMax[users4.UserModel], users4.PosMin[users4.UserModel],
users4.PosMax[users4.UserModel], users4.usMin[users4.UserModel], users4.usMax[users4.UserModel], users4.PosMax[users4.UserModel], users4.usMin[users4.UserModel], users4.usMax[users4.UserModel],
users4.Data); //处理函数 users4.Data); //处理函数
Valuepass[5] = current(users5.NegMin[users5.UserModel], users5.NegMax[users5.UserModel], users5.PosMin[users5.UserModel], Valuepass[5] = current(users5.NegMin[users5.UserModel], users5.NegMax[users5.UserModel], users5.PosMin[users5.UserModel],
users5.PosMax[users5.UserModel], users5.usMin[users5.UserModel], users5.usMax[users5.UserModel], users5.PosMax[users5.UserModel], users5.usMin[users5.UserModel], users5.usMax[users5.UserModel],
users5.Data); //处理函数 users5.Data); //处理函数
Valuepass[6] = current(users6.NegMin[users6.UserModel], users6.NegMax[users6.UserModel], users6.PosMin[users6.UserModel], Valuepass[6] = current(users6.NegMin[users6.UserModel], users6.NegMax[users6.UserModel], users6.PosMin[users6.UserModel],
users6.PosMax[users6.UserModel], users6.usMin[users6.UserModel], users6.usMax[users6.UserModel], users6.PosMax[users6.UserModel], users6.usMin[users6.UserModel], users6.usMax[users6.UserModel],
users6.Data); //处理函数 users6.Data); //处理函数
Valuepass[7] = current(users7.NegMin[users7.UserModel], users7.NegMax[users7.UserModel], users7.PosMin[users7.UserModel], Valuepass[7] = current(users7.NegMin[users7.UserModel], users7.NegMax[users7.UserModel], users7.PosMin[users7.UserModel],
users7.PosMax[users7.UserModel], users7.usMin[users7.UserModel], users7.usMax[users7.UserModel], users7.PosMax[users7.UserModel], users7.usMin[users7.UserModel], users7.usMax[users7.UserModel],
users7.Data); //处理函数 users7.Data); //处理函数
}
else
{
Valuepass = null;
}
return Valuepass; return Valuepass;
} }
...@@ -262,7 +255,7 @@ namespace ModbusDemo ...@@ -262,7 +255,7 @@ namespace ModbusDemo
/*****************有效判断*****************************/ /*****************有效判断*****************************/
if (text[0] == "0.000") if (text[0] == "0.000")
{ {
text[0] = "0"; text[0] = "Burn_out";
return text; return text;
} }
else else
......
...@@ -14,13 +14,9 @@ namespace ModbusDemo ...@@ -14,13 +14,9 @@ namespace ModbusDemo
[STAThread] [STAThread]
static void Main() static void Main()
{ {
Application.EnableVisualStyles();
Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1());
Application.Run(new Form1());
//Application.Run(new Demo_818X());
//Application.Run(new ProTest());
//Application.Run(new MDemo());
} }
} }
} }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ModbusDemo;
namespace ModbusDemo.application
{
class Pond
{
private string Sname;//池子的名称
private bool state;
private double Dlevel;//池子的液位
private double Lowwaterlevel;//液位最低水位
private double Peaklevel;//液位最高水位
private string Agitator;//搅拌器
private ushort current;//电流
private ushort Voltage;//电压
public string Sname1 { get => Sname; set => Sname = value; }
public bool State { get => state; set => state = value; }
public double Dlevel1 { get => Dlevel; set => Dlevel = value; }
public double Lowwaterlevel1 { get => Lowwaterlevel; set => Lowwaterlevel = value; }
public double Peaklevel1 { get => Peaklevel; set => Peaklevel = value; }
public ushort Voltage1 { get => Voltage; set => Voltage = value; }
public ushort Current { get => current; set => current = value; }
public string Agitator1 { get => Agitator; set => Agitator = value; }
//public class Agitator : ModbusAttribute //搅拌器
//{
// public bool state;
// public ushort[] current;//电流
// public ushort[] Voltage;//电压
//}
//public class pump : ModbusAttribute//泵
//{
// public bool state;
// public ushort[] current;//电流
// public ushort[] Voltage;//电压
//}
//public class Level : ModbusAttribute //液位属性
//{
// public ushort[] level;//液位
// public ushort[] passageway; //液位通道
// public double[] Lowwaterlevel; // 液位最低水位
// public double[] Peaklevel; // 液位最高水位
//}
//public class ModbusAttribute //modbus属性
//{
// public byte[] SlaveAddress;
// public ushort[] RegisterAddress;
//}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace ModbusDemo.windows
{
class TransferPool
{
public string position;//位置
public class Source: ModbusAttribute //水源
{
public string Southeastwater; //东南水
public string Northeastwater; //东北水
public string Southwestwater; //西南水
public string Northwestwater; //西北水
public string Timingtime; //定时时间
public bool system_Statue;
}
public class passageway //通道
{
public Agitator agitator;
public pump pump;
public Level Level;//液位属性
}
public class Agitator: ModbusAttribute //搅拌器
{
public bool state;
public ushort[] current;//电流
public ushort[] Voltage;//电压
}
public class pump: ModbusAttribute//泵
{
public bool state;
public ushort[] current;//电流
public ushort[] Voltage;//电压
}
public class Level: ModbusAttribute //液位属性
{
public ushort[] level;//液位
public ushort[] passageway; //液位通道
public double[] Lowwaterlevel; // 液位最低水位
public double[] Peaklevel; // 液位最高水位
}
public class ModbusAttribute //modbus属性
{
public byte[] SlaveAddress;
public ushort[] RegisterAddress;
}
}
}
...@@ -18,14 +18,18 @@ using System.IO; ...@@ -18,14 +18,18 @@ using System.IO;
using System.Diagnostics; using System.Diagnostics;
using ModbusDemo; using ModbusDemo;
using System.Timers; using System.Timers;
using ModbusDemo.application;
namespace ModbusDemo namespace ModbusDemo
{ {
public partial class Form1 : Form public partial class Form1 : Form
{ {
bool Debug_test = false;//打开测试功能 bool Debug_test = true;//打开测试功能
_418X Analog = new _418X();
_414P rtd = new _414P(); _414P rtd = new _414P();
_478C state = new _478C(); _478C state = new _478C();
_418X Analog = new _418X();
Pond FunctionalService = new Pond();
private bool bStart = false; private bool bStart = false;
FileStream fsl; FileStream fsl;
AutoResetEvent exitEvent; AutoResetEvent exitEvent;
...@@ -34,15 +38,38 @@ namespace ModbusDemo ...@@ -34,15 +38,38 @@ namespace ModbusDemo
public delegate void invokeDelegate(); public delegate void invokeDelegate();
System.Timers.Timer timer = new System.Timers.Timer(); System.Timers.Timer timer = new System.Timers.Timer();
System.Timers.Timer MQTTTimer = new System.Timers.Timer(); System.Timers.Timer MQTTTimer = new System.Timers.Timer();
BackgroundWorker m_bgw0 = new BackgroundWorker();
bool m_Isbgw0_CanContinueRun = true;
ModbusDemo.windows.Totxt totxt = new windows.Totxt(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt"); ModbusDemo.windows.Totxt totxt = new windows.Totxt(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
public Form1() public Form1()
{ {
InitializeComponent(); InitializeComponent();
m_bgw0.WorkerSupportsCancellation = true;
m_bgw0.DoWork += m_bgw0_DoWork;
} }
private void Form1_Load(object sender, EventArgs e)
{
cmbBaud.SelectedIndex = 7;
cmbDataBit.SelectedIndex = 1;
cmbParity.SelectedIndex = 0;
cmbStopBit.SelectedIndex = 0;
foreach (string s in SerialPort.GetPortNames())
cmbPort.Items.Add(s);
cmbPort.SelectedIndex = -1;
exitEvent = new AutoResetEvent(false);
waitTime = 6000;
t_UpgradeConn = new Thread(UpgradeProc);
t_UpgradeConn.IsBackground = true;
t_UpgradeConn.Start();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
System.Environment.Exit(0);
}
#region 参数 #region 参数
/// <summary> /// <summary>
...@@ -68,25 +95,27 @@ namespace ModbusDemo ...@@ -68,25 +95,27 @@ namespace ModbusDemo
string mqttPwd; string mqttPwd;
string mqttTopic; string mqttTopic;
string mqttSubscribeTopic; string mqttSubscribeTopic;
string mqttSn; string mqttBackTopic;
string mqttSn= "20193261";
string mqttData;//数据 string mqttData;//数据
string mqttData_Back;//数据
private IMqttClient mqttClient = null; private IMqttClient mqttClient = null;
private bool isReconnect = true; private bool isReconnect = true;
ushort address;
byte ID;
bool[] DI = new bool[10]; bool[] DI = new bool[10];
bool[] DO = new bool[10]; bool[] DO = new bool[10];
float[] AI = new float[10]; float[] AI = new float[10];
float[] AO = new float[10]; float[] AO = new float[10];
#endregion #endregion
private void SetMqtt() private void SetMqtt()
{ {
mqttSn = "20193261";
mqttTopic = "Witium/WTDS78X/" + mqttSn + "/Data"; mqttTopic = "Witium/WTDS78X/" + mqttSn + "/Data";
if (Debug_test == true) if (Debug_test == true)
{ {
mqttIp = "120.27.235.39"; mqttIp = "172.16.1.24";
mqttClientId = GetTimeStamp() + "sxz"; mqttClientId = GetTimeStamp() + "sxz";
mqttPort = 1883; mqttPort = 1883;
mqttUsername = "pasture"; mqttUsername = "pasture";
...@@ -94,18 +123,33 @@ namespace ModbusDemo ...@@ -94,18 +123,33 @@ namespace ModbusDemo
} }
else else
{ {
mqttIp = "47.101.50.24"; mqttIp = "120.27.235.39";
mqttClientId = GetTimeStamp() + "sxz"; mqttClientId = GetTimeStamp() + "sxz";
mqttPort = 1883; mqttPort = 1883;
mqttUsername = "root"; mqttUsername = "pasture";
mqttPwd = "public"; mqttPwd = "Pasture37774020";
} }
} }
private void SetTopic() private void SetTopic()
{ {
mqttSn = "20193261"; mqttSubscribeTopic = "Witium/WTDS78X/" + mqttSn + "/Ctrl";
mqttSubscribeTopic = "Witium/WTDS78X/" + mqttSn + "/OData"; mqttBackTopic = "Witium/WTDS78X/" + mqttSn + "/Back";
}
void m_bgw0_DoWork(object sender, DoWorkEventArgs e)
{
while (m_Isbgw0_CanContinueRun)
{
int _n = 2;
this.Invoke(new Action(() =>
{
}));
Thread.Sleep(1000);
}
} }
#region 时间戳 #region 时间戳
/// <summary> /// <summary>
...@@ -121,92 +165,13 @@ namespace ModbusDemo ...@@ -121,92 +165,13 @@ namespace ModbusDemo
#endregion #endregion
#region 方法 #region 方法
public void control(byte SlaveAddress, ushort startAddress, bool value)
private void SetPort(string pName, int pbaudRate, int dataBits, Parity pparity, StopBits pstopBits)
{
if (serialPort != null)
{
serialPort.Dispose();
}
serialPort = new SerialPort();
serialPort.PortName = portName;
serialPort.BaudRate = baudRate;
serialPort.DataBits = dataBits;
serialPort.Parity = parity;
serialPort.StopBits = stopBits;
}
private void OpenPort()
{
try
{
if (serialPort != null)
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
serialPort.Open();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void CreateModbusRtu()
{
try
{
if (serialPort != null)
{
if (serialPort.IsOpen)
{
master = ModbusSerialMaster.CreateRtu(serialPort);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//private ushort[] ReadHoldingReg(Modular modular, byte slaveId, ushort startAdd, ushort numPoint)
private ushort[] ReadHoldingReg(byte slaveId, ushort startAdd, ushort numPoint)
{
ushort[] data = new ushort[numPoint];
data = master.ReadHoldingRegisters(slaveId, startAdd, numPoint);
return data;
//switch (modular)
//{
// case Modular.M_WTD414P:
// data = master.ReadHoldingRegisters(slaveId, startAdd, numPoint);
// break;
// case Modular.M_WTD418X:
// data = master.ReadHoldingRegisters(slaveId, startAdd, numPoint);
// break;
// case Modular.M_WTD478C:
// break;
// default:
// break;
//}
}
private byte[] ReadCoilStatus(byte slaveId, ushort startAdd, ushort numPoint)
{ {
byte[] data = new byte[numPoint]; bool OutputValue;
int Caution = 0;
data = getByte(master.ReadCoils(slaveId, startAdd, numPoint)); Modbus_WriteSingleCoil(out OutputValue, SlaveAddress, startAddress, value, out Caution);
return data;
} }
public static byte[] getByte(bool[] array) public static byte[] getByte(bool[] array)
{ {
byte[] data = new byte[array.Length]; byte[] data = new byte[array.Length];
...@@ -224,6 +189,10 @@ namespace ModbusDemo ...@@ -224,6 +189,10 @@ namespace ModbusDemo
#endregion #endregion
#region mqtt服务 #region mqtt服务
//创建一个委托,是为访问TextBox控件服务的。
public delegate void UpdateTxt(string msg);
//定义一个委托变量
public UpdateTxt updateTxt;
private async Task Publish() private async Task Publish()
{ {
...@@ -235,7 +204,16 @@ namespace ModbusDemo ...@@ -235,7 +204,16 @@ namespace ModbusDemo
.Build(); .Build();
await mqttClient.PublishAsync(message); await mqttClient.PublishAsync(message);
} }
private async Task Back()
{
var message = new MqttApplicationMessageBuilder()
.WithTopic(mqttBackTopic)
.WithPayload(mqttData_Back)
.WithAtMostOnceQoS()
.WithRetainFlag(false)
.Build();
await mqttClient.PublishAsync(message);
}
private async Task Subscribe() private async Task Subscribe()
{ {
if (!mqttClient.IsConnected) if (!mqttClient.IsConnected)
...@@ -382,7 +360,7 @@ namespace ModbusDemo ...@@ -382,7 +360,7 @@ namespace ModbusDemo
} }
} }
private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e) private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
{ {
Invoke((new Action(() => Invoke((new Action(() =>
{ {
...@@ -396,18 +374,57 @@ namespace ModbusDemo ...@@ -396,18 +374,57 @@ namespace ModbusDemo
txtReceiveMessage.AppendText($">> Topic = {e.ApplicationMessage.Topic}{Environment.NewLine}"); txtReceiveMessage.AppendText($">> Topic = {e.ApplicationMessage.Topic}{Environment.NewLine}");
totxt.Log($">> Topic = {e.ApplicationMessage.Topic}{Environment.NewLine}"); totxt.Log($">> Topic = {e.ApplicationMessage.Topic}{Environment.NewLine}");
}))); })));
Invoke((new Action(() => Invoke((new Action(async () =>
{ {
bool on_off = true;
//消息的内容 //消息的内容
txtReceiveMessage.AppendText($">> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}"); txtReceiveMessage.AppendText($">> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
totxt.Log($">> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}"); totxt.Log($">> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
Console.WriteLine(Encoding.UTF8.GetString(e.ApplicationMessage.Payload)); Console.WriteLine(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
//订阅内容部分jSON 解析转对象 根据modbusID或者设备类型处理设备消息 Ctrl ctrl = JsonConvert.DeserializeObject<Ctrl>(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
//WTDR14P WTD14P = JsonConvert.DeserializeObject<WTDR14P>(Encoding.UTF8.GetString(e.ApplicationMessage.Payload)); Ctrl ctrl_Back = new Ctrl();
//WTDR66C WTD66C =JsonConvert.DeserializeObject<WTDR66C>(Encoding.UTF8.GetString(e.ApplicationMessage.Payload)); List<Ss> ctrl_Back_ss = new List<Ss>();
//解析控制部分 ctrl_Back_ss.Add(new Ss());
string txt = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
for (int i = 0; i < 6; i++)
{
if (txt.Contains("d"+i))
{
address =(ushort) (16 + i);
}
if (ctrl.ss[0].op.d1 == 1 ||
ctrl.ss[0].op.d0 == 1 ||
ctrl.ss[0].op.d2 == 1 ||
ctrl.ss[0].op.d3 == 1 ||
ctrl.ss[0].op.d4 == 1 ||
ctrl.ss[0].op.d5 == 1)
{
on_off = true;
}
else
on_off = false;
}
control(ctrl.ss[0].getAddr(), address, on_off);//根据下发确定控制通道
ID = ctrl.ss[0].getAddr();
Modbus_polling();
ctrl_Back.taskId = ctrl.taskId.ToString();
ctrl_Back_ss[0] = ctrl.ss[0];
ctrl_Back.ss = ctrl_Back_ss;
ctrl_Back.ss[0].op.getStartTime();
if(ctrl.ss[0].op.getStartTime() !=0)
{
Thread objThread = new Thread(new ThreadStart(delegate
{
ThreadMethodTxtAsync(Convert.ToInt32(ctrl.ss[0].op.getDuration()));
}));
objThread.Start();
}
//txtReceiveMessage.Clear(); mqttData_Back = JsonConvert.SerializeObject(ctrl_Back);
await Publish();
await Back();
//订阅内容部分jSON 解析转对象 根据modbusID或者设备类型处理设备消息
//解析控制部分
}))); })));
Invoke((new Action(() => Invoke((new Action(() =>
{ {
...@@ -420,448 +437,258 @@ namespace ModbusDemo ...@@ -420,448 +437,258 @@ namespace ModbusDemo
totxt.Log($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}"); totxt.Log($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}");
}))); })));
} }
#endregion //此为在非创建线程中的调用方法,其实是使用TextBox的Invoke方法。
public async Task ThreadMethodTxtAsync(int n)
#region modbus线程(未写完)
//public static void CallToChildThread()
//{
// Console.WriteLine("Child thread starts");
//}
//ManualResetEvent startrt1 = new ManualResetEvent(false);
//ManualResetEvent startrt2 = new ManualResetEvent(false);
//Thread rt_GetData1;
//private void StartReadThread1()
//{
// if (startrt1 != null)
// {
// startrt1.Reset();
// }
// rt_GetData1 = new Thread(GeData1);
// rt_GetData1.IsBackground = true;
// rt_GetData1.Start();
//}
//public void GetDataStop1()
//{
// startrt1.Set();
//}
//public void GetDataStop()
//{
// this.startrt1.Reset();
//}
//private void GeData1()
//{
// while (!startrt1.WaitOne(60000))
// {
// //数据类型 新建类
// //数据读取
// Modbus_polling();
// Thread.Sleep(60000);
// }
//}
//Thread rt_GetData2;
//private void StartReadThread2()
//{
// if (startrt2 != null)
// {
// startrt2.Reset();
// }
// rt_GetData2 = new Thread(GeData2);
// rt_GetData2.IsBackground = true;
// rt_GetData2.Start();
//}
//public void GetDataStop2()
//{
// startrt2.Set();
//}
//private void GeData2()
//{
// while (!startrt2.WaitOne(500))
// {
// Thread.Sleep(500);
// }
//}
#endregion
#region json字符串转对象
/// <summary>
/// json字符串转对象
/// </summary>
/// <typeparam name="RData">接收的对象</typeparam>
/// <param name="rd">json字符串</param>
/// <returns></returns>
public RData DataConversion<RData>(string rd)
{ {
try this.BeginInvoke(updateTxt, "线程开始执行,执行" + n + "次,每一秒执行一次");
{ int time = n * 60;
return JsonConvert.DeserializeObject<RData>(rd); for (int i = 0; i < time; i++)
}
catch (Exception ex)
{ {
Console.WriteLine(ex.Message); this.BeginInvoke(updateTxt, i.ToString());
return default(RData); //一秒 执行一次
Thread.Sleep(1000);
if (i> time - 2)
{
control(ID, address, false);//根据下发确定控制通道
Modbus_polling();
await Publish();
time = 0;
n = 0;
}
} }
this.BeginInvoke(updateTxt, "线程结束");
} }
public UData DataConverion<UData>(string ud) #endregion
#region modbus线程
private void GetData()
{ {
try timer.Interval = 5000;
{ timer.Enabled = true;
return JsonConvert.DeserializeObject<UData>(ud); timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
} timer.Start();
catch (Exception ex) timer.Elapsed += (o, a) =>
{ {
Console.WriteLine(ex.Message); SetData();
return default(UData); ShowMessage(string.Format("更新时间:" + DateTime.Now));
} };
} }
/// <summary> private void Sendout()
/// 对象转json字符串
/// </summary>
/// <param name="ud">上传实体</param>
/// <returns></returns>
public string DataConversion(UData ud)
{ {
try Control.CheckForIllegalCrossThreadCalls = false;
{ MQTTTimer.Interval = 12000;
return JsonConvert.SerializeObject(ud); MQTTTimer.Enabled = true;
} MQTTTimer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
catch (Exception ex) MQTTTimer.Start();
MQTTTimer.Elapsed += async (o, a) =>
{ {
Console.WriteLine(ex.Message); try
return ""; {
} await Publish();
totxt.Log(mqttData + Environment.NewLine + "\n");
}
catch (Exception ex)
{
ShowMessage(string.Format("更新时间:" + DateTime.Now));
totxt.Log(ex + "," + Environment.NewLine + "\n");
return;
}
};
} }
/// <summary>
/// //声明委托
/// </summary> private delegate void SetDataDelegate();
/// <param name="rD"></param> private void SetData()
/// <returns></returns>
public string DataConversion(RData rD)
{ {
try if (this.InvokeRequired)
{ {
return JsonConvert.SerializeObject(rD); this.Invoke(new SetDataDelegate(SetData));
} }
catch (Exception ex) else
{ {
Console.WriteLine(ex.Message); Modbus_polling();
return "";
} }
} }
#endregion
#region 网络检测
ManualResetEvent network = new ManualResetEvent(false); //声明委托
Thread MonitorThread; private delegate void ShowMessageDelegate(string message);
private void StartMonitorThread() private void ShowMessage(string message)
{ {
if (network != null) if (this.InvokeRequired)
{ {
network.Reset(); ShowMessageDelegate showMessageDelegate = ShowMessage;
this.Invoke(showMessageDelegate, new object[] { message });
} }
MonitorThread = new Thread(MonitorNetWork); else
MonitorThread.IsBackground = true;
MonitorThread.Start();
}
public void MonitorThreadStop()
{
network.Set();
}
private void MonitorNetWork()
{
while (!network.WaitOne(500))
{ {
string url = "www.baidu.com;www.sina.com;www.cnblogs.com;www.google.com;www.163.com;www.csdn.com"; //txtbox.Text = message;
string[] urls = url.Split(new char[] { ';' }); totxt.Log(message);
CheckServeStatus(urls);
Thread.Sleep(1000);
} }
} }
/// <summary> public void Modbus_ReadHoldingRegistersTask(out ushort[] OutputValue, byte slaveAddress, ushort startAddress, ushort numberOfPoints, out int Caution)
/// 检测网络连接状态
/// </summary>
/// <param name="urls"></param>
public static void CheckServeStatus(string[] urls)
{ {
int errCount = 0;//ping时连接失败个数 try
if (!LocalConnectionStatus())
{ {
Console.WriteLine("网络异常~无连接"); OutputValue = master.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints);
Caution = 0;
} }
else if (!MyPing(urls, out errCount)) catch (Exception exception)
{ {
if ((double)errCount / urls.Length >= 0.3) //Connection exception
{ //No response from server.
Console.WriteLine("网络异常~连接多次无响应"); //The server maybe close the com port, or response timeout.
} if (exception.Source.Equals("System"))
else
{ {
Console.WriteLine("网络不稳定"); timer.Stop();
} Console.WriteLine(DateTime.Now.ToString() + " " + exception.Message);
} totxt.Log(DateTime.Now.ToString() + " " + exception.Message);
else OutputValue = null;
{ Caution = -1;
Console.WriteLine("网络正常");
}
}
private const int INTERNET_CONNECTION_MODEM = 1;
private const int INTERNET_CONNECTION_LAN = 2;
[System.Runtime.InteropServices.DllImport("winInet.dll")]
private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved);
/// <summary>
/// 判断本地的连接状态
/// </summary>
/// <returns></returns>
private static bool LocalConnectionStatus()
{
System.Int32 dwFlag = new Int32();
if (!InternetGetConnectedState(ref dwFlag, 0))
{
Console.WriteLine("LocalConnectionStatus--未连网!");
return false;
}
else
{
if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
{
Console.WriteLine("LocalConnectionStatus--采用调制解调器上网。");
return true;
} }
else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0) //The server return error code.
//You can get the function code and exception code.
if (exception.Source.Equals("nModbusPC"))
{ {
Console.WriteLine("LocalConnectionStatus--采用网卡上网。"); string str = exception.Message;
return true; int FunctionCode;
} string ExceptionCode;
}
return false;
}
/// <summary> str = str.Remove(0, str.IndexOf("\r\n") + 17);
/// Ping命令检测网络是否畅通 FunctionCode = Convert.ToInt16(str.Remove(str.IndexOf("\r\n")));
/// </summary> Console.WriteLine("Function Code: " + FunctionCode.ToString("X"));
/// <param name="urls">URL数据</param> totxt.Log("Function Code: " + FunctionCode.ToString("X"));
/// <param name="errorCount">ping时连接失败个数</param>
/// <returns></returns> str = str.Remove(0, str.IndexOf("\r\n") + 17);
public static bool MyPing(string[] urls, out int errorCount) ExceptionCode = str.Remove(str.IndexOf("-"));
{ switch (ExceptionCode.Trim())
bool isconn = true;
Ping ping = new Ping();
errorCount = 0;
try
{
PingReply pr;
for (int i = 0; i < urls.Length; i++)
{
pr = ping.Send(urls[i]);
if (pr.Status != IPStatus.Success)
{ {
isconn = false; case "1":
errorCount++; Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
break;
case "2":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
break;
case "3":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
break;
case "4":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
break;
case "5":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
break;
case "6":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
break;
case "8":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
break;
case "A":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
break;
case "B":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!");
break;
} }
Console.WriteLine("Ping " + urls[i] + " " + pr.Status.ToString());
} }
OutputValue = null;
Caution = -1;
} }
catch
{
isconn = false;
errorCount = urls.Length;
}
//if (errorCount > 0 && errorCount < 3)
// isconn = true;
return isconn;
} }
public void Modbus_ReadCoilsTask(out bool[] OutputValue, byte slaveAddress, ushort startAddress, ushort numberOfPoints, out int Caution)
#endregion
private void Form1_Load(object sender, EventArgs e)
{
cmbBaud.SelectedIndex = 7;
cmbDataBit.SelectedIndex = 1;
cmbParity.SelectedIndex = 0;
cmbStopBit.SelectedIndex = 0;
foreach (string s in SerialPort.GetPortNames())
cmbPort.Items.Add(s);
cmbPort.SelectedIndex = -1;
exitEvent = new AutoResetEvent(false);
waitTime = 6000;
t_UpgradeConn = new Thread(UpgradeProc);
t_UpgradeConn.IsBackground = true;
t_UpgradeConn.Start();
}
private void GetData()
{ {
timer.Interval = 6000; try
timer.Enabled = true;
timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
timer.Start();
timer.Elapsed += (o, a) =>
{ {
SetData(); OutputValue = master.ReadCoils(slaveAddress, startAddress, numberOfPoints);
ShowMessage(string.Format("更新时间:" + DateTime.Now)); Caution = 0;
}; }
} catch (Exception exception)
private void Sendout()
{
Control.CheckForIllegalCrossThreadCalls = false;
MQTTTimer.Interval = 1000;
MQTTTimer.Enabled = true;
MQTTTimer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
MQTTTimer.Start();
MQTTTimer.Elapsed += async (o, a) =>
{ {
try //Connection exception
//No response from server.
//The server maybe close the com port, or response timeout.
if (exception.Source.Equals("System"))
{ {
await Publish(); timer.Stop();
totxt.Log(mqttData + Environment.NewLine + "\n"); Console.WriteLine(DateTime.Now.ToString() + " " + exception.Message);
txtReceiveMessage.AppendText(mqttData + Environment.NewLine + "\n"); totxt.Log(DateTime.Now.ToString() + " " + exception.Message);
OutputValue = null;
Caution = -1;
} }
catch (Exception ex) //The server return error code.
//You can get the function code and exception code.
if (exception.Source.Equals("nModbusPC"))
{ {
ShowMessage(string.Format("更新时间:" + DateTime.Now)); string str = exception.Message;
totxt.Log(ex + "," + Environment.NewLine + "\n"); int FunctionCode;
return; string ExceptionCode;
//throw ex;
}
};
}
//声明委托
private delegate void SetDataDelegate();
private void SetData()
{
if (this.InvokeRequired)
{
this.Invoke(new SetDataDelegate(SetData));
}
else
{
Modbus_polling();
}
}
//声明委托 str = str.Remove(0, str.IndexOf("\r\n") + 17);
private delegate void ShowMessageDelegate(string message); FunctionCode = Convert.ToInt16(str.Remove(str.IndexOf("\r\n")));
private void ShowMessage(string message) Console.WriteLine("Function Code: " + FunctionCode.ToString("X"));
{ totxt.Log("Function Code: " + FunctionCode.ToString("X"));
if (this.InvokeRequired)
{
ShowMessageDelegate showMessageDelegate = ShowMessage;
this.Invoke(showMessageDelegate, new object[] { message });
}
else
{
//txtbox.Text = message;
totxt.Log(message);
}
}
private void btOpenCOM_Click(object sender, EventArgs e) str = str.Remove(0, str.IndexOf("\r\n") + 17);
{ ExceptionCode = str.Remove(str.IndexOf("-"));
if (Debug_test == true) switch (ExceptionCode.Trim())
{ {
comPort.PortName = "COM1"; case "1":
comPort.BaudRate = 9600; Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
comPort.Parity = Parity.None; totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
comPort.StopBits = StopBits.One; break;
comPort.DataBits = 8; case "2":
} Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
else totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
{ break;
if (cmbPort.Text == "") case "3":
{ Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
MessageBox.Show("串口打开错误"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
return; break;
} case "4":
comPort.PortName = cmbPort.Text; Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
comPort.BaudRate = int.Parse(cmbBaud.Text); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
comPort.DataBits = int.Parse(cmbDataBit.Text); break;
if (cmbParity.Text.Substring(0, 1) == "0") case "5":
{ Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
comPort.Parity = Parity.None; totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
} break;
else if (cmbParity.Text.Substring(0, 1) == "1") case "6":
{ Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
comPort.Parity = Parity.Odd; totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
} break;
else if (cmbParity.Text.Substring(0, 1) == "2") case "8":
{ Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
comPort.Parity = Parity.Even; totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
} break;
if (cmbStopBit.Text == "0") case "A":
{ Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
comPort.StopBits = StopBits.None; totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
} break;
else if (cmbStopBit.Text == "1") case "B":
{ Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!");
comPort.StopBits = StopBits.One; totxt.Log("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!");
break;
}
} }
OutputValue = null;
Caution = -1;
} }
try
{
comPort.Open();
isReconnect = true;
SetMqtt();
Thread t = new Thread(new ThreadStart(GetData));
t.IsBackground = true;
t.Start();
Thread MQTT_thread = new Thread(new ThreadStart(Sendout));
MQTT_thread.IsBackground = true;
MQTT_thread.Start();
Task.Run(async () => { await ConnectMqttServerAsync(); });
master =ModbusSerialMaster.CreateRtu(comPort);
master.Transport.Retries = 6; //重试次数
master.Transport.ReadTimeout = 1500; //读取串口数据超时时间(ms)
master.Transport.WriteTimeout = 1500;//写入串口数据超时时间(ms)
master.Transport.WaitToRetryMilliseconds = 500;//重试间隔(ms)
modbus_Timer.Enabled = true;
btOpenCOM.Enabled = false;
btCloseCOM.Enabled = true;
totxt.Log(DateTime.Now.ToString() + " =>Open " + comPort.PortName + " sucessfully!");
}
catch (Exception ex)
{
totxt.Log("Error: " + ex.Message);
MessageBox.Show("Error: " + ex.Message);
return;
}
}
private void btCloseCOM_Click(object sender, EventArgs e)
{
//Close comport first,then stop and dispose slave.
timer.Stop();
isReconnect = false;
modbus_Timer.Enabled = false;
btOpenCOM.Enabled = true;
btCloseCOM.Enabled = false;
Task.Run(async () => { await mqttClient.DisconnectAsync(); });
comPort.Close();
totxt.Log(DateTime.Now.ToString() + " =>Disconnect " + comPort.PortName);
} }
public void Modbus_WriteSingleCoil(out bool OutputValue, byte slaveAddress, ushort startAddress, bool value, out int Caution)
public void Modbus_ReadHoldingRegistersTask(out ushort[] OutputValue, byte slaveAddress , ushort startAddress, ushort numberOfPoints, out int Caution)
{ {
try try
{ {
OutputValue = master.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints); master.WriteSingleCoil(slaveAddress, startAddress, value);
OutputValue = value;
Caution = 0; Caution = 0;
} }
catch (Exception exception) catch (Exception exception)
...@@ -874,7 +701,7 @@ namespace ModbusDemo ...@@ -874,7 +701,7 @@ namespace ModbusDemo
timer.Stop(); timer.Stop();
Console.WriteLine(DateTime.Now.ToString() + " " + exception.Message); Console.WriteLine(DateTime.Now.ToString() + " " + exception.Message);
totxt.Log(DateTime.Now.ToString() + " " + exception.Message); totxt.Log(DateTime.Now.ToString() + " " + exception.Message);
OutputValue = null; OutputValue = false;
Caution = -1; Caution = -1;
} }
//The server return error code. //The server return error code.
...@@ -932,17 +759,92 @@ namespace ModbusDemo ...@@ -932,17 +759,92 @@ namespace ModbusDemo
break; break;
} }
} }
OutputValue = null; OutputValue = false;
Caution = -1; Caution = -1;
} }
} }
public void Modbus_ReadCoilsTask(out bool [] OutputValue, byte slaveAddress, ushort startAddress, ushort numberOfPoints, out int Caution) private void Modbus_polling()
{ {
float EastTemperature = 0;
float Easternwaterlevel = 0;
float WestWaterLevel = 0;
try try
{ {
OutputValue = master.ReadCoils(slaveAddress, startAddress, numberOfPoints); ushort[] temperature = { };
Caution = 0; ushort[] type = { };
string[] vs = { };
string[] s = { };
string[] s6 = { };
ushort[] register = { };
ushort[] Inputtype = { };
ushort[] registerN = { };
ushort[] InputtypeN = { };
bool[] EIO = { };
bool[] SIO = { };
bool[] WIO = { };
int[] EOnOff = { 0 };
int[] SOnOff = { 0 };
int[] WOnOff = { 0 };
Modbus_ReadHoldingRegistersTask(out temperature, 3, 0, 4, out int signT); //修改前1
Modbus_ReadHoldingRegistersTask(out type, 3, 10, 4, out int sign);
//Modbus_ReadHoldingRegistersTask(out register, 1, 0, 8, out int signr); //修改前3
//Modbus_ReadHoldingRegistersTask(out Inputtype, 1, 10, 8, out int signI);
//Modbus_ReadHoldingRegistersTask(out registerN, 6, 0, 8, out int signre);
//Modbus_ReadHoldingRegistersTask(out InputtypeN, 6, 10, 8, out int signIn);
//Modbus_ReadCoilsTask(out EIO, 5, 16, 6,out int signE);
//Modbus_ReadCoilsTask(out SIO, 8, 16, 6, out int signS);
Modbus_ReadCoilsTask(out WIO, 4, 16, 6, out int signW);
//if (sign == -1 || signT ==-1||signr==-1||signI == -1|| signre==-1|| signIn==-1||signE==-1||signS==-1|| signW ==-1)
if (sign == -1 || signT == -1 || signW == -1)
{
vs = null;
type = null;
EastTemperature = 0;
Easternwaterlevel = 0;
WestWaterLevel = 0;
}
else
{
vs = rtd.RtdValue(temperature, type);
EastTemperature = float.Parse(vs[0]);
//s = Analog.Value(register, Inputtype);
//Easternwaterlevel = (float.Parse(s[0]) - 4) / 16 * 6;
//s6 = Analog.Value(registerN, InputtypeN);
//WestWaterLevel = (float.Parse(s6[0]) - 4) / 16 * 6;
//label3.Text = EastTemperature.ToString();
//label4.Text = Easternwaterlevel.ToString();
//EOnOff = state.IO(EIO);////东中转池
//SOnOff = state.IO(SIO);////东南北水
WOnOff = state.IO(WIO); ////西中转池
}
WTDR14P x = new WTDR14P("1", EastTemperature, 0, 0, 0, GetTimeStamp());
//WTDR18X p = new WTDR18X("3", Easternwaterlevel, 0, 0, 0, 0, 0, 0, 0, GetTimeStamp());
//WTDR18X q = new WTDR18X("6", WestWaterLevel, 0, 0, 0, 0, 0, 0, 0, GetTimeStamp());
//东搅拌
//WTDR66C EastStir = new WTDR66C("5", EOnOff[0], EOnOff[1], EOnOff[2], EOnOff[3], EOnOff[4], EOnOff[5], GetTimeStamp());
//西搅拌
WTDR66C WestStir = new WTDR66C("4", WOnOff[0], WOnOff[1], WOnOff[2], WOnOff[3], WOnOff[4], WOnOff[5], GetTimeStamp());
//东南北水
//WTDR66C SouthWater = new WTDR66C("4", SOnOff[0], SOnOff[1], SOnOff[2], SOnOff[3], SOnOff[4], SOnOff[5], GetTimeStamp());
mqttData = "[" +
JsonConvert.SerializeObject(x) + "," +
//JsonConvert.SerializeObject(p)+"," +
//JsonConvert.SerializeObject(q) +","+
//JsonConvert.SerializeObject(EastStir)+","+
// JsonConvert.SerializeObject(WestStir) + "," +
JsonConvert.SerializeObject(WestStir)
+ "]";
} }
catch (Exception exception) catch (Exception exception)
{ {
//Connection exception //Connection exception
...@@ -953,8 +855,7 @@ namespace ModbusDemo ...@@ -953,8 +855,7 @@ namespace ModbusDemo
timer.Stop(); timer.Stop();
Console.WriteLine(DateTime.Now.ToString() + " " + exception.Message); Console.WriteLine(DateTime.Now.ToString() + " " + exception.Message);
totxt.Log(DateTime.Now.ToString() + " " + exception.Message); totxt.Log(DateTime.Now.ToString() + " " + exception.Message);
OutputValue = null; return;
Caution = -1;
} }
//The server return error code. //The server return error code.
//You can get the function code and exception code. //You can get the function code and exception code.
...@@ -968,6 +869,7 @@ namespace ModbusDemo ...@@ -968,6 +869,7 @@ namespace ModbusDemo
FunctionCode = Convert.ToInt16(str.Remove(str.IndexOf("\r\n"))); FunctionCode = Convert.ToInt16(str.Remove(str.IndexOf("\r\n")));
Console.WriteLine("Function Code: " + FunctionCode.ToString("X")); Console.WriteLine("Function Code: " + FunctionCode.ToString("X"));
totxt.Log("Function Code: " + FunctionCode.ToString("X")); totxt.Log("Function Code: " + FunctionCode.ToString("X"));
//MessageBox.Show("Function Code: " + FunctionCode.ToString("X"));
str = str.Remove(0, str.IndexOf("\r\n") + 17); str = str.Remove(0, str.IndexOf("\r\n") + 17);
ExceptionCode = str.Remove(str.IndexOf("-")); ExceptionCode = str.Remove(str.IndexOf("-"));
...@@ -975,234 +877,255 @@ namespace ModbusDemo ...@@ -975,234 +877,255 @@ namespace ModbusDemo
{ {
case "1": case "1":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!"); Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
break; break;
case "2": case "2":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!"); Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
break; break;
case "3": case "3":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!"); Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
break; break;
case "4": case "4":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!"); Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
break; break;
case "5": case "5":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!"); Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
break; break;
case "6": case "6":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !"); Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
break; break;
case "8": case "8":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !"); Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
break; break;
case "A": case "A":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !"); Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
break; break;
case "B": case "B":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!"); Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!"); totxt.Log("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY TARGET DEVICE FAILED TO RESPOND!");
break; break;
} }
return;
} }
OutputValue = null;
Caution = -1;
} }
return;
} }
private void Form1_FormClosed(object sender, FormClosedEventArgs e) #endregion
#region json字符串转对象
/// <summary>
/// json字符串转对象
/// </summary>
/// <typeparam name="RData">接收的对象</typeparam>
/// <param name="rd">json字符串</param>
/// <returns></returns>
public RData DataConversion<RData>(string rd)
{ {
System.Environment.Exit(0); try
{
return JsonConvert.DeserializeObject<RData>(rd);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return default(RData);
}
} }
public UData DataConverion<UData>(string ud)
private void Modbus_polling() {
try
{
return JsonConvert.DeserializeObject<UData>(ud);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return default(UData);
}
}
/// <summary>
/// 对象转json字符串
/// </summary>
/// <param name="ud">上传实体</param>
/// <returns></returns>
public string DataConversion(UData ud)
{
try
{
return JsonConvert.SerializeObject(ud);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "";
}
}
/// <summary>
///
/// </summary>
/// <param name="rD"></param>
/// <returns></returns>
public string DataConversion(RData rD)
{
try
{
return JsonConvert.SerializeObject(rD);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "";
}
}
#endregion
#region 网络检测
ManualResetEvent network = new ManualResetEvent(false);
Thread MonitorThread;
private void StartMonitorThread()
{
if (network != null)
{
network.Reset();
}
MonitorThread = new Thread(MonitorNetWork);
MonitorThread.IsBackground = true;
MonitorThread.Start();
}
public void MonitorThreadStop()
{
network.Set();
}
private void MonitorNetWork()
{
while (!network.WaitOne(500))
{
string url = "www.baidu.com;www.sina.com;www.cnblogs.com;www.google.com;www.163.com;www.csdn.com";
string[] urls = url.Split(new char[] { ';' });
CheckServeStatus(urls);
Thread.Sleep(1000);
}
}
/// <summary>
/// 检测网络连接状态
/// </summary>
/// <param name="urls"></param>
public static void CheckServeStatus(string[] urls)
{ {
int errCount = 0;//ping时连接失败个数
float EastTemperature = 0;
float Easternwaterlevel = 0;
float WestWaterLevel = 0;
try
{
ushort[] temperature = {};
ushort[] type = { };
string[] vs = {};
string[] s = { };
string[] s6 = { };
ushort[] register = { };
ushort[] Inputtype = { };
ushort[] registerN = { };
ushort[] InputtypeN = { };
bool[] EIO = { };
bool[] SIO = { };
bool[] WIO = { };
int[] EOnOff = {0};
int[] SOnOff = {0};
int[] WOnOff = {0};
Modbus_ReadHoldingRegistersTask(out temperature, 1, 0, 4, out int signT);
Modbus_ReadHoldingRegistersTask(out type,1,10,4,out int sign);
Modbus_ReadHoldingRegistersTask(out register, 3, 0, 8, out int signr);
Modbus_ReadHoldingRegistersTask(out Inputtype, 3, 10, 8, out int signI);
Modbus_ReadHoldingRegistersTask(out registerN, 6, 0, 8, out int signre);
Modbus_ReadHoldingRegistersTask(out InputtypeN, 6, 10, 8, out int signIn);
Modbus_ReadCoilsTask(out EIO, 5, 16, 6,out int signE);
Modbus_ReadCoilsTask(out SIO, 8, 16, 6, out int signS);
Modbus_ReadCoilsTask(out WIO, 4, 16, 6, out int signW);
if (sign == -1 || signT ==-1||signr==-1||signI == -1|| signre==-1|| signIn==-1||signE==-1||signS==-1|| signW ==-1) if (!LocalConnectionStatus())
{
Console.WriteLine("网络异常~无连接");
}
else if (!MyPing(urls, out errCount))
{
if ((double)errCount / urls.Length >= 0.3)
{ {
Console.WriteLine("网络异常~连接多次无响应");
vs = null ;
type = null;
EastTemperature = 0;
Easternwaterlevel = 0;
WestWaterLevel = 0 ;
} }
else else
{ {
vs = rtd.RtdValue(temperature, type); Console.WriteLine("网络不稳定");
EastTemperature =float.Parse(vs[0]);
s = Analog.Value(register, Inputtype);
Easternwaterlevel = (float.Parse(s[0]) - 4) / 16 * 6;
s6 = Analog.Value(registerN, InputtypeN);
WestWaterLevel = (float.Parse(s6[0]) - 4) / 16 * 6;
label3.Text = EastTemperature.ToString();
label4.Text = Easternwaterlevel.ToString();
EOnOff = state.IO(EIO);////东中转池
SOnOff = state.IO(SIO);////东南北水
WOnOff = state.IO(WIO); ////西中转池
} }
}
else
{
Console.WriteLine("网络正常");
}
}
private const int INTERNET_CONNECTION_MODEM = 1;
private const int INTERNET_CONNECTION_LAN = 2;
WTDR14P x = new WTDR14P("1", EastTemperature, 0, 0, 0, GetTimeStamp());
WTDR18X p = new WTDR18X("3", Easternwaterlevel, 0, 0, 0, 0, 0, 0, 0, GetTimeStamp());
WTDR18X q = new WTDR18X("6", WestWaterLevel, 0, 0, 0, 0, 0, 0, 0, GetTimeStamp());
//东搅拌
WTDR66C EastStir = new WTDR66C("5", EOnOff[0], EOnOff[1], EOnOff[2], EOnOff[3], EOnOff[4], EOnOff[5], GetTimeStamp());
//西搅拌
WTDR66C WestStir = new WTDR66C("8", WOnOff[0], WOnOff[1], WOnOff[2], WOnOff[3], WOnOff[4], WOnOff[5], GetTimeStamp());
//东南北水
WTDR66C SouthWater = new WTDR66C("4", SOnOff[0], SOnOff[1], SOnOff[2], SOnOff[3], SOnOff[4], SOnOff[5], GetTimeStamp());
mqttData = "[" + [System.Runtime.InteropServices.DllImport("winInet.dll")]
JsonConvert.SerializeObject(x)+"," + private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved);
JsonConvert.SerializeObject(p)+"," +
JsonConvert.SerializeObject(q) +","+
JsonConvert.SerializeObject(EastStir)+","+
JsonConvert.SerializeObject(WestStir) + "," +
JsonConvert.SerializeObject(SouthWater)
+ "]";
//txtReceiveMessage.AppendText("["+ /// <summary>
// JsonConvert.SerializeObject(x)+","+ /// 判断本地的连接状态
// JsonConvert.SerializeObject(p) +","+ /// </summary>
// JsonConvert.SerializeObject(q) + "," + /// <returns></returns>
// JsonConvert.SerializeObject(EastStir) + "," + private static bool LocalConnectionStatus()
// JsonConvert.SerializeObject(WestStir) + "," + {
// JsonConvert.SerializeObject(SouthWater) System.Int32 dwFlag = new Int32();
// + "]" + Environment.NewLine + "\n"); if (!InternetGetConnectedState(ref dwFlag, 0))
{
//totxt.Log("[" + Console.WriteLine("LocalConnectionStatus--未连网!");
// JsonConvert.SerializeObject(x) + "," + return false;
// JsonConvert.SerializeObject(p) + "," +
// JsonConvert.SerializeObject(q) + "," +
// JsonConvert.SerializeObject(EastStir) + "," +
// JsonConvert.SerializeObject(WestStir) + "," +
// JsonConvert.SerializeObject(SouthWater)
// + "]" + Environment.NewLine + "\n");
} }
else
catch (Exception exception)
{ {
//Connection exception if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
//No response from server.
//The server maybe close the com port, or response timeout.
if (exception.Source.Equals("System"))
{ {
timer.Stop(); Console.WriteLine("LocalConnectionStatus--采用调制解调器上网。");
Console.WriteLine(DateTime.Now.ToString() + " " + exception.Message); return true;
totxt.Log(DateTime.Now.ToString() + " " + exception.Message);
return;
} }
//The server return error code. else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
//You can get the function code and exception code.
if (exception.Source.Equals("nModbusPC"))
{ {
string str = exception.Message; Console.WriteLine("LocalConnectionStatus--采用网卡上网。");
int FunctionCode; return true;
string ExceptionCode; }
}
str = str.Remove(0, str.IndexOf("\r\n") + 17); return false;
FunctionCode = Convert.ToInt16(str.Remove(str.IndexOf("\r\n"))); }
Console.WriteLine("Function Code: " + FunctionCode.ToString("X"));
totxt.Log("Function Code: " + FunctionCode.ToString("X"));
//MessageBox.Show("Function Code: " + FunctionCode.ToString("X"));
str = str.Remove(0, str.IndexOf("\r\n") + 17); /// <summary>
ExceptionCode = str.Remove(str.IndexOf("-")); /// Ping命令检测网络是否畅通
switch (ExceptionCode.Trim()) /// </summary>
/// <param name="urls">URL数据</param>
/// <param name="errorCount">ping时连接失败个数</param>
/// <returns></returns>
public static bool MyPing(string[] urls, out int errorCount)
{
bool isconn = true;
Ping ping = new Ping();
errorCount = 0;
try
{
PingReply pr;
for (int i = 0; i < urls.Length; i++)
{
pr = ping.Send(urls[i]);
if (pr.Status != IPStatus.Success)
{ {
case "1": isconn = false;
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!"); errorCount++;
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal function!");
break;
case "2":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data address!");
break;
case "3":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Illegal data value!");
break;
case "4":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> Slave device failure!");
break;
case "5":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> ACKNOWLEDGE!");
break;
case "6":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> SLAVE DEVICE BUSY !");
break;
case "8":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> MEMORY PARITY ERROR !");
break;
case "A":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY PATH UNAVAILABLE !");
break;
case "B":
Console.WriteLine("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!");
totxt.Log("Exception Code: " + ExceptionCode.Trim() + "---->GATEWAY TARGET DEVICE FAILED TO RESPOND!");
//MessageBox.Show("Exception Code: " + ExceptionCode.Trim() + "----> GATEWAY TARGET DEVICE FAILED TO RESPOND!");
break;
} }
return; Console.WriteLine("Ping " + urls[i] + " " + pr.Status.ToString());
} }
} }
return; catch
{
isconn = false;
errorCount = urls.Length;
}
//if (errorCount > 0 && errorCount < 3)
// isconn = true;
return isconn;
} }
#endregion
#region 更新线程 #region 更新线程
string ImagefilePath = null; string ImagefilePath = null;
private void bgWorker_DoWork(object sender, DoWorkEventArgs e) private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
...@@ -1559,6 +1482,90 @@ namespace ModbusDemo ...@@ -1559,6 +1482,90 @@ namespace ModbusDemo
SetTopic(); SetTopic();
await Subscribe(); await Subscribe();
} }
private void btOpenCOM_Click(object sender, EventArgs e)
{
if (Debug_test == true)
{
comPort.PortName = "COM2";
comPort.BaudRate = 9600;
comPort.Parity = Parity.None;
comPort.StopBits = StopBits.One;
comPort.DataBits = 8;
}
else
{
if (cmbPort.Text == "")
{
MessageBox.Show("串口打开错误");
return;
}
comPort.PortName = cmbPort.Text;
comPort.BaudRate = int.Parse(cmbBaud.Text);
comPort.DataBits = int.Parse(cmbDataBit.Text);
if (cmbParity.Text.Substring(0, 1) == "0")
{
comPort.Parity = Parity.None;
}
else if (cmbParity.Text.Substring(0, 1) == "1")
{
comPort.Parity = Parity.Odd;
}
else if (cmbParity.Text.Substring(0, 1) == "2")
{
comPort.Parity = Parity.Even;
}
if (cmbStopBit.Text == "0")
{
comPort.StopBits = StopBits.None;
}
else if (cmbStopBit.Text == "1")
{
comPort.StopBits = StopBits.One;
}
}
try
{
comPort.Open();
isReconnect = true;
SetMqtt();
Thread t = new Thread(new ThreadStart(GetData));
t.IsBackground = true;
t.Start();
Thread MQTT_thread = new Thread(new ThreadStart(Sendout));
MQTT_thread.IsBackground = true;
MQTT_thread.Start();
Task.Run(async () => { await ConnectMqttServerAsync(); });
master = ModbusSerialMaster.CreateRtu(comPort);
master.Transport.Retries = 6; //重试次数
master.Transport.ReadTimeout = 1500; //读取串口数据超时时间(ms)
master.Transport.WriteTimeout = 1500;//写入串口数据超时时间(ms)
master.Transport.WaitToRetryMilliseconds = 500;//重试间隔(ms)
modbus_Timer.Enabled = true;
btOpenCOM.Enabled = false;
btCloseCOM.Enabled = true;
totxt.Log(DateTime.Now.ToString() + " =>Open " + comPort.PortName + " sucessfully!");
}
catch (Exception ex)
{
totxt.Log("Error: " + ex.Message);
MessageBox.Show("Error: " + ex.Message);
return;
}
}
private void btCloseCOM_Click(object sender, EventArgs e)
{
//Close comport first,then stop and dispose slave.
timer.Stop();
isReconnect = false;
modbus_Timer.Enabled = false;
btOpenCOM.Enabled = true;
btCloseCOM.Enabled = false;
Task.Run(async () => { await mqttClient.DisconnectAsync(); });
comPort.Close();
totxt.Log(DateTime.Now.ToString() + " =>Disconnect " + comPort.PortName);
}
} }
......
namespace ModbusRTU_Master
{
partial class frmInputValue
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtValue = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.button9 = new System.Windows.Forms.Button();
this.button10 = new System.Windows.Forms.Button();
this.btcommon = new System.Windows.Forms.Button();
this.btdel = new System.Windows.Forms.Button();
this.btMinus = new System.Windows.Forms.Button();
this.btPlus = new System.Windows.Forms.Button();
this.btClr = new System.Windows.Forms.Button();
this.btnok = new System.Windows.Forms.Button();
this.btncancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// txtValue
//
this.txtValue.Location = new System.Drawing.Point(22, 15);
this.txtValue.Margin = new System.Windows.Forms.Padding(5, 6, 5, 6);
this.txtValue.Name = "txtValue";
this.txtValue.Size = new System.Drawing.Size(291, 30);
this.txtValue.TabIndex = 0;
this.txtValue.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// button1
//
this.button1.Location = new System.Drawing.Point(22, 200);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(46, 41);
this.button1.TabIndex = 1;
this.button1.Tag = "0";
this.button1.Text = "0";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.Number_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(22, 153);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(46, 41);
this.button2.TabIndex = 2;
this.button2.Tag = "1";
this.button2.Text = "1";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.Number_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(74, 153);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(46, 41);
this.button3.TabIndex = 3;
this.button3.Tag = "2";
this.button3.Text = "2";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.Number_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(126, 153);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(46, 41);
this.button4.TabIndex = 4;
this.button4.Tag = "3";
this.button4.Text = "3";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.Number_Click);
//
// button5
//
this.button5.Location = new System.Drawing.Point(22, 106);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(46, 41);
this.button5.TabIndex = 5;
this.button5.Tag = "4";
this.button5.Text = "4";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.Number_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(74, 106);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(46, 41);
this.button6.TabIndex = 6;
this.button6.Tag = "5";
this.button6.Text = "5";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.Number_Click);
//
// button7
//
this.button7.Location = new System.Drawing.Point(126, 106);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(46, 41);
this.button7.TabIndex = 7;
this.button7.Tag = "6";
this.button7.Text = "6";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.Number_Click);
//
// button8
//
this.button8.Location = new System.Drawing.Point(22, 59);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(46, 41);
this.button8.TabIndex = 8;
this.button8.Tag = "7";
this.button8.Text = "7";
this.button8.UseVisualStyleBackColor = true;
this.button8.Click += new System.EventHandler(this.Number_Click);
//
// button9
//
this.button9.Location = new System.Drawing.Point(74, 59);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(46, 41);
this.button9.TabIndex = 9;
this.button9.Tag = "8";
this.button9.Text = "8";
this.button9.UseVisualStyleBackColor = true;
this.button9.Click += new System.EventHandler(this.Number_Click);
//
// button10
//
this.button10.Location = new System.Drawing.Point(126, 59);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(46, 41);
this.button10.TabIndex = 10;
this.button10.Tag = "9";
this.button10.Text = "9";
this.button10.UseVisualStyleBackColor = true;
this.button10.Click += new System.EventHandler(this.Number_Click);
//
// btcommon
//
this.btcommon.Location = new System.Drawing.Point(74, 200);
this.btcommon.Name = "btcommon";
this.btcommon.Size = new System.Drawing.Size(46, 41);
this.btcommon.TabIndex = 11;
this.btcommon.Tag = "";
this.btcommon.Text = ".";
this.btcommon.UseVisualStyleBackColor = true;
this.btcommon.Click += new System.EventHandler(this.btcommon_Click);
//
// btdel
//
this.btdel.Location = new System.Drawing.Point(126, 200);
this.btdel.Name = "btdel";
this.btdel.Size = new System.Drawing.Size(46, 41);
this.btdel.TabIndex = 12;
this.btdel.Tag = "";
this.btdel.Text = "<";
this.btdel.UseVisualStyleBackColor = true;
this.btdel.Click += new System.EventHandler(this.btdel_Click);
//
// btMinus
//
this.btMinus.Location = new System.Drawing.Point(178, 59);
this.btMinus.Name = "btMinus";
this.btMinus.Size = new System.Drawing.Size(46, 41);
this.btMinus.TabIndex = 13;
this.btMinus.Tag = "";
this.btMinus.Text = "-";
this.btMinus.UseVisualStyleBackColor = true;
this.btMinus.Click += new System.EventHandler(this.btMinus_Click);
//
// btPlus
//
this.btPlus.Location = new System.Drawing.Point(178, 106);
this.btPlus.Name = "btPlus";
this.btPlus.Size = new System.Drawing.Size(46, 41);
this.btPlus.TabIndex = 14;
this.btPlus.Tag = "";
this.btPlus.Text = "+";
this.btPlus.UseVisualStyleBackColor = true;
this.btPlus.Click += new System.EventHandler(this.btPlus_Click);
//
// btClr
//
this.btClr.Location = new System.Drawing.Point(178, 153);
this.btClr.Name = "btClr";
this.btClr.Size = new System.Drawing.Size(46, 41);
this.btClr.TabIndex = 15;
this.btClr.Tag = "";
this.btClr.Text = "C";
this.btClr.UseVisualStyleBackColor = true;
this.btClr.Click += new System.EventHandler(this.btClr_Click);
//
// btnok
//
this.btnok.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnok.Location = new System.Drawing.Point(230, 59);
this.btnok.Name = "btnok";
this.btnok.Size = new System.Drawing.Size(83, 41);
this.btnok.TabIndex = 16;
this.btnok.Tag = "";
this.btnok.Text = "OK";
this.btnok.UseVisualStyleBackColor = true;
//
// btncancel
//
this.btncancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btncancel.Location = new System.Drawing.Point(230, 106);
this.btncancel.Name = "btncancel";
this.btncancel.Size = new System.Drawing.Size(83, 41);
this.btncancel.TabIndex = 17;
this.btncancel.Tag = "";
this.btncancel.Text = "Cancel";
this.btncancel.UseVisualStyleBackColor = true;
//
// frmInputValue
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 23F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(333, 257);
this.Controls.Add(this.btncancel);
this.Controls.Add(this.btnok);
this.Controls.Add(this.btClr);
this.Controls.Add(this.btPlus);
this.Controls.Add(this.btMinus);
this.Controls.Add(this.btdel);
this.Controls.Add(this.btcommon);
this.Controls.Add(this.button10);
this.Controls.Add(this.button9);
this.Controls.Add(this.button8);
this.Controls.Add(this.button7);
this.Controls.Add(this.button6);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.txtValue);
this.Font = new System.Drawing.Font("Tahoma", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Margin = new System.Windows.Forms.Padding(5, 6, 5, 6);
this.Name = "frmInputValue";
this.Text = "InputValue";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtValue;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.Button btcommon;
private System.Windows.Forms.Button btdel;
private System.Windows.Forms.Button btMinus;
private System.Windows.Forms.Button btPlus;
private System.Windows.Forms.Button btClr;
private System.Windows.Forms.Button btnok;
private System.Windows.Forms.Button btncancel;
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ModbusRTU_Master
{
public partial class frmInputValue : Form
{
public frmInputValue()
{
InitializeComponent();
}
public double Value
{
set
{
this.txtValue.Text = value.ToString();
}
get { return Convert_To_Double(this.txtValue.Text); }
}
public string StringValue
{
set
{
this.txtValue.Text = value;
}
get
{
return this.txtValue.Text;
}
}
private double Convert_To_Double(string sKey)
{
if (sKey == "")
sKey = "0";
return double.Parse(sKey);
}
private void Number_Click(object sender, EventArgs e)
{
txtValue.Text = txtValue.Text + ((Button)sender).Tag;
}
private void btcommon_Click(object sender, EventArgs e)
{
if (txtValue.Text.IndexOf(".") < 0)
txtValue.Text += ".";
}
private void btdel_Click(object sender, EventArgs e)
{
txtValue.Text = txtValue.Text.Substring(0, txtValue.Text.Length - 1);
}
private void btClr_Click(object sender, EventArgs e)
{
txtValue.Text = "";
}
private void btMinus_Click(object sender, EventArgs e)
{
if (Convert_To_Double(txtValue.Text) > 0)
{
txtValue.Text = (Convert_To_Double(txtValue.Text) * (-1)).ToString();
}
}
private void btPlus_Click(object sender, EventArgs e)
{
if (Convert_To_Double(txtValue.Text) < 0)
{
txtValue.Text = (Convert_To_Double(txtValue.Text) * (-1)).ToString();
}
}
}
}
\ No newline at end of file
<?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=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
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment