I'm working on BluetoothLE, I want to see the devices around me in a list with their names, and I want to see the properties, services and characters of a device, but I can't see these devices even though the bluetooth of my phone and headset is turned on, the list always comes up empty.
Here is my sample code:
private GattCharacteristic gattCharacteristic;
private BluetoothLEDevice bluetoothLeDevice;
public List<DeviceInformation> bluetoothLeDevicesList = new List<DeviceInformation>();
public DeviceInformation selectedBluetoothLeDevice = null;
public bool IsScannerActiwe { get; set; }
public bool ButtonPressed { get; set; }
public bool IsConnected { get; set; }
public static string StopStatus = null;
public BluetoothLEAdvertisementWatcher watcher;
private DeviceWatcher deviceWatcher;
public void StartWatcher()
{
try
{
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.IsPresent", "System.Devices.Aep.ContainerId", "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.Manufacturer", "System.Devices.Aep.ModelId", "System.Devices.Aep.ProtocolId", "System.Devices.Aep.SignalStrength" };
deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
}
catch (Exception ex)
{
Console.WriteLine("Exception -> ", ex.Message);
}
}
public List<DeviceInformation> GetBluetoothLEDevicesList()
{
try
{
return bluetoothLeDevicesList;
}
catch (Exception ex)
{
Console.WriteLine("Exception Handled -> GetBluetoothLEDevices: " + ex);
throw ex;
}
}
public List<string> GetBluetoothLEDevices()
{
try
{
return bluetoothLeDevicesList.Select(x => x.Name).ToList();
}
catch (System.Exception ex)
{
Trace.WriteLine("Exception Handled -> GetBluetoothLEDevices: " + ex);
throw ex;
}
}
I started a few new advertisements with my iphone via the nrF Connect application and I can see it on my pc, but I want to put them all in a list and navigate through that list.
This is Test.cs:
class Test
{
static void Main(string[] args)
{
// Since the StartWatcher method is called from within the constructor method,
that method will always run whenever an instance is created.
BLEControllers bLEControllers = new BLEControllers();
var devices = bLEControllers.GetBluetoothLEDevicesList();
foreach (var device in devices)
{
if (device != null)
{
Console.WriteLine(device.Name);
}
Console.WriteLine("empty");
}
//bLEControllers.ConnectDevice(device);
//bLEControllers.ConnectDevice();
Console.Read();
}
}
Whenever I run this code, neither device names nor empty text appears on the console, only the startWatcher function works and ends. Is there any function to list all the devices? And how can I see the supported service and characteristic uuids? is there a way to do this?
Related
I'm stucked for a while trying to use zkemkeeper sdk to use on a Windows Service that uses a InBios(Controller) for fingerprint.
i first connect to the device and then i add the event OnAttTransactionEx, someone can point me what i'm doing wrong.
Here is the code snippet
`
protected override void OnStart(string[] args)
{
Thread TT = new Thread(new ThreadStart(WorkedThread));
TT.IsBackground = true;
TT.SetApartmentState(ApartmentState.STA);
this.isServiceStarted = true;
TT.Start();
}
private void WorkedThread()
{
WriteToFile("Worker Thread Started.");
ZKemClient objZkeeper = new ZKemClient(filepath);
this.isDeviceConnected = objZkeeper.Connect_Net("19x.x.x.24x", 4370);
if (this.isDeviceConnected)
{
WriteToFile("Device connected.");
WriteToFile("While loop execution starting.");
while (true)
{
WriteToFile(filepath, "While loop execution started.");
}
}
else
{
WriteToFile("Failed to connect to Device.");
}
}
// ZMClient class
public bool Connect_Net(string IPAdd, int Port)
{
bool bResult = false;
try
{
// Actual SDK class
CZKEM objCZKEM = new CZKEM();
if (objCZKEM.Connect_Net(IPAdd, Port))
{
if (objCZKEM.RegEvent(1, 32767))
{
// [ Register your events here ]
objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
}
bResult = true;
}
}
catch (Exception ex)
{
WriteToFile("Connect_Net() Exception->" + ex.Message);
}
return bResult;
}
`
After playing a lot with threading, found a solution.
For windows service - Add reference to System.Windows.Forms
Thread TT1 = new Thread(() =>
{
this.objCZKEM = new CZKEM();
Application.Run();
});
TT1.IsBackground = true;
TT1.SetApartmentState(ApartmentState.STA);
TT1.Start();
Simply continue with current thread
if (this.objCZKEM.Connect_Net(IP, 4370))
{
this.WriteToFile("ZKEM device connected");
if (this.objCZKEM.RegEvent(1, 32767))
{
this.WriteToFile("ZKEM device events registration started");
// [ Register your events here ]
this.objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
this.WriteToFile("Done with ZKEM device events registration.");
}
You should not able to receive finger events from device.
I am working on an IOT module with wifi connection,I am testing using a samsung with android 10.
The chip is a ESP8266.The Wi-Fi signal, does not have an internet connection.
the project is developed in xamarin.
The problem, is when I try to connect to the device's signal. When I'm making the connection request, multiple pop ups appear in the device, requesting the connection, and it does not wait until it is connected, immediately the device launches the connection requests again and again, finally crash.
when i'm debugging, the NetworkAvailable runs, but even the phone does not finish connecting to the signal, the phone lunch a new request network again, don't wait until you are actually connected, and I don't know why multiple requests are launched.
Here is my code.
public async Task<bool> Connect(string WiFiName, string WifiPassword)
{
bool result = false;
var formattedSsid = $"\"{WiFiName}\"";
var formattedPassword = $"\"{WifiPassword}\"";
try
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
var wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
.SetSsid(WiFiName)
.SetWpa2Passphrase(WifiPassword)
.Build();
var networkRequest = new NetworkRequest.Builder()
.AddTransportType(TransportType.Wifi) // we want WiFi
.SetNetworkSpecifier(wifiNetworkSpecifier) // we want _our_ network
.Build();
UnregisterNetworkCallback(_networkCallback);
_networkCallback = new NetworkCallback()
{
NetworkAvailable = network =>
{
result = true;
autoResetEvent.Set(); //signal
},
NetworkUnavailable = () =>
{
result = false;
autoResetEvent.Set(); //signal
},
};
connectivityManager.RequestNetwork(networkRequest, _networkCallback);
autoResetEvent.WaitOne();
}
catch (Exception e)
{
Crashes.TrackError(e);
}
finally
{
}
return result;
}
private void UnregisterNetworkCallback(NetworkCallback _networkCallback)
{
if (_networkCallback != null)
{
try
{
_connectivityManager.UnregisterNetworkCallback(_networkCallback);
}
catch (Exception) {
} finally
{
_networkCallback = null;
}
}
}
public class NetworkCallback : ConnectivityManager.NetworkCallback
{
public Action<Network> NetworkAvailable { get; set; }
public Action NetworkUnavailable { get; set; }
public NetworkCallback()
{
}
public override void OnAvailable(Network network)
{
try
{
WiFiAndroid.connectivityManager.BindProcessToNetwork(null);
WiFiAndroid.connectivityManager.BindProcessToNetwork(network);
}
catch (Exception ex)
{
var error = ex;
}
}
public override void OnUnavailable()
{
base.OnUnavailable();
NetworkUnavailable?.Invoke();
}
}
the image, is the request that is throw over and over again.
I'm using camera2basic, when I change flash parameter on runtime it not working and load first parameter when app loading.
example : when I set auto-flash in hardcode it worked when I change it to Off in my app it not work and flash parameter is auto-flash yet.
I want to set flash parameter in application not hardcode. How can i do it?
**//Camera2BasicFragment.cs**
public void CaptureStillPicture()
{
try
{
var activity = Activity;
if (null == activity || null == mCameraDevice)
{
return;
}
// This is the CaptureRequest.Builder that we use to take a picture.
if (stillCaptureBuilder == null)
stillCaptureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
stillCaptureBuilder.AddTarget(mImageReader.Surface);
SetFlash(stillCaptureBuilder);
// Orientation
int rotation = (int)activity.WindowManager.DefaultDisplay.Rotation;
stillCaptureBuilder.Set(CaptureRequest.JpegOrientation, GetOrientation(rotation));
mCaptureSession.StopRepeating();
mCaptureSession.Capture(stillCaptureBuilder.Build(), new CameraCaptureStillPictureSessionCallback(this), null);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
ControlAEMode AeFlashMode = ControlAEMode.Off;
public void SetFlash(CaptureRequest.Builder requestBuilder)
{
if (mFlashSupported)
{
requestBuilder.Set(CaptureRequest.ControlAeMode, (int)AeFlashMode);
}
}
-------------------------------
**//CameraCaptureSessionCallback.cs**
public override void OnConfigured(CameraCaptureSession session)
{
// The camera is already closed
if (null == owner.mCameraDevice)
{
return;
}
// When the session is ready, we start displaying the preview.
owner.mCaptureSession = session;
try
{
// Auto focus should be continuous for camera preview.
owner.SetFocus(owner.mPreviewRequestBuilder);
// Flash is automatically enabled when necessary.
owner.SetFlash(owner.mPreviewRequestBuilder);
// Finally, we start displaying the camera preview.
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
You can add following code to your CameraCaptureSessionCallback.cs
public void ISFlashOpenOrClose(bool isTorchOn)
{
owner.mCaptureSession = this.session;
if (isTorchOn)
{
owner.mPreviewRequestBuilder.Set(CaptureRequest.FlashMode, (int)ControlAEMode.On);
// owner.mPreviewRequestBuilder.Set(CaptureRequest.FlashMode, (int)FlashMode.Off);
// mPreviewSession.SetRepeatingRequest(mPreviewBuilder.build(), null, null);
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
// isTorchOn = false;
}
else
{
owner.mPreviewRequestBuilder.Set(CaptureRequest.ControlAeMode, (int)ControlAEMode.Off);
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
}
}
Here is all of code about CameraCaptureSessionCallback.cs
public class CameraCaptureSessionCallback : CameraCaptureSession.StateCallback
{
private readonly Camera2BasicFragment owner;
CameraCaptureSession session;
public CameraCaptureSessionCallback(Camera2BasicFragment owner)
{
if (owner == null)
throw new System.ArgumentNullException("owner");
this.owner = owner;
}
public override void OnConfigureFailed(CameraCaptureSession session)
{
owner.ShowToast("Failed");
}
private bool isTorchOn;
public override void OnConfigured(CameraCaptureSession session)
{
// The camera is already closed
if (null == owner.mCameraDevice)
{
return;
}
this.session = session;
// When the session is ready, we start displaying the preview.
owner.mCaptureSession = session;
try
{
// Auto focus should be continuous for camera preview.
owner.mPreviewRequestBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.ContinuousPicture);
// Flash is automatically enabled when necessary.
owner.SetAutoFlash(owner.mPreviewRequestBuilder);
// Flash is automatically enabled when necessary.
// owner.SetFlash(owner.mPreviewRequestBuilder);
// Finally, we start displaying the camera preview.
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
public void ISFlashOpenOrClose(bool isTorchOn)
{
owner.mCaptureSession = this.session;
if (isTorchOn)
{
owner.mPreviewRequestBuilder.Set(CaptureRequest.FlashMode, (int)ControlAEMode.On);
// owner.mPreviewRequestBuilder.Set(CaptureRequest.FlashMode, (int)FlashMode.Off);
// mPreviewSession.SetRepeatingRequest(mPreviewBuilder.build(), null, null);
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
// isTorchOn = false;
}
else
{
owner.mPreviewRequestBuilder.Set(CaptureRequest.ControlAeMode, (int)ControlAEMode.Off);
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
}
}
}
}
You can change it by ISFlashOpenOrClose method at runtime.
I have been struggling to programatically add a delegate to a user (boss/admin scenario).
After running my test code in the boss sfb client the admin appears as a delegate however, in the admin's sfb client the boss does not appear under the section "people I manage calls for". I verified in the rtc frontend database that the delegation is configured, however the admin subscription record does not list the boss. Below is the code I used to achieve this.
Any ideas why the admin sfb client is not being notified of the new delegation?
Thanks,
Simon
1) add delegate-management
public void SendAddDelegate()
{
string body = string.Format($"<setDelegates xmlns=\"http://schemas.microsoft.com/2007/09/sip/delegate-management\" version=\"1\"><delegate uri=\"sip:admin#example.com\" action=\"add\"/></setDelegates>");
byte[] encBody = Encoding.UTF8.GetBytes(body);
RealTimeAddress rta = new RealTimeAddress("sip:boss#example.com");
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType("application/msrtc-setdelegate+xml")
endpoint.InnerEndpoint.BeginSendMessage(MessageType.Service, rta, contentType, encBody, SendAddDelegateManagementMessageComplete, null);
}
private void SendAddDelegateManagementMessageComplete(IAsyncResult result)
{
try
{
SipResponseData srd = endpoint.InnerEndpoint.EndSendMessage(result);
logger.Debug($"srd.ResponseCode - {srd.ResponseCode}");
}
catch (Exception exc)
{
logger.Error("Exception SendMessageComplete with message - {0}", exc.Message);
}
}
2) Publish presence
public void PublishRoutingCategory(string delegateUri)
{
//routes not created here for sample brevity
routes.DelegateRingEnabled = true;
routes.Delegates.Add(delegateUri);
routes.SimultaneousRingEnabled = true;
routes.SimultaneousRing.Add(delegateUri);
routes.SkipPrimaryEnabled = true;
routes.ForwardAudioAppInvitesEnabled = true;
try
{
userEndpoint.LocalOwnerPresence.BeginPublishPresence(new PresenceCategory[] { routes }, PublishComplete, null);
}
catch (Exception exc)
{
logger.Error("Unknown error - {0}", exc.Message);
}
}
private void PublishComplete(IAsyncResult result)
{
try
{
endpoint.LocalOwnerPresence.EndPublishPresence(result);
}
catch (Exception exc)
{
logger.Error("Error Publish Complete- {0}", exc.Message);
}
}
I have a search text-box in my app. In my database there are two column named English and Bangla. I can search either Bangla or English. there is a button beside search text-box.By default English search is activated. I can change the search option by clicking the button. It works correctly but problem is that the search is very slow.
search option selection code by clicking button is:
private void button5_Click(object sender, RoutedEventArgs e)
{
if (SearchMood % 2 != 0)
{
//search bangla column from the database
button5.Content = "Eng";
}
else {
//search english column from the database
button5.Content = "Bng";
}
SearchMood++;
}
Code for searching is:
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
List<dataLists> mylist = new List<dataLists>();
string word = textBox1.Text;
try
{
if (SearchMood % 2 == 0)// for english search
{
// show 5 words in listbox matched with entered text
var contacts = (from m in db.Dics where m.English.StartsWith(word) select new { m.English, m.Bangla }).Take(5);
string s1, s2;
try
{
foreach (var a in contacts)
{
s1 = a.English;
s2 = a.Bangla;
mylist.Add(new dataLists() { Eng = s1, Bng = s2 });
}
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
listBox1.ItemsSource = mylist;
}
else // for bangla search
{
// show 5 words in listbox matched with entered text
var contacts = (from m in db.Dics where m.Bangla.StartsWith(word) select new { m.English, m.Bangla }).Take(5);
string s1, s2;
try
{
foreach (var a in contacts)
{
s1 = a.English;
s2 = a.Bangla;
mylist.Add(new dataLists() { Eng = s1, Bng = s2 });
}
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
listBox1.ItemsSource = mylist;
}
}
catch { }
}
How can I increase the performance of searching??? Can anyone give any solution|???
N:B: My table creation script looks like
public System.Data.Linq.Table<Dic> Dics
{
get
{
return this.GetTable<Dic>();
}
}
public System.Data.Linq.Table<Learn_table> Learn_tables
{
get
{
return this.GetTable<Learn_table>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dic")]
public partial class Dic : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Serial;
private string _English;
private string _Bangla;
private System.Nullable<int> _Fav;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnSerialChanging(int value);
partial void OnSerialChanged();
partial void OnEnglishChanging(string value);
partial void OnEnglishChanged();
partial void OnBanglaChanging(string value);
partial void OnBanglaChanged();
partial void OnFavChanging(System.Nullable<int> value);
partial void OnFavChanged();
#endregion
public Dic()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="serial", Storage="_Serial", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int Serial
{
get
{
return this._Serial;
}
set
{
if ((this._Serial != value))
{
this.OnSerialChanging(value);
this.SendPropertyChanging();
this._Serial = value;
this.SendPropertyChanged("Serial");
this.OnSerialChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="english", Storage="_English", DbType="NVarChar(2000)")]
public string English
{
get
{
return this._English;
}
set
{
if ((this._English != value))
{
this.OnEnglishChanging(value);
this.SendPropertyChanging();
this._English = value;
this.SendPropertyChanged("English");
this.OnEnglishChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="bangla", Storage="_Bangla", DbType="NVarChar(2000)")]
public string Bangla
{
get
{
return this._Bangla;
}
set
{
if ((this._Bangla != value))
{
this.OnBanglaChanging(value);
this.SendPropertyChanging();
this._Bangla = value;
this.SendPropertyChanged("Bangla");
this.OnBanglaChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="fav", Storage="_Fav", DbType="Int")]
public System.Nullable<int> Fav
{
get
{
return this._Fav;
}
set
{
if ((this._Fav != value))
{
this.OnFavChanging(value);
this.SendPropertyChanging();
this._Fav = value;
this.SendPropertyChanged("Fav");
this.OnFavChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Your problem appears in using TextChanged event Handler. Place a breakpoint there and you will see it firing twice and hence causing the slow performance for you. It seems a bug in WP7 TextBox control.
Use KeyUp event handler, instead of textBox1_TextChanged
void textBox1_KeyUp(object sender, KeyEventArgs e)
{
//your code
}
Hope this solves your problem. !!
You can use of AutoCompleteBox rather than use of TextBox. AutoCompleteBox available in Microsoft.Phone.Control.Toolkit.
Execute you select query at once when you select language on buttonClick and assign result of your query to AutoCompleteBox.Itemsource. It should really increase search performance.
<toolkit:AutoCompleteBox x:Name="AutoBoxFood" Width="440" SelectionChanged="txtFodd_SelectionChanged" FilterMode="StartsWith" HorizontalAlignment="Left" Height="70"/>
Add indexes to the columns in the database file.