Sei sulla pagina 1di 63

Smart Surveillance System for Parked Cars (3SPC)

Submitted By
Sagar Kumar & Marsha Nawal

Supervisor: Dr. Abdul Rehman Gilal

DEPARTMENT OF COMPUTER SCIENCE


SUKKUR IBA UNIVERSITY

2019
Smart Surveillance System for Parked Cars
By
Sagar Kumar and Marsha Nawal

SUBMITTED TO THE DEPARTMENT OF COMPUTER


SCIENCE IN PARTIAL FULFILLMENT OF THE
REQUIREMENTS FOR THE DEGREE OF

BACHELOR OF SCIENCE IN COMPUTERR SCIENCE

SUKKUR IBA UNIVERSITY

February 2019

© 2013 Sagar Kumar and Marsha Nawal. All


rights reserved.

The author hereby grants permission to Sukkur IBA to


reproduce and distribute publicly paper and electronic
copies of this thesis and grant others the right to do so.

Signature of Author

Sagar Kumar and Marsha Nawal


Department of Computer Science

Certified by:

Internal Examiner Signature

Dr. Abdul Rehman Gilal


Designation
Thesis Supervisor

External Examiner Signature


Dr Tariq Mahmood
Associate Professor,
PAF-KIET, Karachi.

Accepted by:
Dr. Ahmed Waqas
Head,
Department of Computer Science
EXORDIUM

First of all, we would like to thanks Allah Almighty for giving us this opportunity to
complete this project and thesis. We are indebted to many people for their help and
guidance throughout this project.

We would like to give bundle of thanks to our beloved supervisor, Dr. Abdul
Rehman Gilal who has always supported us with ideas, suggestions and identifying
problems and their subsequent solutions.

Sagar Kumar, Marsha Nawal

Feburary 10, 2019

iii
DEDICATION

We are especially thankful to our parents whose prayers, love and support have
always been a constant source of strength for us. We also thankful to our teachers,
who gave the knowledge, support and inspire us in all aspects.

iv
Table of Contents
EXORDIUM ........................................................................................................................................... iii
DEDICATION ........................................................................................................................................ iv
LIST OF FIGURES ............................................................................................................................... viii
LIST OF TABLES .................................................................................................................................. ix
ACRONYMS AND ABBRIVIATIONS .................................................................................................. x
ABSTRACT ............................................................................................................................................ xi
CHAPTER 1............................................................................................................................................. 1
INTRODUCTION .................................................................................................................................... 1
1.1. Overview ..................................................................................................................................... 1
1.2. Background ................................................................................................................................. 1
1.3. Introduction ................................................................................................................................. 1
1.4. Problem Statement ...................................................................................................................... 2
1.5. Research Question ....................................................................................................................... 2
1.6. Scope Of FYP Report .................................................................................................................. 2
1.7. Chapter Summary........................................................................................................................ 3
CHAPTER 2............................................................................................................................................. 4
METHODOLOGY ................................................................................................................................... 4
2.1. Overview ..................................................................................................................................... 4
2.2. Study Design ............................................................................................................................... 4
2.1.1. Product Design Phases ............................................................................................................ 4
2.3. Agile Methodology ..................................................................................................................... 4
2.3.1. Design ..................................................................................................................................... 5
2.3.1.2 Tools and Techniques ......................................................................................................... 5
2.3.1.3 Procedure ............................................................................................................................ 5
2.3.2. Development ........................................................................................................................... 5
2.3.2.1. Prototype Development ...................................................................................................... 5
2.3.2.2. Mobile Application ............................................................................................................. 6
2.3.2.3 Language/Editor ................................................................................................................. 7
2.3.3. Testing/ Inspection .................................................................................................................. 7
2.3.4.1. Functional Testing Types ................................................................................................... 7
2.3.4.2. Unit Testing ........................................................................................................................ 7
2.3.4.3. Integration Testing.............................................................................................................. 7
2.3.4.4. System Testing ................................................................................................................... 7
2.3.4.5. Interface Testing ................................................................................................................. 8
2.3.4.1. Non-Functional Testing Types ........................................................................................... 8
2.3.4.2. Performance Testing ........................................................................................................... 8
2.3.4.3. Security Testing .................................................................................................................. 8
2.3.4.4. Compatibility Testing ......................................................................................................... 8
2.4. Chapter Summary........................................................................................................................ 8
CHAPTER 3........................................................................................................................................... 10
SOFTWARE REQUIREMENT SPECIFICATIONS (SRS) .................................................................. 10

v
3.1. Introduction ............................................................................................................................... 10
3.1.1. Purpose ................................................................................................................................. 10
3.1.2. Document Conventions ......................................................................................................... 10
3.1.3. Intended Audience and Reading Suggestions ....................................................................... 10
3.1.4. Product Scope ....................................................................................................................... 10
3.1.5. References............................................................................................................................. 10
3.2. Overall System Description/Functional Requirements ............................................................. 11
3.2.1. Prototype Perspective ........................................................................................................... 11
3.2.2. Prototype Functions .............................................................................................................. 11
3.2.3. Application Functions ........................................................................................................... 12
3.2.4. User Classes and Characteristics........................................................................................... 12
3.2.5. Operating Environment ......................................................................................................... 12
3.2.6. Design and Implementation Constraints ............................................................................... 12
3.2.7. Assumptions and Dependencies............................................................................................ 12
3.3. External Interface Requirements ............................................................................................... 13
3.3.1. Hardware Interfaces .............................................................................................................. 13
3.3.2. Software Interfaces ............................................................................................................... 13
3.3.3. Communications Interfaces .................................................................................................. 13
3.4. Prototype Features ..................................................................................................................... 13
3.4.1. Identifying an object ............................................................................................................. 13
3.4.2. Notification ........................................................................................................................... 13
3.4.3. Record ................................................................................................................................... 13
3.5. Other Non-Functional Requirements ........................................................................................ 14
3.5.1. Performance Requirements ................................................................................................... 14
3.5.2. Security Requirements .......................................................................................................... 14
CHAPTER 4........................................................................................................................................... 15
SYSTEM DESIGN SPECIFICATION (SDS) ....................................................................................... 15
4.1. Purpose Of This Document ....................................................................................................... 15
4.2. Scope Of The Development Project .......................................................................................... 15
4.3. Definitions, And Acronyms ...................................................................................................... 15
4.4. Assumptions .............................................................................................................................. 15
4.5. Constraints ................................................................................................................................ 15
4.6. Architecture ............................................................................................................................... 16
4.7. Overview ................................................................................................................................... 16
4.8. Detailed Software Design .......................................................................................................... 17
4.9. Domain Model .......................................................................................................................... 18
4.10. Use Case Diagrams ................................................................................................................... 19
4.11. Sequence Diagrams ................................................................................................................... 20
4.12. System Sequence Diagram ........................................................................................................ 22
4.13. Activity Diagram ....................................................................................................................... 22
4.16.2 Deployment Diagram ............................................................................................................ 25
CHAPTER 5........................................................................................................................................... 26

vi
RESULTS .............................................................................................................................................. 26
5.1. INTRODUCTION..................................................................................................................... 26
5.2. RESULTS ................................................................................................................................. 26
5.3. Screenshots ................................................................................................................................ 29
CHAPTER 6........................................................................................................................................... 34
CONCLUSION AND FUTURE WORK ............................................................................................... 34
BIBLIOGRAPHY/REFERENCE .......................................................................................................... 35
APPENDIX ............................................................................................................................................ 36
Application Code.................................................................................................................................... 36
Prototype Code ....................................................................................................................................... 46

