Geek IT Guide

My blog on linux, coding, web design, hardware hacking and everything else in between.

By

SecurityPi Part 4

As I continue where I left off, I was going to begin on getting a web interface together to be used for management of the system. responsive

Thinking about some of the requirements that first came to mind:

1. It needs to be non-device dependent, meaning it needs to be a responsive layout. mind were:

2. It needs to have a fairly quick load time.

3. It needs to be modular in design, so it will be easy to add to as new ideas and features get added.

As I looked around for ideas, for how I wanted to design it, I stumbled across an awesome free twitter bootstrap 2 web admin template that Muhammad Usman was offering on his site. Since it utilized a twitter bootstrap’s features, among many other things, it would easily meet the first two requirements, and after looking it over and checking out the documentation and source, it easily met the third by being very easy to manipulate to my needs.

Charisma web template ss

The template was very complete and includes so many features I cant list them all here, but some of the main features that really interested me were the different themes, the user control panel, jquery datatables, full web calendar, bootstrap alert, web file manager and very clean look. Feel free to look more at it here and show Muhammad some love for his work.

After downloading and looking over the live demo, I quickly got to work getting a rough draft of what I wanted on the main page to offer and what was else was needed as far as pages go.

SecurityPi web interface main1 ss

Seeing how this is a rough draft I am sure it will change as I go along, however for now I think it meets the needs pretty well as well as keeping things simple and uncluttered. I wanted the main page to have a “dashboard” look, so I made sure all of the items of concerned were covered in one easy view.

Following the title at the top I added a few quick view items:

Charisma quick views

This allowed me to have the ability to have quick views and shortcuts for each item I felt was important in a security/home automation system. This might change in the future but I think for now it should be fine.

Next I found that I should look at one of the most important aspect of a security system and that was the ability to add, assign, and move sensors through the web interface.  I thought about how it should look and feel so I put together a editable jquery datatable that was attached to the sqlite database.

sensors page ss

The jquery datatables library is awesome, and it really allows for a very responsive and editable table. To get it up and running I did the following:

added the following html:

<div class="box span12">
   <div class="box-header well" data-original-title>
    <h2><i class="icon-list-alt"></i> Sensors</h2>
      <div class="box-icon">
       <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a>
       <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a>
       <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a>
   </div>
 </div>
 <!-- Place holder where add and delete buttons will be generated -->
 <div class="add_delete_toolbar"></div>
   <div class="box-content">
    <table id="sensorstable" class="table table-striped table-bordered bootstrap-datatable datatable">
     <thead>
      <tr>
       <th>Sensor</th>
       <th>Location</th>
       <th>Zone</th>
       <th>Sensor Type</th>
       <th>Status</th>
       <th>Last Update</th>
      </tr>
     </thead>
     <tbody></tbody>
    </table>
  </div>
 </div><!--/span-->

This provided a means for the table to be populated in a twitter bootstrap box.

Then I added the following javascript at the bottom of the page:

<script src="../js/jquery.jeditable.js"></script>
 <!-- data table plugin -->
 <script src="../js/jquery.dataTables.min.js"></script>
 <!-- data table Bootstrap paging plugin -->
 <script src="../js/jquery.dataTables.bs.paging.js"></script>
 <!-- data table editor plugin -->
 <script src="../js/jquery.dataTables.editable.js"></script>
 <!-- sensor data table -->
 <script>
 $(document).ready(function() {
  jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay =
  function ( oSettings, iDelay ) {
    iDelay = (iDelay &amp;&amp; (/^[0-9]+$/.test(iDelay))) ? iDelay : 250;
    var $this = this, oTimerId;
    var anControl = $( 'div.dataTables_filter input:text' );
    anControl.unbind( 'keyup' ).bind( 'keyup', function() {
    var $$this = $this;
    window.clearTimeout(oTimerId);
    oTimerId = window.setTimeout(function() {
    $$this.fnFilter( anControl.val() );
      }, iDelay);
  });
    return this;
 }
   $('#sensorstable').dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "../php/getall_sensor_data.php",
    "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span4'i><'span4'p>>",
    "sPaginationType": "bootstrap",
    "sWrapper": "dataTables_wrapper form-inline"
 } )
.makeEditable( {
 {
  //sUpdateURL: "../php/updatesensordata.php"
  "sUpdateURL": function(value, settings){
  return(value); //Simulation of server-side response using a callback function
  },
    "sAddURL": "../php/addsensordata.php",
    "sDeleteURL": "../php/deletesensordata.php",
    "sAddDeleteToolbarSelector": ".dataTables_length"
  } )
   fnSetFilteringDelay();
} );
</script>

As you can see above, alot of the js is making various calls to php scripts, as of right now I only built the get_all_sensordata.php as it populates the datatable. The other php scripts are responsible for various other functions, such as adding and deleting sensors and updating the datatable when it is edited. I got the majority of the script completed with the documentation provided with jquery datatables.

Then this is the php script I call in the ajax call to populate the datatable:

