Beispiel #1
0
        /// <summary>
        /// 生成批量写入寄存器的报文信息
        /// </summary>
        /// <param name="address">地址</param>
        /// <param name="values">实际值</param>
        /// <returns>包含结果对象的报文</returns>
        public OperateResult <byte[]> BuildWriteRegisterCommand(string address, byte[] values)
        {
            // 解析富地址
            OperateResult <ModbusAddress> analysis = ModbusInfo.AnalysisReadAddress(address, isAddressStartWithZero);

            if (!analysis.IsSuccess)
            {
                return(OperateResult.CreateFailedResult <byte[]>(analysis));
            }

            // 获取消息号
            ushort messageId = (ushort)softIncrementCount.GetCurrentValue( );

            // 生成最终tcp指令
            byte[] buffer = ModbusInfo.PackCommandToTcp(analysis.Content.CreateWriteRegister(station, values), messageId);
            return(OperateResult.CreateSuccessResult(buffer));
        }
Beispiel #2
0
        private void SocketAsyncCallBack(IAsyncResult ar)
        {
            if (ar.AsyncState is AppSession session)
            {
                try
                {
                    int receiveCount = session.WorkSocket.EndReceive(ar);

                    ModbusTcpMessage       mdMessage = new ModbusTcpMessage( );
                    OperateResult <byte[]> read1     = ReceiveByMessage(session.WorkSocket, 5000, mdMessage);
                    if (!read1.IsSuccess)
                    {
                        LogNet?.WriteDebug(ToString( ), string.Format(StringResources.Language.ClientOfflineInfo, session.IpEndPoint));
                        RemoveClient(session);
                        return;
                    }
                    ;

                    ushort id   = (ushort)(read1.Content[0] * 256 + read1.Content[1]);
                    byte[] back = ModbusInfo.PackCommandToTcp(ReadFromModbusCore(SoftBasic.BytesArrayRemoveBegin(read1.Content, 6)), id);
                    if (back != null)
                    {
                        session.WorkSocket.Send(back);
                    }
                    else
                    {
                        session.WorkSocket.Close( );
                        RemoveClient(session);
                        return;
                    }

                    RaiseDataReceived(read1.Content);
                    session.WorkSocket.BeginReceive(new byte[0], 0, 0, SocketFlags.None, new AsyncCallback(SocketAsyncCallBack), session);
                }
                catch
                {
                    // 关闭连接,记录日志
                    session.WorkSocket?.Close( );
                    LogNet?.WriteDebug(ToString( ), string.Format(StringResources.Language.ClientOfflineInfo, session.IpEndPoint));
                    RemoveClient(session);
                    return;
                }
            }
        }