2016-05-01 24 views
0

これら3つのコードを一緒に結合する際に問題があります。このプロジェクトはSmoke System Alarmです。煙センサーが煙を検知すると、写真が撮影され、写真が添付された電子メールが送信されます。私が混乱していることは、3つのコードを一緒に結合する方法です。Python 3 Together Code Together - Raspberry Pi

ありがとうございました!

カメラコード:

#!/usr/bin/python 
import os 
import pygame, sys 

from pygame.locals import * 
import pygame.camera 

width = 480 
height = 360 

#initialise pygame 
pygame.init() 
pygame.camera.init() 
cam = pygame.camera.Camera("/dev/video0",(width,height)) 
cam.start() 

#setup window 
windowSurfaceObj = pygame.display.set_mode((width,height),1,16) 
pygame.display.set_caption('Camera') 

#take a picture 
image = cam.get_image() 
cam.stop() 

#display the picture 
catSurfaceObj = image 
windowSurfaceObj.blit(catSurfaceObj,(0,0)) 
pygame.display.update() 

#save picture 
pygame.image.save(windowSurfaceObj,'picture.jpg') 

メールコード:

#!/usr/bin/env python 
# encoding: utf-8 
import os 
import smtplib 
from email import encoders 
from email.mime.base import MIMEBase 
from email.mime.multipart import MIMEMultipart 

COMMASPACE = ', ' 

def main(): 
    sender = '' 
    gmail_password = '' 
    recipients = [''] 

    # Create the enclosing (outer) message 
    outer = MIMEMultipart() 
    outer['Subject'] = 'SMOKE HAS BEEN DETECTED!' 
    outer['To'] = COMMASPACE.join(recipients) 
    outer['From'] = sender 
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' 

    # List of attachments 
    attachments = [''] 

    # Add the attachments to the message 
    for file in attachments: 
     try: 
      with open(file, 'rb') as fp: 
       msg = MIMEBase('application', "octet-stream") 
       msg.set_payload(fp.read()) 
      encoders.encode_base64(msg) 
      msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) 
      outer.attach(msg) 
     except: 
      print("Unable to open one of the attachments. Error: ", sys.exc_info()[0]) 
      raise 

    composed = outer.as_string() 

    # Send the email 
    try: 
     with smtplib.SMTP('smtp.gmail.com', 587) as s: 
      s.ehlo() 
      s.starttls() 
      s.ehlo() 
      s.login(sender, gmail_password) 
      s.sendmail(sender, recipients, composed) 
      s.close() 
     print("Email sent!") 
    except: 
     print("Unable to send the email. Error: ", sys.exc_info()[0]) 
     raise 

if __name__ == '__main__': 
    main() 

MQ2煙センサーコード:

import time 
import botbook_mcp3002 as mcp # 

smokeLevel= 0 

def readSmokeLevel(): 
global smokeLevel 
smokeLevel= mcp.readAnalog() 

def main(): 
while True: # 
readSmokeLevel() # 
print ("Current smoke level is %i " % smokeLevel) # 
if smokeLevel > 120: 
print("Smoke detected") 
time.sleep(0.5) # s 

if_name_=="_main_": 
main() 

答えて

-1

おそらく最も簡単な方法は、Python 3.5(またはsubprocess.callsubprocess.runを使用することです以前のバージョンでは)最初に写真プログラムを起動し、次に電子メールプログラム煙探知プログラムからのラム。

もう1つの方法は、カメラプログラムと電子メールプログラムをモジュールに変換することです。

カメラモジュールはこのように見えます。

"""Camera module""" 

import pygame 


def picture(filename): 
    """Take a picture. 

    Arguments: 
     filename: Path where to store the picture 
    """ 
    pygame.init() 
    pygame.camera.init() 
    cam = pygame.camera.Camera("/dev/video0", (480, 360)) 
    cam.start() 
    image = cam.get_image() 
    cam.stop() 
    pygame.image.save(image, filename) 

と同じように、あなたは機能send_mail(sender, password, recipient, attachments)emailモジュールを作成することができます。

煙探知プログラムでは、そうすることができます。

import camera 
import email 

# if smoke detected... 
imagename = 'smoke.jpg' 
camera.picture(imagename) 
email.send_mail('[email protected]', 'sfwrterger', '[email protected]', 
       [imagename]) 
1

あなたが1つのファイルを作成することですやりたいPythonのチュートリアルや2 :)

最も簡単な方法(必ずしも必要ではないが最善の方法を)やってから恩恵を受ける可能性があるようです、そうです上部にあるすべてのimport文を入れた後、次の操作を行います。

は、カメラのコードを追加しますが、関数に変換します

def take_picture(): 
    width = 480 
    height = 360 

    # initialise pygame 
    pygame.init() 
    [etc.] 

注意、先頭の空白は重要です。

この関数は、呼び出されたときにファイル名を指定するように記述することもできます(Rolandの例のように)。複数の画像を保存したい場合に備えて、これを行うより良い方法です。

次に、電子メールコードを追加しますが、ここでmain関数の名前をemail_pictureのように変更する必要があります。また、たとえば次のような詳細を記入する必要があります。 attachments変数をtake_picture関数が保存しているファイルの名前と一致するように変更します。 (ここでも、呼び出し側は、ローランドの例のように、送信者/受信者のアドレスとファイル名のようなもの(複数可)を指定することができるようにする方が良いでしょう。また、ここでif __name__ == "__main__"一部が含まれていません

例:。。

COMMASPACE = ', ' 

def email_picture(): 
    sender = '[email protected]' 
    gmail_password = 'YourGmailPassword' 
    recipients = ['[email protected]'] 

    # Create the enclosing (outer) message 
    outer = MIMEMultipart() 
    outer['Subject'] = 'SMOKE HAS BEEN DETECTED!' 
    outer['To'] = COMMASPACE.join(recipients) 
    outer['From'] = sender 
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' 

    # List of attachments 
    # This must match what the take_picture funtion is saving the file as 
    attachments = ['picture.jpg'] 
    [etc.] 

次に、煙検知コードを追加してください。あなたの投稿のコードは少しばらまきがあります。先頭のスペースが欠落しており、一部の2重のアンダースコアが1つのアンダースコアに変更されています。

煙検知コードにカメラコードと電子メールコードの呼び出しを追加します。また、煙が検出されたときに電子メールを送信した後に睡眠を追加して、煙が検出されるたびにスクリプトが何百/何千もの電子メールを送信しないようにすることもできます。

(グローバル変数は不要と思われるが)それはより次のようになります。

smokeLevel = 0 

def readSmokeLevel(): 
    global smokeLevel 
    smokeLevel = mcp.readAnalog() 

def main(): 
    while True: # Loop forever 
     readSmokeLevel() # 
     print("Current smoke level is %i " % smokeLevel) # 
     if smokeLevel > 120: 
      print("Smoke detected") 
      take_picture() 
      email_picture() 
      time.sleep(600) # Cut down on emails when smoke detected 
     time.sleep(0.5) # seconds 

if __name__ == "__main__": 
    main() 
関連する問題