public void Main(string _argument, UpdateType updateSource)
        {
            counter++;

            if (updateSource == UpdateType.Terminal || firstRun)
            {
                argument = _argument;
                Initialise();
            }

            if (!test)
            {
                switch (ConnectorFront.Status)
                {
                case MyShipConnectorStatus.Unconnected:
                    ExtendPistons();
                    break;

                case MyShipConnectorStatus.Connectable:
                    if (PistonBack1.Status == PistonStatus.Extended)
                    {
                        ConnectorFront.Connect();
                        ConnectorBack.Disconnect();
                    }
                    break;

                case MyShipConnectorStatus.Connected:

                    break;
                }

                switch (ConnectorBack.Status)
                {
                case MyShipConnectorStatus.Unconnected:
                    RetractPistons();
                    break;

                case MyShipConnectorStatus.Connectable:
                    if (PistonBack1.Status == PistonStatus.Retracted)
                    {
                        ConnectorBack.Connect();
                        ConnectorFront.Disconnect();
                    }
                    break;

                case MyShipConnectorStatus.Connected:
                    if (ConnectorFront.Status == MyShipConnectorStatus.Connected)
                    {
                        ConnectorBack.Disconnect();
                        RetractPistons();
                    }
                    break;
                }
            }

            UpdateAssemblers();

            PrintStatus();
        }
            public void Update()
            {
                MyShipConnectorStatus ship_connector_status = shipConnector.Status;

                if (lastShipConnectorStatus != ship_connector_status)
                {
                    switch (ship_connector_status)
                    {
                    case MyShipConnectorStatus.Unconnected:
                    case MyShipConnectorStatus.Connectable:
                        if (lastShipConnectorStatus == MyShipConnectorStatus.Connected)
                        {
                            if (registeredShipIGC == null)
                            {
                                OnForeignGridDisconnected?.Invoke(lastConnectedEntityID);
                            }
                            else if (lastConnectedEntityID == registeredShipIGC.ShipID)
                            {
                                OnRegisteredShipDisconnected?.Invoke(registeredShipIGC);
                            }
                            else
                            {
                                OnForeignGridDisconnected?.Invoke(lastConnectedEntityID);
                            }
                        }
                        break;

                    case MyShipConnectorStatus.Connected:
                        lastConnectedEntityID = shipConnector.OtherConnector.CubeGrid.EntityId;
                        if (registeredShipIGC == null)
                        {
                            shipConnector.Disconnect();
                            OnForeignGridConnected?.Invoke(lastConnectedEntityID);
                        }
                        else if (shipConnector.OtherConnector.CubeGrid.EntityId == registeredShipIGC.ShipID)
                        {
                            OnRegisteredShipConnected?.Invoke(registeredShipIGC);
                        }
                        else
                        {
                            shipConnector.Disconnect();
                            OnForeignGridConnected?.Invoke(lastConnectedEntityID);
                        }
                        break;
                    }
                    lastShipConnectorStatus = ship_connector_status;
                }
            }
Example #3
0
 public void MoveX() // step 1, release and move piston
 {
     _PistonX.Enabled = true;
     if (xDir == Dir.forward || xDir == Dir.backward)
     {
         _MoveConX.Connect();
         if (_MoveConX.Status == MyShipConnectorStatus.Connected)
         {
             _ConnectorX.Disconnect();
             _MergeX.Enabled = false;
             if (xPosMerge < xTar)
             {
                 _PistonX.Velocity = -1 * maxMovementSpeed;
                 xDir = Dir.movingForward;
             }
             else if (xPosMerge > xTar)
             {
                 _PistonX.Velocity = maxMovementSpeed;
                 xDir = Dir.movingBackward;
             }
         }
     }
     else if (xDir == Dir.movingForward || xDir == Dir.movingBackward) // step 2, merge and continue
     {
         _MergeX.Enabled = true;
         if (_MergeX.IsConnected)
         {
             moveReady = true;
             _ConnectorX.Connect();
             _MoveConX.Disconnect();
             if (xDir == Dir.movingForward)
             {
                 xDir = Dir.forward;
                 if (autoMode)
                 {
                     _PistonX.Velocity = maxToolSpeed;
                 }
                 else
                 {
                     _PistonX.Velocity = maxMovementSpeed;
                 }
             }
             if (xDir == Dir.movingBackward)
             {
                 xDir = Dir.backward;
                 if (autoMode)
                 {
                     _PistonX.Velocity = -1 * maxToolSpeed;
                 }
                 else
                 {
                     _PistonX.Velocity = -1 * maxMovementSpeed;
                 }
             }
         }
     }
 }
// TODO надо переработать
    public void ActionUndock()
    {
        PrintLine($"Do Action <ActionUndock>");

        PrintLine("Undocking...");
        switch (State["stage"])
        {
        case STAGE_DOCKED:
            if (Events[0] == EVENT_MOVING_DOWN && bottom_connector.Status == CONNECTED)
            {
                PrintLine("Disconnect TOP, MID.");
                top_connector.Disconnect();
                middle_connector.Disconnect();
            }
            else if (Events[0] == EVENT_MOVING_UP && top_connector.Status == CONNECTED)
            {
                middle_connector.Disconnect();
                bottom_connector.Disconnect();
            }
            else
            {
                PrintLine("<Error while Trying undock>");
            }
            break;

        case STAGE_DOCKED_BETWEEN:
            if (Events[0] == EVENT_MOVING_DOWN && top_connector.Status == CONNECTED)
            {
                PrintLine("Disconnect MID, BOT.");
                bottom_connector.Disconnect();
            }
            else if (Events[0] == EVENT_MOVING_UP && bottom_connector.Status == CONNECTED)
            {
                top_connector.Disconnect();
            }
            else
            {
                PrintLine("<Error while Trying undock>");
            }
            break;
        }
    }
