Ejemplo n.º 1
0
        private async Task OnSliderValueChanged(int index, double newValue)
        {
            // for Cut mode
            if (IsSliderActive[index].Value)
            {
                // Cancel deactivation (Keep 1.0)
                if (SliderValue[index].Value < 1.0)
                {
                    SliderValue[index].Value = 1.0;
                }
                return;
            }
            if (newValue < Epsilon)
            {
                // Do nothing
                return;
            }

            // Change active slider
            for (var i = 0; i < SliderValue.Length; i++)
            {
                IsSliderActive[i].Value = (i == index);
            }
            for (var i = 0; i < SliderValue.Length; i++)
            {
                SliderValue[i].Value = IsSliderActive[i].Value ? 1.0 : 0.0;
            }

            await ConnectedDevice.SwitchCut(index);
        }
Ejemplo n.º 2
0
        public void BindDeviceProxy(IIdentity identity, IDeviceProxy deviceProxy)
        {
            ConnectedDevice device = this.GetOrCreateConnectedDevice(Preconditions.CheckNotNull(identity, nameof(identity)));

            device.UpdateDeviceProxy(Preconditions.CheckNotNull(deviceProxy, nameof(deviceProxy)));
            Events.BindDeviceProxy(identity);
        }
Ejemplo n.º 3
0
        public IActionResult CreateConnectedDevice([FromBody] ConnectedDeviceCreateModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (model == null)
            {
                return(BadRequest(ModelState));
            }
            ClaimsIdentity claimIdentity = HttpContext.User.Identity as ClaimsIdentity;
            string         userId        = claimIdentity.FindFirst(ClaimTypes.Name)?.Value;

            if (userId == null)
            {
                return(BadRequest(ModelState));
            }
            ConnectedDevice connectedDevice = new ConnectedDevice
            {
                UserId = userId,
                ConnectedDeviceTypeId = model.ConnectedDeviceTypeId,
                Location        = model.Location,
                Name            = model.Name,
                DeviceUsedGPIOs = model.DeviceUsedGPIOs
            };

            connectedDeviceRepository.CreateConnectedDevice(connectedDevice);
            return(Ok("Create Success"));
        }
Ejemplo n.º 4
0
 private async void ReadSpeed()
 {
     if (ConnectedDevice == null || ConnectedDevice.ConnectionState == BACConnectionState.DISCONNECTED)
     {
         Model.Speed = 0;
         return;
     }
     while (ConnectedDevice != null && ConnectedDevice.ConnectionState == BACConnectionState.CONNECTED)
     {
         try
         {
             var speed = Math.Round(await ConnectedDevice.Read(260) / (float)256 / 1.609344, 0);
             Model.Speed = speed;
             if (speed > App.LifetimeSpeed)
             {
                 Stats.LifetimeSpeed = speed;
                 App.LifetimeSpeed   = speed;
             }
             if (speed > Stats.SessionSpeed)
             {
                 Stats.SessionSpeed = speed;
             }
         }
         catch (Exception exception)
         {
             Console.WriteLine(exception);
             UnsubscribeToDevice();
             HandleConnectionState();
         }
     }
 }
