2016年5月8日 星期日

Raspberry Pi: Real-Time Face Detection With USB Webcam & GPIO(I2C)

since: 2016/05/08
update: 2016/08/11
reference:
1. openframeworks
2. GitHub - kashimAstro/ofxGPIO
3. I touchs: Raspberry Pi: Connected Arduino Using I2C


A. 功能測試: opencvHaarFinderExample

    // 單張照片臉部辨識
    $ cd /home/pi/of_v0.9.3/examples/addons/opencvHaarFinderExample
    $ make
    $ ./bin/opencvHaarFinderExample    // 結果

-----------------------------------------------------------------------------------------------

B. 功能測試: videoGrabberExample
    // USB Web Cam
    $ cd /home/pi/of_v0.9.3/examples/video/videoGrabberExample
    $ make
    $ ./bin/videoGrabberExample

    // 結果

-----------------------------------------------------------------------------------------------

C. Face Detection With USB Webcam
    1. addons.make
        ofxOpenCv

***********************************************

    2. main.cpp
#include "ofMain.h"
#include "ofApp.h"

//========================================================================
int main( ){
    ofSetLogLevel(OF_LOG_VERBOSE);
   
    // read config file
    vector<string> _linesOfTheFile;
    ofBuffer _buffer = ofBufferFromFile("config.txt");
    for (auto line : _buffer.getLines()){
        _linesOfTheFile.push_back(line);
    }
   
    // local variables
    int _debug = ofToBool(_linesOfTheFile[1]);
    int _camWidth = ofToInt(_linesOfTheFile[4]);
    int _camHeight = ofToInt(_linesOfTheFile[7]);
    bool _fullScreen = ofToBool(_linesOfTheFile[10]);
   
    // show debug message
    if(_debug) {
        ofLog() << "****** main()";
        ofLog() << "debug: " << _debug;
        ofLog() << "OpenGL width: " << _camWidth;
        ofLog() << "OpenGL height: " << _camHeight;
        ofLog() << "fullScreen: " << _fullScreen;
    }

    // fullScreen
    if(_fullScreen) {
        // set camWidth & camHeight as window's
        ofSetupOpenGL(_camWidth, _camHeight, OF_FULLSCREEN);
    }
    // window
    else {
        // set camWidth & camHeight as window's
        ofSetupOpenGL(_camWidth, _camHeight, OF_WINDOW);
    }
   
    // this kicks off the running of my app
    // can be OF_WINDOW or OF_FULLSCREEN
    // pass in width and height too:

    ofRunApp(new ofApp());
}


***********************************************

    3. ofApp.h
#pragma once

#include "ofMain.h"
#include "ofxCvHaarFinder.h"

class ofApp : public ofBaseApp{

    public:
        void setup();
        void update();
        void draw();

        void keyPressed(int key);
        void keyReleased(int key);
        void mouseMoved(int x, int y );
        void mouseDragged(int x, int y, int button);
        void mousePressed(int x, int y, int button);
        void mouseReleased(int x, int y, int button);
        void mouseEntered(int x, int y);
        void mouseExited(int x, int y);
        void windowResized(int w, int h);
        void dragEvent(ofDragInfo dragInfo);
        void gotMessage(ofMessage msg);
   
        //@add for VideoGrabber
        ofVideoGrabber vidGrabber;

        //@add for CvHaarFinder
        //ofImage img;

        ofxCvHaarFinder finder;
   
        //@add second record
        float countROI;
        long readSeconds; // read from totalSeconds record file
        long writeSeconds; // write to totalSeconds record file
        long latestSeconds; // latestSeconds
   
        // config file
        bool debug;
        int camWidth;
        int camHeight;
        bool fullScreen;
        int frameRate;
        bool concurrentVisit;
        float minROI;
        float maxROI;
        float weightROI;
        string recordFile;
};


***********************************************

    4. ofApp.cpp
