I have developed a PC based API in C# to communicate with an embedded electronic device. This API reads the PC COM port, decodes packets, constructs packets and raises events. Now I need to develop the same API in Android mobile. As there are differences between C# and Java Events, I'm quite confused how to achieve the same in Java.
The following C# code rises events:
public class MARGserial
{
dataObject = BT_DeconstructPacket(encodedPacket);
if (dataObject != null) // if packet successfully deconstructed
{
OnMARGdataReceived(dataObject);
if (dataObject is RawMARGdata)
{
OnRawMARGdataReceived((RawMARGdata)dataObject);
PacketsReadCounter.RawMARGdataPackets++;
}
}
public delegate void onRawMARGdataReceived(object sender, RawMARGdata e);
public event onRawMARGdataReceived RawMARGdataReceived;
protected virtual void OnRawMARGdataReceived(RawMARGdata e)
{
if (RawMARGdataReceived != null)
RawMARGdataReceived(this, e);
}
}/*End of MARGserial class */
The following code is for subscribing to Event OnRawMARGdataReceived in windows console application.
public static MARG_api.MARGserial MARGserial = new MARG_api.MARGserial("COM44");
MARGserial.RawMARGdataReceived += new MARG_api.MARGserial.onRawMARGdataReceived(MARGserial_RawMARGdataReceived);
static void MARGserial_RawMARGdataReceived(object sender, MARG_api.RawMARGdata e)
{
Console.WriteLine("Data : " + e.Accelerometer[0].ToString() + " "+e.Accelerometer[1].ToString()+ " "+e.Accelerometer[2].ToString());
}
In case of Android Java application, Main Activity class in the application itself has to subscribe for events which are fired inside of another class thread ( this thread reads Bluetooth buffer & constructs packets)
You could use Design Patterns here, notably Observer:
In Observer you have an interface called IObserver with a method called update() that you make all your interested objects implement. Then the master object stores a set of s and when something happens it calls .update() on every object in that collection (the callback in essence). This is common in MVC architectures too if you want to go that way for GUI, when the model state changes and the view needs to be updated.
You could also achieve Delegate style first order functions using the Command design pattern, which is very useful in Java given there is no native support for this concept.
I'm not sure if the above will help in your specific context, but Design Patterns are usually a good way to go and solve all manner of problems.
If you are not using a GUI-Toolkit like "Swing" then in Java the Listener Pattern is quite common for this kind of task.
That is you have a listener that registers itself at the host, which in turn holds a list of listeners. If the event corresponding to the listener happens, the listeners then get notified.
It is pretty similar to the Observer Pattern.
Maybe this SO question is helpful.
I successfully developed android application which can connect to my bluetooth device using the BluetoothChat sample provided by Google. The bluetooth module of device has SPP (serial port profile) which is from RovingNetworks (RN-41).
Please check out -
http://v-lad.org/projects/gnu.io.android/
Related
I am trying to understand Event Tracing in Windows (ETW). What I want to do is capture which menu item was selected in Notepad. If I click Word Wrap, I want ETW to tell me this.
I have looked at the samples on GitHub. One of the Event Producers is the demo:
namespace TraceEventSamples
{
// In these demos, we generate events with System.Diagnostics.Tracing.EventSource and read them with ETWTraceEventSource
//
// Normally the EventSource and the ETWTraceEventSource would be indifferent processes, however, we
// don't do this here to make the scenario really easy to run. The code works in the multi-process case, however.
namespace Producer
{
[EventSource(Name = "Microsoft-Demos-SimpleMonitor")] // This is the name of my eventSource outside my program.
class MyEventSource : EventSource
{
// Notice that the bodies of the events follow a pattern: WriteEvent(ID, <args>) where
// ID is a unique ID starting at 1 and incrementing for each new event method. and
// <args> is every argument for the method.
// WriteEvent then takes care of all the details of actually writing out the values complete
// with the name of the event (method name) as well as the names and types of all the parameters.
public void MyFirstEvent(string MyName, int MyId) { WriteEvent(1, MyName, MyId); }
public void MySecondEvent(int MyId) { WriteEvent(2, MyId); }
public void Stop() { WriteEvent(3); }
// Typically you only create one EventSource and use it throughout your program. Thus a static field makes sense.
public static MyEventSource Log = new MyEventSource();
// You don't need to define this override, but it does show you when your eventSource gets commands, which
// is helpful for debugging (you know that your EventSource got the command.
protected override void OnEventCommand(EventCommandEventArgs command)
{
EventGenerator.Out.WriteLine("EventSource Gets command {0}", command.Command);
}
// We could add Keyword definitions so that you could turn on some events but not others
// but we don't do this here to keep it simple. Thus you either turn on all events or none.
}
This is creating events for the demo, but how can I wire this to Notepad instead? Can ETW be used for this type of logging, knowing what someone clicked on a menu of an application?
I have looked at various SO questions, but they did not help. One generic was, Is there a Microsoft (built-in) ETW Provider for tracing ETW lifecycle events?
I considered this because it does not require C#, C++ Event Tracing for Windows (ETW) wrapper but didn't understand how it helped me.
This makes me think I cannot do it with managed code if I didn't write the original program:
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.tracing.eventsource?redirectedfrom=MSDN&view=netcore-3.1
What I am attempting to do is capture which menu item is selected, and take action with my program that caught the event. The reason for this is an old VB6 program. I cannot do what I need to do, so my last resort is to capture the menu item and get my application to do what I want. I wanted to start with a simple notepad.exe.
VB6 user clicks "View X." My C# application does "View Y".
I'm building a dll that will be used from wpf and other kind of framework (windows form, asp...). For this reason I don't want to use Messagebox. Which is the best way to send notification from dll to app and each decide the way to show the message to user (and wait an answer from user)? Somebody can help me to find the correct way?
Unless the library (.dll) is only intended to work with a particular UI, the library shouldn't "decide" how or if notifications get displayed. It's a separation of concerns. If a library determined that it should show a MessageBox then you wouldn't be able to use that same library with a web app or some out-of-sight service.
Here are two ways (not exhaustive) that we might get information from a separate library, including our own:
We call a function and the library returns a response. For example, it might indicate that an action succeeded or failed. The library doesn't know what type of app it's being called from or whether anyone needs to see the response. It just returns it. Your app can then receive that result and display a message.
A class within the library raises an event which indicates that something has happened. Same thing - it doesn't know what is listening for that even or what will happen as a result. It just raises the notification. Our app determines that in response to that event it should display a message.
When our libraries work that way they are easier to test using automated tests like unit tests and integration tests. It's easy to write a test which verifies that calling a method returns a certain result. It's much harder to verify that a MessageBox pops up.
And, as mentioned, it makes it more likely that we can use more of our code with different types of user interfaces. For those reasons it's beneficial to write as much of our code as possible in isolation from any UI, which means not including input/output behaviors that are specific to one type of UI.
You could expose an event that the consumers can subscribe to. Here is the general pattern to do this kind of thing:
You can create your own class to carry the data about the event:
public class NotificationEventArgs : EventArgs
{
public NotificationEventArgs(string message)
{
Message = message;
}
public string Message { get; }
}
You then create a delegate to represent the signature of the event:
public delegate void OnNotificationEventHandler(SomeClass sender, NotificationEventArgs args);
Your class or classes can then expose this delegate as an event:
public class SomeClass
{
private OnNotificationEventHandler _notificationEventHandler;
public event OnNotificationEventHandler OnNotification
{
add { _notificationEventHandler += value; }
remove { _notificationEventHandler -= value; }
}
protected void RaiseNotificationEvent(NotificationEventArgs args)
{
_notificationEventHandler?.Invoke(this, args);
}
public void SomeMethod()
{
//Your class does something that requires consumer notification
var args = new NotificationEventArgs("Something happened!");
//Raise the event for the consumers who are listening (if any)
RaiseNotificationEvent(args);
}
}
Finally, your consuming classes will subscribe to this event:
SomeClass obj = new SomeClass();
obj.OnNotification += Obj_OnNotification;
private static void Obj_OnNotification(SomeClass sender, NotificationEventArgs args)
{
//Handle the notification from the class here.
Console.WriteLine(args.Message);
}
The general idea is that consumers of your class only need to know that something has happened as well as details of what happened. How that event is consumed, handled or displayed is not the responsibility of your component.
I'm attempting to detect two events for this particular USB device (blink1): insert and remove
I've successfully enumerated the device(s) and can send commands, though I'm having a difficult time establishing the delegates and getting either event to trigger.
The HidLibrary.cs library contains two event handlers titled "InsertedEventHandler", "RemovedEventHandler" and the functions "DeviceEventMonitorInserted", "DeviceEventMonitorRemoved" which seem to be attached to an instance of the HidDeviceEventMonitor.cs class. I'm attempting to establish connect/disconnect/re-connect methods within the calling class where I utilize the HidLibrary class as:
using HidLibrary
...
private HidDevice hidDevice;
...
hidDevice.command(var1, var2, ..);
I feel this is a simple task, and I've established and worked with event handlers, routed events and delegates in the past to a limited degree in C# but I seem to be missing a crucial concept when dealing with this particular situation.
Update: In case anyone else comes across this when working with the blink1 HidLibrary, to enable the EventMonitor you must set hidDevice.MonitorDeviceEvents = true after calling OpenDevice() on the HidDevice instance. This isn't in any of the documentation and only became apparent after getting the event routing down.
I don't have any Blink1 devices, but after spending a few minutes with the code, I think this might work:
public static void Main()
{
HidDevice device;
// device declaration
device.Inserted += Device_Inserted;
device.Removed += Device_Removed;
}
private static void Device_Removed()
{
// Some stuff to do when device is removed
throw new NotImplementedException();
}
private static void Device_Inserted()
{
// Some stuff to do when device is inserted
throw new NotImplementedException();
}
I’ve been supplied with a DLL by a third party which processes the data it’s supplied and returns its results through an event as below.
private IBlackbox blackbox;
// Capture the processed data from the BlackBox
public void blackbox_Processed(object sender, BlackBoxEventArgs e)
{
string returndata = e.ReturnData;
// Do something with the data
}
public void blackbox_Run(string datavalues)
{
blackbox.Processed += new EventHandler(blackbox_Processed);
blackbox = BlackBox.Create(datavalues);
blackbox.Start();
}
This implementation works fine when called from a Windows form with the blackbox.Processed event firing in less than a second. However, when I implement this in a WCF method the blackbox.Processed event is never trapped.
Can anyone help?
It's hard to say for certain since you haven't provided code for your service but my guess is that the call to your service method is returning before your blackbox component fires the event. One thing you could look at would be using a WCF duplex service which would allow you to publish an event from the server to the client.
WCF Duplex Services
I developed a C# class library, some of their methods shows information of its processing progress because they read and write millions of records, and the user asked for knowing how the process is going and the time they should wait.
Using dependency injection to avoid the "if console app write progress on console else if WPF app display progress bar", (1) I have got the displaying on the console the time for every one million records processed if the method is invoked from a console application and (2) I have got the displaying a progress bar on a GUI if the method is invoked from a WPF application.
The question here is, is it a good practice what I am doing or, is there better/correct alternative to this matter?
My best regards.
Please don't do this. If you are building a class library, you should make zero assumptions about the UI is interacting with the user.
Your solution sounds like it might work if you have a console window or a WPF application, but what if it's being called from a website or inside a service? I've seen many a service get brought down beause some rogue class library was trying to display a dialog but there was nobody around to click OK.
The better solution is to simply raise an event whenever you want to report some progress, and let the consuming UI application worry how it wants to display that progress to the user.
See how the BackgroundWorker class works for a good model of this: http://msdn.microsoft.com/en-us/library/8xs8549b.aspx
I wouldn't expect a class library to display the progress itself. I'd expect it provide hooks - probably in the form of events - so that whatever using the class library can display that information in the most appropriate form.
Quite how much control you want to give over that (e.g. report to me on every item or every N items) is a matter you'll have to work out for yourself - but it should be fairly easy for a handler to work that sort of thing out for itself.
Here's an example of raising events, this code will go in your class that is doing the work on the background thread. The MessageEventsArgs derives from EventArgs (MessageEventArgs : EventArgs) so custom information can be passed to the caller. This isn't required, one could use EventArgs e as well.
public delegate void SchemaProcessorMessageEventHandler(object sender, MessageEventArgs e);
public event SchemaProcessorMessageEventHandler SchemaProcessorMessage;
protected virtual void OnSchemaProcessorMessage(MessageEventArgs e)
{
if (SchemaProcessorMessage != null)
{
SchemaProcessorMessage(this, e);
}
}
Now in your caller (UI) set up the event listener. Remove the event listener -= when finished.
_SchemaProcessor = new ServerSchemaUtilityFramework.SchemaProcessor();
_SchemaProcessor.SchemaProcessorMessage += new ServerSchemaUtilityFramework.SchemaProcessor.SchemaProcessorMessageEventHandler(sp_SchemaProcessorMessage);
void sp_SchemaProcessorMessage(object sender, ServerSchemaUtilityFramework.MessageEventArgs e)
{
//Update the UI, if on background will need to (!this.Dispatcher.CheckAccess())
}