laatzen/Common/Service/MeterProcessState/Controllers/FinalCheckController.cs
2025-06-30 10:26:44 +02:00

1638 lines
73 KiB
C#

using LaaPackages.SqlClient;
using Logic.ProductionToProductMapper.Cordonel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
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.TestResults;
using Xylem.Common.Logic.ProductionOrderCore.Vako;
using Xylem.Common.Logic.ServiceCore;
namespace Xylem.Common.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
);
}
///// <summary>
///// Get the values to correct battery usage in field
///// </summary>
///// <param name="pcbID">PcbID from Meter</param>
///// <returns></returns>
//[Route("GetPowermonCorrectionData"), HttpGet]
//public async Task<HttpResponseMessage> GetPowermonCorrectionData(String pcbID)
//{
// try
// {
// return await Task.Run(() =>
// {
// using (var dataAccess = new SqlDataAccess(GlobalConfig.ConnectionString.Value))
// {
// var sb = new StringBuilder();
// sb.AppendLine($" SELECT distinct[MapPcbIdToSerialNumber_SerialNumber], mapOrder.CordonelPressureTest_FertigungsAuftragsNr ");
// sb.AppendLine($" FROM Auftrag.dbo.Cordonel_PressureTest mapOrder ");
// sb.AppendLine($" left outer join [Auftrag].[dbo].[MapPcbIdToSerialNumber] map on mapOrder.CordonelPressureTest_PcbId = map.MapPcbIdToSerialNumber_PcbId ");
// sb.AppendLine($" left outer join Auftrag.dbo.AuftragPositionSerienNr mapSrn on map.[MapPcbIdToSerialNumber_SerialNumber] = mapSrn.SerienNr and mapSrn.Pruefgangnr = 0 ");
// sb.AppendLine($" left outer join Auftrag.dbo.AlleAuftragPositionen auftraginfo on auftraginfo.AuftragNr = mapSrn.AuftragNr and auftraginfo.PositionNr = mapSrn.PositionNr ");
// sb.AppendLine($" where mapOrder.CordonelPressureTest_PcbId = '{pcbID}'");
// var mapData = dataAccess.ExecuteQuery(sb.ToString());
// if (mapData.Rows.Count != 1)
// {
// throw new ApplicationException("No base data found");
// }
// orderNr = (Int32)mapData.Rows[0]["CordonelPressureTest_FertigungsAuftragsNr"];
// }
// return Request.CreateResponse(HttpStatusCode.OK, ret);
// });
// }
// catch (Exception ex)
// {
// return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
// }
//}
//LocalWebRequest
/// <summary>
/// Get Radio Configuration from database matching the PcbID
/// </summary>
/// <param name="pcbID">PcbID from Meter</param>
/// <returns></returns>
[Route("GetProgrammingParameters"), HttpGet] // 244839518
public async Task<HttpResponseMessage> GetProgrammingParameters(String pcbID)
{
try
{
return await Task.Run(() =>
{
var builder = new StringBuilder();
var ret = OrderProgrammingParameters.GetProgrammingParameters(pcbID, GlobalConfig.ConnectionString.Value);
foreach (var r in ret.Where(r => r.RegisterName == "SENSUSRADIO_EncryptionKey"))
{
foreach (var t in r.RegisterValue)
{
builder.Append(t.ToString("x2"));
}
break;
}
return Request.CreateResponse(HttpStatusCode.OK, ret);
});
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
}
//LocalWebRequest
/// <summary>
/// Get Radio Configuration from database matching the PcbID
/// </summary>
/// <param name="pcbID">PcbID from Meter</param>
/// <returns></returns>
[Route("GetProgrammingParametersFixNa"), HttpGet]
public async Task<HttpResponseMessage> GetProgrammingParametersFixNa()
{
try
{
return await Task.Run(() =>
{
var builder = new StringBuilder();
var ret = OrderProgrammingParameters.GetProgrammingParametersFixNa(GlobalConfig.ConnectionString.Value);
foreach (var r in ret.Where(r => r.RegisterName == "SENSUSRADIO_EncryptionKey"))
{
foreach (var t in r.RegisterValue)
{
builder.Append(t.ToString("x2"));
}
break;
}
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("GetEncryptionKey"), HttpGet]
public async Task<HttpResponseMessage> GetEncryptionKey(String PcbID)
{
try
{
return await Task.Run(() =>
{
var builder = new StringBuilder();
var ret = OrderProgrammingParameters.GetProgrammingParameters(PcbID, GlobalConfig.ConnectionString.Value);
var key = ret.FirstOrDefault(r => r.RegisterName == "SENSUSRADIO_EncryptionKey" && r.Source == ProgrammingSource.Csd) ??
ret.FirstOrDefault(r => r.RegisterName == "SENSUSRADIO_EncryptionKey" && r.Source == ProgrammingSource.Vako);
if (key != null)
{
foreach (var t in key.RegisterValue)
{
builder.Append(t.ToString("x2"));
}
}
return Request.CreateResponse(HttpStatusCode.OK, builder.ToString());
});
}
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, Boolean withPressure)
{
try
{
return await Task.Run(() =>
{
var radio = OrderRadioParameter.GetRadioParams(PcbID, GlobalConfig.ConnectionString.Value, withPressure ? "p" : "");
if (radio != null)
{
if (radio.EncryptionKey != null)
{
var builder = new StringBuilder();
foreach (var t in radio.EncryptionKey)
{
builder.Append(t.ToString("x2"));
}
}
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 = (Int64)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(Int32 ProductionOrderNumber, Int32? CheckPcbId = null)
{
try // 3243648 251919004
{
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 distinct [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 = (Int32)row["menge"];
ret.AssignedPicking = (Int32)row["AssignedPicking"];
ret.PressureTested = (Int32)row["PressureTested"];
ret.HeliumTested = (Int32)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(Int32? 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(Int32 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_PCBRADIOTEST_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())
{
var jsonString = item["JSON"].ToString();
var jResults = JsonConvert.DeserializeObject<JToken>(jsonString);
if (DateTimeOffset.TryParse(jResults["JsonObject"]["StartDT"].ToString(), out ret))
{
return ret;
}
}
return DateTimeOffset.MinValue;
}));
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
}
}
[Route("GetPossibleRadioLengths"), HttpGet]
public async Task<HttpResponseMessage> GetPossibleRadioLengths(Int32 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());
Int32? 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(Int32 ProductionOrderNumber, Int32? 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(Int32 ProductionOrderNumber, Int32? CheckPcbId)
{
var ignorProductionDate = new DateTime();
return GetPickingItem(ProductionOrderNumber, CheckPcbId, out ignorProductionDate);
}
private PickingCompareItem GetPickingItem(Int32 ProductionOrderNumber, Int32? 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 ");
sb.AppendLine($" Id, ");
sb.AppendLine($" RadioFrequencyMhz, ");
sb.AppendLine($" FlexnetAppId, ");
sb.AppendLine($" Version, ");
sb.AppendLine($" Deleted ");
sb.AppendLine($" FROM Cordonel_CurrentFw ");
sb.AppendLine($" where Deleted is null ");
sb.AppendLine($" and RadioFrequencyMhz = {FrequencyIndicator} ");
sb.AppendLine($" and Metersize = {MeterSize} ");
sb.AppendLine($" and CurrentForProd = 1 ");
var checkAppsData = dataacces.ExecuteQuery(sb.ToString());
foreach (DataRow row in checkAppsData.Rows)
{
UInt32 AppID = uint.MaxValue;
UInt32 Version = uint.MaxValue;
if (uint.TryParse(row["FlexnetAppId"].ToString(), out AppID) && uint.TryParse(row["Version"].ToString(), out Version))
{
checkAppsIdVersion.Add(AppID, Version);
}
}
if (CheckPcbId.HasValue)
{
var SkipRadioCheck = false;
sb = new StringBuilder();
sb.AppendLine($" select [id] ");
sb.AppendLine($" ,[OrderNumber] ");
sb.AppendLine($" ,[PcbId] ");
sb.AppendLine($" ,[SkipRadioParameters] ");
sb.AppendLine($" ,[SkipFWCheck] ");
sb.AppendLine($" ,[SkipBatteyCheck] ");
sb.AppendLine($" ,[SkipLUT] ");
sb.AppendLine($" ,[Date] ");
sb.AppendLine($" ,[Name] ");
sb.AppendLine($" FROM [Auftrag].[dbo].[CordonelSkipChecks] ");
sb.AppendLine($" where ");
sb.AppendLine($" (OrderNumber = {ProductionOrderNumber} or OrderNumber is null) ");
sb.AppendLine($" and (PcbId = {CheckPcbId.Value} or PcbId is null) ");
var dt = dataacces.ExecuteQuery(sb.ToString());
if (dt.Rows.Count == 1)
{
//invert is a skip not a do value
SkipRadioCheck = (Boolean)dt.Rows[0]["SkipRadioParameters"];
}
if (FrequencyIndicator == 0)
{
SkipRadioCheck = true;
}
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 ");
dt = dataacces.ExecuteQuery(sb.ToString());
//"StartDT":"29.07.2022 06:47:27"
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" || LengthString == "300"))
{
hitAmbi = findMatchingTestResult(ref lastProdDate, "200", dnString, radioTestResult);
}
}
}
}
}
if (SkipRadioCheck)
{
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();//
}
try
{
sb = new StringBuilder();
sb.AppendLine(" SELECT top 1 [DS_ID] ,[ID_PCB] ,[ID_TEST] ,[JSON] FROM [MyOraDB]..[DELTACHEF].[GENESIS_PCBFUNCTIONALTEST_PD] ");
sb.AppendLine($" where [ID_PCB] = '{CheckPcbId.Value}' ");
sb.AppendLine(" order by ID_TEST desc ");
var dtPrdDate = dataacces.ExecuteQuery(sb.ToString());
if (dtPrdDate.Rows.Count == 1)
{
var St = dtPrdDate.Rows[0]["JSON"].ToString();
var startInex = St.IndexOf("\"StartDT\":\"") + "\"StartDT\":\"".Length;
var datestring = St.Substring(startInex, "29.07.2022 06:47:27".Length);
DateTime.TryParse(datestring, out lastProdDate);
}
}
catch (Exception)
{
throw;
}
dateTime = lastProdDate;
return new PickingCompareItem(MeterSize, FrequencyIndicator, PressurePresent, checkAppsIdVersion);
}
}
private static Boolean findMatchingTestResult(ref DateTime lastProdDate, String LengthString, String dnString, RadioTest radioTestResult)
{
var TestStepLoopCalibratesOk = radioTestResult.TestStepLoopCalibrate.Values.Where(w => w != null && w.ResultCalibration != null && w.LengthCode != 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 = TestStepLoopCalibratesOk.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("SetMeterEOLState"), HttpPost]
public async Task<HttpResponseMessage> SetMeterEOLState(int PcbID, int OrderNumber)
{
try
{
var sb = new StringBuilder();
sb.AppendLine($" UPDATE [dbo].[CordonelEol] ");
sb.AppendLine($" SET ");
sb.AppendLine($" [CordonelEolPcbId] = {PcbID} ");
sb.AppendLine($" ,[CordonelEolOrderNumber] = {OrderNumber} ");
sb.AppendLine($" ,[CordonelEolDate] = CURRENT_TIMESTAMP ");
sb.AppendLine($" ,[CordonelEolPublishAction] = null ");
sb.AppendLine($" ,[CordonelEolSAPFeedback] = null ");
sb.AppendLine($" WHERE [CordonelEolPcbId] = {PcbID} ");
sb.AppendLine($" and [CordonelEolOrderNumber] = {OrderNumber} ");
sb.AppendLine($"IF @@ROWCOUNT = 0 ");
sb.AppendLine($" BEGIN ");
sb.AppendLine($" INSERT INTO [dbo].[CordonelEol] ");
sb.AppendLine($" ([CordonelEolPcbId] ");
sb.AppendLine($" ,[CordonelEolOrderNumber] ");
sb.AppendLine($" ,[CordonelEolDate] ");
sb.AppendLine($" ,[CordonelEolPublishAction] ");
sb.AppendLine($" ,[CordonelEolSAPFeedback]) ");
sb.AppendLine($" VALUES ");
sb.AppendLine($" ( {PcbID} ");
sb.AppendLine($" ,{OrderNumber} ");
sb.AppendLine($" ,CURRENT_TIMESTAMP ");
sb.AppendLine($" ,null ");
sb.AppendLine($" ,null) ");
sb.AppendLine($" END ");
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("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 distinct 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(Int32 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(Int32 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<Int64> { };
for (Int32 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 Int64[] Digits { get; set; }
public Dictionary<String, String> Values { get; set; }
}
private static void GetVakoProgramming(Int32 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());
}
}
[HttpGet]
[Route("CalibrationResultsFromRun/{CalibrationResultId}")]
public IHttpActionResult CalibrationResultsFromRun(int CalibrationResultId)
{
var result = SqlConnection
.CreateSqlConnection(GlobalConfig.ConnectionString.Value)
.CreateCommand($@"
SELECT TOP 1
ID
, PcbId
, CalFactor1
, CalFactor2
, CalFactor3
, ZeroOffset1
, ZeroOffset2
, ZeroOffset3
, FirstHitUpdatePeriod
, FirstHitShift
, FirstHitPercent1
, FirstHitPercent2
, FirstHitPercent3
, ToFTempOffset1
, ToFTempOffset2
, ToFTempOffset3
, MeterSize
, date
, successful
FROM CordonelMeterCalibrationResults
WHERE successful = 1
AND ID = @{nameof(CalibrationResultId)}
ORDER BY date DESC")
.SetParameter(nameof(CalibrationResultId), CalibrationResultId)
.FirstOrDefault(x => new CalibrationResults
{
Id = x.GetValue<Int32>(0),
PcbId = x.GetValue<String>(1),
CalFactor1 = x.GetValue<UInt16>(2),
CalFactor2 = x.GetValue<UInt16>(3),
CalFactor3 = x.GetValue<UInt16>(4),
ZeroOffset1 = x.GetValue<Int32>(5),
ZeroOffset2 = x.GetValue<Int32>(6),
ZeroOffset3 = x.GetValue<Int32>(7),
FirstHitUpdatePeriod = x.GetValue<Byte>(8),
FirstHitShift = x.GetValue<Byte>(9),
FirstHitPercent1 = x.GetValue<Byte>(10),
FirstHitPercent2 = x.GetValue<Byte>(11),
FirstHitPercent3 = x.GetValue<Byte>(12),
ToFTempOffset1 = x.GetValue<Int32>(13),
ToFTempOffset2 = x.GetValue<Int32>(14),
ToFTempOffset3 = x.GetValue<Int32>(15),
MeterSize = x.GetValue<Byte>(16),
Date = x.GetValue<DateTime>(17),
Succeeded = x.GetValue<Boolean>(18),
});
if (result is null)
{
return this.NotFound();
}
return this.Json(result);
}
[HttpGet]
[Route("CalibrationResults/{pcbId}")]
public IHttpActionResult CalibrationResults(string pcbId)
{
var result = SqlConnection
.CreateSqlConnection(GlobalConfig.ConnectionString.Value)
.CreateCommand($@"
SELECT res.ID
, res.PcbId
, ISNULL(resQ3.P1Cal, res.CalFactor1)
, ISNULL(resQ3.P2Cal, res.CalFactor2)
, ISNULL(resQ3.P3Cal, res.CalFactor3)
, res.ZeroOffset1
, res.ZeroOffset2
, res.ZeroOffset3
, res.FirstHitUpdatePeriod
, res.FirstHitShift
, res.FirstHitPercent1
, res.FirstHitPercent2
, res.FirstHitPercent3
, res.ToFTempOffset1
, res.ToFTempOffset2
, res.ToFTempOffset3
, res.MeterSize
, res.date
, res.successful
FROM CordonelMeterCalibrationResults AS res
LEFT JOIN Cordonel_Q3Calibration AS resQ3
ON res.PcbId = resQ3.PcbId
WHERE res.successful = 1
AND res.PcbId = @{nameof(pcbId)}
ORDER BY res.date DESC, resQ3.Date DESC")
.SetParameter(nameof(pcbId), pcbId)
.FirstOrDefault(x => new CalibrationResults
{
Id = x.GetValue<int>(0),
PcbId = x.GetValue<string>(1),
CalFactor1 = x.GetValue<ushort>(2),
CalFactor2 = x.GetValue<ushort>(3),
CalFactor3 = x.GetValue<ushort>(4),
ZeroOffset1 = x.GetValue<int>(5),
ZeroOffset2 = x.GetValue<int>(6),
ZeroOffset3 = x.GetValue<int>(7),
FirstHitUpdatePeriod = x.GetValue<byte>(8),
FirstHitShift = x.GetValue<byte>(9),
FirstHitPercent1 = x.GetValue<byte>(10),
FirstHitPercent2 = x.GetValue<byte>(11),
FirstHitPercent3 = x.GetValue<byte>(12),
ToFTempOffset1 = x.GetValue<int>(13),
ToFTempOffset2 = x.GetValue<int>(14),
ToFTempOffset3 = x.GetValue<int>(15),
MeterSize = x.GetValue<byte>(16),
Date = x.GetValue<DateTime>(17),
Succeeded = x.GetValue<bool>(18),
});
if (result is null)
{
return this.NotFound();
}
const ushort DEFAULT_CAL_FACTOR = 15625;
if (result.CalFactor1 == DEFAULT_CAL_FACTOR && result.CalFactor2 == DEFAULT_CAL_FACTOR && result.CalFactor3 == DEFAULT_CAL_FACTOR)
{
ushort CalFactorOrDefault(string hexString)
{
ushort calFactor;
try
{
var hexBytes = hexString.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
Array.Resize(ref hexBytes, 2);
Array.Reverse(hexBytes);
hexString = string.Join(string.Empty, hexBytes);
calFactor = Convert.ToUInt16(hexString, 16);
}
catch
{
calFactor = DEFAULT_CAL_FACTOR;
}
return calFactor;
}
SqlConnection
.CreateSqlConnection(GlobalConfig.ConnectionString.Value)
.CreateCommand($@"
SELECT gmrh.PcbId
, gmrh1.Value AS Cal1
, gmrh2.Value AS Cal2
, gmrh3.Value AS Cal3
FROM MapPcbIdToSerialNumber AS map
JOIN (SELECT _map.MapPcbIdToSerialNumber_PcbId AS PcbId
, MAX(c1.ID) AS CalId1
, MAX(c2.ID) AS CalId2
, MAX(c3.ID) AS CalId3
FROM MapPcbIdToSerialNumber AS _map
LEFT JOIN GenesisMeterRegisterHistory AS c1
ON c1.Address = '0F-0D'
AND c1.Value IS NOT NULL
AND c1.Value <> 'NULL'
AND _map.MapPcbIdToSerialNumber_PcbId = c1.PcbId
LEFT JOIN GenesisMeterRegisterHistory AS c2
ON c2.Address = '0F-0E'
AND c2.Value IS NOT NULL
AND c2.Value <> 'NULL'
AND _map.MapPcbIdToSerialNumber_PcbId = c2.PcbId
LEFT JOIN GenesisMeterRegisterHistory AS c3
ON c3.Address = '0F-0F'
AND c3.Value IS NOT NULL
AND c3.Value <> 'NULL'
AND _map.MapPcbIdToSerialNumber_PcbId = c3.PcbId
WHERE _map.MapPcbIdToSerialNumber_PcbId = @{nameof(pcbId)}
GROUP BY _map.MapPcbIdToSerialNumber_PcbId)
AS gmrh
ON gmrh.PcbId = map.MapPcbIdToSerialNumber_PcbId
JOIN GenesisMeterRegisterHistory AS gmrh1 ON gmrh1.ID = gmrh.CalId1
JOIN GenesisMeterRegisterHistory AS gmrh2 ON gmrh2.ID = gmrh.CalId2
JOIN GenesisMeterRegisterHistory AS gmrh3 ON gmrh3.ID = gmrh.CalId3")
.SetParameter(nameof(pcbId), pcbId)
.FirstOrDefault(x =>
{
result.CalFactor1 = CalFactorOrDefault(x.GetValue<string>(1));
result.CalFactor2 = CalFactorOrDefault(x.GetValue<string>(2));
result.CalFactor3 = CalFactorOrDefault(x.GetValue<string>(3));
});
}
return this.Json(result);
}
// using (var dataacces = new SqlDataAccess(GlobalConfig.ConnectionString.Value))
// {
// var sbCal = new StringBuilder();
// sbCal.AppendLine(" select map.MapPcbIdToSerialNumber_PcbId, v1.Value as Cal1, v2.Value as Cal2, v3.Value as Cal3 from MapPcbIdToSerialNumber map ");
// sbCal.AppendLine(" ");
// sbCal.AppendLine(" inner join ");
// sbCal.AppendLine(" ( ");
// sbCal.AppendLine(" select map.MapPcbIdToSerialNumber_PcbId as mPcbid, max(c1.ID)as M1,max(c2.ID) as M2, max(c3.ID) as m3 from MapPcbIdToSerialNumber map ");
// sbCal.AppendLine(" left outer join GenesisMeterRegisterHistory c1 on c1.Address = '0F-0D' and map.MapPcbIdToSerialNumber_PcbId =c1.PcbId ");
// sbCal.AppendLine(" left outer join GenesisMeterRegisterHistory c2 on c2.Address = '0F-0E' and map.MapPcbIdToSerialNumber_PcbId =c2.PcbId ");
// sbCal.AppendLine(" left outer join GenesisMeterRegisterHistory c3 on c3.Address = '0F-0F' and map.MapPcbIdToSerialNumber_PcbId =c3.PcbId ");
// sbCal.AppendLine($" where map.MapPcbIdToSerialNumber_PcbId = '{pcbId}' ");
// sbCal.AppendLine(" group by MapPcbIdToSerialNumber_PcbId ) as maxT ");
// sbCal.AppendLine(" on mPcbid = map.MapPcbIdToSerialNumber_PcbId ");
// sbCal.AppendLine(" ");
// sbCal.AppendLine(" inner join GenesisMeterRegisterHistory v1 on v1.ID = M1 ");
// sbCal.AppendLine(" inner join GenesisMeterRegisterHistory v2 on v2.ID = M2 ");
// sbCal.AppendLine(" inner join GenesisMeterRegisterHistory v3 on v3.ID = M3
// var dt = dataacces.ExecuteQuery(sbCal.ToString());
// foreach (var item in dt.Select())
// {
// var strC1 = item["Cal1"].ToString();
// string strc1Coor = "";
// foreach (String hex in strC1.Split('-').Reverse().ToArray())
// {
// strc1Coor += hex;
// }
//result.CalFactor1 = Convert.ToUInt16(strc1Coor, 16);
// var strC2 = item["Cal2"].ToString();
//string strc2Coor = "";
// foreach (String hex in strC2.Split('-').Reverse().ToArray())
// {
// strc2Coor += hex;
// }
// result.CalFactor2 = Convert.ToUInt16(strc2Coor, 16);
// var strC3 = item["Cal3"].ToString();
//string strc3Coor = "";
// foreach (String hex in strC3.Split('-').Reverse().ToArray())
// {
// strc3Coor += hex;
// }
// result.CalFactor3 = Convert.ToUInt16(strc3Coor, 16);
// }
// }
}
}
//================================================================================================
//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
//================================================================================================
//================================================================================================