| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780 | #!/usr/bin/env python3.5import paho.mqtt.client as mqttimport timeimport sysimport http.client, urllibimport jsonimport threadingimport osimport shutilimport uuidimport hashlibimport serialimport arrayimport base64import urllib.requestimport datetimeimport requestsimport logging""" Device Information - the information about this deviceThese device information is used for the MQTT topic. This program will subscribe and publish tothe MQTT topic.MQTT topic to subscribe to: AISKY/<project_name>/<model_name>/<device_id>MQTT topic to publish to : AISKY/<project_name>/<model_name>/<device_id>/Log"""# @var project_name  The project name comes from the u-boot environment variable 'project'.# @var model_name    The model name comes from the u-boot environment variable 'model'.# @var device_id     The device id comes from the mac address of eth0.project_name = os.popen('cat /etc/aisky.conf | grep project').readline().split('=')[1].strip()model_name = os.popen('cat /etc/aisky.conf | grep model').readline().split('=')[1].strip()device_id = open('/sys/class/net/eth0/address').readline().strip()""" NOTE: Remember to setup the u-boot environment variables before executing this program. Thecommands to setup the u-boot environment variables are as follows.Setup the 'project' variable: The following command sets the 'project' variable to AppleFarm.    root@mylinkit:~# fw_setenv project AppleFarmSetup the 'model' variable: The following command sets the 'model' variable to MK-G.    root@mylinkit:~# fw_setenv model MK-GThen, the following command can be used to display the u-boot environment variables.    root@mylinkit:~# fw_printenv"""""" MQTT ServerIf you don't have your own MQTT server, you can use the public MQTT server 'iot.eclipse.org'. Butwith the public MQTT server, you can only publish and subscribe without a user name and password.Sometimes the public MQTT server is unstable."""# @var mqtt_server  The URL or IP address of the MQTT server to connect to.# @var mqtt_port    The port of the MQTT server to connect to.# @var mqtt_alive   Maximum period in seconds allowed between communications with the broker. If#                   no other messages are being exchanged, this controls the rate at which the #                   client will send ping messages to the broker.mqtt_server = "52.195.10.119"mqtt_port = 1883mqtt_alive = 60# camera API commandcamera_ircut_high = 'http://192.168.50.94/cgi-bin/camerasetting_cgi?action=set&channel=0&user=admin&pwd=abcd1234&TRCutLevel=high'camera_ircut_low = 'http://192.168.50.94/cgi-bin/camerasetting_cgi?action=set&channel=0&user=admin&pwd=abcd1234&TRCutLevel=low'camera_image = 'http://192.168.50.94/cgi-bin/images_cgi?channel=0&user=admin&pwd=abcd1234'camera_zoomin = "http://192.168.50.94/cgi-bin/ptz_cgi?action=ZoomAdd&user=admin&pwd=abcd1234"camera_zoomout = "http://192.168.50.94/cgi-bin/ptz_cgi?action=ZoomSub&user=admin&pwd=abcd1234"#php pathndvi_path = 'http://60.250.156.234/cust/c21.php'ppv_path = 'http://60.250.156.234/cust/p21.php'impv_path = 'http://60.250.156.234/cust/im21.php'log_path = 'http://52.195.10.119/MQTT/BBtoMQTT.php'logpv_path = 'http://52.195.10.119/MQTT/BBtoMQTT_preview.php'#loglogging.basicConfig(level=logging.INFO, filename='/tmp/mqtt.log',format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')# @var mqtt_sub_topic  The MQTT topic to subscribe to.# @var mqtt_pub_topic  The MQTT topic to publish to.mqtt_sub_topic = "AISKY/" + project_name + "/" + model_name + "/" + device_idmqtt_pub_topic = mqtt_sub_topic + "/Log"##nrnr = "KDARES21"##angleTilt_old = 0Pan_old = 0Zoom_old = 0## Calculate the SHA256 checksum of the file.# @param file  [in] The file path for which you want to calculate the checksum.def get_sha256sum(file):    with open(file, "rb") as f:        bytes = f.read()        return hashlib.sha256(bytes).hexdigest()## Send logs to the server.# @param command   [in] The command received from the server.# @param response  [in] The response message to the command.def server_log(command, response):    localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())    # message to be sent in JSON format    payload = {        # let server know which device the message came from        'device_id': device_id,        # let server know when the message was sent from the device        'localtime': localtime,        'command': command,        'response': response    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)## Reset this device.def system_reboot():    server_log('reboot', 'Restarting system')    logging.info('system reboot')    time.sleep(5)    os.system('sudo reboot')    time.sleep(10)## Reset this device to factory default.def factory_reset():    server_log('factory_reset', 'Resetting to factory default')    logging.info('system reset')    time.sleep(5)    os.system('firstboot -y')    os.system('reboot -f')    time.sleep(10)## Receive the system action  to this device .def ndvi_1(msg):    server_log('ndvi_1', 'start')    print(msg['orPan'])    print(msg['orTilt'])    print(msg['orZoom'])    print(msg['position'])    orpan(msg)    ortilt(msg)    orzoom(msg)    time.sleep(2)    ndvi1()    logging.info('ndvi 1')    data = {'nr': nr, 'tilt_angle': int(msg['orTilt']), 'pan_angle': int(msg['orPan']),'zoom': int(msg['orZoom'])}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 1 angle  ok")    data = {'nr': nr, 'MODE': int(msg['position']), 'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0,'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 1 ok")def ndvi_2(msg):    server_log('ndvi_2', 'start')    print(msg['orPan'])    print(msg['orTilt'])    print(msg['orZoom'])    print(msg['position'])    orpan(msg)    ortilt(msg)    orzoom(msg)    time.sleep(2)    ndvi2()    logging.info('ndvi 2')    data = {'nr': nr, 'tilt_angle': int(msg['orTilt']), 'pan_angle': int(msg['orPan']),'zoom': int(msg['orZoom'])}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 2 angle  ok")    data = {'nr': nr, 'MODE': int(msg['position']), 'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0,'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 2 ok")def ndvi_3(msg):    server_log('ndvi_3', 'start')    print(msg['orPan'])    print(msg['orTilt'])    print(msg['orZoom'])    print(msg['position'])    orpan(msg)    ortilt(msg)    orzoom(msg)    time.sleep(2)    ndvi3()    logging.info('ndvi 3')    data = {'nr': nr, 'tilt_angle': int(msg['orTilt']), 'pan_angle': int(msg['orPan']),'zoom': int(msg['orZoom'])}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 3 angle  ok")    data = {'nr': nr, 'MODE': int(msg['position']), 'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0,'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 3 ok")def ndvi_4(msg):    server_log('ndvi_4', 'start')    print(msg['orPan'])    print(msg['orTilt'])    print(msg['orZoom'])    print(msg['position'])    orpan(msg)    ortilt(msg)    orzoom(msg)    time.sleep(2)    ndvi4()    logging.info('ndvi 4')    data = {'nr': nr, 'tilt_angle': int(msg['orTilt']), 'pan_angle': int(msg['orPan']),'zoom': int(msg['orZoom'])}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 4 angle  ok")    data = {'nr': nr, 'MODE': int(msg['position']), 'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0,'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 4 ok")def ndvi_5(msg):    server_log('ndvi_5', 'start')    print(msg['orPan'])    print(msg['orTilt'])    print(msg['orZoom'])    print(msg['position'])    orpan(msg)    ortilt(msg)    orzoom(msg)    time.sleep(2)    ndvi5()    logging.info('ndvi 5')    data = {'nr': nr, 'tilt_angle': int(msg['orTilt']), 'pan_angle': int(msg['orPan']),'zoom': int(msg['orZoom'])}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 5 angle  ok")    data = {'nr': nr, 'MODE': int(msg['position']), 'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0,'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 5 ok")def ndvi_6(msg):    server_log('ndvi_6', 'start')    print(msg['orPan'])    print(msg['orTilt'])    print(msg['orZoom'])    print(msg['position'])    orpan(msg)    ortilt(msg)    orzoom(msg)    time.sleep(2)    ndvi6()    logging.info('ndvi 6')    data = {'nr': nr, 'tilt_angle': int(msg['orTilt']), 'pan_angle': int(msg['orPan']),'zoom': int(msg['orZoom'])}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 6 angle  ok")    data = {'nr': nr, 'MODE': int(msg['position']), 'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0,'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 6 ok")def ndvi_7(msg):    server_log('ndvi_7', 'start')    print(msg['orPan'])    print(msg['orTilt'])    print(msg['orZoom'])    print(msg['position'])    orpan(msg)    ortilt(msg)    orzoom(msg)    time.sleep(2)    ndvi7()    logging.info('ndvi 7')    data = {'nr': nr,'tilt_angle': int(msg['orTilt']), 'pan_angle': int(msg['orPan']),'zoom': int(msg['orZoom'])}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 7 angle  ok")    data = {'nr': nr, 'MODE': int(msg['position']), 'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0, 'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 7 ok")def ndvi_8(msg):    server_log('ndvi_8', 'start')    print(msg['orPan'])    print(msg['orTilt'])    print(msg['orZoom'])    print(msg['position'])    orpan(msg)    ortilt(msg)    orzoom(msg)    time.sleep(2)    ndvi8()    logging.info('ndvi 8')    data = {'nr': nr, 'tilt_angle': int(msg['orTilt']), 'pan_angle': int(msg['orPan']),'zoom': int(msg['orZoom'])}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 8 angle  ok")    data = {'nr': nr, 'MODE': int(msg['position']), 'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0,'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("NDVI 8 ok")def manual_ndvi():    server_log('manual_ndvi', 'start')    ndvi()    logging.info('manual ndvi ')    # -----------------------log---------------------------------------------------    data = {'nr': nr, 'MODE': 9,'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0, 'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read();    print("MANUAL NDVI  ok")def p1_preview_photo():    server_log('p1_preview_photo', 'start')    req = requests.get(camera_ircut_high)    fileName = datetime.datetime.now().strftime("/home/pi/p1/1.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    dress = '/home/pi/p1/'    for root, dirs, files in os.walk(dress):        print('files: {}'.format(len(files)))        if len(files) >= 1:            files.sort()            for f in files:                with open(os.path.join(root, f), "rb") as imageFile:                    str = base64.b64encode(imageFile.read())                url = ppv_path                values = {'p22_1': str, 'p22_name_1': f}                p22_1 = urllib.parse.urlencode(values)                p22_1 = p22_1.encode('utf-8')                req = urllib.request.Request(url, p22_1)                req.add_header('User-Agent', 'Magic Browser')                resp = urllib.request.urlopen(req)                respData = resp.read()                print(os.path.join(root, f))                #print(respdata)                os.remove(os.path.join(root, f))                print("ok")                logging.info('p1_preview_photo')    data = {'nr': nr,'MODE': 0, 'p1': 1, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0, 'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("p1_preview_photo ok")def p2_preview_photo():    server_log('p2_preview_photo', 'start')    req = requests.get(camera_ircut_high)    fileName = datetime.datetime.now().strftime("/home/pi/p2/2.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    dress = '/home/pi/p2/'    for root, dirs, files in os.walk(dress):        print('files: {}'.format(len(files)))        if len(files) >= 1:            files.sort()            for f in files:                with open(os.path.join(root, f), "rb") as imageFile:                    str = base64.b64encode(imageFile.read())                url = ppv_path                values = {'p22_2': str, 'p22_name_2': f}                p22_2 = urllib.parse.urlencode(values)                p22_2 = p22_2.encode('utf-8')                req = urllib.request.Request(url, p22_2)                req.add_header('User-Agent', 'Magic Browser')                resp = urllib.request.urlopen(req)                respData = resp.read()                print(os.path.join(root, f))                #print(respdata)                os.remove(os.path.join(root, f))                print("ok")                logging.info('p2_preview_photo')    data = {'nr': nr,'MODE': 0,'p1': 0, 'p2': 1, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0, 'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("p2_preview_photo ok")def p3_preview_photo():    server_log('p3_preview_photo', 'start')    req = requests.get(camera_ircut_high)    fileName = datetime.datetime.now().strftime("/home/pi/p3/3.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    dress = '/home/pi/p3/'    for root, dirs, files in os.walk(dress):        print('files: {}'.format(len(files)))        if len(files) >= 1:            files.sort()            for f in files:                with open(os.path.join(root, f), "rb") as imageFile:                    str = base64.b64encode(imageFile.read())                url = ppv_path                values = {'p22_3': str, 'p22_name_3': f}                p22_3 = urllib.parse.urlencode(values)                p22_3 = p22_3.encode('utf-8')                req = urllib.request.Request(url, p22_3)                req.add_header('User-Agent', 'Magic Browser')                resp = urllib.request.urlopen(req)                respData = resp.read()                print(os.path.join(root, f))                #print(respdata)                os.remove(os.path.join(root, f))                print("ok")                logging.info('p3_preview_photo')    data = {'nr': nr,'MODE': 0, 'p1': 0, 'p2': 0, 'p3': 1, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0, 'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("p3_preview_photo ok")def p4_preview_photo():    server_log('p4_preview_photo', 'start')    req = requests.get(camera_ircut_high)    fileName = datetime.datetime.now().strftime("/home/pi/p4/4.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    dress = '/home/pi/p4/'    for root, dirs, files in os.walk(dress):        print('files: {}'.format(len(files)))        if len(files) >= 1:            files.sort()            for f in files:                with open(os.path.join(root, f), "rb") as imageFile:                    str = base64.b64encode(imageFile.read())                url = ppv_path                values = {'p22_4': str, 'p22_name_4': f}                p22_4 = urllib.parse.urlencode(values)                p22_4 = p22_4.encode('utf-8')                req = urllib.request.Request(url, p22_4)                req.add_header('User-Agent', 'Magic Browser')                resp = urllib.request.urlopen(req)                respData = resp.read()                print(os.path.join(root, f))                #print(respdata)                os.remove(os.path.join(root, f))                print("ok")                logging.info('p4_preview_photo')    data = {'nr': nr,'MODE': 0,'p1': 0, 'p2': 0, 'p3': 0, 'p4': 1, 'p5': 0, 'p6': 0, 'p7': 0, 'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("p4_preview_photo ok")def p5_preview_photo():    server_log('p5_preview_photo', 'start')    req = requests.get(camera_ircut_high)    fileName = datetime.datetime.now().strftime("/home/pi/p5/5.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    dress = '/home/pi/p5/'    for root, dirs, files in os.walk(dress):        print('files: {}'.format(len(files)))        if len(files) >= 1:            files.sort()            for f in files:                with open(os.path.join(root, f), "rb") as imageFile:                    str = base64.b64encode(imageFile.read())                url = ppv_path                values = {'p22_5': str, 'p22_name_5': f}                p22_5 = urllib.parse.urlencode(values)                p22_5 = p22_5.encode('utf-8')                req = urllib.request.Request(url, p22_5)                req.add_header('User-Agent', 'Magic Browser')                resp = urllib.request.urlopen(req)                respData = resp.read()                print(os.path.join(root, f))                #print(respdata)                os.remove(os.path.join(root, f))                print("ok")                logging.info('p5_preview_photo')    data = {'nr': nr,'MODE': 0,'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 1, 'p6': 0, 'p7': 0, 'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("p5_preview_photo ok")def p6_preview_photo():    server_log('p6_preview_photo', 'start')    req = requests.get(camera_ircut_high)    fileName = datetime.datetime.now().strftime("/home/pi/p6/6.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    dress = '/home/pi/p6/'    for root, dirs, files in os.walk(dress):        print('files: {}'.format(len(files)))        if len(files) >= 1:            files.sort()            for f in files:                with open(os.path.join(root, f), "rb") as imageFile:                    str = base64.b64encode(imageFile.read())                url = ppv_path                values = {'p22_6': str, 'p22_name_6': f}                p22_6 = urllib.parse.urlencode(values)                p22_6 = p22_6.encode('utf-8')                req = urllib.request.Request(url, p22_6)                req.add_header('User-Agent', 'Magic Browser')                resp = urllib.request.urlopen(req)                respData = resp.read()                print(os.path.join(root, f))                #print(respdata)                os.remove(os.path.join(root, f))                print("ok")                logging.info('p6_preview_photo')    data = {'nr': nr,'MODE': 0,'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 1, 'p7': 0, 'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("p6_preview_photo ok")def p7_preview_photo():    server_log('p7_preview_photo', 'start')    req = requests.get(camera_ircut_high)    fileName = datetime.datetime.now().strftime("/home/pi/p7/7.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    dress = '/home/pi/p7/'    for root, dirs, files in os.walk(dress):        print('files: {}'.format(len(files)))        if len(files) >= 1:            files.sort()            for f in files:                with open(os.path.join(root, f), "rb") as imageFile:                    str = base64.b64encode(imageFile.read())                url = ppv_path                values = {'p22_7': str, 'p22_name_7': f}                p22_7 = urllib.parse.urlencode(values)                p22_7 = p22_7.encode('utf-8')                req = urllib.request.Request(url, p22_7)                req.add_header('User-Agent', 'Magic Browser')                resp = urllib.request.urlopen(req)                respData = resp.read()                print(os.path.join(root, f))               # print(respdata)                os.remove(os.path.join(root, f))                print("ok")                logging.info('p7_preview_photo')    data = {'nr': nr,'MODE': 0,'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 1, 'p8': 0}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("p7_preview_photo ok")def p8_preview_photo():    server_log('p8_preview_photo', 'start')    req = requests.get(camera_ircut_high)    fileName = datetime.datetime.now().strftime("/home/pi/p8/8.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    dress = '/home/pi/p8/'    for root, dirs, files in os.walk(dress):        print('files: {}'.format(len(files)))        if len(files) >= 1:            files.sort()            for f in files:                with open(os.path.join(root, f), "rb") as imageFile:                    str = base64.b64encode(imageFile.read())                url = ppv_path                values = {'p22_8': str, 'p22_name_8': f}                p22_8 = urllib.parse.urlencode(values)                p22_8 = p22_8.encode('utf-8')                req = urllib.request.Request(url, p22_8)                req.add_header('User-Agent', 'Magic Browser')                resp = urllib.request.urlopen(req)                respData = resp.read()                print(os.path.join(root, f))                #print(respdata)                os.remove(os.path.join(root, f))                print("ok")                logging.info('p8_preview_photo')    data = {'nr': nr,'MODE': 0,'p1': 0, 'p2': 0, 'p3': 0, 'p4': 0, 'p5': 0, 'p6': 0, 'p7': 0, 'p8': 1}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(logpv_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("p8_preview_photo ok")def tilt(msg):    global Tilt_old    Tilt_old = msg['Tilt'] + Tilt_old    if (Tilt_old > 90):        Tilt_old = 90        server_log('tilt', Tilt_old)        Tilt(90)        take_preview_photo()        logging.info('tilt max')    elif (Tilt_old < -25):        Tilt_old = -25        server_log('tilt', Tilt_old)        Tilt(-25)        take_preview_photo()        logging.info('tilt min')    else:        server_log('tilt', Tilt_old)        Tilt(Tilt_old)        take_preview_photo()        logging.info('tilt')    data = {'nr': nr,'tilt_angle': Tilt_old,'pan_angle':Pan_old,'zoom':  Zoom_old}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("Tilt ok")def pan(msg):    global Pan_old    Pan_old = msg['Pan'] + Pan_old    if (Pan_old > 360):        Pan_old = Pan_old - 360        server_log('pan', Pan_old)        Pan(Pan_old)        take_preview_photo()    elif (Pan_old < 0):        Pan_old = 360 + Pan_old        server_log('pan', Pan_old)        Pan(Pan_old)        take_preview_photo()    else:        server_log('pan', Pan_old)        Pan(Pan_old)        take_preview_photo()        logging.info('pan')    data = {'nr': nr,'tilt_angle':Tilt_old, 'pan_angle': Pan_old,'zoom': Zoom_old}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("Pan ok")def zoom(msg):    global Zoom_old    Zoom_old = msg['Zoom']+ Zoom_old    print(Zoom_old)    if (Zoom_old > 5):        Zoom_old = 5        server_log('zoom', Zoom_old)        Zoom(0)        take_preview_photo()        logging.info('zoom max')    elif (Zoom_old < 0):        Zoom_old = 0        server_log('zoom', Zoom_old)        Zoom(0)        take_preview_photo()        logging.info('zoom min')    else:        server_log('zoom', Zoom_old)        Zoom(int(msg['Zoom']))        take_preview_photo()        logging.info('zoom')    data = {'nr': nr,'tilt_angle':Tilt_old, 'pan_angle':Pan_old,'zoom': Zoom_old}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(log_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("Zoom ok")def orpan(msg):    global Pan_old    Pan_old = int(msg['orPan'])    if (Pan_old>360):        Pan_old = Pan_old - 360        server_log('orpan', Pan_old)        Pan(Pan_old)    elif(Pan_old<0):        Pan_old = 360 + Pan_old        server_log('orpan', Pan_old)        Pan(Pan_old)    else:        server_log('orpan',Pan_old)        Pan(Pan_old)        logging.info('pan')def ortilt(msg):    global Tilt_old    Tilt_old = int(msg['orTilt'])    if (Tilt_old > 90):        Tilt_old = 90        server_log('ortilt', Tilt_old)        Tilt(90)        logging.info('ortilt max')    elif (Tilt_old < -25):        Tilt_old = -25        server_log('ortilt',Tilt_old)        Tilt(-25)        logging.info('ortilt min')    else:        server_log('ortilt',  Tilt_old)        Tilt(Tilt_old)        logging.info('ortilt')def orzoom(msg):    global Zoom_old    Zoom_old = int(msg['orZoom']) - Zoom_old    print(Zoom_old)    server_log('orzoom', int(msg['orZoom']))    Zoom(Zoom_old)    Zoom_old = int(msg['orZoom'])    logging.info('orzoom')##  device action.def take_preview_photo():    im = datetime.datetime.now().strftime('/home/pi/immediate/PV.jpg')    save_photo = datetime.datetime.now().strftime(im)    fileName = datetime.datetime.now().strftime(save_photo)    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    dress = '/home/pi/immediate/'    for root, dirs, files in os.walk(dress):        print('files: {}'.format(len(files)))        if len(files) >= 1:            files.sort()            for f in files:                with open(os.path.join(root, f), "rb") as imageFile:                    str = base64.b64encode(imageFile.read())                url = impv_path                values = {'data': str, 'name': f}                data = urllib.parse.urlencode(values)                data = data.encode('utf-8')                req = urllib.request.Request(url, data)                req.add_header('User-Agent', 'Magic Browser')                resp = urllib.request.urlopen(req)                respData = resp.read()                #print(respData)                #os.remove(os.path.join(root, f))                print("ok")def ndvi():    fileName = datetime.datetime.now().strftime("/home/pi/n_image1/b.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/ir_image1/a.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    def main_n():        dress = '/home/pi/ir_image1/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'data_ira21': str, 'name_ira21': f, 'nr21': nr}                    data = urllib.parse.urlencode(values)                    data = data.encode('utf-8')                    req = urllib.request.Request(url, data)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                   # print(respData)                    os.remove(os.path.join(root, f))                    print("ok")    def main_ir():        dress = '/home/pi/n_image1/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'c_na21': str, 'name_na21': f, 'nr21': nr}                    c = urllib.parse.urlencode(values)                    c = c.encode('utf-8')                    req = urllib.request.Request(url, c)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")        # ---------------------------------------------------------------------------------------    main_n()    main_ir()def Pan(pan):    a = pan    if a == 360:        w = a - 1        a1 = w * 100        print(a1)        k = '{0:x}'.format(a1)        h = k.zfill(4)        print(h)        p3 = (h[0:2])        p4 = (h[2:])        str_10 = int(p3, 16)        str_10_2 = int(p4, 16)        sum_10 = (str_10 + str_10_2 + 76)        str_16 = hex(sum_10)        sum = (str_16[-2:])        str_10_sum = int(sum, 16)        SERIAL_PORT = '/dev/ttyS0'        ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)        Pan = [0xFF, 0x01, 0x00, 0x4B, str_10, str_10_2, str_10_sum]        ser.write(array.array('B', Pan).tostring())        print('left360')    elif 0 < a <= 359:        a1 = a * 100        print(a1)        k = '{0:x}'.format(a1)        h = k.zfill(4)        print(h)        p3 = (h[0:2])        p4 = (h[2:])        str_10 = int(p3, 16)        str_10_2 = int(p4, 16)        sum_10 = (str_10 + str_10_2 + 76)        str_16 = hex(sum_10)        sum = (str_16[-2:])        str_10_sum = int(sum, 16)        SERIAL_PORT = '/dev/ttyS0'        ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)        Pan = [0xFF, 0x01, 0x00, 0x4B, str_10, str_10_2, str_10_sum]        ser.write(array.array('B', Pan).tostring())        print('left')    elif a == 0:        SERIAL_PORT = '/dev/ttyS0'        ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)        Pan = [0xFF, 0x01, 0x00, 0x4B, 0x00, 0x00, 0x4C]        ser.write(array.array('B', Pan).tostring())        print('leftzore')def Tilt(tilt):    a = tilt    def up():        q = int(360)        a1 = (q - a) * 100        print(a1)        k = '{0:x}'.format(a1)        h = k.zfill(4)        print(h)        p3 = (h[0:2])        ##print(p3)        p4 = (h[2:])        ##print(p4)        str_10 = int(p3, 16)        str_10_2 = int(p4, 16)        sum_10 = (str_10 + str_10_2 + 78)        str_16 = hex(sum_10)        ##print(str_16)        sum = (str_16[-2:])        str_10_sum = int(sum, 16)        SERIAL_PORT = '/dev/ttyS0'        ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)        Pan = [0xFF, 0x01, 0x00, 0x4D, str_10, str_10_2, str_10_sum]        ser.write(array.array('B', Pan).tostring())        print('up')    def down():        k = abs(a)        a1 = k * 100        print (a1)        k = '{0:x}'.format(a1)        h = k.zfill(4)        print(h)        p3 = (h[0:2])        ##print(p3)        p4 = (h[2:])        ##print(p4)        str_10 = int(p3, 16)        str_10_2 = int(p4, 16)        sum_10 = (str_10 + str_10_2 + 78)        str_16 = hex(sum_10)        ##print(str_16)        sum = (str_16[-2:])        str_10_sum = int(sum, 16)        SERIAL_PORT = '/dev/ttyS0'        ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)        Pan = [0xFF, 0x01, 0x00, 0x4D, str_10, str_10_2, str_10_sum]        ser.write(array.array('B', Pan).tostring())        print('down')    if -1 < a <= 90:        up()    elif 0 > a >= -25:        down()def Zoom(zoom):    def Zoom1():        headers = {'Content-Type': 'text/xml'}        data = '<?xml version="1.0" encoding="utf-8"?><request><ptzcmd><protocol>0</protocol><cmd>0</cmd><addr>1</addr></</request>'        url = camera_zoomin        r = requests.post(url, headers=headers, data=data)        print (r.content)    def Zoom_1():        headers = {'Content-Type': 'text/xml'}        data = '<?xml version="1.0" encoding="utf-8"?><request><ptzcmd><protocol>0</protocol><cmd>0</cmd><addr>1</addr></</request>'        url = camera_zoomout        r = requests.post(url, headers=headers, data=data)        print (r.content)        print ('you')    a = zoom    print(a)    if (a == 0):        print("NO")    elif (a>0):        for i in range((10*a)):            Zoom1()    else:        a=-1*a        for i in range((10*a)):            Zoom_1()def ndvi1():    fileName = datetime.datetime.now().strftime("/home/pi/b1/b1.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/a1/a1.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    def main_n():        dress = '/home/pi/a1/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'data_ira21': str, 'name_ira21': f, 'nr21': nr}                    data = urllib.parse.urlencode(values)                    data = data.encode('utf-8')                    req = urllib.request.Request(url, data)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")    def main_ir():        dress = '/home/pi/b1/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'c_na21': str, 'name_na21': f, 'nr21': nr}                    c = urllib.parse.urlencode(values)                    c = c.encode('utf-8')                    req = urllib.request.Request(url, c)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")        # ---------------------------------------------------------------------------------------    main_n()    main_ir()def ndvi2():    fileName = datetime.datetime.now().strftime("/home/pi/b2/b2.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/a2/a2.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    def main_n():        dress = '/home/pi/a2/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'data_ira21': str, 'name_ira21': f, 'nr21': nr}                    data = urllib.parse.urlencode(values)                    data = data.encode('utf-8')                    req = urllib.request.Request(url, data)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")    def main_ir():        dress = '/home/pi/b2/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'c_na21': str, 'name_na21': f, 'nr21': nr}                    c = urllib.parse.urlencode(values)                    c = c.encode('utf-8')                    req = urllib.request.Request(url, c)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")        # ---------------------------------------------------------------------------------------    main_n()    main_ir()def ndvi3():    fileName = datetime.datetime.now().strftime("/home/pi/b3/b3.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/a3/a3.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    def main_n():        dress = '/home/pi/a3/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'data_ira21': str, 'name_ira21': f, 'nr21': nr}                    data = urllib.parse.urlencode(values)                    data = data.encode('utf-8')                    req = urllib.request.Request(url, data)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                   # print(respData)                    os.remove(os.path.join(root, f))                    print("ok")    def main_ir():        dress = '/home/pi/b3/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'c_na21': str, 'name_na21': f, 'nr21': nr}                    c = urllib.parse.urlencode(values)                    c = c.encode('utf-8')                    req = urllib.request.Request(url, c)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")        # ---------------------------------------------------------------------------------------    main_n()    main_ir()def ndvi4():    fileName = datetime.datetime.now().strftime("/home/pi/b4/b4.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/a4/a4.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    def main_n():        dress = '/home/pi/a4/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'data_ira21': str, 'name_ira21': f, 'nr21': nr}                    data = urllib.parse.urlencode(values)                    data = data.encode('utf-8')                    req = urllib.request.Request(url, data)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")    def main_ir():        dress = '/home/pi/b4/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'c_na21': str, 'name_na21': f, 'nr21': nr}                    c = urllib.parse.urlencode(values)                    c = c.encode('utf-8')                    req = urllib.request.Request(url, c)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")        # ---------------------------------------------------------------------------------------    main_n()    main_ir()def ndvi5():    fileName = datetime.datetime.now().strftime("/home/pi/b5/b5.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/a5/a5.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    def main_n():        dress = '/home/pi/a5/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'data_ira21': str, 'name_ira21': f, 'nr21': nr}                    data = urllib.parse.urlencode(values)                    data = data.encode('utf-8')                    req = urllib.request.Request(url, data)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                   # print(respData)                    os.remove(os.path.join(root, f))                    print("ok")    def main_ir():        dress = '/home/pi/b5/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'c_na21': str, 'name_na21': f, 'nr21': nr}                    c = urllib.parse.urlencode(values)                    c = c.encode('utf-8')                    req = urllib.request.Request(url, c)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")        # ---------------------------------------------------------------------------------------    main_n()    main_ir()def ndvi6():    fileName = datetime.datetime.now().strftime("/home/pi/b6/b6.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/a6/a6.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    def main_n():        dress = '/home/pi/a6/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'data_ira21': str, 'name_ira21': f, 'nr21': nr}                    data = urllib.parse.urlencode(values)                    data = data.encode('utf-8')                    req = urllib.request.Request(url, data)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")    def main_ir():        dress = '/home/pi/b6/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'c_na21': str, 'name_na21': f, 'nr21': nr}                    c = urllib.parse.urlencode(values)                    c = c.encode('utf-8')                    req = urllib.request.Request(url, c)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")        # ---------------------------------------------------------------------------------------    main_n()    main_ir()def ndvi7():    fileName = datetime.datetime.now().strftime("/home/pi/b7/b7.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/a7/a7.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    def main_n():        dress = '/home/pi/a7/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'data_ira21': str, 'name_ira21': f, 'nr21': nr}                    data = urllib.parse.urlencode(values)                    data = data.encode('utf-8')                    req = urllib.request.Request(url, data)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")    def main_ir():        dress = '/home/pi/b7/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'c_na21': str, 'name_na21': f, 'nr21': nr}                    c = urllib.parse.urlencode(values)                    c = c.encode('utf-8')                    req = urllib.request.Request(url, c)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")        # ---------------------------------------------------------------------------------------    main_n()    main_ir()def ndvi8():    fileName = datetime.datetime.now().strftime("/home/pi/b8/b8.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/a8/a8.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    def main_n():        dress = '/home/pi/a8/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'data_ira21': str, 'name_ira21': f, 'nr21': nr}                    data = urllib.parse.urlencode(values)                    data = data.encode('utf-8')                    req = urllib.request.Request(url, data)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")    def main_ir():        dress = '/home/pi/b8/'        for root, dirs, files in os.walk(dress):            print('files: {}'.format(len(files)))            if len(files) >= 1:                files.sort()                for f in files:                    with open(os.path.join(root, f), "rb") as imageFile:                        str = base64.b64encode(imageFile.read())                    url = ndvi_path                    nr = '21'                    values = {'c_na21': str, 'name_na21': f, 'nr21': nr}                    c = urllib.parse.urlencode(values)                    c =  c.encode('utf-8')                    req = urllib.request.Request(url, c)                    req.add_header('User-Agent', 'Magic Browser')                    resp = urllib.request.urlopen(req)                    respData = resp.read()                    print(os.path.join(root, f))                    #print(respData)                    os.remove(os.path.join(root, f))                    print("ok")        # ---------------------------------------------------------------------------------------    main_n()    main_ir()## Report the system information about this device to the server.def system_info():    # get firmware version from the file    fw_version = open('/etc/fw_version').readline().strip()    localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())     # message to be sent in JSON format    payload = {        'device_id': device_id,        'localtime': localtime,        'command': 'system_info',        'project': project_name,        'model': model_name,        'fw_version': fw_version,        'mqtt_sub_topic': mqtt_sub_topic,        'mqtt_pub_topic': mqtt_pub_topic    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)    logging.info('system info')## Update system firmware.# @param msg  [in] The message from the server in JSON format.def system_update(msg):    if (msg['filetype'] == 'img'):        # create a directory to store the firmware image        dirname = '/tmp/' + str(uuid.uuid1()) + '/'        filepath = dirname + 'update.img'        os.makedirs(dirname)        # start to download the firmware image        server_log('system_update', 'Downloading system firmware')        logging.info('system downloading')        urllib.urlretrieve(msg['url'], filepath)        # check the SHA256 checksum of the firmware image        if (msg['sha256sum'] == get_sha256sum(filepath)):            server_log('system_update', 'Updating system firmware')            logging.info('system update')            # start to upgrade the system firmware            os.system('sysupgrade -n ' + filepath)        else:            server_log('system_update', 'ERROR: SHA256 checksum is wrong')            logging.info('checksum wrong')            shutil.rmtree(dirname, ignore_errors=True)## The callback function for connecting.# @param client    [in] The client instance for this callback.# @param userdata  [in] The private user data as set in Client() or user_data_set().# @param flags     [in] Response flags sent by the broker.# @param rc        [in] The connection result.def on_connect(client, userdata, flags, rc):    # subscribe MQTT topic on connection    client.subscribe(mqtt_sub_topic, qos=2)    server_log('reboot | factory_reset', 'Boot completed')    logging.info('system running')## The callback function for processing messages from the server.# @param client    [in] The client instance for this callback.# @param userdata  [in] The private user data as set in Client() or user_data_set().# @param msg       [in] An instance of MQTT message.def on_message(client, userdata, msg):    # print(msg.payload)    msg.payload = msg.payload.decode('utf-8')    jsonmsg = json.loads(msg.payload)    #print(jsonmsg)    print('Received:')    print(json.dumps(jsonmsg, sort_keys=True, indent=4, separators=(',', ':')))    # processing the command from the server    if (jsonmsg['command'] == 'reboot'):        system_reboot()    elif (jsonmsg['command'] == 'factory_reset'):        factory_reset()    elif (jsonmsg['command'] == 'system_info'):        system_info()    elif (jsonmsg['command'] == 'scheduled_ndvi'):        if (jsonmsg['nr'] == "KDARES21"):            if (jsonmsg['position'] == '1'):                ndvi_1(jsonmsg)            elif (jsonmsg['position'] == '2'):                ndvi_2(jsonmsg)            elif (jsonmsg['position'] == '3'):                ndvi_3(jsonmsg)            elif (jsonmsg['position'] == '4'):                ndvi_4(jsonmsg)            elif (jsonmsg['position'] == '5'):                ndvi_5(jsonmsg)            elif (jsonmsg['position'] == '6'):                ndvi_6(jsonmsg)            elif (jsonmsg['position'] == '7'):                ndvi_7(jsonmsg)            elif (jsonmsg['position'] == '8'):                ndvi_8(jsonmsg)    elif (jsonmsg['command'] == 'manual_ndvi'):        manual_ndvi()    elif (jsonmsg['command'] == 'tilt'):        tilt(jsonmsg)    elif (jsonmsg['command'] == 'pan'):        pan(jsonmsg)    elif (jsonmsg['command'] == 'zoom'):        zoom(jsonmsg)    elif (jsonmsg['command'] == 'p1_preview_photo'):        p1_preview_photo()    elif (jsonmsg['command'] == 'p2_preview_photo'):        p2_preview_photo()    elif (jsonmsg['command'] == 'p3_preview_photo'):        p3_preview_photo()    elif (jsonmsg['command'] == 'p4_preview_photo'):        p4_preview_photo()    elif (jsonmsg['command'] == 'p5_preview_photo'):        p5_preview_photo()    elif (jsonmsg['command'] == 'p6_preview_photo'):        p6_preview_photo()    elif (jsonmsg['command'] == 'p7_preview_photo'):        p7_preview_photo()    elif (jsonmsg['command'] == 'p8_preview_photo'):        p8_preview_photo()    elif (jsonmsg['command'] == 'system_update'):        system_update(jsonmsg)    else:        server_log(jsonmsg['command'], 'ERROR: Unknown command')## A thread used to subscribe to and wait for messages from the server.def thread_job():    # create a MQTT client with a user name and password to subscribe to the messages    mqtt_thread_client = mqtt.Client()    mqtt_thread_client.on_connect = on_connect    mqtt_thread_client.on_message = on_message    mqtt_thread_client.username_pw_set(username='aisky-client', password='aiskyc')    mqtt_thread_client.connect(mqtt_server, mqtt_port, mqtt_alive)    mqtt_thread_client.loop_forever()# create a MQTT client with a user name and password to publish messagesmqtt_client = mqtt.Client()mqtt_client.username_pw_set(username='aisky-client', password='aiskyc')mqtt_client.connect(mqtt_server, mqtt_port, mqtt_alive)# create a thread to subscribe to and wait for messages from the servermqtt_subscribe_thread = threading.Thread(target=thread_job)mqtt_subscribe_thread.start()mqtt_client.loop_forever()
 |