예제 #1
0
 public SerialPortView()
 {
     InitializeComponent();
     try
     {
         serialPort                = new SerialPortEx();
         serialPort.BaudRate       = 115200;
         serialPort.ReadTimeout    = 2000;
         serialPort.WriteTimeout   = 1000;
         serialPort.ReadBufferSize = 8192;
         serialPort.DtrEnable      = true;
         serialPort.Disposed      += new EventHandler(serialPort_Disposed);
         serialPort.DataReceived  += new SerialDataReceivedEventHandler(serialPort_DataReceived);
         cBoxSerialPort.Items.Clear();
         foreach (object newItem in SerialPortEx.GetPortNamesEx())
         {
             cBoxSerialPort.Items.Add(newItem);
         }
         cBoxSerialPort.SelectionChanged += new SelectionChangedEventHandler(cBoxSerialPort_SelectionChanged);
         if (cBoxSerialPort.Items.Count <= 0)
         {
             SerialToggle.IsEnabled = false;
         }
         cBoxSerialPort.SelectedIndex = Convert.ToInt32(Settings.Default.SerialPortIndex);
     }
     catch (Exception ex)
     {
         Console.WriteLine("serial port : {0}", (object)ex);
     }
 }
예제 #2
0
        public override void Run(CancellationToken token)
        {
            //create an UART port
            using (var uart = new SerialPortEx())
            {
                //open the serial port
                uart.PortName = HardwareModel.Instance.SerialPort;
                uart.Open();

                var prm = new SerialPortParams(
                    HardwareModel.Instance.SerialSettings,
                    false);

                //create a wrapper around the uart
                ICommClient medium = uart
                                     .GetClient(prm);

                //create a client driver
                var driver = new ModbusClient(new ModbusRtuCodec());
                driver.Address = (byte)HardwareModel.Instance.Address;

                //run actual task
                base.RunCore(
                    medium,
                    driver,
                    token);
            }
        }
예제 #3
0
        /// <summary>
        /// 完成串口对设备的连接
        /// </summary>
        /// <param name="connectionDevice">连接的设备</param>
        /// <param name="useDevice">使用的设备</param>
        public static void CompleteSerialPortConnection(SerialPortEx serial, IDevice device)
        {
            serial.Name             = device.SerialPortDevice.Name;
            serial.Index            = device.SerialPortDevice.Index;
            device.SerialPortDevice = serial;
            device.SetDataReceived();

            ViewCallFunction.ViewSerialPortChanged(device.SerialPortDevice);
        }
예제 #4
0
        public DistanceDevice(SerialPortEx serial, string name)
        {
            SerialPortDevice = serial;
            SetDataReceived();
            if (!string.IsNullOrEmpty(name))
            {
                SerialPortDevice.Name = name;
            }

            m_Validation = new DataValidation();
        }
예제 #5
0
        public static SerialPortEx CreateSerialPort()
        {
            SerialPortEx serialPort = new SerialPortEx()
            {
                StopBit  = WinApi.STOP_1,
                DataBit  = WinApi.BIT_8,
                BaudRate = WinApi.B19200,
                Parity   = WinApi.p_NONE,
            };

            return(serialPort);
        }
        public SerialDataManager()
        {
            int tickInterval = 100;

            key                       = new object();//创建一个资源
            serialPortEx              = new SerialPortEx();
            serialPortEx.DataArrived += new ShouldPadMachineAssist.DelegateEx.DataArrivedEventHandle(SerialPortEx_DataArrived);
            serialDataHelper          = new SerialDataHelper(tickInterval);
            sendDataManager           = new SendDataManager();
            formTimer                 = new Timer();
            formTimer.Interval        = tickInterval;
            formTimer.Tick           += new EventHandler(FormTimer_Tick);
            serialDataModelCollect    = new SerialDataModelCollect();
        }
예제 #7
0
 private static void ReplaceSerialPort(IDevice device)
 {
     try
     {
         m_SerialPort.DataReceived -= SerialPortDataReceived;
     }
     catch (Exception ex)
     {
         Log4Helper.ErrorInfo(ex.Message, ex);
     }
     SerialPortManager.CompleteSerialPortConnection(m_SerialPort, device);
     m_SerialPort = null;
     m_Validation.Dispose();
 }
