Esempio n. 1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="port"></param>
 /// <param name="portName"></param>
 /// <param name="portType"></param>
 /// <returns>端口是否被占用</returns>
 private static bool PortCheckAndShowMessageBox(int port, string portName, PortType portType = PortType.Both)
 {
     if (!PortHelper.PortInUse(port, portType))
     {
         return(false);
     }
     MessageBoxX.Show(i18N.TranslateFormat("The {0} port is in use.", portName));
     return(true);
 }
Esempio n. 2
0
 private void AllGetPortNamesAreInHelperPorts()
 {
     string[] helperPortNames = PortHelper.GetPorts();
     foreach (string serialPortName in SerialPort.GetPortNames())
     {
         Assert.True(helperPortNames.Contains(serialPortName),
                     $"{serialPortName} is not present in PortHelper.GetPorts result\r\n{PortInformationString}");
     }
 }
Esempio n. 3
0
 private void ModuleTest()
 {
     _isModuleSet = false;
     byte[] by = PortAgreement.GetSetModule("ABCDEF");
     if (PortHelper.IsConnection)
     {
         PortHelper.SerialPortWrite(by);
         Thread.Sleep(150);
     }
 }
Esempio n. 4
0
        public bool ResetPort()
        {
            Console.WriteLine($"device: reset device with instanceId: {instanceId}");
            bool result = PortHelper.TryResetPortByInstanceId(instanceId);

            // Search for new devices attaching
            RescanForHardwareChanges();

            return(result);
        }
Esempio n. 5
0
 private void SetModuleTid(int id)
 {
     _isModuleSet = false;
     byte[] by = PortAgreement.GetSetModule(string.Format("AT+TID=01{0}", id.ToString().PadLeft(8, '0')));
     if (PortHelper.IsConnection)
     {
         PortHelper.SerialPortWrite(by);
         Thread.Sleep(150);
     }
 }
Esempio n. 6
0
        /// <summary>
        /// 自动连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Rbtn_AutoConnection_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtn_AutoConnection.Checked)
            {
                cb_SerialPortName.Enabled        = false;
                btn_SerialPortConnection.Enabled = false;

                PortHelper.SetAutoDevice(true);
            }
        }
Esempio n. 7
0
 private void SetModuleComesBack(int value)
 {
     _isModuleSet = false;
     byte[] by = PortAgreement.GetSetModule(string.Format("AT+BACK={0}", value));
     if (PortHelper.IsConnection)
     {
         PortHelper.SerialPortWrite(by);
         Thread.Sleep(150);
     }
 }
Esempio n. 8
0
 public IOHelper(CardHelper card, IOSetInfo ioSet, AxisSetInfo axisSet, AbsolutePosSetInfo apSet, PortHelper plcHelper, PortHelper _232Helper, FormMain form)
 {
     this.card       = card;
     this.form       = form;
     this.ioSet      = ioSet;
     this.axisSet    = axisSet;
     this.apSet      = apSet;
     this.plcHelper  = plcHelper;
     this._232Helper = _232Helper;
 }
Esempio n. 9
0
        /// <summary>
        /// 解析数据
        /// 0,申请关闭服务
        /// 1,申请开启服务,带端口
        /// </summary>
        /// <param name="s"></param>
        public void Analysis(string s)
        {
            string[] r = s.Split(',');
            if (r[0] == "check")    //验证
            {
                if (r[1] != "1.0.1")
                {
                    ns.H_Send("fail,客户端版本过低 请更新版本");
                    connentHost.serverModels.FirstOrDefault(l => l.machineCode == r[5])?.DisClientConn();
                    machineCode = r[5];
                }
                else
                {
                    ns.H_Send("pass");
                }
            }
            else if (r[0] == "stop")    //申请关闭服务
            {
                DisClientConn();
            }
            else if (r[0] == "s_Start")    //申请开启服务
            {
                int  outPort = Convert.ToInt32(r[1]);
                bool b       = PortHelper.PortInUse(outPort);
                if (b)                                   //如果申请的端口正在使用
                {
                    ns.H_Send("s_PortOccupied," + r[4]); //拒绝
                }
                else
                {
                    ns.H_Send("s_PortAccess," + r[4]);   //同意
                    ConnentPort connentPort = new ConnentPort()
                    {
                        connentIP  = this,
                        InPort     = PortHelper.GetFirstAvailablePort(),
                        OutPort    = outPort,
                        ClientIP   = r[2],
                        ClientPort = Convert.ToInt32(r[3]),
                        ID         = r[4],
                    };
                    connentPort.Start();
                    connentPorts.Add(connentPort);
                }
            }

            else if (r[0] == "s_Stop")    //申请关闭服务
            {
                ConnentPort connentPort = connentPorts.FirstOrDefault(l => l.ID == r[1]);
                if (connentPort != null)
                {
                    connentPort.DisClientConn();
                    connentPorts.Remove(connentPort);
                }
            }
        }
