Home alarm on Rpi + PiFace Digital


Features:
-video stream from usb cameras
-motion detection and automatic image recording
-control via web browser
-input with delay (front door)
-tamper line input
-sends a email message of alarm activity
-after rebooting the system is set to the last state of alarm
-login any activity alarm 

We will need a few useful programs:
$ sudo apt-get install monit
$ sudo apt-get install screen
$ sudo apt-get install chkconfig

Install Motion for cameras:
$ sudo apt-get install motion
$ sudo chmod 777 /etc/motion/motion.conf
$ sudo mkdir /home/pi/ftp
$ sudo chmod 777 /home/pi/ftp
$ sudo mkdir /home/pi/ftp/cam1
$ sudo chmod 777 /home/pi/ftp/cam1
$ sudo mkdir /home/pi/ftp/cam2
$ sudo chmod 777 /home/pi/ftp/cam2

We need an additional programs:
$ wget http://www.lavrsen.dk/foswiki/pub/Motion/MjpegProxyGrab/mjpeg-proxygrab-1.2.tar.gz
$ tar xvzf mjpeg-proxygrab-1.2.tar.gz
$ cd mjpeg-proxygrab-1.2

We must edit files nph-mjgrab.c and nph-mjprox.c:
$ sudo nano nph-mjgrab.c
char chbuffer[40000] = ""; -> char chbuffer[100000] = "";

/*  User defined parameters - EDIT HERE */
#define IPADDR "127.0.0.1" /* IP address of motion server, 127.0.0.1 = localhost */
#define PORTBASE 8080      /* If your camera 1 is on port 8081 set this to one lower = 8080 */
#define UPPERCAMERANUMBER 2  /* Set this to your upper limit of cameras */

$ sudo nano nph-mjprox.c
/*  User defined parameters - EDIT HERE */
#define IPADDR "127.0.0.1" /* IP address of motion server, 127.0.0.1 = localhost */
#define PORTBASE 8080      /* If your camera 1 is on port 8081 set this to one lower = 8080 */
#define UPPERCAMERANUMBER 2  /* Set this to your upper limit of cameras */

compile and install:
$ make
$ sudo make install

Install Python 3.5.2 (pyenv) with PiFace Digital:
$ git clone https://github.com/yyuu/pyenv.git ~/.pyenv
$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.profile
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.profile
$ echo 'eval "$(pyenv init -)"' >> ~/.profile

Note: the next command (installation of Python) takes a long time!
$ pyenv install 3.5.2
we should see:
Installing Python-3.5.2...
and then type:
$ pyenv global 3.5.2
$ pip install --update pip
$ pip install pifacedigitalio
$ pip install pifacecommon

It is good to once every few days to restart the system, and once a day, you can execute the command:
sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"

We can, of course, write the script run from Cron:
$ sudo mkdir /usr/local/bin/myservice
$ sudo nano /usr/local/bin/myservice/freemem.sh
#!/bin/sh
sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"

we set the permissions:
$ chmod 755 freemem.sh

we must edit crontab:
$ sudo nano /etc/crontab
10 12   * * 7   root    sudo /sbin/reboot
1 12    * * 1-7 root    /usr/local/bin/myservice/freemem.sh

Description of electrical connections PiFace Digital:
Output 0 - external siren.
Output 1 - internal siren for tamper line.
Output 2 - logical "1" = alarm is disarm,  logical "0" = alarm is arm.
Input 0 - delayed line.
Input 1 - line without delay.
Input  2 - arm.
Input 3 - disarm.
Input 5 - tamper line input.
Input 6 - arm status (arm/disarm).
Input 7 - alarm status (active/inactive).

Connect in_5 to siren relay, use shottky diode BYV10-40 in5--|>|--relay / observe polarity!
Connect in_6 to out_2, use shottky diode BYV10-40 in6--|>|--out2 / observe polarity!
Connect in_7 to out_0, use shottky diode BYV10-40 in7--|>|--out0 / observe polarity!
Power for the siren connected via the relay control siren. The mass of the siren to the mass of the system.

Alarm script in python:
Note: If you copy the code, be sure to swap space at the beginning of the line to the appropriate number of tabs.