#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    ofSetLogLevel(OF_LOG_VERBOSE);
   
    // read config file
    vector<string> linesOfTheFile;
    ofBuffer buffer = ofBufferFromFile("config.txt");
    for (auto line : buffer.getLines()){
        linesOfTheFile.push_back(line);
    }
    //for (int i = 0; i < linesOfTheFile.size(); i++) {
    //    ofLog(OF_LOG_VERBOSE, "cur.width = %s", linesOfTheFile[i].c_str());
    //}

   
    debug = ofToBool(linesOfTheFile[1]);
    camWidth = ofToInt(linesOfTheFile[4]);
    camHeight = ofToInt(linesOfTheFile[7]);
    fullScreen = ofToBool(linesOfTheFile[10]);
    frameRate = ofToInt(linesOfTheFile[13]);
    concurrentVisit = ofToBool(linesOfTheFile[16]);
    minROI = ofToFloat(linesOfTheFile[19]);
    maxROI = ofToFloat(linesOfTheFile[22]);
    weightROI = ofToFloat(linesOfTheFile[25]);
    recordFile = linesOfTheFile[28];
   
    if(debug)
    {
        ofLog() << "****** ofApp::setup()";
        ofLog() << "debug: " << debug;
        ofLog() << "camWidth: " << camWidth;
        ofLog() << "camHeight: " << camHeight;
        ofLog() << "fullScreen: " << fullScreen;
        ofLog() << "frameRate: " << frameRate;
        ofLog() << "concurrentVisit: " << concurrentVisit;
        ofLog() << "minROI: " << minROI;
        ofLog() << "maxROI: " << maxROI;
        ofLog() << "weightROI: " << weightROI;
        ofLog() << "recordFile: " << recordFile;
    }
   
    // read totalSeconds record file
    vector<string> totalSecondsFile;
    ofBuffer sbuffer = ofBufferFromFile(recordFile);
    for (auto line : sbuffer.getLines()){
        totalSecondsFile.push_back(line);
    }
   
    readSeconds = ofToFloat(totalSecondsFile[0]);
   
    if(debug)
    {
        ofLog() << "****** read totalSeconds record file";
        ofLog() << "readSeconds: " << readSeconds;
    }
   
    //ofSetFrameRate(5);
    ofSetFrameRate(frameRate);
   
    //@add for VideoGrabber
    //we can now get back a list of devices.

    vector<ofVideoDevice> devices = vidGrabber.listDevices();
   
    for(int i = 0; i < devices.size(); i++){
        if(devices[i].bAvailable){
            ofLogNotice() << devices[i].id << ": " << devices[i].deviceName;
        }else{
            ofLogNotice() << devices[i].id << ": " << devices[i].deviceName << " - unavailable ";
        }
    }
   
    vidGrabber.setDeviceID(0);
    //vidGrabber.setDesiredFrameRate(60);
    vidGrabber.setDesiredFrameRate(frameRate);
    vidGrabber.initGrabber(camWidth, camHeight);
    ofSetVerticalSync(true);
   
    //@add for CvHaarFinder
    //img.load("test.jpg");

    finder.setup("haarcascade_frontalface_default.xml");
    //finder.findHaarObjects(img);
}

//--------------------------------------------------------------
void ofApp::update(){
    //@add for VideoGrabber
    ofBackground(100, 100, 100);
    vidGrabber.update();
   
    //@add for CvHaarFinder
    if(vidGrabber.isFrameNew()){
        ofPixels & pixels = vidGrabber.getPixels();
        finder.findHaarObjects(pixels);
    }
}

//--------------------------------------------------------------
void ofApp::draw(){
   
    //@add for VideoGrabber
    ofSetHexColor(0xffffff);
    vidGrabber.draw(0, 0);
   
    //@add for CvHaarFinder
    //img.draw(0, 0);

   
    ofNoFill();
    for(unsigned int i = 0; i < finder.blobs.size(); i++) {
       
        ofRectangle cur = finder.blobs[i].boundingRect;
       
        //if(debug){
        //    ofLog(OF_LOG_VERBOSE, "ROI width = %f", cur.width);
        //    ofLog(OF_LOG_VERBOSE, "ROI height = %f", cur.height);
        //}
       
        //if((cur.width >= 50.0 && cur.width <= 150.0) &&
        //   (cur.height >= 50.0 && cur.height <= 150.0)) {

        if((cur.width >= (minROI * camWidth) && cur.width <= (maxROI * camWidth)) &&
          (cur.height >= (minROI * camWidth) && cur.height <= (maxROI * camWidth))) {
           
            countROI++;
            ofSetColor(255, 0, 0); // red color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
           
            if(debug) {
                ofSetColor(ofColor::yellow);
                ofDrawBitmapString("ROI = " + ofToString(cur.width) + " x " + ofToString(cur.height), camWidth/5, camHeight/1.02);
            }
           
            // not concurrent Visit
            if(!concurrentVisit){
                break;
            }
        }
        else {
            ofSetColor(0, 0, 255); // blue color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
        }
    }
   
    // writeSeconds
    writeSeconds = readSeconds + (countROI / frameRate * weightROI); // weightROI: for calibrate detect missing
   
    if(writeSeconds > latestSeconds){
        // Write data
        if(debug) {
            // totalSeconds record file
            ofLog() << "****** write totalSeconds record file: " << writeSeconds;
        }
       
        ofBuffer secondsBuff;
        secondsBuff.set(ofToString(writeSeconds));
        bool fileWritten = ofBufferToFile(recordFile, secondsBuff);
       
        latestSeconds = writeSeconds;
    }

    if(debug){
        // show message
        ofSetColor(ofColor::white);
        ofDrawBitmapString("total seconds: " + ofToString(writeSeconds), camWidth/5, camHeight/1.2);
        ofDrawBitmapString(ofToString(minROI * camWidth) + " <= ROI <= " + ofToString(maxROI * camWidth), camWidth/5, camHeight/1.1);
    }
   
    ofSetColor(100, 100, 100);
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){
    //@add for VideoGrabber
    if(key == 'd' || key == 'D'){
        debug = !debug;
    }
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){

}

