/// <summary>
        /// Initializes the FrameProcessor class
        /// </summary>
        /// <param name="amntTargetBoxes">Amount of colours to be stored (the amount of targets set)</param>
        public FrameProcessor(SendOSCMsg sendOscMsg, SendOSCBoxes sendOSCBoxes, RuntimeSettings settings)
        {
            this.sendOSCMsg = sendOscMsg;
            this.sendOSCBoxes = sendOSCBoxes;
            pixelBGRAData = new byte[(640 * 480 * 4)];

            this.settings = settings;
            processTargetBoxChanges(settings); // Process the first-time settings
            settings.settingsChanged += this.processTargetBoxChanges;

            // Setting up the backgroundProcesses
            backgroundProcessColour = new BackgroundWorker();
            backgroundProcessDepth = new BackgroundWorker();
            backgroundProcessColour.DoWork += new DoWorkEventHandler(this.ProcessColourData);
            backgroundProcessDepth.DoWork += new DoWorkEventHandler(this.ProcessDepthData);

            #if DEBUG5
            bitmaps.box1 = new WriteableBitmap(108, 108, 96.0, 96.0, PixelFormats.Bgr32, null);
            bitmaps.box2 = new WriteableBitmap(108, 108, 96.0, 96.0, PixelFormats.Bgr32, null);
            bitmaps.box3 = new WriteableBitmap(108, 108, 96.0, 96.0, PixelFormats.Bgr32, null);
            bitmaps.box4 = new WriteableBitmap(108, 108, 96.0, 96.0, PixelFormats.Bgr32, null);
            bitmaps.box5 = new WriteableBitmap(108, 108, 96.0, 96.0, PixelFormats.Bgr32, null);

            previewWindow = new TargetBoxPreview();
            previewWindow.Box1.Source = bitmaps.box1;
            previewWindow.Box2.Source = bitmaps.box2;
            previewWindow.Box3.Source = bitmaps.box3;
            previewWindow.Box4.Source = bitmaps.box4;
            previewWindow.Box5.Source = bitmaps.box5;

            previewWindow.Show();
            #endif
        }
 private void ProcessSettingsChanges(object sender)
 {
     this.Dispatcher.Invoke((Action)(() =>
     {
         settings = sender as RuntimeSettings;
         this.Targets.Value  = this.settings.amntTargetBoxes;
         this.Zoom.IsChecked = this.settings.zoom;
         this.VolumeSlider.Value = (double)this.settings.volume;
         this.SynthType.SelectedIndex = (int)settings.synthType;
     }));
 }
        public InitConfigWindow()
        {
            // Show the splash just a wee bit longer
            Thread.Sleep(500);

            previewImages = new ResourceDictionary();
            previewImages.Source = new Uri("/Resources/PreviewImagesDictionary.xaml", UriKind.Relative);
            settings = RuntimeSettings.Instance;

            InitializeComponent();
        }
Ejemplo n.º 4
0
 public void RunStep(RuntimeSettings settings, ILog log)
 {
     _session.CurrentChannel = new Channel
     {
         Title         = settings.Configuration.Metadata.Title,
         Link          = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressTargetHost],
         PubDate       = DateTime.UtcNow.ToWpTimeFormat(),
         Language      = "hu",
         Wxr_version   = "1.2",
         Base_site_url = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressTargetHost],
         Base_blog_url = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressTargetHost],
         Generator     = "BookGen",
         Description   = string.Empty,
         Author        = new Author
         {
             Author_display_name = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressAuthorDisplayName],
             Author_email        = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressAuthorEmail],
             Author_first_name   = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressAuthorFirstName],
             Author_last_name    = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressAuthorLastName],
             Author_id           = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressAuthorId],
             Author_login        = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressAuthorLogin]
         }
     };
 }
Ejemplo n.º 5
0
        internal async Task SetOutput(bool On, string Actor)
        {
#if GPIO
            if (this.gpioPin != null)
            {
                this.gpioPin.Write(On ? GpioPinValue.High : GpioPinValue.Low);
#else
            if (this.arduino != null)
            {
                this.arduino.digitalWrite(9, On ? PinState.HIGH : PinState.LOW);
#endif
                await RuntimeSettings.SetAsync("Actuator.Output", On);

                this.output = On;

                Log.Informational("Setting Control Parameter.", string.Empty, Actor ?? "Windows user",
                                  new KeyValuePair <string, object>("Output", On));

                if (Actor != null)
                {
                    await MainPage.Instance.OutputSet(On);
                }

                this.outputResource?.TriggerAll();
            }
        }

        /// <summary>
        /// Invoked when Navigation to a certain page fails
        /// </summary>
        /// <param name="sender">The Frame which failed navigation</param>
        /// <param name="e">Details about the navigation failure</param>
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }
    public void OnInspectorGUI2()
    {
        //GUILayout.Space(4);

        //GUILayout.BeginHorizontal();
        //GUILayout.Space(2);
        //GUI.DrawTexture(GUILayoutUtility.GetRect(128, 128, 64, 64, GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false)), Resources.Load("AscensionLogo") as Texture2D);
        //GUILayout.EndHorizontal();

        GUILayout.Space(2);

        EditorGUI.BeginDisabledGroup(Application.isPlaying);

        AscensionEntity entity     = (AscensionEntity)target;
        PrefabType      prefabType = PrefabUtility.GetPrefabType(entity.gameObject);

        RuntimeSettings settings = RuntimeSettings.Instance;

#if DEBUG
        EditorGUILayout.LabelField("Prefab Type", prefabType.ToString());
#endif

        // Prefab Id
        switch (prefabType)
        {
        case PrefabType.Prefab:
        case PrefabType.PrefabInstance:
            EditorGUILayout.LabelField("Prefab Id", entity.PrefabId.ToString());

            if (entity.prefabId < 0)
            {
                EditorGUILayout.HelpBox("Prefab id not set, run the 'Ascension/Emit Code' menu option to correct", MessageType.Error);
            }

            if (prefabType == PrefabType.Prefab)
            {
                if (PrefabDatabase.Contains(entity) == false)
                {
                    EditorGUILayout.HelpBox("Prefab lookup not valid, run the 'Ascension/Emit Code' menu option to correct", MessageType.Error);
                }
            }
            break;

        case PrefabType.None:
            if (entity.prefabId != 0)
            {
                // force 0 prefab id
                entity.prefabId = 0;

                // set dirty
                EditorUtility.SetDirty(this);
            }

            DEditorGUI.Disabled(() =>
            {
                EditorGUILayout.IntField("Prefab Id", entity.prefabId);
            });

            break;

        case PrefabType.DisconnectedPrefabInstance:
            entity.prefabId = EditorGUILayout.IntField("Prefab Id", entity.prefabId);

            if (entity.prefabId < 0)
            {
                EditorGUILayout.HelpBox("Prefab Id not set", MessageType.Error);
            }
            break;
        }

        EditState(entity);
        EditProperties(entity);
        EditSceneProperties(entity, prefabType);

        EditorGUI.EndDisabledGroup();

        if (prefabType == PrefabType.Prefab)
        {
            SaveEntity(entity);
        }
        else
        {
            if (Application.isPlaying)
            {
                RuntimeInfoGUI(entity);
            }
            else
            {
                SaveEntity(entity);
            }
        }
    }
