Exemple #1
0
        public string SubmitCreateMeterData(MeterData MeterData)
        {
            var                       User     = System.Web.HttpContext.Current.User.Identity.Name;
            FormsIdentity             id       = (FormsIdentity)HttpContext.Current.User.Identity;
            FormsAuthenticationTicket ticket   = id.Ticket;
            string                    userData = ticket.UserData;

            string[]  roles     = userData.Split(',');
            string    userRole  = roles[0];
            UserOpMap userOpMap = new UserOpMap();

            BAL.BAL_Common bAL_Common = new BAL.BAL_Common();
            userOpMap = bAL_Common.GetUserOperationMapping(HttpContext.Current.User.Identity.Name, userRole);

            EntitySubmittedResponse entitySubmittedResponse = new EntitySubmittedResponse();

            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            try
            {
                BAL.BAL_Meter bAL_Meter = new BAL.BAL_Meter();
                long          meterID   = bAL_Meter.CreateMeter(MeterData, userOpMap);
                entitySubmittedResponse.submited = true;
                entitySubmittedResponse.message  = "Meter Data Created Successfully!";
                return(js.Serialize("Meter Data Created Successfully"));
            }
            catch (Exception ex)
            {
                entitySubmittedResponse.submited = false;
                entitySubmittedResponse.message  = string.Format("Error occured while creating meter with message:{0}", ex.Message);
                return(js.Serialize(string.Format("Error occured while creating meter with message:{0}", ex.Message)));
            }
        }
Exemple #2
0
        private object ReadParameter(BitStream s, ParameterDefinition paramDefinition)
        {
            IParameter param = null;

            switch (paramDefinition.ParameterType)
            {
            case ParameterType.Float: { param = new FloatValue(); } break;

            case ParameterType.EntityFilter: { param = new EntityFilter(); } break;

            case ParameterType.GenericReference: { param = new GenericReference(); } break;

            case ParameterType.IntegerReference: { param = new IntegerReference(); } break;

            case ParameterType.Meter: { param = new MeterData(); } break;

            case ParameterType.ObjectReference: { param = new ObjectReference(); } break;

            case ParameterType.PlayerReference: { param = new PlayerReference(); } break;

            case ParameterType.Shape: { param = new BoundaryData(); } break;

            case ParameterType.StringReference: { param = new StringReference(); } break;

            case ParameterType.StringReferenceOneToken: { param = new StringReferenceOneToken(); } break;

            case ParameterType.StringReferenceTwoTokens: { param = new StringReferenceTwoTokens(); } break;

            case ParameterType.StringReferenceThreeTokens: { param = new StringReferenceThreeTokens(); } break;

            case ParameterType.TargetReference: { param = new TargetReference(); } break;

            case ParameterType.TeamReference: { param = new TeamReference(); } break;

            case ParameterType.TimerReference: { param = new TimerReference(); } break;

            case ParameterType.VirtualTrigger: { param = new VirtualTrigger(); } break;

            case ParameterType.WaypointIcon: { param = new WaypointIconData(); } break;

            case ParameterType.Coordinates3d: { param = new Coordinates3d(); } break;

            case ParameterType.Boolean:
                return(s.Reader.ReadBit());

            default:
                object value = 0;
                StreamIntegerValue(s, paramDefinition, ref value);
                return(value);
            }

            if (param != null)
            {
                param.SerializeObject(s, paramDefinition);
            }

            return(param);
        }
 public MeterDataExtended(MeterData data)
 {
     Id          = data.Id;
     Meter_Id    = data.Meter_Id;
     Customer_Id = data.Customer_Id;
     Resolution  = data.Resolution;
     From        = data.From;
     To          = data.To;
 }
        public async Task <IActionResult> PostMeter([FromBody] MeterData meterData)
        {
            if (meterData == null)
            {
                return(BadRequest($"Invalid arguments"));
            }

            var houseId      = meterData.houseId;
            var serialNumber = meterData.serialNumber;

            if (houseId == default(int))
            {
                return(BadRequest($"Field {nameof(houseId)} is required"));
            }

            if (String.IsNullOrWhiteSpace(serialNumber))
            {
                return(BadRequest($"Field {nameof(serialNumber)} is required"));
            }

            var meterWithSameSnCount = await _context.Meter
                                       .CountAsync(i => i.SerialNumber == serialNumber);

            if (meterWithSameSnCount > 0)
            {
                return(BadRequest($"Meter with the same Serial Number: {serialNumber} is already exists"));
            }

            var houseObj = await _context.House.AsNoTracking()
                           .Include(i => i.Meter)
                           .FirstOrDefaultAsync(i => i.Id == houseId);

            if (houseObj == null)
            {
                if (String.IsNullOrWhiteSpace(serialNumber))
                {
                    return(BadRequest($"House with id {houseId} is not exists"));
                }
            }
            else
            {
                var meterFromHouse = houseObj.Meter.FirstOrDefault();
                if (meterFromHouse != null)
                {
                    _context.Meter.Remove(meterFromHouse);
                }
            }
            var meter = new Meter {
                HouseId = houseId, House = null, SerialNumber = serialNumber
            };

            _context.Meter.Add(meter);
            await _context.SaveChangesAsync();

            return(Ok());
        }
Exemple #5
0
        public long CreateMeter(MeterData meterData, UserOpMap userOpMap)
        {
            DAL_Meter         dAL_Meter         = new DAL_Meter();
            Meter             meter             = new Meter();
            DailyMeterReading dailyMeterReading = new DailyMeterReading();

            meter.Name        = meterData.Name;
            meter.Description = meterData.Description;
            meter.FuelTypeId  = meterData.FuelTypeID;
            dailyMeterReading.DayStartReading = meterData.DayStartReading;
            dailyMeterReading.DayEndReading   = meterData.DayEndReading;
            return(dAL_Meter.CreateMeter(meter, dailyMeterReading, userOpMap));
        }