//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}


***********************************************

    5. bin/data 資料夾
        a. haarcascade_frontalface_default.xml // from ofxOpenCv

        b. totalSeconds.txt // record second
            0

        c. config.txt // config file
# debug (true/false)
false

# cam width (int)
320

# cam height (int)
240

# full screen (true/false)
false

# frame rate (int)
5

# concurrent visit (true/false)

false

# minimum width ratio of ROI(region of interest) (float)
0.125

# maximum width ratio of ROI(region of interest) (float)
0.5

# weight of ROI (float)
1.0

# recordFile (string)
totalSeconds.txt

-----------------------------------------------------------------------------------------------

* 無法正常作用(可能要配合 ofx 0.9.2) *
D. 利用 GPIO( or I²C: Inter-Integrated Circuit) 傳送資料給 Arduino
     1. 參考: I touchs: Raspberry Pi: Connected Arduino Using I2C
         > 讓 Raspberry Pi 的 I2C 功能啟用, 並且記下以下的資料

           $ ls /dev/i2c*
           /dev/i2c-1

           以及 Arduino 裡的定義:
          
#define SLAVE_ADDRESS 0x04
 
     2. 安裝 ofxGPIO
         $ cd /home/pi/of_v0.9.3/addons 
         $ git clone https://github.com/kashimAstro/ofxGPIO

     3. 修改專案的 addons.make 檔案如下:
         /home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB/addons.make
         ofxOpenCv
         ofxGPIO


     4.
修改 ofApp.h 如下:
/home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB/src/
ofApp.h
 
#pragma once

#include "ofMain.h"
#include "ofxCvHaarFinder.h"
//@add for GPIO
#include "ofxGPIO.h"

class ofApp : public ofBaseApp{

    public:
        void setup();
        void update();
        void draw();
        //@add for GPIO 
        //void exit();

        void keyPressed(int key);
        void keyReleased(int key);
        void mouseMoved(int x, int y );
        void mouseDragged(int x, int y, int button);
        void mousePressed(int x, int y, int button);
        void mouseReleased(int x, int y, int button);
        void mouseEntered(int x, int y);
        void mouseExited(int x, int y);
        void windowResized(int w, int h);
        void dragEvent(ofDragInfo dragInfo);
        void gotMessage(ofMessage msg);
   
        //@add for VideoGrabber
        ofVideoGrabber vidGrabber;

        //@add for CvHaarFinder
        //ofImage img;
        ofxCvHaarFinder finder;
   
        //@add second record
        float countROI;
        long readSeconds; // read from totalSeconds record file
        long writeSeconds; // write to totalSeconds record file
        long latestSeconds; // latestSeconds
   
        // config file
        bool debug;
        int camWidth;
        int camHeight;
        bool fullScreen;
        int frameRate;
        bool concurrentVisit;
        float minROI;
        float maxROI;
        float weightROI;
        string recordFile;

        //@add for I2C
        //I2CBus * bus;

        //@add for GPIO
        //GPIO ofxGPIO;
        GPIO* ofxGPIO;

};

 
     5.
