UPDATE:
Thank you for the thoughts. I have debugged the issue I believe down to the connection between the android to the ESP8266. I believe there may be something going on with the ESP because when I connect the android to my pc it seems to connect and work well. There are some very minor delays but nothing like when it is connected to the ESP. Therefore I am thinking the ESP is causing the delay. That being said I am not sure what could cause this. I have tried using the ESP8266 2.3.0 ver of the libraries in Arduino IDE 1.6.8 but can't seem to figure out why the delay. I did connect the android app to my internal router and then send to the PC with no issues. However it doesn't seem to work with the ESP. I can't believe I am the only one that is seeing this... If anyone else has this working please let me know how you did it. My eternal gratitude would be yours.
Here is the ESP Arduino code:
WiFiServer server(2390); // TCP/IP
SoftwareSerial mySerial( 4, 5); // RX, TX
void setup( )
{
Serial.begin( 115200 );
WiFi.mode(WIFI_STA);
WiFi.softAP( "mySSID", "myPASS");
server.begin();// START TCP/IP SERVER
}
WiFiClient client;
void loop( )
{
if (client)
{
while (client.connected())
{
if (client.available())
{
char command = client.read();
Serial.println(itoa(command,buffer,10));
}
}
}
else
{
client = server.available();
}
}
I am trying to get almost instantaneous communication using TCP/IP sockets between android (Java) and ESP8266. The problem I am seeing is a significant delay between when I press the button to when the android will actually send the data. It seems to sometimes send right when I tap the Go Button but after the first time it will not send for 5-10 seconds. When it is stuck I tap the Go button a number of times and after the delay they all seem to send at once or start sending in spurts. I look at the network monitor in Android Studio and the delay is noticable from the time I tap the button until the traffic shows up on the network panel in the Monitors tab.
I am using the Android Studio Debugger to test the code.
Is there something that I am not doing correctly? Or perhaps is there a better implementation for near instant communication between devices?
Thank you for your assistance in advance!
Android Device:
Samsung Note 4 - v5.1.1 Android v2.0
Android Studio
ESP Device:
ESP8266 using Arduino Studio 1.6.8
Here is my Code:
public class MainActivity extends AppCompatActivity
{
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view)
{
try
{
new AsyncTaskRunner().execute("");
}
catch (Exception e)
{
e.printStackTrace();
}
}
private class AsyncTaskRunner extends AsyncTask<String, String, String>
{
private String resp;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params)
{
try
{
DataOutputStream dataOut;
Socket s = new Socket("192.168.4.1", 2390);
dataOut=new DataOutputStream(s.getOutputStream());
byte[] outputData = new byte[9];
outputData[0] = 1;
outputData[1] = 2;
outputData[2] = 3;
outputData[3] = 4;
outputData[4] = 5;
outputData[5] = 6;
outputData[6] = 7;
outputData[7] = 8;
outputData[8] = 9;
dataOut.write(outputData); // Red
dataOut.flush();
dataOut.close();
s.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.jered.networktest.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go"
android:onClick="onClick"/>
</RelativeLayout>
I had this problem for the case while I wanted to transmit some data to an access point Esp8266-01. I think this delay occurred since if (client. available()) inside while (client.connected())loop waits to receive data until client is available. hence, makes a delay (it was exactly 5 seconds me). to avoid this unpleasant behavior, I appended a carriage return '\r' in write command of AsyncTask in the android MainActivity.java file then modified Arduino sketch to wait until the server receives a carriage return, I mean some code like this String request = client.readStringUntil('\r');
finally, two buttons as known as btn1 and btn2 in the android app send two strings /led/on and /led/off respectively. by now ESP8266 receives carriage return and flush client immediately then there is no delay to execute other section of the program.
the following program turns one led on or off (GPIO 0 pin of the ESP8266-01) according to the pressed button in Android app. but don't forget to set ground GPIO 0 of ESP8266-01 just while programming it and don't forget to connect mobile wifi to ESP wifi network first but you can use wifi configuration to connect to ESP wifi automatically too (see this link).
Arduino code:
#include<ESP8266WiFi.h>
// WiFi Definitions
const char* ssid = "Esp8266TestNet";
const char* password = "Esp8266Test"; // has to be longer than 7 chars
const char* value = "";
int ledPin = 0; // GPIO 0
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH); // turn on
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password, 1, false);
server.begin();
}
void loop() {
// Check of client has connected
WiFiClient client = server.available();
if(!client) {
return;
}
// Read the request line
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match request
if(request.indexOf("/led/on") != -1) {
digitalWrite(ledPin, HIGH);
value = "on";
} else if (request.indexOf("/led/off") != -1) {
digitalWrite(ledPin, LOW);
value = "off";
}
else {
Serial.println("not validate");
}
client.flush();
// JSON response
String s = "HTTP/1.1 200 OK\r\n";
s += "Content-Type: application/json\r\n\r\n";
s += "{\"data\":{\"message\":\"success\",\"value\":\"";
s += value;
s += "\"}}\r\n";
s += "\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disconnected");
// The client will actually be disconnected when the function returns and the client object is destroyed
}
manifest XML:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myhgrtest">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn1"
android:text="btn1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
></Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn2"
android:text="btn2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
></Button>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java:
package com.example.myhgrtest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
Button btn1,btn2;
TcpClient mTcpClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=findViewById(R.id.btn1);
btn2=findViewById(R.id.btn2);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
send_request1();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
send_request2();
}
});
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//response received from server
Log.d("test", "response " + values[0]);
//process server response here....
}
}
public void send_request1() {
send_request1 sr = new send_request1();
sr.execute();
}
public void send_request2() {
send_request2 sr = new send_request2();
sr.execute();
}
class send_request1 extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
try { /*note : ip address must be in Quotation mark*/
/*note : port doesn't need to be inside the Quotation mark*/
Socket s = new Socket(/*ip address :*/"192.168.4.1",/*port :*/ 80);
PrintWriter printWriter = new PrintWriter(s.getOutputStream());
printWriter.write("/led/on"+"\r");
printWriter.flush();
printWriter.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(final String Data) {
/*Data is what you receive from your server*/
Log.e("my_Data","Data is : " + Data);
}
}
class send_request2 extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
try {
/*note : ip address must be in Quotation mark*/
/*note : port doesn't need to be inside the Quotation mark*/
Socket s = new Socket(/*ip address :*/"192.168.4.1",/*port :*/ 80);
PrintWriter printWriter = new PrintWriter(s.getOutputStream());
printWriter.write("/led/off"+"\r");
printWriter.flush();
printWriter.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(final String Data) {
/*Data is what you receive from your server*/
Log.e("my_Data","Data is : " + Data);
//Toast.makeText(MainActivity.this, Data, Toast.LENGTH_SHORT).show();
}
}
}
I don't think anyone can say for certain where the problem lays.
To prevent you (and others) from chasing ghosts, you really want to split up your problem:
Make sure your 'doInBackground' isn't delayed, e.g. by logging to the android logging system, console, debugger, or doing something easy in the ui.
Make sure sending on the Android side isn't delayed, by writing a tiny listener in e.g. Java, and running that on your PC.
Make sure listening isn't delayed, by creating a tiny sender in Java, and running that on your PC.
This way divide your problem till you find the root cause :)
Related
I'm trying to make an app where I send the input from my android device to the server i.e. my pc where Arduino is connected. So the Pc(server) sends the input to the Arduino. But using Mirror, i am having slight difficulties regarding the syncing of data. I'm able to connect both the server and the client but I'm not able to send the data from client to server or from server to client.
I have tried the YouTube tutorials and the [Command] too but I think I'm missing something.
I just want to send command from the client to server so it sends to Arduino. If anyone can help, it will be a great deal.
The code for script is as
using System.Collections.Generic;
using UnityEngine;
using Mirror;
using TMPro;
public class syncData : NetworkBehaviour
{
public GameObject DFA;
public TMP_Text data1;
public TMP_Text data2;
public TMP_Text data3;
[SyncVar]
string receivedString;
public delegate void StringChangedDelegate(string receivedString);
/*[SyncEvent]*/
public event StringChangedDelegate EventStringChanged;
private void SetString(string receivedString)
{
receivedString = DFA.GetComponent<Comunicacion>().receivedstring;
}
public override void OnStartServer()
{
SetString(receivedString);
}
// Start is called before the first frame update
void Start()
{
// DFA = GameObject.FindWithTag("dfa"); // tag, not name
}
/* [Command]
private void changeString() => SetString(receivedString);
*/
// Update is called once per frame
// [ClientCallBack]
void Update()
{
// Debug.Log("Client is sending information.");
// receivedString = DFA.GetComponent<Comunicacion>().receivedstring;
refresh(receivedString);
}
[Server]
void FunctionServer()
{
Debug.Log("Running the program in Server mode.");
}
[ClientRpc]
void refresh(string receivedString)
{
// receivedString = DFA.GetComponent<Comunicacion>().receivedstring;
if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.B))
{
Debug.Log(" Right Arrow Button was pressed on Vuzix");
}
else if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.X))
{
Debug.Log(" Left Arrow Button was pressed on Vuzix");
}
refresher();
// string[] datos = receivedString.Split(':'); //My arduino script returns a 3 part value (IE: 12,30,18)
//// data1.SetText(datos[0]);// Try to forcefully re-enter values from DFA
// data2.SetText(datos[1]);
// data3.SetText(datos[2]);
}
[Command]
void refresher()
{
// receivedString = DFA.GetComponent<Comunicacion>().receivedstring;
refresh(receivedString);
Debug.Log("A command has been sent");
// gm.Update()
}
}
I am developing an android app to retrieve data through php,mysql,json from a database. I need to create a service or any way to call getData() method every 10 minutes. I tried placing these 2 methods in a broadcast receiver and used alarm manager to repeat every 10 mins but it didn't run properly, it worked only for Toast and Log.d (simple operations). Is there an simple approach to achieve what I want ? I did search a lot, but couldn't find a clear answer
//METHOD 1
private void getData() {
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
// METHOD 2
private void showJSON(String response){
String id="";
String time="";
String value = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
for (int i = 0; i < result.length(); i++) {
JSONObject tempData = result.getJSONObject(i);
id = tempData.getString(Config.KEY_NAME);
time = tempData.getString(Config.KEY_ADDRESS);
value = tempData.getString(Config.KEY_VC);
String data = "Id:\t"+id+", Time:\t" +time+ ", Value:\t"+ value;
all += data+"\n";
}
}
catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText(all);
}
Your way of using a broadcast receiver (BR) and an Alarm manager sounds like a good approach and I'm not sure exactly what problem you encountered. Could you tell us more?
Without all the details I'd say that a potential problem is that a Broadcast receiver is normally executed in the UI thread of Android and that does not for example allow you to perform network access and it must finish within X seconds.
1) You don't have the right permissions to access internet? From what I remember the log of this can be easy to miss.
2) Either you can request the BR to run the a background thread, I know you can do it, not tried myself.
3) You can start another thread. As you seen to update the UI you should probably use an Async Task for this. So you can do the network in a background thread and then you you get a call in the UI thread with the new data. (This would probably be the option to go to)
Side note: for parsing json, I'd recommend you to look at Gson. It's a library from google that makes the parsin of Json much simpler. https://github.com/google/gson
import com.google.android.gms.gcm.GcmTaskService;
import com.google.android.gms.gcm.TaskParams;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.gcm.GcmNetworkManager;
import com.google.android.gms.gcm.OneoffTask;
import com.google.android.gms.gcm.PeriodicTask;
import com.google.android.gms.gcm.Task;
import com.rcsplcms.ess.Constant;
import com.rcsplcms.ess.GPSTracker;
import com.rcsplcms.ess.R;
import com.rcsplcms.ess.application.ESSApplication;
import com.rcsplcms.ess.util.AppLog;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.util.List;
import java.util.Locale;
/**
* Created by MAYURKUMAR TERAIYA on 20-09-2017.
*/
public class GCMServiceTracking extends GcmTaskService {
private static final String TAG = GCMServiceTracking.class.getSimpleName();
public static final String GCM_ONEOFF_TAG = "oneoff|[0,0]";
public static final String GCM_REPEAT_TAG = "repeat|[7200,1800]";
#Override
public void onInitializeTasks() {
//called when app is updated to a new version, reinstalled etc.
//you have to schedule your repeating tasks again
super.onInitializeTasks();
}
#Override
public int onRunTask(TaskParams taskParams) {
//do some stuff (mostly network) - executed in background thread (async)
//Toast.makeText(getApplicationContext(), "Service Executed",
Toast.LENGTH_SHORT).show();
//obtain your data
Bundle extras = taskParams.getExtras();
Handler h = new Handler(getMainLooper());
Log.v(TAG, "onRunTask");
if (taskParams.getTag().equals(GCM_ONEOFF_TAG)) {
h.post(new Runnable() {
#Override
public void run() {
//Toast.makeText(GCMServiceTracking.this, "ONEOFF executed",
Toast.LENGTH_SHORT).show();
}
});
} else if (taskParams.getTag().equals(GCM_REPEAT_TAG)) {
h.post(new Runnable() {
#Override
public void run() {
//Toast.makeText(GCMServiceTracking.this, "REPEATING executed", Toast.LENGTH_SHORT).show();
gpsTracker = new GPSTracker(GCMServiceTracking.this);
Toast.makeText(getApplicationContext(), "Data Syncing.", Toast.LENGTH_SHORT).show();
}
});
}
return GcmNetworkManager.RESULT_SUCCESS;
}
public static void scheduleOneOff(Context context) {
//in this method, single OneOff task is scheduled (the target service
that will be called is MyTaskService.class)
Bundle data = new Bundle();
data.putString("some key", "some budle data");
try {
OneoffTask oneoff = new OneoffTask.Builder()
//specify target service - must extend GcmTaskService
.setService(GCMServiceTracking.class)
//tag that is unique to this task (can be used to cancel task)
.setTag(GCM_ONEOFF_TAG)
//executed between 0 - 10s from now
.setExecutionWindow(10, 10)
//set required network state, this line is optional
.setRequiredNetwork(Task.NETWORK_STATE_ANY)
//request that charging must be connected, this line is optional
.setRequiresCharging(false)
//set some data we want to pass to our task
.setExtras(data)
//if another task with same tag is already scheduled, replace it with this task
.setUpdateCurrent(true)
.build();
GcmNetworkManager.getInstance(context).schedule(oneoff);
Log.v(TAG, "oneoff task scheduled");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void scheduleRepeat(Context context) {
//in this method, single Repeating task is scheduled (the target service that will be called is MyTaskService.class)
try {
PeriodicTask periodic = new PeriodicTask.Builder()
//specify target service - must extend GcmTaskService
.setService(GCMServiceTracking.class)
//repeat every 60 seconds
.setPeriod(300)
//specify how much earlier the task can be executed (in seconds)
.setFlex(30)
//tag that is unique to this task (can be used to cancel task)
.setTag(GCM_REPEAT_TAG)
//whether the task persists after device reboot
.setPersisted(true)
//if another task with same tag is already scheduled, replace it with this task
.setUpdateCurrent(true)
//set required network state, this line is optional
.setRequiredNetwork(Task.NETWORK_STATE_ANY)
//request that charging must be connected, this line is optional
.setRequiresCharging(false)
.build();
GcmNetworkManager.getInstance(context).schedule(periodic);
Log.v(TAG, "repeating task scheduled");
} catch (Exception e) {
Log.e(TAG, "scheduling failed");
e.printStackTrace();
}
}
public static void cancelOneOff(Context context) {
GcmNetworkManager
.getInstance(context)
.cancelTask(GCM_ONEOFF_TAG, GCMServiceTracking.class);
}
public static void cancelRepeat(Context context) {
GcmNetworkManager
.getInstance(context)
.cancelTask(GCM_REPEAT_TAG, GCMServiceTracking.class);
}
public static void cancelAll(Context context) {
GcmNetworkManager
.getInstance(context)
.cancelAllTasks(GCMServiceTracking.class);
}
}
// CODE FOR START BACKGROUND TASK
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
Int errorCheck = api.isGooglePlayServicesAvailable(LoginActivity.this);
if(errorCheck == ConnectionResult.SUCCESS) {
//google play services available, hooray
} else if(api.isUserResolvableError(errorCheck)) {
//GPS_REQUEST_CODE = 1000, and is used in onActivityResult
api.showErrorDialogFragment(LoginActivity.this, errorCheck, GPS_REQUEST_CODE);
//stop our activity initialization code
return;
} else {
//GPS not available, user cannot resolve this error
//todo: somehow inform user or fallback to different
method
//stop our activity initialization code
return;
}
GCMServiceTracking.scheduleRepeat(LoginActivity.this);
GRADLE FILE
compile 'com.google.android.gms:play-services:8.3.0'
MENIFEST FILE
<service
android:name=".services.GCMServiceTracking"
android:exported="true"
android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
<intent-filter>
<action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
</intent-filter>
</service>
I'm trying to run a server on a Android device using the JLAN library.
After some works, it seems running, stopping.
From an other Android device, I can connect and see my share folder by adding manually a server with smb://192.168.0.10:1445.
Here my problems:
1) I rooted the Android Device but I can't use the port above 1024. (So I use 1445 instead 445)
2) From any other device, I can't see automaticaly my server.
It seems my netbios or my broadcast configuration is incorrect.
3) I tried connect it from a MAC like a "anonym" with smb://192.168.0.10:1445.
The authentication windows appears but when I confirm MAC said that I have no the right or that there is not any share folder.
Code of my files:
My Xml configuration file:
<?xml version="1.0" standalone="no"?>
<jlanserver>
<servers>
<SMB/>
<noFTP/>
<noNFS/>
</servers>
<SMB>
<host name="serveur" domain="Workgroup">
<broadcast>255.255.0.0</broadcast>
<smbdialects>Core,LanMan,NT</smbdialects>
<netBIOSSMB sessionPort="1139" namePort="1137" datagramPort="1138" platforms="linux,solaris,macosx,windows"/>
<tcpipSMB platforms = "linux,macosx,windows,solaris" port = "1445"/>
<comment>SMB Android Server</comment>
</host>
<authenticator type="local">
<class>org.alfresco.jlan.server.auth.LocalAuthenticator</class>
<mode>USER</mode>
<Debug/>
<allowGuest/>
</authenticator>
<!-- Debug -->
<sessionDebug flags="Netbios,State,Negotiate,Tree,Transact,Echo"/>
<netbiosDebug/>
<announceDebug/>
</SMB>
<shares>
<diskshare name="ESPACE" comment="Dossier de Partage">
<driver>
<class>org.alfresco.jlan.smb.server.disk.JavaFileDiskDriver</class>
<LocalPath>/tmp</LocalPath>
</driver>
<size totalSize="2T" freeSize="100G"/>-->
<accessControl default="Write"/>
</diskshare>
</shares>
<security>
<authenticator type="local">
<class>org.alfresco.jlan.server.auth.LocalAuthenticator</class>
<mode>USER</mode>
<Debug/>
<allowGuest/>
</authenticator>
</security>
<shareMapper>
<class>org.alfresco.jlan.smb.server.DefaultShareMapper</class>
<debug/>
</shareMapper>
My Main Class:
(Launchserver and StopServer are called clicking buttons in my activity)
package archisoft.com.smbserverandroid;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.alfresco.jlan.app.XMLServerConfiguration;
import org.alfresco.jlan.smb.server.CIFSConfigSection;
import org.alfresco.jlan.smb.server.SMBServer;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Configuration extends ActionBarActivity {
public static final String TAG = "ServiceServerSMB";
private Button stopButton = null;
private Button startButton = null;
private XMLServerConfiguration srvConfig;
SMBServer MonServer;
// A la création
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "####### onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuration);
}
// Au redémarrage
#Override
public void onStart()
{
Log.d(TAG, "####### onStart");
super.onStart();
// On bind les boutons
startButton = (Button) findViewById(R.id.buttonStart);
stopButton = (Button) findViewById(R.id.buttonStop);
}
// Au retour sur l'activité
#Override
public void onResume()
{
Log.d(TAG, "####### onResume");
super.onResume();
}
// A l'arrêt
#Override
public void onStop()
{
Log.d(TAG, "####### onStop");
super.onStop();
}
#Override
public void onPause()
{
Log.d(TAG, "####### onPause");
super.onPause();
}
// Destruction
#Override
public void onDestroy() {
Log.d(TAG, "####### Destruction");
super.onDestroy();
}
// Appelé lorsque l'on clique sur "Start Server"
public void LaunchServer(View view)
{
Log.d(TAG, "####### Launch server");
try {
InputStream stream = getResources().openRawResource(R.raw.jlanconfiguration);
srvConfig = new XMLServerConfiguration();
srvConfig.loadConfiguration(new InputStreamReader(stream));
((CIFSConfigSection) srvConfig.getConfigSection(CIFSConfigSection.SectionName)).setDatagramPort(1138);
((CIFSConfigSection) srvConfig.getConfigSection(CIFSConfigSection.SectionName)).setNameServerPort(1137);
((CIFSConfigSection) srvConfig.getConfigSection(CIFSConfigSection.SectionName)).setSessionPort(1139);
CIFSConfigSection cifsConfig = (CIFSConfigSection) srvConfig.getConfigSection(CIFSConfigSection.SectionName);
MonServer = new SMBServer(srvConfig);
MonServer.startServer();
Log.d(TAG, "Lancement serveur");
} catch (Exception e) {
Log.e(TAG, "Erreur lancement serveur", e);
}
}
public void StopServer(View view)
{
Log.d(TAG, "####### StopServer");
MonServer.shutdownServer(true);
}
}
Thanks for all people who will try to help me.
Any advice would be welcome.
If you have any question, feel free to ask.
Best regards!
Anthony
You can see the shared folder in PC from android mobile by using jcifs which is cool please try this link pass your username and password and u can get all the shared folders by just one step smbFile.listfiles(). try it it worked for me.
Here's my situation: i have a server written with sails.js where i have a user model. I have a dashboard where i can see all the users, create new, delete them and so on...Now i want to create an android app where i can get, using socket.io, notification about the events that occour to the user model.
Example: if i delete a user from my dashboard i want the app to recive a notification from the server that the user has been deleted.
Here's my code for the app:
public class MainActivity extends Activity {
//socket instance
private Socket mSocket;
{
try {
mSocket = IO.socket("http://server_url:port/user");
} catch (URISyntaxException e) {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //set the layout for this activity
final TextView tv = (TextView) findViewById(R.id.textView);
mSocket.on("user", new Emitter.Listener() {
#Override
public void call(Object... args) {
tv.setVisibility(View.INVISIBLE);
}
});
mSocket.connect();
final Button btn_createUser = (Button)findViewById(R.id.button);
btn_createUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSocket.connected()) {
//tv.setVisibility(View.INVISIBLE);
}
}
});
}
}
Like i did with the dashboard to connect the socket to the server i did the same thing here, but it seems like the socket doesn't connect, in fact, when i delete a user from the dashboard i get no notification.
Here's the code (that works) i used in my dashboard to connect my socket to the server and listen to updates from the user model:
//connect to the server and listen to updates from user model
io.socket.get('/user', function(data, jwres) {
$scope.users = data;
$scope.$apply(); //write users in the table...
});
//wait for updates...
io.socket.on('user', function serverResponded (data) {
if(data.verb == "updated")
{
//get the user index in the array and update it
var index = getIndex(data.id, $scope.users);
$scope.users[index].online = data.data.online;
$scope.$apply();
}
if(data.verb == "destroyed")
{
//get the user index in the array and remove it
var index = getIndex(data.id, $scope.users);
$scope.users.splice(index, 1);
$scope.$apply();
}
if(data.verb == "created")
{
//simply update the array
$scope.users.push(data.data);
$scope.$apply();
}
});
Now, i think all i'm missing out in the android app is the GET request which automatically subscribe my socket to the model and get notified if something happen...but i don't know hot to do it.
I hope i was clear enough...thank to everyone who will answer me!
PS: i don't want to use AndroidAsync because i need the ultimate version of socket.io!
In case someone need it, i found the solution: https://github.com/balderdashy/sails/issues/2640 here you can find out how to solve the issue! :)
Dont get angry on me please. I have two questions, I think on very similar theme, so I decided to merge them into one. I have my app on android that is using sensors to do some calculations. I am storing there sesults in my database. What i want to do is to send my data from my phone to my desktop app also with a database (on button click).
To be more precise, here is an example: My light sensor reads current light intensity. Lets say it is 1000lux. Now, when I click my button "Send" in my android app, it will send this value to my desktop apps database. That desktop app will read that value and will show it to user.
Is it possible via WIFI? or better via web, so i will not be limited with distance?
How can android manage this kind of communication?
And my second question is, if controlling media player on my PC is similar to what i said.
EDIT:
I did some research and found one Socket tutorial. I tried it exactly like it is there. So i have this in my android app:
public class Client extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
Client myCli = new Client();
try {
myCli.run();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_client, menu);
return true;
}
public void run() throws Exception {
Socket mySkt = new Socket("192.168.1.6", 9999);
PrintStream myPS = new PrintStream(mySkt.getOutputStream());
myPS.println("Hello server");
BufferedReader myBR = new BufferedReader
(new InputStreamReader(mySkt.getInputStream()));
}
}
and this in netBeans:
//Author: WarLordTech
//Website: http://www.youtube.com/user/WarLordTech
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception{
Server myServ = new Server();
myServ.run();
}
public void run() throws Exception{
ServerSocket mySS = new ServerSocket(9999);
Socket SS_accept = mySS.accept();
BufferedReader SS_BF= new BufferedReader(new InputStreamReader
(SS_accept.getInputStream()));
String temp = SS_BF.readLine();
System.out.println(temp);
if (temp!=null) {
PrintStream SSPS = new PrintStream(SS_accept.getOutputStream());
SSPS.println("Got something");
}
}
}
It still isnt workiong. Do I have to set up my network somehow?
You could do it using TCP Sockets. Many languages have implementations for Socket programming so you would "need" to program your desktop app in Java (of course that is always possible!).
Socket Tutorial in Java
This would work over the net and local wifi. You could use other methods for local wifi such as a UDP connection. You'd need to setup a TCP server and make sure you had access etc.
There may be other ways to do this but it's not such a trivial task to do!