C#

RS232 파일전송 - type com1: >> data.log

안녕1999 2020. 5. 23. 01:32

RS232FileTXRX.zip
0.00MB
RS232FileTXRX-.zip
0.00MB

type com1: >> data.log

 

mode COM21 BAUD=115200 PARITY=n DATA=8

copy yourfile.txt /B \\.\COM21

@Echo Off
echo 1l. > COM6:
SetLocal
Set Handle=%@FileOpen[COM6:,r,b]
Set Char=%@FileRead[%Handle,1]
Set Count=0
Do While "%Char" != "**EOF**"
Do While "%Count" <= 999 
  Set /A Count+=1
  @EchoS %Count: %Char^n
  Set Char=%@FileRead[%Handle,1]
EndDo
EndLocal
Pause

 

 

namespace SerialPortExample
{
  class SerialPortProgram
  {
    // Create the serial port with basic settings
    private SerialPort port = new SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One);

    [STAThread]
    static void Main(string[] args)
    { 
      // Instatiate this class
      new SerialPortProgram();
    }

    private SerialPortProgram()
    {
      Console.WriteLine("Incoming Data:");

      // Attach a method to be called when there
      // is data waiting in the port's buffer
      port.DataReceived += new 
        SerialDataReceivedEventHandler(port_DataReceived);

      // Begin communications
      port.Open();

      // Enter an application loop to keep this thread alive
      Application.Run();
    }

    private void port_DataReceived(object sender,
      SerialDataReceivedEventArgs e)
    {
      // Show all the incoming data in the port's buffer
      Console.WriteLine(port.ReadExisting());
    }
  }
}












using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using class
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;
 
namespace SensingWaterLeak
{
    public partial class MainLeakInfo : Form
    {
        private SerialPort mSerialPort;
 
        public MainLeakInfo()
        {
            InitializeComponent();
        }
 
        private void btn_leak_data_load_Click(object sender, EventArgs e)
        {
        }
 
        private void btn_leak_data_send_Click(object sender, EventArgs e)
        {
            try
            {
                if (mSerialPort != null && mSerialPort.IsOpen)
                {
                    mSerialPort.Close();
                    mSerialPort = null;
                }
                //Comport 와, baudRate 설정
                //USB의 기본 파라미터 설정을 해줌
                mSerialPort = new SerialPort("COM6", 9600);
                mSerialPort.Encoding = Encoding.Default;
                mSerialPort.Parity = Parity.None;
                mSerialPort.DataBits = 8;
                mSerialPort.StopBits = StopBits.One;
                //USB device로 부터 message receive시 callback 되는 listener
                mSerialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
                //Open을 했으면 close는 필수
                mSerialPort.Open();
                listBox.Items.Add("open 성공");
                byte[] buffer = new byte[3] {0xAA, 0xBB, 0xFB};
                //write 성공
                mSerialPort.Write(buffer, 0, 3);
                
                listBox.Items.Add("write");
            }
            catch (Exception eu)
            {
                System.Console.Out.WriteLine(eu.ToString());
                listBox.Items.Add(eu.ToString());
            }
 
        }
 
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            System.Console.Out.WriteLine("===============recevied================");
            try
            {
                listBox.Items.Add(mSerialPort.ReadLine());
            }
            catch (Exception et)
            {
                System.Console.Out.WriteLine(et.ToString());
            }
        }
    }
}



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
// 필요한 class를 using 해주자
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet;
using LibUsbDotNet.Main;
 
 
namespace SensingWaterLeak
{
    public partial class MainLeakInfo : Form
    {
        //변수 선언
        public static IDeviceNotifier mUsbDeviceNotifier = DeviceNotifier.OpenDeviceNotifier();
        public static UsbDeviceFinder mUsbDeviceFinder;
        public static UsbDevice mUsbDevice;
 