vii
LIST OF FIGURES

Figure 2.1 Product Design Phases ............................................................................................................ 4


Figure 4.1 Architecture......................................................................................................................... 186
Figure 4.2 Detailed Software Design ................................................................................................... 187
Figure 4.3 Domain Model Diagram……………………………………………………………………18
Figure 4.4 Use Case Model .................................................................... Error! Bookmark not defined.
Figure 4.5 Sequence Diagram for Login ............................................................................................... 20
Figure 4.6 Sequence Diagram for Logut ............................................................................................... 20
Figure 4.7 Sequence Diagram for View Videos ................................... 2Error! Bookmark not defined.
Figure 4.8 Sequence Diagram for Generate Notification ..................... 2Error! Bookmark not defined.
Figure 4.9 System Sequence Diagram................................................................................................... 22
Figure 4.10 Activity Diagram for Login ............................................................................................... 22
Figure 4.11 Activity Diagram for System On/Off ................................................................................. 23
Figure 4.12 Activity Diagram for Logut ............................................................................................... 23
Figure 4.13 Activity Diagram for View Video ...................................................................................... 24
Figure 4.14 Component Diagram .......................................................................................................... 24
Figure 4.15 Deployment Diagram………………………………………………………………………25
Figure 5.1 Connection between application and LAMP server……………………………………...26
Figure 5.2 HttpURLConnection for getting data from web URL……………………………………27
Figure 5.3 Login Page………………………………………………………………………………..28
Figure 5.4 Signup Screen……………………………………………………………………………29
Figure 5.5 Homepage Screen…………………………………………………………………………30
Figure 5.6 Menu Screen………………………………………………………………………………31
Figure 5.7 Videos Screen…………………………………………………………………………..32

viii
LIST OF TABLES

Table 2.1 3SPC Components ................................................................................................................... 5

ix
ACRONYMS AND ABBRIVIATIONS

3SPC: Smart Surveillance System for Parked Cars

FYP: Final Year Project

UML: Unified Modeling Language

OOP: Object Oriented Programming

ERD: Entity Relationship Diagram

DBMS: Database Management System

OS: Operating System

SMS: Short Message Service

API: Application Programming Interface

SMTP: Simple Mail Transfer Protocol

MIME: Multipurpose Internet Mail Extensions

PWM: Pulse Width Modulation

LAMP: Linux Apache MySQL PHP

Hz: Hertz

MP: Mega Pixel

x
ABSTRACT

The industrialization of the world, increase in population, slow paced city


development and mismanagement of the available parking space has resulted in
parking related problems such as bumps, scratches and collisions. The current
unmanaged car parks and transportation facilities have made it difficult to
accommodate the increasing number of vehicles in a proper, convenient manner so it
is necessary to have a secure, intelligent, efficient and reliable system especially in
Pakistan. The determination of producing this smart system is to let someone know
that car in the parking area has been jounced with hefty object. In this domain of
smart technology, we are developing a smart surveillance system that is based on
usage of smart phones, sensors monitoring techniques with a camera which is used as
a sensor to take photos and record video to show the occurrence of an uncertain event
with the parked car. The sensor automatically becomes active when car is hit with
someone or something and user will be notified immediately even if he/she is far from
his/her car. We are proposing a new parking system which will link a car parking
moves directly to the user phones through”Global system for mobile”. By installing
this system, users will be able to monitor their car just a single tap away. In this way,
owner of the car can easily reach to the person who will be responsible in activity.
Thus, the installation of smart surveillance system will be able to reduce monitoring
problems that are arising due to unavailability of reliable, efficient, and modern
parking system.

xi
CHAPTER 1
INTRODUCTION

1.1. Overview

In this chapter, we will describe the project background, problems and scope of
the overall system. The study is being undertaken because to bring the
technological solution and implementation of modern sensory technology in the
system that may reduce the human efforts. Smart Surveillance System for parked
cars (3SPC) is a system with sensory technology which notifies the owner of the
parked car, when his/her car is hit with another object. This study is carried out to
use the resources very efficiently to save the storage capacity and cost of
surveillance systems that are implemented in different places.

1.2. Background

The industrial growth of the world is reflected by the increase in the number of
automobiles on the streets throughout the world, which has caused a lot of parking
related problems. The slow paced city planning has increased the problem even
more. The current unmanaged car parks and transportation facilities have made it
difficult to accommodate the increasing number of vehicles in a proper,
convenient manner so it is necessary to have a secure, intelligent, reliable and
efficient system especially in Pakistan.

Human errors are the major source of traffic accidents, therefore building in-car
technologies for checking the parking lot, avoiding accidents and guidance to the
parking facility is turning out to be an integral area for research. Currently used
parking system is not an efficient one; as the drivers are allowed to park without
any restriction, which cause damage to others cars.

1.3. Introduction

It is very common to have crowds in place like mega shopping malls, and
stadiums during peak periods. In shopping malls, discounts and season sales
offered by merchants can attract thousands of customers of to come during the
sales periods. Most of the customers travel to the shopping malls with their own
vehicles and it is not surprising to see the car parks are always full during this
periods. In addition, sometimes, when a driver parks his car in an uncontrolled
area or a tiny spot, there is a risk that the vehicle gets scratched or damaged
without that the driver gets notified. Therefore, modern parking systems for
meeting driver parking needs are required. Using modern electronic technologies,
smart oriented assistance parking, and wireless connections in the vehicle help
improving the driver parking skills and reduce the risk for car damages.

3SPC is an innovative system which notify the owner of the car, when his/her car
hits with another object. The system will be integrated in to car. This System uses
the automated sensory technology. The 3SPC provide its user a portable
1
accessibility at every place. If an incident occurs the 3SPC generates a
notification and send to user with proof of video of incident that will be
generated by system via email.

A hardware device is integrated in car with sensors (shock, vibration) and mobile
application is installed on the user smart phone, through which he can switch
on/off the System. When an event occurs the 3SPC will turn on the camera and
start recording the current situation and recorded video will be send to the owner
of car using Wi-Fi connection. The SMS alert will be provided by system using
WhatsApp in which user can be notified at runtime when an incident occurs.

1.4. Problem Statement

With the high percentage of vehicle ownership, car monitoring in a parking has
become a confusing situation for a number of people at uncontrolled zone.
Whether at an airport, bus station and shopping centers, problems with parking
are an everyday occurrence. Lack of accessible parking may cause several
accidents while parking in a tiny area. It may causes damage to your vehicle.

1.5. Research Question

Q1: How to develop a Smart Surveillance System for Parked Cars (3SPC)?
Answer: For the development of Smart Surveillance System for Parked Cars
(3SPC) we have surpass three phases that are enlisted below:
1. Designing
2. Development
3. Testing/Validating
In designing phase we had designed the system sketches on paper and then use
some tools to model it. That designed model shows the working of the system.
Then we started the development of project, the development is divided into two
phases:
1. Mobile Application Development
2. Prototype Development
These both above phases are explained in detailed in Chapter 2.
At the last we tested system and then validate from different users such as car
drivers of Sukkur IBA University, students and other officials.

1.6. Scope Of FYP Report

The overall scope of FYP Report is to develop it in to the prototype perspective


and the mobile application perspective that are required in the system
development. Each and every detail required is mentioned in Chapter 2, 3 and 4.
In the Chapter 5 all results are mentioned in the report that will help the reader of
this report to check or calculate the scalability and robustness of system. In the
Appendix chapter, all of the code is mentioned in this report that is used in
prototype and mobile application.

2
1.7. Chapter Summary

The industrialization of the world, increased in population, slow paced city


