error() 공개 정적인 메소드

public static error ( String comp, String msg ) : void
comp String
msg String
리턴 void
예제 #1
0
        public void Attach(SensorRegistry registry)
        {
            if (this.Registry != null)
            {
                throw new Exception("Can't attach: Invalid State");
            }
            this.Registry = registry;

            try{
                var reader = new StreamReader(new FileStream(FilePath, FileMode.Open));

                while (true)
                {
                    var line = reader.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    int    vali  = line.IndexOf(" ");
                    string sname = line.Substring(0, vali);
                    string value = line.Substring(vali + 1);
                    // backward compat patch between 0.5 -> 0.6
                    if (sname == "DistanceRun" || sname == "FuelConsumed" || sname == "TripTime" || sname == "IdleTime")
                    {
                        sname = "Common." + sname;
                    }

                    var sensor = Registry.Sensor(sname);
                    if (sensor != null && sensor is IPersistentSensor)
                    {
                        try{
                            ((IPersistentSensor)sensor).RestoreState(value);
                            Registry.TriggerListeners(sensor);
                        }catch (Exception e) {
                            Logger.error("SensorStorage", "fail on RestoreState: " + sname, e);
                        }
                    }
                    else
                    {
                        Logger.error("SensorStorage", "bad sensor: " + sname);
                    }
                }
                reader.Close();
            }catch (FileNotFoundException) {
                Logger.error("SensorStorage", "File not found");
            }catch (Exception e) {
                Logger.error("SensorStorage", "error reading", e);
            }
        }
예제 #2
0
 void ListenerHandler()
 {
     while (triggerQueue != null)
     {
         if (triggerQueue.Count == 0)
         {
             Thread.Sleep(10);
         }
         else
         {
             SensorListener sl     = null;
             var            sensor = triggerQueue.Dequeue();
             if (sensor != null)
             {
                 activeSensors.TryGetValue(sensor, out sl);
             }
             if (sl != null)
             {
                 sl.nextReading = DateTimeMs.Now + sl.period;
                 if (Logger.DUMP)
                 {
                     Logger.dump("SensorRegistry", "ListenerHandler " + sensor.ID + " " + sl.nextReading);
                 }
                 foreach (Action <Sensor> l in sl.listeners.ToArray())
                 {
                     try{
                         if (Logger.DUMP)
                         {
                             Logger.dump("SensorRegistry", "Listener: " + l);
                         }
                         l(sensor);
                     }catch (Exception e)
                     {
                         Logger.error("SensorRegistry", "Listener fail on: " + sensor.ID, e);
                     }
                 }
                 foreach (Action <Sensor> l in PassiveListeners.ToArray())
                 {
                     try{
                         l(sensor);
                     }catch (Exception e)
                     {
                         Logger.error("SensorRegistry", "Passive listener fail on: " + sensor.ID, e);
                     }
                 }
             }
         }
     }
 }
예제 #3
0
        private void DataReceviedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort port = (SerialPort)sender;
            int        read;

            try{
                read = port.Read(sbuf, 0, 128);
            }catch (Exception ex) {
                Logger.error("SerialPort", "port.Read failed", ex);
                return;
            }
            byte[] buf = new byte[read];
            Array.Copy(sbuf, buf, read);
            portQueue.Enqueue(buf);
        }
예제 #4
0
        public virtual void Detach()
        {
            if (Registry == null)
            {
                return;
            }

            try{
                Registry.RemoveListener(this.SensorChanged);
                Registry.RemovePassiveListener(this.SensorChanged);
            }catch (Exception e) {
                Logger.error("SensorTrack", "Detach fail", e);
            }
            Store();
            this.Registry = null;
        }
