public MtuForm(Mtu mtu) { this.dictionary = new Dictionary <string, Parameter> (); //this.conditions = new Conditions ( mtu ); //this.global = Singleton.Get.Configuration.Global; this.mtu = mtu; }
private void Comm_OnReadMtuData(object sender, MTUComm.ReadMtuDataArgs e) { ActionProgressArgs args; switch (e.Status) { case LogQueryResult.LogDataType.Bussy: args = new ActionProgressArgs(0, 0); OnProgress(this, args); break; case LogQueryResult.LogDataType.NewPacket: args = new ActionProgressArgs(e.CurrentEntry, e.TotalEntries); OnProgress(this, args); break; case LogQueryResult.LogDataType.LastPacket: Mtu mtu_type = configuration.GetMtuTypeById((int)e.MtuType.Type); ActionResult result = ReadMTUData(e.Start, e.End, e.Entries, e.MtuType, mtu_type); logger.logReadDataResult(this, result, mtu_type); ActionFinishArgs f_args = new ActionFinishArgs(null); OnFinish(this, f_args); break; } }
private void AssignMtuRow(DataRow row, MtuType type, Mtu mtu, MtuUsage mtu_usage_kw, MtuUsage mtu_usage_cost) { switch (type) { case MtuType.Net: row[0] = "⚡️"; break; case MtuType.Generation: row[0] = "☀️"; break; case MtuType.Load: row[0] = "🔌"; break; case MtuType.Standalone: row[0] = "🏡"; break; } row[1] = mtu.Description; if (type != MtuType.Generation) { row[2] = ((double)mtu_usage_kw.Value / 1000).ToString("N3"); row[3] = ((double)mtu_usage_cost.Value / 100).ToString("C"); } else { row[2] = ((double)(mtu_usage_kw.Value * -1) / 1000).ToString("N3"); row[3] = ((double)(mtu_usage_cost.Value * -1) / 100).ToString("C"); } row[4] = mtu_usage_cost.Value; }
public MtuForm(Mtu mtu) { this.dictionary = new Dictionary <string, Parameter> (); //this.conditions = new Conditions ( mtu ); this.global = Configuration.GetInstance().GetGlobal(); this.mtu = mtu; }
public void logTurnOffResult(Action ref_action, Mtu Mtu) { String uri = CreateFileIfNotExist(); XDocument doc = XDocument.Load(uri); logTurnOffResult(doc.Root.Element("Mtus"), ref_action.DisplayText, ref_action.LogText, ref_action.user, ( uint )Mtu.Id); doc.Save(uri); }
public void ReadData(Action action, ActionResult result, Mtu mtu) { String uri = CreateFileIfNotExist(); XDocument doc = XDocument.Load(uri); PrepareLog_ReadData(doc.Root.Element("Mtus"), action, result, mtu); doc.Save(uri); }
public void logReadDataResult(Action ref_action, ActionResult result, Mtu mtuType) { String uri = CreateFileIfNotExist(); XDocument doc = XDocument.Load(uri); logReadDataResult(doc.Root.Element("Mtus"), ref_action, result, mtuType.Id); doc.Save(uri); }
public MemRegister getFamilyRegister(Mtu mtu, string regsiter_name) { try { return(getFamilyRegister(InterfaceAux.GetmemoryMapTypeByMtuId(mtu), regsiter_name)); } catch (Exception e) { return(null); } }
public Mtu GetMtuTypeById(int mtuId) { Mtu mtu = mtuTypes.FindByMtuId(mtuId); if (mtu == null) { Errors.LogErrorNow(new MtuTypeIsNotFoundException()); } return(mtu); }
private void Comm_OnReadMtu(object sender, MTUComm.ReadMtuArgs e) { currentMtu = e.MtuType; ActionResult result = CreateActionResultUsingInterface(e.MemoryMap, e.MtuType); logger.logReadResult(this, result, e.MtuType); ActionFinishArgs args = new ActionFinishArgs(result); OnFinish(this, args); }
public Mtu GetMtuTypeById(int mtuId) { Mtu mtu = mtuTypes.FindByMtuId(mtuId); // Is not valid MTU ID ( not present in Mtu.xml ) if (mtu == null) { Errors.LogErrorNow(new MtuMissingException()); } return(mtu); }
private static Interface GetInterfaceBytMtuId(Mtu mtu) { Configuration config = Singleton.Get.Configuration; InterfaceConfig xmlInterfaces = config.interfaces; bool meterIdIsNumeric; List <string> portTypes = mtu.Ports[0].GetPortTypes(out meterIdIsNumeric); int interfaceIndex; // Gas MTUs of family 33xx should use family 31xx32xx memorymap if (mtu.IsFamilly33xx && mtu.Port1.IsForPulse && (mtu.Ports[0].Type.Contains("M") || mtu.Ports[0].Type.Contains("R") || (meterIdIsNumeric && config.getMeterTypeById(int.Parse(portTypes[0])).IsForGas))) { interfaceIndex = 1; // Family 31xx32xx } else { MtuInterface iInfoMtu = xmlInterfaces.MtuInterfaces.Find(x => x.Id == mtu.Id); if (iInfoMtu == null) { throw new InterfaceNotFoundException_Internal(); } else { interfaceIndex = iInfoMtu.Interface; } } Interface iInfo = xmlInterfaces.Interfaces.Find(x => x.Id == interfaceIndex); if (iInfo == null) { throw new InterfaceNotFoundException_Internal(); } InterfaceConfig.currentIndexType = interfaceIndex; return(iInfo); }
public async Task <string> DailySnap_Get(MemoryOverload <string> MemoryOverload, dynamic MemoryRegisters) { Global global = Singleton.Get.Configuration.Global; Mtu mtu = Singleton.Get.Action.CurrentMtu; if (!global.AllowDailyReads || !mtu.DailyReads) { return(DISABLED); } int timeDiff = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours; int curTime = await MemoryRegisters.DailyGMTHourRead.GetValue() + timeDiff; if (curTime < 0) { curTime = 24 + curTime; } if (curTime == 0) { return(MIDNIGHT); } else if (curTime <= 11) { return(curTime + AM); } else if (curTime == 12) { return(NOON); } else if (curTime > 12 && curTime < 24) { return((curTime - 12) + PM); } else { return(DISABLED); } }
private static Interface GetInterfaceBytMtuId(Mtu mtu) { Configuration config = Configuration.GetInstance(); InterfaceConfig xmlInterfaces = config.interfaces; bool meterIdIsNumeric; List <string> portTypes = mtu.Ports[0].GetPortTypes(out meterIdIsNumeric); int interfaceIndex; // Gas MTUs of family 33xx should use family 31xx32xx memorymap if (!mtu.Ecoder && (mtu.Ports[0].Type.Contains("M") || mtu.Ports[0].Type.Contains("R") || (meterIdIsNumeric && config.getMeterTypeById(int.Parse(portTypes[0])).Utility.ToLower().Equals("gas")))) { interfaceIndex = 1; // Family 31xx32xx } else { MtuInterface iInfoMtu = xmlInterfaces.MtuInterfaces.Find(x => x.Id == mtu.Id); if (iInfoMtu == null) { throw new MtuNotFoundException("Mtu not found"); } else { interfaceIndex = iInfoMtu.Interface; } } Interface iInfo = xmlInterfaces.Interfaces.Find(x => x.Id == interfaceIndex); if (iInfo == null) { throw new InterfaceNotFoundException("Meter not found"); } return(iInfo); }
public string TurnOnOff(Action action, Mtu mtu, uint mtuId) { String uri = CreateFileIfNotExist(); XDocument doc = XDocument.Load(uri); PrepareLog_TurnOff(doc.Root.Element("Mtus"), action.DisplayText, action.LogText, action.user, mtuId); doc.Save(uri); // Launching multiple times scripts with the same output path, concatenates the actions logs, // but the log send to the explorer should be only the last action performed // but the log send to the explorer should be only the last action performed byte[] byteArray = Encoding.UTF8.GetBytes(CreateBasicStructure()); Stream BasicStruct = new MemoryStream(byteArray); XDocument uniDoc = XDocument.Load(BasicStruct); PrepareLog_TurnOff(uniDoc.Root.Element("Mtus"), action.DisplayText, action.LogText, action.user, mtuId); #if DEBUG string uniUri = Path.Combine(Mobile.LogUniPath, mtu.Id + "-" + action.type + ((mtu.SpecialSet) ? "-Encrypted" : "") + "-" + DateTime.Today.ToString("MM_dd_yyyy") + ".xml"); this.CreateFileIfNotExist(false, uniUri); uniDoc.Save(uniUri); #endif // Write in ActivityLog if (Data.Get.IsFromScripting && !Singleton.Get.Configuration.Global.ScriptOnly) { // Reset fixed_name to add to the ActivityLog in CreateFileIfNotExist this.ResetFixedName(); uri = CreateFileIfNotExist(); doc = XDocument.Load(uri); PrepareLog_TurnOff(doc.Root.Element("Mtus"), action.DisplayText, action.LogText, action.user, mtuId); doc.Save(uri); } return(uniDoc.ToString()); }
internal static void LogUnhandledException(Exception exception) { try { StringBuilder str = new StringBuilder(); // MTU info Mtu mtu = Singleton.Get.Action.CurrentMtu; str.AppendLine(DateTime.Now.ToString()); str.AppendLine("Unhandled Exception"); str.AppendLine(""); str.AppendLine("MTU"); str.AppendLine("---"); str.AppendLine(string.Format("{0,-50} : {1}", "MTU", mtu.Id)); str.AppendLine(string.Format("{0,-50} : {1}", "SpecialSet", mtu.SpecialSet)); str.AppendLine(string.Format("{0,-50} : {1}", "HexNumber", mtu.HexNum)); str.AppendLine(string.Format("{0,-50} : {1}", "Num.Ports", mtu.Ports.Count)); // Action info MTUComm.Action action = Singleton.Get.Action; str.AppendLine(""); str.AppendLine("Action"); str.AppendLine("------"); str.AppendLine(string.Format("{0,-50} : {1}", "Type", action.type)); str.AppendLine(string.Format("{0,-50} : {1}", "User", action.user)); // Add current values in Global.xml str.AppendLine(""); str.AppendLine("Global.XML"); str.AppendLine("----------"); Global global = Singleton.Get.Configuration.Global; foreach (var property in global.GetType().GetProperties()) { if (!property.GetType().IsArray&& property.CanRead) { var value = property.GetValue(global); if (!(value is null)) { str.AppendLine(string.Format("{0,-50} : {1}", property.Name, value)); } } } str.AppendLine(""); str.AppendLine("Exception"); str.AppendLine("---------"); StackTrace traces = new StackTrace(exception.InnerException, true); var capturedTraces = typeof(StackTrace).GetField("captured_traces", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(traces) as StackTrace[]; string traces2 = exception.InnerException.StackTrace; foreach (StackTrace trace in capturedTraces) { foreach (StackFrame frame in trace.GetFrames()) { str.AppendLine(frame.GetFileName() + ".." + Environment.NewLine + frame.GetMethod() + " at line " + frame.GetFileLineNumber() + ", column " + frame.GetFileColumnNumber()); } } str.AppendLine(""); str.AppendLine("---------"); str.AppendLine(exception.InnerException.ToString()); string errorFileName = string.Format("{0}_{1}_{2}.txt", "Exception", action.type, DateTime.Now.ToString("MM-dd-yyyy_HH-mm")); var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var errorFilePath = Path.Combine(libraryPath, errorFileName); File.WriteAllText(errorFilePath, str.ToString()); str.Clear(); str = null; } catch { // just suppress any error logging exceptions } }
public AddMtuForm(Mtu mtu) : base(mtu) { this.dictionary = new Dictionary <FIELD, Parameter> (); Global global = Singleton.Get.Configuration.Global; this.Texts = new Dictionary <FIELD, string[]>() { #region Service Port ID = Account Number = Functl Loctn { FIELD.ACCOUNT_NUMBER, new string[] { "AccountNumber", "AccountNumber", global.AccountLabel } }, { FIELD.ACCOUNT_NUMBER_2, new string[] { "AccountNumber_2", "AccountNumber", global.AccountLabel } }, #endregion #region Field Order = Work Order { FIELD.WORK_ORDER, new string[] { "WorkOrder", "WorkOrder", "Field Order" } }, { FIELD.WORK_ORDER_2, new string[] { "WorkOrder_2", "WorkOrder", "Field Order" } }, #endregion #region Old MTU ID { FIELD.MTU_ID_OLD, new string[] { "OldMtuId", "OldMtuID", "Old MTU ID" } }, #endregion #region Activity Log ID { FIELD.ACTIVITY_LOG_ID, new string[] { "ActivityLogId", "ActivityLogID", "Activity Log ID" } }, #endregion #region Meter Serial Number { FIELD.METER_NUMBER, new string[] { "MeterNumber", "NewMeterSerialNumber", "New Meter Serial Number" } }, { FIELD.METER_NUMBER_2, new string[] { "MeterNumber_2", "NewMeterSerialNumber", "New Meter Serial Number" } }, { FIELD.METER_NUMBER_OLD, new string[] { "MeterNumberOld", "OldMeterSerialNumber", "Old Meter Serial Number" } }, { FIELD.METER_NUMBER_OLD_2, new string[] { "MeterNumberOld_2", "OldMeterSerialNumber", "Old Meter Serial Number" } }, #endregion #region Initial Reading = Meter Reading { FIELD.METER_READING, new string[] { "MeterReading", "NewMeterReading", "New Meter Reading" } }, { FIELD.METER_READING_2, new string[] { "MeterReading_2", "NewMeterReading", "New Meter Reading" } }, { FIELD.METER_READING_OLD, new string[] { "MeterReadingOld", "OldMeterReading", "Old Meter Reading" } }, { FIELD.METER_READING_OLD_2, new string[] { "MeterReadingOld_2", "OldMeterReading", "Old Meter Reading" } }, #endregion #region Meter Type ( Meter ID ) { FIELD.METER_TYPE, new string[] { "Meter", "SelectedMeterId", "Selected Meter ID" } }, { FIELD.METER_TYPE_2, new string[] { "Meter_2", "SelectedMeterId", "Selected Meter ID" } }, #endregion #region Old Meter Working { FIELD.METER_WORKING_OLD, new string[] { "OldMeterWorking", "OldMeterWorking", "Old Meter Working" } }, { FIELD.METER_WORKING_OLD_2, new string[] { "OldMeterWorking_2", "OldMeterWorking", "Old Meter Working" } }, #endregion #region Replace Meter|Register { FIELD.REPLACE_METER_REG, new string[] { "ReplaceMeterRegister", "MeterRegisterStatus", "Meter Register Status" } }, { FIELD.REPLACE_METER_REG_2, new string[] { "ReplaceMeterRegister_2", "MeterRegisterStatus", "Meter Register Status" } }, #endregion #region Number of Dials { FIELD.NUMBER_OF_DIALS, new string[] { "NumberOfDials", "NumberOfDials", "Number of Dials" } }, { FIELD.NUMBER_OF_DIALS_2, new string[] { "NumberOfDials_2", "NumberOfDials", "Number of Dials" } }, #endregion #region Drive Dial Size { FIELD.DRIVE_DIAL_SIZE, new string[] { "DriveDialSize", "DriveDialSize", "Drive Dial Size" } }, { FIELD.DRIVE_DIAL_SIZE_2, new string[] { "DriveDialSize_2", "DriveDialSize", "Drive Dial Size" } }, #endregion #region Unit of Measure { FIELD.UNIT_MEASURE, new string[] { "UnitOfMeasure", "UnitOfMeasure", "Unit of Measure" } }, { FIELD.UNIT_MEASURE_2, new string[] { "UnitOfMeasure_2", "UnitOfMeasure", "Unit of Measure" } }, #endregion #region Read Interval { FIELD.READ_INTERVAL, new string[] { "ReadInterval", "ReadInterval", "Read Interval" } }, #endregion #region Snap Reads { FIELD.SNAP_READS, new string[] { "SnapReads", "SnapReads", "Snap Reads" } }, #endregion #region 2Way { FIELD.TWO_WAY, new string[] { "TwoWay", "Fast-2-Way", "Fast Message Config" } }, #endregion #region Alarm { FIELD.ALARM, new string[] { "Alarm", "Alarms", "Alarms" } }, #endregion #region Demand { FIELD.DEMAND, new string[] { "Demand", "Demands", "Demands" } }, #endregion #region GPS { FIELD.GPS_LATITUDE, new string[] { "GPSLat", "GPS_Y", "Lat" } }, { FIELD.GPS_LONGITUDE, new string[] { "GPSLon", "GPS_X", "Long" } }, { FIELD.GPS_ALTITUDE, new string[] { "GPSAlt", "Altitude", "Elevation" } }, #endregion #region Optional Parameters { FIELD.OPTIONAL_PARAMS, new string[] { "OptionalParams", "OptionalParams", "OptionalParams" } }, #endregion #region Force TimeSync -> Install Confirmation { FIELD.FORCE_TIME_SYNC, new string[] { "ForceTimeSync", "ForceTimeSync", "Force TimeSync" } }, #endregion #region TEST { FIELD.TEST, new string[] { "Test", "Test", "Test" } }, #endregion }; }
private async Task <ActionResult> CreateActionResultUsingInterface( dynamic map = null, Mtu mtu = null, MtuForm form = null) //, //ActionType actionType = ActionType.ReadMtu ) { Parameter paramToAdd; Global global = this.config.Global; Puck puck = Singleton.Get.Puck; Type gType = global.GetType(); ActionResult result = new ActionResult(); InterfaceParameters[] parameters = configuration.getAllInterfaceFields(mtu, ActionType.ReadMtu); //, actionType ); foreach (InterfaceParameters parameter in parameters) { if (parameter.Name.Equals(IFACE_PORT)) { for (int i = 0; i < mtu.Ports.Count; i++) { result.addPort(await ReadPort(i + 1, parameter.Parameters.ToArray(), map, mtu)); } } else { if (await ValidateCondition(parameter.Conditional, map, mtu)) { string value = string.Empty; string sourceWhere = string.Empty; string sourceProperty = parameter.Name; if (!string.IsNullOrEmpty(parameter.Source) && Regex.IsMatch(parameter.Source, NET_IDS + "." + NET_IDS)) { string[] sources = parameter.Source.Split(new char[] { '.' }); sourceWhere = sources[0]; sourceProperty = sources[1]; } paramToAdd = null; try { switch (sourceWhere) { case IFACE_ACTION: value = this.GetProperty(sourceProperty); break; case IFACE_MTU: value = mtu.GetProperty(sourceProperty); break; case IFACE_PUCK: value = puck.GetProperty(sourceProperty); break; case IFACE_FORM: paramToAdd = form.GetParameter(sourceProperty); break; case IFACE_DATA: value = (string.IsNullOrEmpty(value = Data.Get[sourceProperty]) ? string.Empty : value); break; default: value = (await map[sourceProperty].GetValue()).ToString(); break; // MemoryMap.ParameterName } } catch (Exception e) { Utils.Print("Interface: Map Error: " + sourceProperty); throw new Exception(); } if (!sourceWhere.Equals(IFACE_FORM) && !string.IsNullOrEmpty(value)) { string display = (parameter.Display.ToLower().StartsWith("global.")) ? gType.GetProperty(parameter.Display.Split(new char[] { '.' })[1]).GetValue(global, null).ToString() : parameter.Display; paramToAdd = new Parameter(parameter.Name, display, value, parameter.Source); } // To change "name" attribute to show in IFACE_FORM case else { paramToAdd.CustomParameter = parameter.Name; paramToAdd.source = parameter.Source; } if (paramToAdd != null) { paramToAdd.Value = this.FormatLength(paramToAdd.Value, parameter.Length, parameter.Fill); result.AddParameter(paramToAdd); } } } } // Add additional parameters for all actions except for the Add if (form == null) { foreach (Parameter param in this.AdditionalParameters) { result.AddParameter(param); } } return(result); }
public static int GetmemoryMapSizeByMtuId(Mtu mtu) { Interface iInfo = GetInterfaceBytMtuId(mtu); return(iInfo.MemorymapSize); }
private ActionResult ReadPort(int indexPort, InterfaceParameters[] parameters, dynamic map, Mtu mtu) { ActionResult result = new ActionResult(); Port portType = mtu.Ports[indexPort]; // Meter Serial Number int meterId = map.GetProperty("P" + (indexPort + 1) + "MeterType").Value; // Port has installed a Meter if (meterId != 0) { Meter Metertype = configuration.getMeterTypeById(meterId); // Meter type not found in database if (Metertype.Type == "NOTFOUND") { //logger.LogError("No valid meter types were found for MTU type " + Metertype.Id); } // Iterate all parameters for this port foreach (InterfaceParameters parameter in parameters) { if (parameter.Name.Equals("MeterReading")) { if (ValidateCondition(parameter.Conditional, map, mtu, "P" + (indexPort + 1))) { string meter_reading_error = map.GetProperty("P" + (indexPort + 1) + "ReadingError").Value.ToString(); if (meter_reading_error.Length < 1) { ulong meter_reading = 0; try { meter_reading = map.GetProperty("P" + (indexPort + 1) + "Reading").Value; } catch (Exception e) { } ulong tempReadingVal = 0; if (mtu.PulseCountOnly) { tempReadingVal = meter_reading * (ulong)Metertype.HiResScaling; } else { tempReadingVal = meter_reading; } String tempReading = tempReadingVal.ToString(); if (Metertype.LiveDigits < tempReading.Length) { tempReading = tempReading.Substring(tempReading.Length - Metertype.LiveDigits - (tempReading.IndexOf('.') > -1 ? 1 : 0)); } else { tempReading = tempReading.PadLeft(Metertype.LiveDigits, '0'); } if (Metertype.LeadingDummy > 0) // KG 12/08/2008 { tempReading = tempReading.PadLeft(tempReading.Length + Metertype.LeadingDummy, configuration.useDummyDigits() ? 'X' : '0'); } if (Metertype.DummyDigits > 0) // KG 12/08/2008 { tempReading = tempReading.PadRight(tempReading.Length + Metertype.DummyDigits, configuration.useDummyDigits() ? 'X' : '0'); } if (Metertype.Scale > 0 && tempReading.IndexOf(".") == -1) // 8.12.2011 KG add for F1 Pulse { tempReading = tempReading.Insert(tempReading.Length - Metertype.Scale, "."); } if (Metertype.PaintedDigits > 0 && configuration.useDummyDigits()) // KG 12/08/2008 { tempReading = tempReading.PadRight(tempReading.Length + Metertype.PaintedDigits, '0').Insert(tempReading.Length, " - "); } if (tempReading == "") { tempReading = "INVALID"; } result.AddParameter(new Parameter(parameter.Name, parameter.Display, tempReading)); } else { result.AddParameter(new Parameter(parameter.Name, parameter.Display, meter_reading_error)); } } } else { try { if (ValidateCondition(parameter.Conditional, map, mtu, "P" + (indexPort + 1))) { if (parameter.Source == null) { parameter.Source = ""; } string val = null; string property_type = ""; string property_name = ""; if (parameter.Source.Contains(".") && parameter.Source.Length >= 3) { property_type = parameter.Source.Split(new char[] { '.' })[0]; property_name = parameter.Source.Split(new char[] { '.' })[1]; } string name = parameter.Name; switch (property_type) { case "PortType": val = portType.GetProperty(property_name); break; case "MeterType": val = Metertype.GetProperty(property_name); break; case "MtuType": val = mtu.GetProperty(property_name); break; case "MemoryMap": val = map.GetProperty("P" + (indexPort + 1) + property_name).Value.ToString(); name = property_name; break; default: try { val = map.GetProperty("P" + (indexPort + 1) + parameter.Name).Value.ToString(); }catch (Exception e) { val = null; } break; } if (!string.IsNullOrEmpty(val)) { result.AddParameter(new Parameter(name, parameter.Display, val)); } } } catch (Exception e) { Console.WriteLine(e.Message + "\r\n" + e.StackTrace); } } } } // Port has not installed a Meter else { result.AddParameter(new Parameter("Status", "Status", "Not Installed")); result.AddParameter(new Parameter("MeterTypeId", "Meter Type ID", "000000000")); result.AddParameter(new Parameter("MeterReading", "Meter Reading", "Bad Reading")); /* * result.AddParameter(new Parameter("MeterType", "Meter Type", "Not Installed")); * result.AddParameter(new Parameter("MeterTypeId", "Meter Type ID", meterid.ToString())); * result.AddParameter(new Parameter("AcctNumber", "Service Pt. ID", "000000000")); * result.AddParameter(new Parameter("MeterReading", "Meter Reading", "Bad Reading")); */ } return(result); }
private ActionResult CreateActionResultUsingInterface( dynamic map = null, Mtu mtutype = null, MtuForm form = null, dynamic actionParams = null, string actionType = "ReadMTU") { InterfaceParameters[] parameters = configuration.getAllInterfaceFields(mtutype.Id, actionType); ActionResult result = new ActionResult(); foreach (InterfaceParameters parameter in parameters) { if (parameter.Name.Equals("MtuVoltageBattery")) { } if (parameter.Name.Equals("Port")) { for (int i = 0; i < mtutype.Ports.Count; i++) { result.addPort(ReadPort(i, parameter.Parameters.ToArray(), map, mtutype)); } } else { try { if (ValidateCondition(parameter.Conditional, map, mtutype, "", actionParams)) { //if ( parameter.Source == null ) // parameter.Source = ""; string sourceWhere = string.Empty; string sourceProperty = string.Empty; if (!string.IsNullOrEmpty(parameter.Source)) { string[] sources = parameter.Source.Split(new char[] { '.' }); sourceWhere = sources[0]; sourceProperty = sources[1]; } Parameter paramToAdd = null; switch (sourceWhere) { case "Action": string action_property_value = GetProperty(sourceProperty); if (action_property_value != null) { paramToAdd = new Parameter(parameter.Name, parameter.Display, action_property_value); } break; case "MeterType": break; case "MtuType": paramToAdd = new Parameter(parameter.Name, parameter.Display, mtutype.GetProperty(sourceProperty)); break; case "MemoryMap": paramToAdd = new Parameter(sourceProperty, parameter.Display, map.GetProperty(sourceProperty).Value.ToString()); break; case "Form": if (form.ContainsParameter(sourceProperty)) { paramToAdd = form.GetParameter(sourceProperty); } break; case "ActionParams": paramToAdd = new Parameter(parameter.Name, parameter.Display, actionParams.GetType().GetProperty(sourceProperty) .GetValue(actionParams, null).ToString()); break; default: try { paramToAdd = new Parameter(parameter.Name, parameter.Display, map.GetProperty(parameter.Name).Value.ToString()); } catch (Exception e) { paramToAdd = null; } break; } if (paramToAdd != null) { result.AddParameter(paramToAdd); } else { } } } catch (Exception e) { Console.WriteLine(e.Message + "\r\n" + e.StackTrace); } } } return(result); }
private ActionResult ReadMTUData(DateTime start, DateTime end, List <LogDataEntry> Entries, MTUBasicInfo mtuInfo, Mtu mtu) { ActionResult result = new ActionResult(); string log_path = logger.logReadDataResultEntries(mtuInfo.Id.ToString("d15"), start, end, Entries); InterfaceParameters[] parameters = configuration.getAllInterfaceFields(mtu.Id, "DataRead"); foreach (InterfaceParameters parameter in parameters) { if (parameter.Name.Equals("Port")) { for (int i = 0; i < mtu.Ports.Count; i++) { foreach (InterfaceParameters port_parameter in parameter.Parameters) { if (port_parameter.Source != null && port_parameter.Source.StartsWith("ActionParams")) { Parameter sel_parameter = GetParameterByTag(port_parameter.Name, i + 1); if (sel_parameter != null) { result.AddParameter(new Parameter(port_parameter.Name, port_parameter.Display, sel_parameter.Value)); } } } } } else { try { if (parameter.Source != null && parameter.Source.StartsWith("ActionParams")) { Parameter sel_parameter = GetParameterByTag(parameter.Name); if (sel_parameter != null) { result.AddParameter(new Parameter(parameter.Name, parameter.Display, sel_parameter.Value)); } } } catch (Exception e) { Console.WriteLine(e.Message + "\r\n" + e.StackTrace); } } } result.AddParameter(new Parameter("ReadRequest", "Number Read Request Days", "")); result.AddParameter(new Parameter("ReadResult", "Read Result", "Number of Reads " + Entries.Count.ToString() + " for Selected Period From " + start.ToString("dd/MM/yyyy") + " 0:00:00 Till " + end.ToString("dd/MM/yyyy") + " 23:59:59")); result.AddParameter(new Parameter("ReadResultFile", "Read Result File", log_path)); return(result); }
private async Task <bool> ValidateCondition( string conditionStr, dynamic map, Mtu mtu, int portIndex = 1) { if (string.IsNullOrEmpty(conditionStr)) { return(true); } try { List <ConditionObjet> conditions = new List <ConditionObjet> (); string test = conditionStr.Trim().Replace(" ", string.Empty); MatchCollection matches = Regex.Matches(conditionStr.Trim().Replace(" ", string.Empty), REGEX_IFS, RegexOptions.Compiled); foreach (Match m in matches.Cast <Match> ().ToList()) { conditions.Add( new ConditionObjet( Uri.UnescapeDataString(m.Groups[1].Value), // + or | Uri.UnescapeDataString(m.Groups[2].Value), // Type/Class[.Property] Uri.UnescapeDataString(m.Groups[3].Value), // = , < , > or ! Uri.UnescapeDataString(m.Groups[4].Value))); // Value } int finalResult = 0; string port = PORT_PREFIX + portIndex; Global global = this.config.Global; Type gType = global.GetType(); Type pType = typeof(Port); foreach (ConditionObjet condition in conditions) { int result = 0; string currentValue = string.Empty; string[] condMembers = condition.Key.Split(new char[] { '.' }); // Class.Property string condProperty = (condMembers.Length > 1) ? condMembers[1] : condMembers[0]; // Property // Class or Type switch (condMembers[0]) { case IFACE_PORT: currentValue = pType.GetProperty(condProperty).GetValue(mtu.Ports[portIndex - 1]).ToString(); break; case IFACE_ACTION: currentValue = GetProperty(condProperty); break; // User, Date or Type case IFACE_MTU: currentValue = mtu.GetProperty(condProperty); break; // Mtu class case IFACE_GLOBAL: currentValue = gType.GetProperty(condProperty).GetValue(global, null).ToString(); break; // Global class default: // Dynamic MemoryMap // Recover register from MTU memory map // Some registers have port sufix but other not if (map.ContainsMember(port + condProperty)) { currentValue = (await map[port + condProperty].GetValue()).ToString(); } else if (map.ContainsMember(condProperty)) { currentValue = (await map[condProperty].GetValue()).ToString(); } break; } // Compare property value with condition value if (!string.IsNullOrEmpty(currentValue)) { if (condition.IsEqual && currentValue.ToLower().Equals(condition.Value.ToLower()) || condition.IsNot && !currentValue.ToLower().Equals(condition.Value.ToLower()) || condition.IsLower && float.Parse(currentValue) < float.Parse(condition.Value) || condition.IsGreater && float.Parse(currentValue) > float.Parse(condition.Value)) { result = 1; // Ok } } // Concatenate results if (condition.Condition.Equals(IFACE_OR)) { finalResult += result; // If one condition validate, pass } else if (condition.Condition.Equals(IFACE_AND)) { finalResult *= result; // All conditions have to validate } } if (finalResult <= 0) { } return(finalResult > 0); } catch (Exception e) { //... } return(false); }
private ActionResult ReadMTUData(DateTime start, DateTime end, EventLogList eventLogList, MTUBasicInfo mtuInfo, Mtu mtu) { /* * ActionResult result = new ActionResult(); * * string log_path = logger.ReadDataEntries(mtuInfo.Id.ToString("d15"), start, end, Entries); * * InterfaceParameters[] parameters = configuration.getAllInterfaceFields(mtu, ActionType.ReadData ); * foreach (InterfaceParameters parameter in parameters) * { * if (parameter.Name.Equals("Port")) * { * for (int i = 0; i < mtu.Ports.Count; i++) * { * foreach (InterfaceParameters port_parameter in parameter.Parameters) * { * if (port_parameter.Source != null && port_parameter.Source.StartsWith("ActionParams")) * { * Parameter sel_parameter = GetParameterByTag(port_parameter.Name, i + 1); * if (sel_parameter != null) * { * result.AddParameter(new Parameter(port_parameter.Name, port_parameter.Display, sel_parameter.Value)); * } * } * * } * * * } * } * else * { * try * { * * if (parameter.Source != null && parameter.Source.StartsWith("ActionParams")) * { * Parameter sel_parameter = GetParameterByTag(parameter.Name); * if (sel_parameter != null) * { * result.AddParameter(new Parameter(parameter.Name, parameter.Display, sel_parameter.Value)); * } * } * } * catch (Exception e) * { * Utils.Print(e.Message + "\r\n" + e.StackTrace); * } * } * * } * * result.AddParameter(new Parameter("ReadRequest", "Number Read Request Days", "")); * result.AddParameter(new Parameter("ReadResult", "Read Result", "Number of Reads " + Entries.Count.ToString() + " for Selected Period From " + start.ToString("dd/MM/yyyy") + " 0:00:00 Till " + end.ToString("dd/MM/yyyy") + " 23:59:59")); * result.AddParameter(new Parameter("ReadResultFile", "Read Result File", log_path)); * * return result; */ return(null); }
private bool ValidateCondition(string condition, dynamic map, Mtu mtu, String port = "", dynamic actionParams = null) { if (condition == null) { return(true); } try { List <ConditionObjet> conditions = new List <ConditionObjet> (); MatchCollection matches = Regex.Matches(condition, REGEX_IFS, RegexOptions.Compiled); foreach (Match m in matches.Cast <Match> ().ToList()) { conditions.Add( new ConditionObjet( Uri.UnescapeDataString(m.Groups[1].Value), // & or | Uri.UnescapeDataString(m.Groups[3].Value), // Class.Property Uri.UnescapeDataString(m.Groups[4].Value))); // Value } int finalResult = 0; Global global = Configuration.GetInstance().GetGlobal(); foreach (ConditionObjet item in conditions) { string value = string.Empty; int result = 0; string[] member = item.Key.Split(new char[] { '.' }); // Class.Property string property = member[1]; switch (member[0]) { case "Port": // P1 or P2 value = port; break; case "Action": // User, Date or Type value = GetProperty(property); break; case "MeterType": break; case "MtuType": // Reflection over Mtu class value = mtu.GetProperty(property); break; case "ActionParams": value = actionParams.GetType().GetProperty(member[0]) .GetValue(actionParams, null).ToString(); break; case "Global": value = global.GetType().GetProperty(member[0]) .GetValue(global, null).ToString(); break; default: // MemoryMap // Recover register from MTU memory map // Some registers have port sufix but other not if (!string.IsNullOrEmpty(port) && map.ContainsMember(port + property)) { value = map.GetProperty(port + property).Value.ToString(); } // Try to recover register without port prefix else if (map.ContainsMember(property)) { value = map.GetProperty(property).Value.ToString(); } break; } // Compare property value with condition value if (!string.IsNullOrEmpty(value) && value.ToLower().Equals(item.Value.ToLower())) { result = 1; } // Concatenate conditions results // If one validate, pass if (item.Condition.Equals("|")) { finalResult = finalResult + result; } // All conditions have to validate else if (item.Condition.Equals("&")) { finalResult = finalResult * result; } } return(finalResult > 0); } catch (Exception e) { Console.WriteLine(e.Message + "\r\n" + e.StackTrace); } return(true); }
private void PrepareLog_ReadData(XElement parent, Action action, ActionResult result, Mtu mtu) { XElement element = new XElement("Action"); AddAtrribute(element, "display", action.DisplayText); AddAtrribute(element, "type", action.LogText); AddAtrribute(element, "reason", action.Reason); InterfaceParameters[] parameters = Singleton.Get.Configuration.getLogInterfaceFields(mtu, ActionType.ReadData); foreach (InterfaceParameters parameter in parameters) { if (parameter.Name == "Port") { ActionResult[] ports = result.getPorts(); for (int i = 0; i < ports.Length; i++) { Port(i, element, ports[i], parameter.Parameters.ToArray()); } } else { this.ComplexParameter(element, result, parameter); } } parent.Add(element); }
private void PrepareLog_ReadMTU(XElement parent, Action action, ActionResult resultAllInterfaces, Mtu mtu) { XElement element = new XElement("Action"); AddAtrribute(element, "display", action.DisplayText); AddAtrribute(element, "type", action.LogText); AddAtrribute(element, "reason", action.Reason); InterfaceParameters[] parameters = Singleton.Get.Configuration.getLogInterfaceFields(mtu, ActionType.ReadMtu); foreach (InterfaceParameters parameter in parameters) { try { if (parameter.Name == "Port") { ActionResult[] ports = resultAllInterfaces.getPorts(); for (int i = 0; i < ports.Length; i++) { Port(i, element, ports[i], parameter.Parameters.ToArray()); } } else { this.ComplexParameter(element, resultAllInterfaces, parameter); } } catch (Exception ex) { } } // Add additional parameters if (action.type == ActionType.ReadMtu || action.type == ActionType.MtuInstallationConfirmation) { this.AddAdditionalParameters(element, resultAllInterfaces); } parent.Add(element); }
public void DataReadFile( EventLogList eventLogList, Mtu mtu) { /* * <?xml version="1.0" encoding="utf-8"?> * <Log> * <Transfer> * <MtuId>000000063004810</MtuId> * <LocalTimeStamp>2019-06-10 13:36:45</LocalTimeStamp> * <MtuTimeStamp>2019-06-10 11:26:39</MtuTimeStamp> * <Events FilterMode="Match" FilterValue="MeterRead" RangeStart="2019-05-09 00:00:00" RangeStop="2019-06-10 23:59:59"> * <MeterReadEvent FormatVersion="0"> * <TimeStamp>2019-05-10 04:00:01</TimeStamp> * <MeterRead>999994</MeterRead> * <ErrorStatus>0</ErrorStatus> * <ReadInterval>PT720M</ReadInterval> * <PortNumber>PORT1</PortNumber> * <IsDailyRead>False</IsDailyRead> * <IsTopOfHourRead>True</IsTopOfHourRead> * <ReadReason>Scheduled</ReadReason> * <IsSynchronized>True</IsSynchronized> * </MeterReadEvent> * ... * </Events> * </Transfer> * </Log> */ String uri = CreateFileIfNotExist(BasicFileType.DATA_READ, false, mtu.Id + "-" + DateTime.Now.ToString("MMddyyyyHH") + "DataLog.xml"); XDocument doc = XDocument.Load(uri); XElement transfer = doc.Root.Element("Transfer"); transfer.Add(new XElement("MtuId", mtu.Id)); XElement events = doc.Root.Element("Events"); events.Add(new XAttribute("FilterMode", eventLogList.FilterMode)); events.Add(new XAttribute("FilterValue", eventLogList.EntryType)); events.Add(new XAttribute("RangeStart", eventLogList.DateStart)); events.Add(new XAttribute("RangeStop", eventLogList.DateEnd)); foreach (EventLog log in eventLogList.Entries) { XElement parent = new XElement("MeterReadEvent"); parent.Add(new XAttribute("FormatVersion", log.FormatVersion)); parent.Add(new XElement("TimeStamp", log.TimeStamp)); parent.Add(new XElement("MeterRead", log.MeterRead)); parent.Add(new XElement("ErrorStatus", log.ErrorStatus)); parent.Add(new XElement("ReadInterval", log.ReadInterval)); parent.Add(new XElement("PortNumber", "PORT" + log.PortNumber)); parent.Add(new XElement("IsDailyRead", log.IsDailyRead)); parent.Add(new XElement("IsTopOfHourRead", log.IsTopOfHourRead)); parent.Add(new XElement("ReadReason", log.ReasonForRead)); parent.Add(new XElement("IsSynchronized", log.IsSynchronized)); events.Add(parent); } // Update file with new data doc.Save(uri); }
public static string GetmemoryMapTypeByMtuId(Mtu mtu) { Interface iInfo = GetInterfaceBytMtuId(mtu); return(iInfo.Memorymap); }
private async Task <ActionResult> ReadPort( int indexPort, InterfaceParameters[] parameters, dynamic map, Mtu mtu) { ActionResult result = new ActionResult(); Port portType = mtu.Ports[indexPort - 1]; Global global = this.config.Global; Type gType = global.GetType(); // Meter Serial Number int meterId = await map[PORT_PREFIX + indexPort + "MeterType"].GetValue(); // Port has installed a Meter if (meterId > 0) { Meter meter = configuration.getMeterTypeById(meterId); // Meter type not found in database if (meter.Type.Equals("NOTFOUND")) { //logger.LogError("No valid meter types were found for MTU type " + Metertype.Id); return(null); } // Iterate all parameters for this port foreach (InterfaceParameters parameter in parameters) { // Meter readings are treated in a special way if (parameter.Name.Equals(IFACE_MREADING)) { if (await ValidateCondition(parameter.Conditional, map, mtu, indexPort)) { try { string meter_reading_error = string.Empty; string encoderReadingErrorId = PORT_PREFIX + indexPort + IFACE_READERROR; bool mtuHasNotEncoderErrorCodes = !map.ContainsMember(encoderReadingErrorId); if (!mtuHasNotEncoderErrorCodes) { meter_reading_error = (await map[encoderReadingErrorId].GetValue()).ToString(); } // Encoder MTUs have register to know if an error occurred while trying to read the Meter if (mtuHasNotEncoderErrorCodes || meter_reading_error.Length < 1) { ulong meter_reading = await map[PORT_PREFIX + indexPort + IFACE_MREADING].GetValue(); ulong tempReadingVal = (!mtu.PulseCountOnly) ? meter_reading : meter_reading * ( ulong )meter.HiResScaling; String tempReading = tempReadingVal.ToString(); if (meter.LiveDigits < tempReading.Length) { tempReading = tempReading.Substring(tempReading.Length - meter.LiveDigits - (tempReading.IndexOf('.') > -1 ? 1 : 0)); } else { tempReading = tempReading.PadLeft(meter.LiveDigits, '0'); } if (meter.LeadingDummy > 0) { tempReading = tempReading.PadLeft( tempReading.Length + meter.LeadingDummy, configuration.useDummyDigits() ? 'X' : '0'); } if (meter.DummyDigits > 0) { tempReading = tempReading.PadRight( tempReading.Length + meter.DummyDigits, configuration.useDummyDigits() ? 'X' : '0'); } if (meter.Scale > 0 && tempReading.IndexOf(".") == -1) { tempReading = tempReading.Insert(tempReading.Length - meter.Scale, "."); } if (meter.PaintedDigits > 0 && configuration.useDummyDigits()) { tempReading = tempReading.PadRight( tempReading.Length + meter.PaintedDigits, '0').Insert(tempReading.Length, " - "); } if (string.IsNullOrEmpty(tempReading)) { tempReading = "INVALID"; } result.AddParameter(new Parameter(parameter.Name, parameter.Display, tempReading, parameter.Source, indexPort - 1)); } else { result.AddParameter(new Parameter(parameter.Name, parameter.Display, meter_reading_error, parameter.Source, indexPort - 1)); } } catch (Exception e) { //... } } } else { if (await ValidateCondition(parameter.Conditional, map, mtu, indexPort)) { string value = string.Empty; string sourceWhere = string.Empty; string sourceProperty = parameter.Name; if (!string.IsNullOrEmpty(parameter.Source) && Regex.IsMatch(parameter.Source, NET_IDS + "." + NET_IDS)) { string[] sources = parameter.Source.Split(new char[] { '.' }); sourceWhere = sources[0]; sourceProperty = sources[1]; } try { switch (sourceWhere) { case IFACE_PORT: value = portType.GetProperty(sourceProperty); break; case IFACE_MTU: value = mtu.GetProperty(sourceProperty); break; case IFACE_METER: value = meter.GetProperty(sourceProperty); break; default: value = (await map[sourceProperty = PORT_PREFIX + indexPort + sourceProperty].GetValue()).ToString(); break; // MemoryMap.ParameterName } } catch (Exception e) { Utils.Print("Interface: Map Error: " + sourceProperty); throw new Exception(); } if (!string.IsNullOrEmpty(value)) { value = this.FormatLength(value, parameter.Length, parameter.Fill); string display = (parameter.Display.ToLower().StartsWith("global.")) ? gType.GetProperty(parameter.Display.Split(new char[] { '.' })[1]).GetValue(global, null).ToString() : parameter.Display; result.AddParameter(new Parameter(parameter.Name, display, value, parameter.Source, indexPort - 1)); } } } } } // Port has not installed a Meter else { result.AddParameter(new Parameter("Status", "Status", "Not Installed")); result.AddParameter(new Parameter("MeterTypeId", "Meter Type ID", "000000000")); result.AddParameter(new Parameter("MeterReading", "Meter Reading", "Bad Reading")); } return(result); }