using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Matrox.MatroxImagingLibrary;
using System.Runtime.InteropServices;
namespace MAppStart
{
class Program
{
static MIL_ID MilApplication = MIL.M_NULL;
static MIL_ID MilSystem = MIL.M_NULL;
static MIL_ID MilCom = MIL.M_NULL;
static byte Trigger;
static byte ResultACK;
static byte value = 0;
static void Main(string[] args)
{
byte processingResult;
MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL);
MIL.McomAlloc(MilSystem, MIL.M_COM_PROTOCOL_MODBUS, "M_DEFAULT", MIL.M_DEFAULT, MIL.M_DEFAULT, ref MilCom);
Console.Write("Waiting for PLC trigger to happen.\nPress <Enter> to end.\n");
SetInitialStatus();
while (!Console.KeyAvailable)
{
if (!WaitForTriggerFromPLC())
{
processingResult = DoProcessing();
WriteResultToPLC(processingResult);
}
}
SetInitialStatus();
MIL.McomFree(MilCom);
MIL.MappFreeDefault(MilApplication, MilSystem, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL);
}
static void WriteStatus(byte triggerACK, byte resultReady, byte resultValue)
{
byte[] status = new byte[2];
status[0] = (byte)(((resultReady & 0x01) << 1) | (triggerACK & 0x01));
status[1] = resultValue;
MIL.McomWrite(MilCom, MIL.M_INPUT_REGISTER, 0, 1, status);
}
static void ReadControl(ref byte result)
{
byte[] control = new byte[2];
MIL.McomRead(MilCom, MIL.M_HOLDING_REGISTER, 0, 1, control);
Trigger = (byte)(control[0] & 0x1);
ResultACK = (byte)((control[0] & 0x2) >> 1);
result = control[1];
}
static void SetInitialStatus()
{
WriteStatus(0, 0, 0);
}
static bool WaitForTriggerFromPLC()
{
bool KeyHit;
byte ResultValue = 0;
do
{
ReadControl(ref ResultValue);
Thread.Sleep(10);
KeyHit = Console.KeyAvailable;
} while (Trigger == 0 && !KeyHit);
if (!KeyHit)
{
Console.Write("Received Trigger!\n");
WriteStatus(1, 0, 0);
}
return KeyHit;
}
static byte DoProcessing()
{
value++;
return value;
}
static void WriteResultToPLC(byte result)
{
bool KeyHit;
byte ResultCopy = 0;
WriteStatus(0, 1, result);
do
{
ReadControl(ref ResultCopy);
Thread.Sleep(10);
KeyHit = Console.KeyAvailable;
} while (ResultACK == 0 && !KeyHit);
if (!KeyHit)
{
Console.Write(String.Format("Received result ACK! Value:{0} Copy:{1}\n", value, ResultCopy));
WriteStatus(0, 0, ResultCopy);
}
}
}
}