laatzen/Common/Service/MeterProcessState/Controllers/FinalCheckController.cs
2022-04-06 10:42:16 +02:00

1146 lines
48 KiB
C#

using Logic.ProductionToProductMapper.Cordonel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Service.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Xylem.Common.Logic.ProductionOrderCore;
using Xylem.Common.Logic.ProductionOrderCore.KitronTestResults;
using Xylem.Common.Logic.ProductionOrderCore.OrderData;
using Xylem.Common.Logic.ProductionOrderCore.Vako;
namespace Service.MeterProcessState.Controllers
{
[RoutePrefix("api/FinalCheck")]
public class FinalCheckController : ApiController
{
public static class GlobalConfig
{
public static Lazy<string> connectionString = new Lazy<string>(()
=>
System.Configuration.ConfigurationManager.ConnectionStrings["default"].ConnectionString
);
}
//LocalWebRequest
/// <summary>
/// Get Radio Configuration from database matching the PcbID
/// </summary>
/// <param name="PcbID">PcbID from Meter</param>
/// <returns></returns>
[Route("GetProgrammingParameters"), HttpGet]
public async Task<HttpResponseMessage> GetProgrammingParameters(string PcbID)
{
try
{
return await Task.Run(() =>
{
var ret = OrderProgrammingParameters.GetProgrammingParameters(PcbID, GlobalConfig.connectionString.Value);
return Request.CreateResponse(HttpStatusCode.OK, ret);
});
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Get Radio Configuration from database matching the PcbID
/// </summary>
/// <param name="PcbID">PcbID from Meter</param>
/// <returns></returns>
[Route("GetRadioConfiguration"), HttpGet]
public async Task<HttpResponseMessage> GetRadioConfiguration(string PcbID, bool withPressure)
{
try
{
return await Task.Run(() =>
{
var radio = OrderRadioParameter.GetRadioPramas(PcbID, GlobalConfig.connectionString.Value, withPressure ? "p" : "");
if (radio != null)
{
return Request.CreateResponse(HttpStatusCode.OK, radio);
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, $"no parameters found for pcb {PcbID}");
}
});
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Get Configuration from database matching the PcbID
/// </summary>
/// <param name="PcbID">PcbID from Meter</param>
/// <returns></returns>
[Route("GetConfiguration"), HttpGet]
public async Task<HttpResponseMessage> GetConfiguration(string PcbID)
{
try
{
return await Task.Run(() =>
{
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
var sb = new StringBuilder();
sb.AppendLine($" SELECT distinct [MapPcbIdToSerialNumber_SerialNumber],Adresse,FunkschluesselIndex ");
sb.AppendLine($" FROM [Auftrag].[dbo].[MapPcbIdToSerialNumber] pcb ");
sb.AppendLine($" inner join Genesis_Meter meter on meter.Seriennummer = pcb.MapPcbIdToSerialNumber_SerialNumber");
sb.AppendLine($" where [MapPcbIdToSerialNumber_PcbId] = '{PcbID}'");
var MapData = dataacces.ExecuteQuery(sb.ToString());
if (MapData.Rows.Count != 1)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Can not find unique serial number for your request");
}
//MapData.Rows[0]["Adresse"]
var ra = (long)MapData.Rows[0]["Adresse"] - 10000000000;
var resultDic = new Dictionary<string, object>();
resultDic.Add("SENSUSRADIO_RadioAddress", ra);
//E6 - C8 - 88 - 00 - DE - B8 - 68 - C0 - D6 - A8 - 48 - 80 - CE - 98 - 28 - 40
//14 - 30 - 68 - D0 - 14 - 0E-80 - 40 - 63 - 93 - 73 - 22
resultDic.Add("SENSUSRADIO_EncryptionKey", new Byte[] { 0x40, 0x28, 0x98, 0xCE, 0x00 });
//radio
//[Adresse]
//E6C88800DEB868C0D6A84880CE982840
return Request.CreateResponse(HttpStatusCode.OK, resultDic);
}
});
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}
[Route("GetOrderOverview"), HttpGet]
public async Task<HttpResponseMessage> GetOrderOverview(int ProductionOrderNumber, int? CheckPcbId = null)
{
try
{
return await Task.Run(async () =>
{
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
var sb = new StringBuilder();
sb.AppendLine(" Declare @OrderNr as int ");
sb.AppendLine($" set @OrderNr = {ProductionOrderNumber} ");
sb.AppendLine(" SELECT TOP (1000) [auftragnr], ");
sb.AppendLine(" [positionnr], ");
sb.AppendLine(" [menge], ");
sb.AppendLine(" (SELECT Count(*) ");
sb.AppendLine(" FROM [cordonel_assignedpicking] picking ");
sb.AppendLine(" WHERE picking.cordonelassignedpicking_fertigungsauftragsnr = ");
sb.AppendLine(" @OrderNr ");
sb.AppendLine(" AND picking.[cordonelassignedpicking_isdeleted] = 0) ");
sb.AppendLine(" AS AssignedPicking, ");
sb.AppendLine(" (SELECT Count(*) ");
sb.AppendLine(" FROM cordonel_pressuretest Pressure ");
sb.AppendLine(" WHERE Pressure.cordonelpressuretest_fertigungsauftragsnr = ");
sb.AppendLine(" @OrderNr ");
sb.AppendLine(" AND Pressure.[cordonelpressuretest_isdeleted] = 0 ");
sb.AppendLine(" AND Pressure.[CordonelPressureTest_Valid] = 1 ");
sb.AppendLine(" AND Pressure.[CordonelPressureTest_StationId] = 1 ");
sb.AppendLine(" ) AS PressureTested, ");
sb.AppendLine(" (SELECT Count(*) ");
sb.AppendLine(" FROM cordonel_pressuretest Pressure ");
sb.AppendLine(" WHERE Pressure.cordonelpressuretest_fertigungsauftragsnr = ");
sb.AppendLine(" @OrderNr ");
sb.AppendLine(" AND Pressure.[cordonelpressuretest_isdeleted] = 0 ");
sb.AppendLine(" AND Pressure.[CordonelPressureTest_Valid] = 1 ");
sb.AppendLine(" AND Pressure.[CordonelPressureTest_StationId] = 2 ");
sb.AppendLine(" ) AS HeliumTested ");
sb.AppendLine(" FROM [Auftrag].[dbo].[AlleAuftragPositionen] ");
sb.AppendLine(" WHERE [fertigungsauftragnr] = @OrderNr ");
var MapData = dataacces.ExecuteQuery(sb.ToString());
if (MapData.Rows.Count != 1)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Can not find unique serial number for your request");
}
var ret = new OrderOverViewCordonel();
ret.OrderNumber = ProductionOrderNumber;
ret.Count = 0;
ret.AssignedPicking = -1;
ret.PressureTested = -1;
ret.HeliumTested = -1;
foreach (DataRow row in MapData.Rows)
{
ret.Count = (int)row["menge"];
ret.AssignedPicking = (int)row["AssignedPicking"];
ret.PressureTested = (int)row["PressureTested"];
ret.HeliumTested = (int)row["HeliumTested"];
}
if (CheckPcbId.HasValue)
{
var ProductionDate = new DateTime();
var pickingItem = GetPickingItem(ProductionOrderNumber, CheckPcbId, out ProductionDate);
var doubleResponse = new OrderOverViewCordonelWithPicking() { KitronProductionDate = ProductionDate, OrderOverViewCordonel = ret, PickingCompareItem = pickingItem };
return Request.CreateResponse(HttpStatusCode.OK, doubleResponse);
}
return Request.CreateResponse(HttpStatusCode.OK, ret);
}
});
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
[Route("GetKitronProductionResults"), HttpGet]
public async Task<HttpResponseMessage> GetKitronProductionResults(int? SerialNumber = null, string PcbID = "")
{
try
{
var ret = new Dictionary<string, JObject>();
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() =>
{
var sb = new StringBuilder();
sb.AppendLine($" Declare @PcbID nvarchar(50) ");
if (!SerialNumber.HasValue)
{
if (string.IsNullOrEmpty(PcbID))
{
throw new ApplicationException("No identifier given");
}
else
{
sb.AppendLine($" set @PcbID = '{PcbID}' ");
}
}
else
{
sb.AppendLine($" SELECT top 1 @PcbID= mappcbIdToSerialNumber_PcbId ");
sb.AppendLine($" FROM MapPcbIdToSerialNumber ");
sb.AppendLine($" WHERE (MapPcbIdToSerialNumber_SerialNumber = {SerialNumber.Value}) ");
}
sb.AppendLine($" SELECT [DS_ID] ");
sb.AppendLine($" ,[ID_PCB] ");
sb.AppendLine($" ,[ID_TEST] ");
sb.AppendLine($" ,[JSON] ");
sb.AppendLine($" FROM [MyOraDB]..[DELTACHEF].[GENESIS_PCBMETROLOGYTEST_PD] ");
sb.AppendLine($" where [ID_PCB] = @PcbID ");
sb.AppendLine($" order by cast(ID_TEST as int) desc");
var dt = dataacces.ExecuteQuery(sb.ToString());
foreach (var item in dt.Select())
{
try
{
var jsonString = item["JSON"].ToString();
ret.Add(item["ID_TEST"].ToString(), JObject.Parse(jsonString));
}
catch (Exception)
{
}
}
return ret;
}));
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
[Route("GetKitronProductionDate"), HttpGet]
public async Task<HttpResponseMessage> GetKitronProductionDate(int CheckPcbId)
{
try
{
var ret = new DateTimeOffset();
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() =>
{
var sb = new StringBuilder();
sb.AppendLine($" SELECT top 1 [DS_ID] ");
sb.AppendLine($" ,[ID_PCB] ");
sb.AppendLine($" ,[ID_TEST] ");
sb.AppendLine($" ,[JSON] ");
sb.AppendLine($" FROM [MyOraDB]..[DELTACHEF].[GENESIS_PCBMETROLOGYTEST_PD] ");
sb.AppendLine($" where[ID_PCB] = '{CheckPcbId}' ");
sb.AppendLine($" order by cast(ID_TEST as int) desc");
var dt = dataacces.ExecuteQuery(sb.ToString());
foreach (var item in dt.Select())
{
try
{
var jsonString = item["JSON"].ToString();
JObject o = JObject.Parse(jsonString);
if (o.ContainsKey("StartDT") && DateTimeOffset.TryParse(o["StartDT"].ToString(), out ret))
{
return ret;
}
}
catch (Exception)
{
}
}
return DateTimeOffset.MinValue;
}));
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
[Route("GetPossibleRadioLengths"), HttpGet]
public async Task<HttpResponseMessage> GetPossibleRadioLengths(int CheckPcbId)
{
try
{
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
var sb = new StringBuilder();
sb.AppendLine(" declare @PcbId nvarchar(50) ");
sb.AppendLine($" set @PcbId= '{CheckPcbId}' ");
sb.AppendLine(" SELECT [DS_ID] ,[ID_PCB] ,[ID_TEST] ,[JSON] FROM [MyOraDB]..[DELTACHEF].[GENESIS_PCBRADIOTEST_PD] ");
sb.AppendLine(" where [ID_PCB] = @PcbId ");
sb.AppendLine(" order by ID_TEST desc ");
var dt = dataacces.ExecuteQuery(sb.ToString());
int? frq = null;
var listLength = new List<string>();
foreach (var item in dt.Select())
{
try
{
var jsonString = item["JSON"].ToString();
var radioTestResult = RadioTest.FromJson(jsonString);
if (radioTestResult.TestResult != Result.Fail)
{
foreach (var radioTestItem in radioTestResult.TestStepLoopCalibrate.Values.Where(w => w.ResultCalibration.ToLower() == "ok"))
{
listLength.Add(radioTestItem.LengthCode);
if (!frq.HasValue && radioTestItem.SLookupTablePower != null)
{
if (radioTestItem.SLookupTablePower.Contains("433"))
{
frq = 433;
}
else if (radioTestItem.SLookupTablePower.Contains("868"))
{
frq = 868;
}
}
}
}
}
catch (Exception)
{
}
}
var sbRet = new List<string>();
foreach (var item in listLength)
{
var dn = item.Substring(0, 4);
foreach (var lengthcodeAdd in item.Substring(4, item.Length - 4).Split('|'))
{
if (!sbRet.Contains(dn + lengthcodeAdd))
{
sbRet.Add(dn + lengthcodeAdd);
}
}
}
sbRet = sbRet.OrderBy(a => a).ToList();
var stext = "";
sbRet.ForEach(a => stext = stext + a + ";");
//2992 2936
dt = dataacces.ExecuteQuery($"insert into tmpRadioInventur select '{CheckPcbId}', '{stext}', {frq}");
return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return stext; }));
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
[Route("GetOrderDetails"), HttpGet]
public async Task<HttpResponseMessage> GetOrderDetails(int ProductionOrderNumber, int? CheckPcbId = null)
{
try
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, await Task.Run(() => { return GetPickingItem(ProductionOrderNumber, CheckPcbId); }));
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
private PickingCompareItem GetPickingItem(int ProductionOrderNumber, int? CheckPcbId)
{
var ignorProductionDate = new DateTime();
return GetPickingItem(ProductionOrderNumber, CheckPcbId, out ignorProductionDate);
}
private PickingCompareItem GetPickingItem(int ProductionOrderNumber, int? CheckPcbId, out DateTime dateTime)
{
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
var lastProdDate = new DateTime();
List<ProgrammingParameters> programming = new List<ProgrammingParameters>();
GetVakoProgramming(ProductionOrderNumber, dataacces, programming);
var MeterSize = BitConverter.ToUInt32(programming.Find(a => a.RegisterName == "GENESISFLOW_MeterSize").RegisterValue.Reverse().ToArray(), 0);
var p = programming.FirstOrDefault(a => a.RegisterName == "SENSUSRADIO_FrequencyIndicator");
UInt32 FrequencyIndicator = 0;
if (p != null)
{
FrequencyIndicator = BitConverter.ToUInt32(p.RegisterValue.Reverse().ToArray(), 0);
}
var PressurePresent = BitConverter.ToBoolean(programming.Find(a => a.RegisterName == "METROLOGYASST_PressurePresent").RegisterValue.Reverse().ToArray(), 0);
Dictionary<UInt32, UInt32> checkAppsIdVersion = new Dictionary<UInt32, UInt32>();
var sb = new StringBuilder();
sb.AppendLine($" SELECT TOP(200) ");
sb.AppendLine($" CordonelCurrentFw_ID, ");
sb.AppendLine($" CordonelCurrentFw_Frequency, ");
sb.AppendLine($" CordonelCurrentFw_AppID, ");
sb.AppendLine($" CordonelCurrentFw_Version, ");
sb.AppendLine($" CordonelCurrentFw_Deleted ");
sb.AppendLine($" FROM Cordonel_CurrentFw ");
sb.AppendLine($" where CordonelCurrentFw_Deleted is null ");
sb.AppendLine($" and CordonelCurrentFw_Frequency = {FrequencyIndicator} ");
if (PressurePresent)
{
sb.AppendLine($" and CordonelCurrentFw_ForPressure = 1 ");
}
else
{
sb.AppendLine($" and CordonelCurrentFw_ForPressure = 0 ");
}
var checkAppsData = dataacces.ExecuteQuery(sb.ToString());
foreach (DataRow row in checkAppsData.Rows)
{
uint AppID = uint.MaxValue;
uint Version = uint.MaxValue;
if (uint.TryParse(row["CordonelCurrentFw_AppID"].ToString(), out AppID) && uint.TryParse(row["CordonelCurrentFw_Version"].ToString(), out Version))
{
checkAppsIdVersion.Add(AppID, Version);
}
}
if (CheckPcbId.HasValue)
{
sb = new StringBuilder();
sb.AppendLine(" declare @PcbId nvarchar(50) ");
sb.AppendLine(" declare @DN nvarchar(50) ");
sb.AppendLine(" declare @Length nvarchar(50) ");
sb.AppendLine($" set @PcbId= '{CheckPcbId.Value}' ");
sb.AppendLine($" SELECT distinct ");
sb.AppendLine($" @DN = ident.Nennweite, ");
sb.AppendLine($" @Length = ident.Baulaenge ");
sb.AppendLine($" from AuftragPositionSerienNr apinfo ");
sb.AppendLine($" inner join AuftragPosition_Gesamt ap on apinfo.AuftragNr = ap.AuftragNr and apinfo.PositionNr = ap.PositionNr ");
sb.AppendLine($" inner join [Identnr] ident on ap.Identnr = ident.IdentNr ");
sb.AppendLine($" where ap.FertigungsauftragNr = {ProductionOrderNumber}");
sb.AppendLine(" SELECT [DS_ID] ,[ID_PCB] ,[ID_TEST] ,[JSON], @DN as [DN] ,@Length as [Length] FROM [MyOraDB]..[DELTACHEF].[GENESIS_PCBRADIOTEST_PD] ");
sb.AppendLine(" where [ID_PCB] = @PcbId ");
sb.AppendLine(" order by ID_TEST desc ");
var dt = dataacces.ExecuteQuery(sb.ToString());
var hit = false;
var hitAmbi = false;
foreach (var item in dt.Select())
{
var jsonString = item["JSON"].ToString();
var LengthString = item["Length"].ToString();
var dnString = item["Dn"].ToString();
var radioTestResult = RadioTest.FromJson(jsonString);
//Radio test ist eine obsolete klasse das format hat sich geändert
if (radioTestResult == null || radioTestResult.StartDt == null)
{
if (radioTestResult.TestResult != Result.Fail)
{
hit = findMatchingTestResult(ref lastProdDate, LengthString, dnString, radioTestResult);
if (hit)
{
break;
}
else
{
//keien radioparameter für 270 aber 270 ist identisch mit 200 werten
if (dnString == "50" && LengthString == "270")
{
hitAmbi = findMatchingTestResult(ref lastProdDate, "200", dnString, radioTestResult);
}
}
}
}
else
{
if (radioTestResult.TestResult != Result.Fail)
{
hit = findMatchingTestResult(ref lastProdDate, LengthString, dnString, radioTestResult);
if (hit)
{
break;
}
else
{
//keien radioparameter für 270 aber 270 ist identisch mit 200 werten
if (dnString == "50" && LengthString == "270")
{
hitAmbi = findMatchingTestResult(ref lastProdDate, "200", dnString, radioTestResult);
}
}
}
}
}
if (CheckPcbId.Value == 18440026)
{
hit = true;
}
if (!hit)
{
//workaroudn for a year
if (!hitAmbi)
{
throw new Exception("No Radio Parameter found");
}
// return Request.CreateResponse(HttpStatusCode.ExpectationFailed, await Task.Run(() => { return "No radio parameter found!"; }));
}
//return new RadioConfigurationParams();//
}
dateTime = lastProdDate;
return new PickingCompareItem(MeterSize, FrequencyIndicator, PressurePresent, checkAppsIdVersion);
}
}
private static bool findMatchingTestResult(ref DateTime lastProdDate, string LengthString, string dnString, RadioTest radioTestResult)
{
var TestStepLoopCalibratesOk = radioTestResult.TestStepLoopCalibrate.Values.Where(w => w != null && w.ResultCalibration.ToLower() == "ok" && w.LengthCode.StartsWith($"DN{dnString}")).ToList();
//DN50-200
//DN50-270
var a = TestStepLoopCalibratesOk.Where(w => w.ResultCalibration.ToLower() == "ok" && w.LengthCode.StartsWith($"DN{dnString}") && w.LengthCode.Contains($"-{LengthString}") && !w.LengthCode.Contains($"-{LengthString}o")).ToList();
var ao = radioTestResult.TestStepLoopCalibrate.Values.Where(w => w != null && w.ResultCalibration.ToLower() == "ok" && w.LengthCode.StartsWith($"DN{dnString}") && w.LengthCode.Contains($"-{LengthString}o")).ToList();
if (a.Any() && ao.Any())
{
DateTime.TryParse(radioTestResult.StartDt, out lastProdDate);
return true;
}
if (a.Any() && !ao.Any())
{
DateTime.TryParse(radioTestResult.StartDt, out lastProdDate);
return true;
}
return false;
}
//[Route("SetMetersizeProgrammingDataAll"), HttpGet]
//public async Task<HttpResponseMessage> SetMetersizeProgrammingDataAll()
//{
// var listOfDnParams = new Dictionary<string, UInt32>();
// listOfDnParams.Add("GENESISFLOW_LowFlowMaxPeriod", (UInt32)3932160);
// listOfDnParams.Add("GENESISFLOW_LowFlowThreshold", (UInt32)200);
// listOfDnParams.Add("GENESISFLOW_MaxValidAmplitude", (UInt32)2936012800);
// listOfDnParams.Add("GENESISFLOW_MaxValidDeltaToF", (UInt32)247390);
// listOfDnParams.Add("GENESISFLOW_MaxValidToF", (UInt32)24739011);
// listOfDnParams.Add("GENESISFLOW_MinValidAmplitude", (UInt32)629145600);
// listOfDnParams.Add("GENESISFLOW_MinValidToF", (UInt32)13743895);
// listOfDnParams.Add("GENESISFLOW_Timeout", (UInt16)1);
// await SetMetersizeProgrammingData(MeterSize.DN40, listOfDnParams);
// await SetMetersizeProgrammingData(MeterSize.US1_5, listOfDnParams);
// listOfDnParams = new Dictionary<string, UInt32>();
// listOfDnParams.Add("GENESISFLOW_LowFlowMaxPeriod", (UInt32)3932160);
// listOfDnParams.Add("GENESISFLOW_LowFlowThreshold", (UInt32)200);
// listOfDnParams.Add("GENESISFLOW_MaxValidAmplitude", (UInt32)2936012800);
// listOfDnParams.Add("GENESISFLOW_MaxValidDeltaToF", (UInt32)247390);
// listOfDnParams.Add("GENESISFLOW_MaxValidToF", (UInt32)24739011);
// listOfDnParams.Add("GENESISFLOW_MinValidAmplitude", (UInt32)629145600);
// listOfDnParams.Add("GENESISFLOW_MinValidToF", (UInt32)13743895);
// listOfDnParams.Add("GENESISFLOW_Timeout", (UInt16)1);
// await SetMetersizeProgrammingData(MeterSize.DN50, listOfDnParams);
// await SetMetersizeProgrammingData(MeterSize.US2, listOfDnParams);
// listOfDnParams = new Dictionary<string, UInt32>();
// listOfDnParams.Add("GENESISFLOW_LowFlowMaxPeriod", (UInt32)3932160);
// listOfDnParams.Add("GENESISFLOW_LowFlowThreshold", (UInt32)260);
// listOfDnParams.Add("GENESISFLOW_MaxValidAmplitude", (UInt32)2936012800);
// listOfDnParams.Add("GENESISFLOW_MaxValidDeltaToF", (UInt32)402008);
// listOfDnParams.Add("GENESISFLOW_MaxValidToF", (UInt32)32160714);
// listOfDnParams.Add("GENESISFLOW_MinValidAmplitude", (UInt32)629145600);
// listOfDnParams.Add("GENESISFLOW_MinValidToF", (UInt32)17867064);
// listOfDnParams.Add("GENESISFLOW_Timeout", (UInt16)1);
// await SetMetersizeProgrammingData(MeterSize.DN65, listOfDnParams);
// listOfDnParams = new Dictionary<string, UInt32>();
// listOfDnParams.Add("GENESISFLOW_LowFlowMaxPeriod", (UInt32)3932160);
// listOfDnParams.Add("GENESISFLOW_LowFlowThreshold", (UInt32)500);
// listOfDnParams.Add("GENESISFLOW_MaxValidAmplitude", (UInt32)2936012800);
// listOfDnParams.Add("GENESISFLOW_MaxValidDeltaToF", (UInt32)494780);
// listOfDnParams.Add("GENESISFLOW_MaxValidToF", (UInt32)39582418);
// listOfDnParams.Add("GENESISFLOW_MinValidAmplitude", (UInt32)629145600);
// listOfDnParams.Add("GENESISFLOW_MinValidToF", (UInt32)21990232);
// listOfDnParams.Add("GENESISFLOW_Timeout", (UInt16)1);
// await SetMetersizeProgrammingData(MeterSize.DN80, listOfDnParams);
// await SetMetersizeProgrammingData(MeterSize.US3, listOfDnParams);
// listOfDnParams = new Dictionary<string, UInt32>();
// listOfDnParams.Add("GENESISFLOW_LowFlowMaxPeriod", (UInt32)3932160);
// listOfDnParams.Add("GENESISFLOW_LowFlowThreshold", (UInt32)400);
// listOfDnParams.Add("GENESISFLOW_MaxValidAmplitude", (UInt32)2936012800);
// listOfDnParams.Add("GENESISFLOW_MaxValidDeltaToF", (UInt32)618474);
// listOfDnParams.Add("GENESISFLOW_MaxValidToF", (UInt32)49478022);
// listOfDnParams.Add("GENESISFLOW_MinValidAmplitude", (UInt32)629145600);
// listOfDnParams.Add("GENESISFLOW_MinValidToF", (UInt32)27487790);
// listOfDnParams.Add("GENESISFLOW_Timeout", (UInt16)2);
// await SetMetersizeProgrammingData(MeterSize.DN100, listOfDnParams);
// await SetMetersizeProgrammingData(MeterSize.US4, listOfDnParams);
// listOfDnParams = new Dictionary<string, UInt32>();
// listOfDnParams.Add("GENESISFLOW_LowFlowMaxPeriod", (UInt32)3932160);
// listOfDnParams.Add("GENESISFLOW_LowFlowThreshold", (UInt32)600);
// listOfDnParams.Add("GENESISFLOW_MaxValidAmplitude", (UInt32)2936012800);
// listOfDnParams.Add("GENESISFLOW_MaxValidDeltaToF", (UInt32)927711);
// listOfDnParams.Add("GENESISFLOW_MaxValidToF", (UInt32)74217033);
// listOfDnParams.Add("GENESISFLOW_MinValidAmplitude", (UInt32)629145600);
// listOfDnParams.Add("GENESISFLOW_MinValidToF", (UInt32)41231685);
// listOfDnParams.Add("GENESISFLOW_Timeout", (UInt16)2);
// await SetMetersizeProgrammingData(MeterSize.DN150, listOfDnParams);
// await SetMetersizeProgrammingData(MeterSize.US6, listOfDnParams);
// listOfDnParams = new Dictionary<string, UInt32>();
// listOfDnParams.Add("GENESISFLOW_LowFlowMaxPeriod", (UInt32)3932160);
// listOfDnParams.Add("GENESISFLOW_LowFlowThreshold", (UInt32)800);
// listOfDnParams.Add("GENESISFLOW_MaxValidAmplitude", (UInt32)2936012800);
// listOfDnParams.Add("GENESISFLOW_MaxValidDeltaToF", (UInt32)1236948);
// listOfDnParams.Add("GENESISFLOW_MaxValidToF", (UInt32)98956044);
// listOfDnParams.Add("GENESISFLOW_MinValidAmplitude", (UInt32)629145600);
// listOfDnParams.Add("GENESISFLOW_MinValidToF", (UInt32)54975580);
// listOfDnParams.Add("GENESISFLOW_Timeout", (UInt16)2);
// await SetMetersizeProgrammingData(MeterSize.DN200, listOfDnParams);
// await SetMetersizeProgrammingData(MeterSize.US8, listOfDnParams);
// listOfDnParams = new Dictionary<string, UInt32>();
// listOfDnParams.Add("GENESISFLOW_LowFlowMaxPeriod", (UInt32)3932160);
// listOfDnParams.Add("GENESISFLOW_LowFlowThreshold", (UInt32)1200);
// listOfDnParams.Add("GENESISFLOW_MaxValidAmplitude", (UInt32)2936012800);
// listOfDnParams.Add("GENESISFLOW_MaxValidDeltaToF", (UInt32)1855422);
// listOfDnParams.Add("GENESISFLOW_MaxValidToF", (UInt32)148434066);
// listOfDnParams.Add("GENESISFLOW_MinValidAmplitude", (UInt32)629145600);
// listOfDnParams.Add("GENESISFLOW_MinValidToF", (UInt32)82463370);
// listOfDnParams.Add("GENESISFLOW_Timeout", (UInt16)2);
// await SetMetersizeProgrammingData(MeterSize.DN300, listOfDnParams);
// return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return listOfDnParams; }));
//}
[Route("SetMetersizeProgrammingData"), HttpPost]
public async Task<HttpResponseMessage> SetMetersizeProgrammingData(MeterSize ParameterMeterSize, [FromBody] string listOfDnParamsRaw)
{
try
{
var listOfDnParams = JsonConvert.DeserializeObject<Dictionary<string, UInt32>>(listOfDnParamsRaw);
var sb = new StringBuilder();
sb.AppendLine($" delete [Auftrag].[dbo].[CordonelMeterSizesParameter] where [Dn_InternalId] = { ParameterMeterSize.GetHashCode()} ");
foreach (var item in listOfDnParams)
{
sb.AppendLine($" insert into [Auftrag].[dbo].[CordonelMeterSizesParameter] ");
sb.AppendLine($" select {ParameterMeterSize.GetHashCode()}, '{item.Key}', {item.Value};");
}
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return dataacces.ExecuteQuery(sb.ToString()) != null; }));
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
[Route("GetMetersizeProgrammingData"), HttpGet]
public async Task<HttpResponseMessage> GetMetersizeProgrammingData(MeterSize MeterSize)
{
var programming = new Dictionary<string, UInt32>();
var sb = new StringBuilder();
try
{
sb.AppendLine($" SELECT size.[Dn_InternalId], para.DnParameterId, para.ParameterName, para.ParameterValue ");
sb.AppendLine($" FROM [Auftrag].[dbo].[CordonelMeterSizes] size ");
sb.AppendLine($" inner join [Auftrag].[dbo].[CordonelMeterSizesParameter] para on size.Dn_InternalId = para.[Dn_InternalId] ");
sb.AppendLine($" where size.[Dn_InternalId] = {MeterSize.GetHashCode()} ");
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
var MapData = dataacces.ExecuteQuery(sb.ToString());
foreach (DataRow row in MapData.Rows)
{
var tmp = (Int64)row["ParameterValue"];
programming.Add(row["ParameterName"].ToString(), Convert.ToUInt32(tmp));
}
return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return programming; }));
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
[Route("GetVakoPogramming"), HttpGet]
public async Task<HttpResponseMessage> GetVakoPogramming(int ProductionOrderNumber)
{
try
{
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
List<ProgrammingParameters> programming = new List<ProgrammingParameters>();
GetVakoProgramming(ProductionOrderNumber, dataacces, programming);
return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return programming; }));
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
[Route("GetSingleVakoKey"), HttpGet]
public async Task<HttpResponseMessage> GetSingleVakoKey(int ProductionOrderNumber, string KeyName)
{
try
{
return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() =>
{
var rawVako = VakoDbAdapter.GetRawVako(GlobalConfig.connectionString.Value, ProductionOrderNumber);
var rawMapping = VakoDbAdapter.GetVakoMapping(GlobalConfig.connectionString.Value, rawVako.Type);
var vakoData = VakoParser.Parse(rawVako, rawMapping);
var hitList = vakoData.KeyValues.FindAll(g => g.Name == KeyName);
if (hitList.Count != 1)
{
throw new ApplicationException("No unique Key found ");
}
return hitList.First();
}));
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
[Route("GetVakoMapping"), HttpGet]
public async Task<HttpResponseMessage> GetVakoMapping()
{
try
{
return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() =>
{
var ret = new List<VakoNew>();
var rawMapping = VakoDbAdapter.GetVakoMapping(GlobalConfig.connectionString.Value, "GNS");
var grpd = rawMapping.GroupBy(g => g.Name);
foreach (var item in grpd)
{
var l = item.ToList();
var digits = new List<long> { };
for (int i = 1; i <= l.First().Laenge; i++)
{
digits.Add(l.First().Stelle + i);
}
var d = new Dictionary<string, string>();
foreach (var lvalues in l)
{
try
{
d.Add(lvalues.Charcode, lvalues.Wert);
}
catch (Exception)
{
}
}
ret.Add(new VakoNew() { Name = item.Key, Digits = digits.ToArray(), Values = d });
}
return ret;
}));
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
public partial class VakoNew
{
public string Name { get; set; }
public long[] Digits { get; set; }
public Dictionary<string, string> Values { get; set; }
}
private static void GetVakoProgramming(int ProductionOrderNumber, SqlDataAccess dataacces, List<ProgrammingParameters> programming)
{
var rawVako = VakoDbAdapter.GetRawVako(GlobalConfig.connectionString.Value, ProductionOrderNumber);
var rawMapping = VakoDbAdapter.GetVakoMapping(GlobalConfig.connectionString.Value, rawVako.Type);
var vakoData = VakoParser.Parse(rawVako, rawMapping);
var sb = new StringBuilder();
sb.AppendLine($" SELECT ");
sb.AppendLine($" RegisterName ,");
sb.AppendLine($" RegisterValue ");
sb.AppendLine($" from [Auftrag].[dbo].[Cordonel_ProgrammingMapper] ");
sb.AppendLine($" where 1=0 ");
sb.AppendLine($" and RegisterName in ('GENESISFLOW_MeterSize','SENSUSRADIO_FrequencyIndicator','METROLOGYASST_PressurePresent') ");
foreach (var item in vakoData.KeyValues)
{
sb.AppendLine($" or (KEYNAME = '{item.Name}' and KeyValue = '{item.Charcode.Replace("\'", "\'\'")}') ");
}
var MapData = dataacces.ExecuteQuery(sb.ToString());
foreach (DataRow row in MapData.Rows)
{
programming.Add(new ProgrammingParameters(row["RegisterName"].ToString(), (byte[])row["RegisterValue"]));
}
}
[Route("GetLastState")]
public async Task<HttpResponseMessage> GetLastState(string PcbId)
{
try
{
return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() =>
{
using (var dataacces = new SqlDataAccess(GlobalConfig.connectionString.Value))
{
var dt = dataacces.ExecuteQuery($"select top 1 [ProcessState_State] from dbo.MeterProcessState where ProcessState_PcbId like '{PcbId}' order by ProcessState_DateUtc desc ");
foreach (var item in dt.Select())
{
return item["ProcessState_State"];
}
return 0;
}
}));
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex.ToString() + "<br >" + ex.InnerException.ToString());
}
}
}
}
//================================================================================================
//POST https://nodes.sms-esaap.com:8081/api/v3/custom/keysets
//BODY=============================================================================================
//{
// "setCount": 1,
// "keysPerSet": 7
//}
//RESP============================================================================================
//[
// {
// "SetId": "ae85624f-8926-47d9-9af7-b8c1c064b289",
// "Keys": [
// {
// "Index": 1,
// "Key": "71C7111E5524AC1EA3A03B57E26240B7200CD3618D44312903914399816128D8"
// },
// {
// "Index": 2,
// "Key": "BEB78A8732AA149930C669BB5EB02122CDFDCC5B1D502D6617DEF8E0517467C0"
// },
// {
// "Index": 3,
// "Key": "116A3EFB0A8339A17668743A12DC3C4F952C5D8EB2AA3393A07C62558897F960"
// },
// {
// "Index": 4,
// "Key": "CF5A5E0D445F0386C6A4BF7CC8A85B112F42EFF56C13D8F7A5891D779650D6BB"
// },
// {
// "Index": 5,
// "Key": "8CA83D7B2B3AA510E19B71A229482B37B9AD9941176D7997C627A70174CD7D04"
// },
// {
// "Index": 6,
// "Key": "28F7158DD1DAFAC8C5BD6A2B21580268149B208A7BB6E4CBE9B40A92AACCC89E"
// },
// {
// "Index": 7,
// "Key": "8A054BED70C53A5CA0A22775A02825758EE573B232D5AA7D07B356A6801082A6"
// }
// ]
// }
//]
//================================================================================================
//POST https://nodes.sms-esaap.com:8081/api/v3/custom/keysets/devices
//BODY============================================================================================
//[
// {
// "setId":"ae85624f-8926-47d9-9af7-b8c1c064b289",
// "orderNumber":"3118323",
// "radioAdress":"10412000048"
// }
//]
//RESP=============================================================================================
//[
// {
// "setId": "ae85624f-8926-47d9-9af7-b8c1c064b289",
// "radioAdress": "10412000048",
// "orderNumber": "3118323"
// }
//]
//================================================================================================
//GET https://nodes.sms-esaap.com:8081/api/v3/custom/keysetkeys?orderNumber=3118323&radioAdress=10412000048
//================================================================================================
//{
// "SetId": "ae85624f-8926-47d9-9af7-b8c1c064b289",
// "Keys": [
// {
// "Index": 1,
// "Key": "71C7111E5524AC1EA3A03B57E26240B7200CD3618D44312903914399816128D8"
// },
// {
// "Index": 2,
// "Key": "BEB78A8732AA149930C669BB5EB02122CDFDCC5B1D502D6617DEF8E0517467C0"
// },
// {
// "Index": 3,
// "Key": "116A3EFB0A8339A17668743A12DC3C4F952C5D8EB2AA3393A07C62558897F960"
// },
// {
// "Index": 4,
// "Key": "CF5A5E0D445F0386C6A4BF7CC8A85B112F42EFF56C13D8F7A5891D779650D6BB"
// },
// {
// "Index": 5,
// "Key": "8CA83D7B2B3AA510E19B71A229482B37B9AD9941176D7997C627A70174CD7D04"
// },
// {
// "Index": 6,
// "Key": "28F7158DD1DAFAC8C5BD6A2B21580268149B208A7BB6E4CBE9B40A92AACCC89E"
// },
// {
// "Index": 7,
// "Key": "8A054BED70C53A5CA0A22775A02825758EE573B232D5AA7D07B356A6801082A6"
// }
// ]
//}
//================================================================================================
//alle 8 Passwörter
//================================================================================================
//1: 71C7111E5524
//2: BEB78A8732AA
//3: ------------ <== SKELETON KEY !!!!!
//4: 116A3EFB0A83
//5: CF5A5E0D445F
//6: 8CA83D7B2B3A
//7: 28F7158DD1DA
//8: 8A054BED70C5
//================================================================================================
//hashen mit SHA1
//================================================================================================
//================================================================================================