        SerialPort mSerialPort;
        public MainLeakInfo()
        {
            InitializeComponent();
			//Device change listener
			mUsbDeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent;
        }
 
        private void btn_device_no_load_Click(object sender, EventArgs e)
        {
            loadUSB();
        }
        
        //USB 연결/해제시 호출됨
        private void OnDeviceNotifyEvent(object sender, DeviceNotifyEventArgs e)
        {
            listBox.Items.Clear();
            listBox.Items.Add("type :" + e.EventType);
            listBox.Items.Add("Object :" + e.Object);
            listBox.Items.Add("port :" + e.Port);
            listBox.Items.Add("Volume :" + e.Volume);
            if (e.Device != null)
            {
                listBox.Items.Add("vID :" + e.Device.IdVendor);
                listBox.Items.Add("pID :" + e.Device.IdProduct);
                listBox.Items.Add("SerialNumber :" + e.Device.SerialNumber);
                listBox.Items.Add("SymbolicName :" + e.Device.SymbolicName);
                listBox.Items.Add("Name :" + e.Device.Name);
                listBox.Items.Add("ClassGuid :" + e.Device.ClassGuid);
            }
        }
 
        //USB device를 read 한다
        private void loadUSB()
        {
            try
            {
                //finder 방법은 시리얼, vendorID, productID 등의 여러가지 방법이 있다.
                mUsbDeviceFinder = new UsbDeviceFinder("0001");
                //mUsbDeviceFinder = new UsbDeviceFinder("a5dcbf10-6530-11d2-901f-00c04fb951ed");
 
                mUsbDevice = UsbDevice.OpenUsbDevice(mUsbDeviceFinder);
 
                if (mUsbDevice == null)
                {
                    listBox.Items.Add("device is null");
                    return;
                }
 
                IUsbDevice wholeUsbDevice = mUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(0);
                }
 
                UsbEndpointReader reader = mUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
 
            }
            catch (Exception e)
            {
                listBox.Items.Add(e.ToString());
            }
 
        }
    }
}
[출처] C# USB 통신 방법 - LibUsbDotNet|작성자 모암스






using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
namespace USB
{
    public partial class Form1 : Form
    {
        public static UsbDevice usbDevice;
        public static UsbRegistry [] usbRegistry;
        public static int nIdx;
        public UsbEndpointReader reader;
        delegate void txtBox(RichTextBox tb, string text);

        public Form1()
        {
            InitializeComponent();
            //컴퓨터에 연결된 USB 모든장치 로드
            UsbRegDeviceList allDevice = UsbDevice.AllDevices;
            usbRegistry = new UsbRegistry[allDevice.Count];
            int cntUsb = 0;
            //장치들을 하나씩 돌아가면서 조회
            foreach (UsbRegistry tmpUsbRegistry in allDevice)
            {
                //해당 USB가 정상적으로 열리면
                if(tmpUsbRegistry.Open(out usbDevice))
                {
                    //항목들을 하나씩 리스트박스에 추가
                    usbRegistry[cntUsb] = tmpUsbRegistry;
                    listBox1.Items.Add(usbRegistry[cntUsb].FullName);
                }
                cntUsb++;
            }
            UsbDevice.Exit();
        }
        public void setText(RichTextBox txt, string str)
        {
            if (richTextBox1.InvokeRequired)
            {
                txtBox ci = new txtBox(setText);
                richTextBox1.Invoke(ci, richTextBox1, str);
            }
            else
            {
                richTextBox1.Text =  str + "\r\n" + richTextBox1.Text;
            }
        }
        private void listBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            //리스트박스에서 선택된 USB 인덱스
            nIdx = ((System.Windows.Forms.ListBox)(sender)).SelectedIndex; 
            fldManufacturer.Text = (usbRegistry[nIdx].Device).Info.ManufacturerString;
            fldRev.Text = usbRegistry[nIdx].Rev.ToString();
            fldProduct.Text = (usbRegistry[nIdx].Device).Info.ProductString;
            fldSerial.Text = (usbRegistry[nIdx].Device).Info.SerialString;
            fldProductID.Text = usbRegistry[nIdx].Pid.ToString();
            fldVendorID.Text = usbRegistry[nIdx].Vid.ToString();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //데이터 수신 준비
            IUsbDevice wholeUsbDevice = usbDevice as IUsbDevice;
            //USB에서 들어오는 신호를 받기위해 EndPoint 설정
            reader = usbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
            ReadEventinitStart();
            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                wholeUsbDevice.SetConfiguration(1);
                wholeUsbDevice.ClaimInterface(0);
            }
        }
        public void ReadEvent(object sender, EndpointDataEventArgs e)
        {
            //USB에서 신호가 들어오면 활성화 되는 이벤트
            //string str = UnicodeEncoding.ASCII.GetString(e.Buffer, 0, e.Count);
            string str  = BitConverter.ToInt64(e.Buffer, 0).ToString();
            try
            {
                //받아온 데이터를 기록한다.
                setText(richTextBox1, str);
            }
            catch (System.Exception ex)
            {
            }
        }
        public void ReadEventinitStart()
        {
            //리더 활성화
            reader.DataReceivedEnabled = true;
            //이벤트 핸들러 연결
            reader.DataReceived += (ReadEvent);
        }
    }
}
using System;
using System.IO.Ports;

