Browse Tag: LabVIEW

Logo of the Rust project

Why Rust? (The More Technical Edition)

I’ve written a high-level view of why I got interested in Rust on the Wiresmith Technology site.

After many conversations at GDevCon last week, I felt it would be helpful to put down the technical reasons that Rust appealed to me and how I (and therefore you) could decide what a suitable language is for your test & measurement applications.

What’s In A Language

As I spoke to various people, I got more explicit on the areas I’m evaluating for any given programming language.

  1. Mental/Programming “Model” – This is a hard one to explain, but the simple version is some languages just fit the way you think and some don’t. The model includes technical aspects such as your comfort with manual memory management or imperative vs. functional styles.
  2. Runtime/Deployment Capabilities – Can I run this where I want? Different languages are better suited to environments like the web, docker, microcontrollers, and desktops. There are also performance considerations – is this language’s run time environment capable of high-performance or real-time use cases if you need them?
  3. Tooling – Are the tools around the language high quality and meet your needs? These might be tools like package managers, documentation generators, build automation and orchestration.

These are the three most significant areas I use when examining languages.

Why Look Elsewhere (or where LabVIEW is weak)?

I first started using LabVIEW around 15 years ago. So it isn’t a bad tool. Otherwise, I would have jumped ship long ago!

However, my needs have changed, and I’ve seen new capabilities become available in other languages I envied.

My trajectory has moved me into more projects that I call product development or prototyping. In this area, I found some pain points with LabVIEW:

  • I was moving away from its core in test & measurement, meaning more gaps and less investment in the areas I’m using.
  • The emphasis on software engineering tools has grown as development is done over a more extended period and put into the hands of more users who aren’t familiar with the technology.
  • Only deploying to the desktop or NI’s hardware became restrictive. I’ve had customers where the right solution is an embedded PC or high-performance server, and LabVIEW is difficult to deploy to these.
  • Increasingly, there is a need to integrate into web technologies where LabVIEW is poor—for example, running a web server to collect data.

These are my reasons, and they will not apply to your exact circumstances. This is what I want to emphasise here.

My message is not that everyone should be switching to Rust. In my case, it is a great option. If you are working on an automated test system, for example, you probably don’t have the same pain points, and LabVIEW may work very well for you.

Where Did I Look?

So, lets talk through some languages I’ve investigated and highlight some of their unique capabilities and limitations that might be interesting.

Javascript/Typescript

My first trip into text-based languages was Javascript. Having built a web backend in LabVIEW, it turned out the web server had serious scalability issues at the time. LabVIEW’s web services are challenging to use in anything beyond simple use cases.