修改 ofApp.cpp 如下:
/home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB/src/ofApp.cpp
#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    ofSetLogLevel(OF_LOG_VERBOSE);

    // read config file
    vector<string> linesOfTheFile;
    ofBuffer buffer = ofBufferFromFile("config.txt");
    for (auto line : buffer.getLines()){
        linesOfTheFile.push_back(line);
    }
    //for (int i = 0; i < linesOfTheFile.size(); i++) {
    //    ofLog(OF_LOG_VERBOSE, "cur.width = %s", linesOfTheFile[i].c_str());
    //}
   
    debug = ofToBool(linesOfTheFile[1]);
    camWidth = ofToInt(linesOfTheFile[4]);
    camHeight = ofToInt(linesOfTheFile[7]);
    fullScreen = ofToBool(linesOfTheFile[10]);
    frameRate = ofToInt(linesOfTheFile[13]);
    concurrentVisit = ofToBool(linesOfTheFile[16]);
    minROI = ofToFloat(linesOfTheFile[19]);
    maxROI = ofToFloat(linesOfTheFile[22]);
    weightROI = ofToFloat(linesOfTheFile[25]);
    recordFile = linesOfTheFile[28];
   
    if(debug)
    {
        ofLog() << "****** ofApp::setup()";
        ofLog() << "debug: " << debug;
        ofLog() << "camWidth: " << camWidth;
        ofLog() << "camHeight: " << camHeight;
        ofLog() << "fullScreen: " << fullScreen;
        ofLog() << "frameRate: " << frameRate;
        ofLog() << "concurrentVisit: " << concurrentVisit;
        ofLog() << "minROI: " << minROI;
        ofLog() << "maxROI: " << maxROI;
        ofLog() << "weightROI: " << weightROI;
        ofLog() << "recordFile: " << recordFile;
    }
   
    // read totalSeconds record file
    vector<string> totalSecondsFile;
    ofBuffer sbuffer = ofBufferFromFile(recordFile);
    for (auto line : sbuffer.getLines()){
        totalSecondsFile.push_back(line);
    }
   
    readSeconds = ofToFloat(totalSecondsFile[0]);
   
    if(debug)
    {
        ofLog() << "****** read totalSeconds record file";
        ofLog() << "readSeconds: " << readSeconds;
    }
   
    //ofSetFrameRate(5);
    ofSetFrameRate(frameRate);
   
    //@add for VideoGrabber
    //we can now get back a list of devices.
    vector<ofVideoDevice> devices = vidGrabber.listDevices();
   
    for(int i = 0; i < devices.size(); i++){
        if(devices[i].bAvailable){
            ofLogNotice() << devices[i].id << ": " << devices[i].deviceName;
        }else{
            ofLogNotice() << devices[i].id << ": " << devices[i].deviceName << " - unavailable ";
        }
    }
   
    vidGrabber.setDeviceID(0);
    //vidGrabber.setDesiredFrameRate(60);
    vidGrabber.setDesiredFrameRate(frameRate);
    vidGrabber.initGrabber(camWidth, camHeight);
    ofSetVerticalSync(true);
   
    //@add for CvHaarFinder
    //img.load("test.jpg");
    finder.setup("haarcascade_frontalface_default.xml");
    //finder.findHaarObjects(img);

    //@add for GPIO
    //bus = new I2CBus("/dev/i2c-1");
    //bus->addressSet(0x04);


    //@add for GPIO (pin) 
    //ofxGPIO.setup("7");
    //ofxGPIO.export_gpio();
    //ofxGPIO.setdir_gpio("out");

    ofxGPIO = new GPIO("7");
    ofxGPIO->export_gpio();
    ofxGPIO->setdir_gpio("out");

}

//--------------------------------------------------------------
void ofApp::update(){
    //@add for VideoGrabber
    ofBackground(100, 100, 100);
    vidGrabber.update();
   
    //@add for CvHaarFinder
    if(vidGrabber.isFrameNew()){
        ofPixels & pixels = vidGrabber.getPixels();
        finder.findHaarObjects(pixels);
    }
}

//--------------------------------------------------------------
void ofApp::draw(){
   
    //@add for VideoGrabber
    ofSetHexColor(0xffffff);
    vidGrabber.draw(0, 0);
   
    //@add for CvHaarFinder
    //img.draw(0, 0);
   
    ofNoFill();
    for(unsigned int i = 0; i < finder.blobs.size(); i++) {
       
        ofRectangle cur = finder.blobs[i].boundingRect;
       
        //if(debug){
        //    ofLog(OF_LOG_VERBOSE, "ROI width = %f", cur.width);
        //    ofLog(OF_LOG_VERBOSE, "ROI height = %f", cur.height);
        //}
       
        //if((cur.width >= 50.0 && cur.width <= 150.0) &&
        //   (cur.height >= 50.0 && cur.height <= 150.0)) {
        if((cur.width >= (minROI * camWidth) && cur.width <= (maxROI * camWidth)) &&
          (cur.height >= (minROI * camWidth) && cur.height <= (maxROI * camWidth))) {
           
            countROI++;
            ofSetColor(255, 0, 0); // red color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
           
            if(debug) {
                ofSetColor(ofColor::yellow);
                ofDrawBitmapString("ROI = " + ofToString(cur.width) + " x " + ofToString(cur.height), camWidth/5, camHeight/1.02);
            }
           
            // not concurrent Visit
            if(!concurrentVisit){
                break;
            }
        }
        else {
            ofSetColor(0, 0, 255); // blue color
            ofDrawRectangle(cur.x, cur.y, cur.width, cur.height);
        }
    }
   
    // writeSeconds
    writeSeconds = readSeconds + (countROI / frameRate * weightROI); // weightROI: for calibrate detect missing
   
    if(writeSeconds > latestSeconds){
        // Write data
        if(debug) {
            // totalSeconds record file
            ofLog() << "****** write totalSeconds record file: " << writeSeconds;
        }
       
        ofBuffer secondsBuff;
        secondsBuff.set(ofToString(writeSeconds));
        bool fileWritten = ofBufferToFile(recordFile, secondsBuff);
       
        latestSeconds = writeSeconds;

        //@add for GPIO
        //bus->writeByte(0x04, writeSeconds);
        //usleep(50000); // sleep for 0.05 second

        //@add for test

        /*
        bus->writeByte(0x04,1);
        usleep(500000); // sleep for 0.5 second
        bus->writeByte(0x04,0);
        usleep(500000); // sleep for 0.5 second  

        */  

        //@add for GPIO
        //ofxGPIO.setval_gpio("1");
        //usleep(50000); // sleep for 0.05 second
        //ofxGPIO.setval_gpio("0");
        //usleep(50000); // sleep for 0.05 second

        ofxGPIO->setval_gpio("1");
        usleep(50000); // sleep for 0.05 second
        ofxGPIO->setval_gpio("0");
        usleep(50000); // sleep for 0.05 second

    }

    if(debug){
        // show message
        ofSetColor(ofColor::white);
        ofDrawBitmapString("total seconds: " + ofToString(writeSeconds), camWidth/5, camHeight/1.2);
        ofDrawBitmapString(ofToString(minROI * camWidth) + " <= ROI <= " + ofToString(maxROI * camWidth), camWidth/5, camHeight/1.1);
    }
   
    ofSetColor(100, 100, 100);
}

