예제 #1
0
 public override string ToString()
 {
     return($"Type: {this.Cid} Answer, channel index: {this.ChIndex}, frequency: {ConversionHelper.ByteArrayToString(this.Freq)}, min DR: {this.GetMinDR()}, max DR: {this.GetMaxDR()}");
 }
예제 #2
0
 public void Invalid_Rover_Direction_Test()
 {
     Assert.Equal(Direction.Unknown, ConversionHelper.ToDirection("D"));
 }
예제 #3
0
        public void When_Creating_Rxpk_Recreating_Payload_Should_Match_Source_Values(LoRaMessageType loRaMessageType, string data)
        {
            var devAddrText = "00000060";
            var appSKeyText = "00000060000000600000006000000060";
            var nwkSKeyText = "00000060000000600000006000000060";

            ushort fcnt = 12;

            byte[] devAddr = ConversionHelper.StringToByteArray(devAddrText);
            Array.Reverse(devAddr);
            byte[] fCtrl     = new byte[] { 0x80 };
            var    fcntBytes = BitConverter.GetBytes(fcnt);
            var    fopts     = new List <MacCommand>();

            byte[] fPort   = new byte[] { 1 };
            byte[] payload = Encoding.UTF8.GetBytes(data);
            Array.Reverse(payload);

            // 0 = uplink, 1 = downlink
            int direction         = 0;
            var devicePayloadData = new LoRaPayloadData(loRaMessageType, devAddr, fCtrl, fcntBytes, fopts, fPort, payload, direction);

            Assert.Equal(12, devicePayloadData.GetFcnt());
            Assert.Equal(0, devicePayloadData.Direction);
            Assert.Equal(1, devicePayloadData.GetFPort());

            var datr = "SF10BW125";
            var freq = 868.3;

            var uplinkMsg = devicePayloadData.SerializeUplink(appSKeyText, nwkSKeyText, datr, freq, 0);

            // Now try to recreate LoRaPayloadData from rxpk
            Assert.True(LoRaPayload.TryCreateLoRaPayload(uplinkMsg.Rxpk[0], out LoRaPayload parsedLoRaPayload));
            Assert.Equal(loRaMessageType, parsedLoRaPayload.LoRaMessageType);
            Assert.IsType <LoRaPayloadData>(parsedLoRaPayload);
            var parsedLoRaPayloadData = (LoRaPayloadData)parsedLoRaPayload;

            Assert.Equal(12, parsedLoRaPayloadData.GetFcnt());
            Assert.Equal(0, parsedLoRaPayloadData.Direction);
            Assert.Equal(1, parsedLoRaPayloadData.GetFPort());

            // Ensure that mic check and getting payload back works
            Assert.True(parsedLoRaPayloadData.CheckMic(nwkSKeyText)); // does not matter where the check mic happen, should always work!
            var parsedPayloadBytes = parsedLoRaPayloadData.GetDecryptedPayload(appSKeyText);

            Assert.Equal(data, Encoding.UTF8.GetString(parsedPayloadBytes));

            // checking mic and getting payload should not change the payload properties
            Assert.Equal(12, parsedLoRaPayloadData.GetFcnt());
            Assert.Equal(0, parsedLoRaPayloadData.Direction);
            Assert.Equal(1, parsedLoRaPayloadData.GetFPort());

            // checking mic should not break getting the payload
            Assert.True(parsedLoRaPayloadData.CheckMic(nwkSKeyText)); // does not matter where the check mic happen, should always work!
            var parsedPayloadBytes2 = parsedLoRaPayloadData.GetDecryptedPayload(appSKeyText);

            Assert.Equal(data, Encoding.UTF8.GetString(parsedPayloadBytes2));

            // checking mic and getting payload should not change the payload properties
            Assert.Equal(12, parsedLoRaPayloadData.GetFcnt());
            Assert.Equal(0, parsedLoRaPayloadData.Direction);
            Assert.Equal(1, parsedLoRaPayloadData.GetFPort());
        }
