How To Capture GPS NMEA Output in C Program

This post is divided into two sections, first one talks about send shell output to C program and second section makes use of this to show how to redirect GPS NMEA output in C program.

How to Capture the Output of a Linux Shell Command in C

If you google about how to redirect your shell output in C program, you will find couple of answers. There are few ways like using  freopen (“/dev/tty“, “a”, stdout) and playing around with ‘stdout’ file descriptor.

Other common approach is using ‘system’ command. The ‘system’ command executes the command.

int system (const char* command);

 With ‘system‘ function returns an integer indicating success or failure, but not the actual output of the string or command. This is useful when you do not need to stream the command output to your program.

When you need to re-direct command output to your program then you will need to use ‘popen’

popen - pipe to/from shell

FILE *popen(const char *command, const char *type);int pclose(FILE *stream);
Typically usage is:

     FILE *fp;
     char *command;

     /* command contains the command string (a character array) */

     /* If you want to read output from command */
     fp = popen(command,"r"); 
          /* read output from command */
           fscanf(fp,....);   /* or other STDIO input functions */
     
     fclose(fp);

     /* If you want to send input to command */
     fp = popen(command,"w"); 
          /* write to command */
           fprintf(fp,....);   /* or other STDIO output functions */
     
     fclose(fp);

The program cannot both send input to the command and read its output. You pass the command as a string to ‘popen’ function.

How to Capture GPS NMEA Output in C Program

Here is sample program using ‘popen’ to do this. What it does is creates a result buffer, opens up a read-only stream, runs the command, and captures the output, stuffs it into the buffer, then returns it as a string.

#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

  FILE *fp;
  int status;
  char result[512];
  int i=0;
  /* Open the command for reading. */
  fp = popen("gpspipe -r -x 5 | grep '$GPGGA'", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit;
  }
  for(i=0;i<4;i++)
  {
  /* Read the output a line at a time - output it. */
  if (fgets(result, sizeof(result), fp) != NULL) {
    printf("%s", result);
  }

  else printf("no output \n");
  }
  /* close */
  pclose(fp);

  return 0;
}

This program uses ‘gpsd’ client programs to redirect NMEA output to command line. For more on how to install and test with ‘gpsd’ refer this post.

You should test the output of command first on command line. As you know making work GPS module is tricky.

Number of View :728

Tags: ,

No Comments


How to use IS and AS keywords in C#

Using as keyword

Dynamic polymorphism which is evaluated at run time not at compile time so we are sure that errors are not known before execution. Like e.g Explicit casting is evaluated at run time.

object test = new Manager();
//You cant cast test to a Department!
Department dept= (Department) test;

So how can we safely use such casting and handle exception

try
{ 
Department dept = (Department) test;
}
catch(InvalidCastException ex)
{ 
...
}

Above code is about handling exception but how about doing some more logical coding in the failed case, coding into catch not good example.

We can determine whether the given type is compatible with another using ‘as’. Compatibility check will return null value.

Using is Keyword
Unlike as keyword is keyword returns false if compatibility between objects or casting failed.

void(Employee emp)
{
if(emp is Department)
     Console.WriteLine("Sorry, emp is not Department..");
}

Here we are checking runtime what incoming base class reference is actually pointing in memory. So we are not using try catch as well here to wrap the casting.

Happy programming..Number of View :9193

No Comments


Interface Programming tool A Concept

Interface is technique or concept which is used to add set of behavior or functionality to be mandatory. When we derive into class then class has to implement each thing that is in Interface. Something like making skeleton and then giving different look and behavior using that skeleton. Decoupling of object and  its implementation is possible because of interface.

Lets say you create interface of Cycle

Interface ICycle
{
void Handle(); 
void Wheels(); 
}

Inheriting class

class AtlasCycle: ICycle
{
void ResizableHandle()
{...
}
void fourDiaWheels()
{....
}
}

 

