You are not logged in.

#1 2010-03-31 04:44:07

quintaessentia
Member
From: Florida
Registered: 2010-03-19
Posts: 4

Real-time Sensors Program

It's not as grand as a package management wrapper, but...

Here's the code for a simple C program that will run sensors much like top. I'm sure there's something better out there but I'm not an uber coder yet so, this is my contribution cool

 
#include <ncurses.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int  ch;
    int  exch = -1;        /* halfdelay assigns -1 to getch() */
    int  fileid;
    char filepath[50];
    char filebuf[50];
    char sysbuf[50];
    FILE *fp;

    /* avoid different users trying to access the same temp file
        by creating random file names */
    srand( ( unsigned int ) time( NULL ) );
    fileid = rand();

    strcpy( filepath, "/tmp/sensorsrt-");
    sprintf( filebuf, "%d", fileid );
    strcat( filepath, filebuf );

    initscr();
    raw();
    noecho();
    halfdelay(1);
    curs_set(0);

    while ( exch == -1 ) {
        /* Check buffer for input to exit loop */
        exch = getch();                        
    
        /* run bash command to create temp file with sensor data */
        sprintf( sysbuf, "sensors > %s", filepath );    
        system( sysbuf );                    

        /* open file; if not, exit gracefully */
        fp = fopen( filepath, "r" );
        if ( fp == NULL ) {
            perror( "Cannot open input file" );
            exit(1);
        }

        /* Print file to screen buffer */
        while (( ch = fgetc( fp )) != EOF ) {    
            if ( ch == 194 ) continue;    /* check for strange characters, you may need to edit this line */
            printw( "%c", ch );
        }        
        printw( "Press any key to exit" );

        /* Print file buffer to screen */
        refresh();                        

        /* Sensors updates about once every 2 seconds */
        sleep(2);
                
        /* Check buffer for input to exit loop */
        exch = getch();            

        fclose( fp );
        move(0, 0);
    }

    endwin();

    /* remove file from /tmp, as it is no longer needed */
    sprintf( sysbuf, "rm %s", filepath );
    system( sysbuf );                        

    return 0;
}

Offline

Board footer

Powered by FluxBB