示例#1
0
 //Ngắt kết nối COM
 private void button3_Click(object sender, EventArgs e)
 {
     ComPort.Close();
     MessageBox.Show("Ngắt kết nối thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
     lab_KetNoi.Text      = ("Chưa kết nối");
     lab_KetNoi.ForeColor = Color.Red;
 }
示例#2
0
        static void Main(string[] args)
        {
            ComPort port = null;

            try
            {
                port = new ComPort();
                Console.WriteLine("FRF started");

                var thinker = new Thinker(port);
                thinker.MainLoop();

                Console.ReadLine();

                /*while (true)
                 * {
                 *  string str = Console.ReadLine();
                 *  if (str == "exit")
                 *  {
                 *      break;
                 *  }
                 *
                 *  byte degree = Byte.Parse(str);
                 *  port.SendCommand(Commands.Status, new byte[] { degree });
                 * }*/
            }
            finally
            {
                if (port != null)
                {
                    port.Close();
                }
            }
        }
示例#3
0
 // ==== Private ====
 Rslt SendAndGetReply(string SCmd, out string SReply)
 {
     SReply = "";
     if (!ComPort.IsOpen)
     {
         return(Rslt.Failure);
     }
     // Send string
     try {
         ComPort.WriteLine(SCmd);
         SReply = ComPort.ReadLine().Trim();
         return(Rslt.OK);
     }
     catch (System.Exception ex) {
         IsConnected = false;
         LastError   = ex.Message;
         try {
             ComPort.Close();
         }
         catch (System.Exception ex2) {
             LastError = ex2.Message;
         }
     }
     return(Rslt.Failure);
 }
示例#4
0
        //void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        //{

        //    byte[] data = new byte[ComPort.BytesToRead];
        //    for (int i = 0; i < data.Length; i++)
        //    {
        //        data[i] = (byte)ComPort.ReadByte();
        //    }

        //    this.HandleByte(data);


        //    //throw new Exception("The method or operation is not implemented.");
        //}

        private void comboPorts_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ComPort != null)
            {
                ComPort.Close();
                OnConnectedChanged();
            }

            int idx = comboPorts.SelectedIndex;

            if (idx <= 0)
            {
                ComPort = null;
                butEditSerial.Enabled = false;
                return;
            }

            string portName = comboPorts.SelectedItem.ToString();

            ComPort = new SerialPort(portName);

            //ComPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceived);
            butEditSerial.Enabled = true;
            ComPort.Open();
            OnConnectedChanged();
            iSerial = new BoxdorferSerial(ComPort, this);

            atmelVersion.Read(iSerial);
            SynchronizeRead();
        }
示例#5
0
 void OnDestroy()
 {
     DataSource.Close();
     threadStop = true;
     DataThread.Abort();
     DataThread.Join();
 }
示例#6
0
文件: ComY.cs 项目: 3137908255/ComXYZ
 public void Close()
 {
     if (ComPortIsOpen == true)
     {
         ComPort.Close();
         ComPortIsOpen = false;
     }
 }
示例#7
0
 private void disconnect()
 {
     ComPort.Close();
     btnConnect.Text     = "Verbinden";
     btnSend.Enabled     = false;
     btnSendFile.Enabled = false;
     cmbPortName.Enabled = true;
 }
示例#8
0
 public bool Close()
 {
     try
     {
         ComPort.Close();
     }
     catch { }
     return(true);
 }
示例#9
0
 public void PortClose()
 {
     if (ComPortIsOpen == true)
     {
         ComPort.Close();
         ComPortIsOpen = false;
         EnableComButton();
     }
 }
示例#10
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (ComPort != null)
     {
         //readingThread.Abort();
         //readingThread.Join();
         ComPort.Close();
         ComPort.Dispose();
     }
 }
示例#11
0
 public void Disconnect()
 {
     mut.WaitOne();
     if (ser != null)
     {
         ser.Close();
         ser = null;
     }
     mut.ReleaseMutex();
 }
