Example #1
0
        public void Setup(Rainmeter.API api)
        {
            // Init members
            SendAsync             = (api.ReadInt("SendAsync", 0) > 0);
            TryToReconnect        = false;
            KeepConnectionAlive   = (api.ReadInt("KeepAlive", 1) > 0);
            PingServer            = (api.ReadInt("PingServer", 0) > 0);
            MaxReconnectAttempts  = api.ReadInt("MaxReconnectAttempts", 0);
            CurrentAttempt        = 0;
            LastConnectionAttempt = DateTime.Now;
            LastPing = LastConnectionAttempt;

            // Setup WebSocket
            String Address = api.ReadString("Address", "");

            if (!Address.IsNullOrEmpty())
            {
                ws            = new WebSocket(Address);
                ws.NoDelay    = true;
                ws.OnOpen    += OnOpen;
                ws.OnMessage += OnMessage;
                ws.OnError   += OnError;
                ws.OnClose   += OnClose;
                ws.ConnectAsync();
            }

            // Get Commands
            Skin         = api.GetSkin();
            cmdOnOpen    = api.ReadString("OnOpen", "");
            cmdOnMessage = api.ReadString("OnMessage", "");
            cmdOnError   = api.ReadString("OnError", "");
            cmdOnClose   = api.ReadString("OnClose", "");

            // Get Parsable Commands

            // Ex: ParseCommands="AA:|BB:|CMD:"
            // OnAA:=[Some Bang]
            // OnBB:=[Some Bang]
            // OnCMD:=[Some Bang]

            Commands = new List <Command>();
            String cmds = api.ReadString("ParseCommands", "");

            if (!cmds.IsNullOrEmpty())
            {
                var tags = cmds.Split('|');
                foreach (var tag in tags)
                {
                    String c = api.ReadString("On" + tag, "");
                    Commands.Add(new Command {
                        Tag = tag, cmdOnTag = c
                    });
                }
            }
        }
        internal override void Reload(Rainmeter.API api, ref double maxValue)
        {
            base.Reload(api, ref maxValue);

            Name = api.GetMeasureName();
            Skin = api.GetSkin();

            ValueA = api.ReadInt("ValueA", 0);
            ValueB = api.ReadInt("ValueB", 0);
            ValueC = api.ReadInt("ValueC", 0);
        }
        internal void Reload(Rainmeter.API api, ref double maxValue)
        {
            try
            {
                number = api.ReadInt("Value", 0);
            }
            catch (Exception e) {}
            try
            {
                Arc.Thickness = Convert.ToSingle(api.ReadDouble("Width", Arc.Thickness));
            }
            catch (Exception e) {}
            try
            {
                Digit.Size = Convert.ToInt32(api.ReadInt("Size", Digit.Size) * ScaleFactor);
            }
            catch (Exception e) {}
            try
            {
                outFilePath = api.ReadString("Out", string.Format("{0}.png", number.ToString()));
            }
            catch (Exception e) {}
            try
            {
                var colorVals = api.ReadString("Color", string.Format("{0},{1},{2},{3}", Arc.Red, Arc.Green, Arc.Blue, Arc.Opacity)).Split(',').Select(n => Int32.Parse(n)).ToArray();
                switch (colorVals.Length)
                {
                case 4:
                {
                    Arc.Opacity = colorVals[3];
                    goto case 3;
                }

                case 3:
                {
                    Arc.Red   = colorVals[0];
                    Arc.Green = colorVals[1];
                    Arc.Blue  = colorVals[2];
                    break;
                }
                }
            }
            catch (Exception e) {}
            try
            {
                Digit.GlobalAngle = Convert.ToSingle(api.ReadDouble("Angle", Digit.GlobalAngle));
            }
            catch (Exception e) { }
        }
        /*
         * Example activity element in array, notice each entry has profile info as well as "sport" on case RUN and cycling should be sepearte
         *
         * {
         *  id_str: '1234567890',
         *  id: 1234567890,
         *  profileId: 1234567890,
         *  profile: {
         *    id: 1234567890,
         *    publicId: '1234567890-1234567890-1234567890',
         *    firstName: 'Example',
         *    lastName: 'Name',
         *    male: true,
         *    imageSrc: 'https://static-cdn.zwift.com/prod/profile/12345678901234567890',
         *    imageSrcLarge: 'https://static-cdn.zwift.com/prod/profile/12345678901234567890',
         *    playerType: 'NORMAL',
         *    countryAlpha3: 'deu',
         *    countryCode: 276,
         *    useMetric: true,
         *    riding: false,
         *    privacy: [Object],
         *    socialFacts: null,
         *    worldId: null,
         *    enrolledZwiftAcademy: false,
         *    playerTypeId: 1,
         *    playerSubTypeId: null,
         *    currentActivityId: null
         *  },
         *  worldId: 1,
         *  name: 'Zwift Run - Watopia',
         *  description: null,
         *  privateActivity: true,
         *  sport: 'RUNNING',
         *  startDate: '2021-01-01T00:00:00.000+0000',
         *  endDate: '2021-01-01T01:00:00.00+0000',
         *  lastSaveDate: '2021-01-01T01:00:00.00+0000',
         *  autoClosed: false,
         *  duration: '1:00',
         *  distanceInMeters: 1234.56,
         *  fitFileBucket: 's3-fit-prd-uswest2-zwift',
         *  fitFileKey: 'prod/123456/123456-123456123456',
         *  totalElevation: 0,
         *  avgWatts: 0,
         *  rideOnGiven: false,
         *  activityRideOnCount: 42,
         *  activityCommentCount: 0,
         *  snapshotList: null,
         *  calories: 4242.00,
         *  primaryImageUrl: 'https://s3-fit-prd-uswest2-zwift.s3.amazonaws.com/prod/img/123456-123456123456123456',
         *  movingTimeInMs: 123456,
         *  privacy: 'PRIVATE',
         *  topNotableMoment: {
         *    notableMomentTypeId: 1,
         *    activityId: 123456123456123456123456,
         *    incidentTime: 123456,
         *    priority: 8,
         *    aux1: '3',
         *    aux2: '300'
         *  },
         *  avgSpeedInMetersPerSecond: 2.42,
         *  feedImageThumbnailUrl: 'https://s3-fit-prd-uswest2-zwift.s3.amazonaws.com/prod/img/1234561-23456123456123456',
         *  eventSubgroupId: null,
         *  eventId: null,
         *  clubActivity: false
         * },
         *
         */

        internal override void Reload(Rainmeter.API api, ref double maxValue)
        {
            base.Reload(api, ref maxValue);
            Name = api.GetMeasureName();
            Skin = api.GetSkin();

            user      = api.ReadString("zwiftUser", "");
            password  = api.ReadString("zwiftPass", "");
            pastMonth = api.ReadInt("pastMonth", 0);

            var feedArr = fetchZwiftFeed();

            try
            {
                foreach (var activity in feedArr)
                {
                    CultureInfo provider = CultureInfo.InvariantCulture;
                    DateTime    start    = DateTime.Parse(activity.startDate);
                    var         month    = new DateTime(start.Year, start.Month, 1);
                    if (!distanceDict.ContainsKey(month))
                    {
                        distanceDict[month] = 0;
                    }
                    distanceDict[month] += Convert.ToDouble(activity.distanceInMeters);
                }
            }
            catch (Exception e)
            {
                api.Log(API.LogType.Error, "ZWIFT_RM_API.dll: Reload error:" + e.Message);
            };
        }
