public override void ProcessRequest(HttpCwsContext context)
            {
                string resourceUrl = "";

                try
                {
                    resourceUrl = GetResourceUrl(context);
                    string subID = context.Request.RouteData.Values["subid"].ToString();
                    if (server.sublists[COLLECTION_SUBLIST].ContainsKey(subID))
                    {
                        if (context.Request.HttpMethod == "DELETE")
                        {
                            // remove the internal subscription resource
                            server.sublists[COLLECTION_SUBLIST].Remove(subID);
                            CrestronConsole.PrintLine("subscription " + subID + " has been deleted by " + context.Request.UserHostAddress);
                            // send the response
                            context.Response.StatusCode        = 204;
                            context.Response.StatusDescription = "No Content";
                            context.Response.End();
                        }
                        else
                        {
                            RespondWithJsonError(context, 405, "Method Not Allowed", resourceUrl, "allowed methods: " + allowedMethods);
                        }
                    }
                    else
                    {
                        RespondWithJsonError(context, 404, "Not Found", resourceUrl, null);
                    }
                }
                catch (Exception e)
                {
                    CrestronConsole.PrintLine("Could not process request to " + context.Request.Url.AbsolutePath + ": " + e.Message);
                    RespondWithJsonError(context, 500, "Internal Server Error", resourceUrl, null);
                }
                finally
                {
                    CrestronConsole.PrintLine("Served response for " + context.Request.Url.AbsolutePath);
                }
            }