예제 #5
0
 public object CreateObject(string clazz)
 {
     foreach (var oc in ObjectCreators)
     {
         var obj = oc(clazz);
         if (obj != null)
         {
             return(obj);
         }
     }
     try{
         return(Assembly.GetExecutingAssembly().CreateInstance(clazz));
     }catch (Exception e) {
         Logger.error("SensorRegistry", "CreateObject failed: " + clazz);
     }
     return(null);
 }
예제 #6
0
        public void DumpState()
        {
            var act = "";

            foreach (var sl in activeSensors.Values)
            {
                act += sl.sensor.ID + " \n";
            }
            Logger.error("SensorRegistry", "========================== active: " + act);
            foreach (var sl in activeSensors.Values)
            {
                act = sl.sensor.ID + " \n";
#if DEBUG
                act += sl.bt;
#endif
                Logger.error("SensorRegistry", "========================== active: " + act);
            }
        }
예제 #7
0
        public static void Run(string homepage)
        {
            while (ReloadUI)
            {
                try{
                    ReloadUI = false;
                    Thread main = new Thread(() => {
                        try{
                            FleuxPage home = (FleuxPage)Assembly.GetExecutingAssembly().CreateInstance(homepage);
                            FleuxApplication.Run(home);
                            home.Dispose();
                        }catch (Exception e) {
                            Logger.error("HOBD", "fatal UI thread failure, exiting", e);
                        }
                    });
                    main.Start();
                    main.Join();
                }catch (Exception e) {
                    Logger.error("HOBD", "fatal failure, exiting", e);
                    if (engine != null && engine.IsActive())
                    {
                        engine.Deactivate();
                    }
                }
            }

            if (engine != null)
            {
                engine.Deactivate();
            }
            if (Registry != null)
            {
                Registry.Deactivate();
            }
            config.Save();
            Logger.info("HOBD", "app exit");

#if !WINCE
            // hanged threads?
            Environment.Exit(0);
#endif
        }
예제 #8
0
        public byte[] Read()
        {
            if (port == null)
            {
                return(null);
            }

            int read;

            try{
                read = port.Read(sbuf, 0, 128);
            }catch (Exception ex) {
                Close();
                Logger.error("SerialPort", "port.Read failed", ex);
                return(null);
            }
            byte[] buf = new byte[read];
            Array.Copy(sbuf, buf, read);
            return(buf);
        }
예제 #9
0
        void DiscoverBT()
        {
            try{
                BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
                BluetoothClient bluetoothClient = new BluetoothClient();
                UpdateBTStatus(HOBD.t("Scanning Bluetooth.."));

                bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10, true, false, true);
                foreach (var di in bluetoothDeviceInfo)
                {
                    Logger.info("ConfigurationPage", "BT name=" + di.DeviceName + ", addr=" + di.DeviceAddress.ToString());
                }
            }catch (Exception e) {
                UpdateBTStatus(HOBD.t("Bluetooth scan failed"));
                Logger.error("ConfigurationPage", "", e);
            }
            UpdateBTStatus(HOBD.t("Scan Again"));
            CreateItems();
            discoverBThread = null;
        }
예제 #10
0
        public void StoreState()
        {
            if (Registry == null)
            {
                return;
            }

            var sensors = Registry.EnumerateSensors().Where(s => s is IPersistentSensor).ToList();

            try{
                var writer = new StreamWriter(new FileStream(FilePath, FileMode.Create));

                sensors.ForEach(s => {
                    writer.WriteLine(s.ID + " " + ((IPersistentSensor)s).StoreState());
                });
                writer.Close();
            }catch (Exception e) {
                Logger.error("SensorStorage", "error writing", e);
            }
        }
