Thursday, 11 October 2012

a quick demo CO2 + Telosb




Change following lines in sky/dev/light-sensor.c

#define INPUT_CHANNEL      (1 << INCH_0)#define INPUT_REFERENCE     SREF_0
#define PHOTOSYNTHETIC_MEM  ADC12MEM0
#define TOTAL_SOLAR_MEM     ADC12MEM0

Then, the light sensor channel is redirected into CO2.

I try to creat a new sensor file in Contiki for Telosb, but it alway fails.
Any one know offical documents about this issues? Thanks for the help

Monday, 1 October 2012

write-USB Contiki OS Telosb

#include "dev/serial-line.h"
PROCESS(gas_client, "GAS Client Process");
AUTOSTART_PROCESSES(&gas_client);

/*----------------------------------------------------------------------------*/
PROCESS_THREAD(gas_client, ev, data)
{
    PROCESS_BEGIN();
  //  bootup();
   // printf("Welcome to GAS Client process!\n");
    uint8_t command_str[10] = {'\0'};
   // uint8_t contents[10] = {'\0'};
    while(1) {
      
        PROCESS_WAIT_EVENT_UNTIL(ev == serial_line_event_message && data != NULL);

        strcpy( command_str, (uint8_t *) data);
        printf( "\nReceived command %s", command_str);
      
       // if (strncmp(command_str, ADDR_C, 2) == 0) {
                   
       // }
       
       //   strcpy(command_str, "");
    }
    PROCESS_END();
}



Terminal1:
echo "hello" > /dev/ttyUSB4
Terminal2:
make login
Received command hello

Friday, 7 September 2012

sriLCD

void setup()
{
  Serial.begin(9600);
  backlightOn();
}
void loop()

  selectLineOne();
  Serial.print(millis());
  selectLineTwo();
  Serial.print(millis()/2);
  delay(100);
}
void selectLineOne(){  //puts the cursor at line 0 char 0.
   Serial.write(0xFE);   //command flag
   Serial.write(128);    //position
   delay(10);
}
void selectLineTwo(){  //puts the cursor at line 0 char 0.
   Serial.write(0xFE);   //command flag
   Serial.write(192);    //position
   delay(10);
}
void goTo(int position) { //position = line 1: 0-15, line 2: 16-31, 31+ defaults back to 0
if (position<16){ Serial.write(0xFE);   //command flag
              Serial.write((position+128));    //position
}else if (position<32){Serial.write(0xFE);   //command flag
              Serial.write((position+48+128));    //position
} else { goTo(0); }
   delay(10);
}
void clearLCD(){
   Serial.write(0xFE);   //command flag
   Serial.write(0x01);   //clear command.
   delay(10);
}
void backlightOn(){  //turns on the backlight
    Serial.write(0x7C);   //command flag for backlight stuff
    Serial.write(157);    //light level.
   delay(10);
}
void backlightOff(){  //turns off the backlight
    Serial.write(0x7C);   //command flag for backlight stuff
    Serial.write(128);     //light level for off.
   delay(10);
}
void serCommand(){   //a general function to call the command flag for issuing all other commands  
  Serial.write(0xFE);
}

RTC Control v1.00

http://combustory.com/wiki/index.php/RTC1307_-_Real_Time_Clock