示例#12
0
        public bool Connect()
        {
            mut.WaitOne();
            ser          = new ComPort();
            ser.Baudrate = 115200;
            ser.Close();
            //WT 20170730
            //暂时修改COM口
            if (ser.Open(2) == false)
            {
                ser.Close();

                ser = null;
                mut.ReleaseMutex();
                return(false);
            }
            mut.ReleaseMutex();
            return(true);
        }
示例#13
0
 public void Stop()
 {
     while (cannotStop)
     {
         Thread.Sleep(10);
     }
     stopSending();
     port.Close();
     isRunning = false;
 }
示例#14
0
 void SetupIndex()
 {
     Properties.Settings.Default.Com = Int32.Parse(toolStripComboBox1.SelectedItem.ToString().Substring(3));
     Properties.Settings.Default.Save();
     if (ComPort.IsOpen)
     {
         ComPort.Close();
     }
     ComPort.PortName           = "COM" + Properties.Settings.Default.Com;
     toolStripStatusLabel2.Text = ComPort.PortName + " Connected";
 }
示例#15
0
 public void Close()
 {
     Trace.WriteLineIf(IsDebug, "Closing com port...");
     if (ComPort.IsOpen)
     {
         ComPort.BaseStream.Flush();
         ComPort.Close();
         ComPort.Dispose();
         ComPort = null;
         return;
     }
 }
示例#16
0
 private void Window_Closing(object sender, FormClosingEventArgs e)
 {
     try
     {
         System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
         System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
         wb.Close(false, Type.Missing, Type.Missing);
         xlApp.Quit();
         ComPort.Close();
     }
     catch { }
     appRunning = false;
 }
示例#17
0
 public void Dispose()
 {
     if (_comPort.IsOpen)
     {
         //_comPort.Flush();
         _comPort.Close();
         _comPort = null;
     }
     if (ComPort.IsOpen)
     {
         ComPort.Close();
         ComPort = null;
     }
 }
示例#18
0
        // 포트 닫기
        private void btnClose_Click(object sender, EventArgs e)
        {
            DialogResult ret = 0;

            timer1.Stop();
            timer2.Stop();
            btnSave.Enabled    = true;
            btnPrint.Enabled   = true;
            btnOpen.Enabled    = true;
            txtCommand.Enabled = true;
            dataNum            = 0;                                     // 시퀀스 넘버 리셋
            sectimer           = 0;                                     // 타이머 리셋
            this.Icon          = RsComCs.Properties.Resources.AND_Blue; //아이콘 변경
            iconShow           = true;                                  // 아이콘 관련
            if (ComPort.IsOpen)
            {
                ComPort.Close();
                // 콤보박스 활성화
                boxPort.Enabled       = true;
                boxBaudrate.Enabled   = true;
                boxLength.Enabled     = true;
                boxParity.Enabled     = true;
                boxStopbits.Enabled   = true;
                boxTerminator.Enabled = true;
            }
            else
            {
                if (txtBox.Text != string.Empty)
                {
                    ret = MessageBox.Show("Will you save this data", "RsCom C#", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
                    if (ret == DialogResult.Yes)
                    {
                        this.Close();
                    }
                    else if (ret == DialogResult.No)
                    {
                        this.Close();
                    }
                }
                else
                {
                    this.Close();
                }
            }
            btnOpen.Text  = "Start";
            btnClose.Text = "End";
        }
示例#19
0
        void FindComPort()
        {
            toolStripComboBox1.Items.Clear();

            for (int i = 1; i < 15; i++)
            {
                if (ComPort.IsOpen)
                {
                    ComPort.Close();
                }
                ComPort.PortName = "COM" + i;
                int portcount = 0;
                try
                {
                    ComPort.Open();
                    if (ComPort.IsOpen)
                    {
                        ComPort.Close();
                    }

                    toolStripComboBox1.Items.Add(ComPort.PortName);
                    portcount++;
                }
                catch { }
                if (i == Properties.Settings.Default.Com)
                {
                    if (toolStripComboBox1.Items.Count == portcount)
                    {
                        toolStripComboBox1.SelectedIndex = portcount - 1;
                    }
                    else
                    {
                        toolStripComboBox1.SelectedIndex = portcount;
                    }
                }
            }
            this.toolStripComboBox1.SelectedIndexChanged += new System.EventHandler(this.COM_Selected);
            ComPort.PortName = "COM" + Properties.Settings.Default.Com.ToString();
            //serialPort1.PortName = "COM12";
        }
示例#20
0
 /// <summary>
 /// 关闭
 /// </summary>
 public void Close()
 {
     _Port.Close();
 }
示例#21
0
 private void button2_Click(object sender, EventArgs e)
 {
     timer1.Enabled = false;
     ComPort.Close();
     sw.Close();
 }
 public void Close()
 {
     ComPort.Close();
 }
示例#23
0
        private bool SendGetData(ComPort port, int totRead, bool close)
        {
            string exceptionMsg = "";

            if (!port.IsOpen)
                try
                {
                    port.Open();
                }
                catch { }

            if (port.IsOpen && port.Write(InputData))
            {
                //WinAPI.OutputDebugString("W");

                int t = totRead;
                byte[] buffer = new byte[512];
                OutputData = new byte[0];
                do
                {
                    Array.Clear(buffer, 0, buffer.Length);
                    //WinAPI.OutputDebugString("R");
                    if (port.Read(ref buffer, out ReadedBytes))
                    {
                        Array.Resize<byte>(ref OutputData, (int)(OutputData.Length + ReadedBytes));
                        Array.Copy(buffer, 0, OutputData, OutputData.Length - ReadedBytes, ReadedBytes);
                        try
                        {
                            //WinAPI.OutputDebugString("D");
                            switch (DecodeAnswer())
                            {
                                case "busy":
                                    {
                                        //WinAPI.OutputDebugString("S");
                                        Thread.Sleep(200);
                                        break;
                                    }
                                case "true":
                                    {
                                        //WinAPI.OutputDebugString("T");
                                        ErrorFlags[lastFuncName] = false;
                                        return true;
                                    }
                                case "false":
                                    {
                                        //WinAPI.OutputDebugString("F");
                                        t--;
                                        Thread.Sleep(50);
                                        break;
                                    }
                                case "failed":
                                    {
                                        throw new Exception("������� ��������� ������� \"" + lastFuncName + "\"");
                                    }
                            }
                        }
                        catch (Exception ex)
                        {
                            exceptionMsg = "\r\n" + ex.Message;
                            break;
                        }
                    }
                    else
                        break;

                } while (t > 0);
                //WinAPI.OutputDebugString("E");
            }

            if (close)
                port.Close();

            ErrorFlags[lastFuncName] = true;
            throw new Exception("������� ������� � ���������� ��������" + " " + Protocol_Name + exceptionMsg);
        }
示例#24
0
 private void button3_Click(object sender, EventArgs e)
 {
     ComPort.Close();
     this.Close();
 }
示例#25
0
        private void LoadBMP(ComPort port, ushort progPass, bool allow, string fpath)
        {
            lastFuncName = "LoadBMP";
            NOM = 45;

            byte[] binArr = null;
            byte[] pass = Methods.GetByteArray((uint)progPass, 2);
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(fpath);
            byte[] img = new byte[bmp.Width / 8 * bmp.Height];
            byte oneByte = 0x00;
            int k = 0;
            int wo = 0;

            for (int h = 0, w = 0; h < bmp.Height; h++)
                for (w = 0; w < (bmp.Width / 8 * 8); w += 8)
                {
                    for (wo = 0; wo < 8; wo++)
                    {
                        oneByte <<= 1;
                        if (bmp.GetPixel(w + wo, h).Name == "ff000000")
                            oneByte |= 1;
                    }

                    img[k] = oneByte;
                    k++;
                }
            k = img.Length / 64;
            if (img.Length % 64 != 0)
                k++;
            object[] imgBlocks = new object[k];
            long idx = 0;
            byte cs = 0;
            for (k = 0; k < imgBlocks.Length; k++)
            {
                if (idx + 64 < img.Length)
                    binArr = new byte[64];
                else
                    binArr = new byte[img.Length - idx];

                Array.Copy(img, idx, binArr, 0, binArr.Length);
                cs = (byte)(0 - Methods.SumMas(binArr));
                Array.Resize<byte>(ref binArr, binArr.Length + 1);
                binArr[binArr.Length - 1] = cs;
                imgBlocks[k] = binArr;
                idx += 64;
            }
            //Creating data
            DataForSend = new byte[2 + 1 + 2 + 2];
            DataForSend[0] = pass[0];
            DataForSend[1] = pass[1];

            if (allow)
                DataForSend[2] = (byte)1;
            else
                DataForSend[2] = (byte)0;

            binArr = Methods.GetByteArray(bmp.Width / 8 * 8, 2);
            DataForSend[3] = binArr[0];
            DataForSend[4] = binArr[1];

            binArr = Methods.GetByteArray(bmp.Height, 2);
            DataForSend[5] = binArr[0];
            DataForSend[6] = binArr[1];

            //Making data
            InputData = CreateInputData(NOM, DataForSend);

            //sending and getting data

            if (!port.IsOpen)
                port.Open();

            byte[] buffer = new byte[1];
            uint rb = 20;
            int totRd = 20;
            bool enqDetected = false;
            port.Write(InputData);
            for (k = 0; k < imgBlocks.Length; k++)
            {
                totRd = 20;
                enqDetected = false;
                buffer = new byte[1];
                while (true)
                {
                    if (totRd < 0)
                        break;
                    port.Read(ref buffer, out rb);
                    if (buffer[0] == ENQ)
                    {
                        port.PortClear();
                        enqDetected = true;
                        break;
                    }
                    if (buffer[0] == SYN)
                        continue;
                    totRd--;
                }

                if (!enqDetected)
                    break;

                port.Write((byte[])imgBlocks[k]);
            }
            port.Close();

            //Next code for command
            GetNextCmdCode();
        }
示例#26
0
 void OnDestroy()
 {
     DataSource.Close();
 }
示例#27
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (btnConnect.Text == "Connect Port AND Test COMPORT")
            {
                if (!(ComPort.IsOpen)) // if comport is not already open
                {
                    try
                    {
                        ComPort.PortName = Convert.ToString(cbSelectPort.Text);
                        ComPort.BaudRate = Convert.ToInt32(cbSelectBaud.Text);
                        ComPort.Open();
                        btnConnect.Text = "Open";
                        ((userFirstScreen)(this.MdiParent)).statusPanel.Text = ComPort.PortName.ToString() + " Connected";
                    }
                    catch (FormatException)
                    {
                        if (cbSelectBaud.SelectedItem == null)
                        {
                            ComPort.BaudRate = 19200; // default baud rate of 19200 will be selected
                            MessageBox.Show("Please Select Baud rate");
                        }
                        else if (cbSelectPort.SelectedItem == null)
                        {
                            MessageBox.Show("Please Select COM Port");
                        }
                    }
                    catch (ArgumentException)
                    {
                        MessageBox.Show("Select Com port");
                    }
                    catch (UnauthorizedAccessException)
                    {
                        MessageBox.Show("Reconnect COM Port Once");
                    }
                } // isopen loop ends here
            }     // Connect port loop ends here
            else if (btnConnect.Text == "Open")
            { // close comport if open
                btnConnect.Text = "Closed";
                ComPort.Close();
                ((userFirstScreen)(this.MdiParent)).statusPanel.Text = "Disconnected";
            } // open loop ends here
            else if (btnConnect.Text == "Closed")
            {
                if (!ComPort.IsOpen)
                {
                    ComPort.Open();
                    btnConnect.Text = "Open";
                    ((userFirstScreen)(this.MdiParent)).statusPanel.Text = "Connected";
                }
            } // closed loop ends here

            if (ComPort.IsOpen)  // send test string to Master board to check if comm setup is working fine
            {
                if (umsObj.serviceType == true)
                {
                    String testString = "@ Test from PC#";
                    //umsObj.getServiceList("Queue Prefix", "Ticket Start");
                    testString = umsObj.sendServiceSetupToMaster();
                    ComPort.Write(testString);
                    rtSerialTx.Text = testString;
                    MessageBox.Show(testString);
                }
                ((userFirstScreen)(this.MdiParent)).statusPanel.Text = "Connected";
            }
        }
