Esempio n. 1
0
        internal override async Task <int> InvokeDeviceMethodAsync(
            string deviceId,
            string targetModuleId,
            string methodName,
            ulong directMethodCount,
            CancellationToken none)
        {
            MethodRequest  request = new MethodRequest(methodName, Encoding.UTF8.GetBytes($"{{ \"Message\": \"Hello\", \"DirectMethodCount\": \"{directMethodCount.ToString()}\" }}"));
            MethodResponse result  = await this.moduleClient.InvokeMethodAsync(deviceId, targetModuleId, request);

            return(result.Status);
        }
Esempio n. 2
0
        /// <summary>
        /// Handle unpublish node method call.
        /// </summary>
        public virtual async Task <MethodResponse> HandleUnpublishEventsMethodAsync(MethodRequest methodRequest, object userContext)
        {
            string logPrefix  = "HandleUnpublishEventsMethodAsync:";
            Guid   endpointId = Guid.Empty;
            UnpublishNodesMethodRequestModel unpublishNodesMethodData = null;
            HttpStatusCode statusCode     = HttpStatusCode.OK;
            List <string>  statusResponse = new List <string>();
            string         statusMessage  = string.Empty;

            try
            {
                Logger.Debug($"{logPrefix} called");
                unpublishNodesMethodData = JsonConvert.DeserializeObject <UnpublishNodesMethodRequestModel>(methodRequest.DataAsJson);
                endpointId = new Guid(unpublishNodesMethodData.EndpointId);
            }
            catch (FormatException e)
            {
                statusMessage = $"Exception ({e.Message}) while parsing EndpointId '{unpublishNodesMethodData.EndpointId}'";
                Logger.Error(e, $"{logPrefix} {statusMessage}");
                statusResponse.Add(statusMessage);
                statusCode = HttpStatusCode.InternalServerError;
            }
            catch (Exception e)
            {
                statusMessage = $"Exception ({e.Message}) while deserializing message payload";
                Logger.Error(e, $"{logPrefix} {statusMessage}");
                statusResponse.Add(statusMessage);
                statusCode = HttpStatusCode.InternalServerError;
            }

            var unpublishStatusResponse = new List <string>();

            (statusCode, unpublishStatusResponse) = await UnpublishEventsAsync(endpointId, unpublishNodesMethodData.OpcEvents).ConfigureAwait(false);

            statusResponse.AddRange(unpublishStatusResponse);

            // adjust response size
            AdjustResponse(ref statusResponse);

            // build response
            string resultString = JsonConvert.SerializeObject(statusResponse);

            byte[] result = Encoding.UTF8.GetBytes(resultString);
            if (result.Length > MaxResponsePayloadLength)
            {
                Logger.Error($"{logPrefix} Response size is too long");
                Array.Resize(ref result, result.Length > MaxResponsePayloadLength ? MaxResponsePayloadLength : result.Length);
            }
            MethodResponse methodResponse = new MethodResponse(result, (int)statusCode);

            Logger.Information($"{logPrefix} completed with result {statusCode.ToString()}");
            return(methodResponse);
        }