Example #5
0
        public static void Reload(IntPtr data, IntPtr rm, ref double maxValue)
        {
            Measure measure = (Measure)data;

            Rainmeter.API api = (Rainmeter.API)rm;

            measure.updateRate = api.ReadInt("Timer", 1);
            //We dont have to replace measures here as they will be replaced during Execute so we can pass false.
            //Note though that doing that measures will always then have their current info in update but variables will not. See the commented out code below to have both always act like DynamicVariables=1
            measure.myCommand = api.ReadString("OnTimer", "", false);
        }
Example #6
0
        internal void Reload(Rainmeter.API api, ref double maxValue)
        {
            int rank = api.ReadInt("Rank", 1);

            if (rank > 0)
            {
                Rank = rank;
            }
            else
            {
                Rank = 1;
            }
        }
        public static void Reload(IntPtr data, IntPtr rm, ref double maxValue)
        {
            Measure measure = (Measure)data;

            Rainmeter.API api = (Rainmeter.API)rm;

            //Get starting value if one is defined
            int startValue = api.ReadInt("StartingValue", -1);

            //If string from option was null read from file
            if (startValue == -1)
            {
                char[] outString = new char[MAXSIZE];

                //Read from Rainmeter.data file, if no instace exists start at 0
                GetPrivateProfileString(PluginName, KeyName, "0", outString, MAXSIZE, API.GetSettingsFile());

                try
                {
                    //Need try catch just in case someone tampers with the file and the value stored is not a number
                    string intString = new string(outString);
                    measure.myCounter = Convert.ToInt32(intString);
                }
                catch
                {
                    api.Log(API.LogType.Error, "Error converting value stored in Rainmeter.data to integer");
                }
            }
            else
            {
                measure.myCounter = startValue;
            }

            //If store data is 1 then save data when measure is unloaded
            measure.storeData = api.ReadInt("StoreData", 0) == 1 ? true : false;
        }
