Different value from the same child in Firebase Unity - c#

When I start game in the Unity Editor, I get the float value from the DB (Realtime DB Firebase) and pring it in the console.
Problem: the value sometimes is different. When in the DB it's 1, I am getting 4 from the DB. I run TryDownloadData method to download the data and print it.
The DB structure is very simple:
{
"users" : {
"5bf700187027d43cc8295afb69cc4495aecff695" : {
"gravitationalAcceleration" : -9.8100004196167
}
}
}
User class:
public class User
{
public float gravitationalAcceleration;
public User(float gravitationalAcceleration)
{
this.gravitationalAcceleration = gravitationalAcceleration;
}
}
And finally the class that connects to the DB and gets the gravitationalAcceleration value.
public class Firebase : MonoBehaviour
{
private string userID;
private DatabaseReference dbReference;
private void Awake()
{
userID = SystemInfo.deviceUniqueIdentifier;
dbReference = FirebaseDatabase.DefaultInstance.RootReference;
StartCoroutine(TryDownloadData());
}
public void CreateUser()
{
User user = new User(Physics.gravity.y);
string json = JsonUtility.ToJson(user);
dbReference.Child("users").Child(userID).SetRawJsonValueAsync(json);
print("New user created");
}
public void TrySendData(User user)
{
StartCoroutine(SendData(user));
}
private IEnumerator SendData(User user)
{
string json = JsonUtility.ToJson(user);
var task = dbReference.Child("users").Child(userID).SetRawJsonValueAsync(json);
yield return new WaitUntil(() => task.IsCompleted);
if (task.Exception != null)
{
print("Exception uploading data!");
print(task.Exception);
}
print("Data sent!");
}
private IEnumerator TryDownloadData()
{
var task = dbReference.Child("users").GetValueAsync();
yield return new WaitUntil(() => task.IsCompleted);
if (task.Exception != null)
{
print("Exception while downloading data!");
print(task.Exception);
}
if (task.Result.Value == null)
{
print("No info from DB");
CreateUser();
}
else
{
print("Got Data!");
DataSnapshot snapshot = task.Result;
if (snapshot.Child(userID).Exists)
{
var val = float.Parse(snapshot.Child(userID).Child("gravitationalAcceleration").Value.ToString());
Debug.Log("User exists. The value " + val);
}
else
{
Debug.Log("User does not exist");
CreateUser();
}
}
}
}

You need to initialize the firebase. After that it started working ok! (returning correct values)
private string userID;
private DatabaseReference dbReference;
private void Start()
{
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
{
if (task.Exception != null)
{
Debug.Log("Init Exception! " + task.Exception);
return;
}
userID = SystemInfo.deviceUniqueIdentifier;
dbReference = FirebaseDatabase.DefaultInstance.RootReference;
//OnInit?.Invoke();
Debug.Log("Firebase initialized!");
TryLogin();
});
}

Related

Xamarin unable get instance from async