development and mismanagement of the available parking space has resulted
parking related problems such as bumps, scratches and collisions. The current
unmanaged car parks and transportation facilities have made it difficult to
accommodate the increasing number of vehicles in a proper, convenient manner
so it is necessary to have a secure, intelligent, efficient and reliable system
especially in Pakistan. In this domain, a new parking monitoring system has been
introduced by our team whose purpose is to provide notification to the owner of
the car when his/her car is hit by another object. This system can be controlled by
smart phone. Mobile application has been provided to the owner of car in which
user or owner has been registered himself/herself. So the system can make
decision to send notification to the registered person while an incident occurs.

3
CHAPTER 2
METHODOLOGY

2.1. Overview

In this chapter, we will discuss the design, workflow and methodologies relevant
to the 3SPC. It investigates the approaches, procedures, concepts, theories and
techniques relevant to this project. Some of the questions are briefly explained in
this chapter:
 What methods or life cycle is used while development of system?
 What testing techniques are applied when system has been developed?
 What tools and techniques are used, in designing of the system?

2.2. Study Design

2.1.1. Product Design Phases

Figure 2.1 Product Design Phases

2.3. Agile Methodology

Agile Software Development is an iterative approach to software development


and delivery. We create and schedule our activities and we completely focused
on its phases called sprints. Rapid development dragged us to agile methodology.
 Incremental Delivery
4
 Maintain Simplicity
 Development according to user easiness.

2.3.1. Design

The Project designing is done in UML (Unified Modeling Language)


using Visual Paradigm for UML. Mobile Application Interface is done in
XML. MySQL for designing the relational database. We have designed
and described the main activities of the project in Chapter 4.

2.3.1.2 Tools and Techniques

 Visual Paradigm for UML


 XML for Designing Mobile Application Interface
 LAMP for database schema

2.3.1.3 Procedure

 The Procedure of design we kept simple we started from rough


sketches using pencil, graphite and copy. Then we used a tool like
Visual Paradigm for UML for complete physical and abstract
design. We also used Android Studio for high-fidelity prototype.

2.3.2. Development

The Project development is divided in to two phases


1. Prototype Development
2. Mobile Application Development

2.3.2.1. Prototype Development


In the prototype development, these following components
are used:

Component Component Quantity Range Degree Frequency Covered


Name Model Range/
Degree/
Frequency
Camera Pi camera 5 1 - 30º- - 30º - 160º
MP 160º
Ultrasonic HC-SR04 1 0 -156 inches - - 5 inch
Sensor
Shock Sensor Ky-031 1 - 9 Hz 9 Hz

Servo Motor Servo(PWM) 1 - 0 º-180 40Hz 20º - 145º,


º 40 Hz

Table 2.1 3SPC Components


5
In the development of prototype, these above given
components are used. Each component is programmed
specifically by using object oriented programing approach.
Ultra Sonic Sensor has been integrated in the system whose
minimum range is 0.07 feet, maximum range is 13 feet and
input signal is set to 1 millisecond. Ultrasonic Sensor is
attached with servo motor because ultrasonic sensor send the
input signal on 90 degree straight. For covering the different
angles we use servo motor. The 5.0 MP raspberry pi camera
has been integrated in the system which can cover the range of
30 to 160 degree. Camera will start for 30 seconds when the
ultrasonic sensor sends a signal. After 30 seconds system
checks if the ultrasonic sends the signal according to given
conditions then camera will be continued recording otherwise
the recording will be stop and deleted from system. In other
words camera will be dependent on the ultrasonic sensor.
Shock sensor is also integrated in system that helps for
detecting the vibration when another object hits the car and
then generate the notification to the owner of the car by
sending the email with attachment of video, insert video in
database for keep record and also for mobile application
access for that video, and also notification on whatsApp
through text message.

2.3.2.2. Mobile Application

In the Mobile Application development following


functionalities are done:
1. Signup
Sign up activity will be used for the first time to create the
account of a person that will be the owner of car. Some of
the required information would be given to create an
account (such as username, mobile number, email address,
car model and password etc.). This required information
will help the system to recognize the owner of car and for
sending the notification in future.

2. Login
Login activity or page will be used for the authentication
of user. User may enter the username and password which
was given in the time of registration.

3. Switch On/Off
Switch On/Off activity contains two buttons.
1. On: The On button starts the prototype.
2. Off: The Off button starts the prototype.
Each button performs its functionality independently.

6
4. View Video
This activity shows the list of available videos that are
available in database provided by system or prototype.

2.3.2.3 Language/Editor

 Python 2.7 for Controlling Hardware (Prototype).


 Java to develop an Android Application.

2.3.3. Testing/ Inspection

Testing or Inspection is necessary and most important part of the application


or system development. It is performed to know whether the developed
application and prototype is giving the desirable output at given specified
input. We have performed the following testing techniques.

2.3.4.1. Functional Testing Types

We have performed functional testing by testing each and


every requirement of user that is mandatory in the business
model. All of the requirements are properly satisfied by our
application and prototype. All of the sensors, motors and other
modules such as API are working properly according to given
input. We received the desired output.

2.3.4.2. Unit Testing

We have performed Unit testing in python code and java code


by dividing the code in to small chunks. Each chunk of code
tested individually to check the accuracy and robustness of the
system and application.

2.3.4.3. Integration Testing

After Unit testing, we simply started Integration testing by


combining each chunk of code in modules that we have
divided in Unit testing. Then we check the system behavior
whether its works properly or not with other modules, system
or sub-system.

2.3.4.4. System Testing

When all the other tests done successfully, we simply started


testing by placing a system as whole, the system is performing
the functionality that we have implemented on it, and then
checks that it returns the desired output or not.

7
2.3.4.5. Interface Testing

We have given the application to the different users (Students,


Drivers and Some IBA officials) and ask them to comment
about the user interface.

2.3.4.1. Non-Functional Testing Types

To perform non-functional testing, we tested system behavior,


security and performance of the system. After errors how the
system reacts, and also when the prototype has been hit by
another object then what is the behavior of the system, what
portion of the system work.

2.3.4.2. Performance Testing

We applied performance testing by testing our system by


checking the response time of system such as Ultrasonic
system range and also trigger rate or time, servo motors
angles, impact sensor range and camera timing and system
startup and off from given Mobile Application.

2.3.4.3. Security Testing

We performed security testing while sending the notification


to the registered user or owner. We applied built-in security
algorithm of security provided by python such as encoder
module. We performed security check using validation with
the help of regular expression, taking care about input format
provided by user while registration and login.

2.3.4.4. Compatibility Testing

We check the compatibility of our given android application


by running it over different android supported mobiles. It
works well with the android marshmallow and above
supported versions.

2.4.Chapter Summary

Testing is an important part of the system after system development. It checks


whether the system works well or not in the real time environment. Testing is
divided in to two parts and then its sub-parts:
1. Functional Testing
2. Non Functional Testing
In Functional testing, the system is checked according to the given input and
desired output, we can say that the system is tested by applying black box testing
technique. Each unit of the system is tested individually without checking the
internal code or structure of the system.
8
On the other side, In Non-functional testing, the system is checked according to
its performance reliability and security perspective. What algorithms and libraries
and APIs are implemented on it? Internal structure of the application and system
has been checked precisely and accurately.

9
CHAPTER 3

SOFTWARE REQUIREMENT SPECIFICATIONS (SRS)

3.1. Introduction
3.1.1. Purpose

The purpose of this document is to describe the requirements, scope,


problem, constraints, functional and non-functional requirements, and
also components including hardware and software of 3SPC System.