Above cycle skeleton can be used to derive any brand of bicycle with different feature values.

  • Interface has by default all fields, properties and methods Public. But you can have internally private and use it appropriately inside interface.
  • One which is public has to be implemented in inheriting class So it better than having base class.
  • Class can inherit as many as interfaces So structures can also use interfaces.
  • Interface does not have implementation only declarations.
  • It is highly used to design architecture. So it is architecture job to define what to be exposed and what not to client.

Happy Programming..Number of View :8962

No Comments


C# Language Features OOPS .NET

Quick walkthrough on C# features.

DATA TYPES

Object Types: It is parent type of all other known types in .Net. If used as an argument in Method call then passing any type to method will cause late binding assignment to that argument.
Value and Reference Type: This type categorized on the storage of value in memory. Value Type are stored in Stack. e.g type INT, DOUBLE.
Reference types are stored in heap. e.g Type String and Object.
Converting value type into reference type called as Boxing and reverse is UnBoxing.

DECLARATION
C# allows simple and component variable declaration.

ENUMRATION
It is declared as set which are mapped to integers. This type allows us to have series which can have their mapping to unique integer value inside the set.

public enum EmployeeRole{ Trainee=0, Programmer=1, Sr Programmer=2}

 

Arrays: This type holds list.
e.g

int [] intArray;

 

OPERATORS Representing symbols for operations.
e.g Arithmetic[+, _, +], Logical[||, &&], String Concatenate[&], Increment and Decrement[+=], Comparison[<=, =>], Cast[()] etc..

FLOW CONTROL Controls the flow of your programme. e.g conditional statement [if ..else, switch], loops[while, do..while, for, foreach], functions.

CLASSES Class is type which includes all types, members, methods etc. It has visibility, its lifetime, relation, inheritance, method overloading..

REFLECTION Dynamically gather information of underlined type in late bound fashion. e.g Attributes allows to attach metadata to class and its members.

INTEROPERABILITY This feature facilitates to work with other programming language and API.
COM INTEROPERABILITY: This allows to integrate legacy components with .Net classes.
INVOKING WINDOWS API: This is same as VB6 feature to invoke and use windows API. Reference dll and create wrapper functions.

[sysimport(dll="user32.dll")]
private static extern int MessageBoxA(int hwind, string Message, string caption, int Type);

 

STRUCTURED ERROR HANDLING This is way of handling error by blocking code. e.g

Try
{}
Catch(){}
Finally{}

 

C# PREPROCESSOR This feature allows programmer to do better programming like expanding code, collapsing code…

Happy programming..Number of View :7963

Tags:

No Comments


Microsoft office 2007 OneNote How to use OneNote?

First Lets understand OneNote. What is OneNote? It is one of information capturing service or feature of Microsoft Office 2007. Capturing notes, saving notes, browsing your notes and also sharing notes is all possible with our regular paper notebook.. Here is the difference, Its all that what we have been doing for taking notes in office or any other place and writing information into our NoteBook and In one OneNote it is mobile, we can carry anywhere and share anywhere. What is special in OneNote, well you can carry your text capturing device anywhere so you have onenote that device whether its smartphone or digital notebook, windows phone , Second its office features, graphics and speed So you can carry it anywhere and share it. Unlike Paper you can copy info from other files, you can copy , create images and save it in page.

For onenote you can work offline or work online.

Features
Onenote has text, Image, video , audio capturing features.
You can create your own template and customize it.
Can share notes with others.
You can use notebook multiple computers.

How to Use OneNote?
You need to install Office 2007 for better features.Latest you have Office 2013 Onenote.
Then you can start working with OneNote right away. Detail information can be found at office site of microsoft
Number of View :3459

No Comments


Buzz Windows Azure HDInsight Service Hadoop Big Data

What is upcoming in microsoft? What is latest in Microsoft Winodws Azure -HDInsight?

So what is HDInsight?