Ejemplo n.º 5
0
        private async void ReadVoltage()
        {
            if (ConnectedDevice == null || ConnectedDevice.ConnectionState == BACConnectionState.DISCONNECTED)
            {
                Model.Voltage           = 0.0;
                VoltageLabel.LabelText  = "0.0";
                VoltageLabel.LabelColor = Color.DimGray;
                return;
            }

            while (ConnectedDevice != null && ConnectedDevice.ConnectionState == BACConnectionState.CONNECTED)
            {
                try
                {
                    Model.Voltage = await ConnectedDevice.Read(265) / (double)32;

                    VoltageLabel.LabelText  = Model.Voltage.ToString("F0");
                    VoltageLabel.LabelColor = Color.Black;
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    UnsubscribeToDevice();
                }
            }
        }
        /// <summary>
        /// Run the test on the specified device.
        /// </summary>
        /// <param name="device">The device.</param>
        private void RunTestOnDevice(ConnectedDevice device)
        {
            switch (device.Platform)
            {
            case TestPlatform.WindowsDx:
            case TestPlatform.WindowsOgl:
            case TestPlatform.WindowsOgles:
                RunWindowsTest(device.Serial, device.Platform);
                break;

            case TestPlatform.Android:
                if (onBamboo)
                {
                    RunAndroidTestOnBamboo(device.Serial);
                }
                else
                {
                    RunAndroidTest(device.Serial);
                }
                break;

            case TestPlatform.Ios:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 7
0
        public async void SubscribeAndHandleDeviceAsync(IBacGenericDevice device)
        {
            //check if we chose the same device
            if (ConnectedDevice == device)
            {
                return;
            }

            if (ConnectedDevice != null)
            {
                //unsubsribe from connection events. Devices could potentially persist.
                ConnectedDevice.ConnectionStateChanged -= Device_ConnectionStateChanged;

                //Disconnect if choosing new device.
                if (ConnectedDevice.ConnectionState != BACConnectionState.DISCONNECTED)
                {
                    await ConnectedDevice.Disconnect();
                }
            }

            ConnectedDevice = device;

            if (ConnectedDevice != null)
            {
                ConnectedDevice.ConnectionStateChanged  += Device_ConnectionStateChanged;
                Application.Current.Properties["device"] = ConnectedDevice.Guid;
            }

            // HandleConnectionState();
        }
Ejemplo n.º 8
0
        public override async Task InitializeAsync()
        {
            if (Disposed)
            {
                throw new Exception(DeviceDisposedErrorMessage);
            }

            await GetDeviceAsync(DeviceId);

            if (ConnectedDevice != null)
            {
                var usbInterface = ConnectedDevice.Configuration.UsbInterfaces.FirstOrDefault();

                if (usbInterface == null)
                {
                    ConnectedDevice.Dispose();
                    throw new Exception("There was no Usb Interface found for the device.");
                }

                var interruptPipe = usbInterface.InterruptInPipes.FirstOrDefault();

                if (interruptPipe == null)
                {
                    throw new Exception("There was no interrupt pipe found on the interface");
                }

                interruptPipe.DataReceived += InterruptPipe_DataReceived;

                //TODO: Fill in the DeviceDefinition...

                // TODO: It should be possible to select a different configurations, interface, and pipes

                _DefaultConfigurationInterface = ConnectedDevice.Configuration.UsbInterfaces.FirstOrDefault();

                //TODO: Clean up this messaging and move down to a base class across platforms
                if (_DefaultConfigurationInterface == null)
                {
                    throw new Exception("Could not get the default interface configuration for the USB device");
                }

                _DefaultOutPipe = _DefaultConfigurationInterface.InterruptOutPipes.FirstOrDefault();

                if (_DefaultOutPipe == null)
                {
                    throw new Exception("Could not get the default out pipe for the default USB interface");
                }

                _DefaultInPipe = _DefaultConfigurationInterface.InterruptInPipes.FirstOrDefault();

                if (_DefaultOutPipe == null)
                {
                    throw new Exception("Could not get the default in pipe for the default USB interface");
                }
            }
            else
            {
                throw new Exception($"Could not connect to device with Device Id {DeviceId}. Check that the package manifest has been configured to allow this device.");
            }
        }
        private void bindContactQuality()
        {
            var connectedDevice = new ConnectedDevice();

            Container.BindInstance(contactQualityController);
            Container.BindInstance(connectedDevice);
            bindContactQualityNodes();
        }
Ejemplo n.º 10
0
        public ActionResult DeleteConfirmed(int id)
        {
            ConnectedDevice connectedDevice = db.ConnectedDevices.Find(id);

            db.ConnectedDevices.Remove(connectedDevice);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Start an auto-connection sequence
        /// </summary>
        private async void StartAutoConnectionRoutine()
        {
            Console.WriteLine("Started auto connect !!");
            if (ConnectedDevice != null)
            {
                await ConnectedDevice.Disconnect();

                ConnectedDevice = null;
            }

            while (ConnectedDevice == null && List.Count > 0)
            {
                ConnectedDevice = await BacCommunication.CurrentRepository.StartBluetoothLeAutoConnection(List);

                if (ConnectedDevice != null)
                {
                    var wheelDiameter = await ConnectedDevice.Read(227);

                    if (Math.Abs(wheelDiameter - 279.4) > 0.1)
                    {
                        try
                        {
                            await ConnectedDevice.Write(227, (short)279.4);
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception);
                            UnsubscribeToDevice();
                            HandleConnectionState();
                        }
                    }

                    var gearRatio = await ConnectedDevice.Read(226) / 256;

                    if (gearRatio != 1)
                    {
                        try
                        {
                            await ConnectedDevice.Write(226, 1);
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception);
                            UnsubscribeToDevice();
                            HandleConnectionState();
                        }
                    }
                }
            }
            if (ConnectedDevice == null)
            {
                return;
            }
            App.LocalDevice = ConnectedDevice;
            HandleConnectionState();
            SubscribeToConnectedDevice();
        }
Ejemplo n.º 12
0
 public void SetDependencies(ConnectedDevice device, HeadsetGroup headsetGroup,
                             ConnectionIndicatorGroup connectionIndicatorGroup,
                             DataSubscriber subscriber)
 {
     this.connectedDevice          = device;
     this.headsetGroup             = headsetGroup;
     this.connectionIndicatorGroup = connectionIndicatorGroup;
     dataSubscriber = subscriber;
 }
Ejemplo n.º 13
0
        public List <Channel> GetAllOutputChannels(ConnectedDevice device)
        {
            if (device == null)
            {
                return(null);
            }
            var outputTypes = new[] { "do", "ao" };

            return(device.Channels.Where(channel => outputTypes.Any(type => channel.Type.Equals(type))).ToList());
        }
Ejemplo n.º 14
0
        public List <Channel> GetAllInputChannels(ConnectedDevice device)
        {
            if (device == null)
            {
                return(null);
            }
            var inputTypes = new[] { "ai", "relay", "di" };

            return(device.Channels.Where(channel => inputTypes.Any(type => channel.Type.Equals(type))).ToList());
        }
Ejemplo n.º 15
0
 public ActionResult Edit([Bind(Include = "ConnectedDeviceID,Mac")] ConnectedDevice connectedDevice)
 {
     if (ModelState.IsValid)
     {
         db.Entry(connectedDevice).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(connectedDevice));
 }
        public void UpdateConnectedDevice(string connectedDeviceId, ConnectedDevice updateConnectedDevice)
        {
            FilterDefinition <ConnectedDevice> filter = Builders <ConnectedDevice> .Filter.Eq(connectedDevice => connectedDevice.Id, connectedDeviceId);

            UpdateDefinition <ConnectedDevice> update = Builders <ConnectedDevice> .Update
                                                        .Set(connectedDevice => connectedDevice.Name, updateConnectedDevice.Name)
                                                        .Set(connectedDevice => connectedDevice.Location, updateConnectedDevice.Location);

            connectedDevices.FindOneAndUpdate(filter, update);
        }
Ejemplo n.º 17
0
 // checks to see if a connected device exists in database and adds it if not
 public void autoCreateConnectedDevice(string macAddress)
 {
     if (!db.ConnectedDevices.Any(x => x.Mac == macAddress))
     {
         ConnectedDevice newConnDev = new ConnectedDevice();
         newConnDev.Mac = macAddress;
         db.ConnectedDevices.Add(newConnDev);
         db.SaveChanges();
     }
 }
Ejemplo n.º 18
0
        public ActionResult Create([Bind(Include = "ConnectedDeviceID,Mac")] ConnectedDevice connectedDevice)
        {
            if (ModelState.IsValid)
            {
                db.ConnectedDevices.Add(connectedDevice);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(connectedDevice));
        }
Ejemplo n.º 19
0
 public void PowerUpdateResistanceChange()
 {
     FlushResistanceAndUp(this.gameObject);
     if (connectedDevices.Count > 0)
     {
         foreach (IElectricityIO ConnectedDevice in connectedDevices)
         {
             ConnectedDevice.ResistanceInput(ElectricalSynchronisation.currentTick, 1.11111111f, this.gameObject, null);
         }
         ElectricityFunctions.CircuitResistanceLoop(this, this);
     }
 }
Ejemplo n.º 20
0
        public async Task <Try <ICloudProxy> > CreateCloudConnectionAsync(IClientCredentials credentials)
        {
            Preconditions.CheckNotNull(credentials, nameof(credentials));

            ConnectedDevice        device             = this.CreateOrUpdateConnectedDevice(credentials.Identity);
            Try <ICloudConnection> newCloudConnection = await device.CreateOrUpdateCloudConnection(c => this.CreateOrUpdateCloudConnection(c, credentials));

            Events.NewCloudConnection(credentials.Identity, newCloudConnection);
            Try <ICloudProxy> cloudProxyTry = GetCloudProxyFromCloudConnection(newCloudConnection, credentials.Identity);

            return(cloudProxyTry);
        }
Ejemplo n.º 21
0
        async Task <byte[]> IConfigService.ReadConfig(string property)
        {
            var ConfigService = await ConnectedDevice.GetServiceAsync(ConfigServiceGuid);

            var KeyCharacteristic = await ConfigService.GetCharacteristicAsync(KeyCharacteristicGuid);

            var ValueCharacteristic = await ConfigService.GetCharacteristicAsync(ValueCharacteristicGuid);

            await KeyCharacteristic.WriteAsync(Encoding.UTF8.GetBytes(property));

            return(await ValueCharacteristic.ReadAsync());
        }
Ejemplo n.º 22
0
        public async Task <uint> WriteReportAsync(byte[] data, byte reportId, CancellationToken cancellationToken = default)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (DataReceiver.HasData)
            {
                Logger.LogWarning("Writing to device but data has already been received that has not been read");
            }

            var tranformedData = _writeTransferTransform(data, reportId);

            var buffer = tranformedData.AsBuffer();

            //We pass the report id. All this does is sets the array at index zero to the report id
            //This gets overwritten by the tranform anyway
            //It would probably be nice to set the values in outReport.Data from index 1-Length but it doesn't seem possible to do that
            var outReport = ConnectedDevice.CreateOutputReport(reportId);

            outReport.Data = buffer;

            try
            {
                var operation = ConnectedDevice.SendOutputReportAsync(outReport);
                var count     = await operation.AsTask(cancellationToken);

                if (count == tranformedData.Length)
                {
                    //Get the actual data sent, and the actual number of bytes written and log them
                    var transferResult = new TransferResult(outReport.Data.ToArray(), count);
                    Logger.LogDataTransfer(new Trace(true, transferResult));
                }
                else
                {
                    Logger.LogError(Messages.GetErrorMessageInvalidWriteLength(tranformedData.Length, count) + "{length} {count}", tranformedData.Length, count, GetType().Name);
                    throw new IOException(Messages.GetErrorMessageInvalidWriteLength(tranformedData.Length, count));
                }

                return(count);
            }
            catch (ArgumentException ex)
            {
                //TODO: Check the string is nasty. Validation on the size of the array being sent should be done earlier anyway
                if (string.Equals(ex.Message, "Value does not fall within the expected range.", StringComparison.Ordinal))
                {
                    throw new IOException("It seems that the data being sent to the device does not match the accepted size. Try specifying a write transfer transform", ex);
                }
                throw;
            }
        }
