在一個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();
}
}
}
}