$ sudo nano /usr/local/bin/myservice/alarm.py

#!/home/pi/.pyenv/versions/3.5.2/bin/python
#/usr/bin/env python3
# PiFace Digital
# home alarm by fuse
# v.1.3.5
# 25.06.2016
# Python 3
# out 0 - siren
# out 1 - internal siren (sabotage alarm)
# out 2 - logic 1 = disarm alarm, logic 0 = arm alarm
#  in 0 - line A (delayed)
#  in 1 - line B
#  in 2 - arm alarm
#  in 3 - disarm alarm
# connect in_5 to siren relay, use shottky diode BYV10-40 in5--|>|--relay / observe polarity!!!
# connect in_6 to out_2, use shottky diode BYV10-40 in6--|>|--out2 / observe polarity!!!
# connect in_7 to out_0, use shottky diode BYV10-40 in7--|>|--out0 / observe polarity!!!
# in 5 - sabotage siren line input
# in 6 - arm status
# in 7 - alarm status
# http://address:port/?output_port=arm - arm alarm
# http://address:port/?output_port=disarm - disarm alarm
# http://address:port/?output_port=wipe - wipe log file
# http://address:port/?output_port=rst - reboot rpi

import sys
import subprocess
import http.server
import urllib.parse
import urllib.request
import pifacedigitalio as alarm
from threading import Timer
import time
import logging
import logging.handlers
import argparse
import smtplib
from email.mime.text import MIMEText

msg_email = 'main_email@gmail.com'
msg_pwd = 'password'
msg = MIMEText('Alarm email system.')
msg['From'] = msg_email
msg['To'] = msg_email
msg['Subject'] = 'Alarm - START'

try:
    server = smtplib.SMTP('smtp.gmail.com', 587)
#    server.ehlo()
    server.starttls()
    server.login(msg_email, msg_pwd)
    server.sendmail(msg_email, msg_email, msg.as_string())
    server.quit()
except:
    print ('failed to send mail')

try:
    logging.basicConfig(filename='/var/www/alarmlog.log', format='%(asctime)s %(message)s', datefmt='%y/%m/%d %H:%M:%S', level=logging.INFO)
except:
    logging.basicConfig(filename='/var/tmp/alarmlog.log', format='%(asctime)s %(message)s', datefmt='%y/%m/%d %H:%M:%S', level=logging.INFO)

# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
username_motion = 'user'
password_motion = 'password'
# Add the username and password.
# If we knew the realm, we could use it instead of None.
motion_url = 'http://address:8080/'
pause1_url = 'http://address:8080/1/detection/pause'
start1_url = 'http://address8080/1/detection/start'
pause2_url = 'http://address:8080/2/detection/pause'
start2_url = 'http://address:8080/2/detection/start'
password_mgr.add_password(None, motion_url, username_motion, password_motion)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL
#opener.open(pause2_url)

# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
#urllib.request.install_opener(opener)

alarm.init()

JSON_FORMAT = "[{{\"Arm\":\"{input6}\",\"Alarm\":\"{input7}\",\"Siren\":\"{output0}\"}}]"
#JSON_FORMAT = "{{\"I\":[{input7},{input6},{input5},{input4},{input3},{input2},{input1},{input0}], \"O\":[{output7},{output6},{output5},{output4},{output3},{output2},{output1},{output0}]}}"
DEFAULT_PORT = 8000
OUTPUT_PORT_GET_STRING = "output_port"
GET_IP_CMD = "hostname -I"

# Deafults
LOG_FILENAME = "/var/www/alarmpy.log"
LOG_LEVEL = logging.ERROR # Could be e.g. "DEBUG" or "WARNING"

# Define and parse command line arguments
parser = argparse.ArgumentParser(description="Python alarm service")
parser.add_argument("-l", "--log", help="file to write log to (default '" + LOG_FILENAME + "')")

# If the log file is specified on the command line then override the default
args = parser.parse_args()
if args.log:
    LOG_FILENAME = args.log

