通过c#服务器控制arduino UNO与android应用程序
本文关键字:android 应用程序 UNO arduino 服务器 控制 通过 | 更新日期: 2023-09-27 18:05:47
我是新来的,这是我的第一个问题。
我有和Arduino UNO,我想建立一个与c# web服务器通信的android应用程序,web服务器将数据发送到Arduino,反之亦然。Arduino没有任何屏蔽(以太网或wifi),通过USB连接到笔记本电脑。我有一些代码,我需要一个帮助来修复它,使其工作。
/*************************SERVER*************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO;
namespace SocketServer {
class Program
{
static void Main(string[] args)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 18001);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = socket.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
string welcome = "HELLO 1 FROM SERVER";
/*read*/
byte[] data = new byte[200];
int receiveddata = client.Receive(data);
Console.WriteLine("Received data from CLIENT1: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data).Trim());
/*write*/
ASCIIEncoding asen = new ASCIIEncoding();
byte[] data2 = new byte[200];
data2 = asen.GetBytes(welcome);
int sentdata = client.Send(data2, data2.Length, SocketFlags.None);
Console.WriteLine("Sent data from SERVER: {0}", welcome);
/*read*/
byte[] data3 = new byte[200];
Console.WriteLine("Receiving data from CLIENT : {0}", "...");
receiveddata = client.Receive(data3);
Console.WriteLine("Received data from CLIENT2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3).Trim());
/*write*/
byte[] data4 = new byte[200];
data4 = asen.GetBytes("HELLO 2 FROM SERVER");
sentdata = client.Send(data4, data4.Length, SocketFlags.None);
client.Close();
socket.Close();
Console.WriteLine("Disconnected from {0}", clientep.Address);
Console.ReadLine();
}//main
} }
和这里是android应用程序代码(我是新的android开发):MainActivity.java
package com.example.smarthomefinal;
import eneter.messaging.diagnostic.EneterTrace;
import eneter.messaging.endpoints.typedmessages.*;
import eneter.messaging.messagingsystems.messagingsystembase.*;
import eneter.messaging.messagingsystems.tcpmessagingsystem.TcpMessagingSystemFactory;
import eneter.net.system.EventHandler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.R;
public class MainActivity extends Activity
{
// Request message type
// The message must have the same name as declared in the service.
// Also, if the message is the inner class, then it must be static.
public static class MyRequest
{
public String Text;
}
// Response message type
// The message must have the same name as declared in the service.
// Also, if the message is the inner class, then it must be static.
public static class MyResponse
{
public int Length;
}
// UI controls
private Handler myRefresh = new Handler();
private EditText myMessageTextEditText;
private EditText myResponseEditText;
private Button mySendRequestBtn;
// Sender sending MyRequest and as a response receiving MyResponse.
private IDuplexTypedMessageSender<MyResponse, MyRequest> mySender;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get UI widgets.
myMessageTextEditText = (EditText) findViewById(R.id.messageTextEditText);
myResponseEditText = (EditText) findViewById(R.id.messageLengthEditText);
mySendRequestBtn = (Button) findViewById(R.id.sendRequestBtn);
// Subscribe to handle the button click.
mySendRequestBtn.setOnClickListener(myOnSendRequestClickHandler);
// Open the connection in another thread.
// Note: From Android 3.1 (Honeycomb) or higher
// it is not possible to open TCP connection
// from the main thread.
Thread anOpenConnectionThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
openConnection();
}
catch (Exception err)
{
EneterTrace.error("Open connection failed.", err);
}
}
});
anOpenConnectionThread.start();
}
@Override
public void onDestroy()
{
// Stop listening to response messages.
mySender.detachDuplexOutputChannel();
super.onDestroy();
}
private void openConnection() throws Exception
{
// Create sender sending MyRequest and as a response receiving MyResponse
IDuplexTypedMessagesFactory aSenderFactory =
new DuplexTypedMessagesFactory();
mySender = aSenderFactory.createDuplexTypedMessageSender(MyResponse.class, MyRequest.class);
// Subscribe to receive response messages.
mySender.responseReceived().subscribe(myOnResponseHandler);
// Create TCP messaging for the communication.
// Note: 10.0.2.2 is a special alias to the loopback (127.0.0.1)
// on the development machine
IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
IDuplexOutputChannel anOutputChannel =
aMessaging.createDuplexOutputChannel("tcp://10.0.2.2:8060/");
// Attach the output channel to the sender and be able to send
// messages and receive responses.
mySender.attachDuplexOutputChannel(anOutputChannel);
}
private void onSendRequest(View v)
{
// Create the request message.
MyRequest aRequestMsg = new MyRequest();
aRequestMsg.Text = myMessageTextEditText.getText().toString();
// Send the request message.
try
{
mySender.sendRequestMessage(aRequestMsg);
}
catch (Exception err)
{
EneterTrace.error("Sending the message failed.", err);
}
}
private void onResponseReceived(Object sender, final TypedResponseReceivedEventArgs<MyResponse> e)
{
// Display the result - returned number of characters.
// Note: Marshal displaying to the correct UI thread.
myRefresh.post(new Runnable()
{
@Override
public void run()
{
myResponseEditText.setText(Integer.toString(e.getResponseMessage().Length));
}
});
}
private EventHandler<TypedResponseReceivedEventArgs<MyResponse>> myOnResponseHandler
= new EventHandler<TypedResponseReceivedEventArgs<MyResponse>>()
{
@Override
public void onEvent(Object sender,
TypedResponseReceivedEventArgs<MyResponse> e)
{
onResponseReceived(sender, e);
}
};
private OnClickListener myOnSendRequestClickHandler = new OnClickListener()
{
@Override
public void onClick(View v)
{
onSendRequest(v);
}
};
}
AndroidManifest.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.client"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".AndroidNetCommunicationClientActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
你离你的目标还有一点远。我建议你把解决方案分成几个步骤:
1)下载安装http://sourceforge.net/projects/sockettest/。SocketTest是一个非常有用的java程序,允许你发送/接收TCP/UDP消息。
2)借助SocketTest扩展您的c#服务器(不是web服务器,有区别),以接收来自网络的文本消息,并通过适当的COM端口向Arduino发送命令(请记住,Arduino将通过USB接口连接时显示为串行设备)。
3)一旦你的c#服务器和Arduino草图工作正常,修改你的Android代码,使它发送的消息,你的c#程序可以响应。
我希望这能给你指明正确的方向