Exemple #6
0
    public void Save()
    {
        BinaryFormatter bf   = new BinaryFormatter();
        FileStream      file = File.Create(Application.persistentDataPath + "/meterData.nut");
        MeterData       data = new MeterData();

        //<<<-------------SAVING DATA--------------->>>
        data.currentAmount = happiness;
        //<<<-------------END OF SAVING DATA--------------->>>

        //need a different file for each data
        bf.Serialize(file, data);
        file.Close();
    }
Exemple #7
0
    public void Load()
    {
        if (File.Exists(Application.persistentDataPath + "/turnData.nut"))
        {
            BinaryFormatter bf   = new BinaryFormatter();
            FileStream      file = File.Open(Application.persistentDataPath + "/meterData.nut", FileMode.Open);
            MeterData       data = (MeterData)bf.Deserialize(file);

            //<<<-------------LOADING DATA--------------->>>
            happiness = 0;
            fillMeter(data.currentAmount);
            //<<<-------------END OF LOADING DATA--------------->>>

            file.Close();
        }
    }
Exemple #8
0
        public MeterData GetMeterDataByID(string meterID)
        {
            MeterData                meterRetData          = new MeterData();
            List <Meter>             meterList             = new List <Meter>();
            List <DailyMeterReading> dailyMeterReadingList = new List <DailyMeterReading>();
            Fuel fuel = new Fuel();

            BAL.BAL_Meter bAL_Meter = new BAL.BAL_Meter();
            meterList             = bAL_Meter.GetMeterList();
            dailyMeterReadingList = bAL_Meter.GetDailyMeterReading();

            foreach (Meter meter in meterList)
            {
                if (Convert.ToString(meter.Id) == meterID)
                {
                    MeterData meterData = new MeterData();
                    meterData.Id          = meter.Id;
                    meterData.Name        = meter.Name;
                    meterData.Description = meter.Description;
                    meterData.FuelTypeID  = meter.FuelTypeId;
                    fuel = bAL_Meter.GetFuelByFuelID(meterData.FuelTypeID);
                    meterData.FuelType = fuel.Type;
                    foreach (DailyMeterReading dailyMeterReading in dailyMeterReadingList)
                    {
                        if (dailyMeterReading.MeterId == meter.Id)
                        {
                            meterData.DayStartReading = dailyMeterReading.DayStartReading;
                            meterData.DayEndReading   = dailyMeterReading.DayEndReading;
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    meterRetData = meterData;
                    break;
                }
                else
                {
                    continue;
                }
            }
            return(meterRetData);
        }
Exemple #9
0
        private void filterAndSave(string line)
        {
            //split timestamp and value
            string[] substrings = line.Split(' ');
            if (substrings.Length > 1)
            {
                if (this.starttime != new DateTime(2000, 1, 1) && this.endtime != new DateTime(2000, 1, 1)) //check if time filter is set
                {
                    filterByTime(this.starttime, this.endtime);                                             //check if timestamp fits between start and endtime
                }
                else
                {
                    fitsTimeFilter = true;
                }

                if (this.types != null && fitsTimeFilter) //check if any type filters are set and if time is right
                {
                    filterByType();
                }
                else
                {
                    fitsTypeFilter = true;
                }

                if (this.application != null && fitsTimeFilter && fitsTypeFilter) //check if any application filters are set and if time and types are right
                {
                    filterByApplication();
                }
                else
                {
                    fitsApplicationFilter = true;
                }

                if (fitsTimeFilter && fitsTypeFilter && fitsApplicationFilter) //check if data fits all filters
                {
                    temp = new MeterData(REDDMeter.GetMeterId());
                    temp.SetTimestamp(substrings[0]);
                    temp.SetPowerP1(Convert.ToDouble(substrings[1], CultureInfo.InvariantCulture));
                    myDatabase.InsertMeterDataIntoDb(temp);
                }
                fitsTimeFilter        = false;
                fitsTypeFilter        = false;
                fitsApplicationFilter = false;
            }
        }
Exemple #10
0
        private static Dictionary <string, MeterData> GetMeterData(string subscriptionId, string organizationId, string offerId, string currency, string language, string regionInfo, string baseUrl)
        {
            string requesturl = String.Format("{0}/ratecard/GetBillingData?subscriptionId={1}&organizationId={2}&offerId={3}&currency={4}&language={5}&regionInfo={6}",
                                              baseUrl, subscriptionId, organizationId, offerId, currency, language, regionInfo);

            //Build Request
            DateTime       jobStartTime = DateTime.UtcNow;
            HttpWebRequest request      = (HttpWebRequest)WebRequest.Create(requesturl);

            // Read Response
            HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
            StreamReader    reader     = new StreamReader(response.GetResponseStream());
            var             jsonString = reader.ReadToEnd();
            //Get Run Id
            JToken outer  = JToken.Parse(jsonString);
            var    meters = (JArray)outer["Meters"];
            var    meterRateDictionary = new Dictionary <string, MeterData>();

            foreach (var item in meters)
            {
                var meterId          = (string)item["MeterId"];
                var meterRates       = (JObject)item["MeterRates"];
                var IncludedQuantity = (double)item["IncludedQuantity"];
                if (!meterRateDictionary.ContainsKey(meterId))
                {
                    var meterData = new MeterData {
                        MeterId = meterId, IncludedQuantity = IncludedQuantity
                    };
                    meterData.TieredRates = new Dictionary <double, double>();
                    foreach (var property in meterRates)
                    {
                        meterData.TieredRates.Add(double.Parse(property.Key), double.Parse((string)property.Value));
                    }

                    meterRateDictionary.Add(meterData.MeterId, meterData);
                }
            }

            return(meterRateDictionary);
        }
Exemple #11
0
        public void InsertMeterDataIntoDb(MeterData newData)
        {
            this.ConnectToDB();
            try
            {
                String sqlCommand = @"INSERT INTO meter_data VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15, @p16)";

                using (SqlCommand cmd = new SqlCommand(sqlCommand, connection))
                {
                    String[] data = newData.GetData();

                    cmd.Parameters.AddWithValue("@p1", Int32.Parse(data[0]));
                    cmd.Parameters.AddWithValue("@p2", Int32.Parse(data[1]));
                    cmd.Parameters.AddWithValue("@p3", this.UnixTimeStampToDateTime(Convert.ToDouble(data[2])));
                    cmd.Parameters.AddWithValue("@p4", Convert.ToDouble(data[3]));
                    cmd.Parameters.AddWithValue("@p5", Convert.ToDouble(data[4]));
                    cmd.Parameters.AddWithValue("@p6", Convert.ToDouble(data[5]));
                    cmd.Parameters.AddWithValue("@p7", Convert.ToDouble(data[6]));
                    cmd.Parameters.AddWithValue("@p8", Convert.ToDouble(data[7]));
                    cmd.Parameters.AddWithValue("@p9", Convert.ToDouble(data[8]));
                    cmd.Parameters.AddWithValue("@p10", Convert.ToDouble(data[9]));
                    cmd.Parameters.AddWithValue("@p11", Convert.ToDouble(data[10]));
                    cmd.Parameters.AddWithValue("@p12", Convert.ToDouble(data[11]));
                    cmd.Parameters.AddWithValue("@p13", Convert.ToDouble(data[12]));
                    cmd.Parameters.AddWithValue("@p14", Convert.ToDouble(data[13]));
                    cmd.Parameters.AddWithValue("@p15", Convert.ToDouble(data[14]));
                    cmd.Parameters.AddWithValue("@p16", Convert.ToDouble(data[15]));

                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            this.CloseConnection();
        }
Exemple #12
0
        public static MeterData ToViewData(this Meter node, CategoryDictionary suffix = CategoryDictionary.None)
        {
            if (node == null)
            {
                return(null);
            }
            var model = new MeterData()
            {
                Id               = node.Id,
                ParentId         = node.ParentId,
                TreeId           = node.TreeId,
                Rank             = node.Rank,
                Parent           = (suffix & CategoryDictionary.Parent) == CategoryDictionary.Parent && node.ParentId.HasValue ? node.Parent.ToViewData() : null,
                HasChildren      = node.Children.Count,
                BuildingId       = node.BuildingId,
                RelayElecState   = node.RelayElecState,
                PaulElecState    = node.PaulElecState,
                Building         = (suffix & CategoryDictionary.Building) == CategoryDictionary.Building ? node.Building.ToViewData() : null,
                EnergyCategoryId = node.EnergyCategoryId,
                EnergyCategory   = (suffix & CategoryDictionary.EnergyCategory) == CategoryDictionary.EnergyCategory ? (DictionaryCache.Get()[node.EnergyCategoryId].ToViewData()) : null,
                BrandId          = node.BrandId,
                BrandName        = node.Brand == null ? null : node.Brand.Name,
                Brand            = (suffix & CategoryDictionary.Brand) == CategoryDictionary.Brand ? node.Brand.ToViewData() : null,
                CoordinateMapId  = node.CoordinateMapId,
                Coordinate2dId   = node.Coordinate2dId,
                IsControlByHand  = node.IsControlByHand,
                Coordinate3dId   = node.Coordinate3dId,
                Code             = node.Code,
                GbCode           = node.GbCode,
                Name             = node.Name,
                AliasName        = node.AliasName,
                Initial          = node.Initial,
                Type             = node.Type,
                TypeDict         = (suffix & CategoryDictionary.Dictionary) == CategoryDictionary.Dictionary || (suffix & CategoryDictionary.MeterType) == CategoryDictionary.MeterType ? DictionaryCache.Get()[node.Type].ToViewData() : null,
                Access           = node.Access,
                Sequence         = node.Sequence,
                Address          = node.Address,
                MacAddress       = node.MacAddress,
                Enable           = node.Enable,
                StatusNote       = node.StatusNote,
                GetInterval      = node.GetInterval,
                BranchName       = node.BranchName,
                BranchEnable     = node.BranchEnable,
                Rate             = node.Rate,
                Description      = node.Description,
                IsTurnOn         = node.IsTurnOn,
                SetupMode        = node.SetupMode,
                PortNumber       = node.PortNumber,
                Rs485Address     = node.Rs485Address,
                ActivePrecise    = node.ActivePrecise,
                ReactivePrecise  = node.ReactivePrecise,
                BasicCurrent     = node.BasicCurrent,
                ComProtocol      = node.ComProtocol,
                SpeedRate        = node.SpeedRate,
                IsHarmonic       = node.IsHarmonic,
                Precision        = node.Precision,
                PtRate           = node.PtRate,
                RangeRatio       = node.RangeRatio,
                Caliber          = node.Caliber,
                Hydraulic        = node.Hydraulic,
                Flow             = node.Flow,
                //SetupPosition = node.SetupPosition,
                SupplyRegion       = node.SupplyRegion,
                Manufactor         = node.Manufactor,
                SetupDate          = node.SetupDate,
                InitialValue       = node.InitialValue,
                PortDescription    = node.PortDescription,
                EffectiveBasePrice = node.EffectiveBasePrice,
                EffectiveModel     = node.EffectiveModel,
                Status             = node.MeterStatus.Where(s => s.Enabled).ToList().OrderByDescending(o => o.MeterMessageType.FirstValue).ThenByDescending(o => o.MeterMessageType.SecondValue).Select(s => s.ToViewData()).ToList(),
                Organization       = ((suffix & CategoryDictionary.Organization) == CategoryDictionary.Organization) && node.Building != null && node.Building.Organization != null?node.Building.Organization.ToViewData() : null,
            };

            if ((suffix & CategoryDictionary.Momentary) == CategoryDictionary.Momentary)
            {
                model.MomentaryValues = node.MomentaryValues.Select(x => x.ToViewData()).ToList();
            }
            if ((suffix & CategoryDictionary.Children) == CategoryDictionary.Children)
            {
                model.Children = node.Children.Select(x => x.ToViewData(suffix & CategoryDictionary.Momentary)).ToList();
            }
            if ((suffix & CategoryDictionary.Descendant) == CategoryDictionary.Descendant)
            {
                model.Descendants = node.Descendants(false).Select(x => x.ToViewData()).ToList();
            }
            if ((suffix & CategoryDictionary.Ancestor) == CategoryDictionary.Ancestor)
            {
                model.Ancestors = node.Ancestors().Select(x => x.ToViewData()).ToList();
            }
            EmpContext ctx = null;

            if ((suffix & CategoryDictionary.Gateway) == CategoryDictionary.Gateway)
            {
                if (ctx == null)
                {
                    ctx = new EmpContext();
                }
                var m = ctx.Meters.FirstOrDefault(x => x.Type == 50101 && x.Access == node.Access);
                model.Gateway = m == null ? null : m.ToViewData(suffix & CategoryDictionary.Momentary);
            }
            if ((suffix & CategoryDictionary.Sibling) == CategoryDictionary.Sibling)
            {
                if (ctx == null)
                {
                    ctx = new EmpContext();
                }
                model.Siblings = ctx.Meters.Where(x => x.ParentId == node.ParentId && x.Access == node.Access).ToList().Select(x => x.ToViewData(CategoryDictionary.Children | CategoryDictionary.Momentary)).ToList();
            }
            if ((suffix & CategoryDictionary.ExtensionField) == CategoryDictionary.ExtensionField)
            {
                if (ctx == null)
                {
                    ctx = new EmpContext();
                }
                model.ExtensionFields = ctx.ExtensionFields.Where(x => x.Table == "Meter" && x.JoinId == node.Id).ToViewList();
            }
            return(model);
        }
Exemple #13
0
        private void workDisagregationFile(String path)
        {
            String[] paths = path.Split('\\');

            ///For later usage to find the household
            String household       = paths[paths.Count() - 2];
            int    householdNumber = (int)Char.GetNumericValue(household[household.Count() - 1]);

            ///Device identifier
            String device = paths[paths.Count() - 1];

            String[] deviceParts        = device.Split('.');
            String[] furtherDeviceParts = deviceParts[0].Split('_');
            int      deviceNumber       = Int32.Parse(furtherDeviceParts[1]);

            bool filterOk = false;

            ///Filter for appliance
            if (this.application != null)
            {
                foreach (ApplicationEnum currentApp in this.application)
                {
                    filterOk |= this.compareApplicationEnumWithCurrentHouseholdApp(currentApp, householdNumber, deviceNumber);
                }
            }
            else
            {
                filterOk = true;
            }

            if (filterOk == true)
            {
                using (StreamReader file = new StreamReader(path))
                {
                    if (file != null)
                    {
                        String line = "";
                        while ((line = file.ReadLine()) != null)
                        {
                            if (line != null)
                            {
                                String[] values = line.Split(' ');

                                String[] PowerValues = new String[(values.Count())];


                                if (!swapTimestampifSecondsPassed(values[0]))
                                {
                                    continue;
                                }

                                ///Only store data to database if the current timestamp is in the given boundries
                                if (Int32.Parse(values[0]) < this.getUnixTimestampFromDate(this.starttime) || Int32.Parse(values[0]) > this.getUnixTimestampFromDate(this.endtime) && this.filterByTimeEnabled)
                                {
                                }
                                else
                                {
                                    for (int i = 0; i < values.Count(); i++)
                                    {
                                        PowerValues[i] = values[i];
                                    }

                                    ///CHANGE TO REAL METERS
                                    MeterData temp = new MeterData(this.housesList[0].Item1);
                                    temp.SetTimestamp(values[0]);
                                    temp.SetPowerP1(Convert.ToDouble(values[1]));

                                    myDatabase.InsertMeterDataIntoDb(temp);
                                }
                            }
                        }
                    }
                }
                Console.WriteLine("Loaded " + household + " " + device + " sucessfully!");
            }
        }
Exemple #14
0
        public static MeterData ToViewData(this MeterFullInfo node, CategoryDictionary suffix = CategoryDictionary.None)
        {
            if (node == null)
            {
                return(null);
            }
            var model = new MeterData()
            {
                Id       = node.Id,
                ParentId = node.ParentId,
                TreeId   = node.TreeId,
                Rank     = node.Rank,
                Parent   = (suffix & CategoryDictionary.Parent) == CategoryDictionary.Parent && node.ParentId.HasValue ? new MeterData
                {
                    Id   = (int)node.ParentId,
                    Name = node.ParentName
                } : null,
                HasChildren = (node.HasChildren == null ? 0 : (int)node.HasChildren),
                BuildingId  = node.BuildingId,
                Building    = (suffix & CategoryDictionary.Building) == CategoryDictionary.Building && node.BuildingId.HasValue ? new BuildingData
                {
                    Id                 = (int)node.BuildingId,
                    Name               = node.BuildingName,
                    OrganizationId     = node.OrganizationId,
                    BuildingCategoryId = node.BuildingCategoryId == null ? -1 : (int)node.BuildingCategoryId,
                    GbCode             = node.BuildingGBCode,
                } : null,
                EnergyCategoryId = node.EnergyCategoryId,
                EnergyCategory   = (suffix & CategoryDictionary.EnergyCategory) == CategoryDictionary.EnergyCategory ? new DictionaryData
                {
                    Id          = node.EnergyCategoryId,
                    ChineseName = DictionaryCache.Get()[node.EnergyCategoryId].ChineseName
                } : null,
                BrandId = node.BrandId,
                Brand   = (suffix & CategoryDictionary.Brand) == CategoryDictionary.Brand ? new BrandData
                {
                    Id            = node.BrandId,
                    Name          = node.brandName,
                    Description   = node.BrandDescription,
                    MeterTypeName = node.TypeName,
                    Model         = node.Model,
                    Producer      = node.Producer
                } : null,
                CoordinateMapId = node.CoordinateMapId,
                Coordinate2dId  = node.Coordinate2dId,
                Coordinate3dId  = node.Coordinate3dId,
                Code            = node.Code,
                GbCode          = node.GbCode,
                Name            = node.Name,
                AliasName       = node.AliasName,
                Initial         = node.Initial,
                Type            = node.Type,
                Access          = node.Access,
                Sequence        = node.Sequence,
                Address         = node.Address,
                MacAddress      = node.MacAddress,
                Enable          = node.Enable,
                StatusNote      = node.StatusNote,
                GetInterval     = node.GetInterval,
                BranchName      = node.BranchName,
                BranchEnable    = node.BranchEnable,
                Rate            = node.Rate,
                Description     = node.Description
            };

            if ((suffix & CategoryDictionary.ExtensionField) == CategoryDictionary.ExtensionField)
            {
                var ctx = new EmpContext();
                model.ExtensionFields = ctx.ExtensionFields.Where(x => x.Table == "Meter" && x.JoinId == node.Id).ToViewList();
            }
            return(model);
        }
Exemple #15
0
        public static AzusaDexTimeline LoadFrom(DexcomDevice dd)
        {
            AzusaDexTimeline result = new AzusaDexTimeline();

            result.Timestamp = dd.ReadRTC();
            PartitionInfo pi = dd.ReadDatabaseParitionInfo();

            for (int i = 0; i < pi.Partition.Length; i++)
            {
                DatabasePageRange dpr = dd.ReadDatabasePageRange(pi.Partition[i]);
                if (dpr.Start == -1)
                {
                    continue;
                }
                for (int j = dpr.Start; j < dpr.End; j++)
                {
                    DatabasePage page = dd.ReadDatabasePage(pi.Partition[i], j);
                    for (int k = 0; k < page.Record.Length; k++)
                    {
                        switch (page.RecordType)
                        {
                        case RecordType.SensorData:
                            SensorData sd = page.Record[k] as SensorData;
                            result[sd.DisplayTime].Rssi             = sd.Rssi;
                            result[sd.DisplayTime].SensorFiltered   = sd.Filtered;
                            result[sd.DisplayTime].SensorUnfiltered = sd.Unfiltered;
                            break;

                        case RecordType.EgvData:
                            EGVRecord egv = page.Record[k] as EGVRecord;
                            if (egv.SpecialGlucoseValue == null)
                            {
                                result[egv.DisplayTime].Glucose = egv.Glucose;
                            }
                            else
                            {
                                result[egv.DisplayTime].SpecialGlucoseValue = egv.SpecialGlucoseValue;
                            }
                            result[egv.DisplayTime].TrendArrow = egv.TrendArrow;
                            break;

                        case RecordType.InsertionTime:
                            InsertionTime it = page.Record[k] as InsertionTime;
                            result[it.DisplayTime].SessionState = it.SessionState;
                            break;

                        case RecordType.MeterData:
                            MeterData md = page.Record[k] as MeterData;
                            result[md.DisplayTime].MeterGlucose = md.MeterGlucose;
                            break;

                        case RecordType.UserEventData:
                            UserEventData ued = page.Record[k] as UserEventData;
                            result[ued.DisplayTime2].EventType = ued.EventType;
                            switch (ued.EventType)
                            {
                            case EventType.Carbs:
                                result[ued.DisplayTime2].Carbs = ued.EventValue;
                                break;

                            case EventType.Insulin:
                                result[ued.DisplayTime2].Insulin = ued.EventValue;
                                break;

                            default:
                                result[ued.DisplayTime2].HealthEvent   = ued.HealthEvent;
                                result[ued.DisplayTime2].ExerciseEvent = ued.ExerciseEvent;
                                break;
                            }
                            break;

                        case RecordType.ManufacturingData:
                            ManufacturingParameters mp = page.Record[k] as ManufacturingParameters;
                            result[mp.DisplayTime].ManufacturingParameters = mp;
                            break;

                        case RecordType.FirmwareParameterData:
                            FirmwareParameterData fpd = page.Record[k] as FirmwareParameterData;
                            result[fpd.DisplayTime].FirmwareParameters = fpd.FPR;
                            break;

                        case RecordType.PcSoftwareParameter:
                            PcSoftwareParameter pcp = page.Record[k] as PcSoftwareParameter;
                            result[pcp.DisplayTime].PcSoftwareParameter = pcp;
                            break;

                        case RecordType.CalSet:
                        case RecordType.ReceiverLogData:
                        case RecordType.UserSettingData:
                        case RecordType.Deviation:
                            break;

                        default:
                            throw new NotImplementedException(page.RecordType.ToString());
                        }
                    }
                }
            }

            result.Order();
            return(result);
        }
Exemple #16
0
        private void workFile(String path)
        {
            String pathToVoltageFile = path;
            String pathToCurrentFile = "";

            String[] paths = pathToVoltageFile.Split('\\');

            //Gets the household number
            String household       = paths[paths.Count() - 2];
            int    householdNumber = (int)Char.GetNumericValue(household[household.Count() - 1]);

            for (int i = 0; i < (paths.Count() - 1); i++)
            {
                pathToCurrentFile += paths[i] + "\\";
            }
            String[] timestamp = paths[paths.Count() - 1].Split('-');

            String curentTimestamp = this.removeMilisFromTimestamp(timestamp[0]);

            pathToCurrentFile += timestamp[0] + "-current";

            int chunkSize = 1024;

            using (FileStream fsVoltage = new FileStream(pathToVoltageFile, FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader binReaderVoltage = new BinaryReader(fsVoltage, new ASCIIEncoding()))
                {
                    using (FileStream fsCurrent = new FileStream(pathToCurrentFile, FileMode.Open, FileAccess.Read))
                    {
                        using (BinaryReader binReaderCurrent = new BinaryReader(fsCurrent, new ASCIIEncoding()))
                        {
                            byte[] chunkVolts;
                            byte[] chunkAmps;

                            int k = 0;
                            int l = 0;

                            while (binReaderVoltage.BaseStream.Position != binReaderVoltage.BaseStream.Length)
                            {
                                int realTimestamp = Int32.Parse(curentTimestamp) + l;

                                if (!swapTimestampifSecondsPassed(realTimestamp.ToString()))
                                {
                                    if (k == (16000 / chunkSize))
                                    {
                                        k = 0;
                                        l++;
                                    }
                                    k++;

                                    continue;
                                }

                                ///If value timestamp is out of timestampvalue / Filter by time
                                if (realTimestamp < this.getUnixTimestampFromDate(this.starttime) || realTimestamp > this.getUnixTimestampFromDate(this.endtime) && this.filterByTimeEnabled)
                                {
                                }
                                else
                                {
                                    if (this.frequenzy == 0)
                                    {
                                        chunkVolts = binReaderVoltage.ReadBytes(chunkSize);
                                        chunkAmps  = binReaderCurrent.ReadBytes(chunkSize);

                                        double[] voltValues = new double[chunkVolts.Length / 8];
                                        double[] ampValues  = new double[chunkAmps.Length / 8];
                                        for (int j = 0; j < voltValues.Length; j++)
                                        {
                                            voltValues[j]  = BitConverter.ToDouble(chunkVolts, j * 8);
                                            voltValues[j] *= Math.Pow(2, 31); //conversion factor
                                            voltValues[j] *= (1.90101491444 * Math.Pow(10, -7));
                                        }

                                        for (int j = 0; j < ampValues.Length; j++)
                                        {
                                            ampValues[j]  = BitConverter.ToDouble(chunkAmps, j * 8);
                                            ampValues[j] *= Math.Pow(2, 31); //conversion factor
                                            ampValues[j] *= (4.9224284384 * Math.Pow(10, -8));
                                        }

                                        double[] powerValue = new double[ampValues.Length];
                                        for (int i = 0; i < powerValue.Count(); i++)
                                        {
                                            powerValue[i] = voltValues[i] * ampValues[i];

                                            ///Filtering whole houses does not work yet
                                            MeterData temp = new MeterData(this.housesList[householdNumber - 1].Item1);

                                            ///Frequenzy = 16kHz
                                            ///all 16 tousand times, one second passes
                                            temp.SetTimestamp(realTimestamp.ToString());
                                            temp.SetPowerP1(powerValue[i]);
                                            temp.SetVoltage(voltValues[i]);

                                            myDatabase.InsertMeterDataIntoDb(temp);
                                        }
                                    }
                                    else
                                    {
                                        chunkVolts = binReaderVoltage.ReadBytes(chunkSize);
                                        chunkAmps  = binReaderCurrent.ReadBytes(chunkSize);

                                        double[] voltValues = new double[chunkVolts.Length / 8];
                                        double[] ampValues  = new double[chunkAmps.Length / 8];
                                        for (int j = 0; j < voltValues.Length; j++)
                                        {
                                            voltValues[j]  = BitConverter.ToDouble(chunkVolts, j * 8);
                                            voltValues[j] *= Math.Pow(2, 31); //conversion factor
                                            voltValues[j] *= (1.90101491444 * Math.Pow(10, -7));
                                        }

                                        for (int j = 0; j < ampValues.Length; j++)
                                        {
                                            ampValues[j]  = BitConverter.ToDouble(chunkAmps, j * 8);
                                            ampValues[j] *= Math.Pow(2, 31); //conversion factor
                                            ampValues[j] *= (4.9224284384 * Math.Pow(10, -8));
                                        }

                                        double[] powerValue = new double[ampValues.Length];
                                        for (int i = 0; i < 1; i++)
                                        {
                                            powerValue[i] = voltValues[i] * ampValues[i];

                                            MeterData temp = new MeterData(this.housesList[householdNumber - 1].Item1);

                                            ///Frequenzy = 16kHz
                                            ///all 16 tousand times, one second passes
                                            temp.SetTimestamp(realTimestamp.ToString());
                                            temp.SetPowerP1(powerValue[i]);
                                            temp.SetVoltage(voltValues[i]);

                                            myDatabase.InsertMeterDataIntoDb(temp);
                                        }
                                    }
                                }

                                if (k == (16000 / chunkSize))
                                {
                                    k = 0;
                                    l++;
                                }
                                k++;
                            }
                        }
                    }
                }
            }
        }
Exemple #17
0
        protected override void processFile(String path)
        {
            //open file
            //get datastream
            //save data --> not implemented yet
            //close file
            StreamReader reader = new StreamReader(File.OpenRead(path));

            if (reader != null)
            {
                String line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                    Console.WriteLine();

                    String[] values = line.Split(',');

                    if (sort == false)
                    {
                        if (isU)
                        {
                            String[] voltage = new String[values.Count()];

                            for (int i = 0; i < values.Count(); i++)
                            {
                                voltage[i] = values[i];
                            }

                            int countFrequency = 0;
                            foreach (String value in voltage)
                            {
                                if ((countFrequency % frequenzy) == 0)
                                {
                                    MeterData temp = new MeterData(ADRESMeterId);
                                    temp.SetVoltage(Convert.ToDouble(value, CultureInfo.InvariantCulture));

                                    myDatabase.InsertMeterDataIntoDb(temp);
                                }
                                countFrequency++;
                            }
                        }
                        else
                        {
                            String[] power = new String[values.Count()];

                            for (int i = 0; i < values.Count(); i++)
                            {
                                power[i] = values[i];
                            }

                            int counter = 0;
                            foreach (String value in power)
                            {
                                if (this.frequenzy == 0)
                                {
                                    this.frequenzy = 1;
                                }

                                if ((counter % (2 * frequenzy) == 0))
                                {
                                    MeterData temp = new MeterData(ADRESMeterId);
                                    temp.SetPowerP1(Convert.ToDouble(value, CultureInfo.InvariantCulture));
                                    myDatabase.InsertMeterDataIntoDb(temp);
                                }

                                counter++;
                            }
                        }
                    }
                    else
                    {
                        if (sortU)
                        {
                            if (isU)
                            {
                                String[] voltage = new String[values.Count()];

                                for (int i = 0; i < values.Count(); i++)
                                {
                                    voltage[i] = values[i];
                                }

                                int countFrequency = 0;
                                foreach (String value in voltage)
                                {
                                    if (this.frequenzy == 0)
                                    {
                                        this.frequenzy = 1;
                                    }

                                    if ((countFrequency % frequenzy) == 0)
                                    {
                                        MeterData temp = new MeterData(ADRESMeterId);
                                        temp.SetVoltage(Convert.ToDouble(value, CultureInfo.InvariantCulture));
                                        myDatabase.InsertMeterDataIntoDb(temp);
                                    }
                                    countFrequency++;
                                }
                            }
                        }
                        if (sortP)
                        {
                            String[] power = new String[values.Count()];

                            for (int i = 0; i < values.Count(); i++)
                            {
                                power[i] = values[i];
                            }

                            int counter = 0;
                            foreach (String value in power)
                            {
                                if (this.frequenzy == 0)
                                {
                                    this.frequenzy = 1;
                                }

                                if ((counter % (2 * frequenzy)) == 0)
                                {
                                    MeterData temp = new MeterData(ADRESMeterId);
                                    temp.SetPowerP1(Convert.ToDouble(value, CultureInfo.InvariantCulture));
                                    myDatabase.InsertMeterDataIntoDb(temp);
                                }

                                counter++;
                            }
                        }
                    }
                }
                reader.Close();
            }
        }
Exemple #18
0
        public async Task <IHttpActionResult> GetMetersForBuilding(Guid idBuilding)
        {
            var meterData = new MeterData();

            return(Ok(await meterData.GetMetersForBuilding(idBuilding)));
        }
 /// <summary>
 /// ToDataSeries
 /// </summary>
 /// <param name="faultCurve"></param>
 /// <returns></returns>
 private DataGroup ToDataSeries(MeterData.EventDataRow faultCurve)
 {
     DataGroup dataGroup = new DataGroup();
     dataGroup.FromData(faultCurve.FrequencyDomainData);
     return dataGroup;
 }
Exemple #20
0
        public static Meter ToModel(this MeterData node)
        {
            var model = new Meter()
            {
                Id                 = node.Id,
                ParentId           = node.ParentId,
                TreeId             = node.TreeId,
                Rank               = node.Rank,
                IsControlByHand    = node.IsControlByHand,
                BuildingId         = node.BuildingId,
                EnergyCategoryId   = node.EnergyCategoryId,
                BrandId            = node.BrandId,
                CoordinateMapId    = node.CoordinateMapId,
                Coordinate2dId     = node.Coordinate2dId,
                Coordinate3dId     = node.Coordinate3dId,
                Code               = node.Code,
                EffectiveBasePrice = node.EffectiveBasePrice,
                EffectiveModel     = node.EffectiveModel,
                GbCode             = node.GbCode,
                Name               = node.Name,
                AliasName          = node.AliasName,
                Initial            = node.Initial,
                RelayElecState     = node.RelayElecState,
                PaulElecState      = node.PaulElecState,
                Type               = node.Type,
                Access             = node.Access,
                Sequence           = node.Sequence,
                Address            = node.Address,
                MacAddress         = node.MacAddress,
                Enable             = node.Enable,
                StatusNote         = node.StatusNote,
                GetInterval        = node.GetInterval,
                BranchName         = node.BranchName,
                BranchEnable       = node.BranchEnable,
                Rate               = node.Rate,
                Description        = node.Description,
                IsTurnOn           = node.IsTurnOn,
                SetupMode          = node.SetupMode,
                PortNumber         = node.PortNumber,
                Rs485Address       = node.Rs485Address,

                ActivePrecise   = node.ActivePrecise,
                ReactivePrecise = node.ReactivePrecise,
                BasicCurrent    = node.BasicCurrent,
                ComProtocol     = node.ComProtocol,
                SpeedRate       = node.SpeedRate,
                IsHarmonic      = node.IsHarmonic,
                Precision       = node.Precision,
                PtRate          = node.PtRate,
                RangeRatio      = node.RangeRatio,
                Caliber         = node.Caliber,
                Hydraulic       = node.Hydraulic,
                Flow            = node.Flow,
                //SetupPosition = node.SetupPosition,
                SupplyRegion    = node.SupplyRegion,
                Manufactor      = node.Manufactor,
                SetupDate       = node.SetupDate,
                InitialValue    = node.InitialValue,
                PortDescription = node.PortDescription
            };

            return(model);
        }
        public IActionResult Post([FromBody] JObject data)
        {
            try
            {
                MeterData mdata = new MeterData
                {
                    Id          = Guid.NewGuid(),
                    Meter_Id    = data["meter_id"].ToString(),
                    Customer_Id = data["customer_id"].ToString(),
                    Resolution  = data["resolution"].ToString(),
                    From        = DateTime.Parse(data["from"].ToString()),
                    To          = DateTime.Parse(data["to"].ToString()),
                };
                var savedMData = _repository.MeterData.SaveMeterData(mdata);
                _repository.Save();

                ArrayList arr    = new ArrayList();
                var       jobj   = JObject.Parse(data.ToString());
                var       values = jobj["values"];
                var       dict   = JsonConvert.DeserializeObject <Dictionary <DateTime, double> >
                                       (values.ToString());


                foreach (var item in dict)
                {
                    var meterValue = new MeterValue
                    {
                        Id           = Guid.NewGuid(),
                        MeterDataId  = mdata.Id,
                        Meter_Id     = mdata.Meter_Id,
                        Custormer_Id = mdata.Customer_Id,
                        Hour         = item.Key,
                        Value        = item.Value
                    };
                    var returnedMeterValue = new MeterValueReturned
                    {
                        Hour  = item.Key,
                        Value = item.Value
                    };
                    _repository.MeterValue.SaveMeterValue(meterValue);
                    arr.Add(returnedMeterValue);
                    _repository.Save();
                }

                MeterDataExtended returnedMeterData = new MeterDataExtended
                {
                    Id          = savedMData.Id,
                    Meter_Id    = savedMData.Meter_Id,
                    Customer_Id = savedMData.Customer_Id,
                    Resolution  = savedMData.Resolution,
                    From        = savedMData.From,
                    To          = savedMData.To,
                    Values      = arr
                };

                return(Ok(returnedMeterData));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex.Message));
            }
        }
        private void workFile(string path)
        {
            String[] pathParts = path.Split('\\');
            String   household = pathParts[pathParts.Count() - 2];

            StreamReader file = new StreamReader(path);

            if (file != null)
            {
                //First line gets lost here on purpose
                String line = file.ReadLine();

                while ((line = file.ReadLine()) != null)
                {
                    if (line != null)
                    {
                        String[] values = line.Split(',');

                        ///The file reader can overflow. This protects that case
                        if (values[0] == "timestamp")
                        {
                            break;
                        }

                        String[] PowerValues = new String[(values.Count() - 1)];

                        for (int i = 1; i < values.Count(); i++)
                        {
                            PowerValues[i - 1] = values[i];
                        }

                        ///Aplication filter
                        List <int> foundIndicesWithDuplicates    = new List <int>();
                        List <int> foundIndicesWithoutDuplicates = new List <int>();
                        if (this.application != null)
                        {
                            foreach (ApplicationEnum currentCheckApplication in this.application)
                            {
                                int startAplicationList = this.currentHouseholdNumber * 9;
                                for (int i = startAplicationList; i < startAplicationList + 9; i++)
                                {
                                    if (currentCheckApplication == this.meterList[i].Item2)
                                    {
                                        foundIndicesWithDuplicates.Add(i - (9 * startAplicationList));
                                    }
                                }
                            }
                            foundIndicesWithoutDuplicates = foundIndicesWithDuplicates.Distinct().ToList();
                        }
                        int j = 0;
                        foreach (String value in PowerValues)
                        {
                            if (j == 0)
                            {
                                ///If value timestamp is out of timestampvalue / Filter by time
                                if ((Int32.Parse(removeMilisFromTimestamp(values[0])) < this.getUnixTimestampFromDate(this.starttime) || Int32.Parse(removeMilisFromTimestamp(values[0])) > this.getUnixTimestampFromDate(this.endtime)) && this.filterByTimeEnabled)
                                {
                                    break;
                                }

                                ///Checks if the given accuracy time has already passed. if not, break out.
                                if (!swapTimestampifSecondsPassed(values[0]))
                                {
                                    break;
                                }
                            }

                            if (foundIndicesWithoutDuplicates.Count != 0)
                            {
                                foreach (int searchedIndex in foundIndicesWithoutDuplicates)
                                {
                                    if (j == searchedIndex)
                                    {
                                        MeterData temp = new MeterData(getMeterId(j));
                                        temp.SetTimestamp(removeMilisFromTimestamp(values[0]));

                                        if (value == "NULL")
                                        {
                                            temp.SetPowerP1(Convert.ToDouble(0.0, CultureInfo.InvariantCulture));
                                        }
                                        else
                                        {
                                            temp.SetPowerP1(Convert.ToDouble(value, CultureInfo.InvariantCulture));
                                        }

                                        myDatabase.InsertMeterDataIntoDb(temp);
                                    }
                                }
                            }
                            else
                            {
                                MeterData temp = new MeterData(getMeterId(j));
                                temp.SetTimestamp(removeMilisFromTimestamp(values[0]));

                                if (value == "NULL")
                                {
                                    temp.SetPowerP1(Convert.ToDouble(0.0, CultureInfo.InvariantCulture));
                                }
                                else
                                {
                                    temp.SetPowerP1(Convert.ToDouble(value, CultureInfo.InvariantCulture));
                                }

                                myDatabase.InsertMeterDataIntoDb(temp);
                            }
                            j++;
                        }
                    }
                }
            }
        }
 public void Upsert(MeterData.DailyTrendingSummaryRow row)
 {
     Upsert(row.ChannelID, row.Date, row.Minimum, row.Maximum, row.Average, row.ValidCount, row.InvalidCount);
 }