private void FixedUpdate() { var stone = _remoteCameraPlatform.GetSocketedStone(); if (stone == null) { if (_hasLoadedAssets) { _hasLoadedAssets = false; _streamingGroup.ReleaseRequiredAssets(); _streamingGroup.ReleaseGeneralAssets(); _streamingGroup = null; } } else { if (!_hasLoadedAssets) { _hasLoadedAssets = true; _streamingGroup = StreamingGroup.GetStreamingGroup(NomaiRemoteCameraStreaming.NomaiRemoteCameraPlatformIDToSceneName(stone.GetRemoteCameraID())); _streamingGroup.RequestRequiredAssets(); _streamingGroup.RequestGeneralAssets(); } } }
private async Task <EntertainmentLayer> GetOrCreateEntertainmentLayerAsync() { if (entertainmentLayer != null) { return(entertainmentLayer); } var group = (await deviceInfo.Client.GetEntertainmentGroups()).FirstOrDefault(); if (group == null) { ErrorMessage = "No default entertainment group"; return(null); } Debug.WriteLine($"Group: {group.Name}"); var streamClient = new StreamingHueClient(deviceInfo.Address, localSettings.AppKey, localSettings.StreamingKey); var stream = new StreamingGroup(group.Lights); await streamClient.Connect(group.Id); streamClient.AutoUpdate(stream, globalEffectsCancelSource.Token); return(entertainmentLayer = stream.GetNewLayer(isBaseLayer: true)); }
/// <summary> /// Auto update the streamgroup /// </summary> /// <param name="streamingGroup"></param> /// <param name="cancellationToken"></param> /// <param name="frequency"></param> /// <param name="onlySendDirtyStates">Only send light states that have been changed since last update</param> public Task AutoUpdate(StreamingGroup streamingGroup, CancellationToken cancellationToken, int frequency = 50, bool onlySendDirtyStates = false) { if (!_simulator) { int groupCount = (streamingGroup.Count / 10) + 1; frequency = frequency / groupCount; } else { onlySendDirtyStates = false; //Simulator does not understand partial updates } var waitTime = TimeSpan.FromMilliseconds(TimeSpan.FromSeconds(1).TotalMilliseconds / frequency); return(Task.Run(() => { int missedMessages = 0; #if DEBUG int lastSecond = 0; int msgPerSecondCount = 0; #endif while (!cancellationToken.IsCancellationRequested) { var sw = Stopwatch.StartNew(); IEnumerable <IEnumerable <StreamingLight> > chunks = streamingGroup.GetChunksForUpdate(forceUpdate: !onlySendDirtyStates); if (chunks != null) { Send(chunks); } else { missedMessages++; if (missedMessages > frequency) { //If there are no updates, still send updates to keep connection open chunks = streamingGroup.GetChunksForUpdate(forceUpdate: true); Send(chunks); missedMessages = 0; } } sw.Stop(); //#if DEBUG // //Debug.WriteLine("Elasped: " + sw.ElapsedMilliseconds); // msgPerSecondCount++; // if (DateTime.Now.Second != lastSecond) // { // Debug.WriteLine("Msg per second: " + msgPerSecondCount); // msgPerSecondCount = 0; // lastSecond = DateTime.Now.Second; // } //#endif if (sw.Elapsed < waitTime) { Thread.Sleep(waitTime - sw.Elapsed); //Better performance than Task.Delay } } })); }
public bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool exclusiveAccessIfPossible = false, bool throwExceptions = false) { IsInitialized = false; try { UpdateTrigger.Stop(); IList <IRGBDevice> devices = new List <IRGBDevice>(); UpdateTrigger.ClientGroups = new Dictionary <StreamingHueClient, StreamingGroup>(); foreach (HueClientDefinition clientDefinition in ClientDefinitions) { // Create a temporary for this definition ILocalHueClient client = new LocalHueClient(clientDefinition.Ip); client.Initialize(clientDefinition.AppKey); // Get the entertainment groups, no point continuing without any entertainment groups IReadOnlyList <Group> entertainmentGroups = client.GetEntertainmentGroups().GetAwaiter().GetResult(); if (!entertainmentGroups.Any()) { continue; } // Get all lights once, all devices can use this list to identify themselves List <Light> lights = client.GetLightsAsync().GetAwaiter().GetResult().ToList(); foreach (Group entertainmentGroup in entertainmentGroups.OrderBy(g => int.Parse(g.Id))) { StreamingHueClient streamingClient = new StreamingHueClient(clientDefinition.Ip, clientDefinition.AppKey, clientDefinition.ClientKey); StreamingGroup streamingGroup = new StreamingGroup(entertainmentGroup.Locations); streamingClient.Connect(entertainmentGroup.Id).GetAwaiter().GetResult(); UpdateTrigger.ClientGroups.Add(streamingClient, streamingGroup); foreach (string lightId in entertainmentGroup.Lights.OrderBy(int.Parse)) { HueDeviceInfo deviceInfo = new HueDeviceInfo(entertainmentGroup, lightId, lights); HueDevice device = new HueDevice(deviceInfo); device.Initialize(new HueUpdateQueue(UpdateTrigger, lightId, streamingGroup)); devices.Add(device); } } } UpdateTrigger.Start(); Devices = new ReadOnlyCollection <IRGBDevice>(devices); IsInitialized = true; } catch { if (throwExceptions) { throw; } return(false); } return(true); }
/// <summary> /// Can be used if you dont want to use the AutoUpdate, but need the same logic for sending updated to the bridge /// </summary> /// <param name="streamingGroup"></param> /// <param name="onlySendDirtyStates"></param> public void ManualUpdate(StreamingGroup streamingGroup, bool onlySendDirtyStates = false) { IEnumerable <IEnumerable <StreamingLight> > chunks = streamingGroup.GetChunksForUpdate(forceUpdate: !onlySendDirtyStates); if (chunks != null) { Send(chunks); } }
public HueLightClient( StreamingHueClient hueClient, StreamingGroup streamingGroup) { this.hueClient = hueClient; this.streamingGroup = streamingGroup; hueLayer = streamingGroup.GetNewLayer(true); Lights = hueLayer.Select(l => new Position((float)l.LightLocation.X, (float)l.LightLocation.Y)).ToArray(); }
protected virtual void Send(IEnumerable <IEnumerable <StreamingChannel> > chunks) { if (entConfigIdBytes == null) { throw new HueEntertainmentException("This client is not connected to a group"); } var msg = StreamingGroup.GetCurrentStateAsByteArray(this.entConfigIdBytes, chunks); Send(msg); }
public static async Task <StreamingGroup> SetupAndReturnGroup() { //string ip = "192.168.0.4"; //string key = "8JwWAj5J1tSsKLxyUOdAkWmcCQFcNc51AKRhxdH9"; //string entertainmentKey = "AFFD322C34C993C19503D369481869FD"; //var useSimulator = false; //string ip = "10.42.39.194"; //string key = "tocjq6GmPJ8KX5DyLDKXQreZE6txQVQ5oBqbYDFn"; //string entertainmentKey = "DB088F63639524B5A8CDC8AEEAC9C322"; //var useSimulator = false; string ip = "127.0.0.1"; string key = "aSimulatedUser"; string entertainmentKey = "01234567890123456789012345678901"; var useSimulator = true; //Initialize streaming client StreamingHueClient client = new StreamingHueClient(ip, key, entertainmentKey); //Get the entertainment group var all = await client.LocalHueClient.GetEntertainmentGroups(); var group = all.FirstOrDefault(); if (group == null) { throw new Exception("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample"); } else { Console.WriteLine($"Using Entertainment Group {group.Id}"); } //Create a streaming group var stream = new StreamingGroup(group.Locations); stream.IsForSimulator = useSimulator; //Connect to the streaming group await client.Connect(group.Id, simulator : useSimulator); //Start auto updating this entertainment group client.AutoUpdate(stream, new System.Threading.CancellationToken(), 50); //Optional: Check if streaming is currently active var bridgeInfo = await client.LocalHueClient.GetBridgeAsync(); Console.WriteLine(bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active"); return(stream); }
public static async Task <StreamingGroup> SetupAndReturnGroup() { //string ip = "192.168.0.4"; //string key = "8JwWAj5J1tSsKLxyUOdAkWmcCQFcNc51AKRhxdH9"; //string entertainmentKey = "AFFD322C34C993C19503D369481869FD"; //var useSimulator = false; //string ip = "10.70.16.38"; //string key = "dpzXfw8NvafvCCvtLkQLUET-6Kc4jT4RovPg59Rx"; //string entertainmentKey = "260FE0B7251DF783CFB9FBAB1D1E8B0C"; //var useSimulator = false; string ip = "127.0.0.1"; string key = "aSimulatedUser"; string entertainmentKey = "01234567890123456789012345678901"; var useSimulator = true; //Initialize streaming client StreamingHueClient client = new StreamingHueClient(ip, key, entertainmentKey); //Get the entertainment group var all = await client.LocalHueClient.GetEntertainmentGroups(); var group = all.FirstOrDefault(); if (group == null) { throw new HueException("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample"); } else { Console.WriteLine($"Using Entertainment Group {group.Id}"); } //Create a streaming group var stream = new StreamingGroup(group.Locations); stream.IsForSimulator = useSimulator; //Connect to the streaming group await client.Connect(group.Id, simulator : useSimulator); //Start auto updating this entertainment group client.AutoUpdate(stream, new System.Threading.CancellationToken(), 50, onlySendDirtyStates: false); //Optional: Check if streaming is currently active var bridgeInfo = await client.LocalHueClient.GetBridgeAsync(); Console.WriteLine(bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active"); return(stream); }
static void UpdateHue(StreamingGroup streamingLights) { do { var lights = streamingLights.OrderBy(x => new Guid()); foreach (StreamingLight light in lights) { int colInt = streamingLights.IndexOf(light) % 4; light.SetState(new RGBColor(colors[colInt].R, colors[colInt].G, colors[colInt].B), 1); Thread.Sleep(5); } //Thread.Sleep(50); } while (running); }
public static async Task <StreamingGroup> SetupAndReturnGroup() { string ip = "192.168.0.4"; string key = "im5PBqU--4CJq2N2t8xMVNvZ2qxOtgzLcfVTkwzP"; string entertainmentKey = "32C1FEB5439F313891C44369FF71388C"; var useSimulator = false; //string ip = "127.0.0.1"; //string key = "aSimulatedUser"; //string entertainmentKey = "01234567890123456789012345678901"; //var useSimulator = true; //Initialize streaming client StreamingHueClient client = new StreamingHueClient(ip, key, entertainmentKey); //Get the entertainment group var all = await client.LocalHueApi.GetEntertainmentConfigurations(); var group = all.Data.FirstOrDefault(); if (group == null) { throw new HueEntertainmentException("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample"); } else { Console.WriteLine($"Using Entertainment Group {group.Id}"); } //Create a streaming group var stream = new StreamingGroup(group.Channels); stream.IsForSimulator = useSimulator; //Connect to the streaming group await client.Connect(group.Id, simulator : useSimulator); //Start auto updating this entertainment group client.AutoUpdate(stream, new CancellationToken(), 50, onlySendDirtyStates: false); //Optional: Check if streaming is currently active var entArea = await client.LocalHueApi.GetEntertainmentConfiguration(group.Id); Console.WriteLine(entArea.Data.First().Status == HueApi.Models.EntertainmentConfigurationStatus.active ? "Streaming is active" : "Streaming is not active"); return(stream); }
public static async Task <StreamingGroup> SetupAndReturnGroup() { string ip = ApplicationManager.Instance.Settings.HueBridgeIP; string key = ApplicationManager.Instance.Settings.HueKey; string entertainmentKey = ApplicationManager.Instance.Settings.HueEntertainmentKey; bool useSimulator = ApplicationManager.Instance.Settings.HueUseSimulator; StreamingGroup = null; Layers = null; StreamingHueClient = new StreamingHueClient(ip, key, entertainmentKey); var allEntertainmentGroups = await StreamingHueClient.LocalHueClient.GetEntertainmentGroups(); var entertainmentGroup = allEntertainmentGroups.FirstOrDefault(); if (entertainmentGroup == null) { throw new Exception("No Entertainment Group found."); } var stream = new StreamingGroup(entertainmentGroup.Locations); stream.IsForSimulator = useSimulator; await StreamingHueClient.Connect(entertainmentGroup.Id, simulator : useSimulator); StreamingHueClient.AutoUpdate(stream, 50); StreamingGroup = stream; var baseLayer = stream.GetNewLayer(isBaseLayer: true); var effectLayer = stream.GetNewLayer(isBaseLayer: false); Layers = new List <EntertainmentLayer>() { baseLayer, effectLayer }; baseLayer.AutoCalculateEffectUpdate(); effectLayer.AutoCalculateEffectUpdate(); return(stream); }
public async Task OnStartReading() { try { if (_config.Model.hueSettings.hueType == HueType.Basic) { if (_config.Model.hueSettings.turnLightOnIfOff) { var command = new LightCommand { On = true, TransitionTime = _frameTimeSpan }; command.TurnOn(); await _client.SendCommandAsync(command, UseRoom.Lights); } } else if (_config.Model.hueSettings.hueType == HueType.Entertainment) { _cancelSource = new CancellationTokenSource(); _cancelToken = _cancelSource.Token; _streamGroup = new StreamingGroup(UseRoom.Locations); await _streamClient.Connect(UseRoom.Id); _streamBaseLayer = _streamGroup.GetNewLayer(true); foreach (var light in _streamBaseLayer) { if (_config.Model.hueSettings.turnLightOnIfOff) { light.SetState(_cancelToken, new RGBColor(1.0, 1.0, 1.0), 0.5); } } _streamClient.ManualUpdate(_streamGroup); } } catch (Exception ex) { Console.WriteLine(ex); _ = Task.Run(() => _logger?.WriteLog(ex.ToString())); } }
private async Task <HueLightClient> Connect(StreamingHueClient hueClient, string entertainmentGroupName) { var entertainmentGroups = await hueClient.LocalHueClient.GetEntertainmentGroups(); var entertainmentGroup = entertainmentGroups.FirstOrDefault(g => g.Name == entertainmentGroupName); if (entertainmentGroup == null) { throw new ArgumentException($"Cannot find entertainment group {entertainmentGroupName}"); } var streamingGroup = new StreamingGroup(entertainmentGroup.Locations); Console.WriteLine("Attempting to connect to entertainment group"); await hueClient.Connect(entertainmentGroup.Id).ConfigureAwait(false); Console.WriteLine("Connected"); return(new HueLightClient(hueClient, streamingGroup)); }
public static async Task connect(CancellationToken token, string ip = null) { if (ip == null) { ip = await FindBridge(); } token.ThrowIfCancellationRequested(); var appKey = Settings.ChromaConfig.Instance.HueAppKey; var clientKey = Settings.ChromaConfig.Instance.HueClientKey; Debug.Log("Connecting to bridge..."); var client = new StreamingHueClient(ip, appKey, clientKey); token.ThrowIfCancellationRequested(); Debug.Log("Connected! Getting entertainment group..."); var group = (await client.LocalHueClient.GetEntertainmentGroups()).FirstOrDefault(); if (group == null) { Debug.Log("Group is missing!"); return; } token.ThrowIfCancellationRequested(); var entGroup = new StreamingGroup(group.Locations); Debug.Log("Found group! Connecting to lightbulbs..."); await client.Connect(group.Id); token.ThrowIfCancellationRequested(); Debug.Log("Connected to bulbs! Syncing..."); _ = client.AutoUpdate(entGroup, token); var entLayer = entGroup.GetNewLayer(true); LightInfo.setInfo(client, entLayer, token); await Task.Delay(TimeSpan.FromMilliseconds(50), token); if (Settings.ChromaConfig.Instance.LowLight == true) { entLayer.SetState(token, new RGBColor(255, 255, 255), 0.5); } }
public async Task InitializeEntertainmentGroup(Group group, int autoUpdateFrequency) { // Create a streaming group SelectedEntertainmentGroup = new StreamingGroup(group.Locations); SelectedEntertainmentGroup.IsForSimulator = true; bool doProfileSave = false; // If there are no group settings, initialize list if (Profile.GroupSettings == null) { Profile.GroupSettings = new List <HueGroupSetting>(); doProfileSave = true; } // If there's no profile for this group, grab a default if (Profile.GroupSettings.FirstOrDefault(g => g.GroupName == group.Name) == null) { Profile.GroupSettings.Add(HueGroupSetting.GetDefault(group.Id, group.Name)); doProfileSave = true; } if (doProfileSave) { SaveProfile(); } // Connect to the streaming group await connectToHueBridge(group.Id); _isConnected = true; // Start auto updating this entertainment group Client.AutoUpdate(SelectedEntertainmentGroup, autoUpdateFrequency); // Send an event indicating group has been selected SelectedGroupSetting = Profile.GroupSettings.First(g => g.GroupId == group.Id); // Default to picking first light profile SelectedLightProfile = SelectedGroupSetting.LightProfiles[0]; }
public async Task OnStopReading() { if (_config.Model.hueSettings.hueType == HueType.Basic) { if (_config.Model.hueSettings.shutLightOffOnStop) { var command = new LightCommand { On = false, TransitionTime = _frameTimeSpan }; command.TurnOff(); await _client.SendCommandAsync(command, UseRoom.Lights); } } else if (_config.Model.hueSettings.hueType == HueType.Entertainment) { if (_config.Model.hueSettings.shutLightOffOnStop && _streamBaseLayer != null) { foreach (var light in _streamBaseLayer) { light.SetState(_cancelToken, brightness: 0.0, timeSpan: _frameTimeSpan); } } if (_streamGroup != null) { _streamClient?.ManualUpdate(_streamGroup); } _cancelSource?.Cancel(); _cancelSource?.Dispose(); _streamGroup = null; _streamBaseLayer = null; //Closing disposes the client so we need to reconnect if we want to reuse it. _streamClient?.Close(); _streamClient = null; await ConnectToBridge(); } }
/// <summary> /// Auto update the streamgroup /// </summary> /// <param name="entGroup"></param> /// <param name="frequency"></param> /// <param name="onlySendDirtyStates">Only send light states that have been changed since last update</param> /// <param name="cancellationToken"></param> public void AutoUpdate(StreamingGroup entGroup, CancellationToken cancellationToken, int frequency = 50, bool onlySendDirtyStates = false) { if (!_simulator) { int groupCount = (entGroup.Count / 10) + 1; frequency = frequency / groupCount; } else { onlySendDirtyStates = false; //Simulator does not understand partial updates } var waitTime = (int)TimeSpan.FromSeconds(1).TotalMilliseconds / frequency; Task.Run(async() => { int missedMessages = 0; while (!cancellationToken.IsCancellationRequested) { IEnumerable <IEnumerable <StreamingLight> > chunks = entGroup.GetChunksForUpdate(forceUpdate: !onlySendDirtyStates); if (chunks != null) { Send(chunks); } else { missedMessages++; if (missedMessages > frequency) { //If there are no updates, still send updates to keep connection open chunks = entGroup.GetChunksForUpdate(forceUpdate: true); Send(chunks); missedMessages = 0; } } await Task.Delay(waitTime, cancellationToken).ConfigureAwait(false); } }); }
/// <summary> /// Used to auto update and apply effects that are added to the Effects list of the StreamingGroup /// </summary> /// <param name="entGroup"></param> /// <param name="cancellationToken"></param> public void AutoCalculateEffectUpdate(StreamingGroup entGroup, CancellationToken cancellationToken = new CancellationToken()) { Task.Run(async() => { int waitTime = 50; while (!cancellationToken.IsCancellationRequested) { foreach (var effect in entGroup.Effects.Where(x => x.State != null)) { foreach (var light in entGroup) { var effectMultiplier = effect.GetEffectStrengthMultiplier(light); if (effectMultiplier.HasValue) { light.SetState(effect.State.RGBColor, effect.State.Brightness * effectMultiplier.Value); } } } await Task.Delay(waitTime).ConfigureAwait(false); } }, cancellationToken); }
public async Task Start() { StreamingGroup stream = await StreamingSetup.SetupAndReturnGroup(); var baseEntLayer = stream.GetNewLayer(isBaseLayer: true); var effectLayer = stream.GetNewLayer(); //Optional: calculated effects that are placed on this layer baseEntLayer.AutoCalculateEffectUpdate(new CancellationToken()); effectLayer.AutoCalculateEffectUpdate(new CancellationToken()); //Order lights based on position in the room var orderedLeft = baseEntLayer.GetLeft().OrderByDescending(x => x.LightLocation.Y).ThenBy(x => x.LightLocation.X).To2DGroup(); var orderedRight = baseEntLayer.GetRight().OrderByDescending(x => x.LightLocation.Y).ThenByDescending(x => x.LightLocation.X); var allLightsOrdered = baseEntLayer.OrderBy(x => x.LightLocation.X).ThenBy(x => x.LightLocation.Y).ToList().To2DGroup(); var allLightsOrderedFlat = baseEntLayer.OrderBy(x => x.LightLocation.X).ThenBy(x => x.LightLocation.Y).ToList(); var orderedByDistance = baseEntLayer.OrderBy(x => x.LightLocation.Distance(0, 0)).To2DGroup(); var orderedByAngle = baseEntLayer.OrderBy(x => x.LightLocation.Angle(0, 0)).To2DGroup(); var line1 = baseEntLayer.Where(x => x.LightLocation.X <= -0.6).ToList(); var line2 = baseEntLayer.Where(x => x.LightLocation.X > -0.6 && x.LightLocation.X <= -0.1).ToList(); var line3 = baseEntLayer.Where(x => x.LightLocation.X > -0.1 && x.LightLocation.X <= 0.1).ToList(); var line4 = baseEntLayer.Where(x => x.LightLocation.X > 0.1 && x.LightLocation.X <= 0.6).ToList(); var line5 = baseEntLayer.Where(x => x.LightLocation.X > 0.6).ToList(); var allLightsReverse = allLightsOrdered.ToList(); allLightsReverse.Reverse(); CancellationTokenSource cst = new CancellationTokenSource(); //Console.WriteLine("Blue line on 90 degree angle"); //var blueLineEffect = new HorizontalScanLineEffect(); //baseEntLayer.PlaceEffect(blueLineEffect); //blueLineEffect.Start(); //cst = WaitCancelAndNext(cst); //blueLineEffect.Stop(); //Ref<int?> stepSize = 20; //blueLineEffect.Rotate(stepSize); //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.WriteLine("Finished"); //cst = WaitCancelAndNext(cst); //blueLineEffect.Stop(); var quarter = new[] { baseEntLayer.GetLeft().GetFront(), baseEntLayer.GetLeft().GetBack(), baseEntLayer.GetRight().GetBack(), baseEntLayer.GetRight().GetFront() }.ToList(); baseEntLayer.SetState(cst.Token, new RGBColor("FFFFFF"), 1); cst = WaitCancelAndNext(cst); Console.WriteLine("Transition to red in 10 seconds"); baseEntLayer.SetState(cst.Token, new RGBColor("FF0000"), TimeSpan.FromSeconds(10)); Console.ReadLine(); Console.WriteLine("Transition to bri 0.25"); baseEntLayer.SetState(cst.Token, null, default, 0.25, TimeSpan.FromSeconds(1), true);
protected virtual void Send(IEnumerable <IEnumerable <StreamingLight> > chunks) { var msg = StreamingGroup.GetCurrentStateAsByteArray(chunks); Send(msg); }
public async Task Run(CancellationToken token, string ip = null) { try { if (ip == null) { ip = await FindBridge(); } token.ThrowIfCancellationRequested(); var appKey = prefs.GetString("HueSaber", "appKey"); var clientKey = prefs.GetString("HueSaber", "clientKey"); log.Info("Connecting to bridge..."); var client = new StreamingHueClient(ip, appKey, clientKey); token.ThrowIfCancellationRequested(); log.Info("Connected! Getting entertainment group..."); var group = (await client.LocalHueClient.GetEntertainmentGroups()).ElementAtOrDefault(prefs.GetInt("HueSaber", "overrideRoom", 0)); if (group == null) { log.Error("Group is missing!"); return; } token.ThrowIfCancellationRequested(); var entGroup = new StreamingGroup(group.Locations); log.Info("Found group! Connecting to lightbulbs..."); await client.Connect(group.Id); token.ThrowIfCancellationRequested(); log.Info("Connected to bulbs! Tracking background color..."); _ = client.AutoUpdate(entGroup, token); var layer = entGroup.GetNewLayer(true); while (!token.IsCancellationRequested) { //log.Info($"Color is {currentColor}"); var color = (Color)currentColor; var miss = DateTimeOffset.UtcNow - (DateTimeOffset)missTime; var cut = DateTimeOffset.UtcNow - (DateTimeOffset)cutTime; var rgbColor = new RGBColor(color.r, color.g, color.b); var hsbColor = rgbColor.GetHSB(); if (hsbColor.Saturation > 35) { hsbColor.Saturation = 200; } var brightness = 0.7; if (miss < TimeSpan.FromMilliseconds(100)) { brightness = 0.5; } else if (cut < TimeSpan.FromMilliseconds(100)) { brightness = 1; } layer.SetState(token, hsbColor.GetRGB(), brightness, TimeSpan.FromMilliseconds(50)); await Task.Delay(TimeSpan.FromMilliseconds(1000.0 / 30.0), token); } } catch (Exception ex) { log.Error(ex); throw; } }
public async void Init(Label labelHint) { client = new StreamingHueClient(ip, key, entertainmentKey); //Get the entertainment group IReadOnlyList <Group> all = null; try { all = await client.LocalHueClient.GetEntertainmentGroups(); } catch (Exception e) { labelHint.Text = "Hue init exception: " + e.Message; return; } var group = all.FirstOrDefault(); if (group == null) { //throw new Exception("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample"); labelHint.Text = "No Entertainment Group found"; return; } else { labelHint.Text = $"Using Entertainment Group {group.Id}"; Console.WriteLine($"Using Entertainment Group {group.Id}"); } //Create a streaming group entGroup = new StreamingGroup(group.Locations); //Connect to the streaming group await client.Connect(group.Id); //Start auto updating this entertainment group client.AutoUpdate(entGroup, 50); //Optional: calculated effects that are placed in the room client.AutoCalculateEffectUpdate(entGroup); //Optional: Check if streaming is currently active var bridgeInfo = await client.LocalHueClient.GetBridgeAsync(); Console.WriteLine(bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active"); labelHint.Text = bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active"; //Order lights based on position in the room var orderedLeft = entGroup.GetLeft().OrderByDescending(x => x.LightLocation.Y).ThenBy(x => x.LightLocation.X); var orderedRight = entGroup.GetRight().OrderByDescending(x => x.LightLocation.Y).ThenByDescending(x => x.LightLocation.X); var allLightsOrdered = orderedLeft.Concat(orderedRight.Reverse()).ToArray(); var allLightsReverse = allLightsOrdered.ToList(); allLightsReverse.Reverse(); Random rnd = new Random(); hue = rnd.Next(0, 65535); entGroup.SetState(HueToRGB(hue, 1, 1), 1, TimeSpan.FromMilliseconds(0)); isInit = true; }
public async Task Start() { StreamingGroup stream = await StreamingSetup.SetupAndReturnGroup(); var baseEntLayer = stream.GetNewLayer(isBaseLayer: true); var effectLayer = stream.GetNewLayer(); //Optional: calculated effects that are placed on this layer baseEntLayer.AutoCalculateEffectUpdate(new CancellationToken()); effectLayer.AutoCalculateEffectUpdate(new CancellationToken()); //Order lights based on position in the room var orderedLeft = baseEntLayer.GetLeft().OrderByDescending(x => x.LightLocation.Y).ThenBy(x => x.LightLocation.X).To2DGroup(); var orderedRight = baseEntLayer.GetRight().OrderByDescending(x => x.LightLocation.Y).ThenByDescending(x => x.LightLocation.X); var allLightsOrdered = baseEntLayer.OrderBy(x => x.LightLocation.X).ThenBy(x => x.LightLocation.Y).ToList().To2DGroup(); var allLightsOrderedFlat = baseEntLayer.OrderBy(x => x.LightLocation.X).ThenBy(x => x.LightLocation.Y).ToList(); var orderedByDistance = baseEntLayer.OrderBy(x => x.LightLocation.Distance(0, 0)).To2DGroup(); var orderedByAngle = baseEntLayer.OrderBy(x => x.LightLocation.Angle(0, 0)).To2DGroup(); var line1 = baseEntLayer.Where(x => x.LightLocation.X <= -0.6).ToList(); var line2 = baseEntLayer.Where(x => x.LightLocation.X > -0.6 && x.LightLocation.X <= -0.1).ToList(); var line3 = baseEntLayer.Where(x => x.LightLocation.X > -0.1 && x.LightLocation.X <= 0.1).ToList(); var line4 = baseEntLayer.Where(x => x.LightLocation.X > 0.1 && x.LightLocation.X <= 0.6).ToList(); var line5 = baseEntLayer.Where(x => x.LightLocation.X > 0.6).ToList(); var allLightsReverse = allLightsOrdered.ToList(); allLightsReverse.Reverse(); CancellationTokenSource cst = new CancellationTokenSource(); Console.WriteLine("Blue line on 90 degree angle"); var blueLineEffect = new HorizontalScanLineEffect(); baseEntLayer.PlaceEffect(blueLineEffect); blueLineEffect.Start(); cst = WaitCancelAndNext(cst); blueLineEffect.Stop(); //Ref<int?> stepSize = 20; //blueLineEffect.Rotate(stepSize); //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.ReadLine(); //stepSize.Value -= 5; //Console.WriteLine("Finished"); //cst = WaitCancelAndNext(cst); //blueLineEffect.Stop(); var quarter = new[] { baseEntLayer.GetLeft().GetFront(), baseEntLayer.GetLeft().GetBack(), baseEntLayer.GetRight().GetBack(), baseEntLayer.GetRight().GetFront() }.ToList(); Console.WriteLine("Random color All / All"); quarter.SetRandomColor(cst.Token, IteratorEffectMode.All, IteratorEffectMode.All, waitTime: () => TimeSpan.FromMilliseconds(500)); cst = WaitCancelAndNext(cst); Console.WriteLine("Flash on lights Cycle / Random"); quarter.FlashQuick(cst.Token, new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Cycle, IteratorEffectMode.Random, waitTime: () => TimeSpan.FromMilliseconds(50)); cst = WaitCancelAndNext(cst); Console.WriteLine("SetColor white Single / Single"); quarter.SetColor(cst.Token, new RGBColor("FFFFFF"), IteratorEffectMode.Single, IteratorEffectMode.Single, waitTime: () => TimeSpan.FromMilliseconds(200)); cst = WaitCancelAndNext(cst); Console.WriteLine("Flash on lights Cycle / All"); quarter.FlashQuick(cst.Token, new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Cycle, IteratorEffectMode.All, waitTime: () => TimeSpan.FromMilliseconds(50)); cst = WaitCancelAndNext(cst); Console.WriteLine("Flash on lights Cycle / Single"); quarter.FlashQuick(cst.Token, new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Cycle, IteratorEffectMode.Single, waitTime: () => TimeSpan.FromMilliseconds(50)); cst = WaitCancelAndNext(cst); Console.WriteLine("Random color Cycle / All"); quarter.SetRandomColor(cst.Token, IteratorEffectMode.Cycle, IteratorEffectMode.All, waitTime: () => TimeSpan.FromMilliseconds(500)); cst = WaitCancelAndNext(cst); Console.WriteLine("Random color Cycle / AllIndividual"); quarter.SetRandomColor(cst.Token, IteratorEffectMode.Cycle, IteratorEffectMode.AllIndividual, waitTime: () => TimeSpan.FromMilliseconds(500)); cst = WaitCancelAndNext(cst); Console.WriteLine("Random color Cycle / Single"); quarter.SetRandomColor(cst.Token, IteratorEffectMode.Cycle, IteratorEffectMode.Single, waitTime: () => TimeSpan.FromMilliseconds(500)); cst = WaitCancelAndNext(cst); Console.WriteLine("Random color Cycle / Random"); quarter.SetRandomColor(cst.Token, IteratorEffectMode.Cycle, IteratorEffectMode.Random, waitTime: () => TimeSpan.FromMilliseconds(500)); cst = WaitCancelAndNext(cst); Console.WriteLine("Random color Cycle / Bounce"); quarter.SetRandomColor(cst.Token, IteratorEffectMode.Cycle, IteratorEffectMode.Bounce, waitTime: () => TimeSpan.FromMilliseconds(500)); cst = WaitCancelAndNext(cst); Console.WriteLine("Random color on all lights"); baseEntLayer.To2DGroup().SetRandomColor(cst.Token, IteratorEffectMode.All, waitTime: () => TimeSpan.FromMilliseconds(500)); cst = WaitCancelAndNext(cst); //Uncomment for demo using a secondary layer //var secondGroup = stream.GetNewLayer(); //secondGroup.FlashQuick(new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Cycle, waitTime: TimeSpan.FromMilliseconds(500)); cst = WaitCancelAndNext(cst); //Group demo //Console.WriteLine("Group demo"); ////var groups = new List<IEnumerable<EntertainmentLight>>() { line1, line2, line3, line4, line5 }; //var groups = allLightsOrderedFlat.ChunkBy(5); //var groupstest = allLightsOrderedFlat.ChunkByGroupNumber(4); //groups.IteratorEffect(async (current, duration) => { // //var r = new Random(); // //var color = new RGBColor(r.NextDouble(), r.NextDouble(), r.NextDouble()); // //current.SetState(color, 1); // current.SetRandomColor(IteratorEffectMode.All, TimeSpan.FromMilliseconds(5000), duration: duration); //}, IteratorEffectMode.All, TimeSpan.FromMilliseconds(500)); //cst = WaitCancelAndNext(cst); //Random color from center Console.WriteLine("Fill white color from center"); await orderedByDistance.SetColor(cst.Token, new RGBColor("FFFFFF"), IteratorEffectMode.Single, waitTime : () => TimeSpan.FromMilliseconds(50)); cst = WaitCancelAndNext(cst); //Random color from center Console.WriteLine("Fill red color order by angle from center"); await orderedByAngle.SetColor(cst.Token, new RGBColor("FF0000"), IteratorEffectMode.Single, waitTime : () => TimeSpan.FromMilliseconds(50)); cst = WaitCancelAndNext(cst); Console.WriteLine("A pulse of random color is placed on an XY grid, matching your entertainment setup"); var randomPulseEffect = new RandomPulseEffect(); baseEntLayer.PlaceEffect(randomPulseEffect); randomPulseEffect.Start(); cst = WaitCancelAndNext(cst); randomPulseEffect.Stop(); Console.WriteLine("A pulse of random color is placed on an XY grid, matching your entertainment setup"); var randomPulseEffectNoFade = new RandomPulseEffect(false); baseEntLayer.PlaceEffect(randomPulseEffectNoFade); randomPulseEffectNoFade.Start(); cst = WaitCancelAndNext(cst); randomPulseEffectNoFade.Stop(); Console.WriteLine("Different random colors on all lights"); baseEntLayer.To2DGroup().SetRandomColor(cst.Token, IteratorEffectMode.AllIndividual, waitTime: () => TimeSpan.FromMilliseconds(500)); cst = WaitCancelAndNext(cst); Console.WriteLine("Trailing light effect with transition times"); allLightsOrdered.Flash(cst.Token, new Q42.HueApi.ColorConverters.RGBColor("FF0000"), IteratorEffectMode.Cycle, waitTime: () => TimeSpan.FromMilliseconds(500), transitionTimeOn: () => TimeSpan.FromMilliseconds(1000), transitionTimeOff: () => TimeSpan.FromMilliseconds(1000), waitTillFinished: false); cst = WaitCancelAndNext(cst); Console.WriteLine("Knight rider (works best with 6+ lights)"); allLightsOrdered.KnightRider(cst.Token); cst = WaitCancelAndNext(cst); Ref <TimeSpan> waitTime = TimeSpan.FromMilliseconds(750); Console.WriteLine("Flash lights (750ms), press enter to decrease by 200 ms"); allLightsOrdered.FlashQuick(cst.Token, new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Cycle, waitTime: () => waitTime); Console.ReadLine(); waitTime.Value -= TimeSpan.FromMilliseconds(200); Console.WriteLine($"Flash ({waitTime.Value.TotalMilliseconds})"); Console.ReadLine(); waitTime.Value -= TimeSpan.FromMilliseconds(200); Console.WriteLine($"Flash ({waitTime.Value.TotalMilliseconds})"); Console.ReadLine(); waitTime.Value -= TimeSpan.FromMilliseconds(200); Console.WriteLine($"Flash ({waitTime.Value.TotalMilliseconds})"); Console.ReadLine(); waitTime.Value -= TimeSpan.FromMilliseconds(100); Console.WriteLine($"Flash ({waitTime.Value.TotalMilliseconds})"); cst = WaitCancelAndNext(cst); Console.WriteLine("Flash on random lights"); allLightsOrdered.FlashQuick(cst.Token, new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Random, waitTime: () => waitTime); cst = WaitCancelAndNext(cst); Console.WriteLine("Flash on ALL lights"); waitTime.Value = TimeSpan.FromMilliseconds(150); allLightsOrdered.Flash(cst.Token, new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.All, waitTime: () => waitTime); cst = WaitCancelAndNext(cst); Console.WriteLine("Flash effect with transition times"); baseEntLayer.GetLeft().To2DGroup().Flash(cst.Token, new Q42.HueApi.ColorConverters.RGBColor("FF0000"), IteratorEffectMode.All, waitTime: () => TimeSpan.FromSeconds(1), transitionTimeOn: () => TimeSpan.FromMilliseconds(1000), transitionTimeOff: () => TimeSpan.FromMilliseconds(1000)); await Task.Delay(2000); baseEntLayer.GetRight().To2DGroup().Flash(cst.Token, new Q42.HueApi.ColorConverters.RGBColor("FF0000"), IteratorEffectMode.All, waitTime: () => TimeSpan.FromSeconds(1), transitionTimeOn: () => TimeSpan.FromMilliseconds(1000), transitionTimeOff: () => TimeSpan.FromMilliseconds(1000)); cst = WaitCancelAndNext(cst); Console.WriteLine("A red light that is moving in vertical direction and is placed on an XY grid, matching your entertainment setup"); var redLightEffect = new RedLightEffect(); redLightEffect.Radius = 0.7; redLightEffect.Y = -0.8; redLightEffect.X = -0.8; baseEntLayer.PlaceEffect(redLightEffect); redLightEffect.Start(); Task.Run(async() => { double step = 0.2; while (true) { redLightEffect.Y += step; await Task.Delay(100); if (redLightEffect.Y >= 2) { step = -0.1; } if (redLightEffect.Y <= -2) { step = +0.1; } } }, cst.Token); cst = WaitCancelAndNext(cst); redLightEffect.Stop(); Console.WriteLine("Thank you for using Q42.Hue.Streaming. This library was developed during Christmas 2017."); await allLightsOrdered.Christmas(cst.Token); cst = WaitCancelAndNext(cst); Console.WriteLine("Press Enter to Exit"); Console.ReadLine(); }
public async Task Start() { //string ip = "192.168.0.4"; //string key = "8JwWAj5J1tSsKLxyUOdAkWmcCQFcNc51AKRhxdH9"; //string entertainmentKey = "AFFD322C34C993C19503D369481869FD"; //var useSimulator = false; //string ip = "10.42.39.194"; //string key = "tocjq6GmPJ8KX5DyLDKXQreZE6txQVQ5oBqbYDFn"; //string entertainmentKey = "DB088F63639524B5A8CDC8AEEAC9C322"; //var useSimulator = false; string ip = "127.0.0.1"; string key = "aSimulatedUser"; string entertainmentKey = "01234567890123456789012345678901"; var useSimulator = true; //Initialize streaming client StreamingHueClient client = new StreamingHueClient(ip, key, entertainmentKey); //Get the entertainment group var all = await client.LocalHueClient.GetEntertainmentGroups(); var group = all.FirstOrDefault(); if (group == null) { throw new Exception("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample"); } else { Console.WriteLine($"Using Entertainment Group {group.Id}"); } //Create a streaming group var entGroup = new StreamingGroup(group.Locations); entGroup.IsForSimulator = useSimulator; //Connect to the streaming group await client.Connect(group.Id, simulator : useSimulator); //Start auto updating this entertainment group client.AutoUpdate(entGroup, 50); //Optional: calculated effects that are placed in the room client.AutoCalculateEffectUpdate(entGroup); //Optional: Check if streaming is currently active var bridgeInfo = await client.LocalHueClient.GetBridgeAsync(); Console.WriteLine(bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active"); //Order lights based on position in the room var orderedLeft = entGroup.GetLeft().OrderByDescending(x => x.LightLocation.Y).ThenBy(x => x.LightLocation.X); var orderedRight = entGroup.GetRight().OrderByDescending(x => x.LightLocation.Y).ThenByDescending(x => x.LightLocation.X); var allLightsOrdered = orderedLeft.Concat(orderedRight.Reverse()).ToArray(); var allLightsReverse = allLightsOrdered.ToList(); allLightsReverse.Reverse(); CancellationTokenSource cst = new CancellationTokenSource(); Console.WriteLine("Random color on all lights"); entGroup.SetRandomColor(IteratorEffectMode.All, TimeSpan.FromMilliseconds(250), cancellationToken: cst.Token); cst = WaitCancelAndNext(cst); Console.WriteLine("Different random colors on all lights"); entGroup.SetRandomColor(IteratorEffectMode.AllIndividual, TimeSpan.FromMilliseconds(250), cancellationToken: cst.Token); cst = WaitCancelAndNext(cst); Console.WriteLine("Knight rider (works best with 6+ lights)"); allLightsOrdered.KnightRider(cancellationToken: cst.Token); cst = WaitCancelAndNext(cst); Ref <TimeSpan?> waitTime = TimeSpan.FromMilliseconds(750); Console.WriteLine("Flash lights (750ms), press enter to decrease by 200 ms"); allLightsOrdered.FlashQuick(new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Cycle, waitTime: waitTime, cancellationToken: cst.Token); Console.ReadLine(); waitTime.Value -= TimeSpan.FromMilliseconds(200); Console.WriteLine($"Flash ({waitTime.Value.Value.TotalMilliseconds})"); Console.ReadLine(); waitTime.Value -= TimeSpan.FromMilliseconds(200); Console.WriteLine($"Flash ({waitTime.Value.Value.TotalMilliseconds})"); Console.ReadLine(); waitTime.Value -= TimeSpan.FromMilliseconds(200); Console.WriteLine($"Flash ({waitTime.Value.Value.TotalMilliseconds})"); Console.ReadLine(); waitTime.Value -= TimeSpan.FromMilliseconds(100); Console.WriteLine($"Flash ({waitTime.Value.Value.TotalMilliseconds})"); cst = WaitCancelAndNext(cst); Console.WriteLine("Flash on random lights"); allLightsOrdered.FlashQuick(new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Random, waitTime: waitTime, cancellationToken: cst.Token); cst = WaitCancelAndNext(cst); Console.WriteLine("Flash on ALL lights"); waitTime.Value = TimeSpan.FromMilliseconds(150); allLightsOrdered.Flash(new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.All, waitTime: waitTime, cancellationToken: cst.Token); cst = WaitCancelAndNext(cst); Console.WriteLine("Flash effect with transition times"); entGroup.GetLeft().Flash(new Q42.HueApi.ColorConverters.RGBColor("FF0000"), IteratorEffectMode.All, waitTime: TimeSpan.FromSeconds(1), transitionTimeOn: TimeSpan.FromMilliseconds(1000), transitionTimeOff: TimeSpan.FromMilliseconds(1000), cancellationToken: cst.Token); await Task.Delay(2000); entGroup.GetRight().Flash(new Q42.HueApi.ColorConverters.RGBColor("FF0000"), IteratorEffectMode.All, waitTime: TimeSpan.FromSeconds(1), transitionTimeOn: TimeSpan.FromMilliseconds(1000), transitionTimeOff: TimeSpan.FromMilliseconds(1000), cancellationToken: cst.Token); cst = WaitCancelAndNext(cst); //Console.WriteLine("Or build your own effects"); //Task.Run(async () => //{ // while (true && !cst.Token.IsCancellationRequested) // { // entGroup.SetState(new RGBColor("0000FF"), 1, TimeSpan.FromSeconds(4), cancellationToken: cst.Token); // await Task.Delay(TimeSpan.FromSeconds(5)); // entGroup.SetState(new RGBColor("FF0000"), 0.6, TimeSpan.FromSeconds(4), cancellationToken: cst.Token); // await Task.Delay(TimeSpan.FromSeconds(5)); // } //}, cst.Token); //cst = WaitCancelAndNext(cst); Console.WriteLine("A red light that is moving in horizontal direction and is placed on an XY grid, matching your entertainment setup"); var redLightEffect = new RedLightEffect(); redLightEffect.Radius = 0.3; redLightEffect.Y = -0.8; redLightEffect.X = -0.8; entGroup.PlaceEffect(redLightEffect); redLightEffect.Start(); Task.Run(async() => { double step = 0.2; while (true) { redLightEffect.Y += step; await Task.Delay(100); if (redLightEffect.Y >= 2) { step = -0.1; } if (redLightEffect.Y <= -2) { step = +0.1; } } }, cst.Token); cst = WaitCancelAndNext(cst); redLightEffect.Stop(); Console.WriteLine("Thank you for using Q42.Hue.Streaming. This library was developed during Christmas 2017."); await allLightsOrdered.Christmas(cancellationToken : cst.Token); cst = WaitCancelAndNext(cst); Console.WriteLine("Press Enter to Exit"); Console.ReadLine(); }
public static async Task <StreamingGroup> SetupAndReturnGroup(StreamingHueClient client, BridgeData b, CancellationToken ct) { if (client == null || b == null) { throw new ArgumentException("Invalid argument."); } try { var groupId = b.SelectedGroup; if (groupId == null && b.Groups != null && b.Groups.Count > 0) { groupId = b.Groups[0].Id; } if (groupId == null) { return(null); } //Get the entertainment group var group = client.LocalHueClient.GetGroupAsync(groupId).Result; if (group == null) { var groups = b.Groups; if (groups.Count > 0) { groupId = groups[0].Id; group = client.LocalHueClient.GetGroupAsync(groupId).Result; if (group != null) { LogUtil.Write(@$ "Selected first group: {groupId}"); } else { LogUtil.Write(@"Unable to load group, can't connect for streaming."); return(null); } } } //Create a streaming group if (group != null) { var lights = group.Lights; var mappedLights = new List <string>(); foreach (var light in lights) { foreach (var ml in b.Lights) { if (ml.Id == light && ml.TargetSector != -1) { mappedLights.Add(light); } } } var stream = new StreamingGroup(mappedLights); //Connect to the streaming group try { await client.Connect(group.Id); } catch (SocketException e) { LogUtil.Write(@"Exception: " + e.Message); } catch (InvalidOperationException f) { LogUtil.Write("Exception: " + f.Message); } catch (Exception) { LogUtil.Write("Random exception caught."); } //Start auto updating this entertainment group #pragma warning disable 4014 client.AutoUpdate(stream, ct); #pragma warning restore 4014 return(stream); } } catch (SocketException e) { LogUtil.Write("Socket exception occurred, can't return group right now: " + e.Message); } return(null); }
public HueUpdateQueue(IDeviceUpdateTrigger updateTrigger, string lightId, StreamingGroup group) : base(updateTrigger) { _light = group.First(l => l.Id == byte.Parse(lightId)); }
public static async Task <List <StreamingGroup> > SetupAndReturnGroupAsync(string groupName) { var configSection = GetGroupConfigurations(); var currentGroup = configSection.Where(x => x.Name == groupName).FirstOrDefault(); bool demoMode = currentGroup.Name == "DEMO"; bool useSimulator = demoMode ? true : currentGroup.Connections.First().UseSimulator; //Disconnect any current connections Disconnect(); _cts = new CancellationTokenSource(); foreach (var bridgeConfig in currentGroup.Connections) { //Initialize streaming client var client = new LightDJStreamingHueClient(bridgeConfig.Ip, bridgeConfig.Key, bridgeConfig.EntertainmentKey, demoMode); //Get the entertainment group Dictionary <string, LightLocation> locations = null; if (demoMode) { string demoJson = await File.ReadAllTextAsync($"{bridgeConfig.Ip}_{bridgeConfig.GroupId}.json"); locations = JsonConvert.DeserializeObject <Dictionary <string, LightLocation> >(demoJson); _groupId = bridgeConfig.GroupId; } else { var all = await client.LocalHueClient.GetEntertainmentGroups(); var group = all.Where(x => x.Id == bridgeConfig.GroupId).FirstOrDefault(); if (group == null) { throw new Exception($"No Entertainment Group found with id {bridgeConfig.GroupId}. Create one using the Philips Hue App or the Q42.HueApi.UniversalWindows.Sample"); } else { Console.WriteLine($"Using Entertainment Group {group.Id}"); _groupId = group.Id; } locations = group.Locations; } //Create a streaming group var stream = new StreamingGroup(locations); stream.IsForSimulator = useSimulator; //Connect to the streaming group if (!demoMode) { await client.Connect(_groupId, simulator : useSimulator); } //Start auto updating this entertainment group client.AutoUpdate(stream, _cts.Token, 50, onlySendDirtyStates: true); StreamingHueClients.Add(client); StreamingGroups.Add(stream); } var baseLayer = GetNewLayer(isBaseLayer: true); var effectLayer = GetNewLayer(isBaseLayer: false); Layers = new List <EntertainmentLayer>() { baseLayer, effectLayer }; CurrentConnection = currentGroup; EffectSettings.LocationCenter = currentGroup.LocationCenter ?? new LightLocation() { 0, 0, 0 }; //Optional: calculated effects that are placed on this layer baseLayer.AutoCalculateEffectUpdate(_cts.Token); effectLayer.AutoCalculateEffectUpdate(_cts.Token); return(StreamingGroups); }
private static async Task Connect(bool demoMode, bool useSimulator, ConnectionConfiguration bridgeConfig) { var hub = (IHubContext <StatusHub>?)Startup.ServiceProvider.GetService(typeof(IHubContext <StatusHub>)); if (hub == null) { throw new Exception("Unable to get PreviewHub from ServiceProvider"); } await hub.Clients.All.SendAsync("StatusMsg", $"Connecting to bridge {bridgeConfig.Ip}"); try { //Initialize streaming client var client = new LightDJStreamingHueClient(bridgeConfig.Ip, bridgeConfig.Key, bridgeConfig.EntertainmentKey, demoMode); //Get the entertainment group Dictionary <string, LightLocation> locations = new Dictionary <string, LightLocation>(); if (demoMode) { string demoJson = await File.ReadAllTextAsync($"{bridgeConfig.Ip}_{bridgeConfig.GroupId}.json"); locations = JsonConvert.DeserializeObject <Dictionary <string, LightLocation> >(demoJson); _groupId = bridgeConfig.GroupId; } else { var all = await client.LocalHueClient.GetEntertainmentGroups(); var group = all.Where(x => x.Id == bridgeConfig.GroupId).FirstOrDefault(); if (group == null) { throw new Exception($"No Entertainment Group found with id {bridgeConfig.GroupId}. Create one using the Philips Hue App or the Q42.HueApi.UniversalWindows.Sample"); } else { await hub.Clients.All.SendAsync("StatusMsg", $"Using Entertainment Group {group.Id} for bridge {bridgeConfig.Ip}"); Console.WriteLine($"Using Entertainment Group {group.Id}"); _groupId = group.Id; } locations = group.Locations; } //Create a streaming group var stream = new StreamingGroup(locations); stream.IsForSimulator = useSimulator; //Connect to the streaming group if (!demoMode) { await client.Connect(_groupId, simulator : useSimulator); } //Start auto updating this entertainment group client.AutoUpdate(stream, _cts.Token, 50, onlySendDirtyStates: false); StreamingHueClients.Add(client); StreamingGroups.Add(stream); await hub.Clients.All.SendAsync("StatusMsg", $"Succesfully connected to bridge {bridgeConfig.Ip}"); } catch (Exception ex) { await hub.Clients.All.SendAsync("StatusMsg", $"Failed to connect to bridge {bridgeConfig.Ip}, exception: " + ex); throw; } }
public static async Task Setup(CancellationToken token) { var bridges = await HueBridgeDiscovery.FastDiscoveryWithNetworkScanFallbackAsync(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30)); var bridge = bridges.FirstOrDefault(); RegisterEntertainmentResult registeredInfos; // Is the Hue credentials present ? if (!File.Exists(credentialPath)) { Console.WriteLine("No credentials found please press the bridge button"); // Wait for the user to press the link button await Task.Delay(TimeSpan.FromSeconds(30)); var client = new LocalHueClient(bridge.IpAddress); registeredInfos = await client.RegisterAsync("ScreenHueSync", Environment.MachineName, true); hueCredential = new HueCredential() { Username = registeredInfos.Username, Key = registeredInfos.StreamingClientKey }; File.WriteAllText(credentialPath, Newtonsoft.Json.JsonConvert.SerializeObject(hueCredential)); Console.WriteLine("Registration success credentials are :"); Console.WriteLine("Username : "******"Key : " + registeredInfos.StreamingClientKey); } else { hueCredential = Newtonsoft.Json.JsonConvert.DeserializeObject <HueCredential>(File.ReadAllText(credentialPath)); } registeredInfos = new RegisterEntertainmentResult() { Username = hueCredential.Username, StreamingClientKey = hueCredential.Key }; Console.WriteLine("Get client"); Client = new StreamingHueClient(bridge.IpAddress, registeredInfos.Username, registeredInfos.StreamingClientKey); //Get the entertainment group Console.WriteLine("Get entertainment group"); var all = await Client.LocalHueClient.GetEntertainmentGroups(); var group = all.Last(); //Create a streaming group Console.WriteLine("Get streaming group"); StreamingGroup = new StreamingGroup(group.Locations); //Connect to the streaming group Console.WriteLine("Connect to group"); await Client.Connect(group.Id); Console.WriteLine("Done !"); BaseLayer = StreamingGroup.GetNewLayer(true); Ready = true; //Start auto updating this entertainment group _ = Client.AutoUpdate(StreamingGroup, token, 50); }