/// <summary> /// Broadcast text from server to all connected clients /// </summary> /// <param name="text"></param> public void BroadcastText(string text) { CCriticalSection CCBroadcast = new CCriticalSection(); CCBroadcast.Enter(); try { if (ConnectedClientsIndexes.Count > 0) { byte[] b = Encoding.GetEncoding(28591).GetBytes(text); foreach (uint i in ConnectedClientsIndexes) { if (!SharedKeyRequired || (SharedKeyRequired && ClientReadyAfterKeyExchange.Contains(i))) { SocketErrorCodes error = SecureServer.SendDataAsync(i, b, b.Length, (x, y, z) => { }); if (error != SocketErrorCodes.SOCKET_OK && error != SocketErrorCodes.SOCKET_OPERATION_PENDING) { Debug.Console(2, error.ToString()); } } } } CCBroadcast.Leave(); } catch (Exception ex) { CCBroadcast.Leave(); Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Broadcasting messages from server. Error: {0}", ex.Message); } }
public static void Initialize() { // Tell the program we're busy initializing _ready = false; SplusInitializationCompleteFeedback(0); NotifyProgram("Initializing"); //Initalize variables _pushBulletSocket = new WebSocketClient(); _commandMessages = new Dictionary <int, PushBulletMessage>(); _notificationMessages = new Dictionary <int, PushBulletMessage>(); _critSect = new CCriticalSection(); _sendData = new byte[6]; _dataToSend = "Initializing"; //Setup user information _activeUser = new PushBulletUser(); //Setup websocket _pushBulletSocket.Port = 443; _pushBulletSocket.SSL = true; _pushBulletSocket.VerifyServerCertificate = false; _pushBulletSocket.KeepAlive = true; _pushBulletSocket.SendCallBack = OnSendCallback; _pushBulletSocket.ReceiveCallBack = OnReceiveCallback; _sendData = System.Text.Encoding.ASCII.GetBytes(_dataToSend); _receiveData = new byte[_sendData.Length]; //Connect to the server ConnectToServer(); }
internal static void CriticalSection_Leave(CCriticalSection p) { #if !DISABLE_TRACE Trace.MatchObjectWait(p, "CriticalSection_Leave"); #else System.Threading.Monitor.Exit(p); #endif }
internal static SRes CriticalSection_Init(out CCriticalSection p) { p = new CCriticalSection(); #if !DISABLE_TRACE Trace.MatchObjectCreate(p, "CriticalSection_Init"); #endif return SZ_OK; // never fails in C code either }
public Scene(int sceneID, String name) { critSection = new CCriticalSection(); this._sceneID = sceneID; this._storedLoadState = new List <LoadState>(); this._rooms = new List <LightedRoom>(100); this._name = name; this._atLevel = true; }
/// <summary> /// Adds an item to the processor's list of elements. /// </summary> /// <param name="elementID">The 1-based ID of the element, which should match the Simpl+ module parameter's index.</param> /// <param name="elementPath">The path provided by the Simpl+ module parameter.</param> /// <param name="defaultValue">The default value of the element.</param> public void AddValue(ushort elementID, string elementPath, string defaultValue) { using (var secure = new CCriticalSection()) { var element = new SerialElement(elementID, elementPath); element.AttributeValue = defaultValue; Elements.Add(element); } }
/// <summary> /// Adds an item to the processor's list of elements. /// </summary> /// <param name="elementID">The 1-based ID of the element, which should match the Simpl+ module parameter's index.</param> /// <param name="elementPath">The path provided by the Simpl+ module parameter.</param> /// <param name="defaultValue">The default value of the element.</param> public void AddValue(ushort elementID, string elementPath, ushort defaultValue) { using (var secure = new CCriticalSection()) { var element = new DigitalElement(elementID, elementPath); element.AttributeValue = defaultValue > 0 ? true : false; Elements.Add(element); } }
/// <summary> /// Adds a manager to the public static list of managers. /// </summary> /// <param name="processor"></param> public static void AddManager(Manager processor) { using (var secure = new CCriticalSection()) { if (Managers == null) { Managers = new List <Manager>(); } Managers.Add(processor); } }
/// <summary> /// Returns a Manager object, if a manager with a matching ID exists, otherwise returns null. /// </summary> /// <param name="ID">The ID of the manager to return.</param> /// <returns></returns> public static Manager GetManagerByID(ushort ID) { if (Managers == null || Managers.Count <= 0) { return(null); } using (var secure = new CCriticalSection()) { var man = Managers.Where((p) => p.ID == ID).First(); return(man); } }
/// <summary> /// Adds a Serial processor to this manager instance. /// </summary> /// <param name="proc">The processor to add.</param> public void AddSerial(SerialProcessor proc) { using (var secure = new CCriticalSection()) { if (SerialProcessors == null) { SerialProcessors = new List <SerialProcessor>(); } SerialProcessors.Add(proc); Debug.PrintLine("Added serial XML processor."); } }
/// <summary> /// Adds a Digital processor to this manager instance. /// </summary> /// <param name="proc">The processor to add.</param> public void AddDigital(DigitalProcessor proc) { using (var secure = new CCriticalSection()) { if (DigitalProcessors == null) { DigitalProcessors = new List <DigitalProcessor>(); } DigitalProcessors.Add(proc); Debug.PrintLine("Added digital XML processor."); } }
/// <summary> /// Adds a SignedAnalog processor to this manager instance. /// </summary> /// <param name="proc">The processor to add.</param> public void AddSignedAnalog(SignedAnalogProcessor proc) { using (var secure = new CCriticalSection()) { if (SignedAnalogProcessors == null) { SignedAnalogProcessors = new List <SignedAnalogProcessor>(); } SignedAnalogProcessors.Add(proc); Debug.PrintLine("Added signed analog XML processor."); } }
/// <summary> /// Flips the value of the element with the ID provided. 0 > 1 and 1 > 0. /// </summary> /// <param name="elementID">The 1-based ID of the element, which should match the Simpl+ module parameter's index.</param> public void ToggleValue(ushort elementID) { if (elementID < 1) { Debug.PrintLine("Couldn't toggle value for element. The index was invalid."); return; } using (var secure = new CCriticalSection()) { var element = Elements.Where((e) => e.ID == elementID).First(); if (element != null) { element.AttributeValue = !element.AttributeValue; } ReportValueChange(elementID, element.AttributeValue == true ? (ushort)1 : (ushort)0); manager.IsSaveRequired(1); } }
/// <summary> /// Updates the value of an element, both internally as well as to the Simpl+ module. /// </summary> /// <param name="elementID">The 1-based ID of the element, which should match the Simpl+ module parameter's index.</param> /// <param name="value">The new value to use as a short.</param> public void UpdateValue(ushort elementID, short value) { if (elementID < 1) { CrestronConsole.PrintLine("Couldn't update value for element, due to null values."); return; } using (var secure = new CCriticalSection()) { var element = Elements.Where((e) => e.ID == elementID).First(); if (element == null) { //CrestronConsole.PrintLine("Couldn't find element to update Signed Analog value on."); return; } element.AttributeValue = value; ReportValueChange(elementID, element.AttributeValue); manager.IsSaveRequired(1); } }
/// <summary> /// Returns a total number of elements in all the manager's associated processors. /// Primarly used for calculating a progress percentage for save/load operaations. /// </summary> /// <returns></returns> public ushort GetTotalElements() { using (var secure = new CCriticalSection()) { var total = 0; if (DigitalProcessors != null) { for (var i = 0; i < DigitalProcessors.Count; i++) { total += DigitalProcessors[i].Elements.Count; } } if (AnalogProcessors != null) { for (var i = 0; i < AnalogProcessors.Count; i++) { total += AnalogProcessors[i].Elements.Count; } } if (SignedAnalogProcessors != null) { for (var i = 0; i < SignedAnalogProcessors.Count; i++) { total += SignedAnalogProcessors[i].Elements.Count; } } if (SerialProcessors != null) { for (var i = 0; i < SerialProcessors.Count; i++) { total += SerialProcessors[i].Elements.Count; } } if (total == 0) { total = 1; } return((ushort)total); } }
public DebugContextCollection() { DeviceDebugSettingsLock = new CCriticalSection(); DeviceDebugSettings = new Dictionary <string, object>(); Items = new Dictionary <string, DebugContextItem>(); }
/// <summary> /// Loads data from the file and overwrites any existing values. /// </summary> public void LoadFile() { ReportProgress(0); IsLoading(1); ushort step = (ushort)(65535 / GetTotalElements()); ushort current = 0; CrestronConsole.PrintLine(DateTime.Now.ToShortDateString() + "|" + DateTime.Now.ToLongTimeString() + "|Loading xml file: " + FilePath); using (var secure = new CCriticalSection()) { XDocument doc = null; try { var content = Crestron.SimplSharp.CrestronIO.File.ReadToEnd(FilePath, Encoding.UTF8); var start = content.IndexOf("<?xml", 0); if (start < 0) { Debug.PrintLine("Couldn't find xml element to parse in the file."); CrestronConsole.PrintLine(DateTime.Now.ToShortDateString() + "|" + DateTime.Now.ToLongTimeString() + "| Failed to load xml file."); LoadFailure("Invalid XML file couldn't be loaded."); IsLoading(0); return; } content = content.Substring(start); using (var reader = new XmlReader(content, null)) { reader.MoveToContent(); doc = XDocument.Load(reader); } } catch (Exception ex) { Debug.PrintLine("Exception occurred when loading XML document into XDocument variable."); Debug.PrintLine(ex.Message); CrestronConsole.PrintLine(DateTime.Now.ToShortDateString() + "|" + DateTime.Now.ToLongTimeString() + "| Failed to load xml file."); LoadFailure("Couldn't correctly parse the XML document provided."); IsLoading(0); return; } if (doc == null || doc.Root == null || doc.Root.IsEmpty) { CrestronConsole.PrintLine("Couldn't load XML document. No document exists, or the document is empty."); CrestronConsole.PrintLine(DateTime.Now.ToShortDateString() + "|" + DateTime.Now.ToLongTimeString() + "| Failed to load xml file."); LoadFailure("The XML document provided is empty, missing, or invalid."); IsLoading(0); return; } var value = ""; if (DigitalProcessors != null) { for (var i = 0; i < DigitalProcessors.Count; i++) { for (ushort j = 0; j < DigitalProcessors[i].Elements.Count; j++) { value = FindValue(DigitalProcessors[i].Elements[j].AttributePath, ref doc); try { DigitalProcessors[i].UpdateValue(DigitalProcessors[i].Elements[j].ID, value); } catch { LoadFailure("Error processing digital value for path: " + DigitalProcessors[i].Elements[j].AttributePath); Debug.PrintLine("Error processing digital value for path: " + DigitalProcessors[i].Elements[j].AttributePath); } current += step; YieldProgress(current); } } } if (AnalogProcessors != null) { for (var i = 0; i < AnalogProcessors.Count; i++) { for (ushort j = 0; j < AnalogProcessors[i].Elements.Count; j++) { value = FindValue(AnalogProcessors[i].Elements[j].AttributePath, ref doc); try { AnalogProcessors[i].UpdateValue(AnalogProcessors[i].Elements[j].ID, ushort.Parse(value)); } catch { LoadFailure("Error processing analog value for path: " + DigitalProcessors[i].Elements[j].AttributePath); Debug.PrintLine("Error processing analog value for path: " + DigitalProcessors[i].Elements[j].AttributePath); } current += step; YieldProgress(current); } } } if (SignedAnalogProcessors != null) { for (var i = 0; i < SignedAnalogProcessors.Count; i++) { for (ushort j = 0; j < SignedAnalogProcessors[i].Elements.Count; j++) { value = FindValue(SignedAnalogProcessors[i].Elements[j].AttributePath, ref doc); try { SignedAnalogProcessors[i].UpdateValue(SignedAnalogProcessors[i].Elements[j].ID, short.Parse(value)); } catch { LoadFailure("Error processing signed analog value for path: " + DigitalProcessors[i].Elements[j].AttributePath); Debug.PrintLine("Error processing signed analog value for path: " + DigitalProcessors[i].Elements[j].AttributePath); } current += step; YieldProgress(current); } } } if (SerialProcessors != null) { for (var i = 0; i < SerialProcessors.Count; i++) { for (ushort j = 0; j < SerialProcessors[i].Elements.Count; j++) { value = FindValue(SerialProcessors[i].Elements[j].AttributePath, ref doc); try { SerialProcessors[i].UpdateValue(SerialProcessors[i].Elements[j].ID, value); } catch { LoadFailure("Error processing serial value for path: " + DigitalProcessors[i].Elements[j].AttributePath); Debug.PrintLine("Error processing serial value for path: " + DigitalProcessors[i].Elements[j].AttributePath); } current += step; YieldProgress(current); } } } } CrestronConsole.PrintLine(DateTime.Now.ToShortDateString() + "|" + DateTime.Now.ToLongTimeString() + "|Finished loading xml file:" + FileName); LoadSuccess(); IsLoading(0); IsSaveRequired(0); }
/// <summary> /// Used to save the file. If the construction of the XML file fails, it won't overwrite the existing file. /// </summary> public void SaveFile() { IsSaving(1); CrestronConsole.PrintLine(DateTime.Now.ToShortDateString() + "|" + DateTime.Now.ToLongTimeString() + "|Starting XML file saving for file: " + FilePath); using (var secure = new CCriticalSection()) { var builder = new XmlBuilder(RootElement); if (!builder.WriteDigitals(DigitalProcessors)) { SaveFailure("Unable to write all Digital elements."); Debug.PrintLine("Unable to write all Digital elements."); IsSaving(0); return; } if (!builder.WriteAnalogs(AnalogProcessors)) { SaveFailure("Unable to write all Analog elements."); Debug.PrintLine("Unable to write all Analog elements."); IsSaving(0); return; } if (!builder.WriteSignedAnalogs(SignedAnalogProcessors)) { SaveFailure("Unable to write all Signed Analog elements."); Debug.PrintLine("Unable to write all Signed Analog elements."); IsSaving(0); return; } if (!builder.WriteSerials(SerialProcessors)) { SaveFailure("Unable to write all Serial elements."); Debug.PrintLine("Unable to write all Serial elements."); IsSaving(0); return; } try { if (builder.Save(FilePath)) { CrestronConsole.PrintLine(DateTime.Now.ToShortDateString() + "|" + DateTime.Now.ToLongTimeString() + "|XML file: " + FileName + " saved!"); SaveSuccess(); IsSaving(0); IsSaveRequired(0); return; } else { CrestronConsole.PrintLine(DateTime.Now.ToShortDateString() + "|" + DateTime.Now.ToLongTimeString() + "|XML file: " + FileName + " not saved!"); SaveFailure("Error while saving."); IsSaving(0); return; } } catch (Exception ex) { Debug.PrintLine("Exception encountered while saving XML file to disk."); Debug.PrintLine(ex.Message); } } }
private void StartCycleProperty( Func <CTimer> cycleTimerGetter, Action <CTimer> cycleTimerSetter, ushort cyclePropertyTime, Func <bool?> cycleDirectionGetter, Action <bool?> cycleDirectionSetter, Action <Bool> cyclePropertyInProgressSetter, Func <ushort> propertyGetter, Action <ushort> propertySetter, ushort minPropertyValue, ushort maxPropertyValue) { using (new LockScope(_classLock)) { if (cycleTimerGetter() != null) { cycleTimerGetter().Dispose(); cycleTimerSetter(null); } if (propertyGetter().CompareTo(minPropertyValue) < 0 || !PlatformConverter.ToBool(On)) { cycleDirectionSetter(true); } else if (propertyGetter().CompareTo(maxPropertyValue) >= 0) { cycleDirectionSetter(false); } else if (cycleDirectionGetter() == null) { cycleDirectionSetter(true); } int repeatTime = (int)Math.Max(100.0f, (float)cyclePropertyTime / maxPropertyValue); // NOTE: Max 100 because Philips recommends no more than 10 commands per second be sent to a bulb ushort offset = (ushort)Math.Max(1.0f, maxPropertyValue / (cyclePropertyTime / repeatTime)); cyclePropertyInProgressSetter(PlatformConverter.ToPlatformBool(true)); CCriticalSection inProgressLock = new CCriticalSection(); cycleTimerSetter( new CTimer(data => { using (new LockScope(inProgressLock)) { if (cycleTimerGetter() == null) { return; } bool direction = cycleDirectionGetter() == true; if (direction) { if (propertyGetter() >= maxPropertyValue) { using (new LockScope(_classLock)) { if (cycleTimerGetter() != null) { cycleDirectionSetter(false); cycleTimerGetter().Dispose(); cycleTimerSetter(null); } cyclePropertyInProgressSetter(PlatformConverter.ToPlatformBool(false)); } } else { ushort adjustedOffset = (ushort)Math.Min(offset, maxPropertyValue - propertyGetter()); propertySetter((ushort)(propertyGetter() + adjustedOffset)); } } else { if (propertyGetter() <= minPropertyValue) { using (new LockScope(_classLock)) { if (cycleTimerGetter() != null) { cycleDirectionSetter(true); cycleTimerGetter().Dispose(); cycleTimerSetter(null); } cyclePropertyInProgressSetter(PlatformConverter.ToPlatformBool(false)); } } else { ushort adjustedOffset = (ushort)Math.Min(offset, propertyGetter() - minPropertyValue); propertySetter((ushort)(propertyGetter() - adjustedOffset)); } } } }, 5000 /*dummy value until Reset is called below since CTimer doesn't seem to respect the ctor parameter*/)); cycleTimerGetter().Reset(0, (int)repeatTime); } }
public LockScope(CCriticalSection criticalSection) { _criticalSection = criticalSection; _criticalSection.Enter(); }
internal static void CriticalSection_Delete(CCriticalSection p) { #if !DISABLE_TRACE Trace.MatchObjectDestroy(p, "CriticalSection_Delete"); #endif }