Create a data streaming from C++ stream and read it in LabView

Hi all.

I'm working on a project that is to connect to a tracker of movement and reading data of position and orientation of this in real time. The code to get the data is in c ++, so I decided that the best way to do it would be to create a c++ DLL that contains all the functions necessary to first connect to the device and it reads the data and use the node to call a library function to power the Labview data.

I have a problem, because, ideally, I would like a continuous flow of data from the code c ++ in Labview, and I don't know how to do this. Put the node function of library call for a while loop seems like an obvious solution, but if I do it this way I'd have to reconnect to the device whenever I get the data, which is quite a bit too slow.

So my question is, if I created c ++ function that creates a data stream, could I read that in Labview without continually having to call a function? I would rather have only to call a function once, and then read the data stream until a stop command is given.

I'm using Labview 2010, version 10.0.

Apologies if the question is badly worded, thank you very much for your help.

Dave

dr8086 wrote:

This method resembles an excellent suggestion, but I have a few questions where I don't think I understood fully.

I understand the basic principle is to use a call library function node to access a DLL that creates an instance of the device object and passes a pointer too in labview. Then a separate call library function node would pass this pointer to another DLL that could access the device object, update and read the data. This part could be in a while loop, then continue on reading the data until a stop command is given.

That's all. I'm including some skeleton for example code. I am also including the code because I don't know how you experience multi threading so I show how you can use critical sections to avoid interactions between threads so that they do not lead to questions.

// exported function to access the devices
extern "C"  __declspec(dllexport) int __stdcall init(uintptr_t *ptrOut)
{
    *ptrOut= (uintptr_t)new CDevice();
    return 0;
}

extern "C"  __declspec(dllexport) int __stdcall get_data(uintptr_t ptr, double vals[], int size)
{
    return ((CDevice*)ptr)->get_data(vals, size);
}

extern "C"  __declspec(dllexport) int __stdcall close(uintptr_t ptr, double last_vals[], int size)
{
    int r= ((CDevice*)ptr)->close();
    ((CDevice*)ptr)->get_data(last_vals, size);
    delete (CDevice*)ptr;
    return r;
}

// h file
// Represents a device
class CDevice
{
public:
    virtual ~CDevice();
    int init();
    int get_data(double vals[], int size);
    int close();

    // only called by new thread
    int ThreadProc();

private:
    CRITICAL_SECTION    rBufferSafe;    // Needed for thread saftey
    vhtTrackerEmulator *tracker;
    HANDLE              hThread;
    double              buffer[500];
    int                 buffer_used;
    bool                done;       // this HAS to be protected by critical section since 2 threads access it. Use a get/set method with critical sections inside
}

//cpp file

DWORD WINAPI DeviceProc(LPVOID lpParam)
{
    ((CDevice*)lpParam)->ThreadProc();      // Call the function to do the work
    return 0;
}

CDevice::~CDevice()
{
    DeleteCriticalSection(&rBufferSafe);
}

int CDevice::init()
{
    tracker = new vhtTrackerEmulator();
    InitializeCriticalSection(&rBufferSafe);
    buffer_used= 0;
    done= false;
    hThread = CreateThread(NULL, 0, DeviceProc, this, 0, NULL); // this thread will now be saving data to an internal buffer
    return 0;
}

int CDevice::get_data(double vals[], int size)
{
    EnterCriticalSection(&rBufferSafe);
    if (vals)   // provides a way to get the current used buffer size
    {
        memcpy(vals, buffer, min(size, buffer_used));
        int len= min(size, buffer_used);
        buffer_used= 0;                 // Whatever wasn't read is erased
    } else  // just return the buffer size
        int len= buffer_used;
    LeaveCriticalSection(&rBufferSafe);
    return len;
}

int CDevice::close()
{
    done= true;
    WaitForSingleObject(hThread, INFINITE); // handle timeouts etc.
    delete tracker;
    tracker= NULL;
    return 0;
}

int CDevice::ThreadProc()
{
    while (!bdone)
    {
        tracker->update();
        EnterCriticalSection(&rBufferSafe);
        if (buffer_used<500)
            buffer[buffer_used++]= tracker->getRawData(0);
        LeaveCriticalSection(&rBufferSafe);
        Sleep(100);
    }
    return 0;
}

dr8086 wrote:

My main concern is that the object can get out of memory or be deallocated since it would not take place to any namespace or whatever it is.