I've written a Xamarin.Forms Application that connects to an ESP32 via Bluetooth. Now I'd like to get a value from a CustomControl.JoystickControl from the MainPage.xaml Page.
I've tried it like that:
MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
public static Bluetooth.IBth bth = new Bluetooth.Bth();
public MainPage()
{
InitializeComponent();
Task.Run(async () => bth.Start("mecanumWheelRobot", 200, false));
}
public CustomControls.JoystickControl JoystickControlElement
{
get { return JoystickControl; }
}
public CustomControls.JoystickControl JoystickControlElement1
{
get { return JoystickControl1; }
}
}
Now I'd like to get the JoystickControlElement from the following Async Function:
var mainpage = new Views.MainPage();
string test = mainpage.test;
(these two lines are the problem)
class Bth : IBth
{
private CancellationTokenSource _ct { get; set; }
const int RequestResolveError = 1000;
public Bth()
{
}
public void Start(string name, int sleepTime = 200, bool readAsCharArray = false)
{
Task.Run(async () => loop(name, sleepTime, readAsCharArray));
}
private async Task loop(string name, int sleepTime, bool readAsCharArray)
{
BluetoothDevice device = null;
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
BluetoothSocket BthSocket = null;
_ct = new CancellationTokenSource();
while (_ct.IsCancellationRequested == false)
{
try
{
Thread.Sleep(sleepTime);
adapter = BluetoothAdapter.DefaultAdapter;
if (adapter == null)
System.Diagnostics.Debug.WriteLine("No Bluetooth adapter found.");
else
System.Diagnostics.Debug.WriteLine("Adapter found!!");
if (!adapter.IsEnabled)
System.Diagnostics.Debug.WriteLine("Bluetooth adapter is not enabled.");
else
System.Diagnostics.Debug.WriteLine("Adapter enabled!");
System.Diagnostics.Debug.WriteLine("Try to connect to " + name);
foreach (var bd in adapter.BondedDevices)
{
System.Diagnostics.Debug.WriteLine("Paired devices found: " + bd.Name.ToUpper());
if (bd.Name.ToUpper().IndexOf(name.ToUpper()) >= 0)
{
System.Diagnostics.Debug.WriteLine("Found " + bd.Name + ". Try to connect with it!");
device = bd;
break;
}
}
if (device == null)
{
System.Diagnostics.Debug.WriteLine("Named device not found.");
MainThread.BeginInvokeOnMainThread(() =>
{
// Code to run on the main thread
});
}
else
{
UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
if ((int)Android.OS.Build.VERSION.SdkInt >= 10) // Gingerbread 2.3.3 2.3.4
BthSocket = device.CreateInsecureRfcommSocketToServiceRecord(uuid);
else
BthSocket = device.CreateRfcommSocketToServiceRecord(uuid);
if (BthSocket != null)
{
//Task.Run ((Func<Task>)loop); /*) => {
await BthSocket.ConnectAsync();
if (BthSocket.IsConnected)
{
MainThread.BeginInvokeOnMainThread(() =>
{
service.toast.toastSuccess("Connected!");
// Code to run on the main thread
//pages.bluetoothBarcodeScan.connectedScanner();
});
System.Diagnostics.Debug.WriteLine("Connected!");
MainThread.BeginInvokeOnMainThread(() =>
{
service.toast.toastSuccess("Writing!");
// Code to run on the main thread
//
});
while (_ct.IsCancellationRequested == false)
{
var mainpage = new Views.MainPage();
string test = mainpage.test;
var bytes = Encoding.ASCII.GetBytes("{test}-");
BthSocket.OutputStream.Write(bytes, 0, bytes.Length);
Thread.Sleep(100);
}
System.Diagnostics.Debug.WriteLine("Exit the inner loop");
}
}
else
System.Diagnostics.Debug.WriteLine("BthSocket = null");
}
}
catch(Exception ex)
{
service.toast.toastSuccess(ex.Message);
}
finally
{
if (BthSocket != null)
BthSocket.Close();
device = null;
adapter = null;
}
}
System.Diagnostics.Debug.WriteLine("Exit the external loop");
}
public void Cancel()
{
if (_ct != null)
{
System.Diagnostics.Debug.WriteLine("Send a cancel to task!");
_ct.Cancel();
MainThread.BeginInvokeOnMainThread(() =>
{
service.toast.toastError("Disconnected");
// Code to run on the main thread
});
}
}
public async Task<string> GetData()
{
var mainpage = new Views.MainPage();
string test = mainpage.test;
return "1";
}
public ObservableCollection<string> PairedDevices()
{
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
ObservableCollection<string> devices = new ObservableCollection<string>();
foreach (var bd in adapter.BondedDevices)
devices.Add(bd.Name);
return devices;
}
#endregion
}
The async function always starts new when it comes to this line.
How should I get the variable?
You can change your constructor method like:
public Bth(string txt)
{}
And then pass the mainpage.test like:
public static Bluetooth.IBth bth = new Bluetooth.Bth(txt);

C# call function from async false result [duplicate]

