Почему я не могу подключиться к серверу с помощью физического телефона? - PullRequest
0 голосов
/ 25 марта 2020

Я пытаюсь установить соединение между мобильным устройством android и ноутбуком Microsoft, используя python на ноутбуке и xamarin на устройстве android.

Я написал сервер python который принимает клиента, получает информацию и обрабатывает ее.

import socket
import serial


def main():
    srv_sock = socket.socket()
    ip = "0.0.0.0"
    port = 7013
    srv_sock.bind((ip, port))
    srv_sock.listen(5)

    receiver = serial.Serial('com11', 9600)

    while True:
        new_sock, address = srv_sock.accept()

        print "client connected\n"

        while True:
            command = new_sock.recv(1024)
            command_name = command.split('$')[0]
            try:
                command_param1 = command.split('$')[1]

            except IndexError:
                pass

            if command == "":
                print "\n\n\nCLIENT DISCONNECTED\n\n\n"
                new_sock.close()

            elif command_name.upper() == "START_FORWARD\n":
                receiver.write("START_FORWARD\r\n")

            elif command_name.upper() == "STOP_FORWARD\n":
                receiver.write("STOP_FORWARD\r\n")

            elif command_name.upper() == "START_BACKWARD\n":
                receiver.write("START_BACKWARD\r\n")

            elif command_name.upper() == "STOP_BACKWARD\n":
                receiver.write("STOP_BACKWARD\r\n")

            elif command_name.upper() == "90_TURN_LEFT\n":
                receiver.write("90_TURN_LEFT\r\n")

            elif command_name.upper() == "90_TURN_RIGHT\n":
                receiver.write("90_TURN_RIGHT\r\n")

            elif command_name.upper() == "SET_DRIVE_SPEED\n":
                receiver.write("SET_DRIVE_SPEED$" + command_param1 + "\r\n")

            else:
                print "ERROR: COMMAND UNKNOWN"
                print "COMMAND WAS: " + command


if __name__ == "__main__":
    main()

Я также создал android клиент с xamarin, используя AsyncTask

Основная деятельность:

using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using Android.Content.PM;
using Android.Views;

namespace testing_controller
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Landscape)]
    public class MainActivity : AppCompatActivity, Android.Views.View.IOnTouchListener
    {
        ImageButton ibtnCameraLeft;
        ImageButton ibtnCameraRight;
        ImageView ivVisualFromCar;

        ImageButton ibtnMoveForward;
        ImageButton ibtnTurnLeft;
        ImageButton ibtnTurnRight;

        ImageButton ibtnMoveBackward;
        ImageButton ibtn90TurnLeft;
        ImageButton ibtn90TurnRight;

        TasksInBackground RunningTasks;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            ibtnCameraLeft = FindViewById<ImageButton>(Resource.Id.ibtnCameraLeft);
            ibtnCameraRight = FindViewById<ImageButton>(Resource.Id.ibtnCameraRight);
            ivVisualFromCar = FindViewById<ImageView>(Resource.Id.ivVisualFromCar);

            ibtnMoveForward = FindViewById<ImageButton>(Resource.Id.ibtnMoveForward);
            ibtnTurnLeft = FindViewById<ImageButton>(Resource.Id.ibtnTurnLeft);
            ibtnTurnRight = FindViewById<ImageButton>(Resource.Id.ibtnTurnRight);

            ibtnMoveBackward = FindViewById<ImageButton>(Resource.Id.ibtnMoveBackward);
            ibtn90TurnLeft = FindViewById<ImageButton>(Resource.Id.ibtnHalfTurnLeft);
            ibtn90TurnRight = FindViewById<ImageButton>(Resource.Id.ibtnHalfTurnRight);

            ibtnCameraLeft.SetOnTouchListener(this);
            ibtnCameraRight.SetOnTouchListener(this);
            ibtnMoveForward.SetOnTouchListener(this);
            ibtnMoveBackward.SetOnTouchListener(this);
            ibtnTurnLeft.SetOnTouchListener(this);
            ibtnTurnRight.SetOnTouchListener(this);
            ibtn90TurnLeft.SetOnTouchListener(this);
            ibtn90TurnRight.SetOnTouchListener(this);

            RunningTasks = new TasksInBackground("10.0.0.5", 7013);
            RunningTasks.Execute();

        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        public bool OnTouch(View v, MotionEvent e)
        {
            if (v == ibtnMoveForward)
            {
                RunningTasks.setChosenCommand("FORWARD");

                if (e.Action == MotionEventActions.Down)
                {
                    RunningTasks.setBtnIsPressed(true);
                    RunningTasks.setUpdatedState(false);
                }

                else if (e.Action == MotionEventActions.Up)
                {
                    RunningTasks.setBtnIsPressed(false);
                    RunningTasks.setUpdatedState(false);
                }
            }

            else if (v == ibtnMoveBackward)
            {
                RunningTasks.setChosenCommand("BACKWARD");

                if (e.Action == MotionEventActions.Down)
                {
                    RunningTasks.setBtnIsPressed(true);
                    RunningTasks.setUpdatedState(false);
                }

                else if (e.Action == MotionEventActions.Up)
                {
                    RunningTasks.setBtnIsPressed(false);
                    RunningTasks.setUpdatedState(false);
                }
            }

            else if (v == ibtnTurnLeft)
            {
                RunningTasks.setChosenCommand("TURN_LEFT");

                if (e.Action == MotionEventActions.Down)
                {
                    RunningTasks.setBtnIsPressed(true);
                    RunningTasks.setUpdatedState(false);
                }

                else if (e.Action == MotionEventActions.Up)
                {
                    RunningTasks.setBtnIsPressed(false);
                    RunningTasks.setUpdatedState(false);
                }
            }

            else if (v == ibtn90TurnLeft)
            {
                RunningTasks.setChosenCommand("90_TURN_LEFT");

                if (e.Action == MotionEventActions.Down)
                {
                    RunningTasks.setBtnIsPressed(true);
                    RunningTasks.setUpdatedState(false);
                }

                else if (e.Action == MotionEventActions.Up)
                {
                    RunningTasks.setBtnIsPressed(false);
                    RunningTasks.setUpdatedState(false);
                }
            }

            else if (v == ibtnTurnRight)
            {
                RunningTasks.setChosenCommand("TURN_RIGHT");

                if (e.Action == MotionEventActions.Down)
                {
                    RunningTasks.setBtnIsPressed(true);
                    RunningTasks.setUpdatedState(false);
                }

                else if (e.Action == MotionEventActions.Up)
                {
                    RunningTasks.setBtnIsPressed(false);
                    RunningTasks.setUpdatedState(false);
                }
            }

            else if (v == ibtn90TurnRight)
            {
                RunningTasks.setChosenCommand("90_TURN_RIGHT");

                if (e.Action == MotionEventActions.Down)
                {
                    RunningTasks.setBtnIsPressed(true);
                    RunningTasks.setUpdatedState(false);
                }

                else if (e.Action == MotionEventActions.Up)
                {
                    RunningTasks.setBtnIsPressed(false);
                    RunningTasks.setUpdatedState(false);
                }
            }

            else if (v == ibtnCameraLeft)
            {
                RunningTasks.setChosenCommand("CAMERA_LEFT");

                if (e.Action == MotionEventActions.Down)
                {
                    RunningTasks.setBtnIsPressed(true);
                    RunningTasks.setUpdatedState(false);
                }

                else if (e.Action == MotionEventActions.Up)
                {
                    RunningTasks.setBtnIsPressed(false);
                    RunningTasks.setUpdatedState(false);
                }
            }

            else if (v == ibtnCameraRight)
            {
                RunningTasks.setChosenCommand("CAMERA_RIGHT");

                if (e.Action == MotionEventActions.Down)
                {
                    RunningTasks.setBtnIsPressed(true);
                    RunningTasks.setUpdatedState(false);
                }

                else if (e.Action == MotionEventActions.Up)
                {
                    RunningTasks.setBtnIsPressed(false);
                    RunningTasks.setUpdatedState(false);
                }
            }

            return true;
        }
    }

}

