互联网连接再次启动时做一些事情

时间:2015-02-28 17:06:37

标签: python

我想在Python上实现以下概念,但我想弄清楚编程思想。

如果互联网连接可用,则使用相机拍摄图像,然后将其上传到FTP服务器上,如果没有将图像保存在驱动器上。同时继续做其他事情但是,当互联网连接再次启动时,然后上传它。

这可能是等待上传的图片数量。你觉得怎么样?

我已经编写了代码来拍照并上传,但如果没有互联网连接在ftp服务器上传图像,脚本会返回错误并退出。下面的代码只是我项目的一些部分。我已经分享了我认为有用的东西,可以了解我想要做什么。

def takePicture(self, image_name):
      image_path = '/home/pi/pictures/' + image_name
      interact().ftpSession(image_path, image_name)
      rLink = 'http://www.webpage.com/images/' + image_name
      print rLink
      interact().sendSms("Demo Picture " + rLink)

 def grabPicture(self):
      grab_cam = subprocess.Popen("sudo fswebcam --timestamp '%d-%m-%Y %H:%M:%S (%Z)' -r 640x480 -d /dev/v4l/by-id/usb-OmniVision_Technologies__Inc._USB_Camera-B4.09.24.1-video-index0 -q /home/pi/pictures/%m-%d-%y-%H%M.jpg", shell=True)
      grab_cam.wait()
      todays_date = datetime.datetime.today()
      image_name = todays_date.strftime('%m-%d-%y-%H%M') + '.jpg'
      return image_name

def ftpSession(self, image_path, image_name):
      session = ftplib.FTP('ftp.webpage.com','user','fg78fy87fyg')
      session.cwd('images')                         #Give the rigth folder where to store the image
      print "FTP Connection established"
      file = open(image_path,'rb')                  # file to send
      session.storbinary('STOR ' + image_name, file)     # send the file
      file.close()                                    # close file and FTP
      session.quit()
      link = 'http://www.webpage.com/images/' + image_name
      print "File has been uploaded!"
      return link

def pir():
  prevState = 0
  while True:
    time.sleep(0.1)
    currState=mcp2.input(sensorPin)
    if prevState==0 and currState==128:
      image_name = interact().grabPicture()
      #....#
      status = database().getState()
      #.....#
      if (status == 'True'):
        #Do something
      else:
            if os.path.exists('/home/pi/pictures/'+image_name):
              os.remove('/home/pi/pictures/'+image_name) #Deletes the taken picture in case of False-Alarm
              print 'File', image_name, 'has beeen deleted'

    prevState = currState
    time.sleep(1)

 Process(target=pir).start()

2 个答案:

答案 0 :(得分:2)

我使用urllib进行简单检查,看看互联网是否已连接:

while True:
    try:
        urllib.urlopen('http://google.com')

        break # exit loop if connected

    except:
        print 'Establish a connection.'

    time.sleep(5) # wait five seconds


print 'Now continue' # outside of loop

答案 1 :(得分:0)

有一个尝试每隔一段时间上传一次图像的线程(例如,每5分钟或任何金额似乎符合您的需要),并且如果由于缺少互联网连接而失败则继续迭代(使用try / except)

伪代码:

import time
while True:
  try:
    upload_file()
  except NoConnectionException:
    time.sleep(300)