I've written a Xamarin.Forms Application that connects to an ESP32 via Bluetooth. Now I'd like to get a value from a CustomControl.JoystickControl from the MainPage.xaml Page.
I've tried it like that:
MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
public static Bluetooth.IBth bth = new Bluetooth.Bth();
public MainPage()
{
InitializeComponent();
Task.Run(async () => bth.Start("mecanumWheelRobot", 200, false));
}
public CustomControls.JoystickControl JoystickControlElement
{
get { return JoystickControl; }
}
public CustomControls.JoystickControl JoystickControlElement1
{
get { return JoystickControl1; }
}
}
Now I'd like to get the JoystickControlElement from the following Async Function:
var mainpage = new Views.MainPage();
string test = mainpage.test;
(these two lines are the problem)
class Bth : IBth
{
private CancellationTokenSource _ct { get; set; }
const int RequestResolveError = 1000;
public Bth()
{
}
public void Start(string name, int sleepTime = 200, bool readAsCharArray = false)
{
Task.Run(async () => loop(name, sleepTime, readAsCharArray));
}
private async Task loop(string name, int sleepTime, bool readAsCharArray)
{
BluetoothDevice device = null;
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
BluetoothSocket BthSocket = null;
_ct = new CancellationTokenSource();
while (_ct.IsCancellationRequested == false)
{
try
{
Thread.Sleep(sleepTime);
adapter = BluetoothAdapter.DefaultAdapter;
if (adapter == null)
System.Diagnostics.Debug.WriteLine("No Bluetooth adapter found.");
else
System.Diagnostics.Debug.WriteLine("Adapter found!!");
if (!adapter.IsEnabled)
System.Diagnostics.Debug.WriteLine("Bluetooth adapter is not enabled.");
else
System.Diagnostics.Debug.WriteLine("Adapter enabled!");
System.Diagnostics.Debug.WriteLine("Try to connect to " + name);
foreach (var bd in adapter.BondedDevices)
{
System.Diagnostics.Debug.WriteLine("Paired devices found: " + bd.Name.ToUpper());
if (bd.Name.ToUpper().IndexOf(name.ToUpper()) >= 0)
{
System.Diagnostics.Debug.WriteLine("Found " + bd.Name + ". Try to connect with it!");
device = bd;
break;
}
}
if (device == null)
{
System.Diagnostics.Debug.WriteLine("Named device not found.");
MainThread.BeginInvokeOnMainThread(() =>
{
// Code to run on the main thread
});
}
else
{
UUID uuid = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
if ((int)Android.OS.Build.VERSION.SdkInt >= 10) // Gingerbread 2.3.3 2.3.4
BthSocket = device.CreateInsecureRfcommSocketToServiceRecord(uuid);
else
BthSocket = device.CreateRfcommSocketToServiceRecord(uuid);
if (BthSocket != null)
{
//Task.Run ((Func<Task>)loop); /*) => {
await BthSocket.ConnectAsync();
if (BthSocket.IsConnected)
{
MainThread.BeginInvokeOnMainThread(() =>
{
service.toast.toastSuccess("Connected!");
// Code to run on the main thread
//pages.bluetoothBarcodeScan.connectedScanner();
});
System.Diagnostics.Debug.WriteLine("Connected!");
MainThread.BeginInvokeOnMainThread(() =>
{
service.toast.toastSuccess("Writing!");
// Code to run on the main thread
//
});
while (_ct.IsCancellationRequested == false)
{
var mainpage = new Views.MainPage();
string test = mainpage.test;
var bytes = Encoding.ASCII.GetBytes("{test}-");
BthSocket.OutputStream.Write(bytes, 0, bytes.Length);
Thread.Sleep(100);
}
System.Diagnostics.Debug.WriteLine("Exit the inner loop");
}
}
else
System.Diagnostics.Debug.WriteLine("BthSocket = null");
}
}
catch(Exception ex)
{
service.toast.toastSuccess(ex.Message);
}
finally
{
if (BthSocket != null)
BthSocket.Close();
device = null;
adapter = null;
}
}
System.Diagnostics.Debug.WriteLine("Exit the external loop");
}
public void Cancel()
{
if (_ct != null)
{
System.Diagnostics.Debug.WriteLine("Send a cancel to task!");
_ct.Cancel();
MainThread.BeginInvokeOnMainThread(() =>
{
service.toast.toastError("Disconnected");
// Code to run on the main thread
});
}
}
public async Task<string> GetData()
{
var mainpage = new Views.MainPage();
string test = mainpage.test;
return "1";
}
public ObservableCollection<string> PairedDevices()
{
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
ObservableCollection<string> devices = new ObservableCollection<string>();
foreach (var bd in adapter.BondedDevices)
devices.Add(bd.Name);
return devices;
}
#endregion
}
The async function always starts new when it comes to this line.
How should I get the variable?
You can change your constructor method like:
public Bth(string txt)
{}
And then pass the mainpage.test like:
public static Bluetooth.IBth bth = new Bluetooth.Bth(txt);