3.1.2. Document Conventions

Font Times New Roman


Font Size 10 and 12
Heading Font Size 12
Sub heading font size 12
Font color Black
Quoted text “quote”

3.1.3. Intended Audience and Reading Suggestions

The intended audience of this document is the team members, project


supervisor, and university FYP Management Team.

3.1.4. Product Scope

The overall scope of the product is to send the damage notification to


the owner of car when his/her car is hit or damaged by another object.
We are providing the android based mobile application and a prototype
that are work like a real system.

3.1.5. References

 Design of Damage Notification and Guidance of Car Parking


System by IPS by M.Mounusha, S.Anil Vidya Vikas Institute
of Technology, Chevella, R.R Dist, T.S, India published in
September 2014.

 A Survey of Intelligent Car Parking System , by Faheem,


S.A.Mahmud, G.M.Khan, M.Rahman and H.Zafar University
of Engineering and Technology, Peshawar, Pakistan Published
in October 2013.

 Intelligent Parking System for Car Parking Guidance and


Damage Notification, by Sanaa Alfatihi, Soukaina Chihab and

10
Yassine Salih Alj School of Science and Engineering Al
Akhawayn University, Ifrane Morocco Published in 2013

 Car Accident Detection and Notification System Using


Smartphone, by Hamid M.Ali, Zainab S.Alwan Information
Technology, Baghdad University, Iraq published in April 2015.

 Vehicle damage detection and notification system by Ryan


David Duprey, Continental Automotive Systems Inc. in
November 2015
 Automated Accident Detection System by Charles Harlow, Yu
Wang in January 2017
 Kranig, J., E. Minge, and C. Jones. Field Testing of Urban
Vehicle Operations Using Non-Intrusive Technologies. Report
FHWA-PL-97-018. Minnesota Department of Transportation,
St. Paul, Minn., 1997.
 Automated Crash notification: Evaluation of in-vehicle
principal direction of force estimations by Kristopher
D.Kusano, Hampton C.Gabler

3.2. Overall System Description/Functional Requirements


3.2.1. Prototype Perspective

The world is migrating on efficient and smart solutions for larger


scale of problems. People want the use of technology instead of hiring
people to take care of their important things such as their cars. We are
introducing a new system Smart Surveillance System for Parked Cars
(3SPC) that may help owner of the car to recognize who hits his/her
car. By installing this technology, users will be able to monitor their
car just a single tap away. In this way, owner of the car can easily
reach to the person who will be directly involved in activity. Thus,
the installation of smart surveillance technology will be able to reduce
problems that are arising due to unavailability of reliable, efficient,
and modern parking system.

3.2.2. Prototype Functions

The main function that the prototype will perform that are given
below:
1. Prototype can be On/Off remotely by provided mobile application.
2. Prototype can record video of incident smartly if the given
programming conditions are satisfied.
3. Prototype can send email with attachment of video, if an incident
occurs.
4. Prototype can also send whatsApp notification to registered
mobile number, if an incident occurs.

11
3.2.3. Application Functions

The major function that the application will perform that are given
below:
1. Allow user to create an account.
2. Allow authenticate user to login.
3. Allow user to switch on/off the prototype.
4. Allow user to check the incidental videos that the prototype
recorded.

3.2.4. User Classes and Characteristics

The actual user of system is car owner or driver. Other may be


company or stakeholder. User much has experienced to deal with
android phone and can perform the functionality of system such as
login, on/off, video listing, and also logout.

3.2.5. Operating Environment

Following are the operating environment:


1. Raspberry Pi Module
2. Camera
3. Sensors
4. Android Mobile Application

3.2.6. Design and Implementation Constraints

1. System Constraints
i. Software Constraints
 Application can only run on Android Mobile
Phone.
ii. Hardware Constraints
 Just Create Prototype
 Internet Availability
iii. User Constraints
 Project is developed for car owners.

3.2.7. Assumptions and Dependencies

1. Twilio API
i. For Sending Text Messages via WhatsApp.
2. MIME Packages such as SMTP
i. For sending email with attachment using Gmail.
3. Http URL Connection
i. For connecting mobile application with given URL, it
get the required data such user information for login
and the list of videos in JSON format and then convert
into string.

12
3.3. External Interface Requirements

3.3.1. Hardware Interfaces

Following are the hardware interfaces:


1. Raspberry Pi Module: It is used for controlling the overall
system, all programs are running on it in background, such as
sensors, camera, and motors programmed on it.
2. Sensors: We are receiving input from the environment
through the specified sensors that pass their signals to the
raspberry pi module for further processing. We are using
ultrasonic sensors for detecting the nearest object and
triggering camera while object is nearest in range.

3.3.2. Software Interfaces

Following are the software interfaces:


1. Mobile Interface: The surveillance may be stared whenever
user wants it to start by using the controls provided in the
android application. The application will also receive videos
from the surveillance module and store it in a queue. Those
videos can be viewed by the user at will.

3.3.3. Communications Interfaces

The communication is enabled by two mediums:


1. Messaging Service
2. Internet

Note: Both included in the raspberry pi module.

3.4. Prototype Features

3.4.1. Identifying an object

The prototype can identify the object when it come closure to the car
with the help of integrated sensors in it.

3.4.2. Notification

Prototype cam provide damage notification with attachment of video


recorded by system via email and also send text message (SMS) to the
registered mobile number via whatsApp if an object hits the car.

3.4.3. Record

The prototype will start recording if the integrated sensors send signal
and it will send to the user via email as well as on application if an
object hit to the car.

13
3.5. Other Non-Functional Requirements

3.5.1. Performance Requirements

The performance requirement of this system is that the sensors get the
input accurately in small amount of time.

3.5.2. Security Requirements

System must be connected with internet under password connection.


The access of the software is only for car owner or driver.

14
CHAPTER 4

SYSTEM DESIGN SPECIFICATION (SDS)

4.1. Purpose Of This Document

The purpose of this document is to provide a high-level design framework around


which to build our project 3SPC. It also provides a list of requirements against
which to test the final project and determine whether we were able to
successfully implement the system according to design.

4.2. Scope Of The Development Project

The scope of this project is to provide the prototype and Mobile application that
can be installed and run on owner android based smart phone. It can be further
proceed by making the system implemented in the real car.

4.3. Definitions, And Acronyms

SDS – Software Design Specification


3SPC – Smart Surveillance System for Parked Cars
Raspberry Pi – Hardware Component used as a mini computer
API – Application Programming Interface

4.4. Assumptions

A1. It is assumed that the user of application have sufficient knowledge about
smart surveillance system for parked car.

A2. Handheld device is able to get connected to the internet easily.

4.5. Constraints

1. Platform

a. C1. Works well on android operating system handheld device.

2. Operating System

a. C2. Application is compatible with android API level greater than 21.

b. C3. Python 2.7 is used in backend to control hardware system such as


motors, camera, and sensors.

15
4.6.Architecture

Figure 4.1 Architecture

4.7.Overview

1. Actuator: The actuator is responsible for moving the overall components


of the system such as motors, sensors and camera. It will control the
overall system.
2. Raspberry pi: Raspberry pi is a platform or a PC which will be used for
backend programming such as what action will be performed if this thing
occurs etc. Raspberry pi is used as a programming interface and as a
bridge between mobile application and system.

3. Wi-Fi Module: It will provide the internet connectivity to the system.


Actually it is used for sending emails and WhatsApp Message notification
to the registered user of the system.

4. Database: MySQLi will be used to save the data of owner into server, and
it is also used as bridge for accessing video from raspberry pi to user
smart phone.