/*
//--------------------------------------------------------------
void ofApp::exit(){
   
    //@add for GPIO
    ofxGPIO.unexport_gpio();
}

*/

//--------------------------------------------------------------
void ofApp::keyPressed(int key){
    //@add for VideoGrabber
    if(key == 'd' || key == 'D'){
        debug = !debug;
    }
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}

//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}

 
     6. 編譯與執行:
         $ cd /home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB
         $ make         

         $ ./bin/DPHeadTrackingUSB

     7. 開機後自動執行: (console 的訊息會出不來, 建議改成在 .bashrc 裡執行程式)
         $ cd
         $ touch startHeadTracking.sh
         $ chmod 755 startHeadTracking.sh

         $ sudo nano startHeadTracking.sh
#!/bin/bash
sleep 5
cd /home/pi/of_v0.9.3/apps/myApps/DPHeadTrackingUSB
./bin/DPHeadTrackingUSB


         $ cat startHeadTracking.sh

         $ sudo crontab -e
         ....
         @reboot /home/pi/startHeadTracking.sh

         $ sudo crontab -l

2016年4月28日 星期四

Raspberry Pi: Geolocation

since: 2016/04/28
update: 2016/04/28
reference:
1. geocoder : Python Package Index
2. geopy: Python Package Index
3. python-geoip — python-geoip

A. Get current IP location
    1. install geocoder (for python2 only)
        $ pip --upgrade geocoder

    2. get latitude(緯度) and longitude(經度) from current IP