Ejemplo n.º 23
0
        async Task <Try <ICloudProxy> > TryGetCloudConnection(string id)
        {
            IIdentity       identity = this.identityProvider.Create(Preconditions.CheckNonWhiteSpace(id, nameof(id)));
            ConnectedDevice device   = this.GetOrCreateConnectedDevice(identity);

            Try <ICloudConnection> cloudConnectionTry = await device.GetOrCreateCloudConnection(
                c => this.ConnectToCloud(c.Identity, this.CloudConnectionStatusChangedHandler));

            Events.GetCloudConnection(device.Identity, cloudConnectionTry);
            Try <ICloudProxy> cloudProxyTry = GetCloudProxyFromCloudConnection(cloudConnectionTry, device.Identity);

            return(cloudProxyTry);
        }
Ejemplo n.º 24
0
        public void InjectDependencies(UI_ConnectingToCortex connectingToCortex, HeadsetGroup headsetGroup,
                                       ConnectHeadsetAdapter adapter, ConnectedDevice connectedDevice,
                                       ContactQualityController contactQualityController,
                                       ConnectionIndicatorGroup connectionIndicatorGroup)
        {
            _headsetAdapter           = adapter;
            _connectedDevice          = connectedDevice;
            _contactQualityController = contactQualityController;
            _connectingToCortex       = connectingToCortex;
            _connectionIndicatorGroup = connectionIndicatorGroup;

            init();
        }
