Created
April 13, 2022 20:48
-
-
Save ctacke/da47532d99a54a2e8d789f14e22bfb8a to your computer and use it in GitHub Desktop.
Meadow BLE Server Sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Meadow.Gateways.Bluetooth; | |
using Meadow.Logging; | |
using Meadow.Units; | |
using System; | |
namespace Meadow.Samples | |
{ | |
public delegate void ClicksChangedHandler(int newValue); | |
internal class BleService | |
{ | |
private CharacteristicInt32 _clicksCharacteristic; | |
private CharacteristicString _tempCharacteristic; | |
private Logger _logger; | |
public event ClicksChangedHandler ClicksChanged = delegate { }; | |
public void SetTemp(Temperature temp) | |
{ | |
_tempCharacteristic.SetValue($"{temp.Fahrenheit:0.0}F"); | |
} | |
public void SetClicks(int clicks) | |
{ | |
_clicksCharacteristic.SetValue(clicks); | |
} | |
public BleService(Logger logger) | |
{ | |
_logger = logger; | |
Initialize(); | |
} | |
private void Initialize() | |
{ | |
var definition = GetDefinition(); | |
_logger.Info($"Starting BLE Server with {definition.Services[0].Characteristics.Count} characteristics"); | |
var result = MeadowApp.Device.BluetoothAdapter.StartBluetoothServer(definition); | |
if (!result) | |
{ | |
_logger.Error("Failed to start BLE Server"); | |
} | |
} | |
private Definition GetDefinition() | |
{ | |
_tempCharacteristic = new CharacteristicString( | |
"temp", | |
uuid: "017e99d6-8a61-11eb-8dcd-0242ac1300aa", // just a random GUID, no particular meaning | |
CharacteristicPermission.Read, // temp is read-only | |
CharacteristicProperty.Read, | |
maxLength: 10); | |
_clicksCharacteristic = new CharacteristicInt32( | |
"clicks", | |
uuid: "017e99d6-8a61-11eb-8dcd-0242ac1300bb", // just a random GUID, no particular meaning | |
permissions: CharacteristicPermission.Write | CharacteristicPermission.Read, // allow user to reset value | |
properties: CharacteristicProperty.Write | CharacteristicProperty.Read | |
); | |
_clicksCharacteristic.ValueSet += OnClicksCharacteristicValueSet; | |
var service = new Service( | |
"Meadow", | |
253, | |
_tempCharacteristic, | |
_clicksCharacteristic); | |
return new Definition("PROJECT LAB", service); | |
} | |
private void OnClicksCharacteristicValueSet(ICharacteristic c, object data) | |
{ | |
_logger.Info($"BLE Client set Clicks to {data}"); | |
ClicksChanged?.Invoke((int)data); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment