Esempio n. 1
0
 private static void RunService()
 {
     Console.WriteLine("\r\nRun Mode:Service");
     if (serailports.Length > 0)
     {
         foreach (var name in serailports)
         {
             if (name.Contains("0"))
             {
                 continue;
             }
             CustomSerialPort csp = new CustomSerialPort(name, baudRate);
             csp.ReceivedEvent += Csp_ReceivedEvent;// Csp_DataReceived;
             try
             {
                 csp.Open();
                 servicePorts.Add(name, csp);
                 Console.WriteLine($"Service Open Uart [{name}] Succful!");
             }
             catch (Exception ex)
             {
                 Console.WriteLine($"RunService Open Uart [{name}] Exception:{ex}");
             }
         }
         OpenUartTestTimer();
     }
 }
Esempio n. 2
0
        public static CustomSerialPort GetSerialPort(ArduinoTypes SerialType)
        {
            FindSerialPorts();
            List <CustomSerialPort> WorkingPorts = serialPorts.Where(x => x.PortOpen == false && x.IsMatched == false).ToList();

            foreach (var ClosedPort in WorkingPorts)
            {
                try
                {
                    ClosedPort.Open();
                    ClosedPort.PortOpen = true;
                }
                catch (IOException)
                {
                }
            }

            CustomSerialPort FoundSerialPort = SearchForSerialPorts(SerialType);

            // Close all opened Serialports
            WorkingPorts = serialPorts.Where(x => x.PortOpen == false && x.IsMatched == false).ToList();
            foreach (var Port in WorkingPorts)
            {
                if (Port != FoundSerialPort)
                {
                    Port.PortOpen = false;
                    Port.Close();
                }
            }

            return(FoundSerialPort);
        }
Esempio n. 3
0
 static void FindSerialPorts()
 {
     if (serialPorts.Count == 0)
     {
         List <string> SerialPortNames = getSerialPorts().Where(Item => Item.Contains(getSerialPortNames())).ToList();
         foreach (var Port in SerialPortNames)
         {
             try
             {
                 CustomSerialPort serialPort = new CustomSerialPort(Port, 115200, Parity.None, 8, StopBits.One);
                 serialPort.ReadTimeout  = 1000;
                 serialPort.WriteTimeout = 1000;
                 serialPorts.Add(serialPort);
             }
             catch (IOException)
             {
                 Console.WriteLine($"[{Port}] Invalid Serialport");
             }
             catch (UnauthorizedAccessException)
             {
                 Console.WriteLine($"[{Port}] Unauthorized Access");
             }
         }
     }
 }
Esempio n. 4
0
        private static void CloseUart()
        {
            if (csp != null)
            {
                if (csp.IsOpen)
                {
                    csp.Close();
                }
                csp.ReceivedEvent -= Csp_ReceivedEvent;//Csp_DataReceived;

                csp = null;
                Console.WriteLine($"close serial port:{selectedComPort} succful!");
            }

#if RunIsService
            foreach (var csp in servicePorts.Values)
            {
                if (csp.IsOpen)
                {
                    csp.Close();
                }
            }
#endif
            if (sendTimer != null && sendTimer.Enabled)
            {
                sendTimer.Stop();
                sendTimer.Elapsed -= SendTimer_Elapsed;
            }
            msgIndex = 0;
        }
Esempio n. 5
0
        /// <summary>
        /// Get PortNames
        /// </summary>
        private static void GetPortNames()
        {
            serailports = CustomSerialPort.GetPortNames();

            if (serailports.Length > curSerialPortOrder)
            {
                selectedComPort = serailports[curSerialPortOrder];
            }
        }
Esempio n. 6
0
 public void GetSerial()
 {
     //CustomSerialPort.GetPortNames() 静态方法,获取计算机的所有串口名称
     //因为已经继承,也可以使用 string[] vs = 串口通讯.GetPortNames();
     string[] vs = CustomSerialPort.GetPortNames();
     Console.WriteLine("Serial List:");
     foreach (var i in vs)
     {
         Console.WriteLine(i);
     }
 }
