Serial.cs 
Author Message
 Serial.cs

does anyone have the rest of this?

using System;

using System.Runtime.InteropServices;

namespace JustinIO {
  class CommPort {

    public int PortNum;
    public int BaudRate;
    public byte ByteSize;
    public byte Parity; // 0-4=no,odd,even,mark,space
    public byte StopBits; // 0,1,2 = 1, 1.5, 2
    public int ReadTimeout;

    //comm port win32 file handle
    private int hComm = -1;

    public bool Opened = false;

    //win32 api constants
      private const uint GENERIC_READ = 0x80000000;
      private const uint GENERIC_WRITE = 0x40000000;
      private const int OPEN_EXISTING = 3;
      private const int INVALID_HANDLE_VALUE = -1;

    [StructLayout(LayoutKind.Sequential)]
    public struct DCB {
      //taken from c struct in platform sdk
      public int DCBlength;           // sizeof(DCB)
      public int BaudRate;            // current baud rate
      /* these are the c struct bit fields, bit twiddle flag to set
      public int fBinary;          // binary mode, no EOF check
      public int fParity;          // enable parity checking
      public int fOutxCtsFlow;      // CTS output flow control
      public int fOutxDsrFlow;      // DSR output flow control
      public int fDtrControl;       // DTR flow control type
      public int fDsrSensitivity;   // DSR sensitivity
      public int fTXContinueOnXoff; // XOFF continues Tx
      public int fOutX;          // XON/XOFF out flow control
      public int fInX;           // XON/XOFF in flow control
      public int fErrorChar;     // enable error replacement
      public int fNull;          // enable null stripping
      public int fRtsControl;     // RTS flow control
      public int fAbortOnError;   // abort on error
      public int fDummy2;        // reserved
      */
      public uint flags;
      public ushort wReserved;          // not currently used
      public ushort XonLim;             // transmit XON threshold
      public ushort XoffLim;            // transmit XOFF threshold
      public byte ByteSize;           // number of bits/byte, 4-8
      public byte Parity;             // 0-4=no,odd,even,mark,space
      public byte StopBits;           // 0,1,2 = 1, 1.5, 2
      public char XonChar;            // Tx and Rx XON character
      public char XoffChar;           // Tx and Rx XOFF character
      public char ErrorChar;          // error replacement character
      public char EofChar;            // end of input character
      public char EvtChar;            // received event character
      public ushort wReserved1;         // reserved; do not use
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct COMMTIMEOUTS {
      public int ReadIntervalTimeout;
      public int ReadTotalTimeoutMultiplier;
      public int ReadTotalTimeoutConstant;
      public int WriteTotalTimeoutMultiplier;
      public int WriteTotalTimeoutConstant;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct OVERLAPPED {
        public int  Internal;
        public int  InternalHigh;
        public int  Offset;
        public int  OffsetHigh;
        public int hEvent;
    }

    [DllImport("kernel32.dll")]
    private static extern int CreateFile(
      string lpFileName,                         // file name
      uint dwDesiredAccess,                      // access mode
      int dwShareMode,                          // share mode
      int lpSecurityAttributes, // SD
      int dwCreationDisposition,                // how to create
      int dwFlagsAndAttributes,                 // file attributes
      int hTemplateFile                        // handle to template file
    );
    [DllImport("kernel32.dll")]
    private static extern bool GetCommState(
      int hFile,  // handle to communications device
      ref DCB lpDCB    // device-control block
    );
    [DllImport("kernel32.dll")]
    private static extern bool BuildCommDCB(
      string lpDef,  // device-control string
      ref DCB lpDCB     // device-control block
    );
    [DllImport("kernel32.dll")]
    private static extern bool SetCommState(
      int hFile,  // handle to communications device
      ref DCB lpDCB    // device-control block
    );
    [DllImport("kernel32.dll")]
    private static extern bool GetCommTimeouts(
      int hFile,                  // handle to comm device
      ref COMMTIMEOUTS lpCommTimeouts  // time-out values
    );
    [DllImport("kernel32.dll")]
    private static extern bool SetCommTimeouts(
      int hFile,                  // handle to comm device
      ref COMMTIMEOUTS lpCommTimeouts  // time-out values
    );
    [DllImport("kernel32.dll")]
    private static extern bool ReadFile(
      int hFile,                // handle to file
      byte[] lpBuffer,             // data buffer
      int nNumberOfBytesToRead,  // number of bytes to read
      ref int lpNumberOfBytesRead, // number of bytes read
      ref OVERLAPPED lpOverlapped    // overlapped buffer
    );
    [DllImport("kernel32.dll")]
    private static extern bool WriteFile(
      int hFile,                    // handle to file
      byte[] lpBuffer,                // data buffer
      int nNumberOfBytesToWrite,     // number of bytes to write
      ref int lpNumberOfBytesWritten,  // number of bytes written
      ref OVERLAPPED lpOverlapped        // overlapped buffer
    );
    [DllImport("kernel32.dll")]
    private static extern bool CloseHandle(
      int hObject   // handle to object
    );
    [DllImport("kernel32.dll")]
    private static extern uint GetLastError();

    public void Open() {

     DCB dcbCommPort = new DCB();
     COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

      // OPEN THE COMM PORT.

      hComm = CreateFile("COM" + PortNum ,GENERIC_READ | GENERIC_WRITE,0,
0,OPEN_EXISTING,0,0);

      // IF THE PORT CANNOT BE OPENED, BAIL OUT.
      if(hComm == INVALID_HANDLE_VALUE) {
          throw(new ApplicationException("Comm Port Can Not Be Opened"));
      }

      // SET THE COMM TIMEOUTS.

      GetCommTimeouts(hComm,ref ctoCommPort);
      ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
      ctoCommPort.ReadTotalTimeoutMultiplier = 0;
      ctoCommPort.WriteTotalTimeoutMultiplier = 0;
      ctoCommPort.WriteTotalTimeoutConstant = 0;
      SetCommTimeouts(hComm,ref ctoCommPort);

      // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
      GetCommState(hComm, ref dcbCommPort);
      dcbCommPort.BaudRate=BaudRate;
      dcbCommPort.flags=0;
      //dcb.fBinary=1;
      dcbCommPort.flags|=1;
      if (Parity>0)
      {
        //dcb.fParity=1
          dcbCommPort.flags|=2;
      }
      dcbCommPort.Parity=Parity;
      dcbCommPort.ByteSize=ByteSize;
      dcbCommPort.StopBits=StopBits;
      if (!SetCommState(hComm, ref dcbCommPort))
      {
       //uint ErrorNum=GetLastError();
         throw(new ApplicationException("Comm Port Can Not Be Opened"));
      }
      //unremark to see if setting took correctly
      //DCB dcbCommPort2 = new DCB();
      //GetCommState(hComm, ref dcbCommPort2);
      Opened = true;

    }

    public void Close() {
      if (hComm!=INVALID_HANDLE_VALUE) {
        CloseHandle(hComm);
      }
    }

    public byte[] Read(int NumBytes) {
      byte[] BufBytes;
      byte[] OutBytes;
      BufBytes = new byte[NumBytes];
      if (hComm!=INVALID_HANDLE_VALUE) {
        OVERLAPPED ovlCommPort = new OVERLAPPED();
        int BytesRead=0;
        ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
        OutBytes = new byte[BytesRead];
        Array.Copy(BufBytes,OutBytes,BytesRead);
      }
      else {
        throw(new ApplicationException("Comm Port Not Open"));
      }
      return OutBytes;
    }

    public void Write(byte[] WriteBytes) {
      if (hComm!=INVALID_HANDLE_VALUE) {
        OVERLAPPED ovlCommPort = new OVERLAPPED();
        int BytesWritten = 0;
        WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref
ovlCommPort);
      }
      else {
        throw(new ApplicationException("Comm Port Not Open"));
      }
    }
  }

