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()
}
}
Related
I was trying to add sip incoming calls with linphone sdk, The registration is successful and I can make out going calls and the call status is logging as expected, but I am not able to receive incoming calls. I am using intent service to handle connection.
Here is my code:
protected void onHandleIntent(Intent intent) {
String sipAddress = intent.getStringExtra("address");
String password = intent.getStringExtra("password");
final LinphoneCoreFactory lcFactory = LinphoneCoreFactory.instance();
// First instantiate the core Linphone object given only a listener.
// The listener will react to events in Linphone core.
try {
lc = lcFactory.createLinphoneCore(new LinphoneCoreListenerBase() {
#Override
public void callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State state, String message) {
super.callState(lc, call, state, message);
Log.i(TAG, "callState: ");
}
}, getApplication());
} catch (LinphoneCoreException e) {
e.printStackTrace();
}
lc.setUserAgent("Test app", "1.0");
try {
LinphoneAddress address = lcFactory.createLinphoneAddress(sipAddress);
String username = address.getUserName();
String domain = address.getDomain();
if (password != null) {
lc.addAuthInfo(lcFactory.createAuthInfo(username, password, null, domain));
}
// create proxy config
LinphoneProxyConfig proxyCfg = lc.createProxyConfig(sipAddress, domain, null, true);
proxyCfg.setExpires(2000);
lc.addProxyConfig(proxyCfg); // add it to linphone
lc.setDefaultProxyConfig(proxyCfg);
running = true;
while (running) {
lc.iterate(); // first iterate initiates registration
sleep(20);
}
} catch (LinphoneCoreException e) {
e.printStackTrace();
}
}
What is wrong with my code?
As the IntentService document (https://developer.android.com/reference/android/app/IntentService) stated:
the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
I think you should not put the listener in an IntentService. Instead, put it in a long running Service so that the listener can actually keep staying there to receive events.
Below is the sketch of my Simblee :
#include <SimbleeBLE.h>
void setup() {
Serial.begin(9600);
Serial.println("Waiting for connection...");
SimbleeBLE.deviceName = "Simblee";
SimbleeBLE.advertisementData = "data";
// SimbleeBLE.customUUID = "2220";
SimbleeBLE.advertisementInterval = MILLISECONDS(300);
SimbleeBLE.txPowerLevel = -20; // (-20dbM to +4 dBm)
SimbleeBLE.begin();
}
void loop() {
}
void SimbleeBLE_onConnect()
{
Serial.println("Simblee Connected");
}
void SimbleeBLE_onDisconnect()
{
Serial.println("Simblee Disconnected");
}
void SimbleeBLE_onReceive(byte *data, int len)
{
Serial.println("Data received");
SimbleeBLE.send(1);
printf("%s\n", data);
}
void serialEvent()
{
Serial.println("Serial event");
}
I can easily connect and read data from it, bit writing to it doesn't work from my app. SimbleeBLE_onReceive is never being called.
It actually never is called even when using third party BLE apps like nRF Connect and BLE Terminal.
So I'm suspecting that the issue is with my arduino Sketch and not related to the android code.
The android code is returning GATT_ERROR 133 when trying to write.
Is anything missing from this code ? Strangely I can't find any example online where we're simply sending data to Simblee (without using SimlbeeMobile)
Thanks,
Try changing your onReceive signature to:
void SimbleeBLE_onReceive(char *data, int len)
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! :)
I am using Codenameone and ZXing to read a QRCode. When I call the Scanner, my mobile opens the QRCode reader application and I get to read the QRCode except that when android takes me back to my app it goes through init then start statuses. Which moves me back to the login form of my application instead of continuing filling the form that I was in.
Any help on what to do to stay in the same form? Is there something I'm doing wrong? Thanks in advance.
EverproX.addMessage("Before Scan\n");
CodeScanner.getInstance().scanQRCode(new ScanResult() {
public void scanCompleted(String contents, String formatName, byte[] rawBytes) {
EverproX.addMessage("Scan Completed "+contents);
}
public void scanCanceled() {
EverproX.addMessage("Scan Cancelled");
}
public void scanError(int errorCode, String message) {
EverproX.addMessage("Scan Error "+errorCode+" "+message);
}
});
EverproX can be seen as a log class.
By analyzing our log we can say that as soon as we call the CodeScanner.getInstance().scanQRCode() the application is called for 'Destroy'. Then after the scanning is done it goes again through the init and start. It never goes into the scanComplete scanCanceled or scanError Callbacks.
Is it normal that the App is destroyed upon call of CodeScanner? Many thanks.
Inside your codenameone project, you should find a class named (for example MyApp.java) based on your app's name, modify the code to read something like similar to this:
public class MyApp {
private Form current;
public void init(Object context) {
// Pro users - uncomment this code to get crash reports sent to you automatically
Display.getInstance().addEdtErrorHandler(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
evt.consume();
Log.p("Exception in AppName version " + Display.getInstance().getProperty("AppVersion", "Unknown"));
Log.p("OS " + Display.getInstance().getPlatformName());
Log.p("Error " + evt.getSource());
Log.p("Current Form " + Display.getInstance().getCurrent().getName());
Log.e((Throwable) evt.getSource());
Log.sendLog();
}
});
}
public void start() {
if (current != null) {
current.show();
return;
}
new StateMachine("/theme");
}
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
current = null;
}
}
I am trying to synchronize my CouchDB with my android in a way that it works as good offline as online and as far as I understand the .continues(true/false) is the way to go for this. But is there some way to actually change it on runtime some way? I am thinking of having a BroadcastReciever listening to if there is any CONNECTIVITY_SERVICE and set the value of .continues() accordingly but I can't get it to work... any suggestions?
protected void startEktorp() {
httpClient = new TouchDBHttpClient(server);
dbInstance = new StdCouchDbInstance(httpClient);
HamsterSyncEktorpAsyncTask startupTask = new HamsterSyncEktorpAsyncTask() {
#Override
protected void doInBackground() {
// create a local database
dbConnector = dbInstance.createConnector(DATABASE_NAME, true);
}
#Override
protected void onSuccess() {
// Create the query and get the results
queryDB();
// Start doing the replications!
startReplications();
}
};
startupTask.execute();
}
public synchronized void queryDB() {
ViewQuery viewQuery = new ViewQuery()
.designDocId("_design/" + dDocName).viewName(viewName)
.reduce(false).includeDocs(true);
ViewResult viewResult = dbConnector.queryView(viewQuery);
Log.v("SUCCESS", viewResult.getRows().toString());
notifyHandlers(viewResult);
}
/**
* Replicates the database from server to the phone and vice versa.
*/
public void startReplications() {
// pull this database to the test replication server
pullCommand = new ReplicationCommand.Builder().source(DATABASE_PATH)
.target(DATABASE_NAME).continuous(true).build();
pushCommand = new ReplicationCommand.Builder().source(DATABASE_NAME)
.target(DATABASE_PATH).continuous(true).build();
HamsterSyncEktorpAsyncTask pushReplicaton = new HamsterSyncEktorpAsyncTask() {
#Override
protected void doInBackground() {
dbInstance.replicate(pullCommand);
ReplicationStatus status = dbInstance.replicate(pushCommand);
Log.e(TAG, status.getSessionId().toString());
}
};
pushReplicaton.execute();
}
I am also wondering if there are any way to know if and when the replication actually sent/got something new and update my listview in the app showing all the documents in my database (the queryDB() function)?