androidpythonraspberry-pi2

Call a function on raspberry pi using android application?


I have a project where i need to call a function on raspberry pi. I've wrote the function in python.Both devices will be connected using WiFi. Now i cant figure out how to call the python function in my application.


Solution

  • I connected my raspberry pi and android to the same Wifi network then using the sockets to connect to specific IP and Port. Running the following code on Android.

     class CT implements Runnable {
            String ip1;
            int port1;
            public CT(String ip, int port){
                ip1=ip;
                port1=port;
            }
            @Override
            public void run(){
                try{
                    in = InetAddress.getByName(ip1);
                    s = new Socket(in,port1);
                    i = new DataInputStream(s.getInputStream());
                    send("query");
                    receive();
                }catch(Exception e){}
            }
        }
        public void send(String str){
            try{
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
                out.println(str);
                receive();
            }catch(Exception e){}
        }
        public void receive(){
            stopWorker=false;
            workerThread = new Thread(new Runnable() {
                public void run() {
                    while(!Thread.currentThread().isInterrupted()&&!stopWorker)
                    {
                        try{
                            int n = i.available();
                            if(n>0){
                                byte[] received = new byte[n];
                                i.read(received);
                                data = new String(received,"US-ASCII");
                                h.post(new Runnable()
                                {
                                    public void run()
                                    {
                                        try{
                                            toggleUi(data);
                                        }
                                        catch(Exception x){}
                                    }
                                });
                            }
                        }catch(Exception e){
                            stopWorker=true;
                        }
                    }
                }
            });
            workerThread.start();
        }
    
        public void toggleUi(String data) {
            if(data.contains("PIROK")){
    
    
                t1.setText("PIR IS ON");
    
            }
            if(data.contains("PIROF")){
    
                t1.setText("PIR IS OFF");
    
            }
            if (data.contains("1On"))
                s1.setChecked(true);
            else if(data.contains("1Of"))
                s1.setChecked(false);
            if(data.contains("2On"))
                s2.setChecked(true);
            else if(data.contains("2Of"))
                s2.setChecked(false);
        }
    
        class Close implements Runnable {
    
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try{
                    i.close();
                    out.close();
                    s.close();
                }
                catch(Exception e){}
            }
    
        }
    

    -And this code on Raspberry pi as a service to get the call from android.

    from socket import *
    import RPi.GPIO as GPIO
    import time
    
    GPIO.setwarnings(False)
    def init():
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(11, GPIO.OUT)  # motor 2
        GPIO.setup(13, GPIO.OUT)  # motor 2
        GPIO.setup(15, GPIO.OUT)  # motor 1
        GPIO.setup(16, GPIO.OUT)  # motor 1
        GPIO.setup(36, GPIO.OUT)
        GPIO.setup(37, GPIO.OUT)
    
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(11, GPIO.OUT)
    GPIO.setup(13, GPIO.OUT)
    GPIO.setup(15, GPIO.OUT)
    GPIO.setup(16, GPIO.OUT)
    GPIO.setup(37, GPIO.OUT)  # enable 2
    GPIO.setup(36, GPIO.OUT)  # enable 1
    
    GPIO.output(36, True)  # enable 1
    GPIO.output(37, True)  # enable 2
    
    state = True
    
    HOST = "192.168.0.107"  # local host
    PORT = 9000  # open port 7000 for connection
    s = socket(AF_INET, SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)  # how many connections can it receive at one time
    conn, addr = s.accept()  # accept the connection
    print "Connected by: ", addr  # print the address of the person connected
    while True:
        data = conn.recv(1024)  # how many bytes of data will the server receive
    
        my_data= data.rstrip()
        print ('data is: ',my_data)
        if my_data == 'u':
            init()
            GPIO.output(11, True)
            GPIO.output(13, False)
            GPIO.output(15, True)
            GPIO.output(16, False)
            print 'forward'
            #GPIO.cleanup()
    
        elif my_data == 'l':
            init()
            print 'left'
            GPIO.output(11, True)
            GPIO.output(13, True)
            GPIO.output(15, True)
            GPIO.output(16, False)
            #GPIO.cleanup()
    
        elif my_data == 'r':
            init()
            print 'right'
            GPIO.output(11, True)
            GPIO.output(13, False)
            GPIO.output(15, True)
            GPIO.output(16, True)
            #GPIO.cleanup()
    
        elif my_data == 'd':
            init()
            print 'reverse'
            GPIO.output(11, False)
            GPIO.output(13, True)
            GPIO.output(15, False)
            GPIO.output(16, True)
            #GPIO.cleanup()
        else :
            init()
            print 'stop'
            GPIO.output(11, False)
            GPIO.output(13, False)
            GPIO.output(15, False)
            GPIO.output(16, False)
            #GPIO.cleanup()
    
        print "Received: ", repr(data)
    # reply = raw_input("Reply: ") #server's reply to the client
        reply = ("ok")
        conn.sendall(reply)
    conn.close()