Javascript is an interpreted language and generally runs in a very event-driven manner. Being interpreted means it isn’t the fastest (although it’s [JIT compiler](https://medium.com/nerd-for-tech/inside-the-v8-engine-b81aff3eecdb) means it is faster than you might think). Still, it is well suited to web environments where you find it as _the_ language in the browser, and Node.js means you can build pretty complex web servers with it.

Put simply, though, it is not designed to interact with the hardware system, so it is unlikely you will ever see this on a desktop or embedded system (though there are projects to make it a little easier).

The tooling is reasonably good, but it is a little disjointed and moves quickly. Picking up an 8-year-old project recently required a decent chunk of time to modernise everything to the changes that have occurred!

C#

In the LabVIEW NXG days, NI told us that it would be built in C#, and at least to start with, you would need to use C# to extend the environment.

So I decided I wanted to get my head around it, so I wrote the first version of G CLI in it.

C# is a compiled language that runs on a virtual machine-like runtime called the .net CLR (common language run time). It is designed to be extremely powerful for large applications, having been created by Microsoft as a response to Java.

One of the critical characteristics of C# is that it is a garbage-collected language.

Garbage collection means that instead of the user manually controlling memory allocation, a periodic process in the runtime reviews the current objects in memory and frees whichever aren’t used any more.

The big pro is that you don’t have to worry about forgetting to free memory or other memory-related issues as a user. A significant con is that when the garbage collector runs, it can affect the performance of your application. This performance isn’t critical in many applications, but high-performance or real-time applications are negatively affected.

The large runtime also impacts its uses in embedded applications, but it will run in most other places now there is Linux support and container support – it is most commonly found in desktop applications and web applications.

I also didn’t like the exception-style error handling, which has bothered me in many languages after coming from LabVIEW.

For me, the performance may limit its usage, so once NXG disappeared, so did my use of C#. However, this could be hugely powerful in many applications where you use LabVIEW if it ticks some other boxes.

C/C++

Because of where I ended up – it is worth a small shout out to C and C++.

These are systems languages. Systems languages are designed to run “close to the hardware” and are what many operating systems are built with and interoperate very well with.

They are widely supported across different hardware, and pretty much every other language in the world can call libraries created with these since their minimal runtime is generally built into every environment you might run code in (excluding bare metal).

I picked them up because I needed maximum performance for part of a LabVIEW application, so we wrote the processing logic in C and called in from LabVIEW.

A lot of crucial elements overlap with Rust, so why did I skip over these:

  • C is not a particularly expressive language, and I felt like it would get unproductive without built in templating/generics/polymorphism. C++ is better for this.
  • The test library seemed broken again every time I returned to this project. Package management is limited (but improving), and I could see a lot of fighting with tooling.
  • It is very easy to make memory mistakes that cause application crashes. I was happy building small functions in them, but building a complete application without memory issues seemed daunting.

Python

Another language I’ve been using more is Python.

Famously, Python has a huge user base and a wide array of libraries written for it, especially in data analysis.

The tooling is also good, with excellent testing capabilities and a reasonable package manager (with a few quirks!)

However, I found two significant downsides:

  • Python is an interpreted language, which means it has a significant run time and relatively poor performance. Although not as bad as some believe, most heavy lifting is handed off to compiled libraries.
  • I could not get on with the dynamic typing. I completed one web backend in Python and was cursing the typing constantly!

There is a lot of talk about Python in the LabVIEW ecosystem, but I suspect it is overhyped. For me, typing was a big issue that made me very reluctant to build anything significant in it.

Its power is in automation, connecting different libraries quickly and easily. So, in a test environment, it could be great for building individual test steps with a pretty defined scope.

I still use Python for simple automation tasks or interactive data analysis to experiment with different techniques. I know there will be a library somewhere in Python!

Rust

Rust has proven to be my way forward for several reasons. I have been working with it for 3-4 years at this point and found:

  • The language and type system to be expressive and powerful (but some find it too complex and explicit).
  • The memory safety guarantees resolved my no.1 concern with C++.
  • The tooling ecosystem seems to be second to none. Package management, testing, benchmarking, and documentation are all well-covered and ingrained in the language.
  • It is flexible with deployment. It is a systems language, so I can deploy it to a microcontroller or a large server. I’ve also been experimenting with OpenCL, which still needs small portions in C but allows the use of GPUs, DSPs and other hardware accelerators.

These allow me to offer a better service to my customers by leveraging a range of modern hardware without bumping up against limits. Meanwhile, I still feel as productive as I do in LabVIEW.

There are downsides, of course – Rust does require you to manage your memory, which can be a learning curve and makes applications more complex. But this is necessary for some of the deployment flexibility.

Summary – What Is Right For You?

So what should you do? Well, in many cases, sticking with LabVIEW is a good option if you aren’t feeling the same pain that I am. This article is my story, not a roadmap for everyone.

If you are feeling pain, though, hopefully, the summary above will help signpost you to a language that may fit what you need and start doing some research.

Does it fit my mental model? Do I like the community? Have others managed to solve similar problems in it?

This article should help you to start asking these questions.

Getting VI Analyzer Into Our Workflow

We have long known that VI Analyzer is a good idea – much like unit testing – people on the other side of adoption swear by it.

We’ve found a few hurdles for mainstream adoption into our process, and I suspect yours too.

1. Understanding Why

The first step in adopting VI Analyzer (and keeping that adoption going) is understanding why you are doing it!

What I mean by this is you need to make the tool fit your process – not the other way round. If you use VI Analyzer because NI says so then you’re going to see less benefit and it will feel a lot more effort.

For me –  I believe that consistent style and code inspection reduces bugs and improves readability of the system. I have a style guideline, but I don’t always follow it. As I typically work on my own, then code reviews aren’t an option.

Your “why” will probably be very similar but the subtle differences will make some of the following items slightly different from mine.

2. Complicated Setup

As I said above, VI Analyzer is all about consistency for us. We want every project to follow the same style guidelines. Unfortunately, VI Analyzer does not make it very natural to create a standard test configuration and share it between projects since there is a single configuration file for test setup and which VIs to test.

These are the steps that I went through to build a standard configuration:

  1. Start with your style guidelines. I made mine into a table and identified what already had a VI Analyzer test, what had a custom test in the community, what could have a custom test and what was not testable.

    Style Guide With Tests
  2. I downloaded the custom tests that are available online and created a couple of key tests myself. I didn’t do them all, and I will expand my coverage over time.
  3. I used a project to create a VI Analyzer configuration file. I worked through the tests and configured them to my style guideline. Then I removed all of the VIs to be tested. I saved this configuration file as my standard.
  4. I created a VI package which would install the custom tests and the configuration file to a shared location in my documents. Full credit to Fabiola De La Cueva and Delacor for this idea. They have been helping their customers with this for some time. (You can see their video of this on Youtube)

By completing these steps up front, I can introduce a consistent VI Analyzer configuration to a new project quickly and easily.

3. Defining A Trigger

As with any good habit, you need a trigger to tell you when to do it else you often won’t follow through. There are a few common triggers that I have seen people using:

  • Post-Commit in a CI Server – I’m not a big fan of this one because you now need another trigger to review the results and implement the changes.
  • Pre-Code Review – This is a great one if you are on a team. You should test with VI Analyzer before a code review. You don’t want to waste time picking up things a machine can identify faster. As I am a solo developer, this one is limited for me.
  • Feature Branch Merge – If you are using a branching workflow in Git or Mercurial, then you can use a feature branch merge as a trigger. This is a good trigger as it should limit the scope of what needs testing. However, if the change list gets long, then there could be a lot to review.
  • Pre-Commit – I use a Javascript IDE that has a tick box in the commit tool to check style before the commit. This workflow is what I want in LabVIEW. Testing at each commit makes the tests quick (since only a few files have changed) and it means that you fix issues while you are in the mindset of that code. It also means that once you commit the code, it is “done”. The main problem with this in VI Analyzer is the execution time of the tests.

4. Speed

I wanted my trigger to be a commit. I feel like the code should go through VI Analyzer to be “finished” and only “finished” code should be committed.

This is a problem though. Analyzing a whole project can take many minutes, and I might commit 10+ times a day.

One way to solve this would be to test only changed code, but VI Analyzer lacks any native support for this workflow.

I have developed a tool to tie it to git changes. It isn’t great, so we haven’t shared it yet (it still lacks many essential features), but it has started us using VI Analyzer regularly.

This tool will take a configuration file and then run it against only the code that Git shows as changed. Testing only the changes cuts the test time and now means that it is possible to check at each commit and fix the changes before that commit.

Ugly – But Basically Works

By overcoming these hurdles, VI Analyzer has become a standard part of our workflow. I hope you can use this to incorporate it as well.

Refactoring: When Should I Create A SubVI?

I don’t write code in the best way the first time. No-one does. Instead, if we want to get to a state of clean code (readable, maintainable etc.), we often have to put specific effort into it.

Martin Fowler’s Refactoring book summarises it nicely when talking about refactoring. You need two hats. One for adding functionality and the other for refactoring. Your process may have a nice point to change hats (I use TDD which does) – or you may have to be more deliberate. But at some point, you need to think about refactoring.

I’m not going to go into loads of detail on refactoring now. Instead, I want to focus on one type of refactoring that I use a lot – creating more subVIs.

Why Refactor Code to have more subVIs?

There are several reasons why code with more, smaller subVIs will tend to be easier to work with than a flat VI:

  1. The diagram is smaller – The simplest of them all – your diagram now fits on the screen!
  2. Improved readability through abstraction – This can be a contentious point. We are putting the detailed implementation another click of the mouse away which some people dislike. My experience is that this is outweighed by how much easier the code is to read. By creating a well-named, cohesive subVI, the calling VI is faster to read since you don’t have to worry about the details. You can worry about the problem it is solving and dig into the details if/when you have to. There are also testing and debugging advantages since the new subVI can be debugged in isolation.
  3. Clear and Obvious Coupling – Coupling is one of the primary concepts in software design that you need to grow to understand. A flat diagram can easily hide coupling in the noise, but once you create subVIs, it is obvious if a subVI has too many inputs or inputs that you wouldn’t expect it to have. These are both signs of coupling problems.

Where to start?

I signed up for a presentation at NI Week to talk about clean code and needed to talk about this topic. The day before planning to write the subVI section, I was working on a customer project. As I have a young baby at home, I try to leave at 5 pm every night now, but it was getting on for 5.40pm, and my Wife was messaging me to see where I was so I got the code running but never put on my refactoring hat.

When I came to write my presentation, I realised that stepping through the refactoring of this code was the perfect example! The code I abandoned that evening is the code in the steps below.

Look for Commented Sections

The first and simplest clue, is to look for sections of code with comments describing what they do. If it is enough of an important chunk to comment, it is probably cohesive enough to make a good subVI.

The Original Code

See the sections for formatting at the bottom? There are three types of data to be formatted for the table. One is already in a subVI but the other two are just labelled as doing the conversion. This is the classic sign of a subVI that hasn’t been created yet.

The first step here is to turn these all into subVIs.

Commented Sections in SubVIs

I’ve created the subVIs, aligned them and given them a consistent naming convention.

Different Levels of Abstraction

I’m still looking for a better term for this, but there is still a smell in the code above for me.

Most of the code is now subVIs doing non-trivial functions. Loading from a log, generating tables. But there is a section on the left that is doing array manipulation. This is a problem because it is too much detail for what this code describes. This code is supposed to “say” load the data from the log, convert the sections to a table and combine them all. But instead this story includes handling memory allocation as well!

So my next step is to abstract this into a more descriptive subVI.

Building The Table In A SubVI

I hope you agree; this code is now much more straightforward to read. It is doing everything it was before (as efficiently as it was) but as developers, we can become faster at understanding the code.

Did you notice the coupling?

This highlighted a nice reason for this refactoring. Why is a build table function using an array of timestamps?

Why Use Timestamps To Build A Table?

We sucked these in as part of the “create subVI” process, but they don’t belong. We can refactor the timestamp array out but using the rows in the time table instead to remove the input.

This is a somewhat trivial example, but by abstracting out the subVIs, we can now understand our code in a way that is clearer than before and better visualise the coupling between functional components.

Are we done?

Naturally there is no “perfect” state. This was the stage I stopped at since I had removed the immediate “smells” and the code worked well. Now the code structure is clearer though it actually highlights some other things we could consider:

  1. The build table code could be generalised for reuse by removing some of the labelling. If I need this same function elsewhere, I may come and grab this code.
  2. The program flow shown is that we generate each sub table before building a large table. It may have a higher performance to directly insert each of the subtables directly into the pre-allocated table. Right now the solution above is simpler, and I don’t have any performance concerns, so I haven’t done this.

I’m going to keep on about this – These potential changes are much more obvious in the new structure than the old – that is why those first steps are important. There is also a point where you have to say good enough, or there isn’t enough information to know what is the next best step (options 1 and 2 above may clash so we don’t do them until we know which we want).

A Note On Testing

Isn’t there a risk of breaking your code with refactoring?  In theory refactoring should not make any functional changes to your code but we have all done things with unintended consequences!

Allowing low-risk refactoring is one of the ways that unit testing leads to better code. Because I have tests around this section of code, I could change it as much as I wanted with confidence that it still works. This is why we treat unit testing as a foundational principle at Wiresmith Technology.

Why Do Your Loops Run?

One of the key architectural rules I learnt in LabVIEW is what I always call in my head the “single source of synchronisation” rule. I need to make two opening statements on this:

  • Someone/Something taught me this – Huge apologies I can’t remember the source of this but thank you whoever you are!
  • Its name makes something simple sound very complicated; it isn’t!

It made an appearance in my post on architectural language so I wanted to expand on it. The quote there was:

A loop within an application component. It has a single reason to run.

Why Loops Run

By “run” what I mean is what triggers an iteration of that loop. I’ve identified these sources:

  • Time – Intended to run every x ms.
  • Event – Either a UI or User Event, the loop contains an event structure.
  • Data – Basically a queued message handler but “data” means anything that means a loop waits for data. A data interface could be queues, notifiers, streams, DAQmx etc. Some external process is forcing us to wait for new data to be available.

The rule means, if one loop is trying to use two of these methods (or multiples of one of these types) then problems may occur. Examples might be:

  • Using the timeout on an event structure (did you know it won’t fire if user events fire, even if you aren’t handling them? Thanks Chris R for this demo!) Thanks Fab for the correction: This was a bug that has been fixed.
  • Using the timeout of a queue to perform a repetitive action.

As you can see – time is usually the conflict because the others are kind of obvious to avoid having in the same loop.

Why This Rule Exists

Put simply, in most cases where two of these exist there is a conflict which is hard to resolve consistently 100% of the time, mostly because the event and data drivers depend on external components which aren’t predictable.

Take the timeout case of the queued message handler. If you want to check a state about every 1 second, then the best case is a new external message once every 2 seconds. Then 1 second after that message arrives you perform the check. Maybe you will get a second check before the next message, maybe not. Most likely you will end up performing the check every 2 seconds. Perhaps that is acceptable?

However then an external component generates messages every 0.1 seconds. Now that check doesn’t happen ever, through no fault of yours! (In the context of the code in this loop).

But I Need To…

Perhaps there is a case where you want to break this rule. I have two solutions:

Proxy Loops

Use a second loop as a “proxy”. For example in the case above have a second loop which runs every 1 seconds and enqueues a message for the check.

Another example is when you have an API which generates messages on an event but you need it in a queue. If you have used the actor framework, this how you extend actor core for GUIs.

Break The Rule… And Be Very Careful

If you don’t see a way to design around this rule, then you need to know you are breaking it and be very careful. Most likely by adding some management code to a loop.

The example I could think of was if you needed data from two loops. In this case, you would write code to read from each queue. If one read timed out, perhaps you store the successful data and then try again, reading only the failed queue.

I don’t think there are many cases, but rules are about knowing when you break them and why!

Whats Your Architectural Language?

The word of the year here at Wiresmith Technology is process. In areas where I have standardised processes life has got easier, less stressful and more reliable. Now I’m looking at the software processes to see where we can get the same benefits.

Something that I have wanted to address for a while is architecture. Working on my own has given me the benefit of being able to be quite ad-hoc and try different designs on different projects.

Well, I often think coming back to your own work after 6 months isn’t so different from working with someone else and I’ve certainly felt the drag of having to review how I built the architecture on each project. So I want to at least have some standard templates.

What I found when I came to it was I first had to define what is in a program!

Language Is Important

There are so many conflicting terms and every framework has its own terminology.

I really wanted to start with knowing what I want in a generic sense. By doing this without looking at specific frameworks it gives me the freedom to find a framework that fits the way I work best (as well as the freedom to change or not use frameworks depending on the project).

I’ve seen this approach work in my business. I’ve been trying to find tools to help me be more productive, but it isn’t until I decide on what the process is that these tools are supporting, I waste hours trying to choose as I have no way to determine what is best!

So before even trying to work with templates or frameworks, I reviewed my previous projects to try and pull out and name the different elements of my architectures so I can map other tools to this.

What I Picked

So here is what I listed as my architectural definitions. Before you read them, understand I am sharing these for your curiosity – you may have your own set of definitions in your team already. This isn’t about right or wrong, this is about consistency between team members and projects.

Term Description Not to be confused with…
Application Component An asynchronous VI with it’s own lifetime and own control of when to run. This is the top level of the architecture design.
Data A piece of engineering data e.g. acquired data. Messages: We split this concept as messages are more framework-oriented.
Message A framework command for a process to do something. Data: although they are data in the strictest sense, they are not directly related to the data involved in the engineering domain.
Message Handler A process that receives heterogenous messages and data. Data-driven process: this has homogeneous data to handle.
Module A set of related code. In our system, it is a class. It is generally unit testable. Module (DQMH), Actor (AF) – These are processes or message handlers.
Process A loop within an application component. It has a single reason to run.

I’m pretty happy with this – the one element of confusion is where the actor style module (whether that is an actor framework actor or another QMH based framework like DQMH). In reality, this sits somewhere between a module and a process but I need to experiment more with how to think about those.

The one I think is particularly important is modules. Too often the important logic gets muddled and mixed with framework code

Next Steps

For me the next step now is to create templates or frameworks to handle these items in a consistent way – more on that in a future post.

My challenge to you is to think about this for yourself. Maybe you already have a framework so you don’t need definitions like this, but where do you find you or your time are inconsistent over time and would a common language help?

Testing Events In VI Tester

The APIs that you have to test are not always simple. As well as passing data they may involve events (with the front panel or with user events).

The other day I needed to test that an event fired as part of a test case. I could see a generic solution, so I created a template for it. I had two requirements:

  1. If the event doesn’t fire – test fails.
  2. If the event fires with the wrong data – test fails.

In my given when then sequence then we end up with a test that follows the structure:

  • Given: Who knows, in this case, a UI library has been tied to a control.
  • When: We take some action that should cause an event on that control.
  • Then: Check the event.

To check the event we create an event structure outside of a loop as we don’t want to handle multiple events. We need two cases:

  1. A timeout case with a suitable timeout – In this case, we call the Test Case.lvclass:fail.vi to fail the test. This should never run if the when code fired the event.

    Failing Path
  2. A case that handles the event – If you don’t care about the data then you can do nothing here, otherwise, include tests on the data included in the event.

    Passing Path

 

Additional Complexity

  1. Dynamic Event Registration: If this is a user event then you will need to register for the event. I’ve included this in my template, but you must move the event registration to the given case. If you haven’t registered the event before the action in the when case, it won’t ever fire.
  2. Parallel/Dynamic Event Generation: If your event is in some dynamic code you may need to have this running. My advice: DONT. Try and pull out the internal API and test synchronously. Asynchronous testing in LabVIEW introduces timing concerns which make your tests much more complicated.

Where To Get It

If you want to use this template, or even if you are just using VI tester you can download the new version of the VI Tester Advanced Comparisons (VITAC) tool from https://github.com/WiresmithTech/VITAC/releases/tag/v1.1.0.

 

Where Do I Save Config Files In LabVIEW?

When writing applications that will be used by anyone else you will need a configuration file. In my experience, this is almost universal and the more I make configurable, the more powerful the software becomes and the less small changes I have to make for my customers.

Where do we save config files in LabVIEW? The landscape is more complicated than you would think! In this post, I’m going to summarise what we do on our LabVIEW projects. We are focusing on Windows since RT is simpler (put it in /c/) and I don’t use Mac or Linux with LabVIEW.

Types of Config Data

I’m going to refer to two types of config data:

  • Global Data: No matter who logs into the system they should share the same configuration. In my experience, this covers the vast majority of industrial applications.
  • User Data: Configurations that should change depending on the user. This might be screen layouts for example.

Files or Registry?

Microsoft is actually quite keen that you put this data in the registry – that is what it is for. There is a Software folder in each top level folder where you should create your own Company/App folder structure and you can store settings as different variable types.

For user data, you can store it under HKEY_CURRENT_USER and for global data, you can store it under HKEY_LOCAL_MACHINE. In many ways it is a pretty nice solution to the problem, however, I’ve avoided it for 3 reasons:

  1. Files are much easier for users to get, edit or send you. Whilst I don’t want them directly editing the files much it is great that when there is a problem they can send me a file or even a screenshot of the file (when it is readable) so I can understand their setup.
  2. Files make save as… much easier if the user wants to be able to switch between configurations.
  3. Files are universal. Although I don’t have much cross-platform code I like that I can create multi purpose configuration libraries that work on Windows or RT. Without this, I would have to have different code for the different platforms.

I am curious though about who is using this. Please leave a comment below and let me know why you like this and if I have anything wrong.

If Files, Where?

OK, so we have decided on files, where should we put them? Helpfully Microsoft has an article on this however 7 years on there are still issues!

User Data

User data is the easiest and where Microsoft’s advice still works. In each user folder, there is a hidden AppData folder. This is designed to hold user-based configuration files and so the user has full read/write access to this. It is just hidden to protect you from “users with initiative” as Fab puts it in this presentation! Within here you should create a folder structure with Company Name\App Name to follow the standard convention.

To get this path use the Get System Directory.vi with the User Application Data input.

 

Global Data

Global data is where this gets messy. There is an equivalent folder to the user AppData folder for this purpose, but…

In XP all worked well. It was located under All Users\Application Data and all users had write access and software worked.

Then Windows 7 came and two changes occurred:

  1. The location was changed to C:\ProgramData (A hidden folder)
  2. Folders had restricted access. The creator/owner has write access but no-one else.

One use case for this is to install fixed configurations at installation time and this works well since everyone has read access. However, if you need to write these after installation you normally do not have access.

The solution to use this? You need to set the permissions as part of a post install step to allow all users to have write access to the relevant folders.

One day, I may sit down and get this set up automatically as a post install step. For now, I have too many concerns about managing failures of this causing extra support. My solution? Use the public documents folder.

I follow the same structure but in Public Documents instead of Public Application Data. So far I’m happy with this decision and I haven’t had any headaches due to this.

I would love to hear your thoughts. What do you do? Am I wrong?

Given, When, Then In LabVIEW Tests

A few months ago in the Austrian alps I was skiing and attempting my second ever slalom run on my trip. Those of you that I have seen recently will now it didn’t end well!

I gathered too much speed, caught some ice and tore my ACL.

Since then I have to do some exercises each morning to prepare it for surgery. I tend to try and watch some interesting talks while I do this and make use of my “bonus” time. They are often TED talks but I had watched many of the latest ones so, super geeky, I switched to Go To Conference talks which are software talks – mainly based around web technologies.

I find it interesting to watch some of the talks that skirt the edge of the technical and understand how they can be applied to LabVIEW. This was certainly true of Level Up Your Unit Tests.

Descriptive Tests

The talk is somewhat the story of a developers transition to a new testing tool and there is one piece that really appealed to me.

There is a concept I have come across before for a structure for acceptance tests called Given, When, Then. The idea is it clearly describes every aspect of a test situation:

  • Given: The pre-conditions.
  • When: The trigger or action.
  • Then: What the software/system should do in response.

For example:

Given we have a high temperature alarm, when the user clears the alarm then an alarm should no longer show as active.

In the video Trisha Gee describes a test framework that was new to her that actually describes the tests in this structure which greatly helps with clarity and highlights problems with the code if any section gets too large. Ideally:

  • Given is small. If it starts to get quite big this starts to sound more like an integration test and less of a unit test. It should also contain no tests – this is not the subject of the unit test.
  • When is tiny. This should ONLY be the code you are actually testing.
  • Then is tiny. This contains your actual tests and assertions. Given a unit test should test one thing there should only be one assertion here or multiple tightly related assertions.

Why Looks Matter

What struck me was that my unit tests – while quite effective – are a mess compared to my normal code. I tend to rattle through then and not give them the full attention that they need. This can hurt me when I have to return to them to understand why they fail.

So I have experimented by taking the descriptive structure of the framework that Trisha describes in the video and implementing it in LabVIEW. The idea is we want clearly separate sections for these with defined boundaries so I found flat sequence structures work well.

Let me give you a (kind of) before and after.

Before:

old-test-style

This is the old style. It works, well. However just looking at the code there are test cases spread throughout (5 in total) and it isn’t clear from the code alone what is being tested.

After:

given-when-then-test

(Yes this is a different test, I haven’t rewritten all of my tests to this format)

Here it is much clearer what is just setup code, what is the code under test and then what the conditions are that we really care about.

It also makes it really obvious if I had tests that were really just checking that the setup has worked which is what some of the tests in the before case are doing (Sometimes this can be really useful though, I think the answer is though that this code should have been tested somewhere else – but I need to think this through more)

Now I really am running out of things to say on unit testing! I have a few more OO posts in the pipeline as well as a couple of tips & tricks posts that I hope to do this year. It has been very busy the past couple of months but I will be having some time off over the summer while they reconstruct my knee! So expect a few more posts then.

 

UPDATE:

Thanks to the commenters below I wanted to include a couple of links.

  1. This template is now built into the VITAC toolkit at https://github.com/WiresmithTech/VITAC/releases (thanks for the prompt Fab!)
  2. Ivan’s tip below for adding this to the default class is great and I have this on all my systems now – http://kosist.org/2018/08/modify-default-vi-tester-testcase-template/

Bringing the Command Line Interface to LabVIEW

Those of you that know me or have been following the blog will know that for a while now I have been practicing test driven development in LabVIEW.

This is great, most of my LabVIEW projects now have 50-100 tests attached to them that check various parts of the system are working, but of course, this is only when I remember to run them!

We are all fallible, when it comes to 6pm and I want to go home, I add my last flourish, commit to source code and go home, forgetting to test.

 

Well with my JavaScript code I get a voice from the cloud that tells me off if I make a mistake. The voice is Jenkins – A build server which is used for continuous integration. Every time I check in my code, Jenkins tests and builds my code to make sure nothing is broken.

(Well the voice is an email, but you get the idea)

I get no such prompt with LabVIEW.

 

There have been a number of projects over the years to do this. JKI have a system that we managed to set up and get working some years ago but it depended on some intermediate files and took a bit of fiddling a couple of years ago.

In order to try and make it easier, a couple of years ago I learnt some Java to try and build a plugin for Jenkins which could talk to some corresponding LabVIEW code over TCP. But it was over-complicated and I was over-ambitious and never finished it.

When I then set it up for my javascript application, even though there is no built in support for it, it was so easy! Why?

 

The all-powerful command line interface!

 

Although most people have long given up on it (If you are a LabVIEW developer, your probably more of a GUI kind of person) it is still a common and straightforward way to get two programs to talk together (it forms the backbone of the Unix philosophy)

If we can use the command line, we can talk to Jenkins and any other technology which comes up for the next decade at least.

The problem is LabVIEW’s command line interface is quite basic. You can recieve calling arguments but can’t recieve or send text (stdIn and StdOut) and can’t return an exit code. That last bit is critical since it is how one program determines if another was successful, therefore how we signal to Jenkins whether we have succeeded or failed our tests.

labview-command-line-supported

JKI solved this problem through the use of batch files and text files but I wanted to try a different method.

I created LabVIEW CLI. This has two components:

labview-cli

  • A C# console application. This can run on the command line and basically proxies the interface through TCP to…
  • A corresponding LabVIEW library that gives us the ability to access the command line.

labview-cli-how-it-looks

The philosophy is that the C# application is very small but can be called directly by Jenkins or any other language and will then launch LabVIEW or our LabVIEW built application.

I’m hoping that by keeping it quite simple, it can become a building block for CI tools and others for LabVIEW.

So if your interested you can check out the builds on github and give it a go. I am not currently using this in anger so please don’t bet your job on it working! But early tests look good!

You will need to install the C# application with the installer and then there is a vip package for the LabVIEW library. Look at the readme on github and happy building!

Any issues you can create bugs on the github page or comment on the NI community page.

Labels, Labels, Everywhere

 

I’ve had a few long journeys over the last couple of weeks and managed to catch up on some reading.

In particular I have been jumping into some sections of one of my favourite programming books – Code Complete.

As with most books, the practical techniques directly apply to text based languages. Certain things like naming conventions for variables don’t readily apply to LabVIEW since everything is graphical.

However I think we need to think about text as well. It can be fast to read and unanbiguous in meaning (when done well).

LabVIEW supports text documentation, mostly you interact with it through the context help window.

However, as has been pointed out in the last couple of CLA Summits, we should look to reduce the amount we have to break out of our programming flow.

I’ve talked about comments before, but this triggered some other thoughts.

SubVI Names

Increasingly, certainly for internal APIs I find myself mostly relying on text on the icon other than where there is a well establised precendent (Like init or close).

I like this because it makes my code faster to scan, I don’t have to do the mental translation from icon to meaning if it isn’t automatic.

text-for-icon
Example where I have used text for icons

Think about the last time you drew a flow chart? You use text because it is quick and easy to get the meaning across.

(I know this has internationalisation implications, but this has not been a concern for me yet).

I am also aware of an advantage that we do have over C++ and it’s fellows when it comes to writing text. We can use descriptive names for our subVIs since we can include spaces.

Just because C++ has to use names like InitDaqCard() or ReadTemp() because they have to type it all the time. We can use full names for VIs like Initialise DAQ Card.vi or Read Ambient Temperature() and should take advantage of this.

Variables

Pah! Who needs them?

Well we may not name variables (very often) but controls and indicators can and should follow good conventions, with unambiguous names and inclusion of units. Like with the function names we are also not limited by text based languages naming restrictions in the same way.

Reading though, the part that really struck a chord with me though is about intermediate variables.

Code Complete advocates meaningful intermediate names (so not i, j for loop counters for example). This hugely impacts the readability of code.

It actually goes further and suggests forgoing the performance hit and even adding unneeded variables for complex routines where they improve the readability by giving meaning to intermediate values.

Again does this apply to LabVIEW? We don’t have variables?

Actually we do, they are called wires.

When was the last time you drew a block diagram on a whiteboard and left the arrows unlabeled?

It would be hard to read but I find I rarely label wires in LabVIEW (unless they are obviously unclear) and I suspect I’m not the only one.

Some comments but wires aren't clear or are ambiguous
Some comments but wires aren’t clear or are ambiguous

Context to these connections greatly improves readability. Again we may have them in LabVIEW using context help as some names automatically spread from functions.

But if we labeled wires more it could save you using context help, or even opening subVIs to understand what is going on. Do that a few times a day and the productivity adds up.

Larger but clearer with more wires labelled
Larger but clearer with more wires labelled

Oh, and unlike creating an intermediate variable for readability, this comes with no performance implications in LabVIEW!

I will be trying to use them more often over the next few weeks and see how much I can improve the readability of my code.

 

Does this make sense? Or am I completely wrong? Let me know in the comments.


By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close