class PortDataReceived
{
	public static void Main()
	{
		SerialPort mySerialPort = new SerialPort("COM1");

		mySerialPort.BaudRate = 9600;
		mySerialPort.Parity = Parity.None;
		mySerialPort.StopBits = StopBits.One;
		mySerialPort.DataBits = 8;
		mySerialPort.Handshake = Handshake.None;
		mySerialPort.RtsEnable = true;

		mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

		mySerialPort.Open();

		Console.WriteLine("Press any key to continue...");
		Console.WriteLine();
		Console.ReadKey();
		mySerialPort.Close();
	}

	private static void DataReceivedHandler(
						object sender,
						SerialDataReceivedEventArgs e)
	{
		SerialPort sp = (SerialPort)sender;
		string indata = sp.ReadExisting();
		Console.WriteLine("Data Received:");
		Console.Write(indata);
	}
}
/*using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using class
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;*/

using System;
using System.IO.Ports;
using System.IO;
using System.Diagnostics;

namespace RS232FileRx
{
	class Rs232Rx
	{
		static void RX_file_write(ref SerialPort p, string file, int len)
        {
            int wlen = 0;
            string temp_file = file + ".tmp";
			Debug.WriteLine("RX_file_write()");
            if (file.Length > 0)
            {
                if (len > 0)
                {
                    //using (StreamWriter f = new StreamWriter(temp_file))
					using (BinaryWriter f = new BinaryWriter(File.Open(temp_file, FileMode.Create)))
					//using (FileStream f = File.Open(temp_file, FileMode.CreateNew))
                    {
                        byte[] buf = new byte[1024 * 1024];
                        while (wlen < len)
                        {
                            int blen;
                            blen = p.BytesToRead;
                            if (blen > buf.Length)
                            {
                                blen = buf.Length;
                            }
                            Debug.WriteLine(Convert.ToString(blen));
                            blen = p.Read(buf, 0, blen);
                            f.Write(buf, 0, blen);
                            wlen += blen;
                        }
                        f.Close();
                        if (wlen != len)
                        {
                            //err
                            File.Delete(temp_file);
                        }
                        else
                        {
                            //ok
                            File.Move(temp_file, file);
                        }
                    }
                }
            }
        }
        static void RX_file()//20200605
        {
            string file_name = "";
            int bExit = 0;
            int file_len = 0;
            SerialPort p;

			Debug.WriteLine("RX_file()");
            p = new SerialPort();
            while (bExit == 0)
            {
                foreach (string name in SerialPort.GetPortNames())
                {
					Debug.WriteLine(name);
                    p.PortName = name;
                    p.Open();
                    if (p.IsOpen)
                    {
                        break;
                    }
                }
                Debug.WriteLine(p.PortName);
                p.BaudRate = 115200;
                Debug.WriteLine(Convert.ToString(p.BaudRate));
                if (p.IsOpen)
                {
                    string c;
                    while (bExit == 0)
                    {
                        c = p.ReadLine();
						Debug.WriteLine(c);
                        if (c == "FILE")
                        {
                            file_name = p.ReadLine();
							file_name=file_name.Substring(file_name.LastIndexOf('\\')+1);//경로명 잘라내기
                        }
                        else if (c == "LEN")
                        {
                            file_len = Convert.ToInt32(p.ReadLine());
                        }
                        else if (c == "DATA")
                        {
                            RX_file_write(ref p, file_name, file_len);
                        }
                        else if (c == "EXIT")
                        {
                            bExit = 1;
                            break;
                        }
                        else
                        {
                            //Debug.WriteLine(c);
                            //break;
                        }
                    }
                    p.Close();
                }
            }
        }

