aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.UI/Threading/DefaultDispatcherProvider.cs
blob: 58ab9c24a7990316e2e4612f15bb78ab307137da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using Tango.PPC.Common.Threading;

namespace Tango.PPC.UI.Threading
{
    /// <summary>
    /// Represents the default PPC <see cref="IDispatcherProvider"/> which will invoke action on the current application dispatcher.
    /// </summary>
    /// <seealso cref="Tango.PPC.Common.Threading.IDispatcherProvider" />
    public class DefaultDispatcherProvider : IDispatcherProvider
    {
        private Dispatcher _dispatcher;

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultDispatcherProvider"/> class.
        /// </summary>
        /// <param name="dispatcher">The dispatcher.</param>
        public DefaultDispatcherProvider(Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
        }

        /// <summary>
        /// Invokes the specified action asynchronously.
        /// </summary>
        /// <param name="action">The action.</param>
        public void Invoke(Action action)
        {
            _dispatcher.BeginInvoke(action);
        }

        /// <summary>
        /// Invokes the specified action synchronously.
        /// </summary>
        /// <param name="action">The action.</param>
        public void InvokeBlock(Action action)
        {
            _dispatcher.Invoke(action);
        }
    }
}
n> Tango.Transport.Components; using Tango.Transport.Transporters; namespace Tango.Transport.Discovery { internal static class UsbComPortWin32 { internal static int dwFlagsAndAttributes = 0x40000000; [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr securityAttrs, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); } /// <summary> /// Represents a USB port scanner which will scan all known ports on PC with the specified request and response types. /// </summary> /// <typeparam name="TRequest">The type of the request.</typeparam> /// <typeparam name="TResponse">The type of the response.</typeparam> /// <seealso cref="Tango.Transport.Discovery.ICommunicationScanner{Tango.Transport.Adapters.UsbTransportAdapter, TRequest, TResponse}" /> public class UsbCommunicationScanner<TRequest, TResponse> : ICommunicationScanner<UsbTransportAdapter, TRequest, TResponse> where TRequest : IMessage where TResponse : IMessage { public event Action<String> ScanningPort; /// <summary> /// Gets the baud rate. /// </summary> public UsbSerialBaudRates BaudRate { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="UsbCommunicationScanner{TRequest, TResponse}"/> class. /// </summary> /// <param name="baudRate">The baud rate.</param> public UsbCommunicationScanner(UsbSerialBaudRates baudRate) { BaudRate = baudRate; } /// <summary> /// Scans the environment with the specified request while expecting the type of response. /// </summary> /// <param name="request">The request.</param> /// <param name="timeout">The timeout.</param> /// <returns></returns> public Task<CommunicationScannerResult<UsbTransportAdapter, TResponse>> Scan(TRequest request, TimeSpan timeout) { var logManager = LogManager.Default; logManager.Log("Starting com ports scanning using baud rate " + BaudRate.ToInt32() + "..."); DateTime startTime = DateTime.Now; bool found = false; TaskCompletionSource<CommunicationScannerResult<UsbTransportAdapter, TResponse>> source = new TaskCompletionSource<CommunicationScannerResult<UsbTransportAdapter, TResponse>>(); Task.Factory.StartNew(async () => { CommunicationScannerResult<UsbTransportAdapter, TResponse> result = new CommunicationScannerResult<UsbTransportAdapter, TResponse>(); logManager.Log("Enumerating com ports..."); var comPorts = ComPortEnumerator.EnumerateComPorts(); while (!found && DateTime.Now < startTime.Add(timeout)) { foreach (var port in comPorts) { if (DateTime.Now > startTime.Add(timeout)) { break; } logManager.Log("Scanning " + port.ToString() + "..."); ScanningPort?.Invoke(port.Port); SafeFileHandle hFile = UsbComPortWin32.CreateFile(@"\\.\" + port.Port, -1073741824, 0, IntPtr.Zero, 3, UsbComPortWin32.dwFlagsAndAttributes, IntPtr.Zero); if (hFile.IsInvalid) { logManager.Log(String.Format("Port {0} is already open or invalid.", port.Port)); hFile.Close(); continue; } hFile.Close(); SerialPort serialPort = new SerialPort(port.Port); try { serialPort.Open(); serialPort.Close(); } catch (Exception ex) { logManager.Log(ex, "Could not open port " + port.Port); continue; } BasicTransporter transporter = new BasicTransporter(new UsbTransportAdapter(port.Port, BaudRate)); try { logManager.Log("Connecting transporter..."); await transporter.Connect(); logManager.Log("Sending scanning request..."); var response = await transporter.SendRequest(request, TimeSpan.FromSeconds(0.5)); if (response is TResponse) { logManager.Log("Response received from " + port.ToString()); ITransportAdapter adapter = null; try { adapter = transporter.Adapter; logManager.Log("Disconnecting transporter... (keeping adapter)"); transporter.Adapter = null; await transporter.Disconnect(); } catch { } found = true; logManager.Log("Setting scan task result."); source.SetResult(new CommunicationScannerResult<UsbTransportAdapter, TResponse>() { Adapter = adapter as UsbTransportAdapter, Response = (TResponse)response, }); break; } logManager.Log("Disconnecting transporter..."); await transporter.Disconnect(); } catch (Exception ex) { try { logManager.Log(ex, "Disconnecting transporter..."); await transporter.Disconnect(); } catch { } } } } if (!found) { source.SetException(new TimeoutException(logManager.Log("The com port scanning operation had timed out after " + timeout.TotalSeconds + " seconds."))); } }); return source.Task; } } }