/* RTC Control v1.00 * by <http://www.combustory.com> John Vaughters * * THIS CODE IS FREE FOR ANYTHING - There is no Rocket Science here. No need to create some long GPL statement. * * Credit to: * Maurice Ribble - http://www.glacialwanderer.com/hobbyrobotics for RTC DS1307 code * BB Riley - Underhill Center, VT <brianbr@wulfden.org> For simplification of the Day of Week and month * and updating to Arduino 1.0 * peep rada - from Arduino Forum - Found that only 32 registers per I2C connection was possible * * With this code you can set the date/time, retreive the date/time and use the extra memory of an RTC DS1307 chip. * The program also sets all the extra memory space to 0xff. * Serial Communication method with the Arduino that utilizes a leading CHAR for each command described below. * * Commands: * T(00-59)(00-59)(00-23)(1-7)(01-31)(01-12)(00-99) - T(sec)(min)(hour)(dayOfWeek)(dayOfMonth)(month)(year) - * T - Sets the date of the RTC DS1307 Chip. * Example to set the time for 25-Jan-2012 @ 19:57:11 for the 4 day of the week, use this command - T1157194250112 * Q(1-2) - (Q1) Memory initialization (Q2) RTC - Memory Dump * R - Read/display the time, day and date * * --------------------------------------------------------- * Notes: * Version 1.0 * Moving this code to Version 1.0 because this code has been updated to Arduino v1.0 and the features have * been well tested and improved in a collaborative effort. * - Fixed the issue of not being able to access all the registers - JWV * - Added initialization for all non-time registers - JWV * - Added Dump of all 64 registers - JWV * - Some Date/Time reformatting and cleanup of display, added Day/Month texts - BBR * - Made compatible with Arduino 1.0 - BBR * - Added Rr command for reading date/time - BBR * - Made commands case insensitive - BBR * - Create #define varibles to support pre Arduino v1.0 - JWV * Version 0.01 * Inital code with basics of setting time and the first 37 registers and dumping the first 32 registers. * The code was based on Maurice Ribble's original code. * */

#include "Wire.h"
#define DS1307_I2C_ADDRESS 0x68 // This is the I2C address
// Arduino version compatibility Pre-Compiler Directives
#if defined(ARDUINO) && ARDUINO >= 100 // Arduino v1.0 and newer
  #define I2C_WRITE Wire.write
  #define I2C_READ Wire.read
#else // Arduino Prior to v1.0
  #define I2C_WRITE Wire.send
  #define I2C_READ Wire.receive
#endif
// Global Variables
int command = 0;       // This is the command char, in ascii form, sent from the serial port
int i;
long previousMillis = 0;        // will store last time Temp was updated
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
byte test;
byte zero;
char  *Day[] = {"","Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
char  *Mon[] = {"","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};

// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return ( (val/10*16) + (val%10) );
}

// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return ( (val/16*10) + (val%16) );
}

// 1) Sets the date and time on the ds1307
// 2) Starts the clock
// 3) Sets hour mode to 24 hour clock
// Assumes you're passing in valid numbers, Probably need to put in checks for valid numbers.

void setDateDs1307()               
{

   second = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48)); // Use of (byte) type casting and ascii math to achieve result.
   minute = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   hour  = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   dayOfWeek = (byte) (Serial.read() - 48);
   dayOfMonth = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   month = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   year= (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   Wire.beginTransmission(DS1307_I2C_ADDRESS);
   I2C_WRITE(zero);
   I2C_WRITE(decToBcd(second) & 0x7f);    // 0 to bit 7 starts the clock
   I2C_WRITE(decToBcd(minute));
   I2C_WRITE(decToBcd(hour));      // If you want 12 hour am/pm you need to set
                                   // bit 6 (also need to change readDateDs1307)
   I2C_WRITE(decToBcd(dayOfWeek));
   I2C_WRITE(decToBcd(dayOfMonth));
   I2C_WRITE(decToBcd(month));
   I2C_WRITE(decToBcd(year));
   Wire.endTransmission();
}

// Gets the date and time from the ds1307 and prints result
void getDateDs1307()
{
  // Reset the register pointer
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  I2C_WRITE(zero);
  Wire.endTransmission();

  Wire.requestFrom(DS1307_I2C_ADDRESS, 7);

  // A few of these need masks because certain bits are control bits
  second     = bcdToDec(I2C_READ() & 0x7f);
  minute     = bcdToDec(I2C_READ());
  hour       = bcdToDec(I2C_READ() & 0x3f);  // Need to change this if 12 hour am/pm
  dayOfWeek  = bcdToDec(I2C_READ());
  dayOfMonth = bcdToDec(I2C_READ());
  month      = bcdToDec(I2C_READ());
  year       = bcdToDec(I2C_READ());

  if (hour < 10)
    Serial.print("0");
  Serial.print(hour, DEC);
  Serial.print(":");
  if (minute < 10)
    Serial.print("0");
  Serial.print(minute, DEC);
  Serial.print(":");
  if (second < 10)
    Serial.print("0");
  Serial.print(second, DEC);
  Serial.print(" ");
  Serial.print(Day[dayOfWeek]);
  Serial.print(", ");
  Serial.print(dayOfMonth, DEC);
  Serial.print(" ");
  Serial.print(Mon[month]);
  Serial.print(" 20");
  if (year < 10)
    Serial.print("0");
  Serial.println(year, DEC);

}