Ejemplo n.º 25
0
        private async Task ToOutputMode()
        {
            if (_viewMode.Value == ViewMode.Output)
            {
                return;
            }
            _viewMode.OnNext(ViewMode.Output);

            if (ConnectedDevice.IsConnected)
            {
                await ConnectedDevice.PreviewProgramOut();
            }
        }
Ejemplo n.º 26
0
        private async Task ToInputMode()
        {
            if (_viewMode.Value == ViewMode.Input)
            {
                return;
            }
            _viewMode.OnNext(ViewMode.Input);

            if (ConnectedDevice.IsConnected)
            {
                await ConnectedDevice.PreviewInputTile();
            }
        }
Ejemplo n.º 27
0
        public async Task AddDeviceConnection(IIdentity identity, IDeviceProxy deviceProxy)
        {
            ConnectedDevice       device             = this.GetOrCreateConnectedDevice(Preconditions.CheckNotNull(identity, nameof(identity)));
            Option <IDeviceProxy> currentDeviceProxy = device.UpdateDeviceProxy(Preconditions.CheckNotNull(deviceProxy, nameof(deviceProxy)));

            Events.NewDeviceConnection(identity);

            await currentDeviceProxy
            .Filter(dp => dp.IsActive)
            .ForEachAsync(dp => dp.CloseAsync(new MultipleConnectionsException($"Multiple connections detected for device {identity.Id}")));

            this.DeviceConnected?.Invoke(this, identity);
        }