Esempio n. 7
0
        private void updateComList()
        {
            comSelect.Items.Clear();

            comSelect.Items.AddRange(CustomSerialPort.GetPortNames());

            foreach (var item in typeof(Keys).GetFields())
            {
                keyCode.Items.Add(item.Name);
            }
        }
Esempio n. 8
0
        static MavlinkController()
        {
            mavlink = new Mavlink();
            mavlink.PacketReceived += Mavlink_PacketReceived;
            FlightData              = new FlightData();

            string portName = CustomSerialPort.GetPortNames()[0];

            serialPort = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One);
            serialPort.DataReceived += SerialPort_DataReceived;
            serialPort.Open();
        }
Esempio n. 9
0
 public void drivertest()
 {
     try
     {
         CustomSerialPort sbus = new CustomSerialPort("COM3", 100000, Parity.Even, 8, StopBits.Two);
         sbus.ReceiveTimeoutEnable = false;
         //sbus.ReceiveTimeout = 1;
         sbus.ReceivedEvent += Sbus_ReceivedEvent;
         sbus.Open();
     }
     catch (Exception eeee0)
     {
     }
 }
Esempio n. 10
0
 private static void OpenUart(string portName)
 {
     CloseUart();
     try
     {
         csp                = new CustomSerialPort(portName);
         csp.BaudRate       = baudRate;
         csp.ReceivedEvent += Csp_ReceivedEvent;
         csp.Open();
         OpenUartTestTimer();
         Console.WriteLine($"open serial port:{portName} succful!baudRate:{baudRate}");
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Open Uart Exception:{ex}");
     }
 }