pi@raspberrypi:~ $ python
Python 2.7.9 (default, Mar  8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import geocoder
>>> g = geocoder.ip('me')
>>> g.latlng
[23.5, 121.0]
>>> exit()


-----------------------------------------------------------------------------------------------

B. Measuring Distance
    1. install geopy (for both python2 and python3)
       $ sudo pip install geopy
       $ sudo pip install python-geoip-python3

    2. Measuring Distance (Using great-circle distance)
pi@raspberrypi:~ $ python3
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from geopy.distance import great_circle
>>> newport_ri = (41.49008, -71.312796)
>>> cleveland_oh = (41.499498, -81.695391)
>>> print(great_circle(newport_ri, cleveland_oh).meters)
864456.7616296598
>>> exit()


-----------------------------------------------------------------------------------------------

C. Looks up the IP information (test for python2 only)
    1. install geoip
       $ sudo pip install python-geoip
       $ sudo pip install python-geoip-python3
       $ sudo pip install python-geoip-geolite2

    2. Looks up the IP information (real IP)
pi@raspberrypi:~ $ python
Python 2.7.9 (default, Mar  8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from geoip import geolite2
>>> match = geolite2.lookup('17.0.0.1')
>>> match.location
(37.323, -122.0322)
>>> exit()

2016年3月29日 星期二

Raspberry Pi: Turn It Into An Beacon Node

since: 2016/03/29
update: 2016/04/01

reference:
1. Raspberry Pi應用 - Bluetooth 4.0 使用 iBeacon 
2. Overview | piBeacon - DIY Beacon with a Raspberry Pi 
3. Raspberry Pi 3 as an Eddystone URL beacon 


A. Install Required Libraries
    $ sudo apt-get install libusb-dev libdbus-1-dev libglib2.0-dev libudev-dev libical-dev libreadline-dev

-----------------------------------------------------------------------------------------------

B. Download Bluez

    $ sudo mkdir bluez
    $ cd bluez
    $ sudo wget www.kernel.org/pub/linux/bluetooth/bluez-5.38.tar.xz

-----------------------------------------------------------------------------------------------

C. Unzip and Compile Bluez

    $ sudo unxz bluez-5.38.tar.xz
    $ sudo tar xvf bluez-5.38.tar
    $ cd bluez-5.38
    $ sudo ./configure --disable-systemd
   
    $ sudo make
    $ sudo make install
-----------------------------------------------------------------------------------------------

D. Check for your USB Module

    $ cd /home/pi/bluez/bluez-5.38
    $ tools/hciconfig

    hci0:    Type: BR/EDR  Bus: USB
    BD Address: 00:1A:7D:DA:71:13  ACL MTU: 310:10  SCO MTU: 64:8
    UP RUNNING
    RX bytes:652 acl:0 sco:0 events:43 errors:0
    TX bytes:1533 acl:0 sco:0 commands:43 errors:0


-----------------------------------------------------------------------------------------------

E. Enable the USB Device
    $ sudo tools/hciconfig hci0 up
    $ sudo tools/hciconfig hci0 leadv 3

      LE set advertise enable on hci0 returned status 12

    $ sudo tools/hciconfig hci0 noscan

-----------------------------------------------------------------------------------------------

F. Enter the Beacon Advertising Data
   $ sudo tools/hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61 00 00 00 00 C8 00

< HCI Command: ogf 0x08, ocf 0x0008, plen 32
  1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F
  17 D1 AD 07 A9 61 00 00 00 00 C8 00
> HCI Event: 0x0e plen 4
  01 08 20 00


-----------------------------------------------------------------------------------------------

G. 測試軟體
     1. Mac: Beacon Scan

     2. iOS: Locate Beacon

     3. Android: Locate Beacon

-----------------------------------------------------------------------------------------------

H. 簡易開機自動啟動

     $ sudo nano /home/pi/iBeacon.sh
#!/bin/bash
sleep 5
cd /home/pi/bluez/bluez-5.38/
tools/hciconfig hci0 leadv 3
tools/hciconfig hci0 noscan
tools/hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61 00 00 00 00 C8 00


     $ sudo crontab -e
        ....
        @reboot /home/pi/iBeacon.sh

-----------------------------------------------------------------------------------------------
I. 測試結果:(iOS)








2016年3月3日 星期四

Raspberry Pi: Python Remote Development With PyCharm

since: 2016/03/03
update: 2017/01/21

reference:
1. Feature Spotlight: Python remote development with PyCharm | PyCharm Blog
2. https://www.mercurial-scm.org/wiki/Download

A. 在 Pi 上建立專案資料夾:
    $ cd
    $ mkdir project
    $ cd project
    $ mkdir routine_task

-----------------------------------------------------------------------------------------------

(選擇性)
B. 在  Mac 上安裝 Mercurial 版本控制
     

1. install brew: http://brew.sh
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

     

2. install mercurial
$ brew install mercurial


3. check PyCharm, add hg path: (later)

   
/usr/local/bin/hg


4. add configuration file
    $ cd
    $ vi .hgrc
[ui]
username = Lanli <yourID@gmail.com>


[tortoisehg]
ui.language = zh_TW


[auth]
bitbucket.org.prefix = bitbucket.org
bitbucket.org.username = lanli
bitbucket.org.password =
yourPass 

5. check again
    $ cat .hgrc

 
-----------------------------------------------------------------------------------------------

C. 在 Mac 上用 PyCharm 建立新的專案:

    1. Create New Project:

    2. Setting:
        Location: 本地專案位置
        Interpreter: 直譯器, 選取 remote 的 ssh 連線方式
         > Create

-----------------------------------------------------------------------------------------------

D. 設定將專案內容部署至遠端
     1. PyCharm > Preferences... > Build, Execution, Deployment > Deployment:

         Name: Rasberry Pi2
         Type: SFTP
          > OK


     2. 設定 Connection 頁籤內容:
         Type: SFTP
         SFTP host: 192.168.1.6
         Port: 22
         Root path: /       (建議設為 / )
         User name: pi
         Password: **

     3. 設定 Mapping 頁籤內容:
         Local path: 本地專案位置
         Development path on server 'Raspberry Pi2': 遠端專案目錄
         (備註: 會以
Connection 頁籤裡的 Root path 作為相對位置 )
         > OK


-----------------------------------------------------------------------------------------------

E. 測試:
     1. 將檔案部署至遠端

        a. 新增 python 檔案: HelloPython.py
      #!/usr/bin/python3      
      print('Hello Python')

    b. Tools > Deployment > Upload to Raspberry Pi2

    C. 檢查 pi 上的專案目錄: 

     2. 執行遠端程式:
         a. Run > Run 'HelloPython'


         b. 結果:

-----------------------------------------------------------------------------------------------

F. Create Project By Check out Version Control

    1. 確定已完成:
        B. 在  Mac 上安裝 Mercurial 版本控制


    2. Check out from Version Control

    3. Clone Repository

    4. Checkout From Version Control

2016年3月2日 星期三

Raspberry Pi: Connected Arduino Using I2C

since: 2016/02/25
update: 2016/03/03

reference:
1.Raspberry Pi and Arduino Connected Using I2C - OscarLiang.net
2. [I2C] onRequest and onReceive as slave with Raspberry Pi Master

A. 檢查 Raspberry Pi:
   
1. Linux 版本

    $ uname -a
Linux raspberrypi 4.1.17-v7+ #843 SMP Mon Feb 15 23:35:33 GMT 2016 armv7l GNU/Linux

    2. python 版本
    $ python -V
Python 2.7.9

-----------------------------------------------------------------------------------------------

B. 安裝 I2C 與 python相關套件:
    $ sudo apt-get install python-smbus
    $ sudo apt-get install python3-smbus // for python3
    $ sudo apt-get install i2c-tools

    // check
    $ sudo aptitude search smbus
p   pypy-smbus-cffi        - This Python module allows SMBus access through the I2C /dev              
i   python-smbus            - Python bindings for Linux SMBus access through i2c-dev                   
v   python2.7-smbus      -                                                                          
i   python3-smbus          - Python 3 bindings for Linux SMBus access through i2c-dev


-----------------------------------------------------------------------------------------------

C. 安裝 I2C 的 Kernel Support:
     $ sudo raspi-config
        > 9 Advanced Options

        > A7 I2C

        > Yes
       ....
        > Yes

-----------------------------------------------------------------------------------------------

D. 檢查設定(選擇性)
     $ cat /etc/modules
....
i2c-dev
    
     $ cat /etc/modprobe.d/raspi-blacklist.conf
# ...
# ...


    $ cat /boot/config.txt
....
dtparam=i2c_arm=on

    $ cat /etc/group | grep i2c
i2c:x:998:pi
      // $ sudo adduser pi i2c

-----------------------------------------------------------------------------------------------

E. I2C 測試:
    $ sudo i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- -- 


    $ ls /dev/i2c*
/dev/i2c-1
-----------------------------------------------------------------------------------------------

F. Arduino Code:
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600); // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
    //Serial.println(“Ready!”);
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){

    while(Wire.available()) {
        number = Wire.read();
        //Serial.print(“data received: “);
        //Serial.println(number);


        if (number == 1){

            if (state == 0){
                digitalWrite(13, HIGH); // set the LED on
                state = 1;
            }
            else{
                digitalWrite(13, LOW); // set the LED off
                state = 0;
            }
        }
    }
}

