public static byte GetChar(this Gurux.Serial.GXSerial port, string name) { if (port == null) { throw new NullReferenceException(); } if (port.BaseStream == null) { throw new InvalidOperationException("Cannot change X chars until after the port has been opened."); } try { // Get the base stream and its type which is System.IO.Ports.SerialStream object baseStream = port.BaseStream; Type baseStreamType = baseStream.GetType(); // Get the Win32 file handle for the port SafeFileHandle portFileHandle = (SafeFileHandle)baseStreamType.GetField("_handle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(baseStream); // Get the value of the private DCB field (a value type) FieldInfo dcbFieldInfo = baseStreamType.GetField("dcb", BindingFlags.NonPublic | BindingFlags.Instance); object dcbValue = dcbFieldInfo.GetValue(baseStream); // The type of dcb is Microsoft.Win32.UnsafeNativeMethods.DCB which is an internal type. We can only access it through reflection. Type dcbType = dcbValue.GetType(); return(Convert.ToByte(dcbType.GetField(name).GetValue(dcbValue))); } catch (System.Security.SecurityException) { throw; } catch (OutOfMemoryException) { throw; } catch (Win32Exception) { throw; } catch (Exception ex) { throw new ApplicationException("SetXonXoffChars has failed due to incorrect assumptions about System.IO.Ports.SerialStream which is an internal type.", ex); } }
/// <summary> /// Disables buttons. /// </summary> /// <param name="eventSender"></param> /// <param name="eventArgs"></param> private void Form1_Load(System.Object eventSender, System.EventArgs eventArgs) { try { gxSerial1 = new Gurux.Serial.GXSerial(); gxSerial1.Settings = GXSerialSample.Properties.Settings.Default.MediaSetting; gxSerial1.Trace = TraceLevel.Verbose; gxSerial1.OnTrace += new TraceEventHandler(gxSerial1_OnTrace); gxSerial1.OnError += new ErrorEventHandler(gxSerial1_OnError); gxSerial1.OnReceived += new ReceivedEventHandler(gxSerial1_OnReceived); gxSerial1.OnMediaStateChange += new MediaStateChangeEventHandler(gxSerial1_OnMediaStateChange); PropertiesBtn.Enabled = true; if (gxSerial1.IsOpen) { gxSerial1_OnMediaStateChange(this, new MediaStateEventArgs(MediaState.Open)); } else { gxSerial1_OnMediaStateChange(this, new MediaStateEventArgs(MediaState.Closed)); } } catch (Exception Ex) { MessageBox.Show(Ex.Message); } }
public static void SetChar(Gurux.Serial.GXSerial port, string name, byte value) { if (port == null) { throw new NullReferenceException(); } if (port.BaseStream == null) { throw new InvalidOperationException("Cannot change X chars until after the port has been opened."); } try { // Get the base stream and its type which is System.IO.Ports.SerialStream object baseStream = port.BaseStream; Type baseStreamType = baseStream.GetType(); // Get the Win32 file handle for the port SafeFileHandle portFileHandle = (SafeFileHandle)baseStreamType.GetField("_handle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(baseStream); // Get the value of the private DCB field (a value type) FieldInfo dcbFieldInfo = baseStreamType.GetField("dcb", BindingFlags.NonPublic | BindingFlags.Instance); object dcbValue = dcbFieldInfo.GetValue(baseStream); // The type of dcb is Microsoft.Win32.UnsafeNativeMethods.DCB which is an internal type. We can only access it through reflection. Type dcbType = dcbValue.GetType(); dcbType.GetField(name).SetValue(dcbValue, value); // We need to call SetCommState but because dcbValue is a private type, we don't have enough // information to create a p/Invoke declaration for it. We have to do the marshalling manually. // Create unmanaged memory to copy DCB into IntPtr hGlobal = Marshal.AllocHGlobal(Marshal.SizeOf(dcbValue)); try { // Copy their DCB value to unmanaged memory Marshal.StructureToPtr(dcbValue, hGlobal, false); // Call SetCommState if (!SetCommState(portFileHandle, hGlobal)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Update the BaseStream.dcb field if SetCommState succeeded dcbFieldInfo.SetValue(baseStream, dcbValue); } finally { if (hGlobal != IntPtr.Zero) { Marshal.FreeHGlobal(hGlobal); } } } catch (System.Security.SecurityException) { throw; } catch (OutOfMemoryException) { throw; } catch (Win32Exception) { throw; } catch (Exception ex) { throw new ApplicationException("SetXonXoffChars has failed due to incorrect assumptions about System.IO.Ports.SerialStream which is an internal type.", ex); } }
/// <summary> /// Constructor. /// </summary> public StatusDlg(Gurux.Serial.GXSerial Serial) { //This call is required by the Windows Form Designer. InitializeComponent(); GXSerial1 = Serial; }
static byte[] SendData(IGXMedia media, byte[] data, char baudRate, int wt, bool useCrcSend, bool useCrcReply, bool readAllDataOnce) { ReceiveParameters <byte[]> p = new ReceiveParameters <byte[]>() { Eop = GetEops(), WaitTime = wt }; lock (media.Synchronous) { if (data != null) { media.Send(data, null); if (baudRate != '\0' && media.MediaType == "Serial") { Gurux.Serial.GXSerial serial = media as Gurux.Serial.GXSerial; while (serial.BytesToWrite != 0) { System.Threading.Thread.Sleep(100); } System.Threading.Thread.Sleep(200); switch (baudRate) { case '0': serial.BaudRate = 300; break; case '1': case 'A': serial.BaudRate = 600; break; case '2': case 'B': serial.BaudRate = 1200; break; case '3': case 'C': serial.BaudRate = 2400; break; case '4': case 'D': serial.BaudRate = 4800; break; case '5': case 'E': serial.BaudRate = 9600; break; case '6': case 'F': serial.BaudRate = 19200; break; default: throw new Exception("Unknown baud rate."); } } } if (!media.Receive(p)) { throw new Exception("Failed to receive reply from the device in given time."); } List <byte> reply2 = new List <byte>(); reply2.AddRange(p.Reply); p.Reply = null; string header, frame; byte[] packet = null; if (useCrcSend && data != null) { while ((packet = GetPacket(reply2, false, out header, out frame)) == null) { p.Eop = null; p.Count = 1; if (!media.Receive(p)) { throw new Exception("Failed to receive reply from the device in given time."); } reply2.AddRange(p.Reply); p.Reply = null; } p.Eop = GetEops(); } else { for (int pos = 0; pos != reply2.Count; ++pos) { if (reply2[pos] == 0xA) { ++pos; packet = new byte[pos]; reply2.CopyTo(0, packet, 0, pos); break; } } } //Remove echo. if (data != null && EqualBytes(data, packet)) { reply2.RemoveRange(0, data.Length); if (useCrcReply && reply2.Count != 0)// && !(data != null && data[data.Length - 1] == 0xA)) { while (GetPacket(reply2, false, out header, out frame) == null) { p.Eop = null; p.Count = 1; if (!media.Receive(p)) { throw new Exception("Failed to receive reply from the device in given time."); } reply2.AddRange(p.Reply); p.Reply = null; } } else { if (GetPacket(reply2, false, out header, out frame) == null) { reply2.AddRange(SendData(media, null, baudRate, wt, useCrcSend, useCrcReply, readAllDataOnce)); } } //If there is more data available. if (readAllDataOnce && reply2[reply2.Count - 2] == 0x4) { reply2.AddRange(SendData(media, new byte[] { 6 }, '\0', wt, useCrcSend, useCrcReply, readAllDataOnce)); } return(reply2.ToArray()); } if (useCrcReply && !(data != null && data[data.Length - 1] == 0xA)) { while (GetPacket(reply2, false, out header, out frame) == null) { p.Eop = null; p.Count = 1; if (!media.Receive(p)) { throw new Exception("Failed to receive reply from the device in given time."); } reply2.AddRange(p.Reply); p.Reply = null; } } return(reply2.ToArray()); } }