Example #5
0
 static void Connect(IMyShipConnector connector, bool value)
 {
     if (value)
     {
         connector.Connect();
     }
     else
     {
         connector.Disconnect();
     }
 }
Example #6
0
 void ToggleConnector(bool connect = true)
 {
     if (_connectorBlock != null)
     {
         if (connect)
         {
             _connectorBlock.Connect();
         }
         else
         {
             _connectorBlock.Disconnect();
         }
     }
 }
        public void CheckHummingbird()
        {
            status = releaseStage.ToString();
            if (releaseStage == 0)
            {
                // Check for completeness
                if (!Hummingbird.CheckHummingbirdComponents(ChasisMerge, ref hummingbirdConnector, ref turretRotor, ref PartScratchpad, ref status))
                {
                    return;
                }

                if (!Hummingbird.CheckHummingbirdComponents(TurretMerge, ref hummingbirdConnector, ref turretRotor, ref PartScratchpad, ref status))
                {
                    return;
                }

                if (turretRotor == null || hummingbirdConnector == null)
                {
                    return;
                }

                turretRotor.Detach();

                Connector.Connect();

                var inventoryItem = Host.AmmoBox?.GetItemAt(0);
                if (inventoryItem != null)
                {
                    Host.AmmoBox.TransferItemTo(Connector.OtherConnector.GetInventory(0), (MyInventoryItem)inventoryItem);
                }

                Connector.Disconnect();

                releaseStage    = 1;
                Piston.Velocity = -0.2f;
            }
            else if (releaseStage == 1)
            {
                // Move pistons
                if (Piston.CurrentPosition == Piston.MinLimit)
                {
                    releaseStage = 2;
                }
            }
            else if (releaseStage < 0)
            {
                releaseStage++;
            }
        }
Example #8
0
 void CheckConnector()
 {
     if ((flags & SpaceshipFlags.Dock) == SpaceshipFlags.Dock)
     {
         if (connector.Status == MyShipConnectorStatus.Connectable)
         {
             connector.Connect();
         }
     }
     else if ((flags & SpaceshipFlags.Undock) == SpaceshipFlags.Undock)
     {
         if (connector.Status == MyShipConnectorStatus.Connected)
         {
             connector.Disconnect();
         }
     }
 }
Example #9
0
            void queueConnectionRoute(Vector3D target, Vector3D orientation)
            {
                this.waypoints.Clear();
                ConnectionType   connectionType = Math.Abs(orientation.Dot(UP)) > 0.8 ? ConnectionType.Down : ConnectionType.Front;
                float            angle          = connectionType == ConnectionType.Front ? this.getTargetAngle(orientation) : 0;
                IMyShipConnector con            = this.getCurrentConnected();
                Vector3D         curPos         = this.transformer.Pos((con ?? this.stator ?? this.frontConnector ?? this.downConnector as IMyTerminalBlock).GetPosition());
                ConnectionType   firstType      = ConnectionType.None;

                if (con != null)
                {
                    con.Disconnect();
                    Vector3D firstPos = curPos + (this.transformer.Dir(con.WorldMatrix.Backward) * CONNECTION_SAFETY_OFFSET);
                    // we give a connection type to have the correct connector positioned
                    this.waypoints.Enqueue(new Waypoint(
                                               firstPos,
                                               angle: this.stator?.Angle ?? 0,
                                               needPrecision: true
                                               ));
                    firstType = con == this.frontConnector ? ConnectionType.Front : ConnectionType.Down;
                    curPos    = firstPos;
                }
                Vector3D safetyTarget = target + (orientation * CONNECTION_SAFETY_OFFSET);

                // we give a connection type to have the correct connector positioned for the first points
                this.waypoints.Enqueue(new Waypoint(
                                           new Vector3D(curPos.X, this.max.Y, curPos.Z),
                                           connection: firstType
                                           )).Enqueue(new Waypoint(
                                                          new Vector3D(safetyTarget.X, this.max.Y, safetyTarget.Z)
                                                          )).Enqueue(new Waypoint(
                                                                         new Vector3D(safetyTarget.X, this.max.Y - 3, safetyTarget.Z)
                                                                         )).Enqueue(new Waypoint(
                                                                                        new Vector3D(safetyTarget.X, safetyTarget.Y, safetyTarget.Z),
                                                                                        angle
                                                                                        )).Enqueue(new Waypoint(
                                                                                                       new Vector3D(target.X, target.Y, target.Z),
                                                                                                       angle,
                                                                                                       connectionType,
                                                                                                       needPrecision: true
                                                                                                       ));
            }
Example #10
0
 private void PreFlightPreparations()
 {
     Runtime.UpdateFrequency = UpdateFrequency.Update10;
     Clamp.AutoLock          = false;
     foreach (IMyBatteryBlock battery in Batteries)
     {
         battery.ChargeMode = ChargeMode.Auto;
     }
     foreach (IMyThrust thruster in Thrusters)
     {
         thruster.Enabled = true;
     }
     foreach (IMyGyro gyro in Gyros)
     {
         gyro.Enabled = true;
     }
     Connector.Disconnect();
     Connector.Enabled = false;
     Antenna.Enabled   = true;
 }