How to wait for methods to finish then do new action?

I'm setting up my architechture to use Cef.Offscreen. In order to make it easy to work with I have divided some parts. But I run into a problem that controller loading finshes and serves a view before everything has been able to load.
Here's my structure --> Controller
public ActionResult InitBrowser()
{
ICefSharpRenderer renderer = RendererSingelton.GetInstance();
//Try to render something in default appdomain
renderer.LoginToTradingView(null, null);
ViewBag.SiteTitle = BrowserActions.RunScriptInNamedBrowser("loginbrowser", #"(function() {return document.title;} )();");
ViewBag.ImagesixtyfourUrl = BrowserActions.TakeScreenshot("loginbrowser");
//this is returned to fast, we have to wait for all
return View();
}
I have this class to get do some basic actions and initialize if needed.
public class CefSharpRenderer : MarshalByRefObject, ICefSharpRenderer
{
private ChromiumWebBrowser _browser;
private TaskCompletionSource<JavascriptResponse> _taskCompletionSource;
private string _name;
public void LoginToTradingView(string url, string browserName)
{
CheckIfCefIsInitialized();
BrowserFactory.GetBrowserInstance(#"https://se.tradingview.com/", "loginbrowser");
}
public void CreateBrowserAndGoToUrl(string url, string browserName)
{
CheckIfCefIsInitialized();
BrowserFactory.GetBrowserInstance(url, "browserName");
}
public void CheckIfCefIsInitialized()
{
if (!Cef.IsInitialized)
{
var settings = new CefSettings();
var assemblyPath = Path.GetDirectoryName(new Uri(GetType().Assembly.CodeBase).LocalPath);
settings.BrowserSubprocessPath = Path.Combine(assemblyPath, "CefSharp.BrowserSubprocess.exe");
settings.ResourcesDirPath = assemblyPath;
settings.LocalesDirPath = Path.Combine(assemblyPath, "locales");
var osVersion = Environment.OSVersion;
//Disable GPU for Windows 7
if (osVersion.Version.Major == 6 && osVersion.Version.Minor == 1)
{
// Disable GPU in WPF and Offscreen examples until #1634 has been resolved
settings.CefCommandLineArgs.Add("disable-gpu", "1");
}
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: false, cefApp: null);
}
}
}
I get my browserinstance here and connected the events to be fired.
public static class BrowserFactory
{
public static ChromiumWebBrowser GetBrowserInstance(string _url, string browsername)
{
if (!BrowserContainer.CheckIfBrowserExists(browsername))
{
ChromiumWebBrowser _browser = new ChromiumWebBrowser(_url);
_browser.LoadingStateChanged += BrowserEvents.OnLoadingStateChanged;
BrowserContainer.AddDataHolder(browsername, new DataBrowserHolder { BrowserName = browsername, ChromiumWebBrow = _browser });
return _browser;
}
return null;
}
}
Browserevent loads correct page.
public static class BrowserEvents
{
public static void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
if (args.IsLoading == false)
{
ChromiumWebBrowser cwb = (ChromiumWebBrowser)sender;
if (cwb.Address == "https://se.tradingview.com/")
{
BrowserActions.LogInToTradingView("xxxxx", "yyyyyyy", "loginbrowser");
}
}
}
}
Last my browseractions, spare med for the thread sleeps it's just under construction and it works atm.
public static class BrowserActions
{
public static void LogInToTradingView(string twusername, string twpassword, string browserName)
{
ChromiumWebBrowser _dataholder = BrowserContainer.GetDataHolderByName(browserName).ChromiumWebBrow;
IFrame ifww = _dataholder.GetMainFrame();
// var lull = #"(function() { var serielength = TradingView.bottomWidgetBar._widgets.backtesting._reportWidgetsSet.reportWidget._data.filledOrders.length; return serielength; })();";
// JavascriptResponse _js = Task.Run(async () => { return await _browser.GetMainFrame().EvaluateScriptAsync(lull); }).Result;
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-header__link tv-header__link--signin js-header__signin')[0].click();})();");
// var loginusernamescript =
var loginpasswordscript = #"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[1].value= " + twpassword + "; })();";
var clkloginbtn = #"(function() { document.getElementsByClassName('tv-button tv-button--no-border-radius tv-button--size_large tv-button--primary_ghost tv-button--loader')[0].click();})();";
Thread.Sleep(300);
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[0].click();})();");
Thread.Sleep(50);
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[0].value = '" + twusername + "';})();");
Thread.Sleep(50);
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[1].click();})();");
Thread.Sleep(50);
ifww.ExecuteJavaScriptAsync(#"(function() { window.document.getElementsByClassName('tv-control-material-input tv-signin-dialog__input tv-control-material-input__control')[1].value = '" + twpassword + "';})();");
Thread.Sleep(50);
ifww.ExecuteJavaScriptAsync(#"(function() { document.getElementsByClassName('tv-button tv-button--no-border-radius tv-button--size_large tv-button--primary_ghost tv-button--loader')[0].click();})();");
}
public static string TakeScreenshot(string browserName)
{
try
{
Bitmap img = Task.Run(async () => { return await BrowserContainer.GetDataHolderByName(browserName).ChromiumWebBrow.ScreenshotAsync(); }).Result;
// object mgss = img.Clone();
string baseen = ExtraFunctions.ToBase64String(img, ImageFormat.Png);
return baseen;
}
catch (Exception e)
{
var x = e.InnerException;
return null;
}
}
public static string RunScriptInNamedBrowser(string browserName, string script)
{
try
{
string str = Task.Run(async () => { return await BrowserContainer.GetDataHolderByName(browserName).ChromiumWebBrow.GetMainFrame().EvaluateScriptAsync(script); }).Result.ToString();
// object mgss = img.Clone();
return str;
}
catch (Exception e)
{
var x = e.InnerException;
return null;
}
}
}
How can I get my browser actions to report back to my controller so that I can wait for them to finish?
For a Task asynchronous operation to report back, it's possible to use Progress<T>. How that's done is detailed in Enabling Progress and Cancellation in Async APIs. The key is:
var progressIndicator = new Progress<int>(ReportProgress);
This creates a Progress<T> object that can indicate how far a task is complete, and also call a custom method (ReportProgress) at set intervals. You can create a custom class if necessary instead of using int.
So your browser actions can report back to the controller with the progress reporting method until everything is complete.

