Xamarin.Forms MQTTnet - ApplicationMessageReceived async event causes app to crash
I am working on an MQTTnet application for mobile/wearable devices. I've tested my code in both a standard C# WPF application and .Net Core application, both work as expected. The issue I am having is when I port the code to Xamarin Forms, for running on a Galaxy Watch. The app will run for a few seconds, but then it will crash. I believe it could be from the event firing too often, if that makes sense?
I have an MQTT publisher device pumping out a simple position value at a 10ms interval. Where my other apps will just keep chugging along, the app in Xamarin will lock and then eventually crash.
Here is my Xamarin code, is there a better way to handle this?
I can make it work by only publishing/receiving a message every 1 second, but this isn't ideal for position data presentation on the UI. I did manage to get it to work with 200ms interval, but anything past that it'll lock. Is there a way to ignore the event from firing too often in Xamarin, or prevent it from locking the app?
public App()
{
Task.Run(RunAsync)
}
`
public static async Task RunAsync()
{
var factory = new MqttFactory();
var client = factory.CreateMqttClient();
var clientOptions = new MqttClientOptions
{
ChannelOptions = new MqttClientTcpOptions
{
Server = MQTTBroker
}
};
client.ApplicationMessageReceived += (s, e) =>
{
PayloadLabel.Text = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
};
client.Connected += async (s, e) =>
{
await client.SubscribeAsync(new TopicFilterBuilder().WithTopic(MQTTSubTopic).Build());
};
// Attempt a connection to the broker
try
{
await client.ConnectAsync(clientOptions);
}
catch (Exception exception)
{
PayloadLabel.Text = "Failed to connect..."
}
}
}
See also questions close to this topic
-
Using NuGet.PackageManager, How to get Installed packages with dependencies
Intro
Using NuGet.PackageManagement at runtime to enable users to install packages (from a private repo) where the packages will be loaded by
System.Runtime.Loader.AssemblyLoadContext
and executed.The install method uses a
NuGetPackageManager
andNuGetProject
that's been setup appropriately from what could understood inNuGet.Client
_nugetProject
is an instance extendingFolderNuGetProject
that stores packages in a specified folder andGetInstalledPackagesAsync
returns a list of installed packages instead of an empty list._packageManager
is aNuGetPackageManager
and_packageRepository
is aSourceRepositoryProvider
, both are default instances setup with the appropriate paths and source repos.public async Task InstallPackageAsync(string packageId, SemanticVersion packageVersion, CancellationToken cancellationToken = default) { var packageIdentity = new PackageIdentity(packageId, new NuGetVersion(packageVersion.ToNormalizedString())); using (var sourceCache = new SourceCacheContext()) { var resolutionContext = new ResolutionContext( DependencyBehavior.Highest, includePrelease: true, includeUnlisted: true, VersionConstraints.None, new GatherCache(), sourceCache); var projectContext = new EmptyNuGetProjectContext() { PackageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv3, XmlDocFileSaveMode.Skip, ClientPolicyContext.GetClientPolicy(_nugetSettings, _nugetLogger), _nugetLogger), ActionType = NuGetActionType.Install, }; var previewActions = await _packageManager.PreviewInstallPackageAsync( _nugetProject, packageIdentity, resolutionContext, projectContext, _packageRepository.GetPrimaryRepositories().ToList(), _packageRepository.GetRepositories().ToList(), cancellationToken); // List all actions in debug log. var debugOutput = new StringBuilder(); debugOutput.AppendLine($"Install actions for {packageId}:"); foreach(var action in previewActions) debugOutput.AppendLine($" - {action.NuGetProjectActionType}: {action.PackageIdentity}"); _logger.LogDebug(debugOutput.ToString()); await _packageManager.ExecuteNuGetProjectActionsAsync( _nugetProject, previewActions, projectContext, sourceCache, cancellationToken); } }
Problem
The goal is to get a dependency graph of a specific package that was installed and use that information to load the assembly and it's required dependencies.
The difficulty is not being able to find any relevant API that already exists that would do this. Seeing as this is very common task in Visual Studio, it's been assumed that NuGet would provide a means to build a dependency graph.
There is
await _nugetProject.GetInstalledPackagesAsync(cancellationToken)
However this only returns a list ofPackageReference
s, that only contain theVersionRange
andPackageId
.Note: NuGet.Client has served as the reference for how to use NuGet APIs properly
-
Background Threads and Dialogs
I have a small program that starts as an appbar (a window which docks to the desktop and can be hidden (on the top, right, bottom, or left side of the desktop when not in use). The program permits a user to drag a file (or files) from any given location on to the appbar and convert it to PDF (by converting each file to PDF and then merging the resulting PDF's into a single PDF file).
The conversion process runs on a seperate thread using a backgroundworker. Once the backgroundworker acquires the list of files, I have a modal dialog which pops up, having loaded a listview with the relevant files, and allows the user to reorder them prior to the final merge process.
I am having cross-thread issues with the modal dialog. I have searched high and low for a solution, but am stumped. The problems arises as a result of the use of the keyword this.
I have tried the following code in the midst of the backgroundworker:
using (var md = new MergeDlg()) { md.Files = (string[])files; if (md.ShowDialog(this) == DialogResult.OK) files = md.Files; }
If I remove the keyword this I get no error, but the dialog behaves as if it is started on the main thread and the backgroundworkerthread continues as if there is no modal dialog - I understand that is because the dialog is started on the main UI thread.
I have also tried moving the dialog creation out of the background worker thread and calling it in the thread the code to create the modal dialog is as follows:
private string[] ShowMergeDlg(string[] files) { if (this.InvokeRequired) { this.BeginInvoke(new Action(() => { MergeDlg md = new MergeDlg(); md.Files = (string[])files; if (md.ShowDialog(this) == DialogResult.OK) files = md.Files; } )); } else { MergeDlg md = new MergeDlg(); md.Files = (string[])files; if (md.ShowDialog(this) == DialogResult.OK) files = md.Files; } return files; }
On the backgroundworker thread, the function is called:
files = ShowMergeDlg(files);
Again that code obviously starts the dialog on the main UI thread with the same result.
My question is then:
How do I show a modal dialog on a backgroundworker thread, pausing execution of the thread until such times as the modal dialog has been closed?
-
Showing 2 instances of the same view the same time using MVVM Light
I am builind a C# WPF application using MVVM Light. I need to show 2 different instances of the same view with both having their own viewmodel. But in ViewModelLocator (which I have based on the examples shown by MVVM Light's author) it is always the same instance returned:
public class ViewModelLocator { public ViewModelLocator() { SimpleIoc.Default.Register<MainViewModel>(); SimpleIoc.Default.Register<EditorViewModel>(); } public MainViewModel Main => ServiceLocator.Current.GetInstance<MainViewModel>(); public EditorViewModel Editor => ServiceLocator.Current.GetInstance<EditorViewModel>(); }
Which means that the 2 views will use the same viewmodel.
While debugging I have noticed that the properties Main and Editor are only retrieved by MVVM light when the view is constructed. So by making the following change I can create separate instances of the viewmodel for each call (view):
public MainViewModel Main => new MainViewModel(); public EditorViewModel Editor => new EditorViewModel();
I am not very comfortable with this change. Whenever the property is called a new instance is created. I am concerned that my assumption - that the getter will be called only once for each view - is maybe wrong. One of the reason I think that is the case that the code uses dependency injection. If my assumption would be correct then there would be no need for the dependency injection.
My questions are:
Is there a better way of ensuring that each instance of the same view has it's own viewmodel?
Why is it suggested to use dependency injection here?
-
Creating Custom Background Voice Intent for Android App
I know this has been a topic covered for 8 years, but I haven't been able to find a recent answer to this question.
I'm working on an Android Auto app in my spare time. I'm trying to build out a version of the License Plate Game; when you spot an out-of-state license plate you log it to the app. And hopefully you can find all 50.
Speaking with my wife last night, we realized the smartest way to achieve this would be to activate speaking from the car's steering wheel. From there, an utterance of something like
Add Utah to the License Plate Game
would add Utah to your list of license plates you've seen. A user clearly wouldn't want this app in the foreground for the duration of a car ride, so a background voice action would be the way to go.The Android Auto portion would just be for fun and to learn how to develop for Android Auto with some kind of minimal UI.
Documentation on Voice Actions for Android is minimal when it comes to custom voice utterances. Would I really need to create a Google Assistant extension for an app that is intended to store data and have all logic hosted locally within the project?
Thanks for any and all help!
-
RelativeLayout is not matching parent width inside a ToolBar
So I have a customized toolbar on my home screen, and within this toolbar is a
RelativeLayout
. I have thelayout width
set tomatch_parent
and the parent of the relative layout is just the width of the screen.For some reason, it does not fit the width of the screen because the left edge is some distance away from the edge of the screen. I am not sure why this is but it is making positioning within the
RelativeLayout
a bit more difficult.This is my
.xml
<android.support.v7.widget.Toolbar android:id="@+id/products_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@drawable/bg_gradient" app:layout_constraintStart_toStartOf="parent" app:titleTextColor="#000000"> <RelativeLayout android:id="@+id/topRL" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout_editor_absoluteX="16dp"> <TextView android:id="@+id/toolbar_title" android:layout_width="72sp" android:layout_height="37sp" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_marginStart="137dp" android:layout_marginTop="11dp" android:layout_marginEnd="159dp" android:fontFamily="@font/veganstyle" android:gravity="center" android:text="BL" android:textAlignment="center" android:textColor="#efefef" android:textSize="20dp" android:textStyle="bold" /> </RelativeLayout> </android.support.v7.widget.Toolbar>
And this is a screenshot showing what I am talking about.
As you can see, the blue box surrounding the
RelativeLayout
is not at the edge of the screen, nor will it let me bring it to the edge.Neither the
RelativeLayout
or its parent have any padding or margins, so I am confused why this is an issue and how I can solve it. -
Sqlite Database Error duplicate column name
Error Code : 1 (SQLITE_ERROR) Caused By : SQL(query) error or missing database. (duplicate column name: Floor (code 1)
I tried to save my data i.e. Floor,Floor height, GPS data and Adress which was obtained from another activity to another which implements the SQLite data for saving,loading,editting and deletion. I am always receiving this error message when i try to add the data from the other activity to the database by clicking the list or post button which directs the user to the database.
-
how to get device Id for FCM registration in xamarin
i am trying to connect xamarin app with Azure notification hub. for registration i am using this code in onTokenRefresh method.
var client = new MobileServiceClient(App.MobileServiceUrl); var push = client.GetPush(); var reg = new Registration("??????????", new List<string> { "someTag" }); await push.RegisterAsync(reg);
Registration object needs "deviceId" as first parameter. where to get this id from, in xamarin's Android project ?
-
How can I prevent Shared Perferences from reseting after each deployment?
Each time I build the app in Xamarin, the SP resets. It's really annoying to isnert the values each time, how can I just prevent it from reseting when deploying an application?
sp = Activity.GetSharedPreferences("Added_PC_List",Android.Content.FileCreationMode.Private);
-
Xamarin UWP app throws System.MissingFieldException: Field not found: 'Xamarin.Forms.VisualElement.StyleProperty'
I have an app targeting Android, iOS, and UWP. The main xaml page uses a style property in a label, like so:
<Label Text="{Binding term}" LineBreakMode="WordWrap" Style="{DynamicResource ListItemTextStyle}" FontSize="24" />
This works fine in iOS and Android, but when trying to run in the UWP simulator or locally, I get the error found below. If I remove all style references everything works again...without any styles applied, of course.
Any suggestions on how to get this to work correctly would be appreciated.
Exception thrown: 'System.MissingFieldException' in Xamarin.Forms.Core.dll System.MissingFieldException: Field not found: 'Xamarin.Forms.VisualElement.StyleProperty'. at SomeApp.Views.ItemsPage.<InitializeComponent>_anonXamlCDataTemplate_1.LoadDataTemplate() at Xamarin.Forms.ElementTemplate.CreateContent() at Xamarin.Forms.Internals.TemplatedItemsList`2.ActivateContent(Int32 index, Object item) at Xamarin.Forms.Internals.TemplatedItemsList`2.CreateContent(Int32 index, Object item, Boolean insert) at Xamarin.Forms.Internals.TemplatedItemsList`2.ConvertContent(Int32 startingIndex, IList items, Boolean forceCreate, Boolean setIndex) at Xamarin.Forms.Internals.TemplatedItemsList`2.OnProxyCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at Xamarin.Forms.ListProxy.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at Xamarin.Forms.ListProxy.<>c__DisplayClass33_0.<OnCollectionChanged>b__0() at Xamarin.Forms.ListProxy.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at Xamarin.Forms.ListProxy.WeakNotifyProxy.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at System.Collections.ObjectModel.Collection`1.Add(T item) at SomeApp.ViewModels.ItemsViewModel.<ExecuteLoadItemsCommand>d__9.MoveNext()
-
How do I subscribe/publish messages to an mqtt over websockets broker in PHP?
I'm looking for a way to publish/subscribe messages/channels to a RabbitMQ mqtt over websockets broker from php, and I can't find any code, or any good libraries out there.
I found https://github.com/bluerhinos/phpMQTT but it looks like that's for MQTT, and not for MQTT-over-websockets, plus it looks abandoned.
Why is that so hard - I know I'm not the first person looking for that? Any suggestions?
Thank you
-
callback function for mosquitto is not getting called
For some reason, I had to use C APIs in C++ code. Would anyone please help me in finding the reason for which this code is not working.
void ConfigureBroker() { auto res = mosquitto_lib_init(); if (res == MOSQ_ERR_SUCCESS) std::cout<<" mosquitto_lib_init succeed. "<<std::endl; else std::cout<<" mosquitto_lib_init failed with result : "<<res<<std::endl; struct mosquitto * mosq = NULL; const char *clientId = "mydev"; mosq = mosquitto_new(clientId, true, NULL); if (!mosq) { std::cout<<" mosquitto_new failed. "<<std::endl; return; } else std::cout<<" mosquitto_new succeed. "<<std::endl; res = mosquitto_tls_set(mosq, "path/to/CA.crt", NULL, "path/to/crts/DeviceCert1.crt", "path/to/DeviceCert1.key", NULL); if (MOSQ_ERR_SUCCESS == res) std::cout<<"mosquitto_tls_set succeed."<<std::endl; else std::cout<<"mosquitto_tls_set failed with result : "<<res<<std::endl; mosquitto_connect_callback_set(mosq, my_connect_callback); const char *host = "amazonaws.com"; res = mosquitto_connect(mosq, host, 8883, 60); if (MOSQ_ERR_SUCCESS == res) std::cout<<"mosquitto_connect succeed."<<std::endl; else std::cout<<"mosquitto_connect failed with result : "<<res<<std::endl; while(!mosquitto_loop(mosq, -1, 1)) std::cout<<"mosquitto_loop_forever suceed. \n "<<std::endl; }
The output to the above code is as below
mosquitto_lib_init succeed. mosquitto_new succeed. mosquitto_tls_set succeed. mosquitto_connect succeed. mosquitto_loop_forever suceed. mosquitto_loop_forever suceed. mosquitto_loop_forever suceed. mosquitto_loop_forever suceed. mosquitto_loop_forever suceed. mosquitto_loop_forever suceed. mosquitto_loop_forever suceed.
my_connect_callback() function does get called even though mosquitto_connect() returns 0. In fact none of the callback functions get call.
Though the APIs execute successfully, fail to push data into AWS.
Any help will be appreciated.
-
MQTT in JS without Web Socket
i want to use MQTT connection in my React app without web socket just a pure MQTT.But after researches i figure out that with JS i can use MQTT only with Web Socket. Does any one have a solution re this issue?
-
How to use appium-tizen-driver to connect Tizen TV and automate testing for webapp/ app?
https://github.com/Samsung/appium-tizen-driver as per comments, it is possible to connect to run in emulator but dont know proper steps to use it. Can anyone help ?
I'm trying use to use in python language
-
Debug running Tizen Web Application...?
Tizen Studio has a way to run a Web App in debug mode, which is very handy, but as soon as application is closed, the console gets disconnected as well.
I wonder if it is possible to remotely connect to already running application and debug it?
-
Save sensor data using c in tizen wearable native app
I tried to save some sensor data in my native app using c and pull it to my computer via device manager. I notice that all apps have read and write permissions in media folder and its subfolders on tizen's website, but it doesn't work (permission denied error). Here is my code to get the path and create the file. Do you how to do it properly? Thanks a lot.
void al_start(){ struct tm localtime = {0}; time_t rawtime= time(0); if (localtime_r(&rawtime, &localtime) != NULL) { } char io_stream_w_path[200]; char *storage_path; /* You can find the storage ID using the storage_foreach_device_supported() function */ int storage_id; storage_foreach_device_supported(storage_cb, &storage_id); int error = storage_get_directory(storage_id, STORAGE_DIRECTORY_DOCUMENTS, &storage_path); snprintf(io_stream_w_path, 200, "%s/%04i-%02i-%02i_%02i-%02i-%02i%s", storage_path, localtime.tm_year + 1900, localtime.tm_mon + 1, localtime.tm_mday, localtime.tm_hour, localtime.tm_min, localtime.tm_sec,".txt"); free(storage_path); light_w = fopen(io_stream_w_path, "wb"); if(!light_w){ dlog_print(DLOG_INFO, "TIZEN_N_LIGHT_IO111", "fopen() function failed while opening %s file! %s", io_stream_w_path,strerror(errno)); } else{ dlog_print(DLOG_INFO, "TIZEN_N_LIGHT_IO111", "success"); } fclose(light_w);
}