Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions Botbases/RSBot.Training/TrainingBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,6 @@ public void Stop()
{
lock (Container.Lock)
{
if (Game.Player.InAction)
SkillManager.CancelAction();

Bundles.Stop();
}
}
Expand Down
116 changes: 85 additions & 31 deletions Library/RSBot.Core/Bot.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Threading;
using System.Threading.Tasks;
using System;
using RSBot.Core.Components;
using RSBot.Core.Event;
using RSBot.Core.Plugins;
Expand All @@ -8,6 +9,9 @@ namespace RSBot.Core;

public class Bot
{
private readonly object _lock = new();
private Task _workerTask;

/// <summary>
/// Gets or sets a value indicating whether this <see cref="Bot" /> is running.
/// </summary>
Expand Down Expand Up @@ -50,59 +54,109 @@ public void SetBotbaseView(IBotbaseView botBaseView)
/// </summary>
public void Start()
{
if (Running || Botbase == null)
return;

TokenSource = new CancellationTokenSource();

Task.Factory.StartNew(
async e =>
{
Running = true;
CancellationTokenSource tokenSource;

lock (_lock)
{
if (Running || Botbase == null || (_workerTask != null && !_workerTask.IsCompleted))
return;

tokenSource = new CancellationTokenSource();
TokenSource = tokenSource;
Running = true;
_workerTask = Task.Run(() => RunAsync(tokenSource), tokenSource.Token);
}
}

EventManager.FireEvent("OnStartBot");
Botbase.Start();
private async Task RunAsync(CancellationTokenSource tokenSource)
{
var token = tokenSource.Token;

while (!TokenSource.IsCancellationRequested)
{
if (!Game.Ready)
continue;
try
{
EventManager.FireEvent("OnStartBot");
Botbase.Start();

while (!token.IsCancellationRequested)
{
if (Game.Ready)
Botbase.Tick();
await Task.Delay(100);
}
},
TokenSource.Token,
TaskCreationOptions.LongRunning
);

await Task.Delay(100, token);
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
catch (Exception ex)
{
Log.Fatal(ex);
}
finally
{
if (ReferenceEquals(TokenSource, tokenSource))
Running = false;
}
}

/// <summary>
/// Stops this instance.
/// </summary>
public void Stop()
{
ScriptManager.Stop();
ShoppingManager.Stop();
PickupManager.Stop();
CancellationTokenSource tokenSource;

if (Botbase == null)
return;
lock (_lock)
{
if (Botbase == null || !Running)
return;

if (!Running)
return;
Running = false;
tokenSource = TokenSource;
}

if (!TokenSource.IsCancellationRequested)
TokenSource.Cancel();
if (tokenSource != null && !tokenSource.IsCancellationRequested)
tokenSource.Cancel();

EventManager.FireEvent("OnStopBot");
Log.Notify($"Stopping bot {Botbase.Name}");

CancelActionOnStop();

Game.SelectedEntity = null;

ScriptManager.Stop();
ShoppingManager.Stop();
PickupManager.Stop();
Botbase.Stop();
Running = false;

Log.Notify($"Stopped bot {Botbase.Name}");
Log.Status("Bot stopped");
}

private void CancelActionOnStop()
{
var player = Game.Player;
if (player == null || !player.InAction)
return;

_ = CancelActionOnStopAsync();

async Task CancelActionOnStopAsync()
{
const int attempts = 5;
const int retryDelay = 1000;

for (var i = 0; i < attempts; i++)
{
if (Running || !Game.Ready || !ReferenceEquals(Game.Player, player) || !player.InAction)
return;

SkillManager.CancelAction(0);

if (i == attempts - 1)
return;

await Task.Delay(retryDelay).ConfigureAwait(false);
}
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
34 changes: 26 additions & 8 deletions Library/RSBot.Core/Components/SkillManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -631,24 +631,42 @@ public static void CancelBuff(uint skillId)
/// Cancels the action.
/// </summary>
/// <returns></returns>
public static bool CancelAction()
public static bool CancelAction(int timeout = 500)
{
var packet = new Packet(0x7074);
packet.WriteByte(0x02); //Cancel
if (timeout <= 0)
{
PacketManager.SendPacket(CreateCancelActionPacket(), PacketDestination.Server);
return true;
}

var callback = new AwaitCallback(
response =>
{
return response.ReadByte() == 0x02 && response.ReadByte() == 0x00
? AwaitCallbackResult.Success
: AwaitCallbackResult.ConditionFailed;
var state = response.ReadByte();
var recurring = response.ReadByte();

if (state == 0x02 && recurring == 0x00)
return AwaitCallbackResult.Success;

if (state == 0x02)
return AwaitCallbackResult.Fail;

return AwaitCallbackResult.ConditionFailed;
},
0xB074
);

PacketManager.SendPacket(packet, PacketDestination.Server, callback);
callback.AwaitResponse();
PacketManager.SendPacket(CreateCancelActionPacket(), PacketDestination.Server, callback);
callback.AwaitResponse(timeout);

return callback.IsCompleted;
}

private static Packet CreateCancelActionPacket()
{
var packet = new Packet(0x7074);
packet.WriteByte(0x02); //Cancel

return packet;
}
}
9 changes: 3 additions & 6 deletions Library/RSBot.Core/Network/Socket/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,7 @@ public void Shutdown()
{
try
{
EnablePacketDispatcher = false;
IsClosing = true;

_dispatcherThread?.Join();
StopNetWorker();

//Close Socket
if (_socket != null)
Expand All @@ -81,7 +78,6 @@ public void Shutdown()
}

_protocol = null;
_dispatcherThread = null;
}
catch { }
}
Expand All @@ -97,12 +93,12 @@ private void OnClientConnect(IAsyncResult ar)
if (IsClosing)
return;

EnablePacketDispatcher = true;
_socket = _listener.EndAccept(ar);

_protocol = new SecurityProtocol();
_protocol.GenerateSecurity(true, true, true);

EnablePacketDispatcher = true;
_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, OnBeginReceiveCallback, null);

OnConnected();
Expand Down Expand Up @@ -136,6 +132,7 @@ private void OnBeginReceiveCallback(IAsyncResult ar)
}

_protocol.Recv(_buffer, 0, receivedSize);
SignalPacketDispatcher();
}
catch (SocketException se)
{
Expand Down
Loading
Loading