Android程序和Python程序WIFI服务器通信

时间:2019-04-05 12:59:49

标签: android python sockets communication

我正在创建一个Android应用程序,该应用程序连接到Python Server并发送UP和DOWN命令以及Python代码响应,例如:light打开和Light关闭。

尽管我在Android应用程序中添加了一个按钮,该按钮会将数据发送到Python,而Python服务器将一些字符串或函数发送回显示在Android TextView中的Android应用程序(我需要在Raspberry上运行一个函数并获取结果回到textView中的Android)。

enter code here



package com.example.myapplication;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity {
    Button btnUp;
    Button btnDown;
    Button rButton;
    EditText txtAddress;

    Socket myAppSocket = null;
    public static String wifiModuleIp = "";
    public static int wifiModulePort = 0;
    public static String CMD = "0";



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

        btnUp = (Button) findViewById(R.id.btnUP);
        btnDown = (Button) findViewById(R.id.btnDown);
        rButton = (Button) findViewById(R.id.rButton);

        txtAddress = (EditText) findViewById(R.id.ipAddress);
        btnUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIPandPort();
                CMD = "UP";
                Soket_AsyncTask cmd_increase_servo = new Soket_AsyncTask();
                cmd_increase_servo.execute();
            }
        });

        btnDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIPandPort();
                CMD = "DOWN";
                Soket_AsyncTask cmd_decrease_servo = new Soket_AsyncTask();
                cmd_decrease_servo.execute();
            }
        });

        rButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIPandPort();
                CMD = "VIEW";
                Socket_Received cmd_received_pi = new Socket_Received();
                cmd_received_pi.execute();
            }
        });


    }

    public void getIPandPort() {
        String iPandPort = txtAddress.getText().toString();
        String temp[] = iPandPort.split(":");
        wifiModuleIp = temp[0];
        wifiModulePort = Integer.valueOf(temp[1]);


        //Log.d("MYTEST","IP String" +iPandPort);
        //Log.d("MY TEST","IP:"+wifiModuleIp);
        // Log.d("MY TEST","PORT"+wifiModulePort);


    }

    public class Soket_AsyncTask extends AsyncTask<Void, Void, Void> {
        Socket socket;

        protected Void doInBackground(Void... params) {
            try {
                InetAddress inetAdress = InetAddress.getByName(MainActivity.wifiModuleIp);
                socket = new java.net.Socket(inetAdress, MainActivity.wifiModulePort);
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeBytes(CMD);
                dataOutputStream.close();
                socket.close();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;

        }

    }

    public class Socket_Received extends AsyncTask<String, Void, Void> {
        ServerSocket cScoket;
        Socket socket;
        //public TextView textView;


        private DataInputStream in;

        @SuppressLint("WrongThread")
        protected Void doInBackground(String... params) {
            try {

                cScoket = new ServerSocket(MainActivity.wifiModulePort);
                socket = cScoket.accept();
                in = new DataInputStream(socket.getInputStream());
                InputStreamReader reader = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(reader);
                final TextView textView = (TextView)findViewById(R.id.txtView);
                textView.setText(br.toString());
                socket.close();
                in.close();

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }


    }
}

我的Python代码在这里:

enter code here

import lighton
from socket import *
from time import ctime
import time

    lighton.setUP()

    ctrCmd = ['UP','DOWN','VIEW']

    HOST = ''
    PORT = 5555
    BUFSIZE = 1024
    ADDR = (HOST,PORT)

    tcpSerSock = socket(AF_INET, SOCK_STREAM)
    tcpSerSock.bind(ADDR)
    tcpSerSock.listen(5)

    while True:
            tcpCliSock,addr = tcpSerSock.accept()

            time.sleep(.05)
            data = ''
            data = tcpCliSock.recv(BUFSIZE).decode()


            if not data:
                    print("there is no data")
                    break

            if data == ctrCmd[0]:
                lighton.ledOn()

            if data == ctrCmd[1]:
                lighton.ledOff()

            if data == ctrCmd[2]:
                    r="hello world"
                    tcpCliSock.send(r.encode())

    tcpSerSock.close();

我的Python在这里介绍类代码:

import time

def setUP():
        print("Setting up...")


def ledOn():

    print("led is on")


def ledOff():
    print("led is off")


if __name__ == '__main__':
    setup()

0 个答案:

没有答案