how to send hexadecimal data packets using Bluetooth in flutter - flutter

It's my first time using Dart and Flutter.
I want to send and receive data packets to some device.
I tried a lot of things through google but failed.
Please let me know how I can send it.
Please help me.
void sendData() async {
Uint8List list = new Uint8List(13);
list[0]=0x80;
list[1]=0x80;
list[2]=0xF0;
list[3]=0x7D;
list[4]=0x05;
list[5]=0x00;
list[6]=0x0E;
list[7]=0x01;
list[8]=0x70;
list[9]=0x70;
list[10]=127;
list[11]=0x80;
list[12]=0xF7;
print(list);
await _curPeripheral.discoverAllServicesAndCharacteristics();
_curPeripheral.writeCharacteristic(
"Service Uuid",
"Charactoristic Uuid",
Uint8List.fromList(list), false);
---- debug Console ----
D/com.polidea.flutter_ble_lib.FlutterBleLibPlugin(22538): on native side observed method: discoverAllServicesAndCharacteristics
D/com.polidea.flutter_ble_lib.FlutterBleLibPlugin(22538): on native side observed method: writeCharacteristicForDevice

There are multiple different libraries to choose if you want to send and receive data using Bluetooth Low Energy. For flutter you could use flutter_reactive_ble for example. The description includes usage examples.
Another library for flutter is flutter_blue.

Related

How to add new data into Future<dynamic> in dart / flutter?

I am developing a chat system in mobile application using Flutter / Dart.
I have fetched a user's message records from server by API and received result as Future<dynamic>. This result has list of chat data. If I pass it to FutureBuilder widget. It works and lists chat records in listTile. Everything is working well.
When user adds a new chat message then I post the that text message to server by API to store into database. It works and response status is 200 which means message has been added on server's database.
I have instance of newly added chat message, I want to append / add it to previously fetched Future<dynamic> result.
Kindly suggest me how can I do this? Can we update Future<dynamic> typed data? Thanks.
Future can emit only one item by design. If you want to emit multiple items, use Stream: https://api.flutter.dev/flutter/dart-async/Stream-class.html
To get to know how to generate streams have a look on this: https://dart.dev/articles/libraries/creating-streams
Most likely what you want to do is use rxdart's BehaviorSubject or dart's StreamController (they share api, so just substitute the name, except for ValueStream, which is specific to rxdart, this one will have to be replaced with just Stream):
class Api {
final _subject = BehaviorSubject<DataToDisplay>();
ValueStream<DataToDisplay> get data => _subject.stream;
void fetchData() {
final data = downloadDataFromSomewhere();
_subject.add(data);
}
}
Then just create a StreamBuilder similarly to FutureBuilder.

Unhandled Exception: Bad State: Stream has already been listened to

I have the following code to navigate the user to the Home Screen upon successful authentication
Future navigateToHomeScreen(
StreamedResponse value,
BuildContext context,
) async {
print('Navigating to Home Screen');
String userString = await value.stream.bytesToString();
Map<String, dynamic> logInResponseData = jsonDecode(userString)['data'];
UserManager.persistUser(logInResponseData);
Navigator.of(context).pushReplacementNamed(HomeWidget.routePath);
}
After a successful sign up or sign in the above function is called but I keep getting:
Unhandled Exception: Bad state: Stream has already been listened to.
How do I fix this?
You can't add multiple listeners to a regular stream. In your code, if your navigateToHomeScreen function is getting called multiple times, you are basically adding that many listeners to the stream. You have two ways to fix it.
Check if the stream is already having any listener or not. If it has, remove it before adding a new one.
This is a bit easier one but not the best solution. You can convert your stream to a BroadcastStream by doing : value.stream.asBroadcastStream().bytesToString(); This will convert your regular stream to broadcast stream. By doing this you can add multiple listeners to your stream by why it's not the best option becuase if your previous stream listeners are not killed, they will keep getting notified and will keep consuming your reads. If you are using a service which charge you based on read writes(like cloud firestore) then this might not be a good idea.
https://medium.com/flutter-community/flutter-stream-basics-for-beginners-eda23e44e32f Here is a link to gain better understanding of Streams in Dart and Flutter

Is there a way I can translate my flutter app for free?

I am making a flutter app that fetches data from a database using an API. The client wants me to add multilanguage support, so is there a way with which I can change the language of the whole app. Also the data that is being fetched from database needs to be translated. So it would be better if the data is translated before being displayed.
Thank you.
The best approach would be to get translated data from the backend as it will be a lot faster compared to translating the text at the mobile end.
There is this translator package which you can use to convert the data fetched from the backend.
However, note that your app will become slow when you implement this because you will have to wait for two API calls:
For fetching data from the backend
Uploading this fetched data & then getting translations back
The translator package makes use of Google Translator to translate text into any language that you want.
void main() async {
final translator = GoogleTranslator();
final input = "Здравствуйте. Ты в порядке?";
translator.translate(input, from: 'ru', to: 'en').then(print);
// prints Hello. Are you okay?
var translation = await translator.translate("Dart is very cool!", to: 'pl');
print(translation);
// prints Dart jest bardzo fajny!
print(await "example".translate(to: 'pt'));
// prints exemplo
}
The simple use case example mentioned in the package.

Flutter call http requests from a unit\widget test without mocking

I have an app that follows MVC+service architecture. The service layer makes the http requests for rest APIs. However the response of the http requests change intermittently which cause my models to change or else random crashes in my app. SO to capture the change in these APIs I want to write some automated tests which can tell me exactly what changed. A sample test case is as following:
test("login_valid", () async {
final loginData = LoginData(
email: "abc#gmail.com",
password: "123"
);
final parameters = loginData.toJson();
var json = await httpService.post(parameters);
var loginResponse = LoginResponse.fromJson(json);
expect(loginResponse.status, "OK");
});
However, the above code throws SocketException upon run. I know this exception is thrown when INTERNET permission is not given in AndroidManifest.xml but I don't know how to set this for unit\widget tests.
P.S. I can't mock the service layer using mockit or similar framework because the whole point is to test my service layer which doesn't have any business logic but just provides network integration.
Any solution or suggestion will be really helpful. I am okay with other approaches to achieve the same intent also, if there are any.
Check this or the gihub issue discussion pointed there
https://timm.preetz.name/articles/http-request-flutter-test

Ionic Bluetooth BLE read message all the time

I want read data from sensor by bluetooth all the time. I follow from documentation but I can't set my phone read data from sensor by bluetooth. First i connect mobile with sensor next I add notification by:
this.ble.startNotification(peripheral.id,SERVICE_UUID,
CHARACTERISTIC_UUID).subscribe(
data => {this.onChange(data);}
)
where onChane(data) is :
onChange(buffer :ArrayBuffer){
console.log("onChange method")
var data = new Float32Array(buffer);
console.log(data[0]); }
Next I
this.ble.read(peripheral.id,SERVICE_UUID,CHARACTERISTIC_UUID).then(
(data) => {this.onChange(data);},
(err) => {console.log(err);}
)
I have failed in this.ble.read. CHARACTERISTIC_UUID and SERVICE_UUID are const. What is wrong? How can I correct this that my phone received datas all the time?
If you're using notifications, you don't need to read the characteristic's value. Once you subscribe for notifications, the peripheral will notify you with the new value whenever the value changes. It looks like your onChange function does this.
If your characteristic supports the read property, you can optionally read the value. Look at the peripheral data returned to the connect success callback to see the characteristic properties.
Take a look at my Ionic BLE example code. The thermometer example connects to a peripheral, subscribes for notifications, and reads the value one time so IU can update the UI with the current value. See https://github.com/don/ionic-ble-examples/blob/d0acd2b47ea08011be4d1aa844c4f74426a22273/thermometer/src/pages/detail/detail.ts#L37-L55