Bluetooth Disconnection Takes Too Long - bluetooth-lowenergy

I can connect to my bluetooth device and when I want to disconnect it takes about 30 seconds to disconnect and for a few seconds it disconnects and automatically reconnects to the device in the background I don't want this to happen, how can I disconnect it literally?
I dispose service and device and pull to null but that doesn't work
This is Disconnect method :
public bool DisConnect()
{
try
{
IsScannerActiwe = false;
ButtonPressed = false;
IsConnected = false;
if (currentSelectedGattCharacteristic != null && currentSelectedService != null)
{
currentSelectedGattCharacteristic.Service?.Dispose();
currentSelectedService?.Dispose();
currentSelectedGattCharacteristic = null;
currentSelectedService = null;
if (bluetoothLeDevice != null)
{
bluetoothLeDevice.Dispose();
bluetoothLeDevice = null;
return true;
}
}
}
catch (System.Exception ex)
{
Trace.WriteLine("Exception Handled -> DisConnect: " + ex);
}
return false;
}
I dispose the device and the service and pull it to null and the function returns true but it does not break the connection and it is null for a few seconds and the service continues to run in the background automatically
I also tried another function for disconnection
public async Task<bool> ClearBluetoothLEDevice()
{
if (IsConnected)
{
IsScannerActiwe = false;
ButtonPressed = false;
IsConnected = false;
// Need to clear the CCCD from the remote device so we stop receiving notifications
var result = await currentSelectedGattCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);
if (result != GattCommunicationStatus.Success)
{
return false;
}
else
{
if (currentSelectedGattCharacteristic != null)
{
currentSelectedGattCharacteristic.ValueChanged -= CurrentSelectedGattCharacteristic_ValueChanged;
IsConnected = false;
currentSelectedService.Dispose();
currentSelectedGattCharacteristic.Service.Dispose();
currentSelectedService?.Dispose(); //added code
currentSelectedService = null; //added code
bluetoothLeDevice?.Dispose();
bluetoothLeDevice = null;
currentSelectedGattCharacteristic = null;
return true;
}
}
}
return false;
}
I literally cannot disconnect from the device

Related

Xamarin Forms iOS will not fully connect to Wifi Access Point that has no internet access

