Exemplo n.º 1
0
        public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
        {
            var objs         = MockHassModelFactory.PanelInfoFaker.Generate(10).ToDistinctDictionary(x => x.ComponentName);
            var resultObject = new JRaw(HassSerializer.SerializeObject(objs));

            return(this.CreateResultMessageWithResult(resultObject));
        }
        protected virtual object ProccessDeleteCommand(MockHassServerRequestContext context, JToken merged)
        {
            var model = this.DeserializeModel(merged, out var _);

            context.HassDB.DeleteObject(model);
            return(null);
        }
        protected override void PrepareHassContext(MockHassServerRequestContext context)
        {
            base.PrepareHassContext(context);
            var ownerUser = User.CreateUnmodified(this.faker.RandomUUID(), "owner", true);

            context.HassDB.CreateObject(ownerUser);
        }
Exemplo n.º 4
0
        protected override object ProccessUnknownCommand(string commandType, MockHassServerRequestContext context, JToken merged)
        {
            var entityId = merged.Value <string>("entity_id");

            if (string.IsNullOrEmpty(entityId))
            {
                return(ErrorCodes.InvalidFormat);
            }

            if (commandType.EndsWith("get"))
            {
                return(this.FindRegistryEntry(context, entityId, createIfNotFound: true));
            }
            else if (commandType.EndsWith("remove"))
            {
                var mockEntry = this.FindRegistryEntry(context, entityId, createIfNotFound: false);
                if (mockEntry == null)
                {
                    return(ErrorCodes.NotFound);
                }

                context.HassDB.DeleteObject(mockEntry);
                var result = context.HassDB.DeleteObject(mockEntry.Entry);
                return(result ? null : (object)ErrorCodes.NotFound);
            }

            return(base.ProccessUnknownCommand(commandType, context, merged));
        }
Exemplo n.º 5
0
        public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
        {
            var configuration = MockHassModelFactory.ConfigurationFaker.Generate();
            var resultObject  = new JRaw(HassSerializer.SerializeObject(configuration));

            return(this.CreateResultMessageWithResult(resultObject));
        }
        public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
        {
            if (receivedCommand is SubscribeEventsMessage subscribeMessage)
            {
                var eventType = subscribeMessage.EventType ?? KnownEventTypes.Any.ToEventTypeString();
                if (!this.subscribersByEventType.TryGetValue(eventType, out var subcribers))
                {
                    subcribers = new List <uint>();
                    this.subscribersByEventType.Add(eventType, subcribers);
                }
                subcribers.Add(subscribeMessage.Id);
                return(this.CreateResultMessageWithResult(null));
            }
            else if (receivedCommand is UnsubscribeEventsMessage unsubscribeMessage)
            {
                foreach (var item in this.subscribersByEventType.Values)
                {
                    if (item.Remove(unsubscribeMessage.SubscriptionId))
                    {
                        //success = true;
                        break;
                    }
                }
            }

            return(this.CreateResultMessageWithResult(null));
        }
Exemplo n.º 7
0
        protected override object ProccessUpdateCommand(MockHassServerRequestContext context, JToken merged)
        {
            var newEntityIdProperty = merged.FirstOrDefault(x => (x is JProperty property) && property.Name == "new_entity_id");
            var newEntityId         = (string)newEntityIdProperty;

            newEntityIdProperty?.Remove();

            var entityIdProperty = merged.FirstOrDefault(x => (x is JProperty property) && property.Name == "entity_id");
            var entityId         = (string)entityIdProperty;
            var result           = this.FindRegistryEntry(context, entityId, createIfNotFound: true);

            if (result != null)
            {
                if (newEntityId != null)
                {
                    context.HassDB.DeleteObject(result.Entry);
                    ((JProperty)entityIdProperty).Value = newEntityId;
                }

                this.PopulateModel(merged, result);

                if (newEntityId != null)
                {
                    context.HassDB.CreateObject(result.Entry);
                }
            }

            return(new EntityEntryResponse()
            {
                EntityEntryRaw = new JRaw(HassSerializer.SerializeObject(result))
            });
        }
Exemplo n.º 8
0
        private MockRegistryEntity FindRegistryEntry(MockHassServerRequestContext context, string entityId, bool createIfNotFound)
        {
            var hassDB = context.HassDB;
            var result = hassDB.GetObjects <MockRegistryEntity>()?.FirstOrDefault(x => x.EntityId == entityId);

            if (result != null)
            {
                return(result);
            }

            var entry = hassDB.FindEntityEntry(entityId);

            if (entry == null)
            {
                return(null);
            }

            result = new MockRegistryEntity(entry);

            if (createIfNotFound)
            {
                hassDB.CreateObject(result);
            }

            return(result);
        }
        protected virtual object ProccessCreateCommand(MockHassServerRequestContext context, JToken merged)
        {
            var model = this.DeserializeModel(merged, out var _);

            this.idPropertyInfo.SetValue(model, this.faker.RandomUUID());
            context.HassDB.CreateObject(model);
            return(model);
        }
        protected override object ProccessUpdateCommand(MockHassServerRequestContext context, JToken merged)
        {
            var user = base.ProccessUpdateCommand(context, merged);

            return(new UserResponse()
            {
                UserRaw = new JRaw(HassSerializer.SerializeObject(user))
            });
        }
Exemplo n.º 11
0
 public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
 {
     using (var stream = this.GetResourceStream("GetServicesResponse.json"))
         using (var sr = new StreamReader(stream))
             using (var reader = new JsonTextReader(sr))
             {
                 var resultObject = JRaw.Create(reader);
                 return(this.CreateResultMessageWithResult(resultObject));
             }
 }
Exemplo n.º 12
0
        public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
        {
            var rawCommand  = (RawCommandMessage)receivedCommand;
            var messageType = rawCommand.Type;

            return(new ResultMessage()
            {
                Success = true
            });
        }
        public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
        {
            var callServiceMsg = receivedCommand as CallServiceMessage;
            var state          = new StateModel()
            {
                Context = MockHassModelFactory.ContextFaker.Generate()
            };
            var resultObject = new JRaw(HassSerializer.SerializeObject(state));

            return(this.CreateResultMessageWithResult(resultObject));
        }
        public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
        {
            try
            {
                if (!this.isContextReady)
                {
                    this.isContextReady = true;
                    this.PrepareHassContext(context);
                }

                var    merged      = (receivedCommand as RawCommandMessage).MergedObject as JToken;
                var    commandType = receivedCommand.Type;
                object result      = null;

                if (commandType.EndsWith("list"))
                {
                    result = this.ProccessListCommand(context, merged);
                }
                else if (commandType.EndsWith("create"))
                {
                    result = this.ProccessCreateCommand(context, merged);
                }
                else if (commandType.EndsWith("delete"))
                {
                    result = this.ProccessDeleteCommand(context, merged);
                }
                else if (commandType.EndsWith("update"))
                {
                    result = (object)this.ProccessUpdateCommand(context, merged) ?? ErrorCodes.NotFound;
                }
                else
                {
                    result = this.ProccessUnknownCommand(commandType, context, merged);
                }

                if (result is ErrorCodes errorCode)
                {
                    return(this.CreateResultMessageWithError(new ErrorInfo(errorCode)));
                }
                else
                {
                    var resultObject = new JRaw(HassSerializer.SerializeObject(result));
                    return(this.CreateResultMessageWithResult(resultObject));
                }
            }
            catch (Exception ex)
            {
                return(this.CreateResultMessageWithError(new ErrorInfo(ErrorCodes.UnknownError)
                {
                    Message = ex.Message
                }));
            }
        }
        protected override object ProccessListCommand(MockHassServerRequestContext context, JToken merged)
        {
            var result = base.ProccessListCommand(context, merged);

            if (typeof(TModel) == typeof(Person))
            {
                var persons = (IEnumerable <Person>)result;
                return(new PersonResponse()
                {
                    Storage = persons.Where(p => p.IsStorageEntry).ToArray(),
                    Config = persons.Where(p => !p.IsStorageEntry).ToArray(),
                });
            }

            return(result);
        }
Exemplo n.º 16
0
        protected override void PrepareHassContext(MockHassServerRequestContext context)
        {
            base.PrepareHassContext(context);
            var hassDB = context.HassDB;

            hassDB.CreateObject(new MockRegistryEntity("light.bed_light", "Bed Light")
            {
                UniqueId      = this.faker.RandomUUID(),
                ConfigEntryId = this.faker.RandomUUID(),
            });

            hassDB.CreateObject(new MockRegistryEntity("switch.fake_switch", "Fake Switch", "mdi: switch", DisabledByEnum.Integration)
            {
                UniqueId      = this.faker.RandomUUID(),
                ConfigEntryId = this.faker.RandomUUID()
            });
        }
Exemplo n.º 17
0
        public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
        {
            var commandEntitySource = receivedCommand as EntitySourceMessage;
            IEnumerable <EntitySource> objs;

            if (commandEntitySource.EntityIds?.Count() > 0)
            {
                objs = MockHassModelFactory.EntitySourceFaker.GenerateWithEntityIds(commandEntitySource.EntityIds);
            }
            else
            {
                objs = MockHassModelFactory.EntitySourceFaker.Generate(10);
            }

            var resultObject = new JRaw(HassSerializer.SerializeObject(objs.ToDistinctDictionary(x => x.EntityId)));

            return(this.CreateResultMessageWithResult(resultObject));
        }
Exemplo n.º 18
0
        public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
        {
            var searchMessage  = receivedCommand as SearchRelatedMessage;
            var resultResponse = new SearchRelatedResponse();

            if (searchMessage.ItemType == ItemTypes.Entity &&
                searchMessage.ItemId == "light.bed_light")
            {
                var faker = new Faker();
                resultResponse.AreaIds        = new[] { faker.RandomUUID() };
                resultResponse.AutomationIds  = new[] { faker.RandomUUID() };
                resultResponse.ConfigEntryIds = new[] { faker.RandomUUID() };
                resultResponse.DeviceIds      = new[] { faker.RandomUUID() };
                resultResponse.EntityIds      = new[] { faker.RandomEntityId() };
            }

            var resultObject = new JRaw(HassSerializer.SerializeObject(resultResponse));

            return(this.CreateResultMessageWithResult(resultObject));
        }
        public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
        {
            var commandRenderTemplate = receivedCommand as RenderTemplateMessage;

            this.entityIds = new HashSet <string>();
            var result    = Regex.Replace(commandRenderTemplate.Template, @"{{ (.*) }}", this.RenderTemplateValue);
            var listeners = new ListenersTemplateInfo()
            {
                All  = false,
                Time = false,
            };

            listeners.Entities = this.entityIds.ToArray();
            listeners.Domains  = listeners.Entities.Select(x => x.GetDomain()).ToArray();
            this.entityIds     = null;

            var renderTemplateEvent = new TemplateEventInfo()
            {
                Result    = result,
                Listeners = listeners,
            };

            var eventMsg = new EventResultMessage()
            {
                Id    = commandRenderTemplate.Id,
                Event = new JRaw(HassSerializer.SerializeObject(renderTemplateEvent))
            };

            Task.Factory.StartNew(async() =>
            {
                await Task.Delay(40);
                await context.SendMessageAsync(eventMsg, CancellationToken.None);
            });

            return(this.CreateResultMessageWithResult(null));
        }
 protected override void PrepareHassContext(MockHassServerRequestContext context)
 {
     base.PrepareHassContext(context);
     context.HassDB.CreateObject(MockHassModelFactory.DeviceFaker.Generate());
 }
Exemplo n.º 21
0
 protected override object ProccessListCommand(MockHassServerRequestContext context, JToken merged)
 {
     return(context.HassDB.GetAllEntityEntries().Select(x => x as EntityRegistryEntry ?? EntityRegistryEntry.CreateFromEntry(x)));
 }
Exemplo n.º 22
0
 public abstract BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand);
 protected virtual object ProccessUnknownCommand(string commandType, MockHassServerRequestContext context, JToken merged)
 {
     return(ErrorCodes.NotSupported);
 }
 protected virtual void PrepareHassContext(MockHassServerRequestContext context)
 {
 }
 protected override object ProccessListCommand(MockHassServerRequestContext context, JToken merged)
 {
     return(base.ProccessListCommand(context, merged));
 }
        protected virtual object ProccessUpdateCommand(MockHassServerRequestContext context, JToken merged)
        {
            var model = this.DeserializeModel(merged, out var modelSerialized);

            return(context.HassDB.UpdateObject(model, new JRaw(modelSerialized)));
        }
Exemplo n.º 27
0
        protected override async Task RespondToWebSocketRequestAsync(WebSocket webSocket, CancellationToken cancellationToken)
        {
            var context = new MockHassServerRequestContext(this.hassDB, webSocket);

            await context.SendMessageAsync(new AuthenticationRequiredMessage()
            {
                HAVersion = this.HAVersion.ToString()
            }, cancellationToken);

            try
            {
                while (true)
                {
                    if (context.IsAuthenticating)
                    {
                        var incomingMessage = await context.ReceiveMessageAsync <BaseMessage>(cancellationToken);

                        await Task.Delay(this.ResponseSimulatedDelay);

                        if (!this.IgnoreAuthenticationMessages &&
                            incomingMessage is AuthenticationMessage authMessage)
                        {
                            if (authMessage.AccessToken == this.ConnectionParameters.AccessToken)
                            {
                                await context.SendMessageAsync(new AuthenticationOkMessage()
                                {
                                    HAVersion = this.HAVersion.ToString()
                                }, cancellationToken);

                                context.IsAuthenticating  = false;
                                this.activeRequestContext = context;
                            }
                            else
                            {
                                await context.SendMessageAsync(new AuthenticationInvalidMessage(), cancellationToken);

                                break;
                            }
                        }
                    }
                    else
                    {
                        var receivedMessage = await context.ReceiveMessageAsync <BaseOutgoingMessage>(cancellationToken);

                        var receivedMessageId = receivedMessage.Id;

                        await Task.Delay(this.ResponseSimulatedDelay);

                        BaseIdentifiableMessage response;
                        if (context.LastReceivedID >= receivedMessageId)
                        {
                            response = new ResultMessage()
                            {
                                Error = new ErrorInfo(ErrorCodes.IdReuse)
                            };
                        }
                        else
                        {
                            context.LastReceivedID = receivedMessageId;

                            if (receivedMessage is PingMessage)
                            {
                                response = new PongMessage();
                            }
                            else if (!context.TryProccesMessage(receivedMessage, out response))
                            {
                                response = new ResultMessage()
                                {
                                    Error = new ErrorInfo(ErrorCodes.UnknownCommand)
                                };
                            }
                        }

                        response.Id = receivedMessageId;
                        await context.SendMessageAsync(response, cancellationToken);
                    }
                }
            }
            catch
            {
                Trace.WriteLine("A problem occured while attending client. Closing connection.");
                await webSocket.CloseAsync(WebSocketCloseStatus.InternalServerError, string.Empty, default);
            }
        }
 protected virtual object ProccessListCommand(MockHassServerRequestContext context, JToken merged)
 {
     return(context.HassDB.GetObjects <TModel>());
 }
Exemplo n.º 29
0
 public override BaseIdentifiableMessage ProccessCommand(MockHassServerRequestContext context, BaseIdentifiableMessage receivedCommand)
 {
     return(new PongMessage());
 }