Exemplo n.º 1
0
        private void UpdateWallpaperCache()
        {
            BpWebResponse jsonResponse = wru.GET("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US");

            if (jsonResponse.StatusCode == 200 && jsonResponse.str.Length > 0)
            {
                BingWallpapers wp = JsonConvert.DeserializeObject <BingWallpapers>(jsonResponse.str);
                if (wp.Images != null && wp.Images.Length > 0)
                {
                    Image         img         = wp.Images[0];
                    BpWebResponse imgResponse = wru.GET("https://www.bing.com" + img.urlbase + "_1920x1080.jpg");
                    if (imgResponse.StatusCode == 200 && imgResponse.data.Length > 0)
                    {
                        img.ext_ImageData = imgResponse.data;
                    }
                    else
                    {
                        imgResponse = wru.GET("https://www.bing.com" + img.url);
                        if (imgResponse.StatusCode == 200 && imgResponse.data.Length > 0)
                        {
                            img.ext_ImageData = imgResponse.data;
                        }
                    }

                    if (img.ext_ImageData != null)
                    {
                        wallpaperCache = img;
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets all login records within a time range, ordered by Date descending.  Session must have admin privilege.
        /// </summary>
        /// <returns></returns>
        public ActionResult GeolocateIP()
        {
            GeolocateIPRequest request = ApiRequestBase.ParseRequest <GeolocateIPRequest>(this);

            if (IPAddress.TryParse(request.ip, out IPAddress ip))
            {
                string url = Settings.data.geolocationWebServiceBaseUrl;
                if (string.IsNullOrWhiteSpace(url))
                {
                    return(ApiError("The geolocation web service endpoint is not configured."));
                }
                if (!url.EndsWith("/"))
                {
                    url += "/";
                }
                url += "embed/" + ip.ToString();
                BpWebResponse proxyResponse = proxyClient.GET(url);
                return(Json(new GeolocateIPResponse()
                {
                    html = proxyResponse.str
                }));
            }
            else
            {
                return(ApiError("Invalid IP Address"));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Loads display names for device IDs and returns true if successful.
        /// </summary>
        /// <param name="forceLoad">if true, the load will occur even if data is already loaded</param>
        /// <returns></returns>
        public bool LoadDisplayNames(bool forceLoad = false)
        {
            if (string.IsNullOrWhiteSpace(host))
            {
                return(false);
            }
            if (deviceIdToDisplayName == null || forceLoad)
            {
                lock (displayNameLoadLock)
                {
                    if (deviceIdToDisplayName == null || forceLoad)
                    {
                        ConcurrentDictionary <int, string> map = new ConcurrentDictionary <int, string>();
                        try
                        {
                            BpWebResponse response = http_slow.GET(BaseUrl() + "/port_3480/data_request?id=user_data&output_format=xml");
                            string        xmlStr   = response.str;
                            XDocument     doc      = XDocument.Parse(xmlStr);
                            var           rooms    = doc.Descendants("rooms").First().Descendants("room")
                                                     .Select(room => new
                            {
                                id   = int.Parse(room.Attribute("id").Value),
                                name = room.Attribute("name").Value
                            }).ToDictionary(room => room.id);

                            var devices = doc.Descendants("devices").First().Descendants("device")
                                          .Select(device => new
                            {
                                id     = int.Parse(device.Attribute("id").Value),
                                roomId = device.Attribute("room") == null ? -1 : int.Parse(device.Attribute("room").Value),
                                name   = device.Attribute("name").Value
                            }).ToDictionary(room => room.id);

                            foreach (var device in devices.Values)
                            {
                                string deviceDisplayName = "";
                                if (rooms.ContainsKey(device.roomId))
                                {
                                    deviceDisplayName = rooms[device.roomId].name + " - ";
                                }
                                deviceDisplayName += device.name;
                                map[device.id]     = deviceDisplayName;
                            }
                            return(true);
                        }
                        catch (ThreadAbortException) { }
                        catch (Exception ex)
                        {
                            Logger.Debug(ex, "Error getting data from vera \"" + BaseUrl() + "\"");
                        }
                        finally
                        {
                            deviceIdToDisplayName = map;
                        }
                    }
                }
            }
            return(false);
        }
Exemplo n.º 4
0
        public void Send(EffectData effect)
        {
            if (string.IsNullOrWhiteSpace(host))
            {
                return;
            }
            if (effect == null)
            {
                Logger.Debug("VeraController.Send was given null EffectData");
                return;
            }
            if (effect.vera_deviceNum == null)
            {
                Logger.Debug("VeraController.Send was given null EffectData.vera_deviceNum");
                return;
            }
            try
            {
                string args = null;
                if (effect.vera_service == VeraService.CurtainStop)
                {
                    args = "WindowCovering1&action=Stop";
                }
                else if (effect.vera_service == VeraService.DimmerValue)
                {
                    args = "Dimming1&action=SetLoadLevelTarget&newLoadlevelTarget=" + ToInteger(effect.vera_value, 0, 100);
                }
                else if (effect.vera_service == VeraService.SwitchSet)
                {
                    args = "SwitchPower1&action=SetTarget&newTargetValue=" + ToInteger(effect.vera_value, 0, 1);
                }
                else
                {
                    Logger.Debug("Unknown VeraService value \"" + effect.vera_service + "\"");
                    return;
                }

                if (args == null)
                {
                    Logger.Debug("VeraController does not know how to handle service type \"" + effect.vera_service + "\"");
                    return;
                }
                http_fast.GET(BaseUrl() + "/port_3480/data_request?id=lu_action&output_format=json&DeviceNum=" + effect.vera_deviceNum + "&serviceId=urn:upnp-org:serviceId:" + args);
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logger.Debug(ex.ToString());
            }
        }
Exemplo n.º 5
0
        protected override void threadLoop()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        WebRequestUtility wru = new WebRequestUtility("BandwidthMonitor");
                        wru.BasicAuthCredentials = new NetworkCredential(User, Pass);
                        // Learn the http_id, used in later requests
                        BpWebResponse response          = wru.GET(Address + "ipt-realtime.asp");
                        string        ipt_realtime_page = response.str;
                        Match         m_http_id         = Regex.Match(ipt_realtime_page, "'http_id' ?: ?'([^']+)',");
                        string        http_id           = null;
                        if (m_http_id.Success)
                        {
                            http_id = m_http_id.Groups[1].Value;
                        }
                        else
                        {
                            Logger.Debug("Could not find http_id in response from ipt-realtime.asp");
                            Thread.Sleep(30000);
                            continue;
                        }

                        // Begin retrieving bandwidth usage data.
                        Stopwatch sw = new Stopwatch();
                        // Tomato's bandwidth reporting uses cumulative totals, so we need to keep track of the previous records to know how much has changed.
                        Dictionary <string, BandwidthRecord> previousRecords = new Dictionary <string, BandwidthRecord>();
                        Stopwatch swDevList = new Stopwatch();
                        response = wru.POST(Address + "update.cgi", new string[] { "exec", "devlist", "_http_id", http_id });
                        if (string.IsNullOrWhiteSpace(response.str))
                        {
                            Logger.Info("Received null or whitespace response instead of expected devlist");
                            Thread.Sleep(30000);
                            continue;
                        }
                        HandleDevListResponse(response.str);
                        swDevList.Start();
                        while (true)
                        {
                            sw.Restart();
                            long time = TimeUtil.GetTimeInMsSinceEpoch();
                            response = wru.POST(Address + "update.cgi", new string[] { "exec", "iptmon", "_http_id", http_id });
                            foreach (Match m in rxGetIpData.GetMatches(response.str))
                            {
                                string ip          = m.Groups[1].Value;
                                long   downloadRaw = Hex.PrefixedHexToLong(m.Groups[2].Value);
                                long   uploadRaw   = Hex.PrefixedHexToLong(m.Groups[3].Value);

                                DeviceInfo      device;
                                BandwidthRecord prev;

                                if (!devices.TryGetValue(ip, out device))
                                {
                                    devices[ip] = device = new DeviceInfo(ip);
                                }

                                if (!previousRecords.TryGetValue(ip, out prev))
                                {
                                    previousRecords[ip] = prev = new BandwidthRecord(time, downloadRaw, uploadRaw);
                                }

                                device.Name   = GetName(device.Address);
                                device.MAC    = GetMac(device.Address);
                                device.Vendor = GetMacVendor(device.MAC);

                                long downloadBytes;
                                long uploadBytes;
                                if (downloadRaw < prev.Download)
                                {
                                    downloadBytes = downloadRaw + (0xFFFFFFFF - prev.Download);
                                }
                                else
                                {
                                    downloadBytes = downloadRaw - prev.Download;
                                }
                                if (uploadRaw < prev.Upload)
                                {
                                    uploadBytes = uploadRaw + (0xFFFFFFFF - prev.Upload);
                                }
                                else
                                {
                                    uploadBytes = uploadRaw - prev.Upload;
                                }

                                device.AddNewBandwidthRecord(new BandwidthRecord(time, downloadBytes / 2, uploadBytes / 2));

                                previousRecords[ip] = new BandwidthRecord(time, downloadRaw, uploadRaw);
                            }
                            if (swDevList.Elapsed > timeBetweenDevListUpdates)
                            {
                                swDevList.Restart();
                                response = wru.POST(Address + "update.cgi", new string[] { "exec", "devlist", "_http_id", http_id });
                                HandleDevListResponse(response.str);
                            }
                            sw.Stop();
                            TimeSpan timeToWait = timeBetweenBandwidthUpdates - sw.Elapsed;
                            if (timeToWait > TimeSpan.Zero)
                            {
                                Thread.Sleep(timeToWait);
                            }
                        }
                    }
                    catch (ThreadAbortException) { throw; }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex);
                        Thread.Sleep(5000);
                    }
                }
            }
            catch (ThreadAbortException) { throw; }
            catch (Exception ex)
            {
                Logger.Debug(ex);
            }
        }