Calling an async method inside Background worker dosen't report progress paralelly

I am calling an async method that returns a Task < CurrentCartridgeStatus> from Background worker. Thing is until the CurrentCartridgeStatus changes its state I want to keep calling it. But I am not awaiting on this method call because making the DoWork method async is giving me an exception.
But in my case with my current call(Please see the StartCurrentRun method) the background worker initially reports 1% then it seems to be staying idle, and after the status changes then it reports the rest 99%. Please help how can I make the Background worker report progress in parallel with StartCurrentRun method.
private void StartCurrentRun(bool obj)
{
this.worker = new BackgroundWorker();
this.worker.WorkerReportsProgress = true;
this.worker.WorkerSupportsCancellation = true;
this.worker.DoWork += this.DoWork;
this.worker.ProgressChanged += this.ProgressChanged;
this.worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
IsLiveProgress = true;
StartTimer();
this.worker.RunWorkerAsync();
}
private void DoWork(object sender, DoWorkEventArgs e)
{
CreateEventLogs.WriteToEventLog(string.Format("Run with Assay:{0} Volume{1} has been started", SelectedAssay, SelectedVolume));
if (worker.CancellationPending == true)
{
e.Cancel = true;
return;
}
int current = 1;
CurrentCartridgeStatus status = CurrentCartridgeStatus.NotProcessed;
var instance = ConnectToInstrument.InstrumentConnectionInstance;
do
{
var result = instance.StartCurrentRun(SelectedAssay.display_name, int.Parse(SelectedVolume.Remove(SelectedVolume.Length - 2, 2)));
//var result = Test(current);
status = result.Result;
CurrentStatus = status.ToString();
CreateEventLogs.WriteToEventLog("Run status - " + CurrentStatus);
//Thread.Sleep(2000);
worker.ReportProgress(Math.Min(current, 100));
current++;
}
while (status != CurrentCartridgeStatus.Processed);
ConnectToInstrument.IsAlreadyExecuted = false;
if (current < 100)
{
worker.ReportProgress(current + (100 - current));
}
}
Here is the StartCurrentRun method. It internally calls some firmware logic. Just to make this more clear here is the entire ConnectToInstrument Class.
public class ConnectToInstrument
{
private EventProxy _updater;
private IInstrument _instrument;
private QpCallBack _cb;
//private IQEvent #event;
private QpWrapper _qp;
private InstrumentTypes _type;
private CurrentInstrumentStatus InstrumentCurrentStatus = CurrentInstrumentStatus.NotReady;
private static ManualResetEvent manualResetEvent = new ManualResetEvent(false);
public static bool IsAlreadyExecuted = false;
public bool IsConnected { get; set; }
private static ConnectToInstrument _instrumentConnectionInstance;
public static ConnectToInstrument InstrumentConnectionInstance
{
get
{
if (_instrumentConnectionInstance == null)
{
_instrumentConnectionInstance = new ConnectToInstrument();
}
return _instrumentConnectionInstance;
}
}
private ConnectToInstrument()
{
try
{
_cb = new QpCallBack();
_qp = new QpWrapper();
//var config = new ConfigManager();
//var client = new Dna2Client();
_type = InstrumentTypes.Simulator;
var factory = new ApiFactory(_cb, _qp, _type);
_instrument = factory.GetInstrument();
InitializeQf();
_updater = new EventProxy();
_updater.Start(1);
StartUiProxy().Forget();
}
catch (Exception ex)
{
//Log to Error Log
}
}
private async Task<object> StartUiProxy()
{
while (true)
{
try
{
var #event = await _updater.GetEvent();
switch ((QpSignals)#event.QSignal)
{
case QpSignals.INSTRUMENT_STATUS:
{
var status = #event as UiEvent<InstrumentStatus>;
if (status.Value != InstrumentStatus.Ready)
{
InstrumentCurrentStatus = CurrentInstrumentStatus.NotConnected;
continue;
}
else
{
InstrumentCurrentStatus = CurrentInstrumentStatus.Ready;
return Task.FromResult<object>(InstrumentStatus.Ready);
}
}
case QpSignals.TRAY_STATUS:
{
var status = #event as UiEvent<TrayStatus>;
if (status.QSignal == 6 && status.Value == TrayStatus.Opened)
{
return Task.FromResult<object>(TraySignals.OPEN);
}
else if (status.QSignal == 6 && status.Value == TrayStatus.Opened)
{
return Task.FromResult<object>(TraySignals.CLOSE);
}
return null;
}
case QpSignals.PROCESS_CARTRIDGE:
{
var status = #event as UiEvent<CartridgeStatus>;
if (status.Value == CartridgeStatus.Processing)
{
return status;
}
else if (status.Value == CartridgeStatus.Processed)
{
return status;
}
return null;
}
}
}
catch (Exception ex)
{
//Log to Error Log
}
}
}
private void InitializeQf()
{
QF.Instance.Initialize((int)QpSignals.MAX_SIGNAL - 1);
}
public async Task<bool> Connect()
{
bool status = false;
string[] ports = new string[40];
if (_type == InstrumentTypes.Dgx)
{
ports = await ComPortInfo.GetAvailablePortNamesForDevice("USB Serial Port");
if (ports == null || ports.Length == 0)
{
Exception ex = new Exception("No Serial Devices found.");
//Log
return false;
}
}
try
{
string thermPort = _type == InstrumentTypes.Simulator ? string.Empty : ports[0]; //ports[0] should be changed to combobox selected value
status = _instrument.Connect(ports[0]);
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
return status;
}
public async Task<CurrentInstrumentStatus> GetCurrentInstrumentStatus()
{
return await Task.FromResult(InstrumentCurrentStatus);
//_cb.InstrumentStatusUpdates(InstrumentStatus.Ready);
//var value = await _updater.GetEvent();
//var status = value as UiEvent<InstrumentStatus>;
//if (status.QSignal == 5 && status.Value == InstrumentStatus.Ready)
//{
// return CurrentInstrumentStatus.Ready;
//}
//return CurrentInstrumentStatus.Error;
}
public async Task<CurrentCartridgeStatus> StartCurrentRun(string Assay, int volume)
{
object value;
UiEvent<CartridgeStatus> status;
do
{
//await Task.Delay(1000);
//_cb.ProcessCartridge(CartridgeStatus.Processing);
if (!IsAlreadyExecuted)
{
_instrument.ProcessCartridge();
}
IsAlreadyExecuted = true;
//value = await StartUiProxy();
value = await _updater.GetEvent();
status = value as UiEvent<CartridgeStatus>;
}
while (status == null);
try
{
//IQEvent value;
if (status.QSignal == 9 && status.Value == CartridgeStatus.Processing)
{
return CurrentCartridgeStatus.Processing;
}
if (status.QSignal == 9 && status.Value == CartridgeStatus.Processed)
{
return CurrentCartridgeStatus.Processed;
}
}
catch (Exception ex)
{
//Log it
}
return CurrentCartridgeStatus.Unidentified;
}
}
Here is the CurrentCartridgeStatus enum
public enum CurrentCartridgeStatus
{
Unidentified = 0,
NotProcessed = 1,
Processing = 2,
Processed = 3
}

Unity Facebook SDK build malfunctioning - Unity 5.1, FB SDK 6.2.2

I'm having some trouble with a Facebook Login/Share POC I've put together for the Unity Web Player. When I run it in the editor everything runs fine. I can login, retrieve profile name and picture and share to wall. When I create a build for Web Player however, nothing functions. Clicking login does nothing and all UI elements show up at start even though in code I've set many to be inactive until the login button is clicked. Would really appreciate some help on this, I have no idea why it's getting built incorrectly. Has anyone else experienced this?
Link: https://locomoku.com/projects/facebook/
public GameObject UIFBIsLoggedIn;
public GameObject UIFBNotLoggedIn;
public GameObject UIFBAvatar;
public GameObject UIFBUserName;
private Dictionary<string, string> profile = null;
void Awake()
{
FB.Init(SetInit, OnHideUnity);
}
private void SetInit()
{
Debug.Log("FB Init Done");
if(FB.IsLoggedIn)
{
Debug.Log("FB Logged in");
DealWithFBMenus(true);
}
else
{
DealWithFBMenus(false);
}
}
private void OnHideUnity(bool isGameShown)
{
if(!isGameShown)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
public void FBLogin()
{
FB.Login("public_profile, user_friends", AuthCallback);
}
void AuthCallback(FBResult result)
{
if(FB.IsLoggedIn)
{
Debug.Log("FB Login Worked");
DealWithFBMenus(true);
}
else
{
Debug.Log("FB Login Fail");
DealWithFBMenus(false);
}
}
void DealWithFBMenus(bool isLoggedIn)
{
if(isLoggedIn)
{
UIFBIsLoggedIn.SetActive(true);
UIFBNotLoggedIn.SetActive(false);
// Get Profile Picture Code
FB.API(Util.GetPictureURL("me",128,128),Facebook.HttpMethod.GET,DealWithProfilePicture);
// Get User Name Code
FB.API("/me?fields=id,first_name", Facebook.HttpMethod.GET, DealWithUserName);
}
else
{
UIFBIsLoggedIn.SetActive(false);
UIFBNotLoggedIn.SetActive(true);
}
}
void DealWithProfilePicture(FBResult result)
{
if (result.Error == null)
{
Image img = UIFBAvatar.GetComponent<Image>();
img.sprite = Sprite.Create(result.Texture, new Rect(0,0, 128, 128), new Vector2());
}
else{
Debug.Log("Error with Profile Picture");
}
}
void DealWithUserName(FBResult result)
{
if (result.Error == null)
{
profile = Util.DeserializeJSONProfile(result.Text);
Text userMsg = UIFBUserName.GetComponent<Text>();
userMsg.text = "Hello, " + profile["first_name"];
}
else{
Debug.Log("Error with Profile Name");
}
}
public void ShareWithFriends()
{
FB.Feed(
linkCaption: "Test Captions",
picture: "https://locomoku.com/projects/facebook/shot.jpg",
linkName: "Test Link Name",
link: "http://locomoku.com"
);
}
The Util.cs code -
public static string GetPictureURL(string facebookID, int? width = null, int? height = null, string type = null)
{
string url = string.Format("/{0}/picture", facebookID);
string query = width != null ? "&width=" + width.ToString() : "";
query += height != null ? "&height=" + height.ToString() : "";
query += type != null ? "&type=" + type : "";
if (query != "") url += ("?g" + query);
return url;
}
public static void FriendPictureCallback(FBResult result)
{
if (result.Error != null)
{
Debug.LogError(result.Error);
return;
}
//GameStateManager.FriendTexture = result.Texture;
}
public static Dictionary<string, string> RandomFriend(List<object> friends)
{
var fd = ((Dictionary<string, object>)(friends[Random.Range(0, friends.Count - 1)]));
var friend = new Dictionary<string, string>();
friend["id"] = (string)fd["id"];
friend["first_name"] = (string)fd["first_name"];
return friend;
}
public static Dictionary<string, string> DeserializeJSONProfile(string response)
{
var responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object nameH;
var profile = new Dictionary<string, string>();
if (responseObject.TryGetValue("first_name", out nameH))
{
profile["first_name"] = (string)nameH;
}
return profile;
}
public static List<object> DeserializeScores(string response)
{
var responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object scoresh;
var scores = new List<object>();
if (responseObject.TryGetValue ("data", out scoresh))
{
scores = (List<object>) scoresh;
}
return scores;
}
public static List<object> DeserializeJSONFriends(string response)
{
var responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object friendsH;
var friends = new List<object>();
if (responseObject.TryGetValue("friends", out friendsH))
{
friends = (List<object>)(((Dictionary<string, object>)friendsH)["data"]);
}
return friends;
}
public static void DrawActualSizeTexture (Vector2 pos, Texture texture, float scale = 1.0f)
{
Rect rect = new Rect (pos.x, pos.y, texture.width * scale , texture.height * scale);
GUI.DrawTexture(rect, texture);
}
public static void DrawSimpleText (Vector2 pos, GUIStyle style, string text)
{
Rect rect = new Rect (pos.x, pos.y, Screen.width, Screen.height);
GUI.Label (rect, text, style);
}

Categories