// callback for sending data
void sendData(){
    Wire.write(number);
}


-----------------------------------------------------------------------------------------------

G. Raspberry Pi's  Python Code:
#!/usr/bin/python
#encoding: utf-8

import smbus
import time

# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

def writeNumber(value):
    bus.write_byte(address, value)
    # bus.write_byte_data(address, 0, value)
    return -1

def readNumber():
    number = bus.read_byte(address)
    # number = bus.read_byte_data(address, 1)
    return number

while True:
    var = input("Enter 1 – 9:")
    if not var:
        continue

    writeNumber(var)
    print "RPI: Hi Arduino, I sent you ", var
    # sleep one second
    time.sleep(1)

    number = readNumber()
    print "Arduino: Hey RPI, I received a digit ", number
    print


-----------------------------------------------------------------------------------------------

H. 備註:
When we use read_i2c_block_data(), It was too fast to write a command byte and read the data.

In that time, if we use Serial.println() to print log to serial. Arduino will can not follow the speed. and it missing the i2c read flag.

So, the dataReceive() funtion will not be run at all.

The solution is simple: just do not use Serial library until the i2c is free.

2016年2月19日 星期五

Raspberry Pi: Setting Up The Watchdog

since: 2016/02/19
update: 2016/02/19

reference:
1. 樹莓派硬體看門狗(Watchdog):當機時自動重新開機 - G. T. Wang
2. ssmtp to send emails – Raspberry Pi Projects


