コード例 #1
0
ファイル: Wink.cs プロジェクト: suspended/WinkAtHome
    private List<Device> winkGetDevices(JObject jsonObject = null, bool forceRefresh = false)
    {
        try
        {

            bool firstRun = false;
            if (_devices == null || jsonObject != null || forceRefresh)
            {
                List<Device> Devices = new List<Device>();
                JObject json = null;

                if (_devices == null || forceRefresh)
                {
                    firstRun = true;
                    json = winkCallAPI(ConfigurationManager.AppSettings["winkRootURL"] + ConfigurationManager.AppSettings["winkGetAllDevicesURL"]);
                }
                else if (jsonObject != null)
                {
                    json = jsonObject;
                    Devices = _devices;
                }

                if (json != null)
                {
                    foreach (JObject data in json["data"])
                    {
                        IEnumerable<string> ikeys = data.Properties().Select(p => p.Name);
                        if (ikeys != null)
                        {
                            List<string> keys = ikeys.ToList();

                            string desired_states = string.Empty;
                            string last_readings = string.Empty;

                            string typeName = keys[0];

                            Device device = new Device();
                            device.json = data.ToString();
                            device.name = data["name"] != null ? data["name"].ToString() : "error: name";
                            if (jsonObject != null)
                            {
                                device = Device.getDeviceByName(device.name);
                                Devices.Remove(device);
                            }
                            else
                            {
                                device.iscontrollable = false;

                                device.id = data[typeName] != null ? data[typeName].ToString() : "error: typeName";
                                device.displayName = device.name;
                                device.type = data[typeName] != null ? typeName.Replace("_id", "s").Replace("switchs", "switches") : "error: type";
                                device.menu_type = device.type;

                                if (keys.Contains("device_manufacturer"))
                                {
                                    device.manufacturer = data["device_manufacturer"].ToString();
                                }

                                if (keys.Contains("radio_type"))
                                {
                                    device.radio_type = data["radio_type"].ToString();
                                }

                                if (keys.Contains("model_name"))
                                {
                                    device.model = data["model_name"].ToString();
                                }

                                if (keys.Contains("update_needed"))
                                {
                                    if (!string.IsNullOrWhiteSpace(data["update_needed"].ToString()))
                                    {
                                        string update = data["update_needed"].ToString();
                                        device.update_needed = Convert.ToBoolean(update);
                                    }
                                }

                                if (keys.Contains("hub_id"))
                                {
                                    device.hub_id = data["hub_id"].ToString();
                                }
                            }

                            if (keys.Contains("desired_state"))
                            {
                                JObject states = (JObject)data["desired_state"];
                                desired_states = states.ToString();

                                Device.getDesired_States(device, states);
                            }
                            else
                            {
                                device.issensor = true;
                            }

                            if (keys.Contains("last_reading"))
                            {
                                JObject readings = (JObject)data["last_reading"];
                                last_readings = readings.ToString();

                                Device.getLast_Readings(device, readings);
                            }

                            //FIX THE BROKEN API TEMPORARY FIX
                            if (device.type == "light_bulbs" || device.type == "binary_switches")
                            {
                                device.issensor = false;
                                device.iscontrollable = true;
                                device.desired_states.Add("powered");

                                if (device.type == "light_bulbs")
                                {
                                    device.isvariable = true;
                                    device.desired_states.Add("brightness");
                                }
                            }
                            //END BROKEN API FIX

                            #region NON-SENSOR DEVICE-SPECIFIC CONFIGURATIONS
                            //DEVICE EXCEPTIONS

                            //Power Pivot Genius
                            if (keys.Contains("powerstrip_id"))
                            {
                                device.id = data["powerstrip_id"].ToString();
                                device.type = "powerstrips";
                                device.menu_type = device.type;
                                device.issensor = false;
                                foreach (Device.DeviceStatus status in device.status)
                                    status.id = device.id;

                                foreach (var outlet in data["outlets"])
                                {
                                    Device outletdevice = new Device();
                                    outletdevice.json = outlet.ToString();
                                    outletdevice.id = outlet["outlet_id"].ToString();
                                    outletdevice.name = device.name + " - " + outlet["name"].ToString();
                                    outletdevice.displayName = outletdevice.name;
                                    outletdevice.type = "outlets";
                                    outletdevice.menu_type = "powerstrips";
                                    outletdevice.manufacturer = device.manufacturer;
                                    outletdevice.radio_type = device.radio_type;
                                    outletdevice.model = device.model;

                                    JObject states = (JObject)outlet["desired_state"];
                                    Device.getDesired_States(outletdevice, states);

                                    JObject readings = (JObject)outlet["last_reading"];
                                    Device.getLast_Readings(outletdevice, readings);

                                    Device.DeviceStatus connstatus = device.status.Single(s => s.name == "connection");
                                    outletdevice.status.Add(connstatus);

                                    Devices.Add(outletdevice);
                                }
                            }

                            //Relay
                            if (device.type == "buttons" || device.type == "gangs")
                            {
                                device.issensor = false;
                                device.menu_type = "unknown_devices";
                            }

                            //Relay Switches
                            if (device.type == "binary_switches" && device.radio_type == "project_one")
                            {
                                Device.DeviceStatus status = device.status.SingleOrDefault(s => s.name == "powering_mode");
                                if (status.current_status=="none")
                                {
                                    device.iscontrollable = false;
                                }
                            }

                            //remotes
                            if (device.type == "remotes")
                            {
                                device.issensor = false;
                            }

                            //garage door openers
                            if (device.type == "garage_doors")
                            {
                                device.isvariable = false;
                            }

                            //lock PINs
                            if (keys.Contains("key_id") && keys.Contains("parent_object_type") && data["parent_object_type"].ToString().ToLower() == "lock")
                            {
                                device.id = data["key_id"] != null ? data["key_id"].ToString() : "error: key_id";
                                device.name = data["name"] != null ? data["name"].ToString() : "error: name";
                                device.type = "lock_pins";
                                device.issensor = false;
                                device.menu_type = "locks";
                                foreach (Device.DeviceStatus status in device.status)
                                    status.id = device.id;
                            }
                            #endregion

                            #region SENSOR DEVICE CONFIGURATIONS
                            List<string> capabilities = new List<string>();

                            //Sensor Pods
                            if (keys.Contains("sensor_pod_id"))
                            {
                                device.id = data["sensor_pod_id"].ToString();
                                device.type = "sensor_pods";
                                device.menu_type = device.type;
                                foreach (Device.DeviceStatus status in device.status)
                                    status.id = device.id;
                            }

                            //hubs
                            if (device.type == "hubs")
                            {
                                device.issensor = true;
                                device.iscontrollable = false;

                                if (device.model.ToLower() == "wink relay")
                                    device.type = "wink_relays";
                            }

                            //refuel
                            if (device.type == "propane_tanks")
                            {
                                if (keys.Contains("tank_changed_at"))
                                {
                                    Device.DeviceStatus tankstatus = new Device.DeviceStatus();
                                    tankstatus.id = device.id;
                                    tankstatus.name = "tank_changed_at";
                                    tankstatus.current_status = Common.FromUnixTime(data["tank_changed_at"].ToString(), true).ToString();
                                    tankstatus.last_updated = Common.FromUnixTime(data["tank_changed_at"].ToString(), true);
                                    device.status.Add(tankstatus);
                                }

                                Wink.Device.DeviceStatus stat = device.status.SingleOrDefault(p => p.name == "remaining");
                                if (stat != null)
                                {
                                    Double converted = Convert.ToDouble(stat.current_status) * 100;
                                    string degree = converted.ToString();

                                    string imgDegree = "100";
                                    if (converted <= 10)
                                        imgDegree = "0";
                                    else if (converted <= 30)
                                        imgDegree = "25";
                                    else if (converted <= 60)
                                        imgDegree = "50";
                                    else if (converted <= 90)
                                        imgDegree = "75";
                                    else
                                        imgDegree = "100";

                                    device.sensortripped = imgDegree;
                                }

                            }

                            //POS
                            if (device.model != null && device.model.ToLower() == "egg minder")
                            {
                                device.id = data["eggtray_id"] != null ? data["eggtray_id"].ToString() : "error: key_id";
                                device.type = "eggtray";
                                device.menu_type = "eggtray";

                                capabilities.Add("inventory");
                                capabilities.Add("age");
                            }

                            if (device.type == "smoke_detectors")
                            {
                                device.sensortripped = null;

                                string strStatuses = string.Empty;

                                Wink.Device.DeviceStatus costat = device.status.SingleOrDefault(p => p.name == "co_detected");
                                if (costat != null)
                                    strStatuses += costat.current_status;

                                Wink.Device.DeviceStatus smstat = device.status.SingleOrDefault(p => p.name == "smoke_detected");
                                if (smstat != null)
                                    strStatuses += smstat.current_status;

                                Wink.Device.DeviceStatus teststat = device.status.SingleOrDefault(p => p.name == "test_activated");
                                if (teststat != null && teststat.current_status.ToLower() == "true")
                                    strStatuses += "test";

                                if (strStatuses.ToLower().Contains("true"))
                                    device.sensortripped = "true";
                                else if (strStatuses.ToLower().Contains("test"))
                                    device.sensortripped = "test";

                                device.sensor_type = device.type;

                                capabilities.Add("co_detected");
                                capabilities.Add("smoke_detected");
                            }

                            if (device.issensor)
                            {
                                string model = device.model.ToLower();
                                List<Wink.Device.DeviceStatus> OpenClose = device.status.Where(s => s.name == "opened").ToList();

                                if (OpenClose.Count > 0)
                                {
                                    Wink.Device.DeviceStatus stat = device.status.Single(p => p.name == "opened");
                                    device.sensortripped = stat.current_status.ToLower();

                                    string type = "dooropen";
                                    string lowername = device.name.ToLower();
                                    if (lowername.Contains("window"))
                                        type = "windowopen";
                                    else if (lowername.Contains("patio") || lowername.Contains("deck"))
                                        type = "deckopen";
                                    else if (lowername.Contains("cabinet"))
                                        type = "cabinetopen";

                                    device.sensor_type = type;
                                }
                                else if (model == "spotter")
                                {
                                    device.sensor_type = "spotter";
                                }
                                else if (model.Contains("pir") || model.Contains("infrared") || model.Contains("motion"))
                                {
                                    device.sensor_type = "motion_sensor";
                                }

                                if (string.IsNullOrWhiteSpace(device.sensor_type))
                                {
                                    device.sensor_type = device.type;
                                }

                                //CAPABILITIES
                                if (device.menu_type != "hubs")
                                {
                                    if (keys.Contains("capabilities"))
                                    {
                                        var capabilityList = data["capabilities"];
                                        if (capabilityList != null)
                                        {
                                            var sensor_types = capabilityList["sensor_types"];
                                            if (sensor_types != null)
                                            {
                                                foreach (var type in sensor_types)
                                                {
                                                    string sensorname = type["field"].ToString();
                                                    //if (sensorname != "battery" && sensorname != "external_power")
                                                        capabilities.Add(sensorname);
                                                }
                                            }
                                        }
                                    }
                                }
                                if (capabilities.Count > 0)
                                {
                                    foreach (string capability in capabilities)
                                    {
                                        Device.DeviceStatus status = device.status.SingleOrDefault(s => s.name == capability);
                                        if (status != null)
                                        {
                                            string strValue = status.current_status;
                                            Int32 intValue = 0;
                                            Int32.TryParse(strValue, out intValue);

                                            if (status.name == "temperature")
                                            {
                                                double temp = 0;
                                                double.TryParse(strValue ,out temp);
                                                temp = Common.FromCelsiusToFahrenheit(temp);
                                                status.current_status = Convert.ToString(temp);
                                            }

                                            if (intValue > 1000000000)
                                                status.current_status = Common.FromUnixTime(strValue, true).ToString();

                                            if (status.name.ToLower() != "battery" && status.name.ToLower() != "external_power")
                                            {
                                                if (status.current_status.ToLower() == "true" || status.current_status.ToLower() == "1")
                                                    device.sensortripped = "true";
                                            }

                                            device.sensor_states.Add(status);
                                        }
                                    }
                                }
                            }
                            #endregion

                            Devices.Add(device);

                            //UPDATE DEVICE DB
                            using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + Common.dbPath + ";Version=3;"))
                            {
                                connection.Open();

                                using (SQLiteCommand command = new SQLiteCommand(connection))
                                {
                                    command.CommandText = "UPDATE Devices SET name=@name WHERE UserID=@UserID AND DeviceID = @ID AND Name<>@name;";
                                    command.Parameters.Add(new SQLiteParameter("@UserID", myWink.winkUser.userID));
                                    command.Parameters.Add(new SQLiteParameter("@ID", device.id));
                                    command.Parameters.Add(new SQLiteParameter("@name", device.name));
                                    command.ExecuteNonQuery();

                                    command.CommandText = "INSERT OR IGNORE INTO Devices (UserID, DeviceID, name) VALUES (@UserID, @ID, @name);";
                                    command.ExecuteNonQuery();
                                }
                            }
                        }
                    }
                }
                _devices = Devices.OrderBy(c => !c.iscontrollable).ThenBy(c => c.name).ToList();
            }

            #region RETRIEVE DATABASE VALUES & POST-LOAD PROCESSING
            using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + Common.dbPath + ";Version=3;"))
            {
                connection.Open();

                using (SQLiteCommand command = new SQLiteCommand(connection))
                {
                    DataTable dt = new DataTable();
                    command.CommandText = "SELECT * FROM Devices WHERE UserID=@UserID";
                    command.Parameters.Add(new SQLiteParameter("@UserID", myWink.winkUser.userID));
                    SQLiteDataAdapter da = new SQLiteDataAdapter(command);
                    da.Fill(dt);

                    foreach (Device device in _devices)
                    {
                        //VALUE FROM DATABASE
                        DataRow[] rowArray = dt.Select("DeviceID = '" + device.id + "'");
                        if (rowArray.Length > 0)
                        {
                            DataRow row = rowArray[0];

                            device.position = Convert.ToInt32(row["Position"].ToString());

                            device.subscriptionCapable = Convert.ToBoolean(row["subscriptionCapable"].ToString());

                            device.subscriptionTopic = row["SubscriptionTopic"].ToString();

                            DateTime expires = new DateTime();
                            string date = row["SubscriptionExpires"].ToString();
                            DateTime.TryParse(date, out expires);
                            device.subscriptionExpires = Convert.ToDateTime(expires);

                            if (!string.IsNullOrWhiteSpace(row["DisplayName"].ToString()))
                                device.displayName = row["DisplayName"].ToString();
                        }
                    }
                }
            }
            #endregion

            #region PUBNUB SUBSCRIPTIONS
            if (PubNub.myPubNub.hasPubNub)
            {
                foreach (Device device in _devices)
                {
                    if ((string.IsNullOrWhiteSpace(device.subscriptionTopic) || DateTime.Now > device.subscriptionExpires) && (device.subscriptionCapable || firstRun))
                    {
                        string URL = ConfigurationManager.AppSettings["winkRootURL"] + device.type + "/" + device.id + "/subscriptions";
                        string sendCommand = "{\"publisher_key\":\"" + PubNub.myPubNub.publishKey + "\",\"subscriber_key\":\"" + PubNub.myPubNub.subscriberKey + "\"}";
                        JObject subJSON = winkCallAPI(URL, "POST", sendCommand);
                        if (subJSON != null)
                        {
                            string subCapable = string.Empty;

                            if (subJSON.ToString().Contains("404") && !firstRun)
                            {
                                subCapable = "0";
                                device.subscriptionCapable = false;
                            }
                            else if (subJSON["data"] != null)
                            {
                                subCapable = "1";
                                device.subscriptionCapable = true;

                                if (subJSON["data"]["topic"] != null)
                                    device.subscriptionTopic = subJSON["data"]["topic"].ToString();

                                if (subJSON["data"]["expires_at"] != null)
                                    device.subscriptionExpires = Common.FromUnixTime(subJSON["data"]["expires_at"].ToString());
                            }

                            using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + Common.dbPath + ";Version=3;"))
                            {
                                connection.Open();
                                using (SQLiteCommand command = new SQLiteCommand(connection))
                                {
                                    command.CommandText = "UPDATE Devices SET subscriptionTopic=@subscriptionTopic,subscriptionExpires=@subscriptionExpires,subscriptionCapable=@subscriptionCapable WHERE UserID=@UserID AND DeviceID = @ID;";
                                    command.Parameters.Add(new SQLiteParameter("@UserID", myWink.winkUser.userID));
                                    command.Parameters.Add(new SQLiteParameter("@ID", device.id));
                                    command.Parameters.Add(new SQLiteParameter("@subscriptionTopic", device.subscriptionTopic));
                                    command.Parameters.Add(new SQLiteParameter("@subscriptionExpires", device.subscriptionExpires));
                                    command.Parameters.Add(new SQLiteParameter("@subscriptionCapable", subCapable));
                                    command.ExecuteNonQuery();

                                    command.CommandText = "INSERT OR IGNORE INTO Devices(UserID,DeviceID,subscriptionTopic,subscriptionExpires,subscriptionCapable) VALUES (@UserID, @ID,@subscriptionTopic,@subscriptionExpires,@subscriptionCapable)";
                                    command.ExecuteNonQuery();
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region FINAL PROCESSING
            foreach (Device device in _devices)
            {
                Device hubDevice = _devices.SingleOrDefault(h => h.id == device.hub_id);
                if (hubDevice != null)
                    device.hub_name = hubDevice.displayName;
            }
            #endregion

            return _devices;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
コード例 #2
0
ファイル: Wink.cs プロジェクト: suspended/WinkAtHome
        internal static Device getLast_Readings(Device device, JObject readings)
        {
            List<Device.DeviceStatus> states = new List<Device.DeviceStatus>();
            device.status = new List<Device.DeviceStatus>();

            if (readings != null)
            {
                foreach (var reading in readings)
                {
                    if (!reading.Key.Contains("_updated_at"))
                    {
                        Device.DeviceStatus deviceStatus = new Device.DeviceStatus();
                        deviceStatus.id = device.id;
                        deviceStatus.name = reading.Key;
                        deviceStatus.current_status = reading.Value.ToString();

                        if (readings[reading.Key + "_updated_at"] != null)
                        {
                            string lastupdated = readings[reading.Key + "_updated_at"].ToString();
                            deviceStatus.last_updated = Common.FromUnixTime(lastupdated, true);
                        }

                        device.status.Add(deviceStatus);
                    }
                }
            }

            return device;
        }
コード例 #3
0
ファイル: Device.cs プロジェクト: barbaroony/GMSEC_API
 /// <summary>Simple constructor</summary>
 ///
 /// <param name="name">%Device name</param>
 /// <param name="status">%Device status</param>
 ///
 /// <exception cref="GmsecException">Thrown if the name is null or contains an empty-string</exception>
 public Device(string name, Device.DeviceStatus status)
 {
 }
コード例 #4
0
ファイル: Device.cs プロジェクト: barbaroony/GMSEC_API
 /// <summary>Constructor that accepts list of %Device Parameters</summary>
 ///
 /// <param name="name">Device name</param>
 /// <param name="status">Device status</param>
 /// <param name="params">List of device parameters</param>
 ///
 /// <exception cref="GmsecException">Thrown if the name is null or contains an empty-string</exception>
 public Device(string name, Device.DeviceStatus status, DeviceParamList params)
 {
 }
コード例 #5
0
ファイル: Device.cs プロジェクト: barbaroony/GMSEC_API
 /// <summary>Allows for the setting of the status of the %Device</summary>
 ///
 /// <param name="status">The status of the %Device</param>
 public void SetStatus(Device.DeviceStatus status)
 {
 }