Showing posts with label My Projects. Show all posts
Showing posts with label My Projects. Show all posts

Saturday, 29 July 2017

Webcam and Raspberry Pi Camera Project

Remotely accessing webcams is a fairly common activity that many people perform routinely. It is my intention in this chapter to show you how to put together three projects, each with unique capabilities. The first project uses a standard USB webcam with a comprehensive open source software package named Motion. The second project deals with the specially designed Pi Camera, which only works with the Pi. The final project also uses the Pi Camera but uses the Motion software instead of the specialty applications that typically come bundled with the Pi Camera. 

Conventional Webcam  :

The first project in this chapter uses a high-quality webcam that connects to the Pi using one of the PI’s two USB ports. I used a Logitech C920, shown in Figure 1

                                                                Fig 1: Camera

This a high-definition camera capable of producing excellent videos, but the open source software used within this project will constrain its performance. You may still use any one of the many different webcams that are available as the video requirements are modest and the current Raspian distribution will automatically detect and support many types, including older ones. If you already own a webcam, my suggestion is to plug it into  one of the Pi’s USB ports and then type the following into a command line:
lsusb hit enter

Figure 2 is a screenshot of the command’s output. Device 012 is the webcam while
the other Logitech device listed as 006 is a keyboard. If in doubt, with multiple devices
from the same manufacturer, simply unplug the device and rerun the command to see
which one disappears. 
the other Logitech device listed as 006 is a keyboard. If in doubt, with multiple devices from the same manufacturer, simply unplug the device and rerun the command to see which one disappears. 

                                                    Fig 2: lsusb output

Note that I have found this particular webcam to be somewhat sensitive in terms ofthe USB port it is plugged into. It may not be detected when plugged into one of the two Pi USB ports, in which case, try plugging it into a powered USB hub that provides at least the minimum specification current of 500mA for each USB port.  


Motion Software Package:I selected an open source software package named Motion to enable remote viewing ofthe webcam. This is a very comprehensive package containing a substantial number offeatures, far more than could be covered in this chapter. Creating similar software for amore traditional board, such as one from the Arduino series, would be a substantialundertaking. 

The key feature that is used from the Motion package is the built-in web server. This server receives the video stream from the webcam and sends it off in TCP/IP format over a predefined port. All you need to remotely view the webcam video is a browser pointed to the Pi’s IP address and port number, nothing more. This feature makes the viewing exercise extremely simple. But there is more: Motion enables you to use more than one webcam. You can set up multiple webcams, each with its own port number. Thus, you can monitor multiple locations throughout the observed area. Each webcam video feed is handled by what is known as a thread within the Motion software. I recognized provision for four threads in the Motion configuration file from which I presume four webcams could be handled. However, I seriously wonder if the Pi has the processing power to manage four simultaneous video feeds. In any case, this project is concerned with only one feed, which I know works very well. for four threads in the Motion configuration file from which I presume four webcams could be handled. However, I seriously wonder if the Pi has the processing power to manage four simultaneous video feeds. In any case, this project is concerned with only one feed, which I know works very well. for four threads in the Motion configuration file from which I presume four webcams could be handled. However, I seriously wonder if the Pi has the processing power to manage four simultaneous video feeds. In any case, this project is concerned with only one feed, which I know works very well.

Motion Setup:You will need to install the Motion package before using it. I strongly suggest that you
update and upgrade your distribution prior to installing Motion. Simply type the following at a command-line prompt to update and upgrade the Raspian distribution in use:
sudo apt-get update
sudo apt-get upgrade
Be patient as the updates and upgrades can take a bit of time if there are many to
install. Next, install Motion by typing the following:
sudo apt-get install motion 