Example #11
0
            /// <summary>Requests the autoconnector to disconnect</summary>
            public void Disconnect()
            {
                this.waypoints.Clear();
                IMyShipConnector connector = this.getCurrentConnected()
                                             ?? this.getConnector(this.lastConnectionType)
                                             ?? this.frontConnector
                                             ?? this.downConnector;
                Vector3D curPos         = this.transformer.Pos(connector.GetPosition());
                Vector3D curOrientation = this.transformer.Dir(connector.WorldMatrix.Backward);

                connector.Disconnect();
                Vector3D safetyTarget = curPos + (curOrientation * CONNECTION_SAFETY_OFFSET);

                this.waypoints.Enqueue(new Waypoint(
                                           new Vector3D(safetyTarget.X, safetyTarget.Y, safetyTarget.Z),
                                           this.stator?.Angle ?? 0,
                                           needPrecision: true
                                           )).Enqueue(new Waypoint(
                                                          new Vector3D(safetyTarget.X, this.max.Y, safetyTarget.Z)
                                                          )).Enqueue(new Waypoint(
                                                                         this.restPosition
                                                                         ));
            }
Example #12
0
        public void Main(string argument, UpdateType updateSource)
        {
            write_settings();

            if (updateSource.Equals(UpdateType.Update100))
            {
                drill_pistons_command("status");

                //pistons at max, connector connected
                condition1 = drill_pistons_group_current_distance == drill_pistons_group_max_distance;
                condition2 = drill_connector_status == "Connected";
                if (condition1 & condition2)
                {
                    drill_status = "wait";
                    drill_drills_command("stop");
                    drill_landing_gears_command("status");
                    if (drill_landing_gears_locked == true)
                    {
                        Runtime.UpdateFrequency = UpdateFrequency.None;
                        drill_connector.Disconnect();
                        drill_connector_status = "Unconnected";
                        drill_pistons_command("retract");
                    }
                    write_settings();
                }

                //drill connected and ready
                condition1 = drill_status == "ready";
                condition2 = drill_connector_status == "Connected";
                if (condition1 & condition2)
                {
                    drill_status = "stopped";
                    drill_drills_command("start");
                    drill_status = "running";
                    write_settings();
                }
            }
            else if (updateSource.Equals(UpdateType.Update1))
            {
                //drill wait but unconnected
                condition1 = drill_status == "wait";
                condition2 = drill_connector_status == "reconnecting";
                if (condition1 & condition2)
                {
                    drill_connector.Connect();
                    if (drill_connector.Status.ToString() == "Connected")
                    {
                        drill_status            = "ready";
                        drill_connector_status  = "Connected";
                        Runtime.UpdateFrequency = UpdateFrequency.Update100;
                        write_settings();
                    }
                }
            }
            else if (updateSource.Equals(UpdateType.Trigger) | updateSource.Equals(UpdateType.Terminal))
            {
                write_settings();

                if (argument != "")
                {
                    drill_status = argument;
                }

                verify_availability();

                //switch running state
                if (drill_status == "running")
                {
                    drill_drills_command("stop");
                    drill_status = "stopped";
                }
                else if (drill_status == "stopped")
                {
                    drill_drills_command("start");
                    drill_status = "running";
                }
                else if (drill_status == "wait")
                {
                    drill_pistons_command("reconnect");
                    drill_connector_status  = "reconnecting";
                    Runtime.UpdateFrequency = UpdateFrequency.Update1;
                }
                else
                {
                    drill_status = "stopped";
                    drill_drills_command("stop");
                    drill_status = "stopped";
                }
            }

            //write settings to Programmable block Custom Data field and LCD
            write_settings();
        }
Example #13
0
            Vector3D dockPos3 = new Vector3D(); //Straight Up And Forward Location
            private void DockingIterator(bool Docking, List <Vector3D> COORDINATES, IMyGyro GYRO, IMyShipConnector CONNECTOR, IMyRemoteControl RC)
            {
                if (COORDINATES.Count < 3)
                {
                    return;
                }

                int TargetID  = 0;
                int CurrentID = 0;
                int iter_er   = 0;

                if (Docking == true)
                {
                    TargetID = 1; CurrentID = 0; iter_er = +1;
                }
                if (Docking == false)
                {
                    TargetID = 0; CurrentID = 1; iter_er = -1;
                }

                if (Docking == true)
                {
                    CONNECTOR.Connect();
                }
                if (Docking == true && CONNECTOR.IsWorking == false)
                {
                    CONNECTOR.Enabled = true;
                }
                if (Docking == false && CONNECTOR.IsWorking == true)
                {
                    CONNECTOR.Disconnect(); CONNECTOR.Enabled = true;
                }
                if (CONNECTOR.Status == MyShipConnectorStatus.Connected && Docking == true)
                {
                    for (int j = 0; j < CAF2_THRUST.Count; j++)
                    {
                        (CAF2_THRUST[j] as IMyThrust).Enabled = false;
                    }
                    GYRO.GyroOverride = false;
                    return;
                }
                Vector3D RollOrienter        = Vector3D.Normalize(COORDINATES[COORDINATES.Count - 1] - COORDINATES[COORDINATES.Count - 2]);
                Vector3D Connector_Direction = -1 * ReturnConnectorDirection(CONNECTOR, RC);
                double   RollReqt            = (float)(0.6 * (Vector3D.Dot(RollOrienter, Connector_Direction)));

                //垂直运动在码头
                if (COORD_ID == COORDINATES.Count - 1)
                {
                    Vector3D DockingHeading = Vector3D.Normalize(COORDINATES[COORDINATES.Count - 3] - COORDINATES[COORDINATES.Count - 2]) * 9000000; //Heading
                    GyroTurn6(DockingHeading, RotationalSensitvity, GYRO, RC, RollReqt, PrecisionMaxAngularVel);                                     //Turn to heading
                    if (Vector3D.Dot(RC.WorldMatrix.Forward, Vector3D.Normalize(DockingHeading)) > 0.98)                                             //Error check for small rotational velocity
                    {
                        Vector_Thrust_Manager(COORDINATES[COORD_ID - TargetID], COORDINATES[COORD_ID - CurrentID], CONNECTOR.GetPosition(), 5, 0.7, RC);
                    }                                                                                                                                     //Thrusts to point
                }

                //在码头上的最后/第一个外部Coord
                else if (COORD_ID == 0)
                {
                    print($"启动自动驾驶\n距离目标:{Vector3D.Distance(COORDINATES[0], RC.GetPosition())}");
                    RC_Manager(COORDINATES[0], RC, false);
                }

                //水平和迭代语句
                else
                {
                    var HEADING = Vector3D.Normalize(COORDINATES[COORD_ID - CurrentID] - COORDINATES[COORD_ID - TargetID]) * 9000000;
                    Vector_Thrust_Manager(COORDINATES[COORD_ID - TargetID], COORDINATES[COORD_ID - CurrentID], CONNECTOR.GetPosition(), 8, 1, RC); //Runs docking sequence
                    GyroTurn6(HEADING, RotationalSensitvity, GYRO, RC, RollReqt, PrecisionMaxAngularVel);
                }

                //逻辑检查和迭代
                if (Docking == false && COORD_ID == 0)
                {
                }
                else if ((CONNECTOR.GetPosition() - COORDINATES[COORD_ID - CurrentID]).Length() < 1 || ((RC.GetPosition() - COORDINATES[COORD_ID - CurrentID]).Length() < 10 && COORD_ID == 0))
                {
                    COORD_ID = COORD_ID + iter_er;
                    if (COORD_ID == COORDINATES.Count)
                    {
                        COORD_ID = COORDINATES.Count - 1;
                    }
                    if (COORD_ID < 0)
                    {
                        COORD_ID = 0;
                    }
                }
            }