16
4.8.Detailed Software Design

Figure 4.2 Detailed Software Design

17
4.9.Domain Model

Figure 4.3 3SPC Domain Model Diagram

18
4.10. Use Case Diagrams

Use Case#1 Use Case Diagram of System 4-4

Name System

Actor Owner, System

Pre-Condition Overall system


must be
implemented.
Application
must be installed
on owner’s
smart phone.

Post-Condition N-A

Description This is overall


structure of
System.
Application
contains the data
of owner, video
gallery and also
switches on/off
system. Switch
On/Off
functionality can
start and close
the system from
root. Video
gallery contains
all of the videos
that are recorded
by the system.

Figure 4.4 Use Case Diagram of System

19
4.11. Sequence Diagrams

4.12.1 Sequence Diagram for Login

Figure 4.5 Sequence Diagram for Login

4.12.2 Sequence Diagram for Logout

Figure 4.6 Sequence Diagram for Logout

20
4.12.3 Sequence Diagram for View Videos

Figure 4.7 Sequence Diagram for View Videos

4.12.4 Sequence Diagram for Generate Notification

Figure 4.8 Sequence Diagram for Generate Notification

21
4.12. System Sequence Diagram

Figure 4.9 System Sequence Diagram

4.13. Activity Diagram

4.14.1 Activity Diagram for Login

Figure 4.10 Activity Diagram for Login

22
4.14.2 Activity Diagram for System On/Off

Figure 4.11 Activity Diagram for System On/Off

4.14.3 Activity Diagram for Logout

Figure 4.12 Activity Diagram for Logout

23
4.14.4 Activity Diagram for View Video

Figure 4.13 Activity Diagram for View Video

4.15 Application Architecture Description

4.15.1 Overview of components


The 3SPC is composed of the following components.
 Login
 Server
 Android Application
 Video Gallery
 Camera
 Ultrasonic Sensors
 Vibration Sensors
 Servo Motors 180 degree
4.16 Detailed Description of Components

4.16.1 Component Diagram

Figure 4.14

24
4.16.2 Deployment Diagram

Figure 4.15

25
CHAPTER 5

RESULTS

5.1. INTRODUCTION

The Systems user interface is quite simple and designed under the consideration
of Human Computer Interaction Principles which can be used almost in all
physical condition, the interface will remain same and does not harm user
physically (such as eye-fatigue) or mentally.

5.2. RESULTS

5.2.1. Mobile Application Results

In this section, the working of 3SPC application is shown, in which the


following diagram displays that how application get and send data to the
LAMP server that is install on Raspberry Pi.

Figure: 5.1 1 Connection between application and LAMP server

26
From the above diagram it is shown that the first thing which we require
is the internet for connecting application with the LAMP server. Note
here that we need internet connection for connecting both, application
and 3SPC prototype.

For getting data from LAMP server we have use HttpURLConnection for
reading the data from web URL and get data in JSON format and process
result data String JSON to object JSON.

Figure: 5.2 2 HttpURLConnection for getting data from web URL

For sending data in database we have use PostResponseAsyncTask.

5.2.2. Prototype Results

In this section, we will define the results of the hardware components


that are the part of 3SPC. Each and every component has inspected
individually. It works fine and provide the expected output. Some of
the results are given below:

27
1. We run this system directly by using the python scripts and also
execute the python script using PHP because of connectivity
with mobile phone.
a. Ultrasonic Sensor: Initially ultrasonic sensor was
working with its default range of approximately 13 feet,
frequency is 40 Hz, Trigger input signal is 10µs TTL
Pulse. Sometime it shows the value in negative integers
because when it does not get any object. It will assign
the negative value. To get rid from it we use some logic
in code or program when it does not get any value, so it
will by default 0. And the range we have cover is
maximum 5 inches or 13 cm (for prototype). Now it is
working fine and provide the expected results.
b. Camera: Camera is the most important component of
prototype. It is also controlled by using code. We used
raspberry pi camera with 5 megapixel of resolution.
We put it on the several direction of prototype and got
the expected angles result. When it is implemented
first time system installer should enable the camera
option from configure file, so user can get the desired
results when his/her car will hit by another object.
c. Shock Sensor: After camera the shock sensor is
another most important component in 3SPC, all of the
notification system is dependent on it. It works
properly, but sometimes it create issue while sending
email and text message because of network issue, so it
transfer the data into queue. It may take approximately
45 to 80 seconds to transferring it on queue.

28
5.3. Screenshots

1. Login Screen: This page of our application allow user to login and also
signup if user is new and want to create an account. It checks the valid input
types and text format.

Figure 5.3 Login Page

29
2. Signup Screen: This screen help user to create an account by providing valid
input by user and this information is stored in database when user clicks the
Register button.

Figure 5.4 Signup Screen

30
3. Homepage Screen: This Screen displays the main screen after login in which
user can On/Off the System.

Figure 5.5 Homepage Screen

31
4. Menu Screen: This Menu Screen displays the Menu in which these options
are given:
a. In menu header the image of person would by shown which owner
has been uploaded.
b. In Home icon, Homepage will be show to the user.
c. In system on/off icon, two buttons will be shown which will help user
to on/off the system.
d. In videos icon, List of videos will be show to the user which will be
helpful to user to recognize who hits his car.
e. In Logout icon, User will be in login page.

Figure 5.6 Menu Screen

32
5. Video Screen: This Video Screen shows the list of videos that are recorded
by system while an incident occurs.

Figure 5.7 Video Screen

33
CHAPTER 6

CONCLUSION AND FUTURE WORK

6.1. CONCLUSION

Today, as there are different Surveillance Systems that allow the owner of
vehicle to keep check and balance of their cars like camera’s placed on all four
direction of car and many more.

But still all these systems have loop holes, our system tends to fulfill these loop
holes by using Android application and real-time video streaming mechanism.
This system will provide notification by email and WhatsApp by sending video
as a proof to owner of car. Owner will just need to connect his/her system with
internet. A gallery (keep videos’ of all incident occur) can be viewed by the
owner of car if he/she was unable to check email.

6.2. FUTURE WORK

This system is deployed at Sukkur IBA University. In future, we make complete


automate there is no person involvement. It will be developed into real working
device. Now it is only working for parked cars, but In future we will implement
it on roads too. With its own customized server which will manage it and all
other devices and application. No any person will be required to take care of car.

34
BIBLIOGRAPHY/REFERENCE

 Design of Damage Notification and Guidance of Car Parking System by IPS by


M.Mounusha, S.Anil Vidya Vikas Institute of Technology, Chevella, R.R Dist,
T.S, India published in September 2014.

 A Survey of Intelligent Car Parking System, by Faheem, S.A.Mahmud,


G.M.Khan, M.Rahman and H.Zafar University of Engineering and Technology,
Peshawar, Pakistan Published in October 2013.

 Intelligent Parking System for Car Parking Guidance and Damage Notification, by
Sanaa Alfatihi, Soukaina Chihab and Yassine Salih Alj School of Science and
Engineering Al Akhawayn University, Ifrane Morocco Published in 2013

 Car Accident Detection and Notification System Using Smartphone, by Hamid


M.Ali, Zainab S.Alwan Information Technology, Baghdad University, Iraq
published in April 2015

 Vehicle damage detection and notification system by Ryan David Duprey,


Continental Automotive Systems Inc. in November 2015.

 Automated Accident Detection System by Charles Harlow, Yu Wang in January


2017.

 Kranig, J., E. Minge, and C. Jones. Field Testing of Urban Vehicle Operations
