Ejemplo n.º 1
0
        private void Admin_GetPOI(HttpListenerRequest request, HttpListenerResponse response)
        {
            if (request.QueryString.Count == 2 && request.QueryString.HasKeys())
            {
                double lat = double.NaN;
                double lng = double.NaN;
                foreach (string key in request.QueryString.AllKeys)
                {
                    if (request.QueryString.GetValues(key).Length == 1)
                    {
                        switch (key)
                        {
                        case "lat":
                            double.TryParse(request.QueryString.GetValues(key)[0], out lat);
                            break;

                        case "lng":
                            double.TryParse(request.QueryString.GetValues(key)[0], out lng);
                            break;

                        default:
                            break;
                        }
                    }
                }
                if (lat != double.NaN && lng != double.NaN)
                {
                    Address addr = Geofence.GetInstance().GetPOI(lat, lng, false);
                    if (addr != null)
                    {
                        Dictionary <string, object> data = new Dictionary <string, object>()
                        {
                            { "name", addr.name },
                            { "rawName", addr.rawName },
                            { "lat", addr.lat },
                            { "lng", addr.lng },
                            { "radius", addr.radius },
                            { "IsHome", addr.IsHome },
                            { "IsWork", addr.IsWork },
                            { "IsCharger", addr.IsCharger },
                            { "NoSleep", addr.NoSleep },
                        };
                        Dictionary <string, object> specialflags = new Dictionary <string, object>();
                        foreach (KeyValuePair <Address.SpecialFlags, string> flag in addr.specialFlags)
                        {
                            specialflags.Add(flag.Key.ToString(), flag.Value);
                        }
                        data.Add("SpecialFlags", specialflags);
                        response.AddHeader("Content-Type", "application/json; charset=utf-8");
                        WriteString(response, new JavaScriptSerializer().Serialize(data));
                        return;
                    }
                }
            }
            // finally close response
            WriteString(response, "");
        }
Ejemplo n.º 2
0
        private static void Admin_ReloadGeofence(HttpListenerRequest request, HttpListenerResponse response)
        {
            Logfile.Log("Admin: ReloadGeofence ...");
            Geofence.GetInstance().Init();

            if (request.QueryString.Count == 1 && string.Concat(request.QueryString.GetValues(0)).Equals("html"))
            {
                IEnumerable <string> geofence = Geofence.GetInstance().geofenceList.Select(
                    a => string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>geofence</td></tr>",
                                       a.name,
                                       a.lat,
                                       a.lng,
                                       a.radius,
                                       string.Concat(a.specialFlags.Select(
                                                         sp => string.Format("{0}<br/>",
                                                                             sp.ToString()))
                                                     )
                                       )
                    );
                IEnumerable <string> geofenceprivate = Geofence.GetInstance().geofencePrivateList.Select(
                    a => string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>geofence-private</td></tr>",
                                       a.name,
                                       a.lat,
                                       a.lng,
                                       a.radius,
                                       string.Concat(a.specialFlags.Select(
                                                         sp => string.Format("{0}<br/>",
                                                                             sp.ToString()))
                                                     )
                                       )
                    );
                response.AddHeader("Content-Type", "text/html; charset=utf-8");
                WriteString(response, "<html><head></head><body><table border=\"1\">" + string.Concat(geofence) + string.Concat(geofenceprivate) + "</table></body></html>");
            }
            else
            {
                WriteString(response, "{\"response\":{\"reason\":\"\", \"result\":true}}");
            }
            WebHelper.UpdateAllPOIAddresses();
            Logfile.Log("Admin: ReloadGeofence done");
        }