void setup() {
  Wire.begin();
  Serial.begin(57600);
  zero=0x00;
}

void loop() {
     if (Serial.available()) {      // Look for char in serial que and process if found
      command = Serial.read();
      if (command == 84 || command == 116) {      //If command = "Tt" Set Date
       setDateDs1307();
       getDateDs1307();
       Serial.println(" ");
      }
      else if (command == 82 || command == 114) {      //If command = "Rr" Read Date ... BBR
       getDateDs1307();
       Serial.println(" ");
      }
      else if (command == 81 || command == 113) {      //If command = "Qq" RTC1307 Memory Functions
        delay(100);    
        if (Serial.available()) {
         command = Serial.read();
         if (command == 49) {        //If command = "1" RTC1307 Initialize Memory - All Data will be set to
                                       // 255 (0xff). Therefore 255 or 0 will be an invalid value.
           Wire.beginTransmission(DS1307_I2C_ADDRESS);   // 255 will be the init value and 0 will be considered
                                                          // an error that occurs when the RTC is in Battery mode.
           I2C_WRITE(0x08); // Set the register pointer to be just past the date/time registers.
           for (i = 1; i <= 24; i++) {
               I2C_WRITE(0Xff);
              delay(10);
           }  
           Wire.endTransmission();
           Wire.beginTransmission(DS1307_I2C_ADDRESS);  
           I2C_WRITE(0x21); // Set the register pointer to 33 for second half of registers. Only 32 writes per connection allowed.
           for (i = 1; i <= 33; i++) {
               I2C_WRITE(0Xff);
              delay(10);
           }  
           Wire.endTransmission();
           getDateDs1307();
           Serial.println(": RTC1307 Initialized Memory");
         }
         else if (command == 50) {      //If command = "2" RTC1307 Memory Dump
          getDateDs1307();
          Serial.println(": RTC 1307 Dump Begin");
          Wire.beginTransmission(DS1307_I2C_ADDRESS);
          I2C_WRITE(zero);
          Wire.endTransmission();
          Wire.requestFrom(DS1307_I2C_ADDRESS, 32);
          for (i = 0; i <= 31; i++) {  //Register 0-31 - only 32 registers allowed per I2C connection
             test = I2C_READ();
             Serial.print(i);
             Serial.print(": ");
             Serial.print(test, DEC);
             Serial.print(" : ");
             Serial.println(test, HEX);
          }
          Wire.beginTransmission(DS1307_I2C_ADDRESS);
          I2C_WRITE(0x20);
          Wire.endTransmission();
          Wire.requestFrom(DS1307_I2C_ADDRESS, 32); 
          for (i = 32; i <= 63; i++) {         //Register 32-63 - only 32 registers allowed per I2C connection
             test = I2C_READ();
             Serial.print(i);
             Serial.print(": ");
             Serial.print(test, DEC);
             Serial.print(" : ");
             Serial.println(test, HEX);
          }
          Serial.println(" RTC1307 Dump end");
         }
        } 
       }
      Serial.print("Command: ");
      Serial.println(command);     // Echo command CHAR in ascii that was sent
      }
      command = 0;                 // reset command
      delay(100);
    }
//*****************************************************The End***********************

Thursday, 6 September 2012

baud rate

1200, 2400, 4800, 9600, 19200, 38400, 57600 and 115200 bits

Wednesday, 22 August 2012

Mysql


Get data at certain time period

select * from smartcontainer.SENSOR_DATA where SAMPLING_TIME> '2012-07-28 15:11:45' and SAMPLING_TIME < '2012-07-28 15:12:00';


Datebase to text

select * from smartcontainer.SENSOR_DATA where SAMPLING_TIME> '2012-07-31 00:00:00' and SAMPLING_TIME < '2012-07-31 24:00:00' and VALUE_STRING = 'Telosb41_Temperature' into outfile '/tmp/Telosb41.txt' ;

Get Latest Value