Esempio n. 3
0
            internal async Task <MethodResponse> MethodCallHandler(MethodRequest methodrequest, object usercontext)
            {
                Preconditions.CheckNotNull(methodrequest, nameof(methodrequest));

                Events.MethodCallReceived(this.cloudProxy.clientId);
                var direceMethodRequest = new DirectMethodRequest(this.cloudProxy.clientId, methodrequest.Name, methodrequest.Data, DeviceMethodMaxResponseTimeout);
                DirectMethodResponse directMethodResponse = await this.cloudListener.CallMethodAsync(direceMethodRequest);

                MethodResponse methodResponse = directMethodResponse.Data == null ? new MethodResponse(directMethodResponse.Status) : new MethodResponse(directMethodResponse.Data, directMethodResponse.Status);

                return(methodResponse);
            }
        static async Task <MethodResponse> GetGatewayInfoMethodCallBack(MethodRequest methodRequest, object userContext)
        {
            Console.WriteLine("Executing GetGatewayInfoMethodCallBack");

            var gatewayInfoResponse = new GatewayInfoResponse {
                responseState = 0
            };

            try
            {
                Console.WriteLine("Getting gateway info...");

                if (_controller == null ||
                    _controller.GatewayController == null)
                {
                    gatewayInfoResponse.responseState = -1;
                }
                else
                {
                    var gatewayInfo = await _controller.GatewayController.GetGatewayInfo();

                    if (gatewayInfo == null)
                    {
                        gatewayInfoResponse.responseState = -2;
                    }
                    else
                    {
                        gatewayInfoResponse.commissioningMode     = gatewayInfo.CommissioningMode;
                        gatewayInfoResponse.currentTimeISO8601    = gatewayInfo.CurrentTimeISO8601;
                        gatewayInfoResponse.firmware              = gatewayInfo.Firmware;
                        gatewayInfoResponse.gatewayID             = gatewayInfo.GatewayID;
                        gatewayInfoResponse.gatewayTimeSource     = gatewayInfo.GatewayTimeSource;
                        gatewayInfoResponse.gatewayUpdateProgress = gatewayInfo.GatewayUpdateProgress;
                        gatewayInfoResponse.homekitID             = gatewayInfo.HomekitID;
                        gatewayInfoResponse.ntp            = gatewayInfo.NTP;
                        gatewayInfoResponse.otaType        = gatewayInfo.OtaType;
                        gatewayInfoResponse.OtaUpdateState = gatewayInfo.OtaUpdateState;
                    }
                }

                Console.WriteLine("Info collected.");
            }
            catch (Exception ex)
            {
                gatewayInfoResponse.errorMessage  = ex.Message;
                gatewayInfoResponse.responseState = -999;
            }

            var json     = JsonConvert.SerializeObject(gatewayInfoResponse);
            var response = new MethodResponse(Encoding.UTF8.GetBytes(json), 200);

            return(response);
        }
Esempio n. 5
0
        private ChangePassword ChangePasswordDefault()
        {
            return((SpxChangePassword model, out MethodResponse response) =>
            {
                response = new MethodResponse();
                try
                {
                    IMember user = null;
                    var token = model.Token.DecryptToken();
                    if (token.IsTokenAvaliable(tokenExpireMins))
                    {
                        user = service.GetByKey((Guid)token.UserKey);
                        model.ForceChange = true;
                    }
                    if (user == null)
                    {
                        user = this.service.GetByUsername(model.UserIdentify);
                    }
                    if (user == null)
                    {
                        user = this.service.GetByEmail(model.UserIdentify);
                    }
                    if (user == null)
                    {
                        user = this.service.GetById(model.UserIdentify.Int32());
                    }
                    if (user == null)
                    {
                        user = this.service.GetByKey(new Guid(model.UserIdentify));
                    }

                    if (user != null && (Membership.ValidateUser(user.Name, model.OldPassword) && model.ForceChange))
                    {
                        goto ChangePassword;
                    }
                    return;

ChangePassword:
                    if (!this.PasswordStrengthCheckFunction(model.NewPassword))
                    {
                        response.Error = "Password not strong";
                    }
                    this.service.SavePassword(user, model.NewPassword);
                    response.IsOk = true;
                    return;
                }
                catch (Exception ex)
                {
                    response.ResponseObject = ex;
                }
            });
        }