I have a Xamarin forms application. The application programmatically connects to a an access to point to communicate via sockets with a host machine connected to that same access point. The access point is not required to have internet access. When testing my code in iOS - I get a socket error stating that the 'Destination is unreachable'. However, if I go to settings and click on the wifi connection I want to use - I am taken to the login page for the access point. If I click cancel I get the option to 'Use without Internet'. If I select that option, then go back to my application, I am able to connect to the host. Is there a way to programmatically tell iOS to use the connecting even though it does not have internet? I looked at the Zone property but that is read only. Here is the code I am using. Any assistance would be appreciated.
public async Task<WifiConfiguredEventArgs> ConnectToWifi()
{
try
{
var tobj_WifiManager = new NEHotspotConfigurationManager();
var tobj_SSIDs = await tobj_WifiManager.GetConfiguredSsidsAsync();
if (tobj_SSIDs != null && tobj_SSIDs.Contains(App.gvm_AppSettings.WifiSSID))
{
// We are already connected -- just return
lobj_WifiConfiguredEventArgs.ConnectionStatus = FlexConnectionStatus.eAlreadyConnected;
}
else
{
var tobj_WifiConfig = new NEHotspotConfiguration(App.gvm_AppSettings.WifiSSID, App.gvm_AppSettings.WifiPassword, false);
tobj_WifiManager.ApplyConfiguration(tobj_WifiConfig, async (error) =>
{
if (error != null)
{
lobj_WifiConfiguredEventArgs.ConnectionStatus = FlexConnectionStatus.eErrorEstablishingConnection;
lobj_WifiConfiguredEventArgs.ErrorMessage = error.ToString();
}
else
{
lobj_WifiConfiguredEventArgs.ConnectionStatus = FlexConnectionStatus.eConnectionEstablished;
}
});
}
}
catch(Exception ex)
{
lobj_WifiConfiguredEventArgs.ConnectionStatus = FlexConnectionStatus.eErrorEstablishingConnection;
lobj_WifiConfiguredEventArgs.ErrorMessage = ex.Message;
lobj_WifiConfiguredEventArgs.ErrorException = ex;
App.ProcessException(ex);
}
return lobj_WifiConfiguredEventArgs;
}
}
Someone asked for the socket code so here it is. To be clear, the socket code connects and communicates fine in iOS when the access point has an internet connection. It also works fine in all the android calls.
using FCISelfCheckIn;
using FCISelfCheckIn.Resources;
using FCISharedAll.FCICommObjects;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using static FCISharedAll.FCIEnums.FlexEnums;
namespace FCISelfCheckIn
{
// This template use base socket syntax to change Pattern. (like Send, Receive, and so on)
// Convert to Task-based Asynchronous Pattern. (TAP)
public static class AsynchronousClientSocket
{
private static bool ib_IsConnected = false;
private static Socket iobj_Client = null;
public static async Task<MasterDataObject> SendMessage(string ps_IPAddress, int pi_Port, ge_CommunicationType pe_CommicationType,
string JSONData)
{
MasterDataObject lobj_response = new MasterDataObject();
try
{
//We should already be connected by the time we get here so just continue
//However if we are not - try to connect again
if (!ib_IsConnected)
{
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(ps_IPAddress);
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, pi_Port);
// Create a TCP/IP socket.
iobj_Client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
ib_IsConnected = await iobj_Client.ConnectAsync(remoteEndPoint).ConfigureAwait(false);
}
if (ib_IsConnected)
{
var bytesSent = await iobj_Client.SendAsync(JSONData).ConfigureAwait(false);
// Receive the response from the remote device.
var ls_MasterDataObject = await iobj_Client.ReceiveAsync(60).ConfigureAwait(false);
if (ls_MasterDataObject == null)
{
lobj_response = new MasterDataObject();
lobj_response.CommunicationType = ge_CommunicationType.e_Error;
}
else
{
//deserialize the master data object in order to return it to the client
lobj_response = App.gvm_CommunicationHelper.DeserializeMasterDataObject(ls_MasterDataObject);
iobj_Client.Shutdown(SocketShutdown.Both);
}
}
else
{
lobj_response.CommunicationType = ge_CommunicationType.e_Error;
lobj_response.JSONDataObject = JsonConvert.SerializeObject(AppResources.ServerConnectionError);
}
// Release the socket.
iobj_Client.Close();
}
catch (Exception ex)
{
App.ProcessException(ex);
}
return lobj_response;
}
private static Task<bool> ConnectAsync(this Socket client, IPEndPoint remoteEndPoint)
{
if (client == null) throw new ArgumentNullException(nameof(client));
if (remoteEndPoint == null) throw new ArgumentNullException(nameof(remoteEndPoint));
return Task.Run(() => Connect(client, remoteEndPoint));
}
private static bool Connect(this Socket client, EndPoint remoteEndPoint)
{
bool lb_ReturnValue = true;
try
{
if (client == null || remoteEndPoint == null)
{
lb_ReturnValue = false;
}
else
{
client.Connect(remoteEndPoint);
}
}
catch (System.Net.Sockets.SocketException Socketex)
{
lb_ReturnValue = false;
if (Socketex.ErrorCode != 10061 && Socketex.ErrorCode != 10065)
{
//Dont log if the host is not running.
App.ProcessException(Socketex);
}
}
catch (Exception ex)
{
App.ProcessException(ex);
lb_ReturnValue = false;
}
return lb_ReturnValue;
}
private static async Task<string> ReceiveAsync(this Socket client, int waitForFirstDelaySeconds = 10)
{
if (client == null) throw new ArgumentNullException(nameof(client));
Debug.WriteLine("Receive Message 1");
// Timeout for wait to receive and prepare data.
for (var i = 0; i < waitForFirstDelaySeconds; i++)
{
if (client.Available > 0)
break;
await Task.Delay(3000).ConfigureAwait(false);
}
// return null If data is not available.
if (client.Available < 1)
return null;
Debug.WriteLine("Receive Message 2");
// Size of receive buffer.
const int bufferSize = 1024;
var buffer = new byte[bufferSize];
// Get data
var response = new StringBuilder(bufferSize);
do
{
var size = Math.Min(bufferSize, client.Available);
await Task.Run(() => client.Receive(buffer)).ConfigureAwait(false);
var ts_CurrentSegment = Encoding.ASCII.GetString(buffer, 0, size);
if (ts_CurrentSegment.Length > 0)
{
response.Append(Encoding.ASCII.GetString(buffer, 0, size));
}
} while (!response.ToString().EndsWith(FCIEndOfFile));
// Return result.
return response.ToString().Replace(FCIEndOfFile, "");
}
private static async Task<int> SendAsync(this Socket client, string data)
{
var byteData = Encoding.ASCII.GetBytes(data);
return await SendAsync(client, byteData, 0, byteData.Length, 0).ConfigureAwait(false);
}
private static Task<int> SendAsync(this Socket client, byte[] buffer, int offset,
int size, SocketFlags socketFlags)
{
if (client == null) throw new ArgumentNullException(nameof(client));
return Task.Run(() => client.Send(buffer, offset, size, socketFlags));
}
public async static Task<bool> ForcePermissions(string ps_IPAddress, int pi_Port)
{
bool lb_ReturnValue = false;
try
{
IPAddress ipAddress = IPAddress.Parse(ps_IPAddress);
//This is only done to force the local network permissions access in iOS 14.
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, pi_Port);
// Create a TCP/IP socket.
iobj_Client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
ib_IsConnected = await iobj_Client.ConnectAsync(remoteEndPoint).ConfigureAwait(false);
if (ib_IsConnected)
{
Debug.WriteLine("GEORGE Permissions Connected");
//client.Shutdown(SocketShutdown.Both);
//client.Close();
lb_ReturnValue = true;
}
else
{
Debug.WriteLine("George Permissions not Connected");
}
}
catch (Exception ex)
{
//Just skip if there is an exception
App.ProcessException(ex);
}
return lb_ReturnValue;
}
}
}