Haddop Insight is Apache hadoop service available on azure cloud. This is also dealing with big data which is nothing but managing data, enriching, and refining data virtually. Big data can deal data for personnel, organization and global. HDInsight provides HDFS and Mapreduce softwares available in azure in better way. It has Hive console and Javascript console which we can use for configuring, execution of Hadoop jobs.

So now you must have understood that to work with HDInsight you need Winodws azure storage account and pay for it so that you get maximum feature use.

You can learn more about it http://www.windowsazure.com/en-us/manage/services/hdinsight/

More about Big data

Happy Learning..Number of View :3565

No Comments


ViewState and Server Controls ASP.NET PageLifeCycle

How does view state data value assigned to controls on Html form or How user inputs value retained after post back.

This is all above comes in PageLifeCycle and we can find many articles on that. I have small understanding on very important thing and I would like share..

When Post Back happens or any server side event fired their are major event which plays role to retain data of view state.
LoadPostBackData – This function is only applicable for Postback. When the page is given to asp.net engine with all markup asp.net engine calls for several functions to complete the server side load.
Browser on event firing or postback will pass on the values to ASP.NET engine using HTTP POST header which actually has _VIEWSTATE.
IPostBackDataHandler interface will take care of calling LoadPostdata function for all the server controls for which loading view state is applicable.All listed controls in IPostBackDataHandler will have call for LoadPostdata () method like textbox, listbox. So here we can see that its not viewstate which is only responsible for loading user input to controls.

Page Load – In this event the load view state happens along with post back data.

Save View State -In this stage Page class construct View State for page which has to be maintained across post back. It is called according to the hierarchy defined in Page Instantiation for all the controls(stored in the WINDOWS\Microsoft.NET\Framework\version\Temporary ASP.NET Files).

Very nice explanation of page life cycle and role of view state is written here

Happy programming..Number of View :3344

No Comments


Understanding the Object Oriented Programming

In .net the object plays role everywhere even if you directly code or do not object has its existence.
I have small program which was Interview Question at Microsoft.
C# code and understand the life of object.

Open Visual Studio -> New Project->Select c# and then Select Console Application

Name project – ObjectLifeCycle

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectLifeCycle
{
    public class log
    {
        public Int32 i;

        public void TestA(log obj)
        {
            obj.i = 100;
        }

        public void TestB(log test)
        {
            test = new log();
            test.i = 1000;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            log o = new log();
            o.i = 10;
            Console.WriteLine(o.i.ToString());

            o.TestA(o);
            Console.WriteLine(o.i.ToString());

            o.TestB(o);
            Console.WriteLine(o.i.ToString());          
            
        }
    }
}

 

You can directly paste this code in your .cs file and execute the code , you should see output as followed
10
100
100

So the object of class log which has only one variable in it and methods which has argument passed as its own object is having different scope in different assignment.

In Main Method object is initialized with values first time so first writeline statement gives 10.
Second method call TestA with object o is passed. Inside the method their is just reassign of value to int as 100 so the value 10 is replaced to 100 for object o which is still having same reference.

Third method call TestB in which again object o is passed which had value of int as 100. Now inside method new object initialization happens that means new object o for which int value is 1000.
Now you must be wondering third value is not 1000, this is because TestB created new object with new memory allocation. So test object scope finished ones it came out of the method. Since the Writeline method is calling value available in object o it has given 100.

Lets do one more change on line 35

o.i = o.TestB(o);

 


In above case what is happening is we are copying return value of int from TestB method and assign it to object o.i int value. of course TestB return type has to be changed from void to int.

It should return
10
100
1000

For more details http://msdn.microsoft.com/en-us/library/fa0ab757%28v=vs.100%29.aspx

Happy programming….

Number of View :3221

No Comments


.Net Application With Windows Azure 1.8

Now I have Installed Windows SDK 1.8 kit and started developing asp.net application using video shown in MSDN. But the catch is it is old and the configuration or publishing site ways are improved.