Esempio n. 2
0
        public int ReceiveCallback(byte[] data, uint datalen,
                                   WebSocketClient.WEBSOCKET_PACKET_TYPES opcode,
                                   WebSocketClient.WEBSOCKET_RESULT_CODES error)
        {
            try
            {
                string data_rcv = Encoding.UTF8.GetString(data, 0, data.Length);
                CrestronConsole.PrintLine("[WSClient.ReceiveCallback] data rcv: {0}", data_rcv);

                if (data_rcv.Trim() != "")
                {
                    JObject obj      = JObject.Parse(data_rcv);
                    int     msg_type = int.Parse(obj["msg_type"].ToString());
                    string  dt       = obj["dt"].ToString();
                    switch (msg_type)
                    {
                    case (int)CommonUtil.MSG_TYPE.MSG_PONG:
                        CrestronConsole.PrintLine("[WSClient.ReceiveCallback] rcv PONG");
                        ping_count = 0;
                        break;

                    case (int)CommonUtil.MSG_TYPE.MSG_LIGHT_SWITCH_ONOFF:
                        CrestronConsole.PrintLine("[WSClient.ReceiveCallback] rcv SWITCH ON/OFF");
                        switch_on_off(dt);
                        break;

                    case (int)CommonUtil.MSG_TYPE.MSG_LIGHT_CHANGE_BRIGHTNESS:
                        change_brightness(dt);
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception ex) {
                CrestronConsole.PrintLine("[WSClient.ReceiveCallback] exception : {0}", ex.ToString());
            }
            return(0);
        }
Esempio n. 3
0
        private void SshClientHandler(object src, GenericEventArgs <string> args)
        {
            //TODO response to SSH Client notifications
            string incCallPattern     = @"vtc ringing (?!(stopped)).+ fb";
            string stoppedCallPattern = @"vtc ringing stopped fb";
            string micMutePattern     = @"vtc microphone privacy fb (?=(on|off))\w+";

            if (Regex.IsMatch(args.Value, incCallPattern))
            {
                string[] rx = args.Value.Split(' ');
                CrestronConsole.PrintLine("Incoming call from: {0}", rx[2]);
            }
            else if (Regex.IsMatch(args.Value, stoppedCallPattern))
            {
                CrestronConsole.PrintLine("Incoming call canceled.");
            }
            else if (Regex.IsMatch(args.Value, micMutePattern))
            {
                string[] rx = args.Value.Split(' ');
                CrestronConsole.PrintLine("Mic mute is {0}", rx[rx.Length - 1]);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Called once a button has been pressed and invokes any notifications
        /// and starts timers for holds etc
        /// </summary>
        protected virtual void OnPress()
        {
            _pressState = true;

            if (HoldTime > 0 && holdTimer == null || holdTimer.Disposed)
            {
                this.CurrentHoldTime = 0;
                holdTimer            = new CTimer(holdTimerUpdate, null, 100, 100);
            }

#if DEBUG
            CrestronConsole.PrintLine("OnPress() - {0}, Digital Join {1}", this.GetType().ToString(),
                                      this.PressDigitalJoin.Number);
#endif

            if (_buttonEvent != null)
            {
                _buttonEvent(this,
                             new UIObjectButtonEventArgs(
                                 UIButtonEventType.Pressed, this.CurrentHoldTime));
            }
        }
Esempio n. 5
0
        public void DMInputChange(Switch device, DMInputEventArgs args)
        {
            switch (args.EventId)
            {
            case DMInputEventIds.SourceSyncEventId:
                try
                {
                    DMPSDmInputChange(dmInput.DmInputPort.SyncDetectedFeedback.BoolValue);
                }
                catch (Exception e)
                {
                    CrestronConsole.PrintLine("Error in Source Sync Feedback Event is: " + e);
                }

                break;

            case DMInputEventIds.VideoDetectedEventId:
                DMInput input2 = switcherInputs[args.Number] as DMInput;
                DMPSVideoSyncChange(input2.VideoDetectedFeedback.BoolValue);
                break;
            }
        }
Esempio n. 6
0
        //process feedback
        private void SetRelayState(RelayState state)
        {
            if (_consoleDebuggingEnabled)
            {
                CrestronConsole.PrintLine($"SetRelayState {state}");
            }
            switch (state)
            {
            case RelayState.TurnedOn:
                _relayStateProperty.Value     = TurnedOnLabel;
                _relayStateIconProperty.Value = _onIcon;
                RaiseTurnedOnEvent();
                break;

            case RelayState.TurningOn:
                _relayStateProperty.Value     = TurningOnLabel;
                _relayStateIconProperty.Value = SpinnerIcon;
                _relayProtocol.SendCustomCommandByName("PowerOn");
                break;

            case RelayState.TurnedOff:
                _relayStateProperty.Value     = TurnedOffLabel;
                _relayStateIconProperty.Value = _offIcon;
                RaiseTurnedOffEvent();
                break;

            case RelayState.TurningOff:
                _relayStateProperty.Value     = TurningOffLabel;
                _relayStateIconProperty.Value = SpinnerIcon;
                _relayProtocol.SendCustomCommandByName("PowerOff");
                break;

            case RelayState.Error:
                _relayStateProperty.Value     = ErrorLabel;
                _relayStateIconProperty.Value = ErrorIcon;
                RaiseErrorEvent();
                break;
            }
        }
 public void MotionInit()
 {
     _foundsensor = false;
     MotionOnline = 0;
     if (HueBridge.Populated == true)
     {
         foreach (var sensor in HueBridge.HueSensors)
         {
             if (sensor.Name == MotionName)
             {
                 MotionId     = Convert.ToUInt16(sensor.Id);
                 _foundsensor = true;
                 GetMotion();
                 break;
             }
         }
         if (_foundsensor == false)
         {
             CrestronConsole.PrintLine("Sensor not found: {0}", MotionName);
         }
     }
 }
Esempio n. 8
0
        private object ReadAndBuildInterfaces(object obj)
        {
            CrestronConsole.PrintLine("Building User Interfaces...");
            SystemConfiguration config = (SystemConfiguration)obj;

            Interfaces = ReflectionHelper.GetUserInterfaces(config, this);

            foreach (var kvp in Interfaces)
            {
                if (Interfaces[kvp.Key].Register() == eDeviceRegistrationUnRegistrationResponse.Success)
                {
                    Interfaces[kvp.Key].OnlineStatusChange += InterfacesOnlineStatusChange;
                    Interfaces[kvp.Key].SigChange          += InterfaceSigChange;
                    CrestronConsole.PrintLine("{0} - {1}", kvp.Key, kvp.Value.GetType().FullName);
                }
                else
                {
                    ErrorLog.Error("Unable to register {0} at ID {1}.", Interfaces[kvp.Key], Interfaces[kvp.Key].ID);
                }
            }
            return(null);
        }
 public void clientReceiveCallback(SecureTCPClient client, int bytes_recvd)
 {
     if (bytes_recvd <= 0) // 0 or negative byte count indicates the connection has been closed
     {
         PrintAndLog("clientReceiveCallback: Could not receive message- connection closed");
     }
     else
     {
         try
         {
             CrestronConsole.PrintLine("Received " + bytes_recvd + " bytes from " + client.AddressClientConnectedTo + " port " + client.PortNumber);
             string received = ASCIIEncoding.ASCII.GetString(client.IncomingDataBuffer, 0, client.IncomingDataBuffer.Length);
             CrestronConsole.PrintLine("Server says: " + received);
         }
         catch (Exception e)
         {
             PrintAndLog("Exception in clientReceiveCallback: " + e.Message);
         }
         // Wait for another message
         client.ReceiveDataAsync(clientReceiveCallback);
     }
 }
Esempio n. 10
0
 /// <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 (!IsInitialized)
     {
         return;
     }
     if (elementID < 1)
     {
         CrestronConsole.PrintLine("Couldn't update value for Signed Analog element. The index was invalid.");
         return;
     }
     try
     {
         if (Elements == null ||
             Elements.Count <= 0 ||
             Elements.Where((e) => e.ID == elementID).Count() == 0)
         {
             Debug.PrintLine("No elements present to update Signed Analog value on.");
             return;
         }
         var element = Elements.Where((e) => e.ID == elementID).First();
         if (element == null)
         {
             Debug.PrintLine("Couldn't find element to update Signed Analog value on.");
             return;
         }
         if (element.AttributeValue != value)
         {
             element.AttributeValue = value;
             ReportValueChange(elementID, element.AttributeValue);
             Manager.SetManagerUpdateRequired(ManagerId, true);
         }
     }
     catch (Exception ex)
     {
         Debug.PrintLine("Exception encountered while updating Signed Analog value.");
         Debug.PrintLine(ex.Message);
     }
 }
Esempio n. 11
0
        public void callback(ScheduledEvent e, ScheduledEventCommon.eCallbackReason r)
        {
            CrestronConsole.PrintLine("scheduler at:{0}", DateTime.Now.ToString());
            string fileName   = "\\NVRAM\\" + this.hostID + "_" + this.schdulerID + ".plist";
            var    xml        = new SceneXML();
            string deviceinfo = xml.parseSceneToDevices(fileName);

            if (e.Name == "scene" + this.schdulerID || e.Name == "device" + this.schdulerID)
            {
                if (openit != null)
                {
                    openit(deviceinfo);
                }
            }
            if (e.Name == "e_scene" + this.schdulerID || e.Name == "e_device" + this.schdulerID)
            {
                if (openit != null)
                {
                    closeit(deviceinfo);
                }
            }
        }
Esempio n. 12
0
        private int ReceiveCallback(byte[] bytes, uint bytesLength, WebSocketClient.WEBSOCKET_PACKET_TYPES opcode, WebSocketClient.WEBSOCKET_RESULT_CODES error)
        {
            if (OnReceive != null)
            {
                try
                {
                    RxBuffer = Encoding.ASCII.GetString(bytes, 0, (int)bytesLength);
                    OnReceive((short)opcode, (short)error);
                }
                catch (Exception ex)
                {
                    CrestronConsole.PrintLine("Exception in ReceiveCallback: {0}", ex.Message);
                }
            }

            if (error == WebSocketClient.WEBSOCKET_RESULT_CODES.WEBSOCKET_CLIENT_SUCCESS)
            {
                wsc.ReceiveAsync();
            }

            return((int)error);
        }
        public uint GetStatisticForTime(uint joinNumber, string time)
        {
            var today2355 = DateTime.Today.AddHours(23).AddMinutes(55);
            var lastYear  = today2355.AddYears(-1);

            var jts     = repoLog.GetByTime(joinNumber, lastYear, today2355);
            var jtsTime = jts.Where(jt => jt.Time == time);

            uint result      = 0;
            uint total       = 0;
            uint totalByTime = 0;

            foreach (var jt in jts)
            {
                total = total + jt.Quantity;
            }

            if (debug)
            {
                CrestronConsole.PrintLine("Total click for input {0} total {1}%\n", joinNumber, total);
            }

            foreach (var jtTime in jtsTime)
            {
                totalByTime = totalByTime + jtTime.Quantity;
            }

            if (debug)
            {
                CrestronConsole.PrintLine("Total click for input {0} for {1} time {2}%\n", joinNumber, time, totalByTime);
            }

            if (total != 0)
            {
                result = totalByTime * 100 / total;
            }

            return(result);
        }
        public uint GetForYear(uint joinNumber)
        {
            uint year   = GetNumberOfClickForYear(joinNumber);
            uint total  = GetAllClickForYear();
            uint result = 0;

            if (total != 0)
            {
                result = (year * 100 / total);
            }

            if (debug)
            {
                CrestronConsole.PrintLine("Total click for input {0} for year {1}\n", joinNumber, year);
            }
            if (debug)
            {
                CrestronConsole.PrintLine("Total click for input {0} for year {1}%\n", joinNumber, result);
            }

            return(result);
        }
        public uint GetForMonth(uint joinNumber)
        {
            uint month  = GetNumberOfClickForMonth(joinNumber);
            uint total  = GetAllClickForMonth();
            uint result = 0;

            if (total != 0)
            {
                result = (month * 100 / total);
            }

            if (debug)
            {
                CrestronConsole.PrintLine("Total click for input {0} for month {1}\n", joinNumber, month);
            }
            if (debug)
            {
                CrestronConsole.PrintLine("Total click for input {0} for month {1}%\n", joinNumber, result);
            }

            return(result);
        }
Esempio n. 16
0
        public void UpdateJSON()
        {
            string     jsonToSave;
            FileStream saveToFile;

            saveToFile = new FileStream(filePath, FileMode.Create);

            try
            {
                jsonToSave = JsonConvert.SerializeObject(data);

                saveToFile.Write(jsonToSave, Encoding.ASCII);
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Error saving Contacts to File, Reason: {0}", e.Message);
            }
            finally
            {
                saveToFile.Close();
            }
        }
Esempio n. 17
0
 public bool MyDeleteUser(string username)
 {
     try
     {
         if (!AdminCheck(adminToken))
         {
             panel.StringInput[SerialInputJoins.DeleteUserErrMsg].StringValue =
                 "You do not have sufficient access to perform this operation";
             return(false);
         }
         // Do not allow self-deletion
         if (username == adminToken.UserName)
         {
             panel.StringInput[SerialInputJoins.DeleteUserErrMsg].StringValue =
                 String.Format("Unable to delete {0} because you are " +
                               "currently authenticated as this user", username);
             return(false);
         }
         if (Authentication.RemoveUserFromSystem(ref adminToken, username))
         {
             CrestronConsole.PrintLine("{0} has been deleted", username);
             return(true);
         }
         else
         {
             panel.StringInput[SerialInputJoins.DeleteUserErrMsg].StringValue =
                 String.Format("{0} could not be deleted", username);
             return(false);
         }
     }
     catch (Exception e)
     {
         WriteError("MyDeleteUser", e, SerialInputJoins.DeleteUserErrMsg);
         return(false);
     }
     finally
     {
     }
 }
Esempio n. 18
0
        /// <summary>
        /// Private method to encode username and password to Base64 string
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>authorization</returns>
        private string EncodeBase64(string username, string password)
        {
            var authorization = "";

            try
            {
                if (!string.IsNullOrEmpty(username))
                {
                    string base64String = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", username, password)));
                    authorization = string.Format("Basic {0}", base64String);
                }
            }
            catch (Exception e)
            {
                var msg = string.Format("EncodeBase64({0}, {1}) failed:\r{2}", username, password, e);
                CrestronConsole.PrintLine(msg);
                ErrorLog.Error(msg);
                return("");
            }

            return(authorization);
        }
Esempio n. 19
0
        public void initializeForecast()
        {
            try
            {
                string jsonString = String.Empty;
                url = string.Format("http://api.wunderground.com/api{0}/forecast/q/TX/Dallas.json", userKey);
                var httpClient = new HttpClient();
                httpClient.KeepAlive = false;
                httpClient.Accept    = "text/html";
                HttpClientRequest httpRequest = new HttpClientRequest();
                httpRequest.Url.Parse(url);

                HttpClientResponse rResponse = httpClient.Dispatch(httpRequest);
                var responseString           = rResponse.ContentString;

                forecastObject = JsonConvert.DeserializeObject <ForecastObject>(responseString);
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Error making request: {0}", e);
            }
        }
Esempio n. 20
0
 /// <summary>
 /// Stop the server
 /// </summary>
 public void Stop()
 {
     try
     {
         _ServerLock.Enter();
         if (_Server != null)
         {
             CrestronConsole.PrintLine("Stopping RESTful CWS API HTTP Server");
             _Server.Unregister();
             _Server = null;
             CrestronConsole.PrintLine("Stopped RESTful CWS API HTTP Server");
         }
         else
         {
             throw new InvalidOperationException("Server was not running");
         }
     }
     finally
     {
         _ServerLock.Leave();
     }
 }
Esempio n. 21
0
 /// <summary>
 /// registers with bridge, authorizes a user based on API key from the pairing
 /// </summary>
 public static void register()
 {
     CrestronConsole.PrintLine("registering with bridge...");
     try
     {
         var registerBridge = new HttpClient();
         registerBridge.KeepAlive = false;
         registerBridge.Accept    = "application/json";
         HttpClientRequest bridgeRequest = new HttpClientRequest();
         string            url           = string.Format("http://{0}/api", BridgeIp);
         bridgeRequest.RequestType = Crestron.SimplSharp.Net.Http.RequestType.Post;
         bridgeRequest.Url.Parse(url);
         bridgeRequest.ContentString = "{\"devicetype\":\"my_hue_app#crestron\"}";
         HttpClientResponse lResponse = registerBridge.Dispatch(bridgeRequest);
         var jsontext = lResponse.ContentString;
         CrestronConsole.PrintLine("response is {0}", jsontext);
         if (jsontext.Contains("link button not pressed"))
         {
             Authorized = false;
             CrestronConsole.PrintLine("Registration incomplete press button and retry...");
         }
         else if (jsontext.Contains("username"))
         {
             Authorized = true;
             JArray data = JArray.Parse(jsontext);
             BridgeApi = (String)data[0]["success"]["username"];
             CrestronConsole.PrintLine("API key is {0}", BridgeApi);
             if (CrestronDataStoreStatic.SetLocalStringValue("apikey", BridgeApi) != CrestronDataStore.CDS_ERROR.CDS_SUCCESS)
             {
                 CrestronConsole.PrintLine("error storing apikey");
             }
             CrestronConsole.PrintLine("Bridge registration complete");
         }
     }
     catch (Exception e)
     {
         CrestronConsole.PrintLine("Exception is {0}", e);
     }
 }
        public uint GetForWeek(uint joinNumber)
        {
            uint week   = GetNumberOfClickForWeek(joinNumber);
            uint total  = GetAllClickForWeek();
            uint result = 0;

            if (total != 0)
            {
                result = (week * 100 / total);
            }

            if (debug)
            {
                CrestronConsole.PrintLine("Total click for input {0} for week {1}\n", joinNumber, week);
            }
            if (debug)
            {
                CrestronConsole.PrintLine("Total click for input {0} for week {1}%\n", joinNumber, result);
            }

            return(result);
        }
Esempio n. 23
0
 public void MotionInit()
 {
     _foundsensor = false;
     MotionOnline = 0;
     if (HueBridge.Populated == true)
     {
         foreach (KeyValuePair <string, HueSensor> entry in HueBridge.HueSensors)
         {
             if (entry.Value.Name == MotionName)
             {
                 MotionId     = Convert.ToUInt16(entry.Key);
                 _foundsensor = true;
                 _sensor      = entry.Value;
                 break;
             }
         }
         if (_foundsensor == false)
         {
             CrestronConsole.PrintLine("Sensor not found: {0}", MotionName);
         }
     }
 }
Esempio n. 24
0
 /*This will take the returned ROOMS and DEVICES JOSN lists and put them into objects
  * for use later*/
 private void SerilizeFunction()
 {
     try
     {
         RoomsObj = JsonConvert.DeserializeObject <Rooms>(_Rooms);
     }
     catch (JsonSerializationException e)
     {
         CrestronConsole.PrintLine("Rooms Obj exception: {0}\n", e.Message);
     }
     try
     {
         DevicesObj = JsonConvert.DeserializeObject <Devices>(_Devices);
     }
     catch (JsonSerializationException e)
     {
         CrestronConsole.PrintLine("Device Obj exception: {0}\n", e.Message);
     }
     //For Debugging REMOVE BEFORE FLIGHT!
     CrestronConsole.PrintLine(_Rooms);
     CrestronConsole.PrintLine(_Devices);
 }
Esempio n. 25
0
        /// <summary>
        /// Gathers all values in the ValueCollection as a compiled HTTP form for submission
        /// </summary>
        public string GetValuesAsContentDisposition()
        {
            StringBuilder results = new StringBuilder();
            string        dispositionValue;

            if (ValueCollection.Count == 0)
            {
                CrestronConsole.PrintLine("SimplTeslaCar.Results.FormValues.GetValueAsContentDisposition()::VALUECOLLECTION IS EMPTY!");
                return("");
            }

            foreach (FormValue fv in ValueCollection)
            {
                dispositionValue = ContentFactory.SetFormContentDisposition(fv.Field, fv.Value);
                results.Append(dispositionValue);
            }


            results.Append(ContentFactory.FinalizeFormDisposition());

            return(results.ToString());
        }
Esempio n. 26
0
        internal bool RegisterLoad(Load load)
        {
            try
            {
                lock (Loads)
                {
                    if (!Loads.ContainsKey(load))
                    {
                        Loads.Add(load, new LevelChangeEvent());

                        if (Processor.RoomInterfaces.ContainsKey(_id))
                        {
                            load.Initialize();
                        }

                        if (_debug)
                        {
                            CrestronConsole.PrintLine("Registered Load ID {0}", load.ID);
                        }

                        return(true);
                    }
                    else
                    {
                        CrestronConsole.PrintLine("Already registered Load ID {0}", load.ID);

                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                if (_debug)
                {
                    ErrorLog.Exception("Exception occured in WattstopperDLM.Processor.RegisterLoad", e);
                }
                return(false);
            }
        }
Esempio n. 27
0
        static internal bool RegisterComponent(Component component)
        {
            try
            {
                lock (Components)
                {
                    if (!Components.ContainsKey(component))
                    {
                        Components.Add(component, new InternalEvents());

                        if (isInitialized && IsConnected)
                        {
                            AddComoponentToChangeGroup addControl;

                            addControl                           = new AddComoponentToChangeGroup();
                            addControl.method                    = "ChangeGroup.AddComponentControl";
                            addControl.ComponentParams           = new AddComponentToChangeGroupParams();
                            addControl.ComponentParams.Component = component;
                            commandQueue.Enqueue(JsonConvert.SerializeObject(addControl));

                            if (debug == 2)
                            {
                                CrestronConsole.PrintLine("Registered {0} Component", component.Name);
                            }
                        }
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                if (debug == 1 || debug == 2)
                {
                    ErrorLog.Error("Error registering QsysClient to the QsysProcessor: {0}", e.Message);
                }
                return(false);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Handle messages for from the driver implementing IMediaPlayer
        /// </summary>
        /// <param name="msgDrv">An inbound CRPC message (including header and potentially incomplete JSON objects</param>
        public void ProcessCrpcMessageFromDrv(SimplSharpString msgDrv)
        {
            // First 8 characters are some sort of identifier
            string msgTrim     = msgDrv.ToString().Substring(8);
            int    msgPreamble = Convert.ToInt32(msgDrv.ToString().Substring(0, 8), 16);

#if DEBUG
            CrestronConsole.PrintLine("<--:{0:x8}", msgPreamble);
#endif

            List <string> jsonObjects;
            _msgLock.Enter();
            try
            {
                jsonObjects = SeparateJsonObjects(_messageFromDrv + msgTrim, out _messageFromDrv);
#if DEBUG
                if (jsonObjects.Count > 0)
                {
                    CrestronConsole.PrintLine("Processing {0} objects from Driver", jsonObjects.Count);
                }
#endif
                foreach (string json in jsonObjects)
                {
                    ProcessCrpcMessage(json);
                }
            }
            catch (Exception e)
            {
#if DEBUG
                CrestronConsole.PrintLine("ProcessCrpcMessageFromDrv blew up when splitting JSON objects: " + e.Message);
#endif
                _messageFromDrv = string.Empty;
            }
            finally
            {
                _msgLock.Leave();
            }
        }
Esempio n. 29
0
        private void StartComPortTest()
        {
            _ComPort.BaudRate_Changed     += (Mode) => { CrestronConsole.PrintLine("{2}DMTX Baud Rate Mode: {0}, {1}", Mode.ToString(), _ComPort.BaudRate.ToString(), _ComPort.Name); };
            _ComPort.DataBits_Changed     += (Mode) => { CrestronConsole.PrintLine("{2}DMTX Data Bits Mode: {0}, {1}", Mode.ToString(), _ComPort.DataBits.ToString(), _ComPort.Name); };
            _ComPort.PresetStringReceived += (Cmd, State) => { CrestronConsole.PrintLine("{2}DMTX Command : {0} State is, {1}.", Cmd.Name, State, _ComPort.Name); };
            _ComPort.Parity_Changed       += (Mode) => { CrestronConsole.PrintLine("{2}DMTX Parity Mode: {0}, {1}", Mode.ToString(), _ComPort.Parity.ToString(), _ComPort.Name); };
            _ComPort.rx_Changed           += (Message) => { CrestronConsole.PrintLine("{2}DMTX RX Message: {0}, {1}", MakePrintable(Message), MakePrintable(_ComPort.rx), _ComPort.Name); };
            _ComPort.StopBits_Changed     += (Mode) => { CrestronConsole.PrintLine("{2}DMTX StopBits Mode: {0}, {1}", Mode.ToString(), _ComPort.StopBits.ToString(), _ComPort.Name); };


            CrestronConsole.AddNewConsoleCommand(SetBaudRate, "TSetBaudRateDMTX", "Set Baud Rate for " + _ComPort.Name, ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(SetDataBits, "TSetDataBitsDMTX", "Set Data Bits for " + _ComPort.Name, ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(SetParity, "TSetParityDMTX", "Set Parity for " + _ComPort.Name, ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(SetStopBits, "TSetStopBitsDMTX", "Set Stop Bits for " + _ComPort.Name, ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(TransmitData, "TTransmitDataDMTX", "Transmit Data for " + _ComPort.Name, ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(GetPresetStatus, "TGetPresetStatusDMTX", "Get Message Status for " + _ComPort.Name, ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(TransmitPreset, "TTransmitPresetDMTX", "Transmit Pre Built Message for " + _ComPort.Name, ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(ChangeDelimiter, "TChangeDelimiterDMTX", "Changing Delimiter for " + _ComPort.Name, ConsoleAccessLevelEnum.AccessOperator);

            _ComPort.delimiter = "\r";

            _ComPort.PresetStrings.Add(new ComPortPresetStrings()
            {
                Name = "ProjOn", Command = "Projector On"
            });
            _ComPort.PresetStrings.Add(new ComPortPresetStrings()
            {
                Name = "ProjOff", Command = "\x01\x02Proj Off"
            });
            _ComPort.PresetStrings.Add(new ComPortPresetStrings()
            {
                Name = "ProjIsOn", Command = "Projector Is On"
            });
            _ComPort.PresetStrings.Add(new ComPortPresetStrings()
            {
                Name = "ProjIsOff", Command = "\x01\x02Proj Is Off"
            });
        }
Esempio n. 30
0
        //===================// Constructor //===================//

        static Core()
        {
            startTime = new Stopwatch();
            startTime.Start();

            Sources         = new Dictionary <ushort, Source>();
            Zones           = new Dictionary <ushort, Zone>();
            Displays        = new Dictionary <ushort, Display>();
            Interfaces      = new Dictionary <ushort, Interface>();
            Lifts           = new Dictionary <ushort, Lift>();
            Lights          = new Dictionary <ushort, Light>();
            Shades          = new Dictionary <ushort, Shade>();
            HVACs           = new Dictionary <ushort, HVAC>();
            SecurityKeypads = new Dictionary <ushort, SecurityKeypad>();

            ZoneList           = new List <Zone>();
            SourceList         = new List <Source>();
            DisplayList        = new List <Display>();
            InterfaceList      = new List <Interface>();
            LiftList           = new List <Lift>();
            LightList          = new List <Light>();
            ShadeList          = new List <Shade>();
            HVACList           = new List <HVAC>();
            SecurityKeypadList = new List <SecurityKeypad>();

            RegZones = RegInterfaces = StartupCounter = 0;

            startupCompleteEvent += new DelegateEmpty(StartupCompleteEventHandler);

            // Begin 30 second timer to allow class objects to register with Core
            startupTimer = new CTimer(startupTimerHandler, startupTickInterval);

            CrestronConsole.PrintLine("..."); // Send newline to console for prettification
            ConsoleMessage("[STARTUP] FrameWork Core Initialized, waiting for assets...");

            // Create default 'Off' Source
            RegisterSource(new Source("Off", 0, 169, 169));
        }