예제 #11
0
파일: OBD2Sensor.cs 프로젝트: leewoody/hobd
        public virtual bool SetValue(byte[] dataraw)
        {
            data_offset = 0;
            while (data_offset < dataraw.Length - 1 && !(dataraw[data_offset] == 0x41 && dataraw[data_offset + 1] == this.Command))
            {
                data_offset++;
            }
            if (data_offset >= dataraw.Length - 1)
            {
                data_offset = 0;

                /*
                 * If we set OBD2 command explicitly,
                 * this means we should find this command in response.
                 * In case command was not found - response is assumed to be invalid.
                 */
                if (Command != -1)
                {
                    return(false);
                }
            }

            this.dataraw = dataraw;

            try{
                this.Value = obdValue(this);
            }catch (Exception) {
                string r = "";
                for (int i = 0; i < dataraw.Length; i++)
                {
                    r += dataraw[i].ToString("X2") + " ";
                }
                Logger.error("OBD2Sensor", "Fail parsing sensor value: " + this.ID + " " + r);
                return(false);
            }
            this.TimeStamp = DateTimeMs.Now;
            registry.TriggerListeners(this);
            return(true);
        }
예제 #12
0
        protected virtual void StoreSensorData(SensorTrackData set)
        {
            lock (set)
            {
                try
                {
                    var fs = new FileStream(Path.Combine(DataPath, VersionID + set.id), FileMode.Append);
                    var sw = new BinaryWriter(fs);

                    for (int i = 0; i < set.history_t.Count(); i++)
                    {
                        sw.Write(set.history_t[i]);
                        sw.Write(set.history_v[i]);
                    }
                    set.history_t.Clear();
                    set.history_v.Clear();
                    sw.Close();
                    fs.Close();
                }catch (Exception e) {
                    Logger.error("StoreSensorData", "fail", e);
                }
            }
        }
예제 #13
0
        /**
         *  Searches the files in "fileMask" for DTC descriptions in form:
         *  P0000 Description
         */
        public static Dictionary <string, List <string> > Decode(string filePath, string fileMask, IEnumerable <string> dtcs)
        {
            var result = new Dictionary <string, List <string> >();

            try{
                Directory.GetFiles(filePath, fileMask).ToList().ForEach((f) => {
                    var sr = new StreamReader(new FileStream(f, FileMode.Open));
                    while (true)
                    {
                        var line = sr.ReadLine();
                        if (line == null)
                        {
                            break;
                        }
                        if (line.Length < 6 || line[5] != ' ')
                        {
                            continue;
                        }

                        var cur_dtc = line.Substring(0, 5);
                        if (dtcs.FirstOrDefault((dtc) => dtc == cur_dtc) != null)
                        {
                            if (!result.ContainsKey(cur_dtc))
                            {
                                result.Add(cur_dtc, new List <string>());
                            }
                            result[cur_dtc].Add(line.Substring(6).Trim());
                        }
                    }
                    sr.Close();
                });
            }catch (Exception e) {
                Logger.error("DTCTools", "failed", e);
            }

            return(result);
        }
예제 #14
0
        public ConfigData(string file)
        {
            init();

            XmlReaderSettings xrs = new XmlReaderSettings();

            xrs.IgnoreWhitespace = true;
            xrs.IgnoreComments   = true;

            this.file = file;
            XmlReader reader = XmlReader.Create(file, xrs);

            reader.ReadStartElement("hobd");

            while (true)
            {
                if (reader.NodeType != XmlNodeType.Element)
                {
                    if (!reader.Read())
                    {
                        break;
                    }
                    continue;
                }
                switch (reader.Name)
                {
                case "log-level":
                    this.LogLevel = reader.ReadElementContentAsString();
                    break;

                case "port":
                    this.Port = reader.ReadElementContentAsString();
                    break;

                case "vehicles":
                    var v_file = reader.ReadElementContentAsString();
                    this.vehicle_files.Add(v_file);
                    try{
                        ReadVehicles(v_file);
                    }catch (Exception e) {
                        Logger.error("ConfigData", "fault reading vehicle from " + v_file, e);
                    }
                    break;

                case "vehicle":
                    this.Vehicle = reader.ReadElementContentAsString();
                    break;

                case "drivehub-token":
                    this.Token = reader.ReadElementContentAsString();
                    break;

                case "dpi":
                    this.DPI = reader.ReadElementContentAsInt();
                    break;

                case "fullscreen":
                    this.Fullscreen = reader.ReadElementContentAsString() == "true";
                    break;

                case "language":
                    this.Language = reader.ReadElementContentAsString();
                    break;

                case "units":
                    this.Units = reader.ReadElementContentAsString();
                    break;

                case "theme":
                    this.Theme = reader.ReadElementContentAsString();
                    break;

                case "layout":
                    this.Layout = reader.ReadElementContentAsString();
                    break;

                default:
                    reader.Read();
                    break;
                }
            }
            reader.Close();
        }