To develop ASP.NET application on VS2010 follow steps as below
1) Open VS 2010 -> File Menu -> New -> Project
2) Under Project window you can see various language and options, I am selecting c# and then Cloud here you see at right Panel is Windows Azure Cloud Service

VS 2010- Project- Cloud

VS 2010- Project- Cloud

3) Give name and location of project to save.
4) Next step it will open window to select the project type

Select Cloud Project Type

Select Cloud Project Type

But why is project type with Role like Web, Worker and VM? In short they are nothing but your Web Configuration role. Like you want use IIS for application, you want to run it locally with worker process or using VM… you can find good explanation in msdn,
Have patience here it takes time to get your code files service files to be generated.
Project With all file
4) Now you can do implementation in your project which is of WebRole type.
5) Ones you are ready for hosting of course we will do it on windows azure, select WebRole Project Properties -> Publish to Windows Azure
6) Now here your Windows Azure journey starts , Create Login in if you have already use it. When you try for Trial you still need to provide your bank account details. When you come to Publish First windows will be asking Import credentials which you have, If you have not saved your Credentials from Windows azure login save it by choosing Sign in to download credentials.
Sign in Windows azure

Click Next.
7) Here you need to fill correct details. Read about Windows azure before you do settings in publish.
Options for Create Cloud Publish

As per above image you need to specify Cloud Service(Select Create New from drop-down and give name and location) Name which we give here will become your URL. Provide all other details as well.
8) Go to Advanced Setting Tab and create New Storage Account.
9)Click on Publish.. and Wait for Status in task bar of your project as completed.
This time here it will perform connection with Windows Azure and create your application.
10) Ones you have no failure and Status shows as Completed you can click the URL given in output results and browse.

few steps are different than the videos given by msdn.

Happy Programming..
Number of View :6758

Tags: , , ,

No Comments


Windows azure Cloud .Net Applications

Hmm. . Starting late when Microsoft has already come up with most of the latest versions on their own Cloud that is Windows Azure.
 
Today I got time to go through some of the videos available in MSDN and came to know how cloud works in Windows Azure providing extensions to all available application templates which are heavily used like ASP.NET, Windows Forms, MVC, WCF, SQL. Watching videos gives feeling that Cloud or Windows Azure is simple and I can straight away go ahead create my application in Azure but I am beginner in this so hurdles are sure in starting.

So what I have faced and How I Solved
Problem: I could not get Windows Azure SDK installed on VS 2010 ultimate version.
Reason: Error specified that I had nugets of MVC3 updates installed which are not compatible. It means still some more opportunities to Microsoft for giving fix or Patch.

It is true that I installed MVC4 not MVC3 but it had latest updates which I installed from Nugets option available in VSTF Extension Manager under tools. Why this issue? I am not sure.

I would like to share what I learnt in Videos

Setup environment for Windows Azure by installing Windows Azure SDK latest version 1.8
Create new application under Cloud same way you create without using cloud.
Publish it using options available in properties.
Host it in Windows Azure using your lab account if you do not have it create Trial one.
Deploy it on Windows Azure region.
Execute or Browse it.

If I am not wrong Cloud concept is available from the time Domain has come into picture. Some one is providing domain as well as host server environment and user is just publishing deploying the package.
But Cloud is more advanced gives you more features which are important for Development team like Building, Configuration, Different Data Source management, Versioning many more.

Now above all steps are possible if you are already familiar with .NET.

Lets go back to the problem I had and solution
So here is the solution I followed.
I read FAQ and googled it but could not get the working solution where I can keep MVC4 and then Install Windows Azure. If anyone reading this article and found right solution please do comment.

Solution: I uninstalled MVC4 not from nugets but from Control Panel and then Installed Windows Azure SDK. It worked.

Happy Troubleshooting..
Number of View :6635

No Comments



SetPageWidth
Content Protected Using Blog Protector By: PcDrome.