예제 #1
0
        /// <summary>
        /// Process a PLC request and return a PLC response.
        /// </summary>
        /// <param name="request">Request received from network.</param>
        /// <returns>Response to be sent back to the client.</returns>
        public PLCResponse Handle(PLCRequest request)
        {
            switch (request.Command)
            {
            case PLCRequest.CommandPing:
                return(new PLCResponse {
                });

            case PLCRequest.CommandRead:
                Dictionary <string, object> values = null;
                if (request.Keys != null && request.Keys.Length > 0)
                {
                    values = this.memory.Read(request.Keys);
                }
                return(new PLCResponse {
                    Values = values
                });

            case PLCRequest.CommandWrite:
                if (request.Values != null && request.Values.Count > 0)
                {
                    this.memory.Write(request.Values);
                }
                return(new PLCResponse {
                });

            default:
                throw new PLCInvalidCommandException(String.Format("Command {0} is unknown.", request.Command));
            }
        }
예제 #2
0
        private void _RecvAndSend(ResponseSocket socket)
        {
            string      received = socket.ReceiveFrameString(System.Text.Encoding.UTF8);
            PLCResponse response = null;

            try
            {
                // ask service to handle request
                PLCRequest request = JsonConvert.DeserializeObject <PLCRequest>(received, jsonSettings);
                response = this.service.Handle(request);
            }
            catch (PLCService.PLCServiceException e)
            {
                // reply with an error
                response = new PLCResponse
                {
                    Error = new PLCResponse.PLCError {
                        Type = e.Code, Desc = e.Message
                    },
                };
            }
            catch (System.Exception e)
            {
                // reply with an error
                response = new PLCResponse
                {
                    Error = new PLCResponse.PLCError {
                        Type = "unkown", Desc = e.Message
                    },
                };
            }

            // serialize to json and send
            if (response == null)
            {
                response = new PLCResponse();
            }
            string serialized = JsonConvert.SerializeObject(response, Formatting.None, jsonSettings);

            socket.SendFrame(System.Text.Encoding.UTF8.GetBytes(serialized));
        }