【发布时间】:2014-05-30 06:52:01
【问题描述】:
我是该网站的新手,这是我的第一个问题。
我有和 Arduino UNO,我想构建一个与 c# web 服务器通信的 android 应用程序,web 服务器将数据发送到 arduino,反之亦然。
Arduino 没有任何屏蔽(以太网或 wifi)通过 USB 连接到笔记本电脑。
我有一些代码需要帮助来修复它并使其正常工作。
这里是c#代码:
/*************************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>
【问题讨论】:
-
你的问题到底是什么?我看不到任何与 arduino 通信的代码。
-
以防万一:虽然 arduino 是通过 USB 连接的,但您必须通过 COM 端口与它“交谈”。
-
您好,感谢您的回复。好吧,arduino 草图没问题,我的问题是将数据从 android 应用程序发送到 Web 服务器,然后 Web 服务器(连接 arduino 的同一台电脑)将这些数据发送到 arduino(例如打开 LED)。
标签: java c# android xml eclipse