protected Task DeinitializeLifxClient() { // *** // *** Dispose the current items. // *** foreach (LifxItem item in this.Items) { item.Dispose(); } // *** // *** Clear the list. // *** this.Items.Clear(); // *** // *** Release the client. // *** if (this.LifxClient != null) { this.LifxClient.StopDeviceDiscovery(); this.LifxClient.DeviceDiscovered -= this.LifxClient_DeviceDiscovered; this.LifxClient.DeviceLost -= this.LifxClient_DeviceLost; this.LifxClient.Dispose(); this.LifxClient = null; } return(Task.FromResult(0)); }
private static async Task DemoModifyCollections(LifxClient client) { Group group = (await client.ListGroups()).FirstOrDefault(); if (group == null) { Console.WriteLine("No groups"); } else { Console.WriteLine("Using group: {0}", group); Console.WriteLine("Toggling group"); await group.TogglePower(); Console.WriteLine("Turning group green"); await group.SetColor(LifxColor.Green); } Location location = (await client.ListLocations()).FirstOrDefault(); if (location == null) { Console.WriteLine("No locations"); } else { Console.WriteLine("Using location: {0}", location); Console.WriteLine("Turning off location"); await location.SetPower(false); Console.WriteLine("Turning location pink"); await location.SetColor(LifxColor.Pink); } }
protected async Task InitializeLifxClient() { this.EventAggregator.GetEvent <MessageEvent>().Publish(new MessageEventArgs(MessageEventType.Information, "Ready.")); try { // *** // *** Configure the LIFX client. // *** this.LifxClient = await LifxClient.CreateAsync(); this.LifxClient.DeviceDiscovered += this.LifxClient_DeviceDiscovered; this.LifxClient.DeviceLost += this.LifxClient_DeviceLost; this.LifxClient.StartDeviceDiscovery(); } catch (SocketException) { string message = this.ResourceLoader.GetString(MagicString.Resource.LifxApplicationError); this.EventAggregator.GetEvent <MessageEvent>().Publish(new MessageEventArgs(MessageEventType.Error, message)); } catch (Exception ex) { this.EventAggregator.GetEvent <MessageEvent>().Publish(new MessageEventArgs(MessageEventType.Error, ex.Message)); } }
public static async Task ScanDevices(LifxClient lc) { if (scanning) { return; } scanning = true; var db = GetDb(); // Get dream devices var ld = new LifxDiscovery(lc); var nanoTask = NanoDiscovery.Discover(); var hueTask = HueDiscovery.Discover(); var dreamTask = DreamDiscovery.Discover(); var wLedTask = WledDiscovery.Discover(); var bulbTask = ld.Discover(5); await Task.WhenAll(nanoTask, hueTask, dreamTask, bulbTask).ConfigureAwait(false); var leaves = await nanoTask.ConfigureAwait(false); var bridges = await hueTask.ConfigureAwait(false); var dreamDevices = await dreamTask.ConfigureAwait(false); var bulbs = await bulbTask.ConfigureAwait(false); var wleds = await wLedTask.ConfigureAwait(false); var bridgeCol = db.GetCollection <BridgeData>("Dev_Hue"); var nanoCol = db.GetCollection <NanoData>("Dev_Nanoleaf"); var devCol = db.GetCollection <BaseDevice>("Dev_DreamScreen"); var lifxCol = db.GetCollection <LifxData>("Dev_Lifx"); var wledCol = db.GetCollection <WLedData>("Dev_Wled"); foreach (var b in bridges) { bridgeCol.Upsert(b); } foreach (var n in leaves) { nanoCol.Upsert(n); } foreach (var dd in dreamDevices) { devCol.Upsert(dd); } foreach (var b in bulbs) { lifxCol.Upsert(b); } foreach (var w in wleds) { wledCol.Upsert(w); } bridgeCol.EnsureIndex(x => x.Id); nanoCol.EnsureIndex(x => x.Id); devCol.EnsureIndex(x => x.Id); lifxCol.EnsureIndex(x => x.Id); wledCol.EnsureIndex(x => x.Id); scanning = false; }
public LifxItem(LifxClient client, LightBulb lightBulb) { this.Client = client; this.LightBulb = lightBulb; this.Limiter = new ApiRateLimiter(TimeSpan.FromMilliseconds(50), this.ApiLimiterCallback, TimeSpan.Zero); this.Update().RunAsync(); }
async void StartLivX() { client = await LifxClient.CreateAsync(); client.DeviceDiscovered += Client_DeviceDiscovered; // client.DeviceLost += Client_DeviceLost; client.StartDeviceDiscovery(); }
public static async Task Run(ILogger logger = null) { if (logger == null) { var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); }); logger = loggerFactory.CreateLogger <LightsCore>(); } httpClient = new HttpClient(); SunsetClient sunsetClient = new SunsetClient(httpClient); LifxClient lifxClient = new LifxClient(httpClient); var getAllLightsTask = lifxClient.GetAllLights(); int desiredKelvin = await GetDesiredKelvin(sunsetClient, logger); logger.LogInformation($"Desired kelvin: {desiredKelvin}"); var changes = new List <State>(); var allLightsResult = await getAllLightsTask; foreach (Light light in allLightsResult) { if (light.Color.Kelvin == desiredKelvin) { logger.LogInformation($"Skipping {light.Label} because Kelvin is already {desiredKelvin}."); } else if (light.Color.Saturation > 0) { logger.LogInformation($"Skipping {light.Label} because saturation is greater than zero ({light.Color.Saturation}) indicating a custom colour is set."); } else { logger.LogInformation($"Changing {light.Label} from {light.Color.Kelvin} to {desiredKelvin}"); changes.Add(new State() { Selector = $"label:{light.Label}", Color = $"kelvin:{desiredKelvin}" }); } } if (changes.Any()) { var states = new States() { Fast = true, // See https://api.developer.lifx.com/v1/docs/set-state#fast-mode StateList = changes }; await lifxClient.PutStates(states); } }
private static async Task RunDemos(LifxClient client) { await DemoListing(client); await DemoScenes(client); await DemoModifyLight(client); await DemoModifyCollections(client); await DemoEffects(client); await DemoValidateColor(client); }
public LifxBulb(LifxData d, LifxClient c) { _captureMode = DataUtil.GetItem <int>("captureMode"); Data = d ?? throw new ArgumentException("Invalid Data"); _client = c; B = new LightBulb(d.HostName, d.MacAddress, d.Service, (uint)d.Port); _targetSector = d.TargetSector - 1; Brightness = d.Brightness; Id = d.Id; IpAddress = d.IpAddress; }
private static async Task <int> RunLightOff(string deviceSpec) { var parsedSpec = DeviceSpec.Parse(deviceSpec); var bulb = LightBulb.Create(parsedSpec.IPEndPoint, parsedSpec.MacAddress, service: 1); var client = await LifxClient.CreateAsync(new TraceLogger()); await client.TurnBulbOffAsync(bulb, TimeSpan.FromMilliseconds(0)); return(0); }
private static async Task <int> RunGetDeviceLabel(string deviceSpec) { var parsedSpec = DeviceSpec.Parse(deviceSpec); // TODO: don't assume it's a bulb var device = LightBulb.Create(parsedSpec.IPEndPoint, parsedSpec.MacAddress, service: 1); var client = await LifxClient.CreateAsync(new TraceLogger()); var result = await client.GetDeviceLabelAsync(device); Console.WriteLine(result); return(0); }
public async Task InitAsync(Dictionary <string, string> parameters) { _client = await LifxClient.CreateAsync(); _client.DeviceDiscovered += _client_DeviceDiscovered; _client.DeviceLost += _client_DeviceLost; _client.StartDeviceDiscovery(); if (!parameters.TryGetValue("SELECTED_DEVICE", out _initLabel)) { throw new Exception("SELECTED_DEVICE parameter is not defined."); } }
private static async Task DemoModifyCollections(LifxClient client) { Console.WriteLine(); List <Light> lights = (await client.ListLights(new Selector.LightLabel("LIFX 027d98"))); Group group = (await client.ListGroups()).FirstOrDefault(); if (group == null) { Console.WriteLine("No groups"); } else { Console.WriteLine("Using group: {0}", group); Console.WriteLine("Toggling group, 3 second duration."); await group.TogglePower(3); await Task.Delay(DELAY + 3000); Console.WriteLine("Turning group green"); await group.SetColor(LifxColor.Green, 0); await Task.Delay(DELAY); } Location location = (await client.ListLocations()).FirstOrDefault(); await Task.Delay(DELAY); if (location == null) { Console.WriteLine("No locations"); } else { Console.WriteLine("Using location: {0}", location); Console.WriteLine("Turning off location"); await location.SetPower(PowerState.Off); await Task.Delay(DELAY); Console.WriteLine("Setting color to white with 5 second duration."); await location.SetColor(new LifxColor.White(1), 5); await Task.Delay(DELAY + 5000); Console.WriteLine("Set light to a blue color, using 90% brightness override. Uses SetState explicitely."); await location.SetState(PowerState.On, new LifxColor.HSBK(180, 1, 1, 2000), 0.9, 2); await Task.Delay(DELAY); } }
public void InitialiseBulbs() { // Wait for bulb task to warm up var task = LifxClient.CreateAsync(); task.Wait(); client = task.Result; // Attach discovery event handlers client.DeviceDiscovered += Client_DeviceDiscoveredAsync; client.DeviceLost += Client_DeviceLost; // Trigger discovery process client.StartDeviceDiscovery(); }
public static async Task Init(bool startHTTPListener = true) { if (startHTTPListener) { Log.Bulb("Starting BixListens"); var bixListens = new BixListens(); bixListens.OnHttpEventReceived += BixListens_OnHttpEventReceived; } Log.Bulb("Creating LifxClient"); _client = await LifxClient.CreateAsync(); _client.DeviceDiscovered += Client_DeviceDiscovered; _client.DeviceLost += Client_DeviceLost; Log.Bulb("Start Device Discovery"); _client.StartDeviceDiscovery(); }
public static void CheckDefaults(LifxClient lc) { var db = GetDb(); var sc = db.GetCollection <SystemData>("system"); LogUtil.Write("SC: " + JsonConvert.SerializeObject(sc.ToString())); try { sc.Query().First(); LogUtil.Write("We should be set up already."); } catch (InvalidOperationException) { LogUtil.Write("Creating defaults."); DbDefaults(lc); } catch (NullReferenceException) { LogUtil.Write("Creating defaults."); DbDefaults(lc); } }
private static async Task DemoValidateColor(LifxClient client) { string colorName = "Pink"; Console.WriteLine(); Console.WriteLine(string.Format("Validating color: {0}", colorName)); var color = await client.ValidateColor(colorName); if (color.Item1) { Console.WriteLine(string.Format("{0} is a valid color name. Values are {1}.", colorName, color.Item2)); } else { Console.WriteLine(string.Format("{0} is not a valid color name.", colorName)); } }
// Use this for initialization void Start() { var task = LifxClient.CreateAsync(); task.Wait(); Client = task.Result; Client.DeviceDiscovered += Client_DeviceDiscovered; Client.DeviceLost += Client_DeviceLost; Client.StartDeviceDiscovery(); // Print the label of each device Client.Devices.ToList().ForEach(device => Debug.Log(Client.GetDeviceLabelAsync(device))); // MIDI IN 4 OpenMidiDevice( Tuple.Create("MIDIIN4 (mio4)", 10) ); }
private static async Task <int> RunGetDeviceVersion(string deviceSpec) { var parsedSpec = DeviceSpec.Parse(deviceSpec); // TODO: don't assume it's a bulb var device = LightBulb.Create(parsedSpec.IPEndPoint, parsedSpec.MacAddress, service: 1); var client = await LifxClient.CreateAsync(new TraceLogger()); var versionTask = client.GetDeviceVersionAsync(device); var firmwareVersionTask = client.GetDeviceHostFirmwareAsync(device); var version = await versionTask; var firmwareVersion = await firmwareVersionTask; // TODO: look up values to something meaningful Console.WriteLine($"Vendor ID: {version.Vendor} Product ID: {version.Product} Version: {version.Version}"); Console.WriteLine($"Firmware version {firmwareVersion.Version} (built at {firmwareVersion.Build})"); return(0); }
private static async Task <int> RunDiscover() { var client = await LifxClient.CreateAsync(new TraceLogger()); client.DeviceDiscovered += (o, e) => { Console.WriteLine($"{e.Device.MacAddressName}@{e.Device.Endpoint.Address}:{e.Device.Endpoint.Port}"); //Console.WriteLine($"Device {e.Device.MacAddressName} found @ {e.Device.Endpoint}"); //var version = await client.GetDeviceVersionAsync(e.Device); //var label = await client.GetDeviceLabelAsync(e.Device); //var state = await client.GetLightStateAsync(e.Device as LightBulb); //Console.WriteLine($"{state.Label}\n\tIs on: {state.IsOn}\n\tHue: {state.Hue}\n\tSaturation: {state.Saturation}\n\tBrightness: {state.Brightness}\n\tTemperature: {state.Kelvin}"); }; client.StartDeviceDiscovery(); // give some time for discovery to complete await Task.Delay(1000); return(0); }
public static void DbDefaults(LifxClient lc) { var db = GetDb(); // Check to see if we have our system data object var defaultSet = GetItem("DefaultSet"); if (defaultSet == null || defaultSet == false) { LogUtil.Write("Starting to create defaults."); // If not, create it var sd = new SystemData(true); foreach (var v in sd.GetType().GetProperties()) { LogUtil.Write("Setting: " + v.Name); SetItem(v.Name, v.GetValue(sd)); } var dsIp = GetItem("DsIp"); var ledData = new LedData(true); var myDevice = new DreamScreen4K(dsIp); myDevice.SetDefaults(); myDevice.Id = dsIp; SetObject("LedData", ledData); SetObject("MyDevice", myDevice); LogUtil.Write("Loading first..."); // Get/create our collection of Dream devices var d = db.GetCollection <BaseDevice>("devices"); // Create our default device // Save it d.Upsert(myDevice.Id, myDevice); d.EnsureIndex(x => x.Id); db.Commit(); // Scan for devices ScanDevices(lc).ConfigureAwait(false); } else { LogUtil.Write("Defaults are already set."); } }
private static async Task DemoScenes(LifxClient client) { Console.WriteLine(); Console.WriteLine("Scenes:"); List <Scene> scenes = await client.ListScenes(); if (scenes.Count() > 0) { foreach (var scene in scenes) { Console.WriteLine(scene.ToString()); } Console.WriteLine(string.Format("Activating Scene: {0}", scenes.First().Name)); await client.ActivateScene(scenes.First().UUID); await Task.Delay(EFFECT_DELAY); } else { Console.WriteLine("No scenes on account."); } }
private static async Task DemoListing(LifxClient client) { Console.WriteLine(); Console.WriteLine("Lights:"); foreach (var light in await client.ListLights()) { Console.WriteLine("{0} - {1}", light, light.Color); } Console.WriteLine(); Console.WriteLine("Groups:"); foreach (var group in await client.ListGroups()) { Console.WriteLine("{0} - {1} lights", group, group.Count()); } Console.WriteLine(); Console.WriteLine("Locations:"); foreach (var group in await client.ListLocations()) { Console.WriteLine("{0} - {1} lights", group, group.Count()); } }
private static async Task DemoModifyLight(LifxClient client) { Console.WriteLine(); Light light = (await client.ListLights(new Selector.GroupLabel("Room 1"))).FirstOrDefault(); if (light == null) { // Find a connected light foreach (var l in await client.ListLights()) { if (l.IsConnected) { light = l; break; } } if (!light.IsConnected) { Console.WriteLine("No connected lights"); return; } } Console.WriteLine("Using light: {0}", light); Console.WriteLine("Turning light off"); await light.SetPower(false); await Task.Delay(DELAY); Console.WriteLine("Toggling light on"); await light.TogglePower(); await Task.Delay(DELAY); Console.WriteLine("Turning light soft red"); await light.SetColor(new LifxColor.HSB(0, 0.2f, 0.5f)); await Task.Delay(DELAY); Console.WriteLine("Turning light blue-green"); await light.SetColor(new LifxColor.RGB(0x00c89c)); await Task.Delay(DELAY); Console.WriteLine("Turning light white"); await light.SetColor(LifxColor.DefaultWhite); await Task.Delay(DELAY); Console.WriteLine("Turning light hot white"); await light.SetColor(new LifxColor.White(0.8f, LifxColor.TemperatureMax)); await Task.Delay(DELAY); Console.WriteLine("Named colors:"); foreach (var c in LifxColor.NamedColors) { Console.Write("{0}: ", c); await light.SetColor(c); await light.Refresh(); Console.WriteLine("{0}", light.Color); await Task.Delay(DELAY); } }
// This initializes all of the data in our class and starts function loops private void Initialize() { LogUtil.Write("Initializing dream client..."); // Create cancellation token sources _sendTokenSource = new CancellationTokenSource(); _captureTokenSource = new CancellationTokenSource(); _camTokenSource = new CancellationTokenSource(); // Init lifx client _lifxClient = LifxClient.CreateAsync().Result; // Init nano HttpClient _nanoClient = new HttpClient(); // Init nano socket _nanoSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _nanoSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _nanoSocket.EnableBroadcast = false; // Cache data store // Check default settings DataUtil.CheckDefaults(_lifxClient); var dd = DataUtil.GetDb(); // Get audio input if exists _aStream = GetStream(); // Get our device data _dev = DataUtil.GetDeviceData(); // Create scene builder _dreamScene = new DreamScene(); // Get a list of devices _devices = new List <BaseDevice>(); // Read other variables _devMode = _dev.Mode; _ambientMode = _dev.AmbientModeType; _ambientShow = _dev.AmbientShowType; _ambientColor = ColorFromString(_dev.AmbientColor); _brightness = _dev.Brightness; _autoDisabled = false; try { _autoDisabled = DataUtil.GetItem("AutoDisabled"); } catch { } CaptureMode = DataUtil.GetItem("CaptureMode"); // Set default values _prevMode = -1; _prevAmbientMode = -1; _prevAmbientShow = -1; _streamStarted = false; _showBuilderStarted = false; _group = (byte)_dev.GroupNumber; _targetEndpoint = new IPEndPoint(IPAddress.Parse(DataUtil.GetItem("DsIp")), 8888); _sDevices = new List <IStreamingDevice>(); _wlStrips = new List <WLedStrip>(); // Start our timer to refresh devices StartRefreshTimer(); // Start our service to capture (if capture mode is set) StartCaptureServices(_captureTokenSource.Token); StartVideoCaptureTask(); // Now, start listening for UDP commands StartListening(); // Finally start our normal device behavior if (!_autoDisabled) { UpdateMode(_dev.Mode); } }
public LifxDiscovery(LifxClient client) { _client = client; }
public dynamic?CreateAgent(ControlService cs) { _lc = LifxClient.CreateAsync().Result; return(_lc); }
public static async void RefreshDevices(LifxClient c) { var cs = new CancellationTokenSource(); cs.CancelAfter(10000); LogUtil.Write("Starting scan."); scanning = true; // Get dream devices var ld = new LifxDiscovery(c); var nanoTask = NanoDiscovery.Refresh(cs.Token); var bridgeTask = HueDiscovery.Refresh(cs.Token); var dreamTask = DreamDiscovery.Discover(); var wLedTask = WledDiscovery.Discover(); var bulbTask = ld.Refresh(cs.Token); try { await Task.WhenAll(nanoTask, bridgeTask, dreamTask, bulbTask, wLedTask); } catch (TaskCanceledException e) { LogUtil.Write("Discovery task was canceled before completion: " + e.Message, "WARN"); } catch (SocketException f) { LogUtil.Write("Socket Exception during discovery: " + f.Message, "WARN"); } LogUtil.Write("Refresh complete."); try { var leaves = nanoTask.Result; var bridges = bridgeTask.Result; var dreamDevices = dreamTask.Result; var bulbs = bulbTask.Result; var wleds = wLedTask.Result; var db = GetDb(); var bridgeCol = db.GetCollection <BridgeData>("Dev_Hue"); var nanoCol = db.GetCollection <NanoData>("Dev_Nanoleaf"); var devCol = db.GetCollection <BaseDevice>("Dev_DreamScreen"); var lifxCol = db.GetCollection <LifxData>("Dev_Lifx"); var wledCol = db.GetCollection <WLedData>("Dev_Wled"); foreach (var b in bridges) { bridgeCol.Upsert(b); } foreach (var n in leaves) { nanoCol.Upsert(n); } foreach (var dd in dreamDevices) { devCol.Upsert(dd); } foreach (var b in bulbs) { lifxCol.Upsert(b); } foreach (var w in wleds) { wledCol.Upsert(w); } bridgeCol.EnsureIndex(x => x.Id); nanoCol.EnsureIndex(x => x.Id); devCol.EnsureIndex(x => x.Id); lifxCol.EnsureIndex(x => x.Id); wledCol.EnsureIndex(x => x.Id); } catch (TaskCanceledException) { } catch (AggregateException) { } scanning = false; cs.Dispose(); }
private static async Task DemoEffects(LifxClient client) { Console.WriteLine(); Light light = (await client.ListLights(new Selector.GroupLabel("Room 1"))).FirstOrDefault(); if (light == null) { // Find a connected light foreach (var l in await client.ListLights()) { if (l.IsConnected) { light = l; break; } } if (!light.IsConnected) { Console.WriteLine("No connected lights"); return; } } Console.WriteLine("Using light: {0}", light); Console.WriteLine("Pulsing slowly between previously set color and green"); await light.PulseEffect(LifxColor.Green, 1, 10); await Task.Delay(EFFECT_DELAY); /* If strobing with a single color (therefore the light alternates between the "color" parameter and "fromColor" * parameter which should be set to LifxColor.OffState (zero brightness) you must set the "color" parameter to a custom color * with a brightness value explicitly set. The default named parameters appear to leave the light in a fixed zero brightness state * until the end of the effect. */ Console.WriteLine("Pulsing quickly in white"); await light.PulseEffect(new LifxColor.White(1, 3500), 0.1, 50, fromColor : LifxColor.OffState); await Task.Delay(EFFECT_DELAY); Console.WriteLine("Breathing red alert light."); await light.BreatheEffect(new LifxColor.RGB(120, 0, 0), 2.5, 4, LifxColor.OffState, peak : 0.4d); await Task.Delay(EFFECT_DELAY); Console.WriteLine("\"Party breathe\", will pass through intermediate colors."); await light.BreatheEffect(LifxColor.Cyan, 5, 4, LifxColor.Orange, peak : 0.5d); await Task.Delay(EFFECT_DELAY); List <LightState> stateList = new List <LightState>(); stateList.Add(new LightState(PowerState.On, LifxColor.Pink, 0.5d)); stateList.Add(new LightState(PowerState.On, LifxColor.Pink, 1.0d)); stateList.Add(new LightState(PowerState.On, LifxColor.DefaultWhite, 1.0d)); stateList.Add(new LightState(PowerState.On, LifxColor.Green)); stateList.Add(new LightState(PowerState.On, LifxColor.Blue, 1.0d)); stateList.Add(new LightState(PowerState.On, LifxColor.Blue, 0.5d)); LightState defaults = new LightState(); defaults.Duration = 3.0d; defaults.Brightness = 1.0d; // Cycle forward Console.WriteLine("Cycling forward through set of 6 light states."); for (int i = 0; i < stateList.Count(); i++) { await light.Cycle(stateList, defaults); await Task.Delay(4000); } await Task.Delay(1000); // Cycle backward Console.WriteLine("Cycling backward through set of 6 light states."); for (int i = 0; i < stateList.Count(); i++) { await light.Cycle(stateList, defaults, Direction.Backward); await Task.Delay(4000); } }
private static async Task RunDemos(LifxClient client) { await DemoListing(client); await DemoModifyLight(client); await DemoModifyCollections(client); }