public UdpTransport(Action <string> commandReceivedAction, byte delimiter) { _commandReceivedAction = commandReceivedAction; _delimiter = delimiter; _workHandle = CrestronInvoke.BeginInvoke(HandleQueue); }
private void ReceiveMsg(object obj, int len) { TCPClient client = (TCPClient)obj; try { if (len > 0) { List <byte> rxd = new List <byte>(len); byte[] temprxd = new byte[len]; Array.Copy(client.IncomingDataBuffer, temprxd, len); rxd.AddRange(temprxd); while (client.DataAvailable) { int morelen = client.ReceiveData(); byte[] morerxd = new byte[morelen]; Array.Copy(client.IncomingDataBuffer, morerxd, len); rxd.AddRange(morerxd); } CrestronInvoke.BeginInvoke(new CrestronSharpHelperDelegate((o) => ParseRxd(rxd.ToArray()))); } } catch (TimeoutException e) { ErrorLog.Exception("Exception: ", e); } client.ReceiveDataAsync(new TCPClientReceiveCallback(ReceiveMsg)); }
private object tRxHandler(object obj) { try { while (true) { string rxmsg = null; try { rxmsg = rxMsgs.Dequeue(10000); if (rxmsg != null) { CrestronInvoke.BeginInvoke(new CrestronSharpHelperDelegate(func => InvokeRxProcessor(rxmsg))); } if (rxMsgs.IsEmpty) { CrestronConsole.PrintLine("RX Thread returning - nothing in queue"); _tRXProcessorIL = 0; return(null); } } catch { CrestronConsole.PrintLine("RX Thread - exception dequeueing"); _tRXProcessorIL = 0; return(null); } } } finally { _tRXProcessorIL = 0; } }
protected void OnPowerEvent(bool state) { if (_PowerEvent != null) { CrestronInvoke.BeginInvoke(new CrestronSharpHelperDelegate(o => _PowerEvent(this, new PowerEventArgs(state)))); } }
public void DecodeMultiplePacketsByteArray(byte[] data) { List <MqttMsgBase> packetsInTheByteArray = new List <MqttMsgBase>(); int numberOfBytesProcessed = 0; int numberOfBytesToProcess = 0; int numberOfBytesReceived = data.Length; byte[] packetByteArray; MqttMsgBase tmpPacket = new MqttMsgSubscribe(); while (numberOfBytesProcessed != numberOfBytesReceived) { int remainingLength = MqttMsgBase.decodeRemainingLength(data); int remainingLenghtIndex = tmpPacket.encodeRemainingLength(remainingLength, data, 1); numberOfBytesToProcess = remainingLength + remainingLenghtIndex; packetByteArray = new byte[numberOfBytesToProcess]; Array.Copy(data, 0, packetByteArray, 0, numberOfBytesToProcess); { byte[] tmp = new byte[data.Length - numberOfBytesToProcess]; Array.Copy(data, numberOfBytesToProcess, tmp, 0, tmp.Length); data = tmp; } numberOfBytesProcessed += numberOfBytesToProcess; MqttMsgBase packet = PacketDecoder.DecodeControlPacket(packetByteArray); //RouteControlPacketDelegate r = new RouteControlPacketDelegate(RouteControlPacketToMethodHandler); //r.Invoke(packet); CrestronInvoke.BeginInvoke(RouteControlPacketToMethodHandler, packet); } }
public void Dial(string chanNum) { if (DialIsRunning || !InitSuccess) { return; } if (DialFunctions == null) { Debug.Console(1, "DevicePresets '{0}', not attached to keypad device. Ignoring channel", Key); return; } DialIsRunning = true; CrestronInvoke.BeginInvoke(o => { foreach (var c in chanNum.ToCharArray()) { if (DialFunctions.ContainsKey(c)) { Pulse(DialFunctions[c]); } CrestronEnvironment.Sleep(DigitSpacingMS); } if (EnterFunction != null) { Pulse(EnterFunction); } DialIsRunning = false; }); }
public void InitiateConnection(string url) { CrestronInvoke.BeginInvoke(o => { try { if (string.IsNullOrEmpty(url)) { Debug.Console(0, this, "Error connecting to Server. No URL specified"); return; } Client = new HttpClient(); Request = new HttpClientRequest(); Client.Verbose = true; Client.KeepAlive = true; Request.Url.Parse(url); Request.RequestType = RequestType.Get; Request.Header.SetHeaderValue("Accept", "text/event-stream"); // In order to get a handle on the response stream, we have to get // the request stream first. Boo Client.BeginGetRequestStream(GetRequestStreamCallback, Request, null); CrestronConsole.PrintLine("Request made!"); } catch (Exception e) { ErrorLog.Notice("Exception occured in AsyncWebPostHttps(): " + e.ToString()); } }); }
/// <summary> /// Pulses a boolean input on a smart object on a specific panel for a period of time. /// </summary> /// <param name="smartID">The ID of the smart object.</param> /// <param name="join">The Join # on the smart object to pulse.</param> /// <param name="millisecondDuration">The duration in milliseconds to pulse the join.</param> /// /// <param name="panel">The <see cref="BasicTriListWithSmartObject"/> to pulse the join on.</param> public void Pulse(uint smartID, uint join, int millisecondDuration, BasicTriListWithSmartObject panel) { if (panels.Contains(panel) && panel.Registered) { CrestronInvoke.BeginInvoke( (o) => panel.SmartObjects[smartID].BooleanInput[join].Pulse(millisecondDuration)); } }
/// <summary> /// Pulses a join on a specific touchpanel for a period of time. /// </summary> /// <param name="join">The join # to pulse.</param> /// <param name="millisecondDuration">The duration in milliseconds to pulse the join.</param> /// <param name="panel">The <see cref="BasicTriList"/> to pulse the join on.</param> public void Pulse(uint join, int millisecondDuration, BasicTriList panel) { if (panel.Registered) { CrestronInvoke.BeginInvoke( (o) => panel.BooleanInput[join].Pulse(millisecondDuration)); } }
public static IAsyncResult BeginInvokeEx(this AsyncCallback cb, IAsyncResult asyncResult, AsyncCallback callback, object @object) { var newAr = new AsyncResult(cb, @object); var acs = new AsyncCallbackState(asyncResult, callback, newAr); CrestronInvoke.BeginInvoke(DoCallback, acs); return(newAr); }
/// <summary> /// Pulses a boolean input on a smart object on every panel for a period of time. /// </summary> /// <param name="smartID">The ID of the smart object.</param> /// <param name="join">The Join # on the smart object to pulse.</param> /// <param name="millisecondDuration">The duration in milliseconds to pulse the join.</param> public void Pulse(uint smartID, uint join, int millisecondDuration) { foreach (var panel in panels.OfType <BasicTriListWithSmartObject>()) { if (panel.Registered) { CrestronInvoke.BeginInvoke( (o) => panel.SmartObjects[smartID].BooleanInput[join].Pulse(millisecondDuration)); } } }
/// <summary> /// Pulses a basic boolean input on every touchpanel for a period of time. /// </summary> /// <param name="join">The join # to pulse.</param> /// <param name="millisecondDuration">The duration in milliseconds to pulse the join.</param> public void Pulse(uint join, int millisecondDuration) { foreach (var panel in panels) { if (panel.Registered) { CrestronInvoke.BeginInvoke( (o) => panel.BooleanInput[join].Pulse(millisecondDuration)); } } }
void CommunicationMonitor_StatusChange(object sender, MonitorStatusChangeEventArgs e) { Debug.Console(2, this, "Communication monitor state: {0}", CommunicationMonitor.Status); if (e.Status == MonitorStatus.IsOk) { CrestronInvoke.BeginInvoke((o) => HandleAttributeSubscriptions()); } else if (e.Status != MonitorStatus.IsOk) { StopWatchDog(); } }
void SendSystemMonitorStatusMessage() { Debug.Console(1, "Posting System Monitor Status Message."); // This takes a while, launch a new thread CrestronInvoke.BeginInvoke(o => PostStatusMessage(new { timeZone = SysMon.TimeZoneFeedback.IntValue, timeZoneName = SysMon.TimeZoneTextFeedback.StringValue, ioControllerVersion = SysMon.IoControllerVersionFeedback.StringValue, snmpVersion = SysMon.SnmpVersionFeedback.StringValue, bacnetVersion = SysMon.BaCnetAppVersionFeedback.StringValue, controllerVersion = SysMon.ControllerVersionFeedback.StringValue })); }
/// <summary> /// Private helper method to write formatted message to console prefixed with the assembly identifier. /// </summary> /// <param name="message">Message to be written</param> /// <param name="args">Format arguments for the message</param> private static void InternalWrite(string message, params object[] args) { if (Enable) { try { _writeLock.Enter(); CrestronInvoke.BeginInvoke(_ => _queue.Enqueue(InternalFormat(message, args))); } finally { _writeLock.Leave(); } } }
/// <summary> /// Gets data in separate thread /// </summary> /// <param name="command"></param> void RefreshSystemMonitorData(string command) { // this takes a while, launch a new thread CrestronInvoke.BeginInvoke((o) => { TimeZoneFeedback.FireUpdate(); TimeZoneTextFeedback.FireUpdate(); IOControllerVersionFeedback.FireUpdate(); SnmpVersionFeedback.FireUpdate(); BACnetAppVersionFeedback.FireUpdate(); ControllerVersionFeedback.FireUpdate(); OnSystemMonitorPropertiesChanged(); } ); }
/// <summary> /// Recursive method to receive data /// </summary> /// <param name="server"></param> /// <param name="numBytes"></param> void Receive(UDPServer server, int numBytes) { Debug.Console(2, this, "Received {0} bytes", numBytes); if (numBytes > 0) { var sourceIp = Server.IPAddressLastMessageReceivedFrom; var sourcePort = Server.IPPortLastMessageReceivedFrom; var bytes = server.IncomingDataBuffer.Take(numBytes).ToArray(); var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length); MessageQueue.TryToEnqueue(new GenericUdpReceiveTextExtraArgs(str, sourceIp, sourcePort, bytes)); Debug.Console(2, this, "Bytes: {0}", bytes.ToString()); var bytesHandler = BytesReceived; if (bytesHandler != null) { bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes)); } else { Debug.Console(2, this, "bytesHandler is null"); } var textHandler = TextReceived; if (textHandler != null) { if (StreamDebugging.RxStreamDebuggingIsEnabled) { Debug.Console(0, this, "Recevied: '{0}'", str); } textHandler(this, new GenericCommMethodReceiveTextArgs(str)); } else { Debug.Console(2, this, "textHandler is null"); } } server.ReceiveDataAsync(Receive); // Attempt to enter the CCritical Secion and if we can, start the dequeue thread var gotLock = DequeueLock.TryEnter(); if (gotLock) { CrestronInvoke.BeginInvoke((o) => DequeueEvent()); } }
public void RunRouteAction(string routeKey, string sourceListKey, Action successCallback) { CrestronInvoke.BeginInvoke(o => { Debug.Console(1, this, "Run route action '{0}' on SourceList: {1}", routeKey, sourceListKey); var dict = ConfigReader.ConfigObject.GetSourceListForKey(sourceListKey); if (dict == null) { Debug.Console(1, this, "WARNING: Config source list '{0}' not found", sourceListKey); return; } // Try to get the list item by it's string key if (!dict.ContainsKey(routeKey)) { Debug.Console(1, this, "WARNING: No item '{0}' found on config list '{1}'", routeKey, sourceListKey); return; } var item = dict[routeKey]; foreach (var route in item.RouteList) { DoRoute(route); } // store the name and UI info for routes if (item.SourceKey == "none") { CurrentSourceInfoKey = routeKey; CurrentSourceInfo = null; } else if (item.SourceKey != null) { CurrentSourceInfoKey = routeKey; CurrentSourceInfo = item; } // report back when done if (successCallback != null) { successCallback(); } }); }
public static IAsyncResult BeginInvokeEx(this Delegate dlg, AsyncCallback callback, object obj, params object[] args) { var iar = new AsyncResult(dlg, obj); var invokeInfo = new InvokeInfo { result = iar, callback = callback, state = obj, args = args }; if (_delQueueUserWorkItem != null) { _delQueueUserWorkItem(DoDelegate, invokeInfo); } else { CrestronInvoke.BeginInvoke(DoDelegate, invokeInfo); } return(iar); }
/// <summary> /// InitializeSystem - this method gets called after the constructor has finished. /// </summary> public override void InitializeSystem() { CrestronInvoke.BeginInvoke(o => { try { Debug.WriteProgressLine(this, "Initializing Application Logic."); Debug.WriteDebugLine(this, "This message is only written if debugging is enabled."); Logger.LogWarning(this, "This message is written to the console if debug warnings are enabled and to the registered LogWriters if Warnings are enabled in the Logger."); Debug.WriteProgressLine(this, "Application Initialized."); } catch (Exception e) { this.LogException(e, "Exception while initializing application."); } }); }
//===================// Methods //===================// /** * Method: initializeSystem * Access: internal * @return: void * Description: Invoked by startupTimer to give all SIMPL modules time to register with Core class. * This method then calls individual Initialize functions on registered subclasses. */ internal static void initializeSystem() { int count; count = ZoneList.Count; for (int i = 0; i < count; i++) { CrestronInvoke.BeginInvoke(unused => { ZoneList[i].registerAssets(); }); } // Link displays to zones count = DisplayList.Count; for (int i = 0; i < count; i++) { ushort zid = DisplayList[i].zoneID; if (Zones.ContainsKey(zid)) { if (!Zones[zid].hasDisplay) { Zones[zid].associateDisplay(DisplayList[i]); } else { ConsoleMessage(String.Format("[ERROR] Error associating Display with ZoneID {0}: Zone already has Display.", zid)); } } else { ConsoleMessage(String.Format("[ERROR] Error associating Display with ZoneID {0}: Zone not found.", zid)); } } // Link lifts to zones count = LiftList.Count; for (int i = 0; i < count; i++) { ushort zid = LiftList[i].zoneID; if (Zones.ContainsKey(zid)) { Zones[zid].associateLift(LiftList[i]); } } }
/** * Method: InitializeInterfaces * Access: public * @return: void * Description: Creates threads to initialize all Interface objects */ internal static void InitializeInterfaces() { int count = InterfaceList.Count; for (int i = 0; i < count; i++) { CrestronInvoke.BeginInvoke(unused => { if (InterfaceList[i] != null) { InterfaceList[i].Initialize(); } else { ConsoleMessage(String.Format("[ERROR] Error initializing Interface {0}: Object is Null.", InterfaceList[i].id)); } }); } }
/// <summary> /// Secure Server Socket Status Changed Callback /// </summary> /// <param name="mySecureTCPServer"></param> /// <param name="clientIndex"></param> /// <param name="serverSocketStatus"></param> void SecureServer_SocketStatusChange(SecureTCPServer server, uint clientIndex, SocketStatus serverSocketStatus) { try { // Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange Index:{0} status:{1} Port:{2} IP:{3}", clientIndex, serverSocketStatus, this.SecureServer.GetPortNumberServerAcceptedConnectionFromForSpecificClient(clientIndex), this.SecureServer.GetLocalAddressServerAcceptedConnectionFromForSpecificClient(clientIndex)); if (serverSocketStatus != SocketStatus.SOCKET_STATUS_CONNECTED) { Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "SecureServerSocketStatusChange ConnectedCLients: {0} ServerState: {1} Port: {2}", SecureServer.NumberOfClientsConnected, SecureServer.State, SecureServer.PortNumber); if (ConnectedClientsIndexes.Contains(clientIndex)) { ConnectedClientsIndexes.Remove(clientIndex); } if (HeartbeatRequired && HeartbeatTimerDictionary.ContainsKey(clientIndex)) { HeartbeatTimerDictionary[clientIndex].Stop(); HeartbeatTimerDictionary[clientIndex].Dispose(); HeartbeatTimerDictionary.Remove(clientIndex); } if (ClientReadyAfterKeyExchange.Contains(clientIndex)) { ClientReadyAfterKeyExchange.Remove(clientIndex); } if (WaitingForSharedKey.Contains(clientIndex)) { WaitingForSharedKey.Remove(clientIndex); } if (SecureServer.MaxNumberOfClientSupported > SecureServer.NumberOfClientsConnected) { Listen(); } } } catch (Exception ex) { Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Change Callback. Error: {0}", ex); } //Use a thread for this event so that the server state updates to listening while this event is processed. Listening must be added to the server state //after every client connection so that the server can check and see if it is at max clients. Due to this the event fires and server listening enum bit flag //is not set. Putting in a thread allows the state to update before this event processes so that the subscribers to this event get accurate isListening in the event. CrestronInvoke.BeginInvoke(o => onConnectionChange(clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex)), null); }
/// <summary> /// InitializeSystem - this method gets called after the constructor has finished. /// </summary> public override void InitializeSystem() { CrestronInvoke.BeginInvoke(o => { try { Debug.WriteProgressLine(this, "Initializing Application Logic."); Debug.WriteDebugLine(this, "This message is only written if debugging is enabled."); ConsoleBase.UseProgramSlotAsHeader(); Debug.WriteDebugLine(this, "Now messages have the program slot prepended."); Logger.LogWarning(this, "This message is written to the console if debug warnings are enabled and to the registered LogWriters if Warnings are enabled in the Logger."); Debug.WriteProgressLine(this, "Application Initialized."); Debug.WriteDebugLine(this, "Testing issue-14 Text with {} braces. { \"Value\": true }"); } catch (Exception e) { this.LogException(e, "Exception while initializing application."); } }); }
//public SacnSlave() //{ //} public void InitializeFields(ushort universe) { if (universe >= 1 && universe <= 63999) { Universe = universe; Root = new CommonE1_31.RootLayer(); byte[] RootLayerOctets = Root.RootLayerPacket; Frame = new CommonE1_31.FramingLayer("", universe); byte[] FramingLayerOctets = Frame.FramingLayerPacket; Dmp = new CommonE1_31.DmpLayer(); byte[] DmpLayerOctets = Dmp.DmpLayerPacket; //E131Packet = CommonE1_31.ConcatBytes(new byte[][] { RootLayerOctets, FramingLayerOctets, DmpLayerOctets }); DmxData = new ushort[512]; CrestronInvoke.BeginInvoke(StartUdpThread); } else { ErrorLog.Error(this.ToString()); } }
// Methods #region SendStuff private object tSendData(object sender) { try { while (true) { while (!_StoppingFlag) { string tempmsg = null; try { tempmsg = txMsgs.Dequeue(10000); //CrestronConsole.PrintLine("tSendData Dequeued"); if (tempmsg != null) { CrestronInvoke.BeginInvoke(new CrestronSharpHelperDelegate(o => InvokeSendData(tempmsg))); } if (txMsgs.IsEmpty) { //CrestronConsole.PrintLine("TX Thread returning - nothing in queue"); _tSendDataIL = 0; return(null); } } catch { _tSendDataIL = 0; } } } } finally { _tSendDataIL = 0; } }
/// <summary> /// Used to check if the TouchEventReceived event needs to be invoked and hands the signal data off to be processed. /// </summary> private object ProcessInputQueue(object obj) { while (IsStarted) { try { var action = panelProcessingQueue.Dequeue(); CrestronInvoke.BeginInvoke((s) => { if (TouchEventReceived != null) { TouchEventReceived.Invoke(this, new EventArgs()); } }); if (action != null) { action.Invoke(); } } catch (System.Threading.ThreadAbortException) { CrestronConsole.PrintLine("Thread exiting: {0}", processingThread.Name); if (IsStarted && !Disposed) { ErrorLog.Notice("Touchpanel Input Thread exited prematurely: {0}", processingThread.Name); } } catch (Exception ex) { if (UserCodeExceptionEncountered != null) { UserCodeExceptionEncountered(this, new UnhandledExceptionEventArgs(ex, false)); } } } return(obj); }
private void Resubscribe() { Debug.Console(0, this, "Issue Detected with device subscriptions - resubscribing to all controls"); StopWatchDog(); CrestronInvoke.BeginInvoke((o) => HandleAttributeSubscriptions()); }
private void Port_LineReceived(object dev, GenericCommMethodReceiveTextArgs args) { if (Debug.Level == 2) { Debug.Console(2, this, "RX: '{0}'", ShowHexResponse ? ComTextHelper.GetEscapedText(args.Text) : args.Text); } //Debug.Console(1, this, "RX: '{0}'", args.Text); try { DeviceRx = args.Text; CommandPassthruFeedback.FireUpdate(); if (args.Text.IndexOf("Welcome to the Tesira Text Protocol Server...", StringComparison.Ordinal) > -1) { // Indicates a new TTP session // moved to CustomActivate() method CommunicationMonitor.Start(); CrestronInvoke.BeginInvoke((o) => HandleAttributeSubscriptions()); } else if (args.Text.IndexOf("! ", StringComparison.Ordinal) > -1) { // response is from a subscribed attribute //(if(args.Text const string pattern = "! [\\\"](.*?[^\\\\])[\\\"] (.*)"; var match = Regex.Match(args.Text, pattern); if (!match.Success) { return; } var customName = match.Groups[1].Value; var value = match.Groups[2].Value; AdvanceQueue(args.Text); foreach (var controlPoint in Faders.Where(controlPoint => customName == controlPoint.Value.LevelCustomName || customName == controlPoint.Value.MuteCustomName)) { controlPoint.Value.ParseSubscriptionMessage(customName, value); return; } foreach (var controlPoint in Dialers.Where(controlPoint => customName == controlPoint.Value.AutoAnswerCustomName || customName == controlPoint.Value.ControlStatusCustomName || customName == controlPoint.Value.DialerCustomName)) { controlPoint.Value.ParseSubscriptionMessage(customName, value); return; } foreach (var controlPoint in States.Where(controlPoint => customName == controlPoint.Value.StateCustomName)) { controlPoint.Value.ParseSubscriptionMessage(customName, value); return; } foreach (var controlPoint in Switchers.Where(controlPoint => customName == controlPoint.Value.SelectorCustomName)) { controlPoint.Value.ParseSubscriptionMessage(customName, value); return; } foreach (var controlPoint in Meters.Where(controlPoint => customName == controlPoint.Value.MeterCustomName)) { controlPoint.Value.ParseSubscriptionMessage(customName, value); return; } // same for dialers // same for switchers } else if (args.Text.IndexOf("+OK", StringComparison.Ordinal) > -1) { if (args.Text == "+OK") // Check for a simple "+OK" only 'ack' repsonse or a list response and ignore { return; } // response is not from a subscribed attribute. From a get/set/toggle/increment/decrement command //string pattern = "(?<=\" )(.*?)(?=\\+)"; //string data = Regex.Replace(args.Text, pattern, ""); AdvanceQueue(args.Text); } else if (args.Text.IndexOf("-ERR", StringComparison.Ordinal) > -1) { // Error response Debug.Console(2, this, "Error From DSP: '{0}'", args.Text); switch (args.Text) { case "-ERR ALREADY_SUBSCRIBED": { WatchDogSniffer = false; AdvanceQueue(args.Text); break; } default: { WatchDogSniffer = false; AdvanceQueue(args.Text); break; } } } } catch (Exception e) { if (Debug.Level == 2) { Debug.Console(2, this, "Error parsing response: '{0}'\n{1}", args.Text, e); } } }
/// <summary> /// Fires the update asynchronously within a CrestronInvoke /// </summary> public void InvokeFireUpdate() { CrestronInvoke.BeginInvoke(o => FireUpdate()); }