Пример #1
0
        public DeviceListViewModel(IDispatcherHelper dispatcherHelper, 
            INavigationService navigationService,
            IAdapter adapter,
            Func<IDevice, DeviceViewModel> deviceViewModelFactory)
        {
            _dispatcherHelper = dispatcherHelper;
            _navigationService = navigationService;
            _adapter = adapter;
            _deviceViewModelFactory = deviceViewModelFactory;

            _adapter.ScanTimeoutElapsed += (s, e) =>
            {
                StopScan();
            };
            _adapter.DeviceDiscovered += (s, e) =>
            {
                if (_devices.All(d => d.ID != e.Device.ID))
                {
                    _dispatcherHelper.RunOnUIThread(() =>
                        {
                            _devices.Add(e.Device);
                        });
                }
            };
        }
		public DeviceList (IAdapter adapter)
		{
			InitializeComponent ();
			this.adapter = adapter;
			this.devices = new ObservableCollection<IDevice> ();
			listView.ItemsSource = devices;

			adapter.DeviceDiscovered += (object sender, DeviceDiscoveredEventArgs e) => {
				Device.BeginInvokeOnMainThread(() => {
					devices.Add (e.Device);
				});
			};

			adapter.ScanTimeoutElapsed += (sender, e) => {
				adapter.StopScanningForDevices(); // not sure why it doesn't stop already, if the timeout elapses... or is this a fake timeout we made?
				Device.BeginInvokeOnMainThread ( () => {
					IsBusy = false;
					DisplayAlert("Timeout", "Bluetooth scan timeout elapsed, no heart rate monitors were found", "OK");
				});
			};

			ScanHrmButton.Activated += (sender, e) => {
				InfoFrame.IsVisible = false;
				// this is the UUID for Heart Rate Monitors
				StartScanning (0x180D.UuidFromPartial());
			};
		}
Пример #3
0
 public void SetAdapter(IAdapter adapter)
 {
     if (this.adapter == adapter) return;
     this.adapter = adapter;
     if (adapter != null) adapter.RegisterDataSetObserver(richDataSetObsever);
     ReloadChildViews();
 }
Пример #4
0
 public static void PrintUserInfo(IAdapter adapter)
 {
     Console.WriteLine("Имя:\t\t\t {0}", adapter.Name);
     Console.WriteLine("Возраст:\t\t {0}", adapter.Age);
     Console.WriteLine("Количество друзей:\t {0}", adapter.NumberOfFriends);
     Console.WriteLine("------- -------- ------- -------");
 }
Пример #5
0
		public DeviceList (IAdapter adapter)
		{
			InitializeComponent ();
			this.adapter = adapter;
			this.devices = new ObservableCollection<IDevice> ();
			listView.ItemsSource = devices;

			adapter.DeviceDiscovered += (object sender, DeviceDiscoveredEventArgs e) => {
				Device.BeginInvokeOnMainThread(() => {
					//TODO: uncomment this if there are a lot of Bluetooth devices around cluttering your list (and remove the line below)
//					if (e.Device.Name != null) {
//            			if (e.Device.Name.ToLower().Contains("biscuit")) {
//                			devices.Add(e.Device);
//            			}
//            		}
					devices.Add (e.Device);
				});
			};

			adapter.ScanTimeoutElapsed += (sender, e) => {
				IsBusy = false;
				Debug.WriteLine ("Scan timeout");
				if (autoScan) {
					StartScanning ();
				}
			};

			Appearing += (sender, e) => {
				StartScanning();
			};
		}
Пример #6
0
		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
			};
		}
Пример #7
0
		public DeviceList (IAdapter adapter)
		{
			InitializeComponent ();
			this.adapter = adapter;
			this.devices = new ObservableCollection<IDevice> ();
			listView.ItemsSource = devices;

			adapter.DeviceDiscovered += (object sender, DeviceDiscoveredEventArgs e) => {
				Device.BeginInvokeOnMainThread(() => {
					devices.Add (e.Device);
				});
			};

			adapter.ScanTimeoutElapsed += (sender, e) => {
				IsBusy = false;
				Debug.WriteLine ("Scan timeout");
				if (autoScan) {
					StartScanning ();
				}
			};

			Appearing += (sender, e) => {
				StartScanning();
			};
		}