Again, be a bit patient as this package is over 20MB in size and has many componentparts. Motion will be run in the “background” as a daemon, which means that it will beconstantly available for service. To enable the daemon, you must edit the/etc/default/motion file. Type the following:sudonano /etc/default/motionYou will see in the nano editor the line:start_motion_daemon=noChange the no to yes, and then save the nano buffer (CONTROL-O) and exit the editor
(
(CONTROL-X).
Next comes Motion’s configuration file. Motion has no graphics user interface (GUI)
so it must be configured by making changes to its configuration file,
/etc/motion/motion.conf.
This is a very big text file—well over 600 lines, although much of the file content consists of comments inserted to help the user. Fortunately, only a few changes are necessary for this project. I have provided the changes in Next comes Motion’s configuration file. Motion has no graphics user interface (GUI) so it must be configured by making changes to its configuration file,/etc/motion/motion.conf. This is a very big text file—well over 600 lines, although much of the file content consists of comments inserted to help the user. Fortunately, only a few changes are necessary for this project. I have provided the changes in 

Table 2 to be made by configuration file section, but I do not show you step-by-step instructions as you should be fairly comfortable with how to use the nano editormade by configuration file section, but I do not show you step-by-step instructions as you should be fairly comfortable with how to use the nano editor.

                                       Fig 2 : Motion configuration file changes 

Start the nano editor session as follows:sudonano /etc/motion/motion.confMake the changes as shown in Table 1 if the contents of the table have not already
been configured. Save the changes and exit the nano editor. Now, you must start the Motion server, which is done by entering the following: 
been configured.Save the changes and exit the nano editor. Now, you must start the Motion server,which is done by entering the following:sudo service motion startOne nice feature of having the Motion web server running as a daemon is that it isautomatically started each time you boot the Pi. You may also stop or restart the service bytyping the following:

sudo service motion stopsudo service motion restart

That’s it for the changes to be made in the configuration file. I do want to  briefly discuss why these changes were made. The change from daemon off to daemon on is obvious as it was needed to run Motion as a daemon. The next change making the port number 8081 is a bit historical as the Motion web service has traditionally been assigned to this port. It is not a required port number and you can easily change it to any number that you desire as long as it is greater than 1024 and less than 65535. This range avoids the “well known ports” and goes to the maximum possible port number. My recommendation is to leave it at 8081. Next open your web Browser and type your Raspberry Pi IP  address and give port number to hit enter.


 

 

Saturday, 15 July 2017

Python programming are used to create a chat application

In this program is help to chat with client to server and server to client to send sms.
there are 2 python programs are run in two different CMD.

Step1: server.py  to save these program

import socket
import time


def Main():
    host = "172.16.1.81"
    port = 8080
               
    mySocket = socket.socket()
    mySocket.bind((host,port))
               
    mySocket.listen(1)
    print("socket is Listeining")
    conn, addr = mySocket.accept()
    print ("Connection from: " + str(addr))
    while True:
        data = conn.recv(1024).decode()
        if not data:
            break
        print ("from connected  user: " + str(data))
                                               
        data = str(data)
        print ("Received from User: " + str(data))

        data = input("Enter your Message :")
        conn.send(data.encode())
                                               
    conn.close()
               
               
if __name__ == '__main__':
                Main()

open CMD and run
python server.py


step2: clent_server.py 

import socket

def Main():
host = '172.16.1.81'
port = 8080

mySocket = socket.socket()
mySocket.connect((host,port))


message = input("Enter your message: ")

while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()

print ('Received from server: ' + data)

data = input("Enter uour mesage: ")

mySocket.close()

if __name__ == '__main__':
Main()


open another CMD run this program 
python client_server.py

Thursday, 25 May 2017

Humidity Values is send from Raspberry pi to MQTT Cloud Dashboard

import Adafruit_DHT
import RPi.GPIO as GPIO
import time
import mosquitto ,os , urlparse
import mosquitto
client = mosquitto.Mosquitto()

sensor = Adafruit_DHT.DHT11
#sensor = Adafruit_DHT.DHT22

GPIO.setmode(GPIO.BOARD)

# Defines the GPIO connected to the sensor data pin
pino_sensor=25


# Define event callbacks
def on_connect(mosq, obj, rc):
    print("rc: " + str(rc))

def on_message(mosq, obj, msg):
    print(msg.topic + " reddy" + str(msg.qos) + "reddy" + str(msg.payload))

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))

def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_log(mosq, obj, level, string):
    print(string)

mqttc = mosquitto.Mosquitto()
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe

# Uncomment to enable debug messages
#mqttc.on_log = on_log

# Parse CLOUDMQTT_URL (or fallback to localhost)
cloudurl = raw_input("enter url of broker:")
url_str = os.environ.get('CLOUDMQTT_URL',cloudurl)
url = urlparse.urlparse(url_str)

# Connect
mqttc.username_pw_set('rhmobvzr','kUNFt2x3YSTv')
mqttc.connect('m11.cloudmqtt.com', 13665)

# Start subscribe, with QoS level 0
mqttc.subscribe("iot", 0)

# Publish a message
topicname=raw_input("enter topic name:")
message=raw_input("message:")
mqttc.publish(topicname,message)

# Continue the network loop, exit when an error occurs
rc = 0
while rc == 0:
    rc = mqttc.loop()
print("rc: " + str(rc))
while(1):
   # Read the sensor
   umid, temp = Adafruit_DHT.read_retry (sensor, pino_sensor);
   # If reading case is ok, it shows the values ​​on the screen
   if umid is not None and temp is not None:
     print ("Temperature = {0: 0.1f} Humidity = {1: 0.1f} \ n"). format (temp, umid);
     print ("Wait 5 seconds to re-read ... \ n");
     time.sleep (5)
   else:
     # Communication error message with the sensor
     print ("Failed to read data from DHT11 !!!")
     

Wednesday, 24 May 2017

Amazon Web Service

My Secound programming connection is raspberry pi to AWS.

Sensor details send to raspberry pi board to AWS cloud.

following the programming code is Temperature & Humidity sensor values send to AWS cloud.

from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import paho.mqtt.client as paho
import os
import socket
import ssl
import datetime
from time import sleep
from random import uniform
import RPi.GPIO as GPIO
import Adafruit_DHT

sensor = Adafruit_DHT.DHT11
#sensor = Adafruit_DHT.DHT22
 
GPIO.setmode(GPIO.BOARD)
 
# Defines the GPIO connected to the sensor data pin
pino_sensor=25

connflag = False
def on_connect(client,userdata,flags,rc):
    global connflag
    connflag = True
    print("connection return result:"+str(rc))
def on_message(client,userdata,msg):
    print(msg.Topic+" "+str(msg.payload))

mqttc = paho.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
awshost = "a1ajeyt0psxjow.iot.ap-southeast-1.amazonaws.com"
awsport = 8883
clientId = "temperature"
thingName = "temperature"
caPath = "/home/pi/tempcert/root-CA.crt"
certPath = "/home/pi/tempcert/temperature.cert.pem"
keyPath = "/home/pi/tempcert/temperature.private.key"
mqttc.tls_set(caPath,certfile=certPath,keyfile=keyPath,cert_reqs=ssl.CERT_REQUIRED,tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
mqttc.connect(awshost,awsport,keepalive = 60)
mqttc.loop_start()
timestamp = datetime.datetime.now()
 # Read the sensor
umid, temp = Adafruit_DHT.read_retry (sensor, pino_sensor);
if temp is not None and umid  is not None:
    mqttc.publish("tempandhumd","credo websolutions"+"temperature"+str(temp)+"humidity"+str(umid)+"time"+format(timestamp),qos=1)
    print("temperature"+"%.2f"%temp,"humidity"+"%.2f"%umid,"time" + format(timestamp))
else:
    mqttc.publish("tempandhumd","sensor is not connected",qos=1)
    print("values not sent")
while temp>30  and umid<60:
    sleep(10)
    if connflag == True:
        timestamp = datetime.datetime.now()
        # Read the sensor
        umid, temp = Adafruit_DHT.read_retry (sensor, pino_sensor);
        mqttc.publish("tempandhumd","change in temperature "+"temperature"+str(temp)+"humidity"+str(umid)+"time"+format(timestamp),qos=1)
        print("temperature"+"%.2f"%temp,"humidity"+"%.2f"%umid,"time" + format(timestamp))
    else:
       print("waiting for connection")

o/p: finally run this code DHT11 sensor values is read in AWS cloud.. 

My Project Details

In my first project is PIR sensor connected to the raspberry pi.


import RPi.GPIO as GPIO
import time
import mosquitto ,os , urlparse
import mosquitto
client = mosquitto.Mosquitto()

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

PIR_PIN=21
GPIO.setup(PIR_PIN,GPIO.IN)
GPIO.setup(10,GPIO.OUT)


def on_connect(mosq, obj, rc):
    print("rc: " + str(rc))

def on_message(mosq, obj, msg):
    print(msg.topic + "pir " + str(msg.qos) + " motion" + str(msg.payload))

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))

def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_log(mosq, obj, level, string):
    print(string)

mqttc = mosquitto.Mosquitto()
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe

# Uncomment to enable debug messages
#mqttc.on_log = on_log

# Parse CLOUDMQTT_URL (or fallback to localhost)
cloudurl = raw_input("enter url of broker:")
url_str = os.environ.get('CLOUDMQTT_URL',cloudurl)
url = urlparse.urlparse(url_str)

# Connect
mqttc.username_pw_set('yhkjbhzj','5H2qvOhoLiVU')
mqttc.connect(cloudurl, 13452)

topicname=raw_input("enter topic name:")

# Start subscribe, with QoS level 2
mqttc.subscribe(topicname, 2)

# Publish a message
message=raw_input("message:")
mqttc.publish(topicname,message)
rc = 0
while rc == 0:
    rc = mqttc.loop()
    print("rc: " + str(rc))
    while(1):
        if GPIO.input(PIR_PIN):
            print "motion detected"
            camera.start_preview()
            camera.capture('/home/pi/image%s.jpg' % counter)
            counter = counter + 1
            camera.stop_preview()
            time.sleep (5)
        else:
            # Communication error message with the sensor
            print ("Failed to read data from PIR sensor !!!")

This is following cloudmqtt link

https://www.cloudmqtt.com/

you get the pir sensor capture the photos to mqtt dashboard.