public void OnDeserialization(byte[] bytes, SerializerSession settings)
 {
     this.FromDateTime = DateTimeExtension.GetDateTime(FromRtc, settings.PumpTime.OffSet);
     //255*4 is now, I think..... need to handle this....
     this.ToDateTime = DateTimeExtension.GetDateTime(ToRtc, settings.PumpTime.OffSet);
     settings.PumpDataHistory.CurrentMultiPacketHandler.WaitingForSegment = false;
 }
Example #2
0
 public void OnDeserialization(byte[] bytes, SerializerSession settings)
 {
     this.AllBytes      = bytes;
     this.AllBytesE     = bytes.Reverse().ToArray();
     this.BytesAsString = BitConverter.ToString(AllBytes);
     if (this.Message != null && this.Message.GetType().Equals(typeof(SENSOR_GLUCOSE_READINGS_EXTENDED_Event)))
     {
         try
         {
             var reading = (SENSOR_GLUCOSE_READINGS_EXTENDED_Event)this.Message;
             for (int i = 0; i < reading.Details.Count; i++)
             {
                 if (reading.Timestamp.HasValue)
                 {
                     var read       = reading.Details[i];
                     var readingRtc = this.Rtc - (i * reading.MinutesBetweenReadings * 60);
                     read.Timestamp   = DateTimeExtension.GetDateTime(readingRtc, this.Offset);
                     read.PredictedSg = reading.PredictedSg;
                 }
             }
         }
         catch (Exception)
         {
             throw;
         }
     }
 }
Example #3
0
 public DateTime?GetDateTime(byte[] Rtc)
 {
     if (Rtc != null && this.OffSet != null)
     {
         return(DateTimeExtension.GetDateTime(Rtc, this.OffSet));
     }
     return(null);
 }