Esempio n. 6
0
        static async Task <MethodResponse> DownMethodCallBack(MethodRequest methodRequest, object userContext)
        {
            Console.WriteLine($"Executing DownMethodCallBack at {DateTime.UtcNow}");

            if (methodRequest == null)
            {
                Console.WriteLine($"Moving to initial state");
            }

            var downResponse = new DownResponse {
                responseState = 0
            };

            try
            {
                _liftState = LiftState.MovingDown;

                var task = Task.Run(async() =>
                {
                    await LedScenarios.PlayDownScene(_mcp23xxxWrite, UpDownInterval);
                });

                if (!InDebugMode)
                {
                    _controller.Write(DownRelayPin, PinValue.Low); // start action
                }
                else
                {
                    Console.WriteLine("WARNING: While in debug mode, no DOWN movements are executed!");
                }

                await Task.Delay(UpDownInterval);

                _controller.Write(DownRelayPin, PinValue.High); // stop action

                Console.WriteLine($"Down ended at {DateTime.UtcNow}.");

                _liftState = LiftState.Down;
            }
            catch (Exception ex)
            {
                _liftState = LiftState.Unknown;

                downResponse.errorMessage  = ex.Message;
                downResponse.responseState = -999;
            }

            var json     = JsonConvert.SerializeObject(downResponse);
            var response = new MethodResponse(Encoding.UTF8.GetBytes(json), 200);

            return(response);
        }
Esempio n. 7
0
        public virtual IMessage SyncProcessMessage(IMessage msgRequest)
        {
            IMessage result = null;

            try
            {
                byte[] array  = null;
                byte[] array2 = null;
                CADMethodReturnMessage retmsg = null;
                CADMethodCallMessage   cadmethodCallMessage = CADMethodCallMessage.Create(msgRequest);
                if (cadmethodCallMessage == null)
                {
                    MemoryStream memoryStream = CADSerializer.SerializeMessage(msgRequest);
                    array2 = memoryStream.GetBuffer();
                }
                Context currentContext = Thread.CurrentContext;
                try
                {
                    CrossAppDomainSink.ProcessMessageRes processMessageRes = (CrossAppDomainSink.ProcessMessageRes)AppDomain.InvokeInDomainByID(this._domainID, CrossAppDomainSink.processMessageMethod, null, new object[]
                    {
                        array2,
                        cadmethodCallMessage
                    });
                    array  = processMessageRes.arrResponse;
                    retmsg = processMessageRes.cadMrm;
                }
                finally
                {
                    AppDomain.InternalSetContext(currentContext);
                }
                if (array != null)
                {
                    MemoryStream mem = new MemoryStream(array);
                    result = CADSerializer.DeserializeMessage(mem, msgRequest as IMethodCallMessage);
                }
                else
                {
                    result = new MethodResponse(msgRequest as IMethodCallMessage, retmsg);
                }
            }
            catch (Exception e)
            {
                try
                {
                    result = new ReturnMessage(e, msgRequest as IMethodCallMessage);
                }
                catch (Exception)
                {
                }
            }
            return(result);
        }
Esempio n. 8
0
        private static Task <MethodResponse> GetWeightAsync(MethodRequest methodRequest, object userContext)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");

            userContext = new DeviceData()
            {
                Weight = CurrentWeight
            };
            string         result   = JsonSerializer.Serialize(userContext);
            MethodResponse retValue = new MethodResponse(Encoding.UTF8.GetBytes(result), 200);

            return(Task.FromResult(retValue));
        }
Esempio n. 9
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(1000, stoppingToken);

                // This demo doesn't contain connected users management.
                // Please change null below to correct user identifier and make sure that user is connected before this line is called, otherwise it will hang.
                MethodResponse response = await _rpcCaller.MethodCall(null, new MethodParams
                {
                });
            }
        }
Esempio n. 10
0
        public async Task TruncateFile(string path, string filename, int maxBytes)
        {
            TruncateFileModel model = new TruncateFileModel(path, filename, maxBytes);

            byte[]         message  = GetMessage(model);
            MethodRequest  request  = new MethodRequest("truncateFile", message);
            MethodResponse response = await client.InvokeMethodAsync(deviceId, moduleId, request);

            if (response.Status != 200)
            {
                Console.WriteLine("DirectMethods Client TruncateFile failed");
            }
        }
