Exemplo n.º 1
0
 public Transport(TransportOption option, float maxTimeSeconds)
 {
     this.From             = new CityStay(option.From); //+ staytime default 1 day
     this.To               = new CityStay(option.To);
     this.Option           = option;
     this.MaxTimeInSeconds = maxTimeSeconds;
 }
Exemplo n.º 2
0
            /// <summary>
            /// Create runner
            /// </summary>
            /// <param name="outer"></param>
            /// <param name="config"></param>
            /// <param name="endpointId"></param>
            /// <param name="secret"></param>
            /// <param name="logger"></param>
            public TwinHost(SupervisorServices outer, IModuleConfig config,
                            string endpointId, string secret, ILogger logger)
            {
                _outer   = outer;
                _product = "OpcTwin_" + GetType().Assembly.GetReleaseVersion().ToString();
                _logger  = (logger ?? Log.Logger).ForContext("SourceContext", new {
                    endpointId,
                    product = _product
                }, true);

                BypassCertVerification = config.BypassCertVerification;
                Transport = config.Transport;
                EdgeHubConnectionString = GetEdgeHubConnectionString(config,
                                                                     endpointId, secret);
                EnableMetrics = config.EnableMetrics;

                // Create twin scoped component context for the host
                _container = outer._factory.Create(builder => {
                    builder.RegisterInstance(this)
                    .AsImplementedInterfaces().SingleInstance();
                });

                _cts     = new CancellationTokenSource();
                _reset   = new TaskCompletionSource <bool>();
                _started = new TaskCompletionSource <bool>();
                Status   = EndpointActivationState.Activated;
                _runner  = Task.Run(RunAsync);
            }
Exemplo n.º 3
0
    void tryConnect(TransportProtocol protocol)
    {
        TransportOption option = makeOption(protocol);
        ushort          port   = getPort(protocol, encoding);

        session_.Connect(protocol, encoding, port, option);
    }