예제 #8
0
        public PersonnelDevice(SerialPortEx serial, string name)
        {
            SerialPortDevice          = serial;
            SerialPortDevice.BaudRate = WinApi.B9600;

            SetDataReceived();
            if (!string.IsNullOrEmpty(name))
            {
                SerialPortDevice.Name = name;
            }

            m_Validation = new DataValidation();
            m_Validation.DealHeadEnds.Add(new DealHeadEnd(10, 13));
            m_Validation.DealHeadEnds.Add(new DealHeadEnd(9, 12));
        }
예제 #9
0
        public async static void DoTest()
        {
            using (var port = new SerialPortEx())
            {
                port.PortName = "COM3";
                port.Open();
                Console.WriteLine("PortOpen={0}", port.IsOpen);

                var portSetting = new SerialPortParams(
                    "38400,E,8,1",
                    rtsEnable: false);

                ICommClient portClient = port.GetClient(portSetting);

                var clients = Enumerable
                              .Range(0, 10)
                              .Select(_ =>
                                      new TestModbusRtuClient
                {
                    Name    = "Modbus client #" + _,
                    Address = 0x01,
                })
                              .ToList();

                CommResponse[] result = await Task.WhenAll(
                    clients
                    .Select(_ => _.ExecuteWriteMulti(portClient))
                    );

                foreach (var r in result)
                {
                    var    owner = (TestModbusRtuClient)r.Data.OwnerProtocol;
                    string hex   = null;

                    if (r.Data.IncomingData != null)
                    {
                        hex = ByteArrayHelpers.ToHex(r.Data.IncomingData.ToByteArray());
                    }

                    Console.WriteLine(
                        "Owner={0}; {1}; {2}",
                        owner.Name,
                        r.Status,
                        hex
                        );
                }
            }
        }
예제 #10
0
        public override void Run(CancellationToken token)
        {
            //create an UART port
            using (var uart = new SerialPortEx())
            {
                //open the serial port
                uart.PortName = HardwareModel.Instance.SerialPort;
                uart.Open();

                var prm = new SerialPortParams(
                    HardwareModel.Instance.SerialSettings,
                    false);

                uart.SetParams(prm);

                //create a server driver
                var server = new ModbusServer(new ModbusRtuCodec());
                server.Address = (byte)HardwareModel.Instance.Address;

                while (token.IsCancellationRequested == false)
                {
                    //wait for an incoming connection
                    var listener = uart.GetServer(server);
                    listener.ServeCommand += new ServeCommandHandler(ListenerServeCommand);
                    listener.Start();

                    while (listener.IsRunning)
                    {
                        if (token.IsCancellationRequested)
                        {
                            listener.Abort();
                        }
                        else
                        {
                            Thread.Sleep(1);
                        }
                    }
                }
            }
        }
예제 #11
0
 private static void CurrentPortIsDisconnected(SerialPortEx serial, List <string> serialPortNames)
 {
     try
     {
         foreach (var item in serialPortNames)
         {
             if (serial.PortName == item)
             {
                 return;
             }
         }
         SerialPortManager.CloseSerialPort(serial);
     }
     catch (Exception ex)
     {
         Log4Helper.ErrorInfo(ex.Message, ex);
     }
     finally
     {
         ViewCallFunction.ViewSerialPortChanged(serial);
     }
 }
예제 #12
0
        private void cBoxSerialPort_DropDownOpened(object sender, EventArgs e)
        {
            object selectedItem  = cBoxSerialPort.SelectedItem;
            int    selectedIndex = cBoxSerialPort.SelectedIndex;

            cBoxSerialPort.SelectionChanged -= new SelectionChangedEventHandler(cBoxSerialPort_SelectionChanged);
            cBoxSerialPort.Items.Clear();

            foreach (object newItem in SerialPortEx.GetPortNamesEx())
            {
                cBoxSerialPort.Items.Add(newItem);
            }

            cBoxSerialPort.SelectionChanged += new SelectionChangedEventHandler(cBoxSerialPort_SelectionChanged);
            cBoxSerialPort.SelectedItem      = selectedItem;
            if (cBoxSerialPort.Items.Count <= 0)
            {
                SerialToggle.IsEnabled = false;
            }
            else
            {
                SerialToggle.IsEnabled = true;
            }
        }
