#flutter #arduino #esp8266
#flutter #arduino #esp8266
Вопрос:
Проблема, с которой я сталкиваюсь, заключается в том, что отправка данных с моего телефона на ESP8266 искажена… (Я использую Amica от NodeMCU) Я использую пакет во Flutter, который использует принцип WebSocket. Когда я запускаю приложение, оно подключается нормально. Я получаю сообщения для рукопожатия WebSocket просто отлично, поэтому я завершаю рукопожатие просто отлично. Но когда я отправляю данные из своего приложения Flutter, это, похоже, не работает…
Код, который у меня есть в Flutter:
import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
var ip = 'ws://192.168.1.53:5555';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'WebSocket Demo';
return MaterialApp(
title: title,
home: MyHomePage(
title: title,
channel: IOWebSocketChannel.connect(ip),
),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
final WebSocketChannel channel;
MyHomePage({Key key, @required this.title, @required this.channel})
: super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Form(
child: TextFormField(
controller: _controller,
decoration: InputDecoration(labelText: 'Send a message'),
),
),
StreamBuilder(
stream: widget.channel.stream,
builder: (context, snapshot) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
child: Text(snapshot.hasData ? '${snapshot.data}' : ''),
);
},
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _sendMessage,
tooltip: 'Send message',
child: Icon(Icons.send),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _sendMessage() {
if (_controller.text.isNotEmpty) {
widget.channel.sink.add(_controller.text);
}
}
@override
void dispose() {
widget.channel.sink.close();
super.dispose();
}
}
Я получил этот код из «https://flutter.dev/docs/cookbook/networking/web-sockets «.
Это просто для проверки, сработает ли это, реальное кодирование будет позже…
Я изменил IP, и все.
В Arduino код такой:
String Version = "===================================rn===================================rn===================================rn [NAMEHERE] v1.0rnBugs to fix:rn o N/Arn===================================rn===================================rn===================================rn";
bool keySent = true;
String Key;
char ThrowAway;
String StringSlice;
String HexToBinary;
int HexToNumber;
String EncodedKey = "";
int Count = 0;
#include <ESP8266WiFi.h>
#include <Hash.h>
#include <rBase64.h>
WiFiServer wifiServer(5555);
const char* ssid = "[NAME]";
const char* password = "[PASSWORD]";
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println(Version);
IPAddress ip(192, 168, 1, 53);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
WiFi.config(ip, gateway, subnet);
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting ...");
}
Serial.print("Connected to WiFi. IP: ");
Serial.println(WiFi.localIP());
wifiServer.begin();
}
void loop() {
WiFiClient client = wifiServer.available();
if(client) {
while(client.connected()) {
while(client.available() > 0) {
char c = client.read();
//Reading key if applicable
Serial.write(c);
if(c == 'k') {
c = client.read();
Serial.write(c);
if(c == 'e') {
c = client.read();
Serial.write(c);
if(c == 'y') {
c = client.read();
Serial.write(c);
if(c == ':') {
c = client.read();
Serial.write(c);
c = client.read();
while(c != '=') {
Serial.write(c);
Key = Key c;
c = client.read();
}
while(c == '=') {
Serial.write(c);
Key = Key c;
c = client.read();
}
Serial.print(c);
calculateKey();
keySent = false;
}
}
}
}
}
if(keySent == false) {
Serial.println("SENT:");
Serial.write("HTTP/1.1 101 Switching ProtocolsrnUpgrade: websocketrnConnection: UpgradernSec-WebSocket-Accept: ");
client.write("HTTP/1.1 101 Switching ProtocolsrnUpgrade: websocketrnConnection: UpgradernSec-WebSocket-Accept: ");
Serial.println(Key);
client.print(Key);
client.write("rnrn");
keySent = true;
}
delay(10);
}
client.stop();
Serial.println("Client disconnected");
Serial.println("###################");
Key = "";
EncodedKey = "";
Count = 0;
}
}
void calculateKey(){
Serial.println();
Serial.println();
Serial.println("Calculating new key...");
Key = Key "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
Serial.print("Concatenating that with certain string: ");
Serial.println(Key);
Key = sha1(Key);
Serial.print("Sha1 hash applied to key: ");
Serial.println(Key);
hexToBase64();
Serial.print("And encoded in base64: ");
Key = EncodedKey;
Serial.println(Key);
Serial.println();
}
String binaryToBase64(String x) {
if(x == "000000")
return "A";
else if(x == "000001")
return "B";
else if(x == "000010")
return "C";
else if(x == "000011")
return "D";
else if(x == "000100")
return "E";
else if(x == "000101")
return "F";
else if(x == "000110")
return "G";
else if(x == "000111")
return "H";
else if(x == "001000")
return "I";
else if(x == "001001")
return "J";
else if(x == "001010")
return "K";
else if(x == "001011")
return "L";
else if(x == "001100")
return "M";
else if(x == "001101")
return "N";
else if(x == "001110")
return "O";
else if(x == "001111")
return "P";
else if(x == "010000")
return "Q";
else if(x == "010001")
return "R";
else if(x == "010010")
return "S";
else if(x == "010011")
return "T";
else if(x == "010100")
return "U";
else if(x == "010101")
return "V";
else if(x == "010110")
return "W";
else if(x == "010111")
return "X";
else if(x == "011000")
return "Y";
else if(x == "011001")
return "Z";
else if(x == "011010")
return "a";
else if(x == "011011")
return "b";
else if(x == "011100")
return "c";
else if(x == "011101")
return "d";
else if(x == "011110")
return "e";
else if(x == "011111")
return "f";
else if(x == "100000")
return "g";
else if(x == "100001")
return "h";
else if(x == "100010")
return "i";
else if(x == "100011")
return "j";
else if(x == "100100")
return "k";
else if(x == "100101")
return "l";
else if(x == "100110")
return "m";
else if(x == "100111")
return "n";
else if(x == "101000")
return "o";
else if(x == "101001")
return "p";
else if(x == "101010")
return "q";
else if(x == "101011")
return "r";
else if(x == "101100")
return "s";
else if(x == "101101")
return "t";
else if(x == "101110")
return "u";
else if(x == "101111")
return "v";
else if(x == "110000")
return "w";
else if(x == "110001")
return "x";
else if(x == "110010")
return "y";
else if(x == "110011")
return "z";
else if(x == "110100")
return "0";
else if(x == "110101")
return "1";
else if(x == "110110")
return "2";
else if(x == "110111")
return "3";
else if(x == "111000")
return "4";
else if(x == "111001")
return "5";
else if(x == "111010")
return "6";
else if(x == "111011")
return "7";
else if(x == "111100")
return "8";
else if(x == "111101")
return "9";
else if(x == "111110")
return " ";
else if(x == "111111")
return "/";
}
void hexToBase64() {
WiFiClient client = wifiServer.available();
for(;;) {
StringSlice = Key.substring(Count,Count 1);
Serial.print(StringSlice);
if(StringSlice == "0")
HexToBinary = "0000";
else if(StringSlice == "1")
HexToBinary = "0001";
else if(StringSlice == "2")
HexToBinary = "0010";
else if(StringSlice == "3")
HexToBinary = "0011";
else if(StringSlice == "4")
HexToBinary = "0100";
else if(StringSlice == "5")
HexToBinary = "0101";
else if(StringSlice == "6")
HexToBinary = "0110";
else if(StringSlice == "7")
HexToBinary = "0111";
else if(StringSlice == "8")
HexToBinary = "1000";
else if(StringSlice == "9")
HexToBinary = "1001";
else if(StringSlice == "a")
HexToBinary = "1010";
else if(StringSlice == "b")
HexToBinary = "1011";
else if(StringSlice == "c")
HexToBinary = "1100";
else if(StringSlice == "d")
HexToBinary = "1101";
else if(StringSlice == "e")
HexToBinary = "1110";
else if(StringSlice == "f")
HexToBinary = "1111";
else
break;
Serial.print(" = ");
Serial.println(HexToBinary);
Count ;
StringSlice = Key.substring(Count,Count 1);
if(StringSlice == "0" || StringSlice == "1" || StringSlice == "2" || StringSlice == "3")
HexToBinary = HexToBinary "00";
else if(StringSlice == "4" || StringSlice == "5" || StringSlice == "6" || StringSlice == "7")
HexToBinary = HexToBinary "01";
else if(StringSlice == "8" || StringSlice == "9" || StringSlice == "a" || StringSlice == "b")
HexToBinary = HexToBinary "10";
else if(StringSlice == "c" || StringSlice == "d" || StringSlice == "e" || StringSlice == "f")
HexToBinary = HexToBinary "11";
else {
HexToBinary = HexToBinary "00";
EncodedKey = EncodedKey binaryToBase64(HexToBinary);
EncodedKey = EncodedKey "=";
break;
}
EncodedKey = EncodedKey binaryToBase64(HexToBinary);
StringSlice = Key.substring(Count,Count 1);
HexToBinary = "";
if(StringSlice == "0" || StringSlice == "4" || StringSlice == "8" || StringSlice == "c")
HexToBinary = "00";
else if(StringSlice == "1" || StringSlice == "5" || StringSlice == "9" || StringSlice == "d")
HexToBinary = "01";
else if(StringSlice == "2" || StringSlice == "6" || StringSlice == "a" || StringSlice == "e")
HexToBinary = "10";
else if(StringSlice == "3" || StringSlice == "7" || StringSlice == "b" || StringSlice == "f")
HexToBinary = "11";
Count ;
StringSlice = Key.substring(Count,Count 1);
Serial.print(StringSlice);
if(StringSlice == "0")
HexToBinary = HexToBinary "0000";
else if(StringSlice == "1")
HexToBinary = HexToBinary "0001";
else if(StringSlice == "2")
HexToBinary = HexToBinary "0010";
else if(StringSlice == "3")
HexToBinary = HexToBinary "0011";
else if(StringSlice == "4")
HexToBinary = HexToBinary "0100";
else if(StringSlice == "5")
HexToBinary = HexToBinary "0101";
else if(StringSlice == "6")
HexToBinary = HexToBinary "0110";
else if(StringSlice == "7")
HexToBinary = HexToBinary "0111";
else if(StringSlice == "8")
HexToBinary = HexToBinary "1000";
else if(StringSlice == "9")
HexToBinary = HexToBinary "1001";
else if(StringSlice == "a")
HexToBinary = HexToBinary "1010";
else if(StringSlice == "b")
HexToBinary = HexToBinary "1011";
else if(StringSlice == "c")
HexToBinary = HexToBinary "1100";
else if(StringSlice == "d")
HexToBinary = HexToBinary "1101";
else if(StringSlice == "e")
HexToBinary = HexToBinary "1110";
else if(StringSlice == "f")
HexToBinary = HexToBinary "1111";
else {
HexToBinary = HexToBinary "0000";
EncodedKey = EncodedKey binaryToBase64(HexToBinary);
EncodedKey = EncodedKey "==";
break;
}
Count ;
EncodedKey = EncodedKey binaryToBase64(HexToBinary);
}
Serial.println("#############################################");
Serial.println(EncodedKey);
}
Я буду очищать этот код позже… Основная часть того, что имеет значение, направлена вверх…
Я изменил названия некоторых материалов, для конфиденциальности людей, для которых я это делаю.
Мой журнал напоминает что-то вроде этого:
Flutter sends WebSocket key.
Key sent back by ESP...
Message from App:
⸮⸮uD⸮ZD⸮⸮⸮⸮□⸮⸮□⸮
Я попытался отправить что-то вроде «Привет, мир» или «тест»
Кстати, эти странные символы представляют собой несколько сообщений…
Просто чтобы убедиться, что ключ правильный. Если бы я отправил неправильный ключ обратно, он отключился бы.
У кого-нибудь есть идеи, почему это происходит?
Я думаю, что это связано с таймингами отправки или получения сообщений.
Если мне нужно что-то добавить, пожалуйста, скажите мне.
Комментарии:
1. Ваш вопрос слишком длинный. Я думаю, что вы также усложняете все это, когда вы можете легко общаться через MQTT или Firebase Realtime Database <- (Используйте слушателей здесь). Что вы пытаетесь сделать в своем проекте? Пожалуйста, скажите мне, чтобы я мог вам помочь.
2. глядя на выводимое значение … проверьте, совпадает ли скорость передачи кода в бодах с последовательным монтором