#!/usr/bin/env python
#coding=utf8 
import httplib, urllib
import time
import sys
import time
import ConfigParser
import os
import json

global bConnect
    
#get local path
def cur_file_dir():
     path = sys.path[0]
     if os.path.isdir(path):
         return path
     elif os.path.isfile(path):
         return os.path.dirname(path)

def postdata():
    httpClient = None
    try:       
        fp = open(cur_file_dir() + '/post.json','rw+')
        lines = fp.read()
        fp.close()
        di = json.loads(lines)
        strsn = di['SN']
        strip = di['IP']
        strurl = di['URL']
        nPort = di['PORT']
        print 'SN='+strsn+',IP='+strip+',URL='+strurl+',port='+str(nPort)
        #params = urllib.urlencode({'sn':'dndx02'})
        params = urllib.urlencode({'sn':strsn})
        headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        #httpClient = httplib.HTTPConnection('112.74.80.60', 80, timeout=30)
        httpClient = httplib.HTTPConnection(strip,nPort, timeout=30)
        #httpClient.request('POST', '/dj/ping.php',params,headers)
        httpClient.request('POST', strurl,params,headers)
        response = httpClient.getresponse()
        resstatus = response.status
        #print resstatus
        if (resstatus == 200):
             global bConnect
             bConnect = True
        #print response.reason
        print response.read()
        #print response.getheaders() #获取头信息
        
    except Exception, e:
        print e
    finally:
        if httpClient:
            httpClient.close()

if __name__ == '__main__':
    try:
        #print 'Start ping .'
        print 'Press Ctrl-C to quit.'
        while True:
            global bConnect
            bConnect = False
            postdata()
            print 'Post data finished!'
            if (bConnect):
                 print 'Sleep 30 Min.'
                 time.sleep(30*60)                 
            else:
                 print 'Sleep 1 Min.'
                 time.sleep(60)
                 
    finally:
        pass