Example #14
0
        public void Main(string argument, UpdateType updateSource)
        {
            Echo(IsPaused ? "System paused" : "System working");
            if (argument == "Pause")
            {
                IsPaused = true;
            }
            else if (argument == "Resume")
            {
                IsPaused = false;
            }
            if (IsPaused)
            {
                return;
            }
            //While connector is connected, move stone while at it
            if (Far_Right_Connector.Status == MyShipConnectorStatus.Connected)
            {
                //Move all stones out of drill
                if (GetAnyCargo())
                {
                    //Move all stone
                    foreach (var drill in Far_Array_Drills)
                    {
                        if (drill.GetInventory(0).ItemCount > 0)
                        {
                            //Move stone
                            var inv = drill.GetInventory(0);
                            List <MyInventoryItem> items = new List <MyInventoryItem>();
                            inv.GetItems(items);
                            foreach (var item in items)
                            {
                                inv.TransferItemTo(AnyCargo.GetInventory(0), item);
                            }
                        }
                    }
                }
            }
            //Check connector can connect now
            bool isAllExtended      = IsAllPistonExtended(Far_Top_Pistons);
            bool isAllRetracted     = IsAllPistonRetracted(Far_Top_Pistons);
            bool isMidPush          = IsPistonMidPush(Far_Top_Pistons);
            bool isPistonMergeOn    = Far_PistonEnd_Merge_Top.GetValueBool("OnOff");
            bool isAnyDrillHasStone = IsAnyDrillHasStone(Far_Array_Drills);

            Echo($"Currently all piston: {(isAllExtended ? "Extended" : "")}{(isAllRetracted ? "Retracted" : "")}");
            //Assuming this already push to it fullest
            if (isAllExtended && !isPistonMergeOn && Far_Right_Connector.Status == MyShipConnectorStatus.Connectable && !isMidPush)
            {
                //If it can connect, connect it and turn on side merge block, and turn off top merge block
                Far_Right_Connector.Connect();
                Far_PistonEnd_Merge_Side.SetValueBool("OnOff", true);
                Far_PistonEnd_Merge_Top.SetValueBool("OnOff", false);
                Echo("Connector connected, turn on side merge block, and turn on top merge block");
            }
            else if (!isAllExtended && isPistonMergeOn)
            {
                //Merge block at the tip of piston is off. Time to pull it up
                foreach (var piston in Far_Top_Pistons)
                {
                    piston.SetValueFloat("Velocity", -0.3f);
                }
            }
            //All piston retracted, turn on projector merge block and all welders
            else if (isAllRetracted && !Far_Projector_Merge.GetValueBool("OnOff"))
            {
                Far_Projector_Merge.SetValueBool("OnOff", true);
                //Turn on all welder
                var welders = Far_Top_Welders.Concat(Far_Left_Welders).Concat(Far_Right_Welders).ToList();
                foreach (var welder in welders)
                {
                    welder.SetValueBool("OnOff", true);
                }
                //Extend a piston to build the other side of crane
                Far_Piston_Side_Welders.SetValueFloat("Velocity", 0.3f);
            }
            //Check projector status
            else if (isAllRetracted && Far_Projector.RemainingBlocks < 1 && !isPistonMergeOn)
            {
                //All done and welded. Turn off all welders and retract side welder
                var welders = Far_Top_Welders.Concat(Far_Left_Welders).Concat(Far_Right_Welders).ToList();
                foreach (var welder in welders)
                {
                    welder.SetValueBool("OnOff", false);
                }
                Far_Piston_Side_Welders.SetValueFloat("Velocity", -0.3f);
                //Then extend top piston!
                foreach (var piston in Far_Top_Pistons)
                {
                    piston.SetValueFloat("Velocity", 0.1f);
                    Far_PistonEnd_Merge_Top.SetValueBool("OnOff", true);
                }
            }
            else if (isPistonMergeOn && Far_PistonEnd_Merge_Top.IsConnected)
            {
                //If top merge block is connected, then disable projector merge block
                //Letting it push down
                //Disable side merger, if it connected
                Far_Projector_Merge.SetValueBool("OnOff", false);
                Far_PistonEnd_Merge_Side.SetValueBool("OnOff", false);
            }
            //After it push down for a while
            else if (isPistonMergeOn && isMidPush)
            {
                //Disconnect connector
                Far_Right_Connector.Disconnect();
            }
        }
