public static void BuildResource() { AssetDatabase.Refresh(); //执行依赖性打包 //资源最大等级 int maxLevel = allLevelAssets.Count; if (maxLevel == 0) { return; } //从最低等级开始打包 for (int level = 1; level <= maxLevel; level++) { BuildPipeline.PushAssetDependencies(); //获取不同等级的aaset Dictionary <string, AssetUnit> levelAssets = allLevelAssets[level]; //遍历该等级的所有asset打包 foreach (KeyValuePair <string, AssetUnit> pair in levelAssets) { //根据路径获取asset资源 Object asset = AssetDatabase.LoadMainAssetAtPath(pair.Value.mPath); if (null == asset) { DebugEx.LogError("load " + pair.Value.mPath + " failed!!!", "BuildResource", true); } //生成打包保存路径 string savePath = pair.Value.mPath.Insert(6, assetFilePath) + ResourceCommon.assetbundleFileSuffix; BuildCommon.CheckFolder(BuildCommon.getPath(savePath)); //打包名称去Asset //普通资源 if (pair.Value.mSuffix != "unity")//普通资源 { string assetName = pair.Value.mPath.Replace("Assets/", ""); //资源打包 if (!BuildPipeline.BuildAssetBundleExplicitAssetNames( new Object[] { asset }, new string[] { assetName }, savePath, options, buildPlatform)) { DebugEx.LogError("build assetbundle " + savePath + " failed!!!", "BuildResource", true); } } //场景资源,没有依赖场景的 else { AssetDatabase.Refresh(); BuildPipeline.PushAssetDependencies(); string error = BuildPipeline.BuildStreamedSceneAssetBundle(new string[] { pair.Value.mPath }, savePath, buildPlatform); if (error != "") { DebugEx.LogError(error, "BuildResource", true); } BuildPipeline.PopAssetDependencies(); Debug.Log("scene path" + pair.Value.mPath); //pair.Value.mPath } } } //popdepency依赖 for (int level = 1; level <= maxLevel; level++) { BuildPipeline.PopAssetDependencies(); } }
//------------------------------------------------------------------------------------------------------------------------ public override void OnTransportConnected(string msg) { base.OnTransportConnected(msg); SendQueue.Continue(); DebugEx.TraceLog("Transport connected"); }
//------------------------------------------------------------------------------------------------------------------------ #endregion #region Functions //------------------------------------------------------------------------------------------------------------------------ public override bool Initialize(mNodeConfig mNodeConfig, string PluginConfig, string UserConfig) { //init base if (base.Initialize(mNodeConfig, PluginConfig, UserConfig) == false) { return(false); } //set queue handler SendQueue.SetHandler(s => { if (SendToCloudPort != null) { SetPortState(SendToCloudPort.PortKey, s); } }); //init try { var ports = SerialPort.GetPortNames(); DebugEx.TraceLog("Serial Ports found: " + string.Join(",", ports)); var port = ports?.Where(p => p.Contains("USB")).FirstOrDefault(); if (port != null && !port.IsNullOrEmpty()) { DebugEx.TraceLog("Selected Port: " + port); //replace this with entry from conf mySerial = new SerialPort(port, 9600); if (mySerial.IsOpen) { try { mySerial.Close(); mySerial.Dispose(); } catch { } } mySerial.DataReceived += MySerial_DataReceived; mySerial.ErrorReceived += MySerial_ErrorReceived; mySerial.ReadTimeout = 2000; mySerial.NewLine = "\r\n"; mySerial.Open(); _IsRunning = true; StartSerialPortReadThread(); SendQueue.Start(); SendQueue.Pause(); } else { DebugEx.Assert("The USB port does not exist"); } } catch (Exception ex) { DebugEx.Assert(ex, "Could not init"); } //setup SetupSerialPortThings(); //done return(true); }
private void OnTransportConnectedCb(NodeLibrary.Transport Transport, string msg) { DebugEx.TraceLog("OnConnected transport=" + Transport.ToString() + " msg=" + msg); }
public override void StartLoad() { DebugEx.Info("Loading KIS global settings..."); ConfigAccessor.ReadFieldsInType(typeof(KISAddonConfig), instance: null); ConfigAccessor.ReadFieldsInType(typeof(ModuleKISInventory), instance: null); }
private void OnTransportErrorCb(NodeLibrary.Transport Transport, TransportErrors Error, string msg) { DebugEx.TraceLog("OnTransportError transport=" + Transport.ToString() + " msg=" + msg); }
private void OnUnexpectedMessageCb(object message) { DebugEx.TraceLog("Unexpected message received."); }
public override SegmentMap LoadImageBytes(IPlatform platform, byte[] rawImage, Address addrPreferred) { var segMap = AllocateMemoryAreas( Segments .Where(p => IsLoadable(p.p_pmemsz, p.p_type)) .Select(p => Tuple.Create( Address.Ptr32((uint)p.p_vaddr), (uint)p.p_pmemsz))); foreach (var ph in Segments) { DebugEx.Inform(ElfImageLoader.trace, "ph: addr {0:X8} filesize {0:X8} memsize {0:X8}", ph.p_vaddr, ph.p_filesz, ph.p_pmemsz); if (!IsLoadable(ph.p_pmemsz, ph.p_type)) { continue; } var vaddr = Address.Ptr32((uint)ph.p_vaddr); segMap.TryGetLowerBound(vaddr, out var mem); if (ph.p_filesz > 0) { Array.Copy( rawImage, (long)ph.p_offset, mem.Bytes, vaddr - mem.BaseAddress, (long)ph.p_filesz); } } var segmentMap = new SegmentMap(addrPreferred); if (Sections.Count > 0) { foreach (var section in Sections) { if (string.IsNullOrEmpty(section.Name) || section.Address == null) { continue; } if (segMap.TryGetLowerBound(section.Address, out var mem) && section.Address < mem.EndAddress) { AccessMode mode = AccessModeOf(section.Flags); var seg = segmentMap.AddSegment(new ImageSegment( section.Name, section.Address, mem, mode) { Size = (uint)section.Size }); seg.Designer = CreateRenderer(section, machine); } else { //$TODO: warn } } } else { // There are stripped ELF binaries with 0 sections. If we have one // create a pseudo-section from the segMap. foreach (var segment in segMap) { var imgSegment = new ImageSegment( segment.Value.BaseAddress.GenerateName("seg", ""), segment.Value, AccessMode.ReadExecute) //$TODO: writeable segments. { Size = (uint)segment.Value.Length, }; segmentMap.AddSegment(imgSegment); } } segmentMap.DumpSections(); return(segmentMap); }
/// <summary> /// Executes the change operations annotated into this instance against the underlying /// database as a single logical operation that either succeeds or fails as a whole. /// <para>Once this method is executed all the submitted operations are disposed /// automatically.</para> /// </summary> public void ExecuteChanges() { if (IsDisposed) { throw new ObjectDisposedException(this.ToString()); } lock (MasterLock) { ChangeEntries = new List <ChangeEntry>(); try { DebugEx.IndentWriteLine("\n--- Executing changes for '{0}'...".FormatWith(this)); Link.Transaction.Start(); foreach (var op in UberOperations) { op.OnExecute(); } Link.Transaction.Commit(); DebugEx.Unindent(); DebugEx.IndentWriteLine("\n--- Refreshing changes for '{0}'...".FormatWith(this)); ChangeEntries.Reverse(); foreach (var entry in ChangeEntries) { entry.MetaEntity.Completed = false; } foreach (var entry in ChangeEntries) { if (entry.MetaEntity.Completed) { continue; } if (entry.ChangeType == ChangeType.Delete) { continue; } if (entry.MetaEntity.UberMap == null) { entry.UberMap.RefreshNow(entry.Entity); } else { entry.UberMap.CompleteMembers(entry.MetaEntity); } } } catch (Exception e) { DebugEx.Unindent(); DebugEx.IndentWriteLine("\n--- Reverting changes for '{0}' because '{1}'...", this, e.ToDisplayString()); Link.Transaction.Abort(); Link.Dispose(); ChangeEntries.Reverse(); foreach (var entry in ChangeEntries) { switch (entry.ChangeType) { case ChangeType.Delete: entry.UberMap.Attach(entry.Entity); break; case ChangeType.Insert: entry.UberMap.Detach(entry.Entity); break; } } foreach (var entry in ChangeEntries) { entry.MetaEntity.Completed = false; } foreach (var entry in ChangeEntries) { if (entry.MetaEntity.Completed) { continue; } if (entry.ChangeType == ChangeType.Delete) { continue; } entry.UberMap.RefreshNow(entry.Entity); } throw; } finally { ClearChangeEntries(setToNull: true); DiscardChanges(); DebugEx.Unindent(); } } }
/// <summary> /// Determines whether menu is visible. /// </summary> /// <returns><c>true</c> if menu is visible; otherwise, <c>false</c>.</returns> private bool IsMenuVisible() { DebugEx.Verbose("MainWindowScript.IsMenuVisible()"); return(Global.mainMenuScript.gameObject.activeSelf); }
/// <summary> /// Loads dock widgets layout. /// </summary> private void LoadDockWidgets() { DebugEx.Verbose("MainWindowScript.LoadDockWidgets()"); ServersDockWidgetScript.Create().InsertToDockingArea(Global.dockingAreaScript); }
/// <summary> /// Creates the content. /// </summary> /// <param name="contentTransform">Content transform.</param> /// <param name="width">Width of content.</param> /// <param name="height">Height of content.</param> protected override void CreateContent(Transform contentTransform, out float width, out float height) { DebugEx.VerboseFormat("MainWindowScript.CreateContent(contentTransform = {0})", contentTransform); width = 0f; height = 0f; //*************************************************************************** // MainMenu GameObject //*************************************************************************** #region MainMenu GameObject GameObject mainMenu = new GameObject("MainMenu"); Utils.InitUIObject(mainMenu, contentTransform); #if MENU_BUTTON_TO_SHOW_MENU mainMenu.SetActive(false); #endif //=========================================================================== // RectTransform Component //=========================================================================== #region RectTransform Component RectTransform mainMenuTransform = mainMenu.AddComponent <RectTransform>(); Utils.AlignRectTransformTopStretch(mainMenuTransform, MAIN_MENU_HEIGHT); #endregion //=========================================================================== // MainMenuScript Component //=========================================================================== #region MainMenuScript Component Global.mainMenuScript = mainMenu.AddComponent <MainMenuScript>(); #endregion #endregion //*************************************************************************** // Toolbar GameObject //*************************************************************************** #region Toolbar GameObject GameObject toolbar = new GameObject("Toolbar"); Utils.InitUIObject(toolbar, contentTransform); #if MENU_BUTTON_TO_SHOW_MENU toolbar.SetActive(false); #endif //=========================================================================== // RectTransform Component //=========================================================================== #region RectTransform Component RectTransform toolbarTransform = toolbar.AddComponent <RectTransform>(); Utils.AlignRectTransformTopStretch(toolbarTransform, TOOLBAR_HEIGHT, MAIN_MENU_HEIGHT); #endregion //=========================================================================== // ToolbarScript Component //=========================================================================== #region ToolbarScript Component Global.toolbarScript = toolbar.AddComponent <ToolbarScript>(); #endregion #endregion //*************************************************************************** // DockingArea GameObject //*************************************************************************** #region DockingArea GameObject GameObject dockingArea = new GameObject("DockingArea"); Utils.InitUIObject(dockingArea, contentTransform); //=========================================================================== // RectTransform Component //=========================================================================== #region RectTransform Component RectTransform dockingAreaTransform = dockingArea.AddComponent <RectTransform>(); #if MENU_BUTTON_TO_SHOW_MENU Utils.AlignRectTransformStretchStretch(dockingAreaTransform); #else Utils.AlignRectTransformStretchStretch(dockingAreaTransform, 0f, MAIN_MENU_HEIGHT + TOOLBAR_HEIGHT, 0f, 0f); #endif #endregion //=========================================================================== // DockingAreaScript Component //=========================================================================== #region DockingAreaScript Component Global.dockingAreaScript = dockingArea.AddComponent <DockingAreaScript>(); #endregion #endregion #if HANDLE_ESCAPE_BUTTON EscapeButtonListenerScript.PushHandlerToTop(this); #endif // TODO: [Major] It looks bad on start up on Android LoadDockWidgets(); }
//------------------------------------------------------------------------------------------------------------------------- private void YPChannel_OnOpenEvent(YPChannel.Channel Channel) { DebugEx.TraceLog($"RemoteNode : Openned channel with node. (ip:{IPAddress} port:{RemotePort} nodekey:{RemoteNodeKey})"); //raise events OnChannelOpen?.Invoke(this); }
public void ReadConfig(string xmlFilePath) { ResourceUnit xmlFileUnit = ResourceManager.Instance.LoadImmediate(xmlFilePath, EResourceType.ASSET); TextAsset xmlFile = xmlFileUnit.Asset as TextAsset; if (!xmlFile) { DebugEx.LogError("unable to load " + xmlFilePath); } mXmlDoc = new XmlDocument(); mXmlDoc.LoadXml(xmlFile.text); XmlNodeList infoNodeList = mXmlDoc.SelectSingleNode("MapLoadCfg").ChildNodes; for (int i = 0; i < infoNodeList.Count; i++) { var node = (infoNodeList[i] as XmlElement).GetAttributeNode("MapID"); if (node == null) { continue; } string mapId = node.InnerText; MapInfo mapInfo = new MapInfo(); mapInfo.Id = Convert.ToUInt32(mapId); foreach (XmlElement element in infoNodeList[i].ChildNodes) { switch (element.Name) { case "LoadScene": mapInfo.Scene = Convert.ToString(element.InnerText); break; case "MiniMap": mapInfo.MiniMap = Convert.ToString(element.InnerText); break; case "NameCn": mapInfo.Name = Convert.ToString(element.InnerText); break; case "ACameraPos": mapInfo.ACameraPos = Convert.ToString(element.InnerText); break; case "BCameraPos": mapInfo.BCameraPos = Convert.ToString(element.InnerText); break; case "ShowPic": mapInfo.ShowPic = Convert.ToString(element.InnerText); break; case "PlayerNum": mapInfo.PlayerNum = Convert.ToInt32(element.InnerText); break; case "PlayerMode": mapInfo.PlayerMode = Convert.ToString(element.InnerText); break; case "CameraType": mapInfo.CameraType = Convert.ToInt32(element.InnerText); break; case "IsAI": mapInfo.IsAI = Convert.ToBoolean(Convert.ToInt32(element.InnerText)); break; case "IsNormal": mapInfo.IsNormal = Convert.ToBoolean(Convert.ToInt32(element.InnerText)); break; case "IsRank": mapInfo.IsRank = Convert.ToBoolean(Convert.ToInt32(element.InnerText)); break; case "IsTrain": mapInfo.IsTrain = Convert.ToBoolean(Convert.ToInt32(element.InnerText)); break; case "IsDungeon": mapInfo.IsDungeon = Convert.ToBoolean(Convert.ToInt32(element.InnerText)); break; case "ShopID": mapInfo.ShopId = Convert.ToInt32(element.InnerText); break; } } mMapDic.Add(mapInfo.Id, mapInfo); } }
/// <summary>Localizes the <see cref="PartModule"/> items.</summary> /// <remarks> /// <para> /// The localizable items must be declared as non-static public members. The following items are /// supported: /// <list type="bullet"> /// <item> /// <see cref="KSPField"/>. This type may have multiple localization items: for <c>guiName</c> /// (spec=<c>null</c>) and for <c>guiUnits</c> (spec=<see cref="KspFieldUnitsSpec"/>). /// </item> /// <item><see cref="KSPEvent"/>.</item> /// <item><see cref="KSPAction"/>.</item> /// </list> /// </para> /// <para> /// The original KSP attributes don't need to specify <c>guiName</c> field since it will be /// overwritten anyways. However, it's a good idea to give a default value just in case. /// </para> /// <para> /// This method can be called at any time during the module's life. However, the /// <see cref="IsLocalizableModule.LocalizeModule"/> method looks the most appropriate. /// </para> /// </remarks> /// <param name="module">The module instance to localize.</param> /// <example><code source="Examples/GUIUtils/LocalizationLoader-Examples.cs" region="LocalizationLoaderDemo1"/></example> /// <example><code source="Examples/GUIUtils/LocalizationLoader-Examples.cs" region="LocalizationLoaderDemo2"/></example> /// <seealso cref="LocalizableItemAttribute"/> /// <seealso cref="IsLocalizableModule"/> /// <include file="KSPAPI_HelpIndex.xml" path="//item[@name='T:KSPField']"/> /// <include file="KSPAPI_HelpIndex.xml" path="//item[@name='T:KSPEvent']"/> /// <include file="KSPAPI_HelpIndex.xml" path="//item[@name='T:KSPAction']"/> public static void LoadItemsInModule(PartModule module) { // This method may look ugly and over complicated, but it's because if it's performance // optimized. On a vessel with 100 parts this method can be called 1000 times. So every // millisecond matters. // Go thru all the KSP fields that may have the localizable content. foreach (var field in module.Fields) { var locItems = (LocalizableItemAttribute[])field.FieldInfo.GetCustomAttributes( typeof(LocalizableItemAttribute), false); foreach (var locItem in locItems) { if (string.IsNullOrEmpty(locItem.tag)) { continue; // Localization is disabled for the item. } if (string.IsNullOrEmpty(locItem.spec)) { field.guiName = locItem.GetLocalizedString(); } else if (locItem.spec == KspFieldUnitsSpec) { field.guiUnits = locItem.GetLocalizedString(); } else { DebugEx.Warning("Bad specialization tag for field {0}.{1}: {2}", field.FieldInfo.FieldType.FullName, field.FieldInfo.Name, locItem.spec); } } } // Go thru all the KSP events that may have the localizable content. foreach (var @event in module.Events) { var info = module.GetType().GetMethod(@event.name); if (info != null) { var locItems = (LocalizableItemAttribute[])info.GetCustomAttributes( typeof(LocalizableItemAttribute), false); if (locItems.Length > 0 && !string.IsNullOrEmpty(locItems[0].tag)) { @event.guiName = locItems[0].GetLocalizedString(); } } } // Go thru all the KSP actions that may have the localizable content. foreach (var action in module.Actions) { var info = module.GetType().GetMethod(action.name); if (info != null) { var locItems = (LocalizableItemAttribute[])info.GetCustomAttributes( typeof(LocalizableItemAttribute), false); if (locItems.Length > 0 && !string.IsNullOrEmpty(locItems[0].tag)) { action.guiName = locItems[0].GetLocalizedString(); } } } }
public static string FindLocalIpAddress() { #if NETFX try { //check connection if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { return(null); } //find ethernet foreach (var iface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { if (iface.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up) { if (iface.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet) { if (iface.GetIPProperties().GatewayAddresses.Count > 0) { var addrs = iface.GetIPProperties().UnicastAddresses; if (addrs != null) { foreach (var ip in addrs) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { return(ip.Address.ToStringInvariant()); } } } } } } } //find wifi foreach (var iface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { if (iface.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up) { if (iface.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Wireless80211) { if (iface.GetIPProperties().GatewayAddresses.Count > 0) { var addrs = iface.GetIPProperties().UnicastAddresses; if (addrs != null) { foreach (var ip in addrs) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { return(ip.Address.ToStringInvariant()); } } } } } } } //get a valid address var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { return(ip.ToString()); } } } catch (Exception ex) { DebugEx.TraceWarning("Could not find internal ip (" + ex.Message + ")"); } #endif //not found return("127.0.0.1"); }
/// <summary> /// Attempt to fuse together the definitions of all the identifiers in <paramref name="sids"/>. /// </summary> /// <param name="sids"></param> /// <returns>A new expression if the fusion succeeded, otherwise null.</returns> private Expression FuseIdentifiers(params SsaIdentifier[] sids) { // Are all the definitions of the ids in the same basic block? If they're // not, we give up. if (!AllSame(sids, (a, b) => a.DefStatement.Block == b.DefStatement.Block && a.Identifier.Storage.GetType() == b.Identifier.Storage.GetType())) { return(null); } var dtWide = PrimitiveType.CreateWord(sids.Sum(s => s.Identifier.DataType.BitSize)); Identifier idWide = GenerateWideIdentifier(dtWide, sids); var ass = sids.Select(s => s.DefStatement.Instruction as Assignment).ToArray(); if (ass.All(a => a != null)) { // All assignments. Are they all slices? var slices = ass.Select(AsSlice).ToArray(); if (slices.All(s => s != null)) { if (AllSame(slices, (a, b) => cmp.Equals(a.Expression, b.Expression)) && AllAdjacent(slices)) { trace.Verbose("Prpr: Fusing slices in {0}", ssa.Procedure.Name); trace.Verbose("{0}", string.Join(Environment.NewLine, ass.Select(a => $" {a}"))); return(RewriteSeqOfSlices(dtWide, sids, slices)); } } trace.Warn("Prpr: Couldn't fuse assignments in {0}", ssa.Procedure.Name); trace.Warn("{0}", string.Join(Environment.NewLine, ass.Select(a => $" {a}"))); return(null); } if (idWide != null) { if (sids.All(s => s.DefStatement.Instruction is DefInstruction)) { // All the identifiers are generated by def statements. return(RewriteSeqOfDefs(sids, idWide)); } var phis = sids.Select(s => s.DefStatement.Instruction as PhiAssignment).ToArray(); if (phis.All(a => a != null)) { // We have a sequence of phi functions return(RewriteSeqOfPhi(sids, phis, idWide)); } if (sids[0].DefStatement.Instruction is CallInstruction call && sids.All(s => s.DefStatement == sids[0].DefStatement)) { // All of the identifiers in the sequence were defined by the same call. return(RewriteSeqDefinedByCall(sids, call, idWide)); } } DebugEx.Warn(trace, "Prpr: Couldn't fuse statements in {0}", ssa.Procedure.Name); DebugEx.Warn(trace, "{0}", string.Join(Environment.NewLine, sids.Select(s => $" {s.DefStatement}"))); return(null); }
//private ToolbarScript mScript; /// <summary> /// Initializes a new instance of the <see cref="UI.Windows.MainWindow.Toolbar.ToolbarUI"/> class. /// </summary> /// <param name="script">Toolbar script.</param> public ToolbarUI(ToolbarScript script) { DebugEx.VerboseFormat("Created ToolbarUI(script = {0}) object", script); //mScript = script; }
private PlegmaApiMsg OnUnexpectedRequestCb(object request) { DebugEx.TraceLog("Unexpected request received."); return(null); }
/// <summary> /// Setup user interface. /// </summary> public void SetupUI() { DebugEx.Verbose("ToolbarUI.SetupUI()"); CreateUI(); }
public void Start() { YConfig = Config.Init(); ActiveCfg = YConfig.GetActiveConf(); NodeConfig conf = new NodeConfig() { uuid = ActiveCfg.Uuid, Name = "SkyWriter Node", MqttBrokerHostname = ActiveCfg.MqttBrokerHostname, MqttUseSsl = ActiveCfg.MqttUseSsl, YpServer = ActiveCfg.ApiServer, YpchannelPort = ActiveCfg.YpchannelPort, SecureYpc = ActiveCfg.YpchannelSecure, FrontendServer = ActiveCfg.FrontendServer, CanSolveGraphs = false,// deactivate for GrovePi }; //prepare pairing module var pairmodule = new Yodiwo.NodeLibrary.Pairing.NancyPairing.NancyPairing(); //create node node = new Yodiwo.NodeLibrary.Node(conf, pairmodule, null, null, NodeGraphManager: null ); Helper.node = node; //set TransPort node.Transport = transport; //register callbacks for grovepi node node.OnChangedState += OnChangedStateCb; node.OnNodePaired += OnPaired; node.OnTransportConnected += OnTransportConnectedCb; node.OnTransportDisconnected += OnTransportDisconnectedCb; node.OnTransportError += OnTransportErrorCb; node.OnUnexpectedMessage += OnUnexpectedMessageCb; node.OnThingActivated += OnThingActivatedCb; node.OnThingDeactivated += OnThingDeactivatedCb; //register port event handlers //start Pairing if (String.IsNullOrWhiteSpace(ActiveCfg.NodeKey)) { DebugEx.TraceLog("Starting pairing procedure."); var pair = node.StartPairing(ActiveCfg.FrontendServer, null, ActiveCfg.LocalWebServer).GetResults(); } else { node.SetupNodeKeys(ActiveCfg.NodeKey, ActiveCfg.NodeSecret.ToSecureString()); DebugEx.TraceLog("Node already paired: NodeKey = " + ActiveCfg.NodeKey + ", NodeSecret = ", ActiveCfg.NodeSecret); } //add things Helper.CreateThings(this.pysharp, node); //connect node.Connect(); }
/// <summary> /// Creates user interface. /// </summary> private void CreateUI() { DebugEx.Verbose("ToolbarUI.CreateUI()"); // TODO: [Minor] Implement Create UI }
/// <summary> /// Refuels kerbal's EVA pack up to the maximum, and decreases canister reserve. /// </summary> /// <param name="item">Item to get fuel from.</param> void RefillEvaPack(KIS_Item item) { var p = item.inventory.part; if (!p.isVesselEVA) { HostedDebugLog.Error(this, "Cannot refill non-EVA kerbal"); return; } var stockInventory = p.FindModuleImplementing <ModuleInventoryPart>(); if (stockInventory == null) { HostedDebugLog.Error(this, "Cannot find stock inventory module"); return; } var evaModule = p.FindModuleImplementing <KerbalEVA>(); var propellantResourceField = evaModule.GetType() .GetField("propellantResource", BindingFlags.Instance | BindingFlags.NonPublic); if (propellantResourceField == null) { HostedDebugLog.Error(this, "Cannot access internal KerbalEVA logic: propellant field"); return; } var propellantResource = propellantResourceField.GetValue(evaModule) as PartResource; if (propellantResource == null) { HostedDebugLog.Error(this, "Cannot access internal KerbalEVA logic: propellant field value"); return; } var needAmount = propellantResource.maxAmount - propellantResource.amount; if (needAmount <= double.Epsilon) { ScreenMessaging.ShowPriorityScreenMessage(NoNeedToRefillJetpackMsg); return; } var canisterFuelResource = GetCanisterFuelResource(item); if (canisterFuelResource.amount < double.Epsilon) { ScreenMessaging.ShowPriorityScreenMessage(CanisterIsEmptyMsg); UISounds.PlayBipWrong(); return; } var canProvide = Math.Min(needAmount, canisterFuelResource.amount); var storedResources = stockInventory.storedParts.Values.SelectMany(x => x.snapshot.resources) .Where(x => x.resourceName == StockResourceNames.EvaPropellant) .ToArray(); if (storedResources.Length == 0) { UISounds.PlayBipWrong(); DebugEx.Error("Unexpectedly no EVA resource parts found in: {0}", evaModule); return; } item.UpdateResource(_mainResourceName, -canProvide, isAmountRelative: true); p.TransferResource(propellantResource, canProvide, p); var distributeAmount = canProvide; for (var i = 0; i < storedResources.Length && canProvide > double.Epsilon; i++) { var resource = storedResources[i]; var canAccept = resource.maxAmount - resource.amount; if (canAccept <= double.Epsilon) { continue; } var refillAmount = Math.Min(canAccept, distributeAmount); resource.amount += refillAmount; resource.UpdateConfigNodeAmounts(); distributeAmount -= refillAmount; } if (canProvide < needAmount) { ScreenMessaging.ShowPriorityScreenMessage(JetpackPartiallyRefueledMsg.Format(canProvide)); } else { ScreenMessaging.ShowPriorityScreenMessage(JetpackFullyRefueledMsg); } UISoundPlayer.instance.Play(refuelSndPath); }
public List <ImageSymbol> LoadEntryPoints( uint offEntryTable, NeSegment [] segments, Dictionary <int, string> names, IProcessorArchitecture arch) { DebugEx.Inform(trace, "== Loading entry points from offset {0:X}", offEntryTable); var rdr = new LeImageReader(RawImage, offEntryTable); var entries = new List <ImageSymbol>(); int bundleOrdinal = 1; int nextbundleOrdinal = 1; for (; ;) { var cBundleEntries = rdr.ReadByte(); if (cBundleEntries == 0) { break; } nextbundleOrdinal = bundleOrdinal + cBundleEntries; var segNum = rdr.ReadByte(); if (segNum != 0) { // If segNum had been 0, it would have // meant that all we want to do is allocate // (skip) some ordinal numbers. Since it wasn't 0, // we proceed to generate entry points. for (int i = 0; i < cBundleEntries; ++i) { byte flags = rdr.ReadByte(); (byte iSeg, ushort offset)entry; if (segNum == 0xFF) { entry = ReadMovableSegmentEntry(rdr); } else { entry = ReadFixedSegmentEntry(rdr, segNum); } var seg = segments[entry.iSeg - 1]; var addr = seg.Address + entry.offset; var ep = ImageSymbol.Procedure(arch, addr); ep.Ordinal = bundleOrdinal + i; if (names.TryGetValue(bundleOrdinal + i, out string name)) { ep.Name = name; } ep.Type = SymbolType.Procedure; ep.ProcessorState = arch.CreateProcessorState(); imageSymbols[ep.Address] = ep; entries.Add(ep); DebugEx.Verbose(trace, " {0:X2} {1} {2} - {3}", segNum, ep.Address, ep.Name, ep.Ordinal); } } else { // We have unused entries, they have to occupy a space in the resulting entries table. entries.AddRange(Enumerable.Range(0, cBundleEntries).Select(x => (ImageSymbol)null)); } bundleOrdinal = nextbundleOrdinal; } return(entries); }
//------------------------------------------------------------------------------------------------------------------------ private void MySerial_DataReceived(object sender, SerialDataReceivedEventArgs e) { DebugEx.TraceLog($"{sender} sent {e.EventType}"); }
public BfxParentOrderTransaction(BfTradingMarket market, BfParentOrderRequest request) { DebugEx.EnterMethod(); _market = market; State = new BfxParentOrderTransactionState(_market, request); }
//------------------------------------------------------------------------------------------------------------------------ public override void OnTransportDisconnected(string msg) { base.OnTransportDisconnected(msg); SendQueue.Pause(); DebugEx.TraceLog("Transport disconnected"); }
public SlicerResult VisitBinaryExpression(BinaryExpression binExp, BackwardSlicerContext ctx) { if (binExp.Operator == Operator.Eq || binExp.Operator == Operator.Ne) { // Equality comparisons cannot contribute to determining the size // of the jump table; stop processing this instruction. return(null); } if ((binExp.Operator == Operator.Xor || binExp.Operator == Operator.ISub) && this.slicer.AreEqual(binExp.Left, binExp.Right)) { // XOR r,r (or SUB r,r) clears a register. Is it part of a live register? var regDst = this.assignLhs as Identifier; var regHi = binExp.Left as Identifier; if (regHi != null && regDst != null && DomainOf(regDst) == regHi.Storage.Domain && regDst.Storage.OffsetOf(regHi.Storage) == 8) { // The 8086 didn't have a MOVZX instruction, so clearing the high byte of a // register BX was done by issuing XOR BH,BH var seXor = new SlicerResult { SrcExpr = new Cast(regDst.DataType, new Cast(PrimitiveType.Byte, this.assignLhs)), LiveExprs = new Dictionary <Expression, BackwardSlicerContext> { { this.assignLhs, BackwardSlicerContext.Jump(new BitRange(0, 8)) } } }; return(seXor); } } var seLeft = binExp.Left.Accept(this, ctx); var seRight = binExp.Right.Accept(this, ctx); if (seLeft == null && seRight == null) { return(null); } if (binExp.Operator == Operator.ISub && this.Live != null && (ctx.Type & ContextType.Condition) != 0) { var domLeft = DomainOf(seLeft.SrcExpr); if (Live.Count > 0) { foreach (var live in Live) { if (live.Value.Type != ContextType.Jumptable) { continue; } if ((domLeft != StorageDomain.Memory && DomainOf(live.Key) == domLeft) || (this.slicer.AreEqual(live.Key, binExp.Left))) { //$TODO: if jmptableindex and jmptableindextouse not same, inject a statement. this.JumpTableIndex = live.Key; this.JumpTableIndexToUse = binExp.Left; this.JumpTableIndexInterval = MakeInterval_ISub(live.Key, binExp.Right as Constant); DebugEx.Verbose(BackwardSlicer.trace, " Found range of {0}: {1}", live, JumpTableIndexInterval); return(new SlicerResult { SrcExpr = binExp, Stop = true }); } } } else { // We have no live variables, which means this subtraction instruction // is both computing the jumptable index and also performing the // comparison. this.JumpTableIndex = assignLhs; this.JumpTableIndexToUse = assignLhs; this.JumpTableIndexInterval = MakeInterval_ISub(assignLhs, binExp.Right as Constant); DebugEx.Verbose(BackwardSlicer.trace, " Found range of {0}: {1}", assignLhs, JumpTableIndexInterval); return(new SlicerResult { SrcExpr = null, // the jump table expression already has the correct shape. Stop = true }); } } else if (binExp.Operator == Operator.And) { this.JumpTableIndex = binExp.Left; this.JumpTableIndexToUse = binExp.Left; this.JumpTableIndexInterval = MakeInterval_And(binExp.Left, binExp.Right as Constant); return(new SlicerResult { SrcExpr = binExp, Stop = true, }); } IEnumerable <KeyValuePair <Expression, BackwardSlicerContext> > liveExpr = seLeft.LiveExprs; if (seRight != null) { liveExpr = liveExpr.Concat(seRight.LiveExprs); } var se = new SlicerResult { LiveExprs = liveExpr .GroupBy(e => e.Key) .ToDictionary(k => k.Key, v => v.Max(vv => vv.Value)), SrcExpr = binExp, }; return(se); }
public virtual void ProcessCDPResult(string command_result, CDPDataSet.DevicesRow parent_device, CDPDataSet ds) { if (command_result.IndexOf("CDP is not enabled") >= 0) { parent_device.CDP_status = false; } else { string[] cdp_lines = command_result.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); CDPDataSet.DevicesRow current_device = null; // As going through the CDP output lines, this is the actual neighbor string currentDeviceName = ""; string currentDeviceIP = ""; CDPDataSet.NeighboursRow new_neigbor = null; // This is the neighbor created for current_device as a neighbor of parent_device PGTDataSet.ScriptSettingRow ScriptSettings = SettingsManager.GetCurrentScriptSettings(); // As the ip address must be unique for each device, adding a device with ip address of nocdpip constant would fail for the second time // To overcome this issue, we do indexing for devices with no ip address (such as VMware ESX hosts) int nocdpip_index = 0; foreach (string line in cdp_lines) { DebugEx.WriteLine(String.Format("CDP2VISIO : parsing cdp neighbor row [ {0} ]", line), DebugLevel.Full); try { bool isVMWareESX = false; #region Check for DeviceID line and set currentDeviceName accordingly if (line.IndexOf(DeviceID()) >= 0) { try { if (new_neigbor != null) { ds.Neighbours.AddNeighboursRow(new_neigbor); } } catch (Exception Ex) { // Depending on discovery list, under special circumstances it can happen that we try to add a new neighbor row // with the same connection parameters (same parent, neighbor and interfaces) that will violate unique key constraint DebugEx.WriteLine(String.Format("CDP2VISIO : Error storing neighbor row : {0}", Ex.InnerExceptionsMessage()), DebugLevel.Warning); } new_neigbor = null; string[] words = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); currentDeviceName = words[2].Trim();; currentDeviceIP = ""; DebugEx.WriteLine(String.Format("CDP2VISIO : CDPParser found a new neighbor : {0}", currentDeviceName), DebugLevel.Informational); } #endregion if (currentDeviceName == "") { continue; } #region Check for IPAddress line and set currentDeviceIP accordingly if (line.IndexOf(IPAddress()) >= 0) { string[] words_in_line = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); currentDeviceIP = words_in_line[2].Trim(); if (currentDeviceIP == "") { DebugEx.WriteLine(String.Format("CDP2VISIO : cdp is not reporting ip address for neighbor {0}", currentDeviceName), DebugLevel.Debug); currentDeviceIP = string.Format("{0}_{1}", nocdpip, nocdpip_index); nocdpip_index++; } } #endregion #region Check whether the Platform is VMware ESX if (line.Trim().StartsWith("Platform:")) { string[] words = line.SplitByComma(); // words[0] should be PlatForm, words[1] is Capabilities isVMWareESX = words[0].ToLowerInvariant().IndexOf("vmware esx") >= 0; if (isVMWareESX) { DebugEx.WriteLine(String.Format("CDP2VISIO : neighbor {0} is an ESX host", currentDeviceName), DebugLevel.Debug); currentDeviceIP = string.Format("{0}_{1}", nocdpip, nocdpip_index); nocdpip_index++; } } #endregion if (currentDeviceIP == "") { continue; } #region Add current device as new device or select existing device from Devices table // At this point we can identify the current device(cdp neighbor) by name and ip. This is also a new neighbor // Two devices considered identical if : // - have the same hostname, or // - have the same IPAddress string currentDeviceHostName = DottedNameSpace.TLD(currentDeviceName); current_device = ds.Devices.FirstOrDefault(d => currentDeviceIP != nocdpip && d.IP_Address.SplitBySemicolon().Any(thisIP => thisIP == currentDeviceIP) || d.Name.SplitBySemicolon().Any(thisName => DottedNameSpace.CompateTLD(thisName, currentDeviceHostName)) ); if (current_device == null) { DebugEx.WriteLine(String.Format("CDP2VISIO : neighbor {0} is a new device, adding to devices data table", currentDeviceName), DebugLevel.Informational); // This device is not yet known. Add to device list and also to list of devices in script current_device = ds.Devices.NewDevicesRow(); //if (current_device.Name != currentDeviceName) current_device.Name += ";" + currentDeviceName; //else current_device.Name = currentDeviceName; if (current_device.IsIP_AddressNull() || current_device.IP_Address == "") { current_device.IP_Address = currentDeviceIP; } else if (current_device.IP_Address != currentDeviceIP) { current_device.IP_Address += ";" + currentDeviceIP; } ds.Devices.AddDevicesRow(current_device); // Add a new entry for discovered device if has a valid neighbor ip, Recursion is allowed // and this ip is not defined as discovery boundary if (_AllowRecursion && !currentDeviceIP.StartsWith(nocdpip)) { var includedAddresses = (from addressdefinition in ds.DomainBoundary where addressdefinition.Action == BoundaryAddressAction.Include.ToString() select addressdefinition.IP_Address)?.ToList(); var excludedAddresses = (from addressdefinition in ds.DomainBoundary where addressdefinition.Action == BoundaryAddressAction.Exclude.ToString() select addressdefinition.IP_Address)?.ToList(); if (IPOperations.IsIPAddressInNetworks(currentDeviceIP, includedAddresses, true) && !IPOperations.IsIPAddressInNetworks(currentDeviceIP, excludedAddresses, false)) { string[] newScriptLine = _ConnectionInfo.ScriptLine.Split(ScriptSettings.CSVSeparator.ToCharArray()); newScriptLine[2] = currentDeviceIP; newScriptLine[3] = currentDeviceName; _Executor.AddScriptEntry(string.Join(ScriptSettings.CSVSeparator, newScriptLine)); string msg = string.Format("Added device <{0}> to discovery list.", currentDeviceIP); DebugEx.WriteLine(msg, DebugLevel.Informational); _Executor.ShowActivity(msg); } else { string msg = string.Format("Not adding device <{0}> to discovery list because it is either explicitly excluded or not included in discovery domain", currentDeviceIP); DebugEx.WriteLine(msg, DebugLevel.Full); _Executor.ShowActivity(msg); } } else { string msg = "Not adding device a new neighbor to discovery list because Active Discovery is not allowed or the neighbor does not have a valid ip address detected."; DebugEx.WriteLine(msg, DebugLevel.Full); } } else { DebugEx.WriteLine(String.Format("CDP2VISIO : neighbor {0} is already a known device", currentDeviceName), DebugLevel.Full); } #endregion if (current_device == null) { continue; } #region Create Neighbor for parent_device <-> current_device if (new_neigbor == null) { new_neigbor = ds.Neighbours.NewNeighboursRow(); new_neigbor.Neighbor_ID = current_device.ID; new_neigbor.Parent_ID = parent_device.ID; new_neigbor.Name = current_device.Name; DebugEx.WriteLine(String.Format("CDP2VISIO : new neighbor {0} added for device {1}", currentDeviceName, parent_device.Name), DebugLevel.Full); } #endregion #region Get Platform/Interfaces info and update the neighbor if (line.Trim().StartsWith("Platform") && new_neigbor != null) { string[] words = line.SplitByComma(); // words[0] should be PlatForm, words[1] is Capabilities string[] platformWords = words[0].SplitBySpace(); string[] capabilities = words[1].SplitBySpace(); current_device.Platform = string.Join(" ", platformWords.SkipWhile((string l, int i) => i < 1)); if (current_device.Type != "VSS" && current_device.Type != "ASA" && !current_device.Type.StartsWith("Stack")) { current_device.Type = string.Join(";", capabilities.SkipWhile((s, i) => i < 1)); } DebugEx.WriteLine(String.Format("CDP2VISIO : Platform of neighbor {0} identified as {1}. Device type was set to {2}", currentDeviceName, current_device.Platform, current_device.Type), DebugLevel.Full); } if (line.IndexOf("Interface") >= 0 && new_neigbor != null) { string[] words_in_line = line.SplitBySpace(); int words_length = words_in_line.Length; string neighbour_interfaces = words_in_line[words_length - 1]; neighbour_interfaces = Common.ConvInt(neighbour_interfaces); string local_interfaces = words_in_line[1].Replace(",", ""); local_interfaces = Common.ConvInt(local_interfaces); new_neigbor.Neighbour_Interface = neighbour_interfaces; new_neigbor.Local_Interface = local_interfaces; DebugEx.WriteLine(String.Format("CDP2VISIO : connected interface added {0}::{1} connects to {2}::{3}", currentDeviceName, local_interfaces, parent_device.Name, neighbour_interfaces), DebugLevel.Full); } #endregion } catch (Exception Ex) { DebugEx.WriteLine(String.Format("CDP2VISIO : Error while parsing cdp output line [{0}]. Error is : {1}", line, Ex.InnerExceptionsMessage())); } } if (new_neigbor != null) { ds.Neighbours.AddNeighboursRow(new_neigbor); } } }
/// <summary> /// Relocates all relocations found in the DT_DYNAMIC segment. /// </summary> /// <param name="program"></param> /// <returns></returns> public List <ElfSymbol> RelocateDynamicSymbols(Program program) { var symbols = new List <ElfSymbol>(); foreach (var dynSeg in EnumerateDynamicSegments()) { DumpDynamicSegment(dynSeg); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_STRTAB, out var strtab); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_SYMTAB, out var symtab); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_RELA, out var rela); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_RELASZ, out var relasz); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_RELAENT, out var relaent); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_REL, out var rel); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_RELSZ, out var relsz); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_RELENT, out var relent); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_SYMENT, out var syment); if (symtab == null || (rela == null && rel == null)) { continue; } if (strtab == null) { throw new BadImageFormatException("ELF dynamic segment lacks a string table."); } if (syment == null) { throw new BadImageFormatException("ELF dynamic segment lacks the size of symbol table entries."); } RelocationTable relTable; if (rela != null) { if (relasz == null) { throw new BadImageFormatException("ELF dynamic segment lacks the size of the relocation table."); } if (relaent == null) { throw new BadImageFormatException("ELF dynamic segment lacks the size of relocation table entries."); } relTable = new RelaTable(this, rela.UValue, relasz.UValue); } else { Debug.Assert(rel != null); if (relsz == null) { throw new BadImageFormatException("ELF dynamic segment lacks the size of the relocation table."); } if (relent == null) { throw new BadImageFormatException("ELF dynamic segment lacks the size of relocation table entries."); } relTable = new RelTable(this, rel.UValue, relsz.UValue); } var offStrtab = Loader.AddressToFileOffset(strtab.UValue); var offSymtab = Loader.AddressToFileOffset(symtab.UValue); LoadSymbolsFromDynamicSegment(dynSeg, symtab, syment, offStrtab, offSymtab); // Generate a symbol for each relocation. Debug.Print("Relocating entries in .dynamic:"); foreach (var elfSym in relTable.RelocateEntries(program, offStrtab, offSymtab, syment.UValue)) { symbols.Add(elfSym); var imgSym = Loader.CreateImageSymbol(elfSym, true); if (imgSym == null || imgSym.Address.ToLinear() == 0) { continue; } imageSymbols[imgSym.Address] = imgSym; } // Relocate the DT_JMPREL table. Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_JMPREL, out var jmprel); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_PLTRELSZ, out var pltrelsz); Loader.DynamicEntries.TryGetValue(ElfDynamicEntry.DT_PLTREL, out var pltrel); if (jmprel != null && pltrelsz != null && pltrel != null) { if (pltrel.SValue == 7) // entries are in RELA format. { relTable = new RelaTable(this, jmprel.UValue, pltrelsz.UValue); } else if (pltrel.SValue == 0x11) // entries are in REL format { relTable = new RelTable(this, jmprel.UValue, pltrelsz.UValue); } else { //$REVIEW: bad elf format! continue; } DebugEx.Inform(ElfImageLoader.trace, "Relocating entries in DT_JMPREL:"); foreach (var elfSym in relTable.RelocateEntries(program, offStrtab, offSymtab, syment.UValue)) { symbols.Add(elfSym); var imgSym = Loader.CreateImageSymbol(elfSym, true); if (imgSym == null || imgSym.Address.ToLinear() == 0) { continue; } imageSymbols[imgSym.Address] = imgSym; program.ImportReferences[imgSym.Address] = new NamedImportReference( imgSym.Address, null, // ELF imports don't specify which modile to take the import from imgSym.Name, imgSym.Type); } } } return(symbols); }