Esempio n. 10
0
 private void SetModuleFrequency(int frequency)
 {
     _isModuleSet = false;
     frequency    = 127 - (frequency * 2 - 1);
     byte[] by = PortAgreement.GetSetModule(string.Format("AT+FREQ={0:X2}", frequency));
     if (PortHelper.IsConnection)
     {
         PortHelper.SerialPortWrite(by);
         Thread.Sleep(150);
     }
 }
Esempio n. 11
0
        private void MainForm_Shown(object sender, EventArgs e)
        {
            _m_Port = new PortHelper();
            _m_Port.PortDataReceived = OnPortDataReceived;
            _m_Port.PortIsOpenChange = OnPortOpenAndCloseChange;

            _m_ComPort              = new ComPortHelper();
            _m_ComPort.CountChange += _m_ComPort_CountChange;
            _m_ComPort.Start();

            dgv_CustomerList.Focus();
        }
Esempio n. 12
0
        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Enter_Click(object sender, EventArgs e)
        {
            //获取延期时间
            DateTime newtime = t_NewTime.Value;
            //获取车场分区的值
            int partition = cb_CardPartition.SelectedIndex == 0 ? 0 : GetPartition();

            if (_mCardInfo != null)//定距卡
            {
                btn_Enter.Enabled         = false;
                _mCardInfo.StopTime       = newtime;
                _mCardInfo.FieldPartition = partition;

                try
                {
                    if (_mCardCounting == null)
                    {
                        //获取定距卡计数信息
                        _mCardCounting = Dbhelper.Db.FirstDefault <CbCardCountingState>(" and UseNumber = '" + _mCardInfo.CardNumber + "' ");
                        //计数加1
                        _mCardCounting.UseCounting = DistanceCardHelper.LimitCount(_mCardCounting.UseCounting);
                    }
                    //将数据写入定距卡
                    byte[] by = DistanceCardHelper.SetDistanceData(_mCardInfo.CardNumber, _mCardCounting.UseCounting, _mCardInfo.StopTime, _mCardInfo.FieldPartition);
                    PortHelper.SerialPortWrite(by);
                    StartTimeOut();
                }
                catch (Exception ex)
                {
                    btn_Enter.Enabled = true;
                    CustomExceptionHandler.GetExceptionMessage(ex);
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (_mAssociateCard != null)//单张副卡
            {
                _mAssociateCard.UpdateTime      = newtime;
                _mAssociateCard.SubCardDivision = partition;
                this.Tag          = _mAssociateCard;
                this.DialogResult = DialogResult.OK;
            }
            else //批量延期
            {
                foreach (CbAssociateCard item in _mAssociateCards)
                {
                    item.UpdateTime      = newtime;
                    item.SubCardDivision = partition;
                }
                this.Tag          = _mAssociateCards;
                this.DialogResult = DialogResult.OK;
            }
        }
Esempio n. 13
0
                static void CheckPort(string portName, ushort port, ushort originPort, PortType portType = PortType.Both)
                {
                    if (port == originPort)
                    {
                        return;
                    }

                    if (PortHelper.PortInUse(port, portType))
                    {
                        MessageBoxX.Show(i18N.TranslateFormat("The {0} port is in use.", portName));
                        throw new PortInUseException();
                    }
                }
Esempio n. 14
0
        private void VerifyOrCreateRandomProxyPort()
        {
            if (!PortHelper.IsPortAlreadyInUse(_hoverflyConfig.ProxyPort))
            {
                return;
            }

            if (!_hoverflyConfig.UseRandomProxyPort)
            {
                throw new PortAlreadyInUseException($"Port '{_hoverflyConfig.ProxyPort}' is already in use by other application, please use another one");
            }

            _hoverflyConfig.SetProxyPort(PortHelper.GetRandomPort());
        }
        private List <uint> GetPorts()
        {
            List <uint> ports = new List <uint>();
            Dictionary <uint, Process> mappedPorts = PortHelper.MapPorts();

            foreach ((uint port, Process proc) in mappedPorts)
            {
                if (proc.Id == this.Process.Id && port > 2000)
                {
                    ports.Add(port);
                }
            }

            return(ports);
        }
Esempio n. 16
0
        public void AllHelperPortsAreInGetPortNames()
        {
            if (PlatformDetection.IsWindows && PlatformDetection.IsArmOrArm64Process)
            {
                // [ActiveIssue("https://github.com/dotnet/runtime/issues/28851")]
                throw new SkipTestException("Port detection broken on Windows IoT");
            }

            string[] serialPortNames = SerialPort.GetPortNames();
            foreach (string helperPortName in PortHelper.GetPorts())
            {
                Assert.True(serialPortNames.Contains(helperPortName),
                            $"{helperPortName} is not present in SerialPort.GetPortNames result\r\n{PortInformationString}");
            }
        }
Esempio n. 17
0
        private void AllHelperPortsAreInGetPortNames()
        {
            if (PlatformDetection.IsWindows && PlatformDetection.IsArmOrArm64Process)
            {
                // ActiveIssue: 35722
                throw new SkipTestException("Port detection broken on Windows IoT");
            }

            string[] serialPortNames = SerialPort.GetPortNames();
            foreach (string helperPortName in PortHelper.GetPorts())
            {
                Assert.True(serialPortNames.Contains(helperPortName),
                            $"{helperPortName} is not present in SerialPort.GetPortNames result\r\n{PortInformationString}");
            }
        }
Esempio n. 18
0
        /// /// <inheritdoc/>
        protected async override Task CreateConnectionAsync(TcpClient client, string destinationHost, int destinationPort,
                                                            CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(destinationHost))
            {
                throw new ArgumentException(null, nameof(destinationHost));
            }

            if (!PortHelper.ValidateTcpPort(destinationPort))
            {
                throw new ArgumentOutOfRangeException(nameof(destinationPort));
            }

            if (client == null || !client.Connected)
            {
                throw new SocketException();
            }

            HttpStatusCode statusCode;

            try
            {
                var nStream = client.GetStream();

                await RequestConnectionAsync(nStream, destinationHost, destinationPort, cancellationToken).ConfigureAwait(false);

                statusCode = await ReceiveResponseAsync(nStream, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                client.Close();

                if (ex is IOException || ex is SocketException)
                {
                    throw new ProxyException("Error while working with proxy", ex);
                }

                throw;
            }

            if (statusCode != HttpStatusCode.OK)
            {
                client.Close();
                throw new ProxyException("The proxy didn't reply with 200 OK");
            }
        }
            public static void Initialize(TestContext context)
            {
                host = new NancyHost(
                    new HostConfiguration {
                    UrlReservations = new UrlReservations {
                        CreateAutomatically = true
                    }
                },
                    uri = new Uri(
                        string.Format(
                            "http://localhost:{0}/web-browser-waiter-tests/",
                            PortHelper.GetOrCreateCachedPort()
                            )
                        )
                    );

                host.Start();
            }
Esempio n. 20
0
        private void Btn_SerialPortConnection_Click(object sender, EventArgs e)
        {
            Tab4_Form.GetInstance.IsReadIcCard = false;
            if (PortHelper.sp.IsOpen)
            {
                try
                {
                    PortHelper.sp.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                SerialPortChange(PortHelper.IsConnection);
            }
            else
            {
                PortHelper.sp.PortName = cb_SerialPortName.SelectedItem.ToString();
                try
                {
                    PortHelper.sp.Open();

                    PortHelper.SerialPortWrite(PortAgreement.GetDistanceEncryption(Dal_DevicePwd.DistanceSystemPassword.Pwd));

                    Thread.Sleep(600);

                    if (!PortHelper.IsConnection)
                    {
                        PortHelper.sp.Close();
                        MessageBox.Show("当前端口连接失败,请选择正确的端口进行连接。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        SerialPortChange(PortHelper.IsConnection);
                    }
                }
                catch (Exception ex)
                {
                    CustomExceptionHandler.GetExceptionMessage(ex);
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Esempio n. 21
0
        protected override Task CreateConnectionAsync(TcpClient client, string destinationHost, int destinationPort,
                                                      CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(destinationHost))
            {
                throw new ArgumentException(null, nameof(destinationHost));
            }

            if (!PortHelper.ValidateTcpPort(destinationPort))
            {
                throw new ArgumentOutOfRangeException(nameof(destinationPort));
            }

            if (client == null || !client.Connected)
            {
                throw new SocketException();
            }

            return(Task.CompletedTask);
        }
Esempio n. 22
0
        /// <summary>
        /// Checks to see if the ship has the cargo type and whether it has at least numToRemove
        /// Returns true is remove is succesful
        /// </summary>
        /// <param name="type"></param>
        /// <param name="numToRemove"></param>
        /// <returns></returns>
        public override CargoResult RemoveStatelessCargo(StatelessCargoTypes type, float numToRemove)
        {
            CargoResult result;

            if (!_model.StatelessCargo.ContainsKey(type))
            {
                result = CargoResult.CargoNotInHolds;
            }
            else if (_model.StatelessCargo[type].Quantity > numToRemove)//At least one item will remain
            {
                _model.StatelessCargo[type].Quantity -= numToRemove;
                _model.FilledHolds -= numToRemove * StatelessCargo.SpacePerObject(type);
                if (StatelessCargoPriceGetter != null)
                {
                    SetCargoPurchasePrice(PortHelper.GetPortWareIdentifier(type), StatelessCargoPriceGetter(new StatelessCargo(_model.StatelessCargo[type]), PriceType.PortPurchasing));
                    SetCargoSalePrice(PortHelper.GetPortWareIdentifier(type), StatelessCargoPriceGetter(new StatelessCargo(_model.StatelessCargo[type]), PriceType.PortSelling));
                }
                result = CargoResult.Success;
            }
            else if (_model.StatelessCargo[type].Quantity == numToRemove)//Last item will be removed
            {
                _model.StatelessCargo.Remove(type);

                _model.FilledHolds -= numToRemove * StatelessCargo.SpacePerObject(type);
                _model.Prices_ShipSaleToPort.Remove(PortHelper.GetPortWareIdentifier(type));
                result = CargoResult.Success;
            }
            result = CargoResult.CargoNotInHolds;

            if (result == CargoResult.Success)
            {
                PortWareIdentifier identifier;

                if (Enum.TryParse(type.ToString(), out identifier))
                {
                    UpdateGoodCounts(identifier, -numToRemove);
                }
            }

            return(result);
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (true)
            {
                await Task.Delay(2000);

                if (!IsPortSelected)
                {
                    continue;
                }

                if (portHelper == null)
                {
                    portHelper = new PortHelper();
                }

                Model = InitDataModel();

                //dbHelper.Add(Model);
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Removes the stateful cargo with the given ID if it exists
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override StatefulCargo RemoveStatefulCargo(StatefulCargoTypes type)
        {
            var s = _model.StatefulCargo.First(e => e.Value.CargoType == type);

            if (s.Value != null)//This might crash?
            {
                _model.StatefulCargo.Remove(s.Key);
                _model.FilledHolds -= Core.Models.StatefulCargo.SpacePerObject(type);
                _decrementStatefulCargoCount(type);
                if (StatefulCargoPriceGetter != null)
                {
                    SetCargoPurchasePrice(PortHelper.GetPortWareIdentifier(type), StatefulCargoPriceGetter(new StatefulCargo_RO(s.Value), GetCargoAmount(s.Value.CargoType), PriceType.PortPurchasing));
                    SetCargoSalePrice(PortHelper.GetPortWareIdentifier(type), StatefulCargoPriceGetter(new StatefulCargo_RO(s.Value), GetCargoAmount(s.Value.CargoType), PriceType.PortSelling));
                }
                return(s.Value);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 25
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddCommandLine(args)
                         .Build();
            String ip   = config["ip"];
            int    port = Convert.ToInt32(config["port"]);

            if (port == 0)
            {
                //随机产生可用端口号
                port = PortHelper.GetRandAvailablePort();
            }
            Program.port = port;
            if (ip == null)
            {
                ip = "127.0.0.1";
            }
            Program.ip = ip;
            return(WebHost.CreateDefaultBuilder(args)
                   .UseStartup <Startup>()
                   .UseUrls($"http://{ip}:{port}"));
        }
Esempio n. 26
0
        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Enter_Click(object sender, EventArgs e)
        {
            string oldpwd = tb_OldPwd.Text.Trim();

            if (oldpwd.Length != tb_OldPwd.MaxLength)
            {
                DisplayContent("旧口令长度为 6 位数字,请重新输入旧口令。");
                tb_OldPwd.Focus();
                return;
            }
            try
            {
                IsEnd = false;
                byte[] by = PortAgreement.GetDistanceEncryption(oldpwd);
                PortHelper.SerialPortWrite(by);
                p_Top.Enabled = false;
            }
            catch (Exception ex)
            {
                CustomExceptionHandler.GetExceptionMessage(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Removes the stateful cargo with the given ID if it exists
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override StatefulCargo RemoveStatefulCargo(int id)
        {
            if (_model.StatefulCargo.ContainsKey(id))
            {
                StatefulCargo s = _model.StatefulCargo[id];
                _model.FilledHolds -= Core.Models.StatefulCargo.SpacePerObject(s.CargoType);
                _decrementStatefulCargoCount(s.CargoType);
                if (StatefulCargoPriceGetter != null)
                {
                    SetCargoPurchasePrice(PortHelper.GetPortWareIdentifier(s.CargoType), StatefulCargoPriceGetter(new StatefulCargo_RO(s), GetCargoAmount(s.CargoType), PriceType.PortPurchasing));
                    SetCargoSalePrice(PortHelper.GetPortWareIdentifier(s.CargoType), StatefulCargoPriceGetter(new StatefulCargo_RO(s), GetCargoAmount(s.CargoType), PriceType.PortSelling));
                }


                PortWareIdentifier identifier = PortHelper.GetPortWareIdentifier(s.CargoType);

                if (s.CargoType == StatefulCargoTypes.Module)
                {
                    _model.UIComponent.Modules.Remove(id);
                }
                else if (identifier != PortWareIdentifier.Null)
                {
                    UpdateGoodCounts(identifier, -1);
                    UpdateUIStatLists(identifier, s, false);

                    if (!_model.PortGoodCounts.ContainsKey(identifier))//UpdateGoodCounts will have removed the key if no more goods of this type are in the inventory
                    {
                        _model.Prices_ShipSaleToPort.Remove(identifier);
                    }
                }
                return(s);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 28
0
    private bool OpenEveryPortName()
    {
        bool retValue = true;

        String[]   portNames = SerialPort.GetPortNames();
        SerialPort serialPort;


        for (int i = 0; i < portNames.Length; ++i)
        {
            Console.WriteLine("Opening port " + portNames[i]);
            bool portExists = false;
            foreach (string str in PortHelper.GetPorts())
            {
                if (str == portNames[i])
                {
                    portExists = true;
                    break;
                }
            }
            if (!portExists)
            {
                Console.WriteLine("Real Port does not exist. Ignore the output from SerialPort.GetPortNames()");
                continue;
            }
            serialPort = new SerialPort(portNames[i]);

            try
            {
                serialPort.Open();
            }
            catch (UnauthorizedAccessException) { }
        }

        return(retValue);
    }
 public ushort ValidApiPort(ushort defaultApiPort)
 {
     return(PortHelper.IsValidPort(defaultApiPort) ? ApiPort : defaultApiPort);
 }
 public ushort ValidPort(ushort defaultPort)
 {
     return(PortHelper.IsValidPort(Port) ? Port : defaultPort);
 }