HamBook – Rev 5
?pathlinks?
using HamBook.Radios.Generic;
using HamBook.Radios;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
using HamBook.Properties;
using Serilog.Events;
namespace HamBook
{
public class BandScan
{
private CancellationTokenSource _scanningCancellationTokenSource;
private CancellationToken _scanningCancellationToken;
private Task _aiTask;
private CatAssemblies _catAssemblies;
private int _minFrequency;
private int _maxFrequency;
private SerialPort _serialPort;
private int _currentFrequency;
private BandScan()
{
}
public BandScan(CatAssemblies catAssemblies, int min, int max, SerialPort serialPort) : this()
{
_catAssemblies = catAssemblies;
_minFrequency = min;
_maxFrequency = max;
_serialPort = serialPort;
}
public async Task Start(int step, int pause)
{
if(_scanningCancellationTokenSource != null)
{
_scanningCancellationTokenSource.Cancel();
}
if(_aiTask != null)
{
_aiTask.Wait();
}
_scanningCancellationTokenSource = new CancellationTokenSource();
_scanningCancellationToken = _scanningCancellationTokenSource.Token;
await Scan(step, pause);
}
public void Stop()
{
if (_scanningCancellationTokenSource != null)
{
_scanningCancellationTokenSource.Cancel();
}
if (_aiTask != null)
{
_aiTask.Wait();
}
}
private async Task Scan(int step, int pause)
{
try
{
var squelch = _catAssemblies.CatRead<int>("SQ", new object[] { });
if (squelch == 0)
{
var @default = _catAssemblies.CatGetDefault<int>("SQ", new object[] { });
_catAssemblies.CatSet<int>("SQ", new object[] { @default });
}
_currentFrequency = _minFrequency;
do
{
var taskCompletionSource = new TaskCompletionSource<bool>();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Delay(TimeSpan.FromSeconds(pause)).ContinueWith(_ => taskCompletionSource.TrySetResult(true), _scanningCancellationToken);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
_catAssemblies.CatSet<int>("FA", new object[] { _currentFrequency });
await taskCompletionSource.Task;
_currentFrequency = _currentFrequency + step;
if(_currentFrequency > _maxFrequency)
{
_currentFrequency = _minFrequency;
}
if(_currentFrequency < _minFrequency)
{
_currentFrequency = _minFrequency;
}
} while(!_scanningCancellationToken.IsCancellationRequested);
}
catch(Exception exception)
{
Log.Error(exception, Resources.Scanning_aborted);
}
}
}
}