Search code examples
androidfilearduinoesp8266arduino-esp8266

Problem regarding receiving files from android device into the esp8266


I've been working on a project where i would send a file from the android app i wrote to my esp8266; the esp8266 then will write the file onto the SD card. but when esp receives the file for example a .jpg, it's all garbled and noisy. and if i receive a .txt file it will always add a (¬í ur [B¬óøTà xp ¬) at the beginning, regardless of what method i use.

Here's my android code: (Server thread)

Socket mySocket = null;
ServerSocket serverSocket = null;

class ServerThread implements Runnable{
    int serverPort;
    public ServerThread(int serverPort){
        this.serverPort = serverPort;
    }
    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(serverPort);
            mySocket = serverSocket.accept();
            output = new PrintWriter(mySocket.getOutputStream());
            input = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            Log.i("connection", "server");

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    connection_state = true;
                    LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    TextView thisText = new TextView(MainActivity.this);
                    thisText.setId(append);
                    thisText.setText("Server port: " + 8080 + " ... A client just made connection");
                    thisText.setTextSize(20);
                    thisText.setBackgroundColor(Color.rgb(25, 24, 24));
                    thisText.setTextColor(Color.rgb(0, 100, 0));
                    append++;
                    thisText.setGravity(20);
                    thisText.setLayoutParams(textParams);
                    myTexts.addView(thisText);
                }
            });
            new Thread(new ReceiveStringThread()).start();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("connection", "couldn't establish connection");
        } finally {
            try {
                if (socket != null)
                    socket.close();
                if (serverSocket != null)
                    serverSocket.close();

            }catch (IOException e){
               e.getStackTrace();
            }
        }
    }
}

Send file thread:

class SendFileThread implements Runnable{
    String filePath;

    SendFileThread(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public void run() {
        if(connection_state) {
            File findFile = new File(filePath);

            byte[] sendIt = new byte[(int) findFile.length()];

            try {
                BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));

                bufferFile.read(sendIt, 0, sendIt.length);
                ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
                oos.writeObject(sendIt);
                oos.flush();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
                                       (int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (IOException e) {
                e.getStackTrace();
            }finally {
                try {
                    mySocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

and here's my arduino code for esp8266:

#include <ESP8266WiFi.h>
#include <SD.h>

#ifndef STASSID
#define STASSID "ESP_CLIENT"
#define STAPSK  "client-1234"
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;

const char* host = "192.168.1.103";
const uint16_t port = 8080;

boolean connectionStatus = false;

byte buffer_array[10] = {'0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00'};
int num_read;

WiFiClient client;

void setup() {
    Serial.begin(57600);

    //.................Initiate SD card................//
    if(!SD.begin(SS)){
        Serial.println("SD card initialization failed!");
        return;
    }else{
        Serial.println("SD card initialized successfully");
    }

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

char *printBytes(byte *bytes) {
  char bytesStr[10];
  sprintf(bytesStr, "%02X", *bytes);
  Serial.print("byte: ");
  Serial.println(bytesStr);  

  return bytesStr;
}

void loop() {
    if(!connectionStatus){
        Serial.print("connecting to ");
        Serial.print(host);
        Serial.print(':');
        Serial.println(port);
        
        if (!client.connect(host, port)) {
            Serial.println("********************************************Connection failed************************************************");
            connectionStatus = false;
            delay(1000);
            return;
        }else{
            Serial.println("********************************************Connection established with server***********************************************");
            connectionStatus = true;
        }
        
        Serial.println("sending data to server");
        if (client.connected()) {
          client.println("hello from ESP8266");
        }
    }
    
    if(client.available()){
        Serial.println("Receiving...");
        num_read = client.readBytesUntil('\n',buffer_array, 10);
        Serial.println("bytes read: " + (String)num_read);
        printBytes(buffer_array);

        File appendSD = SD.open("/testESP32.txt", FILE_WRITE);
        if(!appendSD){
            Serial.println("not found");
            return;
        }else{
            Serial.println("Writing byte to file...");
            appendSD.write(buffer_array, num_read);
            appendSD.close();
        }
    }
}

and regardless of which mode i put them into, whether it'll be esp as server and android device as client or reverse, it won't make a difference at all.

anyone knows how to fix this?

i modified the SendFileThread as below but it only worked for sending .txt files correctly. but sending image files like .jpg problem still stands.

class SendFileThread implements Runnable{
    String filePath;

    SendFileThread(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public void run() {
        if(connection_state) {
            File findFile = new File(filePath);

            byte[] sendIt = new byte[(int) findFile.length()];

            try {
                BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));

                bufferFile.read(sendIt, 0, sendIt.length);
                OutputStream os= mySocket.getOutputStream();
                os.write(sendIt);
                os.flush();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
                                       (int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (IOException e) {
                e.getStackTrace();
            }finally {
                try {
                    mySocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }else{

        }
    }
}

and i wanna be able to send all kinds of data like .pdf .doxs as well and ObjectOutputStream sends all this kinds of files just fine if although i'm sending them to another android phone not esp8266


Solution

  • SOLVED: i used

    client.read(buffer_array, 10);

    for image files instead of

    client.readBytesUntil('\n', buffer_array, 10);
    

    and in android changed

    ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
            oos.writeObject(sendIt);
    

    to

    OutputStream os= mySocket.getOutputStream();
                os.write(sendIt);
    

    and it finally worked for all types of files!