如何打开TCP连接并通过WPF中的另一个方法发送数据?

问题描述 投票:0回答:1

我想将我的WPF应用程序连接到Raspberry Pi 3b。经过一些互联网搜索,我决定使用TCP。在当前状态下,我发送一个字符串并立即关闭连接。但是我希望在Raspi上运行的服务器随时向我发送数据,这在Socket关闭时不起作用。 如何打开套接字并在其他方法中访问它?

我试过了:

namespace WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

    private TcpClient tcp;

    public MainWindow()
    {
        InitializeComponent();

    }

    private void _Write(string message)
    {
        NetworkStream stream = tcp.GetStream();
        Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
        stream.Write(data, 0, data.Length);


    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            tcp = new TcpClient(ip_box.Text,Convert.ToInt32(port_box.Text));
            Byte[] data = System.Text.Encoding.ASCII.GetBytes("Hallo");
            NetworkStream stream = tcp.GetStream();

            stream.Write(data, 0, data.Length);

        }
        catch(Exception ex)
        {
            MessageBox.Show("Error");

        }

    }

这是Python代码:

print"Pi is starting..."
import socket
print"Socket importet..."
import time
print"Time importet..."
import RPi.GPIO as GPIO
print"GPIO importet..."
import sys
import thread
print"-----------"



ip = "192.168.178.120"
port = 5335

print"Ip: "+ip
print"Port: "+str(port)


axis_1_to_deg=22
axis_2_to_deg=111

def moveaxis1(a):

         x=0
         mvstp1=int(a)
         if(mvstp1<0):
             GPIO.output(stepper1_dir,GPIO.HIGH)
             mvstp1=int(mvstp1)* -1
         elif(mvstp1>0):
            GPIO.output(stepper1_dir,GPIO.LOW)
         while x<int(mvstp1):
             GPIO.output(stepper1_step,GPIO.LOW)
             GPIO.output(stepper1_step,GPIO.HIGH)
             x=x+1
             time.sleep(0.002)

def moveaxis2(a):

         x=0
         mvstp2=int(a)
         if(mvstp2<0):
             GPIO.output(stepper2_dir,GPIO.HIGH)
             mvstp2=int(mvstp2)* -1
         elif(mvstp2>0):
            GPIO.output(stepper2_dir,GPIO.LOW)
         while x<int(mvstp2):
             GPIO.output(stepper2_step,GPIO.LOW)
             GPIO.output(stepper2_step,GPIO.HIGH)
             x=x+1
             time.sleep(0.00005)


def moveaxis3(a):

         x=0
         mvstp3=int(a)
         if(mvstp3<0):
             GPIO.output(stepper3_dir,GPIO.HIGH)
             mvstp3=int(mvstp3)* -1
         elif(mvstp3>0):
            GPIO.output(stepper3_dir,GPIO.LOW)
         while x<int(mvstp3):
             GPIO.output(stepper3_step,GPIO.LOW)
             GPIO.output(stepper3_step,GPIO.HIGH)
             x=x+1
             time.sleep(0.00005)

print"Thread 3 Declared"
print"Threads Declared"

x=0
stepper1_step=40
stepper2_step=36
stepper3_step=26

stepper1_dir=38
stepper2_dir=32
stepper3_dir=24
calib_1=8
calib_2=10

GPIO.setmode(GPIO.BOARD)
GPIO.setup(calib_1,GPIO.IN)
GPIO.setup(calib_2,GPIO.IN)

GPIO.setup(stepper1_step,GPIO.OUT)
GPIO.setup(stepper1_dir,GPIO.OUT)
GPIO.setup(stepper2_step,GPIO.OUT)
GPIO.setup(stepper2_dir,GPIO.OUT)
GPIO.setup(stepper3_step,GPIO.OUT)
GPIO.setup(stepper3_dir,GPIO.OUT)
GPIO.setmode(GPIO.BOARD)

pos_axis1 = 0
pos_axis2 = 0
pos_axis3 = 0




print " "


    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((ip, port))
    sock.listen(1)




    print("RasPI Server up / awaiting connection...")       

    while True:
       print"------------"
        connection,client_addres =sock.accept()    # buffer size is 1024 bytes

     data = connection.recv(1024)
    print "Received message:", data
    if(data.startswith( 'stp')):
         print "Commands for Steppers are being proccesed"
         stp,move_stp1,move_stp2,move_stp3 = data.split(',')
         print("Steps Axis 1"+move_stp1)
         print("Steps Axis 2"+move_stp2)
         print("Steps Axis 3"+move_stp3)
         print"------------"
         print"Threads are starting..."
         in_pos_1=int(move_stp1)*axis_1_to_deg
         in_pos_2=int(move_stp2)*axis_2_to_deg
         in_pos_3=int(move_stp3)*axis_2_to_deg

         z1 = pos_axis1 - in_pos_1
         z2 = pos_axis2 - in_pos_2
         z3 = pos_axis3 - in_pos_3

         thread.start_new_thread(moveaxis1,(z1,))
         thread.start_new_thread(moveaxis2,(z2,))
         thread.start_new_thread(moveaxis3,(z3,))

         pos_axis1 = in_pos_1
         pos_axis2 = in_pos_2
         pos_axis3 = in_pos_3

         print"Position 1: " +str(pos_axis1)
         print"Position 2: " +str(pos_axis2)
         print"Position 3: " +str(pos_axis3)
    elif(data =="calib"):
        ready = False
        while ready==False:
            if(GPIO.input(calib_1)==True):
                moveaxis1(1)
            else:
                ready=True
                moveaxis1(-40*axis_1_to_deg)
        ready = False
        while ready==False:
            if(GPIO.input(calib_2)==True):
                moveaxis2(1)
            else:
                ready=True
                moveaxis2(-85*axis_2_to_deg)

    elif(data=="set_0"):
        pos_axis1=0
        pos_axis2=0
        pos_axis3=0

    elif(data=="exit"):
        break
    print" "



GPIO.cleanup()
sock.close()
print"Fertig"
wpf tcp
1个回答
0
投票

您可以使用Net Core在Raspberry中创建一个控制台应用程序,您需要在您的覆盆子中安装Net core运行时,(您不应该在您的覆盆子中安装net core sdk)然后您可以使用dot net编译“控制台服务”应用程序。

dotnet publish -r linux-arm

这里参考https://github.com/dotnet/core/blob/master/samples/RaspberryPiInstructions.md

如果丢失任何连接,则使用TCPListener类进行多重连接时,您的控制台应用程序应具有无限性。这里有一些例子:https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx

另外你应该知道“反向连接”如果你的覆盆子有一个路由器和你的客户端应用程序在另一个网络后面,但在本地网络中你应该没有问题。

另一种方式,是使用“Azure IOT Hub”从任何地方控制覆盆子https://azure.microsoft.com/en-us/services/iot-hub/(但我不喜欢这种方式,因为有成本)

© www.soinside.com 2019 - 2024. All rights reserved.