Exemplo n.º 1
0
        public async Task Verifier_Message_SimpleTest_Invalid()
        {
            var msgDefinition = new DeviceMessageDefinition();

            var verifier = new Verifier
            {
                ShouldSucceed = true,
                VerifierType  = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageFieldParser),
                InputType     = EntityHeader <InputTypes> .Create(InputTypes.Binary),
                Input         = "03 32 05"
            };

            verifier.ExpectedOutputs.Add(new ExpectedValue()
            {
                Key = "key1", Value = "8"
            });
            verifier.ExpectedOutputs.Add(new ExpectedValue()
            {
                Key = "key2", Value = "value1"
            });

            var parserMgr = GetParserManager(new KeyValuePair <string, string>("key1", "5"), new KeyValuePair <string, string>("key2", "value1"));
            var verifiers = new MessageParserVerifierRuntime(parserMgr, _resultRepo.Object, _deviceAdminManager.Object);
            var result    = await verifiers.VerifyAsync(new IoT.Runtime.Core.Models.Verifiers.VerificationRequest <DeviceMessageDefinition>()
            {
                Verifier      = verifier,
                Configuration = msgDefinition
            }, null, null);

            WriteResults(result);

            Assert.IsFalse(result.Success);
            Assert.AreEqual(1, result.IterationsCompleted);
        }
        public async Task <InvokeResult> AddDeviceMessageDefinitionAsync(DeviceMessageDefinition deviceMessageConfiguration, EntityHeader org, EntityHeader user)
        {
            await AuthorizeAsync(deviceMessageConfiguration, AuthorizeActions.Create, user, org);

            ValidationCheck(deviceMessageConfiguration, Actions.Create);
            await _deviceMessageDefinitionRepo.AddDeviceMessageDefinitionAsync(deviceMessageConfiguration);

            return(InvokeResult.Success);
        }
Exemplo n.º 3
0
 public static void AddByte(this DeviceMessageDefinition msgDefinition, string key)
 {
     msgDefinition.Fields.Add(new DeviceMessageDefinitionField()
     {
         Key                   = "key1",
         SearchLocation        = EntityHeader <SearchLocations> .Create(SearchLocations.Body), BinaryOffset = 2,
         ParsedBinaryFieldType = EntityHeader <ParseBinaryValueType> .Create(ParseBinaryValueType.Byte)
     });
 }
Exemplo n.º 4
0
        public DeviceMessageDefinition GetDeviceMessage(string name = "msg1", string key = "msg1")
        {
            var msg = new DeviceMessageDefinition();

            msg.Name = name;
            msg.Key  = key;
            msg.Fields.Add(GetDeviceMessageField(name, key));

            return(msg);
        }
Exemplo n.º 5
0
 public InvokeResult Parse(PipelineExecutionMessage pem, DeviceMessageDefinition definition)
 {
     foreach (var kvp in KVPs)
     {
         pem.Envelope.Values.Add(kvp.Key, new MessageValue()
         {
             Value = kvp.Value
         });
     }
     return(InvokeResult.Success);
 }
        public async Task <InvokeResult <DeviceMessageDefinition> > LoadFullDeviceMessageDefinitionAsync(string id, EntityHeader org, EntityHeader user)
        {
            DeviceMessageDefinition message = null;

            try
            {
                message = await _deviceMessageDefinitionRepo.GetDeviceMessageDefinitionAsync(id);
            }
            catch (RecordNotFoundException)
            {
                return(InvokeResult <DeviceMessageDefinition> .FromErrors(Resources.DeviceMessagingAdminErrorCodes.CouldNotLoadDeviceMessageDefinition.ToErrorMessage($"MessageId={id}")));
            }

            var result = new InvokeResult <DeviceMessageDefinition>();

            foreach (var field in message.Fields)
            {
                if (!EntityHeader.IsNullOrEmpty(field.UnitSet))
                {
                    try
                    {
                        field.UnitSet.Value = await _deviceAdminManager.GetAttributeUnitSetAsync(field.UnitSet.Id, org, user);
                    }
                    catch (RecordNotFoundException)
                    {
                        result.Errors.Add(DeviceMessagingAdminErrorCodes.CouldNotLoadUnitSet.ToErrorMessage($"MessageId={id},UnitSetId={field.UnitSet.Id}"));
                    }
                }

                if (!EntityHeader.IsNullOrEmpty(field.StateSet))
                {
                    try
                    {
                        field.StateSet.Value = await _deviceAdminManager.GetStateSetAsync(field.StateSet.Id, org, user);
                    }
                    catch (RecordNotFoundException)
                    {
                        result.Errors.Add(DeviceMessagingAdminErrorCodes.CouldNotLoadStateSet.ToErrorMessage($"MessageId={id},StateSetId={field.StateSet.Id}"));
                    }
                }
            }

            if (result.Successful)
            {
                return(InvokeResult <DeviceMessageDefinition> .Create(message));
            }

            return(result);
        }
        public void Init()
        {
            _messageDefinition = GetDeviceMessage();
            _deviceWorkflow    = GetWorkflow();
            _moduleConfig      = new RouteModuleConfig
            {
                PrimaryOutput = new RouteConnection()
            };
            RefreshMapping();

            _outputTranslatorConfig = new OutputTranslatorConfiguration()
            {
                Key = "key1"
            };
        }
