Example #1
0
 public static TradfriAuth GeneratePsk(string gatewayIp, string appName, string secret)
 {
     try
     {
         var controller = new TradfriController(appName, gatewayIp);
         return(controller.GenerateAppSecret(secret, appName));
     }
     catch (Exception e)
     {
         throw;
     }
 }
Example #2
0
        // Real usage example
        public virtual void BaseSetupRecommendation()
        {
            // Unique name for the application which communicates with Tradfri gateway
            string            applicationName = "UnitTestApp";
            TradfriController controller      = new TradfriController("GatewayName", "IP");

            // This line should only be called once per applicationName
            // Gateway generates one appSecret key per applicationName
            TradfriAuth appSecret = controller.GenerateAppSecret("PSK", applicationName);

            // You should now save programatically appSecret.PSK value and use it
            // when connection to your gateway every other time
            controller.ConnectAppKey(appSecret.PSK, applicationName);
        }
        static async Task <MethodResponse> GenerateAppSecretMethodCallBack(MethodRequest methodRequest, object userContext)
        {
            Console.WriteLine("Executing GenerateAppSecretMethodCallBack");

            var secretResponse = new GenerateAppSecretResponse();

            try
            {
                var messageBytes = methodRequest.Data;
                var messageJson  = Encoding.UTF8.GetString(messageBytes);
                var command      = (GenerateAppSecretRequest)JsonConvert.DeserializeObject(messageJson, typeof(GenerateAppSecretRequest));

                // Never expose command.gatewaySecret !

                ConstructController();

                var applicationName = UseExtendedApplicationName
                                        ? _deviceId + _moduleId
                                        : _moduleId;

                var tradfriAuth = _controller.GenerateAppSecret(command.gatewaySecret, applicationName);

                Console.WriteLine($"Secret for application '{applicationName}' generated of '{tradfriAuth?.PSK?.Length}' characters long. See method response.");

                secretResponse.appSecret = tradfriAuth.PSK;
            }
            catch (Exception ex)
            {
                secretResponse.errorMessage = ex.Message;
            }

            var json     = JsonConvert.SerializeObject(secretResponse);
            var response = new MethodResponse(Encoding.UTF8.GetBytes(json), 200);

            await Task.Delay(TimeSpan.FromSeconds(0));

            return(response);
        }
Example #4
0
        private async void Main_Load(object sender, EventArgs e)
        {
            //preload colors combobox
            cmbColors.DisplayMember = "ColorName";
            //cmbColors.SelectedValueChanged += (s, ev) => cmbColors.SelectedText = s.ToString();
            cmbColors.ValueMember = "ColorId";
            //cmbColors.SelectedValueChanged += (s, ev) => cmbColors.SelectedText = s.ToString();
            foreach (FieldInfo p in typeof(TradfriColors).GetFields())
            {
                object v = p.GetValue(null); // static classes cannot be instanced, so use null...
                cmbColors.Items.Add(new { ColorName = p.Name, ColorId = v });
            }

            // prepare/load settings
            userData = loadUserData();

            // connect
            tradfriController = new TradfriController(Properties.Settings.Default.gatewayName, Properties.Settings.Default.gatewayIp);

            if (string.IsNullOrWhiteSpace(Properties.Settings.Default.appSecret))
            {
                using (EnterGatewayPSK form = new EnterGatewayPSK(Properties.Settings.Default.appName))
                {
                    DialogResult result = form.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        // generating appSecret on gateway - appSecret is connected with the appName so you must use a combination
                        // Gateway generates one appSecret key per applicationName
                        TradfriAuth appSecret = tradfriController.GenerateAppSecret(form.AppSecret, Properties.Settings.Default.appName);
                        // saving programatically appSecret.PSK value to settings
                        Properties.Settings.Default.appSecret = appSecret.PSK;
                        Properties.Settings.Default.Save();
                    }
                    else
                    {
                        MessageBox.Show("You haven't entered your Gateway PSK so applicationSecret can't be generated on gateway." + Environment.NewLine +
                                        "You can also enter it manually into app.config if you have one for your app already.",
                                        "Error acquiring appSecret",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        this.Close();
                    }
                }
            }

            string secret = Properties.Settings.Default.appSecret;

            // connection to gateway
            tradfriController.ConnectAppKey(Properties.Settings.Default.appSecret, Properties.Settings.Default.appName);

            List <TradfriDevice> devices = new List <TradfriDevice>(await tradfriController.GatewayController.GetDeviceObjects()).OrderBy(x => x.DeviceType.ToString()).ToList();
            List <TradfriDevice> lights  = devices.Where(i => i.DeviceType.Equals(DeviceType.Light)).ToList();

            // set datasource for dgv
            dgvDevices.DataSource          = devices;
            dgvDevices.AutoGenerateColumns = true;

            // temporary disable autosave on rowSelectionChange
            loadingSelectedRows = true;
            //reselect rows from settings
            if (userData.SelectedDevices.Count > 0 && devices.Count > 0)
            {
                foreach (DataGridViewRow row in dgvDevices.Rows)
                {
                    if (userData.SelectedDevices.Any(x => x == (long)row.Cells["ID"].Value))
                    {
                        row.Selected = true;
                    }
                }
            }
            // re-enable autosave on rowSelectionChange
            loadingSelectedRows = false;

            if (lights.Count > 0)
            {
                // acquire first and last lights from grid
                TradfriDevice firstLight = lights.FirstOrDefault();
                TradfriDevice lastLight  = lights.LastOrDefault();
                // function handler for observe events
                void ObserveLightEvent(TradfriDevice x)
                {
                    TradfriDevice eventDevice = devices.Where(d => d.ID.Equals(x.ID)).SingleOrDefault();

                    eventDevice = x;
                    if (dgvDevices.SelectedRows.Count > 0)
                    {
                        foreach (object item in dgvDevices.SelectedRows)
                        {
                            if (((TradfriDevice)((DataGridViewRow)item).DataBoundItem).ID.Equals(eventDevice.ID))
                            {
                                this.Invoke((MethodInvoker) delegate
                                {
                                    Debug.WriteLine($"{DateTime.Now} - triggered: {x.DeviceType}, {x.Name}, {x.LightControl[0].State}, {x.LightControl[0].Dimmer}");
                                    lbxLog.Items.Add($"{DateTime.Now} - triggered: {x.DeviceType}, {x.Name}, {x.LightControl[0].State}, {x.LightControl[0].Dimmer}");
                                    lbxLog.SelectedIndex = lbxLog.Items.Count - 1;
                                    trbBrightness.Value  = Convert.ToInt16(eventDevice.LightControl[0].Dimmer * (double)10 / 254);
                                });
                            }
                        }
                    }
                };

                ObserveLightDelegate lightDelegate = new ObserveLightDelegate(ObserveLightEvent);
                // observe first light from grid
                tradfriController.DeviceController.ObserveDevice(firstLight, x => lightDelegate(x));
                // observe last light from grid if the bulbs are different
                if (firstLight.ID != lastLight.ID)
                {
                    tradfriController.DeviceController.ObserveDevice(lastLight, x => lightDelegate(x));
                }
            }
        }
