Compare commits

...
Author SHA1 Message Date
michal c8b5732046 Fix Genesis scheduling and synchronization for up to 10 workers
(cherry picked from commit 684513ee59)
2026-09-10 22:59:56 +02:00
michal 02de7c6c57 FIX GENESIS
Enhance Genesis configuration and validation mechanisms

- Introduce new test methods for testing Genesis properties, boundary validations, runtime behavior, and tooltips with culture-specific fallback.
- Expand configuration validation logic with enhanced error messaging and logging.
- Simplify Genesis property UI: remove legacy settings and refactor controls for robust behavior.
- Add detailed logging for runtime and configuration updates.
- Provide tooltips and localized support for Genesis properties in multiple languages (e.g., `de`, `sk`).
- Update project file to include new test files.
2026-09-10 21:33:55 +02:00
michal 52bd0d01ce Restore Genesis communication and Q3 calibration from special branches
A – Registration and execution
- Register GenesisCommunication Factory in the component list.
- Separate the Genesis form and sequence from iPerl communication.

B – Communication activities
- Restore initialization, connection, PCB reading, password and login.
- Include grouped login, mode switching and disconnection.
- Support processing up to 10 slots.

C1 – Input calibration factors
- Read three factors from Water meters / Text1–Text3.
- Validate integer values in the range 1–65535.
- Preserve the default of 15625 when all three fields are empty.

D – Q3 calibration
- Connect the Prepare Q3 → measurement → Write Q3 workflow.
- Add channel processing to FlyingStart and FlyingStartMassCollection.
- Reset previous measurement data and validate calculated factors.
- Mark factors as stored only after StoreCalibration succeeds.

E – Results and database
- Store calibration factors separately for each meter and channel.
- Add result entities, mappings and Q3 data.
- Extend DB.cs / EnsureSchema to create and update the schema.
- Preserve compatibility with the existing binary format.

Validation:
- Debug build and 18 tests passed.
- Simulated communication runs follow the same activity sequence.
- The complete Q3 workflow has not yet been verified on hardware.

Known limitation:
- An inherited mismatch in simulated responses and error propagation
  can produce an incorrect OK result; this change does not fix it.
2026-09-09 15:04:49 +02:00
michal 88b8bc5534 fix precision correct factor (Mexico), added diff, correction in percentage in Result Configuration 2026-09-07 14:07:07 +02:00
marekf d3c8813012 <Fix>: Correct test-dependent result evaluation in ResultsWriter, increase revision to 3.9.3145.101
Cause:

- ResultsWriter evaluated selected test-dependent items without the actual TestID.
- This caused values such as Test passed(), timestamps, flow, pressure, temperature, conductivity and error data to be empty or incorrect.

Solution:

1. Fixed test-aware result evaluation
   - Uses published regular meter test results.
   - Passes mtr.Name() as TestID to item.Print(wm, testId).

2. Restored correct test result mapping
   - Test-dependent values are now resolved from the correct TestRslt / MeterTestRslt.

3. Increased revision
   - Updated revision to 3.9.3145.101.
2026-09-03 10:00:40 +02:00
marekf 054075a341 <Feat>: Add XML result generation with file and MSSQL output support, increase revision to 3.9.3145.100
Cause:

- ResultsWriter required a generic way to generate customer-specific XML result data from TBF measurement results.
- The customer reference XML contains example runtime values and repeated result structures, so it cannot be used directly as the generated output.
- TBF result variables must be explicitly mapped to destinations in the customer XML structure.
- The generated XML result data must support two output targets:
  - direct creation of an XML file,
  - delivery of the XML payload to a Microsoft SQL stored procedure.
- Preview generation must allow the XML structure and configured mappings to be verified without executing the production database write.
- Increase revision to 3.9.3145.100.

Solution:

1. Added XML reference analysis
   - Creates a clean base XML structure.
   - Extracts the repeating result prototype.
   - Prevents sample runtime values from the customer reference XML from leaking into generated results.
2. Added configurable TBF-to-XML result mapping
   - Allows explicit mapping of TBF result variables to customer XML destinations.
   - Supports one-time and repeating XML destinations.
   - Keeps the mapping independent of the semantic meaning of customer XML attribute names.
3. Added XML destination viewer and configurator
   - Shows the current mapping.
   - Highlights repeating destinations.
   - Identifies already used one-time destinations.
4. Added runtime XML result generation
   - Uses the configured TBF-to-XML mappings.
   - Uses measurement procedure result data.
   - Builds the output from the clean base XML and repeating XML prototype.
   - Generates repeated result records according to the executed measurement procedure.
5. Added simulation-based Preview request
   - Generates a complete XML payload using simulation values.
   - Allows XML structure and mapping verification before production execution.
   - Does not execute the production stored procedure.
6. Added direct XML file output support to UniDataStorageWriter
   - Supports File / .xml as a physical output target.
   - Creates the generated XML result file in the configured output directory.
7. Added Microsoft SQL stored-procedure XML output
   - Supports Microsoft SQL / StoredProcedure as a physical output target.
   - Passes the generated XML payload through the configured stored procedure parameter.
8. Added optional XML payload archiving
   - Allows generated XML payloads to be stored in the configured Payload archive.
   - Can be used together with the Microsoft SQL stored-procedure output.
9. Kept ResultsWriter independent of the physical output target
   - ResultsWriter generates the result payload.
   - UniDataStorageWriter decides how and where the payload is physically written.
   - The same ResultsWriter XML generation mechanism is therefore used for both XML file and MSSQL outputs.
10. Increased revision
   - Updated revision to 3.9.3145.100.
2026-09-02 12:05:10 +02:00
marekf a0d53f9ec9 <Fix>: RefPulses carry-over by restoring testInProgress behavior in StandingStart, increase revision to 3.9.3145
Cause:
1. Background: Restore/ensure testInProgress behavior before the DataEntry sequence and explicitly prevent to reset the pulse.
2. Increase revision to 3.9.3145

Solution:
1. Deleted .AddOperation(testInProgress) calling
2. Increased revision to 3.9.3145
2026-08-25 13:49:49 +02:00
michal dfa8693be9 Added table columns TestRslt -> ConductMean, .... 2026-08-25 10:38:08 +02:00
marekf 1e45f48c75 <Update>: Version to 3.9.3144.0 in AssemblyInfo files 2026-08-25 08:23:27 +02:00
marekf d833eca584 <Merge_Fix>: System.Data.SQLite, System.Data.SQLite.Core, Stub.System.Data.SQLite.Core.NetFramework 2026-08-24 15:36:50 +02:00
marekf c966a7034c <Merge-Fix>: Solve merge conflicts 2026-08-24 15:04:11 +02:00
marekf f051d51ae0 <Fix>: Incorrect cycle resume behavior after Stop and Start, increase revision to 3.9.3134.114
Cause:
1. When the Cycle was stopped during the second or a later test and then resumed using the Start Test button, the resume confirmation was handled incorrectly. After selecting to continue, the sequence restarted from the first test instead of continuing from the interrupted test.
2. Increase revision to 3.9.3134.114

Solution:
1. Corrected the Cycle resume logic so that, after confirming continuation, the sequence resumes from the interrupted test instead of restarting from the first test.
2. Increased revision to 3.9.3134.114
2026-08-24 14:25:19 +02:00
marekf 267159e0a9 <Fix>: RefPulses carry-over by restoring testInProgress behavior in StandingStart, increase revision to 3.9.3134.113
Cause:
1. Background: there was a suspicion that the Bukoven board left RefPulses active across operations; this was investigated and ruled out. The pulse counter is reset by testInProgress when an operation is reused. During the third DataEntry window testInProgress had been temporarily disabled (SLM vs Karlsruhe difference), which allowed RefPulses to appear to persist.
2. Increase revision to 3.9.3134.113

Solution:
1. Restore/ensure testInProgress behavior during the DataEntry sequence and explicitly reset the pulse counter when starting a new operation.
2. Increased revision to 3.9.3134.113
2026-08-24 12:54:15 +02:00
michal 26db172153 Camera WM Purchase Order - crop disabled 2026-08-24 12:21:49 +02:00
michal 2e75f65b4a Update version to 3.9.3142.0 in AssemblyInfo files 2026-08-20 00:27:39 +02:00
michal 432cb91e5a Update Flip Mode handling and introduce SetTestModeOpto7Str alias
Refactor Flip Mode parameter type in `WMeterRsltItemSpec` to `Quantity.String` for consistency. Add `SetTestModeOpto7Str` alias to improve readability and replace legacy A0 test mode reference in `iPerlCommunicationParams`.
2026-08-20 00:27:06 +02:00
michal b0083afa10 DataEntry.UNI - timeout, autoclose improve
Introduce configurable timeouts for data entry volume reads in `IRegReaderSmart` and its implementations: added optional timeout parameters and updated default values across associated forms and methods. Updated `EntryFormCfg` to support customizable timeout settings.
2026-08-19 23:47:50 +02:00
michal 955b59a195 Improve UNI Data Entry auto close
Add tooltip functionality for parameter names in `ComponentCfgCtrl` and auto-close countdown improvements in UNI Data Entry forms
2026-08-19 22:32:14 +02:00
michal b904d0ca41 Fix Flip Mode - ver. 3.9.3141.0
Add robust handling for form closure in UNI Data Entry: prevent operations on disposed/closing forms, enhance logging, and update logic in serial number and volume updates. Increment version to 3.9.3141.0.
2026-08-19 19:13:41 +02:00
michal f34046df2a Update version to 3.9.3140.0 in AssemblyInfo files - FIX DataEntry.UNI 2026-08-19 14:49:24 +02:00
michal 889782068e Added counter to OK button, 5 sec default now
Add auto-close countdown timer for UNI data entry forms: implement timer logic, UI updates, and early exit handling
2026-08-19 14:47:34 +02:00
michal d12ee008db FIX UNI Data Entry - Smart Reader + missing files
Implement smart meter interface enhancements for AllyReader: Add `ISmartMeterReader` interface, update `RegisterReaderSelection` logic, integrate smart-meter position selection, and expand unit test coverage.
2026-08-19 14:33:06 +02:00
michal 6c3c6cd0ef FIX UNI Data Entry - corrensponded with iPerlCommunicationForm.cs
Add debug logging and UI enhancements for data entry processes: Improve register reader handling in sequences and forms, add detailed data entry debug logs, integrate serial number and volume watermarking, and update localized strings in multiple languages.
2026-08-19 13:18:34 +02:00
michal 5803f06bdb Flip mode related to test result - DB column in MeterTestRslt, support back compability
Add Flip Mode support across iPerl-related test methods and database schema: implement FlipMode property, update MeterTestRslt mappings, integrate schema migration logic, and refine test result handling.
2026-08-19 11:52:46 +02:00
michal a4acf30771 Refactor FlipMode enum and update references: rename DisabledConstant to Constant and EnabledRandomized to Randomized across codebase, including unit tests and integration tests, for improved readability and consistency. 2026-08-19 10:47:45 +02:00
michal a4ef208233 Fix ver. 3.9.3139 iPerlCommunicationForm.cs problems + exceptions if another regreadrer has mistakely same ports
Enhance iPerl dialog layout and error handling: improve `ShuffleTextBoxes` with positional mapping, refine checkbox state tracking, add detailed logging for labels and checkboxes, and handle serial port exceptions. Increment version to 3.9.3139.0.
2026-08-18 16:09:21 +02:00
michal be6b40b5cd Fix Optical heads ASIC iPerl dialog manual test communication 2026-08-18 14:05:33 +02:00
michal 8738edd0c5 Added FLIP MODE Constant, Randomised
Add support for Flip Mode configuration in iPerl: Implement `SetFlipMode` functionality in `OptoHeadTest` and `RadioService`, integrate constants, enhance UI, and add unit and integration tests for constant/randomized flip mode settings.
2026-08-18 13:59:59 +02:00
michal c71fe75446 Ally iPerl initial - reader,test method, unit test
Add AllyReader and AllyCalibration support with tests: Introduce new register readers, calibration methods, and comprehensive unit tests for integration and functionality validation. Update project files accordingly.
2026-08-18 10:01:02 +02:00
michal c619c7d3b8 Merge remote-tracking branch 'private-origin/develop/SLM-PT50_genesisDirectDecode' into develop/SLM-PT50_genesisDirectDecode 2026-08-17 10:27:57 +02:00
michal f3e5527145 ver. 3.9.3138.0 - OPTHO FORMATING improve (ASIC,genesis) 2026-08-17 10:27:10 +02:00
michal 39941842d4 OPTHO FORMATING improve (ASIC,genesis)
Enhance iPerlHat protocol logging and error handling: add optical HEX formatting, improve diagnostic messages, and extend test command descriptions.
2026-08-17 10:25:35 +02:00
michal 3488939995 FIX iPerl ASIC meter - mexico
Update MultiplyFactor constant to 1 and increment version to 3.9.3137.0
2026-08-14 14:14:33 +02:00
michal 0f2ef5a5bf bugfix IPERL_ASIC conductivity
update mappings , version 3.9.3136.0
2026-08-13 15:16:58 +02:00
michal 55d2381e8a Mexico - read additional parameters and store to DB, ver. 3.9.3135.0
Add support for reading and handling additional common parameters in OptoHeadTest. Extend RadioService and related classes with enhanced parsing and validation logic. Update UI and constants for functionality integration.
2026-08-12 16:20:16 +02:00
michal 126322584f Merge remote-tracking branch 'private-origin/develop/SLM-PT50_genesisDirectDecode' into develop/SLM-PT50_genesisDirectDecode 2026-08-05 12:48:48 +02:00
michal 4d9ddef3ca IperlASIC - added aditional parameters
Add support for reading additional common parameters in OptoHeadTest. Enhance `RadioService` and `VersionTypeResult` with new parsing logic. Update related constants and UI elements for functionality integration.
2026-08-05 10:57:34 +02:00
marekf 7139cdbe80 Merge branch 'develop/SLM-PT50-7-2026-merged-smart-cam-slm-mex' into develop/SLM-PT50_genesisDirectDecode 2026-08-04 16:31:57 +02:00
marekf 93d7456ccd <Fix>: RefPulses carry-over by restoring testInProgress behavior in StandingStartMassCollection, increase revision to 3.9.3134.112
Cause:
1. Background: there was a suspicion that the Bukoven board left RefPulses active across operations; this was investigated and ruled out. The pulse counter is reset by testInProgress when an operation is reused. During the third DataEntry window testInProgress had been temporarily disabled (SLM vs Karlsruhe difference), which allowed RefPulses to appear to persist.
2. Increase revision to 3.9.3134.112

Solution:
1. Restore/ensure testInProgress behavior during the DataEntry sequence and explicitly reset the pulse counter when starting a new operation.
2. Increased revision to 3.9.3134.112
2026-08-04 16:21:33 +02:00
michal 7a8ce7b6ab IperlASIC - Improved and added tests, hardware integtration tests works
Improve `VersionTypeResult` parsing and handling: Add compact/legacy payload support. Extend `ReadingUnits`. Update `IperlHatIntegrationTests` and `RadioService` with new tests and functionality integration.
2026-08-04 11:53:47 +02:00
michal 865528e344 iPerlASIC - additional parameters.
Add protocolCommons classes and enhance RadioService with support for CalibrationFactor, VersionType, ReadingUnits, and FlipMode operations. Add corresponding unit tests for validation. Update project files.
2026-08-03 15:42:16 +02:00
michal 02bb9ee9fa Update RadioService: Replace IsLoggedOn with IsConnected condition checks 2026-07-31 14:09:10 +02:00
marekf 79de40515a Upgrade: Deleted LANG_PL compilation condition, disabled legalizator before test, and version to 3.9.3134.111
Cause:
1. Unnecessary and mandatory user verification before the test, in addition, a bug appears: the "Approval by legalizer" window is displayed behind the main application window. The window was only needed for the Polish project.
2. `LANG_PL` constant in `TBF.csproj` was no longer needed.
3. Assembly version and file version in `AssemblyInfo.cs` needed to be incremented to `3.9.3134.111`.

Solution:
1. Made `altProcNameLabel` and `altProcNameTextBox` always visible and disabled specific UI controls in `ProcedureDlg.cs`.
2. Removed `LANG_PL` from `DefineConstants` in `TBF.csproj`.
3. Updated assembly version and file version in `AssemblyInfo.cs` to `3.9.3134.111`.
2026-07-28 11:49:37 +02:00
marekf e38c6c1199 Upgrade: Add remaining time display for tests, version 3.9.3134.110
Cause:
1. Missing functionality to display remaining time during tests in `StandingStartMassCollectionSeq.cs` and `StandingStartMassCollectionAdvanceSeq.cs`.
2. Assembly version and file version required an update to reflect changes.

Solution:
1. Implemented remaining time display in `StandingStartMassCollectionSeq.cs` and `StandingStartMassCollectionAdvanceSeq.cs` using `Bridge.OnActivity` to show time in minutes and seconds or seconds only.
2. Updated assembly version and file version in `AssemblyInfo.cs` to `3.9.3134.110`.
2026-07-28 11:32:53 +02:00
marekf dbb35a203e Update: Adjust input unit constants in DataEntry form and increment version to 3.9.3134.109
Cause:
1. Updated `unit` constant in `TestStartEndForm` class within `TBF.Rig.DataEntry.StandardCamera` namespace from `Unit.m3` to `Unit.l`.
2. Updated `unit` constant in `TestStartEndForm` class within `TBF.Rig.DataEntry.StandartCameraPurchaseOrder` namespace from `Unit.m3` to `Unit.l`.
3. Incremented assembly version and file version in `AssemblyInfo.cs` to `3.9.3134.109`.

Solution:
1. Changed `unit` constant in `TestStartEndForm` class within `TBF.Rig.DataEntry.StandardCamera` namespace to `Unit.l`.
2. Changed `unit` constant in `TestStartEndForm` class within `TBF.Rig.DataEntry.StandartCameraPurchaseOrder` namespace to `Unit.l`.
3. Updated assembly version and file version in `AssemblyInfo.cs` to `3.9.3134.109`.
2026-07-28 07:38:30 +02:00
marekf a88a094e86 Release SLM-PT50 3.9.3134.108, increase revision after merge 2026-07-23 13:08:52 +02:00
marekf ffaebbdf07 Merge branch 'develop/SLM-PT50_genesisDirectDecode' of http://87.197.120.129:33300/michal/tbf into develop/SLM-PT50 2026-07-23 12:57:20 +02:00
michal e7d04b55b3 Live Stream Operations: Add StartLiveStream to CJMS11 camera 2026-07-22 10:02:22 +02:00
michal 8301971906 Fix StartEndForm in StandartCameraPurchaseOrder layout and positioning, remove Scroll Bar 2026-07-21 16:03:43 +02:00
michal 693cf7e4e2 Refactor TestStartEndForm - Remove unused methods and comments, simplify image grouping logic. 2026-07-21 15:22:50 +02:00
michal 2fa212e6ff FIX CAMERA - Improve error handling, modularize image processing functions for CJMS11 cameras, and enhance multi-image support in TestStartEndForm. 2026-07-21 14:50:59 +02:00
marekf a210a0d1f2 Upgrade (UniDataStorageWriter): improve writer configuration UX and CSV handling
- added technology-specific default configuration for new writers
- auto-fill default SQL/XLSX write templates
- disabled write templates for CSV technology
- added technology-specific data source hints
- changed test parameter format to Column=Value and Where=Value;Set=Value
- improved parameter validation to prevent invalid input crashes
- added automatic CSV header creation and header validation
- aligned CSV writer behaviour with XLSX writer
- Increase revision number
2026-07-21 11:18:11 +02:00
marekf 4cd191fcb2 Merge branch 'develop/SLM-PT50-7-2026-merged-smart-cam-slm-mex' into develop/Mexico-6-2026 2026-07-20 15:54:01 +02:00
marekf e21833fb5f Release Mexico 3.9.3069.1 2026-07-20 15:47:06 +02:00
marekf b746ceb34a Upgrade - Replace PulsesTypeByQuantity with MultiFunctionalVariables unit filtering based on RegisterReader quantity type - remove PulsesTypeByQuantity-based parameter values
- generate available units using Units.IsQuantity(...)
- use Quantity.MultiFunctionalVariables to populate supported units
- centralize unit selection through Units.GetQuantity()
2026-07-20 14:09:29 +02:00
marekf 83c1f0e817 Update - Actualized revision nr. 2026-07-17 14:15:22 +02:00
marekf a88a5a8db2 Fix - 1. StandingStartMassCollection and StandingStartMassCollectionAdvance - changed all delayed Activity strings, 2. Added UI/Bridge onDelayedActivity() method for universal using 2026-07-17 14:15:04 +02:00
marekf 271200a8da Upgrade - StandingStartMassCollectionAdvance method - 1. changed structure and residual flow delays by changes in StandingStartMassCollection method, 2. added variables, counting and evaluation for volume/mass type of RegisterReader 2026-07-17 12:42:07 +02:00
marekf b703297f5e Fix - 1. repaired StandingStartMassCollection MassEN evaluation, the problem was caused by the end scale measuring only after recalculating the basic values - 2. removed fixed delay for the first diverter switching and first diverter switching was moved after a configurable delay - 3. hidden unitComboBox in the StartEnd dialog of the DataEntry.Standard24 component, because units are now defined using the RegisterReader component 2026-07-17 09:55:03 +02:00
marekf 637d1d021d Fix - StandingMassCollection method - add end mass measurement 2026-07-16 15:19:28 +02:00
marekf dbe424b17a Add - StandingStart method - Store and log default PumpPower for dynamic test repetitions - Read PumpPower from the current pump before starting dynamic tests.
- Store the value as the default PumpPower for subsequent test instances in the cycle.
- Add logging when PumpPower is initialized from the pump.
- Add logging at test start including test name, repetition number,
  last repetition flag, and PumpPower to improve diagnostics.
2026-07-16 14:21:00 +02:00
marekf be0525a319 Upgrade - improved StandingStart method by SLM requirements, added fixed delays for meters stabilization 2026-07-16 13:29:42 +02:00
marekf 0ce130f0ef Fix - repaired merging compatibility problem of GCI return type GciConnectResult - IsLoggedOn and IsConnected, increased VisualStudio version from 17.8 to 18.5 2026-07-16 12:37:59 +02:00
michal c1ee29cd06 Merge remote-tracking branch 'private-origin/develop/SLM-PT50_genesisDirectDecode' into develop/SLM-PT50_genesisDirectDecode 2026-07-16 12:28:36 +02:00
michal 28607e2729 fix Strings - Camera CJMS11 - support dialog multi pictures 2026-07-16 12:28:28 +02:00
michal f1bc71fb92 Camera CJMS11 - support dialog multi pictures 2026-07-16 12:19:27 +02:00
michal 69b607f963 Merge remote-tracking branch 'private-origin/develop/SLM-PT50_genesisDirectDecode' into develop/SLM-PT50_genesisDirectDecode
# Conflicts:
#	TBF/TBF.csproj
2026-07-16 10:28:15 +02:00
marekf 6ac3ea87ef Upgrade - improved StandingStartMassCollection method by SLM requirements, added fixed delays, added residual flow delays 2026-07-16 09:30:59 +02:00
marekf 38973e0030 Add - Store and log default PumpPower for dynamic test repetitions - Read PumpPower from the current pump before starting dynamic tests.
- Store the value as the default PumpPower for subsequent test instances in the cycle.
- Add logging when PumpPower is initialized from the pump.
- Add logging at test start including test name, repetition number,
  last repetition flag, and PumpPower to improve diagnostics.