Exemplo n.º 8
0
        public async Task <DeviceConfiguration> AddDeviceConfigAsync(string name, string key, SentinelConfiguration sentinal,
                                                                     InputTranslatorConfiguration input, DeviceWorkflow workflow, OutputTranslatorConfiguration output,
                                                                     DeviceMessageDefinition msg, EntityHeader org, EntityHeader user, DateTime createTimestamp)
        {
            if (sentinal == null)
            {
                throw new ArgumentNullException(nameof(sentinal));
            }
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }
            if (workflow == null)
            {
                throw new ArgumentNullException(nameof(workflow));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }
            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg));
            }

            await _storageUtils.DeleteIfExistsAsync <DeviceConfiguration>(key, org);

            var deviceConfig = new DeviceConfiguration()
            {
                Id   = Guid.NewGuid().ToId(),
                Name = name,
                Key  = key,
            };

            AddOwnedProperties(deviceConfig, org);
            AddAuditProperties(deviceConfig, createTimestamp, org, user);

            var route = Route.Create();

            route.Name = "Motion Message Handler";
            route.Key  = EXAMPLE_MOTION_KEY;
            AddId(route);
            AddAuditProperties(route, createTimestamp, org, user);
            route.MessageDefinition = new EntityHeader <DeviceMessageDefinition>()
            {
                Id   = msg.Id,
                Text = msg.Name
            };

            var sentinalConfig = route.PipelineModules.Where(pm => pm.ModuleType.Value == PipelineModuleType.Sentinel).First();

            sentinalConfig.Name   = sentinal.Name;
            sentinalConfig.Key    = sentinal.Key;
            sentinalConfig.Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
            {
                Id   = sentinal.Id,
                Text = sentinal.Name
            };

            var inputTranslator = route.PipelineModules.Where(pm => pm.ModuleType.Value == PipelineModuleType.InputTranslator).First();

            inputTranslator.Name   = input.Name;
            inputTranslator.Key    = input.Key;
            inputTranslator.Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
            {
                Id   = input.Id,
                Text = input.Name
            };

            inputTranslator.PrimaryOutput.Mappings.Add(new KeyValuePair <string, object>("motion", "motionstatus"));

            var wf = route.PipelineModules.Where(pm => pm.ModuleType.Value == PipelineModuleType.Workflow).First();

            wf.Key    = workflow.Key;
            wf.Name   = workflow.Name;
            wf.Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
            {
                Id   = workflow.Id,
                Text = workflow.Name
            };

            var outputTranslator = route.PipelineModules.Where(pm => pm.ModuleType.Value == PipelineModuleType.OutputTranslator).First();

            outputTranslator.Name   = output.Name;
            outputTranslator.Key    = output.Key;
            outputTranslator.Module = new EntityHeader <DeviceAdmin.Interfaces.IPipelineModuleConfiguration>()
            {
                Id   = output.Id,
                Text = output.Name
            };

            deviceConfig.Routes.Add(route);

            await _deviceCfgMgr.AddDeviceConfigurationAsync(deviceConfig, org, user);


            return(deviceConfig);
        }
