/// <summary> /// Creates a remote Android test runner. /// </summary> /// <param name="packageName"> the Android application package that contains the tests to run </param> /// <param name="runnerName"> the instrumentation test runner to execute. If null, will use default /// runner </param> /// <param name="remoteDevice"> the Android device to execute tests on </param> public RemoteAndroidTestRunner(string packageName, string runnerName, IDevice remoteDevice) { mPackageName = packageName; mRunnerName = runnerName; mRemoteDevice = remoteDevice; mArgMap = new Dictionary<string, string>(); }
public SysInfoExtended(IDevice Ipod) { byte [] buffer = null; if (Environment.OSVersion.Platform != PlatformID.Unix) //Windows buffer = GetWin32XML (Ipod); else { //TODO: write Unix code to pull buffer } if (buffer == null) throw new FileLoadException ("SCSI_INQUIRY returned null, older iPod?"); string XmlStr = Encoding.UTF8.GetString (buffer); XmlDocument sysInfoXml = new XmlDocument (); sysInfoXml.LoadXml (XmlStr); XmlNode serialNode = sysInfoXml.SelectSingleNode ("/plist/dict/key[text()='SerialNumber']/following-sibling::*[1]"); serialNumber = serialNode.InnerText; XmlNodeList photoNodes = sysInfoXml.SelectNodes ("/plist/dict/key[text()='ImageSpecifications']/following-sibling::*[1]//dict"); if (photoNodes != null) ParseArtwork (photoNodes, ArtworkUsage.Photo); XmlNodeList coverNodes = sysInfoXml.SelectNodes ("/plist/dict/key[text()='AlbumArt']/following-sibling::*[1]//dict"); if (coverNodes != null) ParseArtwork (coverNodes, ArtworkUsage.Photo); }
public SensorTelemetry(ILogger logger, IDevice device, AbstractSensor sensor) { this._logger = logger; this._deviceId = device.DeviceID; this._sensor = sensor; this.TelemetryActive = !string.IsNullOrWhiteSpace(device.HostName) && !string.IsNullOrWhiteSpace(device.PrimaryAuthKey); }
public JavaScriptAudioDevice CreateJavaScriptAudioDevice(IDevice audioDevice) { if (audioDevice == null) return null; return new JavaScriptAudioDevice(Engine, AudioController, audioDevice); }
public ActivityClient( string ip, int port, IDevice device, bool useCache = true ) { LocalCaching = useCache; InitializeEvents(); Ip = ip; Port = port; Address = Net.GetUrl( ip, port, "" ).ToString(); Device = device; try { _eventHandler = new Connection(Address); _eventHandler.JsonSerializer.TypeNameHandling = TypeNameHandling.Objects; _eventHandler.Received += eventHandler_Received; _eventHandler.Start().Wait(); } catch(HttpClientException ex) { Console.WriteLine(ex.ToString()); } }
private MACAddress GetMAC(IDevice device) { if (device == null || device.MAC == null) return new MACAddress { Value = "" }; return device.MAC; }
public MainWindow() { InitializeComponent(); IContext context = Iisu.Iisu.Context; // get iisu handle iisuHandle = context.CreateHandle(); // create iisu device device = iisuHandle.InitializeDevice(); try { // register event listener device.EventManager.RegisterEventListener("SYSTEM.Error", new OnErrorDelegate(onError)); // launch IID script device.CommandManager.SendCommand("IID.loadGraph", "gateway-v2.iid"); } catch (Exception e) { Console.WriteLine(e.Message); Environment.Exit(0); } CompositionTarget.Rendering += UpdateColor; device.Start(); //while (true) { //update(); } }
public IRemoteApplication LaunchApp(string appGuid, IDevice device) { Guid appID = new Guid(appGuid); var app = device.GetApplication(appID); app.Launch(); return app; }
protected override void OnDelete(IDevice device) { string s = string.Format( "delete from tblDevice where DeviceID = {0}", GuidHelper.ConvertToInt32(device.Guid)); DBI.Instance.ExecuteScalar(s); }
public CharacteristicDetail_TISensor (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic) { InitializeComponent (); this.characteristic = characteristic; Title = characteristic.Name; }
public IoTHubTransport(ISerialize serializer, ILogger logger, IConfigurationProvider configurationProvider, IDevice device) { _serializer = serializer; _logger = logger; _configurationProvider = configurationProvider; _device = device; }
public PlantronicsManager(IStatusManager statusManager, IInteractionManager interactionManager, INotificationService notificationService, ITraceContext traceContext) { _statusManager = statusManager; _interactionManager = interactionManager; _traceContext = traceContext; _notificationService = notificationService; m_sessionComManager = new SessionComManagerClass(); m_sessionManagerEvents = m_sessionComManager as ISessionCOMManagerEvents_Event; m_comSession = m_sessionComManager.Register("Interaction Client Plantronics AddIn"); // Now check if our plugin session was created if (m_comSession != null) { // detect devices added/removed m_sessionManagerEvents.DeviceStateChanged += OnDeviceStateChanged; //Get current Device m_device = m_comSession.ActiveDevice; // if we have a device register for events if (m_device != null) { // Register for device events RegisterEvents(); } } }
public SpeakerDetailsPage(string sessionId, IDevice device) { this.sessionId = sessionId; InitializeComponent(); MainScroll.ParallaxView = HeaderView; ListViewSessions.ItemSelected += async (sender, e) => { var session = ListViewSessions.SelectedItem as Session; if(session == null) return; var sessionDetails = new SessionDetailsPage(session, device); App.Logger.TrackPage(AppPage.Session.ToString(), session.Title); await NavigationService.PushAsync(Navigation, sessionDetails); ListViewSessions.SelectedItem = null; }; if (Device.Idiom != TargetIdiom.Phone) Row1Header.Height = Row1Content.Height = 350; }
/// <summary> /// /// </summary> /// <param name="device"></param> /// <param name="operaName"></param> /// <param name="keyValues"></param> public ExecuteResult Execute(IDevice device, string operaName, KeyValueCollection keyValues) { if (device == null) { throw new ArgumentNullException("device"); } if (keyValues == null) { keyValues = new KeyValueCollection(); } if (!(device.Station.CommuniPort != null && device.Station.CommuniPort.IsOpened )) { return ExecuteResult.CreateFailExecuteResult("not connected"); } IOpera opera = device.Dpu.OperaFactory.Create(device.GetType().Name, operaName); foreach (KeyValue kv in keyValues) { opera.SendPart[kv.Key] = kv.Value; } TimeSpan timeout = TimeSpan.FromMilliseconds(device.Station.CommuniPortConfig.TimeoutMilliSecond ); this.Task = new Task(device, opera, Strategy.CreateImmediateStrategy(), timeout, 1); device.TaskManager.Tasks.Enqueue(this.Task); return ExecuteResult.CreateSuccessExecuteResult(); }
public override void DeviceInitialize (IDevice device) { Volume = device as IVolume; if (Volume == null) { throw new InvalidDeviceException (); } if (!Volume.IsMounted && device.MediaCapabilities != null && device.MediaCapabilities.IsType ("ipod")) { Hyena.Log.Information ("Found potential unmounted iDevice, trying to mount it now"); Volume.Mount (); } if (!Volume.IsMounted) { Hyena.Log.Information ("AppleDeviceSource is ignoring unmounted volume " + Volume.Name); throw new InvalidDeviceException (); } Device = new GPod.Device (Volume.MountPoint); if (GPod.ITDB.GetControlPath (Device) == null) { throw new InvalidDeviceException (); } base.DeviceInitialize (device); Name = Volume.Name; SupportsPlaylists = true; SupportsPodcasts = Device.SupportsPodcast; SupportsVideo = Device.SupportsVideo; Initialize (); GPod.ITDB.InitIpod (Volume.MountPoint, Device.IpodInfo == null ? null : Device.IpodInfo.ModelNumber, Name); // HACK: ensure that m4a, and mp3 are set as accepted by the device; bgo#633552 AcceptableMimeTypes = (AcceptableMimeTypes ?? new string [0]).Union (new string [] { "taglib/m4a", "taglib/mp3" }).ToArray (); // FIXME: Properly parse the device, color and generation and don't use the fallback strings // IpodInfo is null on Macos formated ipods. I don't think we can really do anything with them // but they get loaded as UMS devices if we throw an NRE here. if (Device.IpodInfo != null) { AddDapProperty (Catalog.GetString ("Device"), Device.IpodInfo.ModelString); AddDapProperty (Catalog.GetString ("Generation"), Device.IpodInfo.GenerationString); } // FIXME //AddDapProperty (Catalog.GetString ("Color"), "black"); AddDapProperty (Catalog.GetString ("Capacity"), string.Format ("{0:0.00}GB", BytesCapacity / 1024.0 / 1024.0 / 1024.0)); AddDapProperty (Catalog.GetString ("Available"), string.Format ("{0:0.00}GB", BytesAvailable / 1024.0 / 1024.0 / 1024.0)); AddDapProperty (Catalog.GetString ("Serial number"), Volume.Serial); //AddDapProperty (Catalog.GetString ("Produced on"), ipod_device.ProductionInfo.DisplayDate); //AddDapProperty (Catalog.GetString ("Firmware"), ipod_device.FirmwareVersion); //string [] capabilities = new string [ipod_device.ModelInfo.Capabilities.Count]; //ipod_device.ModelInfo.Capabilities.CopyTo (capabilities, 0); //AddDapProperty (Catalog.GetString ("Capabilities"), String.Join (", ", capabilities)); AddYesNoDapProperty (Catalog.GetString ("Supports cover art"), Device.SupportsArtwork); AddYesNoDapProperty (Catalog.GetString ("Supports photos"), Device.SupportsPhoto); }
/// <summary> /// ����������� ������. /// </summary> /// <param name="device">�������������� ����������.</param> public DeviceDiagram(IDevice device, string hostName) { if (device == null) throw new ArgumentNullException("device"); _device = device; _hostName = hostName; _partitionControls = new List<PartitionControl>(); // �������� ������� �����������. SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); MinimumSize = new Size(150, 150); foreach (IPartition part in _device.GetPartitions()) { _partitionControls.Add(new PartitionControl(this, part, _hostName)); } _device.PropertyChanged += new EventHandler<DeviceEventArgs>(_device_PropertyChanged); _device.PartitionAdded += new EventHandler<DeviceEventArgs>(_device_PartitionAdded); _device.PartitionRemoved += new EventHandler<DeviceEventArgs>(_device_PartitionRemoved); _centerControl = new DeviceControl(this, _device); RearrangePartitions(); }
public ServiceList (IAdapter adapter, IDevice device) { InitializeComponent (); this.adapter = adapter; this.device = device; this.services = new ObservableCollection<IService> (); listView.ItemsSource = services; // when device is connected adapter.DeviceConnected += (s, e) => { device = e.Device; // do we need to overwrite this? // when services are discovered device.ServicesDiscovered += (object se, EventArgs ea) => { Debug.WriteLine("device.ServicesDiscovered"); //services = (List<IService>)device.Services; if (services.Count == 0) Device.BeginInvokeOnMainThread(() => { foreach (var service in device.Services) { services.Add(service); } }); }; // start looking for services device.DiscoverServices (); }; // TODO: add to IAdapter first //adapter.DeviceFailedToConnect += (sender, else) => {}; DisconnectButton.Activated += (sender, e) => { adapter.DisconnectDevice (device); Navigation.PopToRootAsync(); // disconnect means start over }; }
public void SetDeviceAndService (IDevice device, IService service) { this._connectedDevice = device; this._currentService = service; this.Title = this._currentService.Name; this._tableSource.Characteristics = this._currentService.Characteristics; // wire up our handler for when characteristics are discovered (this._currentService as Service).CharacteristicsDiscovered += (object sender, EventArgs e) => { Console.WriteLine("CharacteristicsDiscovered"); TableView.ReloadData(); }; // discover the charactersistics (this._currentService as Service).DiscoverCharacteristics (); // // when a descriptor is dicovered, reload the table. // this._connectedDevice.DiscoveredDescriptor += (object sender, CBCharacteristicEventArgs e) => { // foreach (var descriptor in e.Characteristic.Descriptors) { // Console.WriteLine ("Characteristic: " + e.Characteristic.Value + " Discovered Descriptor: " + descriptor); // } // // reload the table // this.CharacteristicsTable.ReloadData(); // }; }
/// <summary> /// Return a list of available devices. /// </summary> internal void TrackJdwpProcessIds(IDevice device, Action<List<int>> callback) { SetDevice(device); Write(FormatAdbRequest("track-jdwp")); var resp = ReadAdbResponse(false); if (!resp.Okay) throw new AdbCommandRejectedException("host:track-devices rejected"); while (true) { int len; if (!TryReadHex4(out len)) { break; } List<int> list; if (len > 0) { var buf = new byte[len]; Read(buf); list = ParseJdwpData(ReplyToString(buf)).ToList(); } else { // Empty list = new List<int>(); } callback(list); } }
public DeviceResult(RequestStatus status, IDevice data, Int32 key, Exception exception) { Status = status; Data = data; Key = key; Exception = exception; }
/// <summary> /// Default ctor /// </summary> public BarDeployer(IDevice device) { this.deviceIp = device.UniqueId; this.password = device.Password; httpClient = new HttpClient(); UserName = "******"; }
public Deployer(String appIdString) { this.appIdString = appIdString; MultiTargetingConnectivity connectivity = new MultiTargetingConnectivity(CultureInfo.CurrentUICulture.LCID); ConnectableDevice connectableDevice = connectivity.GetConnectableDevice(Wvga512DeviceId); this.iDevice = connectableDevice.Connect(); }
protected CapdEmulatorService(IDevice device) { this.device = device; // Список для обратной связи. callbacks = new List<ICapdControlEmulatorEvents>(); currentQuantum = new Quantum(); }
public MainPage(MainViewModel mainViewModel, IDevice device) { _device = device; InitializeComponent(); Setup(mainViewModel); this.BindingContext = mainViewModel; }
public TestWindow(IDevice device) { Device = device; InitializeComponent(); if (device != null && device.Tests != null) { testTreeView.ItemsSource = device.Tests; } }
public async Task SetDevice(IDevice device) { SetValue(devicePropertyKey, device); SetValue(deviceNamePropertyKey, device.Name); await SetDeviceInternal(device); }
public Config(ref IDevice[] devices) { InitializeComponent(); this.devices = new SimpleFileDevice[devices.Length]; this.outDevices = devices; tbs = new TextBox[7]; tbs[0] = tbFile00; tbs[1] = tbFileF1; tbs[2] = tbFileF2; tbs[3] = tbFileF3; tbs[4] = tbFile04; tbs[5] = tbFile05; tbs[6] = tbFile06; for (int i = 0; i < 7; i++) { if (devices[i] is SimpleFileDevice) { if (((SimpleFileDevice)devices[i]).fs != null) tbs[i].Text = ((SimpleFileDevice)devices[i]).fs.Name; this.devices[i] = (SimpleFileDevice)devices[i]; } else { this.devices[i] = null; tbs[i].Text = "Not a file device."; } } }
/// <summary> /// Start looking for JDWP processes now. /// </summary> internal static void StartLaunchMonitor(IIde ide, IDevice device, string apkPath, string packageName, int apiLevel, int launchFlags, Action<LauncherStates, string> stateUpdate, CancellationToken token) { OutputPaneLog.EnsureLoaded(ide); var newMonitor = new LaunchMonitor(ide, device, apkPath, packageName, apiLevel, launchFlags, stateUpdate, token); monitor = newMonitor; newMonitor.Start(); }
public ConnectionManager(ILogger logger, ICredentialProvider credentialProvider, INetworkConnection networkConnectivity, IServerLocator serverDiscovery, string applicationName, string applicationVersion, IDevice device, ClientCapabilities clientCapabilities, ICryptographyProvider cryptographyProvider, Func<IClientWebSocket> webSocketFactory = null, ILocalAssetManager localAssetManager = null) { _credentialProvider = credentialProvider; _networkConnectivity = networkConnectivity; _logger = logger; _serverDiscovery = serverDiscovery; _httpClient = AsyncHttpClientFactory.Create(logger); ClientCapabilities = clientCapabilities; _webSocketFactory = webSocketFactory; _cryptographyProvider = cryptographyProvider; _localAssetManager = localAssetManager; Device = device; ApplicationVersion = applicationVersion; ApplicationName = applicationName; ApiClients = new Dictionary<string, IApiClient>(StringComparer.OrdinalIgnoreCase); SaveLocalCredentials = true; Device.ResumeFromSleep += Device_ResumeFromSleep; var jsonSerializer = new NewtonsoftJsonSerializer(); _connectService = new ConnectService(jsonSerializer, _logger, _httpClient, _cryptographyProvider, applicationName, applicationVersion); }
/// <summary> /// Initializes a new instance of the <see cref="PlaybackManager" /> class. /// </summary> /// <param name="localAssetManager">The local asset manager.</param> /// <param name="device">The device.</param> /// <param name="logger">The logger.</param> /// <param name="localPlayer">The local player.</param> public PlaybackManager(ILocalAssetManager localAssetManager, IDevice device, ILogger logger, ILocalPlayer localPlayer) { _localAssetManager = localAssetManager; _device = device; _logger = logger; _localPlayer = localPlayer; }
private static ObservableCollection <AudioSessionModel> GetCurrentSessionList(this IDevice device, IAudioSessionEnumerator sessionEnum) { var list = new ObservableCollection <AudioSessionModel>(); if (sessionEnum == null) { return(list); } sessionEnum.GetCount(out int sessionCount); for (int i = 0; i < sessionCount; i++) { try { sessionEnum.GetSession(i, out IAudioSessionControl sessionControl); var session = sessionControl.GetAudioSessionModel(out bool isSystemSession); if (session != null) { //put system session on top of the session list if (isSystemSession) { list.Insert(0, session); } else { list.Add(session); } } } catch { } } return(list); }
/// <summary> /// Initializes a new instance of the <see cref="ExtendedDeviceInfoPage"/> class. /// </summary> /// <param name="device">The device.</param> public ExtendedDeviceInfoPage(IDevice device) { this.Title = "Extended Device Info"; if (device == null) { this.Content = new Label() { TextColor = Color.Red, Text = "IDevice has not been configured with the dependency service." }; return; } var scroll = new ScrollView(); var stack = new StackLayout(); #region Display information var display = device.Display; var displayFrame = new Frame(); if (display != null) { displayFrame.Content = new StackLayout() { Children = { new Label { Text = display.ToString() }, new Label { Text = $"Screen width is\t {display.ScreenWidthInches():0.0} inches." }, new Label { Text = $"Screen height is\t {display.ScreenHeightInches():0.0} inches." }, new Label { Text = $"Screen diagonal size is\t {display.ScreenSizeInches():0.0} inches." } } }; } else { displayFrame.Content = new Label { TextColor = Color.Red, Text = "Device does not contain display information." }; } stack.Children.Add(displayFrame); #endregion #region Battery information var battery = device.Battery; var batteryFrame = new Frame(); if (battery != null) { var level = new Label(); var charger = new Label(); var levelAction = new Action(() => level.Text = $"Battery level is {battery.Level}%."); var chargerAction = new Action(() => charger.Text = $"Charger is {(battery.Charging ? "Connected" : "Disconnected")}."); levelAction.Invoke(); chargerAction.Invoke(); batteryFrame.Content = new StackLayout() { Children = { level, charger } }; battery.OnLevelChange += (s, e) => Device.BeginInvokeOnMainThread(levelAction); battery.OnChargerStatusChanged += (s, e) => Device.BeginInvokeOnMainThread(chargerAction); } else { batteryFrame.Content = new Label { TextColor = Color.Red, Text = "Device does not contain battery information." }; } stack.Children.Add(batteryFrame); #endregion #region RAM information var ramLabel = new Label { Text = "Total Memory:" }; var ramText = new Label(); stack.Children.Add(new Frame { Content = new StackLayout { Children = { ramLabel, ramText } } }); double mem; string format; if (device.TotalMemory < 1073741824) { mem = device.TotalMemory / 1024 / 1024d; format = "{0:#,0.00} MB"; } else { mem = device.TotalMemory / 1024 / 1024 / 1024d; format = "{0:#,0.00} GB"; } ramText.Text = string.Format(format, mem); #endregion #region Device Info var idLabel = new Label { Text = "Device Id:" }; var idText = new Label(); stack.Children.Add(new Frame { Content = new StackLayout { Children = { idLabel, idText } } }); try { idText.Text = device.Id; } catch (Exception ex) { idText.Text = ex.Message; } #endregion #region Device Name Information var deviceNameLabel = new Label { Text = "Device Name:" }; var deiceNameText = new Label(); stack.Children.Add(new Frame { Content = new StackLayout { Children = { deviceNameLabel, deiceNameText } } }); try { deiceNameText.Text = device.Name; } catch (Exception ex) { idText.Text = ex.Message; } #endregion #region Device Language Information var languageLabel = new Label { Text = "Device Language Code:" }; var languageText = new Label(); stack.Children.Add(new Frame { Content = new StackLayout { Children = { languageLabel, languageText } } }); try { languageText.Text = device.LanguageCode; } catch (Exception ex) { idText.Text = ex.Message; } #endregion #region Hardware Version Information var hardwareVersionLabel = new Label { Text = "Hardware Version:" }; var hardwareVersionText = new Label(); stack.Children.Add(new Frame { Content = new StackLayout { Children = { hardwareVersionLabel, hardwareVersionText } } }); try { hardwareVersionText.Text = device.HardwareVersion; } catch (Exception ex) { idText.Text = ex.Message; } #endregion #region Network Connetctions Information var networkLabel = new Label { Text = "Network Connections:" }; var networkText = new Label(); stack.Children.Add(new Frame { Content = new StackLayout { Children = { networkLabel, networkText } } }); try { var internetConnectionStatus = device.Network.InternetConnectionStatus(); switch (internetConnectionStatus) { case NetworkStatus.NotReachable: networkText.Text = "No Connetcions"; break; case NetworkStatus.ReachableViaCarrierDataNetwork: networkText.Text = "Mobil device Internet connetions"; break; case NetworkStatus.ReachableViaWiFiNetwork: networkText.Text = "Wi-fi Internet connetcions"; break; case NetworkStatus.ReachableViaUnknownNetwork: networkText.Text = "Unknow connetcions"; break; default: networkText.Text = "Error"; break; } } catch (Exception ex) { idText.Text = ex.Message; } #endregion scroll.Content = stack; this.Content = scroll; }
/// <summary> /// This is the background thread for collecting data /// </summary> public async void CollectionThread() { // Okay, let's enter the loop while (_keep_running) { int collect_count = 0; DateTime next_collect_time = DateTime.MaxValue; // Be safe about this - we don't want this thread to blow up! It's the only one we've got try { // Loop through sensors, and spawn a work item for them for (int i = 0; i < Children.Count; i++) { IDevice dc = Children[i] as IDevice; for (int j = 0; j < dc.Children.Count; j++) { // Allow us to kick out if (!_keep_running) { return; } // Okay, let's work on this sensor ISensor s = dc.Children[j] as ISensor; if ((s.Enabled) && (!s.InFlight) && (s.Frequency != Interval.Never)) { // Spawn a work item in the thread pool to do this collection task if (s.NextCollectTime <= DateTime.UtcNow) { s.InFlight = true; Task.Run(() => s.OuterCollect()); collect_count++; // If it's not time yet, use this to factor when next to wake up } else { if (s.NextCollectTime < next_collect_time) { next_collect_time = s.NextCollectTime; } } } } } // Failsafe } catch (Exception ex) { SensorProject.LogException("Collect", ex); } // Sleep until next collection time, but allow ourselves to kick out if (!_keep_running) { return; } TimeSpan time_to_sleep = next_collect_time - DateTime.UtcNow; int clean_sleep_time = Math.Max(1, Math.Min((int)time_to_sleep.TotalMilliseconds, 1000)); await Task.Delay(clean_sleep_time); } }
/// <summary> /// Adds a new sensor to a device /// </summary> /// <param name="device"></param> public void AddSensor(IDevice device, ISensor sensorToAdd) { sensorToAdd.Identity = GetNextSensorNum(); device.AddChild(sensorToAdd); }
/// <summary> /// Adds a new device to the project /// </summary> /// <param name="deviceToAdd"></param> public void AddDevice(IDevice deviceToAdd) { deviceToAdd.Identity = GetNextDeviceNum(); AddChild(deviceToAdd); }
public static void Close(this IDevice device) { device.Dispose(); }
public void LargeObjectTest1() { MyInput input = default(MyInput); MyLargeOutput output = new MyLargeOutput(); log = Devices.CreateLogDevice(TestContext.CurrentContext.TestDirectory + "\\hlog", deleteOnClose: true); objlog = Devices.CreateObjectLogDevice(TestContext.CurrentContext.TestDirectory + "\\hlog", deleteOnClose: true); Directory.CreateDirectory(TestContext.CurrentContext.TestDirectory + "\\checkpoints"); fht1 = new FasterKV <MyKey, MyLargeValue, MyInput, MyLargeOutput, Empty, MyLargeFunctions> (128, new MyLargeFunctions(), new LogSettings { LogDevice = log, ObjectLogDevice = objlog, MutableFraction = 0.1, MemorySizeBits = 29 }, new CheckpointSettings { CheckpointDir = TestContext.CurrentContext.TestDirectory + "\\checkpoints", CheckPointType = CheckpointType.Snapshot }, new SerializerSettings <MyKey, MyLargeValue> { keySerializer = () => new MyKeySerializer(), valueSerializer = () => new MyLargeValueSerializer() } ); fht2 = new FasterKV <MyKey, MyLargeValue, MyInput, MyLargeOutput, Empty, MyLargeFunctions> (128, new MyLargeFunctions(), new LogSettings { LogDevice = log, ObjectLogDevice = objlog, MutableFraction = 0.1, MemorySizeBits = 29 }, new CheckpointSettings { CheckpointDir = TestContext.CurrentContext.TestDirectory + "\\checkpoints", CheckPointType = CheckpointType.Snapshot }, new SerializerSettings <MyKey, MyLargeValue> { keySerializer = () => new MyKeySerializer(), valueSerializer = () => new MyLargeValueSerializer() } ); int maxSize = 1000; int numOps = 5000; fht1.StartSession(); Random r = new Random(33); for (int key = 0; key < numOps; key++) { var mykey = new MyKey { key = key }; var value = new MyLargeValue(1 + r.Next(maxSize)); fht1.Upsert(ref mykey, ref value, Empty.Default, 0); } fht1.TakeFullCheckpoint(out Guid token); fht1.CompleteCheckpoint(true); fht1.StopSession(); fht1.Dispose(); fht2.Recover(token); fht2.StartSession(); for (int keycnt = 0; keycnt < numOps; keycnt++) { var key = new MyKey { key = keycnt }; var status = fht2.Read(ref key, ref input, ref output, Empty.Default, 0); if (status == Status.PENDING) { fht2.CompletePending(true); } else { for (int i = 0; i < output.value.value.Length; i++) { Assert.IsTrue(output.value.value[i] == (byte)(output.value.value.Length + i)); } } } fht2.StopSession(); fht2.Dispose(); log.Close(); objlog.Close(); new DirectoryInfo(TestContext.CurrentContext.TestDirectory + "\\checkpoints").Delete(true); }
/// <param name='operations'> /// Reference to the LeapDayTinkering.RaspberryPi.IDevice. /// </param> /// <param name='deviceId'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task <bool> PostAsync(this IDevice operations, string deviceId, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Microsoft.Rest.HttpOperationResponse <bool> result = await operations.PostWithOperationResponseAsync(deviceId, cancellationToken).ConfigureAwait(false); return(result.Body); }
public void Setup() { // Clean up log files from previous test runs in case they weren't cleaned up try { new DirectoryInfo(path).Delete(true); } catch {} // Set up the Devices \ logs device = Devices.CreateLogDevice(path + "LogScan", deleteOnClose: true); log = new FasterLog(new FasterLogSettings { LogDevice = device }); deviceUnCommitted = Devices.CreateLogDevice(path + "LogScanUncommitted", deleteOnClose: true); logUncommitted = new FasterLog(new FasterLogSettings { LogDevice = deviceUnCommitted }); //****** Populate log for Basic data for tests // Set Default entry data for (int i = 0; i < entryLength; i++) { entry[i] = (byte)i; } // Enqueue but set each Entry in a way that can differentiate between entries for (int i = 0; i < numEntries; i++) { // Flag one part of entry data that corresponds to index if (i < entryLength) { entry[i] = (byte)entryFlag; } // puts back the previous entry value if ((i > 0) && (i < entryLength)) { entry[i - 1] = (byte)(i - 1); } // Add to FasterLog log.Enqueue(entry); } // Commit to the log log.Commit(true); //****** Populate uncommitted log / device for ScanUncommittedTest // Set Default entry data for (int j = 0; j < entryLength; j++) { entry[j] = (byte)j; } // Enqueue but set each Entry in a way that can differentiate between entries for (int j = 0; j < numEntries; j++) { // Flag one part of entry data that corresponds to index if (j < entryLength) { entry[j] = (byte)entryFlag; } // puts back the previous entry value if ((j > 0) && (j < entryLength)) { entry[j - 1] = (byte)(j - 1); } // Add to FasterLog logUncommitted.Enqueue(entry); } // refresh uncommitted so can see it when scan - do NOT commit though logUncommitted.RefreshUncommitted(true); }
public HealthStatus ProcessAlerts(IDevice device, IEnumerable<Alert> alerts) { HealthStatus formerStatus = device.CurrentStatus; HealthStatus retval = device.CurrentStatus; var alertStatusEvents = new List<AlertStatusChangeEvent>(); if (alerts.Any()) { using ( var ctx = ContextRegistry.NamedContextsFor( ContextRegistry.CreateNamed(ContextRegistry.Kind, UnikContextTypes.UnikTenantContextResourceKind))) { var batches = alerts.InBatchesOf(50); foreach (var batch in batches) { //using (var dc = DocumentStoreLocator.ContextualResolve()) //{ foreach (var it in batch) { int matchHash = it.CreateMatchHash(); /* var matches = dc.Query<Alert>().Where(a => a.MatchHash == matchHash && a.Status != AlertStatus.Closed); */ var querySpecification = new QuerySpecification() { Where = new Filter { Rules = new Comparison[] { new Comparison { Data = matchHash, Field = "MatchHash", Test = Test.Equal }, new Comparison { Data = AlertStatus.Closed, Field = "Status", Test = Test.NotEqual } } } }; var matches = ReportDataProvider.GetFromRepository<Alert>(querySpecification); bool isDuplicate = false; foreach (var candidate in matches) { if (candidate.RelatedDevice == it.RelatedDevice && it.Kind == candidate.Kind && it.AlertHealthLevel == candidate.AlertHealthLevel) { isDuplicate = true; break; } } if (!isDuplicate) { it.MatchHash = matchHash; if (it.AlertHealthLevel > retval) { retval = it.AlertHealthLevel; device.CurrentStatus = retval; alertStatusEvents.Add(new AlertStatusChangeEvent { Identifier = it.Identifier, AlertHealthLevel = it.AlertHealthLevel, AlertTitle = it.AlertTitle, Kind = it.Kind, KindDesc = it.Kind.EnumName().SpacePascalCase(), DeviceTags = it.Tags, Message = it.Message, RelatedDevice = it.RelatedDevice, RelatedDeviceName = it.RelatedDeviceName, Resolved = false, TimeGenerated = it.TimeGenerated, StaleAlertTime = (it.AlertHealthLevel == HealthStatus.Red) ? it.TimeGenerated + TimeSpan.FromHours(6.0) : it.TimeGenerated + TimeSpan.FromHours(24.0), LongestAssignmentTime = TimeSpan.FromSeconds(0.0) }); } ReportDataProvider.StoreInRepository<Alert>(it); //dc.Store(it); } } //dc.SaveChanges(); //} } } } if (formerStatus != retval) { using ( var ctx = ContextRegistry.NamedContextsFor(ContextRegistry.CreateNamed(ContextRegistry.Kind, UnikContextTypes. UnikWarehouseContextResourceKind))) { //using (var dc = DocumentStoreLocator.ContextualResolve()) //{ var deviceHealthChangeEvt = new DeviceHealthStatusEvent { DeviceId = device.Id, DeviceName = device.Name, From = formerStatus, To = retval, DeviceTags = device.Tags, DeviceTagHashes = DeviceHealthStatusEvent.ConvertTagsToHashs(device.Tags), TimeChanged = DateTime.UtcNow }; //dc.Store(deviceHealthChangeEvt); ReportDataProvider.StoreInRepository<DeviceHealthStatusEvent>(deviceHealthChangeEvt); var batches = alertStatusEvents.InBatchesOf(50); foreach (var batch in batches) { foreach (var se in batch) { //dc.Store(se); ReportDataProvider.StoreInRepository<AlertStatusChangeEvent>(se); } //dc.SaveChanges(); } //} } } return retval; }
protected CommandProcessor(IDevice device) { Device = device; }
public MyTimePickerRenderer() { // This is dependent on XForms (see Update note) Device = Resolver.Resolve<IDevice>(); }
/// <summary> /// Sets up the Fax job. /// </summary> /// <param name="device">The device.</param> private void SendFaxSetupJob(IDevice device) { UpdateStatus("Setting up Fax Send job..."); ScanLog.JobEndStatus = "Failed"; if (device == null) { throw new ArgumentNullException(nameof(device)); } UpdateStatus(string.Format("Setting up device at address {0} for user {1}", device.Address, ExecutionData.Credential.UserName)); InitializeAuthenticator(_data.AuthProvider, device, ExecutionData); // Load the fax application _faxApp = FaxAppFactory.Create(device); // need to add the ability for user to set eager or lazy authentication AuthenticationMode am = (_data.ApplicationAuthentication == false) ? AuthenticationMode.Eager : AuthenticationMode.Lazy; _faxApp.WorkflowLogger = Authenticator.WorkflowLogger = WorkflowLogger; _faxApp.Pacekeeper = Authenticator.Pacekeeper = new Pacekeeper(_data.AutomationPause); _faxApp.Launch(Authenticator, am); if (!_data.UseSpeedDial) { if (string.IsNullOrEmpty(_data.FaxNumber) || string.IsNullOrWhiteSpace(_data.FaxNumber)) { // Apply settings from configuration _faxApp.AddRecipient(FilePrefix.ToFaxCode()); } else { _faxApp.AddRecipient(_data.FaxNumber); } } else { Dictionary <string, string> recipients = new Dictionary <string, string>(); string[] FaxNums; if (_data.FaxNumber == null || string.IsNullOrWhiteSpace(_data.FaxNumber)) { // Apply settings from configuration FaxNums = FilePrefix.ToFaxCode().Split(','); foreach (string FaxNum in FaxNums) { recipients[FaxNum] = string.Empty; } _faxApp.AddRecipients(recipients, false); } else { FaxNums = _data.FaxNumber.Split(','); string[] PINs = new string[FaxNums.Length]; _data.PIN.Split(',', (char)StringSplitOptions.None).CopyTo(PINs, 0); for (int i = 0; i < FaxNums.Count(); i++) { recipients[FaxNums[i]] = PINs[i]; } _faxApp.AddRecipients(recipients, _data.UseSpeedDial); } } if (_data.EnableNotification) { EmailBuilder emailAddress = new EmailBuilder(_data.NotificationEmail, ExecutionData); //sending false parameter for thumbNail as it is unchecked bydefault _faxApp.Options.EnableEmailNotification(NotifyCondition.Always, emailAddress.ToString(), false); } //Sets the scan job options SetOptions(_data.ScanOptions, _faxApp.Options.GetType(), _faxApp.GetType(), device); _faxApp.Options.SetJobBuildState(this.UseJobBuild); // OCR is not applicable for fax jobs ScanLog.Ocr = false; UpdateStatus("Job setup complete"); _pacekeeper.Pause(); }
public Device_PlusMinus(IDevice _devicePlus, IDevice _deviceMinus) { devicePlus = _devicePlus; deviceMinus = _deviceMinus; }
private async void UiScanButton_Clicked(object sender, EventArgs e) { bool connected = false; if (!_isScanning) { _isScanning = true; UiScanButton.IsEnabled = !_isScanning; App.ShowToast("Scanning for BLE devices..."); _hasLocationPermission = await CheckLocationPermission(_hasLocationPermission); if (_hasLocationPermission.GetValueOrDefault(false)) { _bleDevice = null; var scanCompletionSource = new TaskCompletionSource <bool>(); _adapter.DeviceDiscovered += async(o, eventArgs) => { if (!String.IsNullOrWhiteSpace(eventArgs.Device.Name) && eventArgs.Device.Name.Contains(DeviceToLookFor)) { Debug.WriteLine($"Bluetooth LE device found: {eventArgs.Device.Name}"); if (await RegisterBleDevice(eventArgs.Device)) { App.ShowToast("Status: Device successfully connected!"); await _adapter.StopScanningForDevicesAsync(); await Task.Delay(3000); scanCompletionSource.SetResult(true); } } }; _adapter.ScanTimeoutElapsed += (o, args) => { Debug.WriteLine("Scan timed out."); scanCompletionSource.SetResult(false); }; _adapter.ScanMode = ScanMode.Balanced; _adapter.ScanTimeout = 10000; //Should be 10 seconds await _adapter.StartScanningForDevicesAsync(); connected = await scanCompletionSource.Task; if (_bleDevice == null) { App.ShowToast("Status: No device found."); await Task.Delay(5000); } } } ; _isScanning = false; if (connected) { UiScanButtonContainer.IsVisible = false; UiButtonsContainer.IsVisible = true; ResetButtonColors(DefaultButtonColor, true); } else { UiScanButton.IsEnabled = !_isScanning; App.ShowToast("Done scanning."); } }
public Core(IDevice device, IRepository repository) { Device = device; Repository = repository; }
private async Task <ICharacteristic> FindBleCharacteristic(Guid serviceId, Guid characteristicId, IDevice device) { ICharacteristic result = null; if (device == null) { throw new InvalidOperationException("Unable to find a characteristic when there is no BLE device."); } try { IService service = (await device.GetServicesAsync())?.FirstOrDefault(f => f.Id == serviceId); if (service != null) { result = (await service.GetCharacteristicsAsync())?.FirstOrDefault(f => f.Id == characteristicId); } } catch (Exception e) { Debug.WriteLine($"Error while retrieving BLE characteristic '{characteristicId}' on service '{serviceId}': {e}"); Debugger.Break(); throw; } return(result); }
private void TakeMainIndexCheckpoint(int tableVersion, IDevice device, out ulong numBytes) { BeginMainIndexCheckpoint(tableVersion, device, out numBytes); }
public void AddDevice(IDevice device) { _devices.Add(device); _logger.Log($"{device.DeviceName} added to Controller."); }
private async Task <bool> RegisterBleDevice(IDevice device) { bool registered = false; bool isConnectable = true; Debug.WriteLine($"BLE device name: {device.Name}"); Debug.WriteLine($"BLE device ID: {device.Id}"); Debug.WriteLine($"BLE device state: {device.State}"); Debug.WriteLine($"BLE device RSSI: {device.Rssi}"); if (device.AdvertisementRecords?.Any() ?? false) { int index = 0; foreach (AdvertisementRecord record in device.AdvertisementRecords) { string value = ""; switch (record.Type) { case AdvertisementRecordType.ShortLocalName: case AdvertisementRecordType.CompleteLocalName: value = Encoding.Default.GetString(record.Data); break; case AdvertisementRecordType.TxPowerLevel: case AdvertisementRecordType.Deviceclass: case AdvertisementRecordType.SimplePairingHash: case AdvertisementRecordType.SimplePairingRandomizer: case AdvertisementRecordType.DeviceId: case AdvertisementRecordType.SecurityManager: case AdvertisementRecordType.SlaveConnectionInterval: case AdvertisementRecordType.SsUuids16Bit: case AdvertisementRecordType.SsUuids128Bit: case AdvertisementRecordType.ServiceData: case AdvertisementRecordType.PublicTargetAddress: case AdvertisementRecordType.RandomTargetAddress: case AdvertisementRecordType.Appearance: case AdvertisementRecordType.DeviceAddress: case AdvertisementRecordType.LeRole: case AdvertisementRecordType.PairingHash: case AdvertisementRecordType.PairingRandomizer: case AdvertisementRecordType.SsUuids32Bit: case AdvertisementRecordType.ServiceDataUuid32Bit: case AdvertisementRecordType.ServiceData128Bit: case AdvertisementRecordType.SecureConnectionsConfirmationValue: case AdvertisementRecordType.SecureConnectionsRandomValue: case AdvertisementRecordType.Information3DData: case AdvertisementRecordType.ManufacturerSpecificData: case AdvertisementRecordType.Flags: case AdvertisementRecordType.UuidsIncomple16Bit: case AdvertisementRecordType.UuidsComplete16Bit: case AdvertisementRecordType.UuidsIncomplete32Bit: case AdvertisementRecordType.UuidCom32Bit: case AdvertisementRecordType.UuidsIncomplete128Bit: case AdvertisementRecordType.UuidsComplete128Bit: value = "Bytes: " + GetByteString(record.Data); break; case AdvertisementRecordType.IsConnectable: isConnectable = record.Data[0] == 1; value = isConnectable.ToString(); break; default: throw new ArgumentOutOfRangeException($"Advertisement Record Type is unknown: {(int)record.Type}"); } Debug.WriteLine($"BLE device AdvertismentRecord {index}: {record.Type}" + (value == "" ? "" : $" - {value}")); index++; } } if (isConnectable) { registered = await ConnectToDevice(device); } return(registered); }
public Robot(IRobotAi <T> ai, IDevice <T> executor) { this.ai = ai; this.device = executor; }
public void RemoveDevice(IDevice device) { _devices.Remove(device); _logger.Log($"{device.DeviceName} removed from Controller."); }
static void HookDeviceEvents(IList <IDisposable> registrations, IDevice device, IObserver <BleLogEvent> ob, BleLogFlags flags) { if (flags.HasFlag(BleLogFlags.ServiceDiscovered)) { registrations.Add(device .WhenServiceDiscovered() .Subscribe(serv => Write(ob, device, BleLogFlags.ServiceDiscovered, serv.Uuid, String.Empty)) ); } registrations.Add(device .WhenAnyCharacteristicDiscovered() .Subscribe(ch => { if (flags.HasFlag(BleLogFlags.CharacteristicDiscovered)) { Write(ob, device, BleLogFlags.CharacteristicDiscovered, ch.Uuid, String.Empty); } if (flags.HasFlag(BleLogFlags.CharacteristicRead)) { registrations.Add(ch .WhenRead() .Subscribe(result => Write(ob, device, result)) ); } if (flags.HasFlag(BleLogFlags.CharacteristicWrite)) { registrations.Add(ch .WhenWritten() .Subscribe(result => Write(ob, device, result)) ); } if (flags.HasFlag(BleLogFlags.CharacteristicNotify) && ch.CanNotify()) { registrations.Add(ch .WhenNotificationReceived() .Subscribe(result => Write(ob, device, result)) ); } }) ); registrations.Add(device .WhenyAnyDescriptorDiscovered() .Subscribe(desc => { if (flags.HasFlag(BleLogFlags.DescriptorDiscovered)) { Write(ob, device, BleLogFlags.DescriptorDiscovered, desc.Uuid, String.Empty); } if (flags.HasFlag(BleLogFlags.DescriptorRead)) { registrations.Add(desc .WhenRead() .Subscribe(result => Write(ob, device, result)) ); } if (flags.HasFlag(BleLogFlags.DescriptorWrite)) { registrations.Add(desc .WhenWritten() .Subscribe(result => Write(ob, device, result)) ); } }) ); }
internal void RecoverFuzzyIndex(int ht_version, IDevice device, ulong num_ht_bytes, IDevice ofbdevice, int num_buckets, ulong num_ofb_bytes) { BeginMainIndexRecovery(ht_version, device, num_ht_bytes); var sectorSize = device.SectorSize; var alignedIndexSize = (uint)((num_ht_bytes + (sectorSize - 1)) & ~(sectorSize - 1)); overflowBucketsAllocator.Recover(ofbdevice, alignedIndexSize, num_buckets, num_ofb_bytes); }
public TurnOff(IDevice device) { bulb = device; }
public RemoteControl(IDevice device) { this.device = device; }
private void ReadAsync <TContext>( ulong alignedSourceAddress, IntPtr alignedDestinationAddress, uint aligned_read_length, IOCompletionCallback callback, PageAsyncReadResult <TContext> asyncResult, IDevice device, IDevice objlogDevice) { if (!Key.HasObjectsToSerialize() && !Value.HasObjectsToSerialize()) { device.ReadAsync(alignedSourceAddress, alignedDestinationAddress, aligned_read_length, callback, asyncResult); return; } asyncResult.callback = callback; asyncResult.count++; asyncResult.objlogDevice = objlogDevice; device.ReadAsync(alignedSourceAddress, alignedDestinationAddress, aligned_read_length, AsyncReadPageCallback <TContext>, asyncResult); }
protected override TrezorManager CreateTrezorManager(IDevice device) => new TrezorManager(EnterPinArgs, EnterPassphraseArgs, device, LoggerFactory.CreateLogger <TrezorManager>());
private void WriteAsync <TContext>(IntPtr alignedSourceAddress, ulong alignedDestinationAddress, uint numBytesToWrite, IOCompletionCallback callback, PageAsyncFlushResult <TContext> asyncResult, IDevice device, IDevice objlogDevice) { if (!Key.HasObjectsToSerialize() && !Value.HasObjectsToSerialize()) { device.WriteAsync(alignedSourceAddress, alignedDestinationAddress, numBytesToWrite, callback, asyncResult); return; } // need to write both page and object cache asyncResult.count++; MemoryStream ms = new MemoryStream(); var buffer = ioBufferPool.Get(PageSize); Buffer.MemoryCopy((void *)alignedSourceAddress, buffer.aligned_pointer, numBytesToWrite, numBytesToWrite); long ptr = (long)buffer.aligned_pointer; List <long> addr = new List <long>(); asyncResult.freeBuffer1 = buffer; // Correct for page 0 of HLOG if (alignedDestinationAddress >> LogPageSizeBits == 0) { ptr += Constants.kFirstValidAddress; } while (ptr < (long)buffer.aligned_pointer + numBytesToWrite) { if (!Layout.GetInfo(ptr)->Invalid) { long pos = ms.Position; Key *key = Layout.GetKey(ptr); Key.Serialize(key, ms); ((AddressInfo *)key)->IsDiskAddress = true; ((AddressInfo *)key)->Address = pos; ((AddressInfo *)key)->Size = (int)(ms.Position - pos); addr.Add((long)key); pos = ms.Position; Value *value = Layout.GetValue(ptr); Value.Serialize(value, ms); ((AddressInfo *)value)->IsDiskAddress = true; ((AddressInfo *)value)->Address = pos; ((AddressInfo *)value)->Size = (int)(ms.Position - pos); addr.Add((long)value); } ptr += Layout.GetPhysicalSize(ptr); } var s = ms.ToArray(); var objBuffer = ioBufferPool.Get(s.Length); asyncResult.freeBuffer2 = objBuffer; var alignedLength = (s.Length + (sectorSize - 1)) & ~(sectorSize - 1); var objAddr = Interlocked.Add(ref segmentOffsets[(alignedDestinationAddress >> LogSegmentSizeBits) % SegmentBufferSize], alignedLength) - alignedLength; fixed(void *src = s) Buffer.MemoryCopy(src, objBuffer.aligned_pointer, s.Length, s.Length); foreach (var address in addr) { *((long *)address) += objAddr; } objlogDevice.WriteAsync( (IntPtr)objBuffer.aligned_pointer, (int)(alignedDestinationAddress >> LogSegmentSizeBits), (ulong)objAddr, (uint)alignedLength, callback, asyncResult); device.WriteAsync((IntPtr)buffer.aligned_pointer, alignedDestinationAddress, numBytesToWrite, callback, asyncResult); }
public AdvancedRemoteController(IDevice device) : base(device) { }