Skip to content

Commit

Permalink
Added cancellationtoken (#1366)
Browse files Browse the repository at this point in the history
* added cancellationToken

* added cancellationtoken
  • Loading branch information
rfaes authored and Yamashi committed Jul 29, 2016
1 parent 3a7f236 commit ded25c6
Show file tree
Hide file tree
Showing 22 changed files with 225 additions and 130 deletions.
18 changes: 13 additions & 5 deletions PoGo.NecroBot.Logic/Navigation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using GeoCoordinatePortable;
using PoGo.NecroBot.Logic.Utils;
Expand All @@ -30,9 +31,10 @@ public Navigation(Client client)
_client = client;
}

public async Task<PlayerUpdateResponse> HumanLikeWalking(GeoCoordinate targetLocation,
double walkingSpeedInKilometersPerHour, Func<Task<bool>> functionExecutedWhileWalking)
public async Task<PlayerUpdateResponse> HumanLikeWalking(GeoCoordinate targetLocation, double walkingSpeedInKilometersPerHour, Func<Task<bool>> functionExecutedWhileWalking, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

var speedInMetersPerSecond = walkingSpeedInKilometersPerHour/3.6;

var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
Expand All @@ -54,6 +56,8 @@ public async Task<PlayerUpdateResponse> HumanLikeWalking(GeoCoordinate targetLoc

do
{
cancellationToken.ThrowIfCancellationRequested();

var millisecondsUntilGetUpdatePlayerLocationResponse =
(DateTime.Now - requestSendDateTime).TotalMilliseconds;

Expand Down Expand Up @@ -85,15 +89,17 @@ public async Task<PlayerUpdateResponse> HumanLikeWalking(GeoCoordinate targetLoc

if (functionExecutedWhileWalking != null)
await functionExecutedWhileWalking(); // look for pokemon
await Task.Delay(500);
await Task.Delay(500, cancellationToken);
} while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30);

return result;
}

public async Task<PlayerUpdateResponse> HumanPathWalking(GpxReader.Trkpt trk,
double walkingSpeedInKilometersPerHour, Func<Task<bool>> functionExecutedWhileWalking)
double walkingSpeedInKilometersPerHour, Func<Task<bool>> functionExecutedWhileWalking, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

//PlayerUpdateResponse result = null;

var targetLocation = new GeoCoordinate(Convert.ToDouble(trk.Lat, CultureInfo.InvariantCulture),
Expand Down Expand Up @@ -121,6 +127,8 @@ public async Task<PlayerUpdateResponse> HumanPathWalking(GpxReader.Trkpt trk,

do
{
cancellationToken.ThrowIfCancellationRequested();

var millisecondsUntilGetUpdatePlayerLocationResponse =
(DateTime.Now - requestSendDateTime).TotalMilliseconds;

Expand Down Expand Up @@ -152,7 +160,7 @@ public async Task<PlayerUpdateResponse> HumanPathWalking(GpxReader.Trkpt trk,
if (functionExecutedWhileWalking != null)
await functionExecutedWhileWalking(); // look for pokemon & hit stops

await Task.Delay(500);
await Task.Delay(500, cancellationToken);
} while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30);

return result;
Expand Down
17 changes: 9 additions & 8 deletions PoGo.NecroBot.Logic/State/FarmState.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#region using directives

using System.Threading;
using System.Threading.Tasks;
using PoGo.NecroBot.Logic.Tasks;

Expand All @@ -9,37 +10,37 @@ namespace PoGo.NecroBot.Logic.State
{
public class FarmState : IState
{
public async Task<IState> Execute(ISession session)
public async Task<IState> Execute(ISession session, CancellationToken cancellationToken)
{
if (session.LogicSettings.EvolveAllPokemonAboveIv || session.LogicSettings.EvolveAllPokemonWithEnoughCandy)
{
await EvolvePokemonTask.Execute(session);
await EvolvePokemonTask.Execute(session, cancellationToken);
}

if (session.LogicSettings.TransferDuplicatePokemon)
{
await TransferDuplicatePokemonTask.Execute(session);
await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
}

if (session.LogicSettings.RenameAboveIv)
{
await RenamePokemonTask.Execute(session);
await RenamePokemonTask.Execute(session, cancellationToken);
}

await RecycleItemsTask.Execute(session);
await RecycleItemsTask.Execute(session, cancellationToken);

if (session.LogicSettings.UseEggIncubators)
{
await UseIncubatorsTask.Execute(session);
await UseIncubatorsTask.Execute(session, cancellationToken);
}

if (session.LogicSettings.UseGpxPathing)
{
await FarmPokestopsGpxTask.Execute(session);
await FarmPokestopsGpxTask.Execute(session, cancellationToken);
}
else
{
await FarmPokestopsTask.Execute(session);
await FarmPokestopsTask.Execute(session, cancellationToken);
}

return this;
Expand Down
3 changes: 2 additions & 1 deletion PoGo.NecroBot.Logic/State/IState.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#region using directives

using System.Threading;
using System.Threading.Tasks;

#endregion
Expand All @@ -8,6 +9,6 @@ namespace PoGo.NecroBot.Logic.State
{
public interface IState
{
Task<IState> Execute(ISession session);
Task<IState> Execute(ISession session, CancellationToken cancellationToken);
}
}
5 changes: 4 additions & 1 deletion PoGo.NecroBot.Logic/State/InfoState.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#region using directives

using System.Threading;
using System.Threading.Tasks;
using PoGo.NecroBot.Logic.Tasks;

Expand All @@ -9,8 +10,10 @@ namespace PoGo.NecroBot.Logic.State
{
public class InfoState : IState
{
public async Task<IState> Execute(ISession session)
public async Task<IState> Execute(ISession session, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

if (session.LogicSettings.AmountOfPokemonToDisplayOnStart > 0)
await DisplayPokemonStatsTask.Execute(session);

Expand Down
23 changes: 15 additions & 8 deletions PoGo.NecroBot.Logic/State/LoginState.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#region using directives

using System;
using System.Threading;
using System.Threading.Tasks;
using PoGo.NecroBot.Logic.Common;
using PoGo.NecroBot.Logic.Event;
Expand All @@ -13,13 +14,17 @@ namespace PoGo.NecroBot.Logic.State
{
public class LoginState : IState
{
public async Task<IState> Execute(ISession session)
public async Task<IState> Execute(ISession session, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

session.EventDispatcher.Send(new NoticeEvent
{
Message = session.Translation.GetTranslation(TranslationString.LoggingIn, session.Settings.AuthType)
});
await CheckLogin(session);

await CheckLogin(session, cancellationToken);

try
{
switch (session.Settings.AuthType)
Expand Down Expand Up @@ -64,7 +69,7 @@ public async Task<IState> Execute(ISession session)
{
session.EventDispatcher.Send(new ErrorEvent { Message = session.Translation.GetTranslation(TranslationString.GoogleTwoFactorAuth) });
session.EventDispatcher.Send(new ErrorEvent { Message = session.Translation.GetTranslation(TranslationString.GoogleTwoFactorAuthExplanation) });
await Task.Delay(7000);
await Task.Delay(7000, cancellationToken);
try
{
System.Diagnostics.Process.Start("https://security.google.com/settings/security/apppasswords");
Expand All @@ -76,7 +81,7 @@ public async Task<IState> Execute(ISession session)
}
}
session.EventDispatcher.Send(new ErrorEvent { Message = session.Translation.GetTranslation(TranslationString.GoogleError) });
await Task.Delay(2000);
await Task.Delay(2000, cancellationToken);
Environment.Exit(0);
}

Expand All @@ -85,16 +90,18 @@ public async Task<IState> Execute(ISession session)
return new PositionCheckState();
}

private static async Task CheckLogin(ISession session)
private static async Task CheckLogin(ISession session, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

if (session.Settings.AuthType == AuthType.Google &&
(session.Settings.GoogleUsername == null || session.Settings.GooglePassword == null))
{
session.EventDispatcher.Send(new ErrorEvent
{
Message = session.Translation.GetTranslation(TranslationString.MissingCredentialsGoogle)
});
await Task.Delay(2000);
await Task.Delay(2000, cancellationToken);
Environment.Exit(0);
}
else if (session.Settings.AuthType == AuthType.Ptc &&
Expand All @@ -104,15 +111,15 @@ private static async Task CheckLogin(ISession session)
{
Message = session.Translation.GetTranslation(TranslationString.MissingCredentialsPtc)
});
await Task.Delay(2000);
await Task.Delay(2000, cancellationToken);
Environment.Exit(0);
}
}

public async Task DownloadProfile(ISession session)
{
session.Profile = await session.Client.Player.GetPlayer();
session.EventDispatcher.Send(new ProfileEvent {Profile = session.Profile});
session.EventDispatcher.Send(new ProfileEvent { Profile = session.Profile });
}
}
}
7 changes: 5 additions & 2 deletions PoGo.NecroBot.Logic/State/PositionCheckState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using PoGo.NecroBot.Logic.Common;
using PoGo.NecroBot.Logic.Event;
Expand All @@ -13,8 +14,10 @@ namespace PoGo.NecroBot.Logic.State
{
public class PositionCheckState : IState
{
public async Task<IState> Execute(ISession session)
public async Task<IState> Execute(ISession session, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

var coordsPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "Configs" +
Path.DirectorySeparatorChar + "Coords.ini";
if (File.Exists(coordsPath))
Expand Down Expand Up @@ -49,7 +52,7 @@ public async Task<IState> Execute(ISession session)
});
}
}
await Task.Delay(200);
await Task.Delay(200, cancellationToken);
}
}
}
Expand Down
18 changes: 12 additions & 6 deletions PoGo.NecroBot.Logic/State/StateMachine.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#region using directives

using System;
using System.Threading;
using System.Threading.Tasks;
using PoGo.NecroBot.Logic.Event;
using PokemonGo.RocketAPI.Exceptions;
Expand All @@ -14,33 +15,38 @@ public class StateMachine
private ISession _ctx;
private IState _initialState;

public Task AsyncStart(IState initialState, Session session)
public Task AsyncStart(IState initialState, Session session, CancellationToken cancellationToken = default(CancellationToken))
{
return Task.Run(() => Start(initialState, session));
return Task.Run(() => Start(initialState, session, cancellationToken), cancellationToken);
}

public void SetFailureState(IState state)
{
_initialState = state;
}

public async Task Start(IState initialState, Session session)
public async Task Start(IState initialState, Session session, CancellationToken cancellationToken = default(CancellationToken))
{
_ctx = session;
var state = initialState;
do
{
try
{
state = await state.Execute(session);
state = await state.Execute(session, cancellationToken);
}
catch(InvalidResponseException)
catch (InvalidResponseException)
{
session.EventDispatcher.Send(new ErrorEvent { Message = "The PokemonGo servers are having a bad time, chill." });
}
catch (OperationCanceledException)
{
session.EventDispatcher.Send(new ErrorEvent { Message = "The bot was stopped." });
return;
}
catch (Exception ex)
{
session.EventDispatcher.Send(new ErrorEvent {Message = ex.ToString()});
session.EventDispatcher.Send(new ErrorEvent { Message = ex.ToString() });
state = _initialState;
}
} while (state != null);
Expand Down
5 changes: 4 additions & 1 deletion PoGo.NecroBot.Logic/State/VersionCheckState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using PoGo.NecroBot.Logic.Event;
using PoGo.NecroBot.Logic.Logging;
Expand All @@ -28,8 +29,10 @@ public class VersionCheckState : IState

public static Version RemoteVersion;

public async Task<IState> Execute(ISession session)
public async Task<IState> Execute(ISession session, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

await CleanupOldFiles();
var autoUpdate = session.LogicSettings.AutoUpdate;
var needupdate = IsLatest();
Expand Down
Loading

0 comments on commit ded25c6

Please sign in to comment.