As you create the object with the new, the object expire not until the dll is unloaded or the process (LabVIEW) closes. If the object will remain valid between condition LabVIEW dll calls not a not unload the dll (who does if the screws are closed). When that happens, I don't know exactly what happens to the active objects (that is, if you forgot to call close), I guess the system recovers the memory, but the device could still be opened.

What to do to make sure that everything is closed when the dll before I could call unloads close and remove the object is whenever I create a new object in the dll that I add to a list when the dll is unloaded, if the object is still on the list, that I'm deleting it.

dr8086 wrote:

I also have a more general question of programming on the purpose of the buffer. The buffer would essentially be a large table of position values, which are stored until they can be read in the rest of the VI?

Yes, see the code example.

However, according to the frequency with which you need to collect data from the device you have this buffer at all. That is, if take you a sample on every 100ms, then you can remove all threads and buffer related functions and instead to read data from the read feature itself like this:

double CDevice::get_data()
{
    tracker->update();
    return tracker->getRawData(0);
}

Because you need only a buffer and a separate if thread you collect data at a high frequency and you can not lose any data.

Matt

Tags: NI Software

Similar Questions

  • BlackBerry Z10 organizing data transfer from my Z10 and Q10 to my curve 9220

    Hi team,

    I want to transfer my contacts from Z10 and Q10 on my device inherited from curve 9220. I have already backed up my data using the BlackBerry link and I know that my curve is not compatible with BlackBerry Link. Can you give me a step-by-step procedure on how to synchronize my contacts from my BlackBerry 10 devices to my Gmail account? I intend to add my Gmail account on my device of curve and I sync my data out there.  Thank you for the quick response on this subject.

    See you soon!

    Lucena

    Even with an older BlackBerry which doesn't BB10 you can use the BB link to transfer information.

    http://docs.BlackBerry.com/en/smartphone_users/deliverables/47561/mwa1354393789617.jsp#mwa1354393854...

  • BlackBerry Q10 organizing data transfer from my Z10 and Q10 to my curve 9220


    You other thread replied.

    Please don't double post and cross post in the forum. Once is enough.

    http://supportforums.BlackBerry.com/T5/BlackBerry-Curve/transferring-Organizer-data-from-my-Z10-and-...

  • BlackBerry Smartphones Organizer data transfer from my Z10 and Q10 to my Curve 9220. Need help.


    Simply open your settings > accounts > your gmail account and turn on your synchronization comes into contact with the settings.

    Verify your Gmail account on the webmail of connection from a PC, and that all of your gmail contacts were synchronized to the server.

    Then, set up the Gmail account on your 9220 and in so doing, enable synchronization of gmail contacts.

  • Input data streams API, readFully()

    Hi all

    I was going through the javadoc for the API for the DataInput stream 4.5 in the Java.io package.

    Looking at the readFully methods, they claim that:

    See the general contract of the readFully  method of DataInput.
    

    I want to know what this means because I am currently using this method to read a DataInputStream in a byteArray and get an EOFException.

    I want to know how to use this method, what are its contractual agreement which the

    «See the general contract of the method of DataInput readFully "means.»

    Anyhelp would be appreciated here,

    Thank you

    Dan

    No problem.. It turns out that the DataInput was in fact an Interface within a single package

    If the contract methods readFully is clearly stated in the DataInput interface.

    Thanks for any answers that were typed!

  • Can we copy the folder and the name of the data file from Windows Explorer and paste as text in Word or Excel?

    I have two records with a similar file; some of them are duplicates, and some may have the same name, but contain different data.

    I would like to compare files from both folders by name and size of the file.  In this way, I could say if I duplicate files, or files with the same name with different data.

    I would copy and paste this information (as text or values) in Word or Excel.  Any way to do it?  Any other suggestions re: comparing these files?

    Just take the b out of my order and you will get info from size.

  • vCO workflow: create a virtual machine from a model and then ask the user about the CPU, memory size...

    Hi guys,.

    I am trying to create a workflow with vCO that can do the job for me:

    -Create a virtual machine (or maybe a several virtual machines) from a model (the model is in vCenter, of course)

    -L' user who is running the workflow has the thr right to say what he wants for the CPU, the memorysize, the disksize

    Any help?

    I found some workflows in the library can seem to do something similar to what I want, but since I'm a beginner I'd rather have your advice

    Hello there and welcome to vCenter Orchestrator

    Take a look at this series of tutorials to get an idea of how start:

    Create a vCO simple self-service VM Provisioning Portal - part 1

    Create a vCO simple self-service VM Provisioning Portal - part 2

    Create a Simple Self Service VM Provisioning Portal vCO - part 3

    The general approach to take would be to determine which of the clone (or clone and customize) workflows adapts to your nearest need (see your customer vCO: workflows\Library\vCenter\Virtual Machine management\Clone\)

    Then, create a NEW WORKFLOW that calls this one... after that your clone operation is complete, keep the computer turned off virtual and add feeds of extra work from the library to your new workflow that do things like change the amount of Ram, adds disks, change CPU, etc...

    Be sure to watch the videos on http://www.vmwarelearning.com/orchestrator to get a basic understanding of the use of vCO.

  • Video playback in the media player in windows (Vista) is perfect. But when I create a dvd in Windows DVD Maker and read the dvd, the sound is off by a fraction of a second on the dvd. Is this a setting problem?

    After burning a dvd, the audio is a fraction of a second offshore on playback of dvd-video.

    Hello

    I suggest you to refer to this link and check if it helps:

    http://Windows.Microsoft.com/en-us/Windows-Vista/troubleshoot-problems-with-creating-a-DVD-video-using-Windows-DVD-Maker

    Check if that helps.

  • Is it possible to remove a video from a window and read it separately?

    I'm watching a live feed from a Web site. Unfortunately, all the other information on the Web site are useless to me. Is it possible that I could remove the video player in the browser and play on his own? If not, is there a way I can expand the video without sending the video in full screen? I disable all the other boxes of projection on screen, but the video is still too small.


    Please note that the flow is completely legal and paid.

    unless the video player allows it, there is no other way to get out of the video.  Regarding resizing, I'm able to get different sizes of the video player by simply by zooming in on the browser.

  • Unable to read the security descriptors data stream

    Whenever I start my computer runs CHKDSK - it says checking file system on E: and then he said that it should be checked for consistency. It works until stage 3 when he says 'impossible to read the security descriptors data stream' how to fix this?

    I tried chkdsk e:/r and it runs before step 3 when I get the "unable to read the security descriptors data stream" and it goes no further.

    I also tried fsutil dirty query e:- but it says something about a parameter incorrect and not if the volume is dirty or clean.

    Then I tried chkdsk e:/f/x - that always gives me the same mistake about it being an incorrect setting.

    As far as I know there is absolutely nothing on E:, I didn't even know that there was an additional drive. Right now I have it turned off so that I can use my computer. It seems to work fine without it. I read an article that said that if I can't fix e: with chkdsk which I have to do a low-level format of the reader? What's my next step? And I can do without the XP disc?

    The syntax

    fsutil dirty query e:

    is correct (except, of course, you try to use from the Recovery Console, where the fsutil command is not available).  Are you logged on as a user with administrative rights when you use fsutil?

    Similarly, the switches /f and/x are not available for chkdsk in the Recovery Console.

    See Recovery Console controls.

    Click on desktop then right-click on E: drive icon and select Properties.  What is indicated for:

    • File system
    • Space used
    • Free space
    • Capacity

    Now double click the icon for E: are shown files?  If not, click Tools > Folder Options > view and select the radio button "Show hidden files and folders" and uncheck "Hide protected files (recommended) operating system.  Now that you see all the files?

    Everything you read 'low level of shaped' is nonsense.  Any modern PC drive cannot be low level formatted by end users.  You can read this, but there is really no necessary even to "zero fill" your drive E: http://seagate.custkb.com/seagate/crm/selfservice/search.jsp?DocId=203931 (I have not checked to see if the WD tools rescuer has similar characteristics to SeaTools for DOS).

    If you are convinced that there is nothing of value on E (for example, installation of backup or restore), you can either format by right-clicking on the drive icon in my computer and selecting "format" or you can start disk management as described previously and use either in electronic format or delete the partition completely.  If you delete the partition, space becomes "unallocated".

    Because I guess C is your system drive (where Windows is), you may be able to use the diskpart tool to extend the partition F to use the unallocated space left if you decide to remove E well it's much easier (and safer) to do with disk management third-party tools such as Easeus Partition Manager free : http://www.partition-tool.com/personal.htm

  • creating a table 1 d of data streaming

    I have 1 item read 10 times per second and I'm trying to figure out how I can make a table 1 d of these data to data from 5 min and once it is full, I would like to than the old data to be replaced by new data.

    Can I get some ideas on how to do this? I'm relatively new to labview.

    Thanks for the help.

    Use a queue. Set the length of the queue to 3000, then use the function of the element of queue with loss to put the latest data at the end. The oldest item is removed, so "service" of the queue is faster that data arrives.

    Maintenance is a fancy way to say use "Élément Dequeue" and do something with the data; write to a file, add a chart, do any calcluation, etc...

    Depending on the item of queue with loss

  • Error on image from the server and display streaming

    Hi all

    Im trying to read an Image that origin of the server and displays on a screen

    Here's the code I'm using to broadcast the image.

    It is streaming on my Simulator as well as on some devices.

    But on some devices, it's not streaming and throw an exception.

    public UrlToEncodedImage(String url)
    {
    HttpConnection connection = null;
    InputStream inputStream = null;
    byte[] dataArray = null;
    
    try
    {
    connection = (HttpConnection) Connector.open(url+getConnectionString(), Connector.READ, true);
    inputStream = connection.openInputStream();
    byte[] responseData = new byte[10000];
    int length = 0;
    StringBuffer rawResponse = new StringBuffer();
    while (-1 != (length = inputStream.read(responseData)))
    {
    rawResponse.append(new String(responseData, 0, length));
    }
    int responseCode = connection.getResponseCode();
    if (responseCode != HttpConnection.HTTP_OK)
    {
    throw new IOException("HTTP response code: "+ responseCode);
    } 
    
    final String result = rawResponse.toString();
    dataArray = result.getBytes();
    }
    catch (final Exception ex)
    { }
    
    finally
    {
    try
    {
    inputStream.close();
    inputStream = null;
    connection.close();
    connection = null;
    }
    catch(Exception e){}
    } 
    
    bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
    // this will scale your image acc. to your height and width of bitmapfield
    
    int multH;
    int multW;
    int currHeight = bitmap.getHeight();
    int currWidth = bitmap.getWidth();
    if(currHeight>350&&currWidth>350){
        bitmap=scaleToFactor(bitmap,currWidth,currHeight,Display.getWidth()-20,250);
    }
    
    }
    public EncodedImage getEncodedImage()
    {
    return bitmap;
    }
    public  EncodedImage scaleToFactor(EncodedImage encoded, int curWidth, int curHeight, int newWidth,
            int newHeight)
    {
         int numerator_width = Fixed32.toFP(curWidth);
         int denominator_width = Fixed32.toFP(newWidth);
         int scale_width = Fixed32.div(numerator_width, denominator_width);
    
         int numerator_height = Fixed32.toFP(curHeight);
         int denominator_height = Fixed32.toFP(newHeight);
         int scale_height = Fixed32.div(numerator_height, denominator_height);
    
         return encoded.scaleImage32(scale_width, scale_height);
    }
    private static String getConnectionString()
    {
        String connectionString = null;
        if(DeviceInfo.isSimulator())
        {
                if(UrlToEncodedImage.USE_MDS_IN_SIMULATOR)
                {
                       connectionString = ";deviceside=false";
                }
                else
                {
                       connectionString = ";deviceside=true";
                }
        }
        else if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
        {
           connectionString = ";interface=wifi";
        }
    
        else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
        {
            String carrierUid = getCarrierBIBSUid();
            if(carrierUid == null)
            {
             connectionString = ";deviceside=true";
            }
            else
            {
               connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=";
            }
        }                
    
       else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
        {
          connectionString = ";deviceside=false";
        }
    
       else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
        {}
        else
        { connectionString = ";deviceside=true";} 
    
        return connectionString;
    }
    private static String getCarrierBIBSUid()
    {
        ServiceRecord[] records = ServiceBook.getSB().getRecords();
        int currentRecord;
    
        for(currentRecord = 0; currentRecord < records.length; currentRecord++)         {             if(records[currentRecord].getCid().toLowerCase().equals("ippp"))             {                 if(records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0)
                {
                    return records[currentRecord].getUid();
                }
            }
        }
    
        return null;
    }
    

    The underlined part of the code is where the uid is sent as public _.

    Please, look in the code and let me know where the error is, or is there a better way to disseminate the image.

    In the hope that you hear.

    Thank you & best regards

    Krishnan

    Hello

    I found the error.

    It's in the URL sent by the server.

    The URL consisted of http://google.com

    But the format required to retrieve the image on several device would be http://www.google.com.

    Thanks for anyone who tried to help him.

    Krishnan.

  • Digital acquisition of data streams

    Hello

    I tried (unsuccessfully) to acquire digital data of a sensor laboratory.  The Guide from the manufacturer:

    "When the excitement of voltage, DTC Decagon sensor makes a measurement.  Three measurement values are passed for about 140 ms of excitement to the data logger as a character of flow series of ASCII.  The series is 1200 asynchronous baud with 8 data bits, no parity and one stop bit.  The voltage levels are 0-3, 6V and logical levels are (low active) TTL.  The power must be removed and repeated his request for a new set of values to pass.  The ASCII data stream contains three numbers separated by spaces.  The first number is the depth of the water in mm, the second number is the temperature in degrees Celsius, with a resolution of 0.1 degree C, and the third number is the electrical conductivity in dS/m, with a resolution of 1 dS/m.  A carriage return follows the three digits, then the character ' t "", which indicates that it is a sensor DTC, and then a control character, and finally a carriage return and supply line. ' "

    My attached VI is a little dubious-it probably looks like something that someone used for analog signals may create.  However, I was hoping it would be enough of a starting point for a more wise to work with LabVIEWer.

    Thank you very much

    Lacksagoo

    The guide said in reality as a data acquisition card OR is the same as a data logger. I've never associated the two as being the same. What I think about a data logger is an autonomous instrument.

    Looking for a more details in your original post, the voltage levels are not standard. You may need a shifter level or need to find a USB-RS232 adapter for TTL levels.

  • Remove the first 5 blocks in a data stream

    Hi all

    I have a problem to remove the first 5 blocks in the data stream. My sampling rate is 1 s, block size is 1 and the entrance is the module «the ddf file read»

    I use the following modules for an average analysis 30 years running.

    [read the folder]---> [Formule1] -> [set variable] -> [formula2]

    |                 ^

    --> [time]-|

    module parameter

    ======                =========

    delay of 30

    Formula1 ${var_1} + in (0) - in (1)

    the value of variable ${var_1}

    Formula2 in (0) / 30

    This configuration is used for channels 13 and one of these channels is used for purposes of triggering. Due to the nature of the variable defined and read in the underlinedmodules, the trigger sequence is delayed for 2 sec. Since I used the trigger to collect the last returns average of each channel, it is now mixed with 2 sec for the next round.

    My question is: is there a way to reduce say 5 blocks of data from the stream? Please help and have a nice day

    Look at the SEPARATE module in the Group of data reduction.

    It allows you to set up an initial leap, then a current break.

    To do this, you want to jump 5 blocks once, does through go zero blocks... who spends the first five and then release all the data blocks of subsequence.

  • network data stream

    Good afternoon

    I need to send the data generated in the vi, by network data stream.

    The problem is that I found no example that does something similar, and this is my first time using Activex with Labview. Can someone explain me how to send Activex data via the network stream please and if possible help me find a solution to the attached vi.

    I think I need to convert the data somehow after control of the room before using the writing and reading items, I tried with strings and arrays unsucessfully, I really think I'm missing something.

    Thank you in advance!

    Erika

    Erika,

    What do you think?  You try to play an .avi file, a .mpg or what?  IMAQdx has functions that can play video and output files 'images', and you can deliver these images via TCP/IP on another computer using network flow.  Indeed, there are cameras that capture video and output via TCP/IP - IMAQdx is used to capture the image directly from the camera and can view or save a file from .avi (for example).

    You have the Vision Module installed on your system?  In your Palette of block diagram, it will appear under the Vision and movement and should include IMAQ (or IMAQdx) and utilities of Vision (which contains the Palette under files to make the reads and writes of video files).  See if you can use this to display your video...

    Bob Schor

Maybe you are looking for

  • I need to backup iphone on itunes if I use icloud

    Hello I'm out of disk space hard and currently use icloud for our two phones and two ipads. I have backups on my Mac iTunes which is about 90 GB. What I always have these backups to local hard drive iTunes if I am using iCloud. Would like to have the

  • Lost images

    I recently upgraded to El Capitan and find that all my .doc, .docx and pdf files have lost their photos and other images. Any advice, please?

  • Unable to update windows install not accessible, also arresting installation of Skype and Webcam live messneger

    I had to reprogram my computer on Saturday, I had limited success running the fix tool that allowed me to get most of my updates including service Pack 3. He says it is fixing my Installer, but it doesn't. I restart and try to finish the updates, .ne

  • visibility of custom dialog problem

    Hello I used a dialog box custom in my project to a pop up. I used the tutorial of the custom dialog box. Depending on whether, when the dialog box appears, the back groundpage will be inactive and when the dialog box is closed, which becomes active.

  • EBS video tutorials

    Hellolooking for video tutorials EBS.Now on youtube, videos are for 12R.No matter what link to find tutorials for E_business 11.5?Thank you.