/// <summary> /// 生成一个读取离散信息的指令头 /// </summary> /// <param name="address">地址</param> /// <param name="length">长度</param> /// <returns>包含结果对象的报文</returns> public OperateResult <byte[]> BuildReadDiscreteCommand(string address, ushort length) { // 解析富地址 OperateResult <ModbusAddress> analysis = ModbusInfo.AnalysisAddress(address, isAddressStartWithZero, ModbusInfo.ReadDiscrete); if (!analysis.IsSuccess) { return(OperateResult.CreateFailedResult <byte[]>(analysis)); } // 获取消息号 ushort messageId = (ushort)softIncrementCount.GetCurrentValue(); // 生成最终tcp指令 byte[] buffer = ModbusInfo.PackCommandToTcp(analysis.Content.CreateReadDiscrete(station, length), messageId); return(OperateResult.CreateSuccessResult(buffer)); }
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; } } }