コード例 #1
0
        public virtual void BaseSetup()
        {
            string applicationName = "UnitTestApp";

            tradfriController = new TradfriController("GatewayName", "IP");
            tradfriController.ConnectAppKey("PSK", applicationName);
        }
コード例 #2
0
        public Task Connect()
        {
            _tradfri = new TradfriController(_name, _gatewayIp);
            _tradfri.ConnectAppKey(_appKey, _name);

            return(Task.CompletedTask);
        }
コード例 #3
0
        /// <summary>
        /// Construct controller before first key generation.
        /// </summary>
        private static void ConstructController()
        {
            CloseController();

            if (!string.IsNullOrEmpty(GatewayName) &&
                !string.IsNullOrEmpty(IpAddress))
            {
                try
                {
                    Console.WriteLine($"Construct '{GatewayName}' at '{IpAddress}'");

                    _controller = new TradfriController(GatewayName, IpAddress);

                    Console.WriteLine($"ontroller constructed");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ConstructController exception {ex.Message}");
                }
            }
            else
            {
                Console.WriteLine($"Constructing controller skipped due to incomplete parameters");
            }
        }
コード例 #4
0
        private static void CloseController()
        {
            if (_controller == null)
            {
                Console.WriteLine($"Controller is already closed");

                return;
            }

            try
            {
                var name = _controller.GateWayName;

                Console.WriteLine($"Closing '{name}'");

                _collectedInformation = null;

                _controller = null;

                Console.WriteLine($"Closed '{name}'");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CloseController exception {ex.Message}");
            }
        }
コード例 #5
0
        /// <summary>
        /// Attach controller to collect information.
        /// Application key is already generated and registered.
        /// </summary>
        private static async Task AttachController()
        {
            _attachingInProgress = true;
            try
            {
                CloseController();

                if (!string.IsNullOrEmpty(AppSecret) &&
                    !string.IsNullOrEmpty(GatewayName) &&
                    !string.IsNullOrEmpty(_deviceId) &&
                    !string.IsNullOrEmpty(_moduleId) &&
                    !string.IsNullOrEmpty(IpAddress))
                {
                    Console.WriteLine($"Connecting to '{GatewayName}' at '{IpAddress}'");

                    _controller = new TradfriController(GatewayName, IpAddress);

                    Console.WriteLine($"Controller created");

                    var applicationName = UseExtendedApplicationName
                                            ? _deviceId + _moduleId
                                            : _moduleId;

                    _controller.ConnectAppKey(AppSecret, applicationName);

                    Console.WriteLine($"Connected application '{applicationName}'");

                    var collected = await CollectInformation();

                    if (collected)
                    {
                        Console.WriteLine($"Constructed '{GatewayName}'");
                    }
                    else
                    {
                        Console.WriteLine($"Connecting controller skipped due to failed collection");
                    }
                }
                else
                {
                    Console.WriteLine($"Connecting controller skipped due to incomplete parameters. Please execute 'generateAppSecret'.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Connecting '{GatewayName}/{_deviceId}/{_moduleId}' failed due to '{ex.Message}'");

                throw;
            }
            finally
            {
                _attachingInProgress = false;
            }
        }
コード例 #6
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;
     }
 }
コード例 #7
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);
        }
コード例 #8
0
 public virtual void BaseSetup()
 {
     tradfriController = new TradfriController("GatewayName", "IP", "PSK");
 }
コード例 #9
0
 public InfoController(TradfriController controller)
 {
     _controller = controller;
 }
コード例 #10
0
 public SmartTaskController(TradfriController controller) : base(controller)
 {
 }
コード例 #11
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));
                }
            }
        }
コード例 #12
0
 public DevicesController(TradfriController controller)
 {
     _controller = controller;
 }
コード例 #13
0
 public MoodsController(TradfriController controller)
 {
     _controller = controller;
 }
コード例 #14
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";
            });
        }
コード例 #15
0
 public SmartTasksController(TradfriController controller)
 {
     _controller = controller;
 }
コード例 #16
0
 //private readonly CoapClient cc;
 //private long id { get; }
 //private TradfriGroup group { get; set; }
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="_id">group id</param>
 /// <param name="_cc">existing coap client</param>
 /// <param name="loadAutomatically">Load group object automatically (default: true)</param>
 public GroupController(TradfriController controller) : base(controller)
 {
 }
コード例 #17
0
 public GroupsController(TradfriController controller)
 {
     _controller = controller;
 }
コード例 #18
0
 public DeviceController(TradfriController controller) : base(controller)
 {
 }
コード例 #19
0
 public GatewayController(TradfriController controller) : base(controller)
 {
     this.mainController = controller;
 }