# Configure logging to log to a file, making a new file at midnight and keeping the last 3 day's data
# Give the logger a unique name (good practice)
logger = logging.getLogger(__name__)
# Set the log level to LOG_LEVEL
logger.setLevel(LOG_LEVEL)
# Make a handler that writes to a file, making a new file at midnight and keeping 3 backups
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when="midnight", backupCount=3)
# Format each log message like this
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
# Attach the formatter to the handler
handler.setFormatter(formatter)
# Attach the handler to the logger
logger.addHandler(handler)

# Make a class we can use to capture stdout and sterr in the log
class MyLogger(object):
    def __init__(self, logger, level):
        """Needs a logger and a logger level."""
        self.logger = logger
        self.level = level

    def write(self, message):
        # Only log if there is a message (not just a new line)
        if message.rstrip() != "":
            self.logger.log(self.level, message.rstrip())
    def flush(self):
        pass
# Replace stdout with logging to file at INFO level
sys.stdout = MyLogger(logger, logging.INFO)
# Replace stderr with logging to file at ERROR level
sys.stderr = MyLogger(logger, logging.ERROR)

class PiFaceWebHandler(http.server.BaseHTTPRequestHandler):
    # main class to present webpages and authentication
    def log_message(self, format, *args):
        pass
    def do_HEAD(self):
        #print ("send header")
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_AUTHHEAD(self):
        #print ("send header")
        self.send_response(401)
        self.send_header('WWW-Authenticate', 'Basic realm=\"Alarm\"')
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    # handles PiFace web control requests
    def do_GET(self):
        # present frontpage with user authentication
        if self.headers['Authorization'] == None:
            self.do_AUTHHEAD()
            self.wfile.write(bytes('no auth header received', 'UTF-8'))
        elif self.headers['Authorization'] == 'Basic xyz': # xyz = user:password encode in base64
            output_value = self.pifacedigital.output_port.value
            input_value = self.pifacedigital.input_port.value
            # parse the query string
            qs = urllib.parse.urlparse(self.path).query
            query_components = urllib.parse.parse_qs(qs)
            # set the output
            if OUTPUT_PORT_GET_STRING in query_components:
                new_output_value = output_value
                if query_components["output_port"][0] == "arm":
                    new_output_value = 4
                    opener.open(start1_url)
                    opener.open(start2_url)
                    logging.info ('Alarm:arm-www.')
                    try:
                        f1 = open('/var/log/alarmstatus.txt','w')
                        f1.write('1')
                        f1.close()
                    except:
                        logging.info ('Alarm:err_write_status_1')
                elif query_components["output_port"][0] == "disarm":
                    new_output_value = 0
                    opener.open(pause1_url)
                    opener.open(pause2_url)
                    logging.info ('Alarm:disarm-www.')
                    try:
                        f1 = open('/var/log/alarmstatus.txt','w')
                        f1.write('0')
                        f1.close()
                    except:
                        logging.info ('Alarm:err_write_status_0.')
                    try:
                        f2 = open('/var/log/alarmactive.txt','w')
                        f2.write('0')
                        f2.close()
                    except:
                        logging.info ('Alarm:err_write_active_0')
                elif query_components["output_port"][0] == "wipe":
                    try:
                        open("/var/www/alarmlog.log","w").close()
                    except:
                        logging.info ('Alarm:wipe_error.')
                elif query_components["output_port"][0] == "rst":
                    try:
                        logging.info ('Alarm:reboot_now')
                        command = "/usr/bin/sudo /sbin/reboot"
                        process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
                        output = process.communicate()[0]
                        print (output)
                    except:
                        logging.info ('Alarm:restart_error.')
                else:
                    logging.info ('Alarm:unknown_command-www.')
                output_value = self.set_output_port(new_output_value, output_value)
            output_value = self.pifacedigital.output_port.value
            input_value = self.pifacedigital.input_port.value
            output_value0 = output_value & 0b00000001
            if output_value0 != 0:
                output_value0 = 1
            output_value1 = output_value & 0b00000010
            if output_value1 != 0:
                output_value1 = 1
            output_value2 = output_value & 0b00000100
            if output_value2 != 0:
                output_value2 = 1
            output_value3 = output_value & 0b00001000
            if output_value3 != 0:
                output_value3 = 1
            output_value4 = output_value & 0b00010000
            if output_value4 != 0:
                output_value4 = 1
            output_value5 = output_value & 0b00100000
            if output_value5 != 0:
                output_value5 = 1
            output_value6 = output_value & 0b01000000
            if output_value6 != 0:
                output_value6 = 1
            output_value7 = output_value & 0b10000000
            if output_value7 != 0:
                output_value7 = 1
            input_value0 = input_value & 0b00000001
            if input_value0 != 0:
                input_value0 = 1
            input_value1 = input_value & 0b00000010
            if input_value1 != 0:
                input_value1 = 1
            input_value2 = input_value & 0b00000100
            if input_value2 != 0:
                input_value2 = 1
            input_value3 = input_value & 0b00001000
            if input_value3 != 0:
                input_value3 = 1
            input_value4 = input_value & 0b00010000
            if input_value4 != 0:
                input_value4 = 1
            input_value5 = input_value & 0b00100000
            if input_value5 != 0:
                input_value5 = 1
            input_value6 = input_value & 0b01000000
            if input_value6 != 0:
                input_value6 = 1
            input_value7 = input_value & 0b10000000
            if input_value7 != 0:
                input_value7 = 1
            # reply with JSON
            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            self.wfile.write(bytes(JSON_FORMAT.format(
                input0=input_value0,
                input1=input_value1,
                input2=input_value2,
                input3=input_value3,
                input4=input_value4,
                input5=input_value5,
                input6=input_value6,
                input7=input_value7,
                output0=output_value0,
                output1=output_value1,
                output2=output_value2,
                output3=output_value3,
                output4=output_value4,
                output5=output_value5,
                output6=output_value6,
                output7=output_value7,
            ), 'UTF-8'))
        else:
            self.do_AUTHHEAD()
            self.wfile.write(bytes('not authenticated', 'UTF-8'))

    def set_output_port(self, new_value, old_value=0):
        # sets the output port value to new_value, defaults to old_value
        #print("Setting output port to {}.".format(new_value))
        port_value = old_value
        try:
            port_value = int(new_value)  # dec
        except ValueError:
            port_value = int(new_value, 16)  # hex
        finally:
            self.pifacedigital.output_port.value = port_value
            return port_value

