Пример #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NPCChatDialogForm"/> class.
        /// </summary>
        /// <param name="position">The position.</param>
        /// <param name="parent">The parent.</param>
        public NPCChatDialogForm(Vector2 position, Control parent) : base(parent, position, new Vector2(400, 300))
        {
            IsVisible = false;

            // NOTE: We want to use a scrollable textbox here... when we finally make one

            float spacing = Font.GetLineSpacing();

            var responseStartY = ClientSize.Y - (_numDisplayedResponses * spacing);
            var textboxSize = ClientSize - new Vector2(0, ClientSize.Y - responseStartY);
            _dialogTextControl = new TextBox(this, Vector2.Zero, textboxSize)
            { IsEnabled = false, CanFocus = false, IsMultiLine = true, Font = GameScreenHelper.DefaultChatFont };
            _dialogTextControl.ClientSize -= _dialogTextControl.Border.Size;

            for (byte i = 0; i < _numDisplayedResponses; i++)
            {
                var r = new ResponseText(this, new Vector2(5, responseStartY + (spacing * i))) { IsVisible = true, Font = GameScreenHelper.DefaultChatFont };
                r.Clicked += ResponseText_Clicked;
                _responseTextControls[i] = r;
            }
        }
Пример #2
0
        public object InterfaceControl(MigInterfaceCommand request)
        {
            ResponseText returnValue = new ResponseText("OK");
            bool raiseEvent = false;
            string eventParameter = ModuleEvents.Status_Level;
            string eventValue = "";

            string nodeId = request.Address;
            Commands command;
            Enum.TryParse<Commands>(request.Command.Replace(".", "_"), out command);
            ZWaveNode node = null;

            byte nodeNumber = 0;
            if (byte.TryParse(nodeId, out nodeNumber))
            {
                if (nodeNumber > 0)
                    node = controller.GetNode(nodeNumber);
                switch (command)
                {

                case Commands.Controller_Discovery:
                    controller.Discovery();
                    break;

                case Commands.Controller_SoftReset:
                    controller.SoftReset();
                    break;

                case Commands.Controller_HardReset:
                    controller.HardReset();
                    controller.Discovery();
                    break;

                case Commands.Controller_HealNetwork:
                    controller.HealNetwork();
                    break;

                case Commands.Controller_NodeNeighborUpdate:
                    controller.RequestNeighborsUpdateOptions(nodeNumber);
                    controller.RequestNeighborsUpdate(nodeNumber);
                    controller.GetNeighborsRoutingInfo(nodeNumber);
                    returnValue = GetResponseValue(nodeNumber, EventPath_RoutingInfo);
                    break;

                case Commands.Controller_NodeRoutingInfo:
                    controller.GetNeighborsRoutingInfo(nodeNumber);
                    returnValue = GetResponseValue(nodeNumber, EventPath_RoutingInfo);
                    break;

                case Commands.Controller_NodeAdd:
                    lastAddedNode = 0;
                    controller.BeginNodeAdd();
                    for (int i = 0; i < 20; i++)
                    {
                        if (lastAddedNode > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    controller.StopNodeAdd();
                    returnValue = new ResponseText(lastAddedNode.ToString());
                    break;

                case Commands.Controller_NodeRemove:
                    lastRemovedNode = 0;
                    controller.BeginNodeRemove();
                    for (int i = 0; i < 20; i++)
                    {
                        if (lastRemovedNode > 0)
                        {
                            break;
                        }
                        Thread.Sleep(500);
                    }
                    controller.StopNodeRemove();
                    returnValue = new ResponseText(lastRemovedNode.ToString());
                    break;

                case Commands.Basic_Set:
                    {
                        raiseEvent = true;
                        var level = int.Parse(request.GetOption(0));
                        eventValue = level.ToString(CultureInfo.InvariantCulture);
                        Basic.Set(node, (byte)level);
                    }
                    break;

                case Commands.Basic_Get:
                    Basic.Get(node);
                    returnValue = GetResponseValue(nodeNumber, EventPath_Basic);
                    break;

                case Commands.SwitchBinary_Set:
                    {
                        raiseEvent = true;
                        var level = int.Parse(request.GetOption(0));
                        eventValue = level.ToString(CultureInfo.InvariantCulture);
                        SwitchBinary.Set(node, (byte)level);
                    }
                    break;

                case Commands.SwitchBinary_Get:
                    SwitchBinary.Get(node);
                    returnValue = GetResponseValue(nodeNumber, EventPath_SwitchBinary);
                    break;

                case Commands.SwitchMultilevel_Set:
                    {
                        raiseEvent = true;
                        var level = int.Parse(request.GetOption(0));
                        eventValue = level.ToString(CultureInfo.InvariantCulture);
                        SwitchMultilevel.Set(node, (byte)level);
                    }
                    break;

                case Commands.SwitchMultilevel_Get:
                    SwitchMultilevel.Get(node);
                    returnValue = GetResponseValue(nodeNumber, EventPath_SwitchMultilevel);
                    break;

                case Commands.MultiInstance_GetCount:
                    {
                        string commandType = request.GetOption(0).Replace(".", "");
                        switch (commandType)
                        {
                        case "SwitchBinary":
                            MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SwitchBinary);
                            break;
                        case "SwitchMultiLevel":
                            MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SwitchMultilevel);
                            break;
                        case "SensorBinary":
                            MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SensorBinary);
                            break;
                        case "SensorMultiLevel":
                            MultiInstance.GetCount(node, (byte)ZWaveLib.CommandClass.SensorMultilevel);
                            break;
                        }
                        returnValue = GetResponseValue(nodeNumber, EventPath_MultiInstance + "." + commandType + ".Count");
                    }
                    break;

                case Commands.MultiInstance_Get:
                    {
                        byte instance = (byte)int.Parse(request.GetOption(1));
                        string commandType = request.GetOption(0).Replace(".", "");
                        switch (commandType)
                        {
                        case "SwitchBinary":
                            MultiInstance.SwitchBinaryGet(node, instance);
                            break;
                        case "SwitchMultiLevel":
                            MultiInstance.SwitchMultiLevelGet(node, instance);
                            break;
                        case "SensorBinary":
                            MultiInstance.SensorBinaryGet(node, instance);
                            break;
                        case "SensorMultiLevel":
                            MultiInstance.SensorMultiLevelGet(node, instance);
                            break;
                        }
                        returnValue = GetResponseValue(nodeNumber, EventPath_MultiInstance + "." + commandType + "." + instance);
                    }
                    break;

                case Commands.MultiInstance_Set:
                    {
                        byte instance = (byte)int.Parse(request.GetOption(1));
                        int value = int.Parse(request.GetOption(2));
                        //
                        //raisepropchanged = true;
                        //parampath += "." + instance; // Status.Level.<instance>
                        //
                        switch (request.GetOption(0))
                        {
                        case "Switch.Binary":
                            MultiInstance.SwitchBinarySet(node, instance, value);
                        //raiseparam = (double.Parse(request.GetOption(2)) / 255).ToString();
                            break;
                        case "Switch.MultiLevel":
                            MultiInstance.SwitchMultiLevelSet(node, instance, value);
                        //raiseparam = (double.Parse(request.GetOption(2)) / 100).ToString(); // TODO: should it be 99 ?
                            break;
                        }
                    }
                    break;

                case Commands.SensorBinary_Get:
                    SensorBinary.Get(node);
                    break;

                case Commands.SensorMultiLevel_Get:
                    SensorMultilevel.Get(node);
                    break;

                case Commands.Meter_Get:
                // see ZWaveLib Sensor.cs for EnergyMeterScale options
                    int scaleType = 0;
                    int.TryParse(request.GetOption(0), out scaleType);
                    Meter.Get(node, (byte)(scaleType << 0x03));
                    break;

                case Commands.Meter_SupportedGet:
                    Meter.GetSupported(node);
                    break;

                case Commands.Meter_Reset:
                    Meter.Reset(node);
                    break;

                case Commands.NodeInfo_Get:
                    controller.GetNodeInformationFrame(nodeNumber);
                    returnValue = GetResponseValue(nodeNumber, EventPath_NodeInfo);
                    break;

                case Commands.Version_Report:
                    ZWaveLib.CommandClasses.Version.Report(node);
                    returnValue = GetResponseValue(nodeNumber, EventPath_VersionReport);
                    break;

                case Commands.Battery_Get:
                    Battery.Get(node);
                    returnValue = GetResponseValue(nodeNumber, EventPath_Battery);
                    break;

                case Commands.Association_Set:
                    Association.Set(node, (byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                    break;

                case Commands.Association_Get:
                    byte group = (byte)int.Parse(request.GetOption(0));
                    Association.Get(node, group);
                    returnValue = GetResponseValue(nodeNumber, EventPath_Associations + "." + group);
                    break;

                case Commands.Association_Remove:
                    Association.Remove(node, (byte)int.Parse(request.GetOption(0)), (byte)int.Parse(request.GetOption(1)));
                    break;

                case Commands.ManufacturerSpecific_Get:
                    ManufacturerSpecific.Get(node);
                    returnValue = GetResponseValue(nodeNumber, EventPath_ManufacturerSpecific);
                    break;

                case Commands.Config_ParameterSet:
                    Configuration.Set(node, (byte)int.Parse(request.GetOption(0)), int.Parse(request.GetOption(1)));
                    break;

                case Commands.Config_ParameterGet:
                    byte position = (byte)int.Parse(request.GetOption(0));
                    Configuration.Get(node, position);
                    returnValue = GetResponseValue(nodeNumber, EventPath_ConfigVariables + "." + position);
                    break;

                case Commands.WakeUp_Get:
                    WakeUp.Get(node);
                    returnValue = GetResponseValue(nodeNumber, EventPath_WakeUpInterval);
                    break;

                case Commands.WakeUp_Set:
                    WakeUp.Set(node, uint.Parse(request.GetOption(0)));
                    break;

                case Commands.WakeUp_SendToSleep:
                    WakeUp.SendToSleep(node);
                    break;

                case Commands.WakeUp_GetAlwaysAwake:
                    returnValue = new ResponseText(WakeUp.GetAlwaysAwake(node) ? "1" : "0");
                    break;

                case Commands.WakeUp_SetAlwaysAwake:
                    WakeUp.SetAlwaysAwake(node, uint.Parse(request.GetOption(0)) == 1 ? true : false);
                    break;

                case Commands.Version_Get:
                    returnValue = new ResponseText("ERROR");
                    CommandClass cclass;
                    Enum.TryParse<CommandClass>(request.GetOption(0), out cclass);
                    if (cclass != CommandClass.NotSet)
                    {
                        var nodeCclass = node.GetCommandClass(cclass);
                        if (nodeCclass != null && nodeCclass.Version != 0)
                        {
                            returnValue = new ResponseText(nodeCclass.Version.ToString());
                        }
                        else
                        {
                            ZWaveLib.CommandClasses.Version.Get(node, cclass);
                            returnValue = GetResponseValue(nodeNumber, "ZWaveNode.Version." + cclass);
                        }
                    }
                    break;

                case Commands.Version_GetAll:
                    controller.GetNodeCcsVersion(node);
                    break;

                case Commands.Control_On:
                    raiseEvent = true;
                    double lastLevel = GetNormalizedValue((double)GetNodeLastLevel(node));
                    eventValue = lastLevel > 0 ? lastLevel.ToString(CultureInfo.InvariantCulture) : "1";
                    if (node.SupportCommandClass(CommandClass.SwitchMultilevel))
                        SwitchMultilevel.Set(node, 0xFF);
                    else if (node.SupportCommandClass(CommandClass.SwitchBinary))
                        SwitchBinary.Set(node, 0xFF);
                    else
                        Basic.Set(node, 0xFF);
                    SetNodeLevel(node, 0xFF);
                    break;

                case Commands.Control_Off:
                    raiseEvent = true;
                    eventValue = "0";
                    if (node.SupportCommandClass(CommandClass.SwitchMultilevel))
                        SwitchMultilevel.Set(node, 0x00);
                    else if (node.SupportCommandClass(CommandClass.SwitchBinary))
                        SwitchBinary.Set(node, 0x00);
                    else
                        Basic.Set(node, 0x00);
                    SetNodeLevel(node, 0x00);
                    break;

                case Commands.Control_Level:
                    {
                        raiseEvent = true;
                        var level = int.Parse(request.GetOption(0));
                        eventValue = Math.Round(level / 100D, 2).ToString(CultureInfo.InvariantCulture);
                        // the max value should be obtained from node parameters specifications,
                        // here we assume that the commonly used interval is [0-99] for most multilevel switches
                        if (level >= 100)
                            level = 99;
                        if (node.SupportCommandClass(CommandClass.SwitchMultilevel))
                            SwitchMultilevel.Set(node, (byte)level);
                        else
                            Basic.Set(node, (byte)level);
                        SetNodeLevel(node, (byte)level);
                    }
                    break;

                case Commands.Control_Toggle:
                    raiseEvent = true;
                    if (GetNodeLevel(node) == 0)
                    {
                        double lastOnLevel = GetNormalizedValue((double)GetNodeLastLevel(node));
                        eventValue = lastOnLevel > 0 ? lastOnLevel.ToString(CultureInfo.InvariantCulture) : "1";
                        if (node.SupportCommandClass(CommandClass.SwitchMultilevel))
                            SwitchMultilevel.Set(node, 0xFF);
                        else if (node.SupportCommandClass(CommandClass.SwitchBinary))
                            SwitchBinary.Set(node, 0xFF);
                        else
                            Basic.Set(node, 0xFF);
                        SetNodeLevel(node, 0xFF);
                    }
                    else
                    {
                        eventValue = "0";
                        if (node.SupportCommandClass(CommandClass.SwitchMultilevel))
                            SwitchMultilevel.Set(node, 0x00);
                        else if (node.SupportCommandClass(CommandClass.SwitchBinary))
                            SwitchBinary.Set(node, 0x00);
                        else
                            Basic.Set(node, 0x00);
                        SetNodeLevel(node, 0x00);
                    }
                    break;

                case Commands.Thermostat_ModeGet:
                    ThermostatMode.Get(node);
                    break;

                case Commands.Thermostat_ModeSet:
                    {
                        ThermostatMode.Value mode = (ThermostatMode.Value)Enum.Parse(typeof(ThermostatMode.Value), request.GetOption(0));
                        //
                        raiseEvent = true;
                        eventParameter = "Thermostat.Mode";
                        eventValue = request.GetOption(0);
                        //
                        ThermostatMode.Set(node, mode);
                    }
                    break;

                case Commands.Thermostat_SetPointGet:
                    {
                        ThermostatSetPoint.Value mode = (ThermostatSetPoint.Value)Enum.Parse(typeof(ThermostatSetPoint.Value), request.GetOption(0));
                        ThermostatSetPoint.Get(node, mode);
                    }
                    break;

                case Commands.Thermostat_SetPointSet:
                    {
                        ThermostatSetPoint.Value mode = (ThermostatSetPoint.Value)Enum.Parse(typeof(ThermostatSetPoint.Value), request.GetOption(0));
                        double temperature = double.Parse(request.GetOption(1).Replace(',', '.'), CultureInfo.InvariantCulture);
                        //
                        raiseEvent = true;
                        eventParameter = "Thermostat.SetPoint." + request.GetOption(0);
                        eventValue = temperature.ToString(CultureInfo.InvariantCulture);
                        //
                        ThermostatSetPoint.Set(node, mode, temperature);
                    }
                    break;

                case Commands.Thermostat_FanModeGet:
                    ThermostatFanMode.Get(node);
                    break;

                case Commands.Thermostat_FanModeSet:
                    {
                        ThermostatFanMode.Value mode = (ThermostatFanMode.Value)Enum.Parse(typeof(ThermostatFanMode.Value), request.GetOption(0));
                        //
                        raiseEvent = true;
                        eventParameter = "Thermostat.FanMode";
                        eventValue = request.GetOption(0);
                        //
                        ThermostatFanMode.Set(node, mode);
                    }
                    break;

                case Commands.Thermostat_FanStateGet:
                    ThermostatFanState.Get(node);
                    break;

                case Commands.Thermostat_OperatingStateGet:
                    ThermostatOperatingState.GetOperatingState(node);
                    break;

                case Commands.UserCode_Set:
                    byte userId = byte.Parse(request.GetOption(0));
                    byte userIdStatus = byte.Parse(request.GetOption(1));
                    byte[] tagCode = ZWaveLib.Utility.HexStringToByteArray(request.GetOption(2));
                    UserCode.Set(node, new ZWaveLib.Values.UserCodeValue(userId, userIdStatus, tagCode));
                    break;

                case Commands.DoorLock_Get:
                    DoorLock.Get(node);
                    returnValue = GetResponseValue(nodeNumber, ModuleEvents.Status_DoorLock);
                    break;

                case Commands.DoorLock_Set:
                    {
                        DoorLock.Value mode = (DoorLock.Value)Enum.Parse(typeof(DoorLock.Value), request.GetOption(0));
                        DoorLock.Set(node, mode);
                    }
                    break;

                case Commands.Db_Update:
                    {
                        var p1db = new Pepper1Db();
                        p1db.Update(request.GetOption(0));
                        break;
                    }
                case Commands.Db_GetDevice:
                    {
                        var p1db = new Pepper1Db();
                        returnValue = new ResponseText(p1db.GetDeviceInfo(request.GetOption(0), request.GetOption(1)));
                        break;
                    }
                }
            }

            if (raiseEvent)
            {
                //ZWaveNode node = _controller.GetDevice ((byte)int.Parse (nodeid));
                OnInterfacePropertyChanged(this.GetDomain(), nodeId, "ZWave Node", eventParameter, eventValue);
            }
            //
            return returnValue;
        }
Пример #3
0
 private ResponseText GetResponseValue(byte nodeNumber, string eventPath)
 {
     ResponseText returnValue = new ResponseText("ERR_TIMEOUT");
     InterfacePropertyChangedEventHandler eventHandler = new InterfacePropertyChangedEventHandler((sender, property) =>
     {
         if (property.EventData.Source == nodeNumber.ToString() && property.EventData.Property == eventPath)
         {
             returnValue = new ResponseText(property.EventData.Value.ToString());
         }
     });
     InterfacePropertyChanged += eventHandler;
     Thread t = new Thread(() =>
     {
         int timeout = 0;
         int delay = 100;
         while (returnValue.ResponseValue == "ERR_TIMEOUT" && timeout < ZWaveMessage.SendMessageTimeoutMs / delay)
         {
             Thread.Sleep(delay);
             timeout++;
         }
     });
     t.Start();
     t.Join(ZWaveMessage.SendMessageTimeoutMs);
     InterfacePropertyChanged -= eventHandler;
     return returnValue;
 }
Пример #4
0
        public object InterfaceControl(MigInterfaceCommand request)
        {
            ResponseText response = new ResponseText("OK");

            string nodeId = request.Address;
            string option = request.GetOption(0);

            Commands command;
            Enum.TryParse<Commands>(request.Command.Replace(".", "_"), out command);

            // Parse house/unit
            var houseCode = XTenLib.Utility.HouseCodeFromString(nodeId);
            var unitCode = XTenLib.Utility.UnitCodeFromString(nodeId);

            switch (command)
            {
            case Commands.Parameter_Status:
                x10lib.StatusRequest(houseCode, unitCode);
                break;
            case Commands.Control_On:
                x10lib.UnitOn(houseCode, unitCode);
                break;
            case Commands.Control_Off:
                x10lib.UnitOff(houseCode, unitCode);
                break;
            case Commands.Control_Bright:
                x10lib.Bright(houseCode, unitCode, int.Parse(option));
                break;
            case Commands.Control_Dim:
                x10lib.Dim(houseCode, unitCode, int.Parse(option));
                break;
            case Commands.Control_Level_Adjust:
                int adjvalue = int.Parse(option);
                //x10lib.Modules[nodeId].Level = ((double)adjvalue/100D);
                OnInterfacePropertyChanged(this.GetDomain(), nodeId, "X10 Module", ModuleEvents.Status_Level, x10lib.Modules[nodeId].Level);
                throw(new NotImplementedException("X10 CONTROL_LEVEL_ADJUST Not Implemented"));
                break;
            case Commands.Control_Level:
                int dimvalue = int.Parse(option) - (int)(x10lib.Modules[nodeId].Level * 100.0);
                if (dimvalue > 0)
                {
                    x10lib.Bright(houseCode, unitCode, dimvalue);
                }
                else if (dimvalue < 0)
                {
                    x10lib.Dim(houseCode, unitCode, -dimvalue);
                }
                break;
            case Commands.Control_Toggle:
                string huc = XTenLib.Utility.HouseUnitCodeFromEnum(houseCode, unitCode);
                if (x10lib.Modules[huc].Level == 0)
                {
                    x10lib.UnitOn(houseCode, unitCode);
                }
                else
                {
                    x10lib.UnitOff(houseCode, unitCode);
                }
                break;
            case Commands.Control_AllLightsOn:
                x10lib.AllLightsOn(houseCode);
                break;
            case Commands.Control_AllLightsOff:
                x10lib.AllUnitsOff(houseCode);
                break;
            }

            return response;
        }
Пример #5
0
        public object InterfaceControl(MigInterfaceCommand request)
        {
            object returnValue = null;
            bool raiseEvent = false;
            string eventParameter = "Status.Unhandled";
            string eventValue = "";
            //
            var device = GetUpnpDevice(request.Address);

            Commands command;
            Enum.TryParse<Commands>(request.Command.Replace(".", "_"), out command);

            // TODO: ??? Commands: SwitchPower, Dimming

            switch (command)
            {
            case Commands.Control_On:
            case Commands.Control_Off:
                {
                    bool commandValue = (command == Commands.Control_On ? true : false);
                    var newValue = new UPnPArgument("newTargetValue", commandValue);
                    var args = new UPnPArgument[] { 
                        newValue
                    };
                    InvokeUpnpDeviceService(device, "SwitchPower", "SetTarget", args);
                    //
                    raiseEvent = true;
                    eventParameter = "Status.Level";
                    eventValue = (commandValue ? "1" : "0");
                }
                break;
            case Commands.Control_Level:
                {
                    var newvalue = new UPnPArgument("NewLoadLevelTarget", (byte)uint.Parse(request.GetOption(0)));
                    var args = new UPnPArgument[] { 
                        newvalue
                    };
                    InvokeUpnpDeviceService(device, "Dimming", "SetLoadLevelTarget", args);
                    //
                    raiseEvent = true;
                    eventParameter = "Status.Level";
                    eventValue = (double.Parse(request.GetOption(0)) / 100d).ToString(System.Globalization.CultureInfo.InvariantCulture);
                }
                break;
            case Commands.Control_Toggle:
                // TODO: not implemented yet
                break;
            case Commands.AvMedia_GetItem:
                {
                    string deviceId = request.Address;
                    string id = request.GetOption(0);
                    //
                    var objectId = new UPnPArgument("ObjectID", id);
                    var flags = new UPnPArgument("BrowseFlag", "BrowseMetadata");
                    var filter = new UPnPArgument("Filter", "upnp:album,upnp:artist,upnp:genre,upnp:title,[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]");
                    var startIndex = new UPnPArgument("StartingIndex", (uint)0);
                    var requestedCount = new UPnPArgument("RequestedCount", (uint)1);
                    var sortCriteria = new UPnPArgument("SortCriteria", "");
                    //
                    var result = new UPnPArgument("Result", "");
                    var returnedNumber = new UPnPArgument("NumberReturned", "");
                    var totalMatches = new UPnPArgument("TotalMatches", "");
                    var updateId = new UPnPArgument("UpdateID", "");
                    //
                    InvokeUpnpDeviceService(device, "ContentDirectory", "Browse", new UPnPArgument[] { 
                        objectId,
                        flags,
                        filter,
                        startIndex,
                        requestedCount,
                        sortCriteria,
                        result,
                        returnedNumber,
                        totalMatches,
                        updateId
                    });
                    //
                    try
                    {
                        string ss = result.DataValue.ToString();
                        var item = XDocument.Parse(ss, LoadOptions.SetBaseUri).Descendants().Where(ii => ii.Name.LocalName == "item").First();
                        returnValue = MIG.Utility.Serialization.JsonSerialize(item, true);
                    }
                    catch
                    {
                        // TODO: MigService.Log.Error(e);
                    }
                }
                break;
            case Commands.AvMedia_GetUri:
                {
                    string deviceId = request.Address;
                    string id = request.GetOption(0);
                    //
                    var objectId = new UPnPArgument("ObjectID", id);
                    var flags = new UPnPArgument("BrowseFlag", "BrowseMetadata");
                    var filter = new UPnPArgument("Filter", "upnp:album,upnp:artist,upnp:genre,upnp:title,[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]");
                    var startIndex = new UPnPArgument("StartingIndex", (uint)0);
                    var requestedCount = new UPnPArgument("RequestedCount", (uint)1);
                    var sortCriteria = new UPnPArgument("SortCriteria", "");
                    //
                    var result = new UPnPArgument("Result", "");
                    var returnedNumber = new UPnPArgument("NumberReturned", "");
                    var totalMatches = new UPnPArgument("TotalMatches", "");
                    var updateId = new UPnPArgument("UpdateID", "");
                    //
                    InvokeUpnpDeviceService(device, "ContentDirectory", "Browse", new UPnPArgument[] { 
                        objectId,
                        flags,
                        filter,
                        startIndex,
                        requestedCount,
                        sortCriteria,
                        result,
                        returnedNumber,
                        totalMatches,
                        updateId
                    });
                    //
                    try
                    {
                        string ss = result.DataValue.ToString();
                        var item = XDocument.Parse(ss, LoadOptions.SetBaseUri).Descendants().Where(ii => ii.Name.LocalName == "item").First();
                        //
                        foreach (var i in item.Elements())
                        {
                            var protocolUri = i.Attribute("protocolInfo");
                            if (protocolUri != null)
                            {
                                returnValue = new ResponseText(i.Value);
                                break;
                            }
                        }
                    }
                    catch
                    {
                        // TODO: MigService.Log.Error(e);
                    }
                }
                break;
            case Commands.AvMedia_Browse:
                {
                    string deviceId = request.Address;
                    string id = request.GetOption(0);
                    //
                    var objectId = new UPnPArgument("ObjectID", id);
                    var flags = new UPnPArgument("BrowseFlag", "BrowseDirectChildren");
                    var filter = new UPnPArgument("Filter", "upnp:album,upnp:artist,upnp:genre,upnp:title,[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]");
                    var startIndex = new UPnPArgument("StartingIndex", (uint)0);
                    var requestedCount = new UPnPArgument("RequestedCount", (uint)0);
                    var sortCriteria = new UPnPArgument("SortCriteria", "");
                    //
                    var result = new UPnPArgument("Result", "");
                    var returnedNumber = new UPnPArgument("NumberReturned", "");
                    var totalMatches = new UPnPArgument("TotalMatches", "");
                    var updateId = new UPnPArgument("UpdateID", "");
                    //
                    InvokeUpnpDeviceService(device, "ContentDirectory", "Browse", new UPnPArgument[] { 
                        objectId,
                        flags,
                        filter,
                        startIndex,
                        requestedCount,
                        sortCriteria,
                        result,
                        returnedNumber,
                        totalMatches,
                        updateId
                    });
                    //
                    try
                    {
                        string ss = result.DataValue.ToString();
                        var root = XDocument.Parse(ss, LoadOptions.SetBaseUri).Elements();
                        //
                        string jsonres = "[";
                        foreach (var i in root.Elements())
                        {
                            string itemId = i.Attribute("id").Value;
                            string itemTitle = i.Descendants().Where(n => n.Name.LocalName == "title").First().Value;
                            string itemClass = i.Descendants().Where(n => n.Name.LocalName == "class").First().Value;
                            jsonres += "{ \"Id\" : \"" + itemId + "\", \"Title\" : \"" + itemTitle.Replace("\"", "\\\"") + "\", \"Class\" : \"" + itemClass + "\" },\n";
                        }
                        jsonres = jsonres.TrimEnd(',', '\n') + "]";
                        //
                        returnValue = jsonres;
                    }
                    catch
                    {
                        // TODO: MigService.Log.Error(e);
                    }
                }
                break;
            case Commands.AvMedia_GetTransportInfo:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var transportState = new UPnPArgument("CurrentTransportState", "");
                    var transportStatus = new UPnPArgument("CurrentTransportStatus", "");
                    var currentSpeed = new UPnPArgument("CurrentSpeed", "");
                    var args = new UPnPArgument[] { 
                        instanceId,
                        transportState,
                        transportStatus,
                        currentSpeed
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "GetTransportInfo", args);
                    //
                    string jsonres = "{ ";
                    jsonres += "\"CurrentTransportState\" : \"" + transportState.DataValue + "\", ";
                    jsonres += "\"CurrentTransportStatus\" : \"" + transportStatus.DataValue + "\", ";
                    jsonres += "\"CurrentSpeed\" : \"" + currentSpeed.DataValue + "\"";
                    jsonres += " }";
                    //
                    returnValue = jsonres;
                }
                break;
            case Commands.AvMedia_GetMediaInfo:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var nrTracks = new UPnPArgument("NrTracks", (uint)0);
                    var mediaDuration = new UPnPArgument("MediaDuration", "");
                    var currentUri = new UPnPArgument("CurrentURI", "");
                    var currentUriMetadata = new UPnPArgument("CurrentURIMetaData", "");
                    var nextUri = new UPnPArgument("NextURI", "");
                    var nextUriMetadata = new UPnPArgument("NextURIMetaData", "");
                    var playMedium = new UPnPArgument("PlayMedium", "");
                    var recordMedium = new UPnPArgument("RecordMedium", "");
                    var writeStatus = new UPnPArgument("WriteStatus", "");
                    var args = new UPnPArgument[] { 
                        instanceId,
                        nrTracks,
                        mediaDuration,
                        currentUri,
                        currentUriMetadata,
                        nextUri,
                        nextUriMetadata,
                        playMedium,
                        recordMedium,
                        writeStatus
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "GetMediaInfo", args);
                    //
                    string jsonres = "{ ";
                    jsonres += "\"NrTracks\" : \"" + nrTracks.DataValue + "\", ";
                    jsonres += "\"MediaDuration\" : \"" + mediaDuration.DataValue + "\", ";
                    jsonres += "\"CurrentURI\" : \"" + currentUri.DataValue + "\", ";
                    jsonres += "\"CurrentURIMetaData\" : " + MIG.Utility.Serialization.JsonSerialize(GetJsonFromXmlItem(currentUriMetadata.DataValue.ToString())) + ", ";
                    jsonres += "\"NextURI\" : \"" + nextUri.DataValue + "\", ";
                    jsonres += "\"NextURIMetaData\" : " + MIG.Utility.Serialization.JsonSerialize(GetJsonFromXmlItem(nextUriMetadata.DataValue.ToString())) + ", ";
                    jsonres += "\"PlayMedium\" : \"" + playMedium.DataValue + "\", ";
                    jsonres += "\"RecordMedium\" : \"" + recordMedium.DataValue + "\", ";
                    jsonres += "\"WriteStatus\" : \"" + writeStatus.DataValue + "\"";
                    jsonres += " }";
                    //
                    returnValue = jsonres;
                }
                break;
            case Commands.AvMedia_GetPositionInfo:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var currentTrack = new UPnPArgument("Track", (uint)0);
                    var trackDuration = new UPnPArgument("TrackDuration", "");
                    var trackMetadata = new UPnPArgument("TrackMetaData", "");
                    var trackUri = new UPnPArgument("TrackURI", "");
                    var relativeTime = new UPnPArgument("RelTime", "");
                    var absoluteTime = new UPnPArgument("AbsTime", "");
                    var relativeCount = new UPnPArgument("RelCount", (uint)0);
                    var absoluteCount = new UPnPArgument("AbsCount", (uint)0);
                    var args = new UPnPArgument[] { 
                        instanceId,
                        currentTrack,
                        trackDuration,
                        trackMetadata,
                        trackUri,
                        relativeTime,
                        absoluteTime,
                        relativeCount,
                        absoluteCount
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "GetPositionInfo", args);
                    //
                    string jsonres = "{";
                    jsonres += "\"Track\" : \"" + currentTrack.DataValue + "\",";
                    jsonres += "\"TrackDuration\" : \"" + trackDuration.DataValue + "\",";
                    jsonres += "\"TrackMetaData\" : " + MIG.Utility.Serialization.JsonSerialize(GetJsonFromXmlItem(trackMetadata.DataValue.ToString())) + ",";
                    jsonres += "\"TrackURI\" : \"" + trackUri.DataValue + "\",";
                    jsonres += "\"RelTime\" : \"" + relativeTime.DataValue + "\",";
                    jsonres += "\"AbsTime\" : \"" + absoluteTime.DataValue + "\",";
                    jsonres += "\"RelCount\" : \"" + relativeCount.DataValue + "\",";
                    jsonres += "\"AbsCount\" : \"" + absoluteCount.DataValue + "\"";
                    jsonres += "}";
                    //
                    returnValue = jsonres;
                }
                break;
            case Commands.AvMedia_SetUri:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var currentUri = new UPnPArgument("CurrentURI", request.GetOption(0));
                    var uriMetadata = new UPnPArgument("CurrentURIMetaData", "");
                    var args = new UPnPArgument[] { 
                        instanceId,
                        currentUri,
                        uriMetadata
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "SetAVTransportURI", args);
                }
                break;
            case Commands.AvMedia_Play:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var speed = new UPnPArgument("Speed", "1");
                    var args = new UPnPArgument[] { 
                        instanceId,
                        speed
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "Play", args);
                }
                break;
            case Commands.AvMedia_Pause:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var args = new UPnPArgument[] { 
                        instanceId
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "Pause", args);
                }
                break;
            case Commands.AvMedia_Seek:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var unit = new UPnPArgument("Unit", "REL_TIME");
                    var target = new UPnPArgument("Target", request.GetOption(0));
                    var args = new UPnPArgument[] { 
                        instanceId,
                        unit,
                        target
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "Seek", args);
                }
                break;
            case Commands.AvMedia_Stop:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var args = new UPnPArgument[] { 
                        instanceId
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "Stop", args);
                }
                break;
            case Commands.AvMedia_Prev:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var args = new UPnPArgument[] { 
                        instanceId
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "Previous", args);
                }
                break;
            case Commands.AvMedia_Next:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var args = new UPnPArgument[] { 
                        instanceId
                    };
                    InvokeUpnpDeviceService(device, "AVTransport", "Next", args);
                }
                break;
            case Commands.AvMedia_GetMute:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var channel = new UPnPArgument("Channel", "Master");
                    var currentMute = new UPnPArgument("CurrentMute", "");
                    var args = new UPnPArgument[] { 
                        instanceId,
                        channel,
                        currentMute
                    };
                    InvokeUpnpDeviceService(device, "RenderingControl", "GetMute", args);
                    returnValue = new ResponseText(currentMute.DataValue.ToString());
                }
                break;
            case Commands.AvMedia_SetMute:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var channel = new UPnPArgument("Channel", "Master");
                    var mute = new UPnPArgument("DesiredMute", request.GetOption(0) == "1" ? true : false);
                    var args = new UPnPArgument[] { 
                        instanceId,
                        channel,
                        mute
                    };
                    InvokeUpnpDeviceService(device, "RenderingControl", "SetMute", args);
                }
                break;
            case Commands.AvMedia_GetVolume:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var channel = new UPnPArgument("Channel", "Master");
                    var currentVolume = new UPnPArgument("CurrentVolume", "");
                    var args = new UPnPArgument[] { 
                        instanceId,
                        channel,
                        currentVolume
                    };
                    InvokeUpnpDeviceService(device, "RenderingControl", "GetVolume", args);
                    returnValue = new ResponseText(currentVolume.DataValue.ToString());
                }
                break;
            case Commands.AvMedia_SetVolume:
                {
                    var instanceId = new UPnPArgument("InstanceID", (uint)0);
                    var channel = new UPnPArgument("Channel", "Master");
                    var volume = new UPnPArgument("DesiredVolume", UInt16.Parse(request.GetOption(0)));
                    var args = new UPnPArgument[] { 
                        instanceId,
                        channel,
                        volume
                    };
                    InvokeUpnpDeviceService(device, "RenderingControl", "SetVolume", args);
                }
                break;
            }

            // raise event
            if (raiseEvent)
            {
                OnInterfacePropertyChanged(this.GetDomain(), device.UniqueDeviceName, "UPnP " + (device != null ? device.StandardDeviceType : "device"), eventParameter, eventValue);
            }

            return returnValue;
        }
        public object InterfaceControl(MigInterfaceCommand request)
        {
            var response = new ResponseText("OK"); //default success value

            Commands command;
            Enum.TryParse<Commands>(request.Command.Replace(".", "_"), out command);

            var module = modules.Find (m => m.Address.Equals (request.Address));

            if (module != null) {
                switch (command) {
                case Commands.Control_On:
                // TODO: ...
                    OnInterfacePropertyChanged (this.GetDomain (), request.Address, "Test Interface", "Status.Level", 1);
                    break;
                case Commands.Control_Off:
                    OnInterfacePropertyChanged (this.GetDomain (), request.Address, "Test Interface", "Status.Level", 0);
                // TODO: ...
                    break;
                case Commands.Temperature_Get:
                    OnInterfacePropertyChanged (this.GetDomain (), request.Address, "Test Interface", "Sensor.Temperature", 19.75);
                // TODO: ...
                    break;
                case Commands.Greet_Hello:
                // TODO: ...
                    OnInterfacePropertyChanged (this.GetDomain (), request.Address, "Test Interface", "Sensor.Message", String.Format ("Hello {0}", request.GetOption (0)));
                    response = new ResponseText ("Hello World!");
                    break;
                }
            }
            else 
            {
                response = new ResponseText ("ERROR: invalid module address");
            }

            return response;
        }