Esempio n. 11
0
        public async Task CompressFile(string path, string filename, string compressPath, string compressFilename)
        {
            CompressFileModel model = new CompressFileModel(path, filename, compressPath, compressFilename);

            byte[]         message  = GetMessage(model);
            MethodRequest  request  = new MethodRequest("compressFile", message);
            MethodResponse response = await client.InvokeMethodAsync(deviceId, moduleId, request);

            if (response.Status != 200)
            {
                Console.WriteLine("DirectMethods Client CompressFile failed");
            }
        }
Esempio n. 12
0
        public JsonResult ActivateWorkroom(int WorkroomId, int LocationMasterId)
        {
            MethodResponse response = new MethodResponse()
            {
                Result = false, ErrorMessage = "Error Activating Workroom"
            };

            Helpers.InspectionService service = new Helpers.InspectionService();
            response.Result       = service.SetActivator(LocationMasterId, WorkroomId, true);
            response.ErrorMessage = service.ErrorMessage;

            return(Json(response));
        }
Esempio n. 13
0
        public async Task DownloadFile(string path, string filename, string sasUri, bool append = false, CancellationToken token = default(CancellationToken))
        {
            DownloadFileModel model = new DownloadFileModel(path, filename, sasUri, append);

            byte[]         message  = GetMessage(model);
            MethodRequest  request  = new MethodRequest("downloadFile", message);
            MethodResponse response = await client.InvokeMethodAsync(deviceId, moduleId, request);

            if (response.Status != 200)
            {
                Console.WriteLine("DirectMethods Client DownloadFile2 failed");
            }
        }
Esempio n. 14
0
        static Task <MethodResponse> OnFirmwareUpdate(MethodRequest request, object context)
        {
            var data = request.DataAsJson;

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Firmware Update Method Called...");
            Console.WriteLine("Rebooting...");
            Console.WriteLine(data);
            Console.ResetColor();
            MethodResponse response = new MethodResponse(new byte[0], 500);

            return(Task.FromResult(response));
        }
Esempio n. 15
0
 public void Logout(out MethodResponse response)
 {
     response = new MethodResponse();
     try
     {
         FormsAuthentication.SignOut();
         response.IsOk = true;
     }
     catch (Exception ex)
     {
         response.ResponseObject = ex;
     }
 }
Esempio n. 16
0
        public async Task UploadFile(string path, string filename, string sasUri, string contentType, bool deleteOnUpload = false, TimeSpan?ttl = null, bool append = false, CancellationToken token = default(CancellationToken))
        {
            UploadFileModel model = new UploadFileModel(path, filename, sasUri, contentType, deleteOnUpload, ttl, append);

            byte[]         message  = GetMessage(model);
            MethodRequest  request  = new MethodRequest("uploadFile", message);
            MethodResponse response = await client.InvokeMethodAsync(deviceId, moduleId, request);

            if (response.Status != 200)
            {
                Console.WriteLine("DirectMethods Client UploadFile2 failed");
            }
        }
Esempio n. 17
0
        public async Task UploadFile(string path, string filename, string blobPath, string blobFilename, string contentType, bool deleteOnUpload = false, TimeSpan?ttl = null, bool append = false, CancellationToken token = default(CancellationToken))
        {
            UploadFileModel model = new UploadFileModel(path, filename, blobPath, blobFilename, contentType, deleteOnUpload, ttl, append);

            byte[]         message  = GetMessage(model);
            string         jstring  = JsonConvert.SerializeObject(model);
            MethodRequest  request  = new MethodRequest("uploadFile", Encoding.UTF8.GetBytes(jstring));
            MethodResponse response = await client.InvokeMethodAsync(deviceId, moduleId, request);

            if (response.Status != 200)
            {
                Console.WriteLine("DirectMethods Client UploadFile failed");
            }
        }
Esempio n. 18
0
        private Task <MethodResponse> WrapWithTaskLogging(MethodRequest methodRequest, Func <MethodRequest, MethodResponse> func)
        {
            _logger.Information("{MethodName} was called via Direct Method", methodRequest.Name);

            Stopwatch sw = Stopwatch.StartNew();

            MethodResponse response = func(methodRequest);

            sw.Stop();

            _logger.Information("{MethodName} completed with status {Status} in {Elapsed} ms.", methodRequest.Name, response.Status, sw.ElapsedMilliseconds);

            return(Task.FromResult(response));
        }