Exemplo n.º 6
0
 private void SyncWithOtherServer()
 {
     try
     {
         WebRequestUtility wru        = new WebRequestUtility("MonitorControl " + Globals.AssemblyVersion, 1000);
         string            lastStatus = "";
         int connectionFailureCount   = 0;
         while (true)
         {
             try
             {
                 if (!Program.settings.syncAllowLocalOverride)
                 {
                     lastStatus = MonitorControlServer.currentMonitorStatus;
                 }
                 string address = Program.settings.syncAddress;
                 if (!string.IsNullOrWhiteSpace(address))
                 {
                     string        url      = "http" + (Program.settings.syncHTTPS ? "s" : "") + "://" + address + ":" + Program.settings.syncPort + "/status";
                     BpWebResponse response = wru.GET(url);
                     if (response.StatusCode == 0)
                     {
                         connectionFailureCount++;
                         syncedServerStatus = "The remote server is not responding.  It may be misconfigured, blocked by a firewall, or not running.";
                         if (connectionFailureCount >= 5)                                 // Don't take action due to a short-term failure.
                         {
                             if (Program.settings.syncFailureAction == 1)
                             {
                                 if (lastStatus != "off")
                                 {
                                     lastStatus = "off";
                                     MonitorControlServer.Off(Program.settings.syncMute);
                                 }
                             }
                             else if (Program.settings.syncFailureAction == 2)
                             {
                                 if (lastStatus != "on")
                                 {
                                     lastStatus = "on";
                                     MonitorControlServer.On(null);
                                 }
                             }
                         }
                     }
                     else
                     {
                         connectionFailureCount = 0;
                         if (response.StatusCode == 403)
                         {
                             syncedServerStatus = "The remote server rejected our request (this server's IP is probably not authorized there).";
                         }
                         else if (response.StatusCode != 200)
                         {
                             syncedServerStatus = "The remote server responded with unexpected status code " + response.StatusCode;
                             try
                             {
                                 syncedServerStatus += " " + response.str;
                             }
                             catch { }
                         }
                         else
                         {
                             try
                             {
                                 syncedServerStatus = "The remote server monitors are " + response.str;
                                 if (response.str != lastStatus)
                                 {
                                     if (response.str == "off")
                                     {
                                         lastStatus = "off";
                                         MonitorControlServer.Off(Program.settings.syncMute);
                                     }
                                     else if (response.str == "on")
                                     {
                                         lastStatus = "on";
                                         MonitorControlServer.On(null);
                                     }
                                 }
                             }
                             catch
                             {
                                 syncedServerStatus = "The remote server provided an invalid response.";
                             }
                         }
                     }
                 }
                 else
                 {
                     connectionFailureCount = 0;
                     syncedServerStatus     = "Not configured to synchronize with a remote server.";
                 }
                 Thread.Sleep(1000);
             }
             catch (ThreadAbortException)
             {
             }
             catch (Exception ex)
             {
                 syncedServerStatus = "An error occurred when synchronizing with a remote server. " + ex.ToString();
                 Logger.Debug(ex);
             }
         }
     }
     catch (ThreadAbortException)
     {
     }
     catch (Exception ex)
     {
         syncedServerStatus = "Remote server sync has experienced a fatal error and will not resume operation until MonitorControl is restarted. " + ex.ToString();
         Logger.Debug(ex);
     }
 }
