LabVIEW: How to share a .NET object created from LabVIEW - labview

I have a class called Camera in the .NET library and once I instantiate the object I want to create a reference of it so that this instance can be used from other VIs. How do I make a reference or how do I make it global ?
Thanks,

There are a couple ways to approach your question.
Possible answer 1: You're looking to let multiple parallel subVIs use the object at the same time. The .NET wire is already a reference wire. Forking that wire does not copy the object. Just wire it into the other VIs, however many there are, and let them all use the reference.
Possible answer 2: You're trying to obtain the existing reference in another VI without passing the reference on a wire through a subVI conpane or Call By Reference node. In this case, you would pass the .NET object refnum the same way you would pass any other bit of data in LabVIEW when avoiding wires. In general, the rule is "avoid passing data outside of dataflow." Seriously... try to pass the refnum through a conpane... if this program is going to have any significant lifetime, you'll be happier when you can take that approach. BUT... when such outside-of-dataflow passing is necessary, there are many tools -- queues, notifiers, global VIs, data value references, functional globals. Which of those tools is the right one depends greatly on what you're actually trying to achieve. The simplest is to create a global VI, but that introduces a lot of polling checks as the second VI has to keep polling the global to see if the first VI has stored the value yet or not. A notifier refnum is probably the most flexible option that I can point you toward... create a named notifier of your .NET refnum type. Both first and second VI can obtain the notifier by name. The second VI then blocks on Wait For Notificiation waiting for the first VI to write the refnum into the notifier. See http://zone.ni.com/reference/en-XX/help/371361L-01/glang/create_notifier/ for more information on notifiers. Or Google the other terms that I listed if that seems insufficient for your needs.

Related

Get value of control refnum in one step in SubVI

