public dynamic Request(string url, Dictionary <string, string> query = null) { log.LogInformation($"Access Token: {accessToken}"); Dictionary <string, string> headers = new Dictionary <string, string> { { "Authorization", $"Bearer {accessToken}" } }; if (query != null) { url += "?"; foreach (KeyValuePair <string, string> q in query) { if (q.Value != null) { url = $"{url}&{q.Key}={q.Value}"; } } } dynamic data_response = Leo.GetJSONResponse(log, url, headers: headers); if (data_response?.error != null) { log.LogError($"{data_response}"); } return(data_response); }
public dynamic PostRequest(string url, dynamic data) { Dictionary <string, string> headers = new Dictionary <string, string> { { "Authorization", $"Bearer {accessToken}" } }; return(Leo.PostJSONResponse(log, url, data, headers)); }
/// <summary> /// Sends a HTTP GET request to turn on a device. /// </summary> /// <param name="log">Logger</param> /// <param name="deviceName">The name of the device, corresponding to the environment variable defined in settings.</param> public static void TurnOnDeviceByHttpRequest(ILogger log, string deviceName) { string envVariable = deviceName + "On"; string deviceOnUrl = Environment.GetEnvironmentVariable(envVariable); if (deviceOnUrl != null) { Leo.GetHttpResponse(log, deviceOnUrl, 3); } else { log.LogError($"Trigger for turning on {deviceName} not found."); } }
/// <summary> /// Schedules turning off a device by sending a message to the service bus queue. /// /// </summary> /// <param name="log">Logger</param> /// <param name="senderName">Sender of the request, for logging purpose.</param> /// <param name="deviceName">The name of the device, corresponding to the environment variable defined in settings.</param> /// <param name="seconds">The number of seconds to wait before turning off the device.</param> /// <returns></returns> public static async Task ScheduleOff(ILogger log, string senderName, string deviceName, int seconds) { Dictionary <string, string> dict = new Dictionary <string, string>() { { "sender", senderName }, { "device", deviceName }, }; string messageText = JsonConvert.SerializeObject(dict); DateTime?turnOffTime = await Leo.SendMessageAsync(log, Leo.turnOffDeviceQueueName, messageText, seconds); if (turnOffTime != null) { log.LogInformation($"Device is scheduled to be turned off at {turnOffTime}"); } else { log.LogError($"Failed to schedule turning off device {deviceName}."); } }
private static Status AlarmStatus(GmailAPI api, ILogger log) { string alarmMode = null; string changedTime = null; string details = null; List <dynamic> messages = api.ListMessages(); foreach (dynamic message in messages) { string messageID = message.id; dynamic fullMessage = api.GetMessage(messageID); dynamic headers = fullMessage.payload.headers; string subject = null; foreach (dynamic header in headers) { if (header.name == "Subject") { subject = header.value; break; } } ringAlarm.TryGetValue(subject, out alarmMode); if (alarmMode != null) { //string msg = JsonConvert.SerializeObject(fullMessage); changedTime = Leo.MillisecondsToLocalTimeString(Convert.ToInt64(fullMessage.internalDate)); // Extract information from snippet Match match = Regex.Match(Convert.ToString(fullMessage.snippet), @".*?(Ring\sAlarm\sin\s[A-Za-z]+\schanged\sto\s.*?)Still\shave\squestions\?"); details = match.Groups[1].Value; break; } } alarmMode = alarmMode ?? "Unknown"; return(new Status { Mode = alarmMode, Time = changedTime, Details = details }); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation($"{DateTime.Now} :: HTTP trigger function processing a \"Turn On Device\" request."); // Get parameters from GET request string deviceName = req.Query["device"]; string senderName = req.Query["sender"]; string condition = req.Query["condition"]; string skip = req.Query["skip"]; // duration will have the value of -1 if it is not specified. Int32.TryParse(req.Query["duration"], out int duration); // Parse request body for POST reqeust string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); // Get parameters from POST request, if parameter is not valid in GET request. deviceName ??= data?.device; senderName ??= data?.sender; condition ??= data?.condition; skip ??= data?.skip; // duration will have the value of -1 if it is not specified. if (duration == -1) { Int32.TryParse(data?.duration, out duration); } log.LogInformation($"Device: {deviceName}, Sender: {senderName}, Duration: {duration}"); string responseMessage = ""; if (deviceName != null) { switch (condition) { // Turn on the device during daytime only. case "day": if (Leo.AtNight(log)) { responseMessage = $"It is nighttime now. {deviceName} not turned on."; log.LogInformation(responseMessage); return(new OkObjectResult($"It is nighttime now. {deviceName} not turned on.")); } break; // Turn on the device during nighttime only. case "night": if (!Leo.AtNight(log)) { responseMessage = $"It is daytime now. {deviceName} not turned on."; log.LogInformation(responseMessage); return(new OkObjectResult(responseMessage)); } break; } // Turn on the device only if skip is null (not found in the parameters). if (skip == null) { // Turn on the device TurnOnDeviceByHttpRequest(log, deviceName); responseMessage += $"Turned on {deviceName}. "; } // Schedule the device to be turned off if (duration > 0) { await ScheduleOff(log, senderName, deviceName, duration); responseMessage += $"Scheduled {deviceName} to be turned off in {duration} seconds."; } // Return Response log.LogInformation(responseMessage); return(new OkObjectResult(responseMessage)); } // Return bad request if the device parameter is null log.LogError("Parameter \"device\" not found on the query string or in the request body."); return(new BadRequestObjectResult("Please pass a \"device\" parameter on the query string or in the request body.")); }