Serial port communication issue from c# to c application - c#

I am writing a c#application which communicates with a device c application.
I am trying to write data from the c# application to c application over the serial port and vice versa.
I am trying to write some sample data using the following code.
C#
using PORT = System.IO.Port.SerialPort;
PORT p = new PORT("COM4", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
string data="HELLO";
//String to byte[] conversion
byte[] byt_buff = new byte[data.Length];
byt_buff = Encoding.ASCII.GetBytes(data);
p.Open();
p.DiscardOutBuffer();
p.Write(byt_buff, 0, byt_buff.Length);
p.Close();
The c application running on the device has the following code.
C
#include<stdio.h>
#include <poll.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include<stdint.h>
#include<string.h>
#define USB_DEV_NODE "usb.dat"
#define MAX_SIZE 20
int main()
{
int fd;
int ret_poll;
int ret_read;
struct pollfd pollfd;
char buf[MAX_SIZE];
int i = 0;
pollfd.events = POLLIN;
fd = open(USB_DEV_NODE, O_RDWR | O_NOCTTY);
pollfd.fd = fd;
while (1)
{
ret_poll = poll( &pollfd, 1, -1);
if( ret_poll == -1 )
{
printf("Gpio_poll poll failed\r\n");
close(fd);
}else{
if (pollfd.revents & POLLIN )
{
ret_read = read(fd, buf, MAX_SIZE);
buf[ret_read]=0;
if(ret_read > 0)
{
for(i=0;i<ret_read ; i++)
{
printf("BUF[%d]=%c\n",i,buf[i]);
}
}
}
}
}
return 0;
}
But I am failing to receive the data written as byte[],No data is recieved. Instead if I write data as a string using p.WriteLine("HELLO"); it will be recieved. Please help.

Related

Not receiving anything when putting NodeMCU as a client and C# as a server using UDP over a WiFi Network

I have been frustrated for days trying to make it work. What I have found relevant doesn't seem to help either. I'm a bit new here and with this, so please be kind. I want to be able to send a message or date from my NodeMCU acting as a client to my C# console application acting as a server through a wifi network using UDP. But it doesn't seem to be working at all.
Here is my C# server:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UDP_Server
{
class Program
{
private const int listenPort = 12346;
private static void StartListener()
{
bool done = false;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (!done)
{
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine("Received broadcast from {0} :\n {1}\n", groupEP.ToString(), Encoding.ASCII.GetString(bytes, 0, bytes.Length));
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
public static int Main()
{
StartListener();
return 0;
}
}
}
And here is my NodeMCU client:
#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
// WIFI
const char* ssid = "****"; // your network SSID (name)
const char* pass = "****"; // your network password
//testing with election server
const char* serverIP="192.168.254.111"; //IPV4 addresss?
unsigned int serverPort = 12346;
byte packetBuffer[512]; //buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
WiFiUDP Udp;
// NodeMCU pin mapping
//const uint8_t D0 = 16;
//const uint8_t D1 = 5;
//const uint8_t D2 = 4;
//const uint8_t D3 = 0;
//const uint8_t D4 = 2;
//const uint8_t D5 = 14;
//const uint8_t D6 = 12;
//const uint8_t D7 = 13;
//const uint8_t D8 = 15;
//const uint8_t D9 = 3;
//const uint8_t D10 = 1;
void setup(){
Serial.begin(115200);
Serial.println("starting");
start_wifi();
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void start_wifi() {
// setting up Station AP
WiFi.begin(ssid, pass);
// Wait for connect to AP
Serial.print("[Connecting]");
Serial.print(ssid);
int tries=0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
tries++;
if (tries > 30){
break;
}
}
Serial.println();
printWifiStatus();
Serial.println("Connected to wifi");
Serial.print("Udp server started at port ");
Serial.println(localPort);
Udp.begin(localPort);
}
void loop() {
Udp.beginPacket(serverIP, serverPort);
Udp.write("Test Message");
delay(500);
Serial.println("OK");
}
I want my client to be able to send messages, received by my C# program. Thank you so much.
I forgot to put Udp.endPacket(); in the loop statement of my client.

c# named pipe two way communcation

I have two programs written in c++ and c#.I want to establish a two way communication using named-pipe between them. The C# client program can be connected to the named-pipe created by c++ server program.But nothing received in both ends.
Here is the c++ part (Server):
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#define UNICODE
using namespace std;
HANDLE hnamedPipe = INVALID_HANDLE_VALUE;
BOOL Finished =false;
HANDLE hThread = NULL;
unsigned long __stdcall CS_RcvThr(void * pParam) ;
int main(int argc, char **argv)
{
hnamedPipe = CreateNamedPipe(
"\\\\.\\pipe\\vikeyP",
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE|
PIPE_READMODE_MESSAGE|
PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
1024,
1024,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
if(hnamedPipe == INVALID_HANDLE_VALUE)
{
cout << "Failed" << endl;
}
while (true)
{
cout<< "Waiting for client"<< endl;
if(!ConnectNamedPipe(hnamedPipe,NULL))
{
if(ERROR_PIPE_CONNECTED != GetLastError())
{
cout << "FAIL"<< endl;
}
}
else
{
cout<<"Connected!"<<endl;
hThread = CreateThread( NULL, 0, &CS_RcvThr, NULL, 0, NULL);
if(hThread) cout<<"read thread created"<<endl; else cout<<"cant crat rd thed\n";
break;
}
}
while(1)
{
cout<<"lst loop"<<endl;
//Send over the message
char chResponse[] = "hello\n";
DWORD cbResponse,cbWritten;
cbResponse = sizeof(chResponse);
if (!WriteFile(
hnamedPipe,
chResponse,
cbResponse,
&cbWritten,
NULL))
{
wprintf(L"failiure w/err 0x%08lx\n",GetLastError);
}
cout<<"Sent bytes :)" << endl;
Sleep(10);
}
}
unsigned long __stdcall CS_RcvThr(void * pParam) {
BOOL fSuccess;
char chBuf[100];
DWORD dwBytesToWrite = (DWORD)strlen(chBuf);
DWORD cbRead;
int i;
while (1)
{
fSuccess =ReadFile( hnamedPipe,chBuf,dwBytesToWrite,&cbRead, NULL);
if (fSuccess)
{
printf("C++ App: Received %d Bytes : ",cbRead);
for(i=0;i<cbRead;i++)
printf("%c",chBuf[i]);
printf("\n");
}
if (! fSuccess && GetLastError() != ERROR_MORE_DATA)
{
printf("Can't Read\n");
if(Finished)
break;
}
}
}
Here is the C# part (Client):
private Thread vikeyClientThread;
public void ThreadStartClient()
{
Console.WriteLine("Thread client started ID ={0} name = {1} " ,
Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.Name);
using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", "vikeyP"))
{
// The connect function will indefinately wait for the pipe to become available
// If that is not acceptable specify a maximum waiting time (in ms)
Console.WriteLine("Connecting to ViKEY server...");
pipeStream.Connect();
Console.WriteLine("Connected :)");
//Write from client to server
StreamWriter sw = new StreamWriter(pipeStream);
while (true)
{
//Read server reply
StreamReader sr = new StreamReader(pipeStream);
string temp = "";
sw.WriteLine(System.DateTime.Now);
byte[] c = new byte[200];
temp = sr.ReadLine();
pipeStream.Read(c, 0, c.Length);
Console.WriteLine("RX =:{0}", Encoding.UTF8.GetString(c, 0, c.Length));
Thread.Sleep(500);
}
}
Console.WriteLine("Vikey pipe Closed");
Console.WriteLine("Thread with ID ={0} name = {1} is closed.",
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name);
}
You've set the server side up as a message type vs byte type. If you want to read an arbitrary number of bytes, you'll need to use a byte type named pipe.
You're wrapping the stream in 2 objects one StreamReader and one StreamWriter. Don't do that, just use a Stream. You're trying to read by line, don't do that either. Instead send the number of bytes to read followed by the bytes. On the client side you'll read the byte count then create a buffer big enough then read. If it's text data you then would use an encoder (probably ASCII) to translate it back into a C# string.
Your while(true) should instead detect when the server has closed the pipe.
You should probably look into using an asynchronous named pipe.

How to convert is C++ Socket Programming Code to C#?

Guys I am a not a pro and some of you might think its a basic question but I really need help as I am on deadline to complete my Final Year Project. So here is what I am doing I found two codes a server and a client in which client sends Images to the server over some specified socket. The code is written in C++ and is for Linux. What I am looking for is a way to convert Server side of the code to C# so that I can run it on Windows and client must remain in C++ to be run on Linux. Both these codes are below for referencing.
Server:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main ( int agrc, char *argv[] )
{
/******** Program Variable Define & Initialize **********/
int Main_Socket; // Main Socket For Server
int Communication_Socket; // Socket For Special Clients
int Status; // Status Of Function
struct sockaddr_in Server_Address; // Address Of Server
struct sockaddr_in Client_Address;// Address Of Client That Communicate with Server
int Port;
char Buff[100] = "";
Port = atoi(argv[2]);
printf ("Server Communicating By Using Port %d\n", Port);
/******** Create A Socket To Communicate With Server **********/
Main_Socket = socket ( AF_INET, SOCK_STREAM, 0 );
if ( Main_Socket == -1 )
{
printf ("Sorry System Can Not Create Socket!\n");
}
/******** Create A Address For Server To Communicate **********/
Server_Address.sin_family = AF_INET;
Server_Address.sin_port = htons(Port);
Server_Address.sin_addr.s_addr = inet_addr(argv[1]);
/******** Bind Address To Socket **********/
Status = bind ( Main_Socket, (struct sockaddr*)&Server_Address, sizeof(Server_Address) );
if ( Status == -1 )
{
printf ("Sorry System Can Not Bind Address to The Socket!\n");
}
/******** Listen To The Port to Any Connection **********/
listen (Main_Socket,12);
socklen_t Lenght = sizeof (Client_Address);
int yx=1;
char bs[10000] = "??";
while (1)
{
Communication_Socket = accept ( Main_Socket, (struct sockaddr*)&Client_Address, &Lenght );
if (!fork())
{
FILE *fp=fopen("recv.jpg","w");
while(1)
{
char Buffer[10000]="";
if (recv(Communication_Socket, Buffer, sizeof(Buffer), 0))
{
if ( strcmp (Buffer,bs) == 0 )
{
break;
}
else
{
fwrite(Buffer,sizeof(Buffer),1, fp);
printf("\n%d) DATA RECIEVED", yx);
yx=yx+1;
}
}
}
fclose(fp);
send(Communication_Socket, "ACK" ,3,0);
printf("\nACK Send\n");
exit(0);
}
}
return 0;
}
Client:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main ( int agrc, char *argv[] )
{
int Socket;
struct sockaddr_in Server_Address;
Socket = socket ( AF_INET, SOCK_STREAM, 0 );
if ( Socket == -1 )
{
printf ("Can Not Create A Socket!");
}
int Port ;
Port = atoi(argv[2]);
Server_Address.sin_family = AF_INET;
Server_Address.sin_port = htons ( Port );
Server_Address.sin_addr.s_addr = inet_addr(argv[1]);
if ( Server_Address.sin_addr.s_addr == INADDR_NONE )
{
printf ( "Bad Address!" );
}
connect ( Socket, (struct sockaddr *)&Server_Address, sizeof (Server_Address) );
FILE *in = fopen("a.jpg","r");
char Buffer[10000] = "";
char bs[10000] = "??";
int len;
int yx=1;
while ((len = fread(Buffer,sizeof(Buffer),1, in)) > 0)
{
send(Socket,Buffer,sizeof(Buffer),0);
printf("\n %d) HELLO DOING IT", yx);
yx = yx + 1;
}
send(Socket,bs,sizeof(Buffer),0);
char Buf[BUFSIZ];
recv(Socket, Buf, BUFSIZ, 0);
if ( strcmp (Buf,"ACK") == 0 )
{
printf("\nRecive ACK\n");
}
close (Socket);
fclose(in);
return 0;
}
P.S. None of these are my own codes they are as I found them on the Internet but they are working perfectly.
Translating socket code from C++ to C# is quite straightforward. Your can do it quite quickly with a near line by line translation. That doesn't take advantage of C# features, but that's easy.
The C# class Socket (documentation) expose the underlying socket API, and you can find the C++ C# equivalent Socket() (constructor), .Bind(), .Listen(), .Accept(), .Receive(), .Send().
For the file IO, you have the File and FileStream classes.

USB to Serial (to and fro) communication using C# and C language

This is the 1st time am posting my query. I am in need of help. Any help is appreciated.
As i agree that i have given my prob as long story. But am sorry i am not getting how to make it short and my intention is give complete information regarding my prob.
Problem :
I have to communicate between two laptops using USB-to-Serial adapter on windows platform. I have written 2 programs one for sending and another for receiving. Programs were written in both C and C# programming languages.
Using C language :
I am able to successfully communicate using C-Programs mentioned below. But the problem is speed. It takes around 1 hour(60min) for just to pass 150MB. Anyone plz help me in improving the performance of this programs or you may suggest me other approaches which is robust and give high performance. I also mention some comments along with programs for self understanding.
Sender File on laptop with serial port :
#include <stdio.h>
#include <bios.h>
#include <conio.h>
#define COM1 0
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0
#define SETTINGS ( 0xE0 | 0x03 | 0x00 | 0x00)
int main(void)
{
int in, out, status, DONE = FALSE,i=0;
char c;
FILE *fp,*fp1;
unsigned long count = 0,shiftcount = 0;
clrscr();
fp = fopen("C:/TC/pic.jpg","rb"); //opened for reading actual content
fp1 = fopen("C:/TC/pic.jpg","rb"); //opened for reading the size of file
fseek(fp1,0L,2);
count = ftell(fp1) + 1; // file size
bioscom(0, SETTINGS, COM1); // initializing the port
printf("No. of Characters = %lu\n",count);
// since bioscom function can send or receive only 8bits at a time, am sending file size in
4 rounds so that we can send at max of 4GB file.
bioscom(1,count,COM1); // sneding 1st lower 8bits
bioscom(1,count>>8,COM1); // sending 2nd set of lower 8bits
bioscom(1,count>>16,COM1); // sending 3rd set of lower 8bits
bioscom(1,count>>24,COM1); // sending upper 8 bits
cprintf("... BIOSCOM [ESC] to exit ...\n");
while (!DONE)
{
status = bioscom(3, 0, COM1);// get the status of port
//printf("%d",status);
if (status & DATA_READY) //checks if data is ready
{
out = bioscom(2, 0, COM1); // receives the ack
if(!feof(fp))
{
c = fgetc(fp); //read character by character from file
bioscom(1,c,COM1);//send character to receiver
putch(c);//display
}
}
//to interrupt
if (kbhit())
{
if ((in = getch()) == '\x1B')
DONE = TRUE;
}
}
fclose(fp);
return 0;
}
Receiving file on laptop with USB port :
#include <stdio.h>
#include <bios.h>
#include <conio.h>
#define COM4 3
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0
#define SETTINGS ( 0xE0 | 0x03 | 0x00 | 0x00)
int main(void)
{
int in, out, status;
char c;
FILE *fp;
unsigned long shiftcount1=0,shiftcount2=0,shiftcount3=0,shiftcount4=0;
unsigned long count = 0, DONE = 1;
clrscr();
fp = fopen("C:/TC/pic1.jpg","wb");// file opened for writing
bioscom(0, SETTINGS, COM4);//initialize tyhe port
cprintf("... BIOSCOM [ESC] to exit ...\n");
//receives all the 32 bits of file size sent from sender
shiftcount1 = bioscom(2,0,COM4);
shiftcount2 = bioscom(2,0,COM4);
shiftcount3 = bioscom(2,0,COM4);
shiftcount4 = bioscom(2,0,COM4);
//send an ack
bioscom(1,'x',COM4);
count = shiftcount1 | (shiftcount2<<8) | (shiftcount3<<16) | (shiftcount4<<24);
printf("shift4 = %lu\tshift3 = %lu\tshift2 = %lu\tshift1 = %lu\n",shiftcount4,shiftcount3,shiftcount2,shiftcount1);
printf("File Size = %lu\n",count);
//loop till the size of the file
while (DONE < count)
{
status = bioscom(3, 0, COM4);// check the status
// printf("%d",status);
if (status & DATA_READY)//check for data ready at the port
{
out = bioscom(2, 0, COM4);//receive the data
DONE++;
fputc(out,fp);
putch(out);
bioscom(1,'x',COM4);//send an ack
}
if (kbhit())
{
if ((in = getch()) == '\x1B')
break;
}
}
fclose(fp);
return 0;
}
Sender file on laptop with USB port:
#include <stdio.h>
#include <bios.h>
#include <conio.h>
#include<dos.h>
#include<stdlib.h>
#include<time.h>
#define RTS 0x02
#define COM1 0
#define COM4 3
#define CURRCOM COM4
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0
#define SETTINGS ( 0xE0 | 0x03 | 0x00 | 0x00)
int main(void)
{
int in, out, status, DONE = FALSE,nextfile = 1;
char c;
FILE *fp,*fp1;
unsigned long count = 0,shiftcount = 0;
clock_t start,end;
start = clock();
clrscr();
fp = fopen("C:/TC/pic.jpg","rb");
fp1 = fopen("C:/TC/pic.jpg","rb");
fseek(fp1,0L,2);
count = ftell(fp1) + 1;
bioscom(0, SETTINGS, CURRCOM);
/* while(!feof(fp1))
{
c = fgetc(fp1);
count++;
} */
printf("No. of Cheracters = %lu\n",count);
bioscom(1,count,CURRCOM);
bioscom(1,count>>8,CURRCOM);
bioscom(1,count>>16,CURRCOM);
bioscom(1,count>>24,CURRCOM);
cprintf("\n... BIOSCOM [ESC] to exit ...\n");
while (!DONE)
{
status = bioscom(3, 0, CURRCOM);
if (status & DATA_READY)
{
out = bioscom(2,0,CURRCOM);
if(!feof(fp))
{
c = fgetc(fp);
bioscom(1,c,CURRCOM);
putch(c);
}
}
if (kbhit())
{
if ((in = getch()) == '\x1B')
DONE = TRUE;
}
}
fclose(fp);
end = clock();
printf("\nTotal time = %d\n",(end - start)/CLK_TCK);
return 0;
}
Receiver file on laptop with serial port :
#include <stdio.h>
#include <bios.h>
#include <conio.h>
#include<time.h>
#define COM1 0
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0
#define SETTINGS ( 0xE0 | 0x03 | 0x00 | 0x00)
int main(void)
{
int in, out, status;
char c;
FILE *fp;
int y = 0,esc;
unsigned long count=0,shiftcount1 = 0,shiftcount2 = 0,shiftcount3 = 0,shiftcount4 = 0, DONE = 1;
clock_t start,end;
start = clock();
clrscr();
fp = fopen("C:/TC/pic1.jpg","wb");
bioscom(0, SETTINGS, COM1);
cprintf("... BIOSCOM [ESC] to exit ...\n");
shiftcount1 = bioscom(2,0,COM1);
shiftcount2 = bioscom(2,0,COM1);
shiftcount3 = bioscom(2,0,COM1);
shiftcount4 = bioscom(2,0,COM1);
bioscom(1,'x',COM1);
count = shiftcount1 | (shiftcount2<<8) | (shiftcount3<<16) | (shiftcount4<<24);
printf("shift4 = %lu\tshift3 = %lu\tshift2 = %lu\t shift1 = %lu\n",shiftcount4,shiftcount3,shiftcount2,shiftcount1);
printf("file size = %lu\n",count);
while (DONE < count)
{
status = bioscom(3, 0, COM1);
//printf("%d",status);
if (status & DATA_READY)
{
out = bioscom(2, 0, COM1);
DONE++;
fputc(out,fp);
putch(out);
bioscom(1,'x',COM1);
}
if (kbhit())
{
if ((in = getch()) == '\x1B')
break;
}
}
fclose(fp);
end = clock();
printf("\nTotal time = %f\n",(end - start)/CLK_TCK);
return 0;
}
The above 4 programs behaves as, sender send a character and receives an ack for every character. I have followed this approach, bcoz other approaches were not working fine (in the sense the complete data is not sent, the amount of data sent is not judgeable, bcoz it will different every tym). when i used this approach it worked fine.
Using C# language :
Below two programs are written in C# using visual studio. I have used SerilaPort class , its properties and methods for communication. Using this, am able to communicate text and xml files on both the sides successfully.Also image files with .jpg extention, can be transferred from USB to serial end withot any loss of data(successful transmission), but if i transfer from serial to usb end, am able receive image with some data loss, even with the data loss am able to see the image.
Sender file on laptop with serial port :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Threading;
namespace Communication
{
class Program
{
static void Main(string[] args)
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
//Thread readThread = new Thread(Read);
FileStream fs = new FileStream("C:/text.xml", FileMode.Open);
//StreamReader sr = new StreamReader(fs);
BinaryReader br = new BinaryReader(fs);
// Create a new SerialPort object with default settings.
SerialPort _serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = "COM1";
_serialPort.BaudRate = 115200;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
bool _continue = true;
//readThread.Start();
int len = (int)fs.Length;
char[] data = new char[len+1];
br.Read(data, 0, len);
for (int i = 0; i < len+1; i++)
{
_serialPort.Write(data, i, 1);
//Console.Write(data,i,1);
}
br.Close();
fs.Close();
_serialPort.Close();
}
}
}
Receiver file on laptop with USB port :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Threading;
using System.Collections;
namespace Communication
{
class Program
{
static void Main(string[] args)
{
SerialComm comm = new SerialComm();
comm.Init();
comm.ReadSerial();
comm.WriteToFile();
comm.ResClose();
Console.ReadKey();
}
}
class SerialComm
{
FileStream fs = null;
BinaryWriter file = null;
ArrayList al = null;
public Boolean Init()
{
if (fs == null)
{
fs = new FileStream("C:/text1.txt", FileMode.OpenOrCreate);
}
if (file == null)
{
file = new BinaryWriter(fs);
}
if (al == null)
{
al = new ArrayList();
}
return true;
}
public void ResClose()
{
file.Close();
fs.Close();
}
public Boolean ReadSerial()
{
SerialPort port;
StreamWriter sw;
ConsoleKeyInfo ck;
port = new SerialPort();
port.PortName = "COM4";
port.BaudRate = 115200;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.Handshake = Handshake.None;
port.Open();
port.BaseStream.Flush();
port.DiscardInBuffer();
int c = 1;
while (c != 0)
{
c = port.ReadByte();
al.Add((byte)c);
}
return true;
}
public void WriteToFile()
{
int i = 0;
byte[] message = al.ToArray(typeof(byte)) as byte[];
file.Write(message, 0, message.Length - 1);
}
}
}
Please help me.
Thanks in advance.
Transmission speed:
Serial ports are simple, not fast. I am assuming that you are using 230kbps which is already more than many hardware can handle. Compression is only thing that might help, but compressing already compressed data (like .mp3) won't help much.
Data loss:
Serial ports are simple, not robust. Data loss is common, and only thing you can do about it is to have protocol to detect errors on incoming frames, and have ability to retry send if there is an error.
Conclusion:
Use TCP/IP instead.
Way too long a question. I've found only one actual question, and that's the performance bit.
Just use Ethernet or WiFi. "Serial port" (you probably mean RS-232) speeds are low. 0.1 Mbit/second is considered fast by RS-232 standards. You clock 1200 Mbit/3600 seconds, which is 0.3 Mbit/second. That is ultra-fast. I'm in fact surprised that you achieve that, your C# program is explicitly setting the speed to 0.1 Mbit/second.

passing c++ char* to c# via shared-memory

Sorry for probably simple question but I'm newbie in shared memory and trying to learn by example how to do things.
On c++ side I receive such pair: const unsigned char * value, size_t length
On c# side I need to have regular c# string. Using shared memory what is the best way to do that?
It's not that easy to using the string.
If it's me, I'll try these ways:
1.simply get a copy of the string. System.Text.Encoding.Default.GetString may convert from a byte array to a string.
You may try in a unsafe code block (for that you could use pointer type) to do:
(1) create a byte array, size is your "length"
byte[] buf = new byte[length];
(2) copy your data to the array
for(int i = 0; i < length; ++i) buf[i] = value[i];
(3) get the string
string what_you_want = System.Text.Encoding.Default.GetString(buf);
2.write a class, having a property "string what_you_want", and each time you access it, the above process will perform.
before all, you should first using P/Invoke feature to get the value of that pair.
edit: this is an example.
C++ code:
struct Pair {
int length;
unsigned char value[1024];
};
#include <windows.h>
#include <stdio.h>
int main()
{
const char* s = "hahaha";
HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(Pair), L"MySharedMemory");
struct Pair* p = (struct Pair*) MapViewOfFile(handle, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(Pair));
if (p != 0) {
p->length = lstrlenA(s);
lstrcpyA((char*)p->value, s);
puts("plz start c# program");
getchar();
} else
puts("create shared memory error");
if (handle != NULL)
CloseHandle(handle);
return 0;
}
and C# code:
using System;
using System.IO.MemoryMappedFiles;
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("MySharedMemory");
MemoryMappedViewStream mmfvs = mmf.CreateViewStream();
byte[] blen = new byte[4];
mmfvs.Read(blen, 0, 4);
int len = blen[0] + blen[1] * 256 + blen[2] * 65536 + blen[3] * 16777216;
byte[] strbuf = new byte[len];
mmfvs.Read(strbuf, 0, len);
string s = System.Text.Encoding.Default.GetString(strbuf);
Console.WriteLine(s);
}
}
just for example.
you may also add error-check part.

Categories

Resources