Exemple #1
0
        public async Task <ActionResult> Put([FromRoute] string id, [FromBody] UpdateDevice command)
        {
            command.Id = id;
            await _mediator.Send(command);

            return(NoContent());
        }
Exemple #2
0
 public JsonResult UpdateDevice(UpdateDevice device)
 {
     if (ModelState.IsValid)
     {
         //调用设备服务
         Status status = new DeviceService().update(device);
         return(Json(new RespondModel(status, ""), JsonRequestBehavior.AllowGet));
     }
     return(Json(new RespondModel(Status.ARGUMENT_ERROR, ModelStateHelper.errorMessages(ModelState)), JsonRequestBehavior.AllowGet));
 }
Exemple #3
0
        void UpdateDeviceInternal(UpdateDevice update)
        {
            CameraInstance selected = update.Body.Selected;
            bool           updated  = false;

            if (_state.Selected != null &&
                _state.Selected.FrameGrabber != null)
            {
                _state.Selected.FrameGrabber.StopCapture();
                _state.Selected.FrameGrabber.Dispose();

                _state.Selected = null;
            }

            foreach (object obj in new vision.CameraCollection())
            {
                using (vision.Camera camera = obj as vision.Camera)
                {
                    if ((!string.IsNullOrEmpty(selected.FriendlyName) && camera.Name == selected.FriendlyName) ||
                        (!string.IsNullOrEmpty(selected.DevicePath) && camera.Path == selected.DevicePath))
                    {
                        selected.FriendlyName               = camera.Name;
                        selected.DevicePath                 = selected.DevicePath;
                        selected.FrameGrabber               = vision.FrameGrabber.FromCamera(camera);
                        selected.SupportedFormats           = ConvertFormats(selected.FrameGrabber.Formats);
                        selected.FrameGrabber.CaptureFrame += OnCaptureFrame;
                        selected.FrameGrabber.StartCapture();
                        selected.Format = new Format(selected.FrameGrabber.Format);

                        updated = true;
                        break;
                    }
                }
            }
            if (updated)
            {
                _state.Selected = selected;

                update.ResponsePort.Post(DefaultUpdateResponseType.Instance);

                SendNotification(_submgrPort, update);
            }
            else
            {
                update.ResponsePort.Post(
                    Fault.FromCodeSubcodeReason(FaultCodes.Receiver,
                                                DsspFaultCodes.UnknownEntry,
                                                "Camera not found"
                                                )
                    );
            }
        }
Exemple #4
0
        public void Device_CRUD_Positive()
        {
            // create
            Device      device        = null;
            Func <Task> asyncFunction = async() => device = await CreateDevice(Client);

            asyncFunction.ShouldNotThrow();
            device.Should().NotBeNull();

            // read
            asyncFunction = async() => device = await Client.ReadDevice(device.Id);

            asyncFunction.ShouldNotThrow();
            device.Should().NotBeNull();

            // read list
            IEnumerable <Device> devices = null;

            asyncFunction = async() => devices = await Client.ReadDevices();

            asyncFunction.ShouldNotThrow();
            devices.Should().NotBeNullOrEmpty();
            devices.Any(x => x.Id == device.Id).Should().BeTrue();

            // update
            var update = new UpdateDevice(device)
            {
                Name        = device.Name + " Updated",
                Description = device.Description + " Updated",
            };

            asyncFunction = async() => device = await Client.UpdateDevice(device.Id, update);

            asyncFunction.ShouldNotThrow();
            device.Should().NotBeNull();
            device.Name.Should().Be(update.Name);
            device.Description.Should().Be(update.Description);
            device.Mac.Should().Be(update.Mac);

            // delete
            asyncFunction = async() => await Client.DeleteDevice(device.Id);

            asyncFunction.ShouldNotThrow();

            // read list
            asyncFunction = async() => devices = await Client.ReadDevices();

            asyncFunction.ShouldNotThrow();
            devices.Should().NotBeNull();
            devices.Any(x => x.Id == device.Id).Should().BeFalse();
        }
Exemple #5
0
        public static async void AddDevice(GXDevice dev)
        {
            UpdateDevice gw = new UpdateDevice();

            gw.Device = dev;
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.PostAsJsonAsync(ServerAddress + "/api/device/UpdateDevice", gw))
                {
                    Helpers.CheckStatus(response);
                    UpdateDeviceResponse r = await response.Content.ReadAsAsync <UpdateDeviceResponse>();

                    dev.Id = r.DeviceId;
                }
            }
        }
Exemple #6
0
        public async Task <ActionResult <Models.DTO.Device> > Put(
            [FromRoute] string id,
            [FromBody] UpdateDevice device,
            CancellationToken cancellationToken)
        {
            var userId        = "GET FROM JWT";
            var tenantId      = "GET FROM JWT";
            var updatedDevice = await _deviceService.Update(
                id,
                userId,
                tenantId,
                device,
                cancellationToken);

            return(Ok(updatedDevice));
        }
Exemple #7
0
        public async Task PutById()
        {
            var all = await localHueClient.GetDevices();

            var id = all.Data.Last().Id;

            UpdateDevice req = new UpdateDevice()
            {
                Identify = new Identify()
            };
            var result = await localHueClient.UpdateDevice(id, req);

            Assert.IsNotNull(result);
            Assert.IsFalse(result.HasErrors);

            Assert.IsTrue(result.Data.Count == 1);
            Assert.AreEqual(id, result.Data.First().Rid);
        }
Exemple #8
0
 public static Models.Domain.Device MapToDomain(
     ObjectId id,
     string userId,
     string tenantId,
     UpdateDevice device)
 {
     return(new Models.Domain.Device
     {
         Id = id,
         Name = device.Name,
         TenantId = tenantId,
         UserId = userId,
         ThingTypes = device.ThingTypes,
         Icons = device.Icons.Select(ImageMapper.MapToDomain),
         Images = device.Images.Select(ImageMapper.MapToDomain),
         ActuatorValues = device.ActuatorValues.Select(ActuatorValueMapper.MapToDomain),
         SensorValues = device.SensorValues.Select(SensorValueMapper.MapToDomain),
         DateAdded = DateTime.UtcNow,
         MessageProtocols = device.MessageProtocols
     });
 }
Exemple #9
0
        public async Task <Models.DTO.Device> Update(
            string id,
            string userId,
            string tenantId,
            UpdateDevice device,
            CancellationToken cancellationToken)
        {
            if (!ObjectId.TryParse(id, out var deviceId))
            {
                throw new ArgumentException("Invalid Id, cannot cast to ObjectId.");
            }

            var deviceToUpdate = DeviceMapper.MapToDomain(
                deviceId,
                userId,
                tenantId,
                device);

            var updatedDevice = await _deviceRepository.Update(
                deviceToUpdate,
                cancellationToken);

            return(DeviceMapper.MapToDto(updatedDevice));
        }
Exemple #10
0
        private void ProcessPacket(byte[] packet)
        {
            if (packet == null || packet.Length < 8)
            {
                return;
            }

            if ((packet[3] & 1) == 0) //Request
            {
                string             methodName = "";
                List <RPCVariable> parameters = _rpcDecoder.DecodeRequest(packet, ref methodName);
                RPCVariable        response   = new RPCVariable(RPCVariableType.rpcVoid);
                if (methodName == "")
                {
                    response = RPCVariable.CreateError(-1,
                                                       "Packet is not well formed: " + BitConverter.ToString(packet));
                }
                else if (methodName == "system.listMethods")
                {
                    response = new RPCVariable(RPCVariableType.rpcArray);
                    response.ArrayValue.Add(new RPCVariable("system.multicall"));
                    response.ArrayValue.Add(new RPCVariable("error"));
                    response.ArrayValue.Add(new RPCVariable("event"));
                    response.ArrayValue.Add(new RPCVariable("newDevices"));
                    response.ArrayValue.Add(new RPCVariable("updateDevice"));
                    response.ArrayValue.Add(new RPCVariable("deleteDevices"));
                    response.ArrayValue.Add(new RPCVariable("newEvent"));
                    response.ArrayValue.Add(new RPCVariable("deleteEvent"));
                    response.ArrayValue.Add(new RPCVariable("updateEvent"));
                }
                else if (methodName == "system.multicall" && parameters.Any())
                {
                    foreach (RPCVariable method in parameters[0].ArrayValue)
                    {
                        if (method.Type != RPCVariableType.rpcStruct || method.StructValue.Count() != 2)
                        {
                            continue;
                        }

                        if (method.StructValue["methodName"].StringValue != "event")
                        {
                            continue;
                        }

                        List <RPCVariable> eventParams = method.StructValue["params"].ArrayValue;
                        if (eventParams.Count() != 5 || eventParams[0].Type != RPCVariableType.rpcString ||
                            eventParams[1].Type != RPCVariableType.rpcInteger ||
                            eventParams[2].Type != RPCVariableType.rpcInteger ||
                            eventParams[3].Type != RPCVariableType.rpcString)
                        {
                            continue;
                        }

                        RPCEvent?.Invoke(this, eventParams[1].IntegerValue, eventParams[2].IntegerValue, eventParams[3].StringValue, eventParams[4], eventParams[0].StringValue);
                    }
                }
                else if (methodName == "error" && parameters.Count() == 3 &&
                         parameters[1].Type == RPCVariableType.rpcInteger &&
                         parameters[2].Type == RPCVariableType.rpcString)
                {
                    HomegearError?.Invoke(this, parameters[1].IntegerValue, parameters[2].StringValue);
                }
                else if (methodName == "newDevices")
                {
                    NewDevices?.Invoke(this);
                }
                else if (methodName == "deleteDevices")
                {
                    DevicesDeleted?.Invoke(this);
                }
                else if (methodName == "updateDevice")
                {
                    if (parameters.Count == 4 && parameters[0].Type == RPCVariableType.rpcString &&
                        parameters[1].Type == RPCVariableType.rpcInteger &&
                        parameters[2].Type == RPCVariableType.rpcInteger &&
                        parameters[3].Type == RPCVariableType.rpcInteger)
                    {
                        UpdateDevice?.Invoke(this, parameters[1].IntegerValue, parameters[2].IntegerValue,
                                             parameters[3].IntegerValue);
                    }
                }
                else if (methodName == "newEvent")
                {
                    if (parameters.Count == 2 && parameters[1].Type == RPCVariableType.rpcStruct)
                    {
                        string id       = "";
                        long   type     = -1;
                        long   peerId   = 0;
                        long   channel  = -1;
                        string variable = "";
                        if (parameters[1].StructValue.ContainsKey("ID"))
                        {
                            id = parameters[1].StructValue["ID"].StringValue;
                        }

                        if (parameters[1].StructValue.ContainsKey("TYPE"))
                        {
                            type = parameters[1].StructValue["TYPE"].IntegerValue;
                        }

                        if (parameters[1].StructValue.ContainsKey("PEERID"))
                        {
                            peerId = parameters[1].StructValue["PEERID"].IntegerValue;
                        }

                        if (parameters[1].StructValue.ContainsKey("PEERCHANNEL"))
                        {
                            channel = parameters[1].StructValue["PEERCHANNEL"].IntegerValue;
                        }

                        if (parameters[1].StructValue.ContainsKey("VARIABLE"))
                        {
                            variable = parameters[1].StructValue["VARIABLE"].StringValue;
                        }

                        NewEvent?.Invoke(this, id, type, peerId, channel, variable);
                    }
                }
                else if (methodName == "deleteEvent")
                {
                    if (parameters.Count == 6)
                    {
                        EventDeleted?.Invoke(this, parameters[1].StringValue, parameters[2].IntegerValue,
                                             parameters[3].IntegerValue, parameters[4].IntegerValue, parameters[5].StringValue);
                    }
                }
                else if (methodName == "updateEvent")
                {
                    if (parameters.Count == 6)
                    {
                        UpdateEvent?.Invoke(this, parameters[1].StringValue, parameters[2].IntegerValue,
                                            parameters[3].IntegerValue, parameters[4].IntegerValue, parameters[5].StringValue);
                    }
                }
                byte[] responsePacket = _rpcEncoder.EncodeResponse(response).ToArray();
                SendPacket(responsePacket);
            }
            else //Response
            {
                _rpcResponse = _rpcDecoder.DecodeResponse(packet);
                _responseReceived.Set();
            }
        }
        /// <summary>
        /// Resyncs a remote devices with the local devices database.
        /// You can enter multiple codes, for the resync to succeed, all the
        /// codes need to be verified. Its more secure to use multiple codes.
        /// 
        /// If is successfully syncs it use the call back for you to unlock the
        /// device and set the correct counter.
        /// </summary>
        ///<param name="device">device that you want to resync</param>
        ///<param name="codes">list of codes that should be verified</param>
        ///<param name="counter">start counter, meaning on what interval should se start resync'ing</param>
        ///<param name="updateDevice">call back delegate for when the resync was successfull, we need to update the device differently depending on HOTP/TOTP</param>
        ///<param name="window">overrides global window for the resync. Set to -1 to use the default window</param>
        ///<exception cref="ArgumentNullException">If codes or ident is null</exception>
        ///<exception cref="ArgumentOutOfRangeException">If window is less than -1</exception>
        /// <exception cref="OtpDecryptionException">if key failed to decrypt</exception>
        ///<returns>true if resync was successfull</returns>
        /// <remarks>
        /// Background info (RFC4226):
        /// As we suggested for the resynchronization to enter a short sequence
        /// (say, 2 or 3) of HOTP values, we could generalize the concept to the
        /// protocol, and add a parameter L that would define the length of the
        /// HOTP sequence to enter.
        ///
        /// Per default, the value L SHOULD be set to 1, but if security needs to
        /// be increased, users might be asked (possibly for a short period of
        /// time, or a specific operation) to enter L HOTP values.
        ///
        /// This is another way, without increasing the HOTP length or using
        /// alphanumeric values to tighten security.
        ///
        /// Note: The system MAY also be programmed to request synchronization on
        /// a regular basis (e.g., every night, twice a week, etc.) and to
        /// achieve this purpose, ask for a sequence of L HOTP values.
        /// </remarks>
        internal bool Resync(Device device, string[] codes, long counter, UpdateDevice updateDevice, int window = -1)
        {
            for (int i = 0; i <= window; i++)
            {
                //check forward in totp/hotp counter
                if (Generate(Decrypt(device.Key), counter + i) == codes[0] && ResyncCheck(ref device, codes, counter + i))
                {
                        updateDevice(ref device, counter + i + codes.Length); //delegate to update devices.
                        return true;
                }

                //check backwards in totp/hotp counter
                if (Generate(Decrypt(device.Key), counter - i) == codes[0] && ResyncCheck(ref device, codes, counter - i))
                {
                    updateDevice(ref device, counter - i + codes.Length); //delegate to update devices.
                    return true;
                }
            }
            return false;
        }
Exemple #12
0
        public ActionResult <UpdateDeviceResponse> Post(UpdateDevice request)
        {
            if (request.Device.TemplateId == 0)
            {
                return(BadRequest("Device template ID is unknown."));
            }
            bool newDevice = request.Device.Id == 0;

            if (request.Device.DeviceSystemTitle != null)
            {
                request.Device.DeviceSystemTitle = request.Device.DeviceSystemTitle.Replace(" ", "");
            }
            if (request.Device.AuthenticationKey != null)
            {
                request.Device.AuthenticationKey = request.Device.AuthenticationKey.Replace(" ", "");
            }
            if (request.Device.BlockCipherKey != null)
            {
                request.Device.BlockCipherKey = request.Device.BlockCipherKey.Replace(" ", "");
            }
            if (newDevice)
            {
                DateTime now = DateTime.Now;
                request.Device.Generation = now;
                //Add new DC.
                List <GXObject> tmp = request.Device.Objects;
                request.Device.Objects    = null;
                request.Device.Generation = now;
                host.Connection.Insert(GXInsertArgs.Insert(request.Device));

                //Add default objects.
                GXSelectArgs arg = GXSelectArgs.SelectAll <GXObjectTemplate>(q => q.DeviceTemplateId == request.Device.TemplateId && q.Removed == DateTime.MinValue);
                arg.Columns.Add <GXAttributeTemplate>();
                arg.Joins.AddLeftJoin <GXObjectTemplate, GXAttributeTemplate>(o => o.Id, a => a.ObjectTemplateId);
                arg.Where.And <GXAttributeTemplate>(q => q.Removed == DateTime.MinValue);
                List <GXObjectTemplate> l = host.Connection.Select <GXObjectTemplate>(arg);
                foreach (GXObjectTemplate it in l)
                {
                    GXObject obj = new GXObject()
                    {
                        TemplateId  = it.Id,
                        Generation  = now,
                        DeviceId    = request.Device.Id,
                        ObjectType  = it.ObjectType,
                        Name        = it.Name,
                        LogicalName = it.LogicalName,
                        ShortName   = it.ShortName,
                    };
                    host.Connection.Insert(GXInsertArgs.Insert(obj));
                    foreach (GXAttributeTemplate ait in it.Attributes)
                    {
                        GXAttribute a = new GXAttribute();
                        a.ObjectId       = obj.Id;
                        a.Index          = ait.Index;
                        a.TemplateId     = ait.Id;
                        a.AccessLevel    = ait.AccessLevel;
                        a.DataType       = ait.DataType;
                        a.UIDataType     = ait.UIDataType;
                        a.Generation     = now;
                        a.ExpirationTime = ait.ExpirationTime;
                        obj.Attributes.Add(a);
                    }
                    ;
                    host.Connection.Insert(GXInsertArgs.InsertRange(obj.Attributes));
                }
                host.SetChange(TargetType.ObjectTemplate, DateTime.Now);
            }
            else
            {
                request.Device.Updated = DateTime.Now;
                host.Connection.Update(GXUpdateArgs.Update(request.Device));
                host.SetChange(TargetType.DeviceTemplate, DateTime.Now);
            }
            return(new UpdateDeviceResponse()
            {
                DeviceId = request.Device.Id
            });
        }
Exemple #13
0
        IEnumerator <ITask> GetInitialState(Srv1CameraState initialState)
        {
            Srv1CameraState state = new Srv1CameraState();

            state.CaptureFile = initialState.CaptureFile;
            state.Quality     = initialState.Quality;

            yield return(InitializeInternalService());

            foreach (object obj in new vision.CameraCollection())
            {
                using (vision.Camera camera = obj as vision.Camera)
                {
                    CameraInstance instance = new CameraInstance();
                    instance.FriendlyName     = camera.Name;
                    instance.DevicePath       = camera.Path;
                    instance.SupportedFormats = ConvertFormats(camera.Formats);

                    state.Cameras.Add(instance);
                }
            }

            state.Image = null;

            Replace replace = new Replace();

            replace.Body = state;
            _fwdPort.Post(replace);

            yield return(Arbiter.Choice(
                             replace.ResponsePort,
                             delegate(DefaultReplaceResponseType success) { },
                             delegate(Fault fault)
            {
                LogError(null, "Unable to set camera list", fault);
            }
                             ));

            UpdateDeviceRequest request = new UpdateDeviceRequest();

            if (initialState.Selected != null)
            {
                request.Selected = initialState.Selected;
            }
            else if (state.Cameras.Count > 0)
            {
                request.Selected = state.Cameras[0];
            }
            else
            {
                yield break;
            }
            UpdateDevice update = new UpdateDevice();

            update.Body = request;
            _fwdPort.Post(update);

            yield return(Arbiter.Choice(
                             update.ResponsePort,
                             delegate(DefaultUpdateResponseType success) { },
                             delegate(Fault fault)
            {
                LogError(null, "Unable to select camera", fault);
            }
                             ));

            if (initialState.Selected == null ||
                initialState.Selected.Format == null)
            {
                yield break;
            }

            UpdateFormat updateFormat = new UpdateFormat();

            updateFormat.Body = initialState.Selected.Format;

            _fwdPort.Post(updateFormat);

            yield return(Arbiter.Choice(
                             updateFormat.ResponsePort,
                             delegate(DefaultUpdateResponseType success) { },
                             delegate(Fault fault)
            {
                LogError(null, "Unable to select format", fault);
            }
                             ));
        }
Exemple #14
0
        public IEnumerator <ITask> HttpPostHandler(HttpPost post)
        {
            Fault fault = null;
            NameValueCollection collection = null;

            ReadFormData readForm = new ReadFormData(post);

            _utilitiesPort.Post(readForm);

            yield return(Arbiter.Choice(
                             readForm.ResultPort,
                             delegate(NameValueCollection col)
            {
                collection = col;
            },
                             delegate(Exception e)
            {
                fault = Fault.FromException(e);
                LogError(null, "Error processing form data", fault);
            }
                             ));

            if (fault != null)
            {
                post.ResponsePort.Post(fault);
                yield break;
            }

            if (!string.IsNullOrEmpty(collection["ChangeCamera"]))
            {
                string device = string.Empty;
                try
                {
                    device = collection["Camera"];
                }
                catch (Exception e)
                {
                    fault = Fault.FromException(e);
                    LogError(null, "Error reading form data", fault);
                }

                if (fault != null)
                {
                    post.ResponsePort.Post(fault);
                    yield break;
                }

                UpdateDeviceRequest request = new UpdateDeviceRequest();
                request.Selected.DevicePath = device;

                UpdateDevice update = new UpdateDevice();
                update.Body = request;

                SpawnIterator(update, UpdateDeviceHandler);

                yield return(Arbiter.Choice(
                                 update.ResponsePort,
                                 delegate(DefaultUpdateResponseType success)
                {
                    SaveState(_state);
                },
                                 delegate(Fault f)
                {
                    fault = f;
                    LogError(null, "Unable to change camera", fault);
                }
                                 ));
            }
            else if (!string.IsNullOrEmpty(collection["ChangeFormat"]))
            {
                int    formatIndex = 0;
                Format format      = null;
                try
                {
                    formatIndex = int.Parse(collection["CaptureFormat"]);
                    format      = _state.Selected.SupportedFormats[formatIndex - 1];
                }
                catch (Exception e)
                {
                    fault = Fault.FromException(e);
                    LogError(null, "Error parsing form data", fault);
                }

                if (fault != null)
                {
                    post.ResponsePort.Post(fault);
                    yield break;
                }

                UpdateFormat update = new UpdateFormat();
                update.Body = format;

                SpawnIterator(update, UpdateFormatHandler);

                yield return(Arbiter.Choice(
                                 update.ResponsePort,
                                 delegate(DefaultUpdateResponseType success)
                {
                    SaveState(_state);
                },
                                 delegate(Fault f)
                {
                    fault = f;
                    LogError(null, "Unable to change format", fault);
                }
                                 ));
            }

            if (fault != null)
            {
                post.ResponsePort.Post(fault);
                yield break;
            }

            post.ResponsePort.Post(new HttpResponseType(HttpStatusCode.OK, _state, _transform));
            yield break;
        }
Exemple #15
0
        public IEnumerator <ITask> UpdateDeviceHandler(UpdateDevice update)
        {
            CameraInstance selected  = update.Body.Selected;
            bool           updated   = false;
            Exception      exception = null;

            if (_state.Selected != null &&
                _state.Selected.Started)
            {
                var stopPort = StopCapture();

                yield return((Choice)stopPort);

                _state.Selected.Started = false;

                _state.Selected         = null;
                _state.CameraDeviceName = null;
            }


            var devicePort = EnumDevices();
            List <CameraInstance> cameras = null;

            yield return(Arbiter.Receive(false, devicePort, list => cameras = list));

            foreach (var camera in cameras)
            {
                if (selected.Equals(camera))
                {
                    var openPort = OpenCamera(camera);

                    yield return((Choice)openPort);

                    exception = openPort;
                    if (exception != null)
                    {
                        LogError("Unable to open device", exception);
                        continue;
                    }

                    var formatsPort = EnumFormats(camera);

                    yield return(Arbiter.Receive(false, formatsPort, list => selected.SupportedFormats = list));

                    Format requestFormat = selected.Format ?? new Format();
                    bool   setFormat     = selected.IsValidFormat(requestFormat);

                    if (setFormat)
                    {
                        var setFormatPort = SetFormat(requestFormat);

                        yield return((Choice)setFormatPort);

                        exception = setFormatPort;
                        if (exception != null)
                        {
                            LogError("Unable to set the requested format", exception);
                            exception = null;
                        }
                    }

                    var startPort = StartCapture();

                    yield return((Choice)startPort);

                    exception = startPort;
                    if (exception != null)
                    {
                        LogError("Unable to start capture", exception);
                        continue;
                    }

                    _state.CameraDeviceName = selected.FriendlyName;
                    updated = true;
                    break;
                }
            }

            if (updated)
            {
                _state.Cameras          = cameras;
                _state.Selected         = selected;
                _state.Selected.Started = true;
                if (selected.Format != null)
                {
                    _state.ImageSize = new physics.Vector2(selected.Format.Width, selected.Format.Height);
                }

                update.ResponsePort.Post(DefaultUpdateResponseType.Instance);

#if !URT_MINCLR
                SendNotification(_submgrPort, update);
#else
                SendNotification(update);
#endif
            }
            else
            {
                update.ResponsePort.Post(Fault.FromCodeSubcodeReason(
                                             W3C.Soap.FaultCodes.Receiver,
                                             DsspFaultCodes.UnknownEntry,
                                             "Camera not found"
                                             )
                                         );
            }
        }