cannot connect to itunes store xamarin forms

enter image description hereHi Thanks in advance i have facing a problem in my xamarin forms ios. Problem is that when i want to purchase product it thrown an exception that cannot to connect to itune store my same code in working fine on xamarin forms android.My code for restore purchases is working fine.
Here is my code for make purchases
private async Task<bool> MakePurchase(string ProductId, string Payload)
{
if (!CrossInAppBilling.IsSupported)
{
return false;
}
var billing = CrossInAppBilling.Current;
try
{
var connected = await billing.ConnectAsync();
if (!connected)//Couldn't connect to billing, could be offline,
alert user
{
DependencyService.Get<IToast>().Show("Something went
wrong or you may not connected with the internet!");
return false;
}
//try to purchase item
var purchase = await billing.PurchaseAsync(ProductId,
ItemType.InAppPurchase, Payload);
if (purchase == null)
{
return false;
}
else
{
//Purchased, save this information
var responseId = purchase.Id;
var responseToken = purchase.PurchaseToken;
var state = purchase.State;
return true;
}
}
catch (InAppBillingPurchaseException ex)
{
if (ex.PurchaseError == PurchaseError.DeveloperError)
{
DependencyService.Get<IToast>().Show("DeveloperError");
ex.Message.ToString();
}
else if (ex.PurchaseError == PurchaseError.AlreadyOwned)
{
DependencyService.Get<IToast>().Show("AlreadyOwned");
return true;
}
else if(ex.PurchaseError == PurchaseError.BillingUnavailable)
{
DependencyService.Get<IToast>
().Show("BillingUnavailable");
return false;
}
else if(ex.PurchaseError == PurchaseError.InvalidProduct)
{
DependencyService.Get<IToast>().Show("InvalidProduct");
return false;
}
else if(ex.PurchaseError == PurchaseError.ItemUnavailable)
{
DependencyService.Get<IToast>().Show("ItemUnavailable");
return false;
}
else if(ex.PurchaseError == PurchaseError.GeneralError)
{
DependencyService.Get<IToast>().Show("General Error");
return false;
}
//Something bad has occurred, alert user
}
finally
{
//Disconnect, it is okay if we never connected
await billing.DisconnectAsync();
}
return false;
}

Push notification not received, windows universal 8.1

HI i have implemented push notification in my application, serer is sending notification but not receiving at my end.
void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
{
string typeString = String.Empty;
string notificationContent = String.Empty;
switch (e.NotificationType)
{
case PushNotificationType.Badge:
typeString = "Badge";
notificationContent = e.BadgeNotification.Content.GetXml();
break;
case PushNotificationType.Tile:
notificationContent = e.TileNotification.Content.GetXml();
typeString = "Tile";
break;
case PushNotificationType.Toast:
notificationContent = e.ToastNotification.Content.GetXml();
typeString = "Toast";
// Setting the cancel property prevents the notification from being delivered. It's especially important to do this for toasts:
// if your application is already on the screen, there's no need to display a toast from push notifications.
e.Cancel = true;
break;
case PushNotificationType.Raw:
notificationContent = e.RawNotification.Content;
typeString = "Raw";
break;
}
// string text = "Received a " + typeString + " notification, containing: " + notificationContent;
var ignored = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// rootPage.NotifyUser(text, NotifyType.StatusMessage);
if (typeString == "Toast")
{
PushNotificationHelper.AddTostNotification(0, notificationContent);
}
else if (typeString == "Badge")
{
PushNotificationHelper.AddBadgeNotification(0, notificationContent);
}
});
}
public async void InitChannel()
{
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
try
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
if (channel != null)
{
//String existingChannel = (String)roamingSettings.Values["ExistingPushChannel"];
roamingSettings.Values["ExistingPushChannel"] = channel.Uri;
dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
channel.PushNotificationReceived += OnPushNotificationReceived;
}
else
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
catch
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
public async void InitNotificationsAsync()
{
try
{
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
String existingChannel = (String)roamingSettings.Values["ExistingPushChannel"];
string tempDevelopmentKey = "";
string Platform = "";
List<string> arrayTags = new List<string>();
#if WINDOWS_APP
Platform = "windows-tablet";
tempDevelopmentKey = "dev_WindowsTabletNotification";
#endif
#if WINDOWS_PHONE_APP
Platform = "windows-phone";
tempDevelopmentKey ="dev_WindowsPhoneNotification";
#endif
arrayTags.Add(Platform) ;
arrayTags.Add(tempDevelopmentKey) ;
string TMBNotification = (string)roamingSettings.Values["TMBNotification"];
if(TMBNotification != null)
{
if(TMBNotification == "on")
{
arrayTags.Add("TMB");
}
}
string TRSNotification = (string)roamingSettings.Values["TRSNotification"];
if (TRSNotification != null)
{
if (TRSNotification == "on")
{
arrayTags.Add("TRS");
}
}
string IMNotification = (string)roamingSettings.Values["IMNotification"];
if (IMNotification != null)
{
if (IMNotification == "on")
{
arrayTags.Add("IM");
}
}
string SWSNotification = (string)roamingSettings.Values["SWSNotification"];
if (SWSNotification != null)
{
if (SWSNotification == "on")
{
arrayTags.Add("ANC");
}
}
string VIDNotification = (string)roamingSettings.Values["VIDNotification"];
if (VIDNotification != null)
{
if (VIDNotification == "on")
{
arrayTags.Add("videos");
}
}
var hub = new NotificationHub("hubname", "endpoint");
var result = await hub.RegisterNativeAsync(existingChannel, arrayTags);
// Displays the registration ID so you know it was successful
if (result.RegistrationId != null)
{
}
}catch
{
}
}
So how can i confirm that there is no issue in my implementation or there is issue from server end.
There are couple of steps you can take to debug this problem:-
There is broadcast and sending notification, using notification hub, option available on azure portal(you can do from VS also from left side server explorer). When you did this there is a log that will show you whether a notifications sent successfully or not.
First just delete all your registrations with notification hub and for very new registration check is your device getting registered with correct tags/channel uri or not(this you cad do from server explorer too)
Make sure you are sending/registering the correct templates that are corresponding to WNS service.
make sure you are using WNS service this different from what is for
WP8 silverlight one.
You can see the errors just at the bottom of this page if any.
There is option for device registrations from where you can alter the registrations.

HTTP upload using WinInet

I'm doing http(PUT) upload using WinInet library, on WinXP its working fine but on Win7 its not working and the strange thing is 'InterWriteFile' function of WinInet files is returning true. Any help will be appreciated.
Thanks in Advance.
//this is the first function that is called when upload is requested.
void Upload()
{
//check if handle is already open or not
if(!m_hNetOpen)
{
//open interconnect: Initializes an application's use of the WinINet functions.
m_hNetOpen = InternetOpen("XYZ",
INTERNET_OPEN_TYPE_DIRECT,
NULL,
NULL,
INTERNET_INVALID_PORT_NUMBER);
//return if handle is NULL
if(m_hNetOpen == NULL)
{
return FALSE;
}
}
//we'll get user specified URL, could be some xyz.com too.
if(!m_hNetConnect)
{
//opens HTTP or FTP connection for a site requested...pchServerName requested
m_hNetConnect = InternetConnect(m_hNetOpen,
strServerName,
INTERNET_DEFAULT_HTTP_PORT,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
INTERNET_FLAG_PASSIVE,
dwContext);
//return if handle is NULL
if(m_hNetConnect == NULL)
{
return FALSE;
}
}
dwContext = 0;
//now, create HTTP request
m_hHttpConnect = HttpOpenRequest(m_hNetConnect,
"PUT",
strObjectName,
NULL,
NULL,
NULL,
INTERNET_FLAG_CACHE_IF_NET_FAIL,
dwContext);
//return if handle is NULL
if(m_hHttpConnect == NULL)
{
return FALSE;
}
//call UseHttpSendReqEx
BOOL bRet = UseHttpSendReqEx(m_hHttpConnect, strUploadFileName);
//if not suuceeded log the message
if(!bRet)
{
//Logmessage
}
if(m_hHttpConnect)
{
//close the handle
InternetCloseHandle(m_hHttpConnect);
}
return bRet;
}
//this function is will send HTTP request and writes data to internetfile
BOOL UseHttpSendReqEx(HINTERNET hConnect, char *upFile)
{
INTERNET_BUFFERS BufferIn = {0};
DWORD dwBytesRead = 0;
DWORD dwBytesWritten = 0;
//buffer
BYTE strBuffer[20480] = {0};
BOOL bRead;
BOOL bRet = TRUE;
//get the size of structure
BufferIn.dwStructSize = sizeof(INTERNET_BUFFERS);
//create file
m_hFile = CreateFile(upFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
//check for invalid handle
if (m_hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}
//get the file size
BufferIn.dwBufferTotal = GetFileSize(m_hFile, NULL);
//send request to HTTP server
if(!HttpSendRequestEx(hConnect, &BufferIn, NULL, HSR_INITIATE, 0))
{
//close the file handle
CloseHandle(m_hFile);
m_hFile = NULL;
return FALSE;
}
DWORD sum = 0;
do
{
//read the file that is to be uploaded
if (!(bRead = ReadFile(m_hFile, strBuffer, sizeof(strBuffer),
&dwBytesRead, NULL)))
{
bRet = FALSE;
break;
}
//write the internet file
bRet=InternetWriteFile(hConnect, strBuffer, dwBytesRead,
&dwBytesWritten);
if(!bRet)
{
DWORD d = GetLastError();
bRet = FALSE;
break;
}
memset(strBuffer, '\0', sizeof(strBuffer));
sum += dwBytesWritten;
}
while(dwBytesRead == sizeof(strBuffer)) ;
//This sleep was introduced as if we immediately after the above loop
//if we try to close the handle then file does not get created on the server
Sleep(100);
BOOL b = CloseHandle(m_hFile);
m_hFile = NULL;
return bRet;
}

SCAN_SDT_UNKNOWN - Motorola OPOS Scanner

I am receiving an odd error with my scanner integration. I am making use of an OPOS scanner in my program. When the program closes I disable, release and close the device, but no other application can use it after my program runs. Also if I restart no application can use it. Not even my application which causes the issue. I did find that if I do not claim the device the issue doesn't happen. I am currently trying to get a fresh copy of the DLL in case the release method is somehow corrupted? Any other ideas?
public bool InitBarcode(bool overrideLGBarcode)
{
Util.LogMessage("Initializing barcode scanner!");
if (_barcodeScanner == null)
{
Util.LogMessage("Barcode scanner was null. instantiating a new one");
_barcodeScanner = new OPOSScanner();
_barcodeScanner.AutoDisable = true;
_barcodeScanner.DataEvent += BarcodeDataEventHandler;
Util.LogMessage("Added event handler");
}
else
{
Util.LogMessage("Barcode scanner was not null");
}
if (_barcodeScanner.Open("STI_USBSCANNER") != 0)
{
Util.LogMessage("Barcode scanner \"STI_USBSCANNER\" could not be opened!");
return false;
}
else
{
Util.LogMessage("STI_USBSCANNER was opened");
}
int result = _barcodeScanner.ClaimDevice(-1);
Util.LogMessage("Claiming barcode scanner returned result: " + result);
_barcodeScanner.DecodeData = true;
_barcodeScanner.DeviceEnabled = true;
_barcodeScanner.DataEventEnabled = true;
return true;
}
public void CloseBarcode()
{
Util.LogMessage("Disabling, Releasing and Closing the barcode scanner!");
_barcodeScanner.DataEvent -= BarcodeDataEventHandler;
Util.LogMessage("Removed event handler");
_barcodeScanner.AutoDisable = false;
_barcodeScanner.DecodeData = false;
_barcodeScanner.DataEventEnabled = false;
_barcodeScanner.DeviceEnabled = false;
if (_barcodeScanner.DeviceEnabled != false)
{
Util.LogMessage("Barcode scanner could not be disabled!");
}
else
{
Util.LogMessage("Barcode scanner was disabled!");
}
int result = _barcodeScanner.ReleaseDevice();
Util.LogMessage("ReleseDevice() yielded result of: " + result);
if (result != 0)
{
Util.LogMessage("Barcode scanner could not be released!");
}
else
{
Util.LogMessage("Barcode scanner was released!");
}
if (_barcodeScanner.Close() != 0)
{
Util.LogMessage("Barcode scanner could not be closed!");
}
else
{
Util.LogMessage("Barcode scanner was closed!");
}
_barcodeScanner = null;
}

Resources