在一个C#控制台应用程序中,Web应用主机端利用HostLink通信规约定时向PLC下位机发送TS和RD命令。Web主机端根据下位机应答的HostLink数据报文刷新实时监测窗体
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using PROTOCOLINTERPRETATIONCOMLib;
namespace dfConApp
{
class Program
{
//声明COM组件
private static ProtocolInterpretation myCommand_ATL = new ProtocolInterpretation();
private static IProtocolInterpretation myCommand = (IProtocolInterpretation)myCommand_ATL;
//定义信号量
private static Semaphore ccout, ccin;
//aa存储报文
private string aa;
//服务器与客户端连接状态status,指令起始终止位置st,en
private int status,st,en;
static void Main(string[] args)
{
Program pro = new Program();
//信号量初始化
//打印信息报文信号量
ccout = new Semaphore(0, 1);
//接收信息报文信号量
ccin = new Semaphore(1, 1);
//定义初始化线程
//打印信息报文线程
Thread Ccout = new Thread(pro.ccRead);
//接收信息报文线程
Thread Ccin = new Thread(pro.ccWrite);
Console.WriteLine("请分别输入要获取的字段位置数:");
pro.st = int.Parse(Console.ReadLine());
pro.en = int.Parse(Console.ReadLine());
//检测指令范围超出异常
if (pro.st >=1 && pro.st <= 11 && pro.st+pro.en<12)
{
Ccout.Start();
Ccin.Start();
}
else
{
Console.WriteLine("获取范围超出异常!!");
}
}
//十六机制转十进制
public string Hex2Ten(string hex)
{
int ten = 0;
for (int i = 0, j = hex.Length - 1; i < hex.Length; i++)
{
ten += HexChar2Value(hex.Substring(i, 1)) * ((int)Math.Pow(16, j));
j--;
}
return ten.ToString();
}
public int HexChar2Value(string hexChar)
{
switch (hexChar)
{
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
return Convert.ToInt32(hexChar);
case "a":
case "A":
return 10;
case "b":
case "B":
return 11;
case "c":
case "C":
return 12;
case "d":
case "D":
return 13;
case "e":
case "E":
return 14;
case "f":
case "F":
return 15;
default:
return 0;
}
}
//获取下位机的指令
public void ccRead()
{
int DeviceNo = 1;
while (true)
{
ccin.WaitOne();
status = myCommand.TestDevice(DeviceNo);
if (status == 1)
{
Console.WriteLine("设备连接正常");
myCommand.ReadDMValue(DeviceNo, out aa, out status); //DateTime.Now.ToString();
}
else
{
Console.WriteLine("设备故障!!");
}
Console.WriteLine("---------------");
Thread.Sleep(500);
ccout.Release();
}
}
//向控制台输出,打印
public void ccWrite()
{
String[] str = { "卷绕速度SET:", "分SET:", "加速时间:", "减速时间:", "空桶直径xx.x:", "振幅:", "阶跃:", "加速:", "减速:", "满筒超率:", "空筒超位率:" };
while (true)
{
ccout.WaitOne();
if (status == 1)
{
for (int i = st; i <= en; i++)
{
Console.WriteLine(str[i] + Hex2Ten(aa.Substring((i - 1), 4)));
}
}
else
{
for (int i = st; i <= en; i++)
{
Console.WriteLine(str[i] + " ");
}
}
Console.WriteLine("===============\n");
Thread.Sleep(500);
ccin.Release();
}
}
}
}