public static void CheckDBCharset() { try { using (MySqlConnection con = new MySqlConnection(DBHelper.DBConnectionstring)) { con.Open(); MySqlCommand cmd = new MySqlCommand("SELECT default_character_set_name FROM information_schema.SCHEMATA WHERE schema_name = 'teslalogger'; ", con); MySqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { string charset = dr[0].ToString(); if (charset != "utf8mb4") { dr.Close(); Logfile.Log("Chage database charset to utf8mb4"); cmd = new MySqlCommand("ALTER DATABASE teslalogger CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci", con); cmd.ExecuteNonQuery(); } } } } catch (Exception ex) { Logfile.Log(ex.ToString()); } }
static Dictionary <string, string> GetLanguageDictionary(string language) { System.Collections.Generic.Dictionary <string, string> ht = new Dictionary <string, string>(); string filename = Path.Combine(FileManager.GetExecutingPath(), "language-" + language + ".txt"); string content = null; if (System.IO.File.Exists(filename)) { try { String[] lines = File.ReadAllLines(filename); foreach (string line in lines) { content = line; if (line.Length == 0) { continue; } if (line.StartsWith("#")) { continue; } if (!line.Contains("=")) { continue; } int pos = line.IndexOf("="); string key = line.Substring(0, pos).Trim(); string value = line.Substring(pos + 1); // Logfile.Log("Key insert: " + key); if (ht.ContainsKey(key)) { Logfile.Log($"Error Key '{key}' already in Dictionary!!!"); continue; } if (value.Trim().Length > 0) { ht.Add(key, value); } else { ht.Add(key, key + " xxx"); } } } catch (Exception ex) { Logfile.Log(ex.Message); Logfile.ExceptionWriter(ex, content); } } return(ht); }
private static void InitNearbySuCService() { try { if (Tools.UseNearbySuCService()) { Thread threadNearbySuCService = new Thread(() => { NearbySuCService.GetSingleton().Run(); }) { Name = "NearbySuCServiceThread" }; threadNearbySuCService.Start(); } else { Logfile.Log("NearbySuCService disabled (enable in settings)"); } } catch (Exception ex) { Logfile.Log(ex.ToString()); } }
private static void InitConnectToDB() { for (int x = 1; x <= 30; x++) // try 30 times until DB is up and running { try { Logfile.Log("DB Version: " + DBHelper.GetVersion()); Logfile.Log("Count Pos: " + DBHelper.CountPos()); // test the DBConnection break; } catch (Exception ex) { if (ex.Message.Contains("Connection refused")) { Logfile.Log($"Wait for DB ({x}/30): Connection refused."); } else { Logfile.Log("DBCONNECTION " + ex.Message); } Thread.Sleep(15000); } } UpdateTeslalogger.Start(); UpdateTeslalogger.UpdateGrafana(); }
private static void InitOpenTopoDataService() { try { if (Tools.UseOpenTopoData()) { Thread threadOpenTopoDataService = new Thread(() => { OpenTopoDataService.GetSingleton().Run(); }) { Name = "OpenTopoServiceThread" }; threadOpenTopoDataService.Start(); } else { Logfile.Log("OpenTopoData disabled (enable in settings)"); } } catch (Exception ex) { Logfile.Log(ex.ToString()); } }
internal static void GetAllCars() { using (DataTable dt = DBHelper.GetCars()) { foreach (DataRow r in dt.Rows) { int id = 0; try { id = Convert.ToInt32(r["id"]); String Name = r["tesla_name"].ToString(); String Password = r["tesla_password"].ToString(); int carid = r["tesla_carid"] as Int32? ?? 0; String tesla_token = r["tesla_token"] as String ?? ""; DateTime tesla_token_expire = r["tesla_token_expire"] as DateTime? ?? DateTime.MinValue; string Model_Name = r["Model_Name"] as String ?? ""; string car_type = r["car_type"] as String ?? ""; string car_special_type = r["car_special_type"] as String ?? ""; string car_trim_badging = r["car_trim_badging"] as String ?? ""; string display_name = r["display_name"] as String ?? ""; string vin = r["vin"] as String ?? ""; string tasker_hash = r["tasker_hash"] as String ?? ""; double? wh_tr = r["wh_tr"] as double?; Car car = new Car(id, Name, Password, carid, tesla_token, tesla_token_expire, Model_Name, car_type, car_special_type, car_trim_badging, display_name, vin, tasker_hash, wh_tr); } catch (Exception ex) { Logfile.Log(id + "# :" + ex.ToString()); } } dt.Clear(); } }
private static void RefreshToken(WebHelper wh) { TimeSpan ts = DateTime.Now - wh.lastTokenRefresh; if (ts.TotalDays > 9) { TimeSpan ts2 = DateTime.Now - lastTryTokenRefresh; if (ts2.TotalMinutes > 30) { lastTryTokenRefresh = DateTime.Now; Logfile.Log("try to get new Token"); var temp = wh.GetTokenAsync().Result; if (temp != "NULL") { Logfile.Log("new Token received!"); wh.Tesla_token = temp; wh.lastTokenRefresh = DateTime.Now; } else { Logfile.Log("Error getting new Token!"); } } } }
private void Setcost(HttpListenerRequest request, HttpListenerResponse response) { try { Logfile.Log("SetCost"); string json; if (request.QueryString["JSON"] != null) { json = request.QueryString["JSON"]; } else { using (StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding)) { json = reader.ReadToEnd(); } } Logfile.Log("JSON: " + json); dynamic j = new JavaScriptSerializer().DeserializeObject(json); using (MySqlConnection con = new MySqlConnection(DBHelper.DBConnectionstring)) { con.Open(); using (MySqlCommand cmd = new MySqlCommand("update chargingstate set cost_total = @cost_total, cost_currency=@cost_currency, cost_per_kwh=@cost_per_kwh, cost_per_session=@cost_per_session, cost_per_minute=@cost_per_minute, cost_idle_fee_total=@cost_idle_fee_total, cost_kwh_meter_invoice=@cost_kwh_meter_invoice where id= @id", con)) { if (DBHelper.DBNullIfEmptyOrZero(j["cost_total"]) is DBNull && DBHelper.IsZero(j["cost_per_session"])) { cmd.Parameters.AddWithValue("@cost_total", 0); } else { cmd.Parameters.AddWithValue("@cost_total", DBHelper.DBNullIfEmptyOrZero(j["cost_total"])); } cmd.Parameters.AddWithValue("@cost_currency", DBHelper.DBNullIfEmpty(j["cost_currency"])); cmd.Parameters.AddWithValue("@cost_per_kwh", DBHelper.DBNullIfEmpty(j["cost_per_kwh"])); cmd.Parameters.AddWithValue("@cost_per_session", DBHelper.DBNullIfEmpty(j["cost_per_session"])); cmd.Parameters.AddWithValue("@cost_per_minute", DBHelper.DBNullIfEmpty(j["cost_per_minute"])); cmd.Parameters.AddWithValue("@cost_idle_fee_total", DBHelper.DBNullIfEmpty(j["cost_idle_fee_total"])); cmd.Parameters.AddWithValue("@cost_kwh_meter_invoice", DBHelper.DBNullIfEmpty(j["cost_kwh_meter_invoice"])); cmd.Parameters.AddWithValue("@id", j["id"]); int done = cmd.ExecuteNonQuery(); Logfile.Log("SetCost OK: " + done); WriteString(response, "OK"); } } } catch (Exception ex) { Logfile.Log(ex.ToString()); WriteString(response, "ERROR"); } }
public static void DebugLog(string text, [CallerFilePath] string _cfp = null, [CallerLineNumber] int _cln = 0) { if (Program.VERBOSE) { string temp = "DEBUG : " + text + " (" + Path.GetFileName(_cfp) + ":" + _cln + ")"; Logfile.Log(temp); } }
private static void InitDebugLogging() { if (ApplicationSettings.Default.VerboseMode) { VERBOSE = true; Logfile.Log("VerboseMode ON"); } }
private static void Main(string[] args) { try { InitDebugLogging(); InitStage1(); InitCheckDocker(); InitStage2(); InitConnectToDB(); InitWebserver(); InitOpenTopoDataService(); InitStaticMapService(); UpdateTeslalogger.StopComfortingMessagesThread(); MQTTClient.StartMQTTClient(); InitTLStats(); UpdateDbInBackground(); Logfile.Log("Init finished, now enter main loop"); GetAllCars(); InitNearbySuCService(); } catch (Exception ex) { Logfile.Log(ex.Message); Logfile.ExceptionWriter(ex, "main loop"); Logfile.Log("Teslalogger Stopped!"); Tools.ExternalLog("Teslalogger Stopped! " + ex.ToString()); } finally { if (!UpdateTeslalogger.DownloadUpdateAndInstallStarted) { try { Logfile.Log("Startup doesn't sucessfully run DownloadUpdateAndInstall() - retry now!"); UpdateTeslalogger.DownloadUpdateAndInstall(); } catch (Exception ex) { Logfile.Log(ex.Message); Logfile.ExceptionWriter(ex, "Emergency DownloadUpdateAndInstall()"); } } } }
public static void CreateParkingMap(double lat, double lng, string name) { try { if (String.IsNullOrEmpty(ApplicationSettings.Default.MapQuestKey)) { return; } string fn = "P-" + name + ".jpg"; string filename = System.IO.Path.Combine(mapdir, fn); if (System.IO.File.Exists(filename)) { return; } StringBuilder sb = new StringBuilder(); sb.Append("http://open.mapquestapi.com/staticmap/v5/map?key="); sb.Append(ApplicationSettings.Default.MapQuestKey); sb.Append("¢er="); sb.Append(lat.ToString(Tools.ciEnUS)).Append(","); sb.Append(lng.ToString(Tools.ciEnUS)); sb.Append("&size=200,150&type=dark"); sb.Append("&locations="); sb.Append(lat.ToString(Tools.ciEnUS)).Append(",").Append(lng.ToString(Tools.ciEnUS)); sb.Append("|marker-3E72B1|"); string url = sb.ToString(); System.Diagnostics.Debug.WriteLine(url); try { using (WebClient webClient = new WebClient()) { webClient.Headers.Add("User-Agent: TeslaLogger"); webClient.Headers.Add("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"); // Download the Web resource and save it into the current filesystem folder. webClient.DownloadFile(url, filename); Logfile.Log("Create File: " + fn); } System.Threading.Thread.Sleep(500); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); Logfile.Log(ex.ToString()); } } catch (Exception ex) { Logfile.Log(ex.ToString()); } }
// do something on state changes private static void HandleStateChange(TeslaState _oldState, TeslaState _newState) { Logfile.Log("change TeslaLogger state: " + _oldState.ToString() + " -> " + _newState.ToString()); DBHelper.currentJSON.CreateCurrentJSON(); // any -> Start if (_oldState != TeslaState.Start && _newState == TeslaState.Start) { webhelper.SetLastShiftState("P"); // reset shift state to default "P" } // charging -> any if (_oldState == TeslaState.Charge && _newState != TeslaState.Charge) { ResetHighFrequencyLogging(); } // sleeping -> any if (_oldState == TeslaState.Sleep && _newState != TeslaState.Sleep) { DBHelper.currentJSON.current_falling_asleep = false; DBHelper.currentJSON.CreateCurrentJSON(); } // any -> charging if (_oldState != TeslaState.Charge && _newState == TeslaState.Charge) { Address addr = WebHelper.geofence.GetPOI(DBHelper.currentJSON.latitude, DBHelper.currentJSON.longitude, false); 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: break; case Address.SpecialFlags.HighFrequencyLogging: HandleSpecialFlag_HighFrequencyLogging(flag.Value); break; case Address.SpecialFlags.EnableSentryMode: break; case Address.SpecialFlags.SetChargeLimit: HandleSpecialFlag_SetChargeLimit(addr, flag.Value); break; case Address.SpecialFlags.ClimateOff: break; default: Logfile.Log("handleShiftStateChange unhandled special flag " + flag.ToString()); break; } } } } }
private void Admin_UpdateElevation(HttpListenerRequest request, HttpListenerResponse response) { int from = 1; int to = DBHelper.GetMaxPosid(); Logfile.Log($"Admin: UpdateElevation ({from} -> {to}) ..."); WriteString(response, $"Admin: UpdateElevation ({from} -> {to}) ..."); DBHelper.UpdateTripElevation(from, to); Logfile.Log("Admin: UpdateElevation done"); }
private void Fsw_Changed(object sender, System.IO.FileSystemEventArgs e) { Logfile.Log("CSV File changed: " + e.Name); fsw.EnableRaisingEvents = false; System.Threading.Thread.Sleep(5000); Init(); fsw.EnableRaisingEvents = true; }
public static string exec_mono(string cmd, string param, bool logging = true) { try { if (!Tools.IsMono()) { return(""); } Logfile.Log("execute: " + cmd + " " + param); StringBuilder sb = new StringBuilder(); System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.FileName = cmd; proc.StartInfo.Arguments = param; proc.Start(); proc.WaitForExit(); while (!proc.StandardOutput.EndOfStream) { string line = proc.StandardOutput.ReadLine(); if (logging) { Logfile.Log(" " + line); } sb.AppendLine(line); } while (!proc.StandardError.EndOfStream) { string line = proc.StandardError.ReadLine(); if (logging) { Logfile.Log("Error: " + line); } } return(sb.ToString()); } catch (Exception ex) { Logfile.Log("Exception " + cmd + " " + ex.Message); return("Exception"); } }
public void Write() { try { dt.WriteXml(FileManager.GetFilePath(TLFilename.GeocodeCache)); } catch (Exception ex) { Logfile.Log(ex.Message); } }
private static void InitStage3() { if (!webhelper.RestoreToken()) { webhelper.Tesla_token = webhelper.GetTokenAsync().Result; } if (webhelper.Tesla_token == "NULL") { ExitTeslaLogger("Tesla_token == NULL"); } LogToken(); if (DBHelper.DBConnectionstring.Length == 0) { ExitTeslaLogger("DBHelper.DBConnectionstring.Length == 0"); } if (webhelper.GetVehicles() == "NULL") { ExitTeslaLogger("wh.GetVehicles() == NULL"); } string online = webhelper.IsOnline().Result; Logfile.Log("Streamingtoken: " + webhelper.Tesla_Streamingtoken); if (DBHelper.GetMaxPosid(false) == 0) { Logfile.Log("Insert first Pos"); webhelper.IsDriving(true); } Logfile.Log("Country Code: " + DBHelper.UpdateCountryCode()); DBHelper.GetEconomy_Wh_km(webhelper); webhelper.DeleteWakeupFile(); string carName = webhelper.carSettings.Name; if (webhelper.carSettings.Raven) { carName += " Raven"; } Logfile.Log("Car: " + carName + " - " + webhelper.carSettings.Wh_TR + " Wh/km"); double.TryParse(webhelper.carSettings.Wh_TR, out DBHelper.currentJSON.Wh_TR); DBHelper.GetLastTrip(); UpdateTeslalogger.Start(webhelper); UpdateTeslalogger.UpdateGrafana(webhelper); DBHelper.currentJSON.current_car_version = DBHelper.GetLastCarVersion(); }
private static void HandleSpeciaFlag_EnableSentryMode(string _flagconfig, string _oldState, string _newState) { string pattern = "([PRND]+)->([PRND]+)"; Match m = Regex.Match(_flagconfig, pattern); if (m.Success && m.Groups.Count == 3 && m.Groups[1].Captures.Count == 1 && m.Groups[2].Captures.Count == 1 && m.Groups[1].Captures[0].ToString().Contains(_oldState) && m.Groups[2].Captures[0].ToString().Contains(_newState)) { Logfile.Log("EnableSentryMode ..."); string result = webhelper.PostCommand("command/set_sentry_mode?on=true", null).Result; Logfile.Log("EnableSentryMode(): " + result); } }
public static void CopyFile(string srcFile, string directory) { try { Logfile.Log("Copy '" + srcFile + "' to '" + directory + "'"); File.Copy(srcFile, directory, true); } catch (Exception ex) { Logfile.Log("CopyFile Exception: " + ex.ToString()); } }
internal static void GrafanaSettings(out string power, out string temperature, out string length, out string language, out string URL_Admin) { power = "hp"; temperature = "celsius"; length = "km"; language = "de"; URL_Admin = ""; 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, "Power")) { power = j["Power"]; } if (IsPropertyExist(j, "Temperature")) { temperature = j["Temperature"]; } if (IsPropertyExist(j, "Length")) { length = j["Length"]; } if (IsPropertyExist(j, "Language")) { language = j["Language"]; } if (IsPropertyExist(j, "URL_Admin")) { if (j["URL_Admin"].ToString().Length > 0) { URL_Admin = j["URL_Admin"]; } } } catch (Exception ex) { Logfile.Log(ex.ToString()); } }
private static void CalculateChargeDuration(int journeyId) { try { using (MySqlConnection con = new MySqlConnection(DBHelper.DBConnectionstring)) { con.Open(); double charge_duration_minutes = 0; using (MySqlCommand cmd = new MySqlCommand(@" SELECT chargingstate.EndDate, chargingstate.StartDate FROM chargingstate WHERE chargingstate.Pos >= (SELECT StartPosID FROM journeys WHERE ID = @journeyID) AND chargingstate.Pos < (SELECT EndPosID FROM journeys WHERE ID = @journeyID) AND chargingstate.carID = (SELECT CarID FROM journeys WHERE ID = @journeyID) ", con)) { cmd.Parameters.AddWithValue("@journeyID", journeyId); Tools.DebugLog(cmd); MySqlDataReader dr = SQLTracer.TraceDR(cmd); while (dr.Read()) { DateTime d1 = (DateTime)dr[0]; DateTime d2 = (DateTime)dr[1]; TimeSpan ts = d1 - d2; charge_duration_minutes += ts.TotalMinutes; } dr.Close(); } using (MySqlCommand cmd = new MySqlCommand(@" UPDATE journeys SET charge_duration_minutes = @charge_duration_minutes WHERE Id = @journeyID", con)) { cmd.Parameters.AddWithValue("@journeyID", journeyId); cmd.Parameters.AddWithValue("@charge_duration_minutes", (int)charge_duration_minutes); Tools.DebugLog(cmd); SQLTracer.TraceNQ(cmd); } } } catch (Exception ex) { ex.ToExceptionless().FirstCarUserID().Submit(); Logfile.Log(ex.ToString()); } }
void Init() { List <Address> list = new List <Address>(); ReadGeofenceFile(list, FileManager.GetFilePath(TLFilename.GeofenceFilename)); UpdateTeslalogger.chmod(FileManager.GetFilePath(TLFilename.GeofencePrivateFilename), 666); ReadGeofenceFile(list, FileManager.GetFilePath(TLFilename.GeofencePrivateFilename)); Logfile.Log("Addresses inserted: " + list.Count); sortedList = list.OrderBy(o => o.lat).ToList(); }
private static void HandleSpecialFlag_OpenChargePort(string _flagconfig, string _oldState, string _newState) { string pattern = "([PRND]+)->([PRND]+)"; Match m = Regex.Match(_flagconfig, pattern); if (m.Success && m.Groups.Count == 3 && m.Groups[1].Captures.Count == 1 && m.Groups[2].Captures.Count == 1 && m.Groups[1].Captures[0].ToString().Contains(_oldState) && m.Groups[2].Captures[0].ToString().Contains(_newState)) { Logfile.Log("OpenChargePort ..."); string result = webhelper.PostCommand("command/charge_port_door_open", null).Result; Logfile.Log("openChargePort(): " + result); } }
public static void SaveImage(Bitmap image, string filename) { try { image.Save(filename); Logfile.Log("Create File: " + filename); } catch (Exception ex) { Tools.DebugLog("Exception", ex); } }
internal static void StartSleeping(out int startSleepingHour, out int startSleepingMinutes) { TimeSpan ts = DateTime.UtcNow - lastSleepingHourMinutsUpdated; if (ts.TotalMinutes < 5) { startSleepingHour = _startSleepingHour; startSleepingMinutes = _startSleepingMinutes; return; } startSleepingHour = -1; startSleepingMinutes = -1; try { string filePath = FileManager.GetFilePath(TLFilename.SettingsFilename); if (!File.Exists(filePath)) { lastSleepingHourMinutsUpdated = DateTime.UtcNow; return; } string json = File.ReadAllText(filePath); dynamic j = new JavaScriptSerializer().DeserializeObject(json); if (IsPropertyExist(j, "SleepTimeSpanEnable") && IsPropertyExist(j, "SleepTimeSpanStart")) { if (bool.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); } } } _startSleepingHour = startSleepingHour; _startSleepingMinutes = startSleepingMinutes; lastSleepingHourMinutsUpdated = DateTime.UtcNow; } catch (Exception ex) { Logfile.Log(ex.ToString()); } }
private static string ReplaceAliasTag(string content, string v, Dictionary <string, string> dictLanguage) { if (!dictLanguage.ContainsKey(v)) { Logfile.Log("Key '" + v + "' not Found in Translationfile!"); return(content); } Regex regexAlias = new Regex("\\\"alias\\\":.*?\\\"" + v + "\\\""); string replace = "\"alias\": \"" + dictLanguage[v] + "\""; return(regexAlias.Replace(content, replace)); }
private static void LogToken() { // don't show full Token in Logfile string tempToken = webhelper.Tesla_token; if (tempToken.Length > 5) { tempToken = tempToken.Substring(0, tempToken.Length - 5); tempToken += "XXXXX"; } Logfile.Log("TOKEN: " + tempToken); }
private static string ReplaceTitleTag(string content, string v, Dictionary <string, string> dictLanguage) { if (!dictLanguage.ContainsKey(v)) { Logfile.Log("Key '" + v + "' not Found in Translationfile!"); return(content); } System.Text.RegularExpressions.Regex regexAlias = new System.Text.RegularExpressions.Regex("\\\"title\\\":.*?\\\"" + v + "\\\""); string replace = "\"title\": \"" + dictLanguage[v] + "\""; return(regexAlias.Replace(content, replace)); }
public Address GetPOI(double lat, double lng, bool logDistance = true) { Address ret = null; double retDistance = 0; int found = 0; lock (sortedList) { double range = 0.2; // apprx 10km foreach (Address p in sortedList) { if (p.lat - range > lat) { return(ret); // da die liste sortiert ist, kann nichts mehr kommen } if ((p.lat - range) < lat && lat < (p.lat + range) && (p.lng - range) < lng && lng < (p.lng + range)) { double distance = GetDistance(lng, lat, p.lng, p.lat); if (p.radius > distance) { found++; if (logDistance) { Logfile.Log($"Distance: {distance} - Radius: {p.radius} - {p.name}"); } if (ret == null) { ret = p; retDistance = distance; } else { if (distance < retDistance) { ret = p; retDistance = distance; } } } } } } return(ret); }