Esempio n. 19
0
        } // DeserializeSoapRequestMessage

        internal static IMessage DeserializeSoapResponseMessage(
            Stream inputStream, IMessage requestMsg, Header[] h, bool bStrictBinding)
        {
            SoapFormatter fmt = CreateSoapFormatter(false, bStrictBinding);

            IMethodCallMessage mcm = (IMethodCallMessage)requestMsg;
            MethodResponse     mr  = new MethodResponse(h, mcm);

            fmt.Deserialize(inputStream, new HeaderHandler(mr.HeaderHandler));

            IMessage resMessage = (IMessage)mr;

            return(resMessage);
        } // DeserializeSoapResponseMessage
Esempio n. 20
0
 private static CrossAppDomainSink.ProcessMessageRes ProcessMessageInDomain(byte[] arrRequest, CADMethodCallMessage cadMsg)
 {
     CrossAppDomainSink.ProcessMessageRes result = default(CrossAppDomainSink.ProcessMessageRes);
     try
     {
         AppDomain.CurrentDomain.ProcessMessageInDomain(arrRequest, cadMsg, out result.arrResponse, out result.cadMrm);
     }
     catch (Exception e)
     {
         IMessage msg = new MethodResponse(e, new ErrorMessage());
         result.arrResponse = CADSerializer.SerializeMessage(msg).GetBuffer();
     }
     return(result);
 }
Esempio n. 21
0
        internal static IMessage CheckReturnMessage(IMessage callMsg, IMessage retMsg)
        {
            IMethodReturnMessage ret = retMsg as IMethodReturnMessage;

            if (ret != null && ret.Exception != null)
            {
                if (RemotingConfiguration.CustomErrorsEnabled(IsLocalCall(callMsg)))
                {
                    Exception ex = new Exception("Server encountered an internal error. For more information, turn off customErrors in the server's .config file.");
                    retMsg = new MethodResponse(ex, (IMethodCallMessage)callMsg);
                }
            }
            return(retMsg);
        }
Esempio n. 22
0
        public void TestBuildMethodResponseQuery()
        {
            var rpc  = new Matrix.Xmpp.Rpc.Rpc();
            var resp = new MethodResponse();

            var pars = new Parameters {
                "Colorado"
            };

            resp.SetParameters(pars);

            rpc.MethodResponse = resp;
            rpc.ShouldBe(Resource.Get("Xmpp.Rpc.rpc_query_response2.xml"));
        }
 private static Task <MethodResponse> GetTimeMethod(MethodRequest methodRequest, object userContext)
 {
     try
     {
         Interlocked.Increment(ref methodCount);
         var response = new MethodResponse(GetPayload(), 200);
         return(Task.FromResult(response));
     }
     catch (Exception ex)
     {
         LogException(ex);
         return(Task.FromResult(new MethodResponse(500)));
     }
 }