Example #8
0
        internal void Reload(Rainmeter.API rm, ref double maxValue)
        {
            SkinHandle     = rm.GetSkin();
            FinishAction   = rm.ReadString("FinishAction", "");
            ConnectionType = rm.ReadString("ConnectionType", "INTERNET").ToUpperInvariant();
            if (ConnectionType != "NETWORK" && ConnectionType != "INTERNET")
            {
                API.Log(API.LogType.Error, "CheckNet.dll: ConnectionType=" + ConnectionType + " not valid");
            }

            UpdateRate = rm.ReadInt("UpdateRate", 20);
            if (UpdateRate <= 0)
            {
                UpdateRate = 20;
            }
        }
Example #9
0
        public static void Initialize(ref IntPtr data, IntPtr rm)
        {
            data = GCHandle.ToIntPtr(GCHandle.Alloc(new Measure()));
            Rainmeter.API api = (Rainmeter.API)rm;

            Measure measure = (Measure)data;

            measure.synth  = new SpeechSynthesizer();
            measure.prompt = new Prompt("");

            measure.voices     = measure.synth.GetInstalledVoices();
            measure.voiceCount = measure.voices.Count;

            measure.synth.SetOutputToDefaultAudioDevice();

            int debug = api.ReadInt("Debug", 0);

            if (debug == 1)
            {
                api.Log(API.LogType.Notice, "------------------------------");
                api.Log(API.LogType.Notice, "* Speech.dll - GetInstalledVoices() API");

                int index = 1;
                foreach (InstalledVoice voice in measure.voices)
                {
                    VoiceInfo info = voice.VoiceInfo;

                    api.LogF(API.LogType.Notice, "Index: {0}", index);
                    api.LogF(API.LogType.Notice, "  Name          : {0}", info.Name);
                    api.LogF(API.LogType.Notice, "  Gender        : {0}", info.Gender);
                    api.LogF(API.LogType.Notice, "  Culture       : {0}", info.Culture);
                    api.LogF(API.LogType.Notice, "  Age           : {0}", info.Age);
                    api.LogF(API.LogType.Notice, "  Description   : {0}", info.Description);
                    api.LogF(API.LogType.Notice, "  ID            : {0}", info.Id);
                    api.LogF(API.LogType.Notice, "  Enabled       : {0}", voice.Enabled);

                    ++index;
                }

                api.Log(API.LogType.Notice, "------------------------------");
            }
        }
Example #10
0
        public static void Reload(IntPtr data, IntPtr rm, ref double maxValue)
        {
            Measure measure = (Measure)data;

            Rainmeter.API api       = (Rainmeter.API)rm;
            string        latitude  = api.ReadString("Latitude", "21.3891", false);
            string        longitude = api.ReadString("Longitude", "39.8579", false);
            int           method    = api.ReadInt("Method", 4);
            int           school    = api.ReadInt("School", 0);
            int           latitudeAdjustmentMethod = api.ReadInt("LatitudeAdjustmentMethod", 1);
            int           hijriAdjustment          = api.ReadInt("HijriAdjustment", 0);
            int           midnightMode             = api.ReadInt("MidnightMode", 0);
            bool          _12hourmode = api.ReadInt("12HourClockMode", 24) == 12;

            measure.Reload(latitude, longitude, method, school, latitudeAdjustmentMethod, hijriAdjustment, midnightMode, _12hourmode);
        }
Example #11
0
        public static void Initialize(ref IntPtr data, IntPtr rm)
        {
            string path = Rainmeter.API.GetSettingsFile();

            Rainmeter.API api       = (Rainmeter.API)rm;
            string        latitude  = api.ReadString("Latitude", "21.3891", false);
            string        longitude = api.ReadString("Longitude", "39.8579", false);
            int           method    = api.ReadInt("Method", 4);
            int           school    = api.ReadInt("School", 0);
            int           latitudeAdjustmentMethod = api.ReadInt("LatitudeAdjustmentMethod", 1);
            int           hijriAdjustment          = api.ReadInt("HijriAdjustment", 0);
            int           midnightMode             = api.ReadInt("MidnightMode", 0);
            bool          _12hourmode = api.ReadInt("12HourClockMode", 24) == 12;

            data = GCHandle.ToIntPtr(GCHandle.Alloc(new Measure(path, latitude, longitude, method, school, latitudeAdjustmentMethod, hijriAdjustment, midnightMode, _12hourmode)));
        }
Example #12
0
        internal virtual void Reload(Rainmeter.API api, ref double maxValue)
        {
            //@TODO Use this port
            int port = api.ReadInt("Port", 58932);

            string playerTypeString = api.ReadString("PlayerType", "Status");

            try
            {
                playerType = (InfoTypes)Enum.Parse(typeof(InfoTypes), playerTypeString, true);

                if (playerType == InfoTypes.Cover)
                {
                    //Unused @TODO Implement using this. Probably would be cleanest to null all other music info locations during write to disk
                    //defaultCoverLocation = api.ReadPath("DefaultPath", "");
                    string temp = api.ReadPath("CoverPath", null);
                    if (temp.Length > 0)
                    {
                        CoverOutputLocation = temp;
                    }
                    temp = api.ReadPath("DefaultPath", null);
                    if (temp.Length > 0)
                    {
                        CoverDefaultLocation = temp;
                    }
                }
                else if (playerType == InfoTypes.Progress)
                {
                    maxValue = 100;
                }
            }
            catch (Exception e)
            {
                API.Log(API.LogType.Error, "WebNowPlaying.dll - Unknown PlayerType:" + playerTypeString);
                API.Log(API.LogType.Debug, "Error:" + e.ToString());
                playerType = InfoTypes.Status;
            }
        }
Example #13
0
        internal override void Reload(Rainmeter.API api, ref double maxValue)
        {
            Rainmeter = api;
            base.Reload(api, ref maxValue);

            Topic    = api.ReadString("Topic", "defaulttopic");
            Property = api.ReadString("Property", "");
            var qos = api.ReadInt("Qos", 0);

            ParentName = api.ReadString("ParentName", "");
            Skin       = api.GetSkin();

            // Find parent using name AND the skin handle to be sure that it's the right one.
            ParentMeasure = null;
            foreach (MqttClientMeasure parentMeasure in MqttClientMeasure.ParentMeasures)
            {
                if (parentMeasure.Skin.Equals(Skin) && parentMeasure.Name.Equals(ParentName))
                {
                    ParentMeasure = parentMeasure;
                    try
                    {
                        DebugLevel = parentMeasure.DebugLevel;
                        ParentMeasure.Subscribe(Topic, (byte)qos);
                    }
                    catch
                    {
                        Debug("Error Subscribing !", 1);
                    }
                }
            }

            if (ParentMeasure == null)
            {
                Log(API.LogType.Error, "ParentChild.dll: ParentName=" + ParentName + " not valid");
            }
        }
Example #14
0
        internal virtual void Reload(Rainmeter.API api, ref double maxValue)
        {
            //@TODO Use this port
            int port = api.ReadInt("Port", 58932);

            myService = api.ReadString("Name", "");
            //If my service does not start with a slash
            if (myService.Substring(0, 1) != "/")
            {
                myService = "/" + myService;
            }

            string newCommandOnOpen    = api.ReadString("OnOpen", "");
            string newCommandOnClose   = api.ReadString("OnClose", "");
            string newCommandOnMessage = api.ReadString("OnMessage", "");

            mySkin = api.GetSkin();
            string myMeasure = api.GetMeasureName();

            bool isNewService = true;
            int  serviceLoc   = 0;

            foreach (string service in services)
            {
                //If new service already exists
                if (myService == service)
                {
                    isNewService = false;
                    bool isNewSkin = true;
                    myServiceID = serviceLoc;

                    //Check if a skin with the same ID already exists if it does then just update instead of making a new skin
                    //Note: we just compare against onOpen, so make sure it is safe to assume they are always in the same loc from same skin @TODO Actually lets just merge execute command to have an open and a close command Edit: Mostly done
                    foreach (ExecuteCommand command in commands[serviceLoc])
                    {
                        //Check if from the same skin
                        if (command.Skin == mySkin)
                        {
                            //Check if from the same measure (No one really should be using two measures in the same service but since I did it for testing I might as well check for it as well)
                            if (command.Measure == myMeasure)
                            {
                                isNewSkin                = false;
                                command.CommandOnOpen    = newCommandOnOpen;
                                command.CommandOnClose   = newCommandOnClose;
                                command.CommandOnMessage = newCommandOnMessage;
                            }
                        }
                    }

                    if (isNewSkin)
                    {
                        commands[serviceLoc].Add(new ExecuteCommand(mySkin, myMeasure, newCommandOnOpen, newCommandOnClose, newCommandOnMessage));
                    }
                }
                serviceLoc++;
            }

            //If new service is actually new service
            if (isNewService)
            {
                services.Add(myService);

                //Add a new item in the top level (Services) of the list that contains a list of one command
                commands.Add(new List <ExecuteCommand>(new ExecuteCommand[] { new ExecuteCommand(mySkin, myMeasure, newCommandOnOpen, newCommandOnClose, newCommandOnMessage) }));

                //Start new service
                wssv.AddWebSocketService <MessagePassing>(myService);
            }
        }
        internal void Reload(Rainmeter.API rm)
        {
            api = rm;

            try
            {
                string hwType  = rm.ReadString("HardwareType", "");
                string hwName  = rm.ReadString("HardwareName", "");
                int    hwIndex = rm.ReadInt("HardwareIndex", 0);

                string sType  = rm.ReadString("SensorType", "");
                string sName  = rm.ReadString("SensorName", "");
                int    sIndex = rm.ReadInt("SensorIndex", 0);

                api.Log(API.LogType.Debug, String.Format("Hardware(type, name, index): ({0}, {1}, {2}), Sensor(type, name, index): ({3}, {4}, {5})", hwType, hwName, hwIndex, sType, sName, sIndex));

                this.ns = wmiROOT + "\\" + rm.ReadString("Namespace", DefaultNamespace);

                WMIQuery hwQuery = new WMIQuery(this.ns, HardwareClass);
                if (hwType.Length > 0)
                {
                    hwQuery.Where("HardwareType", hwType);
                }
                if (hwName.Length > 0)
                {
                    hwQuery.Where("name", hwName);
                }

                api.Log(API.LogType.Debug, "Hardware Query: " + hwQuery.ToString());

                string hardwareID;
                using (var hardware = hwQuery.GetAt(hwIndex))
                {
                    if (hardware == null)
                    {
                        api.Log(API.LogType.Error, "can't find hardware -> check hardware filter, check if OHM/LHM is running");
                        this.sensorID = null;
                        return;
                    }
                    hardwareID = (string)hardware.GetPropertyValue("Identifier");
                    api.Log(API.LogType.Debug, "Hardware Identifier: " + hardwareID.ToString());
                }

                WMIQuery sQuery = new WMIQuery(this.ns, SensorClass);
                sQuery.Where("Parent", hardwareID);
                if (sType.Length > 0)
                {
                    sQuery.Where("SensorType", sType);
                }
                if (sName.Length > 0)
                {
                    sQuery.Where("name", sName);
                }

                api.Log(API.LogType.Debug, "Sensor Query: " + sQuery.ToString());
                using (var sensor = sQuery.GetAt(sIndex))
                {
                    if (sensor == null)
                    {
                        api.Log(API.LogType.Error, "can't find sensor -> check sensor filter");
                        this.sensorID = null;
                        return;
                    }
                    this.sensorID = sensor.GetPropertyValue("Identifier").ToString();
                    api.Log(API.LogType.Debug, "Sensor Identifier: " + sensorID.ToString());
                }
            }
            catch (Exception ex)
            {
                api.Log(API.LogType.Error, "Fatal Error: " + ex.Message);
                api.Log(API.LogType.Debug, ex.ToString());
            }
        }
        internal MqttClientMeasure(Rainmeter.API api)
        {
            ParentMeasures.Add(this);
            ParentRainmeterApis.Add(api);
            this.Rainmeter = api;
            this.Name      = api.GetMeasureName();
            Skin           = api.GetSkin();
            DebugLevel     = (ushort)api.ReadInt("DebugLevel", 0);

            Server        = api.ReadString("Server", "localhost");
            Port          = (ushort)api.ReadInt("Port", 1883);
            RetryInterval = (ushort)api.ReadDouble("RetryInterval", 5.0);
            ClientId      = api.ReadString("ClientId", Guid.NewGuid().ToString());
            Username      = api.ReadString("Username", "");
            Password      = new SecureString();
            foreach (char ch in api.ReadString("Password", ""))
            {
                Password.AppendChar(ch);
            }

            /* Mqtt Server Bangs */
            OnConnectBangs    = SplitBangs(api.ReadString("OnConnect", ""));
            OnDisconnectBangs = SplitBangs(api.ReadString("OnConnect", ""));
            OnReloadBangs     = SplitBangs(api.ReadString("OnReload", ""));
            OnMessageBangs    = SplitBangs(api.ReadString("OnMessage", ""));

            MqttClient = Factory.CreateManagedMqttClient();

            /* Setup Event Handlers */
            MqttClient.UseConnectedHandler(e =>
            {
                if (!MqttClientMeasure.ParentRainmeterApis.Contains(Rainmeter))
                {
                    return;
                }

                Log(API.LogType.Notice, "Connected to " + Server + " : " + Port);

                if (OnConnectBangs.Length > 0)
                {
                    Log(API.LogType.Notice, "Executing OnConnect Bangs");
                    ExecuteBangs(OnConnectBangs);
                }
            });

            MqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                if (!MqttClientMeasure.ParentRainmeterApis.Contains(Rainmeter))
                {
                    return;
                }

                e.GetType();
                String topic   = e.ApplicationMessage.Topic;
                String payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                try
                {
                    Debug("### RECEIVED APPLICATION MESSAGE ###", 3);
                    Debug($" >> Topic = {e.ApplicationMessage.Topic}", 4);
                    Debug($" >> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}", 4);
                    Debug($" >> QoS = {e.ApplicationMessage.QualityOfServiceLevel}", 5);
                    Debug($" >> Retain = {e.ApplicationMessage.Retain}", 5);

                    if (Topics.Contains(topic))
                    {
                        Topics[topic] = payload;
                        Log(API.LogType.Notice, "Received update for " + topic);
                    }
                    else
                    {
                        Topics.Add(topic, payload);
                        Log(API.LogType.Warning, "Received payload for unknown topic " + topic);
                    }

                    if (OnMessageBangs.Length > 0)
                    {
                        Log(API.LogType.Notice, "Executing OnMessage Bangs");
                        ExecuteBangs(OnMessageBangs);
                    }
                }
                catch
                {
                    // Error Application
                }
            });

            MqttClient.UseDisconnectedHandler(e =>
            {
                if (!MqttClientMeasure.ParentRainmeterApis.Contains(Rainmeter))
                {
                    return;
                }

                Log(API.LogType.Error, e.Exception?.Message);
                Log(API.LogType.Error, e.AuthenticateResult?.ReasonString);
                Log(API.LogType.Error, e.ClientWasConnected.ToString());

                if (!MqttClient.IsConnected)
                {
                    Log(API.LogType.Warning, "Lost previous connection to " + Server + " : " + Port);
                }

                if (OnDisconnectBangs.Length > 0)
                {
                    Log(API.LogType.Notice, "Executing OnDisconnect Bangs");
                    ExecuteBangs(OnDisconnectBangs);
                }
            });

            try
            {
                Log(API.LogType.Warning, "Connecting to " + Server + " : " + Port + "...");
                ConnectAsync(Server, Port, Username, Password, ClientId).Wait();
            }
            catch (Exception ex)
            {
                Log(API.LogType.Error, "Exception trying to connect: " + ex);
                return;
            }
        }
        internal override void Reload(Rainmeter.API api, ref double maxValue)
        {
            base.Reload(api, ref maxValue);

            string parentName = api.ReadString(PARAM_PARENT_NAME, "");

            IntPtr skin = api.GetSkin();

            property = api.ReadString(PARAM_PROPERTY, "");


            String mesureName = api.GetMeasureName();

            if (mesureName.StartsWith(parentName))
            {
                String sndx = mesureName.Substring(parentName.Length);
                if (sndx.IndexOf("_") > 0)
                {
                    if (String.IsNullOrEmpty(property))
                    {
                        property = sndx.Substring(sndx.IndexOf("_") + 1);
                    }

                    sndx = sndx.Substring(0, sndx.IndexOf("_"));
                }

                ndx = int.Parse(sndx);
            }
            else
            {
                ndx = api.ReadInt(PARAM_INDEX, 1);
            }

            ndx--;


            // Find parent using name AND the skin handle to be sure that it's the right one
            RuntimeTypeHandle parentType = typeof(ParentMeasure).TypeHandle;

            foreach (KeyValuePair <uint, Measure> pair in Plugin.Measures)
            {
                if (System.Type.GetTypeHandle(pair.Value).Equals(parentType))
                {
                    ParentMeasure parentMeasure = (ParentMeasure)pair.Value;

                    if (parentMeasure.Name.Equals(parentName) &&
                        parentMeasure.Skin.Equals(skin))
                    {
                        HasParent = true;
                        ParentID  = pair.Key;

                        todayDateFormat = api.ReadString(ParentMeasure.PARAM_TODAY_FORMAT, parentMeasure.todayDateFormat);
                        weekDateFormat  = api.ReadString(ParentMeasure.PARAM_WEEK_DATE_FORMAT, parentMeasure.weekDateFormat);
                        dateFormat      = api.ReadString(ParentMeasure.PARAM_DATE_FORMAT, parentMeasure.dateFormat);

                        return;
                    }
                }
            }

            HasParent = false;
            API.Log(API.LogType.Error, "RainGoo.dll: ParentName=" + parentName + " not valid");
        }
