public Program() { Runtime.UpdateFrequency = UpdateFrequency.Update10; antenna = GridTerminalSystem.GetBlockWithName("Antenna") as IMyRadioAntenna; up1 = GridTerminalSystem.GetBlockWithName("up1") as IMyPistonBase; up2 = GridTerminalSystem.GetBlockWithName("up2") as IMyPistonBase; out1 = GridTerminalSystem.GetBlockWithName("out1") as IMyPistonBase; out2 = GridTerminalSystem.GetBlockWithName("out2") as IMyPistonBase; antenna.AttachedProgrammableBlock = Me.EntityId; IGC.RegisterBroadcastListener(Channel); IGC.GetBroadcastListeners(listeners); listeners[0].SetMessageCallback("door"); }
private IEnumerable <IMyBroadcastListener> UpdateBroadcast() { var broadcastTag = $"{Me.CubeGrid.EntityId}.NIN.NAME"; if (_broadcastTag != broadcastTag) { IGC.UnregisterBroadcastListener(_broadcastTag); _broadcastTag = broadcastTag; } var broadcastListener = IGC.RegisterBroadcastListener(broadcastTag); yield return(null); IGC.SendBroadcastMessage(broadcastTag, _priority); yield return(null); while (broadcastListener.HasPendingMessage) { var message = broadcastListener.AcceptMessage(); var priorityReceived = -1; try { priorityReceived = (int)message.Data; } catch { EchoManager.Print($"Received an invalid message in broadcast channel: {message.Data}"); } if (!_ignorePriority && priorityReceived > _priority) { Disable(); } yield return(null); } EnableIfReady(); yield return(broadcastListener); }
// Handler for the test broadcast messages. void TestBroadcastHandler(MyIGCMessage msg) { // NOTE: called on ALL received messages; not just 'our' tag if (msg.Tag != _broadCastTag) { return; // not our message } if (msg.Data is string) { Echo("Received Test Message"); Echo(" Source=" + msg.Source.ToString("X")); Echo(" Data=\"" + msg.Data + "\""); Echo(" Tag=" + msg.Tag); // Now reply to the sender and let them know we received the message IGC.SendUnicastMessage(msg.Source, _unicastTag, "Acknowledge by:" + Me.CustomName); Echo(" Reply Sent"); } }
public void Main() { while (Listener.HasPendingMessage) { MyIGCMessage message = Listener.AcceptMessage(); if (message.Data is string) { Print("Recieved message: " + document.OuterXml); } else { Print("Message is not " + typeof(string).FullName + ", but is " + message.Data.GetType().FullName); } } if (count >= 100U) { IGC.SendBroadcastMessage(Channel, document.OuterXml, TransmissionDistance.AntennaRelay); count = 0U; } ++count; }
public void Main(string argument, UpdateType updateSource) { // Init storage InitializeStorage(); // Set default data if if (!IsDataFormatValid() || argument == "reset") { SetDefaultData(); return; } // Construct & send message. string message = config.ToString(); IGC.SendBroadcastMessage(AntennaChannel, message); Echo("Broadcasting on \"" + AntennaChannel + "\".."); }
public Program() { //hardware _remote = GridTerminalSystem.GetBlockWithName("Remote [t]") as IMyRemoteControl; _gyro = GridTerminalSystem.GetBlockWithName("Gyroscope [t]") as IMyGyro; _connector = GridTerminalSystem.GetBlockWithName("Connector [t]") as IMyShipConnector; _messageBuilder.AppendLine("Hardware located."); //IGC IGC.UnicastListener.SetMessageCallback(); _turtleListenerInit = IGC.RegisterBroadcastListener(_turtleInit); _turtleListenerInit.SetMessageCallback(_turtleInit); var op = GridTerminalSystem.GetBlockWithName("Operator [t]") as IMyProgrammableBlock; _turtleOperatorID = op.GetId(); _messageBuilder.AppendLine("IGC loaded."); // load program state Load(); // custom data reset - log info Me.CustomData = "\t\tPROGRAM LOG:\n\n" + _messageBuilder; Runtime.UpdateFrequency |= UpdateFrequency.Once; _stateMachine = Idle(); }
public void Main(string argument, UpdateType updateSource) { if ((updateSource & UpdateType.IGC) > 0) { if (universalListener != null && universalListener.HasPendingMessage) { MyIGCMessage message = universalListener.AcceptMessage(); List <IMyTextPanel> panels = new List <IMyTextPanel>(); GridTerminalSystem.GetBlocksOfType(panels); if (panels.Count > 0) { panels[0].WriteText(message.Tag + " " + message.Source + " " + message.Data + "\n", false); } } } else { universalListener = IGC.RegisterBroadcastListener(argument); universalListener.SetMessageCallback(); Echo("CURRENT LISTENING CODE: " + argument); } }
public Program() { // Prioritize the given cockpit name rc = GetBlock <IMyShipController>(cockpitName, true); if (rc == null) // Second priority cockpit { rc = GetBlock <IMyCockpit>(); } if (rc == null) // Third priority remote control { rc = GetBlock <IMyRemoteControl>(); } if (rc == null) // No cockpits found. { throw new Exception("No cockpit/remote control found. Set the cockpitName field in settings."); } wheels = new WheelControl(rc, tickSpeed, GetBlocks <IMyMotorSuspension>()); leaderListener = IGC.RegisterBroadcastListener(transmitTag); leaderListener.SetMessageCallback(""); commandListener = IGC.RegisterBroadcastListener(transmitCommandTag); commandListener.SetMessageCallback(""); configurations["default"] = defaultOffset; offset = defaultOffset; LoadStorage(); if (tickSpeed == UpdateFrequency.Update10) { echoFrequency = 10; } else if (tickSpeed == UpdateFrequency.Update100) { echoFrequency = 1; } Echo("Ready."); }
private void UpdateSettings() { var parser = new MyIni(); if (!parser.TryParse(Me.CustomData)) { throw new InvalidOperationException("Couldn't parse CustomData as INI!"); } this.tag = parser.Get(SETTINGS_SECTION, "tag").ToString(MissileCommons.DEFAULT_TAG); this.statusTag = parser.Get(SETTINGS_SECTION, "statusTag").ToString(MissileCommons.STATUS_TAG); this.directing = parser.Get(SETTINGS_SECTION, "directing").ToBoolean(true); if (this.directing) { this.directorTurret = GridTerminalSystem.GetBlockOfType <IMyLargeTurretBase>(t => MyIni.HasSection(t.CustomData, DIRECTOR_TURRET_SECTION)); if (this.directorTurret != null) { LogLine($"Director mode on, found director turret {directorTurret.CustomName}"); } else { LogLine($"No director turret was found. If you have one, add the [{DIRECTOR_TURRET_SECTION}] line to its Custom Data. Disabling director mode."); this.directing = false; } } if (missileMsgListener != null) { missileMsgListener.DisableMessageCallback(); } missileMsgListener = IGC.RegisterBroadcastListener(this.tag); missileMsgListener.SetMessageCallback(); if (missileStatusListener != null) { missileStatusListener.DisableMessageCallback(); } missileStatusListener = IGC.RegisterBroadcastListener(MissileCommons.STATUS_TAG); missileStatusListener.SetMessageCallback(); }
public void Main(string arg) { if (setupcomplete == false) { Echo("Running setup."); Setup(); } else if (setupcomplete == true && requestSent == false) { string messageOut = "Requesting Docking Clearance"; IGC.SendBroadcastMessage(tag1, messageOut, TransmissionDistance.TransmissionDistanceMax); Echo("Requesting Clearance"); requestSent = true; } else if (requestSent == true && clearanceReceived == false) { // Now that we've requested clearance, listen for a clearance response. IGC.RegisterBroadcastListener(tag1); List <IMyBroadcastListener> listeners = new List <IMyBroadcastListener>(); IGC.GetBroadcastListeners(listeners); Echo("checking messages"); if (listeners[0].HasPendingMessage) { Echo("message received"); clearance = listeners[0].AcceptMessage(); clearanceReceived = true; } else { requestSent = false; } } else if (clearanceReceived == true) { Echo(clearance.Data.ToString()); } }
public void Main(string argument, UpdateType updateSource) { // Echo some information aboue 'me' and why we were run Echo("Source=" + updateSource.ToString()); Echo("Me=" + Me.EntityId.ToString("X")); Echo(Me.CubeGrid.CustomName); if (!_areWeInited) { InitMessageHandlers(); _areWeInited = true; } // use if not setting callbacks for any of the desired channels // if (bInit) wicoIGC.ProcessIGCMessages(); // always check for IGC messages in case some aren't using callbacks _wicoIGC.ProcessIGCMessages(); if ((updateSource & UpdateType.IGC) > 0) { // we got a callback for an IGC message. // but we already processed them. } else if ((updateSource & _utTriggers) > 0) { // if we got a 'trigger' source, send out the received argument IGC.SendBroadcastMessage(_broadCastTag, argument); Echo("Sending Message:\n" + argument); } else if ((updateSource & _utUpdates) > 0) { // it was an automatic update // this script doens't have anything to do } }
void Initalize() { var controls = new List <IMyRemoteControl>(); GridTerminalSystem.GetBlocksOfType(controls); mainControl = controls.Find(control => { try { return(JSON.Parse(control.CustomData).jsonObject["type"].jsonString == "mainControl"); } catch { return(false); } }); name = $"Greedle ID {new Random().Next()}"; target = Vector3.Zero; directiveListener = IGC.RegisterBroadcastListener("greedle_directive"); directiveListener.SetMessageCallback(); var antennas = new List <IMyRadioAntenna>(); GridTerminalSystem.GetBlocksOfType(antennas); foreach (var antenna in antennas) { antenna.HudText = name; } Me.GetSurface(0).ContentType = ContentType.TEXT_AND_IMAGE; }
int runcount = 0; // used to show running multiple times public void Main(string argument, UpdateType updateSource) { // Echo some information aboue 'me' and why we were run Echo(updateSource.ToString()); Echo("Me=" + Me.EntityId.ToString()); Echo(Me.CubeGrid.CustomName); runcount++; Echo("Runs=" + runcount.ToString()); // if there is a message pending, process it if (_bListener.HasPendingMessage || _uListener.HasPendingMessage) { if (!HandleMessages()) { return; } } else { // if we were run when there's not a pending message, send out a broadcast message Echo("Sending Broadcast Message"); IGC.SendBroadcastMessage <string>(BroadcastTag, "Me=" + Me.EntityId.ToString() + ":" + Me.CubeGrid.CustomName + "\n" + argument, TransmissionDistance.AntennaRelay); } }
public void Main(string argument, UpdateType updateSource) { if ((updateSource & UpdateType.Terminal) > 0) { // отправляем сообщение count++; string message = "test message " + count; IGC.SendBroadcastMessage <string>(TAG, message, TransmissionDistance.TransmissionDistanceMax); Echo("send: " + message); } else if ((updateSource & UpdateType.IGC) > 0) { // получаем ответ Echo("argument: " + argument); if (listener.HasPendingMessage) { MyIGCMessage message = listener.AcceptMessage(); if (message.Data is string) { Echo("result: " + message.Data.ToString()); } } } }
public void Main(string argument, UpdateType updateSource) { if (argument == "releaseremote") { IGC.SendBroadcastMessage("[PDCFORGE]", ""); } else if (argument == "save") { if (Elevation != null && BaseMerge != null) { var list = new List <IMyTerminalBlock>(); list.Add(Elevation); BaseMerge.CustomData = GridTerminalHelper.BlockListBytePosToBase64(list, BaseMerge); } } else if (argument == "release") { while (ReleaseListener.HasPendingMessage) { var msg = ReleaseListener.AcceptMessage(); if (msg.Data is string && Me.CustomName.Contains((string)msg.Data)) { var otherMerge = GridTerminalHelper.OtherMergeBlock(TopMerge); if (otherMerge != null) { otherMerge.Enabled = false; } } } } else { if (State == 0) { foreach (var welder in Welders) { welder.Enabled = true; } if (Display != null) { Display.WriteText("STATE 0: WELDING - WAITING FOR COMPLETION"); } if (TopProjector.RemainingBlocks == 0 && BaseProjector.RemainingBlocks == 0) { GraceTimer = 5; State = 1; } } else if (State == 1) { GraceTimer--; if (Display != null) { Display.WriteText($"STATE 1: WELDING GRACE PERIOD - {GraceTimer}"); } if (GraceTimer <= 0) { foreach (var welder in Welders) { welder.Enabled = false; } BaseProjector.Enabled = false; TopProjector.Enabled = false; State = 2; } } else if (State == 2) { ElevationScratchpad.Clear(); var block = GridTerminalHelper.Base64BytePosToBlockList(BaseMerge.CustomData, BaseMerge, ref ElevationScratchpad); if (ElevationScratchpad.Count == 1) { Elevation = ElevationScratchpad[0]; if (Display != null) { Display.WriteText($"ELEVATION ROTOR FOUND", true); } Elevation.Detach(); var degrees = -90f * Math.PI / 180f; DriveHinge(SmallHinge, (float)(degrees), 0.3f); DriveHinge(LargeHinge, (float)(degrees), 1f); Sweeper.TargetVelocityRPM = -10; if (Display != null) { Display.WriteText($"STATE 2: SWINGING HINGES SMALL - {SmallHinge.Angle * 180 / Math.PI} / -90 | LARGE - {LargeHinge.Angle * 180 / Math.PI} / -90"); } if (Math.Abs(SmallHinge.Angle - degrees) < 0.01 && Math.Abs(LargeHinge.Angle - degrees) < 0.01) { State = 3; } } else { if (Display != null) { Display.WriteText($"\nCRITICAL ERROR: ELEVATION ROTOR NOT FOUND", true); } } } else if (State == 3) { if (Display != null) { Display.WriteText($"STATE 3: ATTEMPTING ATTACH"); } ElevationScratchpad.Clear(); var block = GridTerminalHelper.Base64BytePosToBlockList(BaseMerge.CustomData, BaseMerge, ref ElevationScratchpad); if (ElevationScratchpad.Count == 1) { Elevation = ElevationScratchpad[0]; if (Display != null) { Display.WriteText($"ELEVATION ROTOR FOUND", true); } Elevation.Attach(); if (Elevation.IsAttached) { GridTerminalHelper.OtherMergeBlock(BaseMerge).Enabled = false; State = 4; } } else { if (Display != null) { Display.WriteText($"\nCRITICAL ERROR: ELEVATION ROTOR NOT FOUND", true); } } } else if (State == 4) { var degrees = 90f * Math.PI / 180f; DriveHinge(SmallHinge, (float)(degrees), 0.3f); if (Display != null) { Display.WriteText($"STATE 4: SWINGING SMALL HINGE - {SmallHinge.Angle * 180 / Math.PI} / 90"); } if (Math.Abs(SmallHinge.Angle - degrees) < 0.01) { State = 5; } } else if (State == 5) { if (Display != null) { Display.WriteText($"STATE 5: COMPLETE - AWAITING PICKUP"); } if (GridTerminalHelper.OtherMergeBlock(TopMerge) == null) { State = 6; GraceTimer = 5; } } else if (State == 6) { GraceTimer--; if (Display != null) { Display.WriteText($"STATE 6: DETACH GRACE PERIOD - {GraceTimer}"); } if (GraceTimer <= 0) { State = 7; } } else if (State == 7) { var degrees = 90f * Math.PI / 180f; var degrees2 = 0; DriveHinge(LargeHinge, (float)(degrees), 1f); DriveHinge(SmallHinge, (float)(degrees2), 1f); Sweeper.TargetVelocityRPM = 10; BaseProjector.Enabled = true; TopProjector.Enabled = true; if (Display != null) { Display.WriteText($"STATE 7: RESETTING SMALL - {SmallHinge.Angle * 180 / Math.PI} / 0 | LARGE - {LargeHinge.Angle * 180 / Math.PI} / 90"); } if (Math.Abs(SmallHinge.Angle - degrees2) < 0.01 && Math.Abs(LargeHinge.Angle - degrees) < 0.01) { State = 0; } } } }
void TransmitCommand(string target, string data, TransmissionDistance distance = TransmissionDistance.AntennaRelay) { MyTuple <string, string> msg = new MyTuple <string, string>(target, data); IGC.SendBroadcastMessage <MyTuple <string, string> >(transmitCommandTag, msg, distance); }
public void Main(string argument, UpdateType updateSource) { if (updateSource == UpdateType.Update100 || updateSource == UpdateType.Update10 || updateSource == UpdateType.Update1) { if (debug || runtime % echoFrequency == 0) { WriteEcho(); } runtime++; if (target != 0 || targetName != null) { MyDetectedEntityInfo?info = null; foreach (IMySensorBlock s in sensors) { if (info.HasValue) { break; } List <MyDetectedEntityInfo> entites = new List <MyDetectedEntityInfo>(); s.DetectedEntities(entites); foreach (MyDetectedEntityInfo i in entites) { if (target != 0) { // target id exists if (i.EntityId == target) { info = i; break; } } else if (targetName != null) { // target id does not exist if (i.Name == targetName) { info = i; target = i.EntityId; Save(); // Update save data with the id break; } } } } if (activeRaycasting && target != 0 && !previousHit.IsEmpty() && !info.HasValue) { float sec = Math.Abs(runtime - hitRuntime); if (Runtime.UpdateFrequency == UpdateFrequency.Update10) { sec *= 1f / 6; } else if (Runtime.UpdateFrequency == UpdateFrequency.Update100) { sec *= 5f / 3; } else { sec *= 1f / 60; } Vector3D prediction = previousHit.Position + previousHit.Velocity * sec; foreach (IMyCameraBlock c in allCameras) { if (!c.EnableRaycast) { c.EnableRaycast = true; } if (c.CanScan(prediction)) { MyDetectedEntityInfo result = c.Raycast(prediction); if (result.EntityId == target) { info = result; } break; } } } if (info.HasValue) { if (activeRaycasting) { previousHit = info.Value; hitRuntime = runtime; } Vector3D up = info.Value.Orientation.Up; if (alignFollowersToGravity) { Vector3D gravity = rc.GetNaturalGravity(); if (gravity != Vector3D.Zero) { up = -Vector3D.Normalize(gravity); } } MatrixD worldMatrix = MatrixD.CreateWorld(info.Value.Position, info.Value.Orientation.Forward, up); IGC.SendBroadcastMessage <MyTuple <MatrixD, Vector3D, long> >(transmitTag, new MyTuple <MatrixD, Vector3D, long>(worldMatrix, info.Value.Velocity, info.Value.EntityId)); } } else if (allowFollowSelf) { MatrixD matrix = rc.WorldMatrix; if (alignFollowersToGravity) { Vector3D gravity = rc.GetNaturalGravity(); if (gravity != Vector3D.Zero) { Vector3D up = -Vector3D.Normalize(gravity); Vector3D right = matrix.Forward.Cross(up); Vector3D forward = up.Cross(right); matrix.Up = up; matrix.Right = right; matrix.Forward = forward; } } IGC.SendBroadcastMessage <MyTuple <MatrixD, Vector3D, long> >(transmitTag, new MyTuple <MatrixD, Vector3D, long>(matrix, rc.GetShipVelocities().LinearVelocity, Me.CubeGrid.EntityId)); } } else { ProcessCommand(argument); } }
private void SendIGCMessage(long address, string message, string arguments) { IGC.SendUnicastMessage(address, fileSystemClientTag, message + " " + arguments); }
private void SendIGCMessage(long address, string message) { IGC.SendUnicastMessage(address, fileSystemClientTag, message); }
public void Main(string argument, UpdateType updateSource) { soundBlock = (IMySoundBlock)GridTerminalSystem.GetBlockWithName(AlarmBlockName); Runtime.UpdateFrequency = UpdateFrequency.Update100; IMyTextPanel MessagePanel = (IMyTextPanel)GridTerminalSystem.GetBlockWithName(messagePanelName); // If setupcomplete is false, run Setup method. if (!setupcomplete) { Echo("Running setup."); Setup(); SaveData(); } else { // To create a listener, we use IGC to access the relevant method. // We pass the same tag argument we used for our message. IGC.RegisterBroadcastListener(broadcastChannel); // Create a list for broadcast listeners. List <IMyBroadcastListener> listeners = new List <IMyBroadcastListener>(); // The method argument below is the list we wish IGC to populate with all Listeners we've made. // Our Listener will be at index 0, since it's the only one we've made so far. IGC.GetBroadcastListeners(listeners); foreach (var item in listeners) { Echo("Somone listen"); } if (listeners[0].HasPendingMessage) { // Let's create a variable for our new message. // Remember, messages have the type MyIGCMessage. MyIGCMessage message = new MyIGCMessage(); // Time to get our message from our Listener (at index 0 of our Listener list). // We do this with the following method: message = listeners[0].AcceptMessage(); // A message is a struct of 3 variables. To read the actual data, // we access the Data field, convert it to type string (unboxing), // and store it in the variable messagetext. string messagetext = message.Data.ToString(); // We can also access the tag that the message was sent with. string messagetag = message.Tag; //Here we store the "address" to the Programmable Block (our friend's) that sent the message. long sender = message.Source; //Do something with the information! Echo("Message received with tag" + messagetag + "\n\r"); Echo("from address " + sender.ToString() + ": \n\r"); Echo(messagetext); MessagePanel.WriteText("Error"); if (knownIp.Contains(sender.ToString())) { Echo("Here222"); Gates("y"); MessagePanel.WriteText(messagetext); } else if (messagetext.Contains(acceptCode)) { MessagePanel.WriteText("Err33or"); soundBlock.Play(); MessagePanel.WriteText("accepted part 2"); Echo("Accepted"); Gates("y"); if (knownIp.Contains(sender.ToString())) { MessagePanel.WriteText("accepted part 3"); } else { knownIp.Add(sender.ToString()); MessagePanel.WriteText(messagetext); } TextMessage = ""; for (int i = 0; i < knownIp.Count; i++) { TextMessage += $"{knownIp[i]}\n"; } userIpPanel.WriteText(TextMessage); } else { Echo("Im here"); MessagePanel.WriteText("Acces denied" + "\n" + TextMessage); Gates("n"); } } } }
public void SendMessage(string message) { IGC.SendBroadcastMessage(ILSAntennaChannel, message, TransmissionDistance.TransmissionDistanceMax); }
void Start() { gridSystem = GridTerminalSystem; gridId = Me.CubeGrid.EntityId; turrets = GetBlocks <IMyLargeTurretBase>(turretGroup, useSubgrids); wcTurrets = new WcPbApi(); try { if (!wcTurrets.Activate(Me)) { wcTurrets = null; } } catch { wcTurrets = null; } if (string.IsNullOrWhiteSpace(rcName)) { rc = GetBlock <IMyRemoteControl>(); } else { rc = GetBlock <IMyRemoteControl>(rcName, useSubgrids); } if (rc == null) { throw new Exception("Remote control block not found."); } gyros = new GyroControl(rc); origin = rc.GetPosition(); this.guns = new List <IMyUserControllableGun>(); List <IMyUserControllableGun> guns = GetBlocks <IMyUserControllableGun>(gunsGroup, useSubgrids); foreach (IMyUserControllableGun g in guns) { if (!(g is IMyLargeTurretBase)) { g.SetValueBool("Shoot", false); if (rocketMode != RocketMode.None) { IMySmallMissileLauncher m = g as IMySmallMissileLauncher; if (m != null) { rockets.Add(m); continue; } } this.guns.Add(g); } } if (receiveHelpMsgs) { helpListener = IGC.RegisterBroadcastListener("AttackDrone_" + commsId); helpListener.SetMessageCallback(""); } thrust = new ThrusterControl(rc, GetBlocks <IMyThrust>(thrustGroup)); maxAngle *= Math.PI / 180; startRuntime = -1; }
public Program() { try { UpdateSettings(); ResetDisplay(); this.remote = GridTerminalSystem.GetBlockOfType <IMyRemoteControl>(rm => rm.CubeGrid == Me.CubeGrid && MyIni.HasSection(rm.CustomData, REFERENCE_RM)); if (remote == null) { throw new InvalidOperationException("Missile MUST have a remote. (That is forward facing)"); } LogLine($"Found remote {remote.CustomName}"); this.separator = GridTerminalSystem.GetBlockOfType <IMyShipMergeBlock>(mb => mb.CubeGrid == Me.CubeGrid && MyIni.HasSection(mb.CustomData, SEPARATOR_MARKER)); if (this.separator != null) { LogLine($"Found separator merge-block {separator.CustomName}"); } else { LogLine($"Warning: No separator block found. Missile can launch without one, but if you do have a separator, add a [{SEPARATOR_MARKER}] line to its custom data."); } this.statusLogger = new Logger(this, STATUS_DISPLAY_SECTION, true); GridTerminalSystem.GetBlocksOfType(allThrusters, th => th.CubeGrid == Me.CubeGrid); foreach (var thruster in allThrusters) { if (thruster.WorldMatrix.Forward == remote.WorldMatrix.Backward) { fwdThrusters.Add(thruster); LogLine($"Found forward thruster {thruster.CustomName}"); } if (thruster.WorldMatrix.Forward == remote.WorldMatrix.Up) { downThrusters.Add(thruster); LogLine($"Found down thruster {thruster.CustomName}"); } thruster.Enabled = false; thruster.ThrustOverridePercentage = 0; } GridTerminalSystem.GetBlocksOfType(warheads, b => b.CubeGrid == Me.CubeGrid); LogLine($"Found {warheads.Count} warheads."); foreach (var warhead in warheads) { warhead.IsArmed = false; } GridTerminalSystem.GetBlocksOfType(gyros, b => b.CubeGrid == Me.CubeGrid); foreach (var gyro in gyros) { gyro.Enabled = false; } GridTerminalSystem.GetBlocksOfType(antennas, b => b.CubeGrid == Me.CubeGrid && MyIni.HasSection(b.CustomData, MISSILE_ANTENNA)); foreach (var ant in antennas) { ant.Enabled = false; ant.Radius = 50000f; ant.CustomName = $"{uuid} Antenna"; } LogLine("Missile is ready to launch"); LogStatus("Missile: Pre-flight"); this.msgHandler = CreateMessageHandler(); IGC.SendBroadcast(new RegisterMissileCommand() { UUID = uuid }); } catch (Exception ex) { LogLine($"[{uuid}] Program() expection: {ex}\nStacktrace: \n{ex.StackTrace}"); } }
public Program() { Runtime.UpdateFrequency = UpdateFrequency.Update100; GridTerminalSystem.GetBlocksOfType <IMyTerminalBlock>(null, CollectParts); StatusBuilder.Clear(); var AOK = true; if (SmallHinge == null) { AOK = false; StatusBuilder.AppendLine("SMALL HINGE NOT FOUND!"); } if (LargeHinge == null) { AOK = false; StatusBuilder.AppendLine("LARGE HINGE NOT FOUND!"); } if (Sweeper == null) { AOK = false; StatusBuilder.AppendLine("SWEEPER NOT FOUND!"); } if (BaseProjector == null) { AOK = false; StatusBuilder.AppendLine("BASE PROJECTOR NOT FOUND!"); } if (TopProjector == null) { AOK = false; StatusBuilder.AppendLine("TOP PROJECTOR NOT FOUND!"); } if (TopMerge == null) { AOK = false; StatusBuilder.AppendLine("TOP MERGE NOT FOUND!"); } if (BaseMerge == null) { AOK = false; StatusBuilder.AppendLine("BASE MERGE NOT FOUND!"); } if (Welders.Count < 5) { AOK = false; StatusBuilder.AppendLine("NOT ENOUGH WELDERS!"); } if (Display != null) { Display.ContentType = ContentType.TEXT_AND_IMAGE; Display.WriteText(StatusBuilder.ToString()); } if (!AOK) { Echo(StatusBuilder.ToString()); Runtime.UpdateFrequency = UpdateFrequency.None; } else { var baseOtherMerge = GridTerminalHelper.OtherMergeBlock(BaseMerge); var topOtherMerge = GridTerminalHelper.OtherMergeBlock(TopMerge); if (topOtherMerge != null && baseOtherMerge == null) { State = 4; } } ReleaseListener = IGC.RegisterBroadcastListener("[PDCFORGE]"); ReleaseListener.SetMessageCallback("release"); }
public Program() { universalListener = IGC.RegisterBroadcastListener("CODE"); universalListener.SetMessageCallback(); }
public void Main(string argument, UpdateType updateSource) { IGC.SendUnicastMessage(_navID, TAG, "R;" + run); Echo("unicast sent " + run); run = run++ % 4; }
/// <summary> /// Should be ran with Tracking output as argument /// </summary> /// <param name="argument"></param> public void Main(string argument) { Echo(argument); if (argument.StartsWith("SwitchTarget")) { Echo("Switching to next target"); if (!mdeis.ContainsKey(selectedEntityId)) { if (mdeis.Count > 0) { selectedEntityId = mdeis.First().Key; } Echo("resetting " + selectedEntityId); } else { bool found = false; foreach (var entId in mdeis.Keys) { if (found) { Echo("setting " + entId); selectedEntityId = entId; found = false; break; } else if (entId == selectedEntityId) { found = true; Echo("found " + entId); } } if (found) { if (mdeis.Count > 0) { selectedEntityId = mdeis.First().Key; } } } } else if (argument.StartsWith("Lock")) { if (mdeis.ContainsKey(selectedEntityId)) { string weaponClass = argument.Substring(5); List <IMyProgrammableBlock> pbs = new List <IMyProgrammableBlock>(); GridTerminalSystem.GetBlocksOfType <IMyProgrammableBlock>(pbs, x => x.CustomName.Contains(weaponClass)); if (pbs.Count > 0) { pbs.First().TryRun("SelectTarget " + selectedEntityId); } } } else if (argument.StartsWith("Broadcast")) { IGC.SendBroadcastMessage("tag", "Navigate HIT " + selectedEntityId, TransmissionDistance.AntennaRelay); } else { //read all inputs foreach (var mdei in StringToMDEIs(argument)) { if (!mdeis.ContainsKey(mdei.EntityId) || mdeis[mdei.EntityId].TimeStamp < mdei.TimeStamp) { mdeis[mdei.EntityId] = mdei; } } StringBuilder outString = new StringBuilder(); foreach (long entID in mdeis.Keys) { outString.AppendFormat("{0} {1,-15} {2,6:N1}\n", entID == selectedEntityId ? "X" : " ", mdeis[entID].Name, Vector3.Distance(Me.CubeGrid.GridIntegerToWorld(Me.Position), mdeis[entID].Position)); } string resultStr = outString.ToString(); List <IMyTextPanel> outPanels = new List <IMyTextPanel>(); GridTerminalSystem.GetBlocksOfType <IMyTextPanel>(outPanels, x => { return(x.CustomName.Contains("[TC]")); }); foreach (var panel in outPanels) { panel.WritePublicText(resultStr); } } }
void doModeDocking() { StatusLog("clear", textPanelReport); StatusLog(moduleName + ":DOCKING!", textPanelReport); // StatusLog(moduleName + ":Docking: current_state=" + current_state, textPanelReport); // StatusLog(moduleName + ":Docking: current_state=" + current_state, textLongStatus, true); // bWantFast = true; Echo("DOCKING: state=" + current_state); bWantSlow = true; IMySensorBlock sb; if (dockingConnector == null) { current_state = 0; } // sInitResults += "DOCKING: state=" + current_state+"\n"; if (current_state == 0) { // sInitResults = "DOCKING: state=" + current_state+"\n"; if (AnyConnectorIsConnected()) { setMode(MODE_DOCKED); return; } // these will replace any existing channel _CONDIGCChannel = IGC.RegisterBroadcastListener("COND"); // What it listens for _CONDIGCChannel.SetMessageCallback("COND"); // What it will run the PB with once it has a message _ACONDIGCChannel = IGC.RegisterBroadcastListener("ACOND"); // What it listens for _ACONDIGCChannel.SetMessageCallback("ACOND"); // What it will run the PB with once it has a message _CONAIGCChannel = IGC.RegisterBroadcastListener("CONA"); // What it listens for _CONAIGCChannel.SetMessageCallback("CONA"); // What it will run the PB with once it has a message doSubModuleTimerTriggers("[DOCKING]"); dockingConnector = getDockingConnector(); if (dockingConnector == null)// || getAvailableRemoteConnector(out targetConnector)) { Echo("No local connector for docking"); StatusLog(moduleName + ":No local Docking Connector Available!", textLongStatus, true); // we could check for merge blocks.. or landing gears.. sStartupError += "\nNo local Docking Connector Available!"; setMode(MODE_ATTENTION); bWantFast = false; return; } else { ResetMotion(); turnDrillsOff(); thrustersInit(dockingConnector, ref thrustDockForwardList, ref thrustDockBackwardList, ref thrustDockDownList, ref thrustDockUpList, ref thrustDockLeftList, ref thrustDockRightList); current_state = 100; } lTargetBase = 0;// iTargetBase = -1; } Vector3D vPos = dockingConnector.GetPosition(); if (!AnyConnectorIsConnected() && AnyConnectorIsLocked()) { ConnectAnyConnectors(); ResetMotion(); setMode(MODE_DOCKED); powerDownThrusters(thrustAllList, thrustAll, true); return; } if (current_state == 100) { // TODO: allow for relay ships that are NOT bases.. // TODO: if memory docking, don't need to adjust antenna // TODO: if stealth mode, don't mess with antenna float range = RangeToNearestBase() + 100f + (float)velocityShip * 5f; antennaMaxPower(false, range); if (sensorsList.Count > 0) { sb = sensorsList[0]; // setSensorShip(sb, 1, 1, 1, 1, 50, 1); } current_state = 110; } else if (current_state == 110) { // wait for slow if (velocityShip < 10) { if (lTargetBase <= 0) { lTargetBase = BaseFindBest(); } // sInitResults += "110: Base=" + iTargetBase; dtDockingActionStart = DateTime.Now; if (lTargetBase > 0) { calculateGridBBPosition(dockingConnector); Vector3D[] points = new Vector3D[4]; _obbf.GetFaceCorners(5, points); // 5 = front // front output order is BL, BR, TL, TR double width = (points[0] - points[1]).Length(); double height = (points[0] - points[2]).Length(); _obbf.GetFaceCorners(0, points); // face 0=right output order is BL, TL, BR, TR ??? double length = (points[0] - points[2]).Length(); string sMessage = "";// = "WICO:CON?:"; string sTag = "CON?"; sMessage += lTargetBase.ToString() + ":"; //$"{height:N1},{width:N1},{length:N1}:"; sMessage += height.ToString("0.0") + "," + width.ToString("0.0") + "," + length.ToString("0.0") + ":"; // sMessage += shipDim.HeightInMeters() + "," + shipDim.WidthInMeters() + "," + shipDim.LengthInMeters() + ":"; sMessage += shipOrientationBlock.CubeGrid.CustomName + ":"; sMessage += SaveFile.EntityId.ToString() + ":"; sMessage += Vector3DToString(shipOrientationBlock.GetPosition()); antSend(sTag, sMessage); // antSend(sMessage); // antSend("WICO:CON?:" + baseIdOf(iTargetBase).ToString() + ":" + "mini" + ":" + shipOrientationBlock.CubeGrid.CustomName + ":" + SaveFile.EntityId.ToString() + ":" + Vector3DToString(shipOrientationBlock.GetPosition())); current_state = 120; } else // No available base { // try to get a base to respond checkBases(true); current_state = 130; // setMode(MODE_ATTENTION); } } else { ResetMotion(); } } else if (current_state == 120) { // wait for reply from base StatusLog("Awaiting Response from Base", textPanelReport); bWantFast = false; DateTime dtMaxWait = dtDockingActionStart.AddSeconds(5.0f); DateTime dtNow = DateTime.Now; if (DateTime.Compare(dtNow, dtMaxWait) > 0) { sStartupError += "\nTime out awaiting CONA"; current_state = 125; return; } // if (sReceivedMessage != "") if (_CONAIGCChannel.HasPendingMessage) { var igcMessage = _CONAIGCChannel.AcceptMessage(); string sMessage = (string)igcMessage.Data; // Echo("Received Message=\n" + sMessage); string[] aMessage = sMessage.Trim().Split(':'); Echo(aMessage.Length + ": Length"); for (int i = 0; i < aMessage.Length; i++) { Echo(i + ":" + aMessage[i]); } if (aMessage.Length > 1) { /* * if (aMessage[0] != "WICO") * { * Echo("not wico system message"); * return; * } * if (aMessage.Length > 2) * { * if (aMessage[1] == "CONA") * { */ Echo("Approach answer!"); //antSend("WICO:CONA:" + droneId +":" + SaveFile.EntityId.ToString(), +":"+Vector3DToString(vApproachPosition)) int iOffset = 0; long id = 0; long.TryParse(aMessage[iOffset++], out id); if (id == SaveFile.EntityId) { // it's a message for us. // sReceivedMessage = ""; // we processed it. long.TryParse(aMessage[iOffset++], out id); double x, y, z; // int iOff = iOffset++; x = Convert.ToDouble(aMessage[iOffset++]); y = Convert.ToDouble(aMessage[iOffset++]); z = Convert.ToDouble(aMessage[iOffset++]); Vector3D vPosition = new Vector3D(x, y, z); vHome = vPosition; bValidHome = true; // StatusLog("clear", gpsPanel); // debugGPSOutput("Home", vHome); current_state = 150; } } // TODO: need to process CONF /* * } * } */ } else { // uses timeout from above Echo("Awaiting reply message"); } } else if (current_state == 125) { // timeout waiting for reply from base.. // move closer to the chosen base's last known position. if (lTargetBase <= 0) { // TODO: remove base from list and try again. ATTENTION if no remaining bases sStartupError += "\nNo Base in range"; setMode(MODE_ATTENTION); return; } else if (RangeToNearestBase() < 3000) { // we think we are close enough // force recheck // sStartupError += "\nForce Recheck"; lTargetBase = -1; checkBases(true); current_state = 110; } else { // get closer // sStartupError += "\nGet Closer"; NavGoTarget(BasePositionOf(lTargetBase), iMode, 110, 3100, "DOCK Base Proximity"); current_state = 126; } // doTravelMovement(BasePositionOf(lTargetBase), 3100, 110, 106); } else if (current_state == 126) { // we are waiting for NAV module to get message and start Echo("Waiting for NAV to start"); } else if (current_state == 130) { // no known bases. requested response. wait for a while to see if we get one StatusLog("Trying to find a base", textPanelReport); bWantFast = false; DateTime dtMaxWait = dtDockingActionStart.AddSeconds(2.0f); DateTime dtNow = DateTime.Now; if (DateTime.Compare(dtNow, dtMaxWait) > 0) { sStartupError += "\nTimeout finding base"; setMode(MODE_ATTENTION); return; } if (BaseFindBest() >= 0) { current_state = 110; } } else if (current_state == 150) { //150 Move to 'approach' location (or current location) ?request 'wait' location? current_state = 175; /* * if (bValidHome) * { * double distancesqHome = Vector3D.DistanceSquared(vHome, shipOrientationBlock.GetPosition()); * if (distancesqHome > 25000) // max SG antenna range //TODO: get max from antenna module * { * current_state = 175; * } * else current_state = 200; * } * else current_state = 200; */ } else if (current_state == 175) { // get closer to approach location NavGoTarget(vHome, iMode, 200, 5, "DOCK Base Approach"); current_state = 176; } else if (current_state == 176) { // we are waiting for NAV module to get message and start Echo("Waiting for NAV to start"); } else if (current_state == 200) {//200 Arrived at approach location // request available docking connector StatusLog("Requsting Docking Connector", textPanelReport); if (velocityShip < 1) { calculateGridBBPosition(dockingConnector); Vector3D[] points = new Vector3D[4]; _obbf.GetFaceCorners(5, points); // 5 = front // front output order is BL, BR, TL, TR double width = (points[0] - points[1]).Length(); double height = (points[0] - points[2]).Length(); _obbf.GetFaceCorners(0, points); // face 0=right output order is BL, TL, BR, TR ??? double length = (points[0] - points[2]).Length(); string sMessage = "";// "WICO:COND?:"; string sTag = "COND?"; sMessage += lTargetBase.ToString() + ":"; sMessage += height.ToString("0.0") + "," + width.ToString("0.0") + "," + length.ToString("0.0") + ":"; // sMessage += shipDim.HeightInMeters() + "," + shipDim.WidthInMeters() + "," + shipDim.LengthInMeters() + ":"; sMessage += shipOrientationBlock.CubeGrid.CustomName + ":"; sMessage += SaveFile.EntityId.ToString() + ":"; sMessage += Vector3DToString(shipOrientationBlock.GetPosition()); antSend(sTag, sMessage);// antSend(sMessage); // antSend("WICO:COND?:" + baseIdOf(iTargetBase) + ":" + "mini" + ":" + shipOrientationBlock.CubeGrid.CustomName + ":" + SaveFile.EntityId.ToString() + ":" + Vector3DToString(shipOrientationBlock.GetPosition())); { dtDockingActionStart = DateTime.Now; current_state = 210; } } else { ResetMotion(); } } else if (current_state == 210) { //210 wait for available connector StatusLog("Awaiting reply with Docking Connector", textPanelReport); bWantFast = false; DateTime dtMaxWait = dtDockingActionStart.AddSeconds(5.0f); DateTime dtNow = DateTime.Now; if (DateTime.Compare(dtNow, dtMaxWait) > 0) { sStartupError += "\nTime out awaiting COND"; current_state = 100; return; } if (getAvailableRemoteConnector(out targetConnector)) { current_state = 250; } else { if (_CONDIGCChannel.HasPendingMessage || _ACONDIGCChannel.HasPendingMessage) // if (sReceivedMessage != "") { // sStartupError += "\nCOND received:"; string sMessage = ""; bool bAlignMessage = false; if (_CONDIGCChannel.HasPendingMessage) { var igcMessage = _CONDIGCChannel.AcceptMessage(); sMessage = (string)igcMessage.Data; } else { var igcMessage = _ACONDIGCChannel.AcceptMessage(); sMessage = (string)igcMessage.Data; bAlignMessage = true; } // Echo("Received Message=\n" + sReceivedMessage); string[] aMessage = sMessage.Trim().Split(':'); Echo(aMessage.Length + ": Length"); for (int i = 0; i < aMessage.Length; i++) { Echo(i + ":" + aMessage[i]); } int iOffset = 0; /* * if (aMessage.Length > 1) * { * if (aMessage[0] != "WICO") * { * Echo("not wico system message"); * return; * } * if (aMessage.Length > 2) * { */ // if (aMessage[1] == "DOCK" || aMessage[1] == "ADOCK") // if (aMessage[1] == "COND" || aMessage[1] == "ACOND") { Echo("Docking answer!"); // FORMAT: antSend("WICO:DOCK:" + aMessage[3] + ":" + connector.EntityId + ":" + connector.CustomName + ":" + Vector3DToString(vPosition) + ":" + Vector3DToString(vVec)); // antSend("WICO:ADOCK:" + incomingID + ":" + connector.EntityId + ":" + connector.CustomName + ":" + Vector3DToString(vPosition) + ":" + Vector3DToString(vVec)+":" + Vector3DToString(vAlign)); long id = 0; long.TryParse(aMessage[iOffset++], out id); if (id == SaveFile.EntityId) { // it's a message for us. // sReceivedMessage = ""; // we processed it. long.TryParse(aMessage[iOffset++], out id); string sName = aMessage[iOffset++]; double x, y, z; // int iOff = 5; x = Convert.ToDouble(aMessage[iOffset++]); y = Convert.ToDouble(aMessage[iOffset++]); z = Convert.ToDouble(aMessage[iOffset++]); Vector3D vPosition = new Vector3D(x, y, z); x = Convert.ToDouble(aMessage[iOffset++]); y = Convert.ToDouble(aMessage[iOffset++]); z = Convert.ToDouble(aMessage[iOffset++]); Vector3D vVec = new Vector3D(x, y, z); // if (aMessage[1] == "ACOND") if (bAlignMessage) { x = Convert.ToDouble(aMessage[iOffset++]); y = Convert.ToDouble(aMessage[iOffset++]); z = Convert.ToDouble(aMessage[iOffset++]); vDockAlign = new Vector3D(x, y, z); bDoDockAlign = true; } vDock = vPosition; vLaunch1 = vDock + vVec * (shipDim.LengthInMeters() * 1.5); vHome = vDock + vVec * (shipDim.LengthInMeters() * 3); bValidDock = true; bValidLaunch1 = true; bValidHome = true; StatusLog("clear", gpsPanel); debugGPSOutput("dock", vDock); debugGPSOutput("launch1", vLaunch1); debugGPSOutput("Home", vHome); current_state = 300; } // else sStartupError += "\nCOND, but not my boat"; } // TODO handle CONF /* * } * } */ } else { // uses timeout from above Echo("Awaiting reply message"); } } } else if (current_state == 250) { //250 when available, calculate approach locations from a saved targetconnector vDock = targetConnector.vPosition; vLaunch1 = vDock + targetConnector.vVector * (shipDim.LengthInMeters() * 1.5); vHome = vDock + targetConnector.vVector * (shipDim.LengthInMeters() * 3); bValidDock = true; bValidLaunch1 = true; bValidHome = true; current_state = 300; StatusLog("clear", gpsPanel); debugGPSOutput("dock", vDock); debugGPSOutput("launch1", vLaunch1); debugGPSOutput("Home", vHome); MoveForwardSlowReset(); bWantFast = true; } else if (current_state == 300) { //300 Start: Move through locations current_state = 310; MoveForwardSlowReset(); // iDockingPushCount = 0; bWantFast = true; } else if (current_state == 310) { // 310 move to home Echo("Moving to Home"); // if(iPushCount<60) iPushCount++; // else NavGoTarget(vHome, iMode, 340, 3, "DOCK Approach"); // doTravelMovement(vHome, 3.0f, 350, 161); current_state = 311; } else if (current_state == 311) { // we are waiting for NAV module to get message and start Echo("Waiting for NAV to start"); } else if (current_state == 340) { // arrived at 'home' from NAV ResetMotion(); Echo("Waiting for ship to stop"); turnEjectorsOff(); MoveForwardSlowReset(); // iDockingPushCount = 0; if (velocityShip < 0.1f) { bWantFast = true; current_state = 350; } else { bWantMedium = true; // bWantFast = false; } } else if (current_state == 350) { // move connector closer to home double distanceSQ = (vHome - ((IMyShipController)shipOrientationBlock).CenterOfMass).LengthSquared(); Echo("DistanceSQ=" + distanceSQ.ToString("0.0")); double stoppingDistance = calculateStoppingDistance(thrustBackwardList, velocityShip, 0); if (distanceSQ > shipDim.BlockMultiplier() * 3) { MoveForwardSlow(3, 5, thrustForwardList, thrustBackwardList); bWantMedium = true; } else { ResetMotion(); doSubModuleTimerTriggers("[DOCKING:APPROACH]"); MoveForwardSlowReset(); current_state = 400; bWantFast = true; } } else if (current_state == 400) { // move to Launch1 Echo("Moving to Launch1"); NavGoTarget(vLaunch1, iMode, 410, 3, "DOCK Connector Entry"); current_state = 401; } else if (current_state == 401) { // we are waiting for NAV module to get message and start Echo("Waiting for NAV to start"); } else if (current_state == 410) { // move closer to Launch1 double distanceSQ = (vLaunch1 - ((IMyShipController)shipOrientationBlock).CenterOfMass).LengthSquared(); Echo("DistanceSQ=" + distanceSQ.ToString("0.0")); double stoppingDistance = calculateStoppingDistance(thrustBackwardList, velocityShip, 0); if (distanceSQ > shipDim.BlockMultiplier() * 3) { MoveForwardSlow(3, 5, thrustForwardList, thrustBackwardList); bWantMedium = true; } else { ResetMotion(); MoveForwardSlowReset(); current_state = 430; bWantFast = true; } } else if (current_state == 430) { // arrived at launch1 bWantFast = true; dockingLastDistance = -1; current_state = 450; // TODO: do/waitfor mechanical changes needed for docking } else if (current_state == 450 || current_state == 452) { //450 452 'reverse' to dock, aiming connector at dock location // align to docking alignment if needed StatusLog("Align Up to Docking Connector", textPanelReport); bWantFast = true; // turnEjectorsOff(); if (!bDoDockAlign) { current_state = 500; return; } Echo("Aligning to dock"); bool bAimed = false; minAngleRad = 0.03f; // TODO: need to change direction if non- 'back' connector bAimed = GyroMain("up", vDockAlign, shipOrientationBlock); bWantFast = true; if (current_state == 452) { current_state = 500; } else if (bAimed) { current_state++; // 450->451 } } else if (current_state == 451) { //451 align to dock StatusLog("Align to Docking Connector", textPanelReport); bWantFast = true; Vector3D vTargetLocation = vDock; Vector3D vVec = vTargetLocation - dockingConnector.GetPosition(); if (!bDoDockAlign) { current_state = 452; } // Vector3D vTargetLocation = shipOrientationBlock.GetPosition() +vDockAlign; // Vector3D vVec = vTargetLocation - shipOrientationBlock.GetPosition(); Echo("Aligning to dock"); bool bAimed = false; minAngleRad = 0.03f; bAimed = GyroMain("forward", vVec, dockingConnector); if (bAimed) { current_state = 452; } else { bWantFast = true; } } else if (current_state == 500) { //500 'reverse' to dock, aiming connector at dock location (really it's connector-forward) // TODO: needs a time-out for when misaligned or base connector moves. // bWantFast = true; StatusLog("Reversing to Docking Connector", textPanelReport); Echo("bDoDockAlign=" + bDoDockAlign); // StatusLog(moduleName + ":Docking: Reversing to dock! Velocity=" + velocityShip.ToString("0.00"), textPanelReport); Echo("Reversing to Dock"); CTRL_COEFF = 0.75; minAngleRad = 0.01f; Vector3D vTargetLocation = vDock; Vector3D vVec = vTargetLocation - dockingConnector.GetPosition(); double distance = vVec.Length(); Echo("distance=" + niceDoubleMeters(distance)); Echo("velocity=" + velocityShip.ToString("0.00")); StatusLog("Distance=" + niceDoubleMeters(distance), textPanelReport); StatusLog("Velocity=" + niceDoubleMeters(velocityShip) + "/s", textPanelReport); if (dockingLastDistance < 0) { dockingLastDistance = distance; } if (dockingLastDistance < distance) { // we are farther away than last time... something is wrong.. // sStartupError += "\nLast=" + niceDoubleMeters(dockingLastDistance) + " Cur=" + niceDoubleMeters(distance); current_state = 590; } if (distance > 10) { minAngleRad = 0.03f; } else { minAngleRad = 0.05f; } // debugGPSOutput("DockLocation", vTargetLocation); bool bAimed = false; /* * if ((craft_operation & CRAFT_MODE_SLED) > 0) * { * double yawangle = CalculateYaw(vTargetLocation, dockingConnector); * DoRotate(yawangle, "Yaw"); * if (Math.Abs(yawangle) < .05) bAimed = true; * } * else */ if (distance > 15) { bAimed = BeamRider(vLaunch1, vDock, dockingConnector); } else { bAimed = GyroMain("forward", vVec, dockingConnector); } /* * double maxThrust = calculateMaxThrust(thrustDockForwardList); * MyShipMass myMass; * myMass = ((IMyShipController)shipOrientationBlock).CalculateShipMass(); * double effectiveMass = myMass.PhysicalMass; * double maxDeltaV = (maxThrust) / effectiveMass; * if (iDockingPushCount < 1) * { * if (maxDeltaV < 2) * iDockingPushCount = 75; * else if (maxDeltaV < 5) * iDockingPushCount = 25; * } */ // Echo("dockingPushCount=" + iDockingPushCount); // TODO: if we aren't moving and dockingpushcount>100, then we need to wiggle. if (bAimed) { // we are aimed at location Echo("Aimed"); if (distance > 15) { bWantMedium = true; Echo(">15"); MoveForwardSlow(5, 10, thrustDockForwardList, thrustDockBackwardList); /* * if (velocityShip < .5) * { * iDockingPushCount++; * powerUpThrusters(thrustDockForwardList, 25 + iDockingPushCount); * } * else if (velocityShip < 5) * { * powerUpThrusters(thrustDockForwardList, 1); * } * else * powerDownThrusters(thrustAllList); */ } else { Echo("<=15"); bWantFast = true; MoveForwardSlow(.5f, 1.5f, thrustDockForwardList, thrustDockBackwardList); /* * if (velocityShip < .5) * { * iDockingPushCount++; * powerUpThrusters(thrustDockForwardList, 25 + iDockingPushCount); * } * else if (velocityShip < 1.4) * { * powerUpThrusters(thrustDockForwardList, 1); * if (iDockingPushCount > 0) iDockingPushCount--; * } * else * powerDownThrusters(thrustAllList); */ } } else { Echo("Aiming"); powerDownThrusters(thrustAllList); bWantFast = true; } } else if (current_state == 590) { // abort dock and try again ResetMotion(); Vector3D vVec = vDock - dockingConnector.GetPosition(); double distance = vVec.Length(); if (distance > shipDim.LengthInMeters() * 1.25) { // we are far enough away. Try again current_state = 0; bWantFast = true; return; } bool bAimed = GyroMain("forward", vVec, dockingConnector); if (!bAimed) { bWantFast = true; } else { bWantMedium = true; } MoveForwardSlow(5, 10, thrustDockBackwardList, thrustDockForwardList); } }
void SendToAEGIS(string tag, string message) { IGC.SendBroadcastMessage(tag, message); }
public void Main(string argument, UpdateType updateSource) { Runtime.UpdateFrequency = UpdateFrequency.Update100 | UpdateFrequency.Update10; IMyTextPanel textPanel = (IMyTextPanel)GridTerminalSystem.GetBlockWithName("LCD"); IMySensorBlock mySensorBlock = (IMySensorBlock)GridTerminalSystem.GetBlockWithName("EraserSensor"); if (mySensorBlock.IsActive) { allmessage = ""; textPanel.WriteText(""); } // If setupcomplete is false, run Setup method. if (!setupcomplete) { Echo("Running setup."); Setup(); } else { string tag1 = "Channel-1"; // To create a listener, we use IGC to access the relevant method. // We pass the same tag argument we used for our message. IGC.RegisterBroadcastListener(tag1); // Create a list for broadcast listeners. List <IMyBroadcastListener> listeners = new List <IMyBroadcastListener>(); // The method argument below is the list we wish IGC to populate with all Listeners we've made. // Our Listener will be at index 0, since it's the only one we've made so far. IGC.GetBroadcastListeners(listeners); if (listeners[0].HasPendingMessage) { // Let's create a variable for our new message. // Remember, messages have the type MyIGCMessage. MyIGCMessage message = new MyIGCMessage(); // Time to get our message from our Listener (at index 0 of our Listener list). // We do this with the following method: message = listeners[0].AcceptMessage(); // A message is a struct of 3 variables. To read the actual data, // we access the Data field, convert it to type string (unboxing), // and store it in the variable messagetext. string messagetext = message.Data.ToString(); // We can also access the tag that the message was sent with. string messagetag = message.Tag; //Here we store the "address" to the Programmable Block (our friend's) that sent the message. long sender = message.Source; //Do something with the information! Echo("Message received with tag" + messagetag + "\n\r"); Echo("from address " + sender.ToString() + ": \n\r"); Echo(messagetext); allmessage += $"\n new message \n {messagetext}"; textPanel.WriteText(allmessage); } } int textlength = textPanel.GetText().Length; if (textlength > 100) { allmessage = ""; } }