How to merge Arduino code with flutter bluetooth? [closed] - flutter
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 14 days ago.
This post was edited and submitted for review 12 days ago and failed to reopen the post:
Needs more focus Update the question so it focuses on one problem only by editing this post.
Improve this question
This is the Slider code: (without bluetooth)
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_sliders/sliders.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:intl/intl.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double height = 70;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("LED control"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Brightness: ${height}", style: TextStyle(fontSize: 30),),
ElevatedButton(
onPressed: (){
showModalBottomSheet(context: context,
builder: (BuildContext context){
return Container(
height: 200,
child: Center(child:
StatefulBuilder(
builder: (context,state){
return Center(
child: SfSlider(
value: height.toDouble(),
max: 100,
min: 50,
showTicks: true,
showLabels: true,
enableTooltip: true,
onChanged: (value) {
state(() {
height = value.round() as double;
});
setState(() {
});
},
),
);
},
),
),
);
}
);
},
child: Text(" Select Value "),
),
],
),
),
);
}
}
This is the ESP 32 Arduino code:
# # ```
Library for Bluetooth Related Functionalities
# # #include "BluetoothSerial.h"
# # //Intialise the Bluetooth
BluetoothSerial ESP_BT;
Stored Variable
String incoming_value;
int onoff=0;
float brightness=0.5;
int colour=127;
int autowc=1;
float g=2.0; //gamma correction
GPIO for LED (Warm- RX2(PIN 16) , Cool-TX2 (Pin17))
int LED1=16;
int LED2=17;
Setting PWM Properties
const int freq = 100000;
const int ledChannel1 = 0;
const int ledChannel2 = 1;
Duty Cycle
const int resolution = 9;
Gamma Correction
const uint8_t PROGMEM gamma8[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,
2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5,
5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10,
10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14,
15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20,
21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27,
28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36,
37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 50, 51, 52, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 72, 73,
74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89,
90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105,
107, 109, 110, 112, 114, 115, 117, 119, 120, 122,
124, 126, 127, 129, 131, 133, 135, 137, 138, 140,
142, 144, 146, 148, 150, 152, 154, 156, 158, 160,
162, 164, 167, 169, 171, 173, 175, 177, 180, 182,
184, 186, 189, 191, 193, 196, 198, 200, 203, 205,
208, 210, 213, 215, 218, 220, 223, 225, 228, 231,
233, 236, 239, 241, 244, 247, 249, 252, 255
# # };
void setup() {
Serial.begin(9600); // Initialise Bluetooth Interface
ESP_BT.begin("ESP32_LED_Control"); // name of bluetooth
Serial.println("Pair your Device"); // Serial Monitor prints this once upload
ledcSetup(ledChannel1, freq, resolution); // Configure and set up LED PWM functions for channel 1
ledcSetup(ledChannel2, freq, resolution); // Configure and set up LED PWM functions for channel 2
ledcAttachPin(LED1, ledChannel1); // LED1 for singal output, Channel 1 will genertate the signal
ledcAttachPin(LED2, ledChannel2); // LED2 for singal output, Channel 2 will genertate the signal
# # }
void loop(){
if (Serial.available()) { // For testing purposes
String input= Serial.readString(); // Key in and read (0-100)
colour= input.toFloat() / 100.0 * 255.0; // Convert to 0-255
Serial.print("Colour inout:"); // print the conversion
Serial.println(input);
# # }
if (ESP_BT.available()) // Check if we receive anything from Bluetooth, adn proceed to next line.
# # {
incoming_value = ESP_BT.readString(); // Read what we received from the phone application
Serial.println(incoming_value); // print what we received from phone application
ON (LED: 1) & OFF (LED:0)
if (incoming_value.indexOf("LED:") >=0)
# # {
incoming_value = incoming_value.substring(incoming_value.lastIndexOf(':') + 1); // Take the string after semicolon (LED)
onoff= incoming_value.toInt(); // Convert the string into Integer
Serial.print("Received:"); // Print the LED value
Serial.println(onoff);
# # }
# # //Brightness (Brightness: x)
else if (incoming_value.indexOf("Brightness:") >=0)
# # {
incoming_value = incoming_value.substring(incoming_value.indexOf(':') + 1); // Take the string after semicolon(Brightness)
brightness = incoming_value.toFloat() / 100.0; // Convert the string into float and divide by 100
brightness= pow(brightness, g);
Serial.print("Received:");
Serial.println(brightness);
# # }
Colour Temperature (colour:x) 0-255
else if (incoming_value.indexOf("Colour Temperature:") >=0)
# # {
incoming_value= incoming_value.substring(incoming_value.indexOf(':') + 1); // Take the string after the semicolon (Colour temperature)
colour= incoming_value.toInt();
Serial.print("Received");
Serial.println(colour);
# # }
# # //Auto-warm 3000K / Auto-Cool 5700k
else if (incoming_value.indexOf("Auto:") >=0 )
# # {
incoming_value = incoming_value.substring(incoming_value.indexOf(':') + 1); // Take the string after semicolon (Auto-Warm / Auto-Cool)
autowc = incoming_value.toInt();
Serial.print("Received:");
Serial.println(autowc);
# # }
# # }
ON
if (onoff ==1 ){
float cool_val= 0;
float warm_val= 0;
ON > Colour temperature 3000K > Get user brightness > Warm Light On > Cool Light Off
if (autowc == 3000){
warm_val = brightness * 255.0;
cool_val = 0;
# # }
ON > Colour Temperature 5700K> Get user brightness > Cool Light On > Warm Light Off
else if (autowc == 5700) {
warm_val = 0;
cool_val = brightness *255.0;
# # }
ON > Customisation > User Input
else if (autowc ==1) {
warm_val = byte(brightness * (255.0 - float(colour)));
cool_val = byte(brightness * float(colour));
# # }
warm_val *= 2.0;
cool_val *= 2.0;
Serial.printf("warm val:%f cool val: %f\n", warm_val, cool_val);
ledcWrite(ledChannel1, int(warm_val));
ledcWrite(ledChannel2, int(cool_val));
# # }
# # //OFF
if (onoff == 0){
ledcWrite(ledChannel1, 0); // Warm Light Off
ledcWrite(ledChannel2, 0); // Cool Light Off
# # }
delay(1); // Short Delay
# # }
# # ```
# # ```
Right now I need some opinions on how to get the create the app using Flutter to work with the Arduino code as well as on the app interface to have a slider control which is able to use bluetooth to communicate with the esp32 to control the hardware which is the LED.
Related
AES/CBC/PKCS5 Padding Encryption using pointycastle package flutter
0 I am trying to encrypt some text with AES/CBC/PKCS5 Padding Encryption using pointycastle package in dart and then decrypt it in java. I have the code for decryption in dart and I'm trying to develop encryption code with the help of the same. Right now I'm stuck in the middle of it. This is the dart code for encryption: import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:pointycastle/block/aes.dart'; import 'package:pointycastle/block/aes_fast.dart'; import 'package:pointycastle/block/modes/cbc.dart'; import 'package:pointycastle/digests/sha1.dart'; import 'package:pointycastle/key_derivators/pbkdf2.dart'; import 'package:pointycastle/macs/hmac.dart'; import 'package:pointycastle/padded_block_cipher/padded_block_cipher_impl.dart'; import 'package:pointycastle/paddings/pkcs7.dart'; import 'package:pointycastle/pointycastle.dart'; class IOTEncodingDecoding { String salt = "FA9A4D0F-5523-4EEF-B226-9A3E8F14FEF8"; String passphrase = "733D3A17-D8A0-454B-AD22-88608FD0C46A"; void encrypt() { String plainText = 'C123492349C1CT20230206130645'; Uint8List? key; Uint8List? iv; var saltBytes = encodeUtf16LE(); var keyIv = generateKey(passphrase, saltBytes); key = keyIv.sublist(0, 32); iv = keyIv.sublist(32, 32 + 16); final CBCBlockCipher cbcCipher = new CBCBlockCipher(new AESEngine()); final ParametersWithIV<KeyParameter> ivParams = new ParametersWithIV<KeyParameter>(new KeyParameter(key), iv); final PaddedBlockCipherParameters<ParametersWithIV<KeyParameter>, Null> paddingParams = new PaddedBlockCipherParameters<ParametersWithIV<KeyParameter>, Null>( ivParams, null); final PaddedBlockCipherImpl paddedCipher = new PaddedBlockCipherImpl(new PKCS7Padding(), cbcCipher); var encodedData = utf8.encode( 'C123492349C1CT20230206130645'); // encoded data= [67, 49, 50, 51, 52, 57, 50, 51, 52, 57, 67, 49, 67, 84, 50, 48, 50, 51, 48, 50, 48, 54, 49, 51, 48, 54, 52, 53] var encryptedByte = paddedCipher.init(true, paddingParams); var encrypted = base64.encode(encryptedByte); print("encodedData => $encodedData"); } Uint8List encodeUtf16LE() { var byteData = ByteData(salt.codeUnits.length * 2); for (var i = 0; i < salt.codeUnits.length; i += 1) { byteData.setUint16(i * 2, salt.codeUnits[i], Endian.little); } return byteData.buffer.asUint8List(); } Uint8List generateKey(String passphrase, Uint8List saltBytes) { final derivator = PBKDF2KeyDerivator(HMac(SHA1Digest(), 64)) ..init(Pbkdf2Parameters(saltBytes, 1000, 32 + 16)); return derivator.process(utf8.encode(passphrase) as Uint8List); } } This is the output of encryption: I/flutter (10774): encodedData => [67, 49, 50, 51, 52, 57, 50, 51, 52, 57, 67, 49, 67, 84, 50, 48, 50, 51, 48, 50, 48, 54, 49, 51, 48, 54, 52, 53] I've got only the encoded data and I'm stuck here. This is the code I got for decryption and it is working fine. Uint8List? decrypt(String ciphertext) { var ciphertext = "8tyHRaQCsxmmGW2xPBFYx/PALmvHkmjx/TzaXC2rIv0="; Uint8List? key; Uint8List? iv; var saltBytes = encodeUtf16LE(); var keyIv = generateKey(passphrase, saltBytes); key = keyIv.sublist(0, 32); iv = keyIv.sublist(32, 32 + 16); var encrypted = base64.decode(ciphertext); PaddedBlockCipherImpl paddingCipher = PaddedBlockCipherImpl(PKCS7Padding(), CBCBlockCipher(AESEngine())) ..init( false, PaddedBlockCipherParameters( ParametersWithIV(KeyParameter(key), iv), null)); var decryptedBytes = paddingCipher.process(encrypted); var decrypted = utf8.decode(decryptedBytes); var val = paddingCipher.process(encrypted); debugPrint('decryptedBytes => $decryptedBytes'); debugPrint('res => $decrypted'); return val; } This is the output of decryption. I/flutter (10774): decryptedBytes => [67, 49, 50, 51, 52, 57, 50, 51, 52, 57, 67, 49, 67, 84, 50, 48, 50, 51, 48, 50, 48, 54, 49, 51, 48, 54, 52, 53] I/flutter (10774): res => C123492349C1CT20230206130645
Map with list as value indexing
I have a Map that contains a List and I want to get a specific value. Here is the map. Map res ={65535: [198, 28, 231, 228, 87, 210, 255, 0, 57, 30, 14]} ; I want to get to the value 57, any help ?
You can follow the snippet where element will find from values and provide key and element index. Map<int, List<int>> res = { 65535: [198, 28, 231, 228, 87, 210, 255, 0, 57, 30, 14] }; // while everything is int here final int findElement = 57; int? keyOf57; int? indexOf57; res.forEach((key, value) { if (value.contains(findElement)) { keyOf57 = key; indexOf57 = value.indexOf(findElement); return; } }); /// also check if `indexOf57` is null or not print("key:$keyOf57 index:$indexOf57 value ${res[keyOf57]?[indexOf57??0]}");
Flutter, how to using square brackets to access dynamic key of list
When I use https://dartpad.dev/?id import 'package:intl/intl.dart'; void main() { final matches = [ { "match_id": 6604501658, "player_slot": 129, "radiant_win": false, "duration": 2020, "game_mode": 22, "lobby_type": 7, "hero_id": 19, "start_time": 1654520510, "version": 21, "kills": 13, "deaths": 7, "assists": 17, "skill": null, "xp_per_min": 780, "gold_per_min": 604, "hero_damage": 36271, "tower_damage": 10042, "hero_healing": 0, "last_hits": 211, "lane": 2, "lane_role": 2, "is_roaming": false, "cluster": 156, "leaver_status": 0, "party_size": 1 }, { "match_id": 6604451816, "player_slot": 4, "radiant_win": false, "duration": 1242, "game_mode": 22, "lobby_type": 7, "hero_id": 52, "start_time": 1654518740, "version": 21, "kills": 7, "deaths": 4, "assists": 1, "skill": null, "xp_per_min": 540, "gold_per_min": 472, "hero_damage": 14678, "tower_damage": 2111, "hero_healing": 0, "last_hits": 136, "lane": 2, "lane_role": 2, "is_roaming": false, "cluster": 156, "leaver_status": 0, "party_size": 1 } ]; final List<String> extraList = ['kills','deaths','assists','gold_per_min','xp_per_min','last_hits','hero_damage','hero_healing','tower_damage','duration']; for(var i in extraList) { print(averMax(matches, i)); } } String averMax(dynamic matches, String field) { final dynamic matchesMap = matches.map((match) => match[field]); final dynamic matchesReduce = matchesMap.reduce((cur, total) => cur + total); return field != 'duration' ? greaterNum((matchesReduce / 20).round(), 1000, 'K') : (matchesReduce / 20).toString(); } String greaterNum(double num, int gN, String unit) { var minus = ''; if (num < 0) { minus = '-'; } num = (num).abs(); if (num > gN) { final newNum = (num / gN).toStringAsFixed(1); return '$minus$newNum$unit'; } else { return '$minus$num'; } } Works However at flutter: Flutter the PlayerMatches is from API which is List I want to map the extraList value as key in the matches to dynamic get data and pass to a List View In dartPad works, however in flutter cant access data use square brackets. My question: Could I access the Object key dynamically like javascript? Thanks for #lepsch who help me At flutter, return match.toJson()[field];
Flutter doesn't support reflection/mirrors so it's not possible to get a property by name. This is on purpose so Flutter knows at compile time all kinds of access to an object that exists and can optimize it accordingly by tree-shaking (Strip out anything that isn’t used). One solution could be converting PlayerRecentMatch to JSON as a Map<String, dynamic>. This way you can access the Map with the brackets operator. Another way though to implement your function is using a first-class function as an argument to get the property instead of the property name. Take a look below: class PlayerRecentMatch { final double score; const PlayerRecentMatch({required this.score}); } double averMax( List<PlayerRecentMatch> matches, double Function(PlayerRecentMatch) getProperty, // <- Here ) { final matchesMap = matches.map((match) { return getProperty(match); }).toList(); final matchesReduce = matchesMap.reduce((sum, total) => sum + total); return matchesReduce / matches.length; } void main() { final matches = [ PlayerRecentMatch(score: 1), PlayerRecentMatch(score: 2), PlayerRecentMatch(score: 3), PlayerRecentMatch(score: 4), ]; print('averMax = ${averMax(matches, (match) => match.score)}'); } https://dartpad.dev/?id=44cbecffd6f86f1714a4553101a16001
Flutter Custom Colors Tree
New to Flutter and am trying to incorporate a tree that I have used for colors on a website as usable colors within Flutter. I have managed so far to create custom colors but only by declaring them individually. class AppColors { final boo = const Color.fromRGBO(0, 32, 255, 1); const AppColors(); } class AppTheme { static const colors = AppColors(); } This I use in app via AppTheme.colors.boo What I want to be able to do is use my entire color scheme as a tree whereby I can grab whatever color I want from the scheme. Here is a basic repository in JSON (I'm not looking to convert from json merely understand how to do this in Flutter (very new, but understand JS well)). { "background": { "solid": { "light": "255, 255 ,255, 1", "dark": "0, 0 ,0, 1" }, "light": { "primary": "255, 255, 255, 0.84", "secondary": "240, 240, 248, 0.84", "tertiary": "224, 224, 232, 0.84" }, "dark": { "primary": "0, 0, 0, 0.84", "secondary": "32, 32, 40, 0.84", "tertiary": "64, 64, 72, 0.84" } }, ... Then to be able to use them in my app as AppTheme.colors.background.solid for example. I appreciate these are rather fundamental issues I am having but this is my way of learning. One way I have found is this: class AppColors { final backgroundSolid = const Color.fromRGBO(255, 255, 255, 1); final backgroundPrimary = const Color.fromRGBO(255, 255, 255, 0.84); final backgroundSecondary = const Color.fromRGBO(240, 240, 248, 0.84); final backgroundTertiary = const Color.fromRGBO(224, 224, 232, 0.84); const AppColors(); } class AppTheme { static const colors = AppColors(); } Is this a reasonable approach?
What Should I Do If a HUAWEI Quick App Freezes When the canvas Component Draws an Image Using setInterval?
In my huawei quick app, the setInterval function is used to cyclically execute the code for using canvas. However, the quick app freezes when rendering an image on a Huawei phone. The code where the exception occurs is as follows: click0() { this.speed = 0.3 let ctx = this.$element('canvas').getContext('2d') setInterval(() => { this.num0 += 2 this.noise = Math.min(0.5, 1) * this.MAX this._draw(ctx) this.MAX <= 200 && (this.MAX += 4) }, 20) }, _draw(ctx) { this.phase = (this.phase + this.speed) % (Math.PI * 64) ctx.clearRect(0, 0, this.width, this.height) this._drawLine(ctx, -2, 'rgba(0, 194, 255, 0.2)') this._drawLine(ctx, -6, 'rgba(0, 194, 255, 0.4)') this._drawLine(ctx, 4, 'rgba(0, 194, 255, 0.6)') this._drawLine(ctx, 2, 'rgba(0, 194, 255, 0.8)') this._drawLine(ctx, 1, 'rgba(0, 194, 255, 1)', 4) },
You can first obtain the service provider by calling the API for querying device information to determine whether the quick app is supported by Huawei Quick App Loader. If so, set the time interval to longer than 100 ms. The sample code is as follows: onShow: function () { var that = this device.getInfo({ success: function (ret) { console.log("handling success:", JSON.stringify(ret)); that.engineProvider = ret.engineProvider; }, fail: function (erromsg, errocode) { console.log("message:", erromsg, errocode); } }) }, click0() { var that = this this.speed = 0.3 console.log(that.engineProvider) let ctx = this.$element('canvas').getContext('2d') if (that.engineProvider === "huawei") { setInterval(() => { this.num0 += 2 this.noise = Math.min(0.5, 1) * this.MAX this._draw(ctx) this.MAX <= 200 && (this.MAX += 4) }, 120) } else { setInterval(() => { this.num0 += 2 this.noise = Math.min(0.5, 1) * this.MAX this._draw(ctx) this.MAX <= 200 && (this.MAX += 4) }, 20) } }, _draw(ctx) { this.phase = (this.phase + this.speed) % (Math.PI * 64) ctx.clearRect(0, 0, this.width, this.height) this._drawLine(ctx, -2, 'rgba(0, 194, 255, 0.2)') this._drawLine(ctx, -6, 'rgba(0, 194, 255, 0.4)') this._drawLine(ctx, 4, 'rgba(0, 194, 255, 0.6)') this._drawLine(ctx, 2, 'rgba(0, 194, 255, 0.8)') this._drawLine(ctx, 1, 'rgba(0, 194, 255, 1)', 4) }, _drawLine(ctx, attenuation, color, width) { ctx.save() ctx.moveTo(0, 0); ctx.beginPath(); ctx.strokeStyle = color; ctx.lineWidth = width || 1; var x, y; for (var i = -this.K; i <= this.K; i += 0.01) { x = this.width * ((i + this.K) / (this.K * 2)) y = this.height / 2 + this.noise * this._globalAttenuationFn(i) * (1 / attenuation) * Math.sin(this.F * i - this.phase) ctx.lineTo(x, y) } ctx.stroke() ctx.restore() }, For Details,pls kindly refer: Introduction to the canvas API Quick app materials