예제 #13
0
        public static void Main()
        {
            //setup the board IP
            NetworkInterface.GetAllNetworkInterfaces()[0]
            .EnableStaticIP("192.168.0.99", "255.255.255.0", "192.168.0.1");

            string localip = NetworkInterface.GetAllNetworkInterfaces()[0]
                             .IPAddress;

            Debug.Print("The local IP address of your Netduino Plus is " + localip);

            //define coils, inputs, and analogs
            _inputs = new InputPort[8];
#if SLAVE_RTU
            _inputs[0] = new InputPort(Pins.GPIO_PIN_D0, true, Port.ResistorMode.PullUp);
            _inputs[1] = new InputPort(Pins.GPIO_PIN_D1, true, Port.ResistorMode.PullUp);
            _inputs[2] = null;
            _inputs[3] = null;
            _inputs[4] = new InputPort(Pins.GPIO_PIN_D4, true, Port.ResistorMode.PullUp);
            _inputs[5] = new InputPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.PullUp);
            _inputs[6] = new InputPort(Pins.GPIO_PIN_D6, true, Port.ResistorMode.PullUp);
            _inputs[7] = new InputPort(Pins.GPIO_PIN_D7, true, Port.ResistorMode.PullUp);
#else
            _inputs[0] = new InputPort(Pins.GPIO_PIN_D0, true, Port.ResistorMode.PullUp);
            _inputs[1] = new InputPort(Pins.GPIO_PIN_D1, true, Port.ResistorMode.PullUp);
            _inputs[2] = new InputPort(Pins.GPIO_PIN_D2, true, Port.ResistorMode.PullUp);
            _inputs[3] = new InputPort(Pins.GPIO_PIN_D3, true, Port.ResistorMode.PullUp);
            _inputs[4] = new InputPort(Pins.GPIO_PIN_D4, true, Port.ResistorMode.PullUp);
            _inputs[5] = new InputPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.PullUp);
            _inputs[6] = new InputPort(Pins.GPIO_PIN_D6, true, Port.ResistorMode.PullUp);
            _inputs[7] = new InputPort(Pins.GPIO_PIN_D7, true, Port.ResistorMode.PullUp);
#endif

            _coils    = new OutputPort[6];
            _coils[0] = new OutputPort(Pins.GPIO_PIN_D8, false);
            _coils[1] = new OutputPort(Pins.GPIO_PIN_D9, false);
            _coils[2] = new OutputPort(Pins.GPIO_PIN_D10, false);
            _coils[3] = new OutputPort(Pins.GPIO_PIN_D11, false);
            _coils[4] = new OutputPort(Pins.GPIO_PIN_D12, false);
            _coils[5] = new OutputPort(Pins.GPIO_PIN_D13, false);

#if MF_FRAMEWORK_VERSION_V4_1
            _analogs    = new AnalogInput[6];
            _analogs[0] = new AnalogInput(Pins.GPIO_PIN_A0);
            _analogs[1] = new AnalogInput(Pins.GPIO_PIN_A1);
            _analogs[2] = new AnalogInput(Pins.GPIO_PIN_A2);
            _analogs[3] = new AnalogInput(Pins.GPIO_PIN_A3);
            _analogs[4] = new AnalogInput(Pins.GPIO_PIN_A4);
            _analogs[5] = new AnalogInput(Pins.GPIO_PIN_A5);
#elif MF_FRAMEWORK_VERSION_V4_2
            _analogs    = new AnalogInput[6];
            _analogs[0] = new AnalogInput(Cpu.AnalogChannel.ANALOG_0);
            _analogs[1] = new AnalogInput(Cpu.AnalogChannel.ANALOG_1);
            _analogs[2] = new AnalogInput(Cpu.AnalogChannel.ANALOG_2);
            _analogs[3] = new AnalogInput(Cpu.AnalogChannel.ANALOG_3);
            _analogs[4] = new AnalogInput(Cpu.AnalogChannel.ANALOG_4);
            _analogs[5] = new AnalogInput(Cpu.AnalogChannel.ANALOG_5);
#endif

