using System;
using System.Threading;
using Matrox.MatroxImagingLibrary;
using McomCclinkSlave;
namespace MAppStart
{
class Program
{
const int _toPLCDataRegister = 0;
const int _fromPLCDataRegister = 0;
const int _fromPLCTriggerFlag = 0;
const int _fromPLCAcknowledgeFlag = 1;
const int _toPLCDataReadyFlag = 0;
static ushort _internalProcessingValue = 0;
static void Main(string[] args)
{
MIL_ID _milApplication = MIL.M_NULL;
MIL_ID _milSystem = MIL.M_NULL;
MIL_ID _milCom = MIL.M_NULL;
ushort 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_CCLINK, "M_DEFAULT", MIL.M_DEFAULT, MIL.M_DEFAULT, ref _milCom);
var slave = new CclinkSlave(_milCom);
if (slave.IsSlaveStopped)
{
Console.Write("Slave stopped. Press <Enter> to end.\n");
goto abort;
}
Console.Write("Press <Enter> to end.\n");
slave.ClearFlag(deviceNumber: _toPLCDataReadyFlag);
slave.WriteRegister(deviceNumber: _toPLCDataRegister, value: 0);
while (!Console.KeyAvailable)
{
if (!WaitForTriggerFromPLC(slave))
{
processingResult = DoProcessing();
WriteResultToPLC(slave, processingResult);
}
}
slave.ClearFlag(deviceNumber: _toPLCDataReadyFlag);
slave.WriteRegister(deviceNumber: _toPLCDataRegister, value: 0);
abort:
MIL.McomFree(_milCom);
MIL.MappFreeDefault(_milApplication, _milSystem, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL);
}
static bool WaitForTriggerFromPLC(CclinkSlave slave)
{
bool _KeyHit;
bool _isTriggerSet = false;
Console.Write("Waiting for trigger from PLC!\n");
do
{
_isTriggerSet = slave.ReadFlag(deviceNumber: _fromPLCTriggerFlag);
Thread.Sleep(10);
_KeyHit = Console.KeyAvailable;
} while (_isTriggerSet == false && !_KeyHit);
if (!_KeyHit)
Console.Write("Received Trigger!\n");
return _KeyHit;
}
static ushort DoProcessing()
{
Console.Write("Computing new data value\n");
_internalProcessingValue++;
return _internalProcessingValue;
}
static void WriteResultToPLC(CclinkSlave slave, ushort result)
{
bool _KeyHit;
bool _isResultRead = false;
ushort valueFromPLC = 0;
slave.WriteRegister(deviceNumber: _toPLCDataRegister, value: result);
slave.SetFlag(deviceNumber: _toPLCDataReadyFlag);
Console.Write("Waiting for PLC acknowledge!\n");
do
{
_isResultRead = slave.ReadFlag(deviceNumber: _fromPLCAcknowledgeFlag);
Thread.Sleep(10);
_KeyHit = Console.KeyAvailable;
} while (_isResultRead == false && !_KeyHit);
if (_KeyHit)
{
valueFromPLC = slave.ReadRegister(deviceNumber: _fromPLCDataRegister);
Console.Write(string.Format("Received result ACK! Value:{0} CopyBack:{1}\n", result, valueFromPLC));
slave.ClearFlag(deviceNumber: _toPLCDataReadyFlag);
}
}
}
}