private void AppendModuleMenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem      item = (MenuItem)sender;
            IModuleConfig defaultModuleConfig = (IModuleConfig)item.Tag;

            AddModule(defaultModuleConfig);
        }
Beispiel #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);
            }
        private void SaveConfig()
        {
            List <IModuleConfig> moduleConfigs = new List <IModuleConfig>();

            foreach (IModule module in Modules)
            {
                IModuleConfig moduleConfig = module.GetConfig();
                moduleConfigs.Add(moduleConfig);
            }

            Config config = new Config()
            {
                WindowRect    = new Rect(this.Left, this.Top, this.Width, this.Height),
                RoomId        = RoomIdBox.Text,
                ModuleConfigs = moduleConfigs
            };
            FileInfo fileInfo = new FileInfo("./config/settings.dat");

            try
            {
                if (!fileInfo.Directory.Exists)
                {
                    fileInfo.Directory.Create();
                }
                using (FileStream fileStream = new FileStream(fileInfo.FullName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(fileStream, config);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #4
0
 /// <summary>
 /// Stop metric server if enabled
 /// </summary>
 /// <returns></returns>
 public static void StopWhenEnabled(this MetricServer server, IModuleConfig config, Serilog.ILogger logger)
 {
     if (config.EnableMetrics)
     {
         server.Stop();;
         logger.Information("Stopped prometheus metric server");
     }
 }
 private void CheckTaskModuleAttribute(TaskModuleAttribute attribute, IModuleConfig config)
 {
     if (attribute.ConfigurationType != config.GetType())
     {
         throw new TypeAccessException(
                   $"config type {config.GetType().Name} not equals attribtue config type {attribute.ConfigurationType}");
     }
 }
Beispiel #6
0
 public LookupPageViewModel(IBase @base, ILeadsService leadsService,
                            ICacheService cacheService, IModuleConfig moduleConfig) : base(@base)
 {
     Title         = Strings.Resources.LookupPageTitle;
     _leadsService = leadsService;
     _cacheService = cacheService;
     _moduleConfig = moduleConfig;
 }
        public MainWindow()
        {
            InitializeComponent();

            IsConnected = false;

            InitCounters();

            Config config = LoadConfig();

            if (config != null)
            {
                RoomIdBox.Text = config.RoomId;
                if (config.WindowRect.Width != 0 && config.WindowRect.Height != 0)
                {
                    this.Left   = config.WindowRect.Left;
                    this.Top    = config.WindowRect.Top;
                    this.Width  = config.WindowRect.Width;
                    this.Height = config.WindowRect.Height;
                }
            }

            List <IModuleConfig> moduleConfigs = null;

            if (config != null && config.ModuleConfigs != null)
            {
                moduleConfigs = config.ModuleConfigs;
            }
            else
            {
                moduleConfigs = new List <IModuleConfig>();
                moduleConfigs.Add(new DanmakuShowConfig());
                moduleConfigs.Add(new DanmakuSpeechConfig());
            }
            Modules = new List <IModule>();
            foreach (IModuleConfig moduleConfig in moduleConfigs)
            {
                AddModule(moduleConfig);
            }

            ContextMenu    appendModuleContextMenu = (ContextMenu)AddModuleBtn.Resources["AppendModuleContextMenu"];
            ModuleLoader   moduleLoader            = new ModuleLoader();
            List <IModule> modules = moduleLoader.LoadModules();

            foreach (IModule module in modules)
            {
                IModuleConfig defaultModuleConfig = module.CreateDefaultConfig();
                MenuItem      menuItem            = new MenuItem();
                menuItem.Header = module.Description;
                menuItem.Tag    = defaultModuleConfig;
                menuItem.Click += AppendModuleMenuItem_Click;
                appendModuleContextMenu.Items.Add(menuItem);
            }


            this.Closing += MainWindow_Closing;
        }
Beispiel #8
0
 /// <summary>
 /// Create supervisor creating and managing twin instances
 /// </summary>
 /// <param name="factory"></param>
 /// <param name="config"></param>
 /// <param name="events"></param>
 /// <param name="process"></param>
 /// <param name="logger"></param>
 public SupervisorServices(IContainerFactory factory, IModuleConfig config,
                           IEventEmitter events, IProcessControl process, ILogger logger)
 {
     _logger  = logger ?? throw new ArgumentNullException(nameof(logger));
     _config  = config ?? throw new ArgumentNullException(nameof(config));
     _events  = events ?? throw new ArgumentNullException(nameof(events));
     _process = process ?? throw new ArgumentNullException(nameof(process));
     _factory = factory ?? throw new ArgumentNullException(nameof(factory));
 }
        private void AddModule(IModuleConfig moduleConfig)
        {
            IModule      module       = moduleConfig.CreateModule();
            ModuleBorder moduleBorder = new ModuleBorder(module);

            moduleBorder.Closing += ModuleBorder_Closing;
            ModulesPanel.Children.Add(moduleBorder);
            Modules.Add(module);
        }
 /// <summary>
 /// Clone module config
 /// </summary>
 /// <param name="config"></param>
 /// <param name="connectionString"></param>
 /// <returns></returns>
 public static IModuleConfig Clone(this IModuleConfig config,
                                   string connectionString = null)
 {
     if (config == null)
     {
         return(null);
     }
     return(new DeviceClientConfig(config, connectionString));
 }
        private static TreeNode CreatTreeNode(IModuleConfig module)
        {
            var item = new TreeNode(module.ModuleName);

            module.RequiredModulesNames.ForEach(c => item.Children.Add(CreateEmptyTreeNode(c, false, true)));
            module.DependingModulesNames.ForEach(c => item.Children.Add(CreateEmptyTreeNode(c, true, false)));
            module.ProvidedServices.Select(s => s.ServiceName).OrderBy(s => s).ToList().ForEach(c => item.Children.Add(CreateSimpleTreeNode(c)));
            return(item);
        }
Beispiel #12
0
        /// <summary>
        ///     To the repository string.
        /// </summary>
        /// <param name="config">The configuration.</param>
        public static string ToRepositoryString(this IModuleConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            return(JsonConvert.SerializeObject(config, _serializerSettings));
        }
        public void AddOrUpdate_HttpContext_ShareModule_Type_IModuleConfig_test()
        {
            HttpContext   context     = null;
            ShareModule   shareModule = null;
            Type          moduleType  = null;
            IModuleConfig config      = null;
            var           result      = Resolve <ITaskModuleConfigService>().AddOrUpdate(context, shareModule, moduleType, config);

            Assert.NotNull(result);
        }
        public void Init(IModuleConfig config)
        {
            giftCacheManager = new GiftCacheManager(5);
            giftCacheManager.CacheExpired += GiftCacheManager_CacheExpired;
            speechProcessor = new SpeechProcessor();
            speechProcessor.QueueChanged += Synthesizer_QueueChanged;

            DanmakuSpeechConfig speechConfig = (DanmakuSpeechConfig)config;

            OptionDict = speechConfig.OptionDict;
            SetVolume(speechConfig.Volume);
            Control = new DanmakuSpeechControl(this, speechConfig.OutputDevice);


            FileInfo fileInfo           = new FileInfo("./config/speech.xml");
            Stream   speechConfigStream = null;

            try
            {
                if (fileInfo.Exists)
                {
                    speechConfigStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                }
                else
                {
                    speechConfigStream = Application.GetResourceStream(new Uri("Config/Speech.xml", UriKind.RelativeOrAbsolute)).Stream;
                }
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(speechConfigStream);
                XmlNode enableAttr = xmlDocument.SelectSingleNode("speech/@enable");
                string  enable     = enableAttr != null ? enableAttr.Value : "true";
                if (enable.ToLower() != "false")
                {
                    XmlNode tokenEndpointNode = xmlDocument.SelectSingleNode("speech/token_endpoint/text()");
                    XmlNode ttsEndpointNode   = xmlDocument.SelectSingleNode("speech/tts_endpoint/text()");
                    XmlNode apiKeyNode        = xmlDocument.SelectSingleNode("speech/api_key/text()");
                    string  tokenEndpoint     = tokenEndpointNode.Value;
                    string  ttsEndpoint       = ttsEndpointNode.Value;
                    string  apiKey            = apiKeyNode.Value;
                    speechProcessor.Init(tokenEndpoint, ttsEndpoint, apiKey);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (speechConfigStream != null)
                {
                    speechConfigStream.Close();
                }
            }
        }
Beispiel #15
0
 /// <summary>
 /// Start metric server
 /// </summary>
 /// <returns></returns>
 public static void StartWhenEnabled(this IMetricServer server, IModuleConfig config, Serilog.ILogger logger)
 {
     if (config.EnableMetrics)
     {
         server.Start();
         logger.Information("Prometheus metric server started.");
     }
     else
     {
         logger.Information("Metrics Collection is disabled. Not starting prometheus metric server.");
     }
 }
            /// <summary>
            /// Create new connection string from existing EdgeHubConnectionString.
            /// </summary>
            /// <param name="config"></param>
            /// <param name="connectionString"></param>
            /// <returns></returns>
            private static string GetEdgeHubConnectionString(IModuleConfig config,
                                                             string connectionString)
            {
                var cs = config.EdgeHubConnectionString;

                if (string.IsNullOrEmpty(connectionString))
                {
                    return(cs);
                }
                var csUpdate = ConnectionString.Parse(connectionString);
                var deviceId = csUpdate.DeviceId;
                var key      = csUpdate.SharedAccessKey;

                if (string.IsNullOrEmpty(cs))
                {
                    // Retrieve information from environment
                    var hostName = Environment.GetEnvironmentVariable("IOTEDGE_IOTHUBHOSTNAME");
                    if (string.IsNullOrEmpty(hostName))
                    {
                        throw new InvalidConfigurationException(
                                  "Missing IOTEDGE_IOTHUBHOSTNAME variable in environment");
                    }
                    var edgeName = Environment.GetEnvironmentVariable("IOTEDGE_GATEWAYHOSTNAME");
                    cs = $"HostName={hostName};DeviceId={deviceId};SharedAccessKey={key}";
                    if (string.IsNullOrEmpty(edgeName))
                    {
                        cs += $";GatewayHostName={edgeName}";
                    }
                }
                else
                {
                    // Use existing connection string as a master plan
                    var lookup = cs
                                 .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                                 .Select(s => s.Trim().Split('='))
                                 .ToDictionary(s => s[0].ToLowerInvariant(), v => v[1]);
                    if (!lookup.TryGetValue("hostname", out var hostName) ||
                        string.IsNullOrEmpty(hostName))
                    {
                        throw new InvalidConfigurationException(
                                  "Missing HostName in connection string");
                    }

                    cs = $"HostName={hostName};DeviceId={deviceId};SharedAccessKey={key}";
                    if (lookup.TryGetValue("GatewayHostName", out var edgeName) &&
                        !string.IsNullOrEmpty(edgeName))
                    {
                        cs += $";GatewayHostName={edgeName}";
                    }
                }
                return(cs);
            }
            /// <summary>
            /// Create new connection string from existing EdgeHubConnectionString.
            /// </summary>
            /// <param name="config"></param>
            /// <param name="endpointId"></param>
            /// <param name="secret"></param>
            /// <returns></returns>
            private static string GetEdgeHubConnectionString(IModuleConfig config,
                                                             string endpointId, string secret)
            {
                var cs = config.EdgeHubConnectionString;

                if (string.IsNullOrEmpty(cs))
                {
                    // Retrieve information from environment
                    var hostName = Environment.GetEnvironmentVariable(IoTEdgeVariables.IOTEDGE_IOTHUBHOSTNAME);
                    if (string.IsNullOrEmpty(hostName))
                    {
                        throw new InvalidConfigurationException(
                                  $"Missing {IoTEdgeVariables.IOTEDGE_IOTHUBHOSTNAME} variable in environment");
                    }
                    var edgeName = Environment.GetEnvironmentVariable(IoTEdgeVariables.IOTEDGE_GATEWAYHOSTNAME);
                    if (string.IsNullOrEmpty(edgeName))
                    {
                        cs = $"HostName={hostName};DeviceId={endpointId};SharedAccessKey={secret}";
                    }
                    else
                    {
                        cs = $"HostName={hostName};DeviceId={endpointId};GatewayHostName={edgeName};SharedAccessKey={secret}";
                    }
                }
                else
                {
                    // Use existing connection string as a master plan
                    var lookup = cs
                                 .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                                 .Select(s => s.Trim().Split('='))
                                 .ToDictionary(s => s[0].ToLowerInvariant(), v => v[1]);
                    if (!lookup.TryGetValue("hostname", out var hostName) ||
                        string.IsNullOrEmpty(hostName))
                    {
                        throw new InvalidConfigurationException(
                                  "Missing HostName in connection string");
                    }

                    if (!lookup.TryGetValue("GatewayHostName", out var edgeName) ||
                        string.IsNullOrEmpty(edgeName))
                    {
                        cs = $"HostName={hostName};DeviceId={endpointId};SharedAccessKey={secret}";
                    }
                    else
                    {
                        cs = $"HostName={hostName};DeviceId={endpointId};GatewayHostName={edgeName};SharedAccessKey={secret}";
                    }
                }
                return(cs);
            }
Beispiel #18
0
        private List <WorkingEntityOperation> SeedForModule(IModuleConfig moduleConfig)
        {
            var workingEntityOperations = moduleConfig.Catalogs
                                          .SelectMany(c => c.Operations.Select(o => new WorkingEntityOperation()
            {
                Id              = o.Id,
                Title           = o.Title,
                SystemModuleId  = moduleConfig.SystemModuleId,
                WorkingEntityId = c.WorkingEntityId
            }))
                                          .ToList();

            return(workingEntityOperations);
        }
 /// <summary>
 /// Start metric server
 /// </summary>
 /// <returns></returns>
 public static void StartWhenEnabled(this IMetricServer server, IModuleConfig config, Serilog.ILogger logger)
 {
     if (config.EnableMetrics)
     {
         try {
             server.Start();
             logger.Information("Prometheus metric server started.");
         }
         catch (HttpListenerException e) {
             logger.Error(e, "Unable to start metric server. For more info, please check troubleshooting guide for edge metrics collection");
         }
     }
     else
     {
         logger.Information("Metrics Collection is disabled. Not starting prometheus metric server.");
     }
 }
        /// <summary>
        /// Create sdk factory
        /// </summary>
        /// <param name="hub">Outer hub abstraction</param>
        /// <param name="config">Module framework configuration</param>
        public IoTHubClientFactory(IIoTHub hub, IModuleConfig config)
        {
            _hub = hub ?? throw new ArgumentNullException(nameof(hub));
            if (string.IsNullOrEmpty(config.EdgeHubConnectionString))
            {
                throw new InvalidConfigurationException(
                          "Must have connection string or module id to create clients.");
            }
            var cs = IotHubConnectionStringBuilder.Create(config.EdgeHubConnectionString);

            if (string.IsNullOrEmpty(cs.DeviceId))
            {
                throw new InvalidConfigurationException(
                          "Connection string is not a device or module connection string.");
            }
            DeviceId = cs.DeviceId;
            ModuleId = cs.ModuleId;
        }
            /// <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);
            }
Beispiel #22
0
        public void Init(IModuleConfig config)
        {
            giftCacheManager = new GiftCacheManager(5);

            DanmakuShowConfig displayConfig = (DanmakuShowConfig)config;

            OptionDict = displayConfig.OptionDict;

            Control = new DanmakuShowControl(this);

            DanmakuShowWindow displayWindow = new DanmakuShowWindow();

            Window = displayWindow;
            if (displayConfig.WindowRect.Width != 0 && displayConfig.WindowRect.Height != 0)
            {
                displayWindow.Left   = displayConfig.WindowRect.Left;
                displayWindow.Top    = displayConfig.WindowRect.Top;
                displayWindow.Width  = displayConfig.WindowRect.Width;
                displayWindow.Height = displayConfig.WindowRect.Height;
            }
            Window.Show();

            Control.SetLock(displayConfig.IsLocked);
        }
		public ModuleDefinition(IModuleEntry moduleEntry, IModuleConfig moduleConfiguration)
		{
			if (moduleEntry == null)
			{
				throw new ArgumentNullException(nameof(moduleEntry));
			}

			if (moduleConfiguration == null)
			{
				throw new ArgumentNullException(nameof(moduleConfiguration));
			}

			this.moduleEntry = moduleEntry;
			this.moduleConfiguration = moduleConfiguration;

			if (moduleConfiguration.ImplementationType == null)
			{
				this.comparableImplementationType = string.Empty;
			}
			else
			{
				this.comparableImplementationType = Regex.Replace(moduleConfiguration.ImplementationType, @"\s", string.Empty);
			}
		}
        public ModuleDefinition(IModuleEntry moduleEntry, IModuleConfig moduleConfiguration)
        {
            if (moduleEntry == null)
            {
                throw new ArgumentNullException(nameof(moduleEntry));
            }

            if (moduleConfiguration == null)
            {
                throw new ArgumentNullException(nameof(moduleConfiguration));
            }

            this.moduleEntry         = moduleEntry;
            this.moduleConfiguration = moduleConfiguration;

            if (moduleConfiguration.ImplementationType == null)
            {
                this.comparableImplementationType = string.Empty;
            }
            else
            {
                this.comparableImplementationType = Regex.Replace(moduleConfiguration.ImplementationType, @"\s", string.Empty);
            }
        }
        /// <summary>
        /// Create sdk factory
        /// </summary>
        /// <param name="config"></param>
        /// <param name="logger"></param>
        public IoTSdkFactory(IModuleConfig config, ILogger logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            // The runtime injects this as an environment variable
            var deviceId = Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
            var moduleId = Environment.GetEnvironmentVariable("IOTEDGE_MODULEID");
            var ehubHost = Environment.GetEnvironmentVariable("IOTEDGE_GATEWAYHOSTNAME");

            if (string.IsNullOrEmpty(deviceId) ||
                string.IsNullOrEmpty(moduleId))
            {
                try {
                    if (!string.IsNullOrEmpty(config.EdgeHubConnectionString))
                    {
                        _cs = IotHubConnectionStringBuilder.Create(config.EdgeHubConnectionString);

                        if (string.IsNullOrEmpty(_cs.SharedAccessKey))
                        {
                            throw new InvalidConfigurationException(
                                      "Connection string is missing shared access key.");
                        }
                        if (string.IsNullOrEmpty(_cs.DeviceId))
                        {
                            throw new InvalidConfigurationException(
                                      "Connection string is missing device id.");
                        }

                        deviceId = _cs.DeviceId;
                        moduleId = _cs.ModuleId;
                        ehubHost = _cs.GatewayHostName;
                    }
                }
                catch (Exception e) {
                    _logger.Error(e, "Bad configuration value in EdgeHubConnectionString config.");
                }
            }

            ModuleId = moduleId;
            DeviceId = deviceId;

            if (string.IsNullOrEmpty(DeviceId))
            {
                var ex = new InvalidConfigurationException(
                    "If you are running outside of an IoT Edge context or in EdgeHubDev mode, then the " +
                    "host configuration is incomplete and missing the EdgeHubConnectionString setting." +
                    "You can run the module using the command line interface or in IoT Edge context, or " +
                    "manually set the 'EdgeHubConnectionString' environment variable.");

                _logger.Error(ex, "The Twin module was not configured correctly.");
                throw ex;
            }

            _bypassCertValidation = config.BypassCertVerification;
            if (!_bypassCertValidation)
            {
                var certPath = Environment.GetEnvironmentVariable("EdgeModuleCACertificateFile");
                if (!string.IsNullOrWhiteSpace(certPath))
                {
                    InstallCert(certPath);
                }
            }

            if (_bypassCertValidation)
            {
                // Running in debug mode - can only use mqtt over tcp
                _transport = TransportOption.MqttOverTcp;
            }
            else
            {
                _transport = config.Transport;
            }

            _timeout = TimeSpan.FromMinutes(5);
        }
Beispiel #26
0
 public void ApplyConfig(IModuleConfig config)
 {
     EventModuleConfig eventModuelConfig = config as EventModuleConfig;
 }
        /// <summary>
        /// Create sdk factory
        /// </summary>
        /// <param name="config"></param>
        /// <param name="logger"></param>
        public IoTSdkFactory(IModuleConfig config, ILogger logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            // The runtime injects this as an environment variable
            var deviceId = Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
            var moduleId = Environment.GetEnvironmentVariable("IOTEDGE_MODULEID");
            var ehubHost = Environment.GetEnvironmentVariable("IOTEDGE_GATEWAYHOSTNAME");

            try {
                if (!string.IsNullOrEmpty(config.EdgeHubConnectionString))
                {
                    _cs = IotHubConnectionStringBuilder.Create(config.EdgeHubConnectionString);
                    if (string.IsNullOrEmpty(_cs.DeviceId))
                    {
                        throw new InvalidConfigurationException(
                                  "Connection string is not a device or module connection string.");
                    }
                    deviceId = _cs.DeviceId;
                    moduleId = _cs.ModuleId;
                    ehubHost = _cs.GatewayHostName;
                }
                else if (string.IsNullOrEmpty(moduleId))
                {
                    throw new InvalidConfigurationException(
                              "Must have connection string or module id to create clients.");
                }
            }
            catch (Exception e) {
                var ex = new InvalidConfigurationException(
                    "The host configuration is incomplete and is missing a " +
                    "connection string for Azure IoTEdge or IoTHub. " +
                    "You either have to run the host under the control of " +
                    "EdgeAgent, or manually set the 'EdgeHubConnectionString' " +
                    "environment variable or configure the connection string " +
                    "value in your 'appsettings.json' configuration file.", e);
                _logger.Error("Bad configuration", () => ex);
                throw ex;
            }

            ModuleId = moduleId;
            DeviceId = deviceId;

            _bypassCertValidation = config.BypassCertVerification;
            if (!_bypassCertValidation)
            {
                var certPath = Environment.GetEnvironmentVariable("EdgeModuleCACertificateFile");
                if (!string.IsNullOrWhiteSpace(certPath))
                {
                    InstallCert(certPath);
                }
            }

            if (_bypassCertValidation)
            {
                // Running in debug mode - can only use mqtt over tcp
                _transport = TransportOption.MqttOverTcp;
            }
            else
            {
                _transport = config.Transport;
            }

            _timeout = TimeSpan.FromMinutes(5);
        }
		private static TreeNode CreatTreeNode(IModuleConfig module)
		{
			var item = new TreeNode(module.ModuleName);
			module.RequiredModulesNames.ForEach(c => item.Children.Add(CreateEmptyTreeNode(c, false, true)));
			module.DependingModulesNames.ForEach(c => item.Children.Add(CreateEmptyTreeNode(c, true, false)));
			module.ProvidedServices.Select(s => s.ServiceName).OrderBy(s => s).ToList().ForEach(c => item.Children.Add(CreateSimpleTreeNode(c)));			
			return item;
		}
 /// <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;
 }
        public async Task <ServiceResult> AddOrUpdate(HttpContext context, ShareModule shareModule, Type moduleType,
                                                      IModuleConfig config)
        {
            TaskModuleConfigBaseService(context);
            var result = ServiceResult.Success;

            if (config == null)
            {
                return(ServiceResult.FailedWithMessage("配置信息不存在"));
            }

            if (moduleType == null)
            {
                return(ServiceResult.FailedWithMessage("类型不能为空"));
            }

            if (string.IsNullOrWhiteSpace(shareModule.Name))
            {
                return(ServiceResult.FailedWithMessage("请输入配置名称"));
            }

            var attribute = GetModuleAttribute(moduleType);

            CheckTaskModuleAttribute(attribute, config);
            //检查是否符合单一原则
            if (!attribute.IsSupportMultipleConfiguration)
            {
                var moduleList = GetList(context);
                var find       = moduleList?.FirstOrDefault(e => e.ModuleId == attribute.Id);
                if (find != null && find.Id != shareModule.Id)
                {
                    return(ServiceResult.FailedWithMessage("该维度已配置,不支持重复配置"));
                }
            }

            try {
                shareModule.ConfigValue = config.ToRepositoryString();

                //添加
                if (shareModule.Id <= 0)
                {
                    var resultToken =
                        await _shareApiClient.AddShareModule(_serverAuthenticationManager.Token.Token, shareModule);

                    if (!resultToken)
                    {
                        return(ServiceResult.FailedWithMessage("添加失败"));
                    }

                    DeleteCache();
                }
                else
                {
                    var find        = GetSingle(context, shareModule.Id);
                    var resultToken =
                        await _shareApiClient.UpdateShareModule(_serverAuthenticationManager.Token.Token, shareModule);

                    if (!resultToken)
                    {
                        return(ServiceResult.FailedWithMessage("更新失败"));
                    }

                    DeleteCache();
                }
            } catch {
                return(ServiceResult.FailedWithMessage("服务异常,请稍后再试"));
            }

            return(result);
        }
        /// <summary>
        /// Create sdk factory
        /// </summary>
        /// <param name="config"></param>
        /// <param name="broker"></param>
        /// <param name="logger"></param>
        public IoTSdkFactory(IModuleConfig config, IEventSourceBroker broker, ILogger logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            if (broker != null)
            {
                _logHook = broker.Subscribe(IoTSdkLogger.EventSource, new IoTSdkLogger(logger));
            }

            // The runtime injects this as an environment variable
            var deviceId = Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
            var moduleId = Environment.GetEnvironmentVariable("IOTEDGE_MODULEID");
            var ehubHost = Environment.GetEnvironmentVariable("IOTEDGE_GATEWAYHOSTNAME");

            try {
                if (!string.IsNullOrEmpty(config.EdgeHubConnectionString))
                {
                    _cs = IotHubConnectionStringBuilder.Create(config.EdgeHubConnectionString);

                    if (string.IsNullOrEmpty(_cs.SharedAccessKey))
                    {
                        throw new InvalidConfigurationException(
                                  "Connection string is missing shared access key.");
                    }
                    if (string.IsNullOrEmpty(_cs.DeviceId))
                    {
                        throw new InvalidConfigurationException(
                                  "Connection string is missing device id.");
                    }

                    deviceId = _cs.DeviceId;
                    moduleId = _cs.ModuleId;
                    ehubHost = _cs.GatewayHostName ?? ehubHost;

                    if (string.IsNullOrWhiteSpace(_cs.GatewayHostName) && !string.IsNullOrWhiteSpace(ehubHost))
                    {
                        _cs = IotHubConnectionStringBuilder.Create(
                            config.EdgeHubConnectionString + ";GatewayHostName=" + ehubHost);
                    }
                }
            }
            catch (Exception e) {
                _logger.Error(e, "Bad configuration value in EdgeHubConnectionString config.");
            }

            ModuleId = moduleId;
            DeviceId = deviceId;
            Gateway  = ehubHost;

            if (string.IsNullOrEmpty(DeviceId))
            {
                var ex = new InvalidConfigurationException(
                    "If you are running outside of an IoT Edge context or in EdgeHubDev mode, then the " +
                    "host configuration is incomplete and missing the EdgeHubConnectionString setting." +
                    "You can run the module using the command line interface or in IoT Edge context, or " +
                    "manually set the 'EdgeHubConnectionString' environment variable.");

                _logger.Error(ex, "The Twin module was not configured correctly.");
                throw ex;
            }

            _bypassCertValidation = config.BypassCertVerification;
            if (!_bypassCertValidation)
            {
                var certPath = Environment.GetEnvironmentVariable("EdgeModuleCACertificateFile");
                if (!string.IsNullOrWhiteSpace(certPath))
                {
                    InstallCert(certPath);
                }
                else if (!string.IsNullOrEmpty(ehubHost))
                {
                    _bypassCertValidation = true;
                }
            }
            if (!string.IsNullOrEmpty(ehubHost))
            {
                // Running in edge mode
                // the configured transport (if provided) will be forced to it's OverTcp
                // variant as follows: AmqpOverTcp when Amqp, AmqpOverWebsocket or AmqpOverTcp specified
                // and MqttOverTcp otherwise. Default is MqttOverTcp
                if ((config.Transport & TransportOption.Mqtt) != 0)
                {
                    // prefer Mqtt over Amqp due to performance reasons
                    _transport = TransportOption.MqttOverTcp;
                }
                else
                {
                    _transport = TransportOption.AmqpOverTcp;
                }
                _logger.Information("Connecting all clients to {edgeHub} using {transport}.",
                                    ehubHost, _transport);
            }
            else
            {
                _transport = config.Transport;
            }
            _timeout = TimeSpan.FromMinutes(5);
        }
Beispiel #32
0
 /// <summary>
 /// Create job scope factory
 /// </summary>
 /// <param name="jobConfig"></param>
 /// <param name="clientConfig"></param>
 public WriterGroupJobContainerFactory(WriterGroupJobModel jobConfig,
                                       IModuleConfig clientConfig)
 {
     _clientConfig = clientConfig ?? throw new ArgumentNullException(nameof(clientConfig));
     _jobConfig    = jobConfig ?? throw new ArgumentNullException(nameof(jobConfig));
 }