Esempio n. 24
0
        public static MethodResponse <List <GPS_DATAS> > Get()
        {
            MethodResponse <List <GPS_DATAS> > response = new MethodResponse <List <GPS_DATAS> >();

            try
            {
                using (SqlConnection context = new SqlConnection(DL.Conexion.ConnectionString()))
                {
                    string     Query = "sp_GetGPS_DATA";
                    SqlCommand cmd   = DL.Conexion.CreateCommand(Query, context);
                    cmd.CommandType = CommandType.StoredProcedure;
                    DataTable table = DL.Conexion.ExecuteCommandSelect(cmd);
                    if (table.Rows.Count > 0)
                    {
                        response.Code     = 200;
                        response.Messagge = "Datos encontrados";
                        response.Result   = new List <GPS_DATAS>();
                        foreach (DataRow row in table.Rows)
                        {
                            GPS_DATAS items = new GPS_DATAS();
                            items.Id         = Convert.ToInt32(row[0]);
                            items.DateSystem = Convert.ToString(row[1]);
                            items.DateEvent  = Convert.ToString(row[2]);
                            items.Latitude   = Convert.ToDouble(row[3]);
                            items.Longitude  = Convert.ToDouble(row[4]);
                            items.Battery    = Convert.ToInt32(row[5]);
                            items.Source     = Convert.ToInt32(row[6]);
                            items.Type       = Convert.ToInt32(row[7]);
                            response.Result.Add(items);
                        }
                        return(response);
                    }
                    else
                    {
                        response.Code     = 400;
                        response.Messagge = "No hay datos que mostrar";
                        response.Result   = new List <GPS_DATAS>();
                        return(response);
                    }
                }
            }
            catch (Exception Ex)
            {
                response.Code     = 500;
                response.Messagge = Ex.ToString();
                response.Result   = new List <GPS_DATAS>();
                return(response);
            }
        }
Esempio n. 25
0
        private static async Task <DeviceClient> CreateDeviceClientAsync(Device device)
        {
            var deviceId = device.Id;

            D2COperationCounts[deviceId] = 0;
            C2DOperationCounts[deviceId] = 0;
            ConsoleLogger.LogInfo($"Device {device.Id} started");
            var tokenRefresher = new DeviceAuthenticationWithSharedAccessKey(EnvironmentVariables.IotHubHost, device.Id, device.Authentication.SymmetricKey.PrimaryKey, TokenTTL);
            ITransportSettings transportSetting;

            if (deviceId.GetHashCode() % 2 == 0)
            {
                transportSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only)
                {
                    RemoteCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true
                };
            }
            else
            {
                transportSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only)
                {
                    RemoteCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true
                };
            }

            ConsoleLogger.LogInfo($"Device {device.Id} transportType: {transportSetting.GetTransportType()}.");

            var deviceClient = DeviceClient.Create(EnvironmentVariables.IotHubHost, EnvironmentVariables.EdgeHubHost, tokenRefresher, new ITransportSettings[] { transportSetting });

            deviceClient.SetConnectionStatusChangesHandler((state, reason) =>
                                                           { ConsoleLogger.LogInfo($"Device {device.Id} Connection state change: state={state}, reason={reason}"); });
            await deviceClient.SetDesiredPropertyUpdateCallbackAsync((desiredProperties, context) =>
            {
                ConsoleLogger.LogInfo($"Device {device.Id} Desired properties change: desiredProperties={desiredProperties.ToJson()}");
                return(Task.CompletedTask);
            },
                                                                     deviceClient);

            await deviceClient.SetMethodHandlerAsync(
                MethodName,
                (request, _) =>
            {
                var echoResponse = new MethodResponse(request.Data, 200);
                return(Task.FromResult(echoResponse));
            },
                deviceClient);

            return(deviceClient);
        }
        public void ReadRequestAndWriteResponse()
        {
            IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
            var         endpoint    = new IPEndPoint(addressList[addressList.Length - 1], 9900);
            var         listener    = new TcpListener(endpoint);

            listener.Start();

            var t = new Thread(new ThreadStart(() =>
            {
                var c      = listener.AcceptTcpClient();
                var handle = new TcpProtocolHandle(c.GetStream());

                //read remoting request
                Console.WriteLine("Preamble: {0}", handle.ReadPreamble());
                Console.WriteLine("MajorVersion: {0}", handle.ReadMajorVersion());
                Console.WriteLine("MinorVersion: {0}", handle.ReadMinorVersion());
                var op = handle.ReadOperation();
                Assert.AreEqual(TcpOperations.Request, op);
                Console.WriteLine("Operation: {0}", op);
                Console.WriteLine("ContentDelimiter: {0}", handle.ReadContentDelimiter());
                Console.WriteLine("ContentLength: {0}", handle.ReadContentLength());
                DumpHelper.DumpDictionary(handle.ReadTransportHeaders());
                var messageRequest = BinaryFormatterHelper.DeserializeObject(handle.ReadContent()) as MethodCall;
                Assert.IsNotNull(messageRequest);
                DumpHelper.DumpMessage(messageRequest);

                //write remoting response
                var responeMessage = new MethodResponse(new Header[] { new Header(MessageHeader.Return, messageRequest.Args[0]) }, messageRequest);
                var responseStream = BinaryFormatterHelper.SerializeObject(responeMessage);
                handle.WritePreamble();
                handle.WriteMajorVersion();
                handle.WriteMinorVersion();
                handle.WriteOperation(TcpOperations.Reply);
                handle.WriteContentDelimiter(TcpContentDelimiter.ContentLength);
                handle.WriteContentLength(responseStream.Length);
                handle.WriteTransportHeaders(null);
                handle.WriteContent(responseStream);
            }));

            t.Start();

            var url     = string.Format("tcp://{0}/remote.rem", endpoint);
            var service = RemotingServices.Connect(typeof(ServiceClass), url) as ServiceClass;

            Assert.AreEqual("Hi", service.Do("Hi"));

            t.Abort();
        }
        static async Task <MethodResponse> CollectBatteryPowerMethodCallBack(MethodRequest methodRequest, object userContext)
        {
            var collectBatteryPowerResponse = new CollectBatteryPowerResponse {
                responseState = 0
            };

            try
            {
                var messageBytes = methodRequest.Data;
                var messageJson  = Encoding.UTF8.GetString(messageBytes);
                var command      = JsonConvert.DeserializeObject <CollectBatteryPowerRequest>(messageJson);

                var all = command.all.HasValue ? command.all.Value : true;

                Console.WriteLine($"Executing collectBatteryPowerMethodCallBack: All: '{all}'");

                if (_controller == null)
                {
                    collectBatteryPowerResponse.responseState = -1;
                }
                else
                {
                    var deviceObjects = await _controller.GatewayController.GetDeviceObjects();

                    if (deviceObjects == null)
                    {
                        collectBatteryPowerResponse.responseState = -4;
                    }
                    else
                    {
                        var collected = await CollectBatteryPower(all);

                        collectBatteryPowerResponse.devices = collected.OrderBy(x => x.battery).ToArray();
                    }
                }
            }
            catch (Exception ex)
            {
                collectBatteryPowerResponse.errorMessage  = ex.Message;
                collectBatteryPowerResponse.responseState = -999;
            }

            var json     = JsonConvert.SerializeObject(collectBatteryPowerResponse);
            var response = new MethodResponse(Encoding.UTF8.GetBytes(json), 200);

            await Task.Delay(TimeSpan.FromSeconds(0));

            return(response);
        }
