public static void ReloadVehicle() { var vehicle = config.GetVehicle(config.Vehicle); if (vehicle == null) { Logger.error("HOBD", "Bad configuration: can't find vehicle " + config.Vehicle); vehicle = ConfigVehicleData.defaultVehicle; } Registry = new SensorRegistry(); Registry.VehicleParameters = vehicle.Parameters; vehicle.Sensors.ForEach((provider) => { Logger.trace("HOBD", "RegisterProvider: " + provider); try{ Registry.RegisterProvider(provider); }catch (Exception e) { Logger.error("HOBD", "bad provider", e); } }); EngineConnect(); }
/** * URL is in form of: * tcp://192.168.1.2:200 */ public void Open(String url) { var u = TCPStream.ParseUrl(url); string host = u[URL_ADDR]; int port = int.Parse(u[URL_PORT]); Logger.trace("TCPStream", "TCP Stream: " + host + ":" + port); try { sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(new IPEndPoint(IPAddress.Parse(host), port)); } catch (Exception) {} if (sock != null && sock.Connected) { //sock.ReceiveTimeout = 50; //sock.ReceiveBufferSize = 128; } else { sock = null; throw new Exception("Can't connect socket " + url); } }
void SendRaw(string command) { if (Logger.TRACE) { Logger.trace("OBD2Engine", "SendRaw:" + command); } byte[] arr = Encoding.ASCII.GetBytes(command); stream.Write(arr, 0, arr.Length); }
int SendCommand(string command) { if (Logger.TRACE) { Logger.trace("OBD2Engine", "SendCommand:" + command); } var realcmd = command + "\r"; int csize = realcmd.Count(c => c == '\r'); byte[] arr = Encoding.ASCII.GetBytes(realcmd); stream.Write(arr, 0, arr.Length); return(csize); }
public virtual void Attach(SensorRegistry registry) { if (this.Registry != null) { throw new Exception("Can't attach: Invalid State"); } this.Registry = registry; Settings.Keys.ToList().ForEach((id) => { var set = Settings[id]; var sensor = Registry.Sensor(id); if (sensor == null) { return; } if (set.id != sensor.ID) { set.id = sensor.ID; Settings.Remove(id); Settings.Add(set.id, set); } Logger.trace("SensorTrack", "attach " + set.id + " period " + set.period + " length " + set.length + " gap " + set.gap); try{ Registry.AddListener(sensor, this.SensorChanged, set.period); }catch (Exception) { Logger.trace("SensorTrack", "attach failed" + sensor.ID); } }); if (this.TrackPassive) { Registry.AddPassiveListener(this.SensorChanged); } if (this.TrackAccum) { foreach (var s in Registry.Sensors.Where(s => s is IAccumulatorSensor)) { try{ Registry.AddListener(s, this.SensorChanged); }catch (Exception) { Logger.trace("SensorTrack", "attach failed" + s.ID); } } } }
public void Open(String url) { try{ var parsed_url = ParseUrl(url); Logger.trace("BluetoothStream", "Open " + parsed_url[URL_ADDR] + " serviceid " + parsed_url[URL_SVC] + " pin " + parsed_url[URL_PIN]); try{ BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; }catch (Exception e) { Logger.error("BluetoothStream", "set_Mode", e); } BluetoothAddress address = BluetoothAddress.Parse(parsed_url[URL_ADDR]); bluetoothClient = new BluetoothClient(); try{ if (parsed_url[URL_PIN] != null) { bluetoothClient.SetPin(address, parsed_url[URL_PIN]); } }catch (Exception) { Logger.error("BluetoothStream", "SetPin"); } #if xxBLUETOOTH_USE_PAIRREQUEST // advice from some user - but was useless. other user reported "unable to connecte because of this" if (parsed_url[URL_PIN] != null) { try{ for (var i = 0; i < 3; i++) { var res = BluetoothSecurity.PairRequest(address, parsed_url[URL_PIN]); if (res) { break; } Logger.error("BluetoothStream", "PairRequest failed, retry " + i); } }catch (Exception) { Logger.error("BluetoothStream", "PairRequest"); } } #endif BluetoothEndPoint btep; // force serviceid for some popular china BT adapters if (parsed_url[URL_SVC] == null && try_with_service) { parsed_url[URL_SVC] = "1"; } if (parsed_url[URL_SVC] != null) { btep = new BluetoothEndPoint(address, BluetoothService.SerialPort, int.Parse(parsed_url[URL_SVC])); } else { btep = new BluetoothEndPoint(address, BluetoothService.SerialPort); } bluetoothClient.Connect(btep); stream = bluetoothClient.GetStream(); if (stream == null) { bluetoothClient.Close(); bluetoothClient = null; } else { if (stream.CanTimeout) { stream.WriteTimeout = 2; stream.ReadTimeout = 2; } } }catch (Exception e) { if (bluetoothClient != null) { bluetoothClient.Close(); bluetoothClient = null; } if (!try_with_service) { try_with_service = true; Open(url); return; } throw; } }
void HandleState() { if (State == ST_ERROR) { Thread.Sleep(SleepOnError); return; } // Means no sensor reading was performed - we have // to wait and search for another sensor if (State == ST_SENSOR) { Thread.Sleep(50); SetState(ST_SENSOR); return; } if (stream.HasData()) { byte[] data = stream.Read(); if (data != null) { if (position + data.Length < buffer.Length) { Array.Copy(data, 0, buffer, position, data.Length); position = position + data.Length; } else { Logger.error("OBD2Engine", "BUFFER OVERFLOW! " + position + data.Length); position = 0; } if (Logger.DUMP) { Logger.dump("OBD2Engine", "BUFFER: " + Encoding.ASCII.GetString(buffer, 0, position)); } if (ReadDelay > 0) { if (Logger.TRACE) { Logger.trace("OBD2Engine", "Sleeping " + ReadDelay + " ms"); } Thread.Sleep(ReadDelay); } if (data.Length > 0) { lastReceiveTS = DateTimeMs.Now; } } data = null; } // nothing to read - wait if (position == 0) { Thread.Sleep(50); return; } for (int isearch = 0; isearch < position; isearch++) { // end of reply found if (buffer[isearch] == '>') { byte[] msg = new byte[isearch]; Array.Copy(buffer, 0, msg, 0, isearch); isearch++; Array.Copy(buffer, isearch, buffer, 0, position - isearch); position = position - isearch; // handle our extracted message HandleReply(msg); break; } } }
void HandleReply(byte[] msg) { string smsg = Encoding.ASCII.GetString(msg, 0, msg.Length); if (Logger.TRACE) { Logger.trace("OBD2Engine", "HandleReply: " + smsg.Trim()); } switch (State) { case ST_INIT: break; case ST_ATZ: if (smsg.Contains("ATZ") || smsg.Contains("ELM")) { VersionInfo = smsg.Replace("ATZ", "").Replace("\r", "").Replace("\n", "").Trim(); Logger.log("INFO", "OBD2Engine", "VersionInfo: " + VersionInfo, null); if (VersionInfo.Length > 2) { criticalErrors[0] = VersionInfo; } SetState(ST_ATE0); } else { SendCommand("ATZ"); } break; case ST_ATE0: if (smsg.Contains("OK")) { SetState(ST_ATL0); } break; case ST_ATL0: if (smsg.Contains("OK")) { SetState(ST_EXTRAINIT); } break; case ST_EXTRAINIT: SetState(ST_EXTRAINIT); break; case ST_SENSOR_INIT: Error = criticalErrors.FirstOrDefault(e => smsg.Contains(e)); if (Error != null) { Logger.error("OBD2Engine", "Critical error on sensor init:" + smsg); // Wait and then do soft reconnect SetState(ST_ERROR_SOFT); StateDetails = State + " " + Error; } else { Logger.log("INFO", "OBD2Engine", "Sensor Init:" + smsg, null); //PIDSupported.SetValue(msg); SetState(ST_QUERY_PROTOCOL); } break; case ST_QUERY_PROTOCOL: try{ var proto = smsg.Replace("A", ""); ProtocolId = int.Parse(proto, NumberStyles.HexNumber); }catch (Exception) { Logger.error("OBD2Engine", "protocol " + smsg); } Logger.log("INFO", "OBD2Engine", "ProtocolId: " + ProtocolId, null); Registry.ProtocolId = ProtocolId; SetState(ST_SENSOR); break; case ST_SENSOR_ACK: // saving local copy var lsl = currentSensorListener; var osensor = (OBD2Sensor)lsl.sensor; nextReadings[currentSensorIndex] = DateTimeMs.Now + lsl.period + (1000 * Math.Min(10, lsl.failures)); // proactively read next sensor! SetState(ST_SENSOR); // valid reply - set value, raise listeners if (osensor.SetRawValue(msg)) { subsequentErrors = 0; lsl.failures = 0; this.Error = null; } else { // search for known errors, increment counters string error = dataErrors.FirstOrDefault(e => smsg.Contains(e)); if (error != null) { this.Error = this.Error == null ? error : this.Error + " " + error; // increase period for this 'bad' sensor if (subsequentErrors == 0) { Logger.info("OBD2Engine", "sensor not responding, increasing period: " + osensor.ID); // !!!! VAZ.Core fail otherwise lsl.failures++; //lsl.period = unchecked((lsl.period +100) * 2); } subsequentErrors++; } else { error = criticalErrors.FirstOrDefault(e => smsg.Contains(e)); if (error != null) { this.Error = error; this.CriticalError = true; Logger.error("OBD2Engine", "Critical error:" + smsg); SetState(ST_ERROR_SOFT); subsequentErrors = 0; } } } // act on too much errors if (subsequentErrors > ErrorThreshold) { Logger.error("OBD2Engine", "Connection error threshold"); this.Error = "Connection error threshold"; subsequentErrors = 0; this.CriticalError = true; SetState(ST_ERROR_SOFT); } break; } }
void SetState(string state2) { State = state2; StateDetails = state2; lastReceiveTS = DateTimeMs.Now; if (Logger.TRACE) { Logger.trace("OBD2Engine", " -> " + State); } switch (State) { case ST_SENSOR: fireStateNotify(STATE_READ); break; case ST_SENSOR_ACK: fireStateNotify(STATE_READ_DONE); break; case ST_ERROR: case ST_ERROR_SOFT: fireStateNotify(STATE_ERROR); break; default: fireStateNotify(STATE_INIT); break; } switch (State) { case ST_INIT_HW: Error = null; try{ stream.Close(); Logger.info("OBD2Engine", "Open " + url); Thread.Sleep(100); stream.Open(url); }catch (Exception e) { Error = e.Message; Logger.error("OBD2Engine", "Init Error", e); SetState(ST_ERROR); break; } PurgeStream(); SetState(ST_INIT); break; case ST_INIT: extraInitCommands.Clear(); extraInitIndex = 0; if (CriticalError) { CriticalError = false; // trigger protocol autosearch TODO: conflicts with some settings, f.e. ATFI setup //extraInitCommands.Add("ATSP 0"); } if (initData != null) { initData.Split(new char[] { ';' }).ToList().ForEach((s) => { var cmd = s.Trim(); if (cmd.Length > 0) { extraInitCommands.Add(cmd); } }); } SensorInitIndex = 0; SetState(ST_ATZ); break; case ST_ATZ: SendCommand("ATZ"); break; case ST_ATE0: SendCommand("ATE0"); break; case ST_ATL0: SendCommand("ATL0"); break; case ST_EXTRAINIT: if (extraInitIndex >= extraInitCommands.Count()) { SetState(ST_SENSOR_INIT); } else { SendCommand(extraInitCommands[extraInitIndex]); StateDetails = State + " " + this.extraInitCommands[this.extraInitIndex]; extraInitIndex++; } break; case ST_SENSOR_INIT: SendCommand("01" + SensorInitIndex.ToString("X2")); break; case ST_QUERY_PROTOCOL: SendCommand("ATDPN"); break; case ST_SENSOR: var sls = Registry.ActiveSensors; if (sls.Length == 0) { if (Logger.TRACE) { Logger.trace("OBD2Engine", " no active sensors "); } break; } currentSensorIndex++; if (currentSensorIndex >= sls.Length) { currentSensorIndex = 0; } int scanSensorIndex = currentSensorIndex; while (true) { currentSensorListener = sls[currentSensorIndex]; // recreate reading timers if layout was changed! if (nextReadings == null || nextReadings.Length != sls.Length) { nextReadings = new long[sls.Length]; } long nextReading = nextReadings[currentSensorIndex]; if (nextReading == 0 || nextReading <= DateTimeMs.Now) { if (currentSensorListener.sensor is OBD2Sensor) { if (Logger.TRACE) { Logger.trace("OBD2Engine", " ----> " + currentSensorListener.sensor.ID); } var osensor = (OBD2Sensor)currentSensorListener.sensor; var cmd = osensor.RawCommand; if (cmd != null) { LinesSent = SendCommand(cmd); SetState(ST_SENSOR_ACK); break; } else { // move to next sensor } } } else { if (Logger.DUMP) { Logger.dump("OBD2Engine", " Skipped " + currentSensorListener.sensor.ID + " with " + (nextReading - DateTimeMs.Now)); } } currentSensorIndex++; if (currentSensorIndex >= sls.Length) { currentSensorIndex = 0; } if (currentSensorIndex == scanSensorIndex) { break; } } break; } }
public static bool Init() { Logger.Init(Path.Combine(HOBD.AppPath, "log.txt")); try{ int handle = FindWindow(null, HomePage.Title); if (handle != 0) { Logger.log("INFO", "HOBD", "App bring to foreground", null); SetForegroundWindow(handle); return(false); } }catch (Exception e) {} try{ Logger.log("INFO", "HOBD", "App start", null); try{ config = new ConfigData(Path.Combine(HOBD.AppPath, "config.xml")); }catch (Exception e) { Logger.error("HOBD", "failure loading config.xml, using defaults", e); config = new ConfigData(); } Logger.SetLevel(config.LogLevel); ReloadLang(); ReloadUnits(); ReloadVehicle(); int dpi_value; var bwidth = Screen.PrimaryScreen.Bounds.Width; if (bwidth > 1920) { bwidth = 800; } dpi_value = (int)(96f / bwidth * 480f); Logger.trace("HOBD", "Bounds.Width: " + bwidth); if (config.DPI != 0) { dpi_value = config.DPI; } FleuxApplication.TargetDesignDpi = dpi_value; ReloadTheme(); }catch (Exception e) { Logger.error("HOBD", "fatal failure, exiting", e); if (engine != null && engine.IsActive()) { engine.Deactivate(); } return(false); } return(true); }
public void Open(String url) { var u = SerialStream.ParseUrl(url); Logger.trace("SerialStream", "Port " + u[0] + " baud " + u[1] + " parity " + u[2] + " hs " + u[3]); var baudRate = 38400; var parity = Parity.None; var dataBits = 8; var stopBits = StopBits.One; if (u[URL_BAUD] != null) { baudRate = int.Parse(u[URL_BAUD]); } switch (u[URL_PARITY]) { case "none": parity = Parity.None; break; case "odd": parity = Parity.Odd; break; case "even": parity = Parity.Even; break; case "mark": parity = Parity.Mark; break; case "space": parity = Parity.Space; break; } try { port = new SerialPort(u[URL_PORT], baudRate, parity, dataBits, stopBits); switch (u[URL_HANDSHAKE]) { case "none": port.Handshake = Handshake.None; break; case "x": port.Handshake = Handshake.XOnXOff; break; case "rts": port.Handshake = Handshake.RequestToSend; break; case "xrts": port.Handshake = Handshake.RequestToSendXOnXOff; break; } port.ReadBufferSize = 0x40; port.ReceivedBytesThreshold = 1; port.ReadTimeout = 2000; port.WriteTimeout = 2000; } catch (Exception) {} try { port.Open(); } catch (Exception) { Close(); throw; } }
protected override void Activate() { lph = registry.Sensor(OBD2Sensors.LitersPerHour); Logger.trace("FCS", "lph: " + lph.ID); registry.AddListener(lph, OnChange, ListenInterval); }