4

I'm trying to get my android studio code to receive txt files from a raspberry pi through the use of sockets. The pi is currently setup as the server, while the app is setup as the client. When the two codes are run, the pi displays that it received the command needed, "SEND1", however nothing is showing up on the app side. Here is the java code I'm using for my application

public class MainActivity extends AppCompatActivity {

Button btnOne;
public String msgRead;
public TextView msg;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnOne = (Button) findViewById(R.id.btnUp);


    btnOne.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CMD = "S s";             //Command to be sent
            wifiPW run = new wifiPW();
            run.execute();
            msg.setText(msgRead);
        }
    });

}

public class wifiPW extends AsyncTask<Void,Void,Void>{
    Socket socket;
    @Override
    protected Void doInBackground(Void... params){
        try{

            //declare sockets, printwriter, and bufferedreader
            socket = new Socket("192.168.42.1",5560);
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //send command to pi
            pw.write(CMD);
            pw.flush();

            //read reply from pi
            msgRead = br.readLine();
            br.close();
            pw.close();
            socket.close();
        }
        catch (UnknownHostException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
}

And here is the python code that I am using on the pi. I'm currently focusing on the "SEND1" command, and am trying to send bytes rather than files. Any and all help is very much appreciated

import socket
import subprocess
from subprocess import call
from subprocess import Popen, PIPE

host = ''
port = 5560
def setupServer():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket created.")
    try:
        s.bind((host, port))
    except socket.error as msg:
        print(msg)
    print("Socket bind complete.")
    return s

def setupConnection():
    s.listen(1) # Allows one connection at a time.
    conn, address = s.accept()
    print("Connected to: " + address[0] + ":" + str(address[1]))
    return conn

def storeFile(filePath):
    print(filePath)
    picFile = open("filePath", mode='wb')
    print("Opened the file.")
    pic = conn.recv(4096)
    while pic:
        print("Receiving file still.")
        picFile.write(pic)
        pic = conn.recv(4096)
    picFile.close()

def sendFile(s, filePath):
    file=open(filePath, 'rb')
    chunk = file.read(4096)
    s.send(str.encode("sending"))
    while chunk:
        print("Sending File")
        s.send(chunk)
        chunk=file.read(4096)

    file.close()
    print("Done Sending")
    s.close()
    return "Done Sending"

def dataTransfer(conn):
    # sends/receives data until told not to.
    while True:
        # Receive the data
        data = conn.recv(4096) # receive the data
        print(data)
        data = data.decode('utf-8')

        dataMessage=data.split(' ', 1)
        command = dataMessage[0]

        if command == 'START':
            print("Prepare for takeoff")
            subprocess.call(['lxterminal', '--command=python start.py'])
            break
        elif command == 'STORE':  # store file on pi
            print("Store command received")
            storeFile(dataMessage[1])
            print("FINISHED STORING FILE")
            break
        elif command == 'KILL':
            print("The server is shutting down.")
            s.close()
            break
        elif command == 'SEND1':  #Send file from Pi to android
            filepath = "/home/pi/Documents/server.py"
            print("Send1 received")
            s.send(bytes("sending"+"\r\n",'UTF-8')) 
            sendFile(s,filepath)         
            break

        else:
            reply = 'Unknown Command'
            print("unknown command")
            s.close()
        # Send the reply back to the client
        conn.sendall(str.encode(reply))
        print("Data has been sent!")
    conn.close()

s = setupServer()

while True:
    try:
        conn = setupConnection()
        dataTransfer(conn)
    except:
        break
KGhadiri
  • 49
  • 5
  • 1
    `Android Studio to Raspberry Pi Socket Communication`. Wrong subject. You want to let an Android device communicate with a raspi. Please adapt. – greenapps Mar 05 '18 at 07:55

0 Answers0