Commit ee7b5c46 authored by shaxuezheng's avatar shaxuezheng

增加控制部分

parent 819bd750
...@@ -37,7 +37,17 @@ namespace ModbusDemo.windows ...@@ -37,7 +37,17 @@ namespace ModbusDemo.windows
writer = new StreamWriter(fileStream); writer = new StreamWriter(fileStream);
} }
writer.WriteLine(DateTime.Now + ": " + info); writer.WriteLine(DateTime.Now + ": " + info);
}
catch (Exception e)
{
if (writer != null)
{
writer.Close();
writer.Dispose();
fileStream.Close();
fileStream.Dispose();
}
throw;
} }
finally finally
{ {
...@@ -49,6 +59,7 @@ namespace ModbusDemo.windows ...@@ -49,6 +59,7 @@ namespace ModbusDemo.windows
fileStream.Dispose(); fileStream.Dispose();
} }
} }
} }
public void CreateDirectory(string infoPath) public void CreateDirectory(string infoPath)
......
...@@ -3,7 +3,7 @@ using System.Collections.Generic; ...@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Collections;
namespace ModbusDemo namespace ModbusDemo
{ {
class startAddress class startAddress
...@@ -95,10 +95,44 @@ namespace ModbusDemo ...@@ -95,10 +95,44 @@ namespace ModbusDemo
} }
public List<Ss> ss { get; set; } public List<Ss> ss { get; set; }
} }
public class Ctrl2
{
public string taskId;
public void settaskId(string taskId)
{
this.taskId = taskId;
}
public string gettaskId()
{
return taskId;
}
public List<Sss> ss { get; set;}
}
public class Sss
{
public byte addr;
private Hashtable dn = new Hashtable();
public Hashtable op
{ get => dn; set => dn = value; }
public void setAddr(byte addr)
{
this.addr = addr;
}
public byte getAddr()
{
return addr;
}
}
public class Op public class Op
{ {
public int duration; public int duration;
public long startTime; public long startTime;
public int d0 public int d0
{ {
get => D0; get => D0;
...@@ -168,6 +202,7 @@ namespace ModbusDemo ...@@ -168,6 +202,7 @@ namespace ModbusDemo
{ {
public byte addr; public byte addr;
public Op op; public Op op;
public void setAddr(byte addr) public void setAddr(byte addr)
{ {
this.addr = addr; this.addr = addr;
...@@ -176,7 +211,6 @@ namespace ModbusDemo ...@@ -176,7 +211,6 @@ namespace ModbusDemo
{ {
return addr; return addr;
} }
public void setOp(Op op) public void setOp(Op op)
{ {
this.op = op; this.op = op;
...@@ -185,6 +219,5 @@ namespace ModbusDemo ...@@ -185,6 +219,5 @@ namespace ModbusDemo
{ {
return op; return op;
} }
} }
} }
...@@ -4,6 +4,7 @@ using System.Linq; ...@@ -4,6 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Timers; using System.Timers;
namespace ModbusDemo.windows namespace ModbusDemo.windows
{ {
class TransferPool class TransferPool
......
...@@ -19,6 +19,7 @@ using System.Diagnostics; ...@@ -19,6 +19,7 @@ using System.Diagnostics;
using ModbusDemo; using ModbusDemo;
using System.Timers; using System.Timers;
using ModbusDemo.application; using ModbusDemo.application;
using System.Collections;
namespace ModbusDemo namespace ModbusDemo
{ {
...@@ -40,7 +41,7 @@ namespace ModbusDemo ...@@ -40,7 +41,7 @@ namespace ModbusDemo
System.Timers.Timer MQTTTimer = new System.Timers.Timer(); System.Timers.Timer MQTTTimer = new System.Timers.Timer();
BackgroundWorker m_bgw0 = new BackgroundWorker(); BackgroundWorker m_bgw0 = new BackgroundWorker();
bool m_Isbgw0_CanContinueRun = true; bool m_Isbgw0_CanContinueRun = true;
bool State_enable = 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");
...@@ -96,13 +97,14 @@ namespace ModbusDemo ...@@ -96,13 +97,14 @@ namespace ModbusDemo
string mqttTopic; string mqttTopic;
string mqttSubscribeTopic; string mqttSubscribeTopic;
string mqttBackTopic; string mqttBackTopic;
string mqttSn= "20193261"; string mqttSn = "20193261";
string mqttData;//数据 string mqttData;//数据
string mqttData_Back;//数据 string mqttData_Back;//数据
private IMqttClient mqttClient = null; private IMqttClient mqttClient = null;
private bool isReconnect = true; private bool isReconnect = true;
ushort address; ushort address;
byte ID; byte ID;
int readyState;
bool[] DI = new bool[10]; bool[] DI = new bool[10];
bool[] DO = new bool[10]; bool[] DO = new bool[10];
...@@ -169,7 +171,39 @@ namespace ModbusDemo ...@@ -169,7 +171,39 @@ namespace ModbusDemo
{ {
bool OutputValue; bool OutputValue;
int Caution = 0; int Caution = 0;
bool[] StateValue = { };
int[] WOnOff = { 0 };
Modbus_ReadCoilsTask(out StateValue, SlaveAddress, 16, 6, out int signW);
WOnOff = state.IO(StateValue);
if (WOnOff[0] == 1)
{
if (startAddress == 18)
{
return;
}
else
{
Modbus_WriteSingleCoil(out OutputValue, SlaveAddress, startAddress, value, out Caution);
Modbus_WriteSingleCoil(out OutputValue, SlaveAddress, (ushort)(startAddress + 1), value, out Caution);
}
}
else if(WOnOff[2]==1)
{
if(startAddress==16)
{
return;
}
else
{
Modbus_WriteSingleCoil(out OutputValue, SlaveAddress, startAddress, value, out Caution); Modbus_WriteSingleCoil(out OutputValue, SlaveAddress, startAddress, value, out Caution);
Modbus_WriteSingleCoil(out OutputValue, SlaveAddress, (ushort)(startAddress + 1), value, out Caution);
}
}
else
{
Modbus_WriteSingleCoil(out OutputValue, SlaveAddress, startAddress, value, out Caution);
Modbus_WriteSingleCoil(out OutputValue, SlaveAddress, (ushort)(startAddress + 1), value, out Caution);
}
} }
public static byte[] getByte(bool[] array) public static byte[] getByte(bool[] array)
...@@ -234,7 +268,8 @@ namespace ModbusDemo ...@@ -234,7 +268,8 @@ namespace ModbusDemo
Console.WriteLine("已订阅[{topic}]主题{Environment.NewLine}"); Console.WriteLine("已订阅[{topic}]主题{Environment.NewLine}");
txtReceiveMessage.AppendText($"已订阅[{mqttSubscribeTopic}]主题{Environment.NewLine}"); txtReceiveMessage.AppendText($"已订阅[{mqttSubscribeTopic}]主题{Environment.NewLine}");
totxt.Log($"已订阅[{mqttSubscribeTopic}]主题{Environment.NewLine}"); //totxt.Log($"已订阅[{mqttSubscribeTopic}]主题{Environment.NewLine}");
//txtReceiveMessage.AppendText($"已订阅[{Data}]主题{Environment.NewLine}"); //txtReceiveMessage.AppendText($"已订阅[{Data}]主题{Environment.NewLine}");
}))); })));
} }
...@@ -262,6 +297,7 @@ namespace ModbusDemo ...@@ -262,6 +297,7 @@ namespace ModbusDemo
.WithClientId(mqttClientId) .WithClientId(mqttClientId)
.WithTcpServer(mqttIp, mqttPort) .WithTcpServer(mqttIp, mqttPort)
.WithCredentials(mqttUsername, mqttPwd) .WithCredentials(mqttUsername, mqttPwd)
//.WithTls()//服务器端没有启用加密协议,这里用tls的会提示协议异常 //.WithTls()//服务器端没有启用加密协议,这里用tls的会提示协议异常
.WithCleanSession() .WithCleanSession()
.Build(); .Build();
...@@ -274,7 +310,7 @@ namespace ModbusDemo ...@@ -274,7 +310,7 @@ namespace ModbusDemo
{ {
//txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); //txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
Console.WriteLine($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); Console.WriteLine($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
totxt.Log($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine); //totxt.Log($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
}))); })));
} }
...@@ -295,7 +331,7 @@ namespace ModbusDemo ...@@ -295,7 +331,7 @@ namespace ModbusDemo
{ {
txtReceiveMessage.Clear(); txtReceiveMessage.Clear();
txtReceiveMessage.AppendText("已连接到MQTT服务器!" + Environment.NewLine); txtReceiveMessage.AppendText("已连接到MQTT服务器!" + Environment.NewLine);
totxt.Log("已连接到MQTT服务器!" + Environment.NewLine); //totxt.Log("已连接到MQTT服务器!" + Environment.NewLine);
//Console.WriteLine("已连接到MQTT服务器!" + Environment.NewLine); //Console.WriteLine("已连接到MQTT服务器!" + Environment.NewLine);
}))); })));
} }
...@@ -308,9 +344,9 @@ namespace ModbusDemo ...@@ -308,9 +344,9 @@ namespace ModbusDemo
DateTime curTime = new DateTime(); DateTime curTime = new DateTime();
curTime = DateTime.UtcNow; curTime = DateTime.UtcNow;
txtReceiveMessage.AppendText($">> [{curTime.ToLongTimeString()}]"); txtReceiveMessage.AppendText($">> [{curTime.ToLongTimeString()}]");
totxt.Log($">> [{curTime.ToLongTimeString()}]"); //totxt.Log($">> [{curTime.ToLongTimeString()}]");
txtReceiveMessage.AppendText("已断开MQTT连接!" + Environment.NewLine); txtReceiveMessage.AppendText("已断开MQTT连接!" + Environment.NewLine);
totxt.Log("已断开MQTT连接!" + Environment.NewLine); //totxt.Log("已断开MQTT连接!" + Environment.NewLine);
//Console.WriteLine("已断开MQTT连接!" + Environment.NewLine); //Console.WriteLine("已断开MQTT连接!" + Environment.NewLine);
}))); })));
...@@ -321,7 +357,7 @@ namespace ModbusDemo ...@@ -321,7 +357,7 @@ namespace ModbusDemo
Invoke((new Action(() => Invoke((new Action(() =>
{ {
txtReceiveMessage.AppendText("正在尝试重新连接" + Environment.NewLine); txtReceiveMessage.AppendText("正在尝试重新连接" + Environment.NewLine);
totxt.Log("正在尝试重新连接" + Environment.NewLine); //totxt.Log("正在尝试重新连接" + Environment.NewLine);
//Console.WriteLine("正在尝试重新连接" + Environment.NewLine); //Console.WriteLine("正在尝试重新连接" + Environment.NewLine);
...@@ -344,7 +380,7 @@ namespace ModbusDemo ...@@ -344,7 +380,7 @@ namespace ModbusDemo
catch catch
{ {
txtReceiveMessage.AppendText("### RECONNECTING FAILED ###" + Environment.NewLine); txtReceiveMessage.AppendText("### RECONNECTING FAILED ###" + Environment.NewLine);
totxt.Log("### RECONNECTING FAILED ###" + Environment.NewLine); //totxt.Log("### RECONNECTING FAILED ###" + Environment.NewLine);
//Console.WriteLine("### RECONNECTING FAILED ###" + Environment.NewLine); //Console.WriteLine("### RECONNECTING FAILED ###" + Environment.NewLine);
} }
}))); })));
...@@ -354,7 +390,7 @@ namespace ModbusDemo ...@@ -354,7 +390,7 @@ namespace ModbusDemo
Invoke((new Action(() => Invoke((new Action(() =>
{ {
txtReceiveMessage.AppendText("已下线!" + Environment.NewLine); txtReceiveMessage.AppendText("已下线!" + Environment.NewLine);
totxt.Log("已下线!" + Environment.NewLine); //totxt.Log("已下线!" + Environment.NewLine);
//Console.WriteLine("已下线!" + Environment.NewLine); //Console.WriteLine("已下线!" + Environment.NewLine);
}))); })));
} }
...@@ -366,31 +402,56 @@ namespace ModbusDemo ...@@ -366,31 +402,56 @@ namespace ModbusDemo
{ {
//收到的消息啦 //收到的消息啦
txtReceiveMessage.AppendText($">> {"### RECEIVED APPLICATION MESSAGE ###"}{Environment.NewLine}"); txtReceiveMessage.AppendText($">> {"### RECEIVED APPLICATION MESSAGE ###"}{Environment.NewLine}");
totxt.Log($">> {"### RECEIVED APPLICATION MESSAGE ###"}{Environment.NewLine}"); //totxt.Log($">> {"### RECEIVED APPLICATION MESSAGE ###"}{Environment.NewLine}");
}))); })));
Invoke((new Action(() => Invoke((new Action(() =>
{ {
//我的订阅主题是。。。。。 //我的订阅主题是。。。。。
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(async () => Invoke((new Action(async () =>
{ {
bool on_off = true; bool on_off = true;
string passageway;
//消息的内容 //消息的内容
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));
Ctrl ctrl = JsonConvert.DeserializeObject<Ctrl>(Encoding.UTF8.GetString(e.ApplicationMessage.Payload)); Ctrl ctrl = JsonConvert.DeserializeObject<Ctrl>(Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
Ctrl ctrl_Back = new Ctrl(); Ctrl ctrl_Back = new Ctrl();
Ctrl2 ctrl2 = new Ctrl2();
List<Sss> ssses = new List<Sss>();
ssses.Add(new Sss());
List<Ss> ctrl_Back_ss = new List<Ss>(); List<Ss> ctrl_Back_ss = new List<Ss>();
ctrl_Back_ss.Add(new Ss()); ctrl_Back_ss.Add(new Ss());
string txt = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); string txt = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
for (int i = 0; i < 6; i++) for (int i = 0; i < 6; i++)
{ {
if (txt.Contains("d"+i)) if (txt.Contains("d" + i))
{ {
address =(ushort) (16 + i); address = (ushort)(16 + i);
ctrl2.taskId= ctrl.taskId.ToString();
passageway = "d" + i;
if (passageway=="d0")
{
readyState = ctrl.ss[0].op.d0;
}
if(passageway =="d2")
{
readyState = ctrl.ss[0].op.d2;
}
if (passageway == "d4")
{
readyState = ctrl.ss[0].op.d4;
}
ssses[0].addr = ctrl.ss[0].getAddr();
ssses[0].op.Add("duration", ctrl.ss[0].op.getDuration());
ssses[0].op.Add("startTime", ctrl.ss[0].op.getStartTime());
ssses[0].op.Add(passageway, readyState);
ssses[0].op.Add("ts",long.Parse(GetTimeStamp()));
ctrl2.ss = ssses;
} }
if (ctrl.ss[0].op.d1 == 1 || if (ctrl.ss[0].op.d1 == 1 ||
ctrl.ss[0].op.d0 == 1 || ctrl.ss[0].op.d0 == 1 ||
...@@ -404,56 +465,69 @@ namespace ModbusDemo ...@@ -404,56 +465,69 @@ namespace ModbusDemo
else else
on_off = false; on_off = false;
} }
control(ctrl.ss[0].getAddr(), address, on_off);//根据下发确定控制通道
ID = ctrl.ss[0].getAddr(); ID = ctrl.ss[0].getAddr();
Modbus_polling(); Modbus_polling();
ctrl_Back.taskId = ctrl.taskId.ToString(); ctrl_Back.taskId = ctrl.taskId.ToString();
ctrl_Back_ss[0] = ctrl.ss[0]; ctrl_Back_ss[0] = ctrl.ss[0];
ctrl_Back.ss = ctrl_Back_ss;
ctrl_Back.ss[0].op.getStartTime(); //ctrl_Back.ss[0].op.setStartTime(long.Parse(GetTimeStamp()));
if(ctrl.ss[0].op.getStartTime() !=0)
if (ctrl.ss[0].op.getStartTime() != 0)
{ {
Thread objThread = new Thread(new ThreadStart(delegate Thread objThread = new Thread(new ThreadStart(async delegate
{ {
ThreadMethodTxtAsync(Convert.ToInt32(ctrl.ss[0].op.getDuration())); await ThreadMethodTxtAsync(Convert.ToInt32(ctrl.ss[0].op.getDuration()));
})); }));
objThread.Start(); objThread.Start();
} }
mqttData_Back = JsonConvert.SerializeObject(ctrl_Back);
if (State_enable == true)
{
control(ctrl.ss[0].getAddr(), address, on_off);//根据下发确定控制通道
mqttData_Back = JsonConvert.SerializeObject(ctrl2);
await Publish(); await Publish();
await Back(); await Back();
}
//订阅内容部分jSON 解析转对象 根据modbusID或者设备类型处理设备消息 //订阅内容部分jSON 解析转对象 根据modbusID或者设备类型处理设备消息
//解析控制部分 //解析控制部分
}))); })));
Invoke((new Action(() => Invoke((new Action(() =>
{ {
txtReceiveMessage.AppendText($">> QoS = {e.ApplicationMessage.QualityOfServiceLevel}{Environment.NewLine}"); txtReceiveMessage.AppendText($">> QoS = {e.ApplicationMessage.QualityOfServiceLevel}{Environment.NewLine}");
totxt.Log($">> QoS = {e.ApplicationMessage.QualityOfServiceLevel}{Environment.NewLine}"); //totxt.Log($">> QoS = {e.ApplicationMessage.QualityOfServiceLevel}{Environment.NewLine}");
}))); })));
Invoke((new Action(() => Invoke((new Action(() =>
{ {
txtReceiveMessage.AppendText($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}"); txtReceiveMessage.AppendText($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}");
totxt.Log($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}"); //totxt.Log($">> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}");
}))); })));
} }
//此为在非创建线程中的调用方法,其实是使用TextBox的Invoke方法。
public async Task ThreadMethodTxtAsync(int n) public async Task ThreadMethodTxtAsync(int n)
{ {
this.BeginInvoke(updateTxt, "线程开始执行,执行" + n + "次,每一秒执行一次"); this.BeginInvoke(updateTxt, "线程开始执行,执行" + n + "次,每一秒执行一次");
int time = n * 60; int time = n * 60;
for (int i = 0; i < time; i++) for (int i = 0; i < time; i++)
{ {
State_enable = false;
this.BeginInvoke(updateTxt, i.ToString()); this.BeginInvoke(updateTxt, i.ToString());
//一秒 执行一次 //一秒 执行一次
Thread.Sleep(1000); Thread.Sleep(1000);
if (i> time - 2)
if (i > time - 2)
{ {
control(ID, address, false);//根据下发确定控制通道 control(ID, address, false);//根据下发确定控制通道
control(ID, (ushort)(address+1), false);//根据下发确定控制通道
Modbus_polling(); Modbus_polling();
await Publish(); await Publish();
time = 0; time = 0;
n = 0; n = 0;
State_enable = true;
} }
} }
this.BeginInvoke(updateTxt, "线程结束"); this.BeginInvoke(updateTxt, "线程结束");
...@@ -470,13 +544,13 @@ namespace ModbusDemo ...@@ -470,13 +544,13 @@ namespace ModbusDemo
timer.Elapsed += (o, a) => timer.Elapsed += (o, a) =>
{ {
SetData(); SetData();
ShowMessage(string.Format("更新时间:" + DateTime.Now)); //ShowMessage(string.Format("更新时间:" + DateTime.Now));
}; };
} }
private void Sendout() private void Sendout()
{ {
Control.CheckForIllegalCrossThreadCalls = false; Control.CheckForIllegalCrossThreadCalls = false;
MQTTTimer.Interval = 12000; MQTTTimer.Interval = 7000;
MQTTTimer.Enabled = true; MQTTTimer.Enabled = true;
MQTTTimer.AutoReset = true;//设置是执行一次(false)还是一直执行(true); MQTTTimer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
MQTTTimer.Start(); MQTTTimer.Start();
...@@ -485,12 +559,12 @@ namespace ModbusDemo ...@@ -485,12 +559,12 @@ namespace ModbusDemo
try try
{ {
await Publish(); await Publish();
totxt.Log(mqttData + Environment.NewLine + "\n"); //totxt.Log(mqttData + Environment.NewLine + "\n");
} }
catch (Exception ex) catch (Exception ex)
{ {
ShowMessage(string.Format("更新时间:" + DateTime.Now)); //ShowMessage(string.Format("更新时间:" + DateTime.Now));
totxt.Log(ex + "," + Environment.NewLine + "\n"); //totxt.Log(ex + "," + Environment.NewLine + "\n");
return; return;
} }
}; };
...@@ -785,20 +859,22 @@ namespace ModbusDemo ...@@ -785,20 +859,22 @@ namespace ModbusDemo
int[] EOnOff = { 0 }; int[] EOnOff = { 0 };
int[] SOnOff = { 0 }; int[] SOnOff = { 0 };
int[] WOnOff = { 0 }; int[] WOnOff = { 0 };
Modbus_ReadHoldingRegistersTask(out temperature, 3, 0, 4, out int signT); //修改前1 Modbus_ReadHoldingRegistersTask(out temperature, 1, 0, 4, out int signT);
Modbus_ReadHoldingRegistersTask(out type, 3, 10, 4, out int sign); Modbus_ReadHoldingRegistersTask(out type, 1, 10, 4, out int sign);
//Modbus_ReadHoldingRegistersTask(out register, 1, 0, 8, out int signr); //修改前3 string time_1 = GetTimeStamp();
//Modbus_ReadHoldingRegistersTask(out Inputtype, 1, 10, 8, out int signI); Modbus_ReadHoldingRegistersTask(out register, 3, 0, 8, out int signr);
//Modbus_ReadHoldingRegistersTask(out registerN, 6, 0, 8, out int signre); Modbus_ReadHoldingRegistersTask(out Inputtype, 3, 10, 8, out int signI);
//Modbus_ReadHoldingRegistersTask(out InputtypeN, 6, 10, 8, out int signIn); string time_2 = GetTimeStamp();
//Modbus_ReadCoilsTask(out EIO, 5, 16, 6,out int signE); Modbus_ReadHoldingRegistersTask(out registerN, 6, 0, 8, out int signre);
//Modbus_ReadCoilsTask(out SIO, 8, 16, 6, out int signS); Modbus_ReadHoldingRegistersTask(out InputtypeN, 6, 10, 8, out int signIn);
Modbus_ReadCoilsTask(out WIO, 4, 16, 6, out int signW); string time_3 = GetTimeStamp();
Modbus_ReadCoilsTask(out EIO, 5, 16, 6, out int signE);
Modbus_ReadCoilsTask(out SIO, 8, 16, 6, out int signS);
//if (sign == -1 || signT ==-1||signr==-1||signI == -1|| signre==-1|| signIn==-1||signE==-1||signS==-1|| signW ==-1) Modbus_ReadCoilsTask(out WIO, 4, 16, 6, out int signW);
if (sign == -1 || signT == -1 || signW == -1) if (sign == -1 || signT ==-1|| signW ==-1 || signr == -1 || signI == -1 || signre == -1 || signIn == -1 || signE == -1 || signS == -1)
{ {
vs = null; vs = null;
type = null; type = null;
EastTemperature = 0; EastTemperature = 0;
...@@ -809,37 +885,37 @@ namespace ModbusDemo ...@@ -809,37 +885,37 @@ namespace ModbusDemo
{ {
vs = rtd.RtdValue(temperature, type); vs = rtd.RtdValue(temperature, type);
EastTemperature = float.Parse(vs[0]); EastTemperature = float.Parse(vs[0]);
//s = Analog.Value(register, Inputtype); s = Analog.Value(register, Inputtype);
//Easternwaterlevel = (float.Parse(s[0]) - 4) / 16 * 6; Easternwaterlevel = (float.Parse(s[0]) - 4) / 16 * 6;
//s6 = Analog.Value(registerN, InputtypeN); s6 = Analog.Value(registerN, InputtypeN);
//WestWaterLevel = (float.Parse(s6[0]) - 4) / 16 * 6; WestWaterLevel = (float.Parse(s6[0]) - 4) / 16 * 6;
//label3.Text = EastTemperature.ToString(); label3.Text = EastTemperature.ToString();
//label4.Text = Easternwaterlevel.ToString(); label4.Text = Easternwaterlevel.ToString();
//EOnOff = state.IO(EIO);////东中转池 EOnOff = state.IO(EIO);////东中转池
//SOnOff = state.IO(SIO);////东南北水 SOnOff = state.IO(SIO);////西中转池
WOnOff = state.IO(WIO); ////西中转池 WOnOff = state.IO(WIO); ////东南北水
} }
WTDR14P x = new WTDR14P("1", EastTemperature, 0, 0, 0, GetTimeStamp()); WTDR14P x = new WTDR14P("1", EastTemperature, 0, 0, 0, time_1);
//WTDR18X p = new WTDR18X("3", Easternwaterlevel, 0, 0, 0, 0, 0, 0, 0, GetTimeStamp()); WTDR18X p = new WTDR18X("3", Easternwaterlevel, 0, 0, 0, 0, 0, 0, 0, time_2);
//WTDR18X q = new WTDR18X("6", WestWaterLevel, 0, 0, 0, 0, 0, 0, 0, GetTimeStamp()); WTDR18X q = new WTDR18X("6", WestWaterLevel, 0, 0, 0, 0, 0, 0, 0, time_3);
//东搅拌 //东搅拌
//WTDR66C EastStir = new WTDR66C("5", EOnOff[0], EOnOff[1], EOnOff[2], EOnOff[3], EOnOff[4], EOnOff[5], 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()); WTDR66C WestStir = new WTDR66C("4", WOnOff[0], WOnOff[1], WOnOff[2], WOnOff[3], WOnOff[4], WOnOff[5], GetTimeStamp());
//西搅拌
WTDR66C SouthWater = new WTDR66C("8", SOnOff[0], SOnOff[1], SOnOff[2], SOnOff[3], SOnOff[4], SOnOff[5], GetTimeStamp());
mqttData = "[" + mqttData = "[" +
JsonConvert.SerializeObject(x) + "," + JsonConvert.SerializeObject(x) + "," +
//JsonConvert.SerializeObject(p)+"," + JsonConvert.SerializeObject(p) + "," +
//JsonConvert.SerializeObject(q) +","+ JsonConvert.SerializeObject(q) + "," +
//JsonConvert.SerializeObject(EastStir)+","+ JsonConvert.SerializeObject(EastStir) + "," +
// JsonConvert.SerializeObject(WestStir) + "," + JsonConvert.SerializeObject(WestStir) + "," +
JsonConvert.SerializeObject(WestStir) JsonConvert.SerializeObject(SouthWater)
+ "]"; + "]";
...@@ -1530,17 +1606,17 @@ namespace ModbusDemo ...@@ -1530,17 +1606,17 @@ namespace ModbusDemo
isReconnect = true; isReconnect = true;
SetMqtt(); SetMqtt();
Thread t = new Thread(new ThreadStart(GetData)); Thread t = new Thread(new ThreadStart(GetData));
t.IsBackground = true; t.IsBackground = false;
t.Start(); t.Start();
Thread MQTT_thread = new Thread(new ThreadStart(Sendout)); Thread MQTT_thread = new Thread(new ThreadStart(Sendout));
MQTT_thread.IsBackground = true; MQTT_thread.IsBackground = true;
MQTT_thread.Start(); MQTT_thread.Start();
Task.Run(async () => { await ConnectMqttServerAsync(); }); Task.Run(async () => { await ConnectMqttServerAsync(); });
master = ModbusSerialMaster.CreateRtu(comPort); master = ModbusSerialMaster.CreateRtu(comPort);
master.Transport.Retries = 6; //重试次数 master.Transport.Retries = 2; //重试次数
master.Transport.ReadTimeout = 1500; //读取串口数据超时时间(ms) master.Transport.ReadTimeout = 1500; //读取串口数据超时时间(ms)
master.Transport.WriteTimeout = 1500;//写入串口数据超时时间(ms) master.Transport.WriteTimeout = 1500;//写入串口数据超时时间(ms)
master.Transport.WaitToRetryMilliseconds = 500;//重试间隔(ms) master.Transport.WaitToRetryMilliseconds = 100;//重试间隔(ms)
modbus_Timer.Enabled = true; modbus_Timer.Enabled = true;
btOpenCOM.Enabled = false; btOpenCOM.Enabled = false;
btCloseCOM.Enabled = true; btCloseCOM.Enabled = true;
......
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