A. Sending Email From Your System with sSMTP
    1. 安裝套件:
        $ sudo apt-get install ssmtp
        $ sudo apt-get install mailutils

    2. 編輯設定檔:
        $ sudo nano /etc/ssmtp/ssmtp.conf
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
#root=postmaster
root=lanlixxxx@gmail.com

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
#mailhub=mail
mailhub=smtp.gmail.com:587

# Where will the mail seem to come from?
#rewriteDomain=

# The full hostname
hostname=raspberrypi

# Auth
AuthUser=pythonicxxxx@gmail.com
AuthPass=pythonxxxx


# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES
UseSTARTTLS=YES


    3. 降低寄發郵件的安全性設定: (AuthUser)
        > GMail 低安全性應用程式 - 帳戶設定

    4. 寄發測試郵件:
        $ echo "Hello world email body" | mail -s "Test Subject" lanlixxxx@gmail.com

    5. 寄發 "附加檔案" 測試郵件:
        $ sudo apt-get install mpack
        $ mpack -s "Test" somefile.txt lanlixxxx@gmail.com

-----------------------------------------------------------------------------------------------

B. 安裝 watchdog

    1. 啟用 bcm2708_wdog 核心模組
        $ sudo nano /etc/modules
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.

i2c-dev

bcm2708_wdog

    2. 立即啟用:
        $ sudo modprobe bcm2708_wdog

    3. 安裝 watchdog 監控 Daemon
        $ sudo apt-get install watchdog

-----------------------------------------------------------------------------------------------

C. 編輯 watchdog 設定檔
    $ sudo nano /etc/watchdog.conf
#ping                   = 172.31.14.1
#ping                   = 172.26.1.255
#interface              = eth0
#interface              = wlan0
# 監控檔案是否可以正常存取

#file                   = /var/log/messages
#change                 = 1407

# Uncomment to enable test. Setting one of these values to '0' disables it.
# These values will hopefully never reboot your machine during normal use
# (if your machine is really hung, the loadavg will go much higher than 25)
max-load-1              = 24
max-load-5              = 18
max-load-15             = 12


# Note that this is the number of pages!
# To get the real size, check how large the pagesize is on your machine.
# 查看自己系統的 page size
# getconf PAGESIZE (4096)

#
#min-memory             = 1 (一張 page 的大小就是 4096 bytes)
#allocatable-memory     = 1

#repair-binary          = /usr/sbin/repair
#repair-timeout         =
#test-binary            =
#test-timeout           =

watchdog-device = /dev/watchdog

# Defaults compiled into the binary

// 檢查 CPU 溫度  (單位: 攝氏千分之一度)
// cat /sys/class/thermal/thermal_zone0/temp     (35780)
#temperature-device     =  /sys/class/thermal/thermal_zone0/temp
#max-temperature        = 120

#max-temperature        = 80000
# Defaults compiled into the binary
#admin                  = root
admin                   = lanlixxxx@gmail.com
#interval               = 1
#logtick                = 1
#log-dir                = /var/log/watchdog

# This greatly decreases the chance that watchdog won't be scheduled before
# your machine is really loaded
realtime                = yes
priority                = 1

# Check if rsyslogd is still running by enabling the following line
#pidfile                = /var/run/rsyslogd.pid

-----------------------------------------------------------------------------------------------

D. 調整: (for 新版 Pi OS: 2016-02-09-raspbian-jessie; still may not work)
     $ sudo nano /lib/systemd/system/watchdog.service
[Unit]
Description=watchdog daemon
Conflicts=wd_keepalive.service
After=multi-user.target
OnFailure=wd_keepalive.service

[Service]
Type=forking
EnvironmentFile=/etc/default/watchdog
ExecStartPre=/bin/sh -c '[ -z "${watchdog_module}" ] || [ "${watchdog_module}" = "none" ] || /sbin/modprobe $watchdog_module
ExecStart=/bin/sh -c '[ $run_watchdog != 1 ] || exec /usr/sbin/watchdog $watchdog_options'
ExecStopPost=/bin/sh -c '[ $run_wd_keepalive != 1 ] || false'

[Install]

WantedBy=multi-user.target

$ systemctl enable watchdog

-----------------------------------------------------------------------------------------------

E. 啟動看門狗
    1. 立即啟動 watchdog 常駐程式
        $ sudo service watchdog start

    2. 開機時自動啟動 watchdog
        $ sudo update-rc.d watchdog defaults

    3. 檢查
        $ ps aux | grep watchdog
root       786  0.0  0.3   1888  1760 ?        SLs  14:34   0:00 /usr/sbin/watchdog
pi         822  0.0  0.3   4276  1956 pts/0    S+   14:36   0:00 grep --color=auto watchdog


    4. 測試       
        kill 掉 watchdog 本身, 會重新開機
        $ sudo kill -9 786