Exemple #1
0
        public override double?GetVehicleMeterReading_kWh()
        {
            string j = null;

            try
            {
                j = GetCurrentData();

                dynamic jsonResult = new JavaScriptSerializer().DeserializeObject(j);
                decimal value1     = jsonResult["emeters"][0]["total"];
                decimal value2     = jsonResult["emeters"][1]["total"];
                decimal value3     = jsonResult["emeters"][2]["total"];

                return((double?)(value1 + value2 + value3) / 1000.0);
            }
            catch (Exception ex)
            {
                Logfile.ExceptionWriter(ex, j);
            }

            return(null);
        }
Exemple #2
0
        private static void ReadGeofenceFile(List <Address> list, string filename)
        {
            if (System.IO.File.Exists(filename))
            {
                Logfile.Log("Read Geofence File: " + filename);
                string line;
                using (System.IO.StreamReader file = new System.IO.StreamReader(filename))
                {
                    while ((line = file.ReadLine()) != null)
                    {
                        try
                        {
                            if (String.IsNullOrEmpty(line))
                            {
                                continue;
                            }

                            var args = line.Split(',');
                            list.Add(new Address(args[0].Trim(),
                                                 Double.Parse(args[1].Trim(), Tools.ciEnUS.NumberFormat),
                                                 Double.Parse(args[2].Trim(), Tools.ciEnUS.NumberFormat)));

                            if (!filename.Contains("geofence.csv"))
                            {
                                Logfile.Log("Address inserted: " + args[0]);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logfile.ExceptionWriter(ex, line);
                        }
                    }
                }
            }
            else
            {
                Logfile.Log("FileNotFound: " + filename);
            }
        }
        public override bool?IsCharging()
        {
            string j = null;

            try
            {
                j = GetCurrentDataVitals();
                j = j.Replace("nan,", "null,");

                dynamic jsonResult = new JavaScriptSerializer().DeserializeObject(j);

                bool vehicle_connected = jsonResult["vehicle_connected"];

                return(vehicle_connected);
            }
            catch (Exception ex)
            {
                Logfile.ExceptionWriter(ex, j);
            }

            return(null);
        }
Exemple #4
0
        private static void EnableHighFrequencyLoggingMode(HFLMode _mode, int _ticklimit, DateTime _until)
        {
            Logfile.Log("enable HighFrequencyLogging - mode: " + _mode.ToString() + (_mode == HFLMode.Ticks ? " ticks: " + _ticklimit : " until: " + _until.ToString()));
            switch (_mode)
            {
            case HFLMode.Ticks:
                highFrequencyLogging           = true;
                highFrequencyLoggingMode       = _mode;
                highFrequencyLoggingTicksLimit = _ticklimit;
                break;

            case HFLMode.Time:
                highFrequencyLogging      = true;
                highFrequencyLoggingMode  = _mode;
                highFrequencyLoggingUntil = _until;
                break;

            default:
                Logfile.Log("EnableHighFrequencyLoggingMode default");
                break;
            }
        }
Exemple #5
0
        public static void HandleShiftStateChange(string _oldState, string _newState)
        {
            Logfile.Log("ShiftStateChange: " + _oldState + " -> " + _newState);
            Address addr = WebHelper.geofence.GetPOI(DBHelper.currentJSON.latitude, DBHelper.currentJSON.longitude, false);

            // process special flags for POI
            if (addr != null && addr.specialFlags != null && addr.specialFlags.Count > 0)
            {
                foreach (KeyValuePair <Address.SpecialFlags, string> flag in addr.specialFlags)
                {
                    switch (flag.Key)
                    {
                    case Address.SpecialFlags.OpenChargePort:
                        HandleSpecialFlag_OpenChargePort(flag.Value, _oldState, _newState);
                        break;

                    case Address.SpecialFlags.HighFrequencyLogging:
                        break;

                    case Address.SpecialFlags.EnableSentryMode:
                        HandleSpeciaFlag_EnableSentryMode(flag.Value, _oldState, _newState);
                        break;

                    default:
                        Logfile.Log("handleShiftStateChange unhandled special flag " + flag.ToString());
                        break;
                    }
                }
            }
            // execute shift state change actions independant from special flags
            // TODO discuss!

            /*if (_newState.Equals("D") && DBHelper.currentJSON.current_is_sentry_mode)
             * {
             *  Logfile.Log("DisableSentryMode ...");
             *  string result = webhelper.PostCommand("command/set_sentry_mode?on=false", null).Result;
             *  Logfile.Log("DisableSentryMode(): " + result);
             * }*/
        }
Exemple #6
0
        string GetCurrentData()
        {
            try
            {
                if (mockup_status != null)
                {
                    return(mockup_status);
                }

                string cacheKey = "3EM_" + guid.ToString();
                object o        = MemoryCache.Default.Get(cacheKey);

                if (o != null)
                {
                    return((string)o);
                }

                string url      = host + "/status";
                string lastJSON = client.DownloadString(url);

                MemoryCache.Default.Add(cacheKey, lastJSON, DateTime.Now.AddSeconds(10));
                return(lastJSON);
            }
            catch (Exception ex)
            {
                if (ex is WebException wx)
                {
                    if ((wx.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
                    {
                        Logfile.Log(wx.Message);
                        return("");
                    }
                }
                ex.ToExceptionless().FirstCarUserID().Submit();
                Logfile.Log(ex.ToString());
            }

            return("");
        }
        public override double?GetVehicleMeterReading_kWh()
        {
            try
            {
                Send("report 3");
                dynamic reportJson;
                do
                {
                    string reply = Receive();
                    reportJson = JsonConvert.DeserializeObject(reply);
                } while (reportJson.ID != 3);

                return((double)reportJson["E total"] / 10000.0);
            }
            catch (Exception ex)
            {
                ex.ToExceptionless().FirstCarUserID().Submit();
                Logfile.Log(ex.ToString());
            }

            return(null);
        }
        public override bool?IsCharging()
        {
            try
            {
                Send("report 2");
                dynamic reportJson;
                do
                {
                    string reply = Receive();
                    reportJson = JsonConvert.DeserializeObject(reply);
                } while (reportJson.ID != 2);

                return((int)reportJson.State == 3);
            }
            catch (Exception ex)
            {
                ex.ToExceptionless().FirstCarUserID().Submit();
                Logfile.Log(ex.ToString());
            }

            return(null);
        }
        public override string GetVersion()
        {
            try
            {
                Send("report 1");
                dynamic reportJson;
                do
                {
                    string reply = Receive();
                    reportJson = JsonConvert.DeserializeObject(reply);
                } while (reportJson.ID != 1);

                return(reportJson.Product + " / fw:" + reportJson.Firmware);
            }
            catch (Exception ex)
            {
                ex.ToExceptionless().FirstCarUserID().Submit();
                Logfile.Log(ex.ToString());
            }

            return(null);
        }
Exemple #10
0
        private void Getchargingstate(HttpListenerRequest request, HttpListenerResponse response)
        {
            string id             = request.QueryString["id"];
            string responseString = "";

            try
            {
                Logfile.Log("HTTP getchargingstate");
                DataTable        dt = new DataTable();
                MySqlDataAdapter da = new MySqlDataAdapter("SELECT chargingstate.*, lat, lng, address, charging.charge_energy_added as kWh FROM chargingstate join pos on chargingstate.pos = pos.id join charging on chargingstate.EndChargingID = charging.id where chargingstate.id = @id", DBHelper.DBConnectionstring);
                da.SelectCommand.Parameters.AddWithValue("@id", id);
                da.Fill(dt);

                responseString = dt.Rows.Count > 0 ? Tools.DataTableToJSONWithJavaScriptSerializer(dt) : "not found!";
            }
            catch (Exception ex)
            {
                Logfile.Log(ex.ToString());
            }

            WriteString(response, responseString);
        }
Exemple #11
0
        private static void HandleSpecialFlag_SetChargeLimit(Address _addr, string _flagconfig)
        {
            string pattern = "([0-9]+)";
            Match  m       = Regex.Match(_flagconfig, pattern);

            if (m.Success && m.Groups.Count == 2 && m.Groups[1].Captures.Count == 1)
            {
                if (m.Groups[1].Captures[0] != null && int.TryParse(m.Groups[1].Captures[0].ToString(), out int chargelimit))
                {
                    if (!lastSetChargeLimitAddressName.Equals(_addr.name))
                    {
                        Task.Factory.StartNew(() =>
                        {
                            Logfile.Log($"SetChargeLimit to {chargelimit} ...");
                            string result = webhelper.PostCommand("command/set_charge_limit", "{\"percent\":" + chargelimit + "}", true).Result;
                            Logfile.Log("set_charge_limit(): " + result);
                            lastSetChargeLimitAddressName = _addr.name;
                        });
                    }
                }
            }
        }
Exemple #12
0
        private static void StartMqttClient()
        {
            string MQTTClientPath = "/etc/teslalogger/MQTTClient.exe";

            try
            {
                if (!System.IO.File.Exists(MQTTClientPath))
                {
                    Logfile.Log("MQTTClient.exe not found!");
                    return;
                }

                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.EnableRaisingEvents              = false;
                proc.StartInfo.UseShellExecute        = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.FileName  = "mono";
                proc.StartInfo.Arguments = MQTTClientPath;

                proc.Start();

                while (!proc.StandardOutput.EndOfStream)
                {
                    string line = proc.StandardOutput.ReadLine();
                    Logfile.Log(line);
                }

                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                Logfile.Log(ex.ToString());
            }
            finally
            {
                Logfile.Log("MQTT terminated");
            }
        }
Exemple #13
0
        private static void UpdateChargingstate(int chargingstate_id, DateTime StartDate, int StartChargingID)
        {
            try
            {
                Logfile.Log($"Update Chargingstate {chargingstate_id} with new StartDate: {StartDate} /  StartChargingID: {StartChargingID}");

                using (MySqlConnection con = new MySqlConnection(DBConnectionstring))
                {
                    con.Open();
                    MySqlCommand cmd = new MySqlCommand(@"update chargingstate set StartDate=@StartDate, StartChargingID=@StartChargingID where id = @id", con);
                    cmd.Parameters.AddWithValue("@id", chargingstate_id);
                    cmd.Parameters.AddWithValue("@StartDate", StartDate);
                    cmd.Parameters.AddWithValue("@StartChargingID", StartChargingID);

                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                Logfile.ExceptionWriter(ex, chargingstate_id.ToString());
                Logfile.Log(ex.ToString());
            }
        }
Exemple #14
0
        private static void InitStage1()
        {
            Tools.SetThreadEnUS();
            UpdateTeslalogger.Chmod("nohup.out", 666, false);
            UpdateTeslalogger.Chmod("backup.sh", 777, false);
            UpdateTeslalogger.Chmod("TeslaLogger.exe", 755, false);

#pragma warning disable CA5364 // Verwenden Sie keine veralteten Sicherheitsprotokolle.
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
#pragma warning restore CA5364 // Verwenden Sie keine veralteten Sicherheitsprotokolle.

            Logfile.Log("TeslaLogger Version: " + Assembly.GetExecutingAssembly().GetName().Version);
            Logfile.Log("Teslalogger Online Version: " + WebHelper.GetOnlineTeslaloggerVersion());
            Logfile.Log("Logfile Version: " + Assembly.GetAssembly(typeof(Logfile)).GetName().Version);
            Logfile.Log("SRTM Version: " + Assembly.GetAssembly(typeof(SRTM.SRTMData)).GetName().Version);
            try
            {
                string versionpath = Path.Combine(FileManager.GetExecutingPath(), "VERSION");
                File.WriteAllText(versionpath, Assembly.GetExecutingAssembly().GetName().Version.ToString());
            }
            catch (Exception)
            { }
        }
        public override double?GetVehicleMeterReading_kWh()
        {
            string j = null;

            try
            {
                j = GetCurrentData();

                dynamic jsonResult = new JavaScriptSerializer().DeserializeObject(j);
                string  key        = "llkwhLP" + LP;
                string  value      = jsonResult[key];

                double v = Double.Parse(value, Tools.ciEnUS);

                return(v);
            }
            catch (Exception ex)
            {
                Logfile.ExceptionWriter(ex, j);
            }

            return(null);
        }
        public override bool?IsCharging()
        {
            string j = null;

            try
            {
                j = GetCurrentDataVitals();
                j = j.Replace("nan,", "null,");

                dynamic jsonResult = JsonConvert.DeserializeObject(j);

                bool vehicle_connected = jsonResult["vehicle_connected"];

                return(vehicle_connected);
            }
            catch (Exception ex)
            {
                ex.ToExceptionless().FirstCarUserID().Submit();
                Logfile.ExceptionWriter(ex, j);
            }

            return(null);
        }
Exemple #17
0
        public override double?GetVehicleMeterReading_kWh()
        {
            string j = null;

            try
            {
                j = GetCurrentData();

                dynamic jsonResult = JsonConvert.DeserializeObject(j);
                decimal value1     = jsonResult["emeters"][0]["total"];
                decimal value2     = jsonResult["emeters"][1]["total"];
                decimal value3     = jsonResult["emeters"][2]["total"];

                return((double?)(value1 + value2 + value3) / 1000.0);
            }
            catch (Exception ex)
            {
                ex.ToExceptionless().FirstCarUserID().Submit();
                Logfile.ExceptionWriter(ex, j);
            }

            return(null);
        }
Exemple #18
0
        internal static string GetLastCarVersion()
        {
            try
            {
                using (MySqlConnection con = new MySqlConnection(DBConnectionstring))
                {
                    con.Open();
                    MySqlCommand    cmd = new MySqlCommand("select version from car_version order by id desc limit 1", con);
                    MySqlDataReader dr  = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        return(dr[0].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                Logfile.ExceptionWriter(ex, "GetLastCarVersion");
                Logfile.Log(ex.ToString());
            }

            return("");
        }
Exemple #19
0
        public override bool?IsCharging()
        {
            string j = null;

            try
            {
                j = GetCurrentData();

                dynamic jsonResult = new JavaScriptSerializer().DeserializeObject(j);
                decimal value1     = jsonResult["emeters"][0]["power"];
                decimal value2     = jsonResult["emeters"][1]["power"];
                decimal value3     = jsonResult["emeters"][2]["power"];
                decimal watt_total = (value1 + value2 + value3);

                return(watt_total > 3000);
            }
            catch (Exception ex)
            {
                Logfile.ExceptionWriter(ex, j);
            }

            return(null);
        }
Exemple #20
0
        private void GetAllCars(HttpListenerRequest request, HttpListenerResponse response)
        {
            string responseString = "";

            try
            {
                using (DataTable dt = new DataTable())
                {
                    using (MySqlDataAdapter da = new MySqlDataAdapter("SELECT id, display_name, tasker_hash, model_name, vin, tesla_name, tesla_carid, lastscanmytesla, freesuc FROM cars order by display_name", DBHelper.DBConnectionstring))
                    {
                        da.Fill(dt);

                        responseString = dt.Rows.Count > 0 ? Tools.DataTableToJSONWithJavaScriptSerializer(dt) : "not found!";
                    }
                }
            }
            catch (Exception ex)
            {
                Logfile.Log(ex.ToString());
            }

            WriteString(response, responseString);
        }
        public override double?GetUtilityMeterReading_kWh()
        {
            string j = null;

            try
            {
                j = GetCurrentData();

                dynamic jsonResult = new JavaScriptSerializer().DeserializeObject(j);
                string  value      = jsonResult["evubezugWh"];

                double v = Double.Parse(value, Tools.ciEnUS);
                v = v / 1000;

                return(v);
            }
            catch (Exception ex)
            {
                Logfile.ExceptionWriter(ex, j);
            }

            return(null);
        }
Exemple #22
0
        private static void InitStage2()
        {
            Logfile.Log("Current Culture: " + Thread.CurrentThread.CurrentCulture.ToString());
            Logfile.Log("Mono Runtime: " + Tools.GetMonoRuntimeVersion());
            Logfile.Log("Grafana Version: " + Tools.GetGrafanaVersion());
            Logfile.Log("OS Version: " + Tools.GetOsVersion());
            Logfile.Log("Update Settings: " + Tools.GetOnlineUpdateSettings().ToString());

            Logfile.Log("DBConnectionstring: " + DBHelper.DBConnectionstring);

            Logfile.Log("KeepOnlineMinAfterUsage: " + ApplicationSettings.Default.KeepOnlineMinAfterUsage);
            Logfile.Log("SuspendAPIMinutes: " + ApplicationSettings.Default.SuspendAPIMinutes);
            Logfile.Log("SleepPositions: " + ApplicationSettings.Default.SleepPosition);
            Logfile.Log("UseScanMyTesla: " + Tools.UseScanMyTesla());
            try
            {
                Logfile.Log($"Free disk space: {Tools.FreeDiskSpaceMB()}mb");
            }
            catch (Exception ex)
            {
                Logfile.ExceptionWriter(ex, ex.ToString());
            }
        }
Exemple #23
0
        public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
        {
            try
            {
                foreach (DirectoryInfo dir in source.GetDirectories())
                {
                    CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
                }

                foreach (FileInfo file in source.GetFiles())
                {
                    string p = Path.Combine(target.FullName, file.Name);

                    Logfile.Log("Copy '" + file.FullName + "' to '" + p + "'");

                    File.Copy(file.FullName, p, true);
                }
            }
            catch (Exception ex)
            {
                Logfile.Log("CopyFilesRecursively Exception: " + ex.ToString());
            }
        }
Exemple #24
0
        public static void chmod(string filename, int chmod)
        {
            try
            {
                if (!Tools.IsMono())
                {
                    return;
                }

                Logfile.Log("chmod " + chmod + " " + filename);

                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.EnableRaisingEvents = false;
                proc.StartInfo.FileName  = "chmod";
                proc.StartInfo.Arguments = chmod + " " + filename;
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                Logfile.Log("chmod " + filename + " " + ex.Message);
            }
        }
Exemple #25
0
        public static bool IsShareData()
        {
            try
            {
                string filepath = System.IO.Path.Combine(FileManager.GetExecutingPath(), "sharedata.txt");
                if (File.Exists(filepath))
                {
                    return(true);
                }

                filepath = System.IO.Path.Combine(FileManager.GetExecutingPath(), "sharedata.txt.txt");
                if (File.Exists(filepath))
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Logfile.ExceptionWriter(ex, "IsShareData");
            }

            return(false);
        }
Exemple #26
0
        private static void InitCheckDocker()
        {
            try
            {
                if (Tools.IsDocker())
                {
                    Logfile.Log("Docker: YES!");

                    if (!File.Exists("/etc/teslalogger/settings.json"))
                    {
                        Logfile.Log("Creating empty settings.json");
                        File.AppendAllText("/etc/teslalogger/settings.json", "{\"SleepTimeSpanStart\":\"\",\"SleepTimeSpanEnd\":\"\",\"SleepTimeSpanEnable\":\"false\",\"Power\":\"hp\",\"Temperature\":\"celsius\",\"Length\":\"km\",\"Language\":\"en\",\"URL_Admin\":\"\",\"ScanMyTesla\":\"false\"}");
                        UpdateTeslalogger.Chmod("/etc/teslalogger/settings.json", 666);
                    }

                    if (!Directory.Exists("/etc/teslalogger/backup"))
                    {
                        Directory.CreateDirectory("/etc/teslalogger/backup");
                        UpdateTeslalogger.Chmod("/etc/teslalogger/backup", 777);
                    }

                    if (!Directory.Exists("/etc/teslalogger/Exception"))
                    {
                        Directory.CreateDirectory("/etc/teslalogger/Exception");
                        UpdateTeslalogger.Chmod("/etc/teslalogger/Exception", 777);
                    }
                }
                else
                {
                    Logfile.Log("Docker: NO!");
                }
            }
            catch (Exception ex)
            {
                Logfile.Log(ex.ToString());
            }
        }
Exemple #27
0
        private static void Main(string[] args)
        {
            try
            {
                InitDebugLogging();

                InitStage1();

                InitCheckDocker();

                InitStage2();

                InitConnectToDB();

                InitWebserver();

                InitOpenTopoDataService();

                UpdateTeslalogger.StopComfortingMessagesThread();

                MQTTClient.StartMQTTClient();

                InitTLStats();

                UpdateDbInBackground();

                Logfile.Log("Init finished, now enter main loop");

                GetAllCars();
            }
            catch (Exception ex)
            {
                Logfile.Log(ex.Message);
                Logfile.ExceptionWriter(ex, "main loop");
                Logfile.Log("Teslalogger Stopped!");
            }
        }
Exemple #28
0
        internal static void StartSleeping(out int startSleepingHour, out int startSleepingMinutes)
        {
            startSleepingHour    = -1;
            startSleepingMinutes = -1;

            try
            {
                var filePath = FileManager.GetFilePath(TLFilename.SettingsFilename);

                if (!File.Exists(filePath))
                {
                    return;
                }

                string  json = File.ReadAllText(filePath);
                dynamic j    = new JavaScriptSerializer().DeserializeObject(json);

                if (IsPropertyExist(j, "SleepTimeSpanEnable") && IsPropertyExist(j, "SleepTimeSpanStart"))
                {
                    if (Boolean.Parse(j["SleepTimeSpanEnable"]))
                    {
                        string   start = j["SleepTimeSpanStart"];
                        string[] s     = start.Split(':');

                        if (s.Length >= 2)
                        {
                            int.TryParse(s[0], out startSleepingHour);
                            int.TryParse(s[1], out startSleepingMinutes);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logfile.Log(ex.ToString());
            }
        }
Exemple #29
0
        // sleep 10000 unless in highFrequencyLogging mode
        private static void HandleState_Charge()
        {
            {
                if (!webhelper.IsCharging())
                {
                    SetCurrentState(TeslaState.Start);
                    webhelper.IsDriving(true);
                }
                else
                {
                    lastCarUsed = DateTime.Now;
                    if (IsHighFrequenceLoggingEnabled())
                    {
                        Logfile.Log("HighFrequenceLogging ...");
                    }
                    else
                    {
                        Thread.Sleep(10000);
                    }

                    //wh.GetCachedRollupData();
                }
            }
        }
Exemple #30
0
        private static void UpdatePHPini()
        {
            try
            {
                string phpinipath = "/etc/php/7.0/apache2/php.ini";
                if (File.Exists(phpinipath))
                {
                    string phpini    = File.ReadAllText("/etc/php/7.0/apache2/php.ini");
                    string newphpini = System.Text.RegularExpressions.Regex.Replace(phpini, "(post_max_size\\s*=)(.*)", "$1 50M");
                    newphpini = System.Text.RegularExpressions.Regex.Replace(newphpini, "(upload_max_filesize\\s*=)(.*)", "$1 50M");

                    File.WriteAllText(phpinipath, newphpini);

                    if (newphpini != phpini)
                    {
                        Logfile.Log("PHP.ini changed!");
                    }
                }
            }
            catch (Exception ex)
            {
                Logfile.Log(ex.ToString());
            }
        }