Ejemplo n.º 7
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(XmppClient).GetTypeInfo().Assembly,
                    typeof(Waher.Content.Markdown.MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(XML).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Expression).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Graphs.Graph).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(this.output);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo == null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                string Host = await RuntimeSettings.GetAsync("XmppHost", "waher.se");

                int Port = (int)await RuntimeSettings.GetAsync("XmppPort", 5222);

                string UserName = await RuntimeSettings.GetAsync("XmppUserName", string.Empty);

                string PasswordHash = await RuntimeSettings.GetAsync("XmppPasswordHash", string.Empty);

                string PasswordHashMethod = await RuntimeSettings.GetAsync("XmppPasswordHashMethod", string.Empty);

                if (string.IsNullOrEmpty(Host) ||
                    Port <= 0 || Port > ushort.MaxValue ||
                    string.IsNullOrEmpty(UserName) ||
                    string.IsNullOrEmpty(PasswordHash) ||
                    string.IsNullOrEmpty(PasswordHashMethod))
                {
                    await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                async() => await this.ShowConnectionDialog(Host, Port, UserName));
                }
                else
                {
                    this.xmppClient = new XmppClient(Host, Port, UserName, PasswordHash, PasswordHashMethod, "en",
                                                     typeof(App).GetTypeInfo().Assembly) // Add "new LogSniffer()" to the end, to output communication to the log.
                    {
                        AllowCramMD5   = false,
                        AllowDigestMD5 = false,
                        AllowPlain     = false,
                        AllowScramSHA1 = true
                    };
                    this.xmppClient.OnStateChanged    += this.StateChanged;
                    this.xmppClient.OnConnectionError += this.ConnectionError;
                    this.AttachFeatures();

                    Log.Informational("Connecting to " + this.xmppClient.Host + ":" + this.xmppClient.Port.ToString());
                    this.xmppClient.Connect();
                }

                this.minuteTimer = new Timer((State) =>
                {
                    if (this.xmppClient != null &&
                        (this.xmppClient.State == XmppState.Error || this.xmppClient.State == XmppState.Offline))
                    {
                        this.xmppClient.Reconnect();
                    }
                }, null, 60000, 60000);
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticateController"/> class.
        /// </summary>
        /// <param name="smsClient">The SMS client.</param>
        /// <param name="dataProtectionProvider">The data protection provider.</param>
        /// <param name="urlHelperFactory">The URL helper factory.</param>
        /// <param name="actionContextAccessor">The action context accessor.</param>
        /// <param name="eventPublisher">The event publisher.</param>
        /// <param name="authorizationCodeStore">The authorization code store.</param>
        /// <param name="authenticationService">The authentication service.</param>
        /// <param name="authenticationSchemeProvider">The authentication scheme provider.</param>
        /// <param name="twoFactorAuthenticationHandler">The two factor authentication handler.</param>
        /// <param name="subjectBuilder">The subject builder.</param>
        /// <param name="consentRepository">The consent repository.</param>
        /// <param name="scopeRepository">The scope repository.</param>
        /// <param name="tokenStore">The token store.</param>
        /// <param name="resourceOwnerRepository">The resource owner repository.</param>
        /// <param name="confirmationCodeStore">The confirmation code store.</param>
        /// <param name="clientStore">The client store.</param>
        /// <param name="jwksStore">The JWKS store.</param>
        /// <param name="accountFilters">The account filters.</param>
        /// <param name="logger">The controller logger.</param>
        /// <param name="runtimeSettings">The runtime settings.</param>
        public AuthenticateController(
            ISmsClient smsClient,
            IDataProtectionProvider dataProtectionProvider,
            IUrlHelperFactory urlHelperFactory,
            IActionContextAccessor actionContextAccessor,
            IEventPublisher eventPublisher,
            IAuthorizationCodeStore authorizationCodeStore,
            IAuthenticationService authenticationService,
            IAuthenticationSchemeProvider authenticationSchemeProvider,
            ITwoFactorAuthenticationHandler twoFactorAuthenticationHandler,
            ISubjectBuilder subjectBuilder,
            IConsentRepository consentRepository,
            IScopeRepository scopeRepository,
            ITokenStore tokenStore,
            IResourceOwnerRepository resourceOwnerRepository,
            IConfirmationCodeStore confirmationCodeStore,
            IClientStore clientStore,
            IJwksStore jwksStore,
            IEnumerable <IAccountFilter> accountFilters,
            ILogger <AuthenticateController> logger,
            RuntimeSettings runtimeSettings)
            : base(
                dataProtectionProvider,
                urlHelperFactory,
                actionContextAccessor,
                eventPublisher,
                authenticationService,
                authenticationSchemeProvider,
                twoFactorAuthenticationHandler,
                authorizationCodeStore,
                consentRepository,
                scopeRepository,
                tokenStore,
                resourceOwnerRepository,
                confirmationCodeStore,
                clientStore,
                jwksStore,
                subjectBuilder,
                accountFilters,
                logger,
                runtimeSettings)
        {
            _eventPublisher        = eventPublisher;
            _confirmationCodeStore = confirmationCodeStore;
            _logger           = logger;
            _getUserOperation = new GetUserOperation(resourceOwnerRepository, logger);
            var generateSms = new GenerateAndSendSmsCodeOperation(smsClient, confirmationCodeStore, logger);

            _smsAuthenticationOperation = new SmsAuthenticationOperation(
                runtimeSettings,
                smsClient,
                confirmationCodeStore,
                resourceOwnerRepository,
                subjectBuilder,
                accountFilters.ToArray(),
                eventPublisher,
                logger);
            _validateConfirmationCode = new ValidateConfirmationCodeAction(confirmationCodeStore);
            _authenticateHelper       = new AuthenticateHelper(
                authorizationCodeStore,
                tokenStore,
                scopeRepository,
                consentRepository,
                clientStore,
                jwksStore,
                eventPublisher,
                logger);
            _generateAndSendSmsCodeOperation = generateSms;
        }
Ejemplo n.º 9
0
 public RuntimeService(IDatabaseContext databaseContext, RuntimeSettings runtimeSettings)
 {
     this.databaseContext = databaseContext;
     this.runtimeSettings = runtimeSettings;
 }