select * from sensor_data where sampling_time in (select max(sampling_time) from sensor_data group by sensor_id

Tuesday, 19 June 2012

Monday, 18 June 2012

C# socket programming

TCP Client


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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Connect("localhost", "hello");
        }
        static void Connect(String server, String message)
        {
            try
            {
                // Create a TcpClient.
                // Note, for this client to work you need to have a TcpServer 
                // connected to the same address as specified by the server, port
                // combination.
                Int32 port = 13000;
                TcpClient client = new TcpClient(server, port);


                // Translate the passed message into ASCII and store it as a Byte array.
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);


                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();


                NetworkStream stream = client.GetStream();


                // Send the message to the connected TcpServer. 
                stream.Write(data, 0, data.Length);


                Console.WriteLine("Sent: {0}", message);


                // Receive the TcpServer.response.
                // Buffer to store the response bytes.
                data = new Byte[256];


                // String to store the response ASCII representation.
                String responseData = String.Empty;


                // Read the first batch of the TcpServer response bytes.
                Int32 bytes = stream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                Console.WriteLine("Received: {0}", responseData);


                // Close everything.
                client.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }


            Console.WriteLine("\n Press Enter to continue...");
            Console.Read();
        }
    }
}


TCP Listener



using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;


class MyTcpListener
{
    public static void Main()
    {
        try
        {
            // Set the TcpListener on port 13000.
            Int32 port = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");


            // TcpListener server = new TcpListener(port);
            TcpListener server = new TcpListener(localAddr, port);


            // Start listening for client requests.
            server.Start();


            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;


            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");


                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");


                data = null;


                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();


                int i;


                // Loop to receive all the data sent by the client.
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine(String.Format("Received: {0}", data));


                    // Process the data sent by the client.
                    data = data.ToUpper();


                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);


                    // Send back a response.
                    stream.Write(msg, 0, msg.Length);
                    Console.WriteLine(String.Format("Sent: {0}", data));
                }


                // Shutdown and end connection
                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }


        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }
}











Friday, 15 June 2012

A simple PHP chat room

index.php
<html>
<head><Title>
online chart
</title></head>
<!-- frames -->
<frameset rows="70%,*" BORDER="0">
<frame name="top" src="_b.php" marginwidth="0" marginheight="0" scrolling="yes" FRAMEBORDER="NO" noresize>
<frame name="bottom" src="_a.php" marginwidth="0" marginheight="0" scrolling="no" frameborder="no" noresize>
</frameset>
<body>
</body>
</html>

_a.php
<html>
<title>
Chart
</title>
<body TOPMARGIN=0 LEFTMARGIN=0 MARGINWIDTH=0 MARGINHEIGHT=0 >
<?php
$person = @$_POST[person];
$msg = @$_POST[message];
if ($person!="" && $msg!=""){
$handle = fopen("msg.txt","r");
$tot = 0;
$oldmsg = array();
while ($content = fgets($handle)){
$oldmsg[] = $content;
++$tot;
}
fclose($handle);
unlink("msg.txt");
$fp = fopen("msg.txt","a+");
$time = date("h:i");
fwrite($fp,"<font color=\"blue\">".$person."</font> in <font color=\"red\">".$time."</font>  says that  <b>".$msg."</b><br>"."\n");
for ($i =0;$i<$tot;++$i){
if ($i>50) break;
fwrite($fp,$oldmsg[$i]);
}
}
?>
<TABLE width="100%" border="0" cellspacing="0" cellpadding="0">
<tr align="left" bgcolor="#666666">
<td height="20">
</td></tr>
<tr bgcolor="#FFCC66">
<td width="1" height="4" ></td>
</tr>
</TABLE>
<table width="100%" border=0 cellspacing=0 cellpadding=0 bgcolor="#EFEFEF">
<tr bgcolor="#666666">
<td align="left">
<table width="100%" height="500" boder=0 cellspacing=0 cellpadding=0 bgcolor="#EFEFEF">
<tr align="left">
<td valign="top">
<font size="-1" color="#666666">
<table width = "100%" border = "0">
<tr>
<form action="_a.php" method = "post">
<td align="left">
<font size="-1">Name:</font>
<input type="text" name="person" size="12" maxlength="80" value="<?php echo $person;?>">
<br>
<font size="-1"></font>
<textarea type="textarea" name="message" rows="9" cols="150" size = 100></textarea>
<input type="submit" value="Say">
</td>
</form>
</tr>
</table>
</font>
</td>
</tr>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>