def get_my_ip():
    # returns this computers IP address as a string
    ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1]
    return ip.strip()

def turn_on_alarm_a(event):
    try:
        if alarm.digital_read(6):
            if not alarm.digital_read(7):
                logging.info ('Alarm:delay_on-A.')
                ta_delay = Timer(10.0, delay_line_a) # set the length of delay for line A
                ta_delay.start()
            else:
                logging.info ('Alarm:already_on-A.')
    except:
        logging.info ('Alarm:turn_on_alarm_a_error.')

def turn_on_alarm_b(event):
    try:
        if alarm.digital_read(6):
            if not alarm.digital_read(7):
                event.chip.leds[0].turn_on()
                logging.info ('Alarm:on-B.')
                tb = Timer(60.0, turn_off_alarm_auto_timer) # set the length of alarm for line B
                tb.start()
            else:
                logging.info ('Alarm:already_on-B.')
            try:
                send_mail_event()                   
                f2ab = open('/var/log/alarmactive.txt','w')
                f2ab.write('1')
                f2ab.close()
            except:
                logging.info ('Alarm:err_write_active_1')
    except:
        logging.info ('Alarm:turn_on_alarm_b_error.')

def disarm_alarm(event):
    try:
        if alarm.digital_read(5):
            event.chip.leds[1].turn_off()
            logging.info ('Alarm:ok-S.')
        else:
            logging.info ('Alarm:on-S.')
        if alarm.digital_read(6):
            event.chip.leds[0].turn_off()
            event.chip.leds[2].turn_off()
            logging.info ('Alarm:disarm.')
            opener.open(pause1_url)
            opener.open(pause2_url)
            try:
                f1a = open('/var/log/alarmstatus.txt','w')
                f1a.write('0')
                f1a.close()
            except:
                logging.info ('Alarm:err_write_status_0.')
            try:                   
                f2a = open('/var/log/alarmactive.txt','w')
                f2a.write('0')
                f2a.close()
            except:
                logging.info ('Alarm:err_write_active_0')
        else:
            logging.info ('Alarm:already_disarm.')
            try:                   
                f2a = open('/var/log/alarmactive.txt','w')
                f2a.write('0')
                f2a.close()
            except:
                logging.info ('Alarm:err_write_active_0')
    except:
        logging.info ('Alarm:disarm_error.')

