Пример #1
0
        public void GetVersionsSingleRecord()
        {
            Assert.That(Records, Is.Empty);

            DateTime localHour = DateTime.Now.TrimToHour();

            AreaValueModel model = new AreaValueModel {
                Area = "ROM", Value = 100, Sample = localHour
            };

            Repository.Add(model);

            ModelVersions versions = Repository.GetVersions(model.Id);

            Assert.That(versions, Is.Not.Null);
            Assert.That(versions.Versions, Is.Not.Empty);
            Assert.That(versions.Versions.Count, Is.EqualTo(1));

            ModelVersion <AreaValueModel> version = (ModelVersion <AreaValueModel>)versions.Versions[0];

            Assert.That(version.Display, Is.EqualTo("User created record"));
            Assert.That(version.Model.Id, Is.EqualTo(model.Id));
            Assert.That(version.Model.Area, Is.EqualTo(model.Area));
            Assert.That(version.Model.Sample, Is.EqualTo(model.Sample));
            Assert.That(version.Model.Value, Is.EqualTo(model.Value));

            AmplaAuditRecord history = Repository.GetHistory(model.Id);

            Assert.That(history.Changes, Is.Empty);
        }
Пример #2
0
        private void watchModelVersion(WatchResponse watchResponse)
        {
            Console.WriteLine("Fire Watch");
            if (watchResponse.Events.Count > 0 && watchResponse.Events[0].Kv != null)
            {
                Console.WriteLine(
                    $"{watchResponse.Events[0].Kv.Key.ToStringUtf8()}:{watchResponse.Events[0].Kv.Value.ToStringUtf8()}");
                var json = watchResponse.Events[0].Kv.Value.ToStringUtf8();
                var maybeModelVersion = deserialize <ModelVersion>(json);
                if (maybeModelVersion.IsSuccess)
                {
                    maybeModelVersion.IfSucc(version =>
                    {
                        lock (model_version_lock)
                        {
                            if (version.TimeStamp != _modelVersion.TimeStamp)
                            {
                                _modelVersion = version;
                            }
                        }

                        filterOutModelVersions();
                    });
                }

                Console.WriteLine("Got new modelversion - {0}", _modelVersion);
            }
        }