		//error CS0120: 비정적 필드, 메서드 또는 속성 'Rs232Rx.RX_file()'에 개체 참조가 필요합니다.
		public static void Main()
		{
			RX_file();
			Debug.WriteLine("exit()");
		}
	}
}

set c=C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe
%c% /out:compile.exe "main.c"



static void RX_file_write(ref SerialPort p, string file, int len)
        {
            int wlen = 0;
            string temp_file = file + ".tmp";
            if (file.Length > 0)
            {
                if (len > 0)
                {
                    //using (StreamWriter f = new StreamWriter(temp_file))
                    using (BinaryWriter f = new BinaryWriter(File.Open(file, FileMode.Create)))
                    //using (FileStream f = File.Open(temp_file, FileMode.CreateNew))
                    {
                        byte[] buf = new byte[1024 * 1024];
                        while (wlen < len)
                        {
                            int blen;
                            blen = p.BytesToRead;
                            if (blen > buf.Length)
                            {
                                blen = buf.Length;
                            }
                            Debug.WriteLine(Convert.ToString(blen));
                            blen = p.Read(buf, 0, blen);
                            f.Write(buf, 0, blen);
                            wlen += blen;
                        }
                        f.Close();
                        if (wlen != len)
                        {
                            //err
                            File.Delete(temp_file);
                        }
                        else
                        {
                            //ok
                            File.Move(temp_file, file);
                        }
                    }
                }
            }
        }
        static void RX_file()//20200605
        {
            string file_name = "";
            int bExit = 0;
            int file_len = 0;
            SerialPort p;
            p = new SerialPort();
            while (bExit == 0)
            {
                foreach (string name in SerialPort.GetPortNames())
                {
                    p.PortName = name;
                    p.Open();
                    if (p.IsOpen)
                    {
                        break;
                    }
                }
                Debug.WriteLine(p.PortName);
                p.BaudRate = 115200;
                Debug.WriteLine(Convert.ToString(p.BaudRate));
                if (p.IsOpen)
                {
                    string c;
                    while (bExit == 0)
                    {
                        c = p.ReadLine();
                        if (c == "FILE")
                        {
                            file_name = p.ReadLine();
                            file_name=file_name.Substring(file_name.LastIndexOf('\\')+1);
                        }
                        else if (c == "LEN")
                        {
                            file_len = Convert.ToInt32(p.ReadLine());
                        }
                        else if (c == "DATA")
                        {
                            RX_file_write(ref p, file_name, file_len);
                        }
                        else if (c == "EXIT")
                        {
                            bExit = 1;
                            break;
                        }
                        else
                        {
                            Debug.WriteLine(c);
                            //break;
                        }
                    }
                    p.Close();
                }
            }
        }