private void ThrowIfValueNull <T>(IReadValue <T> value) { if (value == null) { throw new Exception("Не задано значение параметра"); } }
public void Read <T>(IKpk12MeasuringUnit unit, IReadValue <T> value, string source, bool silent = false) { ThrowIfRegisterNull(value.Register); var register = value.Register; try { unit.Read(register); var converted = (Register <T>)register; value.Actual = converted.Value; if (silent) { return; } var message = _formatter.For(register) .With(value) .ModuleId(unit.UnitIdRegister.Value) .Response(); _logger.Info(message, source); } catch (Exception exception) { _logger.Error(string.Format("Ошибка чтения регистра '{0}' модуль '{1}'", register.Address, unit.UnitIdRegister.Value), source, exception); throw; } }
/// <summary> /// Reads process data from the selected location and device resources. /// </summary> /// <param name="pBlock"><see cref="T:CAS.Lib.CommonBus.ApplicationLayer.IBlockDescription" /> selecting the resource containing the data block to be read.</param> /// <param name="pStation">Address of the remote station connected to the common field bus. –1 if not applicable.</param> /// <param name="pData">The buffer <see cref="T:CAS.Lib.CommonBus.ApplicationLayer.IReadValue" /> containing the requested data.</param> /// <param name="pRetries">Number of retries to get data.</param> /// <returns>Result of the operation</returns> /// <exception cref="System.ArgumentOutOfRangeException"></exception> public AL_ReadData_Result ReadData(IBlockDescription pBlock, int pStation, out IReadValue pData, byte pRetries) { pData = null; if (pBlock.dataType != 0) { TraceSource.TraceMessage(TraceEventType.Error, 149, $"Wrong dataType: {pBlock.dataType}; only data type = 0 is expected"); m_statistic.IncStRxInvalid(); } if (!Connected) { TraceSource.TraceMessage(TraceEventType.Verbose, 165, $"ReadData failed because it is not connected; retries/limit={m_RetryCount}/{this.m_TextReaderProtocolParameters.MaxNumberOfRetries}."); return(AL_ReadData_Result.ALRes_DisInd); } m_statistic.IncStTxFrameCounter(); IDataEntity _copy = Interlocked.Exchange <IDataEntity>(ref m_Fifo, m_Fifo); bool _retResult = _copy != null; m_statistic.RxDataBlock(_retResult); if (!_retResult) { m_statistic.IncStRxNoResponseCounter(); TraceSource.TraceMessage(TraceEventType.Information, 186, $"ReadData failed; retries/limit={m_RetryCount}/{this.m_TextReaderProtocolParameters.MaxNumberOfRetries}."); return(AL_ReadData_Result.ALRes_DatTransferErrr); } m_statistic.IncStRxFrameCounter(); pData = new ReadDataEntity(_copy, pBlock); TraceSource.TraceMessage(TraceEventType.Verbose, 191, $"ReadData succeeded for [{pStation}/{pBlock.startAddress}]"); return(AL_ReadData_Result.ALRes_Success); }
/// <summary> /// Read Data /// </summary> /// <param name="block">Block description to be read</param> /// <param name="station">Address of the remote station connected to the common field bus. –1 if not applicable. /// </param> /// <param name="data">The frame with the requested data.</param> /// <param name="retries">Number of retries to get data.</param> /// <returns> /// ALRes_Success: Operation accomplished successfully /// ALRes_DatTransferErrr: Data transfer is imposible because of a communication error – loss of /// communication with a station /// ALRes_DisInd: Disconnect indication – connection has been shut down remotely or lost because of /// communication error. Data is unavailable /// </returns> AL_ReadData_Result IApplicationLayerMaster.ReadData (IBlockDescription block, int station, out IReadValue data, byte retries) { data = null; if (!m_protocol.GetICommunicationLayer.Connected) { return(AL_ReadData_Result.ALRes_DisInd); } T_ALMessage request = m_Pool.GetEmptyISesDBuffer(); T_ALMessage response; request.PrepareRequest(station, block); AL_ReadData_Result res = TxGetResponse(request, out response, retries); if (res == AL_ReadData_Result.ALRes_Success) { response.SetBlockDescription(station, block); data = (IReadValue)response; } else if (response != null && !((IEnvelope)response).InPool) { EventLogMonitor.WriteToEventLogInfo("TxGetResponse has failed and response != null && !( (IEnvelope)response ).InPool", 195); response.ReturnEmptyEnvelope(); } request.ReturnEmptyEnvelope(); m_protocol.GetIProtocolParent.RxDataBlock(res == AL_ReadData_Result.ALRes_Success); return(res); }
/// <summary> /// The get as bool. /// </summary> /// <param name="readValue"> /// The read value. /// </param> /// <param name="key"> /// The key. /// </param> /// <param name="defaultValue"> /// The default value. /// </param> /// <returns> /// The get as bool. /// </returns> public static bool GetAsBool([NotNull] this IReadValue <string> readValue, [NotNull] string key, bool defaultValue) { CodeContracts.VerifyNotNull(readValue, "readValue"); CodeContracts.VerifyNotNull(key, "key"); var value = readValue.Get(key); return(Equals(value, null) ? defaultValue : Convert.ToBoolean(value.ToLower())); }
/// <summary> /// Gets a value with a default value... /// </summary> /// <param name="readValue"> /// </param> /// <param name="key"> /// </param> /// <param name="defaultValue"></param> /// <typeparam name="T"> /// </typeparam> /// <returns> /// </returns> public static T Get <T>([NotNull] this IReadValue <T> readValue, [NotNull] string key, [CanBeNull] T defaultValue) { CodeContracts.VerifyNotNull(readValue, "readValue"); CodeContracts.VerifyNotNull(key, "key"); var value = readValue.Get(key); return(Equals(value, default(T)) ? defaultValue : value); }
/// <summary> /// Gets a value with a default value... /// </summary> /// <param name="readValue"> /// </param> /// <param name="key"> /// </param> /// <param name="getValue"> /// </param> /// <typeparam name="T"> /// </typeparam> /// <returns> /// </returns> public static T Get <T>([NotNull] this IReadValue <T> readValue, [NotNull] string key, [NotNull] Func <T> getValue) { CodeContracts.VerifyNotNull(readValue); CodeContracts.VerifyNotNull(key); CodeContracts.VerifyNotNull(getValue); var value = readValue.Get(key); return(Equals(value, default(T)) ? getValue() : value); }
public static T Get <T>( [NotNull] this IReadValue <string> readValue, [NotNull] string key, [CanBeNull] T defaultValue = default(T)) { if (readValue == null) { throw new ArgumentNullException(nameof(readValue)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } return(readValue.Get(key, () => defaultValue)); }
}//Tag internal virtual void UpdateAllTags(IReadValue val) { for (ushort idx = 0; (idx < mylength); idx++) { try { tagHendlers[idx].UpdateTag(val.ReadValue(idx, tagHendlers[idx].TagCanonicalType)); } catch (Exception ex) { tagHendlers[idx].MarkTagQuality(Opc.Da.qualityBits.badCommFailure); CommServerComponent.Tracer.TraceWarning(187, "DataBlock.UpdateAllTags", "An exception was thrown during data read: " + ex.Message); } } }
public static T Get <T>( [NotNull] this IReadValue <string> readValue, [NotNull] string key, [CanBeNull] T defaultValue = default(T)) { if (readValue == null) { throw new ArgumentNullException(nameof(readValue)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } string value = readValue.Get(key); return(value.IsDefault() ? defaultValue : value.ToType <T>()); }
/// <summary> /// Reads process data from the selected location and device resources. /// </summary> /// <param name="pBlock"><see cref="IBlockDescription"/> selecting the resource containing the data block to be read.</param> /// <param name="pStation">Address of the remote station connected to the common field bus. –1 if not applicable.</param> /// <param name="pData">The buffer <see cref="IReadValue"/> containing the requested data.</param> /// <param name="pRetries">Number of retries to get data.</param> /// <returns>Result of the operation</returns> public AL_ReadData_Result ReadData(IBlockDescription pBlock, int pStation, out IReadValue pData, byte pRetries) { pData = null; try { return(mDataProvider.ReadData(pBlock, pStation, out pData, pRetries)); } catch (Exception ex) { if ((pData != null) && !pData.InPool) { pData.ReturnEmptyEnvelope(); } pData = null; TraceException(ex, 46); return(AL_ReadData_Result.ALRes_DatTransferErrr); } }
public static T Get <T>( [NotNull] this IReadValue <string> readValue, [NotNull] string key, [NotNull] Func <T> getDefaultValue) { if (readValue == null) { throw new ArgumentNullException(nameof(readValue)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (getDefaultValue == null) { throw new ArgumentNullException(nameof(getDefaultValue)); } string value = readValue.Get(key); return(value.IsNullOrWhiteSpace() ? getDefaultValue() : value.ToType <T>()); }
public AL_ReadData_Result ReadData(IBlockDescription pBlock, int pStation, out IReadValue pData, byte pRetries) { Assert.IsTrue(myConnected, "Must be connected while ReadData"); MonitorEnter(); pData = null; myNumberOfReadOperations++; if (myBreakConnection) { myBreakConnection = false; myMakeError = false; myConnected = false; MonitorExit(); return(AL_ReadData_Result.ALRes_DisInd); } if (!myMakeError) { pData = new FacadeIReadValue(this); MonitorExit(); return(AL_ReadData_Result.ALRes_Success); } MonitorExit(); return(AL_ReadData_Result.ALRes_DatTransferErrr); }
/// <summary> /// Read Data /// </summary> /// <param name="block">Data block description to be read</param> /// <param name="station">Address of the remote station connected to the common field bus. –1 if not applicable. /// </param> /// <param name="data">The buffer with the requested data.</param> /// <param name="retries">Number of retries to get data.</param> /// <returns>Result of the operation</returns> AL_ReadData_Result IApplicationLayerMaster.ReadData(IBlockDescription block, int station, out IReadValue data, byte retries) { lock (this) { rPackNum++; data = null; data = (IReadValue)pool.GetEmptyISesDBuffer(); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); ((NULL_message)data).SetBlockDescription(station, block); ((NULL_message)data).ReadFromDB(); myStatistic.IncStTxFrameCounter(); myStatistic.IncStRxFrameCounter(); myStatistic.RxDataBlock(true); return(AL_ReadData_Result.ALRes_Success); } }
public override void Read(ReadArgs args) { IReadValue rv = args.Read.GetReadValue(); ValueRecord vr = args.ValueRec; int readChar = args.ReadOne(); switch (readChar) { case iBoolTrue: args.AddValue(true); rv.ReadValue(vr, args.valPos, true); break; case iBoolFalse: args.AddValue(false); rv.ReadValue(vr, args.valPos, false); break; case iStringEncl: String str = base.ReadStringStrict(args, false); args.AddValue(str); rv.ReadValue(vr, args.valPos, str); break; case iRefPrefix: Record rc = base.ReadRef(args, false); if (rc.RecType != RecordType.Instance && rc.RecType != RecordType.Array) { throw Error.UnexpectedRecordType(RecordType.Instance, rc.RecType); } args.AddValue(rc); rv.ReadValue(vr, args.valPos, rc); return; case iDateTimePrefix: DateTime dt = new DateTime( ReadDateTimeDigits(args, 4), ReadDateTimeDigits(args, 2), ReadDateTimeDigits(args, 2), ReadSkipOne(args, iDateTimeT).ReadDateTimeDigits(args, 2), ReadDateTimeDigits(args, 2), ReadDateTimeDigits(args, 2), ReadDateTimeDigits(args, 3) ); args.AddValue(dt); rv.ReadValue(vr, args.valPos, dt); break; case iFieldSep: args.AddValue(null); rv.ReadValueNull(vr, args.valPos); return; case iRecordSep: args.AddValue(null); rv.ReadValueNull(vr, args.valPos); args.State = ReaderNewRecord.Singleton; return; case -1: args.AddValue(null); rv.ReadValueNull(vr, args.valPos); args.State = ReaderEnd.Singleton; return; default: ReadNumber(args, readChar); return; } // fixed width values (bool, datetime) or values with delimiter (string) // still have one extra character to read in order to determine next step readChar = args.ReadOne(); if (readChar == iFieldSep) { args.State = ReaderField.Singleton; } else if (readChar == iRecordSep) { args.State = ReaderNewRecord.Singleton; } else if (readChar == -1) { args.State = ReaderEnd.Singleton; } else { throw Error.UnexpectedChars(Constants.FieldSeparator, (char)readChar); } }
AL_ReadData_Result IApplicationLayerSniffer.ReadData(out IBlockDescription block, out IReadValue data) { lock (this) { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); data = null; System.Random rand = new Random((int)(System.DateTime.Now.Ticks % 10000)); int station = 1; if (rand.Next(10) > 5) { station = 2; //tylko 2 stacje - 1 i 2 } data = (IReadValue)pool.GetEmptyISesDBuffer(); Medium_T dt = Medium_T.Flag; if (rand.Next(10) > 5) { dt = Medium_T.Register; // 50% szans ze to rejestry } int address = 0; // adres startowy 0-5 int len = 5; //maksymalna dlugosc bloku 5 object _value = false; for (int i = address; i < address + len; i++) { if (station == 1) { switch (dt) { case Medium_T.Flag: case Medium_T.Input: case Medium_T.Output: { _value = false; if (rand.Next(10) > 4) { _value = true; } break; } case Medium_T.Counter: case Medium_T.Register: case Medium_T.Timer: { _value = (int)rand.Next(1000); break; } } } else { switch (dt) { case Medium_T.Flag: case Medium_T.Input: case Medium_T.Output: { _value = false; break; } case Medium_T.Counter: case Medium_T.Register: case Medium_T.Timer: { _value = 0; break; } } } ((NULL_message)data).setDBTag(station, address, (short)dt, _value); } ((NULL_message)data).SetBlockDescription(station, address, (short)dt, len); ((NULL_message)data).ReadFromDB(); block = ((NULL_message)data); myStatistic.IncStTxFrameCounter(); myStatistic.IncStRxFrameCounter(); myStatistic.RxDataBlock(true); return(AL_ReadData_Result.ALRes_Success); } }//ReadData
}//ReadData #endregion #region IApplicationLayerSniffer /// <summary> /// Interface of the passive reader station, i.e. responsible for reading master station commands and slave station responses /// and gathering the data from coupled pairs. /// </summary> /// <param name="block">Data block description.</param> /// <param name="data">Message containing obtained data.</param> /// <returns> /// ALRes_Success: /// Operation accomplished successfully /// ALRes_DatTransferErrr: Data transfer is imposible because of a communication error – loss of /// communication with a station /// ALRes_DisInd: Disconnect indication – connection has been shut down remotely or lost because of /// communication error. Data is unavailable /// </returns> AL_ReadData_Result IApplicationLayerSniffer.ReadData(out IBlockDescription block, out IReadValue data) { bool resetanswer = false; SBUSbase_message SBUS_Frame1, SBUS_Frame2; AL_ReadData_Result res = GetFrame(out SBUS_Frame1, null, true, ref resetanswer); //otrzymalismy polecenie zapisu lub odczytu if (res == AL_ReadData_Result.ALRes_Success) { do { resetanswer = false; //TODO it is protected and must be used as an inherited member SBUS_Frame1.CalculateExpectedResulLength(); switch (SBUS_Frame1.cmd) { case SBUSbase_message.ProtocolCmd.coRS0: case SBUSbase_message.ProtocolCmd.coRS1: case SBUSbase_message.ProtocolCmd.coRS2: case SBUSbase_message.ProtocolCmd.coRS3: case SBUSbase_message.ProtocolCmd.coRS4: case SBUSbase_message.ProtocolCmd.coRS5: case SBUSbase_message.ProtocolCmd.coRS6: case SBUSbase_message.ProtocolCmd.coRS7: case SBUSbase_message.ProtocolCmd.coRR: case SBUSbase_message.ProtocolCmd.coRF: #region read if (GetFrame(out SBUS_Frame2, SBUS_Frame1, false, ref resetanswer) == AL_ReadData_Result.ALRes_Success) { if (!resetanswer) { // odczytywanie danych - wiec pierwsza przechwycona ramka zawiera opis bloku, // a druga zawiera wlasciwe dane block = SBUS_Frame1; data = SBUS_Frame2; m_ALProtocol.GetIProtocolParent.RxDataBlock(true); return(AL_ReadData_Result.ALRes_Success); } else { SBUS_Frame1 = SBUS_Frame2; } } m_ALProtocol.GetIProtocolParent.RxDataBlock(false); #endregion break; case SBUSbase_message.ProtocolCmd.coWR: case SBUSbase_message.ProtocolCmd.coWF: #region write if (GetFrame(out SBUS_Frame2, SBUS_Frame1, false, ref resetanswer) == AL_ReadData_Result.ALRes_Success) { if (!resetanswer) { // zapisywanie danych - wiec pierwsza przechwycona ramka zawiera opis bloku+dane, // a druga zawiera potwierdzenie czy jest OK //jesli w ostatnim IF bylo OK - tzn - ze dostalismy ACK: //wiec : block = SBUS_Frame1; SBUS_Frame2.PrepareDataResponse(block); for (int idx = 0; idx < block.length; idx++) { ((IResponseValue)(SBUS_Frame2))[idx] = ((IReadCMDValue)SBUS_Frame1)[idx]; } data = SBUS_Frame2; m_ALProtocol.GetIProtocolParent.TxDataBlock(true); return(AL_ReadData_Result.ALRes_Success); } else { SBUS_Frame1 = SBUS_Frame2; } } m_ALProtocol.GetIProtocolParent.TxDataBlock(false); #endregion break; default: break; } } while (resetanswer); } block = null; data = null; return(AL_ReadData_Result.ALRes_DatTransferErrr); }
public RegisterValueFormatter With <T>(IReadValue <T> value) { _value = _formatter.Format(value.Actual); return(this); }
}// Tag internal override void UpdateAllTags(IReadValue val) { base.UpdateAllTags(val); ResetCounter(); }
/// <summary> /// Read Data /// </summary> /// <param name="block">Block description to be read</param> /// <param name="station">Address of the remote station connected to the common field bus. –1 if not applicable. /// </param> /// <param name="data">The buffer with the requested data.</param> /// <param name="retries">Number of retries to get data.</param> /// <returns>Result of the operation</returns> AL_ReadData_Result IApplicationLayerMaster.ReadData(IBlockDescription block, int station, out IReadValue data, byte retries) { lock (this) { InterFrameStopwatch.Reset(); InterFrameStopwatch.Start(); m_rPackNum++; data = null; bool TransmissionIsOK = true; data = (IReadValue)pool.GetEmptyISesDBuffer(); //informacja ze dziala transmitter: ((Message)data).TransmitterON(station); //Timer.Wait( Timer.TInOneSecond ); ((Message)data).SetBlockDescription(station, block); ((Message)data).ReadFromDB(); myStatistic.IncStTxFrameCounter(); myStatistic.IncStRxFrameCounter(); myStatistic.TimeCharGapAdd(1); myStatistic.TimeMaxResponseDelayAdd(InterFrameStopwatch.ElapsedMilliseconds); ((Message)data).TransmitterOFF(station); if (m_errorfrequency > 0 && (m_rPackNum % (100 / (ulong)m_errorfrequency)) == 0) { TransmissionIsOK = false; } if (TransmissionIsOK && ((Message)data).TestCommunication(station)) { myStatistic.RxDataBlock(true); return(AL_ReadData_Result.ALRes_Success); } else { myStatistic.RxDataBlock(false); data.ReturnEmptyEnvelope(); data = null; return(AL_ReadData_Result.ALRes_DatTransferErrr); } } }
internal void UpdateAllTags(IReadValue val) { myInterface.myRetries.MarkSuccess(); myData.UpdateAllTags(val); }
/// <summary> /// Read Data /// </summary> /// <param name="block">Block description to be read</param> /// <param name="station">Address of the remote station connected to the common field bus. –1 if not applicable. /// </param> /// <param name="data">The buffer with the requested data.</param> /// <param name="retries">Number of retries to get data.</param> /// <returns>Result of the operation</returns> AL_ReadData_Result IApplicationLayerMaster.ReadData(IBlockDescription block, int station, out IReadValue data, byte retries) { lock (this) { m_rPackNum++; data = null; myStatistic.IncStTxFrameCounter(); if ((m_errorfrequency > 0) && (m_rPackNum % (ulong)m_errorfrequency == 0)) { myStatistic.IncStRxFragmentedCounter(); myStatistic.RxDataBlock(false); return(AL_ReadData_Result.ALRes_DatTransferErrr); } data = (IReadValue)pool.GetEmptyISesDBuffer(); // Processes.Timer.Wait(Processes.Timer.TInOneSecond/4); ((NULL_message)data).SetBlockDescription(station, block); ((NULL_message)data).ReadFromDB(); bool success = true; if (CommunicationThroughCommunicationLayer) { success = SendReceive(); } if (success) { myStatistic.IncStRxFrameCounter(); } myStatistic.RxDataBlock(success); return(AL_ReadData_Result.ALRes_Success); } }
AL_ReadData_Result IApplicationLayerSniffer.ReadData(out IBlockDescription block, out IReadValue data) { throw new NotImplementedException("using IApplicationLayerSniffer.ReadData is not valid for this DataProvider"); }//ReadData