示例#28
0
        static GlucoResponse dumpFromComPort(SerialPort ComPort, string selectedPortName)
        {
            GlucoResponse glucoResponse = new GlucoResponse();

            glucoResponse.operationResult = GlucoOperationResultEnum.Failed;
            glucoResponse.error           = (string)null;
            bool        abortRead          = false;
            List <byte> lastRead           = new List <byte>();
            byte        num1               = 0;
            byte        num2               = 0;
            bool        needInicializePort = true;

            while (num2.ToString("X") != "AA" && num1.ToString("X") != "55" && !abortRead)
            {
                num2 = num1;
                try
                {
                    if (needInicializePort)
                    {
                        if (ComPort != null && ComPort.IsOpen)
                        {
                            ComPort.Close();
                        }
                        ComPort                = new SerialPort(selectedPortName);
                        ComPort.BaudRate       = 2400;
                        ComPort.DataBits       = 8;
                        ComPort.Parity         = Parity.Odd;
                        ComPort.StopBits       = StopBits.One;
                        ComPort.ReadTimeout    = 125;
                        ComPort.ReadBufferSize = 4096;
                        ComPort.ParityReplace  = (byte)0;
                        try
                        {
                            //  this.stopwatcher.Start();
                            ComPort.Open();
                            needInicializePort = false;
                            ComPort.DiscardInBuffer();

                            SendCurrentDateTime(ComPort);
                        }
                        catch (Exception e)
                        {
                            Console.Write(".");
                        }
                    }
                    if (ComPort.IsOpen)
                    {
                        num1 = (byte)ComPort.ReadByte();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception2:" + e);
                }
            }
            if (!abortRead)
            {
                //       this.OnPercentChange(0);
                //     this.OnAddStatusText("Az adatok számítógépre történő feltöltése folyamatban van, amely néhány percet is igénybe vehet.");
                Console.WriteLine("abortRead");
                ComPort.ReadTimeout = 5000;
            }
            int num3 = 21;
            int num4 = num3;
            int num5 = 2;

            while (!abortRead && num5 < num4)
            {
                if ((num5 & 15) == 0)
                {
                    int percentage = Math.Min(100, num5 * 100 / num4);
                    Console.WriteLine("%: " + percentage);
                }
                //  this.OnPercentChange();
                if (num5 == 8)
                {
                    num4 = 5 * (int)(short)((int)lastRead[4] + ((int)lastRead[5] << 8)) + num3;
                }
                try
                {
                    lastRead.Add((byte)ComPort.ReadByte()); ++num5;
                }
                catch (TimeoutException ex)
                {
                    Console.WriteLine("TimeoutException:" + ex);
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception3:" + ex);
                    break;
                }
            }
            if (ComPort.IsOpen)
            {
                ComPort.Close();
                ComPort.Dispose();
            }
            List <byte> byteList = new List <byte>();

            byteList.Add((byte)170);
            byteList.Add((byte)85);
            byteList.AddRange((IEnumerable <byte>)lastRead);
            if (abortRead)
            {
                Console.WriteLine("Felhasználó által megszakítva.");
                return(glucoResponse);
            }
            if (!ValidateCheckSum(byteList.ToArray()))
            {
                /*
                 * glucoResponse.operationResult = GlucoOperationResultEnum.Failed;
                 * glucoResponse.error = this.CHECKSUM_ERROR;
                 * this.OnAddStatusText(this.CHECKSUM_ERROR);
                 * glucoResponse.returnValue = (object)this.lastRead;
                 */
                Console.WriteLine("checksum error");
            }
            else if (glucoResponse.error == null)
            {
                glucoResponse.returnValue     = (object)lastRead;
                glucoResponse.operationResult = GlucoOperationResultEnum.Success;
            }

            Console.WriteLine("OK!");
            return(glucoResponse);
        }
示例#29
0
 void OnApplicationQuit()
 {
     portListener.Close();
 }
示例#30
0
 private void ScanStore_FormClosed(object sender, FormClosedEventArgs e)
 {
     xlApp.Quit();
     ComPort.Close();
     appRunning = false;
 }
示例#31
0
 public void Dispose()
 {
     Console.WriteLine(ComPort.PortName + " closing");
     ComPort.Close();
     ComPort.Dispose();
 }