Example #18
0
        public static void Reload(IntPtr data, IntPtr rm, ref double maxValue)
        {
            Measure measure = (Measure)data;

            Rainmeter.API api = (Rainmeter.API)rm;

            string name       = api.ReadString("Name", "");
            bool   nameExists = name != "" ? true : false;

            VoiceGender gender    = VoiceGender.NotSet;
            string      genderStr = api.ReadString("Gender", "").ToUpper();

            if (genderStr == "MALE")
            {
                gender = VoiceGender.Male;
            }
            else if (genderStr == "FEMALE")
            {
                gender = VoiceGender.Female;
            }
            else if (genderStr != "")
            {
                api.Log(API.LogType.Warning, "Speech.dll: Invalid gender");
            }
            bool genderExists = gender != VoiceGender.NotSet;

            measure.gender = gender;

            int index = api.ReadInt("Index", 0);

            measure.index = index;

            int volume = api.ReadInt("Volume", 100);

            if (volume < 0 || volume > 100)
            {
                volume = 100;
            }

            int rate = api.ReadInt("Rate", 0);

            if (rate < -10 || rate > 10)
            {
                rate = 0;
            }

            measure.synth.Volume = volume;
            measure.synth.Rate   = rate;

            // Setup voice
            int    i            = 1;
            String selectedName = "";

            foreach (InstalledVoice voice in measure.voices)
            {
                // If no options are "defined", use the first voice.
                if (!nameExists && !genderExists && (index <= 0))
                {
                    selectedName = voice.VoiceInfo.Name;
                    break;
                }

                // If name is defined, use this voice.
                if (nameExists && (name.ToUpper() == voice.VoiceInfo.Name.ToUpper()))
                {
                    selectedName = voice.VoiceInfo.Name;
                    break;
                }

                // If gender is defined, only look for voices of the same gender
                if (!nameExists && genderExists)
                {
                    if (gender != voice.VoiceInfo.Gender)
                    {
                        continue;
                    }

                    if (index > 0)
                    {
                        if (index == i)
                        {
                            selectedName = voice.VoiceInfo.Name;
                            break;
                        }

                        ++i;
                        continue;
                    }
                    else
                    {
                        selectedName = voice.VoiceInfo.Name;
                        break;
                    }
                }

                // Select by index
                if (!nameExists && index == i)
                {
                    selectedName = voice.VoiceInfo.Name;
                    break;
                }

                ++i;
            }

            measure.selectedName = selectedName;

            // Something went wrong
            //  Name is incorrect
            //  No matching gender was found
            //  Invalid index
            if (selectedName == "")
            {
                api.Log(API.LogType.Warning, "Speech.dll: Invalid Name, Gender and/or Index. Using best matching valid voice.");
            }
        }