Esempio n. 28
0
        public Task <MethodResponse> reboot(MethodRequest methodRequest, object userContext)
        {
            string         retval = string.Empty;
            MethodResponse retValue;

            try
            {
                retValue = new MethodResponse(Encoding.UTF8.GetBytes(retval), 200);
            }
            catch (Exception ex)
            {
                retValue = new MethodResponse(Encoding.UTF8.GetBytes(retval), 200);
            }
            return(Task.FromResult(retValue));
        }
        public void Add <T>(T input, out MethodResponse response) where T : class
        {
            if (input == null)
            {
                response = new MethodResponse()
                {
                    Success         = false,
                    ResponseMessage = "Input is Null",
                };
                return;
            }
            var typeName = input.GetMongoCollectionName(out var type);

            Add <T>(input, typeName, out response);
        }
Esempio n. 30
0
        private static async Task <MethodResponse> BottleHoldersMethodCallBack(MethodRequest methodRequest, object userContext)
        {
            Console.WriteLine($"Executing BottleHoldersMethodCallBack at {DateTime.UtcNow}");

            var bottleHoldersResponse = new BottleHoldersResponse {
                responseState = 0
            };

            try
            {
                var mcp23x1x = _mcp23xxxRead as Mcp23x1x;

                if (mcp23x1x == null)
                {
                    bottleHoldersResponse.errorMessage  = "Unable to cast Mcp23017 Read GPIO.";
                    bottleHoldersResponse.responseState = 1;
                }
                else
                {
                    byte dataPortA = mcp23x1x.ReadByte(Register.GPIO, Port.PortA);
                    byte dataPortB = mcp23x1x.ReadByte(Register.GPIO, Port.PortB);

                    var beerLiftMessage = new BeerLiftMessage(_deviceId, dataPortA, dataPortB, _liftState);

                    var pinValue = _controller.Read(FloodedPin); // Moisture sensor

                    var flooded = pinValue.ToString().ToLower() == "low" ? false : true;

                    beerLiftMessage.isFlooded = flooded;

                    bottleHoldersResponse.BeerLiftMessage = beerLiftMessage;

                    Console.WriteLine($"BottleHolders ended at {DateTime.UtcNow}.");

                    await Task.Delay(1);
                }
            }
            catch (Exception ex)
            {
                bottleHoldersResponse.errorMessage  = ex.Message;
                bottleHoldersResponse.responseState = -999;
            }

            var json     = JsonConvert.SerializeObject(bottleHoldersResponse);
            var response = new MethodResponse(Encoding.UTF8.GetBytes(json), 200);

            return(response);
        }
        public void ShouldLoginWithUsernameSuccess()
        {
            String methodId = "SomeRandomId";
            _connection.IdGenerator = () => methodId;

            MethodResponse response = new MethodResponse
            {
                Id = methodId,
                Error = null,
                Result = new JObject(new JProperty("tokenExpires", JToken.FromObject(new DdpDate())), new JProperty("token", "SomeTokenId"))
            };
            _mock.Setup(websocket => websocket.SendJson(It.IsAny<MethodModel>()))
                .Callback(() => _mock.Raise(socket => socket.DdpMessage += null, null, new DdpMessage("result", JsonConvert.SerializeObject(response))));

            string username = "******";
            string password = "******";

            bool wasRaised = false;
            EventHandler<LoginResponse> handler = null;
            handler = delegate(object sender, LoginResponse loginResponse)
            {
                wasRaised = true;
                Assert.IsFalse(loginResponse.HasError());
                Assert.IsNotNull(loginResponse.Token);
                Assert.IsNotNull(loginResponse.TokenExpires);
                _connection.Login -= handler;
            };
            _connection.Login += handler;

            _connection.LoginWithUsername(username, password);

            _mock.Verify(websocket => websocket.SendJson(It.Is<MethodModel>(method =>
                method.Id == methodId &&
                method.Method == "login" &&
                method.Params.Length == 1 &&
                method.Params[0] is BasicLoginModel<UsernameUser>)));
            Assert.IsTrue(wasRaised);
        }
        public void ShouldHandleMethodDynamic()
        {
            string id = "ShouldHandleMethodDynamic";
            string methodName = "MethodName";
            int parameter = 5;
            _connection.IdGenerator = () => id;

            MethodResponse response = new MethodResponse
            {
                Id = id,
                Error = null,
                Result = new JObject(new JProperty("someResult", 10))
            };

            _mock.Setup(webSocket => webSocket.SendJson(It.Is<MethodModel>(model => model.Id == id)))
                .Callback(() => _mock.Raise(webSocket => webSocket.DdpMessage += null, null, new DdpMessage("result", JsonConvert.SerializeObject(response))));

            bool wasCalled = false;
            Action<MethodResponse> callback = mResponse =>
            {
                wasCalled = true;
                Assert.IsNull(mResponse.Error);
                Assert.IsNotNull(mResponse.Result);
            };

            _connection.Call(methodName, callback, parameter);

            _mock.Verify(webSocket => webSocket.SendJson(It.Is<MethodModel>(model => model.Id == id)));
            Assert.IsTrue(wasCalled);
        }