_b.php
<html>
<head>
<title>
Chat
</title>
</head>
<META HTTP-EQUIV=Refresh CONTENT="5; URL=_b.php">
<body bgcolor="#EFEFEF">
<?php
$handle=fopen("msg.txt","r");
//$oldmsg = array();
while ($content = fgets($handle)){
//$oldmsg[] = $content;
//++$tot;
echo $content;
}
?>
</body>
</html>

Tuesday, 5 June 2012

sky-shell-exec

Software engineering like a handcraft.
Just add on something, but not delete something.

Tuesday, 29 May 2012

Login as Root in Ubuntu 11.04

Type the command below to create a new password for the root user

$ sudo passwd root

Monday, 28 May 2012

Writing to expansion pins on Telos B

#include "contiki.h"
#include "httpd-simple.h"
#include "net/rpl/rpl.h"
#include "dev/leds.h"
#include <stdio.h>
#include <io.h>

#define P23_OUT() P2DIR |= BV(3)
#define P23_IN() P2DIR &= ~BV(3)
#define P23_SEL() P2SEL &= ~BV(3)
#define P23_IS_1  (P2OUT & BV(3))
#define P23_WAIT_FOR_1() do{}while (!P23_IS_1)
#define P23_IS_0  (P2OUT & ~BV(3))
#define P23_WAIT_FOR_0() do{}while (!P23_IS_0)
#define P23_1() P2OUT |= BV(3)
#define P23_0() P2OUT &= ~BV(3)


static uint8_t toggle;
PROCESS(web_sense_process, "Sense Web Demo");
PROCESS(webserver_nogui_process, "Web server");
PROCESS_THREAD(webserver_nogui_process, ev, data)
{
  PROCESS_BEGIN();
  httpd_init();
  while(1) {
    PROCESS_WAIT_EVENT_UNTIL(ev == tcpip_event);
    httpd_appcall(data);
  }
  PROCESS_END();
}
AUTOSTART_PROCESSES(&web_sense_process,&webserver_nogui_process);
/*---------------------------------------------------------------------------*/
static const char *TOP = "<html><head><title>Contiki Web Sense</title></head><body>\n";
static const char *BOTTOM = "</body></html>\n";
/*---------------------------------------------------------------------------*/
/* Only one single request at time */
static char buf[256];
static int blen;
#define ADD(...) do {                                                   \
    blen += snprintf(&buf[blen], sizeof(buf) - blen, __VA_ARGS__);      \
  } while(0)
static
PT_THREAD(send_values(struct httpd_state *s))
{
  PSOCK_BEGIN(&s->sout);
 // SEND_STRING(&s->sout, TOP);
  if(strncmp(s->filename, "/index", 6) == 0 ||
     s->filename[1] == '\0') {
  } else if(s->filename[1] == '0') {
    /* Turn off leds */ 
    toggle=0;
    //leds_off(LEDS_ALL);
   //  SEND_STRING(&s->sout, "Turned off leds!");
  } else if(s->filename[1] == '1') {
    /* Turn on leds */ 
    toggle=1;
    //leds_on(LEDS_ALL);
   // SEND_STRING(&s->sout, "Turned on leds!");
  }
 
  //SEND_STRING(&s->sout, BOTTOM);
  PSOCK_END(&s->sout);
}
/*---------------------------------------------------------------------------*/
httpd_simple_script_t
httpd_simple_get_script(const char *name)
{
  return send_values;
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(web_sense_process, ev, data)
{
  static struct etimer timer;
  PROCESS_BEGIN();
  etimer_set(&timer, CLOCK_SECOND * 2);
  P23_OUT();
  P23_SEL();
 

  while(1) {
    PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&timer));
    etimer_reset(&timer);
    if(toggle==0)
    {  
          P23_1();  
          rpl_repair_dag(rpl_get_dag(RPL_ANY_INSTANCE));     
    }
    else
    {
          P23_0();   
          rpl_repair_dag(rpl_get_dag(RPL_ANY_INSTANCE));
    }
  }
  PROCESS_END();
}
/*---------------------------------------------------------------------------*/