Ejemplo n.º 10
0
 public ConfigurationService(ISerializeService s, IProcessService p, Logger l, RuntimeSettings settings)
 {
     serializeService = s;
     logger           = l;
     processService   = p;
     runtimeSettings  = settings;
     CreateOrMigrateSettings();
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Loads the value of the resource, from persisted storage.
 /// </summary>
 public override async Task ReadPersistedValue()
 {
     this.value = await RuntimeSettings.GetAsync(this.Path, this.value);
 }
Ejemplo n.º 12
0
 public static void Initialize(NetworkModes mode, IPEndPoint endPoint, string autoloadScene, RuntimeSettings config)
 {
     Core.Initialize(mode, endPoint, config, autoloadScene);
 }
Ejemplo n.º 13
0
 public ConfigSettings()
 {
     runTimeSettings = new RuntimeSettings();
     reportSettings = new ReportSettings();
     httpProxy = new HttpProxy();
     imageCompareSettings = new ImageCompareSettings();
     purpleSettings = new PurpleSettings();
     browserStackSettings = new BrowserStackSettings();
     sauceLabsSettings = new SauceLabsSettings();
 }
 public VoiceRecognition()
 {
     this.settings = RuntimeSettings.Instance;
 }
Ejemplo n.º 15
0
 static CompositeRuntimeSettings()
 {
     runtimeSettings = new RuntimeSettings();
 }
Ejemplo n.º 16
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ICoapContentFormat).GetTypeInfo().Assembly,
                    typeof(IDtlsCredentials).GetTypeInfo().Assembly,
                    typeof(Lwm2mClient).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                       Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);
                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low);

                            this.digitalOutput0?.Set(this.output.Value);
                            this.actuation0?.Set(this.output.Value);
                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                            this.digitalOutput0?.Set(this.output.Value);
                            this.actuation0?.Set(this.output.Value);
                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                /************************************************************************************
                * To create an unencrypted CoAP Endpoint on the default CoAP port:
                *
                *    this.coapEndpoint = new CoapEndpoint();
                *
                * To create an unencrypted CoAP Endpoint on the default CoAP port,
                * with a sniffer that outputs communication to the window:
                *
                *    this.coapEndpoint = new CoapEndpoint(new LogSniffer());
                *
                * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using
                * the users defined in the IUserSource users:
                *
                *    this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users);
                *
                * To create a CoAP endpoint, that listens to both the default CoAP port, for
                * unencrypted communication, and the default CoAPS port, for encrypted,
                * authenticated and authorized communication, using
                * the users defined in the IUserSource users. Only users having the given
                * privilege (if not empty) will be authorized to access resources on the endpoint:
                *
                *    this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                *       new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false);
                *
                ************************************************************************************/

                this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                                                     new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false);

                this.outputResource = this.coapEndpoint.Register("/Output", (req, resp) =>
                {
                    string s;

                    if (this.output.HasValue)
                    {
                        s = this.output.Value ? "true" : "false";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, async(req, resp) =>
                {
                    try
                    {
                        string s = req.Decode() as string;
                        if (s is null && req.Payload != null)
                        {
                            s = Encoding.UTF8.GetString(req.Payload);
                        }

                        if (s is null || !CommonTypes.TryParse(s, out bool Output))
                        {
                            resp.RST(CoapCode.BadRequest);
                        }
                        else
                        {
                            resp.Respond(CoapCode.Changed);
                            await this.SetOutput(Output, req.From.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                }, Notifications.Acknowledged, "Digital Output.", null, null,
        internal static void AddBotRuntimePlugins(this IServiceCollection services, IConfiguration configuration, RuntimeSettings runtimeSettings)
        {
            using (IServiceScope serviceScope = services.BuildServiceProvider().CreateScope())
            {
                var pluginEnumerator = serviceScope.ServiceProvider.GetService <IBotPluginEnumerator>() ?? new AssemblyBotPluginEnumerator(AssemblyLoadContext.Default);

                // Iterate through configured plugins and load each one
                foreach (BotPluginDefinition plugin in runtimeSettings.Plugins)
                {
                    plugin.Load(pluginEnumerator, services, configuration);
                }
            }
        }
        public void AddComponent_ConfiguredComponent()
        {
            // Setup
            // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="This is a fake password.")]
            const string contosoSecret = "shh123";

            // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="This is a fake password.")]
            const string adventureWorksSecret = "superSecret!@!";

            var assemblyName = typeof(RuntimeComponentTests).Assembly.GetName().Name;

            var settings = new Dictionary <string, string>
            {
                { $"{assemblyName}:contosoSecret", contosoSecret },
                { $"{assemblyName}:AdventureWorksSkillId", "myCoolSkill" },
                { $"{assemblyName}:AdventureWorksSecret", adventureWorksSecret },
            };

            // Full component settings
            var runtimeSettings = new RuntimeSettings()
            {
                // Declare plugin
                Components = new[]
                {
                    new BotComponentDefinition()
                    {
                        Name           = assemblyName,
                        SettingsPrefix = assemblyName
                    }
                },

                // Adapters
                Adapters = new[]
                {
                    new AdapterSettings()
                    {
                        Name = assemblyName, Route = "contoso", Enabled = true
                    },
                    new AdapterSettings()
                    {
                        Name = assemblyName, Route = "adventureworks", Enabled = true
                    },
                }
            };

            IServiceCollection services      = new ServiceCollection();
            IConfiguration     configuration = new ConfigurationBuilder()
                                               .AddInMemoryCollection(settings)
                                               .AddRuntimeSettings(runtimeSettings)
                                               .Build();

            services.AddSingleton <IConfiguration>(configuration);

            // Test
            services.AddBotRuntimeComponents(configuration);

            // Assert
            var provider = services.BuildServiceProvider();

            // Assert adapters
            var httpAdapters = provider.GetServices <IBotFrameworkHttpAdapter>();

            Assert.Contains(httpAdapters, a => a.GetType().Equals(typeof(ContosoAdapter)));
            Assert.Contains(httpAdapters, a => a.GetType().Equals(typeof(AdventureWorksAdapter)));
        }
        internal static void AddBotRuntimeStorage(this IServiceCollection services, IConfiguration configuration, RuntimeSettings runtimeSettings)
        {
            services.AddSingleton <UserState>();
            services.AddSingleton <ConversationState>();

            // Cosmosdb
            if (runtimeSettings?.Storage == nameof(CosmosDbPartitionedStorage))
            {
                var cosmosDbOptions = configuration?.GetSection(nameof(CosmosDbPartitionedStorage)).Get <CosmosDbPartitionedStorageOptions>();
                services.AddSingleton <IStorage>(sp => new CosmosDbPartitionedStorage(cosmosDbOptions));
            }

            // Blob
            else if (runtimeSettings?.Storage == nameof(BlobsStorage))
            {
                var blobOptions = configuration?.GetSection(nameof(BlobsStorage)).Get <BlobsStorageSettings>();
                services.AddSingleton <IStorage>(sp => new BlobsStorage(blobOptions?.ConnectionString, blobOptions?.ContainerName));
            }

            // Default
            else
            {
                // If no storage is configured, default to memory storage
                services.AddSingleton <IStorage, MemoryStorage>();
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Saves the value of the resource, to persisted storage.
 /// </summary>
 /// <returns></returns>
 public override async Task WritePersistedValue()
 {
     await RuntimeSettings.SetAsync(this.Path, this.value);
 }
Ejemplo n.º 21
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(LastOn ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo == null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, LastOn ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty);
                //this.mqttClient = new MqttClient("iot.eclipse.org", 8883, true, this.deviceId, string.Empty, new LogSniffer());
                this.mqttClient.OnStateChanged += (sender, state) =>
                {
                    Log.Informational("MQTT client state changed: " + state.ToString());

                    if (state == MqttState.Connected)
                    {
                        this.mqttClient.SUBSCRIBE("Waher/MIOT/" + this.deviceId + "/Set/+", MqttQualityOfService.AtLeastOnce);
                    }
                };

                this.mqttClient.OnContentReceived += async(sender, e) =>
                {
                    try
                    {
                        if (e.Topic.EndsWith("/On"))
                        {
                            string s = Encoding.UTF8.GetString(e.Data);
                            s = s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower();

                            if (bool.TryParse(s, out bool On))
                            {
                                await this.SetOutput(On, "MQTT");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                DateTime Now = DateTime.Now;
                this.reconnectionTimer = new Timer(this.CheckConnection, null, 120000 - Now.Millisecond - Now.Second * 1000, 60000);
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
Ejemplo n.º 22
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

            var            commandLineParser = new Parser(settings => settings.CaseSensitive = false);
            var            optionsResult     = commandLineParser.ParseArguments <ConsoleOptions>(args);
            var            runtimeDictionary = new Dictionary <string, string>();
            ConsoleOptions consoleOptions    = new ConsoleOptions();

            optionsResult.WithNotParsed(errors =>
            {
                var text       = HelpText.AutoBuild(optionsResult);
                text.Copyright = " ";
                text.Heading   = "Jackett v" + EnvironmentUtil.JackettVersion;
                Console.WriteLine(text);
                Environment.Exit(1);
                return;
            });

            optionsResult.WithParsed(options =>
            {
                if (string.IsNullOrEmpty(options.Client))
                {
                    bool runningOnDotNetCore = RuntimeInformation.FrameworkDescription.IndexOf("Core", StringComparison.OrdinalIgnoreCase) >= 0;

                    if (runningOnDotNetCore)
                    {
                        options.Client = "httpclientnetcore";
                    }
                    else
                    {
                        options.Client = "httpclient";
                    }
                }

                Settings          = options.ToRunTimeSettings();
                consoleOptions    = options;
                runtimeDictionary = GetValues(Settings);
            });

            LogManager.Configuration = LoggingSetup.GetLoggingConfiguration(Settings);
            Logger logger = LogManager.GetCurrentClassLogger();

            logger.Info("Starting Jackett v" + EnvironmentUtil.JackettVersion);

            // create PID file early
            if (!string.IsNullOrWhiteSpace(Settings.PIDFile))
            {
                try
                {
                    var proc = Process.GetCurrentProcess();
                    File.WriteAllText(Settings.PIDFile, proc.Id.ToString());
                }
                catch (Exception e)
                {
                    logger.Error(e, "Error while creating the PID file");
                }
            }

            Initialisation.CheckEnvironmentalVariables(logger);
            Initialisation.ProcessSettings(Settings, logger);

            ISerializeService     serializeService     = new SerializeService();
            IProcessService       processService       = new ProcessService(logger);
            IConfigurationService configurationService = new ConfigurationService(serializeService, processService, logger, Settings);

            if (consoleOptions.Install || consoleOptions.Uninstall || consoleOptions.StartService || consoleOptions.StopService || consoleOptions.ReserveUrls)
            {
                bool isWindows = Environment.OSVersion.Platform == PlatformID.Win32NT;

                if (isWindows)
                {
                    ServerConfig serverConfig = configurationService.BuildServerConfig(Settings);
                    Initialisation.ProcessWindowsSpecificArgs(consoleOptions, processService, serverConfig, logger);
                }
                else
                {
                    logger.Error($"ReserveUrls and service arguments only apply to Windows, please remove them from your start arguments");
                    Environment.Exit(1);
                }
            }

            var builder = new ConfigurationBuilder();

            builder.AddInMemoryCollection(runtimeDictionary);
            builder.AddJsonFile(Path.Combine(configurationService.GetAppDataFolder(), "appsettings.json"), optional: true);

            Configuration = builder.Build();

            do
            {
                if (!isWebHostRestart)
                {
                    if (consoleOptions.Port != 0 || consoleOptions.ListenPublic || consoleOptions.ListenPrivate)
                    {
                        ServerConfig serverConfiguration = configurationService.BuildServerConfig(Settings);
                        Initialisation.ProcessConsoleOverrides(consoleOptions, processService, serverConfiguration, configurationService, logger);
                    }
                }

                ServerConfig serverConfig = configurationService.BuildServerConfig(Settings);
                Int32.TryParse(serverConfig.Port.ToString(), out Int32 configPort);
                string[] url = serverConfig.GetListenAddresses(serverConfig.AllowExternal);

                isWebHostRestart = false;

                try
                {
                    logger.Debug("Creating web host...");
                    string applicationFolder = Path.Combine(configurationService.ApplicationFolder(), "Content");
                    logger.Debug($"Content root path is: {applicationFolder}");

                    CreateWebHostBuilder(args, url, applicationFolder).Build().Run();
                }
                catch (Exception ex)
                {
                    if (ex.InnerException is Microsoft.AspNetCore.Connections.AddressInUseException)
                    {
                        logger.Error("Address already in use: Most likely Jackett is already running. " + ex.Message);
                        Environment.Exit(1);
                    }
                    logger.Error(ex);
                    throw;
                }
            } while (isWebHostRestart);
        }
Ejemplo n.º 23
0
        private static void Run(string[] args, ThreadExecuter threadExecuter)
        {
            var factory = new SessionFactory();

            // Settings should be upgraded early, it contains the language pack etc and some services depends on settings.
            var            settingsService = StartupService.LoadSettingsService();
            IPlayerItemDao playerItemDao   = new PlayerItemRepo(threadExecuter, factory);

            IDatabaseItemDao databaseItemDao = new DatabaseItemRepo(threadExecuter, factory);

            RuntimeSettings.InitializeLanguage(settingsService.GetLocal().LocalizationFile, databaseItemDao.GetTagDictionary());
            DumpTranslationTemplate();

            threadExecuter.Execute(() => new MigrationHandler(factory).Migrate());

            IDatabaseSettingDao databaseSettingDao = new DatabaseSettingRepo(threadExecuter, factory);

            LoadUuid(databaseSettingDao);
            var azurePartitionDao = new AzurePartitionRepo(threadExecuter, factory);
            IDatabaseItemStatDao databaseItemStatDao = new DatabaseItemStatRepo(threadExecuter, factory);
            IItemTagDao          itemTagDao          = new ItemTagRepo(threadExecuter, factory);


            IBuddyItemDao         buddyItemDao         = new BuddyItemRepo(threadExecuter, factory);
            IBuddySubscriptionDao buddySubscriptionDao = new BuddySubscriptionRepo(threadExecuter, factory);
            IRecipeItemDao        recipeItemDao        = new RecipeItemRepo(threadExecuter, factory);
            IItemSkillDao         itemSkillDao         = new ItemSkillRepo(threadExecuter, factory);
            AugmentationItemRepo  augmentationItemRepo = new AugmentationItemRepo(threadExecuter, factory, new DatabaseItemStatDaoImpl(factory));
            var grimDawnDetector = new GrimDawnDetector(settingsService);

            Logger.Debug("Updating augment state..");
            augmentationItemRepo.UpdateState();

            // TODO: GD Path has to be an input param, as does potentially mods.
            ParsingService parsingService = new ParsingService(itemTagDao, null, databaseItemDao, databaseItemStatDao, itemSkillDao, settingsService.GetLocal().LocalizationFile);

            StartupService.PrintStartupInfo(factory, settingsService);



            if (RuntimeSettings.Language is EnglishLanguage language)
            {
                foreach (var tag in itemTagDao.GetClassItemTags())
                {
                    language.SetTagIfMissing(tag.Tag, tag.Name);
                }
            }

            if (args != null && args.Any(m => m.Contains("-logout")))
            {
                Logger.Info("Started with -logout specified, logging out of online backups.");
                settingsService.GetPersistent().AzureAuthToken = null;
            }

            using (CefBrowserHandler browser = new CefBrowserHandler())
            {
                _mw = new MainWindow(browser,
                                     databaseItemDao,
                                     databaseItemStatDao,
                                     playerItemDao,
                                     azurePartitionDao,
                                     databaseSettingDao,
                                     buddyItemDao,
                                     buddySubscriptionDao,
                                     recipeItemDao,
                                     itemSkillDao,
                                     itemTagDao,
                                     parsingService,
                                     augmentationItemRepo,
                                     settingsService,
                                     grimDawnDetector
                                     );

                Logger.Info("Checking for database updates..");

                StartupService.PerformIconCheck(databaseSettingDao, grimDawnDetector);
                playerItemDao.DeleteDuplidates();

                _mw.Visible = false;
                if (new DonateNagScreen(settingsService).CanNag)
                {
                    Application.Run(new DonateNagScreen(settingsService));
                }

                Logger.Info("Running the main application..");

                StartupService.PerformGrimUpdateCheck(settingsService);
                Application.Run(_mw);
            }

            Logger.Info("Application ended.");
        }
Ejemplo n.º 24
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ImageCodec).GetTypeInfo().Assembly,
                    typeof(MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(MarkdownToHtmlConverter).GetTypeInfo().Assembly,
                    typeof(IJwsAlgorithm).GetTypeInfo().Assembly,
                    typeof(Expression).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                       Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);
                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                this.tokenAuthentication = new JwtAuthentication(this.deviceId, this.users, this.tokenFactory);

                this.httpServer = new HttpServer();
                //this.httpServer = new HttpServer(new LogSniffer());

                StorageFile File = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Root/favicon.ico"));

                string Root = File.Path;
                Root = Root.Substring(0, Root.Length - 11);
                this.httpServer.Register(new HttpFolderResource(string.Empty, Root, false, false, true, true));

                this.httpServer.Register("/", (req, resp) =>
                {
                    throw new TemporaryRedirectException("/Index.md");
                });

                this.httpServer.Register("/Momentary", (req, resp) =>
                {
                    resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store");

                    if (req.Header.Accept != null)
                    {
                        switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json"))
                        {
                        case "text/xml":
                        case "application/xml":
                            this.ReturnMomentaryAsXml(req, resp);
                            break;

                        case "application/json":
                            this.ReturnMomentaryAsJson(req, resp);
                            break;

                        default:
                            throw new NotAcceptableException();
                        }
                    }
                    else
                    {
                        this.ReturnMomentaryAsXml(req, resp);
                    }

                    return(Task.CompletedTask);
                }, this.tokenAuthentication);

                this.httpServer.Register("/Set", null, async(req, resp) =>
                {
                    try
                    {
                        if (!req.HasData)
                        {
                            throw new BadRequestException();
                        }

                        if (!(req.DecodeData() is string s) || !CommonTypes.TryParse(s, out bool OutputValue))
                        {
                            throw new BadRequestException();
                        }

                        if (req.Header.Accept != null)
                        {
                            switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json"))
                            {
                            case "text/xml":
                            case "application/xml":
                                await this.SetOutput(OutputValue, req.RemoteEndPoint);
                                this.ReturnMomentaryAsXml(req, resp);
                                break;

                            case "application/json":
                                await this.SetOutput(OutputValue, req.RemoteEndPoint);
                                this.ReturnMomentaryAsJson(req, resp);
                                break;

                            default:
                                throw new NotAcceptableException();
                            }
                        }
                        else
                        {
                            await this.SetOutput(OutputValue, req.RemoteEndPoint);
                            this.ReturnMomentaryAsXml(req, resp);
                        }

                        await resp.SendResponse();
                    }
                    catch (Exception ex)
                    {
                        await resp.SendResponse(ex);
                    }
                }, false, this.tokenAuthentication);

                this.httpServer.Register("/Login", null, (req, resp) =>
                {
                    if (!req.HasData || req.Session is null)
                    {
                        throw new BadRequestException();
                    }

                    object Obj = req.DecodeData();

                    if (!(Obj is Dictionary <string, string> Form) ||
                        !Form.TryGetValue("UserName", out string UserName) ||
                        !Form.TryGetValue("Password", out string Password))
                    {
                        throw new BadRequestException();
                    }

                    string From = null;

                    if (req.Session.TryGetVariable("from", out Variable v))
                    {
                        From = v.ValueObject as string;
                    }

                    if (string.IsNullOrEmpty(From))
                    {
                        From = "/Index.md";
                    }

                    IUser User = this.Login(UserName, Password);
                    if (User != null)
                    {
                        Log.Informational("User logged in.", UserName, req.RemoteEndPoint, "LoginSuccessful", EventLevel.Minor);

                        req.Session["User"] = User;
                        req.Session.Remove("LoginError");

                        throw new SeeOtherException(From);
                    }
                    else
                    {
                        Log.Warning("Invalid login attempt.", UserName, req.RemoteEndPoint, "LoginFailure", EventLevel.Minor);
                        req.Session["LoginError"] = "Invalid login credentials provided.";
                    }

                    throw new SeeOtherException(req.Header.Referer.Value);
                }, true, false, true);

                this.httpServer.Register("/GetSessionToken", null, (req, resp) =>
                {
                    if (!req.Session.TryGetVariable("User", out Variable v) ||
                        !(v.ValueObject is IUser User))
                    {
                        throw new ForbiddenException();
                    }

                    string Token = this.tokenFactory.Create(new KeyValuePair <string, object>("sub", User.UserName));

                    resp.ContentType = JwtCodec.ContentType;
                    resp.Write(Token);

                    return(Task.CompletedTask);
                }, true, false, true);
            }
Ejemplo n.º 25
0
 public JackettModule(RuntimeSettings runtimeSettings)
 {
     _runtimeSettings = runtimeSettings;
 }
Ejemplo n.º 26
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ICoapContentFormat).GetTypeInfo().Assembly,
                    typeof(IDtlsCredentials).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                       Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);
                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += () =>
                    {
                        Log.Informational("Device ready.");

                        this.arduino.pinMode(13, PinMode.OUTPUT);                            // Onboard LED.
                        this.arduino.digitalWrite(13, PinState.HIGH);

                        this.arduino.pinMode(8, PinMode.INPUT);                              // PIR sensor (motion detection).
                        PinState Pin8 = this.arduino.digitalRead(8);
                        this.lastMotion = Pin8 == PinState.HIGH;
                        MainPage.Instance.DigitalPinUpdated(8, Pin8);

                        this.arduino.pinMode(9, PinMode.OUTPUT);                             // Relay.
                        this.arduino.digitalWrite(9, 0);                                     // Relay set to 0

                        this.arduino.pinMode("A0", PinMode.ANALOG);                          // Light sensor.
                        MainPage.Instance.AnalogPinUpdated("A0", this.arduino.analogRead("A0"));

                        this.sampleTimer = new Timer(this.SampleValues, null, 1000 - DateTime.Now.Millisecond, 1000);
                    };

                    this.arduino.AnalogPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.AnalogPinUpdated(pin, value);
                    };

                    this.arduino.DigitalPinUpdated += (pin, value) =>
                    {
                        MainPage.Instance.DigitalPinUpdated(pin, value);

                        if (pin == 8)
                        {
                            this.lastMotion = (value == PinState.HIGH);
                            this.motionResource?.TriggerAll();
                            this.momentaryResource?.TriggerAll();
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }

                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                /************************************************************************************
                * To create an unencrypted CoAP Endpoint on the default CoAP port:
                *
                *    this.coapEndpoint = new CoapEndpoint();
                *
                * To create an unencrypted CoAP Endpoint on the default CoAP port,
                * with a sniffer that outputs communication to the window:
                *
                *    this.coapEndpoint = new CoapEndpoint(new LogSniffer());
                *
                * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using
                * the users defined in the IUserSource users:
                *
                *    this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users);
                *
                * To create a CoAP endpoint, that listens to both the default CoAP port, for
                * unencrypted communication, and the default CoAPS port, for encrypted,
                * authenticated and authorized communication, using
                * the users defined in the IUserSource users. Only users having the given
                * privilege (if not empty) will be authorized to access resources on the endpoint:
                *
                *    this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                *       new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false);
                *
                ************************************************************************************/

                this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                                                     new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false);

                this.lightResource = this.coapEndpoint.Register("/Light", (req, resp) =>
                {
                    string s;

                    if (this.lastLight.HasValue)
                    {
                        s = ToString(this.lastLight.Value, 2) + " %";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, Notifications.Unacknowledged, "Light, in %.", null, null,
                                                                new int[] { PlainText.ContentFormatCode });

                this.lightResource?.TriggerAll(new TimeSpan(0, 0, 5));

                this.motionResource = this.coapEndpoint.Register("/Motion", (req, resp) =>
                {
                    string s;

                    if (this.lastMotion.HasValue)
                    {
                        s = this.lastMotion.Value ? "true" : "false";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, Notifications.Acknowledged, "Motion detector.", null, null,
                                                                 new int[] { PlainText.ContentFormatCode });

                this.motionResource?.TriggerAll(new TimeSpan(0, 1, 0));

                this.momentaryResource = this.coapEndpoint.Register("/Momentary", (req, resp) =>
                {
                    if (req.IsAcceptable(Xml.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsXml(req, resp);
                    }
                    else if (req.IsAcceptable(Json.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsJson(req, resp);
                    }
                    else if (req.IsAcceptable(PlainText.ContentFormatCode))
                    {
                        this.ReturnMomentaryAsPlainText(req, resp);
                    }
                    else if (req.Accept.HasValue)
                    {
                        throw new CoapException(CoapCode.NotAcceptable);
                    }
                    else
                    {
                        this.ReturnMomentaryAsPlainText(req, resp);
                    }
                }, Notifications.Acknowledged, "Momentary values.", null, null,
                                                                    new int[] { Xml.ContentFormatCode, Json.ContentFormatCode, PlainText.ContentFormatCode });

                this.momentaryResource?.TriggerAll(new TimeSpan(0, 0, 5));
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
Ejemplo n.º 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCompression();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                       options =>
            {
                options.LoginPath        = new PathString("/UI/Login");
                options.AccessDeniedPath = new PathString("/UI/Login");
                options.LogoutPath       = new PathString("/UI/Logout");
                options.Cookie.Name      = "Jackett";
                options.Cookie.SameSite  = SameSiteMode.None;
            });



#if NET461
            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();         //Web app uses Pascal Case JSON
            });
#else
            services.AddControllers(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();         //Web app uses Pascal Case JSON
            });
#endif

            RuntimeSettings runtimeSettings = new RuntimeSettings();
            Configuration.GetSection("RuntimeSettings").Bind(runtimeSettings);

            DirectoryInfo dataProtectionFolder = new DirectoryInfo(Path.Combine(runtimeSettings.DataFolder, "DataProtection"));

            services.AddDataProtection()
            .PersistKeysToFileSystem(dataProtectionFolder)
            .SetApplicationName("Jackett");

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var builder = new ContainerBuilder();

            Helper.SetupLogging(builder);

            builder.Populate(services);
            builder.RegisterModule(new JackettModule(runtimeSettings));
            builder.RegisterType <SecuityService>().As <ISecuityService>().SingleInstance();
            builder.RegisterType <ServerService>().As <IServerService>().SingleInstance();
            builder.RegisterType <ProtectionService>().As <IProtectionService>().SingleInstance();
            builder.RegisterType <ServiceConfigService>().As <IServiceConfigService>().SingleInstance();
            builder.RegisterType <FilePermissionService>().As <IFilePermissionService>().SingleInstance();

            IContainer container = builder.Build();
            Helper.ApplicationContainer = container;

            Helper.Logger.Debug("Autofac container built");

            Helper.Initialize();

            return(new AutofacServiceProvider(container));
        }
Ejemplo n.º 28
0
        private async Task RegisterDevice(string RegistryJid)
        {
            if (this.registryClient == null || this.registryClient.ThingRegistryAddress != RegistryJid)
            {
                if (this.registryClient != null)
                {
                    this.registryClient.Dispose();
                    this.registryClient = null;
                }

                this.registryClient = new ThingRegistryClient(this.xmppClient, RegistryJid);
            }

            string             s;
            List <MetaDataTag> MetaInfo = new List <MetaDataTag>()
            {
                new MetaDataStringTag("CLASS", "Actuator"),
                new MetaDataStringTag("TYPE", "MIoT Actuator"),
                new MetaDataStringTag("MAN", "waher.se"),
                new MetaDataStringTag("MODEL", "MIoT ActuatorXmpp"),
                new MetaDataStringTag("PURL", "https://github.com/PeterWaher/MIoT"),
                new MetaDataStringTag("SN", this.deviceId),
                new MetaDataNumericTag("V", 1.0)
            };

            if (await RuntimeSettings.GetAsync("ThingRegistry.Location", false))
            {
                s = await RuntimeSettings.GetAsync("ThingRegistry.Country", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("COUNTRY", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Region", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("REGION", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.City", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("CITY", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Area", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("AREA", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Street", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("STREET", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.StreetNr", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("STREETNR", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Building", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("BLD", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Apartment", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("APT", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Room", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("ROOM", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Name", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    MetaInfo.Add(new MetaDataStringTag("NAME", s));
                }

                this.UpdateRegistration(MetaInfo.ToArray());
            }
            else
            {
                try
                {
                    await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                    {
                        try
                        {
                            RegistrationDialog Dialog = new RegistrationDialog();

                            switch (await Dialog.ShowAsync())
                            {
                            case ContentDialogResult.Primary:
                                await RuntimeSettings.SetAsync("ThingRegistry.Country", s = Dialog.Reg_Country);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("COUNTRY", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Region", s = Dialog.Reg_Region);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("REGION", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.City", s = Dialog.Reg_City);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("CITY", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Area", s = Dialog.Reg_Area);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("AREA", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Street", s = Dialog.Reg_Street);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("STREET", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.StreetNr", s = Dialog.Reg_StreetNr);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("STREETNR", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Building", s = Dialog.Reg_Building);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("BLD", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Apartment", s = Dialog.Reg_Apartment);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("APT", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Room", s = Dialog.Reg_Room);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("ROOM", s));
                                }

                                await RuntimeSettings.SetAsync("ThingRegistry.Name", s = Dialog.Name);
                                if (!string.IsNullOrEmpty(s))
                                {
                                    MetaInfo.Add(new MetaDataStringTag("NAME", s));
                                }

                                this.RegisterDevice(MetaInfo.ToArray());
                                break;

                            case ContentDialogResult.Secondary:
                                await this.RegisterDevice();
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    });
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
            }
        }
Ejemplo n.º 29
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(ICoapContentFormat).GetTypeInfo().Assembly,
                    typeof(IDtlsCredentials).GetTypeInfo().Assembly,
                    typeof(Lwm2mClient).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low);

                            this.digitalOutput0?.Set(this.output.Value);
                            this.actuation0?.Set(this.output.Value);
                            await MainPage.Instance.OutputSet(this.output.Value);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output.Value));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                foreach (DeviceInformation DeviceInfo in Devices)
                {
                    if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith("Arduino"))
                    {
                        Log.Informational("Connecting to " + DeviceInfo.Name);

                        this.arduinoUsb = new UsbSerial(DeviceInfo);
                        this.arduinoUsb.ConnectionEstablished += () =>
                                                                 Log.Informational("USB connection established.");

                        this.arduino              = new RemoteDevice(this.arduinoUsb);
                        this.arduino.DeviceReady += async() =>
                        {
                            try
                            {
                                Log.Informational("Device ready.");

                                this.arduino.pinMode(13, PinMode.OUTPUT);                                    // Onboard LED.
                                this.arduino.digitalWrite(13, PinState.HIGH);

                                this.arduino.pinMode(8, PinMode.INPUT);                                      // PIR sensor (motion detection).

                                this.arduino.pinMode(9, PinMode.OUTPUT);                                     // Relay.

                                this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                                this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                                this.digitalOutput0?.Set(this.output.Value);
                                this.actuation0?.Set(this.output.Value);
                                await MainPage.Instance.OutputSet(this.output.Value);

                                Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                                  new KeyValuePair <string, object>("Output", this.output.Value));

                                this.arduino.pinMode("A0", PinMode.ANALOG);                                 // Light sensor.
                            }
                            catch (Exception ex)
                            {
                                Log.Critical(ex);
                            }
                        };

                        this.arduinoUsb.ConnectionFailed += message =>
                        {
                            Log.Error("USB connection failed: " + message);
                        };

                        this.arduinoUsb.ConnectionLost += message =>
                        {
                            Log.Error("USB connection lost: " + message);
                        };

                        this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                        break;
                    }
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                /************************************************************************************
                * To create an unencrypted CoAP Endpoint on the default CoAP port:
                *
                *    this.coapEndpoint = new CoapEndpoint();
                *
                * To create an unencrypted CoAP Endpoint on the default CoAP port,
                * with a sniffer that outputs communication to the window:
                *
                *    this.coapEndpoint = new CoapEndpoint(new LogSniffer());
                *
                * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using
                * the users defined in the IUserSource users:
                *
                *    this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users);
                *
                * To create a CoAP endpoint, that listens to both the default CoAP port, for
                * unencrypted communication, and the default CoAPS port, for encrypted,
                * authenticated and authorized communication, using
                * the users defined in the IUserSource users. Only users having the given
                * privilege (if not empty) will be authorized to access resources on the endpoint:
                *
                *    this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                *       new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false);
                *
                ************************************************************************************/

                this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort },
                                                     new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false);

                this.outputResource = this.coapEndpoint.Register("/Output", (req, resp) =>
                {
                    string s;

                    if (this.output.HasValue)
                    {
                        s = this.output.Value ? "true" : "false";
                    }
                    else
                    {
                        s = "-";
                    }

                    resp.Respond(CoapCode.Content, s, 64);
                }, async(req, resp) =>
                {
                    try
                    {
                        string s = req.Decode() as string;
                        if (s == null && req.Payload != null)
                        {
                            s = Encoding.UTF8.GetString(req.Payload);
                        }

                        if (s == null || !CommonTypes.TryParse(s, out bool Output))
                        {
                            resp.RST(CoapCode.BadRequest);
                        }
                        else
                        {
                            resp.Respond(CoapCode.Changed);
                            await this.SetOutput(Output, req.From.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                }, Notifications.Acknowledged, "Digital Output.", null, null,
                                                                 new int[] { PlainText.ContentFormatCode });

                this.outputResource?.TriggerAll(new TimeSpan(0, 1, 0));

                this.lwm2mClient = new Lwm2mClient("MIoT:Actuator:" + this.deviceId, this.coapEndpoint,
                                                   new Lwm2mSecurityObject(),
                                                   new Lwm2mServerObject(),
                                                   new Lwm2mAccessControlObject(),
                                                   new Lwm2mDeviceObject("Waher Data AB", "ActuatorLwm2m", this.deviceId, "1.0", "Actuator", "1.0", "1.0"),
                                                   new DigitalOutput(this.digitalOutput0 = new DigitalOutputInstance(0, this.output.HasValue && this.output.Value, "Relay")),
                                                   new Actuation(this.actuation0         = new ActuationInstance(0, this.output.HasValue && this.output.Value, "Relay")));

                this.digitalOutput0.OnRemoteUpdate += async(Sender, e) =>
                {
                    try
                    {
                        await this.SetOutput(((DigitalOutputInstance)Sender).Value, e.Request.From.ToString());
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                this.actuation0.OnRemoteUpdate += async(Sender, e) =>
                {
                    try
                    {
                        await this.SetOutput(((ActuationInstance)Sender).Value, e.Request.From.ToString());
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                await this.lwm2mClient.LoadBootstrapInfo();

                this.lwm2mClient.OnStateChanged += (sender, e) =>
                {
                    Log.Informational("LWM2M state changed to " + this.lwm2mClient.State.ToString() + ".");
                };

                this.lwm2mClient.OnBootstrapCompleted += (sender, e) =>
                {
                    Log.Informational("Bootstrap procedure completed.");
                };

                this.lwm2mClient.OnBootstrapFailed += (sender, e) =>
                {
                    Log.Error("Bootstrap procedure failed.");

                    this.coapEndpoint.ScheduleEvent(async(P) =>
                    {
                        try
                        {
                            await this.RequestBootstrap();
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    }, DateTime.Now.AddMinutes(15), null);
                };

                this.lwm2mClient.OnRegistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server registration completed.");
                };

                this.lwm2mClient.OnRegistrationFailed += (sender, e) =>
                {
                    Log.Error("Server registration failed.");
                };

                this.lwm2mClient.OnDeregistrationSuccessful += (sender, e) =>
                {
                    Log.Informational("Server deregistration completed.");
                };

                this.lwm2mClient.OnDeregistrationFailed += (sender, e) =>
                {
                    Log.Error("Server deregistration failed.");
                };

                this.lwm2mClient.OnRebootRequest += async(sender, e) =>
                {
                    Log.Warning("Reboot is requested.");

                    try
                    {
                        await this.RequestBootstrap();
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                };

                await this.RequestBootstrap();
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
    public override void OnInspectorGUI()
    {
        RuntimeSettings settings = RuntimeSettings.Instance;

        GUIStyle s = new GUIStyle(EditorStyles.boldLabel);

        s.normal.textColor = new Color(0.47f, 0.87f, 0.47f, 75);

        AscensionEntity entity = (AscensionEntity)target;

        //GUILayout.BeginHorizontal();
        //GUI.DrawTexture(GUILayoutUtility.GetRect(128, 128, 64, 64, GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false)), Resources.Load("AscensionLogo") as Texture2D);
        //GUILayout.EndHorizontal();

        GUILayout.Label("Prefab & State", s);

        DrawPrefabInfo(entity);
        EditState(entity);

        GUILayout.Label("Settings", s);

        entity.updateRate = EditorGUILayout.IntField("Replication Rate", entity.updateRate);
        HelpBox("Controls how often this entity should be considered for replication. 1 = Every packet, 2 = Every other packet, etc.");

        entity.persistThroughSceneLoads = EditorGUILayout.Toggle("Persistent", entity.persistThroughSceneLoads);
        HelpBox("If enabled Ascension will not destroy this object when a new scene is loaded through AscensionNetwork.LoadScene().");

        entity.alwaysProxy = EditorGUILayout.Toggle("Always Replicate", entity.alwaysProxy);
        HelpBox("If enabled Ascension will always replicate this entity and its state, even when operations that normally would block replication is taking place (example: loading a scene).");

        entity.allowFirstReplicationWhenFrozen = EditorGUILayout.Toggle("Proxy When Frozen", entity.allowFirstReplicationWhenFrozen);
        HelpBox("If enabled Ascension will allow this entity to perform its first replication even if its frozen.");

        entity.detachOnDisable = EditorGUILayout.Toggle("Detach On Disable", entity.detachOnDisable);
        HelpBox("If enabled this entity will be detached from the network when its disabled.");

        entity.sceneObjectAutoAttach = EditorGUILayout.Toggle("Auto Attach On Load", entity.sceneObjectAutoAttach);
        HelpBox("If enabled this to automatically attach scene entities on map load.");

        entity.autoFreezeProxyFrames = EditorGUILayout.IntField("Auto Freeze Frames", entity.autoFreezeProxyFrames);
        HelpBox("If larger than 0, this entity will be automatically frozen by Ascension for non-owners if it has not received a network update for the amount of frames specified.");

        entity.autoRemoveChildEntities = EditorGUILayout.Toggle("Remove Parent On Detach", entity.autoRemoveChildEntities);
        HelpBox("If enabled this tells Ascension to search the entire transform hierarchy of the entity being detached for nested entities and set their transform.parent to null.");

        entity.clientPredicted = EditorGUILayout.Toggle("Controller Predicted Movement", entity.clientPredicted);
        HelpBox("If enabled this tells Ascension that this entity is using commands for moving and that they are applied on both the owner and controller.");

        EditorGUILayout.LabelField("Scene ID", entity.sceneGuid);
        HelpBox("The scene id of this entity");

        if (settings.clientCanInstantiateAll == false)
        {
            entity.allowInstantiateOnClient = EditorGUILayout.Toggle("Allow Client Instantiate", entity.allowInstantiateOnClient);
            HelpBox("If enabled this prefab can be instantiated by clients, this option can be globally enabled/disabled by changing the 'Instantiate Mode' setting in the 'Window/Ascension/Settings' window");
        }

        if (AscensionNetwork.IsRunning)
        {
            RuntimeInfoGUI(entity);
        }
    }
Ejemplo n.º 31
0
 // Adds all platforms to the settings asset, so they get stored in the same file as the main
 // Settings object.
 public void AddPlatformsToAsset()
 {
     RuntimeSettings.ForEachPlatform(AddPlatformToAsset);
 }
Ejemplo n.º 32
0
        public static LoggingConfiguration GetLoggingConfiguration(RuntimeSettings settings, bool fileOnly = false)
        {
            var logFileName = settings.CustomLogFileName ?? "log.txt";
            var logLevel    = settings.TracingEnabled ? NLog.LogLevel.Debug : NLog.LogLevel.Info;

            // Add custom date time format renderer as the default is too long
            ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("simpledatetime", typeof(SimpleDateTimeRenderer));

            var logConfig = new LoggingConfiguration();

            var logFile = new FileTarget();

            logFile.Layout           = "${longdate} ${level} ${message} ${exception:format=ToString}";
            logFile.FileName         = Path.Combine(settings.DataFolder, logFileName);
            logFile.ArchiveFileName  = Path.Combine(settings.DataFolder, logFileName + ".{#####}.txt");
            logFile.ArchiveAboveSize = 500000;
            logFile.MaxArchiveFiles  = 5;
            logFile.KeepFileOpen     = false;
            logFile.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
            logConfig.AddTarget("file", logFile);

            var microsoftRule = new LoggingRule();

            microsoftRule.LoggerNamePattern = "Microsoft.*";
            microsoftRule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal);
            microsoftRule.Final = true;
            microsoftRule.Targets.Add(logFile);

            var microsoftDebugRule = new LoggingRule();

            microsoftDebugRule.LoggerNamePattern = "Microsoft.*";
            microsoftDebugRule.SetLoggingLevels(LogLevel.Debug, LogLevel.Info);
            microsoftDebugRule.Final = true;
            if (settings.TracingEnabled)
            {
                microsoftDebugRule.Targets.Add(logFile);
            }
            logConfig.LoggingRules.Add(microsoftDebugRule);

            var logFileRule = new LoggingRule("*", logLevel, logFile);

            logConfig.LoggingRules.Add(logFileRule);

            if (!fileOnly)
            {
                var logConsole = new ColoredConsoleTarget();
                logConsole.Layout = "${simpledatetime} ${level} ${message} ${exception:format=ToString}";
                logConfig.AddTarget("console", logConsole);

                var logConsoleRule = new LoggingRule("*", logLevel, logConsole);
                logConfig.LoggingRules.Add(logConsoleRule);

                var logService = new LogCacheService();
                logConfig.AddTarget("service", logService);

                var serviceRule = new LoggingRule("*", logLevel, logService);
                logConfig.LoggingRules.Add(serviceRule);

                microsoftRule.Targets.Add(logConsole);
                microsoftRule.Targets.Add(logService);

                if (settings.TracingEnabled)
                {
                    microsoftDebugRule.Targets.Add(logConsole);
                    microsoftDebugRule.Targets.Add(logService);
                }
            }

            logConfig.LoggingRules.Add(microsoftRule);

            return(logConfig);
        }
Ejemplo n.º 33
0
        private async Task <MetaDataTag[]> GetMetaData(MetaDataTag[] MetaData)
        {
            List <MetaDataTag> Result = new List <MetaDataTag>(MetaData);
            string             s;

            if (await RuntimeSettings.GetAsync("ThingRegistry.Location", false))
            {
                s = await RuntimeSettings.GetAsync("ThingRegistry.Country", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("COUNTRY", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Region", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("REGION", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.City", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("CITY", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Area", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("AREA", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Street", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("STREET", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.StreetNr", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("STREETNR", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Building", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("BLD", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Apartment", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("APT", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Room", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("ROOM", s));
                }

                s = await RuntimeSettings.GetAsync("ThingRegistry.Name", string.Empty);

                if (!string.IsNullOrEmpty(s))
                {
                    Result.Add(new MetaDataStringTag("NAME", s));
                }
            }
            else
            {
                TaskCompletionSource <bool> UserInput = new TaskCompletionSource <bool>();

                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    try
                    {
                        RegistrationDialog Dialog = new RegistrationDialog();

                        switch (await Dialog.ShowAsync())
                        {
                        case ContentDialogResult.Primary:
                            await RuntimeSettings.SetAsync("ThingRegistry.Country", s = Dialog.Reg_Country);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("COUNTRY", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Region", s = Dialog.Reg_Region);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("REGION", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.City", s = Dialog.Reg_City);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("CITY", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Area", s = Dialog.Reg_Area);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("AREA", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Street", s = Dialog.Reg_Street);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("STREET", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.StreetNr", s = Dialog.Reg_StreetNr);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("STREETNR", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Building", s = Dialog.Reg_Building);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("BLD", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Apartment", s = Dialog.Reg_Apartment);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("APT", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Room", s = Dialog.Reg_Room);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("ROOM", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Name", s = Dialog.Name);
                            if (!string.IsNullOrEmpty(s))
                            {
                                Result.Add(new MetaDataStringTag("NAME", s));
                            }

                            await RuntimeSettings.SetAsync("ThingRegistry.Location", true);

                            UserInput.SetResult(true);
                            break;

                        case ContentDialogResult.Secondary:
                            UserInput.SetResult(false);
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                });

                await UserInput.Task;
            }

            return(Result.ToArray());
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Set Timestamp of last backup.
 /// </summary>
 public static async Task SetLastBackupAsync(DateTime Value)
 {
     lastBackup = Value;
     await RuntimeSettings.SetAsync("LastBackup", Value);
 }
Ejemplo n.º 35
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(ObjectSerializer).GetTypeInfo().Assembly,                        // Waher.Persistence.Serialization was broken out of Waher.Persistence.FilesLW after the publishing of the MIoT book.
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                       Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);
                Database.Register(db);
                await db.RepairIfInproperShutdown(null);

                await db.Start();

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(LastOn ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device");
                if (DeviceInfo is null)
                {
                    Log.Error("Unable to find Arduino device.");
                }
                else
                {
                    Log.Informational("Connecting to " + DeviceInfo.Name);

                    this.arduinoUsb = new UsbSerial(DeviceInfo);
                    this.arduinoUsb.ConnectionEstablished += () =>
                                                             Log.Informational("USB connection established.");

                    this.arduino              = new RemoteDevice(this.arduinoUsb);
                    this.arduino.DeviceReady += async() =>
                    {
                        try
                        {
                            Log.Informational("Device ready.");

                            this.arduino.pinMode(13, PinMode.OUTPUT);                                // Onboard LED.
                            this.arduino.digitalWrite(13, PinState.HIGH);

                            this.arduino.pinMode(8, PinMode.INPUT);                                  // PIR sensor (motion detection).

                            this.arduino.pinMode(9, PinMode.OUTPUT);                                 // Relay.

                            bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.arduino.digitalWrite(9, LastOn ? PinState.HIGH : PinState.LOW);

                            await MainPage.Instance.OutputSet(LastOn);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", LastOn));

                            this.arduino.pinMode("A0", PinMode.ANALOG);                             // Light sensor.
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    };

                    this.arduinoUsb.ConnectionFailed += message =>
                    {
                        Log.Error("USB connection failed: " + message);
                    };

                    this.arduinoUsb.ConnectionLost += message =>
                    {
                        Log.Error("USB connection lost: " + message);
                    };

                    this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                }
#endif
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }