protected void SerialPortConfig(ESerialDevice device) { switch (device) { case ESerialDevice.K3Scales: if (SerialPort == null) { SerialPort = new SerialPort("COM3"); } SerialPort.DataBits = 8; SerialPort.BaudRate = 9600; SerialPort.Parity = Parity.None; SerialPort.StopBits = StopBits.One; SerialPort.NewLine = ((char)3).ToString(); SerialPort.ReadTimeout = 10000; break; } MyLogger.LogText("Port " + SerialPort.PortName + " CONFIGURED", "SerialPortMng::SerialPortConfig"); MyLogger.LogText(" DataBits: "+ SerialPort.DataBits); MyLogger.LogText(" BaudRate: "+ SerialPort.BaudRate); MyLogger.LogText(" Parity: "+ SerialPort.Parity); MyLogger.LogText(" StopBits: "+ SerialPort.StopBits); MyLogger.LogText(" NewLine: "+ SerialPort.NewLine); }
public void StopRead() { try { Status = PortMngStatus.Stop; if (PortReaderThread == null) { return; } while (PortReaderThread.IsAlive) { continue; } if (SerialPort != null) { SerialPort.Close(); } Status = PortMngStatus.Stop; } catch (Exception ex) { MyLogger.LogException(ex, "SerialPortMng::StopRead"); } finally { MyLogger.LogText("Port " + SerialPort.PortName + " CLOSED", "SerialPortMng::StopRead"); PortReaderThread = null; SerialPort = null; } }
public void SaveScaleLine() { try { if (Status != EStatus.Working) { return; } if (LastLine.Line == string.Empty) { return; } Pesajes pesajes = Pesajes.NewList(); Pesaje item = pesajes.NewItem(); CopyFromLine(item, LastLine); pesajes.OpenNewSession(); pesajes.BeginTransaction(); pesajes.Save(); pesajes.CloseSession(); MyLogger.LogText("Line saved: " + LastLine.Line, "ScalesMng::SaveScaleLine"); Status = EStatus.Closed; } catch (Exception ex) { MyLogger.LogException(ex, "ScalesMng::SaveScaleLine"); Status = EStatus.Error; } }
protected void StartStatusMonitor() { try { if (Monitor) { MyLogger.LogText("MONITOR ENABLED", "ServiceBase::StartStatusMonitor"); MonitorMng.Instance.ComponentApiKey = ApiKey; MonitorMng.Instance.ComponentSecretKey = SecretKey; MonitorMng.Instance.ComponentSerial = SerialNumber; MonitorMng.Instance.ComponentName = ComponentName; MonitorMng.Instance.ComponentType = EComponentType.WinService; MonitorMng.Instance.ComponentStatus = EComponentStatus.OK; MonitorMng.Instance.ComponentInterval = MonitorPollInterval; MonitorMng.Instance.StartPoll(MonitorPollInterval); } else { MyLogger.LogText("MONITOR DISABLED", "ServiceBase::StartStatusMonitor"); } } catch (Exception ex) { MyLogger.LogException(ex, "ServiceBase::StartStatusMonitor"); } }
public void Run() { if (Status == EStatus.Working) { return; } Status = EStatus.Working; bool _isLogEnabled = false; string setting = System.Configuration.ConfigurationManager.AppSettings["LogEnabled"]; bool.TryParse(setting, out _isLogEnabled); CompanyList empresas = null; try { if (_isLogEnabled) { string msg = "AUTOPILOT::START"; MyLogger.LogText(msg); } AppController.Instance.InitFromService(); Principal.Login(); empresas = CompanyList.GetList(AppContext.User.GetInfo(), false); foreach (CompanyInfo item in empresas) { MyLogger.LogText("AUTOPILOT::INFO: SCHEMA '" + item.Name + "'"); AppContext.Principal.ChangeUserSchema((item as ISchemaInfo)); AppController.Instance.AutoPilot(); } if (_isLogEnabled) { string msg = "AUTOPILOT::FINISH"; MyLogger.LogText(msg); } Status = EStatus.Closed; } catch (Exception ex) { Status = EStatus.Error; if (_isLogEnabled) { MyLogger.LogText("AUTOPILOT::ERROR: " + iQExceptionHandler.GetAllMessages(ex, true)); } } finally { AppController.Instance.Close(); } }
public void StartPoll(int pollInterval, bool waitResponse) { MyLogger.LogText("Monitor Timer Started: Tick every " + pollInterval + "s", "MonitorMng::StartPoll"); MyLogger.LogText("Monitor Host: " + SettingsMng.Instance.GetApiBaseUrl(), "MonitorMng::StartPoll"); TimerGuid = TimerMng.Instance.InitTimer(ETimerType.System, MonitorStatusTimerController, pollInterval); //Initial Poll UpdateMonitorStatus(waitResponse); }
protected void InitTimer() { string setting = System.Configuration.ConfigurationManager.AppSettings["LogEnabled"]; bool.TryParse(setting, out _isLogEnabled); try { string msg = "AUTOPILOT SERVICE START"; this.EventLog.WriteEntry(msg, EventLogEntryType.Information, 20); if (_isLogEnabled) { MyLogger.LogText(msg); } _timer = new System.Timers.Timer(); _timer.Enabled = false; _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed); setting = System.Configuration.ConfigurationManager.AppSettings["PullInterval"]; double interval = 3600; if (double.TryParse(setting, out interval)) { _timer.Interval = interval * 1000; } else { _timer.Interval = 3600 * 1000; } _timer.Start(); msg = string.Format("Tick every {0} s. EventLog is {1}\r\n", _timer.Interval / 1000, _isLogEnabled ? "enabled" : "disabled" ); this.EventLog.WriteEntry(msg, EventLogEntryType.Information, 20); if (_isLogEnabled) { MyLogger.LogText(msg); } } catch (Exception ex) { string msg = "AUTOPILOT SERVICE ERROR: " + ex.Message; this.EventLog.WriteEntry(msg, EventLogEntryType.Error, 100); if (_isLogEnabled) { MyLogger.LogText(msg); } } }
private bool IsNegativeLine(string line) { try { return(line.Substring(2, 1) == "-"); //((char)0x04).ToString()); } catch (Exception ex) { MyLogger.LogText(ex.Message + ex.StackTrace, "ScalesMng::IsNegativeLine:: line = " + line); return(true); } }
private bool IsZeroLine(string line) { try { return(line.Substring(1, 1).Equals("")); //((char)0x08).ToString()); } catch (Exception ex) { MyLogger.LogText(ex.Message + ex.StackTrace, "ScalesMng::IsZeroLine:: line = " + line); } return(true); }
private bool IsDistinctLine(string line) { try { return(LastLine.Line != line); } catch (Exception ex) { MyLogger.LogText(ex.Message + ex.StackTrace, "ScalesMng::IsDistinctLine:: line = " + line); } return(true); }
public void BackupErrorHandler(object sender, iQExceptionHandler.ErrorEventArgs e) { Status = EStatus.Error; switch (e.Exception.Code) { case iQExceptionCode.INFO: MyLogger.LogText("BAQUP::INFO: " + e.Exception.Message); break; default: MyLogger.LogException(e.Exception, "BaQup::BackupErrorHandler"); break; } }
protected void PortLineReader() { try { if (SerialPort == null) { return; } Status = PortMngStatus.Reading; MyLogger.LogText("Opening port " + SerialPort.PortName + " ...", "SerialPortMng::PortLineReader"); SerialPort.Open(); MyLogger.LogText("Port " + SerialPort.PortName + " OPEN", "SerialPortMng::PortLineReader"); if (Status == PortMngStatus.Reading) { MyLogger.LogText("Listening Port " + SerialPort.PortName, "SerialPortMng::PortLineReader"); } string value = string.Empty; //Port Reading Loop while (Status == PortMngStatus.Reading) { try { value = SerialPort.ReadLine(); } catch (TimeoutException) { value = string.Empty; MyLogger.LogText("Port read Timeout", "SerialPortMng::PortLineReader"); } if (!string.IsNullOrEmpty(value)) { LineHandlerDelegate(value); } } MyLogger.LogText("Stop listening Port " + SerialPort.PortName, "SerialPortMng::PortLineReader"); } catch (Exception ex) { MyLogger.LogException(ex, "SerialPortMng::PortLineReader"); } }
public void StartRead(ESerialDevice device, PortByteHandlerDelegate handler) { if (Status == PortMngStatus.Reading) { MyLogger.LogText("Serial Port Manager is reading. Please stop it first", "SerialPortMng::StartRead"); throw new iQException("Serial Port Manager is reading. Please stop it first", "SerialPortMng::StartRead"); } SerialPortConfig(device); ByteHandlerDelegate = handler; Status = PortMngStatus.Reading; PortReaderThread = new Thread(PortByteReader); PortReaderThread.Start(); }
private bool IsValidWeigth(string line) { try { if (IsNegativeLine(line)) { return(false); } decimal value = Convert.ToDecimal(line.Substring(2, 8)); return(value > 5); } catch (Exception ex) { MyLogger.LogText(ex.Message + ex.StackTrace, "ScalesMng::IsValidWeigth:: line = " + line); return(true); } }
public bool ZeroLine(string line) { try { if (IsNegativeLine(line)) { return(false); } decimal value = Convert.ToDecimal(line.Substring(2, 8)); return(value == 0); } catch (Exception ex) { MyLogger.LogText(ex.Message + ex.StackTrace, "ScalesMng::ZeroLine:: line = " + line); } return(true); }
public void Run() { if (Status == EStatus.Working) { return; } Status = EStatus.Working; try { MyLogger.LogText("BAQUP START", "BaQup::Run"); try { AppController.Instance.InitFromService(BackupErrorHandler); Principal.Login(Library.SettingsMng.GetServicesUser(), Library.SettingsMng.GetServicesPassword()); Library.SettingsMng.Instance.SetBackupsPath(Properties.Settings.Default.BACKUPS_PATH); CompanyList companies = CompanyList.GetList(AppContext.User.GetInfo(), false); AppController.AutoBackup(companies.ToList <ISchemaInfo>(), true); MyLogger.LogText("BAQUP FINISH", "BaQup::Run"); } catch (Exception ex) { Status = EStatus.Error; MyLogger.LogException(ex, "BaQup::Run"); } Status = EStatus.Closed; } catch (Exception ex) { Status = EStatus.Error; MyLogger.LogException(ex, "BaQup::Run"); } finally { AppController.Instance.Close(); } }
void _timer_Elapsed(object sender, ElapsedEventArgs e) { try { string msg = "TIMER ELAPSED START"; this.EventLog.WriteEntry(msg, EventLogEntryType.Information, 100); Autopilot.Instance.Run(); BaQup.Instance.Run(); this.EventLog.WriteEntry("TIMER ELAPSED FINISH", EventLogEntryType.Information, 100); } catch (Exception ex) { if (_isLogEnabled) { MyLogger.LogText("TIMER ELAPSED ERROR: " + ex.Message); } this.EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error, 100); } }
public void CopyFromLine(Pesaje item, TLine line) { try { switch (SerialDevice) { case ESerialDevice.K3Scales: { try { item.Neto = Convert.ToDecimal(line.Line.Substring(2, 8)); } catch { item.Neto = 0; } item.Fecha = line.Date; item.Tara = 0; item.Bruto = item.Tara + item.Neto; item.Observaciones = EnumText <ESerialDevice> .GetLabel(ESerialDevice.K3Scales) + " | " + line.Line; } break; } } catch (Exception ex) { MyLogger.LogText(ex.Message + ex.StackTrace, "CALLER", "ScalesMng::CopyFromLine"); } }
public void POSTToSite(string url, DlgPackPOSTData packer) { TProxyResult result = new TProxyResult { Status = EComponentStatus.WORKING, Message = string.Empty, ExceptionStatus = WebExceptionStatus.Success, }; try { // Generate post objects Dictionary <string, object> postParameters = new Dictionary <string, object>(); Dictionary <string, object> postParametersLog = new Dictionary <string, object>(); packer(postParameters, postParametersLog); // Parameters are written to log file in JSON string postParameteresJson = JsonConvert.SerializeObject(postParametersLog); string userAgent = string.Empty; // Properties.Settings.Default.UserAgent; string postURL = url; try { /*if (Settings.Default.IsDebug) * { * MyLogger.LogText(postURL); * MyLogger.LogText("POST Parameters"); * foreach (KeyValuePair<string, object> item in postParameters) * MyLogger.LogText(item.Key + ": " + item.Value); * }*/ MyLogger.LogText("BEGIN DATA POST TO " + postURL, "Proxy::POSTToSite"); result.Response = MultipartFormDataPost(postURL, userAgent, postParameters); MyLogger.LogText("END DATA POST", "Proxy::POSTToSite"); } catch (System.Net.WebException ex) { result.Status = EComponentStatus.ERROR; result.Message = Resources.Errors.SERVER_CONNECTION; result.Response = ex.Response as HttpWebResponse; result.ExceptionStatus = ex.Status; MyLogger.LogText("ERROR IN POST: " + iQExceptionHandler.GetAllMessages(ex) + System.Environment.NewLine + "POST URL: " + postURL + System.Environment.NewLine + "POST RESPONSE: " + result.Response.ToString(), "Proxy::POSTToSite"); InsertResult(url, result); return; } if (result.Response.StatusCode == HttpStatusCode.OK) { // Process response StreamReader responseReader = new StreamReader(result.Response.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); result.Response.Close(); try { Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer(); Newtonsoft.Json.JsonReader r = new Newtonsoft.Json.JsonTextReader(new StringReader(fullResponse)); Newtonsoft.Json.Linq.JObject res = ser.Deserialize(r) as Newtonsoft.Json.Linq.JObject; StringBuilder sb = new StringBuilder(); foreach (KeyValuePair <string, JToken> kvp in res) { switch (kvp.Key) { case "message": { result.Status = (kvp.Value.ToString() == "OK") ? EComponentStatus.OK : EComponentStatus.ERROR; sb.AppendLine((kvp.Value != null ? (kvp.Value.HasValues ? kvp.Value.First.ToString() : kvp.Value.ToString()) : "")); } break; default: sb.AppendLine(kvp.Value != null ? (kvp.Value.HasValues ? kvp.Value.First.ToString() : kvp.Value.ToString()) : ""); break; } } result.Message = sb.ToString(); } catch { MyLogger.LogText("JSON DESERIALIZE ERROR", "Proxy::POSTToSite"); MyLogger.LogText("FULL RESPONSE: " + fullResponse, "Proxy::POSTToSite"); result.Message = fullResponse; } } else { MyLogger.LogText("HTTP REQUEST STATUS ERROR.", "Proxy::POSTToSite"); MyLogger.LogText("HTTP URL: " + url, "Proxy::POSTToSite"); } } catch (Exception ex) { MyLogger.LogText("IN POSTToSite: " + ex.Message, "Proxy::POSTToSite"); result.Status = EComponentStatus.ERROR; result.Message = ex.Message; } finally { InsertResult(url, result); } }
public void StopPoll() { MyLogger.LogText("Monitor Timer Stopped", "MonitorMng::StopPoll"); TimerMng.Instance.CloseTimer(TimerGuid); }
public void PutMonitor() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(SettingsMng.Instance.GetApiBaseUrl()); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); FillToken(client); // Create a new monitor MonitorViewModel monitor = MonitorViewModel.New(); monitor.ComponentSerial = ComponentSerial; monitor.ComponentType = (long)ComponentType; monitor.ComponentName = ComponentName; monitor.ComponentStatus = (long)EComponentStatus.OK; monitor.ComponentInterval = ComponentInterval; Uri gizmoUri = null; // Update the monitor HttpResponseMessage response = null; string responsephrase = string.Empty; int count = 0; do { MyLogger.LogText("CALL TO " + MonitorURL + monitor.ComponentSerial + " (attempt " + (count + 1) + ")", "MonitorMng::PutMonitor"); response = client.PutAsJsonAsync(MonitorControllerURL + monitor.ComponentSerial, monitor).Result; if (response != null) { _responseCode = response.StatusCode; responsephrase = response.ReasonPhrase; } else { _responseCode = HttpStatusCode.Unused; responsephrase = "RESPONSE IS NULL"; } count++; MyLogger.LogText(String.Format("{0} ({1})", _responseCode, responsephrase), "MonitorMng::PutMonitor"); //Si el servidor no responde esperamos 10s para el siguiente intento if ((int)_responseCode == 404) { Thread.Sleep(10000); } }while (!response.IsSuccessStatusCode && count < 5); if (response.IsSuccessStatusCode) { gizmoUri = response.Headers.Location; ComponentStatus = EComponentStatus.OK; LastUpdate = DateTime.Now; } else { ComponentStatus = EComponentStatus.ERROR; } if (MonitorController != null) { MonitorController(); } }
public void RestartPoll() { MyLogger.LogText("Monitor Timer Restarted"); TimerMng.Instance.ResetTimer(TimerGuid); }
protected void PortByteReader() { if (SerialPort == null) { return; } Status = PortMngStatus.Reading; SerialPort.Open(); MyLogger.LogText("Port " + SerialPort.PortName + " OPEN", "SerialPortMng::PortByteReader"); byte[] line = new byte[14]; //Bucle de sincronizacion con el puerto while (true) { SerialPort.Read(line, 0, 1); //MyLogger.LogText("Leido caracter de sincronizacion '" + (char)line[0] + "'"); if ((char)line[0] == (char)3) { line = new byte[14]; string value = string.Empty; while (SerialPort.BytesToRead < line.Length) { } SerialPort.Read(line, 0, line.Length); for (int i = 0; i < line.Length; i++) { value += line[i].ToString() + " | "; } //MyLogger.LogText("Leida linea de sincronizacion '" + value + "'"); if ((char)line[0] == 2 && line[13] == 3) { ByteHandlerDelegate(line); break; } } } while (Status == PortMngStatus.Reading) { if (SerialPort.BytesToRead < line.Length) { continue; } SerialPort.Read(line, 0, line.Length); string value = string.Empty; for (int i = 0; i < line.Length; i++) { value += (char)line[i] + " | "; } //MyLogger.LogText("Leida linea '" + value + "'"); if (line[0] == 2 && line[13] == 3) { ByteHandlerDelegate(line); } } }