def arm_alarm(event):
    try:
        if not alarm.digital_read(6):
            logging.info ('Alarm:will_be_arm.')
            time.sleep(1)            # set the delay time
            event.chip.leds[0].turn_off()
            event.chip.leds[2].turn_on()
            logging.info ('Alarm:arm.')
            opener.open(start1_url)
            opener.open(start2_url)
            try:
                f1a = open('/var/log/alarmstatus.txt','w')
                f1a.write('1')
                f1a.close()
            except:
                logging.info ('Alarm:err_write_status_1.')
        else:
            logging.info ('Alarm:already_arm.')
    except:
        logging.info ('Alarm:arm_error.')       

def delay_line_a():
    try:
        if alarm.digital_read(6):
            pifacedigital.leds[0].turn_on()
            logging.info ('Alarm:on-A.')
            ta = Timer(60.0, turn_off_alarm_auto_timer) # set the length of alarm for line A
            ta.start()
        try:
            send_mail_event()                   
            f2aa = open('/var/log/alarmactive.txt','w')
            f2aa.write('1')
            f2aa.close()
        except:
            logging.info ('Alarm:err_write_active_1')

    except:
        logging.info ('Alarm:delay_line_a_error.')

def turn_off_alarm_auto_timer():
    try:
        if alarm.digital_read(7):
            pifacedigital.leds[0].turn_off()
            logging.info ('Alarm:autotimer_off.')
    except:
        logging.info ('Alarm:turn_off_alarm_auto_timer_error.')

def sabotage_line(event):
    try:
        if not alarm.digital_read(7):
            if not alarm.digital_read(5):
                event.chip.leds[1].turn_on()
                logging.info ('Alarm:on-S.')
    except:
        logging.info ('Alarm:sabotage_line_error.')

def send_mail_event():
    msg = MIMEText('Alarm email system.')
    msg['From'] = msg_email
    msg['To'] = msg_email
    msg['Subject'] = 'Alarm - ACTIVE'
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
#        server.ehlo()
        server.starttls()
        server.login(msg_email, msg_pwd)
        server.sendmail(msg_email, msg_email, msg.as_string())
        server.quit()
    except:
        print ('failed to send mail')

if __name__ == "__main__":
    # get the port
    if len(sys.argv) > 1:
        port = int(sys.argv[1])
    else:
        port = DEFAULT_PORT

    # set up PiFace Digital
    PiFaceWebHandler.pifacedigital = alarm.PiFaceDigital()

    logging.info ("Starting PiFace alarm at: http://{addr}:{port}"
        .format(addr=get_my_ip(), port=port))

    # run the server
    server_address = ('', port)   
    pifacedigital = alarm.PiFaceDigital()
    listener = alarm.InputEventListener(chip=pifacedigital)
    listener.register(0, alarm.IODIR_RISING_EDGE, turn_on_alarm_a)
    # _RISING_ for reverse logic, _FALLING_ for normal logic
    listener.register(1, alarm.IODIR_RISING_EDGE, turn_on_alarm_b)
    # _RISING_ for reverse logic, _FALLING_ for normal logic
    listener.register(5, alarm.IODIR_RISING_EDGE, sabotage_line)
    listener.register(2, alarm.IODIR_FALLING_EDGE, arm_alarm)
    listener.register(3, alarm.IODIR_FALLING_EDGE, disarm_alarm)
    listener.activate()

    try:
        f = open('/var/log/alarmstatus.txt','r')
        status = f.read(1)
        if status == "1":
            try:
                pifacedigital.output_port.value = 0x04
                logging.info ('Alarm:arm_at_boot')
                opener.open(start1_url)
                opener.open(start2_url)
            except:
                logging.info ('Alarm:arm_error_at_boot')
        else:
            try:
                pifacedigital.output_port.value = 0x00
                logging.info ('Alarm:disarm_at_boot')
                opener.open(pause1_url)
                opener.open(pause2_url)
            except:
                logging.info ('Alarm:disarm_error_at_boot')
    except:
        logging.info ('Alarm:unknow_status_at_boot.')

    try:
        httpd = http.server.HTTPServer(server_address, PiFaceWebHandler)
        httpd.serve_forever()
    except KeyboardInterrupt:
        logging.info ('^C received, shutting down server')
        httpd.socket.close()