Exemple #16
0
        IEnumerator <ITask> GetInitialState(WebCamState initialState)
        {
            bool deviceSelected = false;

            try
            {
                WebCamState state = new WebCamState();
                state.CaptureFile    = initialState.CaptureFile;
                state.Quality        = initialState.Quality;
                state.FramesOnDemand = initialState.FramesOnDemand;

#if !URT_MINCLR
                yield return(InitializeInternalService());
#endif


                Port <EmptyValue> completion = new Port <EmptyValue>();

                SpawnIterator(state, completion, RefreshCameraList);

                yield return(Arbiter.Receive(false, completion, EmptyHandler));

                state.Image = null;

                Replace replace = new Replace();
                replace.Body = state;
                _fwdPort.Post(replace);

                yield return(Arbiter.Choice(
                                 replace.ResponsePort,
                                 delegate(DefaultReplaceResponseType success) { },
                                 delegate(Fault fault)
                {
                    LogError(null, "Unable to set camera list", fault);
                }
                                 ));

                int deviceIndex;

                if (initialState.Selected != null &&
                    (!string.IsNullOrEmpty(initialState.Selected.DevicePath) ||
                     !string.IsNullOrEmpty(initialState.Selected.FriendlyName)))
                {
                    deviceIndex = -1;
                }
                else
                {
                    deviceIndex = 0;
                }

                bool gotDevice = false;
                while (deviceIndex < state.Cameras.Count && !gotDevice)
                {
                    UpdateDeviceRequest request = new UpdateDeviceRequest();

                    if (deviceIndex < 0)
                    {
                        request.Selected       = initialState.Selected;
                        request.Selected.InUse = false;
                    }
                    else if (deviceIndex < state.Cameras.Count)
                    {
                        request.Selected = state.Cameras[deviceIndex];
                    }

                    if (!request.Selected.InUse)
                    {
                        UpdateDevice update = new UpdateDevice();
                        update.Body = request;
                        _fwdPort.Post(update);

                        yield return(Arbiter.Choice(
                                         update.ResponsePort,
                                         success => gotDevice = true,
                                         fault => LogInfo("Unable to select camera: " + deviceIndex + ": " + fault)
                                         ));
                    }
                    else
                    {
                        LogInfo("Not trying camera (InUse = true): " + deviceIndex);
                    }

                    deviceIndex++;
                }

                if (!gotDevice)
                {
                    LogError("Unable to select device");
                    yield break;
                }

                deviceSelected = true;

                if (initialState.Selected == null ||
                    initialState.Selected.Format == null)
                {
                    yield break;
                }

                UpdateFormat updateFormat = new UpdateFormat();
                updateFormat.Body = initialState.Selected.Format;

                _fwdPort.Post(updateFormat);

                yield return(Arbiter.Choice(
                                 updateFormat.ResponsePort,
                                 delegate(DefaultUpdateResponseType success) { },
                                 delegate(Fault fault)
                {
                    LogError(null, "Unable to select format", fault);
                }
                                 ));
            }
            finally
            {
                if (deviceSelected)
                {
                    DirectoryInsert();
                }
                else
                {
                    LogWarning(LogGroups.Console, "Dropping webcam service, no cameras found");
                    _fwdPort.Post(new DsspDefaultDrop());
                }
            }
        }
        /// <summary>
        /// Read data from the meter.
        /// </summary>
        private static void ReadMeter(object parameter)
        {
            GXDLMSReader reader = null;

            System.Net.Http.HttpClient httpClient = Helpers.client;
            using (GXNet media = (GXNet)parameter)
            {
                try
                {
                    var config = new ConfigurationBuilder()
                                 .SetBasePath(Directory.GetCurrentDirectory())
                                 .AddJsonFile("appsettings.json", optional: true)
                                 .Build();
                    ListenerOptions        listener = config.GetSection("Listener").Get <ListenerOptions>();
                    GXDLMSObjectCollection objects  = new GXDLMSObjectCollection();
                    GXDLMSSecureClient     client   = new GXDLMSSecureClient(listener.UseLogicalNameReferencing, listener.ClientAddress, listener.ServerAddress, (Authentication)listener.Authentication, listener.Password, (InterfaceType)listener.Interface);
                    reader = new GXDLMSReader(client, media, _logger);
                    GXDLMSData ldn = new GXDLMSData("0.0.42.0.0.255");
                    ldn.SetUIDataType(2, DataType.String);
                    reader.InitializeConnection();
                    reader.Read(ldn, 2);
                    Console.WriteLine("Meter connected: " + ldn.Value);
                    //Find device.
                    GXDevice            dev  = null;
                    ListDevicesResponse devs = null;
                    {
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                        {
                            Name = (string)ldn.Value
                        }).Result)
                        {
                            Helpers.CheckStatus(response);
                            devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                        }
                        //If device is unknown.
                        if (devs.Devices.Length == 0)
                        {
                            if (listener.DefaultDeviceTemplate == 0)
                            {
                                string str = "Unknown Meter try to connect to the Gurux.DLMS.AMI server: " + ldn.Value;
                                Console.WriteLine(str);
                                AddSystemError info = new AddSystemError();
                                info.Error = new GXSystemError()
                                {
                                    Error = str
                                };
                                using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                                {
                                    Helpers.CheckStatus(response);
                                }
                                return;
                            }
                            ListDeviceTemplates lt = new ListDeviceTemplates()
                            {
                                Ids = new UInt64[] { listener.DefaultDeviceTemplate }
                            };
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/template/ListDeviceTemplates", lt).Result)
                            {
                                Helpers.CheckStatus(response);
                                ListDeviceTemplatesResponse ret = response.Content.ReadAsAsync <ListDeviceTemplatesResponse>().Result;
                                if (ret.Devices.Length != 1)
                                {
                                    throw new Exception("DefaultDeviceTemplate value is invalid: " + listener.DefaultDeviceTemplate);
                                }
                                dev = new GXDevice();
                                GXDevice.Copy(dev, ret.Devices[0]);
                                dev.Name         = Convert.ToString(ldn.Value);
                                dev.TemplateId   = listener.DefaultDeviceTemplate;
                                dev.Manufacturer = ret.Devices[0].Name;
                            }
                            dev.Dynamic = true;
                            UpdateDevice update = new UpdateDevice();
                            update.Device = dev;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/UpdateDevice", update).Result)
                            {
                                Helpers.CheckStatus(response);
                                UpdateDeviceResponse r = response.Content.ReadAsAsync <UpdateDeviceResponse>().Result;
                                dev.Id = r.DeviceId;
                            }
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                            {
                                Ids = new UInt64[] { dev.Id }
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                            }
                        }
                        else if (devs.Devices.Length != 1)
                        {
                            throw new Exception("There are multiple devices with same name: " + ldn.Value);
                        }
                        else
                        {
                            dev = devs.Devices[0];
                            if (dev.Security != Security.None)
                            {
                                Console.WriteLine("Reading frame counter.");
                                GXDLMSData fc = new GXDLMSData(listener.InvocationCounter);
                                reader.Read(fc, 2);
                                dev.InvocationCounter = 1 + Convert.ToUInt32(fc.Value);
                                Console.WriteLine("Device ID: " + dev.Id + " LDN: " + (string)ldn.Value);
                                Console.WriteLine("Frame counter: " + dev.FrameCounter);
                            }
                            GetNextTaskResponse ret;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/GetNextTask", new GetNextTask()
                            {
                                Listener = true, DeviceId = dev.Id
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                ret = response.Content.ReadAsAsync <GetNextTaskResponse>().Result;
                            }
                            if (ret.Tasks == null || ret.Tasks.Length == 0)
                            {
                                Console.WriteLine("No tasks to execute");
                            }
                            else
                            {
                                Console.WriteLine("Task count: " + ret.Tasks.Length);
                                if (client.ClientAddress != dev.ClientAddress || dev.Security != Security.None)
                                {
                                    reader.Release();
                                    reader.Disconnect();
                                    client             = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, dev.ClientAddress, dev.PhysicalAddress, (Authentication)dev.Authentication, dev.Password, dev.InterfaceType);
                                    client.UtcTimeZone = dev.UtcTimeZone;
                                    client.Standard    = (Standard)dev.Standard;
                                    if (dev.Conformance != 0)
                                    {
                                        client.ProposedConformance = (Conformance)dev.Conformance;
                                    }
                                    client.Priority                    = dev.Priority;
                                    client.ServiceClass                = dev.ServiceClass;
                                    client.Ciphering.SystemTitle       = GXCommon.HexToBytes(dev.ClientSystemTitle);
                                    client.Ciphering.BlockCipherKey    = GXCommon.HexToBytes(dev.BlockCipherKey);
                                    client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(dev.AuthenticationKey);
                                    client.ServerSystemTitle           = GXCommon.HexToBytes(dev.DeviceSystemTitle);
                                    client.Ciphering.InvocationCounter = dev.InvocationCounter;
                                    client.Ciphering.Security          = (Security)dev.Security;
                                    reader = new GXDLMSReader(client, media, _logger);
                                    reader.InitializeConnection();
                                }
                                List <GXValue> values = new List <GXValue>();
                                foreach (GXTask task in ret.Tasks)
                                {
                                    GXDLMSObject obj = GXDLMSClient.CreateObject((ObjectType)task.Object.ObjectType);
                                    obj.LogicalName = task.Object.LogicalName;
                                    try
                                    {
                                        if (task.TaskType == TaskType.Write)
                                        {
                                            if (obj.LogicalName == "0.0.1.1.0.255" && task.Index == 2)
                                            {
                                                client.UpdateValue(obj, task.Index, GXDateTime.ToUnixTime(DateTime.UtcNow));
                                            }
                                            else
                                            {
                                                client.UpdateValue(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data));
                                            }
                                            reader.Write(obj, task.Index);
                                        }
                                        else if (task.TaskType == TaskType.Action)
                                        {
                                            reader.Method(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data), DataType.None);
                                        }
                                        else if (task.TaskType == TaskType.Read)
                                        {
                                            Reader.Reader.Read(null, httpClient, reader, task, media, obj);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        task.Result = ex.Message;
                                        AddError error = new AddError();
                                        error.Error = new GXError()
                                        {
                                            DeviceId = dev.Id,
                                            Error    = "Failed to " + task.TaskType + " " + task.Object.LogicalName + ":" + task.Index + ". " + ex.Message
                                        };
                                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error).Result)
                                        {
                                            Helpers.CheckStatus(response);
                                            response.Content.ReadAsAsync <AddErrorResponse>();
                                        }
                                    }
                                    using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady()
                                    {
                                        Tasks = new GXTask[] { task }
                                    }).Result)
                                    {
                                        Helpers.CheckStatus(response);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        AddSystemError info = new AddSystemError();
                        info.Error = new GXSystemError()
                        {
                            Error = ex.Message
                        };
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                        {
                            Helpers.CheckStatus(response);
                        }
                    }
                    catch (Exception ex2)
                    {
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
 public async Task <IActionResult> Put(Guid id, UpdateDevice command)
 => await SendAsync(command.Bind(c => c.Id, id),
                    resourceId : command.Id, resource : "devices");
Exemple #19
0
 IEnumerator <ITask> UpdateDeviceHandler(UpdateDevice update)
 {
     UpdateDeviceInternal(update);
     yield break;
 }
 public Task <HuePutResponse> UpdateDevice(Guid id, UpdateDevice data) => HuePutRequest(ResourceIdUrl(DeviceUrl, id), data);
Exemple #21
0
 protected virtual void OnUpdateDevice(IUpdateDevice packet)
 {
     UpdateDevice.Raise(this, new EventArgs <IUpdateDevice> {
         Value = packet
     });
 }