Using Non-Intrusive Technologies. Report FHWA-PL-97-018. Minnesota
Department of Transportation, St. Paul, Minn., 1997.

 Automated Crash notification: Evaluation of in-vehicle principal direction of force


estimations by Kristopher D.Kusano, Hampton C.Gabler.

 Surround surveillance system for mobile body, and mobile body, car, and train
using the same by Kiyoshi Kumata,Toru Shigeta.

35
APPENDIX

Application Code
1. Login:
package com.example.marshanawal.appdesign1;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class LogInPage extends AppCompatActivity {

EditText txtEmail;
EditText txtPassword;
Button btnLogin;
Button btnSignup;
static String[] userEmail;
static String[] userPassword;
static String[] userName;
String getUsername ="";
String emailValue;
String passwordValue;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("LogIn");
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtPassword = (EditText) findViewById(R.id.txtPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnSignup = (Button) findViewById(R.id.btnSignUp);

if(!new PreferenceManager(this).isUserLogout())
{
getUsername = new PreferenceManager(this).getUsername();
StartHomePageActivity(getUsername);
}
}

public void onClickLogin(View view)


36
{
emailValue = txtEmail.getText().toString();
passwordValue = txtPassword.getText().toString();

if(!emailValue.equals("") && !passwordValue.equals(""))


{
getJSON("http://192.168.43.188" + "/getLogInData.php");
}
else
{
Toast.makeText(getApplicationContext(), "Please Fill Email/Password",
Toast.LENGTH_LONG).show();
}
}

public void onClickSignUp(View view)


{
Intent intent = new Intent(this, SignUp.class);
startActivity(intent);
}

public void getJSON(final String urlWebService) {


class GetJSON extends AsyncTask<Void, Void, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
// Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
getDataFromURL(s);
} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
protected String doInBackground(Void... voids) {

try {
URL url = new URL(urlWebService);

HttpURLConnection con = (HttpURLConnection) url.openConnection();


StringBuilder stringBuilder = new StringBuilder();

BufferedReader bufferedReader = new BufferedReader(new


InputStreamReader(con.getInputStream()));

String json;

while ((json = bufferedReader.readLine()) != null) {


stringBuilder.append(json + "\n");
}

return stringBuilder.toString().trim();
} catch (Exception e) {

37
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}

public void getDataFromURL(String json) throws JSONException {


JSONArray jsonArray = new JSONArray(json);
userEmail = new String[jsonArray.length()];
userPassword = new String[jsonArray.length()];
userName = new String[jsonArray.length()];
String name="";
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
userEmail[i] = obj.getString("Receiver_Email");
userPassword[i] = obj.getString("Password");
userName[i] = obj.getString("Owner_Name");
name += userName[i];
}
// Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
VerifyUser(userEmail, userPassword, userName);
}

public void VerifyUser(String[] email, String[] password, String[] username)


{
String emailValue = txtEmail.getText().toString();
String passwordValue = txtPassword.getText().toString();
for(int i=0; i<email.length; i++)
{
if(email[i].equals(emailValue))
{
if (password[i].equals(passwordValue)) {
saveUserData(emailValue, username[i], passwordValue);
// Toast.makeText(this, emailValue+""+passwordValue+""+username[i],
Toast.LENGTH_SHORT).show();
StartHomePageActivity(username[i]);
}
else {
Toast.makeText(this, "Incorrect
Email/Password!",Toast.LENGTH_SHORT).show();
}
}
}
}

public void saveUserData(String email, String username, String password)


{
PreferenceManager prefManager = new PreferenceManager(this);
prefManager.saveStudentLoginData(email, username, password);
}

public void StartHomePageActivity(String username)


{
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("Username",username);
startActivity(intent);

38
}
}
2. Signup
package com.example.marshanawal.appdesign1;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.kosalgeek.asynctask.AsyncResponse;
import com.kosalgeek.asynctask.PostResponseAsyncTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SignUp extends AppCompatActivity implements AsyncResponse{

EditText txtName;
EditText txtPassword;
EditText txtConfirmPassword;
EditText txtEmailReceiver;
EditText txtModelNo;
EditText txtMobileNo;
Button btnRegister;
String nameValue;
String passwordValue;
String confirmPassValue;
String modelNoValue;
String mobileNoValue;
String emailValue;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
setTitle("SignUp");
txtName = (EditText) findViewById(R.id.txtUserName);
txtPassword = (EditText) findViewById(R.id.txtPassword);
txtConfirmPassword = (EditText) findViewById(R.id.txtReTypePassword);
txtMobileNo = (EditText) findViewById(R.id.txtContactNo);
txtEmailReceiver = (EditText) findViewById(R.id.txtEmail);
txtModelNo = (EditText) findViewById(R.id.txtModelNumber);
btnRegister = (Button) findViewById(R.id.btnRegister);

btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
nameValue = txtName.getText().toString();
modelNoValue = txtModelNo.getText().toString();
39
mobileNoValue= txtMobileNo.getText().toString();
passwordValue = txtPassword.getText().toString();
confirmPassValue = txtConfirmPassword.getText().toString();
emailValue = txtEmailReceiver.getText().toString();

if (!nameValue.equals("") && !modelNoValue.equals("") &&


!mobileNoValue.equals("") && !passwordValue.equals("") &&
!confirmPassValue.equals("") && !emailValue.equals(""))
{
if(passwordValue.equals(confirmPassValue))
{
if(mobileNoValue.length() <= 11)
{
// another if-else condition to check if user already registered or not
// create another php file getting fields gmail , cell number, model
number
// Toast.makeText(getApplicationContext(), mobileNoValue.length() + "",
Toast.LENGTH_LONG).show();
sendData(nameValue, passwordValue, confirmPassValue,
modelNoValue, mobileNoValue, emailValue);
}
else {
Toast.makeText(getApplicationContext(), "Incorrect Mobile Number",
Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(), "Incorrect Password",
Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(getApplicationContext(), "Please Fill All Fields",
Toast.LENGTH_LONG).show();
}
}
});
}

public void sendData(String name, String password, String confirmPassword, String


modelNo, String mobileNo, String email)
{
Toast.makeText(this, name+ password+confirmPassword+mobileNo+modelNo+
email, Toast.LENGTH_LONG).show();
try{
HashMap hashMap = new HashMap();
hashMap.put("userName", name);
hashMap.put("ModelNo", modelNo);
hashMap.put("password", password);
hashMap.put("confirmPass", confirmPassword);
hashMap.put("EmailReceiver", email);
hashMap.put("mobileNumber", mobileNo);
// hashMap.put("emailSender", "abc@gmail.com");

PostResponseAsyncTask postResponseAsyncTask = new


PostResponseAsyncTask(this, hashMap);
postResponseAsyncTask.execute("http://192.168.43.188/savingData.php");
}
catch (ArrayIndexOutOfBoundsException e)
{

40
e.printStackTrace();
}
}

public void onClickBackToLogin(View view)


{
Intent intent = new Intent(this, LogInPage.class);
startActivity(intent);
}

@Override
public void processFinish(String s) {
emptyField();
Intent intent = new Intent(this, LogInPage.class);
startActivity(intent);

public void emptyField()


{
txtName.setText("");
txtModelNo.setText("");
txtEmailReceiver.setText("");
txtMobileNo.setText("");
txtConfirmPassword.setText("");
txtPassword.setText("");
}
}
3. System On/Off
package com.example.marshanawal.appdesign1;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.kosalgeek.asynctask.AsyncResponse;
import com.kosalgeek.asynctask.PostResponseAsyncTask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

public class SystemOnOff extends android.support.v4.app.Fragment implements