<?php
// { initialise variables
// { amount of records to show
$amt=10;
if(isset($_REQUEST['iDisplayLength'])){
$amt=(int)$_REQUEST['iDisplayLength'];
if($amt>100 || $amt<10)$amt=10;
}
// }
// { where to start showing the records from
$start=0;
if(isset($_REQUEST['iDisplayStart'])){
$start=(int)$_REQUEST['iDisplayStart'];
if($start<0) $start=0;
}
// { sort by
$cols=array('sensors.sensor_id',
        'locations.location_name',
        'locations.area_id',
        'sensortypes.sensor_name',
        'status.status_description',
        'sensors.sensor_last_update');
$scol=1;
if(isset($_REQUEST['iSortCol_0'])){
$scol=(int)$_REQUEST['iSortCol_0'];
if($scol>3 || $scol<0) $scol=0;
}
$sdir='asc';
if(isset($_REQUEST['iSortDir_0'])){
if($_REQUEST['iSortDir_0']!='asc') $sdir='desc';
}
$scol_name=$cols[$scol];
// }
// { database file
$database="/run/shm/security";
// }

// { connect to database
function dbRow($db, $sql){
   $q=$db->query($sql);
   $r=$q->fetchArray();
   return $r;
}
function dbAll($db, $sql){
   $q=$db->query($sql);
   $rs=array();
   while($r=$q->fetchArray())$rs[]=$r;
   return $rs;
}
$db = new SQLite3($database);
// }
// { count existing records
$r=dbRow($db, 'SELECT count(sensor_id) AS c FROM sensors');
$total_records=$r['c'];
// { count records after filtering
$total_after_filter=$total_records;
if($search_sql){
$r=dbRow("SELECT count(sensor_id) AS c FROM sensors $search_sql");
$total_after_filter=$r['c'];
}

// { start displaying records
echo '{"iTotalRecords":'.$total_records.',
"iTotalDisplayRecords":'.$total_after_filter.',
"aaData":[';
$rs=dbAll($db, "SELECT sensors.sensor_id,
        locations.location_name,
        locations.area_id,
        sensortypes.sensor_name,
        status.status_description,
        sensors.sensor_last_update
FROM sensors
        INNER JOIN locations ON sensors.sensor_locationid = locations.location_id
        INNER JOIN sensortypes ON sensors.sensor_type = sensortypes.sensor_type
        INNER JOIN status ON sensors.sensor_status = status.sensor_status
$search_sql
ORDER BY $scol_name $sdir limit $start,$amt");
$f=0;
foreach($rs as $r){
   if($f++) echo ',';
      echo '["',$r['sensor_id'],'",
      "',addslashes($r['location_name']),'",
      "',$r['area_id'],'",
      "',$r['sensor_name'],'",
      "',$r['status_description'],'",
      "',$r['sensor_last_update'],'"]';
}
echo ']}';
// }
touch('/run/shm/test');
?>

The php code above simply queries the sqlite database stored in memory (/run/shm/security) and joins the data and populates the datatable. I do a touch at the end to timestamp the last query, this was primarily for testing, but I might keep it to provide a means to see when the last query happens. This code might change depending on how I mess with the tables in the database, but for now you are returned with something like this:

sensor datable

On my next segment, I will continue working with the web interface, and continue working on testing and development.

Go Back to Part 3 Intial Testing and Development   OR   Continue to Part 5 Continued Testing, Development

Responses

  1. Gabriel says:

    March 6th, 2014 at 8:09 pm (#)

    Incredible. I wonder how the project is going and also if you plan implementation along with comercial alarm panels.
    Congrats!

  2. Chris says:

    March 12th, 2014 at 12:02 am (#)

    Thanks for the feedback.. It is going good, right now I am working on the back end a little more and experimenting with some of the custom arduino based prototype sensors. I will update within the next week. As of right now, I don’t intend on integrating directly with commercial alarm panels, but definitely in the future it might be a possibility.

  3. alex says:

    April 1st, 2014 at 9:56 am (#)

    super.great job.when you finish your project.i want to make myself somthing like that.

  4. Chris says:

    May 2nd, 2014 at 10:53 pm (#)

    Thank you for the feedback Alex,
    I have not had much time to work on it lately, I have finished the new sqlite3 database and the python script I am now just trying to figure out my own messaging system for custom commands.

  5. Bugzy says:

    May 31st, 2014 at 1:18 am (#)

    Wow. Chris, this is excellent, it is exactly what I got my Raspberry Pi for. The only problem is that I have a much lower code tolerance level than you do. On my Pi I am running Pidora with mochad and tried to setup a Domogik as a web frontend (sehttp://www.domogik.org/en) with no luck. So I am very interested in trying to reproduce what you are doing here. Hope you find some time to continue working on this.

  6. Chris says:

    June 4th, 2014 at 4:13 am (#)

    Bugzy,
    I am glad to see that someone else is trying to get the same result. I have done alot since my last update, just have not had the chance to update for a while now. I will try to get something up soon.
    On another note, Domogik looks very cool, I am surprised I have not run across this yet..
    I might look into it for some ideas.
    Thanks for your feedback.

Leave a Response