private tCommand PostApi(tCommand oCommandSend, string strIMEI)
        {
            HttpWebRequest  request;
            HttpWebResponse response = null /* TODO Change to default(_) if this is not a reference type */;
            StreamReader    reader;
            Uri             address;
            string          appId;
            string          strResponse = "";
            UInt32          uInt32StartDatetime;
            UInt32          uInt32EndDatetime;

            Stream postStream = null;
            string strUrl;

            byte[]        byteData;
            StringBuilder data;
            tCommand      oCommandReply = new tCommand();

            oCommandReply.PostStatus = "offline";



            strUrl = strApiUrl;

            strUrl = strUrl + oCommandSend.UrlPath;
            strUrl = strUrl.Replace("{devid}", strIMEI);
            strUrl = strUrl.Replace("{pathelement}", oCommandSend.PathElement);

            if (oCommandSend.StartTime != null && oCommandSend.EndTime != null)
            {
                uInt32StartDatetime = DateTimeToUnixTime(oCommandSend.StartTime);
                uInt32EndDatetime   = DateTimeToUnixTime(oCommandSend.EndTime);
                strUrl = strUrl + "?startTime=" + uInt32StartDatetime.ToString() + "&endTime=" + uInt32EndDatetime.ToString();
            }



            address = new Uri(strUrl);

            try
            {
                // The reply is mainly the same as the send, for easier processing by the client, ie send and reply together

                oCommandReply.CommandJson   = oCommandSend.CommandJson;
                oCommandReply.CommandName   = oCommandSend.CommandName;
                oCommandReply.CompanionJson = oCommandSend.CompanionJson;
                oCommandReply.CompanionName = oCommandSend.CompanionName;
                oCommandReply.EndTime       = oCommandSend.EndTime;
                oCommandReply.PathElement   = oCommandSend.PathElement;
                oCommandReply.StartTime     = oCommandSend.StartTime;
                oCommandReply.ToEco         = oCommandSend.ToEco;

                request = (HttpWebRequest)WebRequest.Create(address);
                if (oCommandSend.ToEco == true)
                {
                    request.Method = "PATCH";
                }
                else
                {
                    request.Method = "GET";
                }

                request.ContentType = "application/x-www-form-urlencoded";

                request.Headers.Add("x-api-key", strApiKey);

                appId = "ss-form";
                if (oCommandSend.ToEco == true)
                {
                    data = new StringBuilder();

                    data.Append(oCommandSend.CommandJson);

                    byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

                    // Set the content length in the request headers
                    request.ContentLength = byteData.Length;

                    // Write data
                    try
                    {
                        postStream = request.GetRequestStream();
                        postStream.Write(byteData, 0, byteData.Length);
                    }
                    finally
                    {
                        if (postStream != null)
                        {
                            postStream.Close();
                        }
                    }
                }
                else
                {
                    if (postStream != null)
                    {
                        postStream.Close();
                    }
                }
                try
                {
                    // Get response
                    response = (HttpWebResponse)request.GetResponse();

                    // Get the response stream into a reader
                    reader = new StreamReader(response.GetResponseStream());

                    strResponse = reader.ReadToEnd();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        oCommandReply.PostStatus = "ok";
                        oCommandReply.ReplyJson  = strResponse;

                        return(oCommandReply);
                    }
                    else
                    {
                    }
                }
                finally
                {
                    if (response != null)
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            oCommandReply.PostStatus = "ok";
                        }

                        if (response.StatusCode.ToString().IndexOf("504") != -1)
                        {
                            oCommandReply.PostStatus = "timeout";
                        }
                        response.Close();
                    }
                    else
                    {
                        oCommandReply.PostStatus = "offline";
                    }
                }
            }
            catch (Exception ex)
            {
            }


            return(oCommandReply);
        }
        public tResult FunctionHandler(tInput oInput, ILambdaContext context)
        {
            string         strQuery = "";
            SqlDataAdapter daCheck  = new SqlDataAdapter();
            DataSet        dsCheck  = new DataSet();

            SqlConnection oSqlConnection = null;
            tResult       oResult        = new tResult();
            int           intIdx;

            int           intDhwFlowTempID   = -1;
            int           intDhwReturnTempID = -1;
            int           intDhwRateID       = -1;
            string        strJson;
            tCommand      oCommandSend;
            controlreport oControlReport;
            sensorreport  oSensorReport;
            mbusreport    oMbusReport;
            string        strIMEI;

            try
            {
                // All values are returned as strings, ready for display

                context.Logger.LogLine("FunctionHandler 1 " + oInput.ToString());

                try
                {
                    oSqlConnection = new SqlConnection(ecoCommon.GetSecret("CloudEcoPlus", context)); oSqlConnection.Open();
                    context.Logger.LogLine("FunctionHandler 2");
                }
                catch (Exception ex)
                {
                    context.Logger.LogLine("WriteRecord Ex  1" + ex.Message);
                }

                try
                {
                    oSqlConnection.Open();
                }
                catch (Exception)
                {
                }


                strIMEI = ecoCommon.GetDeviceIMEINumber(oInput.SerialNumber, context, ref oSqlConnection);


                // get the last seen



                oResult.LastSeenMinutesAgo = GetLastSeen(strIMEI, context);



                // End Get last seen



                // Get the configuration for the current property
                strQuery = "SELECT TOP 1 EhiuInstallDetailCommands.MbusId, EhiuInstallDetailCommands.SendJson, EhiuInstallDetailCommands.ReplyJson, EhiuInstallDetailCommands.CompanionName, EhiuInstallDetailCommands.CompanionItemJson, " +
                           " EhiuInstallDetailCommands.DateCreated, EhiuInstall.FromDate, EhiuInstall.ToDate, Property.PropertyNumber, Property.BlockName, EhiuInstall.EhiuInstallID " +
                           " FROM EhiuInstall INNER JOIN " +
                           " EhiuInstallDetail ON EhiuInstall.EhiuInstallID = EhiuInstallDetail.EhiuInstallID INNER JOIN " +
                           " EhiuInstallDetailCommands ON EhiuInstallDetail.EhiuInstallDetailID = EhiuInstallDetailCommands.EhiuInstallDetailID INNER JOIN " +
                           " Property ON EhiuInstall.PropertyID = Property.PropertyID " +
                           " WHERE (EhiuInstallDetailCommands.CommandName = N'mbusconfig') AND (EhiuInstallDetailCommands.MbusId IS NOT NULL) AND (EhiuInstall.SerialNumber = @SerialNumber) AND (EhiuInstallDetailCommands.MbusId = 1) AND  " +
                           " (EhiuInstall.ToDate IS NULL) " +
                           " ORDER BY EhiuInstallDetailCommands.DateCreated DESC";

                daCheck = new SqlDataAdapter(strQuery, oSqlConnection);

                SqlParameter sqlParamSerialNumber = new SqlParameter("@SerialNumber", SqlDbType.NVarChar);
                sqlParamSerialNumber.Value = oInput.SerialNumber;
                daCheck.SelectCommand.Parameters.Add(sqlParamSerialNumber);

                daCheck.Fill(dsCheck);

                for (intIdx = 0; intIdx <= dsCheck.Tables[0].Rows.Count - 1; intIdx++)
                {
                    strJson = (string)dsCheck.Tables[0].Rows[intIdx]["CompanionItemJson"];

                    tMbusconfig_Companion mbusconfig_Companion;
                    mbusconfig_Companion = JsonSerializer.Deserialize <tMbusconfig_Companion>(strJson);

                    intDhwFlowTempID   = mbusconfig_Companion.FlowTempID;
                    intDhwReturnTempID = mbusconfig_Companion.ReturnTempID;
                    intDhwRateID       = mbusconfig_Companion.FlowRate;

                    oResult.IsInstalled = true;
                }
                // Build list to send
                if (oResult.IsInstalled == false)
                {
                    oResult.Info = "Not installed";
                }


                // -- Send Command -----------------------------------------------------------------
                oCommandSend = new tCommand();

                oCommandSend.CommandName = "controlreport";
                oCommandSend.UrlPath     = "controlreport/{devid}";
                oCommandSend.CommandJson = "";
                oCommandSend.ToEco       = false;

                tCommand oControlreportReply = new tCommand();

                oControlreportReply = PostApi(oCommandSend, strIMEI);
                if (oControlreportReply.PostStatus != "ok")
                {
                    oResult.HasError = true;
                    oResult.Info     = "Controlreport " + oControlreportReply.PostStatus;
                    return(oResult);
                }
                ;


                oControlReport = JsonSerializer.Deserialize <controlreport>(oControlreportReply.ReplyJson);
                // -- End Command -----------------------------------------------------------------



                // -- Send Command -----------------------------------------------------------------
                oCommandSend = new tCommand();

                oCommandSend.CommandName = "sensorreport";
                oCommandSend.UrlPath     = "sensorreport/{devid}";
                oCommandSend.CommandJson = "";
                oCommandSend.ToEco       = false;

                tCommand oSensorreportReply = new tCommand();

                oSensorreportReply = PostApi(oCommandSend, strIMEI);
                if (oSensorreportReply.PostStatus != "ok")
                {
                    oResult.HasError = true;
                    oResult.Info     = "SensorReport " + oSensorreportReply.PostStatus;
                    return(oResult);
                }
                ;


                oSensorReport = JsonSerializer.Deserialize <sensorreport>(oSensorreportReply.ReplyJson);
                // -- End Command -----------------------------------------------------------------



                // -- Send Command -----------------------------------------------------------------
                oCommandSend = new tCommand();

                oCommandSend.CommandName = "mbusreport";
                oCommandSend.UrlPath     = "mbusreport/{devid}/{pathelement}";
                oCommandSend.CommandJson = "";
                oCommandSend.PathElement = "1";
                oCommandSend.ToEco       = false;

                tCommand oMbusReportReply = new tCommand();

                oMbusReportReply = PostApi(oCommandSend, strIMEI);
                if (oMbusReportReply.PostStatus != "ok")
                {
                    oResult.HasError = true;
                    oResult.Info     = "SensorReport " + oMbusReportReply.PostStatus;
                    return(oResult);
                }
                ;


                oMbusReport = JsonSerializer.Deserialize <mbusreport>(oMbusReportReply.ReplyJson);
                // -- End Command -----------------------------------------------------------------


                if (oSensorReport.payg == 0)
                {
                    oResult.PaygoStatus = "Off";
                }
                else
                {
                    oResult.PaygoStatus = "On";
                };

                if (oResult.IsInstalled == true)
                {
                    oResult.PrimaryFlowRate       = GetSubValue(oMbusReport, intDhwRateID).ToString("0.0") + " l/m";
                    oResult.PrimaryFlowReturnTemp = GetSubValue(oMbusReport, intDhwReturnTempID).ToString("0.0") + " c";
                    oResult.PrimaryFlowTemp       = GetSubValue(oMbusReport, intDhwFlowTempID).ToString("0.0") + " c";
                }
                else
                {
                    oResult.PrimaryFlowRate       = "n/a";
                    oResult.PrimaryFlowReturnTemp = "n/a";
                    oResult.PrimaryFlowTemp       = "n/a";
                }


                oResult.PumpSpeed = oControlReport.chPump.ToString();
                oResult.SpaceHeatActuatorPosition = oControlReport.chValve.ToString();
                oResult.SpaceHeatDemandPresent    = oSensorReport.chDemand.ToString("0.0");
                oResult.SpaceHeatFlowReturnTemp   = oSensorReport.chInTemp.ToString("0.0") + " c";

                oResult.SpaceHeatFlowTemp = oSensorReport.chOutTemp.ToString("0.0") + " c";
                oResult.SpacePreasure     = oSensorReport.chPressure.ToString("0.0") + " bar";

                oResult.DhwFlow   = oSensorReport.hwInTemp.ToString("0.0") + " c";
                oResult.DhwReturn = oSensorReport.hwOutTemp.ToString("0.0") + " c";
                oResult.DhwRate   = oSensorReport.hwFlowRate.ToString("0.0") + " l/m";

                oResult.ActuatorPositionDhw = oControlReport.hwValve.ToString();

                if (oSensorReport.hwFlowRate == 0)
                {
                    oResult.DemandPresentDhw = "Yes";
                }
                else
                {
                    oResult.DemandPresentDhw = "No";
                }
            }



            catch (Exception ex)
            {
                context.Logger.LogLine("Ex in FunctionHandler " + ex.Message);
                oResult.HasError = false;
                oResult.Info     = ex.Message;
            }

            return(oResult);
        }