예제 #15
0
        void init(SensorRegistry registry)
        {
            if (reader == null)
            {
                throw new Exception("Can't do double init");
            }

            reader.ReadToFollowing("parameters");

            this.Namespace   = reader.GetAttribute("namespace") ?? "Default";
            this.Description = reader.GetAttribute("description") ?? "";

            reader.ReadStartElement("parameters");

            while (reader.NodeType == XmlNodeType.Element)
            {
                if (reader.Name == "include")
                {
                    var name   = reader.ReadElementString().Trim();
                    var ecuinc = new ECUXMLSensorProvider(System.IO.Path.Combine(Path, name));
                    ecuinc.init(registry);
                    continue;
                }

                if (reader.Name != "parameter")
                {
                    reader.ReadElementString();
                    continue;
                }

                var id      = reader.GetAttribute("id");
                var display = reader.GetAttribute("display");

                reader.ReadStartElement();

                int    command     = 0;
                string clazz       = null;
                string rawcommand  = null;
                string basename    = null;
                string basenameraw = null;

                int    replyoffset = 0;
                string units       = null;

                string value   = null;
                string word    = null;
                string wordle  = null;
                string dword   = null;
                string dwordle = null;

                bool   signed  = false;
                double scale   = 1;
                double offset  = 0;
                int    bit     = -1;
                int?   cutlow  = null;
                int?   cuthigh = null;

                while (reader.NodeType == XmlNodeType.Element)
                {
                    try{
                        switch (reader.Name)
                        {
                        case "class":
                            clazz = reader.ReadElementString().Trim();
                            break;

                        case "address":
                            reader.ReadStartElement();
                            var hexval = reader.ReadElementString("byte").Trim();
                            if (hexval.StartsWith("0x"))
                            {
                                hexval = hexval.Substring(2);
                            }
                            command = int.Parse(hexval, NumberStyles.HexNumber);
                            reader.ReadEndElement();
                            break;

                        case "raw":
                            rawcommand = reader.ReadElementString().Trim().Replace(";", "\r");
                            break;

                        case "base":
                            basename = reader.ReadElementString().Trim();
                            break;

                        case "base-raw":
                            basenameraw = reader.ReadElementString().Trim();
                            break;

                        case "value":
                        case "valuea":
                            value       = reader.ReadElementString();
                            scale       = double.Parse(value, UnitsConverter.DefaultNumberFormat);
                            replyoffset = 0;
                            break;

                        case "valueb":
                            value       = reader.ReadElementString();
                            scale       = double.Parse(value, UnitsConverter.DefaultNumberFormat);
                            replyoffset = 1;
                            break;

                        case "valuec":
                            value       = reader.ReadElementString();
                            scale       = double.Parse(value, UnitsConverter.DefaultNumberFormat);
                            replyoffset = 2;
                            break;

                        case "valued":
                            value       = reader.ReadElementString();
                            scale       = double.Parse(value, UnitsConverter.DefaultNumberFormat);
                            replyoffset = 3;
                            break;

                        case "valueab":
                            word        = reader.ReadElementString();
                            scale       = double.Parse(word, UnitsConverter.DefaultNumberFormat);
                            replyoffset = 0;
                            break;

                        case "valuebc":
                            word        = reader.ReadElementString();
                            scale       = double.Parse(word, UnitsConverter.DefaultNumberFormat);
                            replyoffset = 1;
                            break;

                        case "valuecd":
                            word        = reader.ReadElementString();
                            scale       = double.Parse(word, UnitsConverter.DefaultNumberFormat);
                            replyoffset = 2;
                            break;

                        case "signed":
                            signed = true;
                            reader.ReadElementString();
                            break;

                        case "offset":
                            offset = double.Parse(reader.ReadElementString(), UnitsConverter.DefaultNumberFormat);
                            break;

                        case "bit":
                            bit = int.Parse(reader.ReadElementString());
                            break;

                        case "cut-low":
                            cutlow = int.Parse(reader.ReadElementString());
                            break;

                        case "cut-high":
                            cuthigh = int.Parse(reader.ReadElementString());
                            break;

                        case "description":
                            reader.ReadStartElement();
                            while (reader.NodeType == XmlNodeType.Element)
                            {
                                switch (reader.Name)
                                {
                                case "unit":
                                    units = reader.ReadElementString().Trim();
                                    break;

                                default:
                                    reader.ReadElementString();
                                    break;
                                }
                            }
                            reader.ReadEndElement();
                            break;

                        default:
                            if (reader.Name.StartsWith("value-"))
                            {
                                replyoffset = int.Parse(reader.Name.Replace("value-", ""));
                                value       = reader.ReadElementContentAsString();
                                scale       = double.Parse(value, UnitsConverter.DefaultNumberFormat);
                            }
                            else
                            if (reader.Name.StartsWith("word-"))
                            {
                                replyoffset = int.Parse(reader.Name.Replace("word-", ""));
                                word        = reader.ReadElementContentAsString();
                                scale       = double.Parse(word, UnitsConverter.DefaultNumberFormat);
                            }
                            else
                            if (reader.Name.StartsWith("wordle-"))
                            {
                                replyoffset = int.Parse(reader.Name.Replace("wordle-", ""));
                                wordle      = reader.ReadElementContentAsString();
                                scale       = double.Parse(wordle, UnitsConverter.DefaultNumberFormat);
                            }
                            else
                            if (reader.Name.StartsWith("dword-"))
                            {
                                replyoffset = int.Parse(reader.Name.Replace("dword-", ""));
                                dword       = reader.ReadElementContentAsString();
                                scale       = double.Parse(dword, UnitsConverter.DefaultNumberFormat);
                            }
                            else
                            if (reader.Name.StartsWith("dwordle-"))
                            {
                                replyoffset = int.Parse(reader.Name.Replace("dwordle-", ""));
                                dwordle     = reader.ReadElementContentAsString();
                                scale       = double.Parse(dwordle, UnitsConverter.DefaultNumberFormat);
                            }
                            else
                            {
                                throw new Exception("unknown tag `" + reader.Name + "` while creating PID " + id);
                            }
                            break;
                        }
                    }catch (Exception e) {
                        Logger.error("ECUXMLSensorProvider", "bad sensor param: " + id, e);
                    }
                }

                Func <double, double> evaluator = (v) => {
                    if (signed)
                    {
                        if (dword != null || dwordle != null)
                        {
                            v = (double)(int)((uint)v);
                        }
                        else if (word != null || wordle != null)
                        {
                            v = (double)(short)((ushort)v);
                        }
                        else
                        {
                            v = (double)(sbyte)((byte)v);
                        }
                    }
                    var res = v * scale + offset;
                    if (bit != -1)
                    {
                        res = ((int)res >> bit) & 1;
                    }
                    if (cutlow != null)
                    {
                        res = res < cutlow ? 0 : res;
                    }
                    if (cuthigh != null)
                    {
                        res = res > cuthigh ? 0 : res;
                    }
                    return(res);
                };

                CoreSensor sensor = null;
                if (clazz != null)
                {
                    sensor = (CoreSensor)registry.CreateObject(clazz);
                }
                // OBD2 derived sensor
                else if (basename != null)
                {
                    // Custom derived sensor
                    var s = new DerivedSensor("", basename, null);
                    if (value != null)
                    {
                        s.DerivedValue = (a, b) => evaluator(a.Value);
                    }
                    sensor = s;
                }
                // RAW data from base sensor
                else if (basenameraw != null)
                {
                    // Custom derived sensor
                    var s = new DerivedSensor("", basenameraw, null);
                    if (value != null)
                    {
                        s.DerivedValue = (a, b) => evaluator((a as OBD2Sensor).getraw(replyoffset));
                    }
                    if (word != null)
                    {
                        s.DerivedValue = (a, b) => evaluator((a as OBD2Sensor).getraw_word(replyoffset));
                    }
                    if (wordle != null)
                    {
                        s.DerivedValue = (a, b) => evaluator((a as OBD2Sensor).getraw_wordle(replyoffset));
                    }
                    if (dword != null)
                    {
                        s.DerivedValue = (a, b) => evaluator((a as OBD2Sensor).getraw_dword(replyoffset));
                    }
                    if (dwordle != null)
                    {
                        s.DerivedValue = (a, b) => evaluator((a as OBD2Sensor).getraw_dwordle(replyoffset));
                    }
                    sensor = s;
                }
                // command / raw command
                else if (basename == null)
                {
                    var s = new OBD2Sensor();

                    if (value != null)
                    {
                        s.obdValue = (p) => evaluator(p.get(replyoffset));
                    }
                    if (word != null)
                    {
                        s.obdValue = (p) => evaluator(p.get_word(replyoffset));
                    }
                    sensor = s;
                }

                if (sensor != null && sensor is OBD2Sensor)
                {
                    if (rawcommand != null)
                    {
                        (sensor as OBD2Sensor).RawCommand = rawcommand;
                    }
                    else if (command != 0)
                    {
                        (sensor as OBD2Sensor).Command = command;
                    }
                }

                if (sensor != null)
                {
                    sensor.ID   = this.Namespace + "." + id;
                    sensor.Name = id;
                    //sensor.Display = display;
                    if (units != null)
                    {
                        sensor.Units = units;
                    }

                    registry.Add(sensor);
                }
                reader.ReadEndElement();
            }

            reader.ReadEndElement();
            reader.Close();
            reader = null;
        }
