473,326 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

reading from a comport in windows CE environment using C#

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
0 3443

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Jim Potts | last post by:
What is the best way in Python version 2.x to read/get Windows (nt/2000/xp) system and user environment variables? Thanks for the help! jep
19
by: Lionel B | last post by:
Greetings, I need to read (unformatted text) from stdin up to EOF into a char buffer; of course I cannot allocate my buffer until I know how much text is available, and I do not know how much...
0
by: Jim Dunn | last post by:
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...
14
by: Zahid | last post by:
Hi, What is a VDT file? How do I read a VDT file into my application? I know how to read text files etc but not VDT files. Im preparing in advance a prototype that read VDT files and does...
3
by: Chris Paul | last post by:
I'm having trouble with PHP & PostgreSQL/OpenLDAP/Apache on Windows. I've set this up countless times on BSD (piece of cake) but I'm trying to do this on Windows now so that my developer can work...
4
by: RhavoX | last post by:
Hi. This may be a very stupid question but I'll leave you to judge it ;) I know there were lots of questions about this but none of the answers suits me. I'm wondering how to get the BINARY type...
0
by: koh soo min | last post by:
Hi, Can anyone give me hints to write VB code for send and receive message between two computer using ComPort. Thanks.
0
by: atc769 | last post by:
I am working on barcode reading software. Runs ok, but reads at the most 8 characters at a time. How can I get it to read the entire barcode rather than in pieces? Here is a snippet of my code ...
2
by: Rymfax | last post by:
Hey all. I need to determine whether or not a Windows Driver is digitally signed using a C# application. Can anyone point me in the right direction for doing this? I know it has something to...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.