Exemplo n.º 4
0
 public static bool EnoughForTransportOption(TransportOption option)
 {
     foreach (KeyValuePair <Type, float> entry in option.TransportType.ResourceCostsPerDistance)
     {
         if (entry.Key != typeof(CO2Resource))
         {
             if (GetPlayer().Resources[entry.Key].Value < entry.Value)
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Exemplo n.º 5
0
    public static TransportOption GetTransportOption(City from, string to, string transportType)
    {
        City            toCity = GetCity(to);
        TransportOption op     = null;

        foreach (TransportOption option in cityConnections)
        {
            if (option.From == from && option.To == toCity && option.TransportType.Name == transportType)
            {
                op = option;
                break;
            }
        }
        return(op);
    }
Exemplo n.º 6
0
        public void Connect(bool session_reliability)
        {
            message_number_ = 0;

            if (session_ == null)
            {
                session_ = FunapiSession.Create(server_ip_, session_reliability);
                session_.SessionEventCallback    += onSessionEvent;
                session_.TransportEventCallback  += onTransportEvent;
                session_.TransportErrorCallback  += onTransportError;
                session_.ReceivedMessageCallback += onReceivedMessage;

                for (int i = 0; i < 3; ++i)
                {
                    TransportOption option = new TransportOption();
                    if (protocols[i] == TransportProtocol.kTcp)
                    {
                        TcpTransportOption tcp_option = new TcpTransportOption();
                        tcp_option.EnablePing          = true;
                        tcp_option.PingIntervalSeconds = 1;
                        tcp_option.PingTimeoutSeconds  = 3;
                        option = tcp_option;
                    }
                    else
                    {
                        option = new TransportOption();
                    }

                    option.ConnectionTimeout = 3f;

                    //if (protocols[i] == TransportProtocol.kTcp)
                    //    option.Encryption = EncryptionType.kIFunEngine1Encryption;
                    //else
                    //    option.Encryption = EncryptionType.kIFunEngine2Encryption;

                    ushort port = getPort(protocols[i], encodings[i]);
                    session_.Connect(protocols[i], encodings[i], port, option);
                }
            }
            else
            {
                for (int i = 0; i < 3; ++i)
                {
                    session_.Connect(protocols[i]);
                }
            }
        }
    public void OnButtonConnect()
    {
        if (session == null || address_changed)
        {
            createSession();
        }

        TransportOption option = null;

        if (info.protocol == TransportProtocol.kTcp)
        {
            TcpTransportOption tcp = new TcpTransportOption();

            // If this option is set to true,
            // it will automatically try to reconnect within the Transport when it is disconnected.
            tcp.AutoReconnect = false;
            option            = tcp;
        }

        session.Connect(info.protocol, info.encoding, info.port, option);
    }
Exemplo n.º 8
0
            /// <summary>
            /// Create runner
            /// </summary>
            /// <param name="outer"></param>
            /// <param name="config"></param>
            /// <param name="endpointId"></param>
            /// <param name="secret"></param>
            public TwinHost(SupervisorServices outer,
                            IModuleConfig config, string endpointId, string secret)
            {
                _outer = outer;

                BypassCertVerification = config.BypassCertVerification;
                Transport = config.Transport;
                EdgeHubConnectionString = GetEdgeHubConnectionString(config,
                                                                     endpointId, secret);

                // Create twin scoped component context for the host
                _container = outer._factory.Create(builder => {
                    builder.RegisterInstance(this)
                    .AsImplementedInterfaces().SingleInstance();
                });

                _cts     = new CancellationTokenSource();
                _reset   = new TaskCompletionSource <bool>();
                _started = new TaskCompletionSource <bool>();
                Status   = EndpointActivationState.Activated;
                _runner  = Task.Run(RunAsync);
            }
Exemplo n.º 9
0
        /// <summary>
        /// Ищет транспорт по ключу в нужном репозитории и Удаляет его.
        /// Удаленный транспорт помещается в deletedTransport.
        /// </summary>
        private async Task RemoveTransportAsync(KeyTransport keyTransport, TransportOption deletedTransport)
        {
            switch (keyTransport.TransportType)
            {
            case TransportType.SerialPort:
                deletedTransport.SerialOptions.Add(await _serialPortOptionRep.GetSingleAsync(sp => sp.Port == keyTransport.Key));
                await _serialPortOptionRep.DeleteAsync(sp => sp.Port == keyTransport.Key);

                break;

            case TransportType.TcpIp:
                deletedTransport.TcpIpOptions.Add(await _tcpIpOptionRep.GetSingleAsync(tcpip => tcpip.Name == keyTransport.Key));
                await _tcpIpOptionRep.DeleteAsync(tcpip => tcpip.Name == keyTransport.Key);

                break;

            case TransportType.Http:
                deletedTransport.HttpOptions.Add(await _httpOptionRep.GetSingleAsync(http => http.Name == keyTransport.Key));
                await _httpOptionRep.DeleteAsync(http => http.Name == keyTransport.Key);

                break;
            }
        }
Exemplo n.º 10
0
    TransportOption makeOption(TransportProtocol protocol)
    {
        TransportOption option = null;

        if (protocol == TransportProtocol.kTcp)
        {
            TcpTransportOption tcp_option = new TcpTransportOption();
            tcp_option.Encryption    = tcpEncryption;
            tcp_option.AutoReconnect = autoReconnect;
            tcp_option.DisableNagle  = disableNagle;

            if (usePing)
            {
                tcp_option.SetPing(1, 20, true);
            }

            option = tcp_option;
        }
        else if (protocol == TransportProtocol.kUdp)
        {
            option            = new TransportOption();
            option.Encryption = udpEncryption;
        }
        else if (protocol == TransportProtocol.kHttp)
        {
            HttpTransportOption http_option = new HttpTransportOption();
            http_option.Encryption = httpEncryption;
            http_option.UseWWW     = useWWW;

            option = http_option;
        }

        option.ConnectionTimeout  = 10f;
        option.SequenceValidation = sequenceValidation;

        return(option);
    }
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (ProcessorArchitecture.Expression != null)
            {
                targetCommand.AddParameter("ProcessorArchitecture", ProcessorArchitecture.Get(context));
            }

            if (SessionType.Expression != null)
            {
                targetCommand.AddParameter("SessionType", SessionType.Get(context));
            }

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (AssemblyName.Expression != null)
            {
                targetCommand.AddParameter("AssemblyName", AssemblyName.Get(context));
            }

            if (ApplicationBase.Expression != null)
            {
                targetCommand.AddParameter("ApplicationBase", ApplicationBase.Get(context));
            }

            if (ConfigurationTypeName.Expression != null)
            {
                targetCommand.AddParameter("ConfigurationTypeName", ConfigurationTypeName.Get(context));
            }

            if (RunAsCredential.Expression != null)
            {
                targetCommand.AddParameter("RunAsCredential", RunAsCredential.Get(context));
            }

            if (ThreadApartmentState.Expression != null)
            {
                targetCommand.AddParameter("ThreadApartmentState", ThreadApartmentState.Get(context));
            }

            if (ThreadOptions.Expression != null)
            {
                targetCommand.AddParameter("ThreadOptions", ThreadOptions.Get(context));
            }

            if (AccessMode.Expression != null)
            {
                targetCommand.AddParameter("AccessMode", AccessMode.Get(context));
            }

            if (UseSharedProcess.Expression != null)
            {
                targetCommand.AddParameter("UseSharedProcess", UseSharedProcess.Get(context));
            }

            if (StartupScript.Expression != null)
            {
                targetCommand.AddParameter("StartupScript", StartupScript.Get(context));
            }

            if (MaximumReceivedDataSizePerCommandMB.Expression != null)
            {
                targetCommand.AddParameter("MaximumReceivedDataSizePerCommandMB", MaximumReceivedDataSizePerCommandMB.Get(context));
            }

            if (MaximumReceivedObjectSizeMB.Expression != null)
            {
                targetCommand.AddParameter("MaximumReceivedObjectSizeMB", MaximumReceivedObjectSizeMB.Get(context));
            }

            if (SecurityDescriptorSddl.Expression != null)
            {
                targetCommand.AddParameter("SecurityDescriptorSddl", SecurityDescriptorSddl.Get(context));
            }

            if (ShowSecurityDescriptorUI.Expression != null)
            {
                targetCommand.AddParameter("ShowSecurityDescriptorUI", ShowSecurityDescriptorUI.Get(context));
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }

            if (NoServiceRestart.Expression != null)
            {
                targetCommand.AddParameter("NoServiceRestart", NoServiceRestart.Get(context));
            }

            if (PSVersion.Expression != null)
            {
                targetCommand.AddParameter("PSVersion", PSVersion.Get(context));
            }

            if (SessionTypeOption.Expression != null)
            {
                targetCommand.AddParameter("SessionTypeOption", SessionTypeOption.Get(context));
            }

            if (TransportOption.Expression != null)
            {
                targetCommand.AddParameter("TransportOption", TransportOption.Get(context));
            }

            if (ModulesToImport.Expression != null)
            {
                targetCommand.AddParameter("ModulesToImport", ModulesToImport.Get(context));
            }

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
 /// <summary>
 /// Create clone
 /// </summary>
 /// <param name="config"></param>
 /// <param name="connectionString"></param>
 public DeviceClientConfig(IModuleConfig config, string connectionString)
 {
     EdgeHubConnectionString = GetEdgeHubConnectionString(config, connectionString);
     BypassCertVerification  = config.BypassCertVerification;
     Transport = config.Transport;
 }
Exemplo n.º 13
0
 private static TransportOption ReverseOption(TransportOption option)
 {
     return(new TransportOption(option.To, option.From, option.TransportType, option.Distance));
 }
Exemplo n.º 14
0
        /// <summary>
        /// Добавить девайс, для которого нужно создать 1 или несколько обменов.
        /// Если обмен не существует, добавим его, если существует, то добавим существующий.
        /// Если для нового обменна не существует транспорт, то создадим транспорт.
        /// Если хотябы 1 транспорт в "transportOption" уже существует, то выкидываем Exception.
        /// </summary>
        private async Task AddDeviceOptionWithNewExchangeOptionsAndNewTransportOptionsAsync(DeviceOption deviceOption, IEnumerable <ExchangeOption> exchangeOptions, TransportOption transportOption)
        {
            //ПРОВЕРКА ОТСУТСВИЯ УСТРОЙСТВА по имени
            if (await IsExistDeviceAsync(deviceOption.Name))
            {
                throw new OptionHandlerException($"Устройство с таким именем уже существует:  {deviceOption.Name}");
            }

            var exceptionStr         = new StringBuilder();
            var exchangeExternalKeys = exchangeOptions.Select(exchangeOption => exchangeOption.Key).ToList();

            //ПРОВЕРКА СООТВЕТСТВИЯ exchangeKeys, УКАЗАННОЙ В deviceOption, КЛЮЧАМ ИЗ exchangeOptions
            var diff = exchangeExternalKeys.Except(deviceOption.ExchangeKeys).ToList();

            if (diff.Count > 0)
            {
                throw new OptionHandlerException("Найденно несоответсвие ключей указанных для Device, ключам указанным в exchangeOptions");
            }

            //ПРОВЕРКА НАЛИЧИЯ ОБМЕНОВ УКАЗАННЫХ ДЛЯ УС-ВА В СПИСКЕ НОВЫХ ОБМЕНОВ ИЛИ В СПИСКЕ СУЩЕСТВУЮЩИХ ОБМЕНОВ
            foreach (var exchKey in deviceOption.ExchangeKeys)
            {
                if (exchangeExternalKeys.Contains(exchKey) || _exchangeOptionRep.IsExist(e => e.Key == exchKey))
                {
                    continue;
                }
                exceptionStr.AppendFormat("{0}, ", exchKey);
            }
            if (!string.IsNullOrEmpty(exceptionStr.ToString()))
            {
                throw new OptionHandlerException($"ExchangeKeys указанные для устройства не найденны в списке существующих и добавляемых обменов:  {exceptionStr}");
            }

            //ПРОВЕРКА СООТВЕТСТВИЯ ключей exchangeOptions, указанному транспорту transportOption
            var keysByExchange   = exchangeOptions.Select(option => option.KeyTransport);
            var keysBySp         = transportOption.SerialOptions.Select(option => new KeyTransport(option.Port, TransportType.SerialPort));
            var keysByTcpIp      = transportOption.TcpIpOptions.Select(option => new KeyTransport(option.Name, TransportType.TcpIp));
            var keysByHttp       = transportOption.HttpOptions.Select(option => new KeyTransport(option.Name, TransportType.Http));
            var keysAllTransport = new List <KeyTransport>();

            keysAllTransport.AddRange(keysBySp);
            keysAllTransport.AddRange(keysByTcpIp);
            keysAllTransport.AddRange(keysByHttp);
            var diffKeys = keysByExchange.Except(keysAllTransport).ToList();

            if (diffKeys.Count > 0)
            {
                foreach (var diffKey in diffKeys)
                {
                    exceptionStr.AppendFormat("{0}, ", diffKey);
                }
                throw new OptionHandlerException($"Найденно несоответсвие ключей указанных для Обмненов, ключам указанным для транспорта {exceptionStr}");
            }

            //ПРОВЕРКА ОТСУТСВИЯ ДОБАВЛЯЕМОГО ТРАНСПОРТА ДЛЯ КАЖДОГО ОБМЕНА (по ключу KeyTransport). Добавялем только уникальный обмен.
            foreach (var exchangeOption in exchangeOptions)
            {
                if (await IsExistTransportAsync(exchangeOption.KeyTransport))
                {
                    exceptionStr.AppendFormat("{0}, ", exchangeOption.KeyTransport);
                }
            }
            if (!string.IsNullOrEmpty(exceptionStr.ToString()))
            {
                throw new OptionHandlerException($"Для ExchangeOption УЖЕ СУЩЕСТВУЕТ ТАКОЙ ТРАНСПОРТ:  {exceptionStr}");
            }

            //ДОБАВИТЬ ДЕВАЙС, ОБМЕНЫ, ТРАНСПОРТ
            await _deviceOptionRep.AddAsync(deviceOption);

            await _exchangeOptionRep.AddRangeAsync(exchangeOptions);

            if (transportOption.SerialOptions != null)
            {
                await _serialPortOptionRep.AddRangeAsync(transportOption.SerialOptions);
            }
            if (transportOption.TcpIpOptions != null)
            {
                await _tcpIpOptionRep.AddRangeAsync(transportOption.TcpIpOptions);
            }
            if (transportOption.HttpOptions != null)
            {
                await _httpOptionRep.AddRangeAsync(transportOption.HttpOptions);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Добавить опции для устройства в репозиторий.
        /// Если exchangeOptions и transportOption не указанны, то добавляетя устройство с существующими обменами
        /// Если transportOption не указанн, то добавляетя устройство вместе со списом обменов, на уже существйющем транспорте.
        /// Если указанны все аргументы, то добавляется устройство со спсиком новых обменом и каждый обмен использует новый транспорт.
        /// </summary>
        public async Task <bool> AddDeviceOptionAsync(DeviceOption deviceOption, IEnumerable <ExchangeOption> exchangeOptions = null, TransportOption transportOption = null)
        {
            if (deviceOption == null && exchangeOptions == null && transportOption == null)
            {
                return(false);
            }

            if (deviceOption != null && exchangeOptions == null && transportOption == null)
            {
                await AddDeviceOptionWithExiststExchangeOptionsAsync(deviceOption);
            }
            else
            if (deviceOption != null && exchangeOptions != null && transportOption == null)
            {
                await AddDeviceOptionWithNewExchangeOptionsAsync(deviceOption, exchangeOptions);
            }
            else
            if (deviceOption != null && exchangeOptions != null)
            {
                await AddDeviceOptionWithNewExchangeOptionsAndNewTransportOptionsAsync(deviceOption, exchangeOptions, transportOption);
            }

            return(true);
        }