예제 #16
0
        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;
            }
        }
예제 #17
0
파일: OBD2Engine.cs 프로젝트: leewoody/hobd
        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;
                }
            }
        }
예제 #18
0
파일: OBD2Engine.cs 프로젝트: leewoody/hobd
        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;
            }
        }
예제 #19
0
파일: OBD2Engine.cs 프로젝트: leewoody/hobd
        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;
            }
        }
예제 #20
0
        public SensorTextElement(Sensor sensor, Dictionary <string, string> attrs)
        {
            this.Text = "-";

            this.Name = HOBD.t("sname." + sensor.Name);

            this.Units          = sensor.Units;
            this.needConversion = HOBD.uConverter.NeedConversion(this.Units);
            if (this.needConversion)
            {
                this.TUnits = HOBD.uConverter.ConvertUnits(this.Units);
            }
            else
            {
                this.TUnits = this.Units;
            }
            this.TUnits = HOBD.t(this.TUnits);
            if (this.Units == "seconds")
            {
                customFormat = true;
            }

            this.Style = new TextStyle(HOBD.theme.PhoneTextNormalStyle);

            string textSize = null;

            attrs.TryGetValue("size", out textSize);

            if (textSize == "small")
            {
                this.Style.FontSize = HOBD.theme.PhoneFontSizeNormal;
            }
            else if (textSize == "large")
            {
                this.Style.FontSize = HOBD.theme.PhoneFontSizeLarge;
            }
            else if (textSize == "huge")
            {
                this.Style.FontSize = HOBD.theme.PhoneFontSizeExtraExtraLarge;
            }
            else if (textSize == "giant")
            {
                this.Style.FontSize = HOBD.theme.PhoneFontSizeHuge;
            }
            else
            {
                this.Style.FontSize = HOBD.theme.PhoneFontSizeMediumLarge;
            }

            string precision = null;

            attrs.TryGetValue("precision", out precision);
            if (precision != null)
            {
                try {
                    this.Precision = int.Parse(precision);
                }catch (Exception e) {
                    Logger.error("SensorTextElement", "init", e);
                }
            }

            //var style = new TextStyle(HOBD.theme.PhoneTextLargeStyle.FontFamily, HOBD.theme.PhoneFontSizeMediumLarge, HOBD.theme.PanoramaNormalBrush);
        }