2026-07-15 11:35:32 +02:00
marekf 37c89a4c9c Fix - missing safe shutdown when PerformSteps returns UiCmdStop
- When STOP is pressed during PerformSteps() in the BeforeTest transition,
Transition() returned immediately and skipped the common shutdown logic.
This caused FM pumps and valves to remain in their previous state.
- Perform the required safe shutdown (FM pump off and default valve setup)
before returning UiCmdStop or Error.
2026-07-14 14:41:53 +02:00
marekf 0075362f92 Fix - Handle scale underload condition
- Added Underload measurement state
- Detect underload responses from Mettler Toledo scales
- Automatically zero the scale after underload detection
- Restart mass measurement after successful zeroing
- Prevent zeroing response from being used as a valid measurement
- Preserve measurement stability by clearing buffered readings after underload
2026-07-13 14:01:57 +02:00
marekf 38d28599ad Merge branch 'develop/SLM-PT50_genesisDirectDecode' of http://87.197.120.129:33300/michal/tbf into develop/SLM-PT50 2026-07-03 13:37:26 +02:00
marekf c9a4b0f3ce Add (develop) - component ResultsWriter - added diag + english comments 2026-07-03 13:35:39 +02:00
marekf b74f1fd644 Add (develop) - first succesfull test - new component ResultsWriter - note: IResultsProcessor type componet, store result variables to database by using of component UniDataStorageWriter to the user-configured storage. The selection of variables is done using the standard UI for selecting the display of measurement results . In other words: The measurement results selected by the user are saved to a user-defined storage. 2026-07-03 12:46:56 +02:00
michal 26b7aa7e8b correction atempt MultiplyFactor for timestamp, volume calculation, 2026-07-02 23:53:15 +02:00
michal 92f63e744d fix INIT - Overload time fix for OptoTelegramRawTest 2026-07-02 23:24:00 +02:00
michal b0581d81ef Extend measurement window for low-flow tests 2026-07-02 23:08:28 +02:00
michal 540b9af871 Overload time fix for OptoTelegramRawTest 2026-07-02 22:32:19 +02:00
michal d11f7107fe fix time calculation from raw data 2026-07-02 21:49:01 +02:00
michal 3c5a28f69d changed LED state from 4 to 7 in 2026-07-02 21:47:14 +02:00
marekf 110b880304 Add (release) new component Modbus.WaterAnalyzerUni derived from original component Modbus.WaterAnalyzer. New component is expanded by the possibility to choose conductivity reading directly from the sensor (Modbus protocol) (original solution) or using a 4-20mA converter to serial line (RS232/485) (Modbus protocol). 2026-07-02 09:01:00 +02:00
marekf 7867044c0a Add (develop) new component ConductivityMeter, because we have papouch AD4RS converter (4-20mA to modbus) - first correct version for testing 2026-07-01 15:58:36 +02:00
marekf 88903f3dac Merge branch 'feature/task/Cordonel-preadjustmentUI-GenesisMeter-ZeroFlowGenesisMeter' into develop/UnionTown 2026-06-12 10:44:51 +02:00
marekf 4e223549ee Develop - GciBridge -> GCI -> PreadjustmentUI functions 7 - successful processes - testbench is exported to UnionTown - without CalibParams DB writer 2026-06-12 10:43:34 +02:00
marekf 2ea0df8faf Develop - GciBridge -> GCI -> create database core in GCI - SkeletoKey - CalibParams - first ok 2026-06-09 19:55:36 +02:00
marekf 061e85ca6b Develop - GciBridge -> GCI -> PreadjustmentUI functions 6 - first successful processes - without CalibParams DB reader and CalibParams DB writer 2026-06-09 08:53:54 +02:00
marekf 269e650b38 Merge branch 'feature/task/SWDocumentation-DocFX' into develop/UnionTown 2026-06-08 10:29:04 +02:00
marekf a3bfc7a43e Develop - GciBridge -> GCI -> PreadjustmentUI functions 5 2026-06-05 15:21:18 +02:00
marekf c2ff40d816 Develop - GCI - create documentation model 2, using DocFX tool - using .md files - output as html page 2026-06-02 07:26:36 +02:00
marekf eb09ae2eca Develop - GCI - create documentation model, using DocFX tool - using .md files - output as html page 2026-05-29 09:49:28 +02:00
marekf d1b6247bb7 Develop - GciBridge -> GCI -> create database core in GCI - SkeletoKey - CalibParams 2026-05-29 09:43:51 +02:00
marekf c5f52e06fa Develop - GciBridge -> GCI -> PreadjustmentUI functions 4 2026-05-26 10:51:18 +02:00
marekf 9700ba7900 Develop - GciBridge -> GCI -> PreadjustmentUI functions 3 2026-05-22 08:52:40 +02:00
marekf bc72130d09 Develop - GciBridge -> GCI -> PreadjustmentUI functions 2 2026-05-21 08:16:02 +02:00
marekf ad208f9633 Develop - GciBridge -> GCI -> PreadjustmentUI functions 2026-05-18 19:20:10 +02:00
marekf ad2bfd3639 Upgrade (develop) - GCI - GciBridge - improved Disconnect 2026-05-14 13:05:21 +02:00
marekf 5e637ae02e Upgrade (develop) - GCI - GciBridge - full parallel threading slots actions 2026-05-13 09:30:27 +02:00
marekf 63f8dd7467 Upgrade (develop) - GCI - GciBridge - InitSlot() - only ports config update if slot already exists 2026-05-12 14:59:15 +02:00
marekf aac3af8714 Upgrade (develop) - GCI - GciBridge - delete meter.Logout() in GetPcbId() 2026-05-12 14:20:24 +02:00
marekf 378917f59d Upgrade (develop) - GCI - GciBridge - GCI-Laatzen interface debugging 2026-05-12 13:30:21 +02:00
marekf 76e7ccb4a6 Update (develop) - GCI - GciBridge - better return for Connect 2026-05-11 17:14:56 +02:00
marekf 953b02a6e8 Upgrade (develop) - GCI - GciBridge - new CleanSlot() - Disconnect Hard Dispose 2026-05-08 11:49:14 +02:00
marekf 71a66dca2d File modified due to the need for MF to compile in advance, but the change is ultimately not necessary for either MF or MB 2026-05-07 18:23:50 +02:00
marekf 978c620287 Update (develop) - GCI - GciBridge - improved PublicModels - fixed bugs 2026-05-07 18:20:18 +02:00
marekf 8489dafdf7 Update (develop) - GCI - GciBridge - progress 2026-05-06 14:58:44 +02:00
michal cfc52f195b Merge remote-tracking branch 'private-origin/develop/SLM-PT50_genesisDirectDecode' into develop/SLM-PT50_genesisDirectDecode
# Conflicts:
#	TBF/TBF.csproj
2026-05-06 10:26:15 +02:00
michal 68a1eb9941 Update project references and paths to replace project dependencies with direct DLL references. Standardize formatting in GenesisImplHeadTestCtrl and refine Operations enum declarations. 2026-05-06 10:24:33 +02:00
marekf c1573390b5 Merge branch 'develop/UnionTown' into develop/SLM-PT50 2026-05-06 09:08:09 +02:00
marekf 5d60523e87 Fixed - next issue with old Newtonsoft.Json v 12.0 - updated to 13.0 2026-05-06 07:38:49 +02:00
marekf 91c63e0792 Fixed - bad copying GenesisCordonelInterface runtime files to TBF target folder 2026-05-06 07:35:17 +02:00
marekf 0940df2f1a Fixed - issue with old Newtonsoft.Json v 12.0 - updated to 13.0 2026-05-06 07:32:55 +02:00
michal 16a76720b8 Update references and paths for Xylem.Common components, refine OptoHeadTest handling for connection requests, and increment assembly version to 3.9.3063.1. 2026-05-05 08:34:21 +02:00
marekf 7101fd679e Merge branch 'develop/UnionTown' into develop/SLM-PT50 2026-05-04 15:45:07 +02:00
marekf 86299da682 Fixed - bad runtime files copying in postbuilding of GenesisCordonelInterface project. Copying is replaced from TBF/Build/ to GCI/Build 2026-05-04 15:40:05 +02:00
marekf 39b951b709 Merge branch 'develop/UnionTown' into develop/SLM-PT50 2026-05-04 13:08:10 +02:00
marekf a475bd80f3 Change - ExternalProjects folder to gitignore 2026-05-04 13:07:28 +02:00
marekf 4e64bcd117 Merged branch Uniontown - GenesisCordonelInterface + GciBridge 2026-05-04 12:49:02 +02:00
marekf fbd0219a4a Update (develop) GCI - GciBridge - big change - for implement to GenesisHead and SmartReader 2026-05-04 11:29:13 +02:00
michal 104a68d9dc Remove unused System.IO.Ports, Common, Config, and other redundant namespaces. Update NuGet package configurations to reflect new paths and tools. 2026-04-29 09:51:05 +02:00
michal 33a5e479a9 Refactor RadioService to improve asynchronous handling, replace legacy code with CommInterfaceBridge, and standardize methods for GenesisHead communication. Remove unused GenesisCommunication components and increment assembly version to 3.9.3062.1. 2026-04-28 16:26:26 +02:00
michal 5482d4ac96 Merge remote-tracking branch 'private-origin/develop/SLM-PT50_genesisDirectDecode' into develop/SLM-PT50_genesisDirectDecode
# Conflicts:
#	TBF/Rig/TestMethods/GenesisCommunication/GenesisHead/GenesisHead.cs
#	TBF/TBF.csproj
2026-04-28 07:51:09 +02:00
michal 0d984a77b3 Refactor RadioService to utilize GciBridge for communication, replace SerialDriver, and add SlotNr support in Genesis configuration and UI. 2026-04-28 07:08:53 +02:00
marekf 7e95e18207 Fixed - genesis library path issue 2026-04-27 16:52:50 +02:00
marekf 38fa86d243 Merge branch 'develop/UnionTown' into develop/SLM-PT50 2026-04-27 16:42:47 +02:00
marekf 4c1ce73de9 Upgrade (develop) - GCI - GciBridge - big change 2026-04-27 16:40:42 +02:00
michal eea80d39c0 Remove GenesisCommunication test methods and components:
- Deleted `CalibrationStruct`, `ConfigStruct`, `Enums`, `Factory`, `GenesisHead`, and related files.
2026-04-27 10:48:27 +02:00
marekf 15dc325275 Upgrade (develop) - GCI - big change 2026-04-27 07:57:16 +02:00
marekf ca333d1772 Upgrade (develop) - GCI UI for TBF - change Forms to Views 2026-04-26 11:40:21 +02:00
marekf a4ece06b05 Upgrade (develop) - GCI UI for TBF - change Forms to Views 2026-04-26 11:39:35 +02:00
marekf 992452052e Upgrade GenesisCommunication - after adding GCI functionality to xylem DLL's updater, adding PortCore DLL is needed 2026-04-26 09:32:30 +02:00
marekf 75192bbd09 Add (develop) GCI - new functionality - xylem DLL's updater for TBF - actualize DLL's in TBF.packages.common of TBF project path - fixed problem witch multiple referencing of GenesisCommunication and GciBridge on one DLL but with difference version 2026-04-26 08:13:43 +02:00
marekf 6199bd48c5 Upgrade .NET Framework 4.7.2 to 4.8 for Laatzen + GCI + TBF compatibility 2026-04-24 13:00:53 +02:00
marekf 25434d70d4 Merge branch 'feature/task/Cordonel-communiation-tests' into develop/SLM-PT50 2026-04-23 10:00:59 +02:00
michal de6dd45dcb Fix Flow - Increment assembly version to 3.9.3059.1. 2026-04-23 09:56:32 +02:00
marekf 74f2e99ed3 Merge branch 'bugfix/Flow-meter-in-parallel-reverse-bug' into develop/SLM-PT50 2026-04-23 09:43:39 +02:00
marekf 99b1f4a171 Fixed FlowMetersInParallel - incorrect ltrPerPulse counting from average value of nominalFreq 2026-04-23 09:40:05 +02:00
marekf 8c10aa3752 Add (develop) GCI - GciBridge 2026-04-23 09:09:27 +02:00
michal 7170da4a70 Add GenesisCommunication test methods and related components:
- Introduce `TestMethod`, `SequenceConditionOp`, and `Factory` for `GenesisCommunication`.
- Add `TestMethodCfgCtrl` and its designer for test configuration UI.
- Update `.csproj` to include new files.
2026-04-22 10:18:42 +02:00
michal 842f009b42 Increment assembly version to 3.9.3058.1 and fix logging format issue in FlowMeter initialization. 2026-04-21 07:43:35 +02:00
michal 7f30ca0cd1 Merge branch 'develop/SLM-PT50_genesisDirectDecode' into develop/SLM-PT50_genesisDirectDecode_morisville
# Conflicts:
#	TBF/Properties/AssemblyInfo.cs
#	TBF/Rig/RegisterReaders/GenesisRegReader/implementations/GenesisSmartReader.cs
2026-04-20 14:25:13 +02:00
michal 93e207c211 Update GenesisSmartReader for refined start/end marker logic, add _endDeltaSeconds property, and improve telegram index resolution methods. Increment assembly version to 3.9.3031.1. 2026-04-20 13:25:25 +02:00
marekf 64cafc088a Merge branch 'bugfix/Flow-meter-in-parallel-reverse-bug' into develop/SLM-PT50 2026-04-20 12:45:25 +02:00
marekf 8a0da27a07 Fixed RegValve + FlowMetersInParallel - incorrect NominalFreq sum 2026-04-20 12:39:51 +02:00
michal 5a8478e782 Refactor GenesisSmartReader Q3 calibration tests and logic:
- Expand Q3 calibration tests with diverse scenarios in `GenesisSmartReader_Q3Test`.
- Introduce channel-specific validation for calibration tests.
- Adjust methods for Q3 calibration in `GenesisSmartReader` to support per-channel factors.
- Add utilities for preparing simulation data and refinements for test consistency.
- Update `CliRunner` with improved task management, timeout handling, and logging enhancements.
2026-04-17 16:05:16 +02:00
marekf 368cd95114 Bug (fixing) RegValve OK, FlowMeterInParallel NOK 2026-04-15 10:50:27 +02:00
michal 33ef914984 Update GenesisReaderTests: add real input parsing, format variation handling, and rollover cases; remove outdated Q3 calibration tests; increment version to 3.9.3056.1 2026-04-15 09:56:54 +02:00
michal 3eb0b87f0d Add Q3 calibration tests for GenesisSmartReader and refactor test cases:
- Introduce new `GenesisSmartReader_Q3Test` class with comprehensive Q3 calibration scenarios.
- Refactor existing tests to utilize simulation data for better consistency and validation.
- Adjust Q3 calibration logic in `GenesisSmartReader` to enhance calculation accuracy and validation criteria.
2026-04-15 09:22:09 +02:00
marekf c13cb725f0 Merged branch > UniDataStorageWriter-and-UniDataStorageReader 2026-04-15 09:13:57 +02:00
marekf c6d4a016b5 Add (develop) GCI - interface of GCI and Laatzen - GciBridge component 2026-04-15 08:46:19 +02:00
marekf eda0644b4b Add (develop) GCI - interface of GCI and Laatzen 2026-04-15 08:41:27 +02:00
michal 711dfc03ef Fix Q3 calibration logic in GenesisSmartReader: replace _rawStartEndByChannel with recalculatedVariablesByChannel for accurate data computation. 2026-04-14 15:54:28 +02:00
michal 93459ccfab Refactor water meter handling in SequenceBase and FlyingStartMassCollectionSeq:
- Enhance logic for enabling/disabling channels based on water meter data.
- Introduce Q3 calibration validation in `GenesisSmartReader` with configurable thresholds.
- Update `GenesisCfgCtrl` UI to disable certain inputs.
2026-04-14 15:41:13 +02:00
marekf 5b73835d94 Add (develop) GCI - interface of GCI and Laatzen 2026-04-14 12:33:06 +02:00
michal 009aefb7c9 Refactor GenesisSmartReader and SequenceBase logic, enhance channel handling in water meters, and update GUI components:
- Adjust `Disabled` logic for water meters in `SequenceBase` allowing conditional enabling of channels based on serial number.
- Introduce `EnableShowChanels` property in `GenesisSmartReader` and integrate into `FlyingStartMassCollectionSeq`.
- Modify `StartupFlushMs` to derive configuration dynamically.
- Update `GenesisCfgCtrl` with a checkbox for enabling channels and input for flush timing.
- Increment assembly version to `3.9.3054.1`.
2026-04-14 08:03:02 +02:00
michal d2e18d615d Bump assembly version to 3.9.3053.1. 2026-04-13 14:17:56 +02:00
michal 69b475eb77 Refactor GenesisSmartReader for improved simulation and testing:
- Add `PrepareCalculatedChannelDataSimulationForTest` and supporting utility methods for generating and cloning test data.
- Update `StartupFlushMs` and sampling intervals for increased flexibility.
- Revise water meter handling logic in `FlyingStartMassCollectionSeq` to support multiple channels.
2026-04-13 14:17:34 +02:00
marekf 9848b97082 Update (develop) UniDataStorageWriter - first successful version 2026-04-13 12:21:52 +02:00
marekf 0b429ffbc2 Merge branch UniDataStorageReader 2026-04-12 10:53:53 +02:00
marekf ef146efaf0 Merge branch UniDataStorageWriter 2026-04-12 10:49:16 +02:00
marekf 431061a685 Add (developing) UniDataStorageWriter 2026-04-12 02:38:58 +02:00
marekf b6edd9c0a0 Add (developing) UniDataStoreWriter 2026-04-12 02:37:14 +02:00
michal 2210bb8240 Enhance FlyingStartMassCollectionSeq with GenesisSmartReader support; add water meter handling logic and bump assembly version to 3.9.3050.1. 2026-04-11 21:55:34 +02:00
marekf 8d7c1adf37 Update (developing) UniDataStorageReader 2026-04-11 20:49:11 +02:00
marekf 3376ac41b4 Merge branch 'develop/SLM-PT50_genesisDirectDecode' of http://87.197.120.129:33300/michal/tbf into develop/SLM-PT50 2026-04-11 11:54:37 +02:00
marekf f9181fee74 Fixed SelectComponentDlg > missing assignment sharedSearchForListBox1.ListBoxEx = availCmpntsLstBox, because of this the application crashes 2026-04-11 11:04:00 +02:00
marekf 4c77d6c06e Add (develop) GenesisCordonelInterface changed project name 2026-04-11 09:33:05 +02:00
marekf b7db39853b Add (develop) GenesisCordonelinterface add TBF.sln project name 2026-04-09 16:44:48 +02:00
marekf 66157ba988 Add (develop) GenesisCordonelinterface - changed GenesisCordonelTester to GenesisCordonelInterface, Add new FormCordonelPreadjustmentUI by Laatzen tool 2026-04-09 16:41:29 +02:00
michal 65ab19290f simulate mode - flow reached 2026-04-09 12:49:00 +02:00
marekf e7e6fc7920 Add (develop) Genesis Cordonel interface - used Laatzen tools in our new tool GenesisCordonelTester 2026-04-09 10:12:00 +02:00
michal 94c7279da1 Add localized string resources for "Test in calculation" and integrate it into FlyingStartMassCollectionSeq
- Add `Test_in_calculation` localized strings to `.resx` files for English, Slovak, and Czech.
- Update `FlyingStartMassCollectionSeq` to display the new activity message during the calculation phase.
2026-04-09 10:08:50 +02:00
michal 2136695b80 Fix Stop 2026-04-08 16:37:27 +02:00
michal c0f9b0ffa0 Refactor GenesisSmartReader stop logic for enhanced thread safety and post-processing; bump assembly version to 3.9.3047.1. 2026-04-08 15:44:59 +02:00
michal c4ef22436f Update GenesisSmartReader Stop logic and bump assembly version to 3.9.3045.1:
- Refactor `Stop` for improved thread safety using `lock` on `_stateSync` and `_stopSync`.
- Enhance `Stop` behavior by introducing state updates during immediate stop requests.
- Fix redundant operations and reorganize log and processing statements for clarity.
- Update `RequestImmediateStopInternal` to accept a new state parameter.
2026-04-08 15:06:45 +02:00
michal 0b73871518 Refactor GenesisSmartReader and add advanced test utilities:
- Introduce `ForceProcessingEnabled`, `InstallSuccessfulProcessingOverride`, and `EnqueueIncomingLine` helpers to streamline test setup.
- Add new test suite `GenesisSmartReaderStopTests` to validate `Stop` behavior for different processing states.
- Enhance `GenesisSmartReader` state management with a dedicated `Reset` method and improved `Stop` logic.
- Improve buffer initialization in `ProcessOptoLine` to address null-value edge cases.
- Update assembly version to `3.9.3043.1`.
2026-04-08 13:51:55 +02:00
michal f7dc6fee5e immediate Stop improve 2026-04-07 16:37:19 +02:00
michal ba848a167d improve 2026-04-07 15:44:32 +02:00
michal dcb0bf9a88 Update GenesisSmartReader logging and bump assembly version to 3.9.3040.1:
- Enhance `Stop` logs with `registerReader` and `optoSerialPort` details for improved traceability.
2026-04-07 15:27:20 +02:00
michal f6433134c1 Add WaitForStartupFlushToFinish and EnableProcessingLoopForTests utilities for improved test reliability:
- Incorporate `WaitForStartupFlushToFinish` in `GenesisSmartReaderThreadedReadTests` to ensure startup flush completion before processing.
- Introduce `EnableProcessingLoopForTests` in `GenesisSmartReaderTest` to streamline test initialization.
- Fix thread-safety issues in startup flush handling and reorder operations in `GenesisSmartReader.Stop`.
- Bump assembly version to `3.9.3039.1`.
2026-04-07 14:45:37 +02:00
michal 7e3df77b5b Refactor GenesisSmartReader processing logic and tests for robust handling:
- Replace property getters with concise expressions in `GenesisSmartReader`.
- Implement FIFO and concurrent producer-consumer unit tests for `ProcessingLoop`.
- Add startup flush mechanism for improved input handling on initialization.
- Refactor processing loop with structured start/stop tasks and cancellation tokens.
- Fix thread-safety issues and enhance logic in `Stop` and `StopDataStreamProcessing`.
- Add internal visibility for tests in `TBFTests` via `InternalsVisibleTo`.
- Update assembly version to `3.9.3038.1`.
2026-04-07 10:42:27 +02:00
marekf ff5954d85b Bugfix FlowMeterInParallel and RegValve OUT OF RANGE regulation part1 2026-04-02 12:02:26 +02:00
michal 08dff1272b Add overflow volume/timestamp handling and related tests for GenesisSmartReader:
- Extend `CalibrationRecord` constructor to include overflow fields (`OverflowVolumeCm`, `OverflowTimeS`).
- Implement additional unit tests in `OptoTelegramRawTest` to validate multi-rollover scenarios and extended calculations.
- Add `GenesisSmartReaderThreadedReadTests` to cover threaded read-loop functionality and serial processing.
- Enhance logging in `Pump` classes (`TurnOff` methods).
- Update project file to include new test files.
2026-04-02 09:25:17 +02:00
marekf c09e266b2c Bugfix ComponentPropertiesDlg frm size 140x80 2026-04-01 12:12:04 +02:00
michal d5c8fd1c8f Refactor GenesisSmartReader with enhanced channel-specific volume and timestamp processing:
- Replace `AverageNullable` with `AverageCachedTime` and introduce `GetCachedVolume`/`GetCachedTime` helpers.
- Add recalibration logic with `_recalculatedStartEndByChannel` and `_rawStartEndByChannel`.
- Implement `PrepareCalculatedChannelData` for refined multi-channel synchronization.
- Add unit tests (`GenesisSmartReaderChannelTests`) for improved coverage and validation of new methods.
- Update `OptoTelegramRaw.Copy` to fix field assignment issues.
2026-03-27 15:12:43 +01:00
michal a34740e838 Update GenesisSmartReaderTest to handle DiscardOutCalls and configure block repetition resets:
- Modify tests to validate `DiscardOutCalls` alongside `DiscardInCalls`.
- Add support for configuring `ResetAfterBlockRepetitions` in test initialization.
2026-03-27 13:19:10 +01:00
michal 836ba5a41f Refactor GenesisSmartReader processing logic and add advanced multi-channel volume and timestamp handling:
- Introduce `TimeDeltaPerChannel` and `GroupRecordsPerChannel` for calculating time and volume deltas across channels.
- Add recalibration logic to synchronize volume and timestamp data with channel-specific maxima.
- Fix `ResetDataBuffer` implementation and replace redundant `ReasetDataBuffer` calls.
- Update handling of flow markers and block completion logic for improved buffer management.
- Add `Copy` method to `OptoTelegramRaw` for efficient cloning and recalculation.
- Bump `AssemblyVersion` and `AssemblyFileVersion` to `3.9.3019.1`.
2026-03-27 13:18:37 +01:00
marekf 545a747ebc Add UniDataStorageWriter component - initial commit 2026-03-27 12:49:35 +01:00
michal 23c83ab452 Enhance GenesisSmartReader multi-channel processing and add tests for telegram handling:
- Refactor `ProcessOptoLine` logic to support output buffer resets at configurable repetition intervals.
- Add tests:
  - `ProcessOptoLine_Block_f_h1_h2_h3_f_ShouldResetBuffersOnlyAfterLastF`
  - `ReadOptoData_FullBlock_ShouldDiscardBuffersAfterClosingF`
  - `ProcessOptoLine_LastF_AfterH3_ShouldRequestBufferReset`
  - `ProcessOptoLine_ShouldReset
2026-03-26 14:45:36 +01:00
michal bc9e583c29 FIX Add ChannelAverages to project and remove unused imports in GenesisHead. 2026-03-26 07:29:13 +01:00
michal 18cef617da Enhance Genesis SmartReader with channel-specific volume and timestamp tracking:
- Add per-channel `VolumeStart`, `VolumeEnd`, `TimeStart`, and `TimeEnd` processing for improved multi-channel support.
- Introduce `ChannelAverages` for centralized average calculations across channels.
- Refactor `GenesisSmartReader` to improve data decoding and logging for calibration and flow test records.
- Add telemetry unwrapping helpers for precise volume and timestamp calculations.
- Update `OptoTelegramRaw` to support channel-specific updates and robust data processing.
- Update `AssemblyVersion` and `AssemblyFileVersion` to `3.9.3013.1`.
2026-03-26 07:19:22 +01:00
michal 4ee736cff5 Add advanced multi-channel processing for Genesis SmartReader:
- Refactor `VolumeLtrStart` and `VolumeLtrEnd` to compute channel-specific averages at test boundaries.
- Implement `ProcessOptoLine_ShouldInsertTelegrams` tests for validating telegram insertion and channel updates.
- Add `VolumeLtrEnd_ShouldAverageOnlyAvailableChannels` to handle partial channel data gracefully.
- Introduce `VolumeFromChannelsAtStart` and `VolumeFromChannelsAtEnd` helpers for refined channel data handling.
- Update Opto telegram processing logic to support robust volume and timestamp unwrapping.
- Enhance `GenesisSmartReader.ToString()` for clearer configuration representation.
- Add `OptoTelegramRawTest` to validate telegram behavior, flag handling, and delta computations.
- Update `AssemblyVersion` to `3.9.3012.1`.
2026-03-24 15:23:06 +01:00
michal 4e40dc8601 Comment out Detect_BaudRate_By_ViewFactoryId test method in TouchReadBaudRateDetectionTests. 2026-03-24 10:07:24 +01:00
michal a5a68ec457 Refactor Genesis serial communication handling (ISerialDriver interface compatible with SerialPort):
- Replace method-based `IsOpen()` checks with property-based `IsOpen` usage in `ISerialDriver` and related classes.
- Simplify `Open()` and add `Close()` methods to unify connection management.
- Introduce `InitializeThreeChannelState()` helper in `GenesisSmartReaderTest` for multi-channel state initialization.
- Adjust calculations in `CalculateTimeByChannels()` and `CalculateVolumeByChannels()` for clarity.
- Add new tests for multi-channel processing and validation of updated telegram handling logic.
2026-03-24 10:04:30 +01:00
michal e26d88d437 Refactor Genesis use 3 chanels reader structure:
- Replace `Xylem.Common` namespace references with `TBF.Rig.RegisterReaders`.
- Introduce `GenesisSmartReaderTest` and `FakeSerialDriver` for unit testing.
- Revamp `FlowDirectionDetection` to support multiple channels.
- Make constants in `StreamingDecoder` public for enhanced accessibility.
- Update `AssemblyVersion` and `AssemblyFileVersion` to `3.9.3010.1`.
2026-03-24 08:53:16 +01:00
marekf 98ba7d2dee Update UniDataStorageReader developing 2026-03-19 19:28:16 +01:00
marekf 78835c1af6 Add UniDataStorageReader initial commit 2026-03-19 16:30:32 +01:00
michal 2522d1da9f Add Genesis radio/opto communication and configuration components
- Replace `OpthoHeadService` with `RadioService` to enhance Genesis communication handling via serial interface.
- Introduce `OptoReceivedEventArgs` to manage event-driven communication.
- Add foundational protocol implementations (`BaseProtocol`, `IProtocol`, etc.) for Genesis configuration and processing.
- Implement `SirtConfig`, `MeterConfig`, and `ProcessConfig` classes for flexible Genesis configuration management.
- Expand Genesis framework to support diagnostics, activity modes, and version retrieval.
2026-03-18 15:57:04 +01:00
michal 8983c01591 Add integration tests for IperlHat communication and diagnostic LED parsing
- Implement `IperlHatIntegrationTests` to validate serial communication, diagnostic LED states, and Opto data handling.
- Add `HexFormatterTest` for verifying Hex formatting utilities.
- Add `DiagnosticLedParserTest` to test parsing for all diagnostic LED states.
2026-03-17 12:15:52 +01:00
michal 61b1320d4f Add Genesis COM port configuration and update Genesis meter setup logic
- Introduce `OptoComPortNr` and `HeadComPortNr` properties in `GenesisHead`.
- Update `SetupGenesisMeter` to use new COM port configurations.
- Add reference to `Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig`.
2026-03-16 15:48:41 +01:00
michal 2c8a0922d1 Genesis dialog with Com ports 2026-03-16 15:47:12 +01:00
michal b078d9586d Add detailed logging for Genesis operations in FlyingStartMassCollectionSeq and FlyingStartSeq.
- Introduce debug and info logs for Genesis initialization, calibration, measurement, and data storage.
- Ensure proper logging during Genesis operations' start and stop phases.
2026-03-16 15:42:45 +01:00
michal 6e35de5f4d Update AssemblyVersion and AssemblyFileVersion to 3.9.3001.1 2026-03-16 15:36:25 +01:00
michal 2dbe4cded4 Genesis slot max count 10, Add DB writer component
Integrate `DatabaseWriter` component and update GenesisHead configuration:

- Add `DatabaseWriter` factory and related classes (`WriteDBCfgCtrl`, `WriterCfg`, `WritingToDB`).
- Extend GenesisHead slot number range to 1-10 and adjust UI layout accordingly.
2026-03-16 15:36:02 +01:00
michal 10865c6878 Update AssemblyVersion and AssemblyFileVersion to 3.9.3000.1 2026-03-16 15:35:06 +01:00
michal ee1353fe54 Add DatabaseWriter component:
- Implement `DatabaseWriter` factory and configuration logic.
- Add `WriteDbCfgCtrl` for component configuration UI.
- Introduce database connection handling, network adapter selection, and tracing record management.
2026-03-16 15:31:58 +01:00
michal 5cefd7fc3a Integrate Genesis meter support into FlyingStartMassCollectionSeq:
- Add initialization, calibration, and measurement logic for Genesis meters.
- Extend result handling to capture Genesis-specific data (timestamps, volumes, errors).
- Ensure proper cleanup of Genesis meters at test conclusion.
2026-03-16 15:31:49 +01:00
michal ab0e5ea82a Genesis heap 2026-03-16 15:17:56 +01:00
michal b2276c086c Merge branch 'develop/SLM-PT50' into develop/Mexico 2026-03-16 13:33:21 +01:00
michal 4fa462661c Merge remote-tracking branch 'remotes/private-origin/develop/SLM-PT50' into develop/Goeteborg 2026-03-16 13:11:34 +01:00
michal 2b30d0cf34 packages add/clean up 2026-03-13 13:51:42 +01:00
michal df2c56e6c4 FIX NaN - devide by zero
Add simulation logic to `StandingStartStopTestOp` and handle zero `TestTime` edge cases in `FlyingStartMassCollectionSeq`
2026-03-12 16:25:26 +01:00
michal a997c3d7be iPerl ASIC - implementation 2026-03-12 14:50:47 +01:00
marekf 3c964f2aab BugFix - repair test RegisterReader deserialize - FSMC method as in SSMC 2026-03-09 14:37:51 +01:00
marekf c445b3e098 BugFix - after applying the transition valve 40% in procedure-purge begin, the RegValve was not regulating correctly after starting the test 2026-03-09 14:20:37 +01:00
marekf 2ea2a2592e Merge branch 'feature/task_6-add-new-admins' into develop/SLM-PT50 2026-03-04 19:14:22 +01:00
marekf 27072598cd Merge branch 'feature/task_5-new-app-icon' into develop/SLM-PT50 2026-03-04 19:14:02 +01:00
marekf 4a2d4772d7 Add new icon to forms of application 2026-03-04 18:48:46 +01:00
marekf 2bf00606d3 Merge branch 'feature/task_4-ListView-ListBox-navigation' into develop/SLM-PT50 2026-03-04 18:42:25 +01:00
marekf 3773e1d96c Merge branch 'feature/task_3-new-pump-grundfoss' into develop/SLM-PT50 2026-03-04 18:42:15 +01:00
marekf 19ddc753c7 Merge branch 'feature/task_2-dripping-on-the-scale-meassure-mass' into develop/SLM-PT50 2026-03-04 18:33:20 +01:00
marekf 0c41c750e8 Add parameter and management IsOffline for components: Modbus>TempMeter>Groch, Meret and Modbus>PressureMeter>Meret and Rig>Keithley>TempMeter and add indicator redColor itemValue for SchematicDrawing 2026-03-04 18:25:28 +01:00
marekf 4bfd5c8e11 Update output printer OnePerMeter - 1. printer configuration in PrintResultsSelectionDlg, 2. document preview, 3. edit document name, 4. enable more save destinations 2026-03-04 13:21:45 +01:00
marekf f0fb70e38b Add new type of pump - Grundfoss 2026-03-04 11:54:39 +01:00
marekf 6e5bcafec0 Update dripping on the scale and measuring the start mass 2026-03-04 10:37:35 +01:00
marekf d5cb18c910 Fixed incorrect loading of RegisterReader in the StandingStartMassCollection method, when the RR Units and RR Quantity variables in results were filled with only string.empty 2026-03-04 09:44:42 +01:00
marekf 3a2069b255 Refactor variable naming in results in response to mass meter pulse processing 2026-03-04 09:42:55 +01:00
marekf 80c651dbfd Add search and navigation as UI>shared for ListBox-es and ListView-s to components listview, components listbox, procedure listview 2026-02-25 13:22:56 +01:00
marekf 5a3b9b57c4 Add new admins marek and michal 2026-02-25 10:02:09 +01:00
marekf ead350eef3 Add initial MassMeter implementation 2026-02-19 19:22:02 +01:00
marekf b43657a4db Initial import from local copy 2026-02-19 12:02:07 +01:00
michal 8fffb9e366 Update clean.bat to remove build artifacts for AppDiagnostic, NfcC7_DLL, NfcC7_DLL.Tests, and TBFTests 2026-01-23 11:04:23 +01:00
michal 0fdd229141 Refactor IPerlImplHeadTestCtrl to use descriptive enums for operations, update command mappings, introduce IPerlASICCorrections, and improve test configuration checks and NFC handling. 2026-01-23 10:51:47 +01:00
michal 2f1ada3f5b Add DiagnosticLedState classes for States #4-#7, enums for PipeStatus and SpikeDetectionStatus, and implement TouchReadProtocol commands, frames, and builders. 2026-01-19 08:10:36 +01:00
michal 988a8c6642 Update NuGetToolVersion to 7.0.0 in SharedComponents project configuration 2025-12-07 11:27:17 +01:00
michal 42ee9eaee3 Poseidon - Flying - Opto communication
Enhance `FlyingStartMassCollectionSeq` with Poseidon reader support, detailed error handling, and improved test data processing.
2025-12-07 11:27:00 +01:00
michal 3f28051d79 Update .gitignore to exclude NfcC7_DLL.Tests build artifacts 2025-12-07 10:59:19 +01:00
michal 65f13cc868 Add UNIHeadTestCtrl interface and implement IperlHeadTestCtrl with command handling logic. 2025-12-06 12:51:51 +01:00
michal cd8ba3cda3 Add System.Threading 4.3.0 package with support for multiple frameworks and localized XML documentation. 2025-12-06 12:49:58 +01:00
michal a5936c8f19 Fix standing start Store Data
Refactor to use `ICommonRegReader` in `StandingStartSeq` and update parameter handling in `SmartCommunicationSeq`.
2025-12-06 12:48:42 +01:00
michal 2842425673 Add simulation logic for test operations and water metrology, enhance UI initialization, and implement optohead flow rate handling.
- Introduced simulation timers in `FlyingStartStopTestOp`.
- Added `Simulate` methods in `WaterMetrologyData`, `WaterMetrologyDataC7`, and `WaterMetrologyDataC2`.
- Enhanced `SmartCommunicationForm` with textbox resizing logic and initialization code.
- Implemented flow rate and volume calculation from optohead telemetry in `SmartReader`.
- Added unit tests for Poseidon correction parsing.
2025-12-06 12:46:12 +01:00
michal 06a401a1ff bugFix - Morrisville - SerialNr, WMBegginValue
Add support for `ICommonRegReader` interface, enhance `ISmartReader` functionality, and update water meter state handling logic across multiple classes.
2025-11-21 14:14:23 +01:00
michal 3a2fc50fec PurchaseOrderDialog logger Improvement - WRCSwindon
Add detailed logging for purchase order workflows in `CycleBeginningForm`

- Introduced `log_selected` for enhanced debugging of selected orders, items, and serial numbers.
- Added exception handling and logging for serial number loading.
- Improved visibility into runtime behavior with contextual debug and error logs.
2025-11-21 14:12:12 +01:00
michal 38a58ed8b7 Scale rainnig solution, see:
Inplementing mass collection update.
Update AssemblyVersion to 3.9.2149.4, refactor mass collection sequence in StandingStartMassCollection, extend PoseidonCmd with enhanced configuration and dialog options, and improve task handling and UI automation.
2025-11-19 16:44:21 +01:00
michal c7cba20de0 Add ReadStableMassOp unit test and enhance MettlerToledo Scale support
- Introduced `ReadStableMassOpTest` to validate mass reading operations.
- Refactored `Scale` to support `ISerialPort` for improved testability.
- Added `SerialPortDevice` and `SerialPortDeviceFake` implementations, with `GetComponent` overload in `Factory`.
- Enhanced `StateMachine` with `InitializeBoardEtc_Fake` for custom setups.
- Updated project files to include new classes.
2025-11-19 16:28:23 +01:00
michal 6311df49c3 Inplementing mass collection update.
Update AssemblyVersion to 3.9.2149.4, refactor mass collection sequence in StandingStartMassCollection, extend PoseidonCmd with enhanced configuration and dialog options, and improve task handling and UI automation.
2025-11-18 10:59:21 +01:00
michal f1d32a39ba ver 3.9.2149.2 ReadPulses added in Run()
Update AssemblyVersion to 3.9.2149.2 and enhance PoseidonReader with new timing and task-tracking functionality.
2025-11-13 15:58:09 +01:00
michal 224b53f774 Ver 3.9.2149.1 - Update AssemblyVersion and AssemblyFileVersion 2025-11-13 14:39:07 +01:00
michal 1e2777c5e7 Enable ShowDialog for PoseidonCmd, add UI improvements in TestStartEndForm, and introduce new methods for handling reader data and controls. 2025-11-13 14:21:23 +01:00
michal c3c21649fb new Test method Poseidon => StandingStartMassCollectionPoseidon
Add support for `StandingStartMassCollectionPoseidon` test methods.

- Introduced `Compound`, `HeatMeters`, and `Single` components for `StandingStartMassCollectionPoseidon`.
- Included factories, configuration classes, and test parameters for new test methods.
- Updated `TBF.csproj` to include new files and resources.
2025-11-12 13:42:19 +01:00
michal 99ccabc142 Smart meters support MainWnd dialog (must be finished - mouse right click), test supports Poseidon RegisterReader
Refactor `ISmartReader` and related classes to support `SmartHeadsUni`. Remove redundant `IperlHeadsUni` references and introduce `SmartMeterFlyingStartMassCollection` functionality. Enhance regex-based head position extraction.
2025-11-12 12:34:29 +01:00
michal f1e6e94450 work backup
- Register Reader Poseidon works
- Smart Form - wrong functionality
- refactoring
2025-11-06 14:11:13 +01:00
michal 320cddb177 compatible version to TBF
Refactor `NfcHanler` namespace to `NfcHandler` and enhance code consistency.
2025-10-29 16:05:21 +01:00
michal 42002e3fa4 iPerl Fixes 2025-10-27 11:49:42 +01:00
michal 77cabfd712 bugfix Parallel CLI Runner 2025-10-27 11:48:22 +01:00
michal c933e2d759 test disabled 2025-10-27 11:47:38 +01:00
michal f3f0a46627 improvemnet, Sensus Developer super user added 2025-10-27 11:46:56 +01:00
michal b5fb4c2947 improvemnet, Sensus Developer super user added 2025-10-27 11:46:34 +01:00
michal f6cce9df3c bugfix Parallel CLI Runner
Additional needed classes
2025-10-27 11:42:12 +01:00
michal c0385c0782 bugfix Parallel CLI Runner
Add parallel execution tests and improve cancellation handling in `CliRunner`

- Introduced new tests (`RunMultipleTimesTestProgram_CheckParalelWork` and `RunMultipleTimesTestProgram_CheckParalelWorkCumulative`) to verify parallel execution behavior.
- Enhanced `SendAsync` and `RunAndCaptureJsonAsync` methods in `CliRunner` with `CancellationToken` support for better task cancellation.
- Refactored process output handling for improved clarity and robustness.
- Added error handling during CLI logger initialization.
2025-10-27 11:38:43 +01:00
michal db43bdb652 FlowMeter improvement
Add `FromDescription` check in `ParseFlowUnit` for better unit parsing
2025-10-27 11:29:58 +01:00
michal 6bdc10f4a7 Merge branch 'master-3' into feature/SmartMeters 2025-10-22 14:37:04 +02:00
michal 9692dc7f4f HeatMeter - columns exchange
Update `ProcedureDlg` to fix `MetersPath` ordering and version bump to 3.9.2149.0
2025-10-22 12:18:01 +02:00
michal 6795793858 Update iPerlReaderUNI configuration handling and validation
- Replace `PoseidonReader.IPerlCfgCtrl` with `RegisterReaders.iPerlReaderUNI.IPerlUniCfgCtrl` for proper configuration control.
- Add null-check and error handling in `ComponentsManagerDlg` to ensure valid default configurations.
- Mark `ITestParams` as `[XmlIgnore]` in `IPerl` configurations to avoid serialization issues.
- Minor import adjustments and functionality improvements for TestMethod classes.
2025-10-21 10:06:29 +02:00
michal a2c564d789 polishing - work now 2025-10-18 09:59:07 +02:00
michal 3bc9e731e8 Move iPerlReaderUNI.communication components to CommonRR.IPerl.communication and rename associated classes for clarity and consistency. 2025-10-14 14:20:26 +02:00
michal 95c5f09238 Working NfcC7_DLL, tests, clean up
"Remove unused NfcHanler classes and utilities"

This commit deletes several obsolete and unused files from the NfcHanler directory, including utility classes, enums, and a large command handling class. This cleanup improves code maintainability by eliminating unnecessary dependencies and clutter.
2025-10-14 13:15:31 +02:00
michal 0a45d66c0b Add SerialFirmwareDownloadTask to NfcC7_DLL for firmware upgrade handling 2025-10-09 11:01:08 +02:00
michal 96408eaef3 Merge branch 'master-3' into feature/SmartMeters
# Conflicts:
#	NfcC7_DLL/Properties/AssemblyInfo.cs
2025-10-06 11:16:36 +02:00
michal cae3ca7cdf HEAT_METERS enabled 2025-10-03 09:59:44 +02:00
michal c8adc093e0 NfcC7_DLL bug fix 2025-10-02 13:34:29 +02:00
michal 4395516216 test project 2025-10-02 13:30:59 +02:00
michal 9281b52464 Poseidon DLL - Comunication Implementation - not finall 2025-10-02 13:28:37 +02:00
michal 6571de7c32 Add NfcC7_DLL project with initial implementation and solution integration 2025-09-29 09:58:09 +02:00
michal a75d66e028 Merge branch 'refs/heads/master-3' into feature/SmartMeters
# Conflicts:
#	TBF.sln.DotSettings.user
2025-09-27 10:27:40 +02:00
michal e839148a6f Ignore .DotSettings.user file 2025-09-27 10:05:09 +02:00
michal 65b502a9b1 Remove TBF.sln.DotSettings.user file 2025-09-27 09:54:47 +02:00
michal 9cde62b2e2 packages added to git
Add `System.Net.Sockets.xml` documentation for zh-Hant locale in `netstandard1.3` API reference.
2025-09-27 09:53:21 +02:00
michal cc86c38246 Update user credentials in Utils.cs 2025-09-26 16:22:00 +02:00
michal 357df87f49 feature/Enhanced_Writer_NoSeparator_AndName 2025-09-26 15:10:34 +02:00
michal 4b33da565c Untrack TBF.sln.DotSettings.user 2025-09-26 15:02:15 +02:00
michal d11f855325 Update .DotSettings.user file with new ResxEditorPersonal configurations 2025-09-26 14:54:22 +02:00
michal eef1f31a21 Update .DotSettings.user file with adjusted ResxEditorPersonal settings 2025-09-26 14:50:49 +02:00
michal b878ee96a5 Merge branch 'refs/heads/master-3' into feature/camera_jms
# Conflicts:
#	TBF.sln.DotSettings.user
#	TBF/Properties/AssemblyInfo.cs
#	TBF/TBF.csproj
#	TBFTests/obj/Debug/TBFTests.csproj.CoreCompileInputs.cache
#	TBFTests/obj/Release/TBFTests.csproj.CoreCompileInputs.cache
2025-09-26 14:27:01 +02:00
michal 97eed27458 Update .DotSettings.user to include Nullable<T>.cs in force-included files. 2025-09-26 14:18:19 +02:00
michal fe08550dc3 iPerlReaderUNI.Factory => TBF components 2025-09-25 16:24:10 +02:00
michal 8a0ae8080f refactor - completisation Smart Meter <= iPerl 2025-09-24 11:57:47 +02:00
michal ab4025e55f Add ISmartTestMethod interface and initial designer file for iPerlCommunicationForm in SharedDialogs 2025-09-23 11:14:04 +02:00
michal 22fffe602c iPerl Reader - NOT FINISHED
Add initial implementation for `iPerlReaderUNI` with `Factory`, `ProcParams`, and `IPerlReader` classes.
2025-09-23 11:10:55 +02:00
michal e4c0219783 packages update
Add Antlr3.Runtime.xml documentation file for API references.
2025-09-22 13:51:32 +02:00
michal 3362fdfaff Remove bin/, obj/, and other build artifacts from Git tracking 2025-09-22 13:46:49 +02:00
michal 6093db4502 Remove bin/, obj/, and other build artifacts from Git tracking 2025-09-22 13:45:20 +02:00
michal 5e7598667b Remove bin/, obj/, and other build artifacts from Git tracking 2025-09-22 13:36:42 +02:00
michal 4fe8729b85 Remove bin/, obj/, and other build artifacts from Git tracking 2025-09-22 13:34:07 +02:00
michal b1dd6666f1 Version increment to 3.9.2147.1 2025-09-22 12:26:02 +02:00
michal a3613889e1 HEAT_METERS disabled
update `.gitignore` with additional folders and files for better coverage.
2025-09-22 12:25:32 +02:00
michal 7b87d63531 PoseidonReader - fix support Cli version 1.4 - Extend TryGetDeviceId to support JSON format and add corresponding tests 2025-09-22 09:35:22 +02:00
michal d838c78a8a CliRunner - Added test and refactor 2025-09-19 12:02:16 +02:00
michal 7a8bef501a HEAT_METERS enabled 2025-09-19 12:00:59 +02:00
michal 9863b54bc8 Enhance ScopedLoggerFactory to support log file compression with rolling, include LogZipService for managing zipped archives, and update CliRunner configuration accordingly. 2025-09-17 13:00:17 +02:00
michal e57c6a6a02 Add ShowDialog and SaveCommunication fields to EntryFormCfg, implement related functionalities in PoseidonReader and EntryForm, and improve logging with ScopedLoggerFactory integration. 2025-09-17 10:45:40 +02:00
michal afa215534c Version increment to 3.9.2146.4 2025-09-09 20:48:19 +02:00
michal 780d44166e Refactor PoseidonReader to use lazy initialization for CliRunner, introduce SafetyTimeOut, enhance JSON deserialization with fallback logic, and improve error logging using log4net. 2025-09-09 20:47:53 +02:00
michal 35e4078dda Merge branch 'master-3' into PoseidonCmd 2025-09-09 15:13:29 +02:00
michal 47e09584f2 Frequency pulse meter 2025-09-09 12:51:26 +02:00
michal fc8e82c0e8 Merge branch 'master-3' into feature/processLogging
# Conflicts:
#	TBF/Rig/Sequences/ProcessData.cs
#	TBF/Rig/TestMethods/PMaxTest/PMaxTestSeq.cs
2025-09-09 12:24:20 +02:00
michal b729b08da2 Version increment to 3.9.2146.3 2025-09-08 14:34:04 +02:00
michal 3209ff303c Add support for optional IRegReader parameter in ShowCycleBeginFormOp across multiple DataEntry modules and enhance PoseidonReader with SerialNr handling and simulation mode adjustments 2025-09-08 14:32:49 +02:00
michal 41693d9c83 Update configuration for IPERL support and logging enhancements
This commit integrates the `IPERL` mode across multiple projects by updating the `DefineConstants` in project configurations. It also improves logging by adding a `LogCache` appender and modifying root logger settings in the `log4netConfig.xml` file.
2025-09-08 10:09:47 +02:00
michal 8f02f4ff31 Merge branch 'master-3' into PoseidonCmd
# Conflicts:
#	TBF/Properties/AssemblyInfo.cs
2025-09-07 22:36:46 +02:00
michal 1525bb7c1a Patch applied - Add initial implementation for IperlHeadTestCtrl and NfcServices
This commit introduces the `IperlHeadTestCtrl` component and `NfcServices` class, including core functionality for communication with iPerl heads via NFC/RFID. It integrates configuration options, multithreaded commands processing, and logging through `log4net`.
2025-09-07 22:34:06 +02:00
michal 2aeaf42325 Patch applied - Add initial implementation for RegValveLowRegulTimeSaturation module
This commit introduces the `RegValveLowRegulTimeSaturation` module, including core components such as `RegValve`, `ChangeRegValvePositionOp`, `Factory`, `Handlers`, and configuration classes (`RegValveCfg`, `RegValveCfgCtrl`). It integrates `log4net` for logging and adheres to the established modular design architecture.
2025-09-07 22:18:35 +02:00
michal bf4fb469da Add initial implementation for AppDiagnostic project
This commit introduces the AppDiagnostic project structure, including core components like `MainForm`, logging utilities (`LogAdapter`, `LogFilter`), and configuration files. It integrates with `log4net` for logging and uses `SharedComponents` for shared utilities.
2025-09-07 22:13:58 +02:00
michal efd0515295 Patch applied - Added new calibration-related properties for IPERL mode, integrated AppDiagnostic functionality into UI, and updated project configuration. 2025-09-07 17:42:26 +02:00
michal be8ac28bc7 Version increment to 3.9.2146.1 and update PoseidonReader to use VolumeLi instead of VolumeM3 2025-09-07 17:35:20 +02:00
michal 56dc89ac82 Version increment to 3.9.2146.0 2025-09-05 12:29:40 +02:00
michal 62ffc94c49 Add PoseidonCmd DataEntry module integration: EntryForm, EntryFormCfg, Factory, and TestStartEndForm 2025-09-05 12:23:06 +02:00
michal 50a38bc557 "Refactor CJMS11 image grab functionality with timeout handling and error resilience
- Introduced a new `GrabImageListener` method with asynchronous timeout support for improved response handling.
- Enhanced error logging and implemented retry logic for capturing images to address NACK scenarios.
- Added overlay rendering and event-based image delivery for better UI integration.
- Refined `SendImageListener` logic to include command handling improvements and listener termination checks.
- Minor parameter adjustments in `OnImageReceived` for default values support."
2025-07-30 10:34:56 +02:00
michal 3e643854bc Add support for multiple image capture and time gap configuration in CJMS11
- Implemented functionality to handle multiple image captures with adjustable time gaps using the new `MultipleImageOpacity` class.
- Enhanced `RoiCfgCtrl` and `RoiCfg` to integrate multi-image configuration.
- Updated CJMS11 camera to support sequential image handling and delegate events for multiple images.
- Introduced UI elements for specifying image count and time gap in the configuration panel.
- Extended `GrabImagesOp` and event arguments to handle and store multiple grabbed images.
- Refactored project to include `MultipleImageOpacity` utility in TBF solution.
2025-07-28 10:16:07 +02:00
michal 0daefb93bb Add CJMS11 enhancements, logging, and resolution support
- Extended CJMS11 camera handling with new functionalities, including image grabbing, resolution configuration, and improved ROI support.
- Added new `ToString` method implementations for enhanced debugging and logging in key classes like `JmsMessage`, `JmsPacket`, and `RoiCfg`.
- Introduced additional commands (`start_stream_images`, `stop_stream_images`) in `CommandM` and its enum.
- Implemented new resolution handling in `RoiCfg` with support for configurable image frames.
- Refactored resolution-related UI elements in `RoiCfgCtrl` to add a dropdown for selecting resolution.
- Made minor UX improvements by replacing inconsistent string formats with verbatim strings in console messages.
- Updated project dependencies with new resolution-related utilities (`Frame` and `ResolutionFrames`).
- Resolved camera-specific symbolic issues by transitioning to `CJMS11.Camera` over prior naming inconsistencies.
2025-07-18 08:50:22 +02:00
michal f5731c67a0 Improve CJMS11 camera connection handling with timeout support
- Replaced synchronous connection retry logic with asynchronous timeout-based handling.
- Added exception handling for connection attempts exceeding 1 second.
- Introduced `EstablishCameraConnectionRepeticaly` with updated timeout intervals for retries.
2025-06-02 09:58:01 +02:00
michal d2ae5f3e83 It works !!! ??
Add support for `System.Net.Sockets`, enhance JMS camera detection, and refactor adapter connection handling

- Added `System.Net.Sockets` as a project dependency and updated the configuration file accordingly.
- Enhanced timeout logic for JMS camera detection, improving reliability in identifying cameras.
- Refactored `NetAdapter` to support async connection handling with better initialization in simulate mode.
- Fixed IP setup for debugging and added new task management for asynchronous operations.
2025-05-30 15:34:21 +02:00
michal c4d332b68b Add JMS network adapter support and multi-camera handling improvements
- Introduced `AdapterJMS` component and configurations, including its factory, control, and designer files.
- Enhanced CJMS11 camera initialization with improved connection handling via multiple retries.
- Updated TbfComponents to include the new JMS adapter factory.
- Refactored camera test methods and connection logic for better reliability and performance.
- Adjusted resource definitions in the project file to include new JMS adapter resources.
2025-05-30 13:44:40 +02:00
michal 1daa0212ef test of connection - multiple connections 2025-05-29 12:59:21 +02:00
michal 1748a83ec8 Add multi-camera initialization and update dependencies
Enhanced camera initialization with parallel and async tests for two cameras. Removed unused Telnet references, adjusted camera indexing logic, and added `System.Drawing.Common` dependency.
2025-05-28 22:50:47 +02:00
michal b3d6b5a59f Refactor camera handling; add UI and image management support.
Replaced legacy UDP and RTP mechanisms with new live stream, grab, and save image functionality using TCP. Introduced event-based UI command handling and image overlay. Updated resource management for improved reliability and added support for saving captured images to disk.
2025-05-26 08:58:46 +02:00
michal 891795b101 Add support for CJMS11 camera integration
Introduced the CJMS11 camera component and its factory in TbfComponents. Added implementation for the CJMS11 camera class, along with unit tests to validate its functionality and integration. This enhances existing camera support in the system.
2025-05-21 11:31:19 +02:00
michal a20b0761fd Fix nested string formatting in DoubleBox's return statement
Revised the return statement to correctly handle nested string formatting by ensuring the format string is constructed properly. This resolves potential formatting issues with dynamic values.
2025-03-26 10:22:50 +01:00
michal 3b9e8d754d fix valve Debug Simulate mode 2025-01-10 08:48:52 +01:00
michal fed3281525 log for processData in LeakTestSeq.cs set 2025-01-08 07:43:58 +01:00
michal c1d966d86a final add process data to PMaxTestSeq.cs 2025-01-07 16:23:01 +01:00
michal b2d2f8c13b Solved problem with Null Exeprion in ProcessData.cs 2025-01-07 16:22:18 +01:00
michal 4e5e3d63e1 Fixed problem with F2 formating of decimal num 2025-01-07 16:21:28 +01:00
michal 25602fb914 Bug fix - Refactor flow meter handling and add validation checks.
Simplified flow meter logic by introducing a reusable variable for `LtrPerPulse` and handling potential null values. Added batch components correlation validation to ensure water meter counts align with configuration, preventing mismatches. Additionally, improved code formatting for consistency and readability.
2024-12-19 14:16:25 +01:00
michal 602d0d5308 Add logging for process start and measurement steps
Updated `PMaxTestSeq` to include logging of process data at key steps: process start and measurement. Added TODO comments to review logging positions for alignment with expected workflow.
2024-12-17 09:59:31 +01:00
michal f95198e40e revision update 2024-11-13 13:36:54 +01:00
michal d2b2bbb94b Merge branch 'refs/heads/feature/fix_Swindon' into master-3
# Conflicts:
#	TBF/Properties/AssemblyInfo.cs
2024-11-12 09:56:24 +01:00
michal a4246c7ea4 user groups based PL_LANG enabled, DB update needed 2024-11-12 09:52:41 +01:00
michal 498fc21412 DIVERTER close valve end time - Mark Chenges 2024-11-11 14:18:39 +01:00
michal 3f07a506ad Added new Nummer Result - Failed_meters_countE15 2024-11-06 14:58:39 +01:00
michal fb74e2d785 fix, NullPointerExeption If Order have no name 2024-11-04 15:41:09 +01:00
michal 3a2290570d Table merged columns with +,- in mixing mode returning -, old behaviour was last test evaluation 2024-10-30 15:17:24 +01:00
michal 3b68e3f9fd Version increment 2024-10-30 15:15:34 +01:00
michal 3184b1da8e LANG_PL enabled 2024-10-30 15:14:36 +01:00
michal b70a10e697 Merge branch 'master-3' into feature/outputPrinterFix 2024-10-30 06:55:55 +01:00
michal 3433bbbebe removed unnecessary, update of behaviour - textChanged 2024-10-29 09:26:04 +01:00
michal 4c0a797e98 improvement + changed behaviour 2024-10-28 22:45:50 +01:00
michal 203c2498ac temp commit - hepl method 2024-10-25 09:27:33 +02:00
michal 2023ea5221 simulate mode fix problem with Broadcast camera connection 2024-10-21 13:28:21 +02:00
michal cbb3d4f735 Merge branch 'master-3' into feature/KameraKeyenceAdvance 2024-10-11 10:46:32 +02:00
michal 8acf219ba2 packages - added what neccesary, also for JetBains IDE 2024-10-11 10:44:16 +02:00
michal 68884cd7df Merge branch 'master-3' into feature/FixProcessDataFile 2024-10-11 10:23:55 +02:00
michal 1629d82d65 save before update 2024/10/11 2024-10-11 10:00:36 +02:00
michal 17ab11bdf1 version increment 2024-10-11 09:59:43 +02:00
michal d2ef959f15 fix for Stop measurement and save/Collect after End Session 2024-10-09 16:07:11 +02:00
Jan Augustin 21b00e9b83 Oracle data access is only managed. No need to install the Oracle client on test bench anymore. 2024-10-09 10:40:11 +02:00
michal 3d7aaaaa3d Remove TBF.csproj.DotSettings file
This file was deleted because it is no longer needed in the project. It contained resource dictionary entries and paths that are now obsolete.
2024-10-07 10:54:44 +02:00
michal 705f7760af update by Michal requirements, manual setting dialog events changed, camera dialog both behaviour prepared, reload previous results copy image solved,rest API, rest API additional values added, added ShowTestCollectFormOp, added lang string 2024-10-07 10:54:04 +02:00
Jan Augustin 3b385d592d Updated .gitignore 2024-09-26 09:55:15 +02:00
michal cf6a16656b Remove outdated TODO comments 2024-09-04 14:06:06 +02:00
michal f50f9bfa5b Add KeyPress handlers to comboBoxes and buttons
This change introduces KeyPress event handlers to various UI elements such as comboBoxes and buttons to improve key input handling. The corresponding event handlers were implemented and the UI components were updated accordingly.
2024-09-04 14:02:21 +02:00
michal 77d8c95930 Purchase Order - Collector complete, bug fix in entities version 3.9.2149.11 2024-09-02 14:21:40 +02:00
michal 57c2019405 DB purchaseOrder -> Remove Config Entities - moved into Results 2024-09-02 08:30:34 +02:00
michal 46432bc61b Dialog events added 2024-08-30 12:42:29 +02:00
michal a4360f6993 All changes - collect cammera, fixed pictures preview, collecting pictures - 48 meters to grab data 2024-08-30 10:22:57 +02:00
michal 97e0a764b8 Enable -Simulate- for this method !!! 2024-08-14 12:06:45 +02:00
michal 7409af70ac Advance components - StandingStartMassCollectionAdvance 2024-08-14 11:59:26 +02:00
michal 783d51e71a Fix Diverter switching - in sequence, logs 2024-03-15 21:02:39 +01:00
michal a710ab7457 PL lang fix, camera test 2024-03-10 22:25:55 +01:00
michal 6a428e3c76 Keyence Camera 2024-03-10 22:24:03 +01:00
michal 2e56b8e5cf packages log4net.2.0.15 dependency 2024-02-17 20:28:17 +01:00
michal 1a4c18fa35 TBFTest - removed Compile Include test AdjustableMeterTest 2024-02-17 20:26:16 +01:00
michal 153d031125 log4net packages.config 2024-02-12 21:49:30 +01:00
michal 5d4c7dfe68 log4net ver 2.0.15 2024-02-12 21:44:42 +01:00
michal 021beeb47f GroupPrinter - print in separate files/printers 2024-02-12 21:41:25 +01:00
michal 1140d67c75 GroupPrinter 2024-02-04 10:07:50 +01:00
michal f0d26a36be reformating 2024-02-04 10:06:41 +01:00
michal 6afb10351e limit less linear correction 2024-02-04 10:00:22 +01:00
michal 2f3259d063 fix bug paths 2024-02-04 08:38:40 +01:00
michal 30a9396e4a verzia 3.9.2140 2024-01-24 17:51:37 +01:00
michal 2a94347f3e final modification for AdjustableMeter.cs, Added units A,V ElectricUnits, calculation based on [A] 2024-01-24 17:35:56 +01:00
michal 30f5e6c935 mesure Ampers in kPa = 0.01 koef, tranform into pressure linear interpolation 2024-01-07 22:54:47 +01:00
michal 0ad8bc6d75 new Adjustable Meter with value correction - two params 2023-12-28 23:47:56 +01:00
3756 changed files with 3912919 additions and 13908 deletions
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Root Type="DevExpress.CodeRush.Foundation.CodePlaces.Options.FavoritesListContainer">
<Options Language="Neutral">
<Groups />
</Options>
</Root>
+36 -4
View File
@@ -1,3 +1,5 @@
AppDiagnostic/bin/
AppDiagnostic/obj/
Common/bin/
Common/obj/
Config/bin/
@@ -30,6 +32,10 @@ LabelPrinting/bin/
LabelPrinting/obj/
MergeResultsDBs/bin/
MergeResultsDBs/obj/
NfcC7_Dll/bin/
NfcC7_Dll/obj/
NfcC7_DLL.Tests/bin/
NfcC7_DLL.Tests/obj/
OrderManagement/bin/
OrderManagement/obj/
ProductionTracing/bin/
@@ -48,14 +54,18 @@ ResultsParser/bin/
ResultsParser/obj/
S640TestApp/bin/
S640TestApp/obj/
SharedDatabase/bin
SharedDatabase/obj
SchematicDrawing/bin
SchematicDrawing/obj
SharedComponents/bin/
SharedComponents/obj/
SharedDatabase/bin/
SharedDatabase/obj/
SchematicDrawing/bin/
SchematicDrawing/obj/
Statistics/bin/
Statistics/obj/
TBF/bin/
TBF/obj/
TBFTests/bin/
TBFTests/obj/
ToFirstMonitor/bin/
ToFirstMonitor/obj/
ToSecondMonitor/bin/
@@ -66,6 +76,28 @@ WorkflowConfigurator/bin/
WorkflowConfigurator/obj/
Workplace/bin/
Workplace/obj/
DataStreamInterfaceTest/bin/
DataStreamInterfaceTest/obj/
DataStreamMeter/bin/
DataStreamMeter/obj/
Events/bin/
Events/obj/
TracingDB/bin/
TracingDB/obj/
Users/bin/
Users/obj/
.vs/
.idea/
*.suo
*.bak
TBF.sln.DotSettings.user
/ExternalProjects
/GenesisCordonelTester
/packages
/GenesisCordonelInterface/bin/Debug/GenesisCordonelInterfaceLogger.log
/GenesisCordonelInterface/bin/Debug/GenesisCordonelTesterLogger.log
/GenesisCordonelInterface/bin/Debug/SirtConfig.json
/GenesisCordonelInterface/bin/Release
/GenesisCordonelInterface/obj/Debug
/GenesisCordonelInterface/obj/Release
/ExternalProjects
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<log4net>
<appender name="LogCacheAppender" type="Namespace.LogCacheAppender, AssemblyName">
<param name="Cache" value="YourCacheInstance" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogCacheAppender" />
</root>
</log4net>
</configuration>
+105
View File
@@ -0,0 +1,105 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>AppDiagnostic</RootNamespace>
<AssemblyName>AppDiagnostic</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=3.0.3.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.0.3\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BufferedListView.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="DiagApi.cs" />
<Compile Include="LogAdapter.cs" />
<Compile Include="LogFilter.cs" />
<Compile Include="MainForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="MainForm.Designer.cs">
<DependentUpon>MainForm.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="MainForm.resx">
<DependentUpon>MainForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SharedComponents\SharedComponents.csproj">
<Project>{8f942729-f454-4c99-ba6c-746962065ae3}</Project>
<Name>SharedComponents</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="Resources\TBF_icon.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
+16
View File
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public class BufferedListView : ListView
{
public BufferedListView()
{
// Zapne dvojité bufferovanie pre ListView
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
this.UpdateStyles();
}
}
+32
View File
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppDiagnostic
{
public class DiagApi
{
private static MainForm diagWindow; // Udržiava referenciu na existujúce okno
public DiagApi()
{
if (diagWindow == null || diagWindow.IsDisposed) // Ak okno neexistuje, vytvoríme ho
{
diagWindow = new MainForm();
diagWindow.FormClosing += (s, e) =>
{
diagWindow = null; // Keď sa zavrie, vyčistíme referenciu
};
diagWindow.Show();
}
else
{
diagWindow.BringToFront(); // Ak už beží, len ho presunieme na vrch
diagWindow.WindowState = FormWindowState.Normal; // Ak je minimalizované, obnovíme ho
}
}
}
}
+174
View File
@@ -0,0 +1,174 @@
using SharedComponents;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppDiagnostic
{
public class LogAdapter
{
private ListView _listView;
public string _filterText = string.Empty;
private bool _isUserScrolling = false; // Indikátor, že používateľ manuálne scrolluje
private bool _autoScrollEnabled = true; // Indikátor, že automatické scrollovanie je povolené
private Timer _refreshTimer;
private const int RefreshInterval = 1000;
public LogAdapter(ListView listView)
{
_listView = listView;
// Nastavenie ListView
_listView.View = View.Details;
_listView.Columns.Clear();
_listView.Columns.Add("Logs");
_listView.Scrollable = true;
// Nastavenie šírky stĺpca na celú šírku ListView
AdjustColumnWidth();
// Udalosť pre dynamickú zmenu veľkosti stĺpca pri zmene veľkosti ListView
_listView.Resize += (sender, args) => AdjustColumnWidth();
// Pridanie udalosti pre manuálne skrolovanie
_listView.MouseWheel += ListView_MouseWheel;
// Inicializácia časovača na pravidelný refresh
_refreshTimer = new Timer { Interval = RefreshInterval };
_refreshTimer.Tick += (sender, args) => RefreshListView();
_refreshTimer.Start();
}
private void ListView_MouseWheel(object sender, MouseEventArgs e)
{
_isUserScrolling = true;
// Ak sa manuálnym scrollovaním používateľ dostane na koniec, obnovíme automatické scrollovanie
if (IsOnLastItem())
{
_isUserScrolling = false;
_autoScrollEnabled = true;
}
else
{
_autoScrollEnabled = false;
}
}
public void RefreshListView()
{
//LiveLogCache.Instance.AddLog(string.Format("-------------------------------RunDeviceAfter()-------------------------------"));
if (_listView.InvokeRequired)
{
_listView.Invoke(new Action(RefreshListView));
return;
}
_listView.BeginUpdate();
try
{
// Získanie pozície prvého viditeľného prvku pre stabilizáciu scrollovania
int topIndexBeforeRefresh = _listView.TopItem?.Index ?? 0;
// Pred pridaním nových položiek si pamätáme, či bol používateľ na poslednej položke
bool wasOnLastItem = IsOnLastItem();
// Uchovanie aktuálne označených položiek (indexov)
var selectedIndices = _listView.SelectedIndices.Cast<int>().ToList();
// Načítanie logov
var logs = LiveLogCache.Instance.GetLogs(0, LiveLogCache.Instance.GetCount())
.Where(log => string.IsNullOrEmpty(_filterText) ||
log.IndexOf(_filterText, StringComparison.OrdinalIgnoreCase) >= 0)
.ToList();
// Vymazanie existujúcich položiek a pridanie nových
_listView.Items.Clear();
foreach (var log in logs)
{
var item = new ListViewItem(log)
{
BackColor = _listView.Items.Count % 2 == 0 ? Color.White : Color.FromArgb(240, 240, 240)
};
_listView.Items.Add(item);
}
// Obnovenie označených položiek
foreach (var index in selectedIndices)
{
if (index < _listView.Items.Count)
{
_listView.Items[index].Selected = true;
}
}
// Ak bol používateľ na poslednom prvku, nastavíme focus a scroll na posledný prvok
if (_autoScrollEnabled && wasOnLastItem && _listView.Items.Count > 0)
{
var lastItemIndex = _listView.Items.Count - 1;
_listView.EnsureVisible(lastItemIndex);
_listView.Items[lastItemIndex].Focused = true;
}
else
{
// Ak používateľ nebol na spodku, vrátime sa na predchádzajúcu pozíciu scrollu
if (topIndexBeforeRefresh < _listView.Items.Count)
{
_listView.TopItem = _listView.Items[topIndexBeforeRefresh];
}
}
}
finally
{
_listView.EndUpdate();
}
}
public void ApplyFilter(string filterText)
{
_filterText = filterText?.Trim() ?? string.Empty;
RefreshListView();
}
private bool IsOnLastItem()
{
if (_listView.Items.Count == 0)
return false;
// Získame poslednú položku
int lastItemIndex = _listView.Items.Count - 1;
var lastItem = _listView.Items[lastItemIndex];
// Overíme, či je posledná položka úplne viditeľná
return lastItem.Bounds.Bottom <= _listView.ClientRectangle.Bottom;
}
public void EnableAutoScroll()
{
_autoScrollEnabled = true;
}
public void DisableAutoScroll()
{
_autoScrollEnabled = false;
}
private void AdjustColumnWidth()
{
if (_listView.Columns.Count > 0)
{
_listView.Columns[0].Width = _listView.ClientSize.Width;
}
}
}
}
+91
View File
@@ -0,0 +1,91 @@
using SharedComponents;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppDiagnostic
{
public class LogFilter
{
private ListView _listView;
private string _filterText = string.Empty; // Pre uloženie aktuálneho filtrovaného reťazca
// Konstruktor
public LogFilter(ListView listView)
{
_listView = listView;
}
// Metóda na aplikovanie filtra na ListView
public void ApplyFilter(string filterText)
{
_filterText = filterText.ToLower(); // Ukladáme text filtra bez ohľadu na veľkosť písmen
// Po aplikovaní filtra obnovíme zobrazenie
RefreshListView();
}
public void RefreshListView()
{
try
{
// Skontrolujeme, či sme na hlavnom vlákne a v prípade potreby použijeme Invoke
if (_listView.InvokeRequired)
{
// Použijeme Invoke, ak nie sme na hlavnom vlákne
_listView.Invoke(new Action(RefreshListView));
}
else
{
// Vymazanie existujúcich položiek
_listView.Items.Clear();
// Načítame všetky logy (ideálne z cache alebo databázy)
var logs = LiveLogCache.Instance.GetLogs(0, LiveLogCache.Instance.Logs.Count);
// Pridáme len tie logy, ktoré spĺňajú filter
foreach (var log in logs)
{
if (log.ToLower().Contains(_filterText)) // Kontrola, či log obsahuje filter text
{
var listViewItem = new ListViewItem(log);
// Striedanie farieb riadkov
if (_listView.Items.Count % 2 == 0) // Párny index => biela
{
listViewItem.BackColor = Color.White;
}
else // Nepárny index => svetlá sivá
{
listViewItem.BackColor = Color.FromArgb(240, 240, 240); // Veľmi svetlá sivá
}
// Pridanie efektu pre novú položku
ApplyNewItemEffect(listViewItem);
// Pridanie položky do ListView
_listView.Items.Add(listViewItem);
}
}
}
}
catch (Exception ex)
{
// Zachytíme výnimku, ak sa niečo pokazí, a zobrazíme ju užívateľovi
MessageBox.Show($"An error occurred while refreshing the log view: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Môžete pridať ďalšie metódy na zobrazenie alebo efekt pre nové položky, ak je to potrebné
private void ApplyNewItemEffect(ListViewItem item)
{
// Prípadný efekt pre nový pridaný log
// Môžete pridať animáciu alebo zmenu farby atď.
item.ForeColor = Color.Green; // Napríklad zmeníme farbu písma na zelenú
}
}
}
+278
View File
@@ -0,0 +1,278 @@
using System.Windows.Forms;
namespace AppDiagnostic
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
//private BufferedListView memoListView;
private System.Windows.Forms.ColumnHeader columnHeaderTime;
private System.Windows.Forms.ColumnHeader columnHeaderMessage;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.columnHeaderTime = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeaderMessage = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.panel1 = new System.Windows.Forms.Panel();
this.refreshMemoButton = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.filterManagementPanel = new System.Windows.Forms.Panel();
this.button5 = new System.Windows.Forms.Button();
this.filterButton = new System.Windows.Forms.Button();
this.filterTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.wndControlPanel = new System.Windows.Forms.Panel();
this.button2 = new System.Windows.Forms.Button();
this.flowControlsPanel = new System.Windows.Forms.Panel();
this.runButton = new System.Windows.Forms.Button();
this.stopButton = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.memoListView = new BufferedListView();
this.panel1.SuspendLayout();
this.filterManagementPanel.SuspendLayout();
this.wndControlPanel.SuspendLayout();
this.flowControlsPanel.SuspendLayout();
this.SuspendLayout();
//
// columnHeaderTime
//
this.columnHeaderTime.Text = "Time";
this.columnHeaderTime.Width = 150;
//
// columnHeaderMessage
//
this.columnHeaderMessage.Text = "Message";
this.columnHeaderMessage.Width = 350;
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.panel1.Controls.Add(this.refreshMemoButton);
this.panel1.Controls.Add(this.button6);
this.panel1.Controls.Add(this.button7);
this.panel1.Location = new System.Drawing.Point(189, 356);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(283, 26);
this.panel1.TabIndex = 16;
//
// refreshMemoButton
//
this.refreshMemoButton.Location = new System.Drawing.Point(108, 0);
this.refreshMemoButton.Name = "refreshMemoButton";
this.refreshMemoButton.Size = new System.Drawing.Size(84, 26);
this.refreshMemoButton.TabIndex = 17;
this.refreshMemoButton.Text = "Refresh memo";
this.refreshMemoButton.UseVisualStyleBackColor = true;
this.refreshMemoButton.Click += new System.EventHandler(this.refreshMemoButton_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(0, 0);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(102, 26);
this.button6.TabIndex = 4;
this.button6.Text = "Clean diag cache";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// button7
//
this.button7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button7.Location = new System.Drawing.Point(198, 0);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(72, 26);
this.button7.TabIndex = 5;
this.button7.Text = "Save logs";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// filterManagementPanel
//
this.filterManagementPanel.Controls.Add(this.button5);
this.filterManagementPanel.Controls.Add(this.filterButton);
this.filterManagementPanel.Controls.Add(this.filterTextBox);
this.filterManagementPanel.Controls.Add(this.label2);
this.filterManagementPanel.Location = new System.Drawing.Point(127, 6);
this.filterManagementPanel.Name = "filterManagementPanel";
this.filterManagementPanel.Size = new System.Drawing.Size(393, 26);
this.filterManagementPanel.TabIndex = 15;
//
// button5
//
this.button5.Enabled = false;
this.button5.Location = new System.Drawing.Point(294, 4);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(81, 20);
this.button5.TabIndex = 11;
this.button5.Text = "Add new filter";
this.button5.UseVisualStyleBackColor = true;
//
// filterButton
//
this.filterButton.Location = new System.Drawing.Point(225, 4);
this.filterButton.Name = "filterButton";
this.filterButton.Size = new System.Drawing.Size(64, 20);
this.filterButton.TabIndex = 10;
this.filterButton.Text = "Set filter";
this.filterButton.UseVisualStyleBackColor = true;
this.filterButton.Click += new System.EventHandler(this.filterButton_Click_1);
//
// filterTextBox
//
this.filterTextBox.Location = new System.Drawing.Point(33, 4);
this.filterTextBox.Name = "filterTextBox";
this.filterTextBox.Size = new System.Drawing.Size(187, 20);
this.filterTextBox.TabIndex = 7;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 8);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(29, 13);
this.label2.TabIndex = 6;
this.label2.Text = "Filter";
//
// wndControlPanel
//
this.wndControlPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.wndControlPanel.Controls.Add(this.button2);
this.wndControlPanel.Location = new System.Drawing.Point(831, 356);
this.wndControlPanel.Name = "wndControlPanel";
this.wndControlPanel.Size = new System.Drawing.Size(70, 26);
this.wndControlPanel.TabIndex = 14;
//
// button2
//
this.button2.Location = new System.Drawing.Point(3, 0);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(64, 26);
this.button2.TabIndex = 2;
this.button2.Text = "Close";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// flowControlsPanel
//
this.flowControlsPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.flowControlsPanel.Controls.Add(this.runButton);
this.flowControlsPanel.Controls.Add(this.stopButton);
this.flowControlsPanel.Location = new System.Drawing.Point(12, 356);
this.flowControlsPanel.Name = "flowControlsPanel";
this.flowControlsPanel.Size = new System.Drawing.Size(133, 26);
this.flowControlsPanel.TabIndex = 13;
//
// runButton
//
this.runButton.Enabled = false;
this.runButton.Location = new System.Drawing.Point(0, 0);
this.runButton.Name = "runButton";
this.runButton.Size = new System.Drawing.Size(64, 26);
this.runButton.TabIndex = 4;
this.runButton.Text = "Run";
this.runButton.UseVisualStyleBackColor = true;
this.runButton.Click += new System.EventHandler(this.runButton_Click);
//
// stopButton
//
this.stopButton.Location = new System.Drawing.Point(69, 0);
this.stopButton.Name = "stopButton";
this.stopButton.Size = new System.Drawing.Size(64, 26);
this.stopButton.TabIndex = 5;
this.stopButton.Text = "Stop";
this.stopButton.UseVisualStyleBackColor = true;
this.stopButton.Click += new System.EventHandler(this.stopButton_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 19);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(76, 13);
this.label1.TabIndex = 12;
this.label1.Text = "Flow of events";
//
// memoListView
//
this.memoListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.memoListView.FullRowSelect = true;
this.memoListView.GridLines = true;
this.memoListView.HideSelection = false;
this.memoListView.Location = new System.Drawing.Point(12, 38);
this.memoListView.Name = "memoListView";
this.memoListView.Size = new System.Drawing.Size(889, 312);
this.memoListView.TabIndex = 0;
this.memoListView.UseCompatibleStateImageBehavior = false;
this.memoListView.View = System.Windows.Forms.View.Details;
this.memoListView.DoubleClick += new System.EventHandler(this.MemoListView_DoubleClick);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(913, 388);
this.Controls.Add(this.memoListView);
this.Controls.Add(this.panel1);
this.Controls.Add(this.filterManagementPanel);
this.Controls.Add(this.wndControlPanel);
this.Controls.Add(this.flowControlsPanel);
this.Controls.Add(this.label1);
this.Name = "MainForm";
this.Text = "Application live diagnostic";
this.panel1.ResumeLayout(false);
this.filterManagementPanel.ResumeLayout(false);
this.filterManagementPanel.PerformLayout();
this.wndControlPanel.ResumeLayout(false);
this.flowControlsPanel.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Panel filterManagementPanel;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button filterButton;
private System.Windows.Forms.TextBox filterTextBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Panel wndControlPanel;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Panel flowControlsPanel;
private System.Windows.Forms.Button runButton;
private System.Windows.Forms.Button stopButton;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button refreshMemoButton;
private BufferedListView memoListView;
}
}
+268
View File
@@ -0,0 +1,268 @@
using log4net.Config;
using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using log4net.Appender;
using SharedComponents;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.IO; // Pre File.WriteAllLines a prácu so súbormi
using System.Linq;
namespace AppDiagnostic
{
public partial class MainForm : Form
{
private bool stopUpdate = false; // Premenná na zastavenie aktualizácie
private int lastDisplayedLogIndex = 0;
private bool autoScrollEnabled = true; // Automatický posun, predvolene povolený
private MainForm appDiagnosticForm;
private Timer refreshTimer;
private LogAdapter _logAdapter; // Pre LogAdapter
private LogFilter _logFilter; // LogFilter objekt pre filtráciu
public MainForm()
{
this.Icon = Properties.Resources.TBF_icon;
InitializeComponent();
// Inicializujeme LogAdapter a priradíme ho k memoListView
_logAdapter = new LogAdapter(memoListView);
RefreshLogView();
// Pripojenie na udalosť pri pridaní nového logu
// nakoľko sa memo refreshuje cyklicky, tak refresh na udalosť nepotrebujem
//LiveLogCache.Instance.LogAdded += OnLogAdded;
// Vytvoríme LogFilter objekt
//_logFilter = new LogFilter(memoListView);
}
private void OnLogAdded(string log)
{
try
{
RefreshLogView();
}
catch (Exception ex)
{
MessageBox.Show($"Error in OnLogAdded: {ex.Message}");
throw;
}
}
private void RefreshLogView()
{
// Skontrolujte, či voláme z iného vlákna
if (InvokeRequired)
{
Invoke((Action)RefreshLogView);
return;
}
memoListView.BeginUpdate(); // Zabraňuje vizuálnym aktualizáciám počas vykresľovania
try
{
// Skontrolujte, či je užívateľ na poslednom viditeľnom zázname
if (memoListView.Items.Count > 0)
{
var lastVisibleIndex = memoListView.TopItem.Index + memoListView.ClientRectangle.Height / memoListView.Items[0].Bounds.Height;
autoScrollEnabled = lastVisibleIndex >= memoListView.Items.Count - 1;
}
// Získajte nové logy od posledného indexu
var logs = LiveLogCache.Instance.GetLogs(lastDisplayedLogIndex, LiveLogCache.Instance.Logs.Count - lastDisplayedLogIndex);
// Pridajte len nové logy
foreach (var log in logs)
{
memoListView.Items.Add(new ListViewItem(log));
}
// Aktualizujte posledný zobrazený index
lastDisplayedLogIndex = LiveLogCache.Instance.Logs.Count;
// Ak je autoScrollEnabled, posuňte sa na posledný záznam
if (autoScrollEnabled && memoListView.Items.Count > 0)
{
memoListView.EnsureVisible(memoListView.Items.Count - 1);
}
}
finally
{
memoListView.EndUpdate(); // Umožní vizuálne aktualizácie
}
}
// Táto metóda sa spustí pri scrollovaní v memoListView (tzn. ak sa používateľ dostane na spodok listu)
private void memoListView_Scroll(object sender, EventArgs e)
{
// Skontrolujte, či používateľ dosiahol spodok ListView
if (memoListView.Items.Count > 0 &&
memoListView.Items[memoListView.Items.Count - 1].Bounds.Bottom <= memoListView.ClientSize.Height)
{
// Ak áno, načítame ďalšie logy
RefreshLogView();
}
}
private void button6_Click(object sender, EventArgs e)
{
//LiveLogCache.Instance.AddLog("Nový log z hlavnej aplikácie");
LiveLogCache.Instance.ClearLogs();
ClearListView();
}
private void runButton_Click(object sender, EventArgs e)
{
if (stopUpdate) // Ak je časovač zastavený, spustíme ho
{
stopUpdate = false; // Zastav aktualizáciu
runButton.Enabled = false; // Zakážeme tlačidlo Start počas behu
stopButton.Enabled = true; // Povolenie tlačidla Stop
refreshTimer.Start();
}
}
private void stopButton_Click(object sender, EventArgs e)
{
if (!stopUpdate) // Ak časovač beží, môžeme ho zastaviť
{
stopUpdate = true; // Spusti aktualizáciu
runButton.Enabled = true; // Povolenie tlačidla Start
stopButton.Enabled = false; // Zakážeme tlačidlo Stop
refreshTimer.Stop();
}
}
private void ClearListView()
{
if (InvokeRequired)
{
Invoke(new Action(ClearListView));
return;
}
memoListView.Items.Clear();
}
private void refreshMemoButton_Click(object sender, EventArgs e)
{
}
private void button7_Click(object sender, EventArgs e)
{
SaveLogsToFile();
//LiveLogCache.Instance.AddLog("Toto je nový log.");
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
// Odpojenie udalosti, keď sa okno zatvára, inak môže po opätovnom spustení okna a pridaní nového itemu do listu zhhodiť program
// nakoľko sa memo refreshuje cyklicky, tak refresh na udalosť nepotrebujem
//LiveLogCache.Instance.LogAdded -= OnLogAdded;
_logAdapter = null;
base.OnFormClosing(e);
}
private void filterButton_Click_1(object sender, EventArgs e)
{
// Aplikujeme filter na základe textu z filterTextBox
string filterText = filterTextBox.Text;
//_logFilter.ApplyFilter(filterText); // Aplikovanie filtra
_logAdapter.ApplyFilter(filterText);
}
private void SubForm_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
// Vaša logika pri uzatváraní formy
// this.Hide(); // Podforma sa len skryje
}
catch (Exception ex)
{
// Ošetrenie výnimky
MessageBox.Show("Chyba pri zatváraní pod-aplikácie: " + ex.Message);
}
}
private void SaveLogsToFile()
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
saveFileDialog.Title = "Save TBF live logs";
saveFileDialog.DefaultExt = "txt";
saveFileDialog.FileName = "TBFLiveLogs.txt";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
// Načítanie všetkých logov z LiveLogCache
var logs = LiveLogCache.Instance.GetLogs(0, LiveLogCache.Instance.GetCount());
// Uloženie logov do vybraného súboru
File.WriteAllLines(saveFileDialog.FileName, logs);
MessageBox.Show("Logs saved successfully.", "Save TBF live logs", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred while saving TBF live logs: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
//this.Hide(); // Podforma sa len skryje
}
private void MemoListView_DoubleClick(object sender, EventArgs e)
{
if (memoListView.SelectedItems.Count > 0)
{
var selectedItem = memoListView.SelectedItems[0];
int selectedIndex = memoListView.Items.IndexOf(selectedItem);
if (selectedIndex >= 0)
{
// Zrušenie filtra
_logAdapter._filterText = string.Empty;
// Načítanie logov od indexu vybraného riadku
var logs = LiveLogCache.Instance.GetLogs(selectedIndex, LiveLogCache.Instance.GetCount() - selectedIndex);
// Obnovenie ListView s novými údajmi
memoListView.BeginUpdate();
memoListView.Items.Clear();
foreach (var log in logs)
{
var item = new ListViewItem(log)
{
BackColor = memoListView.Items.Count % 2 == 0 ? Color.White : Color.FromArgb(240, 240, 240)
};
memoListView.Items.Add(item);
}
memoListView.EndUpdate();
}
}
}
}
}
+120
View File
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
+22
View File
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppDiagnostic
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
+33
View File
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AppDiagnostic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AppDiagnostic")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fa9abad1-7184-4295-ade8-d44f2e3de6b2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+73
View File
@@ -0,0 +1,73 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AppDiagnostic.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AppDiagnostic.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon TBF_icon {
get {
object obj = ResourceManager.GetObject("TBF_icon", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
}
}
+124
View File
@@ -0,0 +1,124 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="TBF_icon" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\TBF_icon.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>
+30
View File
@@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AppDiagnostic.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="3.0.3" targetFramework="net472" />
</packages>
+12 -5
View File
@@ -17,7 +17,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;LANG_PL</DefineConstants>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
@@ -25,17 +25,22 @@
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;LANG_PL</DefineConstants>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net">
<HintPath>..\packages\log4net.2.0.2\lib\net40-full\log4net.dll</HintPath>
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="NLog, Version=5.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.5.2.2\lib\net46\NLog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
@@ -90,7 +95,9 @@
<Compile Include="Utils.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Forms\ListViewEx.resx">
<DependentUpon>ListViewEx.cs</DependentUpon>
+21 -2
View File
@@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Common
{
@@ -289,11 +290,20 @@ namespace Common
CompoundAux,
Compound,
HeatMeterVolume,
HeatMeterEnergy,
HeatMeterMass,//...MF
HeatMeterEnergy,
SingleOrCompound, /// Only used when querying results
}
public enum Medium
public enum PulsesTypeByQuantity : short
{
[Description("dm3")] Volume_dm3,
[Description("kg")] Mass_kg,
Count
}
public enum Medium
{
[Description("")] NotSpecified,
#if LANG_PL
@@ -829,6 +839,15 @@ namespace Common
E63 = (1L << 62),
}
//...MF
public enum FlowType : int
{
none,
volume,
mass,
Count,
}
#region iPERL enums
public enum Side
+1 -1
View File
@@ -56,7 +56,7 @@ namespace Common.Iperl
public double Flow(double scalingFactor) { return 0.225 * scalingFactor * (double)FlowRaw; }
public double Volume(double scalingFactor) { return 0.0000625 * scalingFactor * (double)VolumeRawExt; }
public Int32 FlipTime() { return Impedance; }
public decimal TimestampDec() { return (decimal)TimestampExt / (decimal)8192; }
public decimal TimestampDec() { return (decimal)TimestampExt; }
public double VolumeDelta(double scalingFactor, OptoTelegramRaw previous) { return (previous == null) ? 0 : Volume(scalingFactor) - previous.Volume(scalingFactor); }
public decimal TimeDelta() { return TimestampDec() - TestStartTimestampDec; }
public string Label()
+131 -23
View File
@@ -2,6 +2,7 @@
/// Copyright (c) 2016-2021 Sensus Slovensko a.s.
///
using System;
using System.Linq;
namespace Common
{
@@ -33,6 +34,20 @@ namespace Common
[Description("m3/m")] m3pm, /// 1 m3/m = 60 m3/h
[Description("cf/s")] cfs, /// 1 cubic foot per second = 101.9406477312 m3/h
[Description("g/s")] gps, /// 1 g/s = 0.0036 t/h
[Description("g/min")] gpm, /// 1 g/min = 0.00006 t/h
[Description("g/h")] gph, /// 1 g/h = 0.000001 t/h
[Description("kg/s")] kgps, /// 1 kg/s = 3.6 t/h
[Description("kg/min")] kgpm, /// 1 kg/min = 0.06 t/h
[Description("kg/h")] kgph, /// 1 kg/h = 0.001 t/h
[Description("t/s")] tps, /// 1 t/s = 3600 t/h
[Description("t/min")] tpm, /// 1 t/min = 60 t/h
[Description("t/h")] tph, /// 1 t/h = 1 t/h
[Description("lb/s")] lbps, /// 1 lb/s ≈ 1.633 t/h
[Description("lb/min")] lbpm, /// 1 lb/min ≈ 0.027216 t/h
[Description("lb/h")] lbph, /// 1 lb/h ≈ 0.0004536 t/h
[Description("g")] g, /// 0.001 kg
[Description("oz")] oz, /// 0.0283495231 kg
[Description("lb")] lb, /// 0.45359237 kg
@@ -105,6 +120,14 @@ namespace Common
///
[Description("pulse/kWh")] ppkWh, /// * 1 pulse/kWh
[Description("kWh/pulse")] kWhpp, /// 1 kWh/pulse
///
[Description("A")] A, /// *1 A
[Description("mA")] mA, /// 1 mA = 0.001 A
///
[Description("V")] V, /// *1 V
[Description("mV")] mV, /// 1 mV = 0.001 V
Count
}
@@ -135,6 +158,8 @@ namespace Common
[Description("Boolean")] Boolean,
[Description("Datum und Uhrzeit")] DateTime,
[Description("Aufgezählt")] Enumerated,
[Description("Strom")] Current,
[Description("Spannung")] Voltage,
#elif LANG_PL
[Description("Objętość")] Volume,
[Description("Przepływ")] Flow,
@@ -158,6 +183,8 @@ namespace Common
[Description("Boolean")] Boolean,
[Description("Data i czas")] DateTime,
[Description("Wyliczone")] Enumerated,
[Description("Prąd")] Current,
[Description("Napięcie")] Voltage,
#elif LANG_CS
[Description("Objem")] Volume,
[Description("Průtok")] Flow,
@@ -181,6 +208,8 @@ namespace Common
[Description("Boolean")] Boolean,
[Description("Datum a čas")] DateTime,
[Description("Vyjmenované")] Enumerated,
[Description("Proud")] Current,
[Description("Napětí")] Voltage,
#elif LANG_IT
[Description("Volume")] Volume,
[Description("Flusso")] Flow,
@@ -204,10 +233,16 @@ namespace Common
[Description("Boolean")] Boolean,
[Description("Data e ora")] DateTime,
[Description("Enumerato")] Enumerated,
[Description("Corrente")] Current,
[Description("Voltaggio")] Voltage,
#else
[Description("RegisterReader")] RegisterReader,
[Description("MultiFunctionalVariables")] MultiFunctionalVariables,
[Description("VolumeFlow")] VolumeFlow,
[Description("Volume")] Volume,
[Description("Flow")] Flow,
[Description("Mass")] Mass,
[Description("MassFlow")] MassFlow,
[Description("Mass")] Mass,
[Description("Time")] Time,
[Description("Temperature")] Temperature,
[Description("Pressure")] Pressure,
@@ -218,6 +253,8 @@ namespace Common
[Description("Energy")] Energy,
[Description("Pulses")] Pulses,
[Description("Pulses/liter")] PulsePerLtr,
[Description("Pulses/kg")] PulsePerKilogram, //...MF
[Description("Pulses/Unit")] PulsePerUnit,//...MF
[Description("Pulses/kWh")] PulsePerKWh,
[Description("Conductivity")] Conductivity,
@@ -227,6 +264,8 @@ namespace Common
[Description("Boolean")] Boolean,
[Description("Date and time")] DateTime,
[Description("Enumerated")] Enumerated,
[Description("Current")] Current,
[Description("Voltage")] Voltage,
#endif
Count,
}
@@ -242,59 +281,103 @@ namespace Common
{
return unit == Unit.l || unit == Unit.m3ph || unit == Unit.kg || unit == Unit.s || unit == Unit.C ||
unit == Unit.bar || unit == Unit.RPct || unit == Unit.Pct || unit == Unit.mm || unit == Unit.kgpm3 ||
unit == Unit.J || unit == Unit.uSpcm || unit == Unit.ppl || unit == Unit.ppkWh;
unit == Unit.J || unit == Unit.uSpcm || unit == Unit.ppl || unit == Unit.ppkWh || unit == Unit.A ||
unit == Unit.V;
}
public static bool IsQuantity(Unit unit, Quantity quantity)
{
return (quantity == GetQuantity(unit));
return GetQuantity(unit).Contains(quantity);
}
public static Quantity GetQuantity(Unit unit)
public static Quantity[] GetQuantity(Unit unit)
{
switch (unit)
{
case Unit.pulse:
case Unit.degree:
return Quantity.Pulses;
return new[] { Quantity.Pulses };
case Unit.ml:
return new[] { Quantity.Volume, Quantity.MultiFunctionalVariables };
case Unit.l:
return new[] { Quantity.Volume, Quantity.MultiFunctionalVariables };
case Unit.dm3:
return new[] { Quantity.Volume, Quantity.MultiFunctionalVariables };
case Unit.USgal:
return new[] { Quantity.Volume, Quantity.MultiFunctionalVariables };
case Unit.UKgal:
return new[] { Quantity.Volume, Quantity.MultiFunctionalVariables };
case Unit.cf:
return new[] { Quantity.Volume, Quantity.MultiFunctionalVariables };
case Unit.m3:
return Quantity.Volume;
return new[] { Quantity.Volume, Quantity.MultiFunctionalVariables };
case Unit.lph:
return new[] { Quantity.Flow };
case Unit.cfph:
return new[] { Quantity.Flow };
case Unit.lpm:
return new[] { Quantity.Flow };
case Unit.USgalpm:
return new[] { Quantity.Flow };
case Unit.m3ph:
return new[] { Quantity.Flow };
case Unit.lps:
return new[] { Quantity.Flow };
case Unit.USgalps:
return new[] { Quantity.Flow };
case Unit.m3pm:
return new[] { Quantity.Flow };
case Unit.cfs:
return Quantity.Flow;
return new[] { Quantity.Flow };
case Unit.gps:
return new[] { Quantity.MassFlow};
case Unit.gpm:
return new[] { Quantity.MassFlow};
case Unit.gph:
return new[] { Quantity.MassFlow};
case Unit.kgps:
return new[] { Quantity.MassFlow};
case Unit.kgpm:
return new[] { Quantity.MassFlow};
case Unit.kgph:
return new[] { Quantity.MassFlow};
case Unit.tps:
return new[] { Quantity.MassFlow};
case Unit.tpm:
return new[] { Quantity.MassFlow};
case Unit.tph:
return new[] { Quantity.MassFlow};
case Unit.lbps:
return new[] { Quantity.MassFlow};
case Unit.lbpm:
return new[] { Quantity.MassFlow};
case Unit.lbph:
return new[] { Quantity.MassFlow};
case Unit.g:
return new[] { Quantity.Mass, Quantity.MultiFunctionalVariables };
case Unit.oz:
return new[] { Quantity.Mass, Quantity.MultiFunctionalVariables };
case Unit.lb:
return new[] { Quantity.Mass, Quantity.MultiFunctionalVariables };
case Unit.kg:
return new[] { Quantity.Mass, Quantity.MultiFunctionalVariables };
case Unit.t:
return Quantity.Mass;
return new[] { Quantity.Mass, Quantity.MultiFunctionalVariables };
case Unit.ms:
case Unit.s:
case Unit.min:
case Unit.hour:
return Quantity.Time;
return new[] { Quantity.Time };
case Unit.C:
case Unit.F:
case Unit.K:
return Quantity.Temperature;
return new[] { Quantity.Temperature };
case Unit.Pa:
case Unit.hPa:
@@ -304,14 +387,14 @@ namespace Common
case Unit.psi:
case Unit.bar:
case Unit.MPa:
return Quantity.Pressure;
return new[] { Quantity.Pressure };
case Unit.RPct:
return Quantity.Humidity;
return new[] { Quantity.Humidity };
case Unit.Promile:
case Unit.Pct:
return Quantity.Error;
return new[] { Quantity.Error };
case Unit.mm:
case Unit.cm:
@@ -320,23 +403,23 @@ namespace Common
case Unit.foot:
case Unit.yard:
case Unit.m:
return Quantity.Length;
return new[] { Quantity.Length };
case Unit.kgpm3:
case Unit.kgpm3:
case Unit.kgpl:
return Quantity.Density;
return new[] { Quantity.Density };
case Unit.J:
case Unit.J:
case Unit.kJ:
case Unit.MJ:
case Unit.Wh:
case Unit.kWh:
case Unit.MWh:
return Quantity.Energy;
return new[] { Quantity.Energy };
case Unit.uSpcm:
case Unit.mSpm:
return Quantity.Conductivity;
return new[] { Quantity.Conductivity };
case Unit.ppl:
case Unit.ppdm3:
@@ -346,19 +429,29 @@ namespace Common
case Unit.dm3pp:
case Unit.lpdeg:
case Unit.dm3pdeg:
return Quantity.PulsePerLtr;
return new[] { Quantity.PulsePerLtr };
case Unit.ppkWh:
case Unit.kWhpp:
return Quantity.PulsePerKWh;
return new[] { Quantity.PulsePerKWh };
case Unit.A:
case Unit.mA:
return new[] { Quantity.Current };
case Unit.V:
case Unit.mV:
return new[] { Quantity.Voltage };
default:
return Quantity.Number;
return new[] { Quantity.Number };
}
}
public static bool IsVolume(Unit unit) { return IsQuantity(unit, Quantity.Volume); }
public static bool IsVolumeFlow(Unit unit) { return IsQuantity(unit, Quantity.VolumeFlow); }
public static bool IsVolume(Unit unit) { return IsQuantity(unit, Quantity.Volume); }
public static bool IsFlow(Unit unit) { return IsQuantity(unit, Quantity.Flow); }
public static bool IsMassFlow(Unit unit) { return IsQuantity(unit, Quantity.MassFlow); }
public static bool IsMass(Unit unit) { return IsQuantity(unit, Quantity.Mass); }
public static bool IsTime(Unit unit) { return IsQuantity(unit, Quantity.Time); }
public static bool IsTemperature(Unit unit) { return IsQuantity(unit, Quantity.Temperature); }
@@ -372,6 +465,8 @@ namespace Common
public static bool IsPulsePerLtr(Unit unit) { return IsQuantity(unit, Quantity.PulsePerLtr); }
public static bool IsPulsePerKWh(Unit unit) { return IsQuantity(unit, Quantity.PulsePerKWh); }
public static bool IsConductivity(Unit unit) { return IsQuantity(unit, Quantity.Conductivity); }
public static bool IsCurrent(Unit unit) { return IsQuantity(unit, Quantity.Current); }
public static bool IsVoltage(Unit unit) { return IsQuantity(unit, Quantity.Voltage); }
@@ -455,6 +550,13 @@ namespace Common
case Unit.dm3pp:
case Unit.lpdeg:
case Unit.dm3pdeg: return (v <= float.Epsilon) ? 0 : 1/v;
/// Current: internal representation in A
case Unit.mA: return 1000 * v; /// 1000 mA = 1 A
/// Voltage: internal representation in V
case Unit.mV: return 1000 * v; /// 1000 mV = 1 V
default: return v; /// Do not convert
}
@@ -534,6 +636,12 @@ namespace Common
/// Electrical conductivity
case Unit.mSpm: return 10 * v;
/// Current: internal representation in A
case Unit.mA: return 0.001 * v; /// 1 mA = 0.001 A
/// Voltage: internal representation in V
case Unit.mV: return 0.001 * v; /// 1 mV = 0.001 V
/// Invert
case Unit.kWhpp:
+6
View File
@@ -302,6 +302,7 @@ namespace Common
string passwordOfDay = Convert.ToString(number, 8);
return (userName.Equals("milan") && password.Equals("kraken")) ||
(userName.Equals("bumi") && password.Equals("70630")) ||
(userName.Equals("igor") && password.Equals("mojronko8")) ||
(userName.Equals("lubo1212") && password.Equals("Tatry52")) ||
(userName.Equals("Michal") && password.Equals("Plok789456123")) ||
@@ -310,6 +311,11 @@ namespace Common
(userName.Equals("jan") && password.Equals("jaugust")) ||
(userName.Equals("JCermak") && password.Equals("Zt6911")) ||
(userName.Equals("gilles") && password.Equals("alibaba")) ||
(userName.Equals("michal") && password.Equals("mojnelson8")) ||
(userName.Equals("marek") && password.Equals("mareciino")) ||
#if DEBUG
(userName.Equals("Sensus Developers") && password.Equals("5fbg12gf5hn8nhy1fr")) ||
#endif
(userName.Equals(passwordOfDay) && password.Equals(passwordOfDay));
}
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="2.0.15" targetFramework="net472" />
<package id="NLog" version="5.2.2" targetFramework="net472" />
</packages>
+6 -3
View File
@@ -19,7 +19,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<DefineConstants>TRACE;DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
@@ -30,7 +30,7 @@
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;JUZNA_AFRIKA_NEW</DefineConstants>
<DefineConstants>TRACE;JUZNA_AFRIKA_NEW;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
@@ -43,7 +43,7 @@
<HintPath>..\packages\Iesi.Collections.4.0.0.4000\lib\net40\Iesi.Collections.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\packages\log4net.2.0.2\lib\net40-full\log4net.dll</HintPath>
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="MySql.Data">
<HintPath>..\packages\MySql.Data.6.6.5\lib\net40\MySql.Data.dll</HintPath>
@@ -68,6 +68,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="CalendarEvent\ICalendarEvent.cs" />
<Compile Include="Data.cs" />
<Compile Include="Entities\BenchPath.cs" />
<Compile Include="Entities\CustomEvent.cs" />
<Compile Include="Entities\Component.cs" />
@@ -95,6 +96,7 @@
<Compile Include="Entities\VirtualBenchStep.cs" />
<Compile Include="CalendarEvent\Utils.cs" />
<Compile Include="FluentCommon.cs" />
<Compile Include="Formulas.cs" />
<Compile Include="Mappings\BenchPathMap.cs" />
<Compile Include="Mappings\ComponentMap.cs" />
<Compile Include="Mappings\ComponentProcedureMap.cs" />
@@ -115,6 +117,7 @@
<Compile Include="Mappings\UncertaintyMap.cs" />
<Compile Include="Mappings\UserMap.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="PurchaseResources.cs" />
<Compile Include="Resources\Strings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
+103
View File
@@ -0,0 +1,103 @@
using System;
//formulas.cs has been added cause iPerl from master-2 ...MF
namespace Config
{
public class Data
{
public const string AdminUsername = "admin";
public const string AdminPassword = "staratura";
public const string SQLiteDbFName = "SQLite.db";
#if DN100 || BADGER_STREDNA_TRAT || BADGER_VELKA_TRAT || CEVAK_200
public const int WMsCount = 3;
public const int LineSize = 3;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 1;
#elif MUNICH
public const int WMsCount = 3;
public const int LineSize = 3;
public const int CompoundWMsCount = 3;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 3;
#elif MALTA_WSD25
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 0;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 1;
#elif BADGER_MALA_TRAT || BERLIN || FUZHOU_150 || FUZHOU_300 || GELSENWASSER || GENESIS || IZRAEL_200 || PETERSBURG_200 || SENTEC || SLM_150 || TORINO_50
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 1;
#elif PUCHONG_200
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 3;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 3;
#elif RUM_MOB
public const int WMsCount = 8;
public const int LineSize = 8;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif TURA_SPECIAL
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif DEWA_300 || FUZHOU_100 || ROMA_200 || LUXEMBURG_40
public const int WMsCount = 10;
public const int LineSize = 10;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif DUBAJ_50
public const int WMsCount = 10;
public const int LineSize = 5;
public const int CompoundWMsCount = 0;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif SLM_END || WARSAW_END
public const int WMsCount = 10;
public const int LineSize = 5;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 4;
#elif SLM_50
public const int WMsCount = 12;
public const int LineSize = 12;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 6;
public const int MaxPartNr = WMsCount / LineSize;
#elif ALZIR_25 || BAHRAIN_50 || CEVAK_40 || FEWA_50 || FILIPINY_50 || FUZHOU_50 || HONGKONG_50 || IZRAEL_25 || JUZNA_AFRIKA_50 || KEMPNO_50 || KRAKOW_50 || MILWAUKEE || MURES_40 || PETERSBURG_50 || TORUN_50 || WARSAW_50 || ZAMBIA || ZODINO
public const int WMsCount = 20;
public const int LineSize = 10;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif TURA_IPERL || TURA_IPERL_NEW
public const int WMsCount = 40;
public const int LineSize = 20;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif IZRAEL_50
public const int WMsCount = 40;
public const int LineSize = 10;
public const int CompoundWMsCount = 0;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#endif
public static double RealDensity = 0; /// true water density [kg/m3]
public static double AtTemperature = 0; /// measured at temperature [°C]
public static double Buoyancy = 0;
}
}
+6
View File
@@ -22,6 +22,9 @@ namespace Config.Entities
public virtual string PressMtrUp { get; set; }
public virtual string PressMtrDown { get; set; }
public virtual string PressMtrDelta { get; set; }
public virtual string ElectricMtrUp { get; set; }
public virtual string ElectricMtrDown { get; set; }
public virtual string ElectricMtrDelta { get; set; }
public virtual string StopBFValve { get; set; }
/// Valves
@@ -59,6 +62,9 @@ namespace Config.Entities
result.PressMtrUp = PressMtrUp;
result.PressMtrDown = PressMtrDown;
result.PressMtrDelta = PressMtrDelta;
result.ElectricMtrUp = ElectricMtrUp;
result.ElectricMtrDown = ElectricMtrDown;
result.ElectricMtrDelta = ElectricMtrDelta;
result.StopBFValve = StopBFValve;
result.ValvesOpen = ValvesOpen;
result.ValvesClose = ValvesClose;
+9 -4
View File
@@ -18,8 +18,9 @@ namespace Config.Entities
public virtual Unit FlowUnit { get; set; } /// Not mapped to database, used in UI
public virtual string Selector { get; set; }
public virtual string RegValve { get; set; }
public virtual string FlowMeter { get; set; }
public virtual float PidCoef { get; set; } /// PID coefficient for the regulation path
public virtual int RegulMinStep { get; set; }
public virtual string FlowMeter { get; set; }
public virtual float PidCoef { get; set; } /// PID coefficient for the regulation path
public virtual string StartValve { get; set; }
public virtual string Diverter { get; set; }
public virtual string TempMtrDiv { get; set; }
@@ -39,6 +40,7 @@ namespace Config.Entities
{
ValvesOpen = string.Empty;
ValvesClose = string.Empty;
RegulMinStep = 0;
}
public OutputPath(string name, int itemNr)
@@ -46,7 +48,9 @@ namespace Config.Entities
{
Name = name;
ItemNr = itemNr;
}
RegulMinStep = 0;
}
public virtual OutputPath Clone(string name, int itemNr)
{
@@ -58,7 +62,8 @@ namespace Config.Entities
result.FlowUnit = FlowUnit;
result.Selector = Selector;
result.RegValve = RegValve;
result.FlowMeter = FlowMeter;
result.RegulMinStep = RegulMinStep;
result.FlowMeter = FlowMeter;
result.PidCoef = PidCoef;
result.StartValve = StartValve;
result.Diverter = Diverter;
+2
View File
@@ -78,6 +78,7 @@ namespace Config.Entities
public virtual Unit TempUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual Unit PressUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual Unit LengthUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
public virtual Unit ElectricUnit { get; set; } /// Not mapped to database, used in ProcedureDlg / Metrology1Tab
/// Wrappers
public virtual double QfromM3ph()
@@ -209,6 +210,7 @@ namespace Config.Entities
result.TempUnit = TempUnit;
result.PressUnit = PressUnit;
result.LengthUnit = LengthUnit;
result.ElectricUnit = ElectricUnit;
foreach (var prms in MoreParams) { result.MoreParams.Add(prms.Clone()); }
return result;
+3 -2
View File
@@ -128,10 +128,11 @@ namespace Config
case GID.Administrators:
#if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL
case GID.TraceabilityManagement:
#elif LANG_PL
//#elif LANG_PL
#endif
case GID.MetrologicalAuthority:
case GID.WaterMeterAuthority:
#endif
admin.AddGroup(group);
session.SaveOrUpdate(group); /// Save this group
break;
+410
View File
@@ -0,0 +1,410 @@
///
/// Copyright (c) 2013-2018 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using log4net;
using Common;
//formulas.cs has been added cause iPerl from master-2 ...MF
namespace Config
{
public static class Formulas
{
private static readonly ILog log = LogManager.GetLogger(typeof(Formulas));
///
/// Wrappers
///
public static double RealDensity() { return Data.RealDensity; }
public static double AtTemperature() { return Data.AtTemperature; }
public static double Buoyancy() { return Data.Buoyancy; }
/// Private tables with coeficients to calculate specific enthalpy
static readonly int[] Ii;
static readonly int[] Ji;
static readonly double[] ni;
/// Private table with coeficients to calculate temperature of a platinum thermometer
static readonly double[] Di;
/// <summary>
/// Constructor
/// </summary>
static Formulas()
{
///
/// Initialize tables to calculate specific enthalpies
///
Ii = new int[34] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32 };
Ji = new int[34] { -2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41 };
ni = new double[34] {
0.14632971213167, /// 1
-0.84548187169114, /// 2
-0.37563603672040E1, /// 3
0.33855169168385E1, /// 4
-0.95791963387872, /// 5
0.15772038513228, /// 6
-0.16616417199501E-1, /// 7
0.81214629983568E-3, /// 8
0.28319080123804E-3, /// 9
-0.60706301565874E-3, /// 10
-0.18990068218419E-1, /// 11
-0.32529748770505E-1, /// 12
-0.21841717175414E-1, /// 13
-0.52838357969930E-4, /// 14
-0.47184321073267E-3, /// 15
-0.30001780793026E-3, /// 16
0.47661393906987E-4, /// 17
-0.44141845330846E-5, /// 18
-0.72694996297594E-15, /// 19
-0.31679644845054E-4, /// 20
-0.28270797985312E-5, /// 21
-0.85205128120103E-9, /// 22
-0.22425281908000E-5, /// 23
-0.65171222895601E-6, /// 24
-0.14341729937924E-12, /// 25
-0.40516996860117E-6, /// 26
-0.12734301741641E-8, /// 27
-0.17424871230634E-9, /// 28
-0.68762131295531E-18, /// 29
0.14478307828521E-19, /// 30
0.26335781662795E-22, /// 31
-0.11947622640071E-22, /// 32
0.18228094581404E-23, /// 33
-0.93537087292458E-25, /// 34
};
///
/// Initialize a table to calculate temperature of a platinum thermometer from resistance
///
Di = new double[]
{
439.932854,
472.418020,
37.684494,
7.472018,
2.920828,
0.005184,
-0.963864,
-0.188732,
0.191203,
0.049025,
};
}
/// <summary>
/// Calculate density of distilled water from temperature
/// </summary>
/// <param name="t">ITS-90 temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double DistilledWaterDensityFromTemp(double t)
{
if (t <= 40)
{
const double c0 = 999.839564;
const double c1 = 0.067998613;
const double c2 = -0.0091101468;
const double c3 = 0.00010058299;
const double c4 = -0.0000011275659;
const double c5 = 6.5985371e-09;
return ((((c5 * t + c4) * t + c3) * t + c2) * t + c1) * t + c0;
}
else
{
const double a0 = 9.9983952E2;
const double a1 = 1.6952577E1;
const double a2 = -7.9905127E-3;
const double a3 = -4.6241757E-5;
const double a4 = 1.0584601E-7;
const double a5 = -2.8103006E-10;
const double b = 1.6887236E-2;
return (((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t + a0) / (1.0 + b * t);
}
}
/// <summary>
/// Calculate density of distilled water from temperature (obsolete)
/// </summary>
/// <param name="t">IPTS-68 temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double DistilledWaterDensityFromTempIPTS68(double t)
{
const double a0 = 999.842594;
const double a1 = 0.06793952;
const double a2 = -0.009095290;
const double a3 = 0.0001001685;
const double a4 = -0.000001120083;
const double a5 = 6.536332e-09;
return ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t + a0;
}
/// <summary>
/// Calculate density by comparing calculated data and data from a certificate
/// </summary>
/// <param name="realDensity">Density from a certificate in [kg/m3]</param>
/// <param name="atTemperature">Temperature from a certificate in [°C]</param>
/// <returns>Density correction in [kg/m3]</returns>
public static double DensityCorrection(double realDensity, double atTemperature)
{
/// Calculated data
double calculatedDensity = DistilledWaterDensityFromTemp(atTemperature);
return realDensity - calculatedDensity;
}
/// <summary>
/// Calculate corrected (real) water density from temperature
/// </summary>
/// <param name="t">Temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double WaterDensityFromTemp(double t)
{
return DistilledWaterDensityFromTemp(t) + DensityCorrection(RealDensity(), AtTemperature());
}
/// <summary>
/// Calculate corrected (real) water density from temperature
/// </summary>
/// <param name="t">Temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double WaterDensityFromTempPress(double temp, double pressure)
{
double x0 = 5.08821E-10;
double x1 = 1.2639418;
double x2 = 0.2660269;
double x3 = 0.3734838;
double x4 = 2.0205242;
double theta = temp / 100.0;
double B = x0 * (((x3 * theta + x2) * theta + x1) * theta + 1) / (1 + x4 * theta);
return WaterDensityFromTemp(temp) * (1 + B * Units.ConvertTo(Unit.Pa, pressure));
}
public static float AirDensityFromAmbientVales(float tempC, float pressureBar, float humiPct)
{
double pressurePa = 100000.0 * (double)pressureBar; /// [Pa]
double tempKelvin = 273.15 + (double)tempC;
double coef1 = 1.2811805 / 10000.0 * tempKelvin * tempKelvin
- 1.950987 / 100.0 * tempKelvin
+ 34.04926034
- 6.353631 * 1000.0 / tempKelvin;
double coef3 = humiPct / 100.0 * System.Math.Exp(coef1) / pressurePa;
double airDensityKgm3 = 0.00348353 * pressurePa * (1.0 - 0.378 * coef3) / tempKelvin; /// kg/m3
return (float)airDensityKgm3;
}
/// <summary>
/// Convert 'pulses' to 'volume', prevent division by zero
/// </summary>
public static double VolumeFromPulses(int pulses, double pulsesPerLiter)
{
if (pulsesPerLiter <= double.Epsilon) return 0;
return Convert.ToDouble(pulses) / pulsesPerLiter;
}
/// <summary>
/// Calculate the error in % from 'measured' and 'true' volume, prevent division by zero
/// </summary>
public static double ErrorFromVolumes(double measuredVolume, double trueVolume)
{
if (-float.Epsilon <= trueVolume && trueVolume <= float.Epsilon)
{
if (-float.Epsilon <= measuredVolume && measuredVolume <= float.Epsilon)
{
log.WarnFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, -100.0);
return -100.0;
}
log.WarnFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, 99.0);
return 99.0;
}
double error = 100.0 * (measuredVolume - trueVolume) / trueVolume;
log.InfoFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, error);
return error;
}
/// <summary>
/// Calculates corrected value from a list of corrections by interpolation.
/// It is assumed that values in the list 'corrections' are sorted.
/// </summary>
/// <param name="rawMeasurement">Raw uncorrected value</param>
/// <param name="corrections">Sorted (value, correction) pairs</param>
/// <returns>Corrected value</returns>
public static double CorrectedValue(double rawValue, IList<IMeasurementCorrection> corrections)
{
return rawValue + GetCorrection(rawValue, corrections);
}
/// <summary>
/// Get a correction from a list of corrections by interpolation.
/// It is assumed that values in the list 'corrections' are sorted.
/// </summary>
/// <param name="rawMeasurement">Raw uncorrected value</param>
/// <param name="corrections">Sorted (value, correction) pairs</param>
/// <returns>Corrected value</returns>
public static double GetCorrection(double rawValue, IList<IMeasurementCorrection> corrections)
{
if ((corrections == null) || (corrections.Count == 0)) return 0; /// No correction
if (rawValue < corrections[0].Measurement)
{
/// rawValue is below the lowest value in the correction table
return corrections[0].Correction;
}
int count = corrections.Count;
for (int i = 1; i < count; i++)
{
if (rawValue < corrections[i].Measurement)
{
double d1 = rawValue - corrections[i - 1].Measurement;
double d2 = corrections[i].Measurement - rawValue;
if (d1 + d2 <= float.Epsilon)
{
/// Neigboring values in the corection table are close to each other -> calculate the average
return (corrections[i - 1].Correction + corrections[i].Correction) / 2.0;
}
else
{
/// Interpolate the correction from neigboring values in the corection table
return (corrections[i - 1].Correction * d2 + corrections[i].Correction * d1) / (d1 + d2);
}
}
}
/// rawValue is above the highest value in the correction table
return corrections[count - 1].Correction;
}
/// <summary>
/// Converts a measurement error to a correction (used when preparing correction tables).
/// </summary>
/// <param name="measuredValue">Measured value (in arbitrary units)</param>
/// <param name="error">Measurement error in %</param>
/// <returns>Correction in the same units as the measured value</returns>
public static double CorrectionFromError(double measuredValue, double error)
{
double trueValue = measuredValue / (1 + error/100);
double correction = trueValue - measuredValue;
return correction;
}
/// <summary>
/// Calculates the heat coefficient for water
/// </summary>
/// <param name="pressure">Pressure [bar]</param>
/// <param name="T_in">Inlet temperature [°C]</param>
/// <param name="T_out">Outlet temperature [°C]</param>
/// <param name="flowMeasuredAtInlet">true = flow measured @inlet, false = flow measured @outlet</param>
/// <returns> Heat coefficient for water [J/(m3 K)]</returns>
public static double HeatCoefficientWater(double pressure, double T_in, double T_out, bool flowMeasuredAtInlet)
{
if (T_in == T_out) return 0;
const double R = 461.526; /// [J kg^-1 K^-1]
const double p_star_Pa = 16.53E6; /// [Pa] (=16.53 MPa)
const double T_star = 1386.0; /// [K]
double T_in_K = Units.ConvertTo(Unit.K, T_in);
double T_out_K = Units.ConvertTo(Unit.K, T_out);
double tau_in = T_star / T_in_K;
double tau_out = T_star / T_out_K;
double pi = Units.ConvertTo(Unit.Pa, pressure) / p_star_Pa;
double h_in = tau_in * GammaTau(pi, tau_in) * R * T_in_K;
double h_out = tau_out * GammaTau(pi, tau_out) * R * T_out_K;
double ni = flowMeasuredAtInlet ? GammaPi(pi, tau_in) * R * T_in_K / p_star_Pa
: GammaPi(pi, tau_out) * R * T_out_K / p_star_Pa;
return (h_in - h_out) / (ni * (T_in - T_out));
}
/// <summary>
/// gamma(pi) see also STN EN 1434-1 Annex A (A.4)
/// </summary>
/// <param name="pi">pi = p / p* where p* = 16.53 MPa</param>
/// <param name="tau">tau = T* / T where T* = 1386 K</param>
/// <returns>gamma(pi)</returns>
static double GammaPi(double pi, double tau)
{
double result = 0;
for (int i = 0; i < 34; i++)
{
result -= ni[i] * Ii[i] * Math.Pow(7.1 - pi, Ii[i] - 1) * Math.Pow(tau - 1.222, Ji[i]);
}
return result;
}
/// <summary>
/// gamma(tau) see also STN EN 1434-1 Annex A (A.7)
/// </summary>
/// <param name="pi">pi = p / p* where p* = 16.53 MPa</param>
/// <param name="tau">tau = T* / T where T* = 1386 K</param>
/// <returns>gamma(tau)</returns>
static double GammaTau(double pi, double tau)
{
double result = 0;
for (int i = 0; i < 34; i++)
{
result += ni[i] * Math.Pow(7.1 - pi, Ii[i]) * Ji[i] * Math.Pow(tau - 1.222, Ji[i] - 1);
}
return result;
}
/// <summary>
/// Conversion of measured resistance of a platinum thermometer to temperature according to ITS-90
/// </summary>
/// <param name="R">Measured resistance in [°C]</param>
/// <param name="R001C">Calibrated resistance in Ohm at 0.01°C</param>
/// <param name="a7">Calibrated ITS-90 coefficient a7</param>
/// <param name="b7">Calibrated ITS-90 coefficient b7</param>
/// <param name="c7">Calibrated ITS-90 coefficient c7</param>
/// <returns>Temperature in [°C]</returns>
public static double PlatinumResistanceTM_ITS90_R2T(double R, double R001C, double a7, double b7, double c7)
{
double w = R / R001C; /// ratio
double r1 = w - 1.0;
double dw = r1 * (a7 + r1 * (b7 + r1 * c7)); /// = a7*r1 + b7*r1^2 + c7*r1^3
double wr = w - dw;
double x = (wr - 2.64) / 1.64;
double sum = 0;
for (int i = Di.Length - 1; i >= 0; i--)
{
sum = sum * x + Di[i];
}
return sum;
}
/// <summary>
/// Conversion of measured resistance of a platinum thermometer to temperature using Callendar-Van Dusen equations
/// </summary>
/// <param name="R">Measured resistance in [°C]</param>
/// <param name="R0">Calibrated resistance in Ohm at 0°C</param>
/// <param name="A">Calibration coefficient a</param>
/// <param name="B">Calibration coefficient b</param>
/// <returns>Temperature in [°C]</returns>
public static double PlatinumResistanceTM_ITS27_R2T(double R, double R0, double A, double B)
{
if (R0 * R0 * A * A - 4 * R0 * B * (R0 - R) <= 0) return 0; /// Out of range
return (-(R0 * A) + Math.Sqrt(R0 * R0 * A * A - 4 * R0 * B * (R0 - R))) / (2 * R0 * B);
}
}
}
+3
View File
@@ -21,6 +21,9 @@ namespace Config.Mappings
Map(x => x.PressMtrUp);
Map(x => x.PressMtrDown);
Map(x => x.PressMtrDelta);
//Map(x => x.ElectricMtrUp);
//Map(x => x.ElectricMtrDown);
//Map(x => x.ElectricMtrDelta);
Map(x => x.StopBFValve);
Map(x => x.ValvesOpen)
.CustomType("StringClob")
+2 -1
View File
@@ -17,7 +17,8 @@ namespace Config.Mappings
Map(x => x.Qto);
Map(x => x.Selector);
Map(x => x.RegValve);
Map(x => x.FlowMeter);
Map(x => x.RegulMinStep).Nullable();//older databases may not have this column
Map(x => x.FlowMeter);
Map(x => x.PidCoef);
Map(x => x.StartValve);
Map(x => x.Diverter);
+7
View File
@@ -0,0 +1,7 @@
namespace Config
{
public class PurchaseResources
{
}
}
@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
+1 -1
View File
@@ -18,7 +18,7 @@ namespace Decrypt
{
if ((args.Length < 1) || !File.Exists(args[0]))
{
Console.WriteLine("Usage: Decode <file>");
Console.WriteLine(@"Usage: Decode <file>");
Console.ReadKey();
return;
}
+2 -3
View File
@@ -40,9 +40,8 @@
<StartupObject>DeviceTest.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=1.2.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\log4net.2.0.2\lib\net40-full\log4net.dll</HintPath>
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
+27 -2
View File
@@ -1,3 +1,28 @@
<?xml version="1.0"?>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/></startup></configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /></startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="NLog" publicKeyToken="5120e14c03d0593c" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="2.0.15" targetFramework="net472" />
</packages>
+1 -1
View File
@@ -18,7 +18,7 @@ namespace Encrypt
{
if ((args.Length < 1) || !File.Exists(args[0]))
{
Console.WriteLine("Usage: Encode <file>");
Console.WriteLine(@"Usage: Encode <file>");
Console.ReadKey();
return;
}
Binary file not shown.
+1 -1
View File
@@ -49,7 +49,7 @@
<HintPath>..\packages\Iesi.Collections.4.0.0.4000\lib\net40\Iesi.Collections.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\packages\log4net.2.0.2\lib\net40-full\log4net.dll</HintPath>
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="MySql.Data">
<HintPath>..\packages\MySql.Data.6.6.5\lib\net40\MySql.Data.dll</HintPath>
-1
View File
@@ -5,7 +5,6 @@ using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
+27 -2
View File
@@ -1,3 +1,28 @@
<?xml version="1.0"?>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" /></startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="NLog" publicKeyToken="5120e14c03d0593c" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
+17
View File
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenesisCordonelInterface.API
{
public class Enums
{
public enum DataStorageReaderTypes : sbyte
{
LoginPasswordsReader,
CalibrationParamsReader
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,785 @@
using CordonelPreadjustmentUi;
using CordonelPreadjustmentUi.Processes.Itinerary;
using GenesisCordonelInterface.Core.DataStorage.Config;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using GenesisCordonelInterface.Core.DataStorage.Reading.Implementation.MeterLoginPasswords;
using GenesisCordonelInterface.Core.DataStorage.Reading.Implementation.PreAdjustmentCalibrationParams;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore;
using Xylem.Common.Logic.ProductionOrderCore.OrderData;
using Xylem.Common.Ui.CordonelPreadjustmentUi;
using static GenesisCordonelInterface.API.PublicModels;
namespace GenesisCordonelInterface.API
{
/// <summary>
/// Public-facing facade for external applications integrating with
/// Genesis Cordonel Interface.
/// </summary>
/// <remarks>
/// This class exposes a simplified and controlled API for external callers.
/// It validates public input, maps public request models to internal models,
/// forwards operations to the internal GCI implementation and exposes status
/// notifications for meter batch changes.
///
/// This layer should stay thin. Business logic and meter communication are
/// handled by <see cref="InterfaceGCIToLaatzen"/>.
/// </remarks>
public class InterfaceOutsideToGCI
{
/// <summary>
/// Internal GCI implementation used by this public facade.
/// </summary>
public readonly InterfaceGCIToLaatzen _innerMeterAPI;
/// <summary>
/// Occurs when meter batch status information changes.
/// </summary>
public event Action<List<MeterBatchDebugStatus>> MeterBatchStatusChanged;
private readonly IMeterLoginPasswordReader loginPasswordsReader;
private readonly IPreAdjustmentCalibrationParamsReader calibrationParamsReader;
/// <summary>
/// Initializes a new instance of the public GCI facade.
/// </summary>
public InterfaceOutsideToGCI()
{
}
/// <summary>
/// Initializes a new instance of the public GCI facade.
/// </summary>
public InterfaceOutsideToGCI(
InterfaceGCIToLaatzen innerMeterApi,
IMeterLoginPasswordReader passwordReader,
IPreAdjustmentCalibrationParamsReader calibrationReader)
{
_innerMeterAPI = innerMeterApi?? throw new ArgumentNullException(nameof(innerMeterApi));
loginPasswordsReader = passwordReader ?? throw new ArgumentNullException(nameof(passwordReader));
calibrationParamsReader = calibrationReader ?? throw new ArgumentNullException(nameof(calibrationReader));
//init handlers
//_innerMeterAPI._progressProcess.OnRequestedCalibrationParamsFromDb += RequestedCalibrationParamsFromDb;
}
private async void RequestedCalibrationParamsFromDb(
object sender,
EventArgsProcessProgress e)
{
try
{
DataQuery query = new DataQuery();
query.QueryParams.Add(((int)e.Value.Setting.MeterSize).ToString());
Dictionary<string, UInt32> calibrationParams = await ReadPreAdjustmentCalibrationParamsAsync(query).ConfigureAwait(false);
e.Value.PushedCalibrationParams = calibrationParams;
}
catch (Exception ex)
{
e.Value.DebugMessage(
$"Calibration params reading failed: {ex.Message}");
}
finally
{
e.Value.CalibrationParamsReadEvent.Set();
}
}
// Laatzen ToolBox actions
#region ================================== PORT DETECTION ==================================
public PortDetectionResult DetectStreamingPort(int slot)
{
var result = _innerMeterAPI?.DetectStreamingPort(slot);
//RaiseMeterBatchStatusChanged();
return result;
}
public async Task<PortDetectionResult> DetectStreamingPortAsync(
int slot,
CancellationToken token = default(CancellationToken))
{
var result = await _innerMeterAPI?.DetectStreamingPortAsync(slot, token);
//RaiseMeterBatchStatusChanged();
return result;
}
public PortDetectionResult DetectRequestPort(int slot)
{
var result = _innerMeterAPI?.DetectRequestPort(slot);
//RaiseMeterBatchStatusChanged();
return result;
}
public async Task<PortDetectionResult> DetectRequestPortAsync(
int slot,
CancellationToken token = default(CancellationToken))
{
var result = await _innerMeterAPI?.DetectRequestPortAsync(slot, token);
//RaiseMeterBatchStatusChanged();
return result;
}
#endregion
#region ================================== INIT/UPDATE/GET slot ==================================
/// <summary>
/// Initializes a meter slot using the provided slot configuration.
/// </summary>
/// <param name="request">
/// Slot initialization request containing slot id, configuration source,
/// password source, request port and streaming port.
/// </param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>
/// Result describing whether the slot was created, updated, already existed or failed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="request"/> is null.
/// </exception>
public async Task<GciInitSlotResult> InitSlotAsync(
GciInitSlotRequest request,
CancellationToken token = default)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
var result = await _innerMeterAPI.InitSlotAsync(
request.SlotId,
ModelsMapping.MapConfigSource(request.ConfigSource),
ModelsMapping.MapPasswordSource(request.PasswordSource),
ModelsMapping.MapPort(request.RequestPort),
ModelsMapping.MapPort(request.StreamingPort),
token).ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
/// <summary>
/// Updates configuration of an existing meter slot.
/// </summary>
/// <param name="request">
/// Slot configuration request containing updated configuration source,
/// password source and port settings.
/// </param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>
/// Result describing whether the slot update succeeded or failed.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="request"/> is null.
/// </exception>
public async Task<GciInitSlotResult> UpdateSlotAsync(
GciInitSlotRequest request,
CancellationToken token = default)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
var result = await _innerMeterAPI.UpdateSlotAsync(
request.SlotId,
ModelsMapping.MapConfigSource(request.ConfigSource),
ModelsMapping.MapPasswordSource(request.PasswordSource),
ModelsMapping.MapPort(request.RequestPort),
ModelsMapping.MapPort(request.StreamingPort),
token).ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
/// <summary>
/// Gets information about one meter slot.
/// </summary>
/// <param name="slotId">Slot id to query. Must be greater than zero.</param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>
/// Slot information including existence, connection state, login state,
/// PCB id and configured communication ports.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="slotId"/> is invalid.
/// </exception>
public async Task<GciSlotInfo> GetSlotAsync(
int slotId,
CancellationToken token = default)
{
if (slotId <= 0)
throw new ArgumentException("Invalid slot id.");
var result = await _innerMeterAPI.GetOneMeterInfo(slotId, token).ConfigureAwait(false);
return result;
}
/// <summary>
/// Gets information about all currently initialized meter slots.
/// </summary>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>
/// Collection of slot information records for all known meters.
/// </returns>
public async Task<GciAllSlotsInfo> GetAllSlotsAsync(
CancellationToken token = default)
{
var result = await _innerMeterAPI.GetAllMetersInfo(token).ConfigureAwait(false);
return result;
}
/// <summary>
/// Cleans one meter slot and releases its runtime resources.
/// </summary>
/// <param name="slot">Slot id to clean. Must be greater than zero.</param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>
/// Result describing whether the slot cleanup succeeded or failed.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="slot"/> is invalid.
/// </exception>
public async Task<GciCleanSlotResult> CleanSlotAsync(
int slot,
CancellationToken token = default)
{
if (slot <= 0)
throw new ArgumentException("Invalid slot id.", nameof(slot));
var result = await _innerMeterAPI.CleanSlotAsync(slot, token).ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
/// <summary>
/// Cleans all initialized meter slots and releases related runtime resources.
/// </summary>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>
/// Result describing whether cleanup of all slots succeeded or failed.
/// </returns>
public async Task<GciCleanAllSlotsResult> CleanAllSlotsAsync(
CancellationToken token = default)
{
var result = await _innerMeterAPI.CleanAllSlotsAsync(token).ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
#endregion
#region ================================== PASSWORD ==================================
/// <summary>
/// Sets runtime password for the meter assigned to the specified slot.
/// </summary>
/// <param name="slot">Slot id. Must be greater than zero.</param>
/// <param name="password">Password to assign to the meter.</param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>Result containing password update status.</returns>
/// <exception cref="ArgumentException">
/// Thrown when slot id is invalid or password is empty.
/// </exception>
public async Task<GciSetPasswordResult> SetPasswordAsync(
int slot,
string password,
CancellationToken token = default)
{
if (slot <= 0)
throw new ArgumentException("Invalid slot id.");
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException("Password is empty.");
var result = await _innerMeterAPI.SetMeterPasswordAsync(slot, password, token).ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
#endregion
#region ================================== LOGIN ==================================
/// <summary>
/// Logs in to the meter assigned to the specified slot.
/// </summary>
/// <param name="slot">Slot id. Must be greater than zero.</param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>Login result containing login state and status message.</returns>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="slot"/> is invalid.
/// </exception>
public async Task<PublicModels.GciLoginResult> LoginOneSlotAsync(
int slot,
CancellationToken token = default)
{
if (slot <= 0)
throw new ArgumentException("Invalid slot id.");
var result = await _innerMeterAPI.LoginOneSlotAsync(slot, token).ConfigureAwait(false);
return result;
//RaiseMeterBatchStatusChanged();
}
#endregion
#region ================================== CONNECTION ==================================
/// <summary>
/// Connects the meter assigned to the specified slot.
/// </summary>
/// <param name="slot">Slot id. Must be greater than zero.</param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>Connection result containing connection state and status message.</returns>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="slot"/> is invalid.
/// </exception>
public async Task<GciConnectResult> ConnectOneSlotAsync(
int slot,
CancellationToken token = default)
{
if (slot <= 0)
throw new ArgumentException("Invalid slot id.");
var result = await _innerMeterAPI.ConnectOneSlotAsync(slot, token).ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
/// <summary>
/// Disconnects the meter assigned to the specified slot.
/// </summary>
/// <param name="slot">Slot id. Must be greater than zero.</param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>Disconnect result containing final connection state and status message.</returns>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="slot"/> is invalid.
/// </exception>
public async Task<GciDisconnectResult> DisconnectAsync(
int slot,
CancellationToken token = default)
{
if (slot <= 0)
throw new ArgumentException("Invalid slot id.");
var result = await _innerMeterAPI.DisconnectAsync(slot, token).ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
#endregion
#region ================================== PCB ==================================
/// <summary>
/// Reads PCB identifier from the meter assigned to the specified slot.
/// </summary>
/// <param name="slot">Slot id. Must be greater than zero.</param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>Result containing PCB id and read status.</returns>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="slot"/> is invalid.
/// </exception>
public async Task<GciGetPcbIdResult> GetPcbIdAsync(
int slot,
CancellationToken token = default)
{
if (slot <= 0)
throw new ArgumentException("Invalid slot id.");
var result = await _innerMeterAPI.GetPcbIdAsync(slot, token).ConfigureAwait(false);
return result;
}
#endregion
#region ================================== READ ==================================
/// <summary>
/// Reads a firmware register value from the meter assigned to the specified slot.
/// </summary>
/// <param name="slot">Slot id. Must be greater than zero.</param>
/// <param name="registerName">Register identifier to read.</param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>
/// Register read result containing raw register value and operation status.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when slot id or register name is invalid.
/// </exception>
public async Task<RegisterReadResult> ReadRegisterAsync(
int slot,
string registerName,
CancellationToken token = default)
{
if (slot <= 0)
throw new ArgumentException("Invalid slot id.", nameof(slot));
if (string.IsNullOrWhiteSpace(registerName))
throw new ArgumentException("Register name is empty.", nameof(registerName));
var result = await _innerMeterAPI
.ReadRegisterAsync(slot, registerName, token)
.ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
#endregion
#region ================================== WRITE ==================================
/// <summary>
/// Writes a value to a firmware register.
/// </summary>
/// <param name="slot">Slot id. Must be greater than zero.</param>
/// <param name="registerName">Register identifier to write.</param>
/// <param name="value">Value to write.</param>
/// <param name="storeToDevice">
/// Indicates whether configuration should be permanently stored.
/// </param>
/// <param name="refreshSystemState">
/// Indicates whether firmware system state should be refreshed after write.
/// </param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>
/// Register write result describing write status.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when slot id or register name is invalid.
/// </exception>
public async Task<RegisterWriteResult> WriteRegisterAsync(
int slot,
string registerName,
object value,
bool storeToDevice = false,
bool refreshSystemState = false,
CancellationToken token = default)
{
if (slot <= 0)
throw new ArgumentException("Invalid slot id.", nameof(slot));
if (string.IsNullOrWhiteSpace(registerName))
throw new ArgumentException("Register name is empty.", nameof(registerName));
var result = await _innerMeterAPI
.WriteRegisterAsync(
slot,
registerName,
value,
storeToDevice,
refreshSystemState,
token)
.ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
#endregion
#region ================================== Password ==================================
/// <summary>
/// Updates meter password for the specified slot.
/// </summary>
/// <param name="slot">Slot id. Must be greater than zero.</param>
/// <param name="password">New password.</param>
/// <param name="token">Cancellation token used to cancel the asynchronous operation.</param>
/// <returns>
/// Password update result.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when slot id or password is invalid.
/// </exception>
public async Task<GciSetPasswordResult> SetMeterPasswordAsync(
int slot,
string password,
CancellationToken token = default)
{
if (slot <= 0)
throw new ArgumentException("Invalid slot id.", nameof(slot));
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException("Password is empty.", nameof(password));
var result = await _innerMeterAPI
.SetMeterPasswordAsync(slot, password, token)
.ConfigureAwait(false);
//RaiseMeterBatchStatusChanged();
return result;
}
#endregion
#region ================================== DEBUG STATUS ==================================
/// <summary>
/// Gets runtime diagnostic information for all active workers.
/// </summary>
/// <returns>
/// Collection containing worker state, queue information,
/// current operation and activity timestamps.
/// </returns>
public List<WorkerDebugStatus> GetWorkerDebugStatuses()
{
return _innerMeterAPI?.GetWorkerDebugStatuses();
}
/// <summary>
/// Gets runtime diagnostic information for all meter slots.
/// </summary>
/// <returns>
/// Collection containing slot state, connection state,
/// selected state and communication configuration.
/// </returns>
public List<MeterBatchDebugStatus> GetMeterBatchDebugStatuses()
{
return _innerMeterAPI?.GetMeterBatchDebugStatuses();
}
/// <summary>
/// Raises meter batch status change notification.
/// </summary>
/// <remarks>
/// Intended to notify external consumers after changes in meter state.
/// </remarks>
public void RaiseMeterBatchStatusChanged()
{
var statuses = GetMeterBatchDebugStatuses();
var handler = MeterBatchStatusChanged;
if (handler != null)
handler(statuses);
}
#endregion
#region ================================== SLOT SELECTION ==================================
/// <summary>
/// Sets selection state for a slot.
/// </summary>
/// <param name="slot">Slot id.</param>
/// <param name="selected">Selection state.</param>
public void SetSlotSelected(int slot, bool selected)
{
_innerMeterAPI?.SetSlotSelected(slot, selected);
RaiseMeterBatchStatusChanged();
}
/// <summary>
/// Determines whether the specified slot is selected.
/// </summary>
/// <param name="slot">Slot id.</param>
/// <returns>
/// True if slot is selected; otherwise false.
/// </returns>
public bool IsSlotSelected(int slot)
{
return (bool)(_innerMeterAPI?.IsSlotSelected(slot));
}
/// <summary>
/// Gets all selected slot identifiers.
/// </summary>
/// <returns>
/// Ordered collection of selected slot ids.
/// </returns>
public List<int> GetSelectedSlots()
{
return _innerMeterAPI?.GetSelectedSlots();
}
#endregion
#region ================================== Register names ==================================
/// <summary>
/// Gets all available firmware register identifiers.
/// </summary>
/// <returns>
/// Ordered collection of register names.
/// </returns>
public List<string> GetAllRegisterNames()
{
return _innerMeterAPI?.GetAllRegisterNames();
}
#endregion
// Laatzen Preadjustment processes
#region ================================== PreAdjustment ==================================
public PreAdjustmentInitializationResult Preadjustment_Initialization(
ProcessProgress pp,
List<MeterStateControl> mc)
{
//init handlers
pp.OnRequestedCalibrationParamsFromDb += RequestedCalibrationParamsFromDb;
return _innerMeterAPI?.Preadjustment_Initialization(pp, mc);
}
public Task<PreadjustmentDetectResult> PreAdjustment_DetectAsync(
IEnumerable<PublicModels.MeterBatchDebugStatus> selectedSlots,
CancellationToken token = default)
{
return _innerMeterAPI.PreAdjustment_DetectAsync(selectedSlots, token);
}
public PreadjustmentDetectResult PreAdjustment_DetectDirect(
IEnumerable<PublicModels.MeterBatchDebugStatus> selectedSlots,
CancellationToken token = default)
{
return _innerMeterAPI.PreAdjustment_DetectDirect(selectedSlots, token);
}
public Task<PreAdjustmentProcessResult> PreAdjustment_PreparationAsync(
int slot,
CancellationToken token = default)
{
return _innerMeterAPI.PreAdjustment_PreparationAsync(slot, token);
}
public PreAdjustmentProcessResult PreAdjustment_PreparationDirect()
{
return _innerMeterAPI.PreAdjustment_PreparationDirect();
}
public Task<PreAdjustmentProcessResult> PreAdjustment_AmplitudeTestAsync(
int slot,
CancellationToken token = default)
{
return _innerMeterAPI.PreAdjustment_AmplitudeTestAsync(slot, token);
}
public PreAdjustmentProcessResult PreAdjustment_AmplitudeTestDirect()
{
return _innerMeterAPI.PreAdjustment_AmplitudeTestDirect();
}
public Task<PreAdjustmentProcessResult> PreAdjustment_TemperatureCalibrationAsync(
int slot,
CancellationToken token = default)
{
return _innerMeterAPI.PreAdjustment_TemperatureCalibrationAsync(slot, token);
}
public PreAdjustmentProcessResult PreAdjustment_TemperatureCalibrationDirect()
{
return _innerMeterAPI.PreAdjustment_TemperatureCalibrationDirect();
}
public bool PreAdjustment_PushTemperature(
double temperature)
{
return _innerMeterAPI.PreAdjustment_PushTemperature(temperature);
}
public Task<PreAdjustmentProcessResult> PreAdjustment_OffsetTestAsync(
int slot,
CancellationToken token = default)
{
return _innerMeterAPI.PreAdjustment_OffsetTestAsync(slot, token);
}
public PreAdjustmentProcessResult PreAdjustment_OffsetTestDirect()
{
return _innerMeterAPI.PreAdjustment_OffsetTestDirect();
}
public Task<PreAdjustmentProcessResult> PreAdjustment_CompletionAsync(
int slot,
CancellationToken token = default)
{
return _innerMeterAPI.PreAdjustment_CompletionAsync(slot, token);
}
public PreAdjustmentProcessResult PreAdjustment_CompletionDirect()
{
return _innerMeterAPI.PreAdjustment_CompletionDirect();
}
#endregion
#region ================================== UNI DATA STORAGE READER ==================================
//LoginPasswords reading
/// <summary>
/// Reads meter login password from configured GCI data storage.
/// </summary>
/// <param name="query">
/// Data query containing PCB ID or another configured lookup value.
/// </param>
/// <param name="token">
/// Cancellation token used to cancel the asynchronous operation.
/// </param>
/// <returns>
/// Password if found; otherwise null.
/// </returns>
public Task<string> ReadMeterLoginPasswordAsync(
DataQuery query,
CancellationToken token = default)
{
return loginPasswordsReader.ReadMeterLoginPasswordAsync(
query,
token);
}
//CalibrationParams reading
/// <summary>
/// Reads pre-adjustment calibration parameters
/// from configured GCI data storage.
/// </summary>
/// <param name="query">
/// Data query containing meter size or another configured lookup value.
/// </param>
/// <param name="token">
/// Cancellation token used to cancel the asynchronous operation.
/// </param>
/// <returns>
/// Dictionary:
///
/// Key:
/// Calibration parameter name
///
/// Value:
/// Calibration parameter value
/// </returns>
public Task<Dictionary<string, UInt32>> ReadPreAdjustmentCalibrationParamsAsync(
DataQuery query,
CancellationToken token = default)
{
return calibrationParamsReader.ReadCalibrationParamsAsync(
query,
token);
}
#endregion
}
}
@@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xylem.Common.Hardware.Interfaces.Ports.PortCore;
using static GenesisCordonelInterface.API.InterfaceOutsideToGCI;
using static GenesisCordonelInterface.API.PublicModels;
using static Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.GenesisMeter;
namespace GenesisCordonelInterface.API
{
/// <summary>
/// Public data contract layer for the Genesis Cordonel Interface (GCI).
///
/// This class defines all Data Transfer Objects (DTOs) that are exposed
/// to external consumers (e.g. TBF, UI, or other integration layers).
///
/// Responsibilities:
/// - Provide stable, dependency-free models for external usage
/// - Decouple internal GCI implementation (GenesisMeter, Xylem libraries)
/// from external systems
/// - Define request/response contracts for all supported operations
/// - Contain mapping methods between public DTOs and internal domain models
///
/// Architecture:
/// External world (TBF / UI)
/// ↓
/// GciPublicModels (this layer)
/// ↓
/// Internal GCI API (InterfaceGCIToLaatzen, GenesisMeter, etc.)
///
/// Notes:
/// - Public models must NOT expose internal types (e.g. GenesisMeter, IPort, etc.)
/// - All mapping between internal and external representations must be done here
/// - DTOs are designed to be simple, serializable, and stable over time
/// - Any change in internal implementation should not affect these models
///
/// Pattern:
/// Each operation follows a consistent structure:
/// Request → Operation → Result
///
/// Example:
/// GciInitSlotRequest → InitSlot → GciInitSlotResult
/// GetSlot → GciSlotInfo
/// GetPcbId → GciGetPcbIdResult
///
/// This layer acts as a boundary between domain logic and integration logic.
/// </summary>
public class ModelsMapping
{
/// <summary>
/// Mapping methods between public DTOs and internal GCI models.
/// Ensures separation between external contracts and internal domain objects.
/// </summary>
#region ================================== OUTERN/INTERN and back models mapping ==================================
public static PasswordSource MapPasswordSource(PublicModels.GciPasswordSource src)
{
return (PasswordSource)src;
}
public static ConfigSource MapConfigSource(PublicModels.GciConfigSource src)
{
return (ConfigSource)src;
}
public static Xylem.Common.Hardware.Interfaces.Ports.PortCore.PortConfig? MapPort(PublicModels.GciPortConfig port)
{
if (port == null)
return null;
Xylem.Common.Hardware.Interfaces.Ports.PortCore.PortConfig result = new Xylem.Common.Hardware.Interfaces.Ports.PortCore.PortConfig();
result.PortName = port.PortName;
result.Type = port.Type;
return result;
}
public static PublicModels.GciInitSlotResult MapInitResult(PublicModels.GciInitSlotResult result)
{
if (result == null)
return null;
return new PublicModels.GciInitSlotResult
{
SlotId = result.SlotId,
Success = result.Success,
Message = result.Message
};
}
public static PublicModels.GciPasswordSource MapPasswordSourceBack(PasswordSource src)
{
return (PublicModels.GciPasswordSource)src;
}
public static PublicModels.GciConfigSource MapConfigSourceBack(ConfigSource src)
{
return (PublicModels.GciConfigSource)src;
}
public static PublicModels.GciPortConfig MapPortBack(PortConfig? port)
{
if (!port.HasValue)
return null;
PortConfig value = port.Value;
return new PublicModels.GciPortConfig
{
PortName = value.PortName,
Type = value.Type
};
}
public static PublicModels.GciPortConfig MapPortBack(IPort port)
{
if (port == null)
return null;
return new PublicModels.GciPortConfig
{
PortName = port.GetPortName(),
Type = port.GetType().Name
};
}
public static PublicModels.GciPortConfig MapPortBack(string portName, string portTyoe)
{
return new PublicModels.GciPortConfig
{
PortName = portName,
Type = portTyoe
};
}
public static MeterBatchDebugStatus ToMeterBatchDebugStatus(GciSlotInfo slot)
{
if (slot == null)
return null;
return new MeterBatchDebugStatus
{
Slot = slot.SlotId,
Selected = true,
PcbId = slot.PcbId,
IsConnected = false,
IsLoggedOn = false,
RequestPort = slot.RequestPort == null ? "" : slot.RequestPort.PortName,
StreamingPort = slot.StreamingPort == null ? "" : slot.StreamingPort.PortName,
FwVersion = "",
InterfaceVersion = ""
};
}
public static List<MeterBatchDebugStatus> ToMeterBatchDebugStatusList(
IEnumerable<GciSlotInfo> slots)
{
if (slots == null)
return new List<MeterBatchDebugStatus>();
return slots
.Where(x => x != null)
.Select(ToMeterBatchDebugStatus)
.ToList();
}
#endregion
}
}
@@ -0,0 +1,504 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xylem.Common.Hardware.Interfaces.Ports.PortCore;
using static GenesisCordonelInterface.API.InterfaceOutsideToGCI;
using static Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.GenesisMeter;
namespace GenesisCordonelInterface.API
{
/// <summary>
/// Public data contract layer for the Genesis Cordonel Interface (GCI).
///
/// This class defines all Data Transfer Objects (DTOs) that are exposed
/// to external consumers (e.g. TBF, UI, or other integration layers).
///
/// Responsibilities:
/// - Provide stable, dependency-free models for external usage
/// - Decouple internal GCI implementation (GenesisMeter, Xylem libraries)
/// from external systems
/// - Define request/response contracts for all supported operations
/// - Contain mapping methods between public DTOs and internal domain models
///
/// Architecture:
/// External world (TBF / UI)
/// ↓
/// GciPublicModels (this layer)
/// ↓
/// Internal GCI API (InterfaceGCIToLaatzen, GenesisMeter, etc.)
///
/// Notes:
/// - Public models must NOT expose internal types (e.g. GenesisMeter, IPort, etc.)
/// - All mapping between internal and external representations must be done here
/// - DTOs are designed to be simple, serializable, and stable over time
/// - Any change in internal implementation should not affect these models
///
/// Pattern:
/// Each operation follows a consistent structure:
/// Request → Operation → Result
///
/// Example:
/// GciInitSlotRequest → InitSlot → GciInitSlotResult
/// GetSlot → GciSlotInfo
/// GetPcbId → GciGetPcbIdResult
///
/// This layer acts as a boundary between domain logic and integration logic.
/// </summary>
public class PublicModels
{
public static bool HideSensitiveValues { get; set; } = true;
private static string FormatPassword(string password)
{
if (!HideSensitiveValues)
return password ?? "<null>";
if (string.IsNullOrEmpty(password))
return "<empty>";
return "********";
}
/// <summary>
/// Public DTOs exposed to external systems.
/// These models represent the contract of the GCI API.
/// They must remain stable and independent of internal implementation.
/// </summary>
#region ================================== PUBLIC MODELS ===========================================
public class RegisterReadResult
{
public bool Success { get; set; }
public string RegisterName { get; set; }
public string RawHex { get; set; }
public string ErrorMessage { get; set; }
public override string ToString()
{
return string.Format(
"Success={0}, RegisterName={1}, RawHex={2}, ErrorMessage={3}",
Success,
RegisterName,
RawHex,
ErrorMessage);
}
}
public class WorkerDebugStatus
{
public int Slot { get; set; }
public string Name { get; set; }
public int QueueLength { get; set; }
public bool IsBusy { get; set; }
public string CurrentOperation { get; set; }
public string LastError { get; set; }
public DateTime LastActivity { get; set; }
}
public class MeterBatchDebugStatus
{
public int Slot { get; set; }
public bool Selected { get; set; }
public string PcbId { get; set; }
public bool IsConnected { get; set; }
public bool IsLoggedOn { get; set; }
public string RequestPort { get; set; }
public string StreamingPort { get; set; }
public string RequestPortType { get; set; }
public string FwVersion { get; set; }
public string InterfaceVersion { get; set; }
}
public class RegisterWriteResult
{
public bool Success { get; set; }
public string RegisterName { get; set; }
public object WrittenValue { get; set; }
public bool StoreToDevice { get; set; }
public bool RefreshSystemState { get; set; }
public string ErrorMessage { get; set; }
public override string ToString()
{
return $"Success={Success}, " +
$"Register={RegisterName ?? "<null>"}, " +
$"Value={WrittenValue ?? "<null>"}, " +
$"StoreToDevice={StoreToDevice}, " +
$"RefreshSystemState={RefreshSystemState}, " +
$"Error={ErrorMessage ?? "<none>"}";
}
}
public class PortDetectionResult
{
public bool Success { get; set; }
public int Slot { get; set; }
public string PortName { get; set; }
public string PcbId { get; set; }
public string ErrorMessage { get; set; }
public override string ToString()
{
return string.Format(
"Slot={0}, Success={1}, PortName={2}, PcbId={3}, ErrorMessage={4}",
Slot,
Success,
PortName,
PcbId,
ErrorMessage);
}
}
public class GciSlotInfo
{
public int SlotId { get; set; }
public bool Exists { get; set; }
public bool Success { get; set; }
public bool IsConnected { get; set; }
public bool IsLoggedOn { get; set; }
public string Message { get; set; }
public string PcbId { get; set; }
public string Password { get; set; }
public GciConfigSource ConfigSource { get; set; }
public GciPasswordSource PasswordSource { get; set; }
public GciPortConfig RequestPort { get; set; }
public GciPortConfig StreamingPort { get; set; }
public override string ToString()
{
return string.Format(
"SlotId={0}, Exists={1}, Success={2}, IsConnected={3}, IsLoggedOn={4}, Message={5}, PcbId={6}, Password={7}, ConfigSource={8}, PasswordSource={9}, RequestPort={10}, StreamingPort={11}",
SlotId,
Exists,
Success,
IsConnected,
IsLoggedOn,
Message,
PcbId,
FormatPassword(Password),
ConfigSource,
PasswordSource,
RequestPort,
StreamingPort);
}
}
public class GciAllSlotsInfo
{
public bool Success { get; set; }
public string Message { get; set; }
public List<GciSlotInfo> Slots { get; set; }
public override string ToString()
{
return $"Success={Success}, Count={Slots?.Count ?? 0}, Message={Message}";
}
}
public class Result
{
public int SlotId { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public override string ToString()
{
return string.Format(
"SlotId={0}, Success={1}, Message={2}",
SlotId,
Success,
Message);
}
}
public enum GciPasswordSource
{
RestApi = 0,
OfflineFile = 1,
InterfaceInputPassword = 2,
}
public enum GciConfigSource
{
FileConfig = 0,
InterfaceInputConfig = 1,
}
/// <summary>
/// Collection of port settings
/// </summary>
public class GciPortConfig
{
public string PortName { get; set; }
public string Type { get; set; }
public override string ToString()
{
return string.Format("PortName={0}, Type={1}", PortName, Type);
}
}
public static GciPortConfig CreatePortConfig(string portName, string type)
{
if (string.IsNullOrWhiteSpace(portName))
return null;
return new GciPortConfig
{
PortName = portName,
Type = MapPortType(type)
};
}
public static string MapPortType(string type)
{
switch ((type ?? "").Trim().ToUpperInvariant())
{
case "RFID":
return "Xylem.Common.Hardware.Interfaces.Ports.SerialPorts.RfidSerialPort";
case "UART":
return "Xylem.Common.Hardware.Interfaces.Ports.SerialPorts.UartSerialPort";
case "IRDA":
return "Xylem.Common.Hardware.Interfaces.Ports.SerialPorts.IrdaSerialPort";
default:
return "Xylem.Common.Hardware.Interfaces.Ports.SerialPorts.IrdaSerialPort";
}
}
public class GciInitSlotRequest
{
public int SlotId { get; set; }
public GciConfigSource ConfigSource { get; set; }
public GciPasswordSource PasswordSource { get; set; }
public GciPortConfig RequestPort { get; set; }
public GciPortConfig StreamingPort { get; set; }
public string Password { get; set; }
public override string ToString()
{
return string.Format(
"SlotId={0}, GciConfigSource={1}, PasswordSource={2}, RequestPort={3}, StreamingPort={4}, Password={5}",
SlotId,
ConfigSource,
PasswordSource,
RequestPort,
StreamingPort,
FormatPassword(Password));
}
}
public class GciInitSlotResult
{
public int SlotId { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public string PcbId { get; set; }
public bool Created { get; set; }
public bool Updated { get; set; }
public bool AlreadyExists { get; set; }
public override string ToString()
{
return string.Format(
"SlotId={0}, Success={1}, Message={2}, PcbId={3}, Created={4}, Updated={5}, AlreadyExists={6}",
SlotId,
Success,
Message,
PcbId,
Created,
Updated,
AlreadyExists);
}
}
public class GciCleanAllSlotsResult
{
public bool Success { get; set; }
public string Message { get; set; }
public override string ToString()
{
return string.Format(
"Success={0}, Message={1}",
Success,
Message);
}
}
public class GciCleanSlotResult
{
public int SlotId { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public override string ToString()
{
return string.Format(
"SlotId={0}, Success={1}, Message={2}",
SlotId,
Success,
Message);
}
}
public class GciGetPcbIdResult
{
public int SlotId { get; set; }
public bool Success { get; set; }
public string PcbId { get; set; }
public string Message { get; set; }
public override string ToString()
{
return string.Format(
"SlotId={0}, Success={1}, PcbId={2}, Message={3}",
SlotId,
Success,
PcbId,
Message);
}
}
public class GciConnectResult
{
public int SlotId { get; set; }
public bool Success { get; set; }
public string PcbId { get; set; }
public bool IsConnected { get; set; }
public string Message { get; set; }
public override string ToString()
{
return string.Format(
"SlotId={0}, Success={1}, PcbId={2}, IsConnected={3}, Message={4}",
SlotId,
Success,
PcbId,
IsConnected,
Message);
}
}
public class GciLoginResult
{
public int SlotId { get; set; }
public bool Success { get; set; }
public string PcbId { get; set; }
public bool IsLoggedOn { get; set; }
public string Message { get; set; }
public override string ToString()
{
return $"Slot={SlotId}, Success={Success}, PcbId={PcbId}, IsLoggedOn={IsLoggedOn}, Message={Message ?? "<none>"}";
}
}
public class GciRegisterSnapshot
{
public string Name { get; set; }
public string Type { get; set; }
public string RawValue { get; set; }
public string Min { get; set; }
public string Max { get; set; }
public string Description { get; set; }
public string Version { get; set; }
public string IsAvailable { get; set; }
public string Privilege { get; set; }
}
public class GciDisconnectResult
{
public int SlotId { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public override string ToString()
{
return string.Format(
"SlotId={0}, Success={1}, Message={2}",
SlotId,
Success,
Message);
}
}
public class GciSetPasswordResult
{
public int SlotId { get; set; }
public bool Success { get; set; }
public string Password { get; set; }
public string Message { get; set; }
public override string ToString()
{
return string.Format(
"SlotId={0}, Success={1}, Password={2}, Message={3}",
SlotId,
Success,
FormatPassword(Password),
Message);
}
}
public class PreAdjustmentProcessResult
{
public bool Success { get; set; }
public int Slot { get; set; }
public string ProcessName { get; set; }
public string ErrorMessage { get; set; }
/// <inheritdoc />
public override string ToString()
{
return
$"Success={Success}, " +
$"Slot={Slot}, " +
$"Process={ProcessName}, " +
$"Error={ErrorMessage ?? "None"}";
}
}
public class PreadjustmentDetectResult
{
public bool Success { get; set; }
public int DetectedMeterCount { get; set; }
public int DetectedThermometerCount { get; set; }
public string ErrorMessage { get; set; }
/// <inheritdoc />
public override string ToString()
{
return
$"Success={Success}, " +
$"Meters={DetectedMeterCount}, " +
$"Thermometers={DetectedThermometerCount}, " +
$"Error={ErrorMessage ?? "None"}";
}
}
public class PreAdjustmentInitializationResult
{
public bool Success { get; set; }
public string Slots { get; set; }
public string ErrorMessage { get; set; }
/// <inheritdoc />
public override string ToString()
{
return
$"Success={Success}, " +
$"Slots={Slots}, " +
$"Error={ErrorMessage ?? "None"}";
}
}
#endregion
}
}
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="NLog" publicKeyToken="5120e14c03d0593c" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Xylem.Common.CommonCore" publicKeyToken="null" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.8.18.17954" newVersion="2.8.18.17954" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
@@ -0,0 +1,36 @@
{
"_Comment": "GCI DataStorage configuration",
"DataStorage": {
"MeterLoginPasswords": {
"___Documentation___": {
"Description": "Reads login passwords for meters by PCB ID",
"Type": "Supported: LocalDatabase, RemoteDatabase, LocalCsv, LocalJson, RestApi",
"DataSource": "Database connection string",
"QueryTemplate": "QUERYPARAM is placeholder for runtime value. Example: WHERE [PcbId]=QUERYPARAM -> PCB ID provided during GetPasswordAsync()."
},
"Name": "MeterLoginPasswords",
"Type": "LocalDatabase",
"DataSource": "Server=(localdb)\\MojaDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
"QueryTemplate": "SELECT [Password] FROM [dbo].[SkeletonKeys] WHERE [PcbId] = QUERYPARAM"
},
"PreAdjustmentCalibrationParams": {
"___Documentation___": {
"Description": "Reads pre-adjustment calibration parameters by meter size",
"Type": "Supported: LocalDatabase, RemoteDatabase, LocalCsv, LocalJson, RestApi",
"DataSource": "Database connection string",
"QueryTemplate": "QUERYPARAM is placeholder for runtime value. Example: WHERE [MeterSize]=QUERYPARAM -> meter size provided during ReadCalibrationParamsAsync()."
},
"Name": "PreAdjustmentCalibrationParams",
"Type": "LocalDatabase",
"DataSource": "Server=(localdb)\\MojaDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
"QueryTemplate": "SELECT [ParameterName], [ParameterValue] FROM [dbo].[PreAdjustmentCalibrationParams] WHERE [MeterSize] = QUERYPARAM"
}
}
}
@@ -0,0 +1,32 @@
namespace GenesisCordonelInterface.Core.Config
{
/// <summary>
/// Root GCI configuration object loaded from gci_config.json.
///
/// This class represents the top-level configuration structure
/// and serves as an entry point for all configurable GCI features.
///
/// Example:
///
/// {
/// "DataStorageSection":
/// {
/// ...
/// }
/// }
/// </summary>
public class GciConfig
{
/// <summary>
/// Data storage configuration section.
///
/// Contains definitions for all configured readers and writers,
/// such as:
///
/// - MeterLoginPasswords
/// - PreAdjustmentCalibrationParams
/// - future storage providers
/// </summary>
public DataStorage.Config.GciDataStorageConfig DataStorageSection { get; set; }
}
}
@@ -0,0 +1,177 @@
using System;
using System.IO;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using Newtonsoft.Json;
namespace GenesisCordonelInterface.Core.Config
{
/// <summary>
/// Loads GCI configuration from gci_config.json.
///
/// Responsibilities:
/// - Locate configuration file
/// - Deserialize JSON into strongly typed objects
/// - Normalize relative file paths
/// - Preserve database connection strings and REST URLs
///
/// Example:
///
/// Config/
/// gci_config.json
///
/// Data/
/// meter_passwords.csv
///
/// Relative paths:
/// Data\file.csv
///
/// become:
///
/// C:\App\bin\Debug\Data\file.csv
///
/// Database sources remain unchanged:
///
/// Server=(localdb)\MojaDB;Database=...
/// </summary>
public static class GciConfigLoader
{
/// <summary>
/// Loads default GCI configuration from:
///
/// Config\gci_config.json
/// </summary>
/// <returns>
/// Loaded GCI configuration.
/// </returns>
public static GciConfig LoadDefault()
{
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string configPath = Path.Combine(
baseDirectory,
"Config",
"gci_config.json");
return Load(configPath, baseDirectory);
}
/// <summary>
/// Loads GCI configuration from specified file.
/// </summary>
/// <param name="configPath">
/// Path to configuration json file.
/// </param>
/// <param name="baseDirectory">
/// Base directory used for resolving relative paths.
/// </param>
/// <returns>
/// Loaded configuration object.
/// </returns>
public static GciConfig Load(
string configPath,
string baseDirectory = null)
{
if (string.IsNullOrWhiteSpace(configPath))
throw new ArgumentException(
"Config path must not be empty.",
nameof(configPath));
if (!File.Exists(configPath))
throw new FileNotFoundException(
"GCI config file was not found.",
configPath);
string json = File.ReadAllText(configPath);
GciConfig config =
JsonConvert.DeserializeObject<GciConfig>(json);
if (config == null)
throw new InvalidOperationException(
"GCI config could not be loaded.");
NormalizeDataStoragePaths(
config,
baseDirectory ?? Path.GetDirectoryName(configPath));
return config;
}
/// <summary>
/// Normalizes paths for all configured data storage entries.
///
/// Converts relative file paths into absolute paths.
/// Database connection strings remain untouched.
/// </summary>
/// <param name="config">
/// Loaded configuration object.
/// </param>
/// <param name="baseDirectory">
/// Base path used for relative resolution.
/// </param>
private static void NormalizeDataStoragePaths(
GciConfig config,
string baseDirectory)
{
if (config.DataStorageSection == null)
return;
NormalizePath(
config.DataStorageSection.MeterLoginPasswords,
baseDirectory);
NormalizePath(
config.DataStorageSection.PreAdjustmentCalibrationParams,
baseDirectory);
}
/// <summary>
/// Converts relative file paths into absolute paths.
///
/// Applies only to:
/// - LocalCsv
/// - RemoteCsv
/// - LocalJson
/// - RemoteJson
///
/// Does not modify:
/// - Database connection strings
/// - REST URLs
/// </summary>
/// <param name="storageConfig">
/// Storage configuration.
/// </param>
/// <param name="baseDirectory">
/// Base path for resolution.
/// </param>
private static void NormalizePath(
DataStorageConfig storageConfig,
string baseDirectory)
{
if (storageConfig == null)
return;
if (string.IsNullOrWhiteSpace(storageConfig.DataSource))
return;
// Database connection strings and URLs
// must never be treated as file paths.
if (storageConfig.Type == DataStorageType.LocalDatabase ||
storageConfig.Type == DataStorageType.RemoteDatabase ||
storageConfig.Type == DataStorageType.RestApi)
{
return;
}
if (Path.IsPathRooted(storageConfig.DataSource))
return;
storageConfig.DataSource =
Path.GetFullPath(
Path.Combine(
baseDirectory,
storageConfig.DataSource));
}
}
}
@@ -0,0 +1,36 @@
{
"_Comment": "GCI DataStorage configuration",
"DataStorageSection": {
"MeterLoginPasswords": {
"___Documentation___": {
"Description": "Reads login passwords for meters by PCB ID",
"Type": "Supported: LocalDatabase, RemoteDatabase, LocalCsv, LocalJson, RestApi",
"DataSource": "Database connection string",
"QueryTemplate": "QUERYPARAM is placeholder for runtime value. Example: WHERE [PcbId]=QUERYPARAM -> PCB ID provided during GetPasswordAsync()."
},
"Name": "MeterLoginPasswords",
"Type": "LocalDatabase",
"DataSource": "Server=(localdb)\\SensusLocalDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
"QueryTemplate": "SELECT [Password] FROM [dbo].[SkeletonKeys] WHERE [PcbId] = QUERYPARAM"
},
"PreAdjustmentCalibrationParams": {
"___Documentation___": {
"Description": "Reads pre-adjustment calibration parameters by meter size",
"Type": "Supported: LocalDatabase, RemoteDatabase, LocalCsv, LocalJson, RestApi",
"DataSource": "Database connection string",
"QueryTemplate": "QUERYPARAM is placeholder for runtime value. Example: WHERE [MeterSize]=QUERYPARAM -> meter size provided during ReadCalibrationParamsAsync()."
},
"Name": "PreAdjustmentCalibrationParams",
"Type": "LocalDatabase",
"DataSource": "Server=(localdb)\\SensusLocalDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
"QueryTemplate": "SELECT [ParameterName], [ParameterValue] FROM [dbo].[PreAdjustmentCalibrationParams] WHERE [MeterSize] = QUERYPARAM"
}
}
}
@@ -0,0 +1,32 @@
namespace GenesisCordonelInterface.Core.DataStorage.Config
{
/// <summary>
/// Root GCI configuration object loaded from gci_config.json.
///
/// This class represents the top-level configuration structure
/// and serves as an entry point for all configurable GCI features.
///
/// Example:
///
/// {
/// "DataStorage":
/// {
/// ...
/// }
/// }
/// </summary>
public class GciConfig
{
/// <summary>
/// Data storage configuration section.
///
/// Contains definitions for all configured readers and writers,
/// such as:
///
/// - MeterLoginPasswords
/// - PreAdjustmentCalibrationParams
/// - future storage providers
/// </summary>
public GciDataStorageConfig DataStorage { get; set; }
}
}
@@ -0,0 +1,177 @@
using System;
using System.IO;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using Newtonsoft.Json;
namespace GenesisCordonelInterface.Core.DataStorage.Config
{
/// <summary>
/// Loads GCI configuration from gci_config.json.
///
/// Responsibilities:
/// - Locate configuration file
/// - Deserialize JSON into strongly typed objects
/// - Normalize relative file paths
/// - Preserve database connection strings and REST URLs
///
/// Example:
///
/// Config/
/// gci_config.json
///
/// Data/
/// meter_passwords.csv
///
/// Relative paths:
/// Data\file.csv
///
/// become:
///
/// C:\App\bin\Debug\Data\file.csv
///
/// Database sources remain unchanged:
///
/// Server=(localdb)\MojaDB;Database=...
/// </summary>
public static class GciConfigLoader
{
/// <summary>
/// Loads default GCI configuration from:
///
/// Config\gci_config.json
/// </summary>
/// <returns>
/// Loaded GCI configuration.
/// </returns>
public static GciConfig LoadDefault()
{
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string configPath = Path.Combine(
baseDirectory,
"Config",
"gci_config.json");
return Load(configPath, baseDirectory);
}
/// <summary>
/// Loads GCI configuration from specified file.
/// </summary>
/// <param name="configPath">
/// Path to configuration json file.
/// </param>
/// <param name="baseDirectory">
/// Base directory used for resolving relative paths.
/// </param>
/// <returns>
/// Loaded configuration object.
/// </returns>
public static GciConfig Load(
string configPath,
string baseDirectory = null)
{
if (string.IsNullOrWhiteSpace(configPath))
throw new ArgumentException(
"Config path must not be empty.",
nameof(configPath));
if (!File.Exists(configPath))
throw new FileNotFoundException(
"GCI config file was not found.",
configPath);
string json = File.ReadAllText(configPath);
GciConfig config =
JsonConvert.DeserializeObject<GciConfig>(json);
if (config == null)
throw new InvalidOperationException(
"GCI config could not be loaded.");
NormalizeDataStoragePaths(
config,
baseDirectory ?? Path.GetDirectoryName(configPath));
return config;
}
/// <summary>
/// Normalizes paths for all configured data storage entries.
///
/// Converts relative file paths into absolute paths.
/// Database connection strings remain untouched.
/// </summary>
/// <param name="config">
/// Loaded configuration object.
/// </param>
/// <param name="baseDirectory">
/// Base path used for relative resolution.
/// </param>
private static void NormalizeDataStoragePaths(
GciConfig config,
string baseDirectory)
{
if (config.DataStorage == null)
return;
NormalizePath(
config.DataStorage.MeterLoginPasswords,
baseDirectory);
NormalizePath(
config.DataStorage.PreAdjustmentCalibrationParams,
baseDirectory);
}
/// <summary>
/// Converts relative file paths into absolute paths.
///
/// Applies only to:
/// - LocalCsv
/// - RemoteCsv
/// - LocalJson
/// - RemoteJson
///
/// Does not modify:
/// - Database connection strings
/// - REST URLs
/// </summary>
/// <param name="storageConfig">
/// Storage configuration.
/// </param>
/// <param name="baseDirectory">
/// Base path for resolution.
/// </param>
private static void NormalizePath(
DataStorageConfig storageConfig,
string baseDirectory)
{
if (storageConfig == null)
return;
if (string.IsNullOrWhiteSpace(storageConfig.DataSource))
return;
// Database connection strings and URLs
// must never be treated as file paths.
if (storageConfig.Type == DataStorageType.LocalDatabase ||
storageConfig.Type == DataStorageType.RemoteDatabase ||
storageConfig.Type == DataStorageType.RestApi)
{
return;
}
if (Path.IsPathRooted(storageConfig.DataSource))
return;
storageConfig.DataSource =
Path.GetFullPath(
Path.Combine(
baseDirectory,
storageConfig.DataSource));
}
}
}
@@ -0,0 +1,30 @@
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
namespace GenesisCordonelInterface.Core.DataStorage.Config
{
/// <summary>
/// Contains all configured GCI data storage sources.
///
/// Each property represents one logical use-case
/// and points to its storage configuration.
///
/// Example:
/// MeterLoginPasswords
/// -> SQL database
///
/// PreAdjustmentCalibrationParams
/// -> CSV file
/// </summary>
public class GciDataStorageConfig
{
/// <summary>
/// Configuration for meter login password lookup.
/// </summary>
public DataStorageConfig MeterLoginPasswords { get; set; }
/// <summary>
/// Configuration for pre-adjustment calibration data lookup.
/// </summary>
public DataStorageConfig PreAdjustmentCalibrationParams { get; set; }
}
}
@@ -0,0 +1,49 @@
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Contracts
{
/// <summary>
/// Defines common contract for all GCI data storage readers.
///
/// Implementations can read data from different storage types:
/// - SQL database
/// - CSV file
/// - JSON file
/// - REST API
///
/// Consumers should use this interface instead of concrete readers.
/// </summary>
public interface IDataStorageReader
{
/// <summary>
/// Reads data from configured storage using provided query.
/// </summary>
/// <param name="query">
/// Query object containing lookup parameters.
/// </param>
/// <returns>
/// Storage-specific result object.
/// </returns>
object GetData(Models.DataQuery query);
/// <summary>
/// Tests whether configured data source is accessible.
/// </summary>
/// <param name="enableDiagnostics">
/// Enables detailed diagnostic output.
/// </param>
/// <returns>
/// Diagnostic result of source test.
/// </returns>
Models.ReaderDiagnosticResult TestSource(bool enableDiagnostics);
/// <summary>
/// Tests whether configured query is valid for the data source.
/// </summary>
/// <param name="enableDiagnostics">
/// Enables detailed diagnostic output.
/// </param>
/// <returns>
/// Diagnostic result of query test.
/// </returns>
Models.ReaderDiagnosticResult TestQuery(bool enableDiagnostics);
}
}
@@ -0,0 +1,94 @@
using System;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Contracts;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common
{
/// <summary>
/// Factory responsible for creating appropriate
/// data storage reader implementations.
///
/// The reader type is selected according to:
///
/// DataStorageConfig.Type
///
/// Example:
///
/// LocalDatabase
/// -> DatabaseDataStorageReader
///
/// LocalCsv
/// -> CsvDataStorageReader
///
/// LocalJson
/// -> JsonDataStorageReader
///
/// RestApi
/// -> RestApiDataStorageReader
///
/// This factory hides implementation details from
/// higher layers and keeps consumers independent
/// of storage technology.
///
/// Trace:
///
/// MeterLoginPasswordReader
/// -> DataStorageReaderFactory.Create()
/// -> DatabaseDataStorageReader
/// -> CsvDataStorageReader
/// -> JsonDataStorageReader
/// -> RestApiDataStorageReader
/// </summary>
public static class DataStorageReaderFactory
{
/// <summary>
/// Creates appropriate reader implementation
/// according to storage configuration.
/// </summary>
/// <param name="config">
/// Data storage configuration loaded from gci_config.json.
/// </param>
/// <returns>
/// Configured storage reader implementation.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Configuration is null.
/// </exception>
/// <exception cref="NotSupportedException">
/// Unsupported storage type.
/// </exception>
public static IDataStorageReader Create(
DataStorageConfig config)
{
if (config == null)
throw new ArgumentNullException(nameof(config));
switch (config.Type)
{
case DataStorageType.RemoteDatabase:
case DataStorageType.LocalDatabase:
return new Providers.DatabaseDataStorageReader(config);
case DataStorageType.RemoteCsv:
case DataStorageType.LocalCsv:
return new Providers.CsvDataStorageReader(config);
case DataStorageType.RemoteJson:
case DataStorageType.LocalJson:
return new Providers.JsonDataStorageReader(config);
case DataStorageType.RestApi:
return new Providers.RestApiDataStorageReader(config);
default:
throw new NotSupportedException(
$"Unsupported DataStorageType: '{config.Type}'");
}
}
}
}
@@ -0,0 +1,58 @@
using System.Collections.Generic;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models
{
/// <summary>
/// Represents query input for data storage readers.
///
/// Query parameters are used as lookup values
/// during storage search operations.
///
/// A single parameter:
///
/// 231630279
///
/// executes one lookup.
///
/// Multiple parameters:
///
/// 231630279
/// 231630243
/// 231630148
///
/// can execute batch operations.
///
/// Example:
///
/// QueryTemplate:
///
/// SELECT [Password]
/// WHERE [PcbId]=QUERYPARAM
///
/// Query:
///
/// QueryParams:
/// 231630279
///
/// Result:
///
/// Password belonging to 231630279.
/// </summary>
public class DataQuery
{
/// <summary>
/// Collection of query values.
///
/// Single item:
///
/// QueryParams[0]
///
/// represents one lookup.
///
/// Multiple items may be processed
/// as batch requests.
/// </summary>
public List<string> QueryParams { get; }
= new List<string>();
}
}
@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models
{
/// <summary>
/// Configuration for one storage source.
/// Loaded from gci_config.json
/// </summary>
public class DataStorageConfig
{
/// <summary>
/// Logical storage name.
/// Example:
/// MeterLoginPasswords
/// CalibrationParameters
/// </summary>
public string Name { get; set; }
/// <summary>
/// Storage implementation type.
/// </summary>
public DataStorageType Type { get; set; }
/// <summary>
/// Connection string,
/// file path,
/// URL etc.
/// </summary>
public string DataSource { get; set; }
/// <summary>
/// Query template.
/// Example:
///
/// SQL:
/// SELECT Password
/// FROM Passwords
/// WHERE PcbId=QUERYPARAM
///
/// CSV:
/// SELECT [Password]
/// WHERE [PcbId]=QUERYPARAM
/// </summary>
public string QueryTemplate { get; set; }
public DataStorageConfig(
string name,
DataStorageType type,
string dataSource,
string queryTemplate)
{
Name = name;
Type = type;
DataSource = dataSource;
QueryTemplate = queryTemplate;
}
}
}
@@ -0,0 +1,79 @@
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models
{
/// <summary>
/// Identifies supported data storage implementations.
///
/// The type determines which reader implementation
/// will be created by DataStorageReaderFactory.
///
/// Example:
///
/// LocalDatabase
/// -> DatabaseDataStorageReader
///
/// LocalCsv
/// -> CsvDataStorageReader
///
/// RestApi
/// -> RestApiDataStorageReader
///
/// Source:
///
/// gci_config.json
///
/// Example:
///
/// "Type":"LocalDatabase"
/// </summary>
public enum DataStorageType
{
/// <summary>
/// REST API endpoint.
///
/// Example:
///
/// https://api.company.com/passwords
/// </summary>
RestApi,
/// <summary>
/// Database located on remote server.
///
/// Example:
///
/// SQL server on network machine.
/// </summary>
RemoteDatabase,
/// <summary>
/// Database located on local machine.
///
/// Example:
///
/// SQL LocalDB
/// SQLite
/// local SQL Server instance
/// </summary>
LocalDatabase,
/// <summary>
/// JSON source stored remotely.
/// </summary>
RemoteJson,
/// <summary>
/// JSON file stored locally.
/// </summary>
LocalJson,
/// <summary>
/// CSV source stored remotely.
/// </summary>
RemoteCsv,
/// <summary>
/// CSV file stored locally.
/// </summary>
LocalCsv
}
}
@@ -0,0 +1,53 @@
using System.Collections.Generic;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models
{
/// <summary>
/// Represents result returned by database-based
/// data storage readers.
///
/// Supports both:
///
/// - Single-row lookups
/// (e.g. MeterLoginPasswords)
///
/// - Multi-row queries
/// (e.g. PreAdjustmentCalibrationParams)
/// </summary>
internal class DatabaseSearchResult
{
/// <summary>
/// Indicates whether at least one record
/// was found.
/// </summary>
public bool Found { get; set; }
/// <summary>
/// Executed SQL query text.
/// Mainly intended for diagnostics
/// and troubleshooting.
/// </summary>
public string Query { get; set; }
/// <summary>
/// First returned row represented as
/// column/value pairs.
///
/// Preserved for backward compatibility
/// with existing readers expecting
/// a single database record.
/// </summary>
public Dictionary<string, object> Values { get; }
= new Dictionary<string, object>();
/// <summary>
/// All returned rows represented as
/// a collection of column/value dictionaries.
///
/// Intended for queries returning
/// multiple records.
/// </summary>
public List<Dictionary<string, object>> Rows { get; }
= new List<Dictionary<string, object>>();
}
}
@@ -0,0 +1,141 @@
using System.Collections.Generic;
using System.Text;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models
{
/// <summary>
/// Represents diagnostic result of data storage operations.
///
/// Used for:
/// - source validation
/// - query validation
/// - connection tests
/// - detailed diagnostic logging
///
/// Example:
///
/// TestSource()
/// -> connection successful
///
/// TestQuery()
/// -> column validation
///
/// Can also carry additional payload data.
/// </summary>
public class ReaderDiagnosticResult
{
/// <summary>
/// Indicates whether operation completed successfully.
/// </summary>
public bool Success { get; set; }
/// <summary>
/// Human readable summary message.
///
/// Example:
///
/// "Connection successful."
///
/// or:
///
/// "Column not found."
/// </summary>
public string Message { get; set; }
/// <summary>
/// Detailed diagnostic output lines.
///
/// Used for debugging and troubleshooting.
/// </summary>
public List<string> Diagnostics { get; set; }
/// <summary>
/// Optional operation payload.
///
/// Example:
///
/// loaded CSV lines
/// SQL test value
/// parsed content
/// </summary>
public object Data { get; set; }
/// <summary>
/// Creates empty diagnostic result.
/// </summary>
public ReaderDiagnosticResult()
{
Diagnostics = new List<string>();
}
/// <summary>
/// Creates successful diagnostic result.
/// </summary>
/// <param name="message">
/// Success message.
/// </param>
/// <returns>
/// Successful result object.
/// </returns>
public static ReaderDiagnosticResult SuccessResult(
string message = "OK")
{
return new ReaderDiagnosticResult
{
Success = true,
Message = message
};
}
/// <summary>
/// Creates failed diagnostic result.
/// </summary>
/// <param name="message">
/// Failure message.
/// </param>
/// <returns>
/// Failed result object.
/// </returns>
public static ReaderDiagnosticResult Failure(
string message)
{
return new ReaderDiagnosticResult
{
Success = false,
Message = message
};
}
/// <summary>
/// Converts diagnostic information into display text.
///
/// Output contains:
///
/// diagnostic lines
/// +
/// summary message
/// </summary>
/// <returns>
/// Formatted text representation.
/// </returns>
public string ToDisplayDiag()
{
StringBuilder sb = new StringBuilder();
if (Diagnostics != null &&
Diagnostics.Count > 0)
{
foreach (string line in Diagnostics)
sb.AppendLine(line);
if (!string.IsNullOrWhiteSpace(Message))
sb.AppendLine();
}
if (!string.IsNullOrWhiteSpace(Message))
sb.AppendLine(Message);
return sb.ToString();
}
}
}
@@ -0,0 +1,394 @@
using System;
using System.Collections.Generic;
using System.IO;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Searching;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Contracts;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Providers
{
/// <summary>
/// Reads and searches CSV based data sources.
///
/// Supported query syntax:
/// SELECT [ReturnColumn] WHERE [MatchColumn] = QUERYPARAM
///
/// Example:
/// SELECT [Password] WHERE [PcbId] = QUERYPARAM
///
/// Supports:
/// - column names: [ColumnName]
/// - column indexes: COLUMN(n)
///
/// Trace:
/// MeterLoginPasswordReader
/// -> CsvDataStorageReader.GetData()
/// -> ConnectToSource()
/// -> ExecuteQuery()
/// </summary>
public class CsvDataStorageReader : IDataStorageReader
{
private readonly DataStorageConfig config;
private string resolvedPath;
private string[] loadedLines;
private string[] loadedHeaders;
/// <summary>
/// Creates CSV data storage reader using provided configuration.
/// </summary>
/// <param name="config">
/// Data storage configuration loaded from gci_config.json.
/// </param>
public CsvDataStorageReader(DataStorageConfig config)
{
this.config = config ?? throw new ArgumentNullException(nameof(config));
}
/// <summary>
/// Reads values from CSV using configured QueryTemplate.
/// </summary>
/// <param name="query">
/// Query parameters used for lookup.
/// </param>
/// <returns>
/// ReaderDiagnosticResult containing lookup result.
/// </returns>
public object GetData(DataQuery query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
ReaderDiagnosticResult sourceResult = ConnectToSource(true);
if (!sourceResult.Success)
throw new InvalidOperationException(sourceResult.Message);
ReaderDiagnosticResult queryResult = ExecuteQuery(query, true);
if (!queryResult.Success)
throw new InvalidOperationException(queryResult.Message);
return queryResult;
}
/// <summary>
/// Validates CSV source accessibility and content.
/// </summary>
/// <param name="enableDiagnostics">
/// Enables detailed diagnostic output.
/// </param>
/// <returns>
/// Diagnostic result.
/// </returns>
public ReaderDiagnosticResult TestSource(bool enableDiagnostics)
{
return ConnectToSource(enableDiagnostics);
}
/// <summary>
/// Validates configured QueryTemplate against CSV header.
/// </summary>
/// <param name="enableDiagnostics">
/// Enables detailed diagnostic output.
/// </param>
/// <returns>
/// Diagnostic result.
/// </returns>
public ReaderDiagnosticResult TestQuery(bool enableDiagnostics)
{
ReaderDiagnosticResult sourceResult = ConnectToSource(enableDiagnostics);
if (!sourceResult.Success)
return sourceResult;
ReaderDiagnosticResult result = new ReaderDiagnosticResult();
try
{
Log(result, enableDiagnostics, "Starting QueryTemplate validation.");
SearchOrderDefinition definition =
SearchOrderParser.Parse(config.QueryTemplate);
int selectIndex = ResolveColumnIndex(
loadedHeaders,
definition.SelectColumn);
int whereIndex = ResolveColumnIndex(
loadedHeaders,
definition.WhereColumn);
Log(result, enableDiagnostics, "QueryTemplate parsed successfully.");
Log(result, enableDiagnostics, "Select column index: " + selectIndex);
Log(result, enableDiagnostics, "Where column index: " + whereIndex);
result.Success = true;
result.Message = "QueryTemplate validation finished successfully.";
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
Log(result, enableDiagnostics, "ERROR: " + ex.Message);
}
return result;
}
/// <summary>
/// Opens CSV file and loads its content.
/// Validates file existence and header.
/// </summary>
/// <param name="enableDiagnostics">
/// Enables detailed diagnostic output.
/// </param>
/// <returns>
/// Source validation result.
/// </returns>
private ReaderDiagnosticResult ConnectToSource(bool enableDiagnostics)
{
ReaderDiagnosticResult result = new ReaderDiagnosticResult();
try
{
Log(result, enableDiagnostics, "Starting CSV source connection test.");
if (string.IsNullOrWhiteSpace(config.DataSource))
throw new InvalidOperationException("CSV data source is empty.");
resolvedPath = Path.GetFullPath(config.DataSource);
Log(result, enableDiagnostics, "Resolved full path: " + resolvedPath);
if (!File.Exists(resolvedPath))
throw new FileNotFoundException("CSV file was not found.", resolvedPath);
loadedLines = File.ReadAllLines(resolvedPath);
if (loadedLines == null || loadedLines.Length == 0)
throw new InvalidOperationException("CSV file is empty.");
loadedHeaders = SplitCsvLine(loadedLines[0]);
if (loadedHeaders == null || loadedHeaders.Length == 0)
throw new InvalidOperationException("CSV header is empty.");
Log(result, enableDiagnostics, "CSV line count: " + loadedLines.Length);
Log(result, enableDiagnostics, "CSV header column count: " + loadedHeaders.Length);
result.Success = true;
result.Message = "CSV source connection finished successfully.";
result.Data = loadedLines;
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
result.Data = null;
Log(result, enableDiagnostics, "ERROR: " + ex.Message);
}
return result;
}
/// <summary>
/// Executes configured QueryTemplate against loaded CSV data.
/// </summary>
/// <param name="query">
/// Query values used for matching.
/// </param>
/// <param name="enableDiagnostics">
/// Enables detailed diagnostic output.
/// </param>
/// <returns>
/// Query result.
/// </returns>
private ReaderDiagnosticResult ExecuteQuery(
DataQuery query,
bool enableDiagnostics)
{
ReaderDiagnosticResult result = new ReaderDiagnosticResult();
try
{
if (query.QueryParams == null || query.QueryParams.Count == 0)
throw new InvalidOperationException("DataQuery.QueryParams is empty.");
SearchOrderDefinition definition =
SearchOrderParser.Parse(config.QueryTemplate);
int selectIndex = ResolveColumnIndex(
loadedHeaders,
definition.SelectColumn);
int whereIndex = ResolveColumnIndex(
loadedHeaders,
definition.WhereColumn);
List<string> matchedValues = new List<string>();
foreach (string param in query.QueryParams)
{
string queryValue = (param ?? string.Empty).Trim();
bool found = false;
for (int lineIndex = 1; lineIndex < loadedLines.Length; lineIndex++)
{
if (string.IsNullOrWhiteSpace(loadedLines[lineIndex]))
continue;
string[] values = SplitCsvLine(loadedLines[lineIndex]);
if (whereIndex >= values.Length)
continue;
string currentValue = (values[whereIndex] ?? string.Empty).Trim();
if (!string.Equals(
currentValue,
queryValue,
StringComparison.OrdinalIgnoreCase))
{
continue;
}
string returnValue =
selectIndex < values.Length
? values[selectIndex]
: string.Empty;
matchedValues.Add(returnValue);
found = true;
break;
}
if (!found)
Log(result, enableDiagnostics, "No match found for: " + queryValue);
}
result.Success = true;
if (query.QueryParams.Count == 1)
{
result.Data = matchedValues.Count > 0 ? matchedValues[0] : null;
result.Message = matchedValues.Count > 0
? "Value found."
: "No match found.";
}
else
{
result.Data = matchedValues;
result.Message =
"Batch query finished. Matches found: " +
matchedValues.Count +
" of " +
query.QueryParams.Count +
".";
}
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
result.Data = null;
Log(result, enableDiagnostics, "ERROR: " + ex.Message);
}
return result;
}
/// <summary>
/// Resolves column index either by name or by explicit index.
/// </summary>
/// <param name="headers">
/// CSV header columns.
/// </param>
/// <param name="columnReference">
/// Parsed QueryTemplate column definition.
/// </param>
/// <returns>
/// Zero-based column index.
/// </returns>
private int ResolveColumnIndex(
string[] headers,
ColumnReference columnReference)
{
if (columnReference == null)
throw new InvalidOperationException("Column reference is null.");
if (columnReference.HasIndex)
{
int index = columnReference.Index.Value;
if (index < 0 || index >= headers.Length)
throw new InvalidOperationException("Column index is out of range.");
return index;
}
if (columnReference.HasName)
{
for (int i = 0; i < headers.Length; i++)
{
if (string.Equals(
headers[i]?.Trim(),
columnReference.Name?.Trim(),
StringComparison.OrdinalIgnoreCase))
{
return i;
}
}
throw new InvalidOperationException(
"Column '" + columnReference.Name + "' was not found in CSV header.");
}
throw new InvalidOperationException("Column reference is not defined.");
}
/// <summary>
/// Splits CSV line using common separators.
/// Supports:
/// ';'
/// ','
/// '\t'
/// </summary>
/// <param name="line">
/// Input CSV line.
/// </param>
/// <returns>
/// Parsed columns.
/// </returns>
private string[] SplitCsvLine(string line)
{
if (string.IsNullOrEmpty(line))
return new string[0];
if (line.Contains(";"))
return line.Split(';');
if (line.Contains(","))
return line.Split(',');
if (line.Contains("\t"))
return line.Split('\t');
return new[] { line };
}
/// <summary>
/// Adds diagnostic line when diagnostics are enabled.
/// </summary>
private void Log(
ReaderDiagnosticResult result,
bool enableDiagnostics,
string message)
{
if (!enableDiagnostics || result == null)
return;
result.Diagnostics.Add(message);
}
}
}
@@ -0,0 +1,397 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Contracts;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Providers
{
/// <summary>
/// Reads data from SQL Server based data storage.
///
/// The reader uses configuration loaded from gci_config.json.
///
/// QueryTemplate must contain QUERYPARAM placeholder.
///
/// Example:
///
/// SELECT [Password]
/// FROM [dbo].[SkeletonKeys]
/// WHERE [PcbId] = QUERYPARAM
///
/// or
///
/// SELECT [ParameterName], [ParameterValue]
/// FROM [dbo].[PreAdjustmentCalibrationParams]
/// WHERE [Dn_InternalId] = QUERYPARAM
///
/// The placeholder is internally converted
/// to SQL parameter @value.
///
/// Supports both:
///
/// - Single-row lookups
/// - Multi-row result sets
/// </summary>
public class DatabaseDataStorageReader : IDataStorageReader
{
/// <summary>
/// Data storage configuration containing
/// connection string and query template.
/// </summary>
private readonly DataStorageConfig config;
/// <summary>
/// Creates SQL Server data storage reader
/// using provided configuration.
/// </summary>
/// <param name="config">
/// Data storage configuration loaded
/// from gci_config.json.
/// </param>
public DatabaseDataStorageReader(
DataStorageConfig config)
{
this.config =
config ?? throw new ArgumentNullException(nameof(config));
}
/// <summary>
/// Executes configured SQL query and returns
/// matching database records.
///
/// Single-row queries populate:
/// DatabaseSearchResult.Values
///
/// Multi-row queries populate:
/// DatabaseSearchResult.Rows
///
/// For backward compatibility, the first row
/// is also stored in Values.
/// </summary>
/// <param name="query">
/// Query object containing lookup parameter.
/// </param>
/// <returns>
/// DatabaseSearchResult containing returned
/// database records.
///
/// Values contains the first returned row.
///
/// Rows contains the complete result set.
/// </returns>
public object GetData(DataQuery query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
ReaderDiagnosticResult sourceResult =
TestSource(true);
if (!sourceResult.Success)
throw new InvalidOperationException(sourceResult.Message);
string sqlText =
PrepareSqlText(config.QueryTemplate);
object queryValue =
ExtractQueryValue(query);
using (SqlConnection connection =
new SqlConnection(config.DataSource))
using (SqlCommand command =
new SqlCommand(sqlText, connection))
{
AddQueryParameter(command, queryValue);
connection.Open();
// Full result set is required because some
// storage definitions return multiple records
// (e.g. PreAdjustmentCalibrationParams).
using (SqlDataReader reader =
command.ExecuteReader())
{
DatabaseSearchResult result =
new DatabaseSearchResult
{
Query = sqlText
};
while (reader.Read())
{
result.Found = true;
// Represents one database row.
Dictionary<string, object> row =
new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
object value =
reader.GetValue(i);
object normalizedValue =
value == DBNull.Value
? null
: value;
row[reader.GetName(i)] =
normalizedValue;
}
// Preserve first row for legacy consumers
// expecting a single returned database record
// (e.g. MeterLoginPasswordReader).
if (result.Rows.Count == 0)
{
foreach (var item in row)
{
result.Values[item.Key] =
item.Value;
}
}
// Store complete database result set.
result.Rows.Add(row);
}
if (result.Rows.Count == 0)
{
result.Found = false;
}
return result;
}
}
}
/// <summary>
/// Tests whether SQL Server connection
/// can be opened.
/// </summary>
/// <param name="enableDiagnostics">
/// Enables detailed diagnostic output.
/// </param>
/// <returns>
/// Diagnostic result of SQL connection test.
/// </returns>
public ReaderDiagnosticResult TestSource(
bool enableDiagnostics)
{
ReaderDiagnosticResult result =
new ReaderDiagnosticResult();
try
{
if (string.IsNullOrWhiteSpace(config.DataSource))
{
throw new InvalidOperationException(
"Data source is empty.");
}
Log(
result,
enableDiagnostics,
"Opening SQL connection.");
using (SqlConnection connection =
new SqlConnection(config.DataSource))
{
connection.Open();
Log(
result,
enableDiagnostics,
"Connection opened successfully.");
using (SqlCommand command =
new SqlCommand("SELECT 1", connection))
{
object value =
command.ExecuteScalar();
Log(
result,
enableDiagnostics,
"Test query result: " + value);
}
}
result.Success = true;
result.Message =
"Connection to SQL Server OK.";
}
catch (Exception ex)
{
result.Success = false;
result.Message =
"Failed to connect to SQL Server. " + ex.Message;
Log(
result,
enableDiagnostics,
ex.ToString());
}
return result;
}
/// <summary>
/// Tests whether configured SQL query
/// can be prepared and executed.
/// </summary>
/// <param name="enableDiagnostics">
/// Enables detailed diagnostic output.
/// </param>
/// <returns>
/// Diagnostic result of query execution test.
/// </returns>
public ReaderDiagnosticResult TestQuery(
bool enableDiagnostics)
{
ReaderDiagnosticResult result =
new ReaderDiagnosticResult();
try
{
if (string.IsNullOrWhiteSpace(config.QueryTemplate))
{
throw new InvalidOperationException(
"Query template is empty.");
}
string sqlText =
PrepareSqlText(config.QueryTemplate);
Log(result, enableDiagnostics, "Original template:");
Log(result, enableDiagnostics, config.QueryTemplate);
Log(result, enableDiagnostics, "Prepared SQL:");
Log(result, enableDiagnostics, sqlText);
using (SqlConnection connection =
new SqlConnection(config.DataSource))
using (SqlCommand command =
new SqlCommand(sqlText, connection))
{
AddQueryParameter(command, "TEST");
connection.Open();
object value =
command.ExecuteScalar();
result.Data = value;
Log(
result,
enableDiagnostics,
"Query executed successfully.");
}
result.Success = true;
result.Message =
"Query executed successfully.";
}
catch (Exception ex)
{
result.Success = false;
result.Message =
"Query execution failed. " + ex.Message;
Log(
result,
enableDiagnostics,
ex.ToString());
}
return result;
}
/// <summary>
/// Converts configured QueryTemplate
/// to executable SQL text.
/// </summary>
/// <param name="queryTemplate">
/// SQL query template containing
/// QUERYPARAM placeholder.
/// </param>
/// <returns>
/// SQL text with QUERYPARAM replaced
/// by @value parameter.
/// </returns>
private static string PrepareSqlText(
string queryTemplate)
{
if (string.IsNullOrWhiteSpace(queryTemplate))
{
throw new ArgumentException(
"Query template must not be empty.",
nameof(queryTemplate));
}
if (!queryTemplate.Contains("QUERYPARAM"))
{
throw new InvalidOperationException(
"Query template must contain QUERYPARAM placeholder.");
}
return queryTemplate.Replace(
"QUERYPARAM",
"@value");
}
/// <summary>
/// Extracts first query parameter value.
/// </summary>
private static object ExtractQueryValue(
DataQuery query)
{
if (query.QueryParams == null ||
query.QueryParams.Count == 0)
{
throw new InvalidOperationException(
"DataQuery does not contain any query parameter.");
}
return query.QueryParams[0];
}
/// <summary>
/// Adds lookup parameter to SQL command.
/// </summary>
private static void AddQueryParameter(
SqlCommand command,
object value)
{
command.Parameters.Clear();
SqlParameter parameter =
command.Parameters.Add(
"@value",
SqlDbType.Variant);
parameter.Value =
value ?? DBNull.Value;
}
/// <summary>
/// Adds diagnostic line when diagnostics
/// are enabled.
/// </summary>
private static void Log(
ReaderDiagnosticResult result,
bool enableDiagnostics,
string message)
{
if (!enableDiagnostics || result == null)
return;
result.Diagnostics.Add(message);
}
}
}
@@ -0,0 +1,31 @@
using System;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Contracts;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Providers
{
public class JsonDataStorageReader : IDataStorageReader
{
private readonly DataStorageConfig config;
public JsonDataStorageReader(DataStorageConfig config)
{
this.config = config ?? throw new ArgumentNullException(nameof(config));
}
public object GetData(DataQuery query)
{
throw new NotImplementedException();
}
public ReaderDiagnosticResult TestSource(bool enableDiagnostics)
{
throw new NotImplementedException();
}
public ReaderDiagnosticResult TestQuery(bool enableDiagnostics)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,31 @@
using System;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Contracts;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Providers
{
public class RestApiDataStorageReader : IDataStorageReader
{
private readonly DataStorageConfig config;
public RestApiDataStorageReader(DataStorageConfig config)
{
this.config = config ?? throw new ArgumentNullException(nameof(config));
}
public object GetData(DataQuery query)
{
throw new NotImplementedException();
}
public ReaderDiagnosticResult TestSource(bool enableDiagnostics)
{
throw new NotImplementedException();
}
public ReaderDiagnosticResult TestQuery(bool enableDiagnostics)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,125 @@
using System;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Searching
{
/// <summary>
/// Parsed representation of QueryTemplate expression.
///
/// Example:
///
/// SELECT [Password] WHERE [PcbId] = QUERYPARAM
///
/// becomes:
///
/// SelectColumn:
/// [Password]
///
/// WhereColumn:
/// [PcbId]
/// </summary>
public class SearchOrderDefinition
{
/// <summary>
/// Column to be returned from lookup result.
///
/// Example:
///
/// SELECT [Password]
///
/// returns:
///
/// [Password]
/// </summary>
public ColumnReference SelectColumn { get; set; }
/// <summary>
/// Column used for row matching.
///
/// Example:
///
/// WHERE [PcbId] = QUERYPARAM
///
/// uses:
///
/// [PcbId]
/// </summary>
public ColumnReference WhereColumn { get; set; }
}
/// <summary>
/// Represents one column definition inside QueryTemplate.
///
/// Supports two forms:
///
/// [ColumnName]
///
/// or:
///
/// COLUMN(number)
///
/// Examples:
///
/// [Password]
///
/// COLUMN(2)
/// </summary>
public class ColumnReference
{
/// <summary>
/// Column name used in named lookup mode.
///
/// Example:
///
/// [Password]
/// </summary>
public string Name { get; set; }
/// <summary>
/// Zero-based column index used in indexed lookup mode.
///
/// Example:
///
/// COLUMN(2)
/// </summary>
public int? Index { get; set; }
/// <summary>
/// Indicates whether column uses name-based lookup.
/// </summary>
public bool HasName
{
get
{
return !string.IsNullOrWhiteSpace(Name);
}
}
/// <summary>
/// Indicates whether column uses index-based lookup.
/// </summary>
public bool HasIndex
{
get
{
return Index.HasValue;
}
}
/// <summary>
/// Returns human readable representation.
/// </summary>
/// <returns>
/// Column expression text.
/// </returns>
public override string ToString()
{
if (HasName)
return "[" + Name + "]";
if (HasIndex)
return "COLUMN(" + Index.Value + ")";
return "<undefined column reference>";
}
}
}
@@ -0,0 +1,167 @@
using System;
using System.Text.RegularExpressions;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Common.Searching
{
/// <summary>
/// Parses SQL-like QueryTemplate expressions used by GCI data storage readers.
///
/// Supported syntax:
///
/// SELECT [ReturnColumn] WHERE [MatchColumn] = QUERYPARAM
///
/// Examples:
///
/// SELECT [Password] WHERE [PcbId] = QUERYPARAM
///
/// SELECT COLUMN(1) WHERE COLUMN(0) = QUERYPARAM
///
/// Mixed forms are also supported:
///
/// SELECT [Password] WHERE COLUMN(0)=QUERYPARAM
///
/// The parser converts text expressions into structured
/// SearchOrderDefinition objects which are later consumed
/// by CSV and other readers.
/// </summary>
public static class SearchOrderParser
{
/// <summary>
/// Full QueryTemplate validation pattern.
///
/// Expected syntax:
///
/// SELECT [Column] WHERE [Column] = QUERYPARAM
/// </summary>
private static readonly Regex FullPattern = new Regex(
@"^\s*SELECT\s+(?<select>\[[^\]]+\]|COLUMN\(\d+\))\s+WHERE\s+(?<where>\[[^\]]+\]|COLUMN\(\d+\))\s*=\s*QUERYPARAM\s*$",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Matches:
///
/// [ColumnName]
/// </summary>
private static readonly Regex NamedColumnPattern = new Regex(
@"^\[(?<name>[^\]]+)\]$",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Matches:
///
/// COLUMN(number)
/// </summary>
private static readonly Regex IndexedColumnPattern = new Regex(
@"^COLUMN\((?<index>\d+)\)$",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Parses QueryTemplate text into structured definition.
///
/// Example:
///
/// SELECT [Password] WHERE [PcbId] = QUERYPARAM
///
/// Result:
///
/// SelectColumn:
/// Password
///
/// WhereColumn:
/// PcbId
/// </summary>
/// <param name="searchOrder">
/// QueryTemplate expression.
/// </param>
/// <returns>
/// Parsed query definition.
/// </returns>
public static SearchOrderDefinition Parse(string searchOrder)
{
if (string.IsNullOrWhiteSpace(searchOrder))
throw new InvalidOperationException(
"QueryTemplate is empty.");
Match match = FullPattern.Match(searchOrder);
if (!match.Success)
{
throw new InvalidOperationException(
"Invalid QueryTemplate syntax. Expected: SELECT [ReturnColumn] WHERE [MatchColumn] = QUERYPARAM");
}
return new SearchOrderDefinition
{
SelectColumn =
ParseColumnReference(
match.Groups["select"].Value),
WhereColumn =
ParseColumnReference(
match.Groups["where"].Value)
};
}
/// <summary>
/// Parses single column definition.
///
/// Supported forms:
///
/// [ColumnName]
///
/// COLUMN(number)
/// </summary>
/// <param name="token">
/// Raw token extracted from QueryTemplate.
/// </param>
/// <returns>
/// Parsed column reference.
/// </returns>
private static ColumnReference ParseColumnReference(
string token)
{
if (string.IsNullOrWhiteSpace(token))
throw new InvalidOperationException(
"Column reference token is empty.");
Match nameMatch =
NamedColumnPattern.Match(token);
if (nameMatch.Success)
{
return new ColumnReference
{
Name =
nameMatch
.Groups["name"]
.Value
.Trim(),
Index = null
};
}
Match indexMatch =
IndexedColumnPattern.Match(token);
if (indexMatch.Success)
{
return new ColumnReference
{
Name = null,
Index =
int.Parse(
indexMatch
.Groups["index"]
.Value)
};
}
throw new InvalidOperationException(
"Invalid column reference '" +
token +
"'. Use [ColumnName] or COLUMN(number).");
}
}
}
@@ -0,0 +1,51 @@
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using System.Threading;
using System.Threading.Tasks;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Implementation.MeterLoginPasswords
{
/// <summary>
/// Defines contract for reading meter login passwords
/// from configured GCI data storage.
///
/// Implementations hide storage details and provide
/// a unified API for password lookup.
///
/// Supported storage types:
/// - SQL database
/// - CSV
/// - JSON
/// - REST API
/// </summary>
public interface IMeterLoginPasswordReader
{
/// <summary>
/// Reads meter login password synchronously.
/// </summary>
/// <param name="queryParam">
/// PCB ID or another configured lookup value.
/// </param>
/// <returns>
/// Password if found; otherwise null.
/// </returns>
string GetPassword(DataQuery query);
/// <summary>
/// Reads meter login password asynchronously.
/// Thread-safe implementation may serialize
/// access to the underlying storage.
/// </summary>
/// <param name="queryParam">
/// PCB ID or another configured lookup value.
/// </param>
/// <param name="token">
/// Cancellation token.
/// </param>
/// <returns>
/// Password if found; otherwise null.
/// </returns>
Task<string> ReadMeterLoginPasswordAsync(
DataQuery query,
CancellationToken token = default);
}
}
@@ -0,0 +1,126 @@
using GenesisCordonelInterface.Core.DataStorage.Reading.Common;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Contracts;
using GenesisCordonelInterface.Core.DataStorage.Reading.Implementation.MeterLoginPasswords;
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Implementation.MeterLoginPasswords
{
/// <summary>
/// Reads meter login password from configured GCI data storage.
/// </summary>
public class MeterLoginPasswordReader : IMeterLoginPasswordReader
{
/// <summary>
/// Universal data storage reader selected by configuration.
/// Can represent database, CSV, JSON or REST reader.
/// </summary>
private readonly IDataStorageReader reader;
/// <summary>
/// Ensures that only one password lookup is executed at a time.
/// </summary>
private readonly SemaphoreSlim readLock = new SemaphoreSlim(1, 1);
/// <summary>
/// Creates password reader using provided data storage configuration.
/// </summary>
/// <param name="config">Data storage configuration loaded from gci_config.json.</param>
public MeterLoginPasswordReader(DataStorageConfig config)
{
reader = DataStorageReaderFactory.Create(config);
}
/// <summary>
/// Asynchronously reads meter login password using
/// the provided data query.
///
/// Thread-safe implementation may serialize
/// access to the underlying storage.
/// </summary>
/// <param name="query">
/// Data query containing lookup parameter values.
/// </param>
/// <param name="token">
/// Cancellation token.
/// </param>
/// <returns>
/// Password if found; otherwise null.
/// </returns>
public async Task<string> ReadMeterLoginPasswordAsync(
DataQuery query,
CancellationToken token = default)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
if (query.QueryParams.Count == 0)
throw new ArgumentException(
"Query does not contain any parameter.",
nameof(query));
await readLock.WaitAsync(token);
try
{
return await Task.Run(
() => GetPassword(query),
token);
}
finally
{
readLock.Release();
}
}
/// <summary>
/// Reads meter login password using
/// the provided data query.
/// </summary>
/// <param name="query">
/// Data query containing lookup parameter values.
/// </param>
/// <returns>
/// Password if found; otherwise null.
/// </returns>
public string GetPassword(
DataQuery query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
if (query.QueryParams.Count == 0)
throw new ArgumentException(
"Query does not contain any parameter.",
nameof(query));
object result =
reader.GetData(query);
if (result is ReaderDiagnosticResult diagnosticResult)
{
return diagnosticResult.Data?.ToString();
}
if (result is DatabaseSearchResult dbResult)
{
if (!dbResult.Found ||
dbResult.Values == null ||
dbResult.Values.Count == 0)
{
return null;
}
foreach (object value in dbResult.Values.Values)
{
return value?.ToString();
}
}
return result?.ToString();
}
}
}
@@ -0,0 +1,62 @@
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Implementation.PreAdjustmentCalibrationParams
{
/// <summary>
/// Provides access to pre-adjustment calibration parameters
/// stored in the configured GCI data source.
///
/// Expected structure:
///
/// MeterSize | ParameterName | ParameterValue
///
/// Example:
///
/// 2 | GENESISFLOW_MinValidToF | 21990232
/// 2 | GENESISFLOW_Timeout | 1
///
/// Parameters are grouped by MeterSize and returned
/// as key/value pairs where:
///
/// Key = ParameterName
/// Value = ParameterValue
/// </summary>
public interface IPreAdjustmentCalibrationParamsReader
{
/// <summary>
/// Reads all pre-adjustment calibration parameters
/// using the provided data query synchronously.
/// </summary>
/// <param name="query">
/// Data query containing meter size as lookup parameter.
/// </param>
/// <returns>
/// Dictionary where key is GENESISFLOW parameter name
/// and value is stored parameter value.
/// </returns>
Dictionary<string, UInt32> GetCalibrationParams(
DataQuery query);
/// <summary>
/// Reads all pre-adjustment calibration parameters
/// using the provided data query asynchronously.
/// </summary>
/// <param name="query">
/// Data query containing meter size as lookup parameter.
/// </param>
/// <param name="token">
/// Cancellation token.
/// </param>
/// <returns>
/// Dictionary where key is GENESISFLOW parameter name
/// and value is stored parameter value.
/// </returns>
Task<Dictionary<string, UInt32>> ReadCalibrationParamsAsync(
DataQuery query,
CancellationToken token = default);
}
}
@@ -0,0 +1,305 @@
using GenesisCordonelInterface.Core.DataStorage.Reading.Common;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Contracts;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace GenesisCordonelInterface.Core.DataStorage.Reading.Implementation.PreAdjustmentCalibrationParams
{
/// <summary>
/// Reads pre-adjustment calibration parameters
/// from configured GCI data storage.
///
/// The underlying storage type is selected
/// through IDataStorageReader and may represent:
///
/// - SQL database
/// - CSV
/// - JSON
/// - REST API
///
/// Expected storage structure:
///
/// MeterSize | ParameterName | ParameterValue
///
/// Example:
///
/// 2 | GENESISFLOW_MinValidToF | 21990232
/// 2 | GENESISFLOW_Timeout | 1
///
/// Returned data are represented as:
///
/// Key = ParameterName
/// Value = ParameterValue
/// </summary>
public class PreAdjustmentCalibrationParamsReader
: IPreAdjustmentCalibrationParamsReader
{
/// <summary>
/// Universal data storage reader selected by configuration.
/// Can represent database, CSV, JSON or REST reader.
/// </summary>
private readonly IDataStorageReader reader;
/// <summary>
/// Ensures that only one calibration parameter lookup
/// is executed at a time.
/// </summary>
private readonly SemaphoreSlim readLock =
new SemaphoreSlim(1, 1);
/// <summary>
/// Creates calibration parameter reader using
/// provided data storage configuration.
/// </summary>
/// <param name="config">
/// Data storage configuration loaded from gci_config.json.
/// </param>
public PreAdjustmentCalibrationParamsReader(
DataStorageConfig config)
{
if (config == null)
throw new ArgumentNullException(nameof(config));
reader = DataStorageReaderFactory.Create(config);
}
/// <summary>
/// Reads all pre-adjustment calibration parameters
/// using the provided data query asynchronously.
///
/// The query is expected to contain meter size
/// as the first lookup parameter.
/// </summary>
/// <param name="query">
/// Data query containing lookup parameter values.
/// </param>
/// <param name="token">
/// Cancellation token.
/// </param>
/// <returns>
/// Dictionary:
///
/// Key:
/// GENESISFLOW parameter name
///
/// Value:
/// Stored parameter value
/// </returns>
public async Task<Dictionary<string, UInt32>> ReadCalibrationParamsAsync(
DataQuery query,
CancellationToken token = default)
{
ValidateQuery(query);
return await Task.Run(
() => GetCalibrationParams(query),
token).ConfigureAwait(false); ;
/*await readLock.WaitAsync(token);
try
{
return await Task.Run(
() => GetCalibrationParams(query),
token);
}
finally
{
readLock.Release();
}*/
}
/// <summary>
/// Reads all pre-adjustment calibration parameters
/// using the provided data query.
///
/// The query is expected to contain meter size
/// as the first lookup parameter.
/// </summary>
/// <param name="query">
/// Data query containing lookup parameter values.
/// </param>
/// <returns>
/// Dictionary:
///
/// Key:
/// GENESISFLOW parameter name
///
/// Value:
/// Stored parameter value
/// </returns>
public Dictionary<string, UInt32> GetCalibrationParams(
DataQuery query)
{
ValidateQuery(query);
object result =
reader.GetData(query);
return ConvertResultToDictionary(result);
}
/// <summary>
/// Validates that data query exists
/// and contains at least one lookup parameter.
/// </summary>
/// <param name="query">
/// Data query to validate.
/// </param>
private static void ValidateQuery(
DataQuery query)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
if (query.QueryParams == null ||
query.QueryParams.Count == 0)
{
throw new ArgumentException(
"Query does not contain any parameter.",
nameof(query));
}
}
/// <summary>
/// Converts provider-specific result objects
/// returned by IDataStorageReader into a unified
/// dictionary representation.
/// </summary>
/// <param name="result">
/// Raw result returned by the configured storage reader.
/// </param>
/// <returns>
/// Dictionary containing calibration parameter
/// name/value pairs.
/// </returns>
private Dictionary<string, UInt32> ConvertResultToDictionary(
object result)
{
Dictionary<string, UInt32> values =
new Dictionary<string, UInt32>();
if (result == null)
return values;
if (result is DatabaseSearchResult dbResult)
{
if (!dbResult.Found)
return values;
foreach (Dictionary<string, object> row in dbResult.Rows)
{
if (!row.TryGetValue("ParameterName", out object parameterNameObject))
continue;
if (!row.TryGetValue("ParameterValue", out object parameterValueObject))
continue;
string parameterName =
parameterNameObject?.ToString();
if (string.IsNullOrWhiteSpace(parameterName))
continue;
if (TryConvertToUInt32(parameterValueObject, out UInt32 parameterValue))
{
values[parameterName] =
parameterValue;
}
}
return values;
}
if (result is ReaderDiagnosticResult diagnosticResult)
{
if (diagnosticResult.Data is Dictionary<string, UInt32> uintDictionary)
return uintDictionary;
if (diagnosticResult.Data is Dictionary<string, string> stringDictionary)
{
foreach (var item in stringDictionary)
{
if (TryConvertToUInt32(item.Value, out UInt32 value))
values[item.Key] = value;
}
return values;
}
if (diagnosticResult.Data is Dictionary<string, object> objectDictionary)
{
foreach (var item in objectDictionary)
{
if (TryConvertToUInt32(item.Value, out UInt32 value))
values[item.Key] = value;
}
return values;
}
}
if (result is Dictionary<string, UInt32> directUIntDictionary)
return directUIntDictionary;
if (result is Dictionary<string, string> directStringDictionary)
{
foreach (var item in directStringDictionary)
{
if (TryConvertToUInt32(item.Value, out UInt32 value))
values[item.Key] = value;
}
return values;
}
if (result is Dictionary<string, object> directObjectDictionary)
{
foreach (var item in directObjectDictionary)
{
if (TryConvertToUInt32(item.Value, out UInt32 value))
values[item.Key] = value;
}
}
return values;
}
private static bool TryConvertToUInt32(
object value,
out UInt32 result)
{
result = 0;
if (value == null)
return false;
if (value is UInt32 uintValue)
{
result = uintValue;
return true;
}
if (value is int intValue && intValue >= 0)
{
result = Convert.ToUInt32(intValue);
return true;
}
if (value is long longValue &&
longValue >= 0 &&
longValue <= UInt32.MaxValue)
{
result = Convert.ToUInt32(longValue);
return true;
}
return UInt32.TryParse(
value.ToString(),
out result);
}
}
}
@@ -0,0 +1,73 @@
using GenesisCordonelInterface.API;
using GenesisCordonelInterface.Core.Config;
using GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UdsReaderType_CalibrationParams = GenesisCordonelInterface.Core.DataStorage.Reading.Implementation.PreAdjustmentCalibrationParams.PreAdjustmentCalibrationParamsReader;
using UdsReaderType_LoginPasswords = GenesisCordonelInterface.Core.DataStorage.Reading.Implementation.MeterLoginPasswords.MeterLoginPasswordReader;
using GciPublicModels = GenesisCordonelInterface.API.PublicModels;
using GciEnums = GenesisCordonelInterface.API.Enums;
using GciType = GenesisCordonelInterface.API.InterfaceOutsideToGCI;
using GciDataStorageReadingModels = GenesisCordonelInterface.Core.DataStorage.Reading.Common.Models;
using GciGUIType = GenesisCordonelInterface.UI.MainView;
namespace GenesisCordonelInterface.Core
{
public class Engine
{
GciConfig gciConfig;
public UdsReaderType_LoginPasswords loginPasswordsDataStorageReader;
public UdsReaderType_CalibrationParams calibrationParamsStorageReader;
//readonly UdsWriterType writer;
//diag GUI for GCI
GciGUIType gciGUI;
Form gciGuiHostForm;
//diag GUI for GciBridge
public UserControl gciBridgeGUIUserControl;
public UI.MainForm gciBridgeGuiForm;
public InterfaceOutsideToGCI gciExternalInterface;
/// <summary>
/// Initializes a new instance of the public GCI facade.
/// </summary>
public Engine()
{
gciConfig = GciConfigLoader.LoadDefault();
loginPasswordsDataStorageReader = new UdsReaderType_LoginPasswords
(
new GciDataStorageReadingModels.DataStorageConfig
(
nameof(GciEnums.DataStorageReaderTypes.LoginPasswordsReader),
GciDataStorageReadingModels.DataStorageType.LocalDatabase,
gciConfig.DataStorageSection.MeterLoginPasswords.DataSource,
gciConfig.DataStorageSection.MeterLoginPasswords.QueryTemplate
)
);
calibrationParamsStorageReader = new UdsReaderType_CalibrationParams
(
new GciDataStorageReadingModels.DataStorageConfig
(
nameof(GciEnums.DataStorageReaderTypes.CalibrationParamsReader),
GciDataStorageReadingModels.DataStorageType.LocalDatabase,
gciConfig.DataStorageSection.PreAdjustmentCalibrationParams.DataSource,
gciConfig.DataStorageSection.PreAdjustmentCalibrationParams.QueryTemplate
)
);
gciExternalInterface = new InterfaceOutsideToGCI(
new InterfaceGCIToLaatzen(),
loginPasswordsDataStorageReader,
calibrationParamsStorageReader);
}
}
}
@@ -0,0 +1,23 @@
Navod na logovanie projektu Laatzen/Common/ pre Genesis Cordonel meradla:
1. Princip:
- logovanie je zabezpecene pomocou nastroja NLog, ktory pouziva Laatzen
- Laatzen vsak pouziva nad NLogom svoj wrapper NLogHelper.cs a teda sa na pracu pri ich projektoch konfiguruje NLog pomocou ich suboru Nlogconfig.xml,
no nakolko ja som nechcel zasahovat do ich konfiguracneho suboru NLogu, pouzil som svoj, ktory je definovany v mojom projekte GenesisCordonelInterface,
s nazvom nlog.config
- z dovodu, ze som teda nechcel zasahovat do ich konfiguracie a zaroven som musel NLog na svoje ucely (presmerovanie logov do mema v mojom projekte),
musel som teda konfigurovat svojim konfiguracnym suborom, a zaroven plati ze pouzivam raw NLog.
- btw ked som pouzil ich wrapper a zaroven moj konfiguracny subor NLogu, tak pri spusten appky ho aj nacitalo, no nasledne sa nacitali Laatzenacke projekty
a nacital sa aj ich konfigurak Nlogu, ci sa prepisal ten moj. Pouzil som ten raw Nlog a uz to bolo ok
- takto je mozne presmerovat pomocou nizsie uvedenej metody logy az do mema v mojom projekte a tiez aj do suboru, pricom vsetko definujem v nlog.config
mojho projektu a nie v projekte Laatzenu
2. prilozene subory UiLogBus.cs a UiTarget.cs musia byt nakopirovane do projektu v ramci Solution s nazvom Common od Laatzenu
- kopiruju sa do top adresara projektu
- musia obsahovat ""namespace Xylem.Common.Utils.Logging"
- v mieste kde chcem logovat, je potrebne:
- zadefinovat:
private readonly ILogger Logger = NLogHelper.CreateOrGetLogger("GenesisCordonelInterface");
- pouzit log:
Logger.Error(ex, $"Slot #{slotNR} failed: {ex.Message}");
Logger.Trace("CONFIG: Setup loaded.");
Logger.Info("CONFIG: Setup loaded.");
...whatever
@@ -0,0 +1,18 @@
using System;
/*namespace Xylem.Common.Utils.Logging
{
public static class UiLogBus
{
public static event Action<string> MessageReceived;
public static void Publish(string message)
{
var handler = MessageReceived;
if (handler != null)
{
handler(message);
}
}
}
}*/
@@ -0,0 +1,15 @@
using NLog;
using NLog.Targets;
/*namespace Xylem.Common.Utils.Logging
{
[Target("UiTarget")]
public class UiTarget : TargetWithLayout
{
protected override void Write(LogEventInfo logEvent)
{
string message = Layout.Render(logEvent);
UiLogBus.Publish(message);
}
}
}*/
@@ -0,0 +1,364 @@
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace GenesisCordonelInterface.Core.Threading
{
/*
ApiWorker per-slot sequential execution worker
This class provides a lightweight background worker that executes actions
sequentially on a dedicated thread.
PRIMARY PURPOSE
---------------
ApiWorker is designed to safely execute hardware-related operations
(e.g. meter communication) without blocking the UI thread and without
allowing concurrent access to the same device.
Each ApiWorker instance typically represents:
1 worker = 1 slot = 1 meter = 1 communication channel
KEY PROPERTIES
--------------
- Single dedicated background thread
- FIFO queue (first-in, first-out)
- Sequential execution (NO parallelism inside one worker)
- Thread-safe enqueueing
- Task-based async interface for callers
WHY THIS IS IMPORTANT
--------------------
Hardware communication (serial ports, meters, etc.) is usually NOT thread-safe.
If multiple commands are executed in parallel, communication may break or corrupt data.
ApiWorker guarantees:
- operations are executed one-by-one
- order is preserved
- no race conditions on the device
HIGH-LEVEL FLOW
---------------
Caller (UI/API)
|
v
RunAsync(...)
|
v
TaskCompletionSource created
|
v
Action wrapped into queue item
|
v
Added to BlockingCollection queue
|
v
Worker thread consumes queue
|
v
Action executed (blocking HW call)
|
v
Result propagated via TaskCompletionSource
|
v
Caller receives result via await
GRAPH
-----
Caller thread (UI)
|
v
RunAsync()
|
v
Queue (BlockingCollection)
|
v
-----------------------------
| Worker Thread (background)|
| while(queue) |
| Execute Action |
-----------------------------
|
v
Task result (await)
THREADING MODEL
---------------
- Producer/Consumer pattern
- Producer: any thread calling RunAsync
- Consumer: single worker thread
- Synchronization handled by BlockingCollection
MAIN COMPONENTS
---------------
1. BlockingCollection<Action> queue
- thread-safe queue
- stores work items
- supports blocking consumption
2. Dedicated Thread
- runs WorkerLoop()
- continuously processes queue
3. TaskCompletionSource<T>
- bridges sync execution → async API
- allows caller to await result
METHODS
-------
RunAsync<T>(Func<T>)
--------------------
- Enqueues a function returning a value
- Wraps it into Action
- Executes on worker thread
- Returns Task<T> to caller
RunAsync(Action)
----------------
- Convenience overload for void methods
- Internally wraps into Func<object>
WorkerLoop()
------------
- Infinite loop consuming queue
- Executes actions one-by-one
- Stops when queue is completed
Dispose()
---------
- Stops accepting new items
- Cleans up queue
- Does NOT forcibly stop running task
CANCELLATION
------------
- CancellationToken is checked BEFORE execution
- If cancelled → Task is cancelled
- Does NOT interrupt running operation
IMPORTANT LIMITATIONS
--------------------
- No parallel execution inside one worker (by design)
- Long-running action blocks worker thread
- No built-in timeout handling
- Dispose does not abort running work
WHEN TO USE
-----------
✔ Per-device communication (serial, TCP, HW)
✔ Ordered execution required
✔ UI must stay responsive
WHEN NOT TO USE
---------------
✘ CPU parallel processing (use Task.Run / Parallel)
✘ High-throughput parallel workloads
✘ Fire-and-forget background tasks
SUMMARY
-------
ApiWorker is a simple, robust solution for:
"Execute commands sequentially per resource, asynchronously from UI"
It is a perfect fit for:
- hardware interfaces
- device drivers
- IO-bound serialized workflows
*/
public sealed class ApiWorker : IDisposable
{
private static readonly NLog.ILogger Logger = NLog.LogManager.GetLogger("GenesisCordonelInterface-threading");
/// <summary>
/// Thread-safe FIFO queue holding work items.
/// </summary>
private readonly BlockingCollection<Action> queue = new BlockingCollection<Action>();
/// <summary>
/// Dedicated worker thread processing the queue.
/// </summary>
private readonly Thread thread;
/// <summary>
/// Indicates whether this worker has been disposed.
/// </summary>
private bool disposed;
public string Name { get; private set; }
public int QueueLength
{
get
{
if (disposed || queue == null)
return 0;
try
{
return queue.Count;
}
catch (ObjectDisposedException)
{
return 0;
}
}
}
public bool IsBusy { get; private set; }
public string CurrentOperation { get; private set; }
public string LastError { get; private set; }
public DateTime LastActivity { get; private set; }
public bool IsDisposed
{
get { return disposed; }
}
/// <summary>
/// Creates a new ApiWorker with its own background thread.
/// </summary>
public ApiWorker(string name)
{
Name = name;
LastActivity = DateTime.Now;
thread = new Thread(WorkerLoop)
{
IsBackground = true,
Name = name
};
thread.Start();
}
/// <summary>
/// Enqueues a function returning a value for sequential execution.
/// </summary>
public Task<T> RunAsync<T>(
Func<T> action,
CancellationToken token = default,
string operationName = null)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
if (disposed)
throw new ObjectDisposedException(nameof(ApiWorker));
var tcs = new TaskCompletionSource<T>(
TaskCreationOptions.RunContinuationsAsynchronously);
try
{
Debug.WriteLine($"ENQUEUE {operationName} slot worker={Name} time={DateTime.Now:HH:mm:ss.fff}");
queue.Add(() =>
{
if (token.IsCancellationRequested)
{
tcs.TrySetCanceled();
return;
}
try
{
IsBusy = true;
CurrentOperation = operationName ?? action.Method.Name;
LastActivity = DateTime.Now;
LastError = null;
var result = action();
tcs.TrySetResult(result);
}
catch (Exception ex)
{
LastError = ex.Message;
tcs.TrySetException(ex);
}
finally
{
IsBusy = false;
CurrentOperation = null;
LastActivity = DateTime.Now;
}
}, token);
}
catch (ObjectDisposedException ex)
{
tcs.TrySetException(ex);
}
catch (InvalidOperationException ex)
{
tcs.TrySetException(new ObjectDisposedException(nameof(ApiWorker), ex));
}
return tcs.Task;
}
public Task RunAsync(
Action action,
CancellationToken token = default(CancellationToken),
string operationName = null)
{
return RunAsync<object>(() =>
{
action();
return null;
}, token, operationName);
}
/// <summary>
/// Enqueues a void action for sequential execution.
/// </summary>
public Task RunAsync(Action action, CancellationToken token = default)
{
return RunAsync<object>(() =>
{
action();
return null;
}, token);
}
/// <summary>
/// Main worker loop processing queued actions.
/// </summary>
private void WorkerLoop()
{
try
{
foreach (var item in queue.GetConsumingEnumerable())
{
if (item == null)
continue;
item();
}
}
catch (ObjectDisposedException)
{
// worker is shutting down
}
}
/// <summary>
/// Stops the worker and releases resources.
/// </summary>
public void Dispose()
{
if (disposed)
return;
disposed = true;
queue.CompleteAdding();
if (Thread.CurrentThread != thread && thread.IsAlive)
thread.Join(1000);
queue.Dispose();
}
}
}
@@ -0,0 +1,150 @@
using System;
using System.Threading.Tasks;
namespace GenesisCordonelInterface.Core.Threading
{
public sealed class RetryResult<T>
{
public T Result { get; set; }
public bool Success { get; set; }
public int Attempts { get; set; }
public TimeSpan Duration { get; set; }
public bool TimedOut { get; set; }
public override string ToString()
{
return string.Format(
"Success={0}, Attempts={1}, Duration={2} ms, TimedOut={3}, Result={4}",
Success,
Attempts,
(int)Duration.TotalMilliseconds,
TimedOut,
Result == null ? "<null>" : Result.ToString());
}
}
public static class RetryWorker
{
/// <summary>
/// Executes an asynchronous operation with retry and timeout protection.
///
/// Important:
/// The timeout here protects the caller from waiting forever, but it does not forcibly abort
/// the underlying hardware operation. Because hardware/COM calls may continue running after
/// the timeout signal, this method waits for the original action to finish before starting
/// the next retry. This prevents overlapping COM requests on the same device.
/// </summary>
public static async Task<RetryResult<T>> RunWithRetryAsync<T>(
Func<Task<T>> action,
Func<T, bool> isSuccess,
Action<string> log,
Action<string, T> logResult,
string operationName,
int maxAttempts = 3,
int delayMs = 500,
int timeoutMs = 30000)
{
var started = DateTime.Now;
T lastResult = default(T);
bool timedOut = false;
for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
Task<T> actionTask = null;
try
{
log?.Invoke($"{operationName} started. Attempt {attempt}/{maxAttempts}");
// Start real operation, for example Connect/GetPcbId/Login.
actionTask = action();
// Start independent timeout timer.
var timeoutTask = Task.Delay(timeoutMs);
// Wait until either operation completes or timeout expires.
var completedTask = await Task.WhenAny(actionTask, timeoutTask)
.ConfigureAwait(false);
if (completedTask == timeoutTask)
{
timedOut = true;
log?.Invoke(
$"{operationName} timed out. Attempt {attempt}/{maxAttempts}. " +
"Waiting for the running operation to finish before retry.");
// Critical part:
// Do NOT immediately start another retry.
// The hardware operation may still be active in ApiWorker.
// Starting another attempt immediately could corrupt communication.
try
{
lastResult = await actionTask.ConfigureAwait(false);
}
catch (Exception ex)
{
log?.Invoke(
$"{operationName} finished after timeout with exception: " +
$"{ex.GetType().Name}: {ex.Message}");
}
}
else
{
// Operation completed before timeout.
lastResult = await actionTask.ConfigureAwait(false);
}
// Decide whether the returned result means success.
if (lastResult != null && isSuccess(lastResult))
{
return new RetryResult<T>
{
Result = lastResult,
Success = true,
Attempts = attempt,
Duration = DateTime.Now - started,
TimedOut = timedOut
};
}
logResult?.Invoke(
$"{operationName} failed. Attempt {attempt}/{maxAttempts}",
lastResult);
}
catch (Exception ex)
{
// Covers exceptions thrown before timeout handling or by action startup.
log?.Invoke(
$"{operationName} exception on attempt {attempt}/{maxAttempts}: " +
$"{ex.GetType().Name}: {ex.Message}");
}
// Delay before next retry, except after the final attempt.
if (attempt < maxAttempts)
{
log?.Invoke($"{operationName} waiting {delayMs} ms before retry.");
await Task.Delay(delayMs).ConfigureAwait(false);
}
}
return new RetryResult<T>
{
Result = lastResult,
Success = false,
Attempts = maxAttempts,
Duration = DateTime.Now - started,
TimedOut = timedOut
};
}
public static void EnsureSuccess<T>(
RetryResult<T> retryResult,
string operationName)
{
if (!retryResult.Success)
throw new Exception($"{operationName} failed after {retryResult.Attempts} attempts.");
}
}
}
@@ -0,0 +1,332 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C955D8AC-76B8-42D8-A83F-8AEB56CF2567}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>GenesisCordonelInterface</RootNamespace>
<AssemblyName>GenesisCordonelInterface</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<LangVersion>7.3</LangVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Common">
<HintPath>..\packages\Common\Common.dll</HintPath>
</Reference>
<Reference Include="Logic.ProductionToProductMapper">
<HintPath>..\packages\Common\Logic.ProductionToProductMapper.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="NLog, Version=5.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.5.2.2\lib\net46\NLog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="Xylem.Common.CommonCore">
<HintPath>..\packages\Common\Xylem.Common.CommonCore.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.CommonCore.Configuration">
<HintPath>..\packages\Common\Xylem.Common.CommonCore.Configuration.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.CommonCore.ThreadWatcher">
<HintPath>..\packages\Common\Xylem.Common.CommonCore.ThreadWatcher.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.Interfaces.Ports.PortCore">
<HintPath>..\packages\Common\Xylem.Common.Hardware.Interfaces.Ports.PortCore.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.Interfaces.Ports.SerialPorts">
<HintPath>..\packages\Common\Xylem.Common.Hardware.Interfaces.Ports.SerialPorts.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.Genesis.Applications">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.Genesis.Applications.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.Genesis.Registers">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.Genesis.Registers.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.WaterMeterCore">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.WaterMeterCore.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.WaterMeterRegisters">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.WaterMeterRegisters.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Logic.ProductionOrderCore">
<HintPath>..\packages\Common\Xylem.Common.Logic.ProductionOrderCore.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Logic.SoftwareAccessHelper">
<HintPath>..\packages\Common\Xylem.Common.Logic.SoftwareAccessHelper.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Utils.ByteArrayStyle">
<HintPath>..\packages\Common\Xylem.Common.Utils.ByteArrayStyle.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Utils.Crc16Ccitt">
<HintPath>..\packages\Common\Xylem.Common.Utils.Crc16Ccitt.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Utils.Logging">
<HintPath>..\packages\Common\Xylem.Common.Utils.Logging.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Utils.ProcessExec">
<HintPath>..\packages\Common\Xylem.Common.Utils.ProcessExec.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="API\ModelsMapping.cs" />
<Compile Include="API\InterfaceOutsideToGCI.cs" />
<Compile Include="API\InterfaceGCIToLaatzen.cs" />
<Compile Include="API\PublicModels.cs" />
<Compile Include="Core\Config\GciConfig.cs" />
<Compile Include="Core\Config\GciConfigLoader.cs" />
<Compile Include="Core\DataStorage\Config\GciDataStorageConfig.cs" />
<Compile Include="API\Enums.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Providers\CsvDataStorageReader.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Providers\DatabaseDataStorageReader.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Models\DatabaseSearchResult.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Models\DataQuery.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Models\DataStorageConfig.cs" />
<Compile Include="Core\DataStorage\Reading\Common\DataStorageReaderFactory.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Models\DataStorageType.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Contracts\IDataStorageReader..cs" />
<Compile Include="Core\DataStorage\Reading\Common\Providers\JsonDataStorageReader.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Models\ReaderDiagnosticResult.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Providers\RestApiDataStorageReader.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Searching\SearchOrderDefinition.cs" />
<Compile Include="Core\DataStorage\Reading\Common\Searching\SearchOrderParser.cs" />
<Compile Include="Core\DataStorage\Reading\Implementation\MeterLoginPasswords\IMeterLoginPasswordReader.cs" />
<Compile Include="Core\DataStorage\Reading\Implementation\MeterLoginPasswords\MeterLoginPasswordReader.cs" />
<Compile Include="Core\DataStorage\Reading\Implementation\PreAdjustmentCalibrationParams\IPreAdjustmentCalibrationParamsReader.cs" />
<Compile Include="Core\DataStorage\Reading\Implementation\PreAdjustmentCalibrationParams\PreAdjustmentCalibrationParamsReader.cs" />
<Compile Include="Core\Engine\Engine.cs" />
<Compile Include="Core\Logging\UiLogBus.cs" />
<Compile Include="Core\Logging\UiTarget.cs" />
<Compile Include="Core\Threading\ApiWorker\ApiWorker.cs" />
<Compile Include="Core\Threading\RetryWorker\RetryWorker.cs" />
<Compile Include="UI\Debug\MeterBatchConfigPanel.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="UI\Debug\MeterBatchConfigPanel.Designer.cs">
<DependentUpon>MeterBatchConfigPanel.cs</DependentUpon>
</Compile>
<Compile Include="UI\Debug\WorkerDebugPanel.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="UI\Debug\WorkerDebugPanel.Designer.cs">
<DependentUpon>WorkerDebugPanel.cs</DependentUpon>
</Compile>
<Compile Include="UI\Grid\MeterGridColumnConfig.cs" />
<Compile Include="UI\Grid\MeterGridConfigProvider.cs" />
<Compile Include="UI\Grid\MeterGridManager.cs" />
<Compile Include="UI\Grid\MeterRowDto.cs" />
<Compile Include="UI\LaatzenAPI_GenesisToolBox\FrmConfigurations.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="UI\LaatzenAPI_GenesisToolBox\FrmConfigurations.Designer.cs">
<DependentUpon>FrmConfigurations.cs</DependentUpon>
</Compile>
<Compile Include="UI\LaatzenAPI_CordonelPreadjustmentUI\FrmCordonelPreadjustmentUI.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="UI\LaatzenAPI_CordonelPreadjustmentUI\FrmCordonelPreadjustmentUI.Designer.cs">
<DependentUpon>FrmCordonelPreadjustmentUI.cs</DependentUpon>
</Compile>
<Compile Include="UI\LaatzenAPI_GenesisToolBox\FrmRegisterStore.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="UI\LaatzenAPI_GenesisToolBox\FrmRegisterStore.Designer.cs">
<DependentUpon>FrmRegisterStore.cs</DependentUpon>
</Compile>
<Compile Include="UI\LaatzenAPI_GenesisToolBox\FrmSetup.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="UI\LaatzenAPI_GenesisToolBox\FrmSetup.Designer.cs">
<DependentUpon>FrmSetup.cs</DependentUpon>
</Compile>
<Compile Include="UI\MainForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="UI\MainForm.Designer.cs">
<DependentUpon>MainForm.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UI\LaatzenAPI_CordonelPreadjustmentUI\PreAdjustmentControl.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="UI\LaatzenAPI_CordonelPreadjustmentUI\PreAdjustmentControl.Designer.cs">
<DependentUpon>PreAdjustmentControl.cs</DependentUpon>
</Compile>
<Compile Include="UI\MainView.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="UI\MainView.Designer.cs">
<DependentUpon>MainView.cs</DependentUpon>
</Compile>
<Compile Include="UI\StaraTuraAPI_GenesisCordonelInterface\FrmGCIAPI.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="UI\StaraTuraAPI_GenesisCordonelInterface\FrmGCIAPI.Designer.cs">
<DependentUpon>FrmGCIAPI.cs</DependentUpon>
</Compile>
<Compile Include="UI\StaraTuraAPI_GenesisCordonelInterface\MeterInitView.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="UI\StaraTuraAPI_GenesisCordonelInterface\MeterInitView.Designer.cs">
<DependentUpon>MeterInitView.cs</DependentUpon>
</Compile>
<Compile Include="UI\StaraTuraAPI_GenesisCordonelInterface\MetersActionView.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="UI\StaraTuraAPI_GenesisCordonelInterface\MetersActionView.Designer.cs">
<DependentUpon>MetersActionView.cs</DependentUpon>
</Compile>
<Content Include="docs\images\GciBridge_component_GUI.png" />
<Content Include="docs\images\GCI__Onboarding_Overview_drawio.svg" />
<Content Include="docs\images\GCI__Onboarding_Overview_drawio__API_architecture__Current_state.svg" />
<Content Include="docs\images\GCI__Onboarding_Overview_drawio__API_architecture__Target_state.svg" />
<Content Include="docs\images\GCI__Onboarding_Overview_drawio__Data_collection_domain.svg" />
<Content Include="docs\images\GCI__Onboarding_Overview_drawio__Meter_management_domain.svg" />
<Content Include="docs\images\logo\logo.png" />
<Content Include="docs\images\logo\logo.svg" />
<Content Include="docs\images\logo\sensus-logo-white-green-rgb.png" />
<Content Include="docs\images\logo\sensus-logo-white-green-rgb.svg" />
<Content Include="docs\styles\main.css" />
<Content Include="RuntimePackage\Build\Copy.targets.xml" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<EmbeddedResource Include="UI\LaatzenAPI_GenesisToolBox\FrmSetup.resx">
<DependentUpon>FrmSetup.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="UI\MainForm.resx">
<DependentUpon>MainForm.cs</DependentUpon>
</EmbeddedResource>
<Content Include="Core\Logging\ImportantInstructions.txt" />
<Content Include="nlog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<EmbeddedResource Include="UI\LaatzenAPI_CordonelPreadjustmentUI\PreAdjustmentControl.resx">
<DependentUpon>PreAdjustmentControl.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="UI\StaraTuraAPI_GenesisCordonelInterface\FrmGCIAPI.resx">
<DependentUpon>FrmGCIAPI.cs</DependentUpon>
</EmbeddedResource>
<Content Include="Core\Config\gci_config.json">
<Link>Config\gci_config.json</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="Core\Config\gci_config.json" />
<None Include="docs\articles\API\index.md" />
<None Include="docs\articles\API\PublicModels.md" />
<None Include="docs\articles\API\InterfaceGCIToLaatzen.md" />
<None Include="docs\articles\API\InterfaceOutsideToGCI.md" />
<None Include="docs\docfx.json" />
<None Include="docs\index.md" />
<None Include="docs\pages\development\page_dev__current_state.md" />
<None Include="docs\pages\development\page_dev__home.md" />
<None Include="docs\pages\development\page_dev__target_state.md" />
<None Include="docs\pages\development\page_dev__migration.md" />
<None Include="docs\pages\development\page_dev__refactoring.md" />
<None Include="docs\pages\development\page_dev__target_architecture.md" />
<None Include="docs\pages\gci\page_gci__app_environment.md" />
<None Include="docs\pages\gci\page_gci__internal_architecture.md" />
<None Include="docs\pages\gci\page_gci__datastorage.md" />
<None Include="docs\pages\gci\page_gci__home.md" />
<None Include="docs\pages\gci\page_gci__interfaces.md" />
<None Include="docs\pages\gci\page_gci__runtime.md" />
<None Include="docs\pages\gci\page_gci__implementation_to_tbf.md" />
<None Include="docs\pages\gci\page_gci__implementation_universal.md" />
<None Include="docs\pages\gci\page_gci__workers.md" />
<None Include="docs\pages\platform\page_platform__configuration_domain.md" />
<None Include="docs\pages\platform\page_platform__data_collection_domain.md" />
<None Include="docs\pages\platform\page_platform__tbf_implementation.md" />
<None Include="docs\pages\platform\page_platform__current_state.md" />
<None Include="docs\pages\platform\page_platform__home.md" />
<None Include="docs\toc.yml" />
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<Folder Include="Config\" />
<Folder Include="Core\DataStorage\Writing\NewFolder1\" />
<Folder Include="RuntimePackage\Package\" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Connected Services\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ExternalProjects\Laatzen\Genesis\Common\CordonelPreadjustmentUi\CordonelPreadjustmentUi.csproj">
<Project>{D0C8D887-ED52-40AB-A069-90BCE0E801E2}</Project>
<Name>CordonelPreadjustmentUi</Name>
</ProjectReference>
<ProjectReference Include="..\ExternalProjects\Laatzen\Genesis\Common\Ui\GenesisToolBox\GenesisToolBox.csproj">
<Project>{95A50087-99EE-4349-9A17-C547290DB42F}</Project>
<Name>GenesisToolBox</Name>
</ProjectReference>
</ItemGroup>
<!-- Import custom GCI runtime packaging logic -->
<Import Project="RuntimePackage\Build\Copy.targets.xml" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
+22
View File
@@ -0,0 +1,22 @@
using GenesisCordonelInterface.UI;
using NLog;
using System;
using System.Windows.Forms;
using Xylem.Common.Utils.Logging;
using System.IO;
namespace GenesisCordonelInterface
{
static class Program
{
private static readonly ILogger Logger = NLogHelper.CreateOrGetLogger("GenesisCordonelInterface");
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GenesisCordonelInterface")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Windows Org")]
[assembly: AssemblyProduct("GenesisCordonelInterface")]
[assembly: AssemblyCopyright("Copyright © Windows Org 2026")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c955d8ac-76b8-42d8-a83f-8aeb56cf2567")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GenesisCordonelInterface.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GenesisCordonelInterface.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
+26
View File
@@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GenesisCordonelInterface.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.14.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,38 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="CopyGciRuntimeToRuntimePackage" AfterTargets="Build">
<PropertyGroup>
<GciRuntimePackageDir>$(ProjectDir)RuntimePackage\Package\</GciRuntimePackageDir>
<TbfPackageCommonDir>$(ProjectDir)..\packages\Common\</TbfPackageCommonDir>
</PropertyGroup>
<MakeDir Directories="$(GciRuntimePackageDir)" />
<MakeDir Directories="$(TbfPackageCommonDir)" />
<ItemGroup>
<GciRuntimeFiles Include="$(TargetDir)*.dll" />
<GciRuntimeFiles Include="$(TargetDir)*.pdb" />
<GciRuntimeFiles Include="$(TargetDir)*.xml" />
<GciRuntimeFiles Include="$(TargetDir)*.exe" />
<GciRuntimeFiles Include="$(TargetDir)*.config" />
<GciRuntimeFiles Include="$(TargetDir)*.json" />
</ItemGroup>
<Message Text="Copying GCI runtime package to $(GciRuntimePackageDir)" Importance="High" />
<Copy
SourceFiles="@(GciRuntimeFiles)"
DestinationFolder="$(GciRuntimePackageDir)"
SkipUnchangedFiles="false"
OverwriteReadOnlyFiles="true" />
<Message Text="Copying GCI runtime package to TBF package common: $(TbfPackageCommonDir)" Importance="High" />
<Copy
SourceFiles="@(GciRuntimeFiles)"
DestinationFolder="$(TbfPackageCommonDir)"
SkipUnchangedFiles="false"
OverwriteReadOnlyFiles="true" />
</Target>
</Project>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="NLog" publicKeyToken="5120e14c03d0593c" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Xylem.Common.CommonCore" publicKeyToken="null" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.8.18.17954" newVersion="2.8.18.17954" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/></startup></configuration>

Some files were not shown because too many files have changed in this diff Show More