Example #4
0
        private T DeserializeInternal <T>(byte[] bytes) where T : class, new()
        {
            _byteLevels.Add(bytes);
            T   byteClass = new T();
            var classtype = (BinaryType)typeof(T).GetTypeInfo().GetCustomAttribute(typeof(BinaryType));

            if (classtype != null)
            {
                if (classtype.IsEncrypted)
                {
                    if (_session.EncryptKey == null || _session.EncryptIV == null)
                    {
                        throw new Exception("Missing encryptKey/IV in serializationsettings.");
                    }
                    bytes = bytes.Decrypt(_session.EncryptKey, _session.EncryptIV);
                }


                var bytelist = new List <byte>(bytes);
                SerializeInfo <T> serInfo = new SerializeInfo <T>(bytes);

                for (int i = 0; i < serInfo.InfoElementOrderedList.Count; i++)
                {
                    var current = serInfo.InfoElementOrderedList[i];

                    int start = current.Element.FieldOffset;
                    if (start < bytes.Length)
                    {
                        var property = current.Info;
                        int length   = 0;
                        if (current.Element.Length != -1)
                        {
                            length = current.Element.Length;
                        }
                        else
                        {
                            if (i + 1 != serInfo.InfoElementOrderedList.Count)
                            {
                                length = serInfo.InfoElementOrderedList[i + 1].Element.FieldOffset - start;
                            }
                            else
                            {
                                length = bytes.Length - start;
                            }
                            //todo: last one
                            if (bytes.Length < (start + length))
                            {
                                length = bytes.Length - start;
                            }
                        }

                        var value = bytelist.GetRange(start, length);



                        object setvalue = null;

                        bool IsLittleEndian = BitConverter.IsLittleEndian;
                        IsLittleEndian = classtype.IsLittleEndian;

                        List <byte> EndianValue = new List <byte>();
                        if (IsLittleEndian)
                        {
                            EndianValue = value;
                        }
                        else
                        {
                            EndianValue = value.ToArray().Reverse().ToList();
                        }


                        if (value != null)
                        {
                            if (property.PropertyType == typeof(byte))
                            {
                                setvalue = EndianValue[0];
                            }

                            if (property.PropertyType == typeof(byte[]))
                            {
                                //do nothing
                                setvalue = EndianValue.ToArray();
                            }

                            if (property.PropertyType == typeof(string))
                            {
                                setvalue = Encoding.ASCII.GetString(EndianValue.ToArray());
                            }

                            if (property.PropertyType == typeof(Int16))
                            {
                                setvalue = EndianValue.ToArray().GetInt16(0);
                            }
                            if (property.PropertyType == typeof(UInt16))
                            {
                                setvalue = EndianValue.ToArray().GetUInt16(0);
                            }

                            if (property.PropertyType == typeof(Int32))
                            {
                                setvalue = EndianValue.ToArray().GetInt32(0);
                            }
                            if (property.PropertyType == typeof(UInt32))
                            {
                                setvalue = EndianValue.ToArray().GetUInt32(0);
                            }

                            if (property.PropertyType == typeof(Int64))
                            {
                                setvalue = EndianValue.ToArray().GetInt64(0);
                            }



                            if (property.PropertyType == typeof(DateTime))
                            {
                                if (IsLittleEndian)
                                {
                                    var startIndex = 0;
                                    var rtc        = bytes.GetInt32(startIndex);
                                    var offset     = bytes.GetInt32(startIndex + 4);

                                    setvalue = DateTimeExtension.GetDateTime(rtc, offset);
                                }
                                else
                                {
                                    var startIndex = 0;
                                    var rtc        = bytes.GetInt32BigE(startIndex);
                                    var offset     = bytes.GetInt32BigE(startIndex + 4);

                                    setvalue = DateTimeExtension.GetDateTime(rtc, offset);
                                }
                            }

                            if (property.PropertyType.GetTypeInfo().IsGenericType&& property.PropertyType.GetGenericTypeDefinition() == typeof(List <>))
                            {
                                var binaryElementLists = (IEnumerable <BinaryElementList>)property.GetCustomAttributes(typeof(BinaryElementList));
                                if (binaryElementLists.Count() > 0)
                                {
                                    BinaryElementList list = binaryElementLists.First();
                                    //var listElement=Activator.CreateInstance(list.Type);
                                    var  listvalue = (IList)property.GetValue(byteClass);
                                    byte listCount = (byte)serInfo.InfoElements[list.CountProperty].Info.GetValue(byteClass);

                                    int listlength = listCount * list.ByteSize;

                                    //var listbytes = value.ToList().GetRange(current.Element.FieldOffset, listlength).ToList();

                                    var           listbytes  = value;
                                    List <Byte[]> splitBytes = new List <byte[]>();
                                    for (int j = 0; j < listCount; j++)
                                    {
                                        int startindex = j * list.ByteSize;

                                        var serByte = value.ToList().GetRange(startindex, list.ByteSize);

                                        var serializerMethodes = typeof(CGM.Communication.Common.Serialize.Serializer).GetRuntimeMethods();
                                        var generic0           = serializerMethodes.FirstOrDefault(e => e.Name == "DeserializeInternal");
                                        var generic            = generic0.MakeGenericMethod(list.Type);
                                        var elementValue       = generic.Invoke(this, new object[] { serByte.ToArray() });
                                        listvalue.Add(elementValue);
                                    }


                                    setvalue = listvalue;
                                }
                            }

                            var attributes = (IEnumerable <MessageType>)property.GetCustomAttributes(typeof(MessageType));

                            bool containssubtype = property.PropertyType.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IBinaryType));
                            if (containssubtype || attributes.Count() > 0)
                            {
                                Type SeriType     = null;
                                int  lengthEquals = 0;
                                if (containssubtype)
                                {
                                    SeriType = property.PropertyType;
                                }



                                if (attributes != null && attributes.Count() > 0)
                                {
                                    foreach (var item in attributes)
                                    {
                                        lengthEquals = item.LengthEquals;
                                        if (!string.IsNullOrEmpty(item.Path))
                                        {
                                            var prop = serInfo.InfoElements.FirstOrDefault(e => e.Value.Info.Name == item.Path);

                                            if (item.Value is IEnumerable <byte> )
                                            {
                                                var newValue        = (IEnumerable <byte>)item.Value;
                                                var validationValue = bytes.ToList().GetRange(prop.Value.Element.FieldOffset, newValue.Count());
                                                if (validationValue.SequenceEqual(newValue))
                                                {
                                                    SeriType = item.Type;
                                                    break;
                                                }
                                            }
                                            else
                                            {
                                                var propinfo        = serInfo.PropertyInfos.FirstOrDefault(e => e.Name == item.Path);
                                                var validationValue = propinfo.GetValue(byteClass);
                                                if (validationValue.Equals(item.Value))
                                                {
                                                    SeriType = item.Type;
                                                    break;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (item.ReportPattern != null)
                                            {
                                                if (item.ReportPattern.Evaluate(_byteLevels[0]))
                                                {
                                                    SeriType = item.Type;
                                                    break;
                                                }
                                            }
                                            else
                                            {
                                                SeriType = item.Type;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (SeriType != null)
                                {
                                    //if (lengthEquals != 0 && lengthEquals != value.Count)
                                    //{
                                    //    throw new Exception($"Expected length {lengthEquals}. Is {value.Count}");
                                    //}
                                    var serializerMethodes = typeof(CGM.Communication.Common.Serialize.Serializer).GetRuntimeMethods();
                                    var generic0           = serializerMethodes.FirstOrDefault(e => e.Name == "DeserializeInternal");
                                    var generic            = generic0.MakeGenericMethod(SeriType);
                                    setvalue = generic.Invoke(this, new object[] { value.ToArray() });
                                    var ctors = (IEnumerable <BinaryPropertyValueTransfer>)property.GetCustomAttributes(typeof(BinaryPropertyValueTransfer));
                                    if (ctors.Count() > 0)
                                    {
                                        foreach (var item in ctors)
                                        {
                                            var propinfo    = serInfo.PropertyInfos.FirstOrDefault(e => e.Name == item.ParentPropertyName);
                                            var parentvalue = propinfo.GetValue(byteClass);

                                            setvalue.GetType().GetProperty(item.ChildPropertyName).SetValue(setvalue, parentvalue);
                                        }
                                    }
                                }
                            }



                            // bool containssubtype = property.PropertyType.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IBinaryType));



                            property.SetValue(byteClass, setvalue);
                        }
                    }
                }
                if (typeof(T).GetTypeInfo().ImplementedInterfaces.Contains(typeof(IBinaryDeserializationSetting)))
                {
                    ((IBinaryDeserializationSetting)byteClass).OnDeserialization(bytes, _session);
                }
                return(byteClass);
            }


            return(null);
        }
Example #5
0
        private void MissingReadings(List <PumpEvent> allEvents)
        {
            var sensorReadings = allEvents.Where(e => e.EventType == MiniMed.Infrastructur.EventTypeEnum.SENSOR_GLUCOSE_READINGS_EXTENDED).ToList();

            if (sensorReadings.Count > 0)
            {
                List <SENSOR_GLUCOSE_READINGS_EXTENDED_Detail> details = new List <SENSOR_GLUCOSE_READINGS_EXTENDED_Detail>();

                foreach (var msg in sensorReadings)
                {
                    var reading = (SENSOR_GLUCOSE_READINGS_EXTENDED_Event)msg.Message;
                    //reading.Details.Reverse();
                    for (int i = 0; i < reading.Details.Count; i++)
                    {
                        if (reading.Timestamp.HasValue)
                        {
                            var read       = reading.Details[i];
                            var readingRtc = msg.Rtc - (i * reading.MinutesBetweenReadings * 60);
                            read.Timestamp = DateTimeExtension.GetDateTime(readingRtc, msg.Offset);// reading.Timestamp.Value.AddMinutes((i * reading.MinutesBetweenReadings*-1));
                            CreateEntrySgv(read.Amount, read.Timestamp.Value.ToString(dateformat), read.Epoch, read.Trend.ToString(), false, msg.Key);
                        }
                    }
                    allEvents.Remove(msg);
                }



                ////Get from nightscout
                //List<Entry> entries = new List<Entry>();
                //var from = orderedDetails.First().Timestamp.Value;
                //var to = orderedDetails.Last().Timestamp.Value;

                ////gt - from this data (include this date)
                ////lt - to this date (NOT including this date). So we add a day to the "to"-date from the reading
                //to = to.AddDays(1);
                //string findStr = $"find[dateString][$gt]={from.ToString("yyyy-MM-dd")}&find[dateString][$lt]={to.ToString("yyyy-MM-dd")}&find[type]=sgv";

                //var allTodayEntries = await _client.EntriesAsync(findStr, 0);


                //var query =
                //       from comp in orderedDetails
                //       join entry in allTodayEntries on comp.Epoch.ToString() equals entry.Key
                //       select comp;

                //var missingReadings = orderedDetails.Except(query.ToList()).ToList();



                //foreach (var reading in missingReadings.OrderBy(e => e.Timestamp))
                //{

                //    await CreateEntrySgv(reading.Amount, reading.Timestamp.Value.ToString(dateformat), reading.Epoch, reading.Trend.ToString(), false);
                //}


                //List<CompareEvents> compares = new List<CompareEvents>();

                //foreach (var pumpevent in sensorReadings)
                //{
                //    var firstdate = pumpevent.Timestamp.Value;
                //    var reading = (SENSOR_GLUCOSE_READINGS_EXTENDED_Event)pumpevent.Message;
                //    for (int i = 0; i < reading.Details.Count; i++)
                //    {
                //        //if (reading.Details[i].Amount <= 400)
                //        //{
                //        var readDateTime = firstdate.AddMinutes(i * -5);
                //        compares.Add(new CompareEvents(reading.Details[i], readDateTime));
                //        //}
                //    }
                //}



                //todo another query by dates would be better. a between query.... but nightscout restapi do not have this...or it does not work.
                //var numberOfDays = to.Value.Subtract(from.Value).Days;
                //List<Entry> entries = new List<Entry>();

                //for (int i = 0; i <= numberOfDays; i++)
                //{
                //    DateTime getdate = from.Value.AddDays(i);

                //    var allTodayEntries = await _client.EntriesAsync($"find[type]=sgv&find[dateString][$gte]={getdate.ToString("yyyy-MM-dd")}", 1000);
                //    entries.AddRange(allTodayEntries);
                //}


                //var allTodayEntries = await _client.EntriesAsync($"find[type]=sgv", 1000);
                //entries.AddRange(allTodayEntries);

                //var query =
                //   from comp in compares
                //   join entry in entries on comp.DateString equals entry.DateString
                //   select comp;

                //var missingReadings = compares.Except(query.ToList()).ToList();

                //if (missingReadings.Count>0)
                //{
                //    gotReadingFromEvent = true;
                //}
            }
        }