Exemplo n.º 9
0
        public async Task <DeviceMessageDefinition> AddDefaultMessage(string name, string key, EntityHeader org, EntityHeader user, DateTime createTimeStamp)
        {
            await _storageUtils.DeleteIfExistsAsync <DeviceMessageDefinition>(key, org);

            await _storageUtils.DeleteIfExistsAsync <Verifier>("exmplmotgparser", org);

            var msgDefinition = new DeviceMessageDefinition()
            {
                Id               = Guid.NewGuid().ToId(),
                Name             = name,
                Key              = key,
                MessageId        = "motion",
                MessageDirection = EntityHeader <MessageDirections> .Create(MessageDirections.Incoming),
                ContentType      = EntityHeader <MessageContentTypes> .Create(MessageContentTypes.JSON)
            };

            msgDefinition.Fields.Add(new DeviceMessageDefinitionField()
            {
                ContentType           = EntityHeader <MessageContentTypes> .Create(MessageContentTypes.JSON),
                FieldIndex            = 0,
                Name                  = "Motion Status",
                SearchLocation        = EntityHeader <SearchLocations> .Create(SearchLocations.Body),
                Id                    = Guid.NewGuid().ToId(),
                JsonPath              = "motion",
                Key                   = "motion",
                StorageType           = EntityHeader <ParameterTypes> .Create(ParameterTypes.String),
                ParsedStringFieldType = EntityHeader <ParseStringValueType> .Create(ParseStringValueType.String),
            });

            msgDefinition.SampleMessages.Add(new SampleMessage()
            {
                Id                 = Guid.NewGuid().ToId(),
                Name               = "Sample Motion Message",
                Key                = "smplmotionmsg",
                Payload            = "{'motion':'on'}",
                PathAndQueryString = "/api/motion/dev001",
                Description        = "Sample message that would be sent by a motion detector.",
                Topic              = String.Empty,
            });

            AddOwnedProperties(msgDefinition, org);
            AddAuditProperties(msgDefinition, createTimeStamp, org, user);

            await _deviceMsgMgr.AddDeviceMessageDefinitionAsync(msgDefinition, org, user);

            await _storageUtils.DeleteIfExistsAsync <Verifier>("examplemotionmsgparser", org);

            var verifier = new Verifier()
            {
                Component = new EntityHeader()
                {
                    Id   = msgDefinition.Id,
                    Text = msgDefinition.Name
                },
                ExpectedOutputs = new System.Collections.ObjectModel.ObservableCollection <ExpectedValue>()
                {
                    new ExpectedValue()
                    {
                        Key = "motion", Value = "on"
                    },
                },
                InputType          = EntityHeader <InputTypes> .Create(InputTypes.Text),
                Name               = "Simple Message Verifier",
                Key                = "exmplmotgparser",
                Description        = "Validates that a Sample Motion Message has the proper field parsers",
                Input              = "{'motion':'on'}",
                PathAndQueryString = "/smplmot001/device001",
                ShouldSucceed      = true,
                VerifierType       = EntityHeader <VerifierTypes> .Create(VerifierTypes.MessageParser)
            };

            AddId(verifier);
            AddOwnedProperties(verifier, org);
            AddAuditProperties(verifier, createTimeStamp, org, user);
            await _verifierMgr.AddVerifierAsync(verifier, org, user);

            return(msgDefinition);
        }