AsyncResponse{

String status;
Button btnOn;
Button btnOff;
Context context;
public SystemOnOff() {
41
// Required empty public constructor
}

public static SystemOnOff newInstance(String param1, String param2) {


return null;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_system_on_off, container, false);
status = "";
context = container.getContext();

btnOn = (Button)view.findViewById(R.id.btnOn);
btnOff = (Button)view.findViewById(R.id.btnOff);

btnOn.setOnClickListener(listener);
btnOff.setOnClickListener(listener);

return view;
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(getActivity().getApplicationContext(), "inside click",
Toast.LENGTH_LONG).show();
if (view.equals(btnOn))
{
status = "On";
Toast.makeText(getActivity().getApplicationContext(), status,
Toast.LENGTH_LONG).show();
actionOnSystem(status);
}
else if(view.equals(btnOff))
{
status = "Off";
Toast.makeText(getActivity().getApplicationContext(), status,
Toast.LENGTH_LONG).show();
actionOnSystem(status);
}
}
};

public void actionOnSystem(String s)


{
try {
HashMap hashMap = new HashMap();
hashMap.put("System", s);

// PostResponseAsyncTask postResponseAsyncTask = new

42
PostResponseAsyncTask(this, hashMap);
PostResponseAsyncTask postResponseAsyncTask = new
PostResponseAsyncTask(context, hashMap, new AsyncResponse() {
@Override
public void processFinish(String s) {
Toast.makeText(getActivity().getApplicationContext(), "Success",
Toast.LENGTH_SHORT ).show();
}
});
postResponseAsyncTask.execute("http://192.168.43.188/systemOnOff.php");
}
catch (ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
}

@Override
public void processFinish(String s) {
Toast.makeText(getActivity().getApplicationContext(), "Success 2",
Toast.LENGTH_SHORT ).show();
}
}

4. ListOfVideos

package com.example.marshanawal.appdesign1;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ListOfVideo extends android.support.v4.app.Fragment {

ListView listView;
VideoView videoView;
ArrayAdapter arrayAdapter;
String path;

43
public ListOfVideo() {
// Required empty public constructor
}

public static ListOfVideo newInstance(String param1, String param2) {


return null;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle("List Of Videos");
/// listView = (ListView)getView().findViewById(R.id.lstVideos);
// videoView = (VideoView)getView().findViewById(R.id.videosView);

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_of_video, container, false);
// Inflate the layout for this fragment
listView = (ListView)view.findViewById(R.id.lstVideos);
videoView = (VideoView)view.findViewById(R.id.videosView);
path ="http://192.168.43.81/listOfVideo.php/";
getJSON(path);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
String name = (String) adapterView.getItemAtPosition(i);
String videoName = name.split(",")[0];
String videopath = "http://192.168.43.188/Video/"+videoName;
Toast.makeText(getActivity().getApplicationContext(), videopath,
Toast.LENGTH_LONG).show();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
videoView.requestFocus();
videoView.start();
}
});
videoView.setVideoURI(Uri.parse(videopath));
}
});

return view;
}

private void getJSON(final String urlWebService) {


class GetJSON extends AsyncTask<Void, Void, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected void onPostExecute(String s) {

44
super.onPostExecute(s);
Toast.makeText(getActivity().getApplicationContext(), s,
Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
protected String doInBackground(Void... voids) {

try {
URL url = new URL(urlWebService);

HttpURLConnection con = (HttpURLConnection) url.openConnection();


StringBuilder stringBuilder = new StringBuilder();

BufferedReader bufferedReader = new BufferedReader(new


InputStreamReader(con.getInputStream()));

String json;

while ((json = bufferedReader.readLine()) != null) {


stringBuilder.append(json + "\n");
}

return stringBuilder.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}

private void loadIntoListView(String json) throws JSONException {


JSONArray jsonArray = new JSONArray(json);
String[] nameDate = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
nameDate[i] = obj.getString("Video_Name") + ", "+
obj.getString("Video_Date");
}
ArrayAdapter<String> arrayAdapter = new
ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1, nameDate);

listView.setAdapter(arrayAdapter);
}
}

45
Prototype Code

import RPi.GPIO as GPIO


import time
import math
import random
from time import sleep
import threading
from subprocess import call
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import glob
import requests
import os
import picamera
import datetime
import pymysql
class SSSPC:
def motor1(self):
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.servo1, GPIO.OUT)
p = GPIO.PWM(self.servo1, 45) # GPIO 17 for PWM with 50Hz
p.start(2.5) # Initialization
try:
while True:
p.ChangeDutyCycle(7)
time.sleep(0.5)
p.ChangeDutyCycle(2.5)
time.sleep(0.5)

except KeyboardInterrupt:
p.stop()
p2.stop()
GPIO.cleanup()

def motor2(self):
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.servo2, GPIO.OUT)
p = GPIO.PWM(self.servo2, 45) # GPIO 17 for PWM with 50Hz
p.start(2.5) # Initialization
try:
while True:
p.ChangeDutyCycle(7)
time.sleep(0.5)
p.ChangeDutyCycle(2.5)
time.sleep(0.5)

except KeyboardInterrupt:
p.stop()
GPIO.cleanup()

GPIO.setwarnings(False)
46
def __init__(self , servo1, servo2,trig1,echo1,trig2,echo2,channel,led):
self.servo1=servo1
self.servo2= servo2
self.trig1 = trig1
self.echo1 = echo1
self.trig2 = trig2
self.echo2 = echo2
self.channel = channel
self.led = led

'''This Function Call When a shock occur'''


def active(self,null):
print('Vibration Detected')
self.WhatsAppNotification()
self.Converter()
self.File()
self.InsertVideo()
print('Email Sent!')
sleep(10)

'''This Function calls callback() method if any shock occur'''


def vib_Sensor(self):
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.channel,GPIO.IN,pull_up_down = GPIO.PUD_UP)

GPIO.add_event_detect(self.channel,GPIO.FALLING,callback=self.active,bouncetime=300)

'''This Function generates signals from ultrasonic 1 sensor'''


def ping1(self):
currentDT =''
t0 = time.time()
list1 = []
new_previous = []
flag = True
flag2 = False
dictionary = {}
while True:
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.trig1,GPIO.OUT)
GPIO.setup(self.echo1,GPIO.IN)

GPIO.output(self.trig1, False)
time.sleep(0.1)

GPIO.output(self.trig1, True)
time.sleep(0.1)

GPIO.output(self.trig1, False)

while GPIO.input(self.echo1)==0:
pulse_start = time.time()

while GPIO.input(self.echo1)==1:
pulse_end = time.time()

47
pulse_duration = pulse_end - pulse_start

distance = pulse_duration * 17150

distance = round(distance, 2)
distance = (distance*0.394)
if(distance<=5):
# print('Sensor_1 {} \n'.format(distance))
list1.append(math.floor(distance))
t1 = time.time()
t2 = t1-t0
if t2 >1:
set_a=set(list1)
for i in set_a:
dictionary[i] = list1.count(i)
maximum = max(dictionary,key = dictionary.get)
new_previous.append(maximum)
print(new_previous)
if(len(new_previous) > 1):
if((new_previous[len(new_previous)-1] > new_previous[len(new_previous)-2]) or
(new_previous[len(new_previous)-1] == new_previous[len(new_previous)-2])):
if (flag2 is True):
# with picamera.PiCamera() as camera:
# camera.stop_recording()
print("Stop Recording")
del list1[:]
del new_previous[:]