Пример #3
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (dataset_ != null)
            {
                hash ^= Dataset.GetHashCode();
            }
            if (revision_ != null)
            {
                hash ^= Revision.GetHashCode();
            }
            if (ModelVersion != 0L)
            {
                hash ^= ModelVersion.GetHashCode();
            }
            hash ^= Metrics.GetHashCode();
            hash ^= targetMetrics_.GetHashCode();
            if (InputType != global::Asgt.Type.Model.Types.InputType.FeatureTensors)
            {
                hash ^= InputType.GetHashCode();
            }
            if (trainStatistics_ != null)
            {
                hash ^= TrainStatistics.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Пример #4
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (dataset_ != null)
            {
                hash ^= Dataset.GetHashCode();
            }
            if (ModelVersion != 0L)
            {
                hash ^= ModelVersion.GetHashCode();
            }
            if (Status.Length != 0)
            {
                hash ^= Status.GetHashCode();
            }
            if (StatusMessage.Length != 0)
            {
                hash ^= StatusMessage.GetHashCode();
            }
            hash ^= artifacts_.GetHashCode();
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Пример #5
0
 internal GreenModel(ModelId id, string name, ModelVersion version)
 {
     this.id             = id;
     this.name           = name;
     this.version        = version;
     this.objects        = ImmutableDictionary <ObjectId, GreenObject> .Empty;
     this.strongObjects  = ImmutableList <ObjectId> .Empty;
     this.lazyProperties = ImmutableDictionary <ObjectId, ImmutableHashSet <Slot> > .Empty;
     this.references     = ImmutableDictionary <ObjectId, ImmutableDictionary <ObjectId, ImmutableHashSet <Slot> > > .Empty;
 }
        protected void AssertModelVersionProperty(ModelVersions modelVersions,
                                                  int index,
                                                  Func <TModel, object> modelFunc,
                                                  IResolveConstraint expectedConstraint)
        {
            Assert.That(modelVersions.Versions.Count, Is.GreaterThan(index), "Unable to find Version {0}", index);
            ModelVersion          modelVersion = modelVersions.Versions[index];
            ModelVersion <TModel> typedModel   = (ModelVersion <TModel>)modelVersion;

            Assert.That(modelFunc(typedModel.Model), expectedConstraint);
        }
Пример #7
0
        private LockStatus LockData(out EpisodeGuid creationDate)
        {
            var sessionToken = CreateServiceModelSessionToken();

            uint lockOptions = 129u;

            ModelVersion localModelVersion = new ModelVersion(new VersionNumber(0), new ModelHistoryCheckInfo(EpisodeGuid.Invalid));

            IClientProxy <IModelService> bufferedProxy = GetBufferedProxy();
            IModelService proxy = bufferedProxy.Proxy;

            return(proxy.LockData(sessionToken, lockOptions, bAllowBecomeNonExclusive: true, localModelVersion, out creationDate));
        }
Пример #8
0
        public Coordinator(string etcdHost)
        {
            this._jsonSerializerOptions = new JsonSerializerOptions();
            _jsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;


            client = new EtcdClient(etcdHost);

            _modelVersion = getModelVersion();

            this._apiHostPorts = new List <APIHostPort>();
            listAndAddNodesBootStrap();

            addWatches();
        }
Пример #9
0
 public void publishModelVersion(ModelVersion modelVersion)
 {
     try
     {
         var lockResponse = client.Lock(name: MODEL_VERSION_LOCK, deadline: DateTime.UtcNow.AddSeconds(5));
         client.Put(MODEL_VERSION, serializeJson(modelVersion));
         client.Unlock(MODEL_VERSION_LOCK);
         filterOutModelVersions();
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
Пример #10
0
            //Set the model of the follower, return success
            public bool SetFollowerModel(int model)
            {
                try {
                    var request = new ModelVersion {
                        Version = model
                    };
                    var ack = _client.SwitchFollowerModel(request);

                    return(ack.Success);
                }
                catch (RpcException e) {
                    Console.Write("RPC failed " + e);
                    throw;
                }
            }
        public bool Bind()
        {
            versions.ModelName = modelProperties.GetModelName();

            AmplaRecordHistory <TModel> history       = new AmplaRecordHistory <TModel>(amplaRecord, auditRecord, viewProperties);
            List <AmplaRecordChanges>   recordChanges = history.Reconstruct();

            ModelVersion <TModel>[] modelVersions = new ModelVersion <TModel> [recordChanges.Count];

            TModel clonedModel = modelProperties.CloneModel(currentModel);

            for (int i = 0; i < modelVersions.Length; i++)
            {
                AmplaRecordChanges recordChange = recordChanges[i];
                bool isCurrent = i == (modelVersions.Length - 1);
                modelVersions[i] = new ModelVersion <TModel>(isCurrent, clonedModel)
                {
                    Version     = i + 1,
                    User        = recordChange.User,
                    VersionDate = recordChange.VersionDateTime,
                    Display     = recordChange.Display
                };
            }

            TModel current = currentModel;

            for (int i = modelVersions.Length - 1; i >= 0; i--)
            {
                var modelVersion = modelVersions[i];
                modelVersion.Model = modelProperties.CloneModel(current);
                AmplaRecordChanges recordChange = recordChanges[i];

                foreach (var field in recordChange.Changes)
                {
                    viewProperties.UpdateModel(current, field.Name, field.OriginalValue, false);
                }
                if (i == 0)
                {
                    modelVersion.Model = modelProperties.CloneModel(current);
                }
            }

            foreach (var modelVersion in modelVersions)
            {
                versions.Versions.Add(modelVersion);
            }
            return(true);
        }
Пример #12
0
        public void GetVersion_NotRelevantChanges()
        {
            Assert.That(Records, Is.Empty);

            AreaValueModel model = new AreaValueModel {
                Area = "ROM", Value = 100
            };

            Repository.Add(model);
            Assert.That(Records.Count, Is.EqualTo(1));

            int recordId = Records[0].RecordId;

            InMemoryRecord record = new InMemoryRecord(ProductionViews.AreaValueModelView())
            {
                Module   = module,
                Location = location,
                RecordId = recordId
            };

            record.SetFieldValue("Sample Period", DateTime.Today);

            UpdateRecord(record);

            Assert.That(Records.Count, Is.EqualTo(1));
            Assert.That(Records[0].GetFieldValue("Sample Period", DateTime.MinValue), Is.EqualTo(DateTime.Today.ToUniversalTime()));

            ModelVersions versions = Repository.GetVersions(model.Id);

            Assert.That(versions, Is.Not.Null);
            Assert.That(versions.Versions, Is.Not.Empty);
            Assert.That(versions.Versions.Count, Is.EqualTo(2));  // one version change ('Sample Period') is not relevant

            ModelVersion <AreaValueModel> last    = (ModelVersion <AreaValueModel>)versions.Versions[0];
            ModelVersion <AreaValueModel> current = (ModelVersion <AreaValueModel>)versions.Versions[1];

            Assert.That(last.Model, Is.Not.Null);
            Assert.That(last.IsCurrentVersion, Is.False);
            Assert.That(last.Model.Id, Is.EqualTo(model.Id));
            Assert.That(last.Model.Value, Is.EqualTo(model.Value));
            Assert.That(last.Model.Area, Is.EqualTo(model.Area));

            Assert.That(current.Model, Is.Not.Null);
            Assert.That(current.IsCurrentVersion, Is.True);
            Assert.That(current.Model.Id, Is.EqualTo(model.Id));
            Assert.That(current.Model.Value, Is.EqualTo(model.Value));
            Assert.That(current.Model.Area, Is.EqualTo(model.Area));
        }
Пример #13
0
 internal GreenModel Update(
     string name,
     ModelVersion version,
     ImmutableDictionary <ObjectId, GreenObject> objects,
     ImmutableList <ObjectId> strongObjects,
     ImmutableDictionary <ObjectId, ImmutableHashSet <Slot> > lazyProperties,
     ImmutableDictionary <ObjectId, ImmutableDictionary <ObjectId, ImmutableHashSet <Slot> > > references)
 {
     if (this.name != name || this.version != version || this.objects != objects ||
         this.strongObjects != strongObjects ||
         this.lazyProperties != lazyProperties || this.references != references)
     {
         return(new GreenModel(this.id, name, version, objects, strongObjects, lazyProperties, references));
     }
     return(this);
 }
        public async Task ModelEvaluationResponseShouldBeCorrect()
        {
            var httpClient = new FkClarifaiHttpClient(
                postResponse: @"
{
    ""status"": {
        ""code"": 10000,
        ""description"": ""Ok""
    },
    ""model_version"": {
        ""id"": ""@versionID"",
        ""created_at"": ""2017-01-01T00:00:00.000000Z"",
        ""status"": {
            ""code"": 21100,
            ""description"": ""Model trained successfully""
        },
        ""active_concept_count"": 2,
        ""metrics"": {
            ""status"": {
                ""code"": 21303,
                ""description"": ""Model is queued for evaluation.""
            }
        },
        ""total_input_count"": 30
    }
}
");
            var client = new ClarifaiClient(httpClient);
            ClarifaiResponse <ModelVersion> response = await client.ModelEvaluation(
                "", "").ExecuteAsync();


            Assert.True(response.IsSuccessful);
            Assert.AreEqual("Ok", response.Status.Description);

            ModelVersion modelVersion = response.Get();

            Assert.AreEqual("@versionID", modelVersion.ID);
            Assert.AreEqual(21100, modelVersion.Status.StatusCode);
            Assert.AreEqual("Model trained successfully", modelVersion.Status.Description);
            Assert.AreEqual(21303, modelVersion.ModelMetricsStatus.StatusCode);
            Assert.AreEqual("Model is queued for evaluation.",
                            modelVersion.ModelMetricsStatus.Description);
            Assert.AreEqual(2, modelVersion.ActiveConceptCount);
            Assert.AreEqual(30, modelVersion.TotalInputCount);
        }
Пример #15
0
        public void GetVersionsWithEdit()
        {
            Assert.That(Records, Is.Empty);

            DateTime localHour = DateTime.Now.TrimToHour();

            AreaValueModel model = new AreaValueModel {
                Area = "ROM", Value = 100, Sample = localHour
            };

            Repository.Add(model);

            AreaValueModel update = new AreaValueModel {
                Id = model.Id, Area = "ROM", Value = 100, Sample = model.Sample.AddMinutes(1)
            };

            Repository.Update(update);

            ModelVersions versions = Repository.GetVersions(model.Id);

            AmplaAuditRecord history = Repository.GetHistory(model.Id);

            Assert.That(versions, Is.Not.Null);
            Assert.That(versions.Versions, Is.Not.Empty);
            Assert.That(versions.Versions.Count, Is.EqualTo(2));

            ModelVersion <AreaValueModel> last    = (ModelVersion <AreaValueModel>)versions.Versions[0];
            ModelVersion <AreaValueModel> current = (ModelVersion <AreaValueModel>)versions.Versions[1];

            Assert.That(last.Display, Is.EqualTo("User created record"));
            Assert.That(last.Model.Id, Is.EqualTo(model.Id));
            Assert.That(last.Model.Area, Is.EqualTo(model.Area));
            Assert.That(last.Model.Sample, Is.EqualTo(model.Sample));
            Assert.That(last.Model.Value, Is.EqualTo(model.Value));

            Assert.That(current.Display, Is.EqualTo("User modified record (Sample Period)"));
            Assert.That(current.Model.Id, Is.EqualTo(update.Id));
            Assert.That(current.Model.Area, Is.EqualTo(update.Area));
            Assert.That(current.Model.Sample, Is.EqualTo(update.Sample));
            Assert.That(current.Model.Value, Is.EqualTo(update.Value));

            Assert.That(history.Changes, Is.Not.Empty);
            Assert.That(history.Changes[0].Fields[0].Name, Is.EqualTo("SampleDateTime"));
        }
Пример #16
0
 private GreenModel(ModelId id,
                    string name,
                    ModelVersion version,
                    ImmutableDictionary <ObjectId, GreenObject> objects,
                    ImmutableList <ObjectId> strongObjects,
                    ImmutableDictionary <ObjectId, ImmutableHashSet <Slot> > lazyProperties,
                    ImmutableDictionary <ObjectId, ImmutableDictionary <ObjectId, ImmutableHashSet <Slot> > > references)
 {
     Debug.Assert(objects != null);
     Debug.Assert(lazyProperties != null);
     Debug.Assert(references != null);
     this.id             = id;
     this.name           = name;
     this.version        = version;
     this.objects        = objects;
     this.strongObjects  = strongObjects;
     this.lazyProperties = lazyProperties;
     this.references     = references;
 }
Пример #17
0
        public void GetVersions_NoChanges()
        {
            Assert.That(Records, Is.Empty);

            AreaValueModel model = new AreaValueModel {
                Area = "ROM", Value = 100
            };

            Repository.Add(model);
            Assert.That(Records.Count, Is.EqualTo(1));

            AmplaRecord record = Repository.FindRecord(model.Id);

            Assert.That(record, Is.Not.Null);

            Assert.That(record.GetValue("Area"), Is.EqualTo(model.Area));
            Assert.That(record.GetValue("Value"), Is.EqualTo(model.Value));
            Assert.That(record.Location, Is.EqualTo(location));
            Assert.That(record.Id, Is.EqualTo(model.Id));

            ModelVersions versions = Repository.GetVersions(model.Id);

            Assert.That(versions, Is.Not.Null);
            Assert.That(versions.Versions, Is.Not.Empty);
            Assert.That(versions.Id, Is.EqualTo(record.Id));
            Assert.That(versions.Location, Is.EqualTo(record.Location));
            Assert.That(versions.Module, Is.EqualTo(record.Module));
            Assert.That(versions.ModelName, Is.EqualTo("Area Value Model"));

            ModelVersion <AreaValueModel> version = (ModelVersion <AreaValueModel>)versions.Versions[0];

            Assert.That(version.Model, Is.Not.Null);
            Assert.That(version.Model.Id, Is.EqualTo(model.Id));
            Assert.That(version.Model.Value, Is.EqualTo(model.Value));
            Assert.That(version.Model.Area, Is.EqualTo(model.Area));

            Assert.That(version.IsCurrentVersion, Is.True);
        }
Пример #18
0
        public void GetVersion_WithChanges()
        {
            Assert.That(Records, Is.Empty);

            DateTime       beforeAdd = DateTime.Now.AddSeconds(-1);
            AreaValueModel model     = new AreaValueModel {
                Area = "ROM", Value = 100
            };

            Repository.Add(model);

            DateTime afterAdd = DateTime.Now.AddSeconds(+1);

            Assert.That(Records.Count, Is.EqualTo(1));

            AmplaRecord record = Repository.FindRecord(model.Id);

            Assert.That(record, Is.Not.Null);

            DateTime beforeUpdate = DateTime.Now.AddSeconds(-1);

            AreaValueModel updated = new AreaValueModel {
                Id = model.Id, Area = "ROM", Value = 200
            };

            DateTime afterUpdate = DateTime.Now.AddSeconds(1);

            Repository.Update(updated);
            record = Repository.FindRecord(model.Id);
            Assert.That(record, Is.Not.Null);

            Assert.That(record.GetValue("Area"), Is.EqualTo(model.Area));
            Assert.That(record.GetValue("Value"), Is.EqualTo(200));
            Assert.That(record.Location, Is.EqualTo(location));
            Assert.That(record.Id, Is.EqualTo(model.Id));

            ModelVersions versions = Repository.GetVersions(model.Id);

            Assert.That(versions, Is.Not.Null);
            Assert.That(versions.Versions, Is.Not.Empty);
            Assert.That(versions.Versions.Count, Is.EqualTo(2));

            ModelVersion <AreaValueModel> last    = (ModelVersion <AreaValueModel>)versions.Versions[0];
            ModelVersion <AreaValueModel> current = (ModelVersion <AreaValueModel>)versions.Versions[1];

            Assert.That(last.Model, Is.Not.Null);
            Assert.That(last.IsCurrentVersion, Is.False);
            Assert.That(last.Model.Id, Is.EqualTo(model.Id));
            Assert.That(last.Model.Value, Is.EqualTo(model.Value));
            Assert.That(last.Model.Area, Is.EqualTo(model.Area));
            Assert.That(last.User, Is.EqualTo("User"));
            Assert.That(last.VersionDate, Is.InRange(beforeAdd, afterAdd));
            Assert.That(last.Version, Is.EqualTo(1));

            Assert.That(current.Model, Is.Not.Null);
            Assert.That(current.IsCurrentVersion, Is.True);
            Assert.That(current.Model.Id, Is.EqualTo(updated.Id));
            Assert.That(current.Model.Value, Is.EqualTo(updated.Value));
            Assert.That(current.Model.Area, Is.EqualTo(updated.Area));
            Assert.That(current.User, Is.EqualTo("User"));
            Assert.That(current.VersionDate, Is.InRange(beforeUpdate, afterUpdate));
            Assert.That(current.Version, Is.EqualTo(2));
        }
Пример #19
0
        private dynamic GetHours(DateTime startDate, DateTime endDate)
        {
            if (ModelVersion.Contains("107"))
            {
                int sMin   = startDate.Minute;
                int sHour  = startDate.Hour;
                int sDay   = startDate.Day;
                int sMonth = startDate.Month;
                int sYear  = startDate.Year - 2000;
                int eMin   = endDate.Minute;
                int eHour  = endDate.Hour;
                int eDay   = endDate.Day;
                int eMonth = endDate.Month;
                int eYear  = endDate.Year - 2000;
                int n      = 0;
                if (sMin == 0)
                {
                    sMin = 30;
                }
                byte[]  bytes = new byte[] { Convert.ToByte(sMin), Convert.ToByte(sHour), Convert.ToByte(sDay), Convert.ToByte(sMonth), Convert.ToByte(sYear), Convert.ToByte(eMin), Convert.ToByte(eHour), Convert.ToByte(eDay), Convert.ToByte(eMonth), Convert.ToByte(eYear) };
                dynamic dt    = Send(MakePackage(0x10, 0x10, 0xff, bytes), 0x10);
                if (!dt.success)
                {
                    return(dt);
                }
                while (n < 3)
                {
                    switch ((int)dt.Body[0])
                    {
                    case 1:
                        log($"Запрос на поиск индексов принят, начат поиск. Повтор запроса через 2 секунды");
                        Thread.Sleep(2000);
                        dt = Send(MakePackage(0x10, 0x10, 0xff, bytes), 0x10);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        break;

                    case 2:
                        log($"Процесс поиска индексов активен, идет поиск. Повтор запроса через 2 секунды");
                        Thread.Sleep(2000);
                        dt = Send(MakePackage(0x10, 0x10, 0xff, bytes), 0x10);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        break;

                    case 3:
                        log($"Найдены более ранние ранние записи");
                        n = 3;
                        break;

                    case 4:
                        log($"Найдены более поздние записи");
                        n = 3;
                        break;

                    case 5:
                        log($"Найдены записи вне диапозона");
                        n = 3;
                        break;

                    case 6:
                        log($"Список пустой");
                        n = 3;
                        break;

                    case 7:
                        log($"Ошибка при работе со списком");
                        n = 3;
                        break;

                    default:
                        n = 3;
                        break;
                    }
                    n++;
                }

                int startIndex = dt.Body[2] << 8 | dt.Body[1];
                int endeIndex  = dt.Body[4] << 8 | dt.Body[3];
                log($"Получен начальный индекс: {startIndex} ");
                log($"Получен конечный индекс: {endeIndex} ");

                log($"Считаем PerfectTime");
                List <DateTime> listPerfectTime = new List <DateTime>();
                DateTime        tmpStart        = startDate;
                listPerfectTime.Add(tmpStart);
                for (int i = 0; tmpStart < endDate; i++)
                {
                    tmpStart = tmpStart.AddMinutes(30);
                    listPerfectTime.Add(tmpStart);
                }

                List <dynamic> listHalfHour = new List <dynamic>();
                List <dynamic> listFullHour = new List <dynamic>();

                dynamic answer = new ExpandoObject();
                answer.success   = true;
                answer.error     = string.Empty;
                answer.errorcode = DeviceError.NO_ERROR;
                answer.records   = new List <dynamic>();

                while (startIndex <= endeIndex)
                {
                    if (cancel())
                    {
                        answer.success   = false;
                        answer.error     = "опрос отменен";
                        answer.errorcode = DeviceError.NO_ERROR;
                        return(answer);
                    }

                    byte    b0            = (byte)(startIndex & 0xFF);
                    byte    b1            = (byte)(startIndex >> 8);
                    byte[]  addBytes      = new byte[] { b0, b1 };
                    dynamic oneHalfRecord = new ExpandoObject();
                    dt = Send(MakePackage(0x0D, 0x10, 0xff, addBytes), 0x0D);
                    if (!dt.success)
                    {
                        return(dt);
                    }

                    DateTime date = new DateTime((int)dt.Body[4] + 2000, (int)dt.Body[3], (int)dt.Body[2], (int)dt.Body[1], (int)dt.Body[0], 0);

                    //double activeEnergy = (double)(dt.Body[6] << 8 | dt.Body[5]) / 5000;
                    //double reactiveEnergy = (double)(dt.Body[8] << 8 | dt.Body[7]) / 5000;

                    double activeEnergy   = (double)BitConverter.ToUInt16(dt.Body, 5) / 5000;
                    double reactiveEnergy = (double)BitConverter.ToUInt16(dt.Body, 7) / 5000;

                    log($"Получена запись с индексом {startIndex}: {date} : активная энергия {activeEnergy} кВт*ч, реактивная энергия {reactiveEnergy} квар*ч");

                    oneHalfRecord.date   = date;
                    oneHalfRecord.valueA = activeEnergy;
                    oneHalfRecord.valueR = reactiveEnergy;
                    listHalfHour.Add(oneHalfRecord);
                    startIndex++;
                }
                //log($"Складываем получасовки");
                for (int i = 0, j = 0; i < listPerfectTime.Count - 1 && j < listHalfHour.Count - 1;)
                {
                    dynamic oneFullRecord = new ExpandoObject();
                    if (listPerfectTime[i] == listHalfHour[j].date && listPerfectTime[i + 1] == listHalfHour[j + 1].date)
                    {
                        if (listHalfHour[j].date.Minute == 30)
                        {
                            oneFullRecord.date   = listHalfHour[j + 1].date;
                            oneFullRecord.valueA = (listHalfHour[j].valueA + listHalfHour[j + 1].valueA) / 2;
                            oneFullRecord.valueR = (listHalfHour[j].valueR + listHalfHour[j + 1].valueR) / 2;
                            oneFullRecord.status = 0;
                            listFullHour.Add(oneFullRecord);
                            j += 2;
                            i += 2;
                        }
                        else
                        {
                            i++; j++;
                        }
                    }
                    else // лезем в журнал вкл. и выкл.
                    {
                        if (listHalfHour[j].date > listPerfectTime[i])
                        {
                            i += 2;
                        }
                        else if (listHalfHour[j].date < listPerfectTime[i])
                        {
                            if (listHalfHour[j].date.Minute == 0)
                            {
                                j++;
                            }
                            else if (listHalfHour[j].date.Minute == 30)
                            {
                                j += 2;
                            }
                        }
                        else if (listHalfHour[j + 1].date > listPerfectTime[i + 1])
                        {
                            i += 2; j++;
                        }
                        if (listPerfectTime[i + 1].Minute == 0)
                        {
                            if (CheckBetween(listPerfectTime[i]))
                            {
                                oneFullRecord.date   = listPerfectTime[i + 1];
                                oneFullRecord.status = 1;
                                listFullHour.Add(oneFullRecord);
                            }
                            else
                            {
                                oneFullRecord.date   = listPerfectTime[i + 1];
                                oneFullRecord.status = 2;
                                listFullHour.Add(oneFullRecord);
                            }
                        }
                    }
                }

                foreach (var item in listFullHour)
                {
                    DateTime dateTime = item.date;
                    dateTime = dateTime.AddHours(-1);
                    if (item.status == 0)
                    {
                        answer.records.Add(MakeHourRecord(hourP, item.valueA, "кВт*ч", dateTime));
                        answer.records.Add(MakeHourRecord(hourQ, item.valueR, "кВт*ч", dateTime));
                        answer.records.Add(MakeHourRecord("Статус", item.status, "", dateTime));
                    }
                    else
                    {
                        answer.records.Add(MakeHourRecord("Статус", item.status, "", dateTime));
                    }
                }
                return(answer);
            }

            if (ModelVersion.Contains("307"))
            {
                int sMin   = startDate.Minute;
                int sHour  = startDate.Hour;
                int sDay   = startDate.Day;
                int sMonth = startDate.Month;
                int sYear  = startDate.Year - 2000;
                int eMin   = endDate.Minute;
                int eHour  = endDate.Hour;
                int eDay   = endDate.Day;
                int eMonth = endDate.Month;
                int eYear  = endDate.Year - 2000;
                int n      = 0;
                if (sMin == 0)
                {
                    sMin = 30;
                }
                byte[]  bytes = new byte[] { Convert.ToByte(sMin), Convert.ToByte(sHour), Convert.ToByte(sDay), Convert.ToByte(sMonth), Convert.ToByte(sYear), Convert.ToByte(eMin), Convert.ToByte(eHour), Convert.ToByte(eDay), Convert.ToByte(eMonth), Convert.ToByte(eYear) };
                dynamic dt    = Send(MakePackage(0x10, 0x10, 0xff, bytes), 0x10);
                if (!dt.success)
                {
                    return(dt);
                }
                while (n < 3)
                {
                    switch ((int)dt.Body[0])
                    {
                    case 1:
                        log($"Запрос на поиск индексов принят, начат поиск. Повтор запроса через 2 секунды");
                        Thread.Sleep(2000);
                        dt = Send(MakePackage(0x10, 0x10, 0xff, bytes), 0x10);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        break;

                    case 2:
                        log($"Процесс поиска индексов активен, идет поиск. Повтор запроса через 2 секунды");
                        Thread.Sleep(2000);
                        dt = Send(MakePackage(0x10, 0x10, 0xff, bytes), 0x10);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        break;

                    case 3:
                        log($"Найдены более ранние ранние записи");
                        n = 3;
                        break;

                    case 4:
                        log($"Найдены более поздние записи");
                        n = 3;
                        break;

                    case 5:
                        log($"Найдены записи вне диапозона");
                        n = 3;
                        break;

                    case 6:
                        log($"Список пустой");
                        n = 3;
                        break;

                    case 7:
                        log($"Ошибка при работе со списком");
                        n = 3;
                        break;

                    default:
                        n = 3;
                        break;
                    }
                    n++;
                }

                int startIndex = dt.Body[2] << 8 | dt.Body[1];
                int endeIndex  = dt.Body[4] << 8 | dt.Body[3];
                log($"Получен начальный индекс: {startIndex} ");
                log($"Получен конечный индекс: {endeIndex} ");

                log($"Считаем PerfectTime");
                List <DateTime> listPerfectTime = new List <DateTime>();
                DateTime        tmpStart        = startDate.AddMinutes(sMin);
                listPerfectTime.Add(tmpStart);
                for (int i = 0; tmpStart < endDate; i++)
                {
                    tmpStart = tmpStart.AddMinutes(30);
                    listPerfectTime.Add(tmpStart);
                }

                List <dynamic> listHalfHour = new List <dynamic>();
                List <dynamic> listFullHour = new List <dynamic>();

                dynamic answer = new ExpandoObject();
                answer.success   = true;
                answer.error     = string.Empty;
                answer.errorcode = DeviceError.NO_ERROR;
                answer.records   = new List <dynamic>();

                int softWareVersion = Int32.Parse(SoftwareVersion);

                if ((softWareVersion >= 300 && softWareVersion <= 399) || (softWareVersion >= 100 && softWareVersion <= 199))
                {
                    while (startIndex <= endeIndex)
                    {
                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        byte    b0            = (byte)(startIndex & 0xFF);
                        byte    b1            = (byte)(startIndex >> 8);
                        byte[]  addBytes      = new byte[] { b0, b1 };
                        dynamic oneHalfRecord = new ExpandoObject();
                        dt = Send(MakePackage(0x0D, 0x10, 0xff, addBytes), 0x0D);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        DateTime date = new DateTime((int)dt.Body[4] + 2000, (int)dt.Body[3], (int)dt.Body[2], (int)dt.Body[1], (int)dt.Body[0], 0);

                        double ActiveEnergy = ConvertFromBcd(dt.Body[5]) * 0.01 + ConvertFromBcd(dt.Body[6]) * 1 + ConvertFromBcd(dt.Body[7]) * 100 + ConvertFromBcd(dt.Body[8]) * 10000;
                        //answer.records.Add(MakeHourRecord("Суммарная активная энергия", ActiveEnergy, "кВт*ч", date));

                        double ReactiveEnergy = ConvertFromBcd(dt.Body[9]) * 0.01 + ConvertFromBcd(dt.Body[10]) * 1 + ConvertFromBcd(dt.Body[11]) * 100 + ConvertFromBcd(dt.Body[12]) * 10000;
                        //answer.records.Add(MakeHourRecord("Суммарная реактивная энергия", ReactiveEnergy, "квар*ч", date));

                        log($"Получена запись с индексом {startIndex}: {date} : активная энергия {ActiveEnergy} кВт*ч : реактивная энергия {ReactiveEnergy} квар*ч");

                        oneHalfRecord.date      = date;
                        oneHalfRecord.valueAct  = ActiveEnergy;
                        oneHalfRecord.valueReac = ReactiveEnergy;
                        listHalfHour.Add(oneHalfRecord);
                        startIndex++;
                    }
                    //log($"Складываем получасовки");
                    for (int i = 0, j = 0; i < listPerfectTime.Count - 1 && j < listHalfHour.Count - 1;)
                    {
                        dynamic oneFullRecord = new ExpandoObject();
                        if (listPerfectTime[i] == listHalfHour[j].date && listPerfectTime[i + 1] == listHalfHour[j + 1].date)
                        {
                            if (listHalfHour[j].date.Minute == 30)
                            {
                                oneFullRecord.date      = listHalfHour[j + 1].date;
                                oneFullRecord.valueAct  = (listHalfHour[j].valueAct + listHalfHour[j + 1].valueAct()) / 2;
                                oneFullRecord.valueReac = listHalfHour[j].valueReac + listHalfHour[j + 1].valueReac;
                                oneFullRecord.status    = 0;
                                listFullHour.Add(oneFullRecord);
                                j += 2;
                                i += 2;
                            }
                            else
                            {
                                i++; j++;
                            }
                        }
                        else // лезем в журнал вкл. и выкл.
                        {
                            if (listHalfHour[j].date > listPerfectTime[i])
                            {
                                i += 2;
                            }
                            else if (listHalfHour[j].date < listPerfectTime[i])
                            {
                                if (listHalfHour[j].date.Minute == 00)
                                {
                                    j++;
                                }
                                else if (listHalfHour[j].date.Minute == 30)
                                {
                                    j += 2;
                                }
                            }
                            else if (listHalfHour[j + 1].date > listPerfectTime[i + 1])
                            {
                                i += 2; j++;
                            }
                            if (listPerfectTime[i + 1].Minute == 0)
                            {
                                if (CheckBetween(listPerfectTime[i]))
                                {
                                    oneFullRecord.date   = listPerfectTime[i + 1];
                                    oneFullRecord.status = 1;
                                    listFullHour.Add(oneFullRecord);
                                }
                                else
                                {
                                    oneFullRecord.date   = listPerfectTime[i + 1];
                                    oneFullRecord.status = 2;
                                    listFullHour.Add(oneFullRecord);
                                }
                            }
                        }
                    }

                    foreach (var item in listFullHour)
                    {
                        DateTime dateTime = item.date;
                        dateTime = dateTime.AddHours(-1);
                        if (item.status == 0)
                        {
                            answer.records.Add(MakeHourRecord(hourP, item.valueAct, "кВт*ч", dateTime));
                            answer.records.Add(MakeHourRecord(hourQ, item.valueReac, "квар*ч", dateTime));
                            answer.records.Add(MakeHourRecord("Статус", item.status, "", dateTime));
                        }
                        else
                        {
                            answer.records.Add(MakeHourRecord("Статус", item.status, "", dateTime));
                        }
                    }
                    return(answer);
                }
                else if ((softWareVersion >= 400 && softWareVersion <= 499) || (softWareVersion >= 200 && softWareVersion <= 299))
                {
                    while (startIndex <= endeIndex)
                    {
                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        byte    b0            = (byte)(startIndex & 0xFF);
                        byte    b1            = (byte)(startIndex >> 8);
                        byte[]  addBytes      = new byte[] { b0, b1 };
                        dynamic oneHalfRecord = new ExpandoObject();
                        dt = Send(MakePackage(0x0D, 0x10, 0xff, addBytes), 0x0D);
                        if (!dt.success)
                        {
                            return(dt);
                        }

                        DateTime date = new DateTime((int)dt.Body[4] + 2000, (int)dt.Body[3], (int)dt.Body[2], (int)dt.Body[1], (int)dt.Body[0], 0);

                        double ImpActiveEnergy = ConvertFromBcd(dt.Body[6]) * 0.01 + ConvertFromBcd(dt.Body[7]) * 1 + ConvertFromBcd(dt.Body[8]) * 100 + ConvertFromBcd(dt.Body[9]) * 10000;
                        log($"Получена запись с индексом {startIndex}: {date} : Суммарная импортируемая активная энергия {ImpActiveEnergy}");
                        //double ExpActiveEnergy = ConvertFromBcd(dt.Body[10]) * 0.01 + ConvertFromBcd(dt.Body[11]) * 1 + ConvertFromBcd(dt.Body[12]) * 100 + ConvertFromBcd(dt.Body[13]) * 10000;
                        double ImpReactiveEnergy = ConvertFromBcd(dt.Body[14]) * 0.01 + ConvertFromBcd(dt.Body[15]) * 1 + ConvertFromBcd(dt.Body[16]) * 100 + ConvertFromBcd(dt.Body[17]) * 10000;
                        //double ExpReactiveEnergy = ConvertFromBcd(dt.Body[18]) * 0.01 + ConvertFromBcd(dt.Body[19]) * 1 + ConvertFromBcd(dt.Body[20]) * 100 + ConvertFromBcd(dt.Body[21]) * 10000;

                        oneHalfRecord.date    = date;
                        oneHalfRecord.valuePI = ImpActiveEnergy;
                        //oneHalfRecord.valuePE = ExpActiveEnergy;
                        oneHalfRecord.valueQI = ImpReactiveEnergy;
                        //oneHalfRecord.valueQE = ExpReactiveEnergy;
                        listHalfHour.Add(oneHalfRecord);
                        startIndex++;
                    }
                    //log($"Складываем получасовки");
                    for (int i = 0, j = 0; i < listPerfectTime.Count - 1 && j < listHalfHour.Count - 1;)
                    {
                        dynamic oneFullRecord = new ExpandoObject();
                        if (listPerfectTime[i] == listHalfHour[j].date && listPerfectTime[i + 1] == listHalfHour[j + 1].date)
                        {
                            if (listHalfHour[j].date.Minute == 30)
                            {
                                oneFullRecord.date    = listHalfHour[j + 1].date;
                                oneFullRecord.valuePI = (listHalfHour[j].valuePI + listHalfHour[j + 1].valuePI) / 2;
                                //oneFullRecord.valuePE = listHalfHour[j].valuePE + listHalfHour[j + 1].valuePE;
                                oneFullRecord.valueQI = listHalfHour[j].valueQI + listHalfHour[j + 1].valueQI;
                                // oneFullRecord.valueQE = listHalfHour[j].valueQE + listHalfHour[j + 1].valueQE;
                                oneFullRecord.status = 0;
                                listFullHour.Add(oneFullRecord);
                                j += 2;
                                i += 2;
                            }
                            else
                            {
                                i++; j++;
                            }
                        }
                        else // лезем в журнал вкл. и выкл.
                        {
                            if (listHalfHour[j].date > listPerfectTime[i])
                            {
                                i += 2;
                            }
                            else if (listHalfHour[j].date < listPerfectTime[i])
                            {
                                if (listHalfHour[j].date == 00)
                                {
                                    j++;
                                }
                                else if (listHalfHour[j].date == 30)
                                {
                                    j += 2;
                                }
                            }
                            else if (listHalfHour[j + 1].date > listPerfectTime[i + 1])
                            {
                                i += 2; j++;
                            }
                            if (listPerfectTime[i + 1].Minute == 0)
                            {
                                if (CheckBetween(listPerfectTime[i]))
                                {
                                    oneFullRecord.date   = listPerfectTime[i + 1];
                                    oneFullRecord.status = 1;
                                    listFullHour.Add(oneFullRecord);
                                }
                                else
                                {
                                    oneFullRecord.date   = listPerfectTime[i + 1];
                                    oneFullRecord.status = 2;
                                    listFullHour.Add(oneFullRecord);
                                }
                            }
                        }
                    }

                    foreach (var item in listFullHour)
                    {
                        DateTime dateTime = item.date;
                        dateTime = dateTime.AddHours(-1);

                        if (item.status == 0)
                        {
                            answer.records.Add(MakeHourRecord(hourP, item.valuePI, "кВт*ч", dateTime));
                            //answer.records.Add(MakeHourRecord("P-", item.valuePE, "кВт*ч", dateTime));
                            answer.records.Add(MakeHourRecord(hourQ, item.valueQI, "квар*ч", dateTime));
                            //answer.records.Add(MakeHourRecord("Q-", item.valueQE, "квар*ч", dateTime));
                            answer.records.Add(MakeHourRecord("Статус", item.status, "", dateTime));
                        }
                        else
                        {
                            answer.records.Add(MakeHourRecord("Статус", item.status, "", dateTime));
                        }
                    }
                    return(answer);
                }
                else
                {
                    log($"Для модели счетичика  {ModelVersion} с версией прошивки {SoftwareVersion} чтение часовых не реализовано");
                }
            }
            dynamic ans = new ExpandoObject();

            ans.success   = false;
            ans.error     = "для данной прошивки чтение часовых не реализовано";
            ans.errorcode = DeviceError.NO_ANSWER;
            return(ans);
        }
Пример #20
0
        private dynamic GetCurrent()
        {
            DateTime dateNow = DateTime.Now;

            if (ModelVersion.Contains("107"))
            {
                dynamic answer = new ExpandoObject();
                dynamic dt     = Send(MakePackage(0x01, 0x04, 0xff), 0x01);
                if (!dt.success)
                {
                    log($"Не удалось прочитать: Энергия активная суммарная");
                }
                else
                {
                    answer.success   = true;
                    answer.error     = string.Empty;
                    answer.errorcode = DeviceError.NO_ERROR;
                    answer.records   = new List <dynamic>();

                    if (cancel())
                    {
                        answer.success   = false;
                        answer.error     = "опрос отменен";
                        answer.errorcode = DeviceError.NO_ERROR;
                        return(answer);
                    }

                    double sumActiveTarifs = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                    log($"Энергия активная суммарная: {sumActiveTarifs} кВт*ч");
                    answer.records.Add(MakeCurrentRecord("Энергия активная суммарная", sumActiveTarifs, "кВт*ч", dateNow));
                    double indication = sumActiveTarifs;
                    setIndicationForRowCache(indication, "кВт*ч", dateNow);
                }

                if (cancel())
                {
                    answer.success   = false;
                    answer.error     = "опрос отменен";
                    answer.errorcode = DeviceError.NO_ERROR;
                    return(answer);
                }



                for (int i = 1; i <= 2; i++)
                {
                    dt = Send(MakePackage(0x01, (byte)(i + 4), 0xff), 0x01);
                    if (!dt.success)
                    {
                        log($"Не удалось прочитать: Энергия активная по тарифу {i}");
                    }
                    else
                    {
                        double activeTarif = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия активная по тарифу {i}: {activeTarif} кВт*ч");
                        answer.records.Add(MakeCurrentRecord($"Энергия активная по тарифу {i}", activeTarif, "кВт*ч", dateNow));
                    }
                }

                if (cancel())
                {
                    answer.success   = false;
                    answer.error     = "опрос отменен";
                    answer.errorcode = DeviceError.NO_ERROR;
                    return(answer);
                }

                dt = Send(MakePackage(0x01, 0x48, 0xff), 0x01);
                if (!dt.success)
                {
                    log($"Не удалось прочитать: Энергия реактивная суммарная");
                }
                else
                {
                    double sumReactiveTarifs = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                    log($"Энергия реактивная суммарная: {sumReactiveTarifs} квар*ч");
                    answer.records.Add(MakeCurrentRecord("Энергия реактивная суммарная", sumReactiveTarifs, "кВт*ч", dateNow));
                }

                if (cancel())
                {
                    answer.success   = false;
                    answer.error     = "опрос отменен";
                    answer.errorcode = DeviceError.NO_ERROR;
                    return(answer);
                }

                for (int i = 1; i <= 2; i++)
                {
                    dt = Send(MakePackage(0x01, (byte)(73 + i), 0xff), 0x01);
                    if (!dt.success)
                    {
                        log($"Не удалось прочитать: Энергия реактивная по тарифу {i}");
                    }
                    else
                    {
                        double reactiveTarif = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия реактивная по тарифу {i}: {reactiveTarif} квар*ч");
                        answer.records.Add(MakeCurrentRecord($"Энергия реактивная по тарифу {i}", reactiveTarif, "кВт*ч", dateNow));
                    }
                }

                if (cancel())
                {
                    answer.success   = false;
                    answer.error     = "опрос отменен";
                    answer.errorcode = DeviceError.NO_ERROR;
                    return(answer);
                }

                dt = Send(MakePackage(0x01, 0x03, 0xff), 0x01);

                double activePower = (dt.Body[3] << 24 | dt.Body[2] << 16 | dt.Body[1] << 8 | dt.Body[0]) * 0.001;
                log($"Активная мощность: {activePower} Вт");
                answer.records.Add(MakeCurrentRecord("Активная мощность", activePower, "Вт", dateNow));

                return(answer);
            }
            else if (ModelVersion.Contains("307"))
            {
                if (Int32.TryParse(SoftwareVersion, out int softWareVersion))
                {
                    if (softWareVersion == 124)
                    {
                        dynamic dt = Send(MakePackage(0x01, 0x76, 0xff), 0x01);

                        dynamic answer = new ExpandoObject();
                        answer.success   = true;
                        answer.error     = string.Empty;
                        answer.errorcode = DeviceError.NO_ERROR;
                        answer.records   = new List <dynamic>();

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        double sumActiveImp = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия активная импортируемая суммарная: {sumActiveImp} кВт*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия активная импортируемая суммарная", sumActiveImp, "кВт*ч", dateNow));
                        dt = Send(MakePackage(0x01, 0x95, 0xff), 0x01);

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        double sumActiveExp = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия активная экспортируемая суммарная: {sumActiveExp} кВт*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия активная экспортируемая суммарная", sumActiveExp, "кВт*ч", dateNow));

                        dt = Send(MakePackage(0x01, 0x7F, 0xff), 0x01);

                        double sumReactiveImp = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия реактивная импортируемая суммарная: {sumReactiveImp} квар*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия реактивная импортируемая суммарная", sumReactiveImp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x9F, 0xff), 0x01);

                        double sumReactiveExp = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия реактивная экспортируемая суммарная: {sumReactiveExp} квар*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия реактивная экспортируемая суммарная", sumReactiveExp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x6d, 0xff), 0x01);

                        double activePower = (dt.Body[3] << 24 | dt.Body[2] << 16 | dt.Body[1] << 8 | dt.Body[0]) * 0.01;
                        log($"Активная мощность суммарная: {activePower} Вт");
                        answer.records.Add(MakeCurrentRecord("Активная мощность суммарная", activePower, "Вт", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x71, 0xff), 0x01);

                        double reactivePower = (dt.Body[3] << 24 | dt.Body[2] << 16 | dt.Body[1] << 8 | dt.Body[0]) * 0.01;
                        log($"Реактивная мощность суммарная: {reactivePower} Вт");
                        answer.records.Add(MakeCurrentRecord("Реактивная мощность суммарная", reactivePower, "Вт", dateNow));

                        double indication = sumActiveImp;
                        setIndicationForRowCache(indication, "кВт*ч", dateNow);
                        return(answer);
                    }
                    else if (softWareVersion == 123)
                    {
                        dynamic dt = Send(MakePackage(0x01, 0x76, 0xff), 0x01);

                        dynamic answer = new ExpandoObject();
                        answer.success   = true;
                        answer.error     = string.Empty;
                        answer.errorcode = DeviceError.NO_ERROR;
                        answer.records   = new List <dynamic>();

                        double sumActiveImp = ConvertFromBcd(dt.Body[0]) * 0.001 + ConvertFromBcd(dt.Body[1]) * 0.1 + ConvertFromBcd(dt.Body[2]) * 10 + ConvertFromBcd(dt.Body[3]) * 1000;
                        log($"Энергия активная импортируемая суммарная: {sumActiveImp} кВт*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия активная импортируемая суммарная", sumActiveImp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x95, 0xff), 0x01);
                        double sumActiveExp = ConvertFromBcd(dt.Body[0]) * 0.001 + ConvertFromBcd(dt.Body[1]) * 0.1 + ConvertFromBcd(dt.Body[2]) * 10 + ConvertFromBcd(dt.Body[3]) * 1000;
                        log($"Энергия активная экспортируемая суммарная: {sumActiveExp} кВт*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия активная экспортируемая суммарная", sumActiveExp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x7F, 0xff), 0x01);
                        double sumReactiveImp = ConvertFromBcd(dt.Body[0]) * 0.001 + ConvertFromBcd(dt.Body[1]) * 0.1 + ConvertFromBcd(dt.Body[2]) * 10 + ConvertFromBcd(dt.Body[3]) * 1000;
                        log($"Энергия реактивная импортируемая суммарная: {sumReactiveImp} квар*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия реактивная импортируемая суммарная", sumReactiveImp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x9F, 0xff), 0x01);
                        double sumReactiveExp = ConvertFromBcd(dt.Body[0]) * 0.001 + ConvertFromBcd(dt.Body[1]) * 0.1 + ConvertFromBcd(dt.Body[2]) * 10 + ConvertFromBcd(dt.Body[3]) * 1000;
                        log($"Энергия реактивная экспортируемая суммарная: {sumReactiveExp} квар*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия реактивная экспортируемая суммарная", sumReactiveExp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x6d, 0xff), 0x01);
                        double activePower = (dt.Body[3] << 24 | dt.Body[2] << 16 | dt.Body[1] << 8 | dt.Body[0]) * 0.01;
                        log($"Активная мощность суммарная: {activePower} Вт");
                        answer.records.Add(MakeCurrentRecord("Активная мощность суммарная", activePower, "Вт", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x71, 0xff), 0x01);
                        double reactivePower = (dt.Body[3] << 24 | dt.Body[2] << 16 | dt.Body[1] << 8 | dt.Body[0]) * 0.01;
                        log($"Реактивная мощность суммарная: {reactivePower} Вт");
                        answer.records.Add(MakeCurrentRecord("Реактивная мощность суммарная", reactivePower, "Вт", dateNow));

                        double indication = sumActiveImp;
                        setIndicationForRowCache(indication, "кВт*ч", dateNow);
                        return(answer);
                    }
                    else if (softWareVersion >= 300 && softWareVersion <= 399)
                    {
                        dynamic dt = Send(MakePackage(0x01, 0x76, 0xff), 0x01);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        dynamic answer = new ExpandoObject();
                        answer.success   = true;
                        answer.error     = string.Empty;
                        answer.errorcode = DeviceError.NO_ERROR;
                        answer.records   = new List <dynamic>();

                        double sumActiveImp = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия активная импортируемая суммарная: {sumActiveImp} кВт*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия активная импортируемая суммарная", sumActiveImp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x95, 0xff), 0x01);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        double sumActiveExp = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия активная экспортируемая суммарная: {sumActiveExp} кВт*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия активная экспортируемая суммарная", sumActiveExp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x7F, 0xff), 0x01);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        double sumReactiveImp = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия реактивная импортируемая суммарная: {sumReactiveImp} квар*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия реактивная импортируемая суммарная", sumReactiveImp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x9F, 0xff), 0x01);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        double sumReactiveExp = ConvertFromBcd(dt.Body[0]) * 0.01 + ConvertFromBcd(dt.Body[1]) * 1 + ConvertFromBcd(dt.Body[2]) * 100 + ConvertFromBcd(dt.Body[3]) * 10000;
                        log($"Энергия реактивная экспортируемая суммарная: {sumReactiveExp} квар*ч");
                        answer.records.Add(MakeCurrentRecord("Энергия реактивная экспортируемая суммарная", sumReactiveExp, "кВт*ч", dateNow));

                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        dt = Send(MakePackage(0x01, 0x6d, 0xff), 0x01);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        double activePower = (dt.Body[3] << 24 | dt.Body[2] << 16 | dt.Body[1] << 8 | dt.Body[0]) * 0.01;
                        log($"Активная мощность суммарная: {activePower} Вт");
                        answer.records.Add(MakeCurrentRecord("Активная мощность суммарная", activePower, "Вт", dateNow));

                        dt = Send(MakePackage(0x01, 0x71, 0xff), 0x01);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        double reactivePower = (dt.Body[3] << 24 | dt.Body[2] << 16 | dt.Body[1] << 8 | dt.Body[0]) * 0.01;
                        log($"Реактивная мощность суммарная: {reactivePower} Вт");
                        answer.records.Add(MakeCurrentRecord("Реактивная мощность суммарная", reactivePower, "Вт", dateNow));

                        double indication = sumActiveImp;
                        setIndicationForRowCache(indication, "кВт*ч", dateNow);
                        return(answer);
                    }
                    dynamic ans1 = new ExpandoObject();
                    ans1.success   = false;
                    ans1.error     = "для данной прошивки чтение часовых не реализовано";
                    ans1.errorcode = DeviceError.NO_ANSWER;
                    return(ans1);
                }
                dynamic ans2 = new ExpandoObject();
                ans2.success   = false;
                ans2.error     = "не удалось прочитать версию прошивки";
                ans2.errorcode = DeviceError.NO_ANSWER;
                return(ans2);
            }
            dynamic ans3 = new ExpandoObject();

            ans3.success   = false;
            ans3.error     = "нет ответа";
            ans3.errorcode = DeviceError.NO_ANSWER;
            return(ans3);
        }
