BLED112 set Encryption? - python-3.x

I'm using BLED112 and "pygatt BGAPI backend" Python library to communicate to a custom 3rd party BLE device.
Using the "Bluegiga BLE GUI" I can read/write to the device characteristic but only after clicking the "Encrypt" button next to the device.
What is the python library equivalent to setting / enabling the encryption?
I can't seem to find encryption parameter in either adapter initialization or in the device connection functions
Simplified code:
import pygatt
adapter = pygatt.BGAPIBackend()
adapter.start()
device = adapter.connect("01:23:45:67:89", address_type=pygatt.BLEAddressType.random, timeout=10)
raw_read = device.char_read_handle(32)

The library has a function "bond" which performs the same command as the "Encrypt" button.
import pygatt
adapter = pygatt.BGAPIBackend()
adapter.start()
device = adapter.connect("01:23:45:67:89", address_type=pygatt.BLEAddressType.random, timeout=10)
device.bond()
raw_read = device.char_read_handle(32)

Related

how do i broadcast Bluetooth inquiry with python sockets AF_bluetooth socket?

Well at the moment I try to learn more about Bluetooth, I've realized that to connect I need to send a packet to the device called inquiry packet. However for my script I'm more interested in broadcasting it, and even though pybluez provides the high level functions for it. I want to do it with sockets as part of learning experience. Can anyone please tell me, how to specify I want to send the inquiry packet? through the sockets like so
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
and how do I broadcast it, instead of sending to one adress?
Are you asking to create a Serial Port Profile (SPP) socket server?
Any example of that is below.
I have used the pydbus library to get the Bluetooth adapter address but you could just hardcode the mac address if you preferred:
import socket
import pydbus
bus = pydbus.SystemBus()
adapter = bus.get('org.bluez', '/org/bluez/hci0')
adapter_addr = adapter.Address
port = 3 # Normal port for rfcomm?
buf_size = 1024
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.bind((adapter_addr, port))
s.listen(1)
try:
print('Listening for connection...')
client, address = s.accept()
print(f'Connected to {address}')
while True:
data = client.recv(buf_size)
if data:
print(data)
except Exception as e:
print(f'Something went wrong: {e}')
client.close()
s.close()

Access Linux Root Files from .NetCore app

