| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785 | using Aitex.Core.RT.Log;using Aitex.Core.Util;using DocumentFormat.OpenXml.InkML;using MECF.Framework.Common.CommonData.PowerSupplier;using MECF.Framework.Common.Communications;using MECF.Framework.Common.Net;using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.IO.Ports;using System.Linq;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;namespace MECF.Framework.Common.Device.PowerSupplier{    public class PowerSupplierSerialPortModbusDevice     {        #region 常量         private const short CURRENT_SETTING_ADDRESS = 0x0101;        private const short OUTPUT_CONTROL_ADDRESS = 0x0110;        private const short STEP_PERIOD_ADDRESS = 0x1400;        private const short STEP_PERIOD_START_ADDRESS = 0x1640;        private const short VOLTAGE_OUTPUT_ADDRESS = 0x0201;        private const short POWER_CONTROL_ADDRESS = 0x0113;        private const short POWER_RUN_MODEL_ADDRESS = 0x0111;        /// <summary>        /// 电源状态(00-cv输出,01-cc输出)        /// </summary>        private const short POWER_STATUS_ADDRESS = 0x0200;        private const string SET_POINT = "SetPoint";        private const string CURRENT = "Current";        private const string VOLTAGE = "Voltage";        private const string ENABLED = "Enabled";        private const string POWER_STATUS = "PowerStatus";        private const string POWER_CONTROL = "PowerControl";        private const string POWER_RUN_MODEL = "PowerRunModel";        /// <summary>        /// 步阶数据数量        /// </summary>        private const int STEP_PERIOD_LENGTH = 6;        #endregion        #region 内部变量        private string _name;        private ConcurrentQueue<PowerSupplierCommand> _commandQueue=new ConcurrentQueue<PowerSupplierCommand>();        private SerialPort _serialPort;        private bool _connected;        private object _locker = new object();        private int _lockTimeout = 1000;        private PowerSupplierMessage _netMessage = new PowerSupplierMessage();        private object _sendLocker = new object();        private object _receiveLocker = new object();        private int _receiveTimeout = 1000;        private int _sendTimeout = 1000;        /// <summary>        /// 错误        /// </summary>        private string _errmsg;        /// <summary>        /// 离线时间        /// </summary>        private DateTime _offlineDateTime = DateTime.Now;        /// <summary>        /// 是否重连        /// </summary>        private bool _reconnect = false;        /// <summary>        /// 首次连接成功        /// </summary>        private bool _isFirstConnected = false;        #endregion        #region 属性        public bool Connected { get { return _connected; } }        #endregion        /// <summary>        /// 构造函数        /// </summary>        /// <param name="ip"></param>        /// <param name="port"></param>        public PowerSupplierSerialPortModbusDevice(string name, string portName, int baudRate = 9600, StopBits stopBits = StopBits.One, int dataBits = 8, Parity parity = Parity.None, bool reconnect = false)         {            _name = name;            _serialPort = new SerialPort();            _serialPort.BaudRate = baudRate;            _serialPort.StopBits = stopBits;            _serialPort.DataBits = dataBits;            _serialPort.Parity = parity;            _serialPort.PortName = portName;            _serialPort.ReadTimeout = _receiveTimeout;            _serialPort.WriteTimeout = _sendTimeout;            _serialPort.ErrorReceived += SerialPort_ErrorReceived;            _reconnect = reconnect;            PeriodicJob periodicJob = new PeriodicJob(20, OnTimer, $"{name}.ModbusDevice.Thread", true);        }        /// <summary>        /// 出现错误        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void SerialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)        {            LOG.WriteLog(eEvent.ERR_POWERSUPPLIER, _name, e.EventType.ToString());        }        /// <summary>        /// 定时器        /// </summary>        /// <returns></returns>        private bool OnTimer()        {            if (!_connected)            {                if (DateTime.Now.Subtract(_offlineDateTime).TotalSeconds >= 5 && _commandQueue.Count != 0)                {                    ClearSendQueue();                }                if (_reconnect&&_isFirstConnected)                {                    Start();                }                return true;            }            if (_commandQueue.Count!=0)            {                if(_commandQueue.TryDequeue(out PowerSupplierCommand command))                {                    if (_connected)                    {                        if (command.CommandCode == 0x03)                        {                            ApplyDataOperation(command);                        }                    }                }            }            return true;         }        /// <summary>        /// 清空发送队列        /// </summary>        private void ClearSendQueue()        {            try            {                while (_commandQueue.Count != 0)                {                    _commandQueue.TryDequeue(out var result);                }            }            catch            {            }        }        /// <summary>        /// 连接        /// </summary>        /// <returns></returns>        public bool Start()        {            if (!_connected)            {                try                {                    _serialPort.Open();                    LOG.WriteLog(eEvent.INFO_LINMOT, _name, $"connect port[{_serialPort.PortName}] success");                    _connected = true;                    if(!_isFirstConnected)                    {                         _isFirstConnected = true;                    }                    return true;                }                catch (Exception ex)                {                                       return false;                }            }            return true;        }        /// <summary>        /// 设置通道输出开关控制        /// </summary>        /// <param name="channel"></param>        /// <param name="currentValue"></param>        /// <returns></returns>        public void SetChannelOutputSwitchControl(byte channel, bool enabled)        {            if (Connected)            {                PowerSupplierCommand command = new PowerSupplierCommand();                command.Channel = channel;                command.CommandCode = 0x06;                command.Address = (ushort)(OUTPUT_CONTROL_ADDRESS);                command.Datas = new ushort[] { enabled ? (ushort)01 : (ushort)00 };                SetOperation(command);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 设置电源控制        /// </summary>        /// <param name="channel"></param>        /// <param name="currentValue"></param>        /// <returns></returns>        public void SetChannelPowerControl(byte channel,byte remoteControl)        {            if (Connected)            {                PowerSupplierCommand command = new PowerSupplierCommand();                command.Channel = channel;                command.CommandCode = 0x06;                command.Address = (ushort)(POWER_CONTROL_ADDRESS);                command.Datas = new ushort[] { remoteControl };                SetOperation(command);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 设置电源运行模式        /// </summary>        /// <param name="channel"></param>        /// <param name="currentValue"></param>        /// <returns></returns>        public void SetChannelPowerRunmodelControl(byte channel,byte model)        {            if (Connected)            {                PowerSupplierCommand command = new PowerSupplierCommand();                command.Channel = channel;                command.CommandCode = 0x06;                command.Address = (ushort)(POWER_RUN_MODEL_ADDRESS);                command.Datas = new ushort[] { model };                SetOperation(command);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 设置步阶数据        /// </summary>        /// <param name="channel"></param>        /// <param name="stepDatas"></param>        public bool SetStepPeriod(byte channel,List<PowerSupplierStepPeriodData> stepDatas,int scale)        {            if(Connected)            {                PowerSupplierCommand command = new PowerSupplierCommand();                command.Channel = channel;                command.CommandCode = 0x10;                command.Address = (ushort)STEP_PERIOD_ADDRESS;                command.RegisterCount =(ushort)(STEP_PERIOD_LENGTH * stepDatas.Count);                command.Datas = new ushort[STEP_PERIOD_LENGTH * stepDatas.Count];                for(int i = 0;i<stepDatas.Count;i++)                {                    PowerSupplierStepPeriodData data = stepDatas[i];                    command.Datas[0 + STEP_PERIOD_LENGTH * i] = (ushort)6000;                    command.Datas[1 + STEP_PERIOD_LENGTH * i] = (ushort)Math.Round(stepDatas[i].Current*scale,0);                    command.Datas[2 + STEP_PERIOD_LENGTH * i] = stepDatas[i].Hour;                    command.Datas[3+STEP_PERIOD_LENGTH*i]= stepDatas[i].Minute;                    command.Datas[4+STEP_PERIOD_LENGTH*i]= stepDatas[i].Second;                    command.Datas[5 + STEP_PERIOD_LENGTH * i] = stepDatas[i].Microsecond;                }                return SetOperation(command);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }            return false;        }        /// <summary>        /// 启动步阶        /// </summary>        /// <param name="channel"></param>        /// <param name="startStep"></param>        /// <param name="endStep"></param>        /// <param name="cycle"></param>        public bool StartStepPeriod(byte channel,ushort startStep,ushort endStep,ushort cycle)        {            if (Connected)            {                PowerSupplierCommand command = new PowerSupplierCommand();                command.Channel = channel;                command.CommandCode = 0x10;                command.Address = (ushort)STEP_PERIOD_START_ADDRESS;                command.RegisterCount = 3;                command.Datas = new ushort[3] { startStep,endStep,cycle };                return SetOperation(command);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }            return false;        }        /// <summary>        /// 设置电流        /// </summary>        /// <param name="channel"></param>        /// <param name="currentValue"></param>        /// <returns></returns>        public void SetCurrentValue(byte channel,ushort currentValue)        {            if (Connected)            {                PowerSupplierCommand command = new PowerSupplierCommand();                command.Channel = channel;                command.CommandCode = 0x06;                command.Address = (ushort)(CURRENT_SETTING_ADDRESS);                command.Datas = new ushort[] { currentValue };                SetOperation(command);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 设置电源状态        /// </summary>        /// <param name="channel"></param>        /// <param name="currentValue"></param>        /// <returns></returns>        public void SetChannelPowerStatus(byte channel, byte powerStatus)        {            if (Connected)            {                PowerSupplierCommand command = new PowerSupplierCommand();                command.Channel = channel;                command.CommandCode = 0x06;                command.Address = (ushort)(POWER_STATUS_ADDRESS);                command.Datas = new ushort[] { powerStatus };                SetOperation(command);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 获取通道输出开关控制        /// </summary>        /// <param name="channel"></param>        /// <returns></returns>        public void GetChannelOutput(byte channel)        {            if (Connected)            {                PowerSupplierCommand applyCommand = new PowerSupplierCommand();                applyCommand.Channel = channel;                applyCommand.CommandCode = 0x03;                applyCommand.Address = (ushort)(OUTPUT_CONTROL_ADDRESS);                applyCommand.RegisterCount = 1;                applyCommand.Variables.Add(ENABLED,(0,1));                _commandQueue.Enqueue(applyCommand);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 获取通道电源控制        /// </summary>        /// <param name="channel"></param>        /// <returns></returns>        public void GetChannelPowerControl(byte channel)        {            if (Connected)            {                PowerSupplierCommand applyCommand = new PowerSupplierCommand();                applyCommand.Channel = channel;                applyCommand.CommandCode = 0x03;                applyCommand.Address = (ushort)(POWER_CONTROL_ADDRESS);                applyCommand.RegisterCount = 1;                applyCommand.Variables.Add(POWER_CONTROL, (0, 1));                _commandQueue.Enqueue(applyCommand);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 获取通道电流设置数值        /// </summary>        /// <param name="channel"></param>        /// <returns></returns>        public void GetChannelCurrentSetting(byte channel)        {            if (Connected)            {                PowerSupplierCommand applyCommand = new PowerSupplierCommand();                applyCommand.Channel = channel;                applyCommand.CommandCode = 0x03;                applyCommand.Address = (ushort)(CURRENT_SETTING_ADDRESS);                applyCommand.RegisterCount = 1;                applyCommand.Variables.Add(SET_POINT,(0,1));                _commandQueue.Enqueue(applyCommand);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 获取电源状态设置数值        /// </summary>        /// <param name="channel"></param>        /// <returns></returns>        public void GetChannelPowerStatus(byte channel)        {            if (Connected)            {                PowerSupplierCommand applyCommand = new PowerSupplierCommand();                applyCommand.Channel = channel;                applyCommand.CommandCode = 0x03;                applyCommand.Address = (ushort)(POWER_STATUS_ADDRESS);                applyCommand.RegisterCount = 1;                applyCommand.Variables.Add(POWER_STATUS, (0,1));                _commandQueue.Enqueue(applyCommand);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 获取电源运行模式        /// </summary>        /// <param name="channel"></param>        /// <returns></returns>        public void GetChannelPowerRunModel(byte channel)        {            if (Connected)            {                PowerSupplierCommand applyCommand = new PowerSupplierCommand();                applyCommand.Channel = channel;                applyCommand.CommandCode = 0x03;                applyCommand.Address = (ushort)(POWER_RUN_MODEL_ADDRESS);                applyCommand.RegisterCount = 1;                applyCommand.Variables.Add(POWER_RUN_MODEL, (0, 1));                _commandQueue.Enqueue(applyCommand);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 申请电压和电流数值        /// </summary>        /// <param name="channel"></param>        /// <returns></returns>        public void GetChannelVoltageAndCurrent(byte channel)        {            if (Connected)            {                PowerSupplierCommand applyCommand = new PowerSupplierCommand();                applyCommand.Channel = channel;                applyCommand.CommandCode = 0x03;                applyCommand.Address = (ushort)(VOLTAGE_OUTPUT_ADDRESS);                applyCommand.RegisterCount = 4;                applyCommand.Variables.Add(VOLTAGE,(0,2));                applyCommand.Variables.Add(CURRENT,(2,2));                _commandQueue.Enqueue(applyCommand);            }            else            {                WriteErrorMsg($"{_name} is not connected");            }        }        /// <summary>        /// 设置操作        /// </summary>        /// <param name="command"></param>        /// <returns></returns>        private bool SetOperation(PowerSupplierCommand command)        {            NetResult netResult = SetData(command);            if (!netResult.IsSuccess)            {                LOG.WriteLog(eEvent.ERR_POWERSUPPLIER, _name, $"write value {command.Datas[0]} failed,{netResult.Message}");                return false;            }            return true;        }        /// <summary>        /// 设置数据        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="data"></param>        /// <returns></returns>        public NetResult SetData(PowerSupplierCommand data)        {            if (Monitor.TryEnter(_locker, _lockTimeout))            {                NetResult result = ReadFromServer(data);                if (!result.IsSuccess)                {                    Monitor.Exit(_locker);                    return NetResult.CreateFailedResult(result.ErrorCode, result.Message);                }                bool confirmResult = _netMessage.ConfirmResponseResult();                if (!confirmResult)                {                    Monitor.Exit(_locker);                    return NetResult.CreateFailedResult(_netMessage.ErrorCode, _netMessage.ErrorMsg);                }                Monitor.Exit(_locker);                return NetResult.CreateSuccessResult();            }            else            {                return NetResult.CreateFailedResult(NetErrorCode.GetLockTimeout);            }        }        /// <summary>        /// 从服务端读取数据        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="data"></param>        /// <returns></returns>        private NetResult ReadFromServer(PowerSupplierCommand data)        {            byte[] buffer = _netMessage.Code(data);            NetResult sendResult = Send(buffer);            if (!sendResult.IsSuccess)            {                return NetResult.CreateFailedResult(sendResult.ErrorCode, sendResult.Message);            }            _netMessage.SendBytes = buffer;            _netMessage.SetProtocolHeadBytesLength();            NetResult<byte[]> headerResult = Receive(_netMessage.ProtocolHeadBytesLength);            if (!headerResult.IsSuccess)            {                return NetResult.CreateFailedResult(headerResult.ErrorCode, headerResult.Message);            }            _netMessage.HeadBytes = headerResult.Data;            if (!_netMessage.CheckHeadBytesLegal())            {                return NetResult.CreateFailedResult(NetErrorCode.InvalidHeader);            }            NetResult<byte[]> contentResult = Receive(_netMessage.GetContentLengthByHeadBytes());            if (!contentResult.IsSuccess)            {                return NetResult.CreateFailedResult(contentResult.ErrorCode, contentResult.Message);            }            _netMessage.ContentBytes = contentResult.Data;            bool dataValid = _netMessage.CheckDataLegal();            if (!dataValid)            {                return NetResult.CreateFailedResult(_netMessage.ErrorCode, _netMessage.ErrorMsg);            }            return NetResult.CreateSuccessResult();        }        /// <summary>        /// 申请数据操作        /// </summary>        /// <param name="command"></param>        private void ApplyDataOperation(PowerSupplierCommand command)        {            NetResult<PowerSupplierCommand> netResult = ApplyData(command);            if (!netResult.IsSuccess)            {                List<string> keys = command.Variables.Keys.ToList();                string str = String.Join(" ", keys);                WriteErrorMsg($"apply {str} error");                return;            }            if(netResult.Data.Datas!=null)            {                Dictionary<string, (int,int)> dictionary = command.Variables;                List<string> keys = dictionary.Keys.ToList();                foreach(string item in keys)                {                    var result = dictionary[item];                    if(item==ENABLED)                    {                        PowerSupplierDeviceConfigManager.Instance.UpdateModuleVariable(_name, command.Channel, ENABLED, netResult.Data.Datas[result.Item1] == 0x01);                    }                    else                    {                        if(result.Item2==1)                        {                            PowerSupplierDeviceConfigManager.Instance.UpdateModuleVariable(_name, command.Channel, item, netResult.Data.Datas[result.Item1]);                        }                        else if(result.Item2==2)                        {                            int value = netResult.Data.Datas[result.Item1] * 255 + netResult.Data.Datas[result.Item1+1];                            PowerSupplierDeviceConfigManager.Instance.UpdateModuleVariable(_name, command.Channel, item, value);                        }                    }                }            }        }        /// <summary>        /// 申请数据        /// </summary>        /// <typeparam name="T">申请指令类型</typeparam>        /// <param name="data">指令对象</param>        /// <returns>返回数据对象</returns>        public NetResult<PowerSupplierCommand> ApplyData(PowerSupplierCommand data)        {            if (Monitor.TryEnter(_locker, _lockTimeout))            {                NetResult result = ReadFromServer(data);                if (!result.IsSuccess)                {                    Monitor.Exit(_locker);                    return NetResult.CreateFailedResult<PowerSupplierCommand>(result.ErrorCode, result.Message);                }                Monitor.Exit(_locker);                return NetResult.CreateSuccessResult<PowerSupplierCommand>(_netMessage.Decode());            }            else            {                return NetResult.CreateFailedResult<PowerSupplierCommand>(NetErrorCode.GetLockTimeout);            }        }        /// <summary>        /// 发送数据        /// </summary>        /// <param name="data"></param>        /// <returns></returns>        public NetResult Send(byte[] data)        {            if (!Connected)            {                return NetResult.CreateFailedResult(NetErrorCode.NetOffline);            }            //清除缓存数据            ClearPreData();            //进入发送            if (Monitor.TryEnter(_sendLocker, _sendTimeout))            {                if (_serialPort == null)                {                    return NetResult.CreateFailedResult(NetErrorCode.NullSocketObject);                }                try                {                    _serialPort.Write(data,0,data.Length);                    Monitor.Exit(_sendLocker);                    return NetResult.CreateSuccessResult();                }                catch (Exception ex)                {                    Monitor.Exit(_sendLocker);                    WriteErrorMsg(ex.Message);                    return NetResult.CreateFailedResult((int)NetErrorCode.InnerException, ex.Message);                }            }            else            {                return NetResult.CreateFailedResult(NetErrorCode.GetLockTimeout);            }        }        /// <summary>        /// 接收数据        /// </summary>        /// <param name="length"></param>        /// <returns></returns>        public NetResult<byte[]> Receive(int length)        {            if (!Connected)            {                return NetResult.CreateFailedResult<byte[]>(NetErrorCode.NetOffline);            }            if (Monitor.TryEnter(_receiveLocker, _receiveTimeout))            {                if (_serialPort == null)                {                    return NetResult.CreateFailedResult<byte[]>(NetErrorCode.NullSocketObject);                }                try                {                    byte[] buffer = new byte[length];                    DateTime dt = DateTime.Now;                    while(true)                    {                        if(_serialPort.BytesToRead>=length)                        {                            _serialPort.Read(buffer, 0, length);                            break;                        }                        if(DateTime.Now.Subtract(dt).TotalMilliseconds>=_receiveTimeout)                        {                            Monitor.Exit(_receiveLocker);                            return NetResult.CreateFailedResult<byte[]>(NetErrorCode.ReceiveTimeout);                        }                    }                    Monitor.Exit(_receiveLocker);                    return NetResult.CreateSuccessResult<byte[]>(buffer);                }                catch (SocketException ex)                {                    Monitor.Exit(_receiveLocker);                    return NetResult.CreateFailedResult<byte[]>((int)NetErrorCode.InnerException, ex.Message);                }                catch (Exception ex)                {                    Monitor.Exit(_receiveLocker);                    return NetResult.CreateFailedResult<byte[]>((int)NetErrorCode.InnerException, ex.Message);                }            }            else            {                return NetResult.CreateFailedResult<byte[]>(NetErrorCode.GetLockTimeout);            }        }        /// <summary>        /// 清除先前的数据        /// </summary>        public void ClearPreData()        {            if (!Connected)            {                return;            }            if (Monitor.TryEnter(_receiveLocker, _receiveTimeout))            {                try                {                    while (_serialPort.BytesToRead != 0)                    {                        byte[] buffer = new byte[_serialPort.BytesToRead];                        _serialPort.Read(buffer,0, buffer.Length);                    }                    Monitor.Exit(_receiveLocker);                }                catch (SocketException ex)                {                    Monitor.Exit(_receiveLocker);                }                catch (Exception ex)                {                    Monitor.Exit(_receiveLocker);                }            }        }        /// <summary>        /// 记录错误信息        /// </summary>        /// <param name="msg"></param>        private void WriteErrorMsg(string msg, bool disConnected = true)        {            if (disConnected)            {                _connected = false;                _offlineDateTime = DateTime.Now;            }            if (_errmsg != msg)            {                _errmsg = msg;                LOG.WriteLog(eEvent.ERR_POWERSUPPLIER, _name, msg);            }        }    }}
 |