Ejemplo n.º 3
0
        public void SendAllChargingData()
        {
            if (!shareData)
            {
                return;
            }

            try
            {
                car.Log("ShareData: SendAllChargingData start");

                int    ProtocolVersion = 5;
                string sql             = @"SELECT chargingstate.id as HostId, StartDate, EndDate, charging.charge_energy_added, conn_charge_cable, fast_charger_brand, fast_charger_type, fast_charger_present, address as pos_name, lat, lng, odometer, charging.outside_temp, StartChargingID, EndChargingID
                FROM chargingstate
                join pos on chargingstate.Pos = pos.id
                join charging on charging.id = chargingstate.EndChargingID
                where chargingstate.carid = " + car.CarInDB + " and (export is null or export < " + ProtocolVersion + @") and (fast_charger_present or address like 'Supercharger%' or address like 'Ionity%' or max_charger_power > 25)
                order by StartDate
                ";

                using (DataTable dt = new DataTable())
                {
                    int ms = Environment.TickCount;

                    using (MySqlDataAdapter da = new MySqlDataAdapter(sql, DBHelper.DBConnectionstring))
                    {
                        da.SelectCommand.CommandTimeout = 600;
                        da.Fill(dt);
                        ms = Environment.TickCount - ms;
                        car.Log("ShareData: SELECT chargingstate ms: " + ms);

                        foreach (DataRow dr in dt.Rows)
                        {
                            // lat, lng
                            if (double.TryParse(dr["lat"].ToString(), out double lat) && double.TryParse(dr["lng"].ToString(), out double lng))
                            {
                                Address addr = Geofence.GetInstance().GetPOI(lat, lng, false);
                                if (addr != null && addr.IsHome)
                                {
                                    car.Log("Do not share ChargingData for +home (" + addr.name + ")");
                                    continue;
                                }
                                // get raw address w/o automatically added unicode characters
                                if (dr["pos_name"] != null && addr != null)
                                {
                                    dr["pos_name"] = addr.rawName;
                                }
                            }

                            int HostId = Convert.ToInt32(dr["HostId"]);

                            Dictionary <string, object> d = new Dictionary <string, object>
                            {
                                { "ProtocolVersion", ProtocolVersion }
                            };
                            string Firmware = car.dbHelper.GetFirmwareFromDate((DateTime)dr["StartDate"]);
                            d.Add("Firmware", Firmware);

                            d.Add("TaskerToken", TaskerToken); // TaskerToken and HostId is the primary key and is used to make sure data won't be imported twice
                            foreach (DataColumn col in dt.Columns)
                            {
                                if (col.Caption.EndsWith("ChargingID"))
                                {
                                    continue;
                                }

                                if (col.Caption.EndsWith("Date"))
                                {
                                    d.Add(col.Caption, ((DateTime)dr[col.Caption]).ToString("s"));
                                }
                                else
                                {
                                    d.Add(col.Caption, dr[col.Caption]);
                                }
                            }

                            List <object> l = GetChargingDT(Convert.ToInt32(dr["StartChargingID"]), Convert.ToInt32(dr["EndChargingID"]), out int count);
                            d.Add("teslalogger_version", TeslaloggerVersion);
                            d.Add("charging", l);

                            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(d);

                            //string resultContent = "";
                            try
                            {
                                using (HttpClient client = new HttpClient())
                                {
                                    client.Timeout = TimeSpan.FromSeconds(30);
                                    using (StringContent content = new StringContent(json, Encoding.UTF8, "application/json"))
                                    {
                                        DateTime            start  = DateTime.UtcNow;
                                        HttpResponseMessage result = client.PostAsync("http://teslalogger.de/share_charging.php", content).Result;
                                        string r = result.Content.ReadAsStringAsync().Result;
                                        DBHelper.AddMothershipDataToDB("teslalogger.de/share_charging.php", start, (int)result.StatusCode);

                                        //resultContent = result.Content.ReadAsStringAsync();
                                        car.Log("ShareData: " + r);

                                        if (r.Contains("ERROR"))
                                        {
                                            Logfile.WriteException(r + "\r\n" + json);
                                        }
                                        else if (r.Contains("Insert OK:"))
                                        {
                                            DBHelper.ExecuteSQLQuery("update chargingstate set export=" + ProtocolVersion + "  where id = " + HostId);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                car.Log("ShareData: " + ex.Message);
                            }
                        }

                        car.Log("ShareData: SendAllChargingData finished");
                    }
                    dt.Clear();
                }
            }
            catch (Exception ex)
            {
                car.Log("Error in ShareData:SendAllChargingData " + ex.Message);
                Logfile.WriteException(ex.ToString());
            }
        }
Ejemplo n.º 4
0
        public void CreateCurrentJSON()
        {
            try
            {
                lastJSONwrite = DateTime.UtcNow;

                int    duration    = 0;
                double distance    = 0;
                double trip_kwh    = 0.0;
                double trip_avg_wh = 0.0;

                try
                {
                    if (current_trip_end == DateTime.MinValue)
                    {
                        duration = (int)(DateTime.Now - current_trip_start).TotalSeconds;
                        distance = current_odometer - current_trip_km_start;
                        trip_kwh = (current_trip_start_range - current_ideal_battery_range_km) * Wh_TR;

                        if (distance > 0)
                        {
                            trip_avg_wh = trip_kwh / distance * 1000;
                        }
                    }
                    else
                    {
                        duration = (int)(current_trip_end - current_trip_start).TotalSeconds;
                        distance = current_trip_km_end - current_trip_km_start;
                        trip_kwh = (current_trip_start_range - current_trip_end_range) * Wh_TR;

                        if (distance > 0)
                        {
                            trip_avg_wh = trip_kwh / distance * 1000;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logfile.Log(ex.ToString());
                    duration = 0;
                }
                if (duration < 0)
                {
                    duration = 0;
                }

                car.GetTeslaAPIState().GetBool("charge_port_door_open", out current_charge_port_door_open);

                Dictionary <string, object> values = new Dictionary <string, object>
                {
                    { "charging", current_charging },
                    { "driving", current_driving },
                    { "online", current_online },
                    { "sleeping", current_sleeping },
                    { "falling_asleep", current_falling_asleep },
                    { "speed", current_speed },
                    { "power", current_power },
                    { "odometer", current_odometer },
                    { "ideal_battery_range_km", current_ideal_battery_range_km },
                    { "battery_range_km", current_battery_range_km },
                    { "outside_temp", current_outside_temp },
                    { "battery_level", current_battery_level },
                    { "charger_voltage", current_charger_voltage },
                    { "charger_phases", current_charger_phases },
                    { "charger_actual_current", current_charger_actual_current },
                    { "charge_energy_added", current_charge_energy_added },
                    { "charger_power", current_charger_power },
                    { "charge_rate_km", current_charge_rate_km },
                    { "charge_port_door_open", current_charge_port_door_open },
                    { "time_to_full_charge", current_time_to_full_charge },
                    { "car_version", current_car_version },
                    { "trip_start", current_trip_start.ToString("t", Tools.ciDeDE) },
                    { "trip_start_dt", current_trip_start.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") },
                    { "trip_max_speed", current_trip_max_speed },
                    { "trip_max_power", current_trip_max_power },
                    { "trip_duration_sec", duration },
                    { "trip_kwh", trip_kwh },
                    { "trip_avg_kwh", trip_avg_wh },
                    { "trip_distance", distance },
                    { "ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") },
                    { "latitude", latitude },
                    { "longitude", longitude },
                    { "charge_limit_soc", charge_limit_soc },
                    { "inside_temperature", current_inside_temperature },
                    { "battery_heater", current_battery_heater },
                    { "is_preconditioning", current_is_preconditioning },
                    { "sentry_mode", current_is_sentry_mode },
                    { "country_code", current_country_code },
                    { "state", current_state },
                    { "display_name", car.display_name },
                    { "heading", heading }
                };

                TimeSpan ts = DateTime.Now - lastScanMyTeslaReceived;
                if (ts.TotalMinutes < 5)
                {
                    values.Add("SMTCellTempAvg", SMTCellTempAvg);
                    values.Add("SMTCellMinV", SMTCellMinV);
                    values.Add("SMTCellAvgV", SMTCellAvgV);
                    values.Add("SMTCellMaxV", SMTCellMaxV);
                    values.Add("SMTCellImbalance", SMTCellImbalance);
                    values.Add("SMTBMSmaxCharge", SMTBMSmaxCharge);
                    values.Add("SMTBMSmaxDischarge", SMTBMSmaxDischarge);
                    values.Add("SMTACChargeTotal", SMTACChargeTotal);
                    values.Add("SMTDCChargeTotal", SMTDCChargeTotal);
                    values.Add("SMTNominalFullPack", SMTNominalFullPack);
                }

                Address addr = Geofence.GetInstance().GetPOI(latitude, longitude, false);
                if (addr != null && addr.rawName != null)
                {
                    values.Add("TLGeofence", addr.rawName);
                    values.Add("TLGeofenceIsHome", addr.IsHome);
                    values.Add("TLGeofenceIsCharger", addr.IsCharger);
                    values.Add("TLGeofenceIsWork", addr.IsWork);
                }
                else
                {
                    values.Add("TLGeofence", "-");
                    values.Add("TLGeofenceIsHome", false);
                    values.Add("TLGeofenceIsCharger", false);
                    values.Add("TLGeofenceIsWork", false);
                }

                current_json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(values);

                jsonStringHolder[car.CarInDB] = current_json;

                // FileManager.WriteCurrentJsonFile(car.CarInDB, current_json);
            }
            catch (Exception ex)
            {
                Logfile.Log(ex.ToString());
                current_json = "";
            }
        }