I have created a .net core app that runs very well on the Raspberry Pi.
I wish to try and connect this device to a wifi router or an access point from an iPhone.
After looking I know you can create a conf file and put it onto the sd card via a card reader.
What I would like to do is allow the user to enter their wifi details via my own interface and for my own c# program to make the chnages.
i have spent sometime but found no examples.
If anyone knows...
The usual approach for GUI based configuration is not to edit the system config files directly, but to talk through the configuration interface provided by the network daemons.
wpa_supplicant can be talked to through the wpa_cli utility. You use it by spawning wpa_cli as a separate process with stdio redirected into a pipe, into which/from you send the configurations commands.
Update: To talk to wpa_cli you'd create a process with redirected output. With Mono you'd do it as following
private void start_wpa_cli()
{
ProcessStartInfo psI = new ProcessStartInfo("wpa_cli");
psI.UseShellExecute = false;
psI.RedirectStandardInput = true;
psI.RedirectStandardOutput = true;
Process p = new Process();
p.StartInfo = psI;
p.Start();
StreamWriter sw = p.StandardInput;
sw.AutoFlush = true;
StreamReader sr = p.StandardOutput;
...
You can then send wpa_cli commands through sw and read the result from sr. The commands for wpa_cli you can find in its manpage.
If NetworkManager is used, you talk to it through its D-Bus interface. Update: To access D-Bus from .Net/Mono you could for example use https://github.com/mono/dbus-sharp

Does WiPy Pysense Device will connect with Other Bluetooth Sensor Devices.?

Does the Pysense(WiPy) device will connect and get service from any other Bluetooth Sensor Devices available in the market.?
Yes we can connect any Bluetooth sensor with mac address using
bluetooth = Bluetooth()
bluetooth.start_scan(5)
while bluetooth.isscanning():
adv = bluetooth.get_adv()
if adv:
if(str(binascii.hexlify(adv.mac).decode()) == '78a50454b267'):
conn = bluetooth.connect(adv.mac)
print(type(conn))

Windows 10 - how to detect when a Bluetooth device is in range

I have previously paired with a Bluetooth device that supports RFCOMM.
When my app is opened I continuously try to connect to the device by opening the RFCOMM. This way my app automatically connects when the device comes in range.
deviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
LogData(String.Format("Number of mldp devices is {0}", deviceInfoCollection.Count));
foreach (DeviceInformation deviceInfo in deviceInfoCollection)
{
LogData(String.Format("ID:{0}, NAME:{1}", deviceInfo.Id, deviceInfo.Name));
}
Then run this on a timer:
try
{
// The first time this method is invoked by a store app, it should be called
// from a UI thread in order to display the consent prompt
// https://msdn.microsoft.com/en-us/windows.devices.bluetooth.rfcomm.rfcommdeviceservice.fromidasync
RfcommDeviceService rfcommService = await RfcommDeviceService.FromIdAsync(deviceInfo.Id);
LogData(String.Format("ID:{0}, NAME:{1}", deviceInfo.Id, deviceInfo.Name));
}
catch (Exception)
{
LogData(String.Format("Can not request rfcomm service from device ID:{0}, NAME:{1}", deviceInfo.Id, deviceInfo.Name));
}
Is there any way to query when the device is in range , rather than trying to connect? I would prefer to only attempt connection when the device is in range.
For RFCOMM (BT2.0, BT2.1) you can run a device enumeration periodically, see also Get bluetooth devices in range
However your actual implementation with a connection attempt may work a little better.
For Bluetooth 4.0, you can listen to the advertisements of the BT module, see also https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BluetoothAdvertisement
If you're talking to an embedded device (e.g. some robot, or homebrew appliances using RFCOMM) I am afraid there is no better solution than what you're doing.
If you're taking to a phone (which supports both BT4.0 and BT2.1) you can use the BT4 advertisements to signal the proximity of the device, then connect via RFCOMM.

Stream Audio to Bluetooth Device in C#

I am trying to stream Audio to a bluetooth device in-code in C#. I've picked up the 32feet.net library to help with this. I am able to get a bluetooth speaker paired just fine, and then I use the code below to connect to the device.
globalClient.BeginConnect(device.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(BluetoothConnectedAsyncHandler), device);
Async Callback method:
private void BluetoothConnectedAsyncHandler(IAsyncResult result)
{
BluetoothDeviceInfo connectedDevice = (BluetoothDeviceInfo)result.AsyncState;
globalClient.EndConnect(result);
if (result.IsCompleted)
{
NetworkStream btStream = globalClient.GetStream();
}
}
This all works well, but when I try to set the service from BluetoothService.SerialPort to BluetoothService.AudioSource, then I receive a SocketException on the "globalClient.EndConnect(result);" line saying "A socket operation failed because the destination host was down". See screenshot:
I've also tried to throw data at the speaker through the NetworkStream when it is setup with BluetoothService.SerialPort, but it doesn't play anything - no noise or static.
My running hypothesis is that this can't be done easily with 32feet.net, and I would have to code up the a2dp spec in code. I think the 32feet.net library is used so that I can tell the Operating System to use the speaker as an output device, rather than control audio output in-code as a supported feature.
Please help! Has anyone done this?
Would it even work if I sent an a2dp compliant stream to the device over the BluetoothService.SerialPort connection?
A2DP spec: https://www.bluetooth.org/docman/handlers/DownloadDoc.ashx?doc_id=8236
Thanks for any help!
Update:
This isn't possible within the 32feet.net library, you can only set the device up to talk the the Microsoft audio service using the setService method call in 32feet.net
www.nudoq.org/#!/Packages/32feet.NET/InTheHand.Net.Personal/MicrosoftSdpService/M/SetService
This MS service manages the A2DP output to the device. There is no way to directly output audio from code into the Bluetooth Device using this library in C#.

Resources