Ejemplo n.º 28
0
        // GET: ConnectedDevices/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ConnectedDevice connectedDevice = db.ConnectedDevices.Find(id);

            if (connectedDevice == null)
            {
                return(HttpNotFound());
            }
            return(View(connectedDevice));
        }
Ejemplo n.º 29
0
        async Task RemoveDeviceConnection(ConnectedDevice device, bool removeCloudConnection)
        {
            await device.DeviceConnection.Filter(dp => dp.IsActive)
            .ForEachAsync(dp => dp.CloseAsync(new EdgeHubConnectionException($"Connection closed for device {device.Identity.Id}.")));

            if (removeCloudConnection)
            {
                await device.CloudConnection.Filter(cp => cp.IsActive)
                .ForEachAsync(cp => cp.CloseAsync());
            }

            Events.RemoveDeviceConnection(device.Identity.Id);
            this.DeviceDisconnected?.Invoke(this, device.Identity);
        }
Ejemplo n.º 30
0
        public async Task WriteReportAsync(byte[] data, byte?reportId)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            byte[] bytes;
            if (DataHasExtraByte)
            {
                bytes = new byte[data.Length + 1];
                Array.Copy(data, 0, bytes, 1, data.Length);
                bytes[0] = reportId ?? DefaultReportId;
            }
            else
            {
                bytes = data;
            }

            var buffer    = bytes.AsBuffer();
            var outReport = ConnectedDevice.CreateOutputReport();

            outReport.Data = buffer;

            try
            {
                var operation = ConnectedDevice.SendOutputReportAsync(outReport);
                var count     = await operation.AsTask();

                if (count == bytes.Length)
                {
                    Tracer?.Trace(true, bytes);
                }
                else
                {
                    var message = Messages.GetErrorMessageInvalidWriteLength(bytes.Length, count);
                    Logger?.Log(message, GetType().Name, null, LogLevel.Error);
                    throw new IOException(message);
                }
            }
            catch (ArgumentException ex)
            {
                //TODO: Check the string is nasty. Validation on the size of the array being sent should be done earlier anyway
                if (string.Equals(ex.Message, "Value does not fall within the expected range.", StringComparison.Ordinal))
                {
                    throw new IOException("It seems that the data being sent to the device does not match the accepted size. Have you checked DataHasExtraByte?", ex);
                }
                throw;
            }
        }
 /// <summary>
 /// Run the test on the specified device.
 /// </summary>
 /// <param name="device">The device.</param>
 private void RunTestOnDevice(ConnectedDevice device)
 {
     switch (device.Platform)
     {
         case TestPlatform.WindowsDx:
         case TestPlatform.WindowsOgl:
         case TestPlatform.WindowsOgles:
             RunWindowsTest(device.Serial, device.Platform);
             break;
         case TestPlatform.Android:
             if (onBamboo)
                 RunAndroidTestOnBamboo(device.Serial);
             else
                 RunAndroidTest(device.Serial);
             break;
         case TestPlatform.Ios:
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
        /// <summary>
        /// Run the test.
        /// </summary>
        /// <param name="device">The device where to run the test.</param>
        /// <param name="gameContext">The game context.</param>
        public void RunTest(ConnectedDevice device, GameContext gameContext = null)
        {
            currentDevice = device;
            runTests = true;
            Console.WriteLine(@"Running test " + this.GetType().Name + @" on device " + device.Name + @" (" + device.Platform + @")");

            // TODO: should be executed after LoadContent for client - or at the first frame?
            RegisterTests();
            
            if (isServer)
            {
                Console.WriteLine(@"Running server" + (onBamboo ? @" on Bamboo" : @"" ));
                // Launch server
                SetUpServer();

                if (!serverUp)
                {
                    Assert.Fail("Unable to create a server.");
                    return;
                }

                // Reset some variables
                imageReceived = false;
                testPerformed = false;
                dataReceivedEvent = new ManualResetEvent(false);

                // Launch remote test
                Console.WriteLine(@"Waiting for a connection... ");
                //server.BeginAcceptTcpClient(GetClientResultCallback, server);
                RunTestOnDevice(device);
                
                // Wait until data is received or timeout
                dataReceivedEvent.WaitOne(Timeout);

                try
                {
                    Console.WriteLine(@"Stopping the server.");
                    serverUp = false;
                    StopServer();
                }
                catch (Exception)
                {
                    Console.WriteLine(@"Stopping the server threw an error.");
                }
                finally
                {
                    // Some tests
                    Assert.IsTrue(imageReceived, "The image was not received.");
                    Assert.IsTrue(testPerformed, "The tests were not correctly performed");
                }
            }
            else
            {
                Console.WriteLine(@"Running test client");
                // 1. Create client
                SetUpClient();

                // 2. Run game
                Run(gameContext);
            }
        }
Ejemplo n.º 33
0
        public int RunAndroidTest(ConnectedDevice device, bool reinstall, string packageName, string packageFile, string resultFile)
        {
            try
            {
                server = StartServer();

                if (reinstall)
                {
                    // force stop - only works for Android 3.0 and above.
                    var o0 = ShellHelper.RunProcessAndGetOutput(@"adb", string.Format(@"-s {0} shell am force-stop {1}", device.Serial, packageName));

                    // uninstall
                    ShellHelper.RunProcessAndGetOutput(@"adb", string.Format(@"-s {0} uninstall {1}", device.Serial, packageName));

                    // install
                    var o1 = ShellHelper.RunProcessAndGetOutput(@"adb", string.Format(@"-s {0} install {1}", device.Serial, packageFile));
                    Console.WriteLine("adb install: exitcode {0}\nOutput: {1}\nErrors: {2}", o1.ExitCode, string.Join(Environment.NewLine, o1.OutputLines), string.Join(Environment.NewLine, o1.OutputErrors));
                    if (o1.ExitCode != 0)
                        throw new InvalidOperationException("Invalid error code from adb install");
                }

                // run
                var parameters = new StringBuilder();
                parameters.Append("-s "); parameters.Append(device.Serial);
                parameters.Append(@" shell am start -a android.intent.action.MAIN -n " + packageName + "/nunitlite.tests.MainActivity");
                AddAndroidParameter(parameters, TestRunner.ParadoxServerIp, serverAddresses);
                AddAndroidParameter(parameters, TestRunner.ParadoxServerPort, ((IPEndPoint)server.Server.LocalEndPoint).Port.ToString());
                AddAndroidParameter(parameters, TestRunner.ParadoxBuildNumber, buildNumber.ToString());
                if (!String.IsNullOrEmpty(branchName))
                    AddAndroidParameter(parameters, TestRunner.ParadoxBranchName, branchName);
                Console.WriteLine(parameters.ToString());

                var o2 = ShellHelper.RunProcessAndGetOutput(@"adb", parameters.ToString());
                Console.WriteLine("adb shell am start: exitcode {0}\nOutput: {1}\nErrors: {2}", o2.ExitCode, string.Join(Environment.NewLine, o2.OutputLines), string.Join(Environment.NewLine, o2.OutputErrors));
                if (o2.ExitCode != 0)
                    throw new InvalidOperationException("Invalid error code from adb shell am start");

                // Wait for client to connect
                var client = server.AcceptTcpClient();

                Console.WriteLine("Device connected, wait for results...");

                var clientStream = client.GetStream();
                var binaryReader = new BinaryReader(clientStream);

                // Read output
                var output = binaryReader.ReadString();
                Console.WriteLine(output);

                // Read XML result
                var result = binaryReader.ReadString();
                Console.WriteLine(result);
                
                // Write XML result to disk
                File.WriteAllText(resultFile, result);
                
                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine(@"An error was thrown when running the test on Android: {0}", e);
                return -1;
            }
        }
Ejemplo n.º 34
0
        public int RunAndroidTest(ConnectedDevice device, bool reinstall, string packageName, string packageFile, string resultFile)
        {
            try
            {
                server = StartServer();
                ProcessOutputs adbOutputs;

                var adbPath = AndroidDeviceEnumerator.GetAdbPath();
                if (adbPath == null)
                    throw new InvalidOperationException("Can't find adb");

                var logStack = new List<string>();
                if (reinstall)
                {
                    // force stop - only works for Android 3.0 and above.
                    adbOutputs = ShellHelper.RunProcessAndGetOutput(adbPath, string.Format(@"-s {0} shell am force-stop {1}", device.Serial, packageName));

                    // uninstall
                    adbOutputs = ShellHelper.RunProcessAndGetOutput(adbPath, string.Format(@"-s {0} uninstall {1}", device.Serial, packageName));

                    // install
                    adbOutputs = ShellHelper.RunProcessAndGetOutput(adbPath, string.Format(@"-s {0} install {1}", device.Serial, packageFile));
                    Console.WriteLine("adb install: exitcode {0}\nOutput: {1}\nErrors: {2}", adbOutputs.ExitCode, adbOutputs.OutputAsString, adbOutputs.ErrorsAsString);
                    if (adbOutputs.ExitCode != 0)
                        throw new InvalidOperationException("Invalid error code from adb install.\n Shell log: {0}");
                }

                // run
                var parameters = new StringBuilder();
                parameters.Append("-s "); parameters.Append(device.Serial);
                parameters.Append(@" shell am start -a android.intent.action.MAIN -n " + packageName + "/nunitlite.tests.MainActivity");
                AddAndroidParameter(parameters, TestRunner.XenkoServerIp, serverAddresses);
                AddAndroidParameter(parameters, TestRunner.XenkoServerPort, ((IPEndPoint)server.Server.LocalEndPoint).Port.ToString());
                AddAndroidParameter(parameters, TestRunner.XenkoBuildNumber, buildNumber.ToString());
                if (!String.IsNullOrEmpty(branchName))
                    AddAndroidParameter(parameters, TestRunner.XenkoBranchName, branchName);
                Console.WriteLine(parameters.ToString());

                adbOutputs = ShellHelper.RunProcessAndGetOutput(adbPath, parameters.ToString());
                Console.WriteLine("adb shell am start: exitcode {0}\nOutput: {1}\nErrors: {2}", adbOutputs.ExitCode, adbOutputs.OutputAsString, adbOutputs.ErrorsAsString);
                if (adbOutputs.ExitCode != 0)
                    throw new InvalidOperationException("Invalid error code from adb shell am start.");

                // Wait for client to connect
                const int WaitingTime = 30;
                for (int i = 0; i < WaitingTime; i++)
                {
                    if (server.Pending())
                        break;

                    Thread.Sleep(1000);
                }
                if (!server.Pending())
                    throw new InvalidOperationException("The client (the remote test application) failed to establish the connection.");

                var client = server.AcceptTcpClient();

                Console.WriteLine("Device connected, wait for results...");

                var clientStream = client.GetStream();
                var binaryReader = new BinaryReader(clientStream);

                // Read output
                var output = binaryReader.ReadString();
                Console.WriteLine(output);

                // Read XML result
                var result = binaryReader.ReadString();
                Console.WriteLine(result);
                
                // Write XML result to disk
                File.WriteAllText(resultFile, result);
                
                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine(@"An error was thrown when running the test on Android: {0}", e);
                return -1;
            }
        }