  class HexCon {
  //converter hex string to byte and byte to hex string
    public static string ByteToString(byte[] InBytes) {
      string StringOut="";
      foreach (byte InByte in InBytes) {
        StringOut=StringOut + String.Format("{0:X2} ",InByte);
      }
      return StringOut;
    }
    public static byte[] StringToByte(string InString) {
      string[] ByteStrings;
      ByteStrings = InString.Split(" ".ToCharArray());
      byte[] ByteOut;
      ByteOut = new byte[ByteStrings.Length-1];
      for (int i = 0;i==ByteStrings.Length-1;i++) {
        ByteOut[i] = Convert.ToByte(("0x" + ByteStrings[i]));
      }
      return ByteOut;
    }
  }

Quote:
}

class MyNewClass {
  static void Main() {
    Console.WriteLine("hello! Welcome to my new program. Home made from
scratch biscuits by .jaeSin->\n");
    JustinIO.CommPort CommPort= new JustinIO.CommPort();

    CommPort.PortNum = 2;
    CommPort.BaudRate = 19200;
    CommPort.ByteSize = 8;
    CommPort.Parity = 0;
    CommPort.StopBits = 0;
    CommPort.ReadTimeout = 2;
    if(CommPort.Opened == false){

      Console.WriteLine("Comm port {0} is closed", CommPort.PortNum);
      CommPort.Open();
      Console.WriteLine("Comm port {0} is opened", CommPort.PortNum);

      CommPort.Write(JustinIO.HexCon.StringToByte("a t # p m o d e = 1
\n"));

      Console.WriteLine(CommPort.Read(2));
      string ConRead = Console.ReadLine ();

      CommPort.Write(JustinIO.HexCon.StringToByte(ConRead));

      CommPort.Close();
      Console.WriteLine("Comm port {0} is closed", CommPort.PortNum);
    }

  }

Quote:
}



Thu, 09 Sep 2004 18:10:22 GMT  
 Serial.cs
what do you expect more?

This is the original:
  http://www.nxys.com/justin/io.htm

Quote:

> does anyone have the rest of this?
> namespace JustinIO {



Thu, 09 Sep 2004 18:24:13 GMT  
 Serial.cs
I meant this one...

 /*
* Author: Marcus Lorentzon, 2001

*
* Freeware: Do not remove this header
*
* File: Serial.cs
*
* Description: Implements a Stream for asynchronous
*              transfers and COMM.
*
* Version: 0.2
*
* Limitations: Curently only supports asynchronous transfers and Windows
2000.
*
*/

namespace LoMaN.IO {

    using System;
    using System.IO;
    using System.Threading;
    using System.Runtime.InteropServices;

    public class SerialStream : Stream {

        public class SerialAsyncResult : IAsyncResult {
            public SerialAsyncResult(object asyncObject) {
                m_AsyncObject = asyncObject;
                m_WaitHandle = new ManualResetEvent(false);
            }

            internal void Init(object stateObject, AsyncCallback callback,
bool bIsRead) {
                m_StateObject = stateObject;
                m_Callback = callback;
                m_bIsRead = bIsRead;
                m_bCompleted = false;
                m_WaitHandle.Reset();
            }

            internal void Reset() {
                m_StateObject = null;
                m_Callback = null;
                m_bCompleted = true;
                m_WaitHandle.Reset();
            }

            internal bool m_bIsRead;
            internal bool m_bCompleted = true;

            public bool IsCompleted { get { return m_bCompleted; } }
            public bool CompletedSynchronously { get { return false; } }

            private object m_AsyncObject;
            public object AsyncObject { get { return m_AsyncObject; } }

            private object m_StateObject;
            public object AsyncState { get { return m_StateObject; } }

            private ManualResetEvent m_WaitHandle;
            public WaitHandle AsyncWaitHandle { get { return
m_WaitHandle; } }

            private AsyncCallback m_Callback;
            public AsyncCallback Callback { get { return m_Callback; } }
        }

        private unsafe void AsyncFSCallback(uint errorCode, uint numBytes,
NativeOverlapped* pOverlapped) {
            SerialAsyncResult sar =
(SerialAsyncResult)Overlapped.Unpack(pOverlapped).AsyncResult;
            sar.m_bCompleted = true;

            if (sar.m_bIsRead)
                m_iReadCount = (int)numBytes;
            else
                m_iWriteCount = (int)numBytes;
            ((ManualResetEvent)sar.AsyncWaitHandle).Set();

            if (sar.Callback != null)
                sar.Callback.Invoke(sar);
        }

        private IOCompletionCallback m_IOCompletionCallback;
        private int m_hFile = 0;

        private string m_sPort;
        public string Port {
            get {
                return m_sPort;
            }
            set {
                if (m_sPort != value) {
                    Close();
                    Open(value);
                }
            }
        }

        private const uint GENERIC_READ = 0x80000000;
        private const uint GENERIC_WRITE = 0x40000000;
        private const uint ERROR_IO_PENDING = 997;

        public void Open(string port) {
            m_hFile = CreateFile(port,
(uint)((m_bRead?GENERIC_READ:0)|(m_bWrite?GENERIC_WRITE:0)), 0, 0, 3,
0x40000000, 0);
            if (m_hFile <= 0) {
                m_hFile = 0;
                throw new FileNotFoundException("Unable to open " + port);
            }
            m_sPort = port;

            ThreadPool.BindHandle(m_hFile);
        }

        public SerialStream(string port, FileAccess access) {
            m_bRead  = (access.ToInt32() & FileAccess.Read.ToInt32()) != 0;
            m_bWrite = (access.ToInt32() & FileAccess.Write.ToInt32()) != 0;
            Open(port);
            m_IOCompletionCallback = new
IOCompletionCallback(AsyncFSCallback);
        }

        private bool m_bRead;
        public bool CanRead { override get { return m_bRead; } }

        private bool m_bWrite;
        public bool CanWrite { override get { return m_bWrite; } }

        public bool CanSeek { override get { return false; } }

        public bool Closed  { get { return m_hFile <= 0; } }

        public bool DataAvailable { override get { return true; } }

        public override long Length { get { return 0; } }

        public override void SetLength(long nLength) { }

        public override void Close() {
            CloseHandle(m_hFile);
            m_hFile = 0;
            m_sPort = null;
        }

        private int m_iReadCount;
        public override IAsyncResult BeginRead(byte[] buffer, int offset,
int count, AsyncCallback callback, object state) {
            SerialAsyncResult ar = new SerialAsyncResult(this);
            ar.Init(state, callback, true);
            Overlapped ov = new Overlapped(0, 0,
ar.AsyncWaitHandle.GetHandle(), ar);
            unsafe fixed (byte* data = &buffer[0]) {
                int read = 0;
                NativeOverlapped* nov = ov.Pack(m_IOCompletionCallback);
                ReadFile(m_hFile, data, count, &read, nov);
            }

            if (GetLastError() == ERROR_IO_PENDING)
                return ar;
            else
                throw new Exception("Unable to initialize read. Errorcode: "
+ GetLastError().ToString());
        }

        private int m_iWriteCount;
        public override IAsyncResult BeginWrite(byte[] buffer, int offset,
int count, AsyncCallback callback, object state) {
            SerialAsyncResult ar = new SerialAsyncResult(this);
            ar.Init(state, callback, false);
            Overlapped ov = new Overlapped(0, 0,
ar.AsyncWaitHandle.GetHandle(), ar);
            unsafe fixed (byte* data = &buffer[0]) {
                int write = 0;
                NativeOverlapped* nov = ov.Pack(m_IOCompletionCallback);
                WriteFile(m_hFile, data, count, &write, nov);
            }
            if (GetLastError() == ERROR_IO_PENDING)
                return ar;
            else
                throw new Exception("Unable to initialize write. Errorcode:
" + GetLastError().ToString());
        }

        public override int EndRead(IAsyncResult asyncResult) {
            SerialAsyncResult sar = (SerialAsyncResult)asyncResult;
            if (!sar.m_bIsRead)
                throw new Exception("Invalid parameter: IAsyncResult is not
from a read");
            sar.AsyncWaitHandle.WaitOne();
            if (!sar.m_bCompleted) {
                ((ManualResetEvent)sar.AsyncWaitHandle).Reset();
                sar.AsyncWaitHandle.WaitOne();
            }
            sar.Reset();

            return m_iReadCount;
        }

        public override int EndWrite(IAsyncResult asyncResult) {
            SerialAsyncResult sar = (SerialAsyncResult)asyncResult;
            if (sar.m_bIsRead)
                throw new Exception("Invalid parameter: IAsyncResult is from
a read");
            sar.AsyncWaitHandle.WaitOne();
            if (!sar.m_bCompleted) {
                ((ManualResetEvent)sar.AsyncWaitHandle).Reset();
                sar.AsyncWaitHandle.WaitOne();
            }
            sar.Reset();

            return m_iWriteCount;
        }

        public override void Flush() { FlushFileBuffers(m_hFile); }

        private const uint PURGE_TXABORT = 0x0001;  // Kill the
pending/current writes to the comm port.
        private const uint PURGE_RXABORT = 0x0002;  // Kill the
pending/current reads to the comm port.
        private const uint PURGE_TXCLEAR = 0x0004;  // Kill the transmit
queue if there.
        private const uint PURGE_RXCLEAR = 0x0008;  // Kill the typeahead
buffer if there.

        public bool PurgeRead() { return(PurgeComm(m_hFile,
PURGE_RXCLEAR)); }
        public bool PurgeWrite() { return(PurgeComm(m_hFile,
PURGE_TXCLEAR)); }
        public bool CancelRead() { return(PurgeComm(m_hFile,
PURGE_RXABORT)); }
        public bool CancelWrite() { return(PurgeComm(m_hFile,
PURGE_TXABORT)); }

        public override long Seek(long offset, SeekOrigin origin) { return
0; }

        public long Position { override get { return 0; } override set { } }

        public void SetTimeouts(int ReadIntervalTimeout, int
ReadTotalTimeoutMultiplier, int ReadTotalTimeoutConstant,
                                int WriteTotalTimeoutMultiplier, int
WriteTotalTimeoutConstant) {
            SerialTimeouts Timeouts = new
SerialTimeouts(ReadIntervalTimeout, ReadTotalTimeoutMultiplier,
ReadTotalTimeoutConstant,
                                         WriteTotalTimeoutMultiplier,
WriteTotalTimeoutConstant);
            unsafe SetCommTimeouts(m_hFile, &Timeouts);
        }

        public enum Parity {None, Odd, Even, Mark, Space};
        public enum StopBits {One, OneAndHalf, Two};
        public enum FlowControl {None, XOnXOff, Hardware};

        [StructLayout(LayoutKind.Sequential)]
        public struct DCB {
            public int DCBlength;
            public uint BaudRate;
            public uint Flags;
            public uint fBinary { get { return Flags&0x0001; }
                                  set { Flags = Flags & ~1U | value; } }
            public uint fParity { get { return (Flags>>1)&1; }
                                  set { Flags = Flags & ~(1U << 1) | (value
<< 1); } }
            public uint fOutxCtsFlow { get { return (Flags>>2)&1; }
                                  set { Flags = Flags & ~(1U << 2) | (value
<< 2); } }
            public uint fOutxDsrFlow { get { return (Flags>>3)&1; }
                                  set { Flags = Flags & ~(1U << 3) | (value
<< 3); } }
            public uint fDtrControl { get { return (Flags>>4)&3; }
                                  set { Flags = Flags & ~(3U << 4) | (value
<< 4); } }
            public uint fDsrSensitivity { get { return (Flags>>6)&1; }
                                  set { Flags = Flags & ~(1U << 6) | (value
<< 6); } }
            public uint fTXContinueOnXoff { get { return (Flags>>7)&1; }
                                  set { Flags = Flags & ~(1U << 7) | (value
<< 7); } }
            public uint fOutX { get {
...

read more »



Thu, 09 Sep 2004 19:37:54 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. The real serial.cs

2. Newbie: separate big .cs file into small .cs files

3. Serial port to serial port copying software

4. using PC/104 serial expansion board with WinCE, 4 serial ports total

5. Challenge: Virtual serial ports from real serial port

6. System Tray ICON for Serial PC card: uses standard serial driver

7. How to show/call Form2.cs from Form1.cs ?

8. Include code in other Cs files

9. Reuse of cs files, namespace, arch advice pls

10. word - automatic numbering/bold/underline/italics

11. How to Generate .cs file at Runtime

12. newbe/cs student, need help w/ code

 

 
Powered by phpBB® Forum Software