Ejemplo n.º 1
0
        public static IServiceCollection AddHue(this IServiceCollection services, Action <HueConfig> configure)
        {
            var options = new HueConfig();

            configure?.Invoke(options);

            services.TryAddSingleton <IHueClientManager>(s =>
            {
                var manager = new HueClientManager();
                if (options.Clients != null)
                {
                    foreach (var client in options.Clients)
                    {
                        manager.SetClient(client.Key, new SyncedHueClient(client.Value));
                    }
                }
                return(manager);
            });

            services.TryAddScoped(typeof(IHueSwitchRepository <,>), typeof(HueSwitchRepository <,>));

            services.AdditionalSwitchConfiguration(o =>
            {
                o.AddSwitch(typeof(IHueSwitchRepository <,>));
            });

            return(services);
        }
Ejemplo n.º 2
0
 public static void saveConfig(HueConfig configToSave)
 {
     if (configToSave != null)
     {
         config = configToSave;
         System.IO.File.WriteAllText(configPath, JsonConvert.SerializeObject(configToSave));
     }
 }
Ejemplo n.º 3
0
 private void CmdSave_Click(object sender, RoutedEventArgs e)
 {
     if (lstLights.SelectedItems.Count == 1)
     {
         HueConfig config = ConfigService.loadConfig();
         config.lightId = ((LightEntity)lstLights.SelectedItems[0]).id;
         config.offset  = Int32.Parse(txtOffset.Text);
         ConfigService.saveConfig(config);
     }
 }
Ejemplo n.º 4
0
        private async void Application_Startup(object sender, StartupEventArgs e)
        {
            MainWindow               = new MainWindow();
            MainWindow.Closing      += MainWindow_Closing;
            _notifyIcon              = new System.Windows.Forms.NotifyIcon();
            _notifyIcon.DoubleClick += (s, args) => ShowMainWindow();
            _notifyIcon.Icon         = DeskHue.Properties.Resources.LightBulb;
            _notifyIcon.Visible      = true;

            CreateContextMenu();
            MainWindow.WindowState = WindowState.Minimized;
            MainWindow.Show();

            HueConfig config = ConfigService.loadConfig();

            if (!config.bound)
            {
                settingsParingWindow = new SettingsParingWindow(ShowMainWindow);
                settingsParingWindow.Show();
            }
            else if (config.autobound)
            {
                var ips = await HueDiscoveryService.discover();

                HueIpAddress matchedIp = null;
                try
                {
                    matchedIp = ips.First(i => i.id == config.deviceId);
                }
                catch (InvalidOperationException ex)
                {
                    MessageBox.Show("Paired bridge not found. Re-pairing");
                    ConfigService.saveConfig(new HueConfig());
                    settingsParingWindow = new SettingsParingWindow(ShowMainWindow);
                    settingsParingWindow.Show();
                }

                if (matchedIp != null)
                {
                    config.ip = matchedIp.internalipaddress;
                    ConfigService.saveConfig(config);
                }
            }
        }
Ejemplo n.º 5
0
 public static HueConfig loadConfig()
 {
     if (config == null)
     {
         try
         {
             string configString = System.IO.File.ReadAllText(configPath);
             config = JsonConvert.DeserializeObject <HueConfig>(configString);
             return(config);
         }
         catch (FileNotFoundException ex)
         {
             config = new HueConfig();
             return(config);
         }
     }
     else
     {
         return(config);
     }
 }
Ejemplo n.º 6
0
        private void AdjustBrightness(Int32 offset, string lightId = null)
        {
            HueConfig config = ConfigService.loadConfig();

            if (lightId == null)
            {
                lightId = config.lightId;
            }
            if (config.ip != null && lightId != null && config.username != null)
            {
                // first get current brightness
                var client     = new RestClient("http://" + config.ip);
                var getRequest = new RestRequest("/api/" + config.username + "/lights/" + lightId);
                var r          = client.Execute <LightEntity>(getRequest, Method.GET);

                //now issue update
                var newBrightnes = r.Data.state.bri + offset;
                var updateBody   = new HueStateUpdate();
                updateBody.bri = newBrightnes;
                var updateRequest = new RestRequest("/api/" + config.username + "/lights/" + lightId + "/state");
                updateRequest.AddJsonBody(updateBody);
                client.Execute(updateRequest, Method.PUT);
            }
        }
