android - 使用android应用程序在树莓派上调用一个函数?

标签 android python raspberry-pi2

我有一个项目,我需要在树莓派上调用一个函数。我已经用 python 编写了函数。两个设备都将使用 WiFi 连接。现在我不知道如何在我的应用程序中调用 python 函数。

最佳答案

我将我的树莓派和安卓连接到同一个 Wifi 网络,然后使用套接字连接到特定的 IP 和端口。在 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){}
        }

    }

- Raspberry pi 上的这段代码作为从 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()

关于android - 使用android应用程序在树莓派上调用一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44021261/

相关文章:

java - 在 onTouchListener 中设置宽度

python - 在install_requires中使用git repo编写setup.py来检测已经安装

python - openpyxl - 调整列宽大小

python - 循环运行 .py 文件

android - 使用 Timer 从 android 做 http 请求

java - 如何修复 "unchecked call to ' AttachView(V )' as a member of raw type ' BasePresenter'"?

android - android 中的自动完成不适用于动态数据

python - 抓取可以应用到这个正在主动重新计算的页面吗?

.net - System.Drawing.GDIPlus.CheckStatus System.Drawing.Image.FromFile System.ArgumentException [GDI+状态: InvalidParameter]

python - 导入树莓派GPIO错误