we set the permissions:
$ chmod 755 alarm.py

We create a script to run alarm as a process  and configure the program Monit:
$ sudo nano /etc/init.d/alarm.sh
#!/bin/sh

### BEGIN INIT INFO
# Provides:          myservice
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Put a short description of the service here
# Description:       Put a long description of the service here
### END INIT INFO

# Change the next 3 lines to suit where you install your script and what you want to call it
DIR=/usr/local/bin/myservice
DAEMON=$DIR/alarm.py
DAEMON_NAME=alarm

# Add any command line options for your daemon here
DAEMON_OPTS=""

# This next line determines what user the script runs as.
# Root generally not recommended but necessary if you are using the Raspberry Pi GPIO from Python.
DAEMON_USER=root

# The process ID of the script when it runs is stored here:
PIDFILE=/var/run/$DAEMON_NAME.pid

. /lib/lsb/init-functions

do_start () {
    log_daemon_msg "Starting system $DAEMON_NAME daemon"
    start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS
    log_end_msg $?
}
do_stop () {
    log_daemon_msg "Stopping system $DAEMON_NAME daemon"
    start-stop-daemon --stop --pidfile $PIDFILE --retry 10
    log_end_msg $?
}

case "$1" in

    start|stop)
        do_${1}
        ;;

    restart|reload|force-reload)
        do_stop
        do_start
        ;;

    status)
        status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
        ;;
    *)
        echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
        exit 1
        ;;

esac
exit 0

we set the permissions:
$ chmod 755 alarm.sh
$ sudo update-rc.d alarm.sh defaults

config Monit:
$ sudo nano /etc/monit/conf.d/alarm
check process alarm with pidfile /var/run/alarm.pid
start program = "/etc/init.d/alarm.sh start"
stop program = "/etc/init.d/alarm.sh stop"

and run Monit:
$ chkconfig monit on
$ sudo service monit start

Web pages - all files must be in the /var/www:

index.html:
<html>
<head>
</head>
<body>
<body style="width:576px">
<iframe src="cam.html" name="camera" width="576px" height="352px" frameBorder="0" marginwidth="0" marginheight="0">
  <p>Your browser does not support iframes.</p>
</iframe>
<br>
<iframe src="status.html" name="status" width="576px" height="100px" frameBorder="0" marginwidth="0" marginheight="0">
  <p>Your browser does not support iframes.</p>
</iframe>
<br>
<iframe src="" name="empty" style="display:none;"></iframe>
<iframe src="" name="empty1" style="display:none;"></iframe>
<iframe src="" name="empty2" style="display:none;"></iframe>
<iframe src="" name="empty3" style="display:none;"></iframe>
<iframe src="" name="empty4" style="display:none;"></iframe>
<iframe src="" name="empty5" style="display:none;"></iframe>
<iframe src="" name="empty6" style="display:none;"></iframe>
<form action="http://address:8000" method="get" target="empty">
<div>
<input type="submit" name="output_port" value="disarm" style="height:50; width:165; font-weight:bold;">
<input type="submit" name="output_port" value="arm" style="height:50; width:165; font-weight:bold;">
<a href="alarmlog.log" target="_blank"><input type="button" value="log" style="height:50; width:53; font-weight:bold;"></a>
<input type="submit" name="output_port" value="wipe" style="height:50; width:52; font-weight:bold;">
<input type="submit" name="output_port" value="rst" style="height:50; width:52; font-weight:bold;">

</div>
<div>
<a href="http://address:8080/1/detection/start" target="empty1"><input type="button" value="start cam1" style="height:50; width:165; font-weight:bold;"></a>
<a href="http://address:8080/1/detection/pause" target="empty2"><input type="button" value="pause cam1" style="height:50; width:165; font-weight:bold;"></a>
<a href="http://address:8080/1/action/snapshot" target="empty3"><input type="button" value="snapshot cam1" style="height:50; width:165; font-weight:bold;"></a>
</div>
<div>
<a href="http://address:8080/2/detection/start" target="empty4"><input type="button" value="start cam2" style="height:50; width:165; font-weight:bold;"></a>
<a href="http://address:8080/2/detection/pause" target="empty5"><input type="button" value="pause cam2" style="height:50; width:165; font-weight:bold;"></a>
<a href="http://address:8080/2/action/snapshot" target="empty6"><input type="button" value="snapshot cam2" style="height:50; width:165; font-weight:bold;"></a>
</div>
</form>
</body>
</html>

cam.html:
<html>
<head>
<meta http-equiv="refresh" content="2" >
</head>
<body>
<body style="width:576px">
<a href="cam1.php" target="_blank"><IMG src="cam1.php"></a><a href="cam2.php" target="_blank"><IMG src="cam2.php"></a>
</body>
</html>

cam1.php:
<?
$camurl = "http://127.0.0.1:8081/";
$boundary = "\n--";
$r="";
$fpr = "";
$fp = fopen($camurl, "r");
$start_jpg = 0xFFD8;
$counter = 0;
  if(!$fp)
  {
    //**** cannot open
    echo "error";
  }
   else
  {
    //**** URL OK
    while ($counter != 2)
    {
      if (substr_count($r,"Content-Length") == 1)
      {
        $counter ++;
      }
      $r = fread($fp,512);
      $fpr = $fpr.$r;
    }
  $start = strpos($fpr,$start_jpg)-1;
  $end   = strpos($fpr,$boundary,$start);
  $frame = substr("$fpr",$start,$end - $start);
  header("Content-type: image/jpeg");
  echo $frame;
  }
fclose($fp);
?>

cam2.php:
<?
$camurl = "http://127.0.0.1:8082/";
$boundary = "\n--";
$r = "";
$fpr = "";
$fp = fopen($camurl, "r");
$start_jpg = 0xFFD8;
$counter = 0;
   if(!$fp)
   {
     //**** cannot open
     echo "error";
     }
      else
     {
     //**** URL OK
     while ($counter != 2)
   {
        if (substr_count($r,"Content-Length") == 1)
        {
            $counter ++;
        }
        $r = fread($fp,512);
        $fpr = $fpr.$r;
    }
   $start = strpos($fpr,$start_jpg)-1;
   $end   = strpos($fpr,$boundary,$start);
   $frame = substr("$fpr",$start,$end - $start);
   header("Content-type: image/jpeg");
   echo $frame;
    }
fclose($fp);
?>

status.html:
<html>
<head>
<meta http-equiv="refresh" content="2" >
</head>
<body>
<body style="width:576px">
<iframe src="http://address:8080/1/detection/status" name="cam1" width="576px" height="25px" frameBorder="0">
 <p>Your browser does not support iframes.</p>
</iframe>
<br>
<iframe src="http://address:8080/2/detection/status" name="cam2" width="576px" height="25px" frameBorder="0">
</iframe>
<br>
<iframe src="lastactive.php" name="lastactive" width="576px" height="25px" frameBorder="0">
  <p>Your browser does not support iframes.</p>
</iframe>
<iframe src="http://address:8000" name="status" width="576px" height="25px" frameBorder="0">
  <p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>

lastactive.php:
<?php
$handle = fopen("/var/log/alarmactive.txt", "r");
if (FALSE === $handle) {
    exit("Failed to open active status");
}

$contents = '';

while (!feof($handle)) {
    $contents .= fread($handle, 1);
}
fclose($handle);
echo "<font size='3' face='sans-serif'>";
echo "Alarm was activated: ";
echo $contents;
echo "</font>";
?>

Comments

Popular Posts