flag = True
flag2 = False
elif(new_previous[len(new_previous)-1] < new_previous[len(new_previous)-2]):
flag = True
if(flag is True):
print("Start Recording")
currentDT = datetime.datetime.now()
with picamera.PiCamera() as camera:

camera.start_recording(str(currentDT.year)+'_'+str(currentDT.month)+'_'+str(currentDT.day)+'_'+str(
currentDT.hour)+'_'+str(currentDT.minute)+'_'+str(currentDT.second)+'.h264')
sleep(5)
camera.stop_recording()
del list1[:]
flag2 = True
flag = False
del new_previous[:]

else:
if(flag is True):
print("Recording Start")
currentDT = datetime.datetime.now()
with picamera.PiCamera() as camera:

camera.start_recording(str(currentDT.year)+'_'+str(currentDT.month)+'_'+str(currentDT.day)+'_'+str(
currentDT.hour)+'_'+str(currentDT.minute)+'_'+str(currentDT.second)+'.h264')
sleep(5)
camera.stop_recording()
flag = False
flag2 = True
48
del list1[:]
del new_previous[:]

dictionary.clear()
del list1[:]
set_a.clear()
t0 = time.time()
t1=0.0

'''This Function generates signals from ultrasonic 2 sensor'''


def ping2(self):
t0 = time.time()
list1 = []
new_previous = []
flag = True
flag2 = False
dictionary = {}

GPIO.setmode(GPIO.BCM)
while True:
GPIO.setup(self.trig2,GPIO.OUT)
GPIO.setup(self.echo2,GPIO.IN)

GPIO.output(self.trig2, False)
time.sleep(0.1)

GPIO.output(self.trig2, True)
time.sleep(0.1)

GPIO.output(self.trig2, False)

while GPIO.input(self.echo2)==0:
pulse_start = time.time()

while GPIO.input(self.echo2)==1:
pulse_end = time.time()

pulse_duration = pulse_end - pulse_start

distance = pulse_duration * 17150

distance = round(distance, 2)
distance = (distance*0.394)
if(distance<=5):
# print('Sensor_2 {} \n'.format(distance))
list1.append(math.floor(distance))
t1 = time.time()
t2 = t1-t0
if t2 >1:
set_a=set(list1)
for i in set_a:
dictionary[i] = list1.count(i)
maximum = max(dictionary,key = dictionary.get)
new_previous.append(maximum)
print(new_previous)
if(len(new_previous) > 1):
49
if((new_previous[len(new_previous)-1] > new_previous[len(new_previous)-2]) or
(new_previous[len(new_previous)-1] == new_previous[len(new_previous)-2])):
if (flag2 is True):
# with picamera.PiCamera() as camera:
# camera.stop_recording()
print("Stop Recording")
flag = True
flag2 = False
del list1[:]
del new_previous[:]

elif(new_previous[len(new_previous)-1] < new_previous[len(new_previous)-2]):


flag = True
if(flag is True):
print("Start Recording")
flag2 = True
flag = False
del list1[:]
del new_previous[:]

else:
if(flag is True):
# with picamera.PiCamera() as camera:
# camera.start_recording('/var/www/html/Video/pythonVideo.h264')
print("Recording Start")
# sleep(5)
flag = False
flag2 = True
del list1[:]
del new_previous[:]

dictionary.clear()
del list1[:]
set_a.clear()
t0 = time.time()
t1=0.0

#This is An Email File Method used to send email to registered person


def File(self):
owneremail = ''
connection = pymysql.connect(host="localhost",
user="pi",
passwd="alpha",
database="fyp",
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
sql = 'SELECT * FROM registration'
cursor.execute(sql)
result = cursor.fetchone()
owneremail = result['Email']

absolute_path=os.path.dirname(os.path.abspath(__file__))
files = glob.glob('/var/www/html/Video/*.*')

50
currentTime = datetime.datetime.now()
currenttime= ' '
if currentTime.hour <12:
currenttime='Good Morning.'
elif 12<= currentTime.hour <18:
currenttime='Good afternoon.'
else:
currenttime='Good evening.'

filename=str(max(files , key = os.path.getctime))


subject = 'Dent Alert!'
msg = MIMEMultipart()
msg['From'] = owneremail
msg['To'] = owneremail
msg['Subject'] = subject
body = 'Hello '+ currenttime +' this email is concerned with 3SPC. Please Find an attachment that is
given below.'
msg.attach(MIMEText(body,'plain'))
attachment = open(filename,'rb')
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition','attachment; filename =' + filename)
msg.attach(part)

text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(owneremail,'jamesjohn1233')
#server.sendmail('from','to',message)
server.sendmail(owneremail,owneremail,text)
server.quit()

print('connection successfully')
connection.close()

def Converter(self):
absolute_path=os.path.dirname(os.path.abspath(__file__))
files = glob.glob('*.h264')
latestfile = max(files,key=os.path.getctime)
convertablevideo = latestfile.split('.',1)
converter = os.system('ffmpeg -i ' +latestfile+ ' -codec copy Video/'+convertablevideo[0]+'.mp4')

def InsertVideo(self):
currentDT = datetime.datetime.now()
video_date = currentDT.strftime('%Y/%m/%d')
absolute_path=os.path.dirname(os.path.abspath(__file__))
files = glob.glob('*.h264')
latestfile = max(files,key=os.path.getctime)
convertablevideo = latestfile.split('.',1)
video_name = convertablevideo[0]+'.mp4'
connection = pymysql.connect(host="localhost",
user="pi",
passwd="alpha",
database="fyp",
charset='utf8mb4',
51
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = 'INSERT INTO video_information (Video_Name,Video_Date) VALUES (%s,%s)'
cursor.execute(sql,(video_name,video_date))
# print('insert')
connection.commit()
finally:
connection.close()
def WhatsAppNotification(self):
accountsid =''
accounttoken =''
whatsappnumber=''
TWILIO_NUMBER = 'whatsapp:+14155238886'
connection = pymysql.connect(host="localhost",
user="pi",
passwd="alpha",
database="fyp",
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = 'select Account_SID,Account_Token,Whatsapp_Number from whatsapp_info'
cursor.execute(sql)
result = cursor.fetchone()
accountsid = result['Account_SID']
accounttoken = result['Account_Token']
whatsappnumber = result['Whatsapp_Number']
finally:
connection.close()
TWILIO_MESSAGE_ENDPOINT = 'https://api.twilio.com/2010-04-
01/Accounts/{TWILIO_SID}/Messages.json'.format(TWILIO_SID=accountsid)

message_data = {
"To": 'whatsapp:'+whatsappnumber,
"From":TWILIO_NUMBER,
"Body":"Dear result[‘owner_Name’], This is a Dent Alert From 3SPC"
}
response = requests.post(TWILIO_MESSAGE_ENDPOINT, data=message_data,
auth=(accountsid, accounttoken))
response_json = response.json()
# print(response_json)

# servo1, servo2,trig1,echo1,trig2,echo2,vibsensor
project = SSSPC(17,18,7,8,16,21,26,19)
thread1= threading.Thread(target = project.motor1, name='motor1_Thread', args=[])
thread2= threading.Thread(target = project.motor2,name='motor2_Thread', args=[])
thread3 = threading.Thread(target = project.ping1,name='ultrasonic1_Thread', args=[])
thread4 = threading.Thread(target = project.ping2,name='ultrasonic2_Thread', args=[])
thread5 = threading.Thread(target = project.vib_Sensor,name='vibration_detector_sensor_Thread',
args=[])
thread1.start()
#thread2.start()
thread3.start()
#thread4.start()
thread5.start()

52

Potrebbero piacerti anche