#if MASTER_TCP
            //create a TCP socket
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                //refine the socket settings
                socket.SetSocketOption(
                    SocketOptionLevel.Tcp,
                    SocketOptionName.NoDelay,
                    true
                    );

                socket.SendTimeout    = 2000;
                socket.ReceiveTimeout = 2000;

                //try the connection against the remote device
                var remoteip = new byte[4] {
                    192, 168, 0, 100
                };
                var ipaddr = new IPAddress(remoteip);
                var ept    = new IPEndPoint(ipaddr, 502);
                socket.Connect(ept);

                //create a wrapper around the socket
                ICommClient portClient = socket.GetClient();

                //create a client driver
                var driver = new ModbusClient(new ModbusTcpCodec());
                driver.Address = DeviceAddress;

                while (true)
                {
                    //compose the Modbus command to be submitted
                    var command = new ModbusCommand(ModbusCommand.FuncReadInputDiscretes);
                    command.Offset = 0;
                    command.Count  = 6;

                    //execute the command synchronously
                    CommResponse result = driver
                                          .ExecuteGeneric(portClient, command);

                    if (result.Status == CommResponse.Ack)
                    {
                        //command successfully
                        for (int i = 0; i < command.Count; i++)
                        {
                            _coils[i + command.Offset].Write(command.Data[i] != 0);
                        }
                    }
                    else
                    {
                        //some error
                        Debug.Print("Error=" + command.ExceptionCode);
                    }

                    //just a small delay
                    Thread.Sleep(100);
                }
            }
#endif

#if MASTER_UDP
            //create a UDP socket
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                //try the connection against the remote device
                var remoteip = new byte[4] {
                    192, 168, 0, 60
                };
                var ipaddr = new IPAddress(remoteip);
                var ept    = new IPEndPoint(ipaddr, 502);
                socket.Connect(ept);

                //create a wrapper around the socket
                ICommClient portClient = socket.GetClient();

                //create a client driver
                var driver = new ModbusClient(new ModbusTcpCodec());
                driver.Address = DeviceAddress;

                while (true)
                {
                    //compose the Modbus command to be submitted
                    var command = new ModbusCommand(ModbusCommand.FuncReadMultipleRegisters);
                    command.Offset = 0;
                    command.Count  = 16;

                    //execute the command synchronously
                    CommResponse result = driver
                                          .ExecuteGeneric(portClient, command);

                    if (result.Status == CommResponse.Ack)
                    {
                        //command successfully
                        Debug.Print("Success!");
                        for (int i = 0; i < command.Count; i++)
                        {
                            Debug.Print("Reg#" + i + "=" + command.Data[i]);
                        }
                    }
                    else
                    {
                        //some error
                        Debug.Print("Error=" + command.ExceptionCode);
                    }

                    //just a small delay
                    Thread.Sleep(1000);
                }
            }
#endif

#if MASTER_RTU
            //create an UART port
            using (var uart = new SerialPortEx("COM2", 38400, Parity.Even, 8, StopBits.One))
            {
                //open the serial port
                uart.Open();

                var prm = new SerialPortParams("38400,E,8,1");

                //create a wrapper around the uart
                ICommClient portClient = uart
                                         .GetClient(prm);

                //create a client driver
                var driver = new ModbusClient(new ModbusRtuCodec());
                driver.Address = DeviceAddress;

                while (true)
                {
                    //compose the Modbus command to be submitted
                    var command = new ModbusCommand(ModbusCommand.FuncWriteMultipleRegisters);
                    command.Offset = 49;
                    command.Count  = 4;

                    //attach the Netduino's input values as data
                    command.Data = new ushort[4];
                    for (int i = 0; i < 4; i++)
                    {
                        command.Data[i] = (ushort)(_inputs[i].Read() ? 0 : 1);
                    }

                    //execute the command synchronously
                    CommResponse result = driver
                                          .ExecuteGeneric(portClient, command);

                    if (result.Status == CommResponse.Ack)
                    {
                        //command successfully
                    }
                    else
                    {
                        //some error
                        Debug.Print("Error=" + command.ExceptionCode);
                    }

                    //just a small delay
                    Thread.Sleep(1000);
                }
            }
#endif

#if SLAVE_TCP
            //create a TCP socket
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                //place it as listener on the port 502 (standard Modbus)
                var ept = new IPEndPoint(IPAddress.Any, 502);
                socket.Bind(ept);
                socket.Listen(10);

                //create a server driver
                var server = new ModbusServer(new ModbusTcpCodec());
                server.Address = DeviceAddress;

                while (true)
                {
                    //wait for an incoming connection
                    var listener = socket.GetTcpListener(server);
                    listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand);
                    listener.Start();

                    Thread.Sleep(1);
                }
            }
#endif

#if SLAVE_UDP
            //create a UDP socket
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                //bind it to the port 502 (standard Modbus)
                var ept = new IPEndPoint(IPAddress.Any, 502);
                socket.Bind(ept);

                //create a server driver
                var server = new ModbusServer(new ModbusTcpCodec());
                server.Address = DeviceAddress;

                //listen for an incoming request
                var listener = socket.GetUdpListener(server);
                listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand);
                listener.Start();

                Thread.Sleep(Timeout.Infinite);
            }
#endif

#if SLAVE_RTU
            //create an UART port
            using (var uart = new SerialPortEx("COM2", 38400, Parity.Even, 8, StopBits.One))
            {
                //open the serial port
                uart.Open();

                //create a server driver
                var server = new ModbusServer(new ModbusRtuCodec());
                server.Address = DeviceAddress;

                while (true)
                {
                    //wait for an incoming connection
                    var listener = uart.GetServer(server);
                    listener.ServeCommand += new ServeCommandHandler(listener_ServeCommand);
                    listener.Start();

                    while (listener.IsRunning)
                    {
                        Thread.Sleep(1);
                    }
                }
            }
#endif
        }
예제 #14
0
 public DUTController()
 {
     m_ComPort = new SerialPortEx();
     m_ComPort.SetDetectString("\r\n");
 }
예제 #15
0
 public static void CloseSerialPort(SerialPortEx port)
 {
     port.Close();
 }
예제 #16
0
        /// <summary>
        /// 端口变化时消息
        /// </summary>
        /// <param name="port"></param>
        public static void ViewSerialPortChanged(SerialPortEx port)
        {
            string json = Utility.JsonSerializerBySingleData <SerialPortEx>(port);

            Main.GetMain.ExecuteJavascript($"ViewSerialPortChanged('{json}')");
        }
예제 #17
0
        public MainWindow()
        {
            InitializeComponent();
            AppConfigManager app = new AppConfigManager();
            var style            = (Style)this.TryFindResource("ViewUCStyle");
            var mainPage         = new MainPage();

            mainPage.Style = style;
            mainPageGrid.Children.Add(mainPage);

            var signalSettingPage = new SignalSettingPage();

            signalSettingPage.Style = style;
            signalSettingPageGrid.Children.Add(signalSettingPage);

            var resultAdjudgeSettingPage = new ResultAdjudgeSettingPage();

            resultAdjudgeSettingPage.Style = style;
            resultAdjudgeSettingPageGrid.Children.Add(resultAdjudgeSettingPage);

            var controlPage = new ControlPage();

            controlPage.Style = style;
            controlPageGrid.Children.Add(controlPage);

            var resultPage = new ResultPage();

            resultPage.Style = style;
            resultPageGrid.Children.Add(resultPage);

            var vm = new MainWindowVM();

            vm.Init();
            vm.AddCommands(this);

            vm.PageNameAndVMDic.Add(MainWindowVM.MAIN_PAGE, mainPage.VM);
            vm.PageNameAndVMDic.Add(MainWindowVM.SIGNAL_SETTING_PAGE, signalSettingPage.VM);
            vm.PageNameAndVMDic.Add(MainWindowVM.RESULT_ADJUDGE_SETTING_PAGE, resultAdjudgeSettingPage.VM);
            vm.PageNameAndVMDic.Add(MainWindowVM.CONTROL_PAGE, controlPage.VM);
            vm.PageNameAndVMDic.Add(MainWindowVM.RESULT_PAGE, resultPage.VM);

            vm.InitObservers();

            VM = vm;
            this.InitCommandBindings();
            this.DataContext = VM;

            var deviceEnumerator = new MMDeviceEnumerator();

            foreach (var d in deviceEnumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active))
            {
                if (d.FriendlyName.Contains(app.GetAppValue("CardDevicesOne")))
                {
                    d.AudioEndpointVolume.MasterVolumeLevelScalar = Convert.ToInt32(app.GetAppValue("CardDevicesOneVolume")) / 100.0f;
                }
                if (d.FriendlyName.Contains(app.GetAppValue("CardDevicesTwo")))
                {
                    d.AudioEndpointVolume.MasterVolumeLevelScalar = Convert.ToInt32(app.GetAppValue("CardDevicesTwoVolume")) / 100.0f;
                }
            }



            try
            {
                ISerial serialPort = new SerialPortEx(TesterConfig.Instance.GetApplicationCom);
                //serialPort.Wirte("ff", 1);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Assert(false, "程序启动时写入ff失败");
                throw;
            }



            //aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

            //aTimer.Interval = 1000;    // 1秒 = 1000毫秒
            //aTimer.Start();
            HistoryTimer hisTimer = new HistoryTimer();
        }