Класс для подключения:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace testing_controller
{
    class TasksInBackground : AsyncTask<string, string, string>
    {
        string ip;
        int port;
        StreamWriter sw;
        StreamReader sr;
        string messageToSend;

        bool btnIsPressed;
        bool updatedState;

        string chosenCommand;

        public TasksInBackground(string ip, int port)
        {
            this.ip = ip;
            this.port = port;
            this.messageToSend = "";
            this.btnIsPressed = false;
            this.updatedState = true;
            this.chosenCommand = "";
        }

        public void setIP(string ip)
        {
            this.ip = ip;
        }

        public string getIp()
        {
            return this.ip;
        }

        public void setPort(int port)
        {
            this.port = port;
        }

        public int getPort()
        {
            return this.port;
        }

        public void setStreamWriter(StreamWriter sw)
        {
            this.sw = sw;
        }

        public StreamWriter getStreamWriter()
        {
            return this.sw;
        }

        public void setStreamReader(StreamReader sr)
        {
            this.sr = sr;
        }

        public StreamReader getStreamReader()
        {
            return this.sr;
        }

        protected override string RunInBackground(params string[] @params)
        {
            TcpClient client = new TcpClient();
            client.Connect(new IPEndPoint(IPAddress.Parse(this.ip), this.port));

            sr = new StreamReader(client.GetStream());
            sw = new StreamWriter(client.GetStream());
            sw.AutoFlush = true;

            setStreamReader(sr);
            setStreamWriter(sw);


            while (true)
            {
                if (messageToSend != "")
                {
                    sw.WriteLine(messageToSend);
                    messageToSend = "";
                }

                if ((btnIsPressed) && (!updatedState))
                {
                    PublishProgress("ON");
                    this.updatedState = true;
                }

                else if ((!btnIsPressed) && (!updatedState))
                {
                    PublishProgress("OFF");
                    this.updatedState = true;
                }
            }
        }

        protected override void OnProgressUpdate(params string[] values)
        {
            base.OnProgressUpdate(values);

            string finalMessage = "";

            if ((this.chosenCommand == "90_TURN_LEFT") || (this.chosenCommand == "90_TURN_RIGHT"))
            {
                finalMessage = "";
            }

            else if (values[0] == "ON")
            {
                finalMessage = "START_";
            }

            else if (values[0] == "OFF")
            {
                finalMessage = "STOP_";
            }

            finalMessage += this.chosenCommand;

            this.SendMessage(finalMessage);
        }

        public void setBtnIsPressed(bool pressed)
        {
            this.btnIsPressed = pressed;
        }

        public void setUpdatedState(bool updated)
        {
            this.updatedState = updated;
        }

        public void SendMessage(string mes)
        {
            this.messageToSend = mes;
        }

        public void setChosenCommand(string chosenCommand)
        {
            this.chosenCommand = chosenCommand;
        }
    }
}

По некоторым причинам это работает так же, как я хочу на эмуляторе, но по некоторым причинам это не работает с физическим телефоном. Локальный IP-адрес моего компьютера - 10.0.0.5, а локальный IP-адрес телефона - 10.0.0.28 (согласно информации в настройках), а маска su bnet: 255.255.255.0, что означает, что они оба находятся в одном и том же локальном сеть, поэтому я понятия не имею, почему это не работает. Спасибо за любую помощь:)

...