I have written two programs and i want both of these to run on my android device which are on the same network but one which is simple client server program it will run on both device and connection will be made...But Unity Master Server will not run fine and not able to connect two android wifi device which are on the same network and this program will run fine on localhost.
Here is simple client server code..This code run fine
var object:Transform;
static var Isconnected:boolean=false;
//172.16.11.4
function Start()
{
Application.runInBackground = true;
Debug.Log("run in back groud");
}
function Update()
{
if(Isconnected)
var temp:Transform;
temp=Instantiate(object,transform.position, transform.rotation);
}
function OnGUI()
{
if(Network.peerType==NetworkPeerType.Disconnected)
{
if(GUILayout.Button(" Initlized server"))
{
var useNat = !Network.HavePublicAddress();
Network.InitializeServer(32,25001,useNat);
Debug.Log("Server has been Initlized");
}
}
if(GUILayout.Button("connect to server"))
{
Network.Connect("172.16.11.4",25001);
}
}
function OnConnectedToServer() {
Debug.Log("Connected to server");
Isconnected=true;
// Send local player name to server ...
}
But this code will not run on wifi...WHile this code run on localhost if we give the ip 127.0.0.1
#pragma strict
private var rotAngle : float = 0;
private var pivotPoint : Vector2;
var Gamename:String="MyGame";
var refreshing:boolean=false;
private var hostdata:HostData[];
function Start () {
}
function Update () {
var farword=Input.GetKey("up");
if(farword==true)
{
//animation.Play("ArmatureAction");
}
transform.Translate(0,0,Input.GetAxis("Vertical"));
transform.Rotate(0,Input.GetAxis("Horizontal"),0);
if(refreshing)
{
if(MasterServer.PollHostList().Length>0)
{
refreshing=false;
hostdata=MasterServer.PollHostList();
Debug.Log(MasterServer.PollHostList().Length);
}
}
}
function startServer()
{
Network.InitializeServer(32,25001,!Network.HavePublicAddress);
MasterServer.RegisterHost(Gamename,"THis is tutorial","THis is tutorial game");
}
function OnServerInitialized()
{
Debug.Log("Sever is initlized");
}
function OnMasterServerEvent(mgs:MasterServerEvent)
{
if(mgs==MasterServerEvent.RegistrationSucceeded)
{
Debug.Log("Register server");
}
}
function refreshHostList(){
MasterServer.RequestHostList(Gamename);
refreshing=true;
}
function OnGUI()
{
if((!Network.isClient && !Network.isServer))
{
if(GUI.Button(Rect(100,100,100,100),"Start Sever"))
{
Debug.Log("Start Server");
startServer();
}
if(GUI.Button(Rect(100,220,100,100),"Refresg Hosts"))
{
Debug.Log("Refresh HOsts");
refreshHostList();
}
if(hostdata)
{
for(var i:int=0;i<hostdata.length;i++)
{
if(GUI.Button(Rect(230,100,100,100),hostdata[i].gameName))
{
Network.Connect("172.16.11.4",25001);
}
}
}
}
if(GUI.Button(Rect(300,300,100,100),"back"))
{
transform.Translate(9,0,0);
}
if(GUI.Button(Rect(300,400,100,100),"farword"))
{
transform.Translate(-9,0,0);
}
}
Any help
I think in second code
if(hostdata)
{
for(var i:int=0;i<hostdata.length;i++)
{
if(GUI.Button(Rect(230,100,100,100),hostdata[i].gameName))
{
Network.Connect("172.16.11.4",25001);
}
}
need to change
if(hostdata)
{
for(var i:int=0;i<hostdata.length;i++)
{
if(GUI.Button(Rect(230,100,100,100),hostdata[i].gameName))
{
Network.Connect(hostdata[i]); //Or Network.Connect( hostdata[i].ip[ 0 ], hostdata[i].port );
}
}
And also your buttons will overlay themselves. (if more than 1 server initialized and found). You need to create Rect with dynamic start height value. Like:
if(hostdata)
{
var y = 100; // or other start y position like 0
for(var i:int=0;i<hostdata.length;i++)
{
if(GUI.Button(Rect(230,y,100,100),hostdata[i].gameName))
{
Network.Connect(hostdata[i]); //Or Network.Connect( hostdata[i].ip[ 0 ], hostdata[i].port );
}
y+=100+ 5 //Some padding.
}
if any problems occurs like can not connect the server keep in mind NAT punchthrough generally cause problems.
Related
I am trying to make an alarm notification and I want it to repeat when this 2 radio buttons are active.
I have this code :
private void Button_Clicked(object sender, EventArgs e) {
if (Radio_Msg.IsChecked) {
CrossToastPopUp.Current.ShowToastWarning("Alarme");
}
if (Radio_Notif.IsChecked) {
CrossLocalNotifications.Current.Show("Miguel", "Módulo 19 – Tecnologias de Acesso a Base de Dados");
}
if (Radio_Msg.IsChecked && RadioRepetir == true) {
CrossToastPopUp.Current.ShowToastMessage("Tesddddte");
Thread.Sleep(500);
CrossToastPopUp.Current.ShowToastMessage("Teste");
}
}
But it doesn't repeat it, it only prints one notification out.
if(Radio_Msg.IsChecked && RadioRepetir == true)
{
var minutes = TimeSpan.FromMinutes(0.2);
Device.StartTimer(minutes, () => {
CrossToastPopUp.Current.ShowToastWarning("Alarme");
return true;
});
I've been using flutter Blue for some now and I'm stuck on the following:
I'm using the example App I downloaded on https://github.com/pauldemarco/flutter_blue, through here the basic idea is that as soon as I connect to my bluetooth device it starts checking if the service "FFE0" exists and then the characteristic "FFE1".
This Characteristic spits out random strings I need for my project.
Image of screen with characteristic open
Through the screen I can see the above is true I just need to somehow automatically set notifications for the characteristic as soon as it connects to the bluetooth device.
This is some current code i'm testing out in the _Connect Function.
_connect(BluetoothDevice d) async {
device = d;
// Connect to device
deviceConnection = _flutterBlue
.connect(device, timeout: const Duration(seconds: 4))
.listen(
null,
onDone: _disconnect,
);
// Update the connection state immediately
device.state.then((s) {
setState(() {
deviceState = s;
});
});
// Subscribe to connection changes
deviceStateSubscription = device.onStateChanged().listen((s) {
setState(() {
deviceState = s;
});
if (s == BluetoothDeviceState.connected) {
device.discoverServices().then((service) {
service.forEach((_service){
var characteristics = _service.characteristics;
_service.characteristics.map((c) {
print(c);
});
for(BluetoothCharacteristic _characteristic in characteristics) {
device.readCharacteristic(_characteristic).then((_value){
print(_value);
if (_value.contains("FFE0")) {
print("Found!!");
// do something
}
});
}
});
setState(() {
services = service;
});
_getServices();
});
}
});
}
I maybe someone has a suggestion on how to approach my problem.
Robin
I found https://github.com/Sensirion/smart-gadget-flutter/tree/master/lib and I was able to fix my problem using the following code:
for(BluetoothService service in services) {
for(BluetoothCharacteristic c in service.characteristics) {
if(c.uuid == new Guid("0000ffe1-0000-1000-8000-00805f9b34fb")) {
_setNotification(c);
} else {
print("Nope");
}
}
}
This was added in the _connect function.
_connect(BluetoothDevice d) async {
device = d;
// Connect to device
deviceConnection = _flutterBlue
.connect(device, timeout: const Duration(seconds: 4))
.listen(
null,
onDone: _disconnect,
);
// Update the connection state immediately
device.state.then((s) {
setState(() {
deviceState = s;
});
});
// Subscribe to connection changes
deviceStateSubscription = device.onStateChanged().listen((s) {
setState(() {
deviceState = s;
});
if (s == BluetoothDeviceState.connected) {
device.discoverServices().then((s) {
services = s;
for(BluetoothService service in services) {
for(BluetoothCharacteristic c in service.characteristics) {
if(c.uuid == new Guid("0000ffe1-0000-1000-8000-00805f9b34fb")) {
_setNotification(c);
} else {
print("Nope");
}
}
}
setState(() {
services = s;
});
_getServices();
});
}
});
}
I'm using the following code to show a message when there is no network. It works well when testing the app in airplane mode. However, it always shows the popup even when there is network when the app code start (rejection.status === 0). How to workaround it?
.config(function($provide, $httpProvider) {
$provide.factory('httpInterceptor', function($q, $injector) {
return {
response: function(response) {
return response || $q.when(response);
},
responseError: function(rejection) {
var interactiveService = $injector.get('interactiveService');
if (rejection.status === 0 || rejection.status === -1) {
interactiveService.showPopup('The internet is disconnected on your device.' + rejection.status);
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('httpInterceptor');
})
If it helps try this
.config(function($provide, $httpProvider) {
$provide.factory('httpInterceptor', function($q, $injector) {
return {
response: function(response) {
return response || $q.when(response);
},
responseError: function(rejection) {
var interactiveService = $injector.get('interactiveService');
/************** New code starts*******/
var networkState = navigator.connection.type;
if(networkState === Connection.NONE){
interactiveService.showPopup('The internet is disconnected on your device.' + rejection.status);
}
/************** New code ends*******/
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('httpInterceptor');
})
I am working on a ionic project and trying to use LokiJS. Below is my code,
controller,
$scope.test ={birthdays:[]};
$ionicPlatform.ready(function() {
BirthdayService.initDB();
BirthdayService.getAllBirthdays().then(function(birthdays){
console.log("birthdays=",birthdays);// gives empty array second run...
//var bday1 = {Name:"abrj",Date:new Date()};
//var bday2 = {Name:"abrj2",Date:new Date()};
//BirthdayService.addBirthday(bday1);
//BirthdayService.addBirthday(bday2); added birthdays during the first run.
});
});
I am using cordova-fs-adapter and cordova-file-plugin.
below is my service for adapter integration,
(function() {
angular.module('starter').factory('BirthdayService', ['$q', 'Loki', BirthdayService]);
function BirthdayService($q, Loki) {
var _db;
var _birthdays;
function initDB() {
var fsAdapter = new LokiCordovaFSAdapter({"prefix": "loki"});
_db = new Loki('birthdaysDB',
{
autosave: true,
autosaveInterval: 1000, // 1 second
adapter: fsAdapter
});
};
function getAllBirthdays() {
return $q(function (resolve, reject) {
var options = {
birthdays: {
proto: Object,
inflate: function (src, dst) {
var prop;
for (prop in src) {
if (prop === 'Date') {
dst.Date = new Date(src.Date);
} else {
dst[prop] = src[prop];
}
}
}
}
};
_db.loadDatabase(options, function () {
_birthdays = _db.getCollection('birthdays');
if (!_birthdays) {
_birthdays = _db.addCollection('birthdays');
}
resolve(_birthdays.data);
});
});
};
function addBirthday(birthday) {
console.log("Birthdays=",_birthdays);
_birthdays.insert(birthday);
};
function updateBirthday(birthday) {
_birthdays.update(birthday);
};
function deleteBirthday(birthday) {
_birthdays.remove(birthday);
};
return {
initDB: initDB,
getAllBirthdays: getAllBirthdays,
addBirthday: addBirthday,
updateBirthday: updateBirthday,
deleteBirthday: deleteBirthday
};
}
})();
In first run I am inserting two documents into the birthdays collections.On second run when I trying to check whether they have persisted, they weren't. I know I am doing something wrong.Do suggest.Local storage also gets cleared everytime i rerun(ionic run android)?!
I want to traverse through each file in the SD card inside all the directories and sub directories using the FILE API of phonegap (which is the w3c file api actually). I have to perform a certain set of operations on these files by looking at their nature. I donot want to search for specific types of files, but traverse through each file in a sequential manner.
Can someone please help me with this? Just a basic loop framework with the necessary requirements for the traversal would be a great help.
Thank You in advance.
I think the following code should work:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystem, fail);
function onRequestFileSystem(fileSystem) {
var directoryReader = fileSystem.root.createReader();
directoryReader.readEntries(onReadEntries, fail);
}
function onReadEntries(entries) {
var i;
for (i = 0; i < entries.length; i++) {
if (entries[i].isFile == true) {
// ...
}
if (entries[i].isDirectory == true) {
var directoryReader = entries[i].fullPath.createReader();
directoryReader.readEntries(onReadEntries, fail);
}
}
}
http://www.c-sharpcorner.com/UploadFile/e83792/filesystem-directoryentry-objects-in-phonegap/
scan : function(url,fileType,callback)
{
var fileTypeCollection = [];
var defer = $q.defer();
url.forEach(function(element, index)
{
//requestLocalFileSystemURL
log(element);
window.resolveLocalFileSystemURL(element,onRequestFileSystem, fail);
log("Ends resolve");
});
function onRequestFileSystem(fileSystem)
{
var directoryReader = fileSystem.createReader();
directoryReader.readEntries(onReadEntries,fail);
} /*onRequestFile Ends*/
function onReadEntries(entries)
{
if(entries.length==0)
{
log("Entries Length....Resolving");
defer.resolve(fileTypeCollection);
}
else
{
entries.forEach( function(element, index)
{
if (element.isDirectory === true)
{
// Recursive -- call back into this subdirectory
onRequestFileSystem(element);
}
if(element.isFile == true)
{
fileType.forEach(function(type)
{
if(element.name.indexOf(type) != -1)
{
fileTypeCollection.push(element);
}
});
} /*is File ENds*/
}); /*Entries For Each Ends*/
}
} /*OnRead Ends*/
function fail(resp)
{
log(resp);
defer.reject();
} /*Fail Ends*/
return defer.promise;
} //Scan Function Ends
try this. remove the promises if u wish and use a callback.promises is kind of broken. if you can fix then its ok else use a callback after push for FileType