Example #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var section = Configuration.GetSection("TradfriSettings");

            services.Configure <TradfriSettings>(section);
            var settings = section.Get <TradfriSettings>();

            settings.GatewayName     = settings.GatewayName ?? Environment.GetEnvironmentVariable("GATEWAY_NAME");
            settings.GatewayIp       = settings.GatewayIp ?? Environment.GetEnvironmentVariable("GATEWAY_IP");
            settings.GatewayPSK      = settings.GatewayPSK ?? Environment.GetEnvironmentVariable("GATEWAY_PSK");
            settings.ApplicationName = settings.ApplicationName ?? Environment.GetEnvironmentVariable("APPLICATION_NAME");
            settings.ApplicationPSK  = settings.ApplicationPSK ?? Environment.GetEnvironmentVariable("APPLICATION_PSK");

            if (string.IsNullOrEmpty(settings.GatewayName))
            {
                Console.WriteLine("You have to set the GatewayName in the appsettings.json file or as 'GATEWAY_NAME' environment variable.");
                Environment.Exit(1);
            }
            if (string.IsNullOrEmpty(settings.GatewayIp))
            {
                Console.WriteLine("You have to set the GatewayIp in the appsettings.json file or as 'GATEWAY_IP' environment variable.");
                Environment.Exit(1);
            }
            if (string.IsNullOrEmpty(settings.ApplicationName))
            {
                Console.WriteLine("You have to set the ApplicationName in the appsettings.json file or as 'APPLICATION_NAME' environment variable.");
                Environment.Exit(1);
            }

            var controller = new TradfriController(settings.GatewayName, settings.GatewayIp);

            if (string.IsNullOrEmpty(settings.ApplicationPSK))
            {
                Console.WriteLine("The ApplicationPSK is not configured in the appsettings.json neither the 'APPLICATION_PSK' environment variable. Creating a new ApplicationPSK");

                if (string.IsNullOrEmpty(settings.GatewayPSK))
                {
                    Console.WriteLine("The GatewayPSK is empty, please add it to the appsettings.json file or as environment variable.");
                    Console.WriteLine("You can find the Gateway PSK on the backside of your Gateway.");
                    Environment.Exit(1);
                }

                var appSecret = controller.GenerateAppSecret(settings.GatewayPSK, settings.ApplicationName);
                if (appSecret != null)
                {
                    settings.ApplicationPSK = appSecret.PSK;
                    Console.WriteLine("A new ApplicationPSK was created, please copy this in a safe place and put the value in the appsetings.json file or in the 'APPLICATION_PSK' environment variable.");
                    Console.WriteLine("ApplicationPSK = " + settings.ApplicationPSK);
                    Console.WriteLine();
                }
                else
                {
                    throw new Exception("The Gateway return a null AppSecret, please change the application name and try again.");
                }
            }
            controller.ConnectAppKey(settings.ApplicationPSK, settings.ApplicationName);
            services.AddSingleton <TradfriController>(controller);

            var devices = controller.GatewayController.GetDeviceObjects().Result;

            services
            .AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                options.SerializerSettings.Formatting = Formatting.Indented;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddOpenApiDocument(options =>
            {
                options.Title   = "Tradfri Api";
                options.Version = "0.1.0";
            });
        }