I'm trying to de-spaghetti a big UI by creating SubVIs that handle only the controls that are relevant, via control refnums.
Now, when extracting the code from the main VI and re-wiring into the subVIs, things get clutter-y.
To read/write these refnums, I have to do a two-step process. First add a terminal to get the control refnum value and then another to get the value of the control.
Wiring the refnums everywhere is not really an option as that will create more spaghetti if there are more than two of them. (usually 4-10)
Is there a better way?
UPDATE
Guys, this is a low-level question about the picture above, not really a queston about large scale architecture / design patterns. I'm using QMH, classes, et.al. where appropriate.
I just feel there should be a way to get the typed value from a typed control ref in one step. It feels kind of common.
In the caller VI, where the controls/indicators actually live, create all your references, then bundle them into clusters of relevant pieces. Pass the clusters into your subVIs, giving a given subVI only the cluster it needs. This both keeps your conpane cleaned up and and makes it clear the interface that each subVI is talking to. Instead of a cluster, you may want to create a LV class to further encapsulate and define the sub-UI operations, but that's generally only on larger projects where some components of the UI will be reused in other UIs.
I'm not sure there is a low-touch way to de-spaghetti a UI with lots of controls and indicators.
My suggestion is to rework the top-level VI into a queued message handler, which would allow you to decouple the user interaction from the application's response. In other words, rather than moving both the controls and the code that handles their changes to subVIs (as you're currently doing), this would keep the controls where they are (so you don't need to use ref nums and property nodes) and only move the code to subVIs.
This design pattern is built-in to recent versions of LabVIEW: navigate to File ยป Create Project to make LabVIEW generate a project you can evaluate. For more information about understanding how to extend and customize it, see this NI slide deck: Decisions Behind the Design of the
Queued Message Handler Template.
In general, it is not the best practice to read/write value using refnum in perspective of performance. It requires a thread swap to the UI thread each time (which is a heavy process), whereas the FP Terminal is privileged to be able to update the panel without switching execution threads and without mutex friction.
Using references to access value
Requires to update the front panel item every single time they are called.
They are a pass by reference function as opposed to a pass by value function. This means they are essentially pointers to specific memory locations. The pointers must be de-referenced, and then the value in memory updated. The process of de-referencing the variables causes them to be slower than Controls/Indicators, or Local Variables.
Property Nodes cause the front panel of a SubVI to remain in memory, which increases memory use. If the front panel of a SubVI is not displayed, remove property nodes to decrease memory use.
If after this you want to use this method you can use VI scripting to speed up the process: http://sine.ni.com/nips/cds/view/p/lang/en/nid/209110

LabVIEW: Programmatically setting FPGA I/O variables (templates?)

Question
Is there a way to programmatically set what FPGA variables I am reading from or writing to so that I can generalize my main simulation loop for every object that I want to run? The simulation loops for each object are identical except for which FPGA variables they read and write. Details follow.
Background
I have a code that uses LabVIEW OOP to define a bunch of things that I want to simulate. Each thing then has an update method that runs inside of a Timed Loop on an RT controller, takes a cluster of inputs, and returns a cluster of outputs. Some of these inputs come from an FPGA, and some of the outputs are passed back to the FPGA for some processing before being sent out to hardware.
My problem is that I have a separate simulation VI for every thing in my code, since different values are read from and returned to the FPGA for each thing. This is a pain for maintainability and seems to cry out for a better method. The problem is illustrated below. The important parts are the FPGA input and output nodes (change for every thing), and the input and output clusters for the update method (always the same).
Is there some way to define a generic main simulation VI and then programmatically (maybe with properties stored in my things) tell it which specific inputs and outputs to use from the FPGA?
If so then I think the obvious next step would be to make the main simulation loop a public method for my objects and just call that method for each object that I need to simulate.
Thanks!
The short answer is no. Unfortunately once you get down to the hardware level with LabVIEW FPGA things begin to get very static and rely on hard-coded IO access. This is typically handled exactly how you have presented your current approach. However, you may be able encapsulate the IO access with a bit of trickery here.
Consider this, define the IO nodes on your diagram as interfaces and abstract them away with a function (or VI or method, whichever term you prefer). You can implement this with either a dynamic VI call or an object oriented approach.
You know the data types defined by your interface are well known because you are pushing and pulling them from clusters that do not change.
By abstracting away the hardware IO with a method call you can then maintain a library of function calls that represent unique hardware access for every "thing" in your system. This will encapsulate changes to the hardware IO access within a piece of code dedicated to that job.
Using dynamic VI calls is ugly but you can use the properties of your "things" to dictate the path to the exact function you need to call for that thing's IO.
An object oriented approach might have you create a small class hierarchy with a root object that represents generic IO access (probably doing nothing) with children overriding a core method call for reading or writing. This call would take your FPGA reference in and spit out the variables every hardware call will return (or vice versa for a read). Under the hood it is taking care of deciding exactly which IO on the FPGA to access. Example below:
Keep in mind that this is nowhere near functional, I just wanted you to see what the diagram might look like. The approach will help you further generalize your main loop and allow you to embed it within a public call as you had suggested.
This looks like an [object mapping] problem which LabVIEW doesn't have great support for, but it can be done.
My code maps one cluster to another assuming the control types are the same using a 2 column array as a "lookup."

How to access object parent in D

Say I have a class, Master, that starts up my program, and I have another class, TerminalIO, that has functions and data for talking to stdin and stdout. I then instantiate a Master object from main().
In code within the methods of TerminalIO, how would I access the properties and functions of Master?
The reason I'm asking about this is because my program needs to store some shared data (both enums and regular variables), and I was wanting to know of an efficient way to do that. I'm not so sure this is the best way, but it's certainly better than toying with the package keyword and trying to store "global" data at module level or whathaveyou.
I think it's worth noting that I will have many other objects that also want access to this shared data, so a simple reference may not be the best of ideas.
You will have to get a reference to Master inside your TerminalIO.
There are a couple of ways you could use:
Have Master be a singleton, so there is only one instance which you can access with Master.instance, so you'll have something like Master.instance.masterProperty.
Having a TerminalIO factory method in Master which constructs a TerminalIO and passes a Master reference to the constructor.

How to share/reuse a Lua script for multiple entities?

I'm in the design/skeleton coding phase of my C++ game with Lua scripting, but I have run into a design issue:
The game will have many copies of the same kind of entities, with behavior controlled by the same script. Is there a straightforward way I can share the script between entities of the same type in a single lua_state? I have only been able to find this question asked a couple of times on the Internet; I have read mixed feedback on whether or not it's a good idea to load the same script in different lua_state's, and not in-depth feedback on alternatives.
It's simple and bullet-proof, but I think loading, compiling, and storing addition copies of the same byte code with each instance of the same entity type created is a tragic waste, so I would like to figure out a smarter solution.
These are the two solutions I have thought of. I'm not new to programming or C or OO concepts but I am still learning when it comes to Lua and especially the Lua/C API. I think my ideas are sound but I am not even sure how I would go about implementing them.:
Implement OO in the Lua script and have each entity be represented by a Lua object; all the Lua logic would act on the object. This would also have the benefit (or the "benefit") of allowing the global environment to be changed by anything single entity.
Encapsulate each entity in its own environment using setfenv and copy references of all of the functions from the global space. As I understand it the env is just a different table than the default global, but I've looked into setfenv but I don't know how I would do that.
1 and 2 are just different sides of the same coin, more or less. It's simply a matter of where the object goes. In type 1, the object is an explicit part of the Lua script. Which means the script decides how it wants to set up its objects.
In type 2, the object is the environment. It is still a Lua table, but one created for it by the external code. The script cannot break free of the confines of this object, except in the ways that the external code allows.
The easiest way for me to implement type 1 would be with Luabind. I'd have an AI object as a C++ class, which Lua would be able to derive from. Running the "main script" for that AI would create an instance of that class. You would pass the script parameters, like the name of the entity it controls, maybe a reference it can use to control it, etc.
Type 2 is fairly simple. First, you create the new environment by creating an empty table and populating it with the global variables that you want the user to be able to have access to. These would be for things like talking to game-state (find other objects in the scene, etc), ways to move the entity in question around, and so forth. There are metatable tricks you can play to effectively make these values immutable and constant, so the user can't modify them later.
Then, you load the script with lua_loadstring or lua_loadfile. This puts a function on the Lua stack that represents that Lua script. Then you apply this table as that script function's environment with lua_setfenv. You can then run that script, passing whatever variables you wish (the name of the entity, etc).

Selecting the Correct View for an Object Type

I've had this problem many times before, and I've never had a solution I felt good about.
Let's say I have a Transaction base class and two derived classes AdjustmentTransaction and IssueTransaction.
I have a list of transactions in the UI, and each transaction is of the concrete type AdjustmentTransaction or IssueTransaction.
When I select a transaction, and click an "Edit" button, I need to decide whether to show an AdjustmentTransactionEditorForm or an IssueTransactionEditorForm.
The question is how do I go about doing this in an OO fashion without having to use a switch statement on the type of the selected transaction? The switch statement works but feels kludgy. I feel like I should be able to somehow exploit the parallel inheritance hierarchy between Transactions and TransactionEditors.
I could have an EditorForm property on my Transaction, but that is a horrible mixing of my UI peanut butter with my Model chocolate.
Thanks in advance.
You need to map your "EditorForm" to a transaction at some point. You have a couple options:
A switch statement...like you, I think this stinks, and scales poorly.
An abstract "EditorForm" property in base Transaction class, this scales better, but has poor seperation of concerns.
A Type -> Form mapper in your frontend. This scales fairly well, and keeps good seperation.
In C#, I'd implement a Type -> Form mapper like this:
Dictionary <Type,Type> typeMapper = new Dictionary<Type,Type>();
typeMapper.Add(typeof(AdjustTransaction), typeof(AdjustTransactionForm));
// etc, in this example, I'm populating it by hand,
// in real life, I'd use a key/value pair mapping config file,
// and populate it at runtime.
then, when edit is clicked:
Type formToGet;
if (typeMapper.TryGetValue(CurrentTransaction.GetType(), out formToGet))
{
Form newForm = (Form)Activator.CreateInstance(formToGet);
}
You probably don't want to tie it to the inheritance tree--that will bind you up pretty good later when you get a slight requirements change.
The relationship should be specified somewhere in an external file. Something that describes the relationship:
Editing AdujustmentTransaction = AdjustmentTransactionEditorForm
Editing IssueTransaction = IssueTransactionEditorForm
With a little bit of parsing and some better language than I've used here, this file could become very generalized and reusable--you could reuse forms for different objects if required, or change which form is used to edit an object without too much effort.
(You might want users named "Joe" to use "JoeIssueTransactionEditorForm" instead, this could pretty easily be worked into your "language")
This is essentially Dependency Injection--You can probably use Spring to solve the problem in more general terms.
Do I miss something in the question? I just ask because the obvious OO answer would be: Polymorph
Just execute Transaction.editWindow() (or however you want to call it), and
overwrite the method in AdjustmentTransaction and IssueTrasaction with the required functionality. The call to element.editWindow() then opens the right dialog for you.
An alternative to the Dictionary/Config File approach would be
1) to define a interface for each of the transaction editors.
2) In your EXE or UI assembly have each of the forms register itself with the assembly that creates the individual transaction.
3) The class controlling the registration should be a singleton so you don't have multiple form instances floating around.
3) When a individual transaction is created it pulls out the correct form variable from the registration object and assigns it do an internal variable.
4) When the Edit method is called it just uses the Show method of the internal method to start the chain of calls that will result in the display of that transacton editor.
This eliminates the need for config files and dictionaries. It continues to separate the UI from the object. Plus you don't need any switch statement
The downside is having to write the interface for each every form in addition to the form itself.
If you have a great deal of different types of editors (dozens) then in that case I recommend that you use the Command Pattern
You have a master command that contains the dictonary recommend by Jonathan. That commands in turns will use that dictornary to execute one of a number of other command that calls the correct form with the correct object. The forms continue to be separate from the object themselves. The forms reside in the Command assembly. In addition you don't have to update the EXE to add another editor only the Command assembly. Finally by putting things inside of Command you can implement Undo/Redo a lot easier. (Implement a Unexecute as well as a Execute)