Ejemplo n.º 7
0
 public HueDeviceService(HueConfig config)
 {
     this.config = config;
 }
        private async void BtnPair_Click(object sender, RoutedEventArgs e)
        {
            HueIpAddress ip = null;

            bool autobound = false;

            if (optDiscoverAuto.IsChecked.HasValue && optDiscoverAuto.IsChecked.Value)
            {
                var ips = await HueDiscoveryService.discover();

                if (ips.Count == 1)
                {
                    ip        = ips[0];
                    autobound = true;
                }
                else
                {
                    MessageBox.Show("More than one hue found. Manual discovery required.");
                    return;
                }
            }
            else if (optDiscoverBind.IsChecked.HasValue && optDiscoverBind.IsChecked.Value)
            {
                if (lstHueIps.SelectedItems.Count == 1)
                {
                    ip        = (HueIpAddress)lstHueIps.SelectedItems[0];
                    autobound = false;
                }
                else
                {
                    MessageBox.Show("You must select an IP or discover automatically");
                    return;
                }
            }

            var client = new RestClient("http://" + ip);

            var request        = new RestRequest("/api", Method.POST);
            var newUserRequest = new NewUserRequest();

            newUserRequest.devicetype = "DeskHue - Windows";
            request.AddJsonBody(newUserRequest);
            var response = await client.ExecuteAsync <List <NewUserResponse> >(request);

            List <NewUserResponse> items = response.Data;

            if (items.Count != 1)
            {
                MessageBox.Show("Incorrect or malformed response from hue bridge: " + response.Content);
                return;
            }

            NewUserResponse newUserResponse = items[0];

            if (newUserResponse.error != null)
            {
                MessageBox.Show(newUserResponse.error.description);
                return;
            }
            else if (newUserResponse.success != null)
            {
                HueConfig hueConfig = new HueConfig();
                hueConfig.ip        = ip.internalipaddress;
                hueConfig.deviceId  = ip.id;
                hueConfig.username  = newUserResponse.success.username;
                hueConfig.bound     = true;
                hueConfig.autobound = autobound;
                ConfigService.saveConfig(hueConfig);
                this.Close();
                showMainWindow();
            }
            else
            {
                MessageBox.Show("Incorrect or malformed response from hue bridge: " + response.Content);
            }
        }
Ejemplo n.º 9
0
        public static IServiceCollection AddLogic(this IServiceCollection services, IConfiguration configuration)
        {
            var smartThings = new SmartThingsConfig();

            configuration.Bind("smartthings", smartThings);
            services.AddHttpClient <SmartThingsClient>(client =>
            {
                client.BaseAddress = new Uri("https://api.smartthings.com/v1");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", smartThings.PAT);
            });

            var hueConfig = new HueConfig();

            configuration.Bind("hue", hueConfig);
            services.AddHttpClient <HueClient>(client =>
            {
                client.BaseAddress = new Uri(hueConfig.BaseUrl);
                client.Timeout     = Timeout.InfiniteTimeSpan;
                client.DefaultRequestHeaders.Add("hue-application-key", hueConfig.Key);
            })
            .ConfigurePrimaryHttpMessageHandler(() => new HueHandler());

            var backup = new BackUpFunctionConfig();

            configuration.Bind("backup", backup);
            services.AddHttpClient <AzBackupClient>(client =>
            {
                client.BaseAddress = new Uri(backup.BaseUrl);
                client.DefaultRequestHeaders.Add("x-functions-key", backup.Key);
            });

            return(services

                   .Configure <GlobalConfig>(configuration.GetSection("global"))

                   .AddDbContext <AppDbContext>((provider, o) => {
                var options = provider.GetService <IOptions <GlobalConfig> >();

                string dataPath = options.Value.DataPath
                                  .TrimEnd('/')
                                  .TrimEnd('\\');

                string personal = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

                if (!Directory.Exists(dataPath))
                {
                    Directory.CreateDirectory(dataPath);
                }

                string file = Path.Combine(dataPath, "smartstuffs.db");

                if (!File.Exists(file))
                {
                    File.Create(file);
                }

                o.UseSqlite($"Data Source={file}",
                            b => b.MigrationsAssembly("SmartHub.DbMigrator"));
                //o.UseMySql(configuration["sql"], ServerVersion.AutoDetect(configuration["sql"]));
                o.EnableSensitiveDataLogging();
                //o.LogTo(ShowMe, Logging.LogLevel.Information, DbContextLoggerOptions.SingleLine);
            })

                   .AddTransient <ActionService>()
                   .AddTransient <EventLogService>()
                   .AddScoped <AutomationService>()
                   .AddScoped <SmartLogic>()
                   .AddTransient <EventService>()
                   .AddTransient <HueService>()

                   //AUTOMATIONS
                   .AddScoped <TurnOnBedroomAutomation>());
        }