Exemplo n.º 10
0
        public void InputTranslatorToWorkflowValidation(ValidationResult result, DeviceMessageDefinition message, DeviceWorkflow workflow)
        {
            if (PrimaryOutput != null)
            {
                if (PrimaryOutput.Mappings == null)
                {
                    PrimaryOutput.Mappings = new List <KeyValuePair <string, object> >();
                }

                foreach (var mapping in PrimaryOutput.Mappings)
                {
                    var mapResult = new ValidationResult();

                    var fieldKey = mapping.Key;
                    if (mapping.Value == null)
                    {
                        mapResult.AddUserError($"Missing Input Key for mapping on work flow {workflow.Name} for input mapping.");
                    }
                    else
                    {
                        var inputKey = mapping.Value.ToString();
                        if (String.IsNullOrEmpty(inputKey))
                        {
                            mapResult.AddUserError($"Missing Input Key for mapping on work flow {workflow.Name} for input mapping.");
                        }

                        if (String.IsNullOrEmpty(fieldKey))
                        {
                            mapResult.AddUserError($"Missing Message Field Key for mapping on work flow {workflow.Name} for input mapping.");
                        }

                        if (mapResult.Successful)
                        {
                            var input = workflow.Inputs.Where(inp => inp.Key == inputKey).FirstOrDefault();
                            var field = message.Fields.Where(fld => fld.Key == fieldKey).FirstOrDefault();

                            if (input == null)
                            {
                                mapResult.AddUserError($"Could not find input {inputKey} on workflow {workflow.Name}");
                            }

                            if (field == null)
                            {
                                mapResult.AddUserError($"Could not find field {fieldKey} on message {message.Name} on workflow {workflow.Name} for input mapping.");
                            }

                            if (field != null && input != null)
                            {
                                if (EntityHeader.IsNullOrEmpty(field.StorageType))
                                {
                                    mapResult.AddUserError($"On field {field.Name} for message {message.Name} storage type is empty.");
                                }
                                else if (EntityHeader.IsNullOrEmpty(input.InputType))
                                {
                                    mapResult.AddUserError($"On input {field.Name} for workflow {workflow.Name} storage type is empty.");
                                }
                                else
                                {
                                    if (field.StorageType.Id != input.InputType.Id)
                                    {
                                        mapResult.AddUserError($"On Mapping for field {field.Name} for message {message.Name} and input {input.Name} type mismatch, {field.StorageType.Text} can not be mapped to {input.InputType.Text}.");
                                    }
                                    else if (field.StorageType.Value == ParameterTypes.State)
                                    {
                                        if (EntityHeader.IsNullOrEmpty(field.StateSet))
                                        {
                                            result.AddUserError($"State Set Not provided on Message {message.Name}, Field {field.Name}.");
                                        }
                                        else if (EntityHeader.IsNullOrEmpty(input.StateSet))
                                        {
                                            result.AddUserError($"State Set Not provided on Input {input.Name}, for work flow {workflow.Name}");
                                        }
                                        else if (field.StateSet.Id != input.StateSet.Id)
                                        {
                                            result.AddUserError($"State Set are different on mapping between Message Field {message.Name}/{field.Name} and input {input.Name} on workflow {workflow.Name} (Field={field.StateSet.Text}, Input={input.StateSet.Text}).");
                                        }
                                    }
                                    else if (field.StorageType.Value == ParameterTypes.ValueWithUnit)
                                    {
                                        if (EntityHeader.IsNullOrEmpty(field.UnitSet))
                                        {
                                            result.AddUserError($"Unit Set Not provided on Message {message.Name}, Field {field.Name}.");
                                        }
                                        else if (EntityHeader.IsNullOrEmpty(input.UnitSet))
                                        {
                                            result.AddUserError($"Unit Set Not provided on Input {input.Name}, for work flow {workflow.Name}");
                                        }
                                        else if (field.UnitSet.Id != input.UnitSet.Id)
                                        {
                                            result.AddUserError($"Units Set are different on mapping between message {message.Name}/{field.Name} and input {input.Name} on workflow {workflow.Name} (Field={field.UnitSet.Text}, Input={input.UnitSet.Text}).");
                                        }
                                    }
                                }
                            }
                        }

                        result.Concat(mapResult);
                    }
                }
            }
        }
 public Task <InvokeResult> UpdateDeviceMessageConfigurationAsync([FromBody] DeviceMessageDefinition deviceMessageConfiguration)
 {
     SetUpdatedProperties(deviceMessageConfiguration);
     return(_deviceConfigManager.UpdateDeviceMessageDefinitionAsync(deviceMessageConfiguration, OrgEntityHeader, UserEntityHeader));
 }
 public Task <InvokeResult> AddDeviceMessageConfigurationAsync([FromBody] DeviceMessageDefinition deviceMessageConfiguration)
 {
     return(_deviceConfigManager.AddDeviceMessageDefinitionAsync(deviceMessageConfiguration, OrgEntityHeader, UserEntityHeader));
 }