Пример #8
0
 public bool Process(Data data, IAdapter adapter)
 {
     if (data.Device == device && (data.Service & service) > 0)
     {
         double value = Util.DataAdapter.GetGraphableValue(data);
         if (comparison == "<")
         {
             if (value < threshold) Email(value, adapter);
         }
         else if (comparison == "<=")
         {
             if (value <= threshold) Email(value, adapter);
         }
         else if (comparison == "==")
         {
             if (value == threshold) Email(value, adapter);
         }
         else if (comparison == ">=")
         {
             if (value >= threshold) Email(value, adapter);
         }
         else if (comparison == ">")
         {
             if (value > threshold) Email(value, adapter);
         }
     }
     return true;
 }
Пример #9
0
 public DockingViewManager(ITransport transport, IAdapter adapter, IScheduler scheduler, LocalScheduler dispatcher)
 {
     _transport = transport;
     _adapter = adapter;
     _scheduler = scheduler;
     _dispatcher = dispatcher;
 }
		public CharacteristicDetail_TISensor (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
		{
			InitializeComponent ();
			this.characteristic = characteristic;

			Title = characteristic.Name;
		}
Пример #11
0
		public TestPage (IAdapter adapter)
		{
			InitializeComponent ();
			this.adapter = adapter;
			this.devices = new ObservableCollection<IDevice> ();
			this.services = new ObservableCollection<IService> ();
			this.characteristics = new ObservableCollection<ICharacteristic> ();

			adapter.BluetoothStateUpdated += Adapter_BluetoothStateUpdated;
			adapter.ScanCompleted += Adapter_ScanCompleted;
			adapter.DeviceDiscovered += Adapter_DeviceDiscovered;
			adapter.DeviceConnected += Adapter_DeviceConnected;
			adapter.DeviceDisconnected += Adapter_DeviceDisconnected;
			adapter.DeviceFailedToConnect += Adapter_DeviceFailedToConnect;
			adapter.CommandResponse += Adapter_CommandResponse;
		
			btnValidate.Clicked += OnStartClicked;
			btnGenerateCode.Clicked += OnGenerateCodeClicked;
			btnDisconnect.Clicked += OnDisconnectDevice;

			btnGenSerial.Clicked += OnGenSerialClicked;
			btnValidateUser.Clicked += BtnValidateUser_Clicked;
			btnChangeUser.Clicked += BtnChangeUser_Clicked;

			//file.CreateFileAsync ("testFile.txt");
		}
 public DurationTraderViewModelController(ITransport transport, IAdapter adapter, IScheduler scheduler, LocalScheduler dispatcher)
 {
     transport.GetTradingObservables()
         .SubscribeOn(scheduler)
         .ObserveOn(dispatcher)
         .Subscribe(fSet => adapter.updater(fSet, ViewModel));
 }
Пример #13
0
		Task<ControlClient> ConnectAsync (IAdapter adapter)
		{
			var tcs = new TaskCompletionSource<ControlClient> ();

			adapter.DeviceDiscovered += (object sender, DeviceDiscoveredEventArgs e) => {
				Device.BeginInvokeOnMainThread(async () => {

					// Look for a specific device
					if (e.Device.ID.ToString ().StartsWith ("af18", StringComparison.OrdinalIgnoreCase)) {

						// Connect to the device
						await adapter.ConnectAsync (e.Device);

						// Establish the control client
						using (var stream = new LEStream (e.Device)) {
							var client = new ControlClient (stream);
							client.RunAsync (CancellationToken.None); // Don't await to run in background
							tcs.SetResult (client);
						}

						// Update the UI
						connectLabel.Text = "Yay " + e.Device + "!";
					}
				});
			};

			adapter.StartScanningForDevices();

			return tcs.Task;
		}
Пример #14
0
 public RequestResourceContext(IAdapter adapter, IAdaptee adaptee,
     RequestType resource)
 {
     Adaptee = adaptee;
     Adapter = adapter;
     ReqType = resource;
 }
    public void SetAdapter(IAdapter adapter)
    {
        mIAdapter = adapter;

        mIDevice.OnConnect(mIAdapter.controller);

    }
Пример #16
0
 public RobotEngine(IAdapter adapter, IHttpServer httpServer, Func<IRobot> robotFunc, Func<IEnumerable<RobotPart>> parts)
 {
     _adapter = adapter;
     _httpServer = httpServer;
     _robotFunc = robotFunc;
     _parts = parts;
     _contextExecutors = new List<IContextExecutor>();
 }
 public OnlineBookStoreService(IBookRepository bookRepository, IDictionaryRepository dictionaryRepository, IOrderRepository orderRepository, ICustomerRepository customerRepository, IAdapter adapter)
 {
     this._bookRepository = bookRepository;
     this._dictionaryRepository = dictionaryRepository;
     this._orderRepository = orderRepository;
     this._customerRepository = customerRepository;
     this._adapter = adapter;
 }
Пример #18
0
 public void SetBinding(IAdapter adapter)
 {
     adapter.Register(
         typeof(ISampleDAO),
         typeof(SampleDAO),
         ContainerEnumerator.LifeCycle.Transient
     );
 }
Пример #19
0
        public override void Initialize(IAdapter adapter)
        {
            base.Initialize(adapter);

            ScreenLayers screenLayers = WaveServices.ScreenLayers;
            screenLayers.AddScene<MyScene>();
            screenLayers.Apply();
        }
Пример #20
0
 public static void Refill(this LinearLayout layout, IAdapter adapter)
 {
     layout.RemoveAllViews();
     var count = adapter.Count;
     for (var i = 0; i < count; i++)
     {
         layout.AddView(adapter.GetView(i, null, layout));
     }            
 }
Пример #21
0
 public Feature(string name, IAdapter adapter, IInstrumenter instrumenter)
 {
     if (instrumenter == null)
     {
         throw new ArgumentNullException("instrumenter");
     }
     Name = name;
     Adapter = adapter;
     Instrumenter = instrumenter;
 }
Пример #22
0
        //Initial class
        public override void Initialize(IAdapter adapter)
        {
            //Initial base classe
            base.Initialize(adapter);

            //Create screen layer
            ScreenLayers screenLayers = WaveServices.ScreenLayers;
            screenLayers.AddScene<MyScene>();
            screenLayers.Apply();
        }
		public CharacteristicDetail_TISensor (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
		{
			InitializeComponent ();
			this.characteristic = characteristic;

			Title = characteristic.Name;

			if (Title.Contains ("Keys Data")) {
				InstructionsText.Text = "Press the two buttons on the TI Sensor to see the data generated below.";
			}
		}
Пример #24
0
		public void setAdapter(IAdapter adapter)
		{
			Debug.WriteLine("SyncHandler: Setting adapter");
			this.Adapter = adapter;

			this.Adapter.BluetoothStateUpdated += Adapter_BluetoothStateUpdated;
			this.Adapter.ScanCompleted += Adapter_ScanCompleted;
			this.Adapter.DeviceDiscovered += Adapter_DeviceDiscovered;
			this.Adapter.DeviceConnected += Adapter_DeviceConnected;
			this.Adapter.DeviceDisconnected += Adapter_DeviceDisconnected;
			this.Adapter.DeviceFailedToConnect += Adapter_DeviceFailedToConnect;
		}
Пример #25
0
        public Startup(IHostingEnvironment env)
        {
            Configuration = new ConfigurationBuilder(".", new[] { new JsonConfigurationSource("config.json") }).Build();
            Adapter = AdapterFactory.GetAdapter(Configuration["Adapter:Type"]);
            Serializer = new JsonSerializer();

            var configText = File.ReadAllText("config.json");
            var o = JsonConvert.DeserializeObject<Dictionary<string, object>>(configText);
            if (o.ContainsKey("PredefinedPages"))
            {
                PredefinedPages = JsonConvert.SerializeObject(o["PredefinedPages"]);
            }
        }
Пример #26
0
        public void RegisterAdapter(IAdapter adapter, string channel)
        {
            if (_adapters.ContainsKey(channel))
                throw new ApplicationException("There is already an adapter registered on that channel.");

            var filteredAdapter = new MessageFilterAdapter(adapter, _filters);

            _adapters.Add(channel, filteredAdapter);

            if (filteredAdapter.Producer != null)
            {
                filteredAdapter.Producer.MessageProduced += OnMessageProduced;
            }
        }
		public CharacteristicDetail (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
		{
			InitializeComponent ();
			this.characteristic = characteristic;

			if (characteristic.CanUpdate) {
				characteristic.ValueUpdated += (s, e) => {
					Debug.WriteLine("characteristic.ValueUpdated");
					Device.BeginInvokeOnMainThread( () => {
						UpdateDisplay(characteristic);
					});
				};
				characteristic.StartUpdates();
			}
		}
        public void SetBinding(IAdapter adapter)
        {
            adapter.Register(
                typeof(IBaseBusiness<>),
                typeof(BaseBusiness<>),
                ContainerEnumerator.LifeCycle.Transient
            );

            adapter.Register(
                typeof(IContextFactory<>),
                typeof(ContextFactory<>),
                ContainerEnumerator.LifeCycle.Singleton
            );

            adapter.Register(
                typeof(IRepositoryFactory<>),
                typeof(RepositoryFactory<>),
                ContainerEnumerator.LifeCycle.Singleton
            );

            adapter.Register(
                typeof(IRepository<>),
                typeof(EntityFrameworkRepository<>),
                ContainerEnumerator.LifeCycle.Transient
            );

            adapter.RegisterMany(
                typeof(IRepository<>),
                new Dictionary<object, Type>
                {
                    {
                        RepositoryEnumerator.RepositoryType.EntityFramework,
                        typeof(EntityFrameworkRepository<>)
                    },
                    {
                        RepositoryEnumerator.RepositoryType.ADO,
                        typeof(ADORepository<>)
                    }
                },
                ContainerEnumerator.LifeCycle.Transient
            );

            adapter.Register(
                typeof(ILogger),
                typeof(Log4NetAdapter),
                ContainerEnumerator.LifeCycle.Singleton
            );
        }
Пример #29
0
		public DeviceDetail (IAdapter adapter, Guid deviceId)
		{
			scheduler = TaskScheduler.FromCurrentSynchronizationContext ();

			this.adapter = adapter;
			this.deviceId = deviceId;
			InitializeComponent ();

			this.Appearing += async (sender, e) => {
				await RunControlAsync ();
			};

			adapter.DeviceDisconnected += (sender, e) => {
				// if device disconnects, return to main list screen
				Navigation.PopToRootAsync();
			};
		}
		public CharacteristicDetail (IAdapter adapter, IDevice device, IService service, ICharacteristic characteristic)
		{
			InitializeComponent ();
			this.characteristic = characteristic;

			if (characteristic.CanUpdate) {
				characteristic.ValueUpdated += (s, e) => {
					Debug.WriteLine("characteristic.ValueUpdated");
					Device.BeginInvokeOnMainThread( () => {
						IsBusy = false; // only spin until the first result is received
						UpdateDisplay(characteristic);
					});

				};
				IsBusy = true;
				characteristic.StartUpdates();
			}
		}
Пример #31
0
 /// <summary>
 /// Starts scanning for BLE devices.
 /// </summary>
 /// <param name="adapter">Target adapter.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
 /// <returns>A task that represents the asynchronous read operation. The Task will finish after the scan has ended.</returns>
 public static Task StartScanningForDevicesAsync(this IAdapter adapter, CancellationToken cancellationToken)
 {
     return(adapter.StartScanningForDevicesAsync(cancellationToken: cancellationToken));
 }
Пример #32
0
 /// <summary>
 /// Starts scanning for BLE devices that fulfill the <paramref name="deviceFilter"/>.
 /// DeviceDiscovered will only be called, if <paramref name="deviceFilter"/> returns <c>true</c> for the discovered device.
 /// </summary>
 /// <param name="adapter">Target adapter.</param>
 /// <param name="deviceFilter">Function that filters the devices.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.</param>
 /// <returns>A task that represents the asynchronous read operation. The Task will finish after the scan has ended.</returns>
 public static Task StartScanningForDevicesAsync(this IAdapter adapter, Func <IDevice, bool> deviceFilter, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(adapter.StartScanningForDevicesAsync(deviceFilter: deviceFilter, cancellationToken: cancellationToken));
 }
Пример #33
0
 /// <summary>
 /// Starts scanning for BLE devices that advertise the services included in <paramref name="serviceUuids"/>.
 /// </summary>
 /// <param name="adapter">Target adapter.</param>
 /// <param name="serviceUuids">Requested service Ids.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.</param>
 /// <returns>A task that represents the asynchronous read operation. The Task will finish after the scan has ended.</returns>
 public static Task StartScanningForDevicesAsync(this IAdapter adapter, Guid[] serviceUuids, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(adapter.StartScanningForDevicesAsync(serviceUuids, null, cancellationToken));
 }
Пример #34
0
 public static Task NavToAdapter(this INavigationService navigator, IAdapter adapter)
 => navigator.Navigate("AdapterPage", new NavigationParameters
 {
     { nameof(adapter), adapter }
 });
Пример #35
0
 public static Task <IDevice> DiscoverDeviceAsync(this IAdapter adapter, Guid deviceId, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(DiscoverDeviceAsync(adapter, device => device.Id == deviceId, cancellationToken));
 }
Пример #36
0
 public BaseViewModel(IAdapter adapter, ILogger <BaseViewModel> log)
 {
     Adapter = adapter;
     _log    = log;
 }
Пример #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BTService" /> class.
 /// </summary>
 /// <param name="dialogService">Access to platform specific dialogs</param>
 public BTService(IDialogService dialogService)
 {
     this.dialogService = dialogService;
     this.logger        = LogManager.GetCurrentClassLogger();
     this.adapter       = CrossBleAdapter.Current;
 }
Пример #38
0
 public BaseViewModel(IAdapter adapter)
 {
     Adapter = adapter;
 }
Пример #39
0
 public override RecordingAdapterRepo CreateAdapterRepo(
     IRecordingRepository repo, IAdapter <RecordingDTO, Recording> adapter)
 {
     return(new RecordingAdapterRepo(repo, adapter));
 }
Пример #40
0
 public Client()
 {
     adapter = new Adapter();
 }
Пример #41
0
        public void BleDevices()
        {
            IAdapter adapter = GetBleDevices();

            ListarDispositivos(adapter);
        }
Пример #42
0
 private static void SetAdapter(AdapterView item, IAdapter adapter)
 {
     _rawAdapterMember.SetValue(item, new object[] { adapter });
 }
Пример #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AnalyticsSystem"/> class.
 /// </summary>
 /// <param name="adapter">The adapter.</param>
 /// <param name="info">The info.</param>
 public AnalyticsSystem(IAdapter adapter, AnalyticsInfo info)
 {
     this.Adapter = adapter;
 }
Пример #44
0
        public ViewModelXerxesReadTemp(IAdapter adapter, IUserDialogs userDialogs) : base(adapter)
        {
            _userDialogs = userDialogs;

            OnReadButtonCommand = new Command(OnReadButtonButtonClick);
        }
        public ServiceList(IAdapter adapter, IDevice device)
        {
            InitializeComponent();
            this.adapter = adapter;
            this.device  = device;


            // 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) => {
                    if (foundScratchflag == false)
                    {
                        Debug.WriteLine("device.ServicesDiscovered");

                        if (foundScratchflag == false)
                        {
                            Device.BeginInvokeOnMainThread(() => {
                                foreach (IService service in device.Services)
                                {
                                    if (service.ID == Scartch_Service && foundScratchflag == false)
                                    {
                                        Service = service;
                                        Debug.WriteLine(Service.ID.ToString());
                                        foundScratchflag = true;
                                    }
                                }
                                if (foundScratchflag == true)
                                {
                                    cm = new CharacteristicManager(adapter, device, Service, Scartch_Service_2);
                                    if (cm.Detail.Characteristic.CanUpdate)
                                    {
                                        cm.Detail.Characteristic.ValueUpdated += (object sender, CharacteristicReadEventArgs eve) => {
                                            Debug.WriteLine("Characteristic.ValueUpdated");
                                            Device.BeginInvokeOnMainThread(() => {
                                                string heart_rate = cm.Detail.UpdateValue(cm.Detail.Characteristic);
                                                hr_label.Text     = String.Format("HR: {0}", heart_rate);
                                            });
                                        };

                                        cm.Detail.Characteristic.StartUpdates();
                                    }
                                }
                            });
                        }
                        Debug.WriteLine("Start Discovery");
                        cm.service.DiscoverCharacteristics();
                    }
                };
                Device.BeginInvokeOnMainThread(() => {
                    IsBusy = false;
                });
                // start looking for services

                device.DiscoverServices();
            };

            DisconnectButton.Activated += (sender, e) => {
                cm.Detail.OnDisappearing();
                adapter.DisconnectDevice(device);
                Navigation.PopToRootAsync();
            };
        }
Пример #46
0
 public override void OnNavigatingTo(INavigationParameters parameters)
 {
     base.OnNavigatingTo(parameters);
     this.adapter = parameters.GetValue <IAdapter>("adapter");
 }
Пример #47
0
 public void HeaderHelperTest1()
 {
     string docFile = Path.Combine(TestUtil.GetTestDataPath(), "E - min_sport_2012_Rukovoditeli_gospredpriyatij,_podvedomstvennyih_ministerstvu.doc");
     //IAdapter adapter = AsposeExcelAdapter.CreateAsposeExcelAdapter(xlsxFile);
     IAdapter adapter = AsposeDocAdapter.CreateAdapter(docFile);
 }
 protected DeviceBase(IAdapter adapter)
 {
     Adapter = adapter;
 }
Пример #49
0
 public void SetAdapter(IAdapter adapter)
 {
     this.adapter = adapter;
 }
Пример #50
0
 /// <summary>
 /// Connects to the <paramref name="device"/>.
 /// </summary>
 /// <param name="adapter">Target adapter.</param>
 /// <param name="device">Device to connect to.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.</param>
 /// <returns>A task that represents the asynchronous read operation. The Task will finish after the device has been connected successfuly.</returns>
 /// <exception cref="DeviceConnectionException">Thrown if the device connection fails.</exception>
 public static Task ConnectToDeviceAsync(this IAdapter adapter, IDevice device, CancellationToken cancellationToken)
 {
     return(adapter.ConnectToDeviceAsync(device, cancellationToken: cancellationToken));
 }
Пример #51
0
 public Client(IAdapter adapter)
 {
     this.adapter = adapter;
 }
Пример #52
0
 public UserRepository(IAdapter adapter) : base(adapter)
 {
 }
Пример #53
0
 public static IController Create(IAdapter adapter, IModel fpsModel)
 {
     return(new FPSController(adapter, fpsModel));
 }
Пример #54
0
 public AssignmentsController(IAdapter adapter, IAssignmentRepository assignmentRepository)
 {
     _adapter = adapter;
     _assignmentRepository = assignmentRepository;
 }
Пример #55
0
        private async void FromCupButton_Clicked(object sender, EventArgs e)
        {
            IBluetoothLE   bluetoothBLE = CrossBluetoothLE.Current;
            IAdapter       adapter      = CrossBluetoothLE.Current.Adapter;
            List <IDevice> deviceList   = new List <IDevice>();
            IDevice        device       = null;

            var state = bluetoothBLE.State;

            CupInput.Text += $"BLE State: {state}\n";

            /*if (bluetoothBLE.State == BluetoothState.Off)
             * {
             *  await DisplayAlert("Error", "Bluetooth disabled.", "OK");
             * }
             * else
             * {
             *  deviceList.Clear();
             *
             *  adapter.ScanTimeout = 3000;
             *  adapter.ScanMode = ScanMode.Balanced;
             *
             *  adapter.DeviceDiscovered += (obj, a) =>
             *  {
             *      if (!deviceList.Contains(a.Device))
             *          deviceList.Add(a.Device);
             *  };
             *
             *
             *  CupInput.Text += $"Start scaning\n";
             *  await adapter.StartScanningForDevicesAsync();
             *
             *  FromCupButton.Text = "Scaning\n";
             * }
             * CupInput.Text += $"Device count: {deviceList.Count}";
             *
             * foreach(var dev in deviceList)
             * {
             *  CupInput.Text += $"{dev.Name} {dev.Id} {dev.State}\n";
             *  if (dev.Name == "CC41-A")
             *  {
             *      device = dev;
             *  }
             * }*/


            CupInput.Text += "Connecting...";
            try
            {
                device = await adapter.ConnectToKnownDeviceAsync(new Guid("00000000-0000-0000-0000-00158310d640"));

                CupInput.Text += $"{device.Name}: {device.State}\n";
            }
            catch (Exception ex)
            {
                CupInput.Text     += $"Error: {ex.Message}\n";
                FromCupButton.Text = "Error";
                return;
            }
            CupInput.Text += "OK\n";



            // start
            var srv = await device.GetServiceAsync(new Guid("0000ffe0-0000-1000-8000-00805f9b34fb"));

            var ch = await srv.GetCharacteristicAsync(new Guid("0000ffe1-0000-1000-8000-00805f9b34fb"));

            await ch.WriteAsync(Encoding.UTF8.GetBytes("1"));

            string hex = BitConverter.ToString(Encoding.UTF8.GetBytes("1"));

            CupInput.Text += $"Hex Repr: {hex}\n";

            var services = await device.GetServicesAsync();

            foreach (var service in services)
            {
                //CupInput.Text += $"Service: {service.Name} {service.Id}\n";
                var chars = await service.GetCharacteristicsAsync();

                foreach (var chr in chars)
                {
                    CupInput.Text += $"--Char: {chr.Name} [{chr.Id},{chr.Uuid}[{chr.StringValue},{chr.Value}] {chr.CanRead} {chr.CanWrite} {chr.CanUpdate}]\n";
                    var desriptors = await chr.GetDescriptorsAsync();

                    foreach (var desc in desriptors)
                    {
                        //CupInput.Text += $"----Desc: {desc.Name} [{desc.Id},{desc.Value}]\n";
                        var res = await desc.ReadAsync();

                        var str = Encoding.UTF8.GetString(res);
                        //CupInput.Text += ($"Readed: /{str}/\n");
                    }
                    if (chr.CanRead)
                    {
                        byte[] bytes;
                        bytes = await chr.ReadAsync();

                        var str = Encoding.UTF8.GetString(bytes);
                        CupInput.Text += ($"Readed: /{str}/\n");
                    }
                    if (chr.CanUpdate)
                    {
                        CupInput.Text += ($"Updatable: /{chr.Name}/\n");

                        /*chr.ValueUpdated += async (obj, a) =>
                         * {
                         *  try
                         *  {
                         *      var res = await a.Characteristic.ReadAsync();
                         *      var str = Encoding.UTF8.GetString(res);
                         *      Console.WriteLine($"[BLE {chr.Name}: '{str}']");
                         *  }
                         *  catch (Exception ex)
                         *  {
                         *      Console.WriteLine($"[BLE ERROR {chr.Name}: '{ex.Message}']");
                         *  }
                         * };
                         * await chr.StartUpdatesAsync();*/
                    }
                }
            }

            Console.WriteLine(CupInput.Text);

            FromCupButton.Text = "Finished";

            /*FromCupButton.BackgroundColor = Color.Green;
             * if (FromCameraButton.BackgroundColor == Color.Green && FromCupButton.BackgroundColor == Color.Green)
             * {
             *  ReadyButton.IsVisible = true;
             *  FromCameraButton.IsVisible = false;
             *  FromCupButton.IsVisible = false;
             * }*/
        }
 public void CheckMyAdapter(IAdapter adapter)
 {
     adapter.StartScanningForDevicesAsync();
 }
Пример #57
0
 public DeviceInfoViewViewModel(IAdapter btAdapter)
 {
     _btAdapter = btAdapter;
 }
Пример #58
0
 public PlantData(IDataAccess db, IAdapter adapter)
 {
     _db      = db;
     _adapter = adapter;
 }
Пример #59
0
        public SettingsPage()
        {
            #region Bluetooth Connection
            Title        = "Blue";
            bluetoothBLE = CrossBluetoothLE.Current;
            adapter      = CrossBluetoothLE.Current.Adapter;

            deviceList = new ObservableCollection <IDevice>();
            //lv.ItemsSource = deviceList;


            Button scanButton = new Button
            {
                Text              = " Scan ",
                Font              = Font.SystemFontOfSize(NamedSize.Small),
                BorderWidth       = 1,
                HorizontalOptions = LayoutOptions.Start,
                VerticalOptions   = LayoutOptions.CenterAndExpand
            };
            scanButton.Clicked += btnScan_Clicked;

            Button GetServicesButton = new Button
            {
                Text              = "GetServices",
                Font              = Font.SystemFontOfSize(NamedSize.Small),
                BorderWidth       = 1,
                HorizontalOptions = LayoutOptions.Center,
                VerticalOptions   = LayoutOptions.CenterAndExpand
            };
            //GetServicesButton.Clicked += btnGetServices_Clicked;


            ListView devicesListed = new ListView
            {
                ItemsSource            = deviceList,
                VerticalOptions        = LayoutOptions.Start,
                IsPullToRefreshEnabled = true,
                ItemTemplate           = new DataTemplate(() =>
                {
                    Label nameLabel = new Label()
                    {
                    };
                    nameLabel.SetBinding(Label.TextProperty, "Name");
                    //Label addressLabel = new Label();
                    //addressLabel.SetBinding(Label.TextProperty, "Id");
                    return(new ViewCell
                    {
                        View = new StackLayout
                        {
                            //Padding = new Thickness(0, 5),
                            Children =
                            {
                                nameLabel,
                                //addressLabel
                            }
                        }
                    });
                }),
            };
            devicesListed.ItemSelected += DevicesList_OnItemSelected;
            #endregion

            #region User info
            var Userinfo = new Label {
                Text = "User info", FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)), HorizontalOptions = LayoutOptions.Start
            };
            var NameLabel = new Label {
                Text = "Name: ", FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center
            };
            var Name = new Entry
            {
                IsReadOnly      = true,
                Text            = "Brian Lee",
                FontSize        = 13,
                Placeholder     = "Enter email address",
                VerticalOptions = LayoutOptions.CenterAndExpand,
            };
            var HeightLabel = new Label {
                Text = "Height: ", FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center
            };
            var Height = new Entry
            {
                IsReadOnly      = true,
                Text            = "5'11''",
                FontSize        = 13,
                Placeholder     = "Enter email address",
                VerticalOptions = LayoutOptions.CenterAndExpand,
            };
            var WeightLabel = new Label {
                Text = "Weight: ", FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center
            };
            var Weight = new Entry
            {
                Text            = "185",
                IsReadOnly      = true,
                FontSize        = 13,
                Placeholder     = "Enter email address",
                VerticalOptions = LayoutOptions.CenterAndExpand,
            };
            var EmailLabel = new Label {
                Text = "Email: ", FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center
            };
            var Email = new Entry
            {
                Text            = "*****@*****.**",
                IsEnabled       = false,
                Keyboard        = Keyboard.Email,
                FontSize        = 13,
                Placeholder     = "Enter email address",
                VerticalOptions = LayoutOptions.CenterAndExpand,
            };
            var PasswordLabel = new Label {
                Text = "Password: "******"asdf1234",
                IsReadOnly      = true,
                Keyboard        = Keyboard.Text,
                FontSize        = 13,
                Placeholder     = "Enter password",
                IsPassword      = true,
                VerticalOptions = LayoutOptions.CenterAndExpand
            };
            #endregion

            Button UpdateButton = new Button
            {
                Text              = "  Update  ",
                Font              = Font.SystemFontOfSize(NamedSize.Small),
                BorderWidth       = 1,
                BorderColor       = Color.Silver,
                HorizontalOptions = LayoutOptions.Start,
                VerticalOptions   = LayoutOptions.Start
            };
            UpdateButton.Clicked += UpdateClicked;
            Button Logout = new Button
            {
                Text              = "  Logout  ",
                Font              = Font.SystemFontOfSize(NamedSize.Small),
                BorderWidth       = 1,
                BorderColor       = Color.Silver,
                HorizontalOptions = LayoutOptions.Start,
                VerticalOptions   = LayoutOptions.Start
            };
            Logout.Clicked += LogoutChaAsync;

            Title   = "Settings";
            Content = new StackLayout
            {
                Margin          = new Thickness(20),
                VerticalOptions = LayoutOptions.FillAndExpand,
                Children        =
                {
                    //new Label { Text = "Settings Page" },
                    Userinfo,
                    new StackLayout()
                    {
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        Orientation       = StackOrientation.Horizontal, Children     = { NameLabel,     Name     }
                    },
                    new StackLayout()
                    {
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        Orientation       = StackOrientation.Horizontal, Children     = { HeightLabel,   Height   }
                    },
                    new StackLayout()
                    {
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        Orientation       = StackOrientation.Horizontal, Children     = { WeightLabel,   Weight   }
                    },
                    new StackLayout()
                    {
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        Orientation       = StackOrientation.Horizontal, Children     = { EmailLabel,    Email    }
                    },
                    new StackLayout()
                    {
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        Orientation       = StackOrientation.Horizontal, Children     = { PasswordLabel, Password }
                    },
                    UpdateButton,
                    texxt,
                    Logout,
                    scanButton,
                    devicesListed
                }
            };


            void UpdateClicked(object sender, EventArgs e)
            {
                if (Name.IsReadOnly == true)
                {
                    Name.IsReadOnly     = false;
                    Height.IsReadOnly   = false;
                    Weight.IsReadOnly   = false;
                    Password.IsReadOnly = false;
                }
                else if (Name.IsReadOnly == false)
                {
                    Name.IsReadOnly     = true;
                    Height.IsReadOnly   = true;
                    Weight.IsReadOnly   = true;
                    Password.IsReadOnly = true;
                }
            }
        }
Пример #60
0
 public Client(IAdapter adapter)
 {
     m_Adapter = adapter;
 }