예제 #21
0
        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);
        }
예제 #22
0
파일: HOBDTheme.cs 프로젝트: leewoody/hobd
        public static HOBDTheme LoadTheme(string file)
        {
            HOBDTheme theme = new HOBDTheme();

            theme.File = file;

            XmlReaderSettings xrs = new XmlReaderSettings();

            xrs.IgnoreWhitespace = true;
            xrs.IgnoreComments   = true;

            try{
                XmlReader reader = XmlReader.Create(file, xrs);

                reader.ReadToDescendant("theme");

                theme.Name       = reader.GetAttribute("name");
                theme.Background = reader.GetAttribute("background");

                reader.ReadStartElement("theme");

                while (true)
                {
                    if (reader.NodeType != XmlNodeType.Element)
                    {
                        if (!reader.Read())
                        {
                            break;
                        }
                        continue;
                    }
                    string name;
                    string val;
                    int    ival;
                    switch (reader.Name)
                    {
                    case "color":
                        name = reader.GetAttribute("name");
                        val  = reader.ReadElementContentAsString();
                        theme.Colors.Add(name, Color.FromArgb(ParseColor(val)));
                        break;

                    case "font-size":
                        name = reader.GetAttribute("name");
                        val  = reader.GetAttribute("value");
                        ival = Int32.Parse(val, NumberStyles.Integer);
                        theme.FontSizes.Add(name, ival);
                        reader.Read();
                        break;

                    case "font-family":
                        name = reader.GetAttribute("name");
                        val  = reader.ReadElementContentAsString();
                        theme.FontFamilies.Add(name, val);
                        break;

                    case "style":
                        name = reader.GetAttribute("name");

                        TextStyle style = new TextStyle(theme.PhoneTextNormalStyle);

                        reader.ReadStartElement();
                        while (reader.NodeType != XmlNodeType.EndElement)
                        {
                            if (reader.NodeType != XmlNodeType.Element)
                            {
                                continue;
                            }

                            switch (reader.Name)
                            {
                            case "font":
                                val = reader.ReadElementContentAsString();
                                theme.FontFamilies.TryGetValue(val, out val);
                                style.FontFamily = val;
                                break;

                            case "size":
                                val = reader.ReadElementContentAsString();
                                if (!theme.FontSizes.TryGetValue(val, out ival))
                                {
                                    ival = Int32.Parse(val);
                                }
                                style.FontSize = ival;
                                break;

                            case "color":
                                val = reader.ReadElementContentAsString();
                                Color color;
                                if (!theme.Colors.TryGetValue(val, out color))
                                {
                                    color = Color.FromArgb(ParseColor(val));
                                }
                                style.Foreground = color;
                                break;
                            }
                        }
                        reader.ReadEndElement();
                        theme.Styles.Add(name, style);
                        break;

                    default:
                        reader.Read();
                        break;
                    }
                }
                reader.Close();

                theme.Styles.TryGetValue("PanoramaTitle", out theme.PhoneTextPanoramaTitleStyle);
                theme.Styles.TryGetValue("PanoramaSubTitle", out theme.PhoneTextPanoramaSubTitleStyle);
                theme.Styles.TryGetValue("PanoramaSectionTitle", out theme.PhoneTextPanoramaSectionTitleStyle);

                theme.Styles.TryGetValue("TextNormal", out theme.PhoneTextNormalStyle);
                theme.Styles.TryGetValue("TextStatus", out theme.PhoneTextStatusStyle);
                theme.Styles.TryGetValue("TextSensorDescr", out theme.PhoneTextSensorDescrStyle);
            }catch (Exception e) {
                Logger.error("HOBDTheme", "error parsing theme file", e);
            }

            return(theme);
        }