Пример #21
0
        public void BindWithEmptyOriginalValue_double()
        {
            AmplaRecord amplaRecord = new AmplaRecord(100)
            {
                Location = location, Module = module, ModelName = ""
            };

            amplaRecord.AddColumn("Value", typeof(double));
            amplaRecord.AddColumn("Area", typeof(string));
            amplaRecord.SetValue("Value", "100.0");
            amplaRecord.SetValue("Area", "ROM");

            AmplaAuditRecord auditRecord = new AmplaAuditRecord
            {
                Id       = amplaRecord.Id,
                Location = amplaRecord.Location,
                Module   = amplaRecord.Module,
                Changes  = new List <AmplaAuditSession>
                {
                    new AmplaAuditSession("User", DateTime.Today)
                }
            };

            auditRecord.Changes[0].Fields.Add(new AmplaAuditField
            {
                Name          = "Value",
                OriginalValue = "",
                EditedValue   = "100"
            });

            AreaValueModel model = new AreaValueModel {
                Id = 100, Area = "ROM", Value = 100.0d
            };
            ModelVersions modelVersions = new ModelVersions(amplaRecord);
            IModelProperties <AreaValueModel> modelProperties = new ModelProperties <AreaValueModel>();

            AmplaViewProperties <AreaValueModel> viewProperties = new AmplaViewProperties <AreaValueModel>(modelProperties);
            GetViewsResponse view = new GetViewsResponse
            {
                Context = new GetViewsResponseContext(),
                Views   = new[] { ProductionViews.AreaValueModelView() }
            };

            viewProperties.Initialise(view);
            AmplaGetDataVersionsBinding <AreaValueModel> binding =
                new AmplaGetDataVersionsBinding <AreaValueModel>(amplaRecord, auditRecord, model, modelVersions,
                                                                 modelProperties, viewProperties);

            Assert.That(binding.Validate(), Is.True);
            Assert.That(binding.Bind(), Is.True);

            Assert.That(modelVersions.Versions, Is.Not.Empty);
            Assert.That(modelVersions.Versions.Count, Is.EqualTo(2));

            ModelVersion <AreaValueModel> last    = (ModelVersion <AreaValueModel>)modelVersions.Versions[0];
            ModelVersion <AreaValueModel> current = (ModelVersion <AreaValueModel>)modelVersions.Versions[1];

            Assert.That(last.IsCurrentVersion, Is.False);
            Assert.That(current.IsCurrentVersion, Is.True);

            Assert.That(last.Model.Area, Is.EqualTo(model.Area));
            Assert.That(current.Model.Area, Is.EqualTo(model.Area));

            Assert.That(last.Model.Value, Is.EqualTo(0d));
            Assert.That(current.Model.Value, Is.EqualTo(100d));

            Assert.That(last.Model.Id, Is.EqualTo(100));
            Assert.That(current.Model.Id, Is.EqualTo(100));
        }
