Problem reading data back from Bluetooth on Flutter flutter_blue_plus - flutter

I am trying to read data back from a custom-built bluetooth board that simply sends back a string of data like this:
printf("Read 0x%2.2X%2.2X%2.2X%2.2X\n\r", d1, d2, d3, d4);
And the value I expect to get back is "Read 0xF2000080\n\r"
But what I get in the following flutter code is "RöØd 0xF2000080"
and sometimes different characters are the wrong ones in that string... the code that runs the printf sends back what is stored in memory for many different memory locations
uartTx.onValueChangedStream.listen((event1) {
processIncomingData(event1);
String stringVal = String.fromCharCodes(event1);
LLog.lLog(_tag, "build: uartTx event 1: String value ${stringVal}");
String stringVal2 = "";
event1.forEach((element) {
stringVal2 += element.toRadixString(16);
});
LLog.lLog(_tag, "build: uartTx event 1: String 2 value ${stringVal2}");
String hexVal = hex.encode(event1);
LLog.lLog(_tag, "build: uartTx event 1: Hex value ${hexVal}");
});
void processIncomingData(List<int> newBytes) {
// convert the List<int> to a list of <byte> sized objects
Uint8List convBytes = Uint8List.fromList(newBytes);
// convert the List<int> into a string:
String stringVal = String.fromCharCodes(newBytes);
// which looks a lot like this:
// [9X0CAF01460E4103][AP0200][BL0200][CL0210][DV0A312E302E30]
// [ and ] apparently are delimiters/terminations between commands
LLog.lLog(_tag, 'processIncomingData: Uint8List of bytes received are = $convBytes and the string conversion of that is $stringVal');
I tried to listen for incoming data on a bluetooth connection:
uartTx.onValueChangedStream.listen((event1) {
processIncomingData(event1);
I get bad characters in the List received:
processIncomingData(event1);
void processIncomingData(List<int> newBytes) {
// convert the List<int> to a list of <byte> sized objects
Uint8List convBytes = Uint8List.fromList(newBytes);
which looks like this:
"RöØd 0xF2000080"
I expect just a regular set of ascii characters instead:
"Read 0xF2000080\n\r"

Related

Dart find string value in a list using contains

I have a list of numbers like below -
List contacts = [14169877890, 17781231234, 14161231234];
Now I want to find if one of the above list element would contain the below string value -
String value = '4169877890';
I have used list.any to do the search, but the below print statement inside the if condition is not printing anything.
if (contacts.any((e) => e.contains(value))) {
print(contacts[0]);
}
I am expecting it to print out the first element of the contacts list as it partially contains the string value.
What is it I am doing wrong here?
contacts isn't a List<String>, so your any search can't be true, you need turn element of contracts to string to able to use contains.
void main() {
var contacts = [14169877890, 17781231234, 14161231234];
print(contacts.runtimeType);
var value = '4169877890';
print(value.runtimeType);
var haveAnyValid = contacts.any((element) {
return "$element".contains(value);
});
print(haveAnyValid);
// result
// JSArray<int>
// String
// true
}
Not sure if contacts is an integer and value is a string on purpose or mistake, but this works in dart pad if you convert it to string:
if (contacts.any((e) => e.toString().contains(value))) {
print(contacts[0]);
}
DartPad Link.

How to Extract Strings from Text

Lets Say this is My Text. Now I want to Extract All 4 Variable Separately from the text
"ScanCode=? scanMsg= ? ItemName=? ID= ?\n"
Please Help i need this is Dart, Flutter
The solution I developed first splits the data according to the space character. It then uses the GetValue() method to sequentially read the data from each piece. The next step will be to use the data by transforming it accordingly.
This example prints the following output to the console:
[ScanCode=1234, ScanMessage=Test, Itemname=First, ID=1]
[1234, Test, First, 1]
The solution I developed is available below:
void main()
{
String text = "ScanCode=1234 ScanMessage=Test ItemName=First ID=1";
List<String> original = text.split(' ');
List<String> result = [];
GetValue(original, result);
print(original);
print(result);
}
void GetValue(List<String> original, List<String> result)
{
for(int i = 0 ; i < original.length ; ++i)
{
result.insert(i, original[i].split('=')[1]);
}
}

Flutter : How to Map values dynmically into list and iterate to its length and how can i do Update and Delete after maping values

I am trying to build json expected output as below through dart programing for my application, I have mapped data to list successfully. But when I trying to delete / add the list, the elements in the list are not getting updated accordingly instead they are hgetting reapeted same data.
Here is my code implimentation
in this set state i am getting required values like Phone, name, email e.t.c
for (int i = 0; i <= selectedContacts.length - 1; i++) {
SimplifiedContact? contact = selectedContacts.elementAt(i);
CreateContestModel(//<-- from here i am getting required values.
contact.phone,
contact.name,
contact.email,
);
}
in below code i am, mapping data and building json
class CreateContestModel {
static List models = [];
String phone = '';
String name = '';
String email;
CreateContestModel(this.phone, this.name, this.email) {
var invitemap = {
'name': name,
'phone': phone,
'email': email,
};
models.add(invitemap);
print(models);
}
}
Output
{
"invitations":[
{
"name":"Acevedo Castro",
"phone":982-475-2009,
"email":"floresjoyner#digifad.com"
},
{
"name":"Acevedo Castro",
"phone":982-475-2009,
"email":"floresjoyner#digifad.com"
},
{
"name":"Abby Webster",
"phone":888-561-2141,
"email":"howardnoel#perkle.com"
},
{
"name":"Abby Webster",
"phone":888-561-2141,
"email":"howardnoel#perkle.com"
},
{
"name":"Abby Webster",
"phone":888-561-2141,
"email":"howardnoel#perkle.com"
}
]
}
As you see above items are not getting updated, but they are getting added more.
Expected Output
{
"invitations":[
{
"name":"Acevedo Castro",
"phone":"982-475-2009",
"email":"floresjoyner#digifad.com"
},
{
"name":"Abby Webster",
"phone":"888-561-2141",
"email":"howardnoel#perkle.com"
}
]
}
That is some seriously flawed program flow. Your object creation as a side effect at the same time fills a static list. And it seems you call your object creation every build. So you would insert into your list whenver the user flips it's phone or drags his browser window.
I'm not entirely sure what you want, but you need state management in your application. There are different ways to do it, you can pick the one you like best from the Flutter documentation on state management.
This is a huge flow issue, You should never do data manipulation in build() function as in flutter build function is called multiple times so the manipulation code will also get called multiple times.
So, the proper way to manipulate data is before the data is being used so make sure that the data is only manipulated in initstate(). In Your case you are also doing something which is not required. You are trying to add data to a list via a constructor to a static list so it will always add the data whenever you call it, This is not a proper way.
class CreateContestModel {
late String phone = '';
late String name = '';
late String email;
CreateContestModel.fromMap(Map<String, String> json) {
phone = json['phone'] ?? '';
phone = json['name'] ?? '';
phone = json['email'] ?? '';
}
}
This is how you should create your class. And always create functions for manipulation if possible.
List<CreateContestModel> createContestModelList =
testData['invitations']!.map(
(data) {
return CreateContestModel.fromMap(data);
},
).toList();
Then use this code to construct your list in initstate() and manipulate this having a static variable in your stateful widget. Make Sure you do not construct the data on build() function.
Need More Help?? here's the Gist link
As per my question i find some work around, i.e., by clear up stack on selecting or updtaing existing contacts because as explained below
in this for loop i am itrating same values on each time, when i hit on submit button
for (int i = 0; i <= selectedContacts.length - 1; i++) { //<--- for every time same elements will be itrated
SimplifiedContact? contact = selectedContacts.elementAt(i);
CreateContestModel(//<-- from here i am getting required values.
contact.phone,
contact.name,
contact.email,
);
}
so the list of sets are not updating as per the displayed list as mentioned in question, so i done some work around in below code while selecting / updating contacts, because my model is static list
void onContactBtnPress(BuildContext context) async { CreateContestModel.models.clear(); //<-- clearing up stack
}

Is there any way to make normal int(65) to hex int(0x65) in flutter?

I'm using flutter_blue for ble communication. I need to send list in write characteristic.
eg. Let say input value is 'A'.
I want the result to be 0x41(int).
Instead I got the result 41(int).
When I send to ble device 0x41 then the reader can get the correct result 'A'.I can't find how to put 0x to infront of a int value.
You can do like this
/// Multiple chars
final _codeUnits = 'Abcd'.codeUnits;
_codeUnits.forEach((codeUnit) => print('0x$codeUnit'));
// Output: 0x65, 0x98, 0x99, 0x100
/// If it is single char
final codeUnit = 'A'.codeUnits.elementAt(0);
print('0x$codeUnit');
// Output: 0x65
// Decode
print(String.fromCharCode('A'.codeUnits.elementAt(0)));
// Output: A
I have the same problem;
I want to get an integer like 0x61 (runtimeType == int)
int count = 9999;
/// count.toRadixString(16); ===> 0x270F runtimeType == String
int.parse(count.toRadixString(16)); /// output => 9999

Support for basic datatypes in H5Attributes?

I am trying out the beta hdf5 toolkit of ilnumerics.
Currently I see H5Attributes support only ilnumerics arrays. Is there any plan to extend it for basic datatypes (such as string) as part of the final release?
Does ilnumerics H5 wrappers provide provision for extending any functionality to a particular
datatype?
ILNumerics internally uses the official HDF5 libraries from the HDF Group, of course. H5Attributes in HDF5 correspond to datasets with the limitation of being not capable of partial I/O. Besides that, H5Attributes are plain arrays! Support for basic (scalar) element types is given by assuming the array stored to be scalar.
Strings are a complete different story: strings in general are variable length datatypes. In terms of HDF5 strings are arrays of element type Char. The number of characters in the string determines the length of the array. In order to store a string into a dataset or attribute, you will have to store its individual characters as elements of the array. In ILNumerics, you can convert your string into ILArrray or ILArray (for ASCII data) and store that into the dataset/ attribute.
Please consult the following test case which stores a string as value into an attribute and reads the content back into a string.
Disclaimer: This is part of our internal test suite. You will not be able to compile the example directly, since it depends on the existence of several functions which may are not available. However, you will be able to understand how to store strings into datasets and attributes:
public void StringASCIAttribute() {
string file = "deleteA0001.h5";
string val = "This is a long string to be stored into an attribute.\r\n";
// transfer string into ILArray<Char>
ILArray<Char> A = ILMath.array<Char>(' ', 1, val.Length);
for (int i = 0; i < val.Length; i++) {
A.SetValue(val[i], 0, i);
}
// store the string as attribute of a group
using (var f = new H5File(file)) {
f.Add(new H5Group("grp1") {
Attributes = {
{ "title", A }
}
});
}
// check by reading back
// read back
using (var f = new H5File(file)) {
// must exist in the file
Assert.IsTrue(f.Get<H5Group>("grp1").Attributes.ContainsKey("title"));
// check size
var attr = f.Get<H5Group>("grp1").Attributes["title"];
Assert.IsTrue(attr.Size == ILMath.size(1, val.Length));
// read back
ILArray<Char> titleChar = attr.Get<Char>();
ILArray<byte> titleByte = attr.Get<byte>();
// compare byte values (sum)
int origsum = 0;
foreach (var c in val) origsum += (Byte)c;
Assert.IsTrue(ILMath.sumall(ILMath.toint32(titleByte)) == origsum);
StringBuilder title = new StringBuilder(attr.Size[1]);
for (int i = 0; i < titleChar.Length; i++) {
title.Append(titleChar.GetValue(i));
}
Assert.IsTrue(title.ToString() == val);
}
}
This stores arbitrary strings as 'Char-array' into HDF5 attributes and would work just the same for H5Dataset.
As an alternative solution you may use HDF5DotNet (http://hdf5.net/default.aspx) wrapper to write attributes as strings:
H5.open()
Uri destination = new Uri(#"C:\yourFileLocation\FileName.h5");
//Create an HDF5 file
H5FileId fileId = H5F.create(destination.LocalPath, H5F.CreateMode.ACC_TRUNC);
//Add a group to the file
H5GroupId groupId = H5G.create(fileId, "groupName");
string myString = "String attribute";
byte[] attrData = Encoding.ASCII.GetBytes(myString);
//Create an attribute of type STRING attached to the group
H5AttributeId attrId = H5A.create(groupId, "attributeName", H5T.create(H5T.CreateClass.STRING, attrData.Length),
H5S.create(H5S.H5SClass.SCALAR));
//Write the string into the attribute
H5A.write(attributeId, H5T.create(H5T.CreateClass.STRING, attrData.Length), new H5Array<byte>(attrData));
H5A.close(attributeId);
H5G.close(groupId);
H5F.close(fileId);
H5.close();