예제 #23
0
파일: HomePage.cs 프로젝트: leewoody/hobd
        protected virtual void LoadSections()
        {
            try{
                XmlReaderSettings xrs = new XmlReaderSettings();
                xrs.IgnoreWhitespace = true;
                xrs.IgnoreComments   = true;

                XmlReader reader = XmlReader.Create(Path.Combine(HOBD.AppPath, HOBD.config.Layout), xrs);
                reader.Read();
                reader.ReadStartElement("ui");

                while (reader.IsStartElement("section"))
                {
                    var title   = t(reader.GetAttribute("name"));
                    var section = CreateCommonSection(title);

                    reader.ReadStartElement("section");

                    if (reader.IsStartElement("grid"))
                    {
                        var rows = reader.GetAttribute("rows");
                        var cols = reader.GetAttribute("cols");

                        var rows_a = rows.Split(seps).Select(r => r.Trim().Length == 0 ? 0 : int.Parse(r.Trim()));
                        var cols_a = cols.Split(seps).Select(r => r.Trim().Length == 0 ? 0 : int.Parse(r.Trim()));

                        var converted = new IEnumerable <int>[] { rows_a, cols_a }.Select(arr => {
                            var arr_s = arr.Sum();
                            if (arr_s < 100)
                            {
                                var count = arr.Count(r => r == 0);
                                if (count > 0)
                                {
                                    int autosize = (100 - arr_s) / count;
                                    arr          = arr.Select(r => r == 0 ? autosize : r);
                                }
                            }
                            return(arr);
                        }).ToList();

                        rows_a = converted[0].Select(r => r * this.layoutY / 100);
                        cols_a = converted[1].Select(r => r * this.layoutX / 100);

                        var grid = new Grid
                        {
                            Columns = cols_a.Select(r => (MeasureDefinition)r).ToArray(),
                            Rows    = rows_a.Select(r => (MeasureDefinition)r).ToArray(),
                        };

                        int crow = 0, ccol = 0;

                        reader.ReadStartElement("grid");
                        while (reader.IsStartElement("item"))
                        {
                            var attrs = new Dictionary <string, string>();
                            while (reader.MoveToNextAttribute())
                            {
                                attrs.Add(reader.Name, reader.Value);
                            }
                            reader.MoveToElement();

                            reader.ReadStartElement("item");

                            // attrs
                            var sensorItem = CreateItem(attrs, section);

                            if (sensorItem != null)
                            {
                                grid.Add(crow, ccol, sensorItem);
                            }

                            // next item in grid
                            ccol++;
                            if (ccol == cols_a.Count())
                            {
                                ccol = 0;
                                crow++;
                            }
                            if (crow == rows_a.Count())
                            {
                                break;
                            }
                        }
                        grid.Location = new Point(10, 0);
                        grid.Size     = new Size(layoutX, layoutY - SectionContentDelta);
                        section.AddElement(grid);

                        reader.ReadEndElement();
                    }
                    this.panorama.AddSection(section);

                    reader.ReadEndElement();
                }
            }catch (XmlException e) {
                Logger.error("HomePage", "error creating layout", e);
            }
        }