using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Timers; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; using Newtonsoft.Json; using ProductionUiCordonel.Model; using Xylem.Common.CommonCore.Configuration; using Xylem.Common.CommonCore.Consts; using Xylem.Common.Hardware.Interfaces.Ports.PortCore; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore; using Xylem.Common.Hardware.WaterMeter.WaterMeterCore; using Xylem.Common.Logic.SoftwareAccessHelper; namespace ProductionUiCordonel { //public class QuantityToBackgroundConverter : IValueConverter //{ // public object Convert(object value, Type targetType, object parameter, CultureInfo culture) // { // var dc = DisplayCodes.None; // if (DisplayCodes.TryParse(value.ToString(), out dc)) // { // string hex = ""; // int intValue; // if (int.TryParse(value.ToString(), out intValue)) // { // hex = intValue.ToString("X"); // } // return $"{dc} ({hex})"; // } // else // { // return "?"; // } // } // public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) // { // throw new NotImplementedException(); // } //} /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow { private Timer tmrAutoDetect; public EventHandler OnPcbIdDetect; private Int32 intervalWithoutDetect = 1000; private Int32 intervalWithDetect = 10000; private String _currentPcbID; public PickingViewModel PickingData = new PickingViewModel(); public String CurrentPcbID { set { if (_currentPcbID != value && !(string.IsNullOrEmpty(_currentPcbID) && value == null)) { if (_currentPcbID != value) { if (!string.IsNullOrEmpty(_currentPcbID) && string.IsNullOrEmpty(value)) { _currentPcbID = value; updateUi(lblPcbID, _currentPcbID); } else { _currentPcbID = value; updateUi(lblPcbID, _currentPcbID); if (!string.IsNullOrEmpty(_currentPcbID)) { GetPcbMapping(_currentPcbID); } } } OnPcbIdDetect?.Invoke(CurrentPcbID, EventArgs.Empty); } } get => _currentPcbID; } public enum uiState { not_connected, connected } private uiState _currentState; public uiState CurrentState { set { _currentState = value; updateUi(lblState, _currentState.ToString()); } get => _currentState; } private String _lastMsg; public String LastMsg { set { _lastMsg = value; updateUi(lblMessage, _lastMsg); } get => _lastMsg; } public MainWindow() { try { if (true) { } InitializeComponent(); } catch (Exception ex) { MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace); } } public ApplicationSettings Settings { get; set; } private void Window_Initialized(Object sender, EventArgs e) { var configfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), nameof(Xylem.Common.Hardware.WaterMeter.Genesis), ProgramConfig.SerialConfigFileName); if (!File.Exists(configfile)) { throw new ApplicationException($"Configuration file {configfile} not found "); } var tr = new StreamReader(configfile); var meterConfigList = JsonConvert.DeserializeObject(tr.ReadToEnd()); cbxSlotBox.Items.Clear(); foreach (var item in meterConfigList.OrderBy(s => s.Slot)) { cbxSlotBox.Items.Add(item.Slot); } cbxSlotBox.SelectedIndex = 0; tmrAutoDetect = new Timer(intervalWithoutDetect); tmrAutoDetect.Elapsed += TmrAutoDetect_Elapsed; tmrAutoDetect.Enabled = false; Settings = new ApplicationSettings("ProductionUiConfig.json"); useSetting(true); } private void TmrAutoDetect_Elapsed(Object sender, ElapsedEventArgs e) { tmrAutoDetect.Enabled = false; var hasDetect = Detect(true, 1); if (hasDetect) { tmrAutoDetect.Interval = intervalWithDetect; } else { tmrAutoDetect.Interval = intervalWithoutDetect; } tmrAutoDetect.Enabled = Settings.AutoDetect; } private void BtnConnect_Click(Object sender, RoutedEventArgs e) { var hasDetect = Detect(false, (Int32)cbxSlotBox.SelectedValue); Settings.Slot = (Int32)cbxSlotBox.SelectedValue; storeSetting(); } private void updateUi(ContentControl c, String content) { c.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { c.Content = content; })); } private void updateUi(TextBox c, String content) { c.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { c.Text = content; })); } private void updateUi(TextBlock c, String content) { c.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { c.Text = content; })); } private MeterBatch CurrentBatch; private GenesisMeter _currentMeter; private Boolean detectIsLocked; private GenesisMeter CurrentMeter { get => _currentMeter; set { _currentMeter = value; if (ucFinalRadioTest != null) { if (_currentMeter?.PcbId != null) { ucFinalRadioTest.CurrentGenesisMeter = value; } else { ucFinalRadioTest.CurrentGenesisMeter = null; } } } } private Boolean Detect(Boolean ignoreErrors, Int32 slot) { if (!detectIsLocked) { LastMsg = "Start Detect"; Boolean hasDetect = false; if (string.IsNullOrEmpty(CurrentPcbID) || CurrentMeter == null) { var mb = new MeterBatch(); var tryMeter = new GenesisMeter(); try { tryMeter.SetupFromConfigFile(slot); mb.AddMeter(tryMeter); tryMeter.Logout(); LastMsg = "Try to get PcbID"; CurrentPcbID = tryMeter.GetPcbId(); hasDetect = !string.IsNullOrEmpty(CurrentPcbID); CurrentBatch = mb; CurrentMeter = tryMeter; if (hasDetect) { LastMsg = $"New PcbID detected {CurrentPcbID}"; CurrentMeter.Login(); } else { LastMsg = "No Meter found"; DisposeAllConnections(); } } catch (Exception e) { if (!ignoreErrors) { MessageBox.Show($"Error occur.{ Environment.NewLine} {e.Message}"); } } } else { LastMsg = "Check if Meter is still connected"; var ret = CurrentMeter.GetPcbId(); if (string.IsNullOrEmpty(ret) || ret != CurrentPcbID) { LastMsg = "Meter connection lost"; hasDetect = false; DisposeAllConnections(); CurrentPcbID = ""; } else { LastMsg = "Meter is still connected"; hasDetect = true; } } return hasDetect; } LastMsg = "Meter is still connected (locked)"; return true; } private void Window_Closing(Object sender, CancelEventArgs e) { DisposeAllConnections(); } private void DisposeAllConnections() { if (CurrentBatch != null) { CurrentBatch.RemoveAllMeters(); if (CurrentMeter != null) { CurrentMeter.Dispose(); } CurrentBatch.Dispose(); } PickingData.Empty(); } private void GetPcbMapping(String pcbID) { if (string.IsNullOrEmpty(pcbID)) { return; } var url = $"{ServiceUrls.MarriageServiceUrl()}GetSerialNumberAndOrderNumber?PcbId={pcbID}&withRadioAdress=true"; Task.Run(() => { try { var responseJson = LocalWebRequest.GetRequest(url); var a = JsonConvert.DeserializeObject(responseJson); if (ucFinalRadioTest != null) { var tmpInt = 0; int.TryParse(a[1], out tmpInt); ucFinalRadioTest.OrderNumber = tmpInt; tmpInt = 0; if (a.Length > 2) { int.TryParse(a[2], out tmpInt); } ucFinalRadioTest.RadioAddress = tmpInt; ucFinalRadioTest.SerialNumber = a[0] + "/" + a[3]; } } catch (Exception ex) { if (ex is WebException) { MessageBox.Show($"Error on Store: {Environment.NewLine} { ((WebException)ex).Message}"); } MessageBox.Show(ex.Message); } }); } private void Button_Click(Object sender, RoutedEventArgs e) { } private void UcFinalRadioTest_Loaded(Object sender, RoutedEventArgs e) { ucFinalRadioTest.OnLockMeter += UcFinalRadioTest_OnLockMeter; ucFinalRadioTest.OnReleaseMeter += UcFinalRadioTest_OnReleaseMeter; } private void UcFinalRadioTest_OnLockMeter(Object sender, EventArgs e) { detectIsLocked = true; } private void UcFinalRadioTest_OnReleaseMeter(Object sender, EventArgs e) { detectIsLocked = false; ucFinalRadioTest.SetUpBlank(false); } private void BtnSwitchAutoDetect_Click(Object sender, RoutedEventArgs e) { Settings.AutoDetect = !Settings.AutoDetect; storeSetting(); useSetting(); } private void CbxSlotBox_SelectionChanged(Object sender, SelectionChangedEventArgs e) { } private void storeSetting() { Settings.Update("ProductionUiConfig.json"); } private void useSetting(Boolean setSlot = false) { tmrAutoDetect.Enabled = Settings.AutoDetect; tblkAutodetectState.Text = "Off"; if (Settings.AutoDetect) { tblkAutodetectState.Text = "On"; } if (setSlot) { cbxSlotBox.SelectedValue = Settings.Slot; } ucFinalRadioTest.OrderHasChanged += delegate { txtOrderNr.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { txtOrderNr.Text = ucFinalRadioTest.OrderNumber.ToString(); })); }; } private void StackPanel_SizeChanged(Object sender, SizeChangedEventArgs e) { ucFinalRadioTest.Height = e.NewSize.Height; } } }