473,395 Members | 1,471 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,395 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, 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 thankx 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 1483

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...
4
by: Primo | last post by:
Hi, This problem has been frustrating me for days and I hope you experts can help me out. I am trying to run a command, which I would normally run from the command line, from within my C#...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.