예제 #18
0
 public static void OpenSerialPort(SerialPortEx port, string portName)
 {
     port.PortName = portName;
     port.Open();
 }
예제 #19
0
 public MKoneFCT()
 {
     m_ComPort = new SerialPortEx();
     m_ComPort.SetDetectString("\r\n");
 }
예제 #20
0
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();
        // Let scroll disappear
        // textviewTextSL.SetScrollAdjustments (GtkScrolledWindowTextSL.Hadjustment, GtkScrolledWindowTextS.Vadjustment);

        // GtkScrolledWindowTextSL.Vadjustment.Lower=0;
        // GtkScrolledWindowTextSL.Vadjustment.Value=0;
        // GtkScrolledWindowTextSL.Vadjustment.Upper=0;

        textviewSend.Buffer.Changed += HandleTextviewSendBufferChanged;
        #region 初始化串口名称
        // 初始化串口名称与comboboxentry
        comboboxentryPortName.Model = portNameModel;
        InitializationPortName();
        SettingsSynchronization();

        MyPort = new SerialPortEx(portName, baudRate, parity, dataBits, stopBits);
        MyPort.DataReceived += new SerialDataReceivedEventHandler(HandleMyPortDataReceived);
        Console.WriteLine("Port initializated");
        #endregion
        #region 初始化发送模式
        // 初始化发送模式
        switch (SendMode)
        {
        case ConvertMode.Text:
            radiobuttonText.Active = true;
            break;

        case ConvertMode.Hex:
            radiobuttonHex.Active = true;
            break;

        case ConvertMode.Dec:
            radiobuttonDec.Active = true;
            break;
        }
        #endregion
        #region 初始化发送定时器
        // 初始化发送定时器
        SendTimer               = new System.Timers.Timer();
        SendTimer.Elapsed      += HandleSendTimerElapsed;
        SendTimer.Interval      = Convert.ToDouble(spinbuttonInterval.Text);
        SendTimer.AutoReset     = true;
        SendTimer.Enabled       = false;
        PortNameTimer           = new System.Timers.Timer();
        PortNameTimer.Elapsed  += HandlePortNameTimerElapsed;
        PortNameTimer.Interval  = 700;
        PortNameTimer.AutoReset = true;
        PortNameTimer.Enabled   = true;
        // 自动复位定时器,一直能触发
        #endregion

        moverText.TextView  = textviewText;
        moverHex.TextView   = textviewHex;
        moverDec.TextView   = textviewDec;
        moverTextS.TextView = textviewTextS;
        moverHexS.TextView  = textviewHexS;
        moverDecS.TextView  = textviewDecS;

        GtkScrolledWindowText.Vadjustment.ValueChanged += delegate(object sender, EventArgs e) {
//						Gtk.Adjustment adjustment = (Gtk.Adjustment)sender;
            processScrollEvent(ConvertMode.Text, false);
        };
        GtkScrolledWindowHex.Vadjustment.ValueChanged += delegate(object sender, EventArgs e) {
            //						Gtk.Adjustment adjustment = (Gtk.Adjustment)sender;
            processScrollEvent(ConvertMode.Hex, false);
        };
        GtkScrolledWindowDec.Vadjustment.ValueChanged += delegate(object sender, EventArgs e) {
            //						Gtk.Adjustment adjustment = (Gtk.Adjustment)sender;
            processScrollEvent(ConvertMode.Dec, false);
        };
        GtkScrolledWindowTextS.Vadjustment.ValueChanged += delegate(object sender, EventArgs e) {
            processScrollEvent(ConvertMode.Text, true);
        };
        GtkScrolledWindowHexS.Vadjustment.ValueChanged += delegate(object sender, EventArgs e) {
            processScrollEvent(ConvertMode.Hex, true);
        };
        GtkScrolledWindowDecS.Vadjustment.ValueChanged += delegate(object sender, EventArgs e) {
            processScrollEvent(ConvertMode.Dec, true);
        };

        scrolledTextViewTimer          = new System.Timers.Timer();
        scrolledTextViewTimer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e) {
            Gdk.Threads.Enter();
            processScrollEvent(ConvertMode.Text, false);
            processScrollEvent(ConvertMode.Hex, false);
            processScrollEvent(ConvertMode.Dec, false);
            processScrollEvent(ConvertMode.Text, true);
            processScrollEvent(ConvertMode.Hex, true);
            processScrollEvent(ConvertMode.Dec, true);
            Gdk.Threads.Leave();
        };
        scrolledTextViewTimer.Interval  = 100;
        scrolledTextViewTimer.AutoReset = true;
        scrolledTextViewTimer.Enabled   = true;
    }