Example #19
0
        internal static void ParseProperties(Rainmeter.API api, object obj)
        {
            LogHelper log  = new LogHelper(api);
            Type      type = obj.GetType();

            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            EventInfo[]    events     = type.GetEvents(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo pinfo in properties)
            {
                if (pinfo.CanWrite)
                {
                    if (pinfo.PropertyType == typeof(string))
                    {
                        //log.LogDebug("Found string Property: " + pinfo.Name);
                        string propval = api.ReadString(pinfo.Name, "");
                        if (propval != "")
                        {
                            log.LogDebug("Setting " + pinfo.PropertyType.Name + " Property " + pinfo.Name + " to " + propval);
                            pinfo.SetValue(obj, propval, null);
                        }
                    }
                    else if (pinfo.PropertyType == typeof(int))
                    {
                        int val = (int)pinfo.GetValue(obj, null);
                        //log.LogDebug("Found int Property: " + pinfo.Name + " with value: " + val);
                        int propval = api.ReadInt(pinfo.Name, val);
                        if (propval != val)
                        {
                            log.LogDebug("Setting " + pinfo.PropertyType.Name + " Property " + pinfo.Name + " to " + propval);
                            pinfo.SetValue(obj, propval, null);
                        }
                    }
                    else if (pinfo.PropertyType == typeof(bool))
                    {
                        bool val = (bool)pinfo.GetValue(obj, null);
                        //log.LogDebug("Found " + pinfo.PropertyType + " Property: " + pinfo.Name + " with value: " + val);
                        bool propval = api.ReadInt(pinfo.Name, Convert.ToInt32(val)) > 0;
                        if (propval != val)
                        {
                            log.LogDebug("Setting " + pinfo.PropertyType.Name + " Property " + pinfo.Name + " to " + propval);
                            pinfo.SetValue(obj, propval, null);
                        }
                    }
                    else if (pinfo.PropertyType == typeof(float))
                    {
                        float val = (float)pinfo.GetValue(obj, null);
                        //log.LogDebug("Found float Property: " + pinfo.Name + " with value: " + val);
                        float propval = (float)api.ReadDouble(pinfo.Name, val);
                        if (propval != val)
                        {
                            log.LogDebug("Setting " + pinfo.PropertyType.Name + " Property " + pinfo.Name + " to " + propval);
                            pinfo.SetValue(obj, propval, null);
                        }
                    }
                    else if (pinfo.PropertyType == typeof(double))
                    {
                        double val = (double)pinfo.GetValue(obj, null);
                        //log.LogDebug("Found double Property: " + pinfo.Name + " with value: " + val);
                        double propval = api.ReadDouble(pinfo.Name, val);
                        if (propval != val)
                        {
                            log.LogDebug("Setting " + pinfo.PropertyType.Name + " Property " + pinfo.Name + " to " + propval);
                            pinfo.SetValue(obj, propval, null);
                        }
                    }
                    else
                    {
                        string propval = api.ReadString(pinfo.Name, "");
                        if (propval != "")
                        {
                            object val = null;

                            if (pinfo.PropertyType == typeof(Color))
                            {
                                val = Util.ColorFromString(propval);
                            }
                            else
                            {
                                val = pinfo.PropertyType.IsEnum ?
                                      Util.EnumFromString(pinfo.PropertyType, propval) :
                                      Util.ObjectFromString(api, pinfo.PropertyType, propval);
                            }

                            if (val != null)
                            {
                                pinfo.SetValue(obj, val, null);
                            }
                            else
                            {
                                log.LogPropertyValueNotValid(propval, pinfo);
                            }
                        }
                    }
                }
            }

            foreach (EventInfo einfo in events)
            {
                // winforms syntax for events
                string evntval = api.ReadString(einfo.Name, "");
                if (evntval == "")
                {
                    // rainmeter syntax for events
                    evntval = api.ReadString("On" + einfo.Name, "");
                    if (evntval == "")
                    {
                        continue;
                    }
                }

                // remove existing event
                cEventHelper.RemoveEventHandler(obj, einfo.Name);

                // create new event
                EventHandler untypedHandler = delegate(object sender, EventArgs args)
                {
                    api.Execute(evntval);
                };

                Delegate typedHandler = Delegate.CreateDelegate(einfo.EventHandlerType,
                                                                untypedHandler.Target, untypedHandler.Method);
                einfo.AddEventHandler(obj, typedHandler);
            }
        }
        internal override void Reload(Rainmeter.API api, ref double maxValue)
        {
            base.Reload(api, ref maxValue);

            Name = api.GetMeasureName();
            //API.Log(API.LogType.Notice, "RainGoo.dll : Measure name is  : " + Name);

            googleClientId     = api.ReadString(PARAM_GOOGLE_CLIENT_ID, "");
            googleClientSecret = api.ReadString(PARAM_GOOGLE_CLIENT_SECRET, "");
            googleAppName      = api.ReadString(PARAM_GOOGLE_APP_NAME, "");
            googleUserName     = api.ReadString(PARAM_GOOGLE_USER_NAME, "");



            if (Name == "mGcal")
            {
                Skin = api.GetSkin();

                calUrls.Clear();

                int    i   = 1;
                String tmp = null;

                while (!String.IsNullOrWhiteSpace((tmp = api.ReadString(PARAM_CAL + i, ""))))
                {
                    if (tmp != "#Calendar2#" && tmp != "#Calendar3#")
                    {
                        calUrls.Add(tmp);
                    }
                    i++;
                }

                max          = api.ReadInt(PARAM_MAX, DEFAULT_MAX);
                Limit2Xdays  = api.ReadInt(PARAM_LIMIT2XDAYS, DEFAULT_LIMITXDAYS);
                MIN_INTERVAL = api.ReadInt(PARAM_REFRESH_CAL, 30) * 1000;


                todayDateFormat = api.ReadString(PARAM_TODAY_FORMAT, "HH:mm");
                weekDateFormat  = api.ReadString(PARAM_WEEK_DATE_FORMAT, "ddd");
                dateFormat      = api.ReadString(PARAM_DATE_FORMAT, "ddd dd MMM");



#if DEBUG
                API.Log(API.LogType.Notice, "RainGoo.dll: Calendars : " + calUrls.Count + " - Max results : " + max + " - Limit 2 X days : " + Limit2Xdays);
#endif

                calendarPath = api.ReadPath(PARAM_INC_PATH, "");

                lastUpdate = 0;
                UpdateEvents();
            }
            else
            {
                Skin = api.GetSkin();
                // Generates include files
                maxGmail  = api.ReadInt(PARAM_MAX, DEFAULT_MAX);
                gmailPath = api.ReadPath(PARAM_INC_PATH, "");
#if DEBUG
                API.Log(API.LogType.Notice, "RainGoo.dll: Gmail inc file path :" + gmailPath);
#endif
                lastUpdategmail   = 0;
                MIN_INTERVALGMAIL = api.ReadInt(PARAM_REFRESH_MAIL, 10) * 1000;
                UpdateGmail();
            }
        }