public void GetAndResolveReceiveBag(object obj) { this.dtuid = obj as string; ReceiveBytes receivedata = ReceiveBytes.GetReceiveBytes(); while (true) { if (receivedata.GetDtuReceivedBytesCount(this.dtuid) > 7) { ReceiveDataInfo recedata = receivedata.GetReceivePackage(this.dtuid); if (recedata != null) { try { var bt = new object(); bt = ReloveCustomTransData.GetInstance.ProtocolOrder(recedata); } catch (Exception ex) { Log.Error(ex.Message); } } else { Thread.Sleep(10); } } else { Thread.Sleep(1000); } } }
void CollectThread_ReceiveLog(ReceiveDataInfo e) { var data = CVT.ByteToHexStr(e.PackagesBytes); SetRecText(string.Format("收到数据,ID:{0},长度:{1},数据:{2}", e.Sender, e.PackagesBytes.Length, data)); SetLogText(string.Format("收到数据,ID:{0},长度:{1}", e.Sender, e.PackagesBytes.Length)); }
//=================================================================================================// private byte[] WriteReadData(byte[] writeData, int writeCount, int readCount) { // // Send the request and return the response // lock (responseSignal) { responsePacket = null; // // Initialise the receive data info // ReceiveDataInfo rdi = this.receiveDataInfo; rdi.bytesRead = 0; rdi.bufferIndex = 0; rdi.expectedPacketLength = readCount; // Write the data to the serial LCD this.SendData(writeData, writeCount); // Wait for the response packet if (Monitor.Wait(responseSignal, MAX_RESPONSE_TIME)) { return(responsePacket); } } return(null); }
/// <summary> /// The protocol order. /// </summary> /// <param name="data"> /// The data. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> public object ProtocolOrder(ReceiveDataInfo data) { if (String.CompareOrdinal(data.Sender, LCJDTUCODE) == 0) { return(new ReloveCustomTransLCJData().ProtocolOrder(data)); } var packet = data.PackagesBytes; if (data.PackagesBytes != null && packet != null) { var dataTypeFactory = new DataTypeFactory(); string dtuId = data.Sender; dataTypeFactory.ReloveTransData(dtuId, packet); } return(null); }
/// <summary> /// The wrapper_ receive data. /// </summary> /// <param name="buff"></param> private void Wrapper_ReceiveData(ReceiveDataInfo buff) { try { if (buff != null) { if (DataHexShowStringLogEventArgs != null) { DataHexShowStringLogEventArgs(buff); } var str = new StringBuilder(); str.Append(buff.Sender).Append(ValueHelper.ByteToHexStr(buff.PackagesBytes)); Log.Debug(str.ToString()); ReceiveBytes.GetReceiveBytes().AddReceiveBytes(buff.Sender, buff.PackagesBytes); } } catch (Exception ex) { Log.Error(ex.Message); } }
//---------------------------------------------------------------------------------------// protected void ReceiveData(byte[] data, int dataLength) { ReceiveDataInfo rdi = this.receiveDataInfo; try { // // Copy all of the data to the receive buffer // Array.Copy(data, 0, rdi.receiveBuffer, rdi.bufferIndex, dataLength); rdi.bytesRead += dataLength; rdi.bufferIndex += dataLength; // // Check if all of the expected data has been read // if (rdi.bytesRead >= rdi.expectedPacketLength) { // // The buffer has at least as many bytes for this packet // this.responsePacket = new byte[rdi.expectedPacketLength]; Array.Copy(rdi.receiveBuffer, 0, this.responsePacket, 0, rdi.expectedPacketLength); // // Signal the waiting thread that the data has been received // lock (responseSignal) { Monitor.Pulse(responseSignal); } } } catch (Exception ex) { Logfile.WriteError(ex.Message); } }
//---------------------------------------------------------------------------------------// /// <summary> /// /// </summary> /// <param name="labEquipmentConfiguration"></param> public DeviceSerialLcdSerial(LabEquipmentConfiguration labEquipmentConfiguration) : base(labEquipmentConfiguration) { const String methodName = "DeviceSerialLcdSerial"; Logfile.WriteCalled(Logfile.Level.Info, STR_ClassName, methodName); try { /* * Serial port settings */ XmlNode xmlNode = XmlUtilities.GetChildNode(this.xmlNodeDevice, Consts.STRXML_Serial); this.serialport = XmlUtilities.GetChildValue(xmlNode, Consts.STRXML_Port); this.baudrate = XmlUtilities.GetChildValueAsInt(xmlNode, Consts.STRXML_Baud); Logfile.Write(Logfile.Level.Config, String.Format(STRLOG_SerialPort_arg2, serialport, baudrate)); /* * Create the receive and report objects */ this.receiveDataInfo = new ReceiveDataInfo(); this.reportQueue = new Queue<LCDPacket>(); this.reportSignal = new Object(); this.responseSignal = new Object(); } catch (Exception ex) { Logfile.WriteError(ex.Message); throw ex; } Logfile.WriteCompleted(Logfile.Level.Info, STR_ClassName, methodName); }
//-------------------------------------------------------------------------------------------------// public ST360Counter(XmlNode xmlNodeEquipmentConfig) { const string STRLOG_MethodName = "ST360Counter"; Logfile.WriteCalled(null, STRLOG_MethodName); // // Initialise local variables // this.disposed = true; this.initialised = false; this.lastError = null; this.configured = false; // // Initialise properties // this.online = false; this.statusMessage = STRLOG_NotInitialised; // // Determine the logging level for this class // try { this.logLevel = (Logfile.LoggingLevels)Utilities.GetIntAppSetting(STRLOG_ClassName); } catch { this.logLevel = Logfile.LoggingLevels.Minimum; } Logfile.Write(Logfile.STRLOG_LogLevel + this.logLevel.ToString()); // // Get initialisation delay // XmlNode xmlNodeST360Counter = XmlUtilities.GetXmlNode(xmlNodeEquipmentConfig, Consts.STRXML_st360Counter); try { this.initialiseDelay = XmlUtilities.GetIntValue(xmlNodeST360Counter, Consts.STRXML_initialiseDelay); if (this.initialiseDelay < 0) { throw new ArgumentException(STRERR_NumberIsNegative); } } catch (ArgumentNullException) { throw new ArgumentException(STRERR_InitialiseDelayNotSpecified); } catch (FormatException) { // Value cannot be converted throw new ArgumentException(STRERR_NumberIsInvalid, Consts.STRXML_initialiseDelay); } catch (Exception ex) { Logfile.WriteError(ex.Message); throw new ArgumentException(ex.Message, Consts.STRXML_initialiseDelay); } // // Get Geiger tube voltage from application's configuration file // this.geigerTubeVoltage = XmlUtilities.GetIntValue(xmlNodeST360Counter, Consts.STRXML_voltage, DEFAULT_HighVoltage); // // Make sure that the high voltage is within range // if (this.geigerTubeVoltage < MIN_HighVoltage) { this.geigerTubeVoltage = MIN_HighVoltage; } else if (this.geigerTubeVoltage > MAX_HighVoltage) { this.geigerTubeVoltage = MAX_HighVoltage; } Logfile.Write(STRLOG_HighVoltage + this.geigerTubeVoltage.ToString()); // // Get speaker volume from application's configuration file // this.speakerVolume = XmlUtilities.GetIntValue(xmlNodeST360Counter, Consts.STRXML_volume, MIN_SpeakerVolume); // // Make sure that the speaker volume is within range // if (this.speakerVolume < MIN_SpeakerVolume) { this.speakerVolume = MIN_SpeakerVolume; } else if (this.speakerVolume > MAX_SpeakerVolume) { this.speakerVolume = MAX_SpeakerVolume; } Logfile.Write(STRLOG_SpeakerVolume + this.speakerVolume.ToString()); // // Get capture time adjustment: y = Mx + C // XmlNode xmlNode = XmlUtilities.GetXmlNode(xmlNodeST360Counter, Consts.STRXML_timeAdjustment, false); string capture = XmlUtilities.GetXmlValue(xmlNode, Consts.STRXML_capture, false); string[] strSplit = capture.Split(new char[] { Engine.Consts.CHR_CsvSplitterChar }); this.timeAdjustmentCapture = new double[strSplit.Length]; for (int i = 0; i < strSplit.Length; i++) { this.timeAdjustmentCapture[i] = Double.Parse(strSplit[i]); } // // Create the receive objects // this.receiveDataInfo = new ReceiveDataInfo(); this.responseSignal = new Object(); Logfile.WriteCompleted(null, STRLOG_MethodName); }
//---------------------------------------------------------------------------------------// protected void ReceiveData(byte[] data, int dataLength) { ReceiveDataInfo rdi = this.receiveDataInfo; int bytesReceived; while (dataLength > 0) { // // Copy the data into the receive buffer // if (dataLength <= rdi.numBytesToRead) { // // Copy all of the data to the receive buffer // Array.Copy(data, 0, rdi.receiveBuffer, rdi.bufferIndex, dataLength); bytesReceived = dataLength; } else { // // Copy only some of the data to the receive buffer // Array.Copy(data, 0, rdi.receiveBuffer, rdi.bufferIndex, rdi.numBytesToRead); bytesReceived = rdi.numBytesToRead; } dataLength -= bytesReceived; // // Check if dataLength for the packet has been determined // if (rdi.expectedPacketLengthIsSet || rdi.bytesRead <= 1) { // // This covers the case when more than 1 entire packet has been read in at a time // rdi.bytesRead += bytesReceived; rdi.bufferIndex = rdi.startPacketIndex + rdi.bytesRead; } if (rdi.bytesRead > 1) { // // The buffer has the dataLength for the packet // if (rdi.expectedPacketLengthIsSet == false) { rdi.expectedPacketLength = rdi.receiveBuffer[(1 + rdi.startPacketIndex) % rdi.receiveBuffer.Length] + 4; rdi.expectedPacketLengthIsSet = true; } if (rdi.bytesRead >= rdi.expectedPacketLength) { // // The buffer has at least as many bytes for this packet // AddPacket(rdi.receiveBuffer, rdi.startPacketIndex); rdi.expectedPacketLengthIsSet = false; if (rdi.bytesRead == rdi.expectedPacketLength) { // // The buffer contains only the bytes for this packet // rdi.bytesRead = 0; rdi.bufferIndex = rdi.startPacketIndex; } else { // // The buffer also has bytes for the next packet // rdi.startPacketIndex += rdi.expectedPacketLength; rdi.startPacketIndex %= rdi.receiveBuffer.Length; rdi.bytesRead -= rdi.expectedPacketLength; rdi.bufferIndex = rdi.startPacketIndex + rdi.bytesRead; } } } // // Update buffer and remaining space, wrapping around end of buffer if necessary // rdi.bufferIndex %= rdi.receiveBuffer.Length; if (rdi.bufferIndex < rdi.startPacketIndex) { rdi.numBytesToRead = rdi.startPacketIndex - rdi.bufferIndex; } else { rdi.numBytesToRead = rdi.receiveBuffer.Length - rdi.bufferIndex; } } }
//---------------------------------------------------------------------------------------// public SerialLcd(XmlNode xmlNodeEquipmentConfig) { const string STRLOG_MethodName = "SerialLcd"; Logfile.WriteCalled(null, STRLOG_MethodName); // // Initialise local variables // this.disposed = true; this.initialised = false; this.lastError = null; this.reportRunning = false; this.captureData = -1; this.lcdKey = LCDKey.None; // // Initialise properties // this.online = false; this.statusMessage = STRLOG_NotInitialised; // // Determine the logging level for this class // try { this.logLevel = (Logfile.LoggingLevels)Utilities.GetIntAppSetting(STRLOG_ClassName); } catch { this.logLevel = Logfile.LoggingLevels.Minimum; } Logfile.Write(Logfile.STRLOG_LogLevel + this.logLevel.ToString()); // // Get initialisation delay // XmlNode xmlNodeSerialLcd = XmlUtilities.GetXmlNode(xmlNodeEquipmentConfig, Consts.STRXML_serialLcd); try { this.initialiseDelay = XmlUtilities.GetIntValue(xmlNodeSerialLcd, Consts.STRXML_initialiseDelay); if (this.initialiseDelay < 0) { throw new ArgumentException(STRERR_NumberIsNegative); } } catch (ArgumentNullException) { throw new ArgumentException(STRERR_InitialiseDelayNotSpecified); } catch (FormatException) { // Value cannot be converted throw new ArgumentException(STRERR_NumberIsInvalid, Consts.STRXML_initialiseDelay); } catch (Exception ex) { Logfile.WriteError(ex.Message); throw new ArgumentException(ex.Message, Consts.STRXML_initialiseDelay); } // // Get WriteLine() time // try { this.writeLineTime = XmlUtilities.GetRealValue(xmlNodeSerialLcd, Consts.STRXML_writeLineTime, 0.0); } catch (Exception ex) { Logfile.WriteError(ex.Message); throw new ArgumentException(ex.Message, Consts.STRXML_writeLineTime); } // // Create the receive and report objects // this.receiveDataInfo = new ReceiveDataInfo(); this.reportQueue = new Queue <LCDPacket>(); this.reportSignal = new Object(); this.responseSignal = new Object(); Logfile.WriteCompleted(null, STRLOG_MethodName); }
//---------------------------------------------------------------------------------------// public SerialLcd(XmlNode xmlNodeEquipmentConfig) { const string STRLOG_MethodName = "SerialLcd"; Logfile.WriteCalled(null, STRLOG_MethodName); // // Initialise local variables // this.disposed = true; this.initialised = false; this.lastError = null; this.reportRunning = false; this.captureData = -1; this.lcdKey = LCDKey.None; // // Initialise properties // this.online = false; this.statusMessage = STRLOG_NotInitialised; // // Determine the logging level for this class // try { this.logLevel = (Logfile.LoggingLevels)Utilities.GetIntAppSetting(STRLOG_ClassName); } catch { this.logLevel = Logfile.LoggingLevels.Minimum; } Logfile.Write(Logfile.STRLOG_LogLevel + this.logLevel.ToString()); // // Get initialisation delay // XmlNode xmlNodeSerialLcd = XmlUtilities.GetXmlNode(xmlNodeEquipmentConfig, Consts.STRXML_serialLcd); try { this.initialiseDelay = XmlUtilities.GetIntValue(xmlNodeSerialLcd, Consts.STRXML_initialiseDelay); if (this.initialiseDelay < 0) { throw new ArgumentException(STRERR_NumberIsNegative); } } catch (ArgumentNullException) { throw new ArgumentException(STRERR_InitialiseDelayNotSpecified); } catch (FormatException) { // Value cannot be converted throw new ArgumentException(STRERR_NumberIsInvalid, Consts.STRXML_initialiseDelay); } catch (Exception ex) { Logfile.WriteError(ex.Message); throw new ArgumentException(ex.Message, Consts.STRXML_initialiseDelay); } // // Get WriteLine() time // try { this.writeLineTime = XmlUtilities.GetRealValue(xmlNodeSerialLcd, Consts.STRXML_writeLineTime, 0.0); } catch (Exception ex) { Logfile.WriteError(ex.Message); throw new ArgumentException(ex.Message, Consts.STRXML_writeLineTime); } // // Create the receive and report objects // this.receiveDataInfo = new ReceiveDataInfo(); this.reportQueue = new Queue<LCDPacket>(); this.reportSignal = new Object(); this.responseSignal = new Object(); Logfile.WriteCompleted(null, STRLOG_MethodName); }
//---------------------------------------------------------------------------------------// /// <summary> /// /// </summary> /// <param name="labEquipmentConfiguration"></param> public DeviceST360CounterSerial(LabEquipmentConfiguration labEquipmentConfiguration) : base(labEquipmentConfiguration) { const String methodName = "DeviceST360CounterSerial"; Logfile.WriteCalled(Logfile.Level.Info, STR_ClassName, methodName); try { /* * Serial port settings */ XmlNode xmlNode = XmlUtilities.GetChildNode(this.xmlNodeDevice, Consts.STRXML_Serial); this.serialport = XmlUtilities.GetChildValue(xmlNode, Consts.STRXML_Port); this.baudrate = XmlUtilities.GetChildValueAsInt(xmlNode, Consts.STRXML_Baud); /* * Create the receive objects */ this.receiveDataInfo = new ReceiveDataInfo(); this.responseSignal = new Object(); /* * Create an instance of the serial port, set read and write timeouts */ this.serialPort = new SerialPort(serialport, baudrate); this.serialPort.ReadTimeout = 1000; this.serialPort.WriteTimeout = 3000; Logfile.Write(String.Format(STRLOG_SerialPortBaudRate_arg2, serialport, baudrate)); } catch (Exception ex) { Logfile.WriteError(ex.Message); throw ex; } Logfile.WriteCompleted(Logfile.Level.Info, STR_ClassName, methodName); }
/// <summary> /// The protocol order. /// </summary> /// <param name="data"> /// The data. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> public object ProtocolOrder(ReceiveDataInfo data) { var packet = data.PackagesBytes; if (packet != null) { var package = new ArrayList(packet); var bll = new Bll(); while (package.Count > 0) { string dtuId = data.Sender; int len = (byte)package[LengthOfFrame]; var by = new byte[len]; package.CopyTo(0, @by, 0, len); int project = BitConverter.ToInt16(@by, ProjectCodeOfFrame); int typeOfData = @by[TypeOfDataOfFrame]; string moduleID = BitConverter.ToInt16(@by, ModuleNumOfFrame).ToString(); int channelId = @by[ChannelIDOfFrame]; var ticks = BitConverter.ToInt64(@by, AcqTimeOfFrame); var acqTime = new DateTime(ticks); var countOfData = (len - 20) / 4; // 一个float数据占4个字节 var value = new float[countOfData]; for (int i = 0; i < countOfData; i++) { value[i] = BitConverter.ToSingle(@by, DataValueOfFrame + (4 * i)); } package.RemoveRange(0, len); try { int sensorID = bll.GetSensorID(project, typeOfData, dtuId, moduleID, channelId); string tableName = bll.GetTableName(typeOfData); switch (typeOfData) { case BridgeVibration: // 27桥面振动 for (int i = 0; i < value.Length; i++) { value[i] = value[i] * 100; } break; case BridgeDeflection: // 21梁段挠度 try { var oridata = new[] { project, value[0] }; bll.InsertDataValues(OriginalDataTable, oridata, sensorID, typeOfData, acqTime); float calData = pressureProcess.CalculatePressValue(sensorID, value[0]); value[0] = calData; } catch (Exception ex) { Log.Error(ex.Message); } break; case BridgeSettle: // 19GPS try { var oridata = new[] { project, value[0], value[1], value[2] }; bll.InsertDataValues(OriginalDataTable, oridata, sensorID, typeOfData, acqTime); float[] calData = gpsProcess.CalulateGpsDataValue(sensorID, value); value = calData; } catch (Exception ex) { Log.Error(ex.Message); } break; } bll.InsertDataValues(tableName, value, sensorID, typeOfData, acqTime); } catch (Exception ex) { Log.Error(ex.Message); } } } return(null); }
public void CopyTo(ReceiveDataInfo obj) { obj.FUNCTION = FUNCTION; obj.PartID = PartID; obj.LotID = LotID; obj.Serial = Serial; }
private async Task<ReceiveDataInfo> ReceiveDataAsync(ServerAddress address, byte[] data, CancellationToken ct, params char[] header) { var udpClient = new UdpClient(); var ipAddr = IPAddress.Parse(address.Ip); try { udpClient.Connect(ipAddr, address.Port); var sendTime = DateTime.Now; await udpClient.SendAsync(data, data.Length); Packet packet = null; return await Task.Run(async () => { while (true) { var clientResult = await udpClient.ReceiveAsync().WithCancellation(ct); var remoteIp = clientResult.RemoteEndPoint.Address.ToString(); var remotePort = clientResult.RemoteEndPoint.Port; var receiveDate = DateTime.Now; var packetReader = new PacketReader(clientResult.Buffer); var packetheader = packetReader.ReadLong(); if (packet == null) { packet = engineFactory.CreatePacket(packetheader); } packet.AddData(clientResult.Buffer); if (packet.IsCompleted) { var messageReader = new PacketReader(packet.Payload); var messageheader = messageReader.ReadByte(); var messageHeaderChar = Convert.ToChar(messageheader); if (header.Contains(messageHeaderChar)) { var result = new ReceiveDataInfo { Ping = (int)(DateTime.Now - sendTime).TotalMilliseconds, Data = packet.Payload, MessageHeaderChar = messageHeaderChar, }; return result; } } } }); } catch { throw new OperationCanceledException(); } finally { udpClient.Close(); } }