예제 #4
0
        private object ReadJsonInternal(IJsonNetReader reader, Type objectType, object existingValue, IJsonNetSerializer serializer, int depth)
        {
            // mbr - 2016-07-07 - if we get null, quit...
            if (reader.TokenType == JsonNetTokenShim.Null)
            {
                return(null);
            }

            string readingName = null;

            // walk...
            var dto = (IDtoBase)Activator.CreateInstance(objectType);

            while (true)
            {
                var didPeek = false;

                // what did we get?
                if (reader.TokenType == JsonNetTokenShim.EndObject)
                {
                    break;
                }
                else if (reader.TokenType == JsonNetTokenShim.PropertyName)
                {
                    readingName = (string)reader.Value;
                }
                else if (reader.TokenType == JsonNetTokenShim.String || reader.TokenType == JsonNetTokenShim.Boolean || reader.TokenType == JsonNetTokenShim.Integer ||
                         reader.TokenType == JsonNetTokenShim.Float || reader.TokenType == JsonNetTokenShim.Date || reader.TokenType == JsonNetTokenShim.Null)
                {
                    // field...
                    var field = dto.Type.GetFieldByJsonName(readingName, false);
                    if (field != null)
                    {
                        // set...
                        if (field.CanWrite)
                        {
                            dto[field] = reader.Value;
                        }
                    }
                    else
                    {
                        // mbr - 2015-06-17 - we might have a property that's not mapped to a field. this will happen if we
                        // use a DtoBase<> as a base type (e.g. "SaveOrderLineDto")...
                        var prop = GetAdhocProperty(dto.GetType(), readingName);
                        if (prop != null && prop.CanWrite)
                        {
                            var toSet = ConversionHelper.ChangeType(reader.Value, prop.PropertyType);
                            prop.SetValue(dto, toSet);
                        }
                    }

                    // reset...
                    readingName = null;
                }
                else if (reader.TokenType == JsonNetTokenShim.StartObject)
                {
                    if (!(string.IsNullOrEmpty(readingName)))
                    {
                        var member = dto.Type.GetMemberByJsonName(readingName, false);
                        if (member != null)
                        {
                            // what is it?
                            if (typeof(IDtoBase).IsAssignableFrom(member.ValueType))
                            {
                                // read something we know...
                                var inner = (IDtoBase)this.ReadJsonInternal(reader, member.ValueType, existingValue, serializer, depth + 1);

                                // set...
                                if (member is DtoLink)
                                {
                                    dto.SetLink((DtoLink)member, inner);
                                }
                                else
                                {
                                    throw new NotSupportedException(string.Format("Cannot handle '{0}'.", member.GetType()));
                                }
                            }
                            else
                            {
                                // read it generally...
                                //var inner = serializer.;
                                //var prop = this.GetAdhocProperty(member.ValueType, member.JsonName);
                                //if (prop != null && prop.CanWrite)
                                //    prop.SetValue(dto, inner);
                                throw new NotImplementedException("This operation has not been implemented.");
                            }
                        }
                        else
                        {
                            // drain here...
                            while (true)
                            {
                                if (!(reader.Read()))
                                {
                                    throw new InvalidOperationException("End of stream encountered whilst looking for end of object. ");
                                }

                                // stop?
                                if (reader.TokenType == JsonNetTokenShim.EndObject)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (reader.TokenType == JsonNetTokenShim.StartArray)
                {
                    // find the field...
                    var field = dto.Type.GetFieldByJsonName(readingName, false);
                    if (field != null)
                    {
                        // go next...
                        if (!(reader.Read()))
                        {
                            throw new InvalidOperationException("End of stream encountered whilst stepping into array.");
                        }

                        // get the object type...
                        Type subtype = null;
                        if (typeof(IEnumerable).IsAssignableFrom(field.DtoProperty.PropertyType))
                        {
                            if (field.DtoProperty.PropertyType.GenericTypeArguments.Length == 1)
                            {
                                subtype = field.DtoProperty.PropertyType.GenericTypeArguments[0];
                            }
                            else
                            {
                                throw new NotSupportedException(string.Format("A parameter of set length '{0}' is invalid.", field.DtoProperty.PropertyType.GenericTypeArguments.Length));
                            }
                        }
                        else
                        {
                            throw new NotSupportedException(string.Format("Cannot handle '{0}'.", field.DtoProperty.PropertyType));
                        }

                        // read...
                        var readingList = (IList)Activator.CreateInstance(field.DtoProperty.PropertyType);
                        while (true)
                        {
                            var inner = this.ReadJsonInternal(reader, subtype, existingValue, serializer, depth + 1);
                            if (inner == null)
                            {
                                throw new InvalidOperationException("'inner' is null.");
                            }

                            // add...
                            readingList.Add(inner);

                            // now what?
                            if (!(reader.Read()))
                            {
                                throw new InvalidOperationException("End of stream encountered whilst peaking array end.");
                            }

                            // what did we get?
                            if (reader.TokenType == JsonNetTokenShim.StartObject)
                            {
                            }
                            else if (reader.TokenType == JsonNetTokenShim.EndArray)
                            {
                                // set the result...
                                dto[field] = readingList;

                                // go back to the top of the loop...
                                didPeek = true;
                                break;
                            }
                            else
                            {
                                throw new NotSupportedException(string.Format("Cannot handle '{0}'.", reader.TokenType));
                            }
                        }
                    }
                    else
                    {
                        // flush...
                        while (true)
                        {
                            if (reader.TokenType == JsonNetTokenShim.EndArray)
                            {
                                break;
                            }
                            if (!(reader.Read()))
                            {
                                throw new InvalidOperationException("End of stream encountered whilst looking for end of array.");
                            }
                        }
                    }
                }

                if (!(didPeek))
                {
                    if (!(reader.Read()))
                    {
                        break;
                    }
                }
            }

            // return...
            return(dto);
        }
예제 #5
0
 /// <summary>
 /// Check to see if the provided value is valid.
 /// </summary>
 /// <param name="value">The provided value.</param>
 /// <returns>True if value found in choices; otherwise false.</returns>
 public virtual bool ValidValue(object value)
 {
     return(!ConversionHelper.IsEmpty(value));
 }
예제 #6
0
파일: DataWriter.cs 프로젝트: radtek/BootFX
 /// <summary>
 /// Formats a value for output.
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 protected virtual string FormatValue(object value)
 {
     return(ConversionHelper.ToString(value, this.Culture));
 }
예제 #7
0
        //public static PagedDataResult<T> ToDtos<T>(this IEnumerable<IDtoCapable> items, PagedDataRequest request)
        //    where T : IDtoBase
        //{
        //    throw new NotImplementedException("This operation has not been implemented.");
        //}

        public static List <T> ToDtos <T>(this IEnumerable <IDtoCapable> items)
            where T : IDtoBase
        {
            var dtoType = DtoType.InferDtoType(items);

            // get...
            using (var conn = Database.CreateConnection(dtoType.ConcreteEntityType))
            {
                conn.BeginTransaction();
                try
                {
                    var dtos = new List <T>();
                    foreach (var item in items)
                    {
                        dtos.Add(item.ToDto <T>());
                    }

                    // next -- preload any linked data that we can find...
                    foreach (var link in dtoType.Links)
                    {
                        var map = new Dictionary <long, IDtoBase>();
                        foreach (var dto in dtos)
                        {
                            // get...
                            var parentId = dto.GetValue <long>(link.ReferenceField);
                            if (parentId != 0 && !(map.ContainsKey(parentId)))
                            {
                                map[parentId] = null;
                            }
                        }

                        // load everything up...
                        var pages = Runtime.Current.GetPages(map.Keys, 500);
                        foreach (var page in pages)
                        {
                            var filter   = new SqlFilter(link.Link.ParentEntityType);
                            var keyField = link.Link.ParentEntityType.GetKeyFields()[0];
                            filter.Constraints.AddValueListConstraint(keyField, page);

                            // add...
                            var gots = filter.ExecuteEntityCollection();
                            foreach (IDtoCapable got in gots)
                            {
                                var id = ConversionHelper.ToInt64(filter.EntityType.Storage.GetValue(got, keyField));
                                if (map.ContainsKey(id))
                                {
                                    map[id] = got.ToDto();
                                }
                            }
                        }

                        // go back and fill them in...
                        foreach (var dto in dtos)
                        {
                            var parentId = dto.GetValue <long>(link.ReferenceField);
                            if (parentId != 0)
                            {
                                dto.SetLink(link, map[parentId]);
                            }
                        }
                    }

                    // ok...
                    conn.Commit();

                    // return...
                    return(dtos);
                }
                catch (Exception ex)
                {
                    conn.Rollback();
                    throw new InvalidOperationException("The operation failed", ex);
                }
            }
        }
예제 #8
0
        public string GetRevisionQuery(NoDbRevision revision, NoDbRevisionDetail detail, NoDbConnectionType connectionType)
        {
            var           queryService  = QueryManager.GetNoDbQueryService(connectionType);
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendFormat("-- Action: {0}, Type: {1}\n", detail.Action, detail.ObjectType);
            if (detail.ObjectType == NoDbRevisionType.Table)
            {
                var oldTable = detail.OldValue is NoDbTable ? (NoDbTable)detail.OldValue : ConversionHelper.ConvertTo <NoDbTable>(detail.OldValue);
                var newTable = detail.NewValue is NoDbTable ? (NoDbTable)detail.NewValue : ConversionHelper.ConvertTo <NoDbTable>(detail.NewValue);
                if (detail.Action == NoDbRevisionAction.Removed)
                {
                    stringBuilder.Append(queryService.DropTableQuery(oldTable) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Added)
                {
                    stringBuilder.Append(queryService.CreateTableQuery(newTable) + "\n");
                }
            }
            else if (detail.ObjectType == NoDbRevisionType.Column)
            {
                var oldColumn = ConversionHelper.ConvertTo <NoDbColumn>(detail.OldValue);
                var newColumn = ConversionHelper.ConvertTo <NoDbColumn>(detail.NewValue);
                if (detail.Action == NoDbRevisionAction.Removed)
                {
                    stringBuilder.Append(queryService.DropColumnQuery(revision.NewTable, oldColumn) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Added)
                {
                    stringBuilder.Append(queryService.AddColumnQuery(revision.NewTable, newColumn) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Renamed)
                {
                    stringBuilder.Append(queryService.RenameColumnQuery(revision.NewTable, oldColumn, newColumn) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Updated)
                {
                    stringBuilder.Append(queryService.UpdateColumnQuery(revision.NewTable, newColumn) + "\n");
                }
            }
            else if (detail.ObjectType == NoDbRevisionType.Index)
            {
                var oldIndex = ConversionHelper.ConvertTo <NoDbIndex>(detail.OldValue);
                var newIndex = ConversionHelper.ConvertTo <NoDbIndex>(detail.NewValue);
                if (detail.Action == NoDbRevisionAction.Removed)
                {
                    stringBuilder.Append(queryService.DropIndexQuery(revision.NewTable, oldIndex) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Added)
                {
                    stringBuilder.Append(queryService.CreateIndexQuery(revision.NewTable, newIndex) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Renamed)
                {
                    stringBuilder.Append(queryService.RenameIndexQuery(revision.NewTable, oldIndex, newIndex) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Updated)
                {
                    stringBuilder.Append(queryService.DropIndexQuery(revision.NewTable, oldIndex) + "\n");
                    stringBuilder.Append(queryService.CreateIndexQuery(revision.NewTable, newIndex) + "\n");
                }
            }
            else if (detail.ObjectType == NoDbRevisionType.Relation)
            {
                var oldRelation = ConversionHelper.ConvertTo <NoDbRelation>(detail.OldValue);
                var newRelation = ConversionHelper.ConvertTo <NoDbRelation>(detail.NewValue);
                if (detail.Action == NoDbRevisionAction.Removed)
                {
                    stringBuilder.AppendFormat(queryService.DeleteRelationQuery(revision.NewTable, oldRelation) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Added)
                {
                    stringBuilder.AppendFormat(queryService.CreateRelationQuery(revision.NewTable, newRelation) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Renamed)
                {
                    stringBuilder.AppendFormat(queryService.RenameRelationQuery(revision.NewTable, oldRelation, newRelation) + "\n");
                }
                else if (detail.Action == NoDbRevisionAction.Updated)
                {
                    stringBuilder.AppendFormat(queryService.DeleteRelationQuery(revision.NewTable, oldRelation) + "\n");
                    stringBuilder.AppendFormat(queryService.CreateRelationQuery(revision.NewTable, newRelation) + "\n");
                }
            }
            return(stringBuilder.ToString());
        }
예제 #9
0
 /// <summary>
 /// Validates the given value and returns its "cleaned" value as an
 /// appropriate .Net object.
 /// </summary>
 /// <param name="value">Value to clean</param>
 /// <returns>Cleaned value</returns>
 /// <exception cref="ValidationException">On an invalid validation</exception>
 public override object Clean(object value)
 {
     return(ConversionHelper.NullBoolean(value));
 }
예제 #10
0
 public static T GetValue <T>(this IDtoBase dto, DtoField field)
 {
     return(ConversionHelper.ChangeType <T>(dto[field]));
 }
예제 #11
0
 public void MapData(PropertyEntityViewModel model, ref PropertyEntity entity)
 {
     entity.EntityName    = model.EntityName;
     entity.EffectiveDate = ConversionHelper.EnsureUtcDate(model.EffectiveDate.Date);
 }
예제 #12
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            MessagesController obj = new MessagesController();
            var activity           = await result as Activity;
            PatientController pC   = new PatientController();
            BotManager        bM   = new BotManager();
            BOTResponse       bR   = new BOTResponse();
            var    state           = string.Empty;
            var    input           = string.Empty;
            var    responseToken   = string.Empty;
            string botResponse     = string.Empty;

            input = activity.Text.ToString().ToLower();
            bool questionResponded = false;

            try
            {
                state         = context.ConversationData.GetValue <string>("state");
                responseToken = context.ConversationData.GetValue <string>("ResponseToken");
            }
            catch (Exception ex)
            {
            }
            if (state == "firstname")
            {
                WebApiApplication.firstName = input;
                bR = pC.SearchPatient(input, 1, null, WebApiApplication.getPatData);
                if (bR.status == true)
                {
                    context.ConversationData.SetValue <string>("state", "lastname");
                    context.ConversationData.SetValue <string>("ResponseToken", bR.RequestToken);
                }
                else
                {
                    context.ConversationData.SetValue <string>("state", "firstname");
                }
                await context.PostAsync($"" + bR.ResponseMessage);

                questionResponded = true;
            }
            if (state == "lastname")
            {
                bR = pC.SearchPatient(input, 2, null, WebApiApplication.getPatFirstName);
                //if (WebApiApplication.getPatLastName.Count == 1)
                //{
                //    await context.PostAsync($"Thank you for Verifying your Details.");
                //    await context.PostAsync($"How can i help you, {Environment.NewLine}{Environment.NewLine}a)Book an appointment{Environment.NewLine}b)Patient Visit History{Environment.NewLine}c)Pay Bills{Environment.NewLine}d)Refill a request{Environment.NewLine}{Environment.NewLine}Please select an Option");
                //    context.ConversationData.SetValue<string>("state", "options");
                //}
                //else
                if (bR.status == true)
                {
                    await context.PostAsync($"" + bR.ResponseMessage);

                    context.ConversationData.SetValue <string>("state", "dob");
                    context.ConversationData.SetValue <string>("ResponseToken", bR.RequestToken);
                }
                else
                {
                    await context.PostAsync($"" + bR.ResponseMessage);

                    context.ConversationData.SetValue <string>("state", "");
                }
                questionResponded = true;
            }
            else if (state == "dob")
            {
                input = ConversionHelper.dateFormat(input);
                if (Validator.checkDateFormat(input))
                {
                    bR = pC.SearchPatient(input, 3, responseToken, WebApiApplication.getPatLastName);
                    if (bR.status == true)
                    {
                        if (WebApiApplication.getPatDOB.Count == 1)
                        {
                            await context.PostAsync($"Thank you for Verifying your Details.");

                            //await context.PostAsync($"How can i help you, {Environment.NewLine}{Environment.NewLine}a)Book an appointment{Environment.NewLine}b)Patient Visit History{Environment.NewLine}c)Pay Bills{Environment.NewLine}d)Refill a request{Environment.NewLine}{Environment.NewLine}Please select an Option");
                            //context.ConversationData.SetValue<string>("state", "options");
                        }
                        else
                        {
                            bool hasSSN       = WebApiApplication.getPatDOB.Exists(x => !string.IsNullOrEmpty(x.SSN));
                            bool hasHomePhone = WebApiApplication.getPatDOB.Exists(x => !string.IsNullOrEmpty(x.PatHomePhone));
                            bool hasWorkPhone = WebApiApplication.getPatDOB.Exists(x => !string.IsNullOrEmpty(x.PatWorkPhone));
                            if (hasHomePhone || hasWorkPhone)
                            {
                                context.ConversationData.SetValue <string>("state", "phone");
                                context.ConversationData.SetValue <string>("ResponseToken", bR.RequestToken);
                                await context.PostAsync($"Please enter the last 4 digits of your Phone number");
                            }
                            else if (hasSSN)
                            {
                                context.ConversationData.SetValue <string>("state", "ssn");
                                context.ConversationData.SetValue <string>("ResponseToken", bR.RequestToken);
                                await context.PostAsync($"" + bR.ResponseMessage);
                            }
                            else
                            {
                            }
                        }
                    }
                    else
                    {
                        context.ConversationData.SetValue <string>("state", "dob");
                        await context.PostAsync($"" + bR.ResponseMessage);
                    }
                }
                else
                {
                    context.ConversationData.SetValue <string>("state", "dob");
                    await context.PostAsync($"Please enter valid Date format, (MM/DD/YYYY)");
                }
                questionResponded = true;
            }
            else if (state == "phone")
            {
                if (Validator.isPhoneNumberValid(input))
                {
                    bR = pC.SearchPatient(input, 6, responseToken, WebApiApplication.getPatDOB);
                    if (WebApiApplication.getPatPhone.Count == 1)
                    {
                        await context.PostAsync($"Thank you for Verifying your Details.");

                        //await context.PostAsync($"How can i help you, {Environment.NewLine}{Environment.NewLine}a)Book an appointment{Environment.NewLine}b)Patient Visit History{Environment.NewLine}c)Pay Bills{Environment.NewLine}d)Refill a request{Environment.NewLine}{Environment.NewLine}Please select an Option");
                        //context.ConversationData.SetValue<string>("state", "options");
                    }
                    else if (bR.status == true)
                    {
                        context.ConversationData.SetValue <string>("state", "ssn");
                        context.ConversationData.SetValue <string>("ResponseToken", bR.RequestToken);
                        await context.PostAsync($"" + bR.ResponseMessage);
                    }
                    else
                    {
                        context.ConversationData.SetValue <string>("state", "");
                        await context.PostAsync($"" + bR.ResponseMessage);
                    }
                }
                else
                {
                    context.ConversationData.SetValue <string>("state", "phone");
                    await context.PostAsync($"Please enter valid Phone format, (xxxxxxxxxx)");
                }
                questionResponded = true;
            }

            else if (state == "zip")
            {
                bR = pC.SearchPatient(input, 5, responseToken, WebApiApplication.getPatZIP);
                if (WebApiApplication.getPatZIP.Count == 1)
                {
                    await context.PostAsync($"Thank you for Verifying your Details.");

                    //await context.PostAsync($"How can i help you, {Environment.NewLine}{Environment.NewLine}a)Book an appointment{Environment.NewLine}b)Patient Visit History{Environment.NewLine}c)Pay Bills{Environment.NewLine}d)Refill a request{Environment.NewLine}{Environment.NewLine}Please select an Option");
                    //context.ConversationData.SetValue<string>("state", "options");
                }
                else if (bR.status == true)
                {
                    context.ConversationData.SetValue <string>("state", "zip");
                    await context.PostAsync($"" + bR.ResponseMessage);

                    //await context.PostAsync($"How can i help you, {Environment.NewLine}{Environment.NewLine}a)Book an appointment{Environment.NewLine}b)Patient Visit History{Environment.NewLine}c)Pay Bills{Environment.NewLine}d)Refill a request{Environment.NewLine}{Environment.NewLine}Please select an Option");
                    //context.ConversationData.SetValue<string>("state", "options");
                    context.ConversationData.SetValue <string>("ResponseToken", bR.RequestToken);
                }
                else
                {
                    context.ConversationData.SetValue <string>("state", "zip");
                    await context.PostAsync($"" + bR.ResponseMessage);
                }
                questionResponded = true;
            }
            else if (state == "ssn")
            {
                bR = pC.SearchPatient(input, 4, responseToken, WebApiApplication.getPatDOB);
                if (WebApiApplication.getPatSSN.Count == 1)
                {
                    await context.PostAsync($"Thank you for Verifying your Details.");

                    //await context.PostAsync($"How can i help you, {Environment.NewLine}{Environment.NewLine}a)Book an appointment{Environment.NewLine}b)Patient Visit History{Environment.NewLine}c)Pay Bills{Environment.NewLine}d)Refill a request{Environment.NewLine}{Environment.NewLine}Please select an Option");
                    //context.ConversationData.SetValue<string>("state", "options");
                }
                else if (bR.status == true)
                {
                    context.ConversationData.SetValue <string>("state", "zip");
                    context.ConversationData.SetValue <string>("ResponseToken", bR.RequestToken);
                    await context.PostAsync($"" + bR.ResponseMessage);
                }
                else
                {
                    context.ConversationData.SetValue <string>("state", "ssn");
                    await context.PostAsync($"" + bR.ResponseMessage);
                }
                questionResponded = true;
            }
            else if (state == "reqdescription")
            {
                context.ConversationData.SetValue <string>("state", "reqdescriptionresp");
                await context.PostAsync($"I'm afraid I can't help with this at this time. Can I ask someone to call you?");

                questionResponded = true;
            }
            else if (state == "reqdescriptionresp")
            {
                if (input == "no")
                {
                    context.ConversationData.SetValue <string>("state", "");
                    await context.PostAsync($"My apologies I wasn't of any help.");

                    questionResponded = true;
                }
                else
                {
                    await context.PostAsync($"I'll need some more details from you so we can contact you at the right number.");

                    context.ConversationData.SetValue <string>("state", "firstname");
                    await context.PostAsync($"Can I know your first name please ?");

                    questionResponded = true;
                }
            }
            else if (state == "options")
            {
                string keyName = "Options.option" + input;
                var    keyVal  = ConfigurationManager.AppSettings[keyName];
                if (input.Length > 1)
                {
                    input   = Validator.getOptionSelected(input).ToString();
                    keyName = "Options.option" + input;
                    try
                    {
                        keyVal = ConfigurationManager.AppSettings[keyName];
                    }
                    catch (Exception)
                    {
                    }
                }
                if (input.ToLower() == "1" || Validator.sentenceComparison(keyVal, input) == true)
                {
                    await context.PostAsync($"You chose to Book an Appointment.");

                    context.ConversationData.SetValue <string>("state", "firstname");
                    await context.PostAsync($"Can I know your first name please ?");

                    questionResponded = true;
                }
                else if (input.ToLower() == "2" || Validator.sentenceComparison(keyVal, input) == true)
                {
                    await context.PostAsync($"You chose to Request Refills.");

                    context.ConversationData.SetValue <string>("state", "firstname");
                    await context.PostAsync($"Can I know your first name please ?");

                    questionResponded = true;
                }
                else if (input.ToLower() == "3" || Validator.sentenceComparison(keyVal, input) == true)
                {
                    await context.PostAsync($"You chose to Update on Lab Orders.");

                    context.ConversationData.SetValue <string>("state", "firstname");
                    await context.PostAsync($"Can I know your first name please ?");

                    questionResponded = true;
                }
                else if (input.ToLower() == "4" || Validator.sentenceComparison(keyVal, input) == true)
                {
                    await context.PostAsync($"You chose to pay your bills.");

                    context.ConversationData.SetValue <string>("state", "firstname");
                    await context.PostAsync($"Can I know your first name please ?");

                    questionResponded = true;
                }
                else if (input.ToLower() == "5" || Validator.sentenceComparison(keyVal, input) == true)
                {
                    await context.PostAsync($"You chose to contact the Doctor.");

                    context.ConversationData.SetValue <string>("state", "firstname");
                    await context.PostAsync($"Can I know your first name please ?");

                    questionResponded = true;
                }
                else if (input.ToLower() == "6" || Validator.sentenceComparison(keyVal, input) == true)
                {
                    await context.PostAsync($"You chose to inquire about your Medical History.");

                    context.ConversationData.SetValue <string>("state", "firstname");
                    await context.PostAsync($"Can I know your first name please ?");

                    questionResponded = true;
                }
                else if (input.ToLower() == "7" || Validator.sentenceComparison(keyVal, input) == true)
                {
                    await context.PostAsync($"Please type a brief description of your requirement.");

                    context.ConversationData.SetValue <string>("state", "reqdescription");
                    questionResponded = true;
                }
                else
                {
                    //await context.PostAsync($"Sorry, Cannot process this input at the moment.");
                    try
                    {
                        var commonQuestions = bM.getCommonQuestions();
                        foreach (var cQuestion in commonQuestions)
                        {
                            try
                            {
                                bool isMatch = Validator.sentenceComparison(cQuestion.Question, input);
                                if (isMatch == true)
                                {
                                    if (cQuestion.ConversationStateValue == "initgreet")
                                    {
                                        await context.PostAsync($"How can i help you today ? {Environment.NewLine}{Environment.NewLine}a)Book an appointment{Environment.NewLine}b)Patient Visit History{Environment.NewLine}c)Pay Bills{Environment.NewLine}d)Refill a request{Environment.NewLine}{Environment.NewLine}Please select an Option");

                                        context.ConversationData.SetValue <string>("state", "options");
                                    }
                                    else if (cQuestion.ConversationStateValue == "greet")
                                    {
                                        botResponse = cQuestion.Answer;
                                        botResponse = botResponse.Replace("{greet}", Validator.checkDayGreeting());
                                        await context.PostAsync(botResponse);

                                        context.ConversationData.SetValue <string>(cQuestion.ConversationState.ToLower(), cQuestion.ConversationStateValue.ToLower());
                                    }
                                    else
                                    {
                                        botResponse = cQuestion.Answer;
                                        await context.PostAsync(botResponse);

                                        context.ConversationData.SetValue <string>(cQuestion.ConversationState.ToLower(), cQuestion.ConversationStateValue.ToLower());
                                    }
                                    questionResponded = true;
                                    break;
                                }
                                else
                                {
                                    questionResponded = false;
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            else
            {
                try
                {
                    var commonQuestions = bM.getCommonQuestions();
                    foreach (var cQuestion in commonQuestions)
                    {
                        try
                        {
                            bool isMatch = Validator.sentenceComparison(cQuestion.Question, input);
                            if (isMatch == true)
                            {
                                if (cQuestion.ConversationStateValue == "initgreet")
                                {
                                    await context.PostAsync($"How can i help you today ?, {Environment.NewLine}{Environment.NewLine}a)Book an appointment{Environment.NewLine}b)Patient Visit History{Environment.NewLine}c)Pay Bills{Environment.NewLine}d)Refill a request{Environment.NewLine}{Environment.NewLine}Please select an Option");

                                    context.ConversationData.SetValue <string>("state", "options");
                                }
                                else if (cQuestion.ConversationStateValue == "greet")
                                {
                                    botResponse = cQuestion.Answer;
                                    botResponse = botResponse.Replace("{greet}", Validator.checkDayGreeting());
                                    await context.PostAsync(botResponse);

                                    context.ConversationData.SetValue <string>(cQuestion.ConversationState.ToLower(), cQuestion.ConversationStateValue.ToLower());
                                }
                                else
                                {
                                    botResponse = cQuestion.Answer;
                                    await context.PostAsync(botResponse);

                                    context.ConversationData.SetValue <string>(cQuestion.ConversationState.ToLower(), cQuestion.ConversationStateValue.ToLower());
                                }
                                questionResponded = true;

                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
            if (questionResponded == false)
            {
                await context.PostAsync($"Sorry, I couldn't get you.");
            }

            //if (input.Contains("hey") || input.Contains("hello"))
            //{
            //    await context.PostAsync($"What is your name ?");
            //    context.ConversationData.SetValue<string>("State","name");
            //}


            //else if (ShortName == null)
            //{
            //    await context.PostAsync($"The ICDcodes is Invalid..Please Enter Valid ICDcode ");
            //}
            //else
            //{
            //    await context.PostAsync($"The ICDcodes is  {activity.Text} and its shortname is  {ShortName} ");
            //    await context.PostAsync($"Do you want to search something else ...press yes or no!!");

            //}
            // Return our reply to the user


            context.Wait(MessageReceivedAsync);
        }
예제 #13
0
        /// <summary>
        /// Converts a string in the file to a field value.
        /// </summary>
        /// <param name="from">The string to convert.</param>
        /// <returns>Returns the field value.</returns>
        public override object StringToField(string @from)
        {
            var result = ConversionHelper.ConvertToNullableBoolean(from);

            return(result);
        }
예제 #14
0
        /// <summary>
        /// Process OTAA join request.
        /// </summary>
        async Task ProcessJoinRequestAsync(LoRaRequest request)
        {
            LoRaDevice loRaDevice = null;
            string     devEUI     = null;
            var        loraRegion = request.Region;

            try
            {
                var timeWatcher = new LoRaOperationTimeWatcher(loraRegion, request.StartTime);

                var    joinReq = (LoRaPayloadJoinRequest)request.Payload;
                byte[] udpMsgForPktForwarder = new byte[0];

                devEUI = joinReq.GetDevEUIAsString();
                var appEUI = joinReq.GetAppEUIAsString();

                var devNonce = joinReq.GetDevNonceAsString();
                Logger.Log(devEUI, $"join request received", LogLevel.Information);

                loRaDevice = await this.deviceRegistry.GetDeviceForJoinRequestAsync(devEUI, appEUI, devNonce);

                if (loRaDevice == null)
                {
                    request.NotifyFailed(devEUI, LoRaDeviceRequestFailedReason.UnknownDevice);
                    // we do not log here as we assume that the deviceRegistry does a more informed logging if returning null
                    return;
                }

                if (string.IsNullOrEmpty(loRaDevice.AppKey))
                {
                    Logger.Log(loRaDevice.DevEUI, "join refused: missing AppKey for OTAA device", LogLevel.Error);
                    request.NotifyFailed(loRaDevice, LoRaDeviceRequestFailedReason.InvalidJoinRequest);
                    return;
                }

                if (loRaDevice.AppEUI != appEUI)
                {
                    Logger.Log(devEUI, "join refused: AppEUI for OTAA does not match device", LogLevel.Error);
                    request.NotifyFailed(loRaDevice, LoRaDeviceRequestFailedReason.InvalidJoinRequest);
                    return;
                }

                if (!joinReq.CheckMic(loRaDevice.AppKey))
                {
                    Logger.Log(devEUI, "join refused: invalid MIC", LogLevel.Error);
                    request.NotifyFailed(loRaDevice, LoRaDeviceRequestFailedReason.JoinMicCheckFailed);
                    return;
                }

                // Make sure that is a new request and not a replay
                if (!string.IsNullOrEmpty(loRaDevice.DevNonce) && loRaDevice.DevNonce == devNonce)
                {
                    if (string.IsNullOrEmpty(loRaDevice.GatewayID))
                    {
                        Logger.Log(devEUI, "join refused: join already processed by another gateway", LogLevel.Information);
                    }
                    else
                    {
                        Logger.Log(devEUI, "join refused: DevNonce already used by this device", LogLevel.Error);
                    }

                    loRaDevice.IsOurDevice = false;
                    request.NotifyFailed(loRaDevice, LoRaDeviceRequestFailedReason.JoinDevNonceAlreadyUsed);
                    return;
                }

                // Check that the device is joining through the linked gateway and not another
                if (!string.IsNullOrEmpty(loRaDevice.GatewayID) && !string.Equals(loRaDevice.GatewayID, this.configuration.GatewayID, StringComparison.InvariantCultureIgnoreCase))
                {
                    Logger.Log(devEUI, $"join refused: trying to join not through its linked gateway, ignoring join request", LogLevel.Information);
                    loRaDevice.IsOurDevice = false;
                    request.NotifyFailed(loRaDevice, LoRaDeviceRequestFailedReason.HandledByAnotherGateway);
                    return;
                }

                var netIdBytes = BitConverter.GetBytes(this.configuration.NetId);
                var netId      = new byte[3]
                {
                    netIdBytes[0],
                    netIdBytes[1],
                    netIdBytes[2]
                };

                var appNonce      = OTAAKeysGenerator.GetAppNonce();
                var appNonceBytes = LoRaTools.Utils.ConversionHelper.StringToByteArray(appNonce);
                var appKeyBytes   = LoRaTools.Utils.ConversionHelper.StringToByteArray(loRaDevice.AppKey);
                var appSKey       = OTAAKeysGenerator.CalculateKey(new byte[1] {
                    0x02
                }, appNonceBytes, netId, joinReq.DevNonce, appKeyBytes);
                var nwkSKey = OTAAKeysGenerator.CalculateKey(new byte[1] {
                    0x01
                }, appNonceBytes, netId, joinReq.DevNonce, appKeyBytes);
                var devAddr = OTAAKeysGenerator.GetNwkId(netId);

                var oldDevAddr = loRaDevice.DevAddr;

                if (!timeWatcher.InTimeForJoinAccept())
                {
                    // in this case it's too late, we need to break and avoid saving twins
                    Logger.Log(devEUI, $"join refused: processing of the join request took too long, sending no message", LogLevel.Information);
                    request.NotifyFailed(loRaDevice, LoRaDeviceRequestFailedReason.ReceiveWindowMissed);
                    return;
                }

                var updatedProperties = new LoRaDeviceJoinUpdateProperties
                {
                    DevAddr            = devAddr,
                    NwkSKey            = nwkSKey,
                    AppSKey            = appSKey,
                    AppNonce           = appNonce,
                    DevNonce           = devNonce,
                    NetID              = ConversionHelper.ByteArrayToString(netId),
                    Region             = request.Region.LoRaRegion,
                    PreferredGatewayID = this.configuration.GatewayID,
                };

                if (loRaDevice.ClassType == LoRaDeviceClassType.C)
                {
                    updatedProperties.SavePreferredGateway = true;
                    updatedProperties.SaveRegion           = true;
                }

                var deviceUpdateSucceeded = await loRaDevice.UpdateAfterJoinAsync(updatedProperties);

                if (!deviceUpdateSucceeded)
                {
                    Logger.Log(devEUI, $"join refused: join request could not save twin", LogLevel.Error);
                    request.NotifyFailed(loRaDevice, LoRaDeviceRequestFailedReason.ApplicationError);
                    return;
                }

                var windowToUse = timeWatcher.ResolveJoinAcceptWindowToUse(loRaDevice);
                if (windowToUse == Constants.INVALID_RECEIVE_WINDOW)
                {
                    Logger.Log(devEUI, $"join refused: processing of the join request took too long, sending no message", LogLevel.Information);
                    request.NotifyFailed(loRaDevice, LoRaDeviceRequestFailedReason.ReceiveWindowMissed);
                    return;
                }

                double freq = 0;
                string datr = null;
                uint   tmst = 0;
                if (windowToUse == Constants.RECEIVE_WINDOW_1)
                {
                    datr = loraRegion.GetDownstreamDR(request.Rxpk);
                    if (!loraRegion.TryGetUpstreamChannelFrequency(request.Rxpk, out freq) || datr == null)
                    {
                        Logger.Log(loRaDevice.DevEUI, "could not resolve DR and/or frequency for downstream", LogLevel.Error);
                        request.NotifyFailed(loRaDevice, LoRaDeviceRequestFailedReason.InvalidRxpk);
                        return;
                    }

                    // set tmst for the normal case
                    tmst = request.Rxpk.Tmst + loraRegion.Join_accept_delay1 * 1000000;
                }
                else
                {
                    Logger.Log(devEUI, $"processing of the join request took too long, using second join accept receive window", LogLevel.Debug);
                    tmst = request.Rxpk.Tmst + loraRegion.Join_accept_delay2 * 1000000;

                    freq = loraRegion.GetDownstreamRX2Freq(devEUI, this.configuration.Rx2Frequency);
                    datr = loraRegion.GetDownstreamRX2Datarate(devEUI, this.configuration.Rx2DataRate, null);
                }

                loRaDevice.IsOurDevice = true;
                this.deviceRegistry.UpdateDeviceAfterJoin(loRaDevice, oldDevAddr);

                // Build join accept downlink message
                Array.Reverse(netId);
                Array.Reverse(appNonceBytes);

                // Build the DlSettings fields that is a superposition of RX2DR and RX1DROffset field
                byte[] dlSettings = new byte[1];

                if (loRaDevice.DesiredRX2DataRate.HasValue)
                {
                    if (request.Region.DRtoConfiguration.ContainsKey(loRaDevice.DesiredRX2DataRate.Value))
                    {
                        dlSettings[0] =
                            (byte)(loRaDevice.DesiredRX2DataRate & 0b00001111);
                    }
                    else
                    {
                        Logger.Log(devEUI, $"twin RX2 DR value is not within acceptable values", LogLevel.Error);
                    }
                }

                if (request.Region.IsValidRX1DROffset(loRaDevice.DesiredRX1DROffset))
                {
                    var rx1droffset = (byte)(loRaDevice.DesiredRX1DROffset << 4);
                    dlSettings[0] = (byte)(dlSettings[0] + rx1droffset);
                }
                else
                {
                    Logger.Log(devEUI, $"twin RX1 offset DR value is not within acceptable values", LogLevel.Error);
                }

                ushort rxDelay = 0;
                if (request.Region.IsValidRXDelay(loRaDevice.DesiredRXDelay))
                {
                    rxDelay = loRaDevice.DesiredRXDelay;
                }
                else
                {
                    Logger.Log(devEUI, $"twin RX delay value is not within acceptable values", LogLevel.Error);
                }

                var loRaPayloadJoinAccept = new LoRaPayloadJoinAccept(
                    LoRaTools.Utils.ConversionHelper.ByteArrayToString(netId), // NETID 0 / 1 is default test
                    ConversionHelper.StringToByteArray(devAddr),               // todo add device address management
                    appNonceBytes,
                    dlSettings,
                    rxDelay,
                    null);

                var joinAccept = loRaPayloadJoinAccept.Serialize(loRaDevice.AppKey, datr, freq, tmst, devEUI);
                if (joinAccept != null)
                {
                    _ = request.PacketForwarder.SendDownstreamAsync(joinAccept);
                    request.NotifySucceeded(loRaDevice, joinAccept);

                    if (Logger.LoggerLevel <= LogLevel.Debug)
                    {
                        var jsonMsg = JsonConvert.SerializeObject(joinAccept);
                        Logger.Log(devEUI, $"{LoRaMessageType.JoinAccept.ToString()} {jsonMsg}", LogLevel.Debug);
                    }
                    else if (Logger.LoggerLevel == LogLevel.Information)
                    {
                        Logger.Log(devEUI, "join accepted", LogLevel.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                var deviceId = devEUI ?? ConversionHelper.ByteArrayToString(request.Payload.DevAddr);
                Logger.Log(deviceId, $"failed to handle join request. {ex.Message}", LogLevel.Error);
                request.NotifyFailed(loRaDevice, ex);
            }
        }
예제 #15
0
 Memory <byte> ByteArray(string value) => ConversionHelper.StringToByteArray(value);
예제 #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalFunctions.ValidateSession())
                {
                    Response.Redirect("~/index.aspx", false);
                    return;
                }
                Page.Title = ConfigurationManager.AppSettings["ProjectTitle"].ToString() + " - Client Information " + ConfigurationManager.AppSettings["Version"].ToString();

                if (!IsPostBack)
                {
                    TitleCaption.Text = "Client Information";
                    ArrayList coldata = new ArrayList();
                    ArrayList coltype = new ArrayList();

                    #region Subscription
                    ViewState["SearchCondition_SubscriptionGet"] = "[vwSubscriptionGet] Where ClientId = " + ConversionHelper.ConvertToString(HtmlSerializer.HtmlToObject(Request.QueryString["p2"]));
                    ViewState["OrderBy_SubscriptionGet"]         = " Order By [SubscriptionId] ASC";
                    ViewState["SelectedField_SubscriptionGet"]   = "[SubscriptionId],[PackageName],[FirstName],[LastName],[CreditPost],[CreditPoint],[PaymentAmount],[PaymentTime],[PaymentId],[PaymentStatus],[PaymentResponse]";
                    DataTable dtSubscriptionGet = BeanHelper.SearchBean.GetData(ViewState["SearchCondition_SubscriptionGet"].ToString() + ViewState["OrderBy_SubscriptionGet"].ToString(), ViewState["SelectedField_SubscriptionGet"].ToString());

                    coldata = new ArrayList();
                    coltype = new ArrayList();
                    for (int i = 0; i < dtSubscriptionGet.Columns.Count; i++)
                    {
                        coldata.Add(dtSubscriptionGet.Columns[i].ColumnName);
                        coltype.Add(dtSubscriptionGet.Columns[i].DataType.Name);
                    }
                    ViewState["Columns_SubscriptionGet"]     = coldata;
                    ViewState["ColumnsType_SubscriptionGet"] = coltype;

                    GlobalFunctions.SetPaging(ref grdSubscriptionGet);
                    grdSubscriptionGet.DataSource = dtSubscriptionGet;
                    grdSubscriptionGet.DataBind();
                    lblRecord_Subscription.Text           = "Subscription Info. : " + (dtSubscriptionGet.Rows.Count.ToString()) + " Record(s)";
                    ViewState["PDFColWidth_Subscription"] = new float[] { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 };
                    #endregion

                    #region ProductRedeem
                    ViewState["SearchCondition_ProductRedeem"] = "vwProductRedeemGet Where ClientId = " + ConversionHelper.ConvertToString(HtmlSerializer.HtmlToObject(Request.QueryString["p2"]));
                    ViewState["OrderBy_ProductRedeem"]         = " Order By [ProductRedeemId] ASC";
                    ViewState["SelectedField_ProductRedeem"]   = "[ProductRedeemId],[FirstName],[LastName],[ProductName],[RedeemPoint]";

                    DataTable dtProductRedeem = BeanHelper.SearchBean.GetData(ViewState["SearchCondition_ProductRedeem"].ToString() + ViewState["OrderBy_ProductRedeem"].ToString(), ViewState["SelectedField_ProductRedeem"].ToString());
                    coldata = new ArrayList();
                    coltype = new ArrayList();
                    for (int i = 0; i < dtProductRedeem.Columns.Count; i++)
                    {
                        coldata.Add(dtProductRedeem.Columns[i].ColumnName);
                        coltype.Add(dtProductRedeem.Columns[i].DataType.Name);
                    }
                    ViewState["Columns_ProductRedeem"]     = coldata;
                    ViewState["ColumnsType_ProductRedeem"] = coltype;

                    GlobalFunctions.SetPaging(ref grdProductRedeemGet);
                    grdProductRedeemGet.DataSource = dtProductRedeem;
                    grdProductRedeemGet.DataBind();
                    lblRecord_ProductRedeemGet.Text        = "Product Redeem Info. : " + (dtProductRedeem.Rows.Count.ToString()) + " Record(s)";
                    ViewState["PDFColWidth_ProductRedeem"] = new float[] { 40, 20, 20, 20 };
                    #endregion
                }
            }
            catch (Exception ex)
            {
                Messagesection.Visible = true;
                Message.Text           = ex.Message;
                LogManager.Log(ex);
            }
        }
예제 #17
0
        public async Task When_Getting_Device_Information_From_Twin_Returns_JoinAccept(string deviceGatewayID)
        {
            var simulatedDevice = new SimulatedDevice(TestDeviceInfo.CreateOTAADevice(1, gatewayID: deviceGatewayID));
            var joinRequest     = simulatedDevice.CreateJoinRequest();

            // Create Rxpk
            var rxpk = joinRequest.SerializeUplink(simulatedDevice.LoRaDevice.AppKey).Rxpk[0];

            var payloadDecoder = new Mock <ILoRaPayloadDecoder>();

            var devNonce = ConversionHelper.ByteArrayToString(joinRequest.DevNonce);
            var devAddr  = string.Empty;
            var devEUI   = simulatedDevice.LoRaDevice.DeviceID;
            var appEUI   = simulatedDevice.LoRaDevice.AppEUI;

            var loRaDeviceClient = new Mock <ILoRaDeviceClient>(MockBehavior.Strict);

            // Device twin will be queried
            var twin = new Twin();

            twin.Properties.Desired[TwinProperty.DevEUI]        = devEUI;
            twin.Properties.Desired[TwinProperty.AppEUI]        = simulatedDevice.LoRaDevice.AppEUI;
            twin.Properties.Desired[TwinProperty.AppKey]        = simulatedDevice.LoRaDevice.AppKey;
            twin.Properties.Desired[TwinProperty.GatewayID]     = deviceGatewayID;
            twin.Properties.Desired[TwinProperty.SensorDecoder] = simulatedDevice.LoRaDevice.SensorDecoder;
            loRaDeviceClient.Setup(x => x.GetTwinAsync()).ReturnsAsync(twin);

            // Device twin will be updated
            string afterJoinAppSKey = null;
            string afterJoinNwkSKey = null;
            string afterJoinDevAddr = null;

            loRaDeviceClient.Setup(x => x.UpdateReportedPropertiesAsync(It.IsNotNull <TwinCollection>()))
            .Callback <TwinCollection>((updatedTwin) =>
            {
                afterJoinAppSKey = updatedTwin[TwinProperty.AppSKey];
                afterJoinNwkSKey = updatedTwin[TwinProperty.NwkSKey];
                afterJoinDevAddr = updatedTwin[TwinProperty.DevAddr];
            })
            .ReturnsAsync(true);

            // Lora device api will be search by devices with matching deveui,
            var loRaDeviceApi = new Mock <LoRaDeviceAPIServiceBase>(MockBehavior.Strict);

            loRaDeviceApi.Setup(x => x.SearchAndLockForJoinAsync(this.ServerConfiguration.GatewayID, devEUI, appEUI, devNonce))
            .ReturnsAsync(new SearchDevicesResult(new IoTHubDeviceInfo(devAddr, devEUI, "aabb").AsList()));

            var loRaDeviceFactory = new TestLoRaDeviceFactory(loRaDeviceClient.Object);

            var memoryCache    = new MemoryCache(new MemoryCacheOptions());
            var deviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, memoryCache, loRaDeviceApi.Object, loRaDeviceFactory);

            // Setup frame counter strategy for FrameCounterLoRaDeviceInitializer
            if (deviceGatewayID == null)
            {
                this.FrameCounterUpdateStrategyFactory.Setup(x => x.GetMultiGatewayStrategy())
                .Returns(this.FrameCounterUpdateStrategy.Object);
            }
            else
            {
                this.FrameCounterUpdateStrategyFactory.Setup(x => x.GetSingleGatewayStrategy())
                .Returns(this.FrameCounterUpdateStrategy.Object);
            }

            // Send to message processor
            var messageProcessor = new MessageProcessor(
                this.ServerConfiguration,
                deviceRegistry,
                this.FrameCounterUpdateStrategyFactory.Object,
                payloadDecoder.Object);

            var downlinkMessage = await messageProcessor.ProcessMessageAsync(rxpk);

            Assert.NotNull(downlinkMessage);
            var joinAccept = new LoRaPayloadJoinAccept(Convert.FromBase64String(downlinkMessage.Txpk.Data), simulatedDevice.LoRaDevice.AppKey);

            Assert.Equal(joinAccept.DevAddr.ToArray(), ConversionHelper.StringToByteArray(afterJoinDevAddr));

            // check that the device is in cache
            Assert.True(memoryCache.TryGetValue <DevEUIToLoRaDeviceDictionary>(afterJoinDevAddr, out var cachedDevices));
            Assert.True(cachedDevices.TryGetValue(devEUI, out var cachedDevice));
            Assert.Equal(afterJoinAppSKey, cachedDevice.AppSKey);
            Assert.Equal(afterJoinNwkSKey, cachedDevice.NwkSKey);
            Assert.Equal(afterJoinDevAddr, cachedDevice.DevAddr);
            Assert.True(cachedDevice.IsOurDevice);
            if (deviceGatewayID == null)
            {
                Assert.Null(cachedDevice.GatewayID);
            }
            else
            {
                Assert.Equal(deviceGatewayID, cachedDevice.GatewayID);
            }

            // fcnt is restarted
            Assert.Equal(0, cachedDevice.FCntUp);
            Assert.Equal(0, cachedDevice.FCntDown);
            Assert.False(cachedDevice.HasFrameCountChanges);
        }
예제 #18
0
 public static string Config(string key, float value)
 {
     return(Config(key, ConversionHelper.ToInt(value)));
 }
예제 #19
0
        public async Task When_Device_Is_Found_In_Api_Should_Update_Twin_And_Return()
        {
            var simulatedDevice = new SimulatedDevice(TestDeviceInfo.CreateOTAADevice(1, gatewayID: this.ServerConfiguration.GatewayID));

            simulatedDevice.LoRaDevice.NwkSKey = string.Empty;
            simulatedDevice.LoRaDevice.AppSKey = string.Empty;
            var joinRequest = simulatedDevice.CreateJoinRequest();

            var loRaDeviceClient = new Mock <ILoRaDeviceClient>();
            var loRaDevice       = TestUtils.CreateFromSimulatedDevice(simulatedDevice, loRaDeviceClient.Object);

            loRaDevice.SetFcntDown(10);
            loRaDevice.SetFcntUp(20);

            // Create Rxpk
            var rxpk = joinRequest.SerializeUplink(simulatedDevice.LoRaDevice.AppKey).Rxpk[0];

            var payloadDecoder = new Mock <ILoRaPayloadDecoder>();

            var devNonce = ConversionHelper.ByteArrayToString(joinRequest.DevNonce);
            var devEUI   = simulatedDevice.LoRaDevice.DeviceID;
            var appEUI   = simulatedDevice.LoRaDevice.AppEUI;

            this.LoRaDeviceRegistry.Setup(x => x.GetDeviceForJoinRequestAsync(devEUI, appEUI, devNonce))
            .ReturnsAsync(() => loRaDevice);

            this.LoRaDeviceRegistry.Setup(x => x.UpdateDeviceAfterJoin(loRaDevice));

            // Ensure that the device twin was updated
            loRaDeviceClient.Setup(x => x.UpdateReportedPropertiesAsync(It.Is <TwinCollection>((t) =>
                                                                                               t.Contains(TwinProperty.DevAddr) && t.Contains(TwinProperty.FCntDown))))
            .ReturnsAsync(true);

            // Send to message processor
            var messageProcessor = new MessageProcessor(
                this.ServerConfiguration,
                this.LoRaDeviceRegistry.Object,
                this.FrameCounterUpdateStrategyFactory.Object,
                payloadDecoder.Object);

            var actual = await messageProcessor.ProcessMessageAsync(rxpk);

            Assert.NotNull(actual);

            var pktFwdMessage = actual.GetPktFwdMessage();

            Assert.NotNull(pktFwdMessage.Txpk);
            var joinAccept = new LoRaPayloadJoinAccept(Convert.FromBase64String(pktFwdMessage.Txpk.Data), loRaDevice.AppKey);

            Assert.Equal(joinAccept.DevAddr.ToArray(), this.ByteArray(loRaDevice.DevAddr).ToArray());

            // Device properties were set with the computes values of the join operation
            Assert.Equal(joinAccept.AppNonce.ToArray(), this.ReversedByteArray(loRaDevice.AppNonce).ToArray());
            Assert.NotEmpty(loRaDevice.NwkSKey);
            Assert.NotEmpty(loRaDevice.AppSKey);
            Assert.True(loRaDevice.IsOurDevice);

            // Device frame counts were reset
            Assert.Equal(0, loRaDevice.FCntDown);
            Assert.Equal(0, loRaDevice.FCntUp);
            Assert.False(loRaDevice.HasFrameCountChanges);

            // Twin property were updated
            loRaDeviceClient.VerifyAll();
        }
예제 #20
0
파일: VcrButtons.cs 프로젝트: radtek/BootFX
        /// <summary>
        /// Finds the given text.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        private bool Find(string text, int from, int to)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            if (text.Length == 0)
            {
                throw new ArgumentOutOfRangeException("'text' is zero-length.");
            }

            if (InnerList == null)
            {
                throw new InvalidOperationException("InnerList is null.");
            }

            // lower...
            text = text.ToLower();

            // examine in turn...
            for (int index = from; index < to; index++)
            {
                // get it...
                object entity = this.InnerList[index];
                if (entity == null)
                {
                    throw new InvalidOperationException("entity is null.");
                }
                entity = EntityView.Unwrap(entity);
                if (entity == null)
                {
                    throw new InvalidOperationException("entity is null (2).");
                }

                // entity type...
                EntityType entityType = EntityType.GetEntityType(entity, OnNotFound.ThrowException);
                if (entityType == null)
                {
                    throw new InvalidOperationException("entityType is null.");
                }

                // walk fields...
                foreach (EntityField field in entityType.Fields)
                {
                    // text?
                    if (this.IsFindCandiate(field))
                    {
                        // get the value...
                        string value = ConversionHelper.ToString(entityType.Storage.GetValue(entity, field, ConversionFlags.Safe), Cultures.User);
                        if (value != null)
                        {
                            // find...
                            value = value.ToLower();
                            int textIndex = value.IndexOf(text);
                            if (textIndex != -1)
                            {
                                this.Position = index;
                                return(true);
                            }
                        }
                    }
                }
            }

            // nope...
            return(false);
        }
        private async Task <byte[]> ProcessJoinRequest(LoRaMessageWrapper loraMessage)
        {
            byte[] udpMsgForPktForwarder = new Byte[0];
            var    joinReq = (LoRaPayloadJoinRequest)loraMessage.LoRaPayloadMessage;

            joinReq.DevEUI.Span.Reverse();
            joinReq.AppEUI.Span.Reverse();
            string devEui   = ConversionHelper.ByteArrayToString(joinReq.DevEUI.ToArray());
            string devNonce = ConversionHelper.ByteArrayToString(joinReq.DevNonce.ToArray());

            Logger.Log(devEui, $"join request received", Logger.LoggingLevel.Info);
            //checking if this devnonce was already processed or the deveui was already refused
            //check if join request is valid.
            //we have a join request in the cache
            if (Cache.TryGetJoinRequestValue(devEui, out LoraDeviceInfo joinLoraDeviceInfo))
            {
                //is our device but the join was not valid
                if (!joinLoraDeviceInfo.IsJoinValid)
                {
                    //if the devNonce is equal to the current it is a potential replay attck
                    if (joinLoraDeviceInfo.DevNonce == devNonce)
                    {
                        Logger.Log(devEui, $"join request refused devNonce already used", Logger.LoggingLevel.Info);
                        return(null);
                    }

                    //Check if the device is trying to join through the wrong gateway
                    if (!String.IsNullOrEmpty(joinLoraDeviceInfo.GatewayID) && string.Compare(joinLoraDeviceInfo.GatewayID, this.configuration.GatewayID, ignoreCase: true) != 0)
                    {
                        Logger.Log(devEui, $"trying to join not through its linked gateway, ignoring join request", Logger.LoggingLevel.Info);
                        return(null);
                    }
                }
            }

            joinLoraDeviceInfo = await this.loraDeviceInfoManager.PerformOTAAAsync(this.configuration.GatewayID, devEui, ConversionHelper.ByteArrayToString(joinReq.AppEUI.ToArray()), devNonce, joinLoraDeviceInfo);


            if (joinLoraDeviceInfo != null && joinLoraDeviceInfo.IsJoinValid)
            {
                if (!loraMessage.LoRaPayloadMessage.CheckMic(joinLoraDeviceInfo.AppKey))
                {
                    Logger.Log(devEui, $"join request MIC invalid", Logger.LoggingLevel.Info);
                }
                //join request resets the frame counters
                joinLoraDeviceInfo.FCntUp   = 0;
                joinLoraDeviceInfo.FCntDown = 0;
                //in this case it's too late, we need to break and awoid saving twins
                if ((DateTime.UtcNow - startTimeProcessing) > TimeSpan.FromMilliseconds(RegionFactory.CurrentRegion.join_accept_delay2 * 1000))
                {
                    Logger.Log(devEui, $"processing of the join request took too long, sending no message", Logger.LoggingLevel.Info);
                }
                //update reported properties and frame Counter
                //in case not successfull we interrupt the flow
                if (!await joinLoraDeviceInfo.HubSender.UpdateReportedPropertiesOTAAasync(joinLoraDeviceInfo))
                {
                    Logger.Log(devEui, $"join request could not save twins, join refused", Logger.LoggingLevel.Error);

                    return(null);
                }

                byte[] appNonce = ConversionHelper.StringToByteArray(joinLoraDeviceInfo.AppNonce);
                byte[] netId    = ConversionHelper.StringToByteArray(joinLoraDeviceInfo.NetId);
                byte[] devAddr  = ConversionHelper.StringToByteArray(joinLoraDeviceInfo.DevAddr);
                string appKey   = joinLoraDeviceInfo.AppKey;
                Array.Reverse(netId);
                Array.Reverse(appNonce);
                LoRaPayloadJoinAccept loRaPayloadJoinAccept = new LoRaPayloadJoinAccept(
                    //NETID 0 / 1 is default test
                    ConversionHelper.ByteArrayToString(netId),
                    //todo add app key management
                    appKey,
                    //todo add device address management
                    devAddr,
                    appNonce,
                    new byte[] { 0 },
                    new byte[] { 0 },
                    null
                    );
                var    datr = RegionFactory.CurrentRegion.GetDownstreamDR(loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0]);
                uint   rfch = loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0].rfch;
                double freq = RegionFactory.CurrentRegion.GetDownstreamChannel(loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0]);
                //set tmst for the normal case
                long tmst = loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0].tmst + RegionFactory.CurrentRegion.join_accept_delay1 * 1000000;

                ////in this case it's too late, we need to break
                //if ((DateTime.UtcNow - startTimeProcessing) > TimeSpan.FromMilliseconds(RegionFactory.CurrentRegion.join_accept_delay2 * 1000))
                //{
                //    Logger.Log(devEui, $"processing of the join request took too long, sending no message", Logger.LoggingLevel.Info);
                //    var physicalResponse = new PhysicalPayload(loraMessage.PhysicalPayload.token, PhysicalIdentifier.PULL_RESP, null);

                //    Logger.Log(devEui, $"processing time: {DateTime.UtcNow - startTimeProcessing}", Logger.LoggingLevel.Info);

                //    return physicalResponse.GetMessage();
                //}
                //in this case the second join windows must be used
                if ((DateTime.UtcNow - startTimeProcessing) > TimeSpan.FromMilliseconds(RegionFactory.CurrentRegion.join_accept_delay1 * 1000 - 100))
                {
                    Logger.Log(devEui, $"processing of the join request took too long, using second join accept receive window", Logger.LoggingLevel.Info);
                    tmst = loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0].tmst + RegionFactory.CurrentRegion.join_accept_delay2 * 1000000;
                    if (string.IsNullOrEmpty(configuration.Rx2DataRate))
                    {
                        Logger.Log(devEui, $"using standard second receive windows for join request", Logger.LoggingLevel.Info);
                        //using EU fix DR for RX2
                        freq = RegionFactory.CurrentRegion.RX2DefaultReceiveWindows.frequency;
                        datr = RegionFactory.CurrentRegion.DRtoConfiguration[RegionFactory.CurrentRegion.RX2DefaultReceiveWindows.dr].configuration;
                    }
                    //if specific twins are set, specify second channel to be as specified
                    else
                    {
                        Logger.Log(devEui, $"using custom  second receive windows for join request", Logger.LoggingLevel.Info);
                        freq = configuration.Rx2DataFrequency;
                        datr = configuration.Rx2DataRate;
                    }
                }
                LoRaMessageWrapper joinAcceptMessage = new LoRaMessageWrapper(loRaPayloadJoinAccept, LoRaMessageType.JoinAccept, loraMessage.PhysicalPayload.token, datr, 0, freq, tmst);

                udpMsgForPktForwarder = joinAcceptMessage.PhysicalPayload.GetMessage();

                //add to cache for processing normal messages. This awoids one additional call to the server.

                Cache.AddRequestToCache(joinLoraDeviceInfo.DevAddr, joinLoraDeviceInfo);

                Logger.Log(devEui, String.Format("join accept sent with ID {0}",
                                                 ConversionHelper.ByteArrayToString(loraMessage.PhysicalPayload.token)),
                           Logger.LoggingLevel.Full);
            }
            else
            {
                Logger.Log(devEui, $"join request refused", Logger.LoggingLevel.Info);
            }

            Logger.Log(devEui, $"processing time: {DateTime.UtcNow - startTimeProcessing}", Logger.LoggingLevel.Info);


            return(udpMsgForPktForwarder);
        }
예제 #22
0
        public static string DecryptData(byte[] ksn, string cipher)
        {
            // set KSN counter to 0
            byte[] ksnZeroCounter = SetKSNZeroCounter(ksn);
            byte[] registerKeys   = new byte[RegisterSize];

            // LEFT REGISTER ENCRYPTION
            byte[] leftRegister = GenerateLeftRegister(ksnZeroCounter);
            Array.Copy(leftRegister, registerKeys, leftRegister.Length);

            // RIGHT REGISTER ENCRYPTION
            byte[] rightRegister = GenerateRightRegister(ksnZeroCounter);
            Array.Copy(rightRegister, 0, registerKeys, rightRegister.Length, rightRegister.Length);

            //1234567890|1234567890|12345
            Debug.WriteLine($"IPEK_______: {ConversionHelper.ByteArrayToHexString(leftRegister)}-{ConversionHelper.ByteArrayToHexString(rightRegister)}");

            byte[] sessionKey = CreateSessionKey(registerKeys, ksn);

            using (var tdes = new TripleDESCryptoServiceProvider())
            {
                tdes.Mode    = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;
                tdes.Key     = registerKeys;

                using (var transform = tdes.CreateEncryptor())
                {
                    byte[] textBytes = UTF8Encoding.UTF8.GetBytes(cipher);
                    byte[] bytes     = transform.TransformFinalBlock(textBytes, 0, textBytes.Length);
                    return(Convert.ToBase64String(bytes, 0, bytes.Length));
                }
            }
        }
        private async Task <byte[]> ProcessLoraMessage(LoRaMessageWrapper loraMessage)
        {
            bool validFrameCounter = false;

            byte[]         udpMsgForPktForwarder = new byte[0];
            string         devAddr        = ConversionHelper.ByteArrayToString(loraMessage.LoRaPayloadMessage.DevAddr.ToArray());
            Message        c2dMsg         = null;
            LoraDeviceInfo loraDeviceInfo = null;

            if (Cache.TryGetRequestValue(devAddr, out ConcurrentDictionary <string, LoraDeviceInfo> loraDeviceInfoCacheList))
            {
                loraDeviceInfo = loraDeviceInfoCacheList.Values.FirstOrDefault(x =>
                                                                               x.NwkSKey != null?loraMessage.CheckMic(x.NwkSKey):false);
            }
            if (loraDeviceInfo == null)
            {
                loraDeviceInfo = await this.loraDeviceInfoManager.GetLoraDeviceInfoAsync(devAddr, this.configuration.GatewayID, loraMessage);

                if (loraDeviceInfo != null && loraDeviceInfo.DevEUI != null)
                {
                    if (loraDeviceInfo.DevEUI != null)
                    {
                        Logger.Log(loraDeviceInfo.DevEUI, $"processing message, device not in cache", Logger.LoggingLevel.Info);
                    }
                    if (loraDeviceInfo.IsOurDevice)
                    {
                        Cache.AddRequestToCache(devAddr, loraDeviceInfo);
                    }
                }
            }
            else
            {
                Logger.Log(devAddr, $"processing message, device in cache", Logger.LoggingLevel.Info);
            }

            if (loraDeviceInfo != null && loraDeviceInfo.IsOurDevice)
            {
                //either there is no gateway linked to the device or the gateway is the one that the code is running
                if (string.IsNullOrEmpty(loraDeviceInfo.GatewayID) || string.Compare(loraDeviceInfo.GatewayID, this.configuration.GatewayID, ignoreCase: true) == 0)
                {
                    if (loraDeviceInfo.HubSender == null)
                    {
                        loraDeviceInfo.HubSender = new IoTHubConnector(loraDeviceInfo.DevEUI, loraDeviceInfo.PrimaryKey, this.configuration);
                    }
                    UInt16 fcntup = BitConverter.ToUInt16(loraMessage.LoRaPayloadMessage.GetLoRaMessage().Fcnt.ToArray(), 0);
                    byte[] linkCheckCmdResponse = null;

                    //check if the frame counter is valid: either is above the server one or is an ABP device resetting the counter (relaxed seqno checking)
                    if (fcntup > loraDeviceInfo.FCntUp || (fcntup == 0 && loraDeviceInfo.FCntUp == 0) || (fcntup == 1 && String.IsNullOrEmpty(loraDeviceInfo.AppEUI)))
                    {
                        //save the reset fcnt for ABP (relaxed seqno checking)
                        if (fcntup == 1 && String.IsNullOrEmpty(loraDeviceInfo.AppEUI))
                        {
                            _ = loraDeviceInfo.HubSender.UpdateFcntAsync(fcntup, 0, true);

                            //if the device is not attached to a gateway we need to reset the abp fcnt server side cache
                            if (String.IsNullOrEmpty(loraDeviceInfo.GatewayID))
                            {
                                bool rit = await this.loraDeviceInfoManager.ABPFcntCacheReset(loraDeviceInfo.DevEUI);
                            }
                        }

                        validFrameCounter = true;
                        Logger.Log(loraDeviceInfo.DevEUI, $"valid frame counter, msg: {fcntup} server: {loraDeviceInfo.FCntUp}", Logger.LoggingLevel.Info);

                        byte[] decryptedMessage = null;
                        try
                        {
                            decryptedMessage = loraMessage.DecryptPayload(loraDeviceInfo.AppSKey);
                        }
                        catch (Exception ex)
                        {
                            Logger.Log(loraDeviceInfo.DevEUI, $"failed to decrypt message: {ex.Message}", Logger.LoggingLevel.Error);
                        }
                        Rxpk    rxPk            = loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0];
                        dynamic fullPayload     = JObject.FromObject(rxPk);
                        string  jsonDataPayload = "";
                        uint    fportUp         = 0;
                        bool    isAckFromDevice = false;
                        if (loraMessage.LoRaPayloadMessage.GetLoRaMessage().Fport.Span.Length > 0)
                        {
                            fportUp = (uint)loraMessage.LoRaPayloadMessage.GetLoRaMessage().Fport.Span[0];
                        }
                        else // this is an acknowledgment sent from the device
                        {
                            isAckFromDevice       = true;
                            fullPayload.deviceAck = true;
                        }
                        fullPayload.port = fportUp;
                        fullPayload.fcnt = fcntup;

                        // ACK from device or no decoder set in LoRa Device Twin. Simply return decryptedMessage
                        if (isAckFromDevice || String.IsNullOrEmpty(loraDeviceInfo.SensorDecoder))
                        {
                            if (String.IsNullOrEmpty(loraDeviceInfo.SensorDecoder))
                            {
                                Logger.Log(loraDeviceInfo.DevEUI, $"no decoder set in device twin. port: {fportUp}", Logger.LoggingLevel.Full);
                            }

                            jsonDataPayload  = Convert.ToBase64String(decryptedMessage);
                            fullPayload.data = jsonDataPayload;
                        }
                        // Decoder is set in LoRa Device Twin. Send decrpytedMessage (payload) and fportUp (fPort) to decoder.
                        else
                        {
                            Logger.Log(loraDeviceInfo.DevEUI, $"decoding with: {loraDeviceInfo.SensorDecoder} port: {fportUp}", Logger.LoggingLevel.Full);
                            fullPayload.data = await LoraDecoders.DecodeMessage(decryptedMessage, fportUp, loraDeviceInfo.SensorDecoder);
                        }

                        fullPayload.eui       = loraDeviceInfo.DevEUI;
                        fullPayload.gatewayid = this.configuration.GatewayID;
                        //Edge timestamp
                        fullPayload.edgets = (long)((startTimeProcessing - new DateTime(1970, 1, 1)).TotalMilliseconds);
                        List <KeyValuePair <String, String> > messageProperties = new List <KeyValuePair <String, String> >();

                        //Parsing MacCommands and add them as property of the message to be sent to the IoT Hub.
                        var macCommand = ((LoRaPayloadData)loraMessage.LoRaPayloadMessage).GetMacCommands();
                        if (macCommand.macCommand.Count > 0)
                        {
                            for (int i = 0; i < macCommand.macCommand.Count; i++)
                            {
                                messageProperties.Add(new KeyValuePair <string, string>(macCommand.macCommand[i].Cid.ToString(), value: JsonConvert.SerializeObject(macCommand.macCommand[i], Newtonsoft.Json.Formatting.None)));
                                //in case it is a link check mac, we need to send it downstream.
                                if (macCommand.macCommand[i].Cid == CidEnum.LinkCheckCmd)
                                {
                                    linkCheckCmdResponse = new LinkCheckCmd(rxPk.GetModulationMargin(), 1).ToBytes();
                                }
                            }
                        }
                        string iotHubMsg = fullPayload.ToString(Newtonsoft.Json.Formatting.None);
                        await loraDeviceInfo.HubSender.SendMessageAsync(iotHubMsg, messageProperties);

                        if (isAckFromDevice)
                        {
                            Logger.Log(loraDeviceInfo.DevEUI, $"ack from device sent to hub", Logger.LoggingLevel.Info);
                        }
                        else
                        {
                            var fullPayloadAsString = string.Empty;
                            if (fullPayload.data is JValue jvalue)
                            {
                                fullPayloadAsString = jvalue.ToString();
                            }
                            else if (fullPayload.data is JObject jobject)
                            {
                                fullPayloadAsString = jobject.ToString(Formatting.None);
                            }
                            Logger.Log(loraDeviceInfo.DevEUI, $"message '{fullPayloadAsString}' sent to hub", Logger.LoggingLevel.Info);
                        }
                        loraDeviceInfo.FCntUp = fcntup;
                    }
                    else
                    {
                        validFrameCounter = false;
                        Logger.Log(loraDeviceInfo.DevEUI, $"invalid frame counter, msg: {fcntup} server: {loraDeviceInfo.FCntUp}", Logger.LoggingLevel.Info);
                    }
                    byte[] fctrl = new byte[1] {
                        0
                    };

                    //we lock as fast as possible and get the down fcnt for multi gateway support for confirmed message
                    if (loraMessage.LoRaMessageType == LoRaMessageType.ConfirmedDataUp && String.IsNullOrEmpty(loraDeviceInfo.GatewayID))
                    {
                        fctrl[0] = (int)FctrlEnum.Ack;
                        ushort newFCntDown = await this.loraDeviceInfoManager.NextFCntDown(loraDeviceInfo.DevEUI, loraDeviceInfo.FCntDown, fcntup, this.configuration.GatewayID);

                        //ok to send down ack or msg
                        if (newFCntDown > 0)
                        {
                            loraDeviceInfo.FCntDown = newFCntDown;
                        }
                        //another gateway was first with this message we simply drop
                        else
                        {
                            Logger.Log(loraDeviceInfo.DevEUI, $"another gateway has already sent ack or downlink msg", Logger.LoggingLevel.Info);
                            Logger.Log(loraDeviceInfo.DevEUI, $"processing time: {DateTime.UtcNow - startTimeProcessing}", Logger.LoggingLevel.Info);
                            return(null);
                        }
                    }
                    //start checking for new c2d message, we do it even if the fcnt is invalid so we support replying to the ConfirmedDataUp
                    //todo ronnie should we wait up to 900 msec?
                    c2dMsg = await loraDeviceInfo.HubSender.ReceiveAsync(TimeSpan.FromMilliseconds(500));

                    if (c2dMsg != null && !ValidateCloudToDeviceMessage(loraDeviceInfo, c2dMsg))
                    {
                        _      = loraDeviceInfo.HubSender.CompleteAsync(c2dMsg);
                        c2dMsg = null;
                    }

                    byte[] bytesC2dMsg = null;
                    byte[] fport       = null;

                    //check if we got a c2d message to be added in the ack message and prepare the message
                    if (c2dMsg != null)
                    {
                        ////check if there is another message
                        var secondC2dMsg = await loraDeviceInfo.HubSender.ReceiveAsync(TimeSpan.FromMilliseconds(40));

                        if (secondC2dMsg != null)
                        {
                            //put it back to the queue for the next pickup
                            //todo ronnie check abbandon logic especially in case of mqtt
                            _ = await loraDeviceInfo.HubSender.AbandonAsync(secondC2dMsg);

                            //set the fpending flag so the lora device will call us back for the next message
                            fctrl[0] += (int)FctrlEnum.FpendingOrClassB;
                            Logger.Log(loraDeviceInfo.DevEUI, $"Additional C2D messages waiting, setting FPending to 1", Logger.LoggingLevel.Info);
                        }

                        bytesC2dMsg = c2dMsg.GetBytes();
                        //default fport
                        fport = new byte[1] {
                            1
                        };

                        if (bytesC2dMsg != null)
                        {
                            Logger.Log(loraDeviceInfo.DevEUI, $"C2D message: {Encoding.UTF8.GetString(bytesC2dMsg)}", Logger.LoggingLevel.Info);
                        }

                        //todo ronnie implement a better max payload size by datarate
                        //cut to the max payload of lora for any EU datarate
                        if (bytesC2dMsg.Length > 51)
                        {
                            Array.Resize(ref bytesC2dMsg, 51);
                        }

                        Array.Reverse(bytesC2dMsg);
                    }
                    //if confirmation or cloud to device msg send down the message
                    if (loraMessage.LoRaMessageType == LoRaMessageType.ConfirmedDataUp || c2dMsg != null)
                    {
                        if (loraMessage.LoRaMessageType == LoRaMessageType.ConfirmedDataUp)
                        {
                            fctrl[0] += (int)FctrlEnum.Ack;
                        }

                        //check if we are not too late for the second receive windows
                        if ((DateTime.UtcNow - startTimeProcessing) <= TimeSpan.FromMilliseconds(RegionFactory.CurrentRegion.receive_delay2 * 1000 - 100))
                        {
                            //if running in multigateway we need to use redis to sync the down fcnt
                            if (!String.IsNullOrEmpty(loraDeviceInfo.GatewayID))
                            {
                                loraDeviceInfo.FCntDown++;
                            }
                            else if (loraMessage.LoRaMessageType == LoRaMessageType.UnconfirmedDataUp)
                            {
                                ushort newFCntDown = await this.loraDeviceInfoManager.NextFCntDown(loraDeviceInfo.DevEUI, loraDeviceInfo.FCntDown, fcntup, this.configuration.GatewayID);

                                //ok to send down ack or msg
                                if (newFCntDown > 0)
                                {
                                    loraDeviceInfo.FCntDown = newFCntDown;
                                }
                                //another gateway was first with this message we simply drop
                                else
                                {
                                    Logger.Log(loraDeviceInfo.DevEUI, $"another gateway has already sent ack or downlink msg", Logger.LoggingLevel.Info);
                                    Logger.Log(loraDeviceInfo.DevEUI, $"processing time: {DateTime.UtcNow - startTimeProcessing}", Logger.LoggingLevel.Info);
                                    return(null);
                                }
                            }
                            Logger.Log(loraDeviceInfo.DevEUI, $"down frame counter: {loraDeviceInfo.FCntDown}", Logger.LoggingLevel.Info);

                            //Saving both fcnts to twins
                            _ = loraDeviceInfo.HubSender.UpdateFcntAsync(loraDeviceInfo.FCntUp, loraDeviceInfo.FCntDown);
                            //todo need implementation of current configuation to implement this as this depends on RX1DROffset
                            //var _datr = ((UplinkPktFwdMessage)loraMessage.LoraMetadata.FullPayload).rxpk[0].datr;
                            var datr = RegionFactory.CurrentRegion.GetDownstreamDR(loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0]);
                            //todo should discuss about the logic in case of multi channel gateway.
                            uint rfch = loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0].rfch;
                            //todo should discuss about the logic in case of multi channel gateway
                            double freq = RegionFactory.CurrentRegion.GetDownstreamChannel(loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0]);
                            //if we are already longer than 900 mssecond move to the 2 second window
                            //uncomment the following line to force second windows usage TODO change this to a proper expression?
                            //Thread.Sleep(901
                            long tmst = loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0].tmst + RegionFactory.CurrentRegion.receive_delay1 * 1000000;

                            if ((DateTime.UtcNow - startTimeProcessing) > TimeSpan.FromMilliseconds(RegionFactory.CurrentRegion.receive_delay1 * 1000 - 100))
                            {
                                if (string.IsNullOrEmpty(configuration.Rx2DataRate))
                                {
                                    Logger.Log(loraDeviceInfo.DevEUI, $"using standard second receive windows", Logger.LoggingLevel.Info);
                                    tmst = loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0].tmst + RegionFactory.CurrentRegion.receive_delay2 * 1000000;
                                    freq = RegionFactory.CurrentRegion.RX2DefaultReceiveWindows.frequency;
                                    datr = RegionFactory.CurrentRegion.DRtoConfiguration[RegionFactory.CurrentRegion.RX2DefaultReceiveWindows.dr].configuration;
                                }
                                //if specific twins are set, specify second channel to be as specified
                                else
                                {
                                    freq = configuration.Rx2DataFrequency;
                                    datr = configuration.Rx2DataRate;
                                    Logger.Log(loraDeviceInfo.DevEUI, $"using custom DR second receive windows freq : {freq}, datr:{datr}", Logger.LoggingLevel.Info);
                                }
                            }
                            Byte[] devAddrCorrect = new byte[4];
                            Array.Copy(loraMessage.LoRaPayloadMessage.DevAddr.ToArray(), devAddrCorrect, 4);
                            Array.Reverse(devAddrCorrect);
                            bool   requestForConfirmedResponse = false;
                            byte[] rndToken = new byte[2];
                            Random rnd      = new Random();
                            rnd.NextBytes(rndToken);

                            //check if the c2d message has a mac command
                            byte[] macbytes = null;
                            if (c2dMsg != null)
                            {
                                if (c2dMsg.Properties.TryGetValueCaseInsensitive("cidtype", out var cidTypeValue))
                                {
                                    Logger.Log(loraDeviceInfo.DevEUI, $"Cloud to device MAC command received", Logger.LoggingLevel.Info);
                                    MacCommandHolder macCommandHolder = new MacCommandHolder(Convert.ToByte(cidTypeValue));
                                    macbytes = macCommandHolder.macCommand[0].ToBytes();
                                }

                                if (c2dMsg.Properties.TryGetValueCaseInsensitive("confirmed", out var confirmedValue) && confirmedValue.Equals("true", StringComparison.OrdinalIgnoreCase))
                                {
                                    requestForConfirmedResponse = true;
                                    Logger.Log(loraDeviceInfo.DevEUI, $"Cloud to device message requesting a confirmation", Logger.LoggingLevel.Info);
                                }
                                if (c2dMsg.Properties.TryGetValueCaseInsensitive("fport", out var fPortValue))
                                {
                                    int fportint = int.Parse(fPortValue);

                                    fport[0] = BitConverter.GetBytes(fportint)[0];
                                    Logger.Log(loraDeviceInfo.DevEUI, $"Cloud to device message with a Fport of " + fPortValue, Logger.LoggingLevel.Info);
                                }
                                Logger.Log(loraDeviceInfo.DevEUI, String.Format("Sending a downstream message with ID {0}",
                                                                                ConversionHelper.ByteArrayToString(rndToken)),
                                           Logger.LoggingLevel.Full);
                            }

                            if (requestForConfirmedResponse)
                            {
                                fctrl[0] += (int)FctrlEnum.FpendingOrClassB;
                            }
                            if (macbytes != null && linkCheckCmdResponse != null)
                            {
                                macbytes = macbytes.Concat(linkCheckCmdResponse).ToArray();
                            }
                            LoRaPayloadData ackLoRaMessage = new LoRaPayloadData(
                                requestForConfirmedResponse ? MType.ConfirmedDataDown : MType.UnconfirmedDataDown,
                                //ConversionHelper.StringToByteArray(requestForConfirmedResponse?"A0":"60"),
                                devAddrCorrect,
                                fctrl,
                                BitConverter.GetBytes(loraDeviceInfo.FCntDown),
                                macbytes,
                                fport,
                                bytesC2dMsg,
                                1);

                            ackLoRaMessage.PerformEncryption(loraDeviceInfo.AppSKey);
                            ackLoRaMessage.SetMic(loraDeviceInfo.NwkSKey);


                            //todo ronnie should check the device twin preference if using confirmed or unconfirmed down
                            LoRaMessageWrapper ackMessage = new LoRaMessageWrapper(ackLoRaMessage, LoRaMessageType.UnconfirmedDataDown, rndToken, datr, 0, freq, tmst);
                            udpMsgForPktForwarder = ackMessage.PhysicalPayload.GetMessage();

                            linkCheckCmdResponse = null;
                            //confirm the message to iot hub only if we are in time for a delivery
                            if (c2dMsg != null)
                            {
                                //todo ronnie check if it is ok to do async so we make it in time to send the message
                                _ = loraDeviceInfo.HubSender.CompleteAsync(c2dMsg);
                                //bool rit = await loraDeviceInfo.HubSender.CompleteAsync(c2dMsg);
                                //if (rit)
                                //    Logger.Log(loraDeviceInfo.DevEUI, $"completed the c2d msg to IoT Hub", Logger.LoggingLevel.Info);
                                //else
                                //{
                                //    //we could not complete the msg so we send only a pushAck
                                //    PhysicalPayload pushAck = new PhysicalPayload(loraMessage.PhysicalPayload.token, PhysicalIdentifier.PUSH_ACK, null);
                                //    udpMsgForPktForwarder = pushAck.GetMessage();
                                //    Logger.Log(loraDeviceInfo.DevEUI, $"could not complete the c2d msg to IoT Hub", Logger.LoggingLevel.Info);

                                //}
                            }
                        }
                        else
                        {
                            //put back the c2d message to the queue for the next round
                            //todo ronnie check abbandon logic especially in case of mqtt
                            if (c2dMsg != null)
                            {
                                _ = await loraDeviceInfo.HubSender.AbandonAsync(c2dMsg);
                            }

                            Logger.Log(loraDeviceInfo.DevEUI, $"too late for down message, sending only ACK to gateway", Logger.LoggingLevel.Info);
                            _ = loraDeviceInfo.HubSender.UpdateFcntAsync(loraDeviceInfo.FCntUp, null);
                        }
                    }
                    //No ack requested and no c2d message we send the udp ack only to the gateway
                    else if (loraMessage.LoRaMessageType == LoRaMessageType.UnconfirmedDataUp && c2dMsg == null)
                    {
                        ////if ABP and 1 we reset the counter (loose frame counter) with force, if not we update normally
                        //if (fcntup == 1 && String.IsNullOrEmpty(loraDeviceInfo.AppEUI))
                        //    _ = loraDeviceInfo.HubSender.UpdateFcntAsync(fcntup, null, true);
                        if (validFrameCounter)
                        {
                            _ = loraDeviceInfo.HubSender.UpdateFcntAsync(loraDeviceInfo.FCntUp, null);
                        }
                    }

                    //If there is a link check command waiting
                    if (linkCheckCmdResponse != null)
                    {
                        Byte[] devAddrCorrect = new byte[4];
                        Array.Copy(loraMessage.LoRaPayloadMessage.DevAddr.ToArray(), devAddrCorrect, 4);
                        byte[] fctrl2 = new byte[1] {
                            0
                        };

                        Array.Reverse(devAddrCorrect);
                        LoRaPayloadData macReply = new LoRaPayloadData(MType.ConfirmedDataDown,
                                                                       devAddrCorrect,
                                                                       fctrl2,
                                                                       BitConverter.GetBytes(loraDeviceInfo.FCntDown),
                                                                       null,
                                                                       new byte[1] {
                            0
                        },
                                                                       linkCheckCmdResponse,
                                                                       1);

                        macReply.PerformEncryption(loraDeviceInfo.AppSKey);
                        macReply.SetMic(loraDeviceInfo.NwkSKey);

                        byte[] rndToken = new byte[2];
                        Random rnd      = new Random();
                        rnd.NextBytes(rndToken);

                        var datr = RegionFactory.CurrentRegion.GetDownstreamDR(loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0]);
                        //todo should discuss about the logic in case of multi channel gateway.
                        uint   rfch = loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0].rfch;
                        double freq = RegionFactory.CurrentRegion.GetDownstreamChannel(loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0]);
                        long   tmst = loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0].tmst + RegionFactory.CurrentRegion.receive_delay1 * 1000000;
                        //todo ronnie should check the device twin preference if using confirmed or unconfirmed down
                        LoRaMessageWrapper ackMessage = new LoRaMessageWrapper(macReply, LoRaMessageType.UnconfirmedDataDown, rndToken, datr, 0, freq, tmst);
                        udpMsgForPktForwarder = ackMessage.PhysicalPayload.GetMessage();
                    }
                }
                else
                {
                    Logger.Log(loraDeviceInfo.DevEUI, $"ignore message because is not linked to this GatewayID", Logger.LoggingLevel.Info);
                }
            }
            else
            {
                Logger.Log(devAddr, $"device is not our device, ignore message", Logger.LoggingLevel.Info);
            }



            Logger.Log(loraDeviceInfo?.DevEUI ?? devAddr, $"processing time: {DateTime.UtcNow - startTimeProcessing}", Logger.LoggingLevel.Info);

            return(udpMsgForPktForwarder);
        }
예제 #24
0
        public void TestMultipleRxpks()
        {
            // create multiple Rxpk message
            string jsonUplink     = @"{""rxpk"":[
	{
		            ""time"":""2013-03-31T16:21:17.528002Z"",
                    ""tmst"":3512348611,
                    ""chan"":2,
                    ""rfch"":0,
                    ""freq"":866.349812,
                    ""stat"":1,
                    ""modu"":""LORA"",
                    ""datr"":""SF7BW125"",
                    ""codr"":""4/6"",
                    ""rssi"":-35,
                    ""lsnr"":5.1,
                    ""size"":32,
                    ""data"":""AAQDAgEEAwIBBQQDAgUEAwItEGqZDhI=""
                }, {
               ""time"":""2013-03-31T16:21:17.528002Z"",
                ""tmst"":3512348611,
                ""chan"":2,
                ""rfch"":0,
                ""freq"":866.349812,
                ""stat"":1,
                ""modu"":""LORA"",
                ""datr"":""SF7BW125"",
                ""codr"":""4/6"",
                ""rssi"":-35,
                ""lsnr"":5.1,
                ""size"":32,
                ""data"":""QAQDAgGAAQABppRkJhXWw7WC""
                 },{
		            ""time"":""2013-03-31T16:21:17.528002Z"",
                    ""tmst"":3512348611,
                    ""chan"":2,
                    ""rfch"":0,
                    ""freq"":866.349812,
                    ""stat"":1,
                    ""modu"":""LORA"",
                    ""datr"":""SF7BW125"",
                    ""codr"":""4/6"",
                    ""rssi"":-35,
                    ""lsnr"":5.1,
                    ""size"":32,
                    ""data"":""AAQDAgEEAwIBBQQDAgUEAwItEGqZDhI=""
                }
]}";
            var    multiRxpkInput = Encoding.Default.GetBytes(jsonUplink);

            byte[] physicalUpstreamPyld = new byte[12];
            physicalUpstreamPyld[0] = 2;
            List <Rxpk> rxpk = Rxpk.CreateRxpk(physicalUpstreamPyld.Concat(multiRxpkInput).ToArray());

            Assert.Equal(3, rxpk.Count);
            TestRxpk(rxpk[0]);
            TestRxpk(rxpk[2]);

            Assert.True(LoRaPayload.TryCreateLoRaPayload(rxpk[1], out LoRaPayload jsonUplinkUnconfirmedMessage));
            Assert.Equal(LoRaMessageType.UnconfirmedDataUp, jsonUplinkUnconfirmedMessage.LoRaMessageType);

            LoRaPayloadData loRaPayloadUplinkObj = (LoRaPayloadData)jsonUplinkUnconfirmedMessage;

            Assert.True(loRaPayloadUplinkObj.Fcnt.Span.SequenceEqual(new byte[2] {
                1, 0
            }));

            Assert.True(loRaPayloadUplinkObj.DevAddr.Span.SequenceEqual(new byte[4] {
                1, 2, 3, 4
            }));
            byte[] loRaPayloadUplinkNwkKey = new byte[16] {
                2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
            };

            Assert.True(loRaPayloadUplinkObj.CheckMic(ConversionHelper.ByteArrayToString(loRaPayloadUplinkNwkKey)));

            byte[] loRaPayloadUplinkAppKey = new byte[16] {
                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
            };
            var key = ConversionHelper.ByteArrayToString(loRaPayloadUplinkAppKey);

            Assert.Equal("hello", Encoding.ASCII.GetString(loRaPayloadUplinkObj.PerformEncryption(key)));
        }
예제 #25
0
        private bool PushTransferProgressHandler(int current, int total, long bytes)
        {
            if (total > 0)
            {
                double progressPercentage = current / (double)total;
                _logger.LogDebug($"Push progress {progressPercentage:P2} : {current}/{total} ({ConversionHelper.FormatBytes(bytes)})");
            }

            return(true);
        }
        public override async Task <EkKioskProductSearchByVinCodeGetResponse> ExecuteAsync(EkKioskProductSearchByVinCodeGetRequest request)
        {
            if (string.IsNullOrEmpty(request.VinCode) ||
                request.VinCode.Length < 8)
            {
                // invalid vin-code
                return(GetEmptyResponse());
            }

            // cancellation token
            var cancellationToken = _httpContextAccessor.HttpContext?.RequestAborted ?? CancellationToken.None;

            // todo: add cancellationToken support to proxy based clients

            var records = await _tecDocWsClient.SearchByVinAsync(request.VinCode);

            if (records.Length == 0)
            {
                // no results by passed vin-code
                return(GetEmptyResponse());
            }

            var modelTypes = await _tecDocWsClient.GetModelTypesAsync(
                records
                .Select(x => x.CarId)
                .ToArray());

            if (modelTypes.Length == 0)
            {
                // no results by passed vin-code
                return(GetEmptyResponse());
            }

            var modifications = modelTypes
                                .Where(x => x.VehicleDetails != null)
                                .Select(x =>
            {
                var modificationName = $"{x.VehicleDetails.ManuName} {x.VehicleDetails.ModelName} {x.VehicleDetails.TypeName}";
                var bodyType         = x.VehicleDetails.ConstructionType;
                var engineType       = x.VehicleDetails.MotorType;
                var engineCode       = x.GetMotorCodesString();
                var capacityCcm      = x.VehicleDetails.CylinderCapacityCcm;
                var engineCapacity   = capacityCcm == null
                            ? null
                            : $"{capacityCcm} ccm";
                var driveType = x.VehicleDetails.ImpulsionType;
                return(new EkCarModelModification()
                {
                    Id = x.CarId,
                    ModelId = x.VehicleDetails.ModId,
                    Name = new MultiLanguageString()
                    {
                        [Languages.RussianCode] = modificationName,
                    },
                    BodyType = new MultiLanguageString()
                    {
                        [Languages.RussianCode] = bodyType,
                    },
                    EngineType = new MultiLanguageString()
                    {
                        [Languages.RussianCode] = engineType,
                    },
                    EngineCode = engineCode,
                    EngineCapacity = engineCapacity,
                    DriveType = new MultiLanguageString()
                    {
                        [Languages.RussianCode] = driveType,
                    },
                    ProducedFrom = ConversionHelper.ConvertStringToYearMonth(x.VehicleDetails.YearOfConstrFrom),
                    ProducedTo = ConversionHelper.ConvertStringToYearMonth(x.VehicleDetails.YearOfConstrTo),
                });
            })
                                .ToArray();

            return(new EkKioskProductSearchByVinCodeGetResponse()
            {
                ModelModifications = modifications,
            });
        }
        public async Task When_Device_Prefers_Second_Window_Should_Send_Downstream_In_Second_Window()
        {
            const int PayloadFcnt           = 10;
            const int InitialDeviceFcntUp   = 9;
            const int InitialDeviceFcntDown = 20;

            var simulatedDevice = new SimulatedDevice(
                TestDeviceInfo.CreateABPDevice(1, gatewayID: this.ServerConfiguration.GatewayID),
                frmCntUp: InitialDeviceFcntUp,
                frmCntDown: InitialDeviceFcntDown);

            var devAddr = simulatedDevice.DevAddr;
            var devEUI  = simulatedDevice.DevEUI;

            var loraDeviceClient = new Mock <ILoRaDeviceClient>(MockBehavior.Strict);

            // Will get twin to initialize LoRaDevice
            var deviceTwin = TestUtils.CreateABPTwin(
                simulatedDevice,
                desiredProperties: new Dictionary <string, object>
            {
                { TwinProperty.PreferredWindow, 2 }
            });

            loraDeviceClient.Setup(x => x.GetTwinAsync()).ReturnsAsync(deviceTwin);

            loraDeviceClient.Setup(x => x.SendEventAsync(It.IsNotNull <LoRaDeviceTelemetry>(), null))
            .ReturnsAsync(true);

            loraDeviceClient.Setup(x => x.UpdateReportedPropertiesAsync(It.IsNotNull <TwinCollection>()))
            .ReturnsAsync(true);

            var cloudToDeviceMessage = new Message(Encoding.UTF8.GetBytes("c2d"));

            cloudToDeviceMessage.Properties[MessageProcessor.FPORT_MSG_PROPERTY_KEY] = "1";
            loraDeviceClient.SetupSequence(x => x.ReceiveAsync(It.IsAny <TimeSpan>()))
            .ReturnsAsync(cloudToDeviceMessage)
            .Returns(this.EmptyAdditionalMessageReceiveAsync);     // 2nd cloud to device message does not return anything

            loraDeviceClient.Setup(x => x.CompleteAsync(cloudToDeviceMessage))
            .ReturnsAsync(true);

            var payloadDecoder = new Mock <ILoRaPayloadDecoder>();

            var loRaDeviceAPI = new Mock <LoRaDeviceAPIServiceBase>();

            loRaDeviceAPI.Setup(x => x.SearchByDevAddrAsync(devAddr))
            .ReturnsAsync(new SearchDevicesResult(new IoTHubDeviceInfo(devAddr, devEUI, "adad").AsList()));

            var loRaDeviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, new MemoryCache(new MemoryCacheOptions()), loRaDeviceAPI.Object, new TestLoRaDeviceFactory(loraDeviceClient.Object));

            // Send to message processor
            var messageProcessor = new MessageProcessor(
                this.ServerConfiguration,
                loRaDeviceRegistry,
                new LoRaDeviceFrameCounterUpdateStrategyFactory(this.ServerConfiguration.GatewayID, loRaDeviceAPI.Object),
                new LoRaPayloadDecoder());

            var payload = simulatedDevice.CreateUnconfirmedDataUpMessage("1234", fcnt: PayloadFcnt);
            var rxpk    = payload.SerializeUplink(simulatedDevice.AppSKey, simulatedDevice.NwkSKey).Rxpk[0];
            var actual  = await messageProcessor.ProcessMessageAsync(rxpk);

            // Expectations
            // 1. Message was sent to IoT Hub
            loraDeviceClient.VerifyAll();

            // 2. Single gateway frame counter strategy was used
            this.FrameCounterUpdateStrategyFactory.VerifyAll();

            // 3. Return is downstream message
            Assert.NotNull(actual);
            Assert.IsType <DownlinkPktFwdMessage>(actual);
            var downlinkMessage = (DownlinkPktFwdMessage)actual;
            var euRegion        = RegionFactory.CreateEU868Region();

            // Ensure we are using second window frequency
            Assert.Equal(euRegion.RX2DefaultReceiveWindows.frequency, actual.Txpk.Freq);

            // Ensure we are using second window datr
            Assert.Equal(euRegion.DRtoConfiguration[euRegion.RX2DefaultReceiveWindows.dr].configuration, actual.Txpk.Datr);

            // Ensure tmst was computed to 2 seconds (2 windows in Europe)
            Assert.Equal(2000000, actual.Txpk.Tmst);

            // Get the device from registry
            var deviceDictionary = loRaDeviceRegistry.InternalGetCachedDevicesForDevAddr(devAddr);

            Assert.True(deviceDictionary.TryGetValue(simulatedDevice.DevEUI, out var loRaDevice));
            var payloadDataDown = new LoRaPayloadData(Convert.FromBase64String(downlinkMessage.Txpk.Data));

            payloadDataDown.PerformEncryption(loRaDevice.AppSKey);
            Assert.Equal(payloadDataDown.DevAddr.ToArray(), ConversionHelper.StringToByteArray(loRaDevice.DevAddr));
            Assert.False(payloadDataDown.IsConfirmed());
            Assert.Equal(LoRaMessageType.UnconfirmedDataDown, payloadDataDown.LoRaMessageType);

            // 4. Frame counter up was updated
            Assert.Equal(PayloadFcnt, loRaDevice.FCntUp);

            // 5. Frame counter down is updated
            var expectedFcntDown = InitialDeviceFcntDown + 10 + 1; // adding 10 as buffer when creating a new device instance

            Assert.Equal(expectedFcntDown, loRaDevice.FCntDown);
            Assert.Equal(expectedFcntDown, payloadDataDown.GetFcnt());

            // 6. Frame count has no pending changes
            Assert.False(loRaDevice.HasFrameCountChanges);
        }
예제 #28
0
        public async Task <IEnumerable <DIBZ.Common.DTO.Swap> > GetAllSwaps()
        {
            //declarations

            try
            {
                List <DIBZ.Common.Model.Swap> tempSwapList   = new List <DIBZ.Common.Model.Swap>();
                List <DIBZ.Common.DTO.Swap>   swapListToShow = new List <DIBZ.Common.DTO.Swap>();
                DIBZ.Common.Model.Swap        swap           = new DIBZ.Common.Model.Swap();

                // 5 day rule check and its impact --- starts
                // DIBZ SRS for phase 2 version 1.5
                //5 day rule starts after both parties have paid.

                var swapListExpiryRule = await Db.Query <DIBZ.Common.Model.Swap>(o => o.IsActive == true && !o.IsDeleted).QueryAsync();

                //AllSwapsRecord Group by with OfferID and get list decrease order
                var groupbyOfferIDsExpiryRule = swapListExpiryRule.OrderByDescending(d => d.Id).GroupBy(g => g.OfferId);

                List <DIBZ.Common.Model.Swap> tempSwapListExpiryRule = new List <DIBZ.Common.Model.Swap>();
                //now for loop to get latest swap status
                foreach (var item in groupbyOfferIDsExpiryRule)
                {
                    //to get latest swap status
                    var tempdata = item.First();
                    swap = (DIBZ.Common.Model.Swap)tempdata;
                    tempSwapListExpiryRule.Add(swap);
                }

                foreach (var tempSwap in tempSwapListExpiryRule)
                {
                    var scorecardLogic = LogicContext.Create <ScorecardLogic>();

                    // ************ 5 day rule starts after both parties have paid. **************

                    var getWorkingDaysCount = GetWorkingDaysCount(ConversionHelper.ConvertDateToTimeZone(tempSwap.CreatedTime));
                    LogHelper.LogInfo("getWorkingDaysCount: " + getWorkingDaysCount);

                    //Condition when both party hasn't sent game on time.
                    if (tempSwap.Offer.OfferStatus == OfferStatus.Accept &&
                        tempSwap.Offer.Transactions.Count() == 2 &&
                        (tempSwap.SwapStatus == SwapStatus.Payment_Done_By_Offerer || tempSwap.SwapStatus == SwapStatus.Payment_Done_By_Swapper) &&
                        getWorkingDaysCount > SystemSettings.DayRule)
                    {
                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(tempSwap.GameSwapPsersonId);

                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(tempSwap.Offer.ApplicationUserId);

                        await this.UpdateOfferStatusToPendingAndSetSwapToInActiveAndRemoveTransactionIfAny(tempSwap.OfferId, tempSwap.Id);
                    }

                    //Condition when offerer party hasn't sent game on time.
                    if (tempSwap.Offer.OfferStatus == OfferStatus.Accept &&
                        tempSwap.Offer.Transactions.Count() == 2 &&
                        (tempSwap.SwapStatus != SwapStatus.Payment_Done_By_Offerer || tempSwap.SwapStatus != SwapStatus.Payment_Done_By_Swapper && tempSwap.SwapStatus == SwapStatus.Game2_Received) &&
                        getWorkingDaysCount > SystemSettings.DayRule)
                    {
                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(tempSwap.Offer.ApplicationUserId);
                        await UpdateOfferStatusToPendingAndSetSwapToInActiveAndRemoveTransactionIfAny(tempSwap.OfferId, tempSwap.Id);
                    }
                    //Condition when swapper party hasn't sent game on time.
                    if (tempSwap.Offer.OfferStatus == OfferStatus.Accept &&
                        tempSwap.Offer.Transactions.Count() == 2 &&
                        (tempSwap.SwapStatus != SwapStatus.Payment_Done_By_Offerer || tempSwap.SwapStatus != SwapStatus.Payment_Done_By_Swapper && tempSwap.SwapStatus == SwapStatus.Game1_Received) &&
                        getWorkingDaysCount > SystemSettings.DayRule)
                    {
                        await scorecardLogic.UpdateScoreCardOfApplicationUserWithNoShow(tempSwap.GameSwapPsersonId);
                        await UpdateOfferStatusToPendingAndSetSwapToInActiveAndRemoveTransactionIfAny(tempSwap.OfferId, tempSwap.Id);
                    }
                }
                // 5 day rule check and its impact --- ends

                var swapList = await Db.Query <DIBZ.Common.Model.Swap>(o => !o.IsDeleted).QueryAsync();

                //AllSwapsRecord Group by with OfferID and get list decrease order
                var groupbyOfferIDs = swapList.OrderByDescending(d => d.Id).GroupBy(g => g.OfferId);

                //now for loop to get latest swap status
                foreach (var item in groupbyOfferIDs)
                {
                    //to get latest swap status
                    var tempdata = item.First();
                    swap = (DIBZ.Common.Model.Swap)tempdata;
                    tempSwapList.Add(swap);
                }
                foreach (var tempSwap in tempSwapList)
                {
                    DIBZ.Common.DTO.Swap swapModel = new DIBZ.Common.DTO.Swap();

                    if (tempSwap.IsActive)
                    {
                        if (tempSwap.SwapStatus == DIBZ.Common.Model.SwapStatus.Game2_Received)
                        {
                            var result = swapList.Where(d => d.OfferId == tempSwap.OfferId).Any(r => r.SwapStatus == DIBZ.Common.Model.SwapStatus.Game1_Received);
                            if (result)
                            {
                                //this assignment is for ,which button to show
                                swapModel.SwapButtonToShow = DIBZ.Common.Model.SwapStatus.Testing;
                            }
                            else
                            {
                                swapModel.SwapButtonToShow = DIBZ.Common.Model.SwapStatus.Game1_Received;
                            }
                        }
                        else if (tempSwap.SwapStatus == DIBZ.Common.Model.SwapStatus.Game1_Received)
                        {
                            var result = swapList.Where(d => d.OfferId == tempSwap.OfferId).Any(r => r.SwapStatus == DIBZ.Common.Model.SwapStatus.Game2_Received);
                            if (result)
                            {
                                swapModel.SwapButtonToShow = DIBZ.Common.Model.SwapStatus.Testing;
                            }
                            else
                            {
                                swapModel.SwapButtonToShow = DIBZ.Common.Model.SwapStatus.Game2_Received;
                            }
                        }
                        if (tempSwap.SwapStatus == DIBZ.Common.Model.SwapStatus.Game2_NoShow)
                        {
                            var result = swapList.Where(d => d.OfferId == tempSwap.OfferId).Any(r => r.SwapStatus == DIBZ.Common.Model.SwapStatus.Game1_NoShow);
                            if (result)
                            {
                                //this assignment is for ,which button to show
                                swapModel.SwapButtonToShow = DIBZ.Common.Model.SwapStatus.Returned;
                            }
                            else
                            {
                                swapModel.SwapButtonToShow = DIBZ.Common.Model.SwapStatus.Game1_NoShow;
                            }
                        }
                        else if (tempSwap.SwapStatus == DIBZ.Common.Model.SwapStatus.Game1_NoShow)
                        {
                            var result = swapList.Where(d => d.OfferId == tempSwap.OfferId).Any(r => r.SwapStatus == DIBZ.Common.Model.SwapStatus.Game2_NoShow);
                            if (result)
                            {
                                swapModel.SwapButtonToShow = DIBZ.Common.Model.SwapStatus.Returned;
                            }
                            else
                            {
                                swapModel.SwapButtonToShow = DIBZ.Common.Model.SwapStatus.Game2_NoShow;
                            }
                        }
                        swapModel.Id                 = tempSwap.Id;
                        swapModel.CreatedTime        = tempSwap.CreatedTime;
                        swapModel.OfferedGameImageId = tempSwap.Offer.GameCatalog.GameImageId;
                        swapModel.SwapGameImageId    = tempSwap.GameSwapWith.GameImageId;

                        swapModel.GameSwapPersonNickName = tempSwap.GameSwapPserson.NickName;
                        swapModel.OfferPersonNickName    = tempSwap.Offer.ApplicationUser.NickName;
                        swapModel.GameSwapWithId         = tempSwap.GameSwapWithId;
                        swapModel.GameSwapPersonId       = tempSwap.GameSwapPsersonId;
                        swapModel.OfferPersonId          = tempSwap.Offer.ApplicationUserId;
                        swapModel.SwapStatus             = (tempSwap.Offer.Transactions.Count == 2 && (tempSwap.SwapStatus == SwapStatus.Payment_Done_By_Offerer || tempSwap.SwapStatus == SwapStatus.Payment_Done_By_Swapper)) ? SwapStatus.Payment_Successful : tempSwap.SwapStatus;
                        swapModel.OfferId         = tempSwap.OfferId;
                        swapModel.GameOffererDFOM = tempSwap.Offer.GameOffererDFOM;
                        swapModel.GameSwapperDFOM = tempSwap.Offer.GameSwapperDFOM;
                        swapModel.OfferStatus     = tempSwap.Offer.OfferStatus;
                        swapListToShow.Add(swapModel);
                    }
                }
                return(swapListToShow);
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex.Message, ex);
            }
            return(null);
        }
 protected override string ToAt(int sequenceNumber)
 {
     return(string.Format("AT*PCMD_MAG={0},{1},{2},{3},{4},{5},{6},{7}\r", sequenceNumber, (int)_mode, ConversionHelper.ToInt(_roll), ConversionHelper.ToInt(_pitch), ConversionHelper.ToInt(_gaz), ConversionHelper.ToInt(_yaw), ConversionHelper.ToInt(_psi), ConversionHelper.ToInt(_accuracy)));
 }
예제 #30
0
 public DataBlockDataItem() : this(ConverterFactory.GetToPlcConverter <TValue>(),
                                   ConverterFactory.GetFromPlcConverter <TValue>(), ConversionHelper.GetElementSize <TValue>())
 {
     if (typeof(TValue) == typeof(bool))
     {
         variableType  = VariableType.Bit;
         transportSize = TransportSize.Bit;
     }
     else
     {
         variableType  = VariableType.Byte;
         transportSize = TransportSize.Byte;
     }
 }
 public MethodPerformanceAdvisor()
 {
     GlimpsePerformanceConfiguration = new GlimpsePerformanceConfiguration();
     ConversionHelper = new ConversionHelper();
     StorageFactory = new StorageFactory();
 }