Пример #22
0
        private dynamic GetDays(DateTime startDate, DateTime endDate)
        {
            if (ModelVersion.Contains("107"))
            {
                int     sHour  = startDate.Hour;
                int     sDay   = startDate.Day;
                int     sMonth = startDate.Month;
                int     sYear  = startDate.Year - 2000;
                int     eHour  = endDate.Hour;
                int     eDay   = endDate.Day;
                int     eMonth = endDate.Month;
                int     eYear  = endDate.Year - 2000;
                int     n      = 0;
                byte[]  bytes  = new byte[] { 0, Convert.ToByte(sHour), Convert.ToByte(sDay), Convert.ToByte(sMonth), Convert.ToByte(sYear), 0, Convert.ToByte(eHour), Convert.ToByte(eDay), Convert.ToByte(eMonth), Convert.ToByte(eYear) };
                dynamic dt     = Send(MakePackage(0x10, 0x42, 0xff, bytes), 0x10);
                if (!dt.success)
                {
                    return(dt);
                }
                while (n < 3)
                {
                    switch ((int)dt.Body[0])
                    {
                    case 1:
                        log($"Запрос на поиск индексов принят, начат поиск. Повтор запроса через 2 секунды");
                        Thread.Sleep(2000);
                        dt = Send(MakePackage(0x10, 0x42, 0xff, bytes), 0x10);
                        break;

                    case 2:
                        log($"Процесс поиска индексов активен, идет поиск. Повтор запроса через 2 секунды");
                        Thread.Sleep(2000);
                        dt = Send(MakePackage(0x10, 0x42, 0xff, bytes), 0x10);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        break;

                    case 3:
                        log($"Найдены более ранние ранние записи");
                        n = 3;
                        break;

                    case 4:
                        log($"Найдены более поздние записи");
                        n = 3;
                        break;

                    case 5:
                        log($"Найдены записи вне диапозона");
                        n = 3;
                        break;

                    case 6:
                        log($"Список пустой");
                        n = 3;
                        break;

                    case 7:
                        log($"Ошибка при работе со списком");
                        n = 3;
                        break;

                    default:
                        n = 3;
                        break;
                    }
                    n++;
                }

                int startIndex = dt.Body[2] << 8 | dt.Body[1];
                int endeIndex  = dt.Body[4] << 8 | dt.Body[3];
                log($"Получен начальный индекс: {startIndex} ");
                log($"Получен конечный индекс: {endeIndex} ");

                dynamic answer = new ExpandoObject();
                answer.success   = true;
                answer.error     = string.Empty;
                answer.errorcode = DeviceError.NO_ERROR;
                answer.records   = new List <dynamic>();


                while (startIndex <= endeIndex)
                {
                    if (cancel())
                    {
                        answer.success   = false;
                        answer.error     = "опрос отменен";
                        answer.errorcode = DeviceError.NO_ERROR;
                        return(answer);
                    }

                    byte   b0       = (byte)(startIndex & 0xFF);
                    byte   b1       = (byte)(startIndex >> 8);
                    byte[] addBytes = new byte[] { b0, b1 };
                    dt = Send(MakePackage(0x0C, 0x42, 0xff, addBytes), 0x0C);
                    if (!dt.success)
                    {
                        continue;
                    }
                    DateTime date1 = new DateTime((int)dt.Body[5] + 2000, (int)dt.Body[4], (int)dt.Body[3], (int)dt.Body[2], (int)dt.Body[1], 0);
                    DateTime date  = date1.AddDays(-1);

                    double sumActiveEnergy = ConvertFromBcd(dt.Body[6]) * 0.01 + ConvertFromBcd(dt.Body[7]) * 1 + ConvertFromBcd(dt.Body[8]) * 100 + ConvertFromBcd(dt.Body[9]) * 10000;
                    answer.records.Add(MakeDayRecord(dayP, sumActiveEnergy, "кВт*ч", date));

                    for (int i = 1; i <= 4; i++)
                    {
                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        double ActiveEnergy = ConvertFromBcd(dt.Body[6 + i * 4]) * 0.01 + ConvertFromBcd(dt.Body[7 + i * 4]) * 1 + ConvertFromBcd(dt.Body[8 + i * 4]) * 100 + ConvertFromBcd(dt.Body[9 + i * 4]) * 10000;
                        answer.records.Add(MakeDayRecord(dayArrP[i - 1], ActiveEnergy, "кВт*ч", date));
                        //log($"индекс {i}: {ActiveEnergy}");
                    }

                    double sumReactiveEnergy = ConvertFromBcd(dt.Body[26]) * 0.01 + ConvertFromBcd(dt.Body[27]) * 1 + ConvertFromBcd(dt.Body[28]) * 100 + ConvertFromBcd(dt.Body[29]) * 10000;
                    answer.records.Add(MakeDayRecord(dayQ, sumReactiveEnergy, "квар*ч", date));

                    log($"Получена запись с индексом {startIndex}: {date} : активная энергия {sumActiveEnergy} кВт*ч, реактивная энергия {sumReactiveEnergy} квар*ч");

                    for (int i = 1; i <= 4; i++)
                    {
                        if (cancel())
                        {
                            answer.success   = false;
                            answer.error     = "опрос отменен";
                            answer.errorcode = DeviceError.NO_ERROR;
                            return(answer);
                        }

                        double ReactiveEnergy = ConvertFromBcd(dt.Body[26 + i * 4]) * 0.01 + ConvertFromBcd(dt.Body[27 + i * 4]) * 1 + ConvertFromBcd(dt.Body[28 + i * 4]) * 100 + ConvertFromBcd(dt.Body[29 + i * 4]) * 10000;
                        answer.records.Add(MakeDayRecord(dayArrQ[i - 1], ReactiveEnergy, "квар*ч", date));
                    }

                    startIndex++;
                }
                return(answer);
            }
            if (ModelVersion.Contains("307"))
            {
                int     sHour  = startDate.Hour;
                int     sDay   = startDate.Day;
                int     sMonth = startDate.Month;
                int     sYear  = startDate.Year - 2000;
                int     eHour  = endDate.Hour;
                int     eDay   = endDate.Day;
                int     eMonth = endDate.Month;
                int     eYear  = endDate.Year - 2000;
                int     n      = 0;
                byte[]  bytes  = new byte[] { 0, Convert.ToByte(sHour), Convert.ToByte(sDay), Convert.ToByte(sMonth), Convert.ToByte(sYear), 0, Convert.ToByte(eHour), Convert.ToByte(eDay), Convert.ToByte(eMonth), Convert.ToByte(eYear) };
                dynamic dt     = Send(MakePackage(0x10, 0x42, 0xff, bytes), 0x10);
                if (!dt.success)
                {
                    return(dt);
                }
                while (n < 3)
                {
                    switch ((int)dt.Body[0])
                    {
                    case 1:
                        log($"Запрос на поиск индексов принят, начат поиск. Повтор запроса через 2 секунды");
                        Thread.Sleep(2000);
                        dt = Send(MakePackage(0x10, 0x42, 0xff, bytes), 0x10);
                        break;

                    case 2:
                        log($"Процесс поиска индексов активен, идет поиск. Повтор запроса через 2 секунды");
                        Thread.Sleep(2000);
                        dt = Send(MakePackage(0x10, 0x42, 0xff, bytes), 0x10);
                        if (!dt.success)
                        {
                            return(dt);
                        }
                        break;

                    case 3:
                        log($"Найдены более ранние ранние записи");
                        n = 3;
                        break;

                    case 4:
                        log($"Найдены более поздние записи");
                        n = 3;
                        break;

                    case 5:
                        log($"Найдены записи вне диапозона");
                        n = 3;
                        break;

                    case 6:
                        log($"Список пустой");
                        n = 3;
                        break;

                    case 7:
                        log($"Ошибка при работе со списком");
                        n = 3;
                        break;

                    default:
                        n = 3;
                        break;
                    }
                    n++;
                }

                int startIndex = dt.Body[2] << 8 | dt.Body[1];
                int endeIndex  = dt.Body[4] << 8 | dt.Body[3];
                log($"Получен начальный индекс: {startIndex} ");
                log($"Получен конечный индекс: {endeIndex} ");

                dynamic answer = new ExpandoObject();
                answer.success   = true;
                answer.error     = string.Empty;
                answer.errorcode = DeviceError.NO_ERROR;
                answer.records   = new List <dynamic>();


                while (startIndex <= endeIndex)
                {
                    if (cancel())
                    {
                        answer.success   = false;
                        answer.error     = "опрос отменен";
                        answer.errorcode = DeviceError.NO_ERROR;
                        return(answer);
                    }

                    byte   b0       = (byte)(startIndex & 0xFF);
                    byte   b1       = (byte)(startIndex >> 8);
                    byte[] addBytes = new byte[] { b0, b1 };
                    dt = Send(MakePackage(0x0C, 0x42, 0xff, addBytes), 0x0C);
                    if (!dt.success)
                    {
                        continue;
                    }
                    DateTime date1 = new DateTime((int)dt.Body[5] + 2000, (int)dt.Body[4], (int)dt.Body[3], (int)dt.Body[2], (int)dt.Body[1], 0);
                    DateTime date  = date1.AddDays(-1);

                    if (Int32.TryParse(SoftwareVersion, out int softWareVersion))
                    {
                        if ((softWareVersion == 124) || (softWareVersion >= 300 && softWareVersion <= 399))
                        {
                            double sumActiveEnergy = ConvertFromBcd(dt.Body[6]) * 0.01 + ConvertFromBcd(dt.Body[7]) * 1 + ConvertFromBcd(dt.Body[8]) * 100 + ConvertFromBcd(dt.Body[9]) * 10000;
                            answer.records.Add(MakeDayRecord("EnergyP+ (сумма тарифов)", sumActiveEnergy, "кВт*ч", date));
                            for (int i = 1; i <= 4; i++)
                            {
                                if (cancel())
                                {
                                    answer.success   = false;
                                    answer.error     = "опрос отменен";
                                    answer.errorcode = DeviceError.NO_ERROR;
                                    return(answer);
                                }

                                double ActiveEnergy = ConvertFromBcd(dt.Body[6 + i * 4]) * 0.01 + ConvertFromBcd(dt.Body[7 + i * 4]) * 1 + ConvertFromBcd(dt.Body[8 + i * 4]) * 100 + ConvertFromBcd(dt.Body[9 + i * 4]) * 10000;
                                answer.records.Add(MakeDayRecord($"EnergyP+ (тариф {i})", ActiveEnergy, "кВт*ч", date));
                                //log($"индекс {i}: {ActiveEnergy}");
                            }

                            double sumReactiveEnergy = ConvertFromBcd(dt.Body[42]) * 0.01 + ConvertFromBcd(dt.Body[43]) * 1 + ConvertFromBcd(dt.Body[44]) * 100 + ConvertFromBcd(dt.Body[45]) * 10000;
                            answer.records.Add(MakeDayRecord("EnergyQ+ (сумма тарифов)", sumReactiveEnergy, "квар*ч", date));
                            log($"Получена запись с индексом {startIndex}: {date} : активная энергия {sumActiveEnergy} кВт*ч, реактивная энергия {sumReactiveEnergy} квар*ч");
                            for (int i = 1; i <= 4; i++)
                            {
                                if (cancel())
                                {
                                    answer.success   = false;
                                    answer.error     = "опрос отменен";
                                    answer.errorcode = DeviceError.NO_ERROR;
                                    return(answer);
                                }

                                double ReactiveEnergy = ConvertFromBcd(dt.Body[42 + i * 4]) * 0.01 + ConvertFromBcd(dt.Body[43 + i * 4]) * 1 + ConvertFromBcd(dt.Body[44 + i * 4]) * 100 + ConvertFromBcd(dt.Body[45 + i * 4]) * 10000;
                                answer.records.Add(MakeDayRecord($"EnergyQ+ (тариф {i})", ReactiveEnergy, "квар*ч", date));
                            }

                            startIndex++;
                        }
                        else if (softWareVersion == 123)
                        {
                            double sumActiveEnergy = ConvertFromBcd(dt.Body[6]) * 0.001 + ConvertFromBcd(dt.Body[7]) * 0.1 + ConvertFromBcd(dt.Body[8]) * 10 + ConvertFromBcd(dt.Body[9]) * 1000;
                            answer.records.Add(MakeDayRecord("EnergyP+ (сумма тарифов)", sumActiveEnergy, "кВт*ч", date));
                            for (int i = 1; i <= 4; i++)
                            {
                                if (cancel())
                                {
                                    answer.success   = false;
                                    answer.error     = "опрос отменен";
                                    answer.errorcode = DeviceError.NO_ERROR;
                                    return(answer);
                                }

                                double ActiveEnergy = ConvertFromBcd(dt.Body[6 + i * 4]) * 0.001 + ConvertFromBcd(dt.Body[7 + i * 4]) * 0.1 + ConvertFromBcd(dt.Body[8 + i * 4]) * 10 + ConvertFromBcd(dt.Body[9 + i * 4]) * 1000;
                                answer.records.Add(MakeDayRecord($"EnergyP+ (тариф {i})", ActiveEnergy, "кВт*ч", date));
                                //log($"индекс {i}: {ActiveEnergy}");
                            }

                            double sumReactiveEnergy = ConvertFromBcd(dt.Body[42]) * 0.001 + ConvertFromBcd(dt.Body[43]) * 0.1 + ConvertFromBcd(dt.Body[44]) * 10 + ConvertFromBcd(dt.Body[45]) * 1000;
                            answer.records.Add(MakeDayRecord("EnergyQ+ (сумма тарифов)", sumReactiveEnergy, "квар*ч", date));
                            log($"Получена запись с индексом {startIndex}: {date} : активная энергия {sumActiveEnergy} кВт*ч, реактивная энергия {sumReactiveEnergy} квар*ч");
                            for (int i = 1; i <= 4; i++)
                            {
                                if (cancel())
                                {
                                    answer.success   = false;
                                    answer.error     = "опрос отменен";
                                    answer.errorcode = DeviceError.NO_ERROR;
                                    return(answer);
                                }

                                double ReactiveEnergy = ConvertFromBcd(dt.Body[42 + i * 4]) * 0.001 + ConvertFromBcd(dt.Body[43 + i * 4]) * 0.1 + ConvertFromBcd(dt.Body[44 + i * 4]) * 10 + ConvertFromBcd(dt.Body[45 + i * 4]) * 1000;
                                answer.records.Add(MakeDayRecord($"EnergyQ+ (тариф {i})", ReactiveEnergy, "квар*ч", date));
                            }

                            startIndex++;
                        }
                        else if (softWareVersion >= 400 && softWareVersion <= 499)
                        {
                            if (cancel())
                            {
                                answer.success   = false;
                                answer.error     = "опрос отменен";
                                answer.errorcode = DeviceError.NO_ERROR;
                                return(answer);
                            }

                            double sumImpActiveEnergy = ConvertFromBcd(dt.Body[6]) * 0.01 + ConvertFromBcd(dt.Body[7]) * 1 + ConvertFromBcd(dt.Body[8]) * 100 + ConvertFromBcd(dt.Body[9]) * 10000;
                            answer.records.Add(MakeDayRecord("EnergyP+ (сумма тарифов)", sumImpActiveEnergy, "кВт*ч", date));

                            for (int i = 1; i <= 4; i++)
                            {
                                if (cancel())
                                {
                                    answer.success   = false;
                                    answer.error     = "опрос отменен";
                                    answer.errorcode = DeviceError.NO_ERROR;
                                    return(answer);
                                }

                                double ActiveEnergy = ConvertFromBcd(dt.Body[6 + i * 4]) * 0.01 + ConvertFromBcd(dt.Body[7 + i * 4]) * 1 + ConvertFromBcd(dt.Body[8 + i * 4]) * 100 + ConvertFromBcd(dt.Body[9 + i * 4]) * 10000;
                                answer.records.Add(MakeDayRecord($"EnergyP+ (тариф {i})", ActiveEnergy, "кВт*ч", date));
                                log($"индекс {i}: {ActiveEnergy}");
                            }

                            double sumExpActiveEnergy = ConvertFromBcd(dt.Body[42]) * 0.01 + ConvertFromBcd(dt.Body[43]) * 1 + ConvertFromBcd(dt.Body[44]) * 100 + ConvertFromBcd(dt.Body[45]) * 10000;
                            answer.records.Add(MakeDayRecord($"EnergyP- (сумма тарифов)", sumExpActiveEnergy, "кВт*ч", date));
                            for (int i = 1; i <= 4; i++)
                            {
                                if (cancel())
                                {
                                    answer.success   = false;
                                    answer.error     = "опрос отменен";
                                    answer.errorcode = DeviceError.NO_ERROR;
                                    return(answer);
                                }

                                double ExpActiveEnergy = ConvertFromBcd(dt.Body[42 + i * 4]) * 0.01 + ConvertFromBcd(dt.Body[43 + i * 4]) * 1 + ConvertFromBcd(dt.Body[44 + i * 4]) * 100 + ConvertFromBcd(dt.Body[45 + i * 4]) * 10000;
                                answer.records.Add(MakeDayRecord($"EnergyP- (тариф {i})", ExpActiveEnergy, "кВт*ч", date));
                            }

                            double sumReactiveEnergy = ConvertFromBcd(dt.Body[78]) * 0.01 + ConvertFromBcd(dt.Body[79]) * 1 + ConvertFromBcd(dt.Body[80]) * 100 + ConvertFromBcd(dt.Body[81]) * 10000;
                            answer.records.Add(MakeDayRecord("EnergyQ+ (сумма тарифов)", sumReactiveEnergy, "квар*ч", date));

                            log($"Получена запись с индексом {startIndex}: {date} : активная энергия {sumImpActiveEnergy} кВт*ч, реактивная энергия {sumReactiveEnergy} квар*ч");

                            for (int i = 1; i <= 4; i++)
                            {
                                if (cancel())
                                {
                                    answer.success   = false;
                                    answer.error     = "опрос отменен";
                                    answer.errorcode = DeviceError.NO_ERROR;
                                    return(answer);
                                }

                                double ReactiveEnergy = ConvertFromBcd(dt.Body[78 + i * 4]) * 0.01 + ConvertFromBcd(dt.Body[79 + i * 4]) * 1 + ConvertFromBcd(dt.Body[80 + i * 4]) * 100 + ConvertFromBcd(dt.Body[81 + i * 4]) * 10000;
                                answer.records.Add(MakeDayRecord($"EnergyQ+ (тариф {i})", ReactiveEnergy, "квар*ч", date));
                            }

                            double sumExpReactiveEnergy = ConvertFromBcd(dt.Body[114]) * 0.01 + ConvertFromBcd(dt.Body[115]) * 1 + ConvertFromBcd(dt.Body[116]) * 100 + ConvertFromBcd(dt.Body[117]) * 10000;
                            answer.records.Add(MakeDayRecord("EnergyQ- (сумма тарифов)", sumExpReactiveEnergy, "квар*ч", date));

                            for (int i = 1; i <= 4; i++)
                            {
                                if (cancel())
                                {
                                    answer.success   = false;
                                    answer.error     = "опрос отменен";
                                    answer.errorcode = DeviceError.NO_ERROR;
                                    return(answer);
                                }

                                double ReactiveEnergy = ConvertFromBcd(dt.Body[114 + i * 4]) * 0.01 + ConvertFromBcd(dt.Body[115 + i * 4]) * 1 + ConvertFromBcd(dt.Body[116 + i * 4]) * 100 + ConvertFromBcd(dt.Body[117 + i * 4]) * 10000;
                                answer.records.Add(MakeDayRecord($"EnergyQ- (тариф {i})", ReactiveEnergy, "квар*ч", date));
                            }
                            startIndex++;
                        }
                        else
                        {
                            log($"Для модели счетичика  {ModelVersion} с версией прошивки {SoftwareVersion} чтение суточных не реализовано");
                        }
                    }
                }
                return(answer);
            }

            dynamic ans = new ExpandoObject();

            ans.success   = false;
            ans.error     = "для данной прошивки чтение часовых не реализовано";
            ans.errorcode = DeviceError.NO_ANSWER;
            return(ans);
        }