Exemplo n.º 13
0
        protected DeviceMessageDefinition GetValidMessage(MessageContentTypes contenttype)
        {
            var msg = new DeviceMessageDefinition()
            {
                Name             = "msg1234",
                MessageId        = "msg1234",
                Key              = "msg1234",
                MessageDirection = EntityHeader <MessageDirections> .Create(MessageDirections.Incoming),
                Id           = Guid.NewGuid().ToId(),
                CreationDate = DateTime.Now.ToJSONString(),
                CreatedBy    = new Core.Models.EntityHeader()
                {
                    Id = Guid.NewGuid().ToId(), Text = "user name"
                }
            };

            msg.LastUpdatedDate = msg.CreationDate;
            msg.LastUpdatedBy   = msg.CreatedBy;

            switch (contenttype)
            {
            case MessageContentTypes.Binary:
                msg.ContentType = new Core.Models.EntityHeader <MessageContentTypes>()
                {
                    Id = DeviceMessageDefinition.ContentType_Binary, Text = "Binary"
                };
                msg.StringParsingStrategy = new Core.Models.EntityHeader <StringParsingStrategy>()
                {
                    Id = DeviceMessageDefinition.StringParsingStrategy_NullTerminated, Text = "Null"
                };
                msg.Endian = new Core.Models.EntityHeader <EndianTypes>()
                {
                    Id = DeviceMessageDefinition.Endian_BigEndian, Text = "Little Endian"
                };
                msg.BinaryParsingStrategy = new Core.Models.EntityHeader <BinaryParsingStrategy>()
                {
                    Id = DeviceMessageDefinition.BinaryParsingStrategy_Absolute, Text = "AbsolutePosition"
                };
                msg.StringLengthByteCount = 2;

                break;

/*                case MessageContentTypes.Custom:
 *                  msg.ContentType = new Core.Models.EntityHeader<MessageContentTypes>() { Id = DeviceMessageDefinition.ContentType_Custom, Text = "Custom" };
 *                  msg.Script = "function() {do something, for now javascript validate}";
 *                  break;*/;

            case MessageContentTypes.Delimited:
                msg.ContentType = new Core.Models.EntityHeader <MessageContentTypes>()
                {
                    Id = DeviceMessageDefinition.ContentType_Delimited, Text = "Delimited"
                };
                msg.Delimiter  = ",";
                msg.QuotedText = false;
                break;

            case MessageContentTypes.JSON:
                msg.ContentType = new Core.Models.EntityHeader <MessageContentTypes>()
                {
                    Id   = DeviceMessageDefinition.ContentType_Json,
                    Text = "JSON"
                };
                break;

            case MessageContentTypes.StringRegEx:
                msg.ContentType = new Core.Models.EntityHeader <MessageContentTypes>()
                {
                    Id = DeviceMessageDefinition.ContentType_StringRegEx, Text = "StringRegEx"
                };
                msg.RegEx = "^parse_me_if_i_was_valid_reg_ex$";
                break;

            case MessageContentTypes.StringPosition:
                msg.ContentType = new Core.Models.EntityHeader <MessageContentTypes>()
                {
                    Id = DeviceMessageDefinition.ContentType_StringPosition, Text = "StringPosition"
                };
                break;

            case MessageContentTypes.XML:
                msg.ContentType = new Core.Models.EntityHeader <MessageContentTypes>()
                {
                    Id = DeviceMessageDefinition.ContentType_Xml, Text = "XML"
                };
                break;
            }

            return(msg);
        }
Exemplo n.º 14
0
 public void Init()
 {
     _messageDefinition = GetDeviceMessage();
     _deviceWorkflow    = GetWorkflow();
 }