By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,563 Members | 1,180 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,563 IT Pros & Developers. It's quick & easy.

reading from a comport in windows CE environment using C#

P: n/a
HI I am having problems with C# with regards to its
compatibility with win32 API methods, I am trying to read
from a windows CE comm port using C# and imported methods
from coredll.dll, it seems that I can set the comm state
however when I try and read from the port using ReadFile
method I cannot, I've tried to change the DCB object flag
types but this does not make a difference as I still
cannot read from the port. I have pasted my code below for
u to take a look at and maybe suggest where I am going
wrong as I have tried everything in My knowledge, trawled
through the web, been to your MSDN website and took from
the information there, I have also tried using news groups
like Experts-Exchange but I think this has not be
attempted before, many thanx for your help

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace SmartDeviceApplication2{

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 long
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 byte
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 uint 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("coredll.dll")]
private static extern bool SetCommState(
int hCommDev,
ref DCB lpDCB);

[DllImport("coredll.dll")]
private static extern bool GetCommState(
int hCommDev,
ref DCB lpDCB) ;

[DllImport("coredll.dll")]
static extern bool ReadFile(
int hFile, Byte[] Buffer,
int nNumberOfBytesToRead,
ref int lpNumberOfBytesRead,
int x); // ref OVERLAPPED lpOverlapped ) ;
[DllImport("coredll.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
int x // overlapped buffer
);

[DllImport("coredll.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("coredll.dll")]
static extern int CloseHandle(int
hObject) ;

[DllImport("coredll.dll")]
private static extern bool GetCommTimeouts(
int hFile, //
handle to comm device
ref COMMTIMEOUTS
lpCommTimeouts // time-out values
);
[DllImport("coredll.dll")]
private static extern bool SetCommTimeouts(
int hFile, //
handle to comm device
ref COMMTIMEOUTS
lpCommTimeouts // time-out values
);
[DllImport("coredll.dll")]
private static extern bool
EscapeCommFunction(
int hFile,
int dwfunc
);
[DllImport("coredll.dll")]
private static extern bool WaitCommEvent(
int hFile,
ref long lpEvtMask,
int x
);

[DllImport("coredll.dll")]
private static extern bool SetCommMask(

int hFile,
int dwEvtMask
);

[DllImport("coredll.dll")]
private static extern uint GetLastError();

[DllImport("coredll.dll")]
private static extern bool
GetCommModemStatus(
int hComm,
ref long lpModemStat
);

[DllImport("coredll.dll")]
private static extern bool GetCommMask(
int hComm,
ref int lpModemStat
);

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

public void Open()
{
DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new
COMMTIMEOUTS();

Close();

// 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)
{
uint ErrorNum=GetLastError
();
throw(new
ApplicationException("Comm Port Can Not Be Opened"));
}

dcbCommPort.DCBlength=
Marshal.SizeOf (dcbCommPort);

bool j = GetCommState(hComm, ref
dcbCommPort);//get the status of current comm
dcbCommPort.fBinary =
1; // Binary mode; no EOF check

dcbCommPort.fParity =
1; // Enable parity checking
dcbCommPort.fOutxCtsFlow =
0; // No CTS output flow control
dcbCommPort.fOutxDsrFlow =
0; // No DSR output flow control
dcbCommPort.fDtrControl = 1;

// DTR flow control type
dcbCommPort.fDsrSensitivity =
0; // DSR sensitivity
dcbCommPort.fTXContinueOnXoff =
1; // XOFF continues Tx
dcbCommPort.fOutX =
0; // No XON/XOFF out flow control

dcbCommPort.fInX =
0; // No XON/XOFF in flow control
dcbCommPort.fErrorChar =
0; // Disable error replacement
dcbCommPort.fNull =
0; // Disable null stripping
dcbCommPort.fRtsControl = 1;
// RTS flow control
dcbCommPort.fAbortOnError = 0; //
Do not abort reads/writes on
dcbCommPort.BaudRate= BaudRate;
dcbCommPort.ByteSize =
ByteSize; // Number of bits/byte, 4-8
dcbCommPort.Parity =
Parity; // 0-4=no,odd,even,mark,space
dcbCommPort.StopBits = StopBits;


bool result = SetCommState(hComm,
ref dcbCommPort);

if (result!=true)
{
uint ErrorNum=GetLastError
();

throw(new
ApplicationException("Comm Port Can Not Be Opened" +
ErrorNum));
}
GetCommTimeouts(hComm, ref
ctoCommPort);

// SET THE COMM TIMEOUTS.
ctoCommPort.ReadIntervalTimeout =
0xffffffff;

ctoCommPort.ReadTotalTimeoutConstant = 0;

ctoCommPort.ReadTotalTimeoutMultiplier = 0;

ctoCommPort.WriteTotalTimeoutMultiplier = 10;

ctoCommPort.WriteTotalTimeoutConstant = 1000;
if (!SetCommTimeouts(hComm,ref
ctoCommPort))
{
throw(new
ApplicationException("Comm time outs cannot be set"));
}
//unremark to see if setting took
correctly
//DCB dcbCommPort2 = new DCB();
//GetCommState(hComm, ref
dcbCommPort2);
int SETDTR = 5;
int SETRTS = 3;
//result = EscapeCommFunction
(hComm, SETDTR);
//bool result2 =
EscapeCommFunction (hComm, SETRTS);

Opened = true;

}
public string Read(int NumBytes)
{

byte[] BufBytes;
//byte[] OutBytes;
BufBytes = new byte[NumBytes];
string g="";

int EV_RXCHAR = 0x0001;
int EV_CTS = 0x0008;
int EV_DSR = 0x0010;
int EV_RLSD = 0x0020;
int EV_RING = 0x0100;
bool result;
bool ndres;

result = SetCommMask(hComm,
EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING);

if (hComm!=INVALID_HANDLE_VALUE)
{

OVERLAPPED ovlCommPort =
new OVERLAPPED();
int BytesRead=0;
long dwCommModemStatus = 0;
int zero = 0;
long lpModemStat = 0;
int lpEvtMask = 0;

GetCommMask(hComm, ref
lpEvtMask);
GetCommModemStatus(hComm,
ref lpModemStat);
ndres = WaitCommEvent
(hComm,ref dwCommModemStatus,zero);

SetCommMask(hComm,
EV_RXCHAR|EV_CTS|EV_DSR|EV_RLSD|EV_RING);

if (dwCommModemStatus.Equals
(EV_RXCHAR))
{

ReadFile(hComm,
BufBytes,NumBytes,ref BytesRead, zero);

g =
Encoding.GetEncoding("ASCII").GetString
(BufBytes,0,NumBytes);
}
}
else
{
throw(new
ApplicationException("Comm Port Not Open"));
}
return g;
}
public void WriteMagicSequence()
{

byte[] abyte = new byte[12];

abyte[0]= 0xF9;
abyte[1] = 0xF9;
abyte[2] = 0xF9;
abyte[3] = 0xF9;
abyte[4] = 0xF9;
abyte[5] = 0x03;
abyte[6] = 0xEF;
abyte[7] = 0x05;
abyte[8] = 0xC3;
abyte[9] = 0x01;
abyte[10] = 0xF2;
abyte[11] = 0xF9;
PortWrite(abyte);

/*
PortWrite (0xF9);
PortWrite ((byte));
PortWrite (0xF9);
PortWrite (0xF9);
PortWrite (0x03);
PortWrite (0xEF);
PortWrite (0x05);
PortWrite (0xC3);
PortWrite (0x01);
PortWrite (0xF2);
PortWrite (0xF9);
*/
}

public void PortWrite(byte[] abyte)
{
int BytesWritten = 0;
int x=0;
if (!WriteFile
(hComm,abyte,abyte.Length,ref BytesWritten,x))
{
MessageBox.Show("the
message could not be written");
}
}
}

}

Nov 15 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.