Esempio n. 11
0
 private static void Csp_ReceivedEvent(object sender, byte[] bytes)
 {
     try
     {
         CustomSerialPort sps  = (CustomSerialPort)sender;
         string           msg  = Encoding.ASCII.GetString(bytes).Replace("\r", "").Replace("\n", "");
         string           echo = $"{sps.PortName} Receive Data:[{msg}].Item already filtered crlf.";
         Console.WriteLine(echo);
         if (!echo.Contains($"{sps.PortName}"))
         {
             sps.WriteLine(msg);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Esempio n. 12
0
        /// <summary>
        /// 关闭串口
        /// </summary>
        public static bool CloseUart()
        {
            bool flag = false;

            try
            {
                if (m_CSP != null)
                {
                    if (m_CSP.IsOpen)
                    {
                        m_CSP.Close();
                    }
                    m_CSP.ReceivedEvent -= Csp_ReceivedEvent;//Csp_DataReceived;

                    m_CSP = null;
                    Console.WriteLine($"关闭串口:{SelectedComPort} 成功!");
                    SelectedComPort = null;
                    flag            = true;
                }
#if RunIsService
                foreach (var csp in servicePorts.Values)
                {
                    if (csp.IsOpen)
                    {
                        csp.Close();
                    }
                }
#endif
                //if (sendTimer != null && sendTimer.Enabled)
                //{
                //    sendTimer.Stop();
                //    sendTimer.Elapsed -= SendTimer_Elapsed;
                //}
                //msgIndex = 0;
            }
            catch (Exception err)
            {
            }
            return(flag);
        }
Esempio n. 13
0
        private static CustomSerialPort serialHandler(ArduinoTypes SerialType, CustomSerialPort serialPort)
        {
            try
            {
                string Data = null;
                try
                {
                    Data = serialPort.ReadLine(); //TODO threw an overflow exception on logdata new
                }
                catch (InvalidOperationException)
                {
                    return(null);
                }

                Console.WriteLine($"[{serialPort.PortName}] Checking... ({SerialType.ToString()})");
                // Console.WriteLine($"DATA: {Data}");
                if (SerialType == ArduinoTypes.INS)
                {
                    if (Data.Contains("AC") || Data.Contains("GY"))
                    {
                        Console.WriteLine($"[{serialPort.PortName}] Matched!");
                        return(serialPort);
                    }
                }
                else if (SerialType == ArduinoTypes.POZYX)
                {
                    if (Data.Contains("PO"))
                    {
                        Console.WriteLine($"[{serialPort.PortName}] Matched!");
                        return(serialPort);
                    }
                }
                return(null);
            }
            catch (TimeoutException)
            {
                Console.WriteLine($"[{serialPort.PortName}] Timeout... Skipping");
                return(null);
            }
        }
Esempio n. 14
0
 public static bool OpenUart(string portName)
 {
     CloseUart();
     try
     {
         m_CSP                = new CustomSerialPort(portName);
         m_CSP.BaudRate       = baudRate;
         m_CSP.ReceivedEvent += Csp_ReceivedEvent;
         m_CSP.Open();
         //OpenUartTestTimer();
         Console.WriteLine($"打开串口:{portName} 成功!波特率:{baudRate}");
         SelectedComPort = portName;
         return(true);
     }
     catch (Exception ex)
     {
         SelectedComPort = null;
         m_CSP           = null;
         Console.WriteLine($"打开串口失败:{ex}");
     }
     return(false);
 }
Esempio n. 15
0
        private static CustomSerialPort SearchForSerialPorts(ArduinoTypes SerialType)
        {
            CustomSerialPort FoundSerialPort = null;

            while (FoundSerialPort == null)
            {
                foreach (var currentSerialPort in serialPorts)
                {
                    if (FoundSerialPort == null)
                    {
                        CustomSerialPort serialPort = serialHandler(SerialType, currentSerialPort);
                        if (serialPort != null)
                        {
                            FoundSerialPort = serialPort;
                            OpenSerialPorts.Add(FoundSerialPort);
                        }
                    }
                }
            }
            FoundSerialPort.IsMatched = true;
            return(FoundSerialPort);
        }
Esempio n. 16
0
        /// <summary>
        /// 测试串口是否成功
        /// </summary>
        /// <param name="portName"></param>
        public static void TestUart(string portName)
        {
            CustomSerialPort sp;

            try
            {
                sp = new CustomSerialPort(portName, baudRate);
                sp.Open();
                string msg;
                msg = "Hello Uart";
                sp.WriteLine(msg);
                Console.WriteLine(msg);
                msg = "Byebye Uart";
                sp.WriteLine(msg);
                sp.Close();
                sp.Dispose();
                sp = null;
                Console.WriteLine(msg);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Open Uart Exception:{ex}");
            }
        }
        static void Main(string[] args)
        {
            #region Fileds
            AsyncTcpServer server = null;
            int            totalNum = 0, rownum = 0, columnum = 0, usedcabinet = 0;
            string         rangeRule  = "";
            string         serverip   = "";
            int            serverport = 0;
            #endregion

            #region Initial

            #region 读取箱体配置文件
            try
            {
                ConfigLoad conip = new ConfigLoad(configPath);
                totalNum    = conip.GetIntValue("totalNum");
                rangeRule   = conip.GetStringValue("rangeRule");
                rownum      = conip.GetIntValue("rowNum");
                columnum    = conip.GetIntValue("colunNum");
                usedcabinet = conip.GetIntValue("usedNum");
                serverip    = conip.GetStringValue("ServerIP");
                serverport  = conip.GetIntValue("ServerPort");
            }
            catch (Exception ex)
            {
                Logger.Custom("log/", $"load config failed with error:{ex}");
            }
            strsend = totalNum.ToString("000") + "-" + rangeRule + "-" + rownum.ToString("000") + "-"
                      + columnum.ToString("000") + "-" + usedcabinet.ToString("000");
            Console.WriteLine(strsend);
            #endregion

            #region 启动服务器
            try
            {
                Console.WriteLine("sever is starting.....");
                Logger.Custom("log/", "sever is starting.....");
                server = new AsyncTcpServer(IPAddress.Parse("192.168.2.20"), 10001);
                //server = new AsyncTcpServer(IPAddress.Parse("127.0.0.1"), 10001);
                server.ClientConnected    += new EventHandler <TcpClientConnectedEventArgs>(Server_ClientConnected);
                server.ClientDisconnected += new EventHandler <TcpClientDisconnectedEventArgs>(Server_ClientDisconnected);
                server.PlaintextReceived  += new EventHandler <TcpDatagramReceivedEventArgs <string> >(Server_PlaintextReceived);
                server.Start();
                Console.WriteLine($"server is started");
                Logger.Custom("log/", "server is started");
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Logger.Custom("log/", $"server starting excetpiton:{ex.Message}");
            }
            #endregion

            #region 建立客户端
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(serverip), serverport);
            AsyncTcpClient = new AsyncTcpClient(iPEndPoint);
            //AsyncTcpClient.DatagramReceived += AsyncTcpClient_DatagramReceived;
            try
            {
                AsyncTcpClient.Connect();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Logger.Custom("log/", $"建立服务器连接出错:{ex.Message}");
            }

            #endregion

            #region 启动串口
            string[] names = CustomSerialPort.GetPortNames();
            foreach (var item in names)
            {
                Console.WriteLine(item);
            }
            try
            {
                mySer = new CustomSerialPort("/dev/COM1", 9600);
                //mySer = new CustomSerialPort("COM1", 9600);
                Console.WriteLine($"PortName:{mySer.PortName}");
                if (mySer != null)
                {
                    mySer.ReceivedEvent += MySer_DataReceived;
                    if (mySer.Open())
                    {
                        Console.WriteLine("Serial Open Success!");
                        Logger.Custom("log/", $"Serial Open Success!");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Logger.Custom("log/", $"Serial Opening exception:{ex.Message}");
            }

            #endregion

            #region 初始化逻辑
            //1是开,2关
            logicals.Clear();
            logicals.Add(new Logical("N-O-D-R", 1, "2", "1", 2));
            logicals.Add(new Logical("A-O-D-R", 1, "2", "1", 2));
            logicals.Add(new Logical("A-R-D-R", 1, "2", "1", -1));
            logicals.Add(new Logical("C-R-D-R", -1, "-1", "1", -1));
            #endregion

            #region 检查柜门状态
            lock (objPortLock)
            {
                mySer.Write(readOneall);
                Thread.Sleep(500);
                mySer.Write(readsecondAll);
                Thread.Sleep(500);
            }

            for (int i = 0; i < 60; i++)
            {
                if (CheckLockState(i + 1) == 2)
                {
                    isNormalClose[i] = true;
                }
                if (i < 3)
                {
                    Console.WriteLine($"D{i.ToString("000")} is normalClosed:{isNormalClose[i].ToString()}");
                }
            }
            #endregion

            Console.WriteLine($"状态数组当前的大小时:{sourcebyte.Length}");
            foreach (var item in sourcebyte)
            {
                Console.WriteLine(item.ToString("X"));
            }

            #endregion



            while (true)
            {
                lock (objPortLock)
                {
                    try
                    {
                        mySer.Write(readOneall);
                        Thread.Sleep(500);
                        mySer.Write(readsecondAll);
                        Thread.Sleep(500);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Logger.Custom("log/", $"主程序出错:{ex.Message}");
                    }
                }

                for (int i = 0; i < 60; i++)
                {
                    #region 检查非法开门
                    if (isNormalClose[i] && CheckLockState(i + 1) == 1 && !isSendError[i])
                    {
                        if (!AsyncTcpClient.Connected)
                        {
                            try
                            {
                                Console.WriteLine("client disconnect!");
                                AsyncTcpClient = new AsyncTcpClient(iPEndPoint);
                                AsyncTcpClient.Connect();
                                if (AsyncTcpClient.Connected)
                                {
                                    AsyncTcpClient.Send(Encoding.Default.GetBytes($"D{(i + 1).ToString("000")} is opened Illegally!"));
                                    isSendError[i] = true;
                                    Console.WriteLine($"D{i + 1}非法开门了!");
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                Logger.Custom("log/", $"建立服务器连接出错:{ex.Message}");
                            }
                        }
                        else
                        {
                            AsyncTcpClient.Send(Encoding.Default.GetBytes($"D{(i+1).ToString("000")} is opened Illegally!"));
                            isSendError[i] = true;
                            Console.WriteLine($"D{i + 1}非法开门了!");
                        }
                    }
                    #endregion

                    #region 等待非法开门关门
                    if (isSendError[i] && CheckLockState(i + 1) == 2)
                    {
                        if (!AsyncTcpClient.Connected)
                        {
                            try
                            {
                                Console.WriteLine("client disconnect!");
                                AsyncTcpClient = new AsyncTcpClient(iPEndPoint);
                                AsyncTcpClient.Connect();
                                if (AsyncTcpClient.Connected)
                                {
                                    AsyncTcpClient.Send(Encoding.Default.GetBytes($"D{(i + 1).ToString("000")} is Closed!"));
                                    isSendError[i] = false;
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                                Logger.Custom("log/", $"建立服务器连接出错:{ex.Message}");
                            }
                        }
                        else
                        {
                            AsyncTcpClient.Send(Encoding.Default.GetBytes($"D{(i+1).ToString("000")} is closed!"));
                            isSendError[i] = false;
                        }
                    }
                    #endregion
                }


                //delete threedays ago logger
                if (DateTime.Now.Hour == 0 && DateTime.Now.Minute == 0 && DateTime.Now.Second < 10)
                {
                    //删除文件
                    for (int i = 0; i < Directory.GetFiles("log").ToList().Count; i++)
                    {
                        try
                        {
                            string   filestr     = Directory.GetFiles("log")[i];
                            string   date        = filestr.Substring(4, filestr.Length - 8);
                            DateTime recoderdate = Convert.ToDateTime(date);
                            TimeSpan timespan    = DateTime.Now - recoderdate;
                            if (timespan > new TimeSpan(72, 0, 0))
                            {
                                File.Delete(Directory.GetFiles("log")[i]);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
        }
 static public void  DealWithLocks(int code, CustomSerialPort serial)
 {
     serial.Write(UnlockCmd(code));
 }
Esempio n. 19
0
 /// <summary>
 /// 获取系统的全部串口名
 /// </summary>
 /// <returns></returns>
 public static string[] GetPorts()
 {
     return(CustomSerialPort.GetPortNames());
 }
Esempio n. 20
0
        private void Form1_Load(object sender, EventArgs e)
        {
            updateComList();

            FileInfo fi = new FileInfo("config.json");

            if (fi.Exists)
            {
                string fileContent = File.ReadAllText("config.json", Encoding.UTF8);

                JObject root = JsonConvert.DeserializeObject <JObject>(fileContent);

                state.Checked = (bool)root["enable"];
                var lastBaudrate = (int)root["last_baudrate"];
                var lastCom      = (string)root["last_com"];
                startMinimun.Checked = (bool)root["start_minimun"];
                startOpen.Checked    = (bool)root["start_open"];

                if (lastBaudrate != 0)
                {
                    baudrate.Text = lastBaudrate.ToString();
                }
                else
                {
                    baudrate.SelectedIndex = 2;
                }

                if (comSelect.Items.Count == 1 && lastCom.Length == 0)
                {
                    comSelect.SelectedIndex = 0;
                }
                else
                {
                    foreach (var item in CustomSerialPort.GetPortNames())
                    {
                        if (item == lastCom)
                        {
                            comSelect.Text = lastCom;
                            break;
                        }
                    }
                }

                if (startMinimun.Checked)
                {
                    Thread thread = new Thread(new ThreadStart(() =>
                    {
                        Thread.Sleep(1000);
                        Visible = false;
                    }));
                    thread.Start();
                }

                if (startOpen.Checked)
                {
                    openSerial();
                }

                JArray ja = (JArray)root["pairs"];
                foreach (var item in ja)
                {
                    RulePair rp = new RulePair();
                    rp.keyCode = (string)item["keycode"];
                    rp.lable   = (string)item["lable"];

                    pairs.Add(Int32.Parse((string)item["ircode"]), rp);
                }

                updateRulesList();

                //rulesList.Items.
            }
        }