Example #15
0
        public void Main(string argument, UpdateType updateSource)
        {
            if (goodsetup)
            {
                Echo("LastR: " + lastReversePath);
                Echo("Mode: " + mode);
                Echo("DockingDir: " + rcDockingDir.ToString());
                Echo("Password: "******"Argument: " + argument);
                    string[] info = argument.Split(new string[] { "," }, StringSplitOptions.None);

                    if (updateSource != UpdateType.Antenna)
                    {
                        if (info[0].ToLower() == "dock")
                        {
                            if (info.Length == 1)
                            {
                                Boolean sent = antenna.TransmitMessage("requestdock," + password + ",default");
                                if (!sent)
                                {
                                    messageQue.Add("requestdock," + password + ",default");
                                }
                            }
                            else if (info.Length == 2)
                            {
                                Boolean sent = antenna.TransmitMessage("requestdock," + password + "," + info[1]);
                                if (!sent)
                                {
                                    messageQue.Add("requestdock," + password + "," + info[1]);
                                }
                                groupName = info[1];
                            }
                            else if (info.Length == 3)
                            {
                                Boolean sent = antenna.TransmitMessage("requestdock," + password + "," + groupName + "," + info[2]);
                                if (!sent)
                                {
                                    messageQue.Add("requestdock," + password + "," + groupName + "," + info[2]);
                                }
                            }
                            else
                            {
                                Echo("ERROR, ARGUMENT SIZE INVALID");
                            }
                        }
                        else if (info[0].ToLower() == "stop")
                        {
                            Storage             = "";
                            dockingConnectorPos = new Vector3D();
                            dockingDir          = new Vector3D();
                            mode = 0;
                            globalPath.Clear();
                            reversePath.Clear();
                            rc.ClearWaypoints();

                            foreach (IMyThrust thrust in allThrusters)
                            {
                                thrust.ThrustOverridePercentage = 0;
                            }

                            foreach (IMyGyro gyro in gyros)
                            {
                                gyro.GyroOverride = false;
                                gyro.Pitch        = 0;
                                gyro.Yaw          = 0;
                                gyro.Roll         = 0;
                            }

                            Boolean sent = antenna.TransmitMessage("canceldock," + password);
                            if (!sent)
                            {
                                messageQue.Add("canceldock," + password);
                            }
                        }

                        else if (info[0] == "depart")
                        {
                            if (mode == 5 && connector.Status == MyShipConnectorStatus.Connected)
                            {
                                Main("dock," + groupName + ",leaving", UpdateType.Mod);
                            }
                            else
                            {
                                Echo("ERROR, WRONG MODE OR ALREADY DISCONNECTED");
                            }
                        }

                        else if (info[0].ToLower() == "newpassword")
                        {
                            Random r = new Random();
                            password = r.Next(1000000, 9999999) + "";
                        }
                    }

                    else if (updateSource == UpdateType.Antenna && info[0] == password)
                    {
                        Echo("Message Received: " + argument);
                        if (info[1] == "received" && info.Length == 3) //info[2] is name of spaceport
                        {
                            Echo("Request to '" + info[2] + "' was received, awaiting further instruction.");
                        }
                        else if (info[1] == "fail")
                        {
                            Echo("Request to '" + info[3] + "' failed.");
                        }
                        else if (info[1] == "rejected")
                        {
                            Echo("TOOK TO LONG, DOCKING PERMISSION REJECTED");
                            mode = 0;
                            rc.SetAutoPilotEnabled(false);
                            antenna.CustomName += " ERROR";
                        }
                        else if (info[1] == "wait")
                        {
                            Echo("Request to '" + info[3] + "' success, but placed into waiting que");
                            waiting = true;
                        }
                        else if (info[1] == "dockinginfo")
                        {
                            if (mode == 5)
                            {
                                connector.Disconnect();
                                List <MyWaypointInfo> path = new List <MyWaypointInfo>();
                                string[] strWaypoints      = new string[info.Length - 5];

                                for (int i = 0; i < strWaypoints.Length; i++)
                                {
                                    strWaypoints[i] = info[i + 5];
                                }

                                foreach (string waypoint in strWaypoints)
                                {
                                    MyWaypointInfo newPoint;
                                    Boolean        pass = MyWaypointInfo.TryParse(waypoint, out newPoint);
                                    if (pass)
                                    {
                                        path.Add(newPoint);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                path.Reverse();
                                reversePath = path;
                                EnableRC(reversePath, out path);
                                mode = 6;
                            }
                            else if (info.Length == 5)
                            {
                                linkedConnectorName = info[2];
                                string strConnectorPos = info[3];
                                string strDockingDir   = info[4];

                                //parse str's into their proper values
                                Boolean pass1 = Vector3D.TryParse(strConnectorPos, out dockingConnectorPos);
                                Boolean pass2 = Vector3D.TryParse(strDockingDir, out dockingDir);

                                Dock2(dockingConnectorPos, dockingDir); mode = 2;
                            }
                            else if (info.Length > 5)
                            {
                                linkedConnectorName = info[2];
                                string   strConnectorPos = info[3];
                                string   strDockingDir   = info[4];
                                string[] strWaypoints    = new string[info.Length - 5];
                                for (int i = 0; i < strWaypoints.Length; i++)
                                {
                                    strWaypoints[i] = info[i + 5];
                                }

                                //parse str's into their proper values
                                Boolean pass1 = Vector3D.TryParse(strConnectorPos, out dockingConnectorPos);
                                Boolean pass2 = Vector3D.TryParse(strDockingDir, out dockingDir);
                                pass2 = false;

                                List <MyWaypointInfo> path = new List <MyWaypointInfo>();
                                Boolean pass3 = true;
                                foreach (string waypoint in strWaypoints)
                                {
                                    pass2 = true;
                                    MyWaypointInfo newPoint;
                                    pass3 = MyWaypointInfo.TryParse(waypoint, out newPoint);
                                    if (pass3)
                                    {
                                        path.Add(newPoint);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                if (pass1 && pass2 && pass3)
                                {
                                    EnableRC(path, out globalPath);
                                    reversePath.Reverse();
                                    mode = 1;
                                }
                                else
                                {
                                    Echo(pass1 + " " + pass2 + " " + pass3);
                                }
                            }
                        }
                    }
                    else if (info[0] == "antennapos" && info.Length == 2)
                    {
                        Boolean updated = Vector3D.TryParse(info[1], out antennaPos);
                        if (updated)
                        {
                            antenna.Radius = (float)(Vector3D.Distance(rc.GetPosition(), antennaPos) + 10);
                        }
                        else
                        {
                            Echo("Failed to update antenna position");
                        }
                    }
                    else if (mode == 2 && !rc.IsAutoPilotEnabled && Vector3D.Distance(rc.GetPosition(), rc.CurrentWaypoint.Coords) >= 5)
                    {
                        rc.SetAutoPilotEnabled(true);
                    }
                    else if (mode == 1 && globalPath.Count != 0)
                    {
                        FollowPath(globalPath, true);
                    }
                }
                else if (mode == 1)
                {
                    FollowPath(globalPath, true);
                }
                else if (mode == 2 && rc.IsAutoPilotEnabled && Vector3D.Distance(rc.GetPosition(), rc.CurrentWaypoint.Coords) < 5)
                {
                    Dock3();
                    Boolean sent = antenna.TransmitMessage("freepath," + groupName);
                    if (!sent)
                    {
                        messageQue.Add("freepath," + groupName);
                    }
                }
                else if (mode == 2 && !rc.IsAutoPilotEnabled && Vector3D.Distance(rc.GetPosition(), rc.CurrentWaypoint.Coords) >= 5)
                {
                    rc.SetAutoPilotEnabled(true);
                }
                else if (mode == 3 && Dock3())
                {
                    Echo("DOCKED!");
                }
                else if (mode == 6)
                {
                    FollowPath(reversePath, false);
                }
                else if (updateSource == UpdateType.Update100)
                {
                    shipMass = rc.CalculateShipMass().TotalMass;
                }

                if (waiting)
                {
                    Echo("Waiting for clearance");
                }
            }
            else
            {
                Echo("SETUP FAILED. DO NOT SETUP WHILE CONNECTED TO ANOTHER GRID");
            }
        }
Example #16
0
            internal void Main()
            {
                ProgramInstance.Echo("Status: " + _status);
                ProgramInstance.Echo("Route length: " + _routeLength);
                ProgramInstance.Echo("Current node: " + _currentNodeNum);

                _gridCenterPosition = _controller.CubeGrid.GetPosition();
                _currentSpeed       = _controller.GetShipSpeed() * 3.7d;

                RadioInput();

                switch (_status)
                {
                case State.STANDBY:
                    if (_commands.Count != 0)
                    {
                        NextCommand();
                    }
                    break;

                case State.MOVE:
                    MovementControl(_route[_currentNodeNum].Direction);
                    break;

                case State.CLEARCOMM:
                    _commands.Clear();
                    _currentNodeNum = 0;
                    NextCommand();
                    break;

                case State.CLEARROUTE: //TODO
                    _currentNodeNum = 0;
                    _route.Clear();
                    NextCommand();
                    break;

                case State.READROUTE:
                    _currentNodeNum = 0;
                    ReadRouteData();
                    NextCommand();
                    break;

                case State.UNDOCKING:
                    if (_connector.Status == MyShipConnectorStatus.Connected)
                    {
                        _connector.Disconnect();
                        _connector.Enabled = false;
                    }
                    else
                    {
                        NextCommand();
                    }
                    break;

                case State.DOCKING:
                    GetForwardAxels();
                    float angle; double distance;
                    CalculatePlanarAngleAndDistanceTo(_route[_currentNodeNum].Position, out angle, out distance);
                    WheelsControl(angle, 1, _route[_currentNodeNum - 1].Speed);


                    if (_currentNodeNum == _routeLength)
                    {
                        if (_connector.Status == MyShipConnectorStatus.Connectable)
                        {
                            _connector.Connect();
                        }
                        if (_connector.Status == MyShipConnectorStatus.Connected)
                        {
                            NextCommand();
                        }
                    }
                    else if (distance < _route[_currentNodeNum].CheckDistance)
                    {
                        _currentNodeNum++;
                        _connector.Enabled = false;
                        if (_currentNodeNum == _routeLength)
                        {
                            _connector.Enabled = true;
                        }
                        WriteData();
                    }

                    break;

                case State.RADIOCALL:
                    ProgramInstance.IGC.SendBroadcastMessage(_radio, "DELIVERY " + _sender + " " + _mode + " " + _recipient);
                    NextCommand();
                    break;
                }
            }
Example #17
0
 protected override void OnExecuting(IMyShipConnector connector)
 => connector.Disconnect();
Example #18
0
            void UnlockConnector()
            {
                IMyShipConnector clamp = Reference as IMyShipConnector;

                clamp.Disconnect();
            }
Example #19
0
        public void Main(string argument)
        {
            //THIS STEP IS IMPORTANT BECAUSE THE TIMER RUNS THE PB WITH DEFAULT PARAMETER, WICH IS EMPTY.
            //IF YOU WERE TO REMOVE THIS, THE FOLLOWING SWITCH WOULDN'T WORK
            if (!String.IsNullOrEmpty(argument))
            {
                timer.CustomData = argument.ToLower() + "1"; //the ToLower method makes argument case not matter
            }
            //DIFFERENT PHASES ARE REGULATED VIA TIMER'S CUSTOM DATA
            //notice that extend and retract processes are not the same in reverse because I found out that it would bump into obstacles
            switch (timer.CustomData)
            {
            case "extend1":
                piston1.Extend();
                piston2.Extend();
                Sleep(1f);
                timer.CustomData = "extend2";     //timer's customData gets updated so next time it runs the PB the next phase gets executed
                break;

            case "extend2":
                if (rotor1.TargetVelocityRPM > 0)     //just to be sure it doesn't reverse in the wrong way
                {
                    rotor1.TargetVelocityRPM *= -1;
                }
                Sleep(2f);
                timer.CustomData = "extend3";
                break;

            case "extend3":
                piston3.Extend();
                if (rotor2.TargetVelocityRPM > 0)
                {
                    rotor2.TargetVelocityRPM *= -1;
                }
                Sleep(2f);
                timer.CustomData = "extend4";
                break;

            case "extend4":
                piston4.Extend();
                Sleep(1.5f);
                timer.CustomData = "extend5";
                break;

            case "extend5":
                connector.Connect();
                timer.CustomData = "";
                break;

            case "retract1":
                connector.Disconnect();
                piston4.Retract();
                if (rotor2.TargetVelocityRPM < 0)
                {
                    rotor2.TargetVelocityRPM *= -1;
                }
                piston3.Retract();
                piston2.Retract();
                if (rotor1.TargetVelocityRPM < 0)
                {
                    rotor1.TargetVelocityRPM *= -1;
                }
                Sleep(1f);
                timer.CustomData = "retract2";
                break;

            case "retract2":
                piston1.Retract();
                timer.CustomData = "";
                break;

            default:
                Echo("unknown timer customdata");
                break;
            }
        }
        public void Main(string argument, UpdateType updateSource)
        {
            // SETUP

            craneCabin     = GridTerminalSystem.GetBlockWithName(cabinName) as IMyCockpit;
            craneRotor     = GridTerminalSystem.GetBlockWithName(rotorName) as IMyMotorAdvancedStator;
            craneConnector = GridTerminalSystem.GetBlockWithName(connectorName) as IMyShipConnector;
            cranePiston    = GridTerminalSystem.GetBlockWithName(pistonName) as IMyPistonBase;

            if (callPanels.Count == 0)
            {
                List <IMyButtonPanel> tempPanels = new List <IMyButtonPanel>();
                GridTerminalSystem.GetBlocksOfType(tempPanels, tempPanel => tempPanel.CustomName.Contains(callPanelName));

                for (int key = 0; key < tempPanels.Count; key++)
                {
                    IMyTextSurfaceProvider panelLCD = (IMyTextSurfaceProvider)tempPanels[key];

                    if (panelLCD.GetSurface(0) != null)
                    {
                        callPanels.Add(tempPanels[key]);
                    }
                }
            }

            if (areaStatusPanels.Count == 0)
            {
                GridTerminalSystem.GetBlocksOfType(areaStatusPanels, tempPanel => tempPanel.CustomName.Contains(areaStatusPanelName));
            }

            if (craneCabin != null)
            {
                pistonMonitor    = craneCabin.GetSurface(1);
                connectorMonitor = craneCabin.GetSurface(2);
                rotorMonitor     = craneCabin.GetSurface(3);
            }

            // END SETUP

            if (argument != "" && callOverride == null)
            {
                if (craneConnector == null || cranePiston == null || craneRotor == null)
                {
                    return;
                }

                callOverride = Math.Min(Math.Max((int.Parse(argument) * 45) - 180, -135), 135);
                UpdateCallPanels();
                lastRotorInput  = 0;
                rotorMultiplier = 0;
                craneConnector.Disconnect();

                if (Math.Floor((craneRotor.Angle * (180 / Math.PI)) + 0.5) < callOverride)
                {
                    craneRotor.UpperLimitDeg     = (float)callOverride;
                    craneRotor.TargetVelocityRPM = 1;
                }
                else
                {
                    craneRotor.LowerLimitDeg     = (float)callOverride;
                    craneRotor.TargetVelocityRPM = -1;
                }
            }

            if ((updateSource & UpdateType.Update100) != 0)
            {
                Runtime.UpdateFrequency = craneCabin.IsUnderControl || rotorMultiplier != 0 || callOverride != null ? UpdateFrequency.Update1 | UpdateFrequency.Update100 : UpdateFrequency.Update100;
                UpdateCallPanels();
            }

            if (callOverride == null)
            {
                if ((updateSource & UpdateType.Update1) != 0 && craneCabin != null)
                {
                    pistonOutput.Length    = 0;
                    connectorOutput.Length = 0;
                    rotorOutput.Length     = 0;

                    connectorOutput.Append("\n\n\n\n");

                    if (craneCabin.IsUnderControl)
                    {
                        pistonOutput.Append("\n\n\n\nPISTON\n");
                        rotorOutput.Append("\n\n\nROTOR\n");

                        if (craneConnector != null)
                        {
                            if (craneCabin.MoveIndicator.Z > 0)
                            {
                                craneConnector.Disconnect();
                            }

                            if (craneConnector.Status == MyShipConnectorStatus.Unconnected)
                            {
                                connectorOutput.Append("DISCONNECTED");
                                connectorMonitor.FontColor = Color.Red;
                            }
                            else if (craneConnector.Status == MyShipConnectorStatus.Connected)
                            {
                                connectorOutput.Append("CONNECTED\n");
                                connectorMonitor.FontColor = Color.Green;
                                string otherName = craneConnector.OtherConnector.CustomName;
                                connectorOutput.Append(otherName.Substring(0, otherName.Length - 10));
                            }
                            else
                            {
                                connectorOutput.Append("READY");
                                connectorMonitor.FontColor = Color.Yellow;
                            }
                        }

                        if (cranePiston != null)
                        {
                            cranePiston.Velocity = (float)ClampVelocity(-craneCabin.MoveIndicator.Z, 1);

                            pistonOutput.Append("[ ");
                            pistonOutput.Append((Math.Floor(cranePiston.CurrentPosition * 10) / 10).ToString("F1"));
                            pistonOutput.Append("m ]");
                        }

                        if (craneRotor != null)
                        {
                            if (craneConnector.Status != MyShipConnectorStatus.Connected)
                            {
                                if (craneCabin.MoveIndicator.X != 0 && Math.Sign(craneCabin.MoveIndicator.X) != Math.Sign(lastRotorInput))
                                {
                                    rotorMultiplier *= -1;
                                }

                                lastRotorInput = (craneCabin.MoveIndicator.X == 0 ? lastRotorInput : craneCabin.MoveIndicator.X);
                                if (craneCabin.MoveIndicator.X != 0)
                                {
                                    rotorMultiplier = Math.Min(Math.Max(rotorMultiplier + (Math.Abs(craneCabin.MoveIndicator.X) * 0.02f), -1), 1);
                                }
                                else
                                {
                                    rotorMultiplier += Math.Max(Math.Min(Math.Abs(0 - rotorMultiplier), 0.02f), 0) * -Math.Sign(rotorMultiplier);
                                }

                                craneRotor.TargetVelocityRPM = (float)ClampVelocity(lastRotorInput, 1) * rotorMultiplier;
                            }

                            rotorOutput.Append("[ ");
                            rotorOutput.Append(Math.Floor((craneRotor.Angle * (180 / Math.PI)) + 0.5).ToString("000.##"));
                            rotorOutput.Append("° ]");
                        }
                    }
                    else
                    {
                        connectorOutput.Append("STANDING BY");
                        connectorMonitor.FontColor = Color.White;

                        if (rotorMultiplier > 0)
                        {
                            rotorMultiplier = Math.Max(rotorMultiplier - 0.02f, 0);
                        }
                        else if (rotorMultiplier < 0)
                        {
                            rotorMultiplier = Math.Min(rotorMultiplier + 0.02f, 0);
                        }
                        else
                        {
                            lastRotorInput = 0;
                        }

                        craneRotor.TargetVelocityRPM = (float)ClampVelocity(lastRotorInput, 1) * rotorMultiplier;
                    }

                    pistonMonitor.WriteText(pistonOutput, false);
                    connectorMonitor.WriteText(connectorOutput, false);
                    rotorMonitor.WriteText(rotorOutput, false);
                }
                else if (craneCabin == null)
                {
                    lastRotorInput  = 0;
                    rotorMultiplier = 0;

                    if (cranePiston != null)
                    {
                        cranePiston.Velocity = 0;
                    }

                    if (craneRotor != null)
                    {
                        craneRotor.TargetVelocityRPM = 0;
                    }
                }
            }
            else
            {
                if (craneConnector == null || cranePiston == null || craneRotor == null)
                {
                    callOverride = null;
                    UpdateCallPanels();
                    return;
                }

                if (Math.Abs((craneRotor.Angle * (180 / Math.PI)) - (float)callOverride) < 0.25)
                {
                    craneRotor.TargetVelocityRPM = 0;
                    craneRotor.UpperLimitDeg     = 135;
                    craneRotor.LowerLimitDeg     = -135;

                    cranePiston.Velocity = 1;

                    if (Math.Abs(cranePiston.CurrentPosition - cranePiston.MaxLimit) < 0.1 && craneConnector.Status == MyShipConnectorStatus.Connectable)
                    {
                        cranePiston.Velocity = 0;
                        craneConnector.Connect();
                        callOverride = null;
                        UpdateCallPanels();
                        return;
                    }
                }
                else
                {
                    cranePiston.Velocity = -1;
                }

                if (craneCabin != null)
                {
                    connectorOutput.Length = 0;
                    rotorOutput.Length     = 0;
                    pistonOutput.Length    = 0;

                    connectorOutput.Append("\n\n\n\nAUTO-DOCKING\n");
                    connectorOutput.Append(((float)callOverride).ToString("000.##"));
                    connectorOutput.Append("°");
                    connectorMonitor.FontColor = Color.Blue;

                    pistonOutput.Append("\n\n\n\nPISTON\n");
                    pistonOutput.Append("[ ");
                    pistonOutput.Append((Math.Floor(cranePiston.CurrentPosition * 10) / 10).ToString("F1"));
                    pistonOutput.Append("m ]");

                    rotorOutput.Append("\n\n\nROTOR\n");
                    rotorOutput.Append("[ ");
                    rotorOutput.Append(Math.Floor((craneRotor.Angle * (180 / Math.PI)) + 0.5).ToString("000.##"));
                    rotorOutput.Append("° ]");

                    pistonMonitor.WriteText(pistonOutput, false);
                    connectorMonitor.WriteText(connectorOutput, false);
                    rotorMonitor.WriteText(rotorOutput, false);
                }
            }
        }