Exemplo n.º 7
0
        private static void ExecuteHotkey(Hotkey hotkey)
        {
            ParallelOptions parallelOptions = new ParallelOptions();

            parallelOptions.MaxDegreeOfParallelism = 16;
            Parallel.ForEach(hotkey.effects, parallelOptions, effect =>
            {
                switch (effect.type)
                {
                case EffectType.HttpGet:
                    {
                        if (!string.IsNullOrWhiteSpace(effect.data.httpget_url) && Uri.TryCreate(effect.data.httpget_url, UriKind.Absolute, out Uri result))
                        {
                            http_fast.GET(effect.data.httpget_url);
                        }
                        break;
                    }

                case EffectType.BroadLink:
                    {
                        BroadLinkController broadLink = ServiceWrapper.config.broadLinks.Get(effect.data.broadlink_name);
                        if (broadLink == null)
                        {
                            Logger.Info("BroadLink \"" + effect.data.broadlink_name + "\" does not exist.");
                            break;
                        }
                        broadLink.SendCommandSync(effect.data.broadlink_commandName, effect.data.broadlink_repeatCount);
                        break;
                    }

                case EffectType.iTach:
                    {
                        iTachController iTach = ServiceWrapper.config.iTachs.Get(effect.data.itach_name);
                        if (iTach == null)
                        {
                            Logger.Info("iTach \"" + effect.data.itach_name + "\" does not exist.");
                            break;
                        }
                        iTach.SendCommandSync(effect.data.itach_commandShortName, effect.data.itach_connectorAddress, effect.data.itach_repeatCount);
                        break;
                    }

                case EffectType.Vera:
                    {
                        VeraController vera = ServiceWrapper.config.veras.Get(effect.data.vera_name);
                        if (vera == null)
                        {
                            Logger.Info("Vera \"" + effect.data.vera_name + "\" does not exist.");
                            break;
                        }
                        vera.Send(effect.data);
                        break;
                    }

                case EffectType.HomeAssistant:
                    {
                        HomeAssistantServer hassServer = ServiceWrapper.config.homeAssistantServers.Get(effect.data.hass_servername);
                        if (hassServer == null)
                        {
                            Logger.Info("HomeAssistant Server \"" + effect.data.hass_servername + "\" does not exist.");
                            break;
                        }
                        hassServer.CallService(effect.data.hass_entityid, effect.data.hass_method.Value, effect.data.hass_value);
                        break;
                    }

                default:
                    Logger.Info("Unhandled hotkey effect type: " + effect.type + " in hotkey with name \"" + hotkey.name + "\"");
                    break;
                }
            });
        }