tbf/TestBenchFramework/BenchControl/Modbus/QuidoRS/QuidoRS.cs

116 lines
3.2 KiB
C#

///
/// Copyright (c) 2015 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using log4net;
using TBF.BenchControl.Generic;
using TBF.Boxes;
namespace TBF.BenchControl.Modbus.QuidoRS
{
public class QuidoRS : ComponentBase, IDevice
{
private static readonly ILog log = LogManager.GetLogger(typeof(QuidoRS));
public override string ToString() { return string.Format("QuidoRS({0})", Cfg.ToString(1)); }
readonly QuidoRSCfg quidoRSCfg;
readonly GenericDevices.IModbus modbus;
private ushort currentOutputs;
ushort watchdogBitMask;
public QuidoRS()
{
}
public QuidoRS(Generic.IComponentCfg cfg, IList<Generic.IComponent> components)
: base(cfg)
{
quidoRSCfg = cfg as QuidoRSCfg;
modbus = (GenericDevices.IModbus)TbfComponents.FindComponent(cfg.ParentName, components);
if (modbus == null) throw new Exception("Cannot find " + Name + " parent");
watchdogBitMask = (ushort)(quidoRSCfg.WatchdogEnabled ? (1 << quidoRSCfg.WatchdogBitNr) : 0);
log.Debug(this.ToString());
}
/// <summary>Initialize this device</summary>
public void Initialize()
{
}
/// <summary>Run this device</summary>
public void RunDeviceBefore()
{
}
/// <summary>Run this device</summary>
public void RunDeviceAfter()
{
if (watchdogBitMask != 0)
{
currentOutputs = (UInt16)((Int32)currentOutputs ^ (Int32)watchdogBitMask);
SendOutputs(currentOutputs);
}
}
/// <summary>Stop this device</summary>
public void StopDevice()
{
}
/// <summary>
/// Set outputs of QuidoRS board
/// </summary>
/// <param name="outputs">output value</param>
public void SetOutputs(ushort outputs)
{
currentOutputs = (UInt16)((Int32)outputs | ((Int32)currentOutputs & (Int32)watchdogBitMask));
SendOutputs(currentOutputs);
}
private void SendOutputs(ushort outputs)
{
byte[] msg = new byte[11];
msg[0] = quidoRSCfg.ModbusAddress;
msg[1] = (byte)Function.ForceMultipleCoils;
msg[2] = 0; /// Data Hi
msg[3] = 0; /// Data Lo
msg[4] = 0; /// Nr. of coils Hi
msg[5] = 16; /// Nr. of coils Lo
msg[6] = 2; /// Byte count
msg[7] = (byte)(outputs & 0xFF); /// Output data Lo
msg[8] = (byte)(outputs >> 8); /// Output data Hi
modbus.SendMessage(msg);
}
/// <summary>
/// Events: SetOpututsDone, Error
/// </summary>
/// <param name="outValue">Reference to a variable for the pressure in Bar</param>
/// <returns>SetOutputsOp instance reference casted to IOperaton</returns>
public IOperation SetOutputsOp(ushort outValue)
{
return new SetOutputsOp(this, outValue);
}
/// <summary>
/// Events: pressureDone, Error
/// </summary>
/// <param name="outValue">Reference to a variable for the pressure in Bar</param>
/// <param name="setOutputsDone">Event returned when SetOutput is done</param>
/// <returns>SetOutputsOp instance reference casted to IOperaton</returns>
public IOperation ReadPressureOp(ushort outValue, Event setOutputsDone)
{
return new SetOutputsOp(this, outValue, setOutputsDone);
}
}
}