예제 #21
0
        private static void OnTimerEvent(object sender, ElapsedEventArgs e)
        {
            m_StartTimer = true;
            byte[] by = null;
            try
            {
                for (int i = 0; i < 3; i++)
                {
                    if (m_StopTimer)
                    {
                        return;
                    }
                    foreach (string portName in SearchSerialPort.SerialPortNames)
                    {
                        if (m_StopTimer)
                        {
                            return;
                        }

                        m_Over = false;
                        if (m_SerialPort == null)
                        {
                            m_SerialPort = SerialPortManager.CreateSerialPort();
                            m_SerialPort.DataReceived += SerialPortDataReceived;
                        }

                        m_SerialPort.PortName = portName;
                        try
                        {
                            m_SerialPort.BaudRate = WinApi.B19200;
                            m_SerialPort.Open();

                            if (!SerialPortManager.Device1.SerialPortDevice.IsOpen)
                            {
                                if (m_StopTimer)
                                {
                                    return;
                                }
                                try
                                {
                                    by = PortAgreement.DistanceDeviceEncryption(DefaultParams.DEVICEDEFAULTCLIENTNUMBER, DefaultParams.DEVICEDEFAULTPASSWORD);
                                    m_SerialPort.Write(by);

                                    bool ret = WaitResult(SerialPortManager.Device1);
                                    if (ret)
                                    {
                                        continue;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log4Helper.ErrorInfo(ex.Message, ex);
#if DEBUG
                                    Console.WriteLine(ex.Message);
#endif
                                }
                            }

                            m_SerialPort.SetBaudRate(WinApi.B9600);
                            Thread.Sleep(50);

                            if (!SerialPortManager.Device2.SerialPortDevice.IsOpen)
                            {
                                int address = 1;
                                try
                                {
                                    for (int number = 1; number <= 50; number++)
                                    {
                                        address = number;
                                        if (m_StopTimer)
                                        {
                                            return;
                                        }
                                        by = PortAgreement.CorridorReadCardData(number);
                                        m_SerialPort.Write(by);
                                        Thread.Sleep(50);
                                        if (m_Over)
                                        {
                                            ReplaceSerialPort(SerialPortManager.Device2);
                                            break;
                                        }
                                    }

                                    if (m_Over)
                                    {
                                        continue;
                                    }
                                    bool ret = WaitResult(SerialPortManager.Device2);
                                    if (ret)
                                    {
                                        continue;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log4Helper.ErrorInfo(ex.Message, ex);
#if DEBUG
                                    Console.WriteLine(ex.Message);
#endif
                                }
                                finally
                                {
                                    SerialPortManager.Device2Address = address;
                                }
                            }

                            m_SerialPort.Close();
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log4Helper.ErrorInfo(ex.Message, ex);
#if DEBUG
                Console.WriteLine(ex.Message);
#endif
            }
            finally
            {
                by = null;
                m_Validation.Dispose();
                if (m_SerialPort != null && m_SerialPort.IsOpen)
                {
                    m_SerialPort.Close();
                }
                m_SerialPort = null;
                if (!m_StopTimer && (!SerialPortManager.Device1.SerialPortDevice.IsOpen && !SerialPortManager.Device2.SerialPortDevice.IsOpen))
                {
                    ViewCallFunction.ViewConnectionFailedMessage();
                }
                m_StartTimer = false;
            }
        }
예제 #22
0
파일: Main.cs 프로젝트: makejack/TestTools
        public Main()
            : base("http://res.app.local/main.html")
        {
            InitializeComponent();
            GetMain = this;

            this.Load += OnLoadForm;

            LoadHandler.OnLoadEnd += (sender, args) =>
            {
                PortMonitor.StartMonitor();
            };

            GlobalObject.AddFunction("ShowDevTools").Execute += (sender, args) =>
            {
                Chromium.ShowDevTools();
            };

            GlobalObject.AddFunction("HostOpenAndCloseSerialDevice").Execute += (sender, args) =>
            {
                try
                {
                    var          callback   = args.Arguments.FirstOrDefault(e => e.IsFunction);
                    string       deviceName = args.Arguments[0].StringValue;
                    SerialPortEx serial     = SelectSerialDevice(deviceName);
                    string       portName   = args.Arguments[1].StringValue;
                    if (!serial.IsOpen)
                    {
                        SerialPortManager.OpenSerialPort(serial, portName);
                    }
                    else
                    {
                        SerialPortManager.CloseSerialPort(serial);
                    }
                    string json = Utility.JsonSerializerBySingleData(serial);
                    callback.ExecuteFunction(null, new Chromium.Remote.CfrV8Value[] { json });
                }
                catch (Exception ex)
                {
                    Log4Helper.ErrorInfo(ex.Message, ex);
                    ViewCallFunction.ViewAlert(ex.Message);
                }
            };

            GlobalObject.AddFunction("HostAutoConnectionDeviced").Execute += (sender, args) =>
            {
                try
                {
                    bool autoConnection = args.Arguments[0].BoolValue;
                    if (autoConnection)
                    {
                        ConnectionSerialDevice.Start();
                    }
                    else
                    {
                        ConnectionSerialDevice.Stop();
                    }
                    ConnectionSerialDevice.AutoConnectioinDevice = autoConnection;
                }
                catch (Exception ex)
                {
                    Log4Helper.ErrorInfo(ex.Message, ex);
                    ViewCallFunction.ViewAlert(ex.Message);
                }
            };

            CardManagerEvh.InitEvent();
            PwdManagerEvh.InitEvent();
            ConfigureManagerEvh.InitEvent();
            WirelessManagerEvh.InitEvent();
            UserManagerEvh.InitEvent();
        }
예제 #23
0
        private void Application_Exit(object sender, ExitEventArgs e)
        {
            if (PlayerModel.afrOne != null)
            {
                PlayerModel.afrOne.Dispose();
                PlayerModel.afrOne = null;
            }
            if (PlayerModel.afrTwo != null)
            {
                PlayerModel.afrTwo.Dispose();
                PlayerModel.afrTwo = null;
            }

            if (PlayerModel.loopOne != null)
            {
                PlayerModel.loopOne.Dispose();
                PlayerModel.loopOne = null;
            }
            if (PlayerModel.loopTwo != null)
            {
                PlayerModel.loopTwo.Dispose();
                PlayerModel.loopTwo = null;
            }

            if (PlayerModel._dsOne != null)
            {
                PlayerModel._dsOne.Dispose();
                PlayerModel._dsOne = null;
            }
            if (PlayerModel._dsTwo != null)
            {
                PlayerModel._dsTwo.Dispose();
                PlayerModel._dsTwo = null;
            }

            if (PlayerModel.wgOne != null)
            {
                PlayerModel.wgOne = null;
            }
            if (PlayerModel.wgTwo != null)
            {
                PlayerModel.wgTwo = null;
            }


            try
            {
                ISerial serialPort = new SerialPortEx(TesterConfig.Instance.GetApplicationCom);
                serialPort.Wirte("09", 1);
                serialPort.Close();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Assert(false, "程序关闭时写入09失败");
                throw;
            }
            if (Cache.Instance.Contexts != null && Cache.Instance.Contexts.Any())
            {
                try
                {
                    //关闭所有的串口
                    Cache.Instance.Contexts.ForEach(c =>
                    {
                        c.Release();
                    });
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }
            }
        }