private void OutputSummary(ThermostatMonitorLib.Thermostat thermostat,ThermostatMonitorLib.Location location)
    {
        DataTable dt = ThermostatMonitorLib.Cycles.LoadFullSummary(thermostat.LocationId, thermostat.Id, new DateTime(2000, 1, 1), DateTime.Today, AppUser.TimezoneDifference(location.Timezone, location.DaylightSavings));
        DataTable resultDt = new DataTable();
        foreach (DataColumn dc in dt.Columns)
        {
            resultDt.Columns.Add(dc.ColumnName.Replace("Seconds", "Minutes"), dc.DataType);
        }
        foreach (DataRow row in dt.Rows)
        {
            DataRow newRow = resultDt.NewRow();
            foreach (DataColumn dc in dt.Columns)
            {
                if (dc.ColumnName.Contains("Seconds"))
                {
                    double minutes = 0;
                    try { minutes = System.Math.Round(Convert.ToDouble(row[dc.ColumnName]) / 60, 2); }
                    catch { }
                    newRow[dc.ColumnName.Replace("Seconds", "Minutes")] = minutes;
                }
                else
                {
                    newRow[dc.ColumnName] = row[dc.ColumnName];
                }
            }
            resultDt.Rows.Add(newRow);
        }

        OutputCSV(ThermostatMonitorLib.Utils.DataTableToCSV(resultDt), "summary.csv");
    }
 public void Login(ThermostatMonitorLib.User user)
 {
     UserData = user;
     IsAuthenticated = true;
 }
    public void Populate(DataTable dt,ThermostatMonitorLib.Thermostat thermostat)
    {
        ThermostatMonitorLib.Location location = ThermostatMonitorLib.Location.LoadLocation(thermostat.LocationId);

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        bool cool = false;
        bool heat = false;
        bool fan = false;

        foreach (DataRow row in dt.Rows)
        {
            if (dt.Columns.Contains("Cool_CycleCount")) cool = true;
            if (dt.Columns.Contains("Heat_CycleCount")) heat = true;
            if (dt.Columns.Contains("Fan_CycleCount")) fan = true;
        }

        sb.Append("<table cellpadding=\"4\" cellspacing=\"0\" style=\"border:1px solid black;\"><tr><td></td>");
        if (cool) sb.Append("<td colspan=\"4\" class=\"cool\"><b>Cool</b></td>");
        if (heat) sb.Append("<td colspan=\"4\" class=\"heat\"><b>Heat</b></td>");
        if (fan) sb.Append("<td colspan=\"4\" class=\"fan\"><b>Fan</b></td>");
        sb.Append("<td colspan=\"2\" class=\"outside\"><b>Outside</b></td></tr>");

        sb.Append("<tr><td><b>Day</b></td>");
        if (cool) sb.Append("<td class=\"cool\"><b>Cycles</b></td><td class=\"cool\"><b>Average</b></td><td class=\"cool\"><b>Total</b></td><td class=\"cool\"><b>Cost</b></td>");
        if (heat) sb.Append("<td class=\"heat\"><b>Cycles</b></td><td class=\"heat\"><b>Average</b></td><td class=\"heat\"><b>Total</b></td><td class=\"heat\"><b>Cost</b></td>");
        if (fan) sb.Append("<td class=\"fan\"><b>Cycles</b></td><td class=\"fan\"><b>Average</b></td><td class=\"fan\"><b>Total</b></td><td class=\"fan\"><b>Cost</b></td>");
        sb.Append("<td class=\"outside\"><b>Min</b></td><td class=\"outside\"><b>Max</b></td></tr>");

        dt.DefaultView.Sort = "LogDate desc";
        //foreach (DataRowView row in dt.DefaultView)
        for (int i=0;i<7;i++)
        {
            DateTime logDate=DateTime.Today.AddDays(-i);
            DataRow row = GetRow(dt, logDate);

            DataRow[] rows = dt.Select("logdate='" + logDate.ToString("MM/dd/yyyy") + "'");
            if (rows.Length > 0) row=rows[0];

            sb.Append("<tr><td><a href=\"/cp/day.aspx?thermostatId=" + thermostat.Id + "&date=" + Convert.ToDateTime(row["LogDate"]).ToString("MM/dd/yyyy") + "\">" + Convert.ToDateTime(row["LogDate"]).ToString("dddd") + "</a></td>");
            if (cool)
            {
                if (Convert.IsDBNull(row["Cool_CycleCount"])) sb.Append("<td class=\"cool\" colspan=\"4\">&nbsp;</td>");
                else
                {
                    double coolCost = (thermostat.ACKilowatts + thermostat.FanKilowatts) * Convert.ToDouble(row["Cool_TotalSeconds"]) / 60.0 / 60.0 * location.ElectricityPrice / 100;
                    sb.Append("<td class=\"cool\">" + row["Cool_CycleCount"].ToString() + "</td><td class=\"cool\">" + (Convert.ToDouble(row["Cool_AverageSeconds"]) / 60).ToString("#,##0.#") + " min</td><td class=\"cool\">" + (Convert.ToDouble(row["Cool_TotalSeconds"]) / 60).ToString("###,##0") + " min</td><td class=\"cool\">" + coolCost.ToString("C") + "</td>");
                }
            }
            if (heat)
            {
                if (Convert.IsDBNull(row["Heat_CycleCount"])) sb.Append("<td class=\"heat\" colspan=\"4\">&nbsp;</td>");
                else
                {
                    double heatCost = thermostat.HeatBtuPerHour * Convert.ToDouble(row["Heat_TotalSeconds"]) / 60.0 / 60.0 * location.HeatFuelPrice / 1000000;
                    double fanCost = (thermostat.FanKilowatts) * Convert.ToDouble(row["Heat_TotalSeconds"]) / 60.0 / 60.0 * location.ElectricityPrice / 100;
                    heatCost += fanCost;

                    sb.Append("<td class=\"heat\">" + row["Heat_CycleCount"].ToString() + "</td><td class=\"heat\">" + (Convert.ToDouble(row["Heat_AverageSeconds"]) / 60).ToString("#,##0.#") + " min</td><td class=\"heat\">" + (Convert.ToDouble(row["Heat_TotalSeconds"]) / 60).ToString("###,##0") + " min</td><td class=\"heat\">" + heatCost.ToString("C") + "</td>");
                }
            }
            if (fan)
            {
                if (Convert.IsDBNull(row["Fan_CycleCount"])) sb.Append("<td class=\"fan\" colspan=\"4\">&nbsp;</td>");
                else
                {
                    sb.Append("<td class=\"fan\">" + row["Fan_CycleCount"].ToString() + "</td><td class=\"fan\">" + (Convert.ToDouble(row["Fan_AverageSeconds"]) / 60).ToString("#,##0.#") + " min</td><td class=\"fan\">" + (Convert.ToDouble(row["Fan_TotalSeconds"]) / 60).ToString("###,##0") + " min</td><td class=\"fan\"></td>");
                }
            }
            sb.Append("<td class=\"outside\">" + row["OutsideMin"].ToString() + "</td><td class=\"outside\">" + row["OutsideMax"].ToString() + "</td></tr>");

        }
        sb.Append("</table>");
        OutputLit.Text=sb.ToString();
    }
 private void OutputCycles(ThermostatMonitorLib.Thermostat thermostat, ThermostatMonitorLib.Location location)
 {
     ThermostatMonitorLib.Cycles cycles=ThermostatMonitorLib.Cycles.LoadRange(thermostat.Id, new DateTime(2000, 1, 1), DateTime.Now);
     OutputCSV(cycles.GetCSV(thermostat.AcKilowatts, thermostat.FanKilowatts, thermostat.HeatBtuPerHour, AppUser.TimezoneDifference(location.Timezone, location.DaylightSavings)), "cycles.csv");
 }
        private void CheckIn(ThermostatMonitorLib.Location location)
        {
            StreamReader reader = new StreamReader(Request.InputStream, Request.ContentEncoding);
            string jsonInput = reader.ReadToEnd();
            reader.Close();
            reader.Dispose();
            CheckinRequest request = CheckinRequest.Load(location, jsonInput);
            CheckinResponse response = new CheckinResponse();

            //Update inside temperature and thermostat state
            foreach (Thermostat thermostat in request.Thermostats)
            {
                string key=location.Id.ToString() + "_" + thermostat.IpAddress;
                Thermostat previousThermostat = new Thermostat();
                if (Thermostats.Cache.ContainsKey(key)) previousThermostat = (Thermostat)Thermostats.Cache[key];
                if (thermostat.Temperature != previousThermostat.Temperature) LogTemperatureChange(location.Id, thermostat, previousThermostat);
                if (thermostat.State != previousThermostat.State) LogStateChange(location.Id, thermostat, previousThermostat);
                Thermostats.Cache[key] = thermostat;
            }

            //Update outside temperature
            response.ZipCode = request.ZipCode;

            string cacheKey = "OutsideTemperature" + location.Id.ToString();
            if (Cache.Get(cacheKey)==null)
            {
                try
                {
                    response.OutsideTemperature = ThermostatMonitorLib.Weather.GetTemperature(location.OpenWeatherCityId);
                    Cache.Add(cacheKey, response.OutsideTemperature, null, DateTime.Now.AddMinutes(4).AddSeconds(30), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                } catch{}
            } else {
                response.OutsideTemperature = Convert.ToInt32(Cache.Get(cacheKey));
            }

            int previousTemperature = -999;
            if (CheckinResponse.ConditionHash.ContainsKey(location.Id)) previousTemperature = Convert.ToInt32(CheckinResponse.ConditionHash[location.Id]);

            if (response.OutsideTemperature != previousTemperature  && response.OutsideTemperature!=0) ThermostatMonitorLib.OutsideCondition.Log(location.Id, response.OutsideTemperature);
            CheckinResponse.ConditionHash[location.Id] = response.OutsideTemperature;

            //Add any pending commands to the response
            response.ReplyCommands = Commands.Get(location.Id);
            Commands.Remove(location.Id);

            try
            {
                Thermostats.CleanCache();
            }
            catch (Exception ex)
            {
                ThermostatMonitorLib.Error error = new ThermostatMonitorLib.Error();
                error.ErrorMessage = ex.ToString();
                error.LogDate = DateTime.Now;
                error.UserId = 0;
                error.Url = "/json/default.aspx";
                ThermostatMonitorLib.Error.SaveError(error);
            }

            Response.Write(response.GetJson());
            Response.End();
        }
        private void LoadSettings(ThermostatMonitorLib.Location location)
        {
            //Build array list of thermostats
            ThermostatMonitorLib.Thermostats thermostats = ThermostatMonitorLib.Thermostats.LoadThermostatsByLocationId(location.Id);
            ArrayList al = new ArrayList();
            foreach (ThermostatMonitorLib.Thermostat thermostat in thermostats)
            {
                System.Collections.Hashtable hash = new System.Collections.Hashtable();
                hash.Add("name", thermostat.DisplayName);
                hash.Add("ipAddress", thermostat.IpAddress);
                hash.Add("brand", thermostat.Brand);

                ThermostatMonitorLib.Cycle c=ThermostatMonitorLib.Cycle.LoadOpenCycle(thermostat.Id);
                if (c == null) hash.Add("state", "Off"); else hash.Add("state",c.CycleType);

                ThermostatMonitorLib.Temperature t = ThermostatMonitorLib.Temperature.LoadCurrentTemperature(thermostat.Id);
                if (t != null) hash.Add("temperature", t.Degrees);

                al.Add(hash);
            }
            Hashtable result = new Hashtable();
            result.Add("thermostats", al);
            string output = ThermostatMonitorLib.JSON.JsonEncode(result);
            OutputLit.Text = output;
        }