Exemple #1
0
        public void WritePowerInfo(string textpanelname)
        {
            PowerInfo            powertotal = new PowerInfo(0, 0);
            PowerInfo            power;
            List <IMySolarPanel> panels   = GetSolarPanelList();
            List <IMyReactor>    reactors = GetReactorList();

            foreach (IMySolarPanel panel in panels)
            {
                power       = new PowerInfo(panel);
                powertotal += power;
            }


            WriteTextToPanel(textpanelname, "", false);
            WriteTextToPanel(textpanelname, "Solar Power Output: {0} for {1} panels", true, powertotal, panels.Count);


            powertotal = new PowerInfo(0, 0);

            foreach (IMyReactor reactor in reactors)
            {
                power       = new PowerInfo(reactor);
                powertotal += power;
            }


            WriteTextToPanel(textpanelname, "", false);
            WriteTextToPanel(textpanelname, "Reactor Power Output: {0} for {1} reactors", true, powertotal, reactors.Count);


            powertotal = new PowerInfo(0, 0);
        }
        private void GetHostControllerPowerMap(IntPtr handle)
        {
            UsbUser.WdmusbPowerState powerState = UsbUser.WdmusbPowerState.WdmUsbPowerSystemWorking;

            for (; powerState <= UsbUser.WdmusbPowerState.WdmUsbPowerSystemShutdown; powerState++)
            {
                UsbUser.UsbuserPowerInfoRequest powerInfoRequest = new UsbUser.UsbuserPowerInfoRequest
                {
                    Header =
                    {
                        UsbUserRequest = UsbUser.UsbuserGetPowerStateMap,
                    },
                    PowerInformation = { SystemState = powerState }
                };

                powerInfoRequest.Header.RequestBufferLength = (uint)Marshal.SizeOf(powerInfoRequest);

                IntPtr ptrPowerInfoRequest = IntPtr.Zero;

                try
                {
                    //
                    // Now query USBHUB for the USB_POWER_INFO structure for this hub.
                    // For Selective Suspend support
                    //
                    int nBytes = Marshal.SizeOf(powerInfoRequest);
                    ptrPowerInfoRequest = Marshal.AllocHGlobal(nBytes);

                    Marshal.StructureToPtr(powerInfoRequest, ptrPowerInfoRequest, true);

                    var success = KernelApi.DeviceIoControl(handle,
                                                            UsbUser.IoctlUsbUserRequest,
                                                            ptrPowerInfoRequest,
                                                            nBytes,
                                                            ptrPowerInfoRequest,
                                                            nBytes,
                                                            out _,
                                                            IntPtr.Zero);

                    if (!success)
                    {
                        CoreTraceSource.Source.TraceEvent(TraceEventType.Error, CoreTraceSource.UsbControllerSourceId,
                                                          $"[{nameof(KernelApi.DeviceIoControl)}] Returned Error Code: [{KernelApi.GetLastError():X}]");
                    }
                    else
                    {
                        powerInfoRequest = (UsbUser.UsbuserPowerInfoRequest)Marshal.PtrToStructure(ptrPowerInfoRequest,
                                                                                                   typeof(UsbUser.UsbuserPowerInfoRequest));
                        PowerInfo.Add(powerInfoRequest.PowerInformation);
                    }
                }
                finally
                {
                    if (ptrPowerInfoRequest != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(ptrPowerInfoRequest);
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                int queryString = RequestHelper.GetQueryString <int>("ID");
                if (queryString != -2147483648)
                {
                    base.CheckAdminPower("ReadAdminGroup", PowerCheckType.Single);
                    AdminGroupInfo info = AdminGroupBLL.ReadAdminGroupCache(queryString);
                    this.Name.Text  = info.Name;
                    this.Note.Text  = info.Note;
                    this.State.Text = info.State.ToString();
                    this.power      = info.Power;
                }
            }
            XmlNode node = new XmlHelper(ServerHelper.MapPath("/Config/AdminPower.Config")).ReadNode("Config");

            foreach (XmlNode node2 in node.ChildNodes)
            {
                PowerInfo item = new PowerInfo();
                item.Text = node2.Attributes["Text"].Value;
                item.Key  = node2.Attributes["Key"].Value;
                item.XML  = node2.InnerXml;
                this.channelPowerList.Add(item);
            }
        }
Exemple #4
0
        public void Step(ref PowerInfo token, int condition)
        {
            var hudEntityViews = entityViewsDB.QueryEntityViews <HUDEntityView>();

            for (int i = 0; i < hudEntityViews.Count; i++)
            {
                UpdatePowerUI(token, hudEntityViews[i]).Run();
            }
        }
Exemple #5
0
 IEnumerator UpdatePowerUI(PowerInfo info, HUDEntityView entityview)
 {
     entityview.powerFilledImageComponent.fillAmount = 0f;
     while (entityview.powerFilledImageComponent.fillAmount < 1f)
     {
         entityview.powerFilledImageComponent.fillAmount += _time.deltaTime / info.cooldown;
         yield return(null);
     }
 }
Exemple #6
0
            public static PowerInfo operator +(PowerInfo arg1, PowerInfo arg2)
            {
                PowerInfo result = new PowerInfo(arg1.MaxWatts, arg1.Watts);

                result.MaxWatts += arg2.MaxWatts;
                result.Watts    += arg2.Watts;


                return(result);
            }
        /// <summary>
        /// 初始化状态
        /// </summary>
        void init_ZhuanTai()
        {
            PowerInfo vPowerInfo = m_PowerMonitoring.GetNewPowerInfo(DianYuanID, LuHao);

            label_ZT_DL.Content   = string.Format("{0}A", vPowerInfo.DianLiu);
            label_ZT_DN.Content   = string.Format("{0}kWh", vPowerInfo.DianNeng);
            label_ZT_DY.Content   = string.Format("{0}V", vPowerInfo.DianYa);
            label_ZT_GLYS.Content = string.Format("{0}", vPowerInfo.GongLuYinShu);
            label_ZT_LDL.Content  = string.Format("{0}mA", vPowerInfo.LouDianLiu);
            label_ZT_PL.Content   = string.Format("{0}Hz", vPowerInfo.PinLu);
            label_ZT_WD.Content   = string.Format("{0}℃", vPowerInfo.WenDu);
            label_ZT_WGGL.Content = string.Format("{0}var", vPowerInfo.WuGongGL);
            label_ZT_YGGL.Content = string.Format("{0}W", vPowerInfo.YouGongGL);
        }
Exemple #8
0
        async void RefreshState()
        {
            await Task.Run(() =>
            {
                while (true)
                {
                    Action action1 = () =>
                    {
                        for (int i = 1; i <= m_LuoHaoList1.Count; i++)
                        {
                            PowerInfo vPowerInfo = m_PowerMonitoring.GetNewPowerInfo(App.PowerID1, m_LuoHaoList1[i - 1]);
                            if (vPowerInfo != null)
                            {
                                Label vLabel_DY   = (Label)FindName(string.Format("label_DY1_DY_{0}", i));
                                vLabel_DY.Content = string.Format("{0}V", vPowerInfo.DianYa);

                                Label vLabel_DL   = (Label)FindName(string.Format("label_DY1_DL_{0}", i));
                                vLabel_DL.Content = string.Format("{0}A", vPowerInfo.DianLiu);

                                CheckBox vCheckBox  = (CheckBox)FindName(string.Format("checkBox_DY1_Switch{0}", i));
                                vCheckBox.IsChecked = vPowerInfo.ZhuangTai;

                                changeSwitchColor(vCheckBox, 1, i);
                            }
                        }

                        for (int i = 1; i <= m_LuoHaoList2.Count; i++)
                        {
                            PowerInfo vPowerInfo = m_PowerMonitoring.GetNewPowerInfo(App.PowerID2, m_LuoHaoList2[i - 1]);
                            if (vPowerInfo != null)
                            {
                                Label vLabel_DY   = (Label)FindName(string.Format("label_DY2_DY_{0}", i));
                                vLabel_DY.Content = string.Format("{0}V", vPowerInfo.DianYa);

                                Label vLabel_DL   = (Label)FindName(string.Format("label_DY2_DL_{0}", i));
                                vLabel_DL.Content = string.Format("{0}A", vPowerInfo.DianLiu);

                                CheckBox vCheckBox  = (CheckBox)FindName(string.Format("checkBox_DY2_Switch{0}", i));
                                vCheckBox.IsChecked = vPowerInfo.ZhuangTai;

                                changeSwitchColor(vCheckBox, 2, i);
                            }
                        }
                    };
                    Dispatcher.BeginInvoke(action1);
                    Thread.Sleep(App.RefreshTime * 1000);
                }
            });
        }
    private void UpdatePowerGridItem(UIGridItem item)
    {
        if (item == null || item.mScripts == null || item.oData == null)
        {
            return;
        }
        PowerInfo info = item.oData as PowerInfo;

        item.onClick = OnClickItem;
        UILabel name  = item.mScripts[0] as UILabel;
        UILabel count = item.mScripts[1] as UILabel;

        name.text  = TextManager.GetUIString("UIGuildPower" + info.power);
        count.text = string.Format("({0}/{1})", info.count, info.totalNum);
    }
    private void OnClickItem(UIGridItem item)
    {
        PowerInfo info = item.oData as PowerInfo;

        if (info.count == info.totalNum)
        {
            GUIManager.SetJumpText(TextManager.GetSystemString("ui_system_guild_err21"));
            return;
        }
        if (PlayerMediator.playerInfo.guildPower <= info.power)
        {
            GUIManager.SetJumpText(TextManager.GetSystemString("ui_system_guild_err11"));
            return;
        }
        ServerCustom.instance.SendClientMethods(GuildProxy.OnClientAppointPower, mInfo.id, info.power);
    }
        protected List <PowerInfo> ReadPowerItem(string xml)
        {
            string      str      = "<root>" + xml + "</root>";
            XmlDocument document = new XmlDocument();

            document.LoadXml(str);
            List <PowerInfo> list = new List <PowerInfo>();

            foreach (XmlNode node in document.SelectNodes("root/Item"))
            {
                PowerInfo item = new PowerInfo();
                item.Text  = node.Attributes["Text"].Value;
                item.Value = node.Attributes["Value"].Value;
                list.Add(item);
            }
            return(list);
        }
Exemple #12
0
        protected List <PowerInfo> ReadPowerItem(string xml)
        {
            string      childNode = "<root>" + xml + "</root>";
            XmlDocument xd        = new XmlDocument();

            xd.LoadXml(childNode);
            List <PowerInfo> itemPowerList = new List <PowerInfo>();

            foreach (XmlNode xn in xd.SelectNodes("root/Item"))
            {
                PowerInfo power = new PowerInfo();
                power.Text  = xn.Attributes["Text"].Value;
                power.Value = xn.Attributes["Value"].Value;
                itemPowerList.Add(power);
            }
            return(itemPowerList);
        }
Exemple #13
0
        protected List <PowerInfo> ReadPowerBlock(string xml)
        {
            string      childNode = "<root>" + xml + "</root>";
            XmlDocument xd        = new XmlDocument();

            xd.LoadXml(childNode);
            List <PowerInfo> blockPowerList = new List <PowerInfo>();

            foreach (XmlNode xn in xd.SelectNodes("root/Block"))
            {
                PowerInfo power = new PowerInfo();
                power.Text = xn.Attributes["Text"].Value;
                power.XML  = xn.InnerXml;
                blockPowerList.Add(power);
            }
            return(blockPowerList);
        }
    public void SetPowerGridDate()
    {
        panel.duty.text = TextManager.GetUIString("UIGuildPower" + mInfo.power);
        List <object> listObj = new List <object>();

        PowerInfo info;

        for (int i = 4; i > 0; i--)
        {
            info          = new PowerInfo();
            info.power    = i;
            info.count    = GetGuildPowerNum(i);
            info.totalNum = GuildOfficialConfig.GetGuildOfficial(i).num;
            listObj.Add(info);
        }

        panel.powerGrid.AddCustomDataList(listObj);
    }
Exemple #15
0
    protected void BTN_ADD_Click(object sender, EventArgs e)
    {
        PowerInfo info = new PowerInfo();

        info.MoudleId   = this.ViewState["ID"].ToString();
        info.PowerName  = this.TXT_POWERNAME.Text;
        info.PowerValue = int.Parse(this.TXT_POWERVALUE.Text.Trim());

        if (this._Power.CreatePower(info))
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('模块功能保存成功!');</script>");
            BuildGrid(this.ViewState["ID"].ToString());
            ClearPage();
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('模块功能保存失败!');</script>");
        }
    }
        IEnumerator Push(PowerEntityView powerEntityView)
        {
            var powerComponent = powerEntityView.powerComponent;
            var scaleComponent = powerEntityView.scaleComponent;

            powerComponent.timer = 0;
            var powerInfo = new PowerInfo(_powerEntityView.ID, AudioType.activate, powerComponent.cooldown);

            _pushPowerSequence.Next(this, ref powerInfo, PowerCondition.Start);
            float powerTimer = 0;

            while (powerTimer < powerComponent.duration)
            {
                powerTimer += _time.deltaTime;
                float   currentScaleSpeed = powerComponent.speed * _time.deltaTime;
                Vector3 newScale          = scaleComponent.scale + new Vector3(currentScaleSpeed, currentScaleSpeed, currentScaleSpeed);
                scaleComponent.scale = newScale;
                yield return(null);
            }
            scaleComponent.scale = new Vector3(0, 0, 0);
            powerInfo.audioType  = AudioType.deactivate;
            _pushPowerSequence.Next(this, ref powerInfo, PowerCondition.Stop);
        }
        private void go_button_Click(object sender, EventArgs e)
        {
            ProgressDialog d = new ProgressDialog();
            string character_path = character_box.Text;
            string macro_path = macro_box.Text;
            List<PowerInfo> powers = new List<PowerInfo>();
            Dictionary<string, int> skills = new Dictionary<string, int>();
            System.Text.RegularExpressions.Regex img_remover = new System.Text.RegularExpressions.Regex(@"<img.*?>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            // save the value of the checkbox
            m_use_compendium = compendium_check.Checked;

            d.AddTask((progress) =>
            {
                progress.Update("Scanning character sheet...");

                using (FileStream fs = File.OpenRead(character_path))
                {
                    XPathDocument doc = new XPathDocument(fs);
                    XPathNavigator nav = doc.CreateNavigator();
                    XPathNodeIterator power_iter, weapon_iter;

                    // select all power nodes
                    power_iter = nav.Select("/D20Character/CharacterSheet/PowerStats/Power");

                    // update the progress steps
                    progress.Update(0, power_iter.Count);

                    // iterate them
                    while (power_iter.MoveNext())
                    {
                        string name;
                        string action_type;
                        List<string> compendium_info = new List<string>();
                        PowerUsage usage;
                        XPathNavigator power_url_nav = null;

                        try
                        {
                            // read the basic stuff
                            name = power_iter.Current.SelectSingleNode("@name").Value;
                            usage = Util.EnumParse<PowerUsage>(power_iter.Current.SelectSingleNode("specific[@name = 'Power Usage']").Value.Replace("-", ""));
                            action_type = power_iter.Current.SelectSingleNode("specific[@name = 'Action Type']").Value.Trim();

                            // get the url for the power in the compendium
                            if (m_use_compendium)
                                power_url_nav = nav.SelectSingleNode("//RulesElementTally/RulesElement[@name = \"" + name + "\"]/@url");

                            // ...and if we did that, pull down the power description
                            if (power_url_nav != null)
                            {
                                HtmlAgilityPack.HtmlDocument scraper_doc = new HtmlAgilityPack.HtmlDocument();
                                HtmlAgilityPack.HtmlNodeNavigator scraper_result;
                                XPathNodeIterator content_iter;
                                XPathNavigator scraper_nav = null;

                                // slurp
                                try
                                {
                                    using (Stream s = m_compendium.GetEntryByUrl(power_url_nav.Value))
                                    {
                                        scraper_doc.Load(s, new UTF8Encoding());
                                        scraper_nav = scraper_doc.CreateNavigator();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    // if the user clicked cancel, stop attempting compendium stuff
                                    if (ex is ApplicationException && ex.Message.ToLowerInvariant().Contains("user refused"))
                                        m_use_compendium = false;
                                    else
                                        MessageBox.Show(ex.ToString(), "Compendium Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }

                                // if the web request succeeded...
                                if (scraper_nav != null)
                                {
                                    // select all the detail p tags
                                    content_iter = scraper_nav.Select("//div[@id = 'detail']/p");

                                    // loop through them
                                    while (content_iter.MoveNext())
                                    {
                                        string line;

                                        // cast to HtmlNodeNavigator
                                        scraper_result = content_iter.Current as HtmlAgilityPack.HtmlNodeNavigator;

                                        // skip publishing stuff
                                        if (scraper_result == null || scraper_result.CurrentNode.InnerHtml.ToLowerInvariant().Contains("published in"))
                                            continue;

                                        // grab the line, strip images, and remove [] stuff
                                        line = scraper_result.CurrentNode.InnerHtml;
                                        line = img_remover.Replace(line, "-");
                                        line = line.Replace("[W]", "<i>W</i>");

                                        // add the line
                                        compendium_info.Add(line);
                                    }
                                }
                            }

                            // select weapons
                            weapon_iter = power_iter.Current.Select("Weapon");

                            // some powers aren't attacks or don't use weapons
                            if (weapon_iter.Count < 1)
                            {
                                powers.Add(new PowerInfo(name, compendium_info, WEAPON_NONE, usage, action_type));
                            }
                            else
                            {
                                while (weapon_iter.MoveNext())
                                {
                                    PowerInfo power = new PowerInfo(name, compendium_info, weapon_iter.Current.SelectSingleNode("@name").Value, usage, action_type);

                                    // when there is more than one weapon, skip the Unarmed weapon
                                    if (power.Weapon == WEAPON_UNARMED && weapon_iter.Count > 1)
                                        continue;

                                    // read the attack info
                                    power.AttackBonus = weapon_iter.Current.SelectSingleNode("AttackBonus").ValueAsInt;
                                    power.AttackStat = weapon_iter.Current.SelectSingleNode("AttackStat").Value.Trim();
                                    power.DamageExpression = weapon_iter.Current.SelectSingleNode("Damage").Value.Trim();
                                    power.Defense = weapon_iter.Current.SelectSingleNode("Defense").Value.Trim();

                                    // all powers list an Unarmed weapon, even if they don't include an attack, set these to WEAPON_NONE
                                    if (power.Defense == "")
                                        power.Weapon = WEAPON_NONE;

                                    // add it to the list
                                    powers.Add(power);
                                }
                            }


                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        // wait briefly to avoid spamming compendium
                        if (m_use_compendium)
                            System.Threading.Thread.Sleep(200);

                        // advance progress
                        progress.Advance();
                    }

                    // detect skills from the RulesElementTally
                    power_iter = nav.Select("//RulesElementTally/RulesElement[@type = 'Skill']/@name");

                    // read the value for each one
                    while (power_iter.MoveNext())
                    {
                        string name = power_iter.Current.Value;
                        int value;
                        XPathNavigator value_node = nav.SelectSingleNode("/D20Character/CharacterSheet/StatBlock/Stat[@name = '" + name + "']/@value");

                        if (value_node != null && int.TryParse(value_node.Value, out value))
                            skills[name] = value;
                    }
                }
            });

            d.AddTask((progress) =>
            {
                progress.Update("Writing macros...");

                using (FileStream fs = File.Open(macro_path, FileMode.Create, FileAccess.Write))
                {
                    XmlWriterSettings settings;

                    settings = new XmlWriterSettings();
                    settings.Encoding = new System.Text.ASCIIEncoding();
                    settings.Indent = true;
                    settings.IndentChars = "  ";
                    settings.OmitXmlDeclaration = false;

                    using (XmlWriter w = XmlWriter.Create(fs, settings))
                    {
                        w.WriteStartDocument();
                        w.WriteStartElement("list");

                        foreach (PowerInfo power in powers)
                        {
                            StringBuilder command = new StringBuilder();
                            string text, background;

                            // skip basic attacks with no weapons
                            if (IsPowerBasicAttack(power.Name) && power.Weapon == WEAPON_NONE)
                                continue;

                            // begin macro definition
                            w.WriteStartElement(MACRO_ELEMENT_NAME);
                            w.WriteElementString("saveLocation", "Token");
                            w.WriteElementString("label", power.Name);
                            w.WriteElementString("autoExecute", "true");
                            w.WriteElementString("sortby", GetSortPriority(power));

                            // set colors based on usage limits
                            if (GetColors(power.Usage, out text, out background))
                            {
                                w.WriteElementString("fontColorKey", text);
                                w.WriteElementString("colorKey", background);
                            }

                            // start with the table and header
                            command.AppendLine("<table border=\"0\">");
                            command.AppendFormat("<tr bgcolor=\"{0}\" style=\"color: white;\">", background);
                            command.AppendLine();
                            command.AppendFormat("<th align=\"left\" style=\"font-size: 1.1em; padding: 2px 4px;\">{0}</th>", power.Name);
                            command.AppendLine();
                            command.AppendFormat("<td align=\"right\" valign=\"middle\" style=\"padding: 2px 4px;\"><i>{0}</i></td></tr>", power.Weapon == WEAPON_NONE ? "" : power.Weapon);
                            command.AppendLine();
                            command.AppendLine("</tr>");

                            // write compendium info
                            foreach (string line in power.CompendiumInfo)
                                command.AppendLine("<tr><td colspan=\"2\">" + line + "</td></tr>");

                            // when we have a weapon, put the macro in the weapon's group and include the rolls
                            if (power.Weapon != WEAPON_NONE)
                            {
                                w.WriteElementString("group", "Attacks - " + power.Weapon);

                                command.AppendFormat("<tr><td nowrap><b>[1d20+{0}]</b></td><td><b>vs. {1}</b></td></tr>", power.AttackBonus, power.Defense);
                                command.AppendLine();
                                command.AppendFormat("<tr><td nowrap>[{0}]</td><td>damage</td></tr>", power.DamageExpression);
                                command.AppendLine();
                            }

                            // finish up the command
                            command.AppendLine("</table>");

                            // write the command and end element
                            w.WriteElementString("command", command.ToString());
                            w.WriteEndElement(); // MACRO_ELEMENT_NAME
                        }

                        // write skill check macros
                        foreach (KeyValuePair<string, int> skill in skills)
                        {
                            // begin macro definition
                            w.WriteStartElement(MACRO_ELEMENT_NAME);
                            w.WriteElementString("saveLocation", "Token");
                            w.WriteElementString("label", skill.Key);
                            w.WriteElementString("autoExecute", "true");
                            w.WriteElementString("group", "Skills");
                            w.WriteElementString("command", string.Format("<p><b>{0} Check</b> [1d20+{1}]</p>", skill.Key, skill.Value));
                            w.WriteEndElement(); // MACRO_ELEMENT_NAME
                        }

                        w.WriteEndDocument();
                    }
                }
            });

            try
            {
                d.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// Worker thread that creates and reads a message queue for power notifications
        /// </summary>
        private void PowerNotifyThread()
        {
            powerThreadRunning = true;

            // Keep going util we are asked to quit
            while (!abortPowerThread)
            {
                IntPtr[] Handles = new IntPtr[2];

                Handles[0] = hMsgQ;
                Handles[1] = powerThreadAbortEvent;//powerThreadAbort.Handle;

                // Wait on two handles because the message queue will never
                // return from a read unless messages are posted.
                Wait res = (Wait)CEWaitForMultipleObjects(
                    (uint)Handles.Length,
                    Handles,
                    false,
                    INFINITE);

                // Exit the loop if an abort was requested
                if (abortPowerThread)
                {
                    break;
                }

                // Else
                switch (res)
                {
                // This must be an error - Exit loop and thread
                case Wait.Abandoned:
                    abortPowerThread = true;
                    break;

                // Timeout - Continue after a brief sleep
                case Wait.Failed:
                    Thread.Sleep(500);
                    break;

                // Read the message from the queue
                case Wait.Object:
                {
                    // Create a new structure to read into
                    PowerInfo Power = new PowerInfo();

                    uint PowerSize = (uint)Marshal.SizeOf(Power);
                    uint BytesRead = 0;
                    uint Flags     = 0;
                    // Read the message
                    if (CEReadMsgQueue(hMsgQ, ref Power, PowerSize,
                                       ref BytesRead, 0, ref Flags))
                    {
                        Int32  ret          = 0;
                        UInt32 mainlevelGet = 0;
                        // 9 = ac
                        // 8 = lowlv
                        // 0 = 5% or Less
                        // 1 = 5% to 30%
                        // 2 = 30% to 50%
                        // 3 = 50% or more
                        //-----------------------------------------------------------
                        // Acquire
                        //-----------------------------------------------------------
                        ret = Device.btGetMainBatteryLevel(ref mainlevelGet);

                        switch (mainlevelGet)
                        {
                        case 0:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 5;
                            break;

                        case 1:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 30;
                            break;

                        case 2:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 50;
                            break;

                        case 3:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 100;
                            break;

                        case 8:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 1;
                            break;

                        case 9:
                            Power.ACLineStatus       = ACLineStatus.OnLine;
                            Power.BatteryLifePercent = 100;
                            break;
                        }

                        //SYSTEM_POWER_STATUS_EX2 status2 = new SYSTEM_POWER_STATUS_EX2();
                        //if (GetSystemPowerStatusEx2(status2, (uint)Marshal.SizeOf(status2), false) == (uint)Marshal.SizeOf(status2))
                        //{
                        //    Power.BatteryLifePercent = status2.BatteryLifePercent;
                        //    Power.ACLineStatus = (ACLineStatus)status2.ACLineStatus;
                        //    Power.BatteryFlag = (BatteryFlags)status2.BatteryFlag;
                        //    Power.BatteryLifeTime = status2.BatteryLifeTime;
                        //    Power.BatteryFullLifeTime = status2.BatteryFullLifeTime;
                        //    Power.BackupBatteryLifeTime = status2.BackupBatteryLifeTime;
                        //    Power.BackupBatteryFullLifeTime = status2.BackupBatteryFullLifeTime;
                        //    Power.BackupBatteryFlag = status2.BackupBatteryFlag;
                        //    Power.BackupBatteryLifePercent = status2.BackupBatteryLifePercent;
                        //}

                        // Set value to zero if percentage is not known
                        //if ((Power.BatteryLifePercent < 0) || (Power.BatteryLifePercent > 100))
                        //    Power.BatteryLifePercent = 0;

                        //if ((Power.BackupBatteryLifePercent < 0) || (Power.BackupBatteryLifePercent > 100))
                        //    Power.BackupBatteryLifePercent = 0;


                        // Add the power structure to the queue so that the
                        // UI thread can get it
                        lock (powerQueue.SyncRoot)
                            powerQueue.Enqueue(Power);

                        // Fire an event to notify the UI
                        if (PowerNotify != null)
                        {
                            PowerNotify(this, null);
                        }
                    }

                    break;
                }

                case Wait.Object1:
                    EventModify(powerThreadAbortEvent, EventAction.EVENT_RESET);
                    abortPowerThread = true;
                    break;
                }
            }

            // Stop receiving power notifications
            if (hReq != IntPtr.Zero)
            {
                CEStopPowerNotifications(hReq);
            }


            // Close the message queue
            if (hMsgQ != IntPtr.Zero)
            {
                CECloseMsgQueue(hMsgQ);
            }

            powerThreadRunning = false;
        }
Exemple #19
0
        void init()
        {
            m_PowerMonitoring = new PowerMonitoring();
            m_LuoHaoList      = new List <int>();
            PowerInfo[] vPowerInfoArray = m_PowerMonitoring.GetPowerLuSu(App.PowerID1);
            // m_LS = vPowerInfoArray == null ? 0 : vPowerInfoArray.Length;

            for (int i = 1; i <= 14; i++)
            {
                if (i <= vPowerInfoArray.LongLength)
                {
                    PowerInfo vPowerInfo = vPowerInfoArray[i - 1];

                    m_LuoHaoList.Add(vPowerInfo.LuHao);

                    GroupBox vGroupBox = (GroupBox)FindName(string.Format("groupBox_{0}", i));
                    vGroupBox.Visibility = Visibility.Visible;
                    vGroupBox.Header     = vPowerInfo.MingCheng;
                    vGroupBox.Tag        = vPowerInfo.LuHao;


                    Image vImageSZ = (Image)FindName(string.Format("image_SZ{0}", i));
                    vImageSZ.Visibility = Visibility.Visible;
                    vImageSZ.Tag        = vPowerInfo.LuHao;

                    Label vLabelSZ = (Label)FindName(string.Format("label_SZ{0}", i));
                    vLabelSZ.Visibility = Visibility.Visible;
                    vLabelSZ.Tag        = vPowerInfo.LuHao;

                    Image vImageDY = (Image)FindName(string.Format("image_DY{0}", i));
                    vImageDY.Visibility = Visibility.Visible;

                    Label vLabelDY = (Label)FindName(string.Format("label_DY{0}", i));
                    vLabelDY.Visibility = Visibility.Visible;

                    Label vLabel_DY = (Label)FindName(string.Format("label_DY_{0}", i));
                    vLabel_DY.Visibility = Visibility.Visible;

                    Image vImageDL = (Image)FindName(string.Format("image_DL{0}", i));
                    vImageDL.Visibility = Visibility.Visible;

                    Label vLabelDL = (Label)FindName(string.Format("label_DL{0}", i));
                    vLabelDL.Visibility = Visibility.Visible;

                    Label vLabel_DL = (Label)FindName(string.Format("label_DL_{0}", i));
                    vLabel_DL.Visibility = Visibility.Visible;

                    CheckBox vCheckBox = (CheckBox)FindName(string.Format("checkBox_Switch{0}", i));
                    vCheckBox.Visibility = Visibility.Visible;
                    vCheckBox.Tag        = (byte)vPowerInfo.LuHao;

                    Label vlabel_Guan = (Label)FindName(string.Format("label_Guan_{0}", i));
                    vlabel_Guan.Visibility = Visibility.Visible;

                    Label vlabel_Kai = (Label)FindName(string.Format("label_Kai_{0}", i));
                    vlabel_Kai.Visibility = Visibility.Visible;
                }
                else
                {
                    GroupBox vGroupBox = (GroupBox)FindName(string.Format("groupBox_{0}", i));
                    vGroupBox.Visibility = Visibility.Hidden;

                    Image vImageSZ = (Image)FindName(string.Format("image_SZ{0}", i));
                    vImageSZ.Visibility = Visibility.Hidden;

                    Label vLabelSZ = (Label)FindName(string.Format("label_SZ{0}", i));
                    vLabelSZ.Visibility = Visibility.Hidden;

                    Image vImageDY = (Image)FindName(string.Format("image_DY{0}", i));
                    vImageDY.Visibility = Visibility.Hidden;

                    Label vLabelDY = (Label)FindName(string.Format("label_DY{0}", i));
                    vLabelDY.Visibility = Visibility.Hidden;

                    Label vLabel_DY = (Label)FindName(string.Format("label_DY_{0}", i));
                    vLabel_DY.Visibility = Visibility.Hidden;

                    Image vImageDL = (Image)FindName(string.Format("image_DL{0}", i));
                    vImageDL.Visibility = Visibility.Hidden;

                    Label vLabelDL = (Label)FindName(string.Format("label_DL{0}", i));
                    vLabelDL.Visibility = Visibility.Hidden;

                    Label vLabel_DL = (Label)FindName(string.Format("label_DL_{0}", i));
                    vLabel_DL.Visibility = Visibility.Hidden;

                    CheckBox vCheckBox = (CheckBox)FindName(string.Format("checkBox_Switch{0}", i));
                    vCheckBox.Visibility = Visibility.Hidden;

                    Label vlabel_Guan = (Label)FindName(string.Format("label_Guan_{0}", i));
                    vlabel_Guan.Visibility = Visibility.Hidden;

                    Label vlabel_Kai = (Label)FindName(string.Format("label_Kai_{0}", i));
                    vlabel_Kai.Visibility = Visibility.Hidden;
                }
            }
            m_IsInit = true;
        }
Exemple #20
0
        /// <summary>
        /// Worker thread that creates and reads a message queue for power notifications
        /// </summary>
        private void PowerNotifyThread()
        {
            powerThreadRunning = true;

            //TO DO : BY NONTAWAT
            PowerInfo Power = new PowerInfo();

            uint PowerSize = (uint)Marshal.SizeOf(Power);
            uint BytesRead = 0;
            uint Flags     = 0;
            int  delayTime = 0;

            //powerThreadAbort.WaitOne();
            // Keep going util we are asked to quit
            while (!abortPowerThread)
            {
                IntPtr[] Handles = new IntPtr[2];

                Handles[0] = hMsgQ;
                Handles[1] = powerThreadAbort.Handle;

                // Wait on two handles because the message queue will never
                // return from a read unless messages are posted.
                Wait res = (Wait)CEWaitForMultipleObjects(
                    (uint)Handles.Length,
                    Handles,
                    false,
                    INFINITE);

                //Wait res = (Wait)CEWaitForSingleObject(Handles[0],INFINITE);

                // Exit the loop if an abort was requested
                if (abortPowerThread)
                {
                    break;
                }

                // Else
                switch (res)
                {
                // This must be an error - Exit loop and thread
                case Wait.Abandoned:
                    abortPowerThread = true;
                    break;

                // Timeout - Continue after a brief sleep
                case Wait.Failed:
                    Thread.Sleep(200);
                    // Create a new structure to read into
                    delayTime++;

                    if (delayTime >= 20)
                    {
                        delayTime = 0;

                        Power = new PowerInfo();

                        PowerSize = (uint)Marshal.SizeOf(Power);
                        BytesRead = 0;
                        Flags     = 0;

                        // Read the message
                        if (CEReadMsgQueue(hMsgQ, ref Power, PowerSize,
                                           ref BytesRead, 0, ref Flags))
                        {
                            // Set value to zero if percentage is not known
                            if ((Power.BatteryLifePercent < 0) || (Power.BatteryLifePercent > 100))
                            {
                                Power.BatteryLifePercent = 0;
                            }

                            if ((Power.BackupBatteryLifePercent < 0) || (Power.BackupBatteryLifePercent > 100))
                            {
                                Power.BackupBatteryLifePercent = 0;
                            }

                            // Add the power structure to the queue so that the
                            // UI thread can get it
                            lock (powerQueue.SyncRoot)
                                powerQueue.Enqueue(Power);

                            // Fire an event to notify the UI
                            if (PowerNotify != null)
                            {
                                PowerNotify(this, null);
                            }
                        }

                        UInt32 mainlevelGet = 0;
                        // 9 = ac
                        // 8 = lowlv
                        // 0 = 5% or Less
                        // 1 = 5% to 30%
                        // 2 = 30% to 50%
                        // 3 = 50% or more
                        //-----------------------------------------------------------
                        // Acquire
                        //-----------------------------------------------------------
                        Device.btGetMainBatteryLevel(ref mainlevelGet);

                        switch (mainlevelGet)
                        {
                        case 0:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 5;
                            break;

                        case 1:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 30;
                            break;

                        case 2:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 50;
                            break;

                        case 3:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 100;
                            break;

                        case 8:
                            Power.ACLineStatus       = ACLineStatus.Offline;
                            Power.BatteryLifePercent = 1;
                            break;

                        case 9:
                            Power.ACLineStatus       = ACLineStatus.OnLine;
                            Power.BatteryLifePercent = 100;
                            break;
                        }
                    }
                    break;

                // Read the message from the queue
                case Wait.Object:
                {
                    // Create a new structure to read into
                    //PowerInfo Power = new PowerInfo();

                    //uint PowerSize = (uint)Marshal.SizeOf(Power);
                    //uint BytesRead = 0;
                    //uint Flags = 0;

                    // Read the message
                    if (CEReadMsgQueue(hMsgQ, ref Power, PowerSize,
                                       ref BytesRead, 0, ref Flags))
                    {
                        // Set value to zero if percentage is not known
                        if ((Power.BatteryLifePercent < 0) || (Power.BatteryLifePercent > 100))
                        {
                            Power.BatteryLifePercent = 0;
                        }

                        if ((Power.BackupBatteryLifePercent < 0) || (Power.BackupBatteryLifePercent > 100))
                        {
                            Power.BackupBatteryLifePercent = 0;
                        }

                        // Add the power structure to the queue so that the
                        // UI thread can get it
                        lock (powerQueue.SyncRoot)
                            powerQueue.Enqueue(Power);

                        // Fire an event to notify the UI
                        if (PowerNotify != null)
                        {
                            PowerNotify(this, null);
                        }
                    }

                    UInt32 mainlevelGet = 0;
                    // 9 = ac
                    // 8 = lowlv
                    // 0 = 5% or Less
                    // 1 = 5% to 30%
                    // 2 = 30% to 50%
                    // 3 = 50% or more
                    //-----------------------------------------------------------
                    // Acquire
                    //-----------------------------------------------------------
                    Device.btGetMainBatteryLevel(ref mainlevelGet);

                    switch (mainlevelGet)
                    {
                    case 0:
                        Power.ACLineStatus       = ACLineStatus.Offline;
                        Power.BatteryLifePercent = 5;
                        break;

                    case 1:
                        Power.ACLineStatus       = ACLineStatus.Offline;
                        Power.BatteryLifePercent = 30;
                        break;

                    case 2:
                        Power.ACLineStatus       = ACLineStatus.Offline;
                        Power.BatteryLifePercent = 50;
                        break;

                    case 3:
                        Power.ACLineStatus       = ACLineStatus.Offline;
                        Power.BatteryLifePercent = 100;
                        break;

                    case 8:
                        Power.ACLineStatus       = ACLineStatus.Offline;
                        Power.BatteryLifePercent = 1;
                        break;

                    case 9:
                        Power.ACLineStatus       = ACLineStatus.OnLine;
                        Power.BatteryLifePercent = 100;
                        break;
                    }

                    break;
                }

                default:
                {
                    //EventModify(powerThreadAbortEvent, EventAction.EVENT_SET);
                    break;
                }
                }
            }

            // Close the message queue
            if (hMsgQ != IntPtr.Zero)
            {
                CECloseMsgQueue(hMsgQ);
            }

            powerThreadRunning = false;
            /////////////////////////////////////////////COMMENT FOR RUNING IN EMULATOR
        }
Exemple #21
0
 private static extern bool CEReadMsgQueue(IntPtr hMsgQ, ref PowerInfo Power, uint BuffSize, ref uint BytesRead, uint Timeout, ref uint Flags);
Exemple #22
0
        ///// <summary>
        ///// Obtain the next PowerInfo structure
        ///// </summary>
        //public PowerInfo GetNextPowerInfo()
        //{
        //    // Get the next item from the queue in a thread safe manner
        //    lock (powerQueue.SyncRoot)
        //        return (PowerInfo)powerQueue.Dequeue();
        //}

        /// <summary>
        /// Worker thread that creates and reads a message queue for power notifications
        /// </summary>
        private void PowerNotifyThread()
        {
            powerThreadRunning = true;

            // Keep going util we are asked to quit
            while (!abortPowerThread)
            {
                IntPtr[] Handles = new IntPtr[2];

                Handles[0] = hMsgQ;
                Handles[1] = powerThreadAbort.Handle;

                // Wait on two handles because the message queue will never
                // return from a read unless messages are posted.
                Wait res = (Wait)CEWaitForMultipleObjects(
                    (uint)Handles.Length,
                    Handles,
                    false,
                    INFINITE);

                // Exit the loop if an abort was requested
                if (abortPowerThread)
                {
                    break;
                }

                // Else
                switch (res)
                {
                // This must be an error - Exit loop and thread
                case Wait.Abandoned:
                    abortPowerThread = true;
                    break;

                // Timeout - Continue after a brief sleep
                case Wait.Failed:
                    Thread.Sleep(500);
                    break;

                // Read the message from the queue
                case Wait.Object:
                {
                    // Create a new structure to read into
                    PowerInfo Power = new PowerInfo();

                    uint PowerSize = (uint)Marshal.SizeOf(Power);
                    uint BytesRead = 0;
                    uint Flags     = 0;

                    // Read the message
                    if (CEReadMsgQueue(hMsgQ, ref Power, PowerSize,
                                       ref BytesRead, 0, ref Flags))
                    {
                        // Set value to zero if percentage is not known
                        if ((Power.BatteryLifePercent < 0) || (Power.BatteryLifePercent > 100))
                        {
                            Power.BatteryLifePercent = 0;
                        }

                        if ((Power.BackupBatteryLifePercent < 0) || (Power.BackupBatteryLifePercent > 100))
                        {
                            Power.BackupBatteryLifePercent = 0;
                        }

                        //// Add the power structure to the queue so that the
                        //// UI thread can get it
                        //lock (powerQueue.SyncRoot)
                        //    powerQueue.Enqueue(Power);

                        // Fire an event to notify the UI
                        if (PowerNotify != null)
                        {
                            PowerNotify(this, new PowerEventArgs(Power));
                        }
                    }

                    break;
                }
                }
            }

            // Close the message queue
            if (hMsgQ != IntPtr.Zero)
            {
                CECloseMsgQueue(hMsgQ);
            }

            powerThreadRunning = false;
        }
Exemple #23
0
        /// <summary>
        /// Get Power Info
        /// </summary>
        /// <param name="pdatype"></param>
        /// <returns></returns>
        public static PowerInfo GetPowerInfo(PDAInfo.DevModel pdatype)
        {
            PowerInfo obj = null;

            try
            {
                int    mRetLen;
                string temp_str;
                ushort temp;
                byte[] mBatVoltageBuf = new byte[2];
                SystemPower.SYSTEM_POWER_STATUS_EX2 sSysPowerStatus = new SystemPower.SYSTEM_POWER_STATUS_EX2();
                int wlen = Marshal.SizeOf(sSysPowerStatus);
                mRetLen = SystemPower.GetSystemPowerStatusEx2(ref sSysPowerStatus, wlen, true);
                if (mRetLen < 1)
                {
                    return(null);                        // Get System Power Status Error
                }
                obj = new PowerInfo();
                if (sSysPowerStatus.ACLineStatus == SystemPower.AC_LINE_ONLINE)
                {
                    obj.PowerType = "AC power supply";
                }
                else
                {
                    obj.PowerType = "Battery power supply";
                }


                {
                    temp = (ushort)(((sSysPowerStatus.BatteryVoltage)) / 100); //2903
                    mBatVoltageBuf[0] = (byte)temp;                            //ProcessVoltageValue(temp);
                }

                mBatVoltageBuf[1] = (byte)(mBatVoltageBuf[0] % 10);
                mBatVoltageBuf[0] = (byte)(mBatVoltageBuf[0] / 10);
                temp_str          = string.Format("{0}.{1}V", mBatVoltageBuf[0], mBatVoltageBuf[1]);
                obj.Voltage       = temp_str;

                //lifePercent;
                temp = sSysPowerStatus.BatteryLifePercent;
                if ((temp >= 100) && (temp != SystemPower.BATTERY_PERCENTAGE_UNKNOWN))
                {
                    temp = 100;
                }
                if ((temp == SystemPower.BATTERY_PERCENTAGE_UNKNOWN) ||
                    (sSysPowerStatus.ACLineStatus == SystemPower.AC_LINE_ONLINE))
                {
                    obj.LifePercent = "Unknow";
                }
                else
                {
                    {
                        mBatVoltageBuf[0] = (byte)temp;
                    }

                    temp_str        = string.Format("{0} %", mBatVoltageBuf[0]);
                    obj.LifePercent = temp_str;
                }

                temp = sSysPowerStatus.BatteryFlag;
                switch ((uint)temp)
                {
                case SystemPower.BATTERY_FLAG_HIGH:
                    obj.BaterryStatus = "Discharge";
                    break;

                case SystemPower.BATTERY_FLAG_LOW:
                    obj.BaterryStatus = "Power lower";
                    break;

                case SystemPower.BATTERY_FLAG_CRITICAL:
                    obj.BaterryStatus = "Power extremely low";
                    break;

                case SystemPower.BATTERY_FLAG_CHARGING:
                    obj.BaterryStatus = "Charging";
                    break;

                case SystemPower.BATTERY_FLAG_NO_BATTERY:
                    obj.BaterryStatus = "No baterry";
                    break;

                case SystemPower.BATTERY_FLAG_UNKNOWN:
                default:
                    obj.BaterryStatus = "Unknown status";
                    break;
                }

                //backup battery
                obj.BakcupBatteryFlag = sSysPowerStatus.BackupBatteryFlag;
                if (obj.BakcupBatteryFlag != SystemPower.BATTERY_FLAG_NO_BATTERY ||
                    obj.BakcupBatteryFlag != sSysPowerStatus.BackupBatteryFlag)
                {
                    int    bval   = sSysPowerStatus.BackupBatteryVoltage;
                    byte[] tmpBuf = new byte[2];
                    tmpBuf[0] = (byte)(bval / 100);
                    tmpBuf[1] = (byte)(tmpBuf[0] / 10);
                    tmpBuf[0] = (byte)(tmpBuf[0] % 10);

                    obj.BakcupBatteryVoltage = Convert.ToSingle(string.Format("{0}.{1}", tmpBuf[1], tmpBuf[0]));

                    int bPer = sSysPowerStatus.BackupBatteryLifePercent;
                    if ((bPer > 100) && (bPer != SystemPower.BATTERY_PERCENTAGE_UNKNOWN))
                    {
                        bPer = 100;
                    }
                    if (bPer == SystemPower.BATTERY_PERCENTAGE_UNKNOWN)
                    {
                        obj.BakcupBatteryLifePercent = 0;
                    }
                    else
                    {
                        obj.BakcupBatteryLifePercent = (byte)bPer;
                    }
                }
            }
            catch { }

            return(obj);
        }
Exemple #24
0
        void init_DianYuan(int powerNum, PowerInfo[] powerInfo, List <int> LuoHaoList)
        {
            for (int i = 1; i <= 14; i++)
            {
                if (i <= powerInfo.LongLength)
                {
                    PowerInfo vPowerInfo = powerInfo[i - 1];

                    LuoHaoList.Add(vPowerInfo.LuHao);

                    GroupBox vGroupBox = (GroupBox)FindName(string.Format("groupBox_DY{0}_{1}", powerNum, i));
                    vGroupBox.Visibility = Visibility.Visible;
                    vGroupBox.Header     = vPowerInfo.MingCheng;
                    vGroupBox.Tag        = new int[] { powerNum, vPowerInfo.LuHao };

                    Image vImageSZ = (Image)FindName(string.Format("image_{0}_SZ{1}", powerNum, i));
                    vImageSZ.Visibility = Visibility.Visible;
                    vImageSZ.Tag        = new int[] { powerNum, vPowerInfo.LuHao };

                    Label vLabelSZ = (Label)FindName(string.Format("label_{0}_SZ{1}", powerNum, i));
                    vLabelSZ.Visibility = Visibility.Visible;
                    vLabelSZ.Tag        = new int[] { powerNum, vPowerInfo.LuHao };

                    Image vImageDY = (Image)FindName(string.Format("image_DY{0}_DY{1}", powerNum, i));
                    vImageDY.Visibility = Visibility.Visible;

                    Label vLabelDY = (Label)FindName(string.Format("label_DY{0}_DY{1}", powerNum, i));
                    vLabelDY.Visibility = Visibility.Visible;

                    Label vLabel_DY = (Label)FindName(string.Format("label_DY{0}_DY_{1}", powerNum, i));
                    vLabel_DY.Visibility = Visibility.Visible;

                    Image vImageDL = (Image)FindName(string.Format("image_DY{0}_DL{1}", powerNum, i));
                    vImageDL.Visibility = Visibility.Visible;

                    Label vLabelDL = (Label)FindName(string.Format("label_DY{0}_DL{1}", powerNum, i));
                    vLabelDL.Visibility = Visibility.Visible;

                    Label vLabel_DL = (Label)FindName(string.Format("label_DY{0}_DL_{1}", powerNum, i));
                    vLabel_DL.Visibility = Visibility.Visible;

                    CheckBox vCheckBox = (CheckBox)FindName(string.Format("checkBox_DY{0}_Switch{1}", powerNum, i));
                    vCheckBox.Visibility = Visibility.Visible;
                    vCheckBox.Tag        = new int[] { powerNum, vPowerInfo.LuHao };

                    Label vlabel_Guan = (Label)FindName(string.Format("label_DY{0}_Guan_{1}", powerNum, i));
                    vlabel_Guan.Visibility = Visibility.Visible;

                    Label vlabel_Kai = (Label)FindName(string.Format("label_DY{0}_Kai_{1}", powerNum, i));
                    vlabel_Kai.Visibility = Visibility.Visible;
                }
                else
                {
                    GroupBox vGroupBox = (GroupBox)FindName(string.Format("groupBox_DY{0}_{1}", powerNum, i));
                    vGroupBox.Visibility = Visibility.Hidden;

                    Image vImageSZ = (Image)FindName(string.Format("image_{0}_SZ{1}", powerNum, i));
                    vImageSZ.Visibility = Visibility.Hidden;


                    Label vLabelSZ = (Label)FindName(string.Format("label_{0}_SZ{1}", powerNum, i));
                    vLabelSZ.Visibility = Visibility.Hidden;


                    Image vImageDY = (Image)FindName(string.Format("image_DY{0}_DY{1}", powerNum, i));
                    vImageDY.Visibility = Visibility.Hidden;

                    Label vLabelDY = (Label)FindName(string.Format("label_DY{0}_DY{1}", powerNum, i));
                    vLabelDY.Visibility = Visibility.Hidden;

                    Label vLabel_DY = (Label)FindName(string.Format("label_DY{0}_DY_{1}", powerNum, i));
                    vLabel_DY.Visibility = Visibility.Hidden;
                    Image vImageDL = (Image)FindName(string.Format("image_DY{0}_DL{1}", powerNum, i));
                    vImageDL.Visibility = Visibility.Hidden;

                    Label vLabelDL = (Label)FindName(string.Format("label_DY{0}_DL{1}", powerNum, i));
                    vLabelDL.Visibility = Visibility.Hidden;

                    Label vLabel_DL = (Label)FindName(string.Format("label_DY{0}_DL_{1}", powerNum, i));
                    vLabel_DL.Visibility = Visibility.Hidden;

                    CheckBox vCheckBox = (CheckBox)FindName(string.Format("checkBox_DY{0}_Switch{1}", powerNum, i));
                    vCheckBox.Visibility = Visibility.Hidden;

                    Label vlabel_Guan = (Label)FindName(string.Format("label_DY{0}_Guan_{1}", powerNum, i));
                    vlabel_Guan.Visibility = Visibility.Hidden;

                    Label vlabel_Kai = (Label)FindName(string.Format("label_DY{0}_Kai_{1}", powerNum, i));
                    vlabel_Kai.Visibility = Visibility.Hidden;
                }
            }
        }
Exemple #25
0
 public PowerEventArgs(PowerInfo powerInfo)
 {
     this.PowerInfo = powerInfo;
 }
 private static string GetSortPriority(PowerInfo power)
 {
     switch (power.Usage)
     {
         case PowerUsage.AtWill:
             if (IsPowerBasicAttack(power.Name))
                 return "09";
             else
                 return "10";
         case PowerUsage.Encounter:
             return "20";
         case PowerUsage.Daily:
             return "30";
         default:
             return "99";
     }
 }
        /// <summary>
        /// Ports a power into a package
        /// </summary>
        /// <param name="targetPackage"></param>
        /// <param name="powerInfo"></param>
        /// <param name="additionalPowers">A list of additioanl powers that are referenced when this powerinfo is an import only power (prevent re-opening package)</param>
        /// <returns></returns>
        public static IEntry PortPowerIntoPackage(IMEPackage targetPackage, PowerInfo powerInfo, out IMEPackage sourcePackage)
        {
            if (powerInfo.IsCorrectedPackage)
            {
                var sourceData = MERUtilities.GetEmbeddedStaticFilesBinaryFile("correctedloadouts.powers." + powerInfo.PackageFileName);
                sourcePackage = MEPackageHandler.OpenMEPackageFromStream(new MemoryStream(sourceData));
            }
            else
            {
                sourcePackage = NonSharedPackageCache.Cache.GetCachedPackage(powerInfo.PackageFileName);
            }

            if (sourcePackage != null)
            {
                var sourceExport = sourcePackage.GetUExport(powerInfo.SourceUIndex);
                if (!sourceExport.InheritsFrom("SFXPower") || sourceExport.IsDefaultObject)
                {
                    throw new Exception("Wrong setup!");
                }
                if (sourceExport.Parent != null && sourceExport.Parent.ClassName != "Package")
                {
                    throw new Exception("Cannot port power - parent object is not Package!");
                }

                var    newParent = EntryExporter.PortParents(sourceExport, targetPackage);
                IEntry newEntry;
                if (powerInfo.ImportOnly)
                {
                    //Debug.WriteLine($"ImportOnly in file {targetPackage.FilePath}");
                    if (powerInfo.RequiresStartupPackage)
                    {
                        ThreadSafeDLCStartupPackage.AddStartupPackage(Path.GetFileNameWithoutExtension(powerInfo.PackageFileName));
                        if (powerInfo.IsCorrectedPackage)
                        {
                            // File must be added to MERFS DLC
                            var outP = Path.Combine(MERFileSystem.DLCModCookedPath, powerInfo.PackageFileName);
                            if (!File.Exists(outP))
                            {
                                sourcePackage.Save(outP, true);
                            }
                        }
                    }

                    newEntry = PackageTools.CreateImportForClass(sourceExport, targetPackage, newParent);

                    // Port in extra imports so the calling class can reference them as necessary.
                    foreach (var addlPow in powerInfo.AdditionalRequiredPowers)
                    {
                        var addlSourceExp = sourcePackage.FindExport(addlPow);
                        PackageTools.CreateImportForClass(addlSourceExp, targetPackage, EntryExporter.PortParents(addlSourceExp, targetPackage));
                    }
                }
                else
                {
#if DEBUG
                    // DEBUG ONLY-----------------------------------
                    //var defaults = sourceExport.GetDefaults();
                    //defaults.RemoveProperty("VFX");
                    //var vfx = defaults.GetProperty<ObjectProperty>("VFX").ResolveToEntry(sourcePackage) as ExportEntry;
                    //vxx.RemoveProperty("PlayerCrust");
                    //vfx.FileRef.GetUExport(1544).RemoveProperty("oPrefab");

                    ////vfx = defaults.FileRef.GetUExport(6211); // Prefab
                    ////vfx.RemoveProperty("WorldImpactVisualEffect");
                    //MERPackageCache cached = new MERPackageCache();
                    //EntryExporter.ExportExportToPackage(vfx, targetPackage, out newEntry, cached);
                    //PackageTools.AddReferencesToWorld(targetPackage, new [] {newEntry as ExportEntry});

                    //return null;


                    // END DEBUG ONLY--------------------------------
#endif
                    List <EntryStringPair> relinkResults = null;
                    if ((powerInfo.IsCorrectedPackage || (PackageTools.IsPersistentPackage(powerInfo.PackageFileName) && MERFileSystem.GetPackageFile(powerInfo.PackageFileName.ToLocalizedFilename()) == null)))
                    {
                        // Faster this way, without having to check imports
                        Dictionary <IEntry, IEntry> crossPCCObjectMap = new Dictionary <IEntry, IEntry>(); // Not sure what this is used for these days. SHould probably just be part of the method
                        relinkResults = EntryImporter.ImportAndRelinkEntries(EntryImporter.PortingOption.CloneAllDependencies, sourceExport, targetPackage,
                                                                             newParent, true, out newEntry, crossPCCObjectMap);
                    }
                    else
                    {
                        // MEMORY SAFE (resolve imports to exports)
                        MERPackageCache cache = new MERPackageCache();
                        relinkResults = EntryExporter.ExportExportToPackage(sourceExport, targetPackage, out newEntry, cache);
                    }

                    if (relinkResults.Any())
                    {
                        Debugger.Break();
                    }
                }

                return(newEntry);
            }
            return(null); // No package was found
        }
Exemple #28
0
 public PowerEventArgs(PowerInfo powerInfo)
 {
     this.PowerInfo = powerInfo;
 }
        internal static bool RandomizeExport(ExportEntry export, RandomizationOption option)
        {
            if (!CanRandomize(export))
            {
                return(false);
            }
#if DEBUG
            //if (!export.ObjectName.Name.Contains("HeavyWeaponMech"))
            //    return false;
#endif

            var powers = export.GetProperty <ArrayProperty <ObjectProperty> >("Powers");

            if (powers == null)
            {
                // This loadout has no powers!
                // Randomly give them some powers.
                if (ThreadSafeRandom.Next(1) == 0)
                {
                    // unlimited power
                    List <ObjectProperty> blankPows = new List <ObjectProperty>();
                    // Add two blanks. We'll strip blanks before writing it
                    blankPows.Add(new ObjectProperty(int.MinValue));
                    blankPows.Add(new ObjectProperty(int.MinValue));
                    powers = new ArrayProperty <ObjectProperty>(blankPows, "Powers");
                }
                else
                {
                    // Sorry mate no powers for you
                    return(false);
                }
            }

            var originalPowerUIndexes = powers.Where(x => x.Value > 0).Select(x => x.Value).ToList();

            foreach (var power in powers.ToList())
            {
                if (power.Value == 0)
                {
                    return(false);                  // Null entry in weapons list
                }
                IEntry existingPowerEntry = null;
                if (power.Value != int.MinValue)
                {
                    // Husk AI kinda depends on melee or they just kinda breath on you all creepy like
                    // We'll give them a chance to change it up though
                    existingPowerEntry = power.ResolveToEntry(export.FileRef);
                    if (existingPowerEntry.ObjectName.Name.Contains("Melee", StringComparison.InvariantCultureIgnoreCase) && ThreadSafeRandom.Next(2) == 0)
                    {
                        MERLog.Information($"Not changing melee power {existingPowerEntry.ObjectName.Name}");
                        continue; // Don't randomize power
                    }
                    if (PowersToNotSwap.Contains(existingPowerEntry.ObjectName.Name))
                    {
                        MERLog.Information($"Not changing power {existingPowerEntry.ObjectName.Name}");
                        continue; // Do not change this power
                    }
                }

                // DEBUG
                PowerInfo randomNewPower = Powers.RandomElement();
                //if (option.SliderValue < 0)
                //{
                //    randomNewPower = Powers.RandomElement();
                //}
                //else
                //{
                //    randomNewPower = Powers[(int)option.SliderValue];
                //}


                // Prevent krogan from getting a death power
                while (export.ObjectName.Name.Contains("Krogan", StringComparison.InvariantCultureIgnoreCase) && randomNewPower.Type == EPowerCapabilityType.Death)
                {
                    MERLog.Information(@"Re-roll no-death-power on krogan");
                    // Reroll. Krogan AI has something weird about it
                    randomNewPower = Powers.RandomElement();
                }

                // Prevent powerful enemies from getting super stat boosters
                while (randomNewPower.Type == EPowerCapabilityType.Buff && (
                           export.ObjectName.Name.Contains("Praetorian", StringComparison.InvariantCultureIgnoreCase) ||
                           export.ObjectName.Name.Contains("ShadowBroker", StringComparison.InvariantCultureIgnoreCase)))
                {
                    MERLog.Information(@"Re-roll no-buffs for powerful enemy");
                    randomNewPower = Powers.RandomElement();
                }

                #region YMIR MECH fixes
                if (export.ObjectName.Name.Contains("HeavyWeaponMech"))
                {
                    // Heavy weapon mech chooses named death powers so we cannot change these
                    // HeavyMechDeathExplosion is checked for existence. NormalExplosion for some reason isn't
                    if ((existingPowerEntry.ObjectName.Name == "SFXPower_HeavyMechNormalExplosion"))
                    {
                        MERLog.Information($@"YMIR mech power HeavyMechNormalExplosion cannot be randomized, skipping");
                        continue;
                    }

                    // Do not add buff powers to YMIR
                    while (randomNewPower.Type == EPowerCapabilityType.Buff)
                    {
                        MERLog.Information($@"Re-roll YMIR mech power to prevent potential enemy too difficult to kill softlock. Incompatible power: {randomNewPower.PowerName}");
                        randomNewPower = Powers.RandomElement();
                    }
                }
                #endregion

                // CHANGE THE POWER
                if (existingPowerEntry == null || randomNewPower.PowerName != existingPowerEntry.ObjectName)
                {
                    if (powers.Any(x => power.Value != int.MinValue && power.ResolveToEntry(export.FileRef).ObjectName == randomNewPower.PowerName))
                    {
                        continue; // Duplicate powers crash the game. It seems this code is not bulletproof here and needs changed a bit...
                    }
                    MERLog.Information($@"Changing power {export.ObjectName} {existingPowerEntry?.ObjectName ?? "(+New Power)"} => {randomNewPower.PowerName }");
                    // It's a different power.

                    // See if we need to port this in
                    var fullName = randomNewPower.PackageName + "." + randomNewPower.PowerName; // SFXGameContent_Powers.SFXPower_Hoops
                    var existingVersionOfPower = export.FileRef.FindEntry(fullName);

                    if (existingVersionOfPower != null)
                    {
                        // Power does not need ported in
                        power.Value = existingVersionOfPower.UIndex;
                    }
                    else
                    {
                        // Power needs ported in
                        power.Value = PortPowerIntoPackage(export.FileRef, randomNewPower, out _)?.UIndex ?? int.MinValue;
                    }

                    if (existingPowerEntry != null && existingPowerEntry.UIndex > 0 && PackageTools.IsPersistentPackage(export.FileRef.FilePath))
                    {
                        // Make sure we add the original power to the list of referenced memory objects
                        // so subfiles that depend on this power existing don't crash the game!
                        var world     = export.FileRef.FindExport("TheWorld");
                        var worldBin  = ObjectBinary.From <World>(world);
                        var extraRefs = worldBin.ExtraReferencedObjects.ToList();
                        extraRefs.Add(new UIndex(existingPowerEntry.UIndex));
                        worldBin.ExtraReferencedObjects = extraRefs.Distinct().ToArray(); // Filter out duplicates that may have already been in package
                        world.WriteBinary(worldBin);
                    }

                    foreach (var addlPow in randomNewPower.AdditionalRequiredPowers)
                    {
                        var existingPow = export.FileRef.FindEntry(addlPow);
                        //if (existingPow == null && randomNewPower.ImportOnly && sourcePackage != null)
                        //{
                        //    existingPow = PackageTools.CreateImportForClass(sourcePackage.FindExport(randomNewPower.PackageName + "." + randomNewPower.PowerName), export.FileRef);
                        //}

                        if (existingPow == null)
                        {
                            Debugger.Break();
                        }
                        powers.Add(new ObjectProperty(existingPow));
                    }
                }
            }

            // Strip any blank powers we might have added, remove any duplicates
            powers.RemoveAll(x => x.Value == int.MinValue);
            powers.ReplaceAll(powers.ToList().Distinct()); //tolist prevents concurrent modification in nested linq

            // DEBUG
#if DEBUG
            var duplicates = powers
                             .GroupBy(i => i.Value)
                             .Where(g => g.Count() > 1)
                             .Select(g => g.Key).ToList();
            if (duplicates.Any())
            {
                foreach (var dup in duplicates)
                {
                    Debug.WriteLine($"DUPLICATE POWER IN LOADOUT {export.FileRef.GetEntry(dup).ObjectName}");
                }
                Debugger.Break();
            }
#endif
            export.WriteProperty(powers);

            // Our precalculated map should have accounted for imports already, so we odn't need to worry about missing imports upstream
            // If this is not a master or localization file (which are often used for imports)
            // Change the number around so it will work across packages.
            // May need disabled if game becomes unstable.

            // We check if less than 10 as it's very unlikely there will be more than 10 loadouts in a non-persistent package
            // if it's > 10 it's likely already a memory-changed item by MER
            var pName = Path.GetFileName(export.FileRef.FilePath);
            if (export.indexValue < 10 && !PackageTools.IsPersistentPackage(pName) && !PackageTools.IsLocalizationPackage(pName))
            {
                export.ObjectName = new NameReference(export.ObjectName, ThreadSafeRandom.Next(2000));
            }

            if (originalPowerUIndexes.Any())
            {
                // We should ensure the original objects are still referenced so shared objects they have (vfx?) are kept in memory
                // Dunno if this actually fixes the problems...
                PackageTools.AddReferencesToWorld(export.FileRef, originalPowerUIndexes.Select(x => export.FileRef.GetUExport(x)));
            }

            return(true);
        }
Exemple #30
0
 private static extern bool CEReadMsgQueue(IntPtr hMsgQ, ref PowerInfo Power, uint BuffSize, ref uint BytesRead, uint Timeout, ref uint Flags);
Exemple #31
0
        ///// <summary>
        ///// Obtain the next PowerInfo structure
        ///// </summary>
        //public PowerInfo GetNextPowerInfo()
        //{
        //    // Get the next item from the queue in a thread safe manner
        //    lock (powerQueue.SyncRoot)
        //        return (PowerInfo)powerQueue.Dequeue();
        //}

        /// <summary>
        /// Worker thread that creates and reads a message queue for power notifications
        /// </summary>
        private void PowerNotifyThread()
        {
            powerThreadRunning = true;

            // Keep going util we are asked to quit
            while (!abortPowerThread)
            {
                IntPtr[] Handles = new IntPtr[2];

                Handles[0] = hMsgQ;
                Handles[1] = powerThreadAbort.Handle;

                // Wait on two handles because the message queue will never
                // return from a read unless messages are posted.
                Wait res = (Wait)CEWaitForMultipleObjects(
                                         (uint)Handles.Length,
                                         Handles,
                                         false,
                                         INFINITE);

                // Exit the loop if an abort was requested
                if (abortPowerThread)
                    break;

                // Else
                switch (res)
                {
                    // This must be an error - Exit loop and thread
                    case Wait.Abandoned:
                        abortPowerThread = true;
                        break;

                    // Timeout - Continue after a brief sleep
                    case Wait.Failed:
                        Thread.Sleep(500);
                        break;

                    // Read the message from the queue
                    case Wait.Object:
                        {
                            // Create a new structure to read into
                            PowerInfo Power = new PowerInfo();

                            uint PowerSize = (uint)Marshal.SizeOf(Power);
                            uint BytesRead = 0;
                            uint Flags = 0;

                            // Read the message
                            if (CEReadMsgQueue(hMsgQ, ref Power, PowerSize,
                                                ref BytesRead, 0, ref Flags))
                            {
                                // Set value to zero if percentage is not known
                                if ((Power.BatteryLifePercent < 0) || (Power.BatteryLifePercent > 100))
                                    Power.BatteryLifePercent = 0;

                                if ((Power.BackupBatteryLifePercent < 0) || (Power.BackupBatteryLifePercent > 100))
                                    Power.BackupBatteryLifePercent = 0;

                                //// Add the power structure to the queue so that the 
                                //// UI thread can get it
                                //lock (powerQueue.SyncRoot)
                                //    powerQueue.Enqueue(Power);

                                // Fire an event to notify the UI
                                if (PowerNotify != null)
                                    PowerNotify(this, new PowerEventArgs(Power));
                            }

                            break;
                        }
                }
            }

            // Close the message queue
            if (hMsgQ != IntPtr.Zero)
                CECloseMsgQueue(hMsgQ);

            powerThreadRunning = false;
        }