コード例 #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));
        }
コード例 #2
0
        public void TryGetEnumFromSnakeCase()
        {
            var success = HassSerializer.TryGetEnumFromSnakeCase <TestEnum>(expectedTestValueEnumResult, out var result);

            Assert.IsTrue(success);
            Assert.AreEqual(TestEnum.TestValue, result);
        }
コード例 #3
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));
        }
コード例 #4
0
        public void TryGetEnumFromSnakeCaseWithInvalidValue()
        {
            var success = HassSerializer.TryGetEnumFromSnakeCase <TestEnum>("invalid_value", out var result);

            Assert.IsFalse(success);
            Assert.AreEqual(default(TestEnum), result);
        }
コード例 #5
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))
            });
        }
コード例 #6
0
        /// <summary>
        /// Creates a <see cref="BaseOutgoingMessage"/> used in specific operations for certain collection registry items.
        /// </summary>
        /// <param name="customOpName">The custom operation name.</param>
        /// <param name="modelId">The unique identifier of the collection registry item.</param>
        /// <param name="model">The object model involved in the operation, if any.</param>
        /// <param name="selectedProperties">White-list containing the name of the properties to extract from the <paramref name="model"/> object.
        /// When <see langword="null"/>, no filter will be applied.</param>
        /// <returns>A <see cref="BaseOutgoingMessage"/> used in specific operations for certain collection registry items.</returns>
        protected BaseOutgoingMessage CreateCustomOperationMessage(string customOpName, string modelId, TModel model = null, IEnumerable <string> selectedProperties = null)
        {
            var mergedObject = model != null?HassSerializer.CreateJObject(model, selectedProperties) : new JObject();

            this.AddModelIdProperty(mergedObject, modelId);
            return(new RawCommandMessage($"{this.apiPrefix}/{customOpName}", mergedObject));
        }
コード例 #7
0
        /// <summary>
        /// Creates a <see cref="BaseOutgoingMessage"/> used to update an existing item from the collection registry.
        /// </summary>
        /// <param name="modelId">The unique identifier of the collection registry item to update.</param>
        /// <param name="model">The object model to be updated.</param>
        /// <param name="selectedProperties">White-list containing the name of the properties to extract from the <paramref name="model"/> object.
        /// When <see langword="null"/>, no filter will be applied.</param>
        /// <returns>
        /// A <see cref="BaseOutgoingMessage"/> used to update an existing item from the collection registry.
        /// </returns>
        protected BaseOutgoingMessage CreateUpdateMessage(string modelId, object model, IEnumerable <string> selectedProperties = null)
        {
            var mergedObject = HassSerializer.CreateJObject(model, selectedProperties);

            this.AddModelIdProperty(mergedObject, modelId);
            return(new RawCommandMessage($"{this.apiPrefix}/update", mergedObject));
        }
コード例 #8
0
        public void EnumValuesAreConvertedFromSnakeCase()
        {
            var result = HassSerializer.DeserializeObject <TestEnum>($"\"{expectedTestValueEnumResult}\"");

            Assert.NotNull(result);
            Assert.AreEqual(TestEnum.TestValue, result);
        }
コード例 #9
0
        public void FieldsAreConvertedFromSnakeCase()
        {
            var result = HassSerializer.DeserializeObject <TestClass>($"{{\"{expectedTestFieldResult}\":\"{nameof(TestClass.TestField)}\"}}");

            Assert.NotNull(result);
            Assert.AreEqual(nameof(TestClass.TestField), result.TestField);
        }
コード例 #10
0
        public void EnumValuesAreConvertedToSnakeCase()
        {
            var value  = TestEnum.TestValue;
            var result = HassSerializer.SerializeObject(value);

            Assert.NotNull(result);
            Assert.AreEqual($"\"{expectedTestValueEnumResult}\"", result);
        }
コード例 #11
0
        public async Task SendMessageAsync(BaseMessage message, CancellationToken cancellationToken)
        {
            var sendMsg    = HassSerializer.SerializeObject(message);
            var sendBytes  = Encoding.UTF8.GetBytes(sendMsg);
            var sendBuffer = new ArraySegment <byte>(sendBytes);

            await this.WebSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, endOfMessage : true, cancellationToken);
        }
コード例 #12
0
        protected virtual PropertyInfo GetModelIdPropertyInfo()
        {
            var modelType       = typeof(TModel);
            var properties      = modelType.GetProperties();
            var modelIdProperty = properties.FirstOrDefault(x => HassSerializer.GetSerializedPropertyName(x) == this.modelIdPropertyName);

            return(modelIdProperty ?? properties.Where(x => x.Name.EndsWith("Id")).OrderBy(x => x.Name.Length).FirstOrDefault());
        }
コード例 #13
0
        protected override object ProccessUpdateCommand(MockHassServerRequestContext context, JToken merged)
        {
            var user = base.ProccessUpdateCommand(context, merged);

            return(new UserResponse()
            {
                UserRaw = new JRaw(HassSerializer.SerializeObject(user))
            });
        }
コード例 #14
0
        private object UpdateObject(Type key, object target, JRaw value)
        {
            if (this.collectionsByType.TryGetValue(key, out var collection) &&
                collection.TryGetValue(target, out var actual))
            {
                HassSerializer.PopulateObject(value, actual);
                return(actual);
            }

            return(default);
コード例 #15
0
        public void EnumValuesAreConvertedToSnakeCasePriorizingEnumMemberAttribute()
        {
            var value       = TestEnum.EnumMemberTestValue;
            var memInfo     = typeof(TestEnum).GetMember(value.ToString());
            var attribValue = memInfo[0].GetCustomAttribute <EnumMemberAttribute>().Value;
            var result      = HassSerializer.SerializeObject(value);

            Assert.NotNull(result);
            Assert.AreEqual($"\"{attribValue}\"", result);
        }
コード例 #16
0
        public void JObjectWithSelectedProperties()
        {
            var selectedProperties = new[] { nameof(TestClass.TestProperty) };
            var result             = HassSerializer.CreateJObject(new TestClass(), selectedProperties);

            Assert.NotNull(result);
            Assert.AreEqual(1, result.Count);
            Assert.IsTrue(result.ContainsKey(expectedTestPropertyResult));
            Assert.IsFalse(result.ContainsKey(expectedTestFieldResult));
        }
コード例 #17
0
        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));
        }
コード例 #18
0
 /// <summary>
 /// Deserializes the event <see cref="Data"/> to the specified .NET type.
 /// </summary>
 /// <typeparam name="T">The type of the object to deserialize to.</typeparam>
 /// <returns>The deserialized data object.</returns>
 public T DeserializeData <T>()
 {
     try
     {
         return(HassSerializer.DeserializeObject <T>(this.Data));
     }
     catch (JsonException)
     {
         throw;
     }
 }
コード例 #19
0
        public void JObjectFieldsAreConvertedToSnakeCase()
        {
            var value = new TestClass()
            {
                TestField = nameof(TestClass.TestField)
            };
            var result = HassSerializer.CreateJObject(value);

            Assert.NotNull(result);
            Assert.AreEqual(value.TestField, result.GetValue(expectedTestFieldResult).ToString());
        }
コード例 #20
0
        public void FieldsAreConvertedToSnakeCase()
        {
            var value = new TestClass()
            {
                TestField = nameof(TestClass.TestField)
            };
            var result = HassSerializer.SerializeObject(value);

            Assert.NotNull(result);
            Assert.IsTrue(result.Contains($"\"{expectedTestFieldResult}\":\"{value.TestField}\""));
        }
コード例 #21
0
        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
                }));
            }
        }
コード例 #22
0
        private string GetModelSerialized(JToken merged)
        {
            string modelSerialized = HassSerializer.SerializeObject(merged);
            var    idPropertyName  = HassSerializer.GetSerializedPropertyName(idPropertyInfo);

            if (this.modelIdPropertyName != idPropertyName)
            {
                modelSerialized = modelSerialized.Replace(this.modelIdPropertyName, idPropertyName);
            }

            return(modelSerialized);
        }
コード例 #23
0
        public BaseOutgoingMessage CreateUpdateMessage(Device device, bool?disable, bool forceUpdate)
        {
            var model = this.CreateDefaultUpdateObject(device, forceUpdate);

            if (disable.HasValue)
            {
                var merged = HassSerializer.CreateJObject(new { DisabledBy = disable.Value ? DisabledByEnum.User : (DisabledByEnum?)null });
                model.Merge(merged);
            }

            return(this.CreateUpdateMessage(device.Id, model));
        }
コード例 #24
0
        private async Task <StateChangedEvent> ForceStateChangedAndGetEventData(MockEventSubscriber subscriber)
        {
            var domain = testEntitytId.GetDomain();
            var update = await this.hassWSApi.CallServiceForEntitiesAsync(domain, "toggle", testEntitytId);

            Assert.NotNull(update, "SetUp failed");

            var eventResultInfo = await subscriber.WaitFirstEventArgWithTimeoutAsync <EventResultInfo>(
                (x) => HassSerializer.TryGetEnumFromSnakeCase <KnownEventTypes>(x.EventType, out var knownEventType) &&
                knownEventType == KnownEventTypes.StateChanged,
                500);

            Assert.NotNull(eventResultInfo, "SetUp failed");

            return(eventResultInfo.DeserializeData <StateChangedEvent>());
        }
コード例 #25
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));
        }
コード例 #26
0
        public async Task <TMessage> ReceiveMessageAsync <TMessage>(CancellationToken cancellationToken)
            where TMessage : BaseMessage
        {
            var receivedString = new StringBuilder();
            WebSocketReceiveResult rcvResult;

            do
            {
                rcvResult = await this.WebSocket.ReceiveAsync(this.receivingBuffer, cancellationToken);

                byte[] msgBytes = this.receivingBuffer.Skip(this.receivingBuffer.Offset).Take(rcvResult.Count).ToArray();
                receivedString.Append(Encoding.UTF8.GetString(msgBytes));
            }while (!rcvResult.EndOfMessage);

            var rcvMsg = receivedString.ToString();

            return(HassSerializer.DeserializeObject <TMessage>(rcvMsg));
        }
コード例 #27
0
        public BaseOutgoingMessage CreateUpdateMessage(EntityRegistryEntry entity, string newEntityId, bool?disable, bool forceUpdate)
        {
            var model = this.CreateDefaultUpdateObject(entity, forceUpdate);

            if (newEntityId != null)
            {
                var merged = HassSerializer.CreateJObject(new { NewEntityId = newEntityId });
                model.Merge(merged);
            }

            if (disable.HasValue)
            {
                var merged = HassSerializer.CreateJObject(new { DisabledBy = disable.Value ? DisabledByEnum.User : (DisabledByEnum?)null });
                model.Merge(merged);
            }

            return(this.CreateUpdateMessage(entity.EntityId, model));
        }
コード例 #28
0
        public Task <bool> RaiseStateChangedEventAsync(string entityId)
        {
            var data = MockHassModelFactory.StateChangedEventFaker
                       .GenerateWithEntityId(entityId);

            var eventResult = new EventResultInfo()
            {
                EventType = KnownEventTypes.StateChanged.ToEventTypeString(),
                Origin    = "mock_server",
                TimeFired = DateTimeOffset.Now,
                Data      = new JRaw(HassSerializer.SerializeObject(data)),
                Context   = data.OldState.Context
            };

            var eventResultObject = new JRaw(HassSerializer.SerializeObject(eventResult));

            return(this.RaiseEventAsync(KnownEventTypes.StateChanged, eventResultObject));
        }
コード例 #29
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));
        }
コード例 #30
0
        public TEnum AsEnum(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                if (this.valueForNullString.HasValue)
                {
                    return(this.valueForNullString.Value);
                }
                else
                {
                    throw new ArgumentException($"'{nameof(value)}' cannot be null or empty", nameof(value));
                }
            }

            if (!this.cache.Forward.TryGetValue(value, out var result) &&
                HassSerializer.TryGetEnumFromSnakeCase(value, out result))
            {
                this.cache.Add(value, result);
            }

            return(result);
        }