| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817 | #!/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 loggingimport cv2import socketimport mathimport pickle""" 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 = "60.250.156.234"mqtt_port = 1883mqtt_alive = 60# camera API commandcamera_ircut_high = 'http://169.254.185.181/cgi-bin/camerasetting_cgi?action=set&channel=0&user=admin&pwd=abcd1234&TRCutLevel=high'camera_ircut_low = 'http://169.254.185.181/cgi-bin/camerasetting_cgi?action=set&channel=0&user=admin&pwd=abcd1234&TRCutLevel=low'camera_image = 'http://169.254.185.181/cgi-bin/images_cgi?channel=0&user=admin&pwd=abcd1234'camera_zoomin = "http://169.254.185.181/cgi-bin/ptz_cgi?action=ZoomAdd&user=admin&pwd=abcd1234"camera_zoomout = "http://169.254.185.181/cgi-bin/ptz_cgi?action=ZoomSub&user=admin&pwd=abcd1234"#php pathpicture_path = 'http://60.250.156.234/cust/c1.php'reboot_path ="http://www.aisky.com.tw/field/status.php"#log# @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 = "GTW009002010"##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, rqnn):    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,        'node_id': nr,        'command': command,        'rqnn': rqnn    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)def call_log(command,msg,rqnn):    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,        'node_id': nr,        'command': command,        'position':msg['position'],        'time':msg['time'],        'rqnn': rqnn    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)def parameter_log(command,msg,rqnn):    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,        'node_id': nr,        'command': command,        'position': msg['position'],        'time': msg['time'],        'Pan':  msg['orPan'],        'Tilt': msg['orTilt'],        'Zoom': msg['orZoom'],        'rqnn': rqnn,    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)def preview_photo_log(command,msg,rqnn):    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,        'node_id': nr,        'command': command,        'position':msg['position'],        'rqnn': rqnn    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)def ndvi_log(command,msg,size1,size2,rqnn):    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,        'node_id': nr,        'command': command,        'position':msg['position'],        'time':msg['time'],        'filename':msg['filename'],        'a': size1,        'b': size2,        'rqnn': rqnn,    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)def tilt_log(command,msg,rqnn):    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,        'node_id': nr,        'command': command,        'tilt':msg['Tilt'],        'rqnn': rqnn    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)def pan_log(command,msg,rqnn):    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,        'node_id': nr,        'command': command,        'pan':msg['Pan'],        'rqnn': rqnn    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)def zoom_log(command,msg,rqnn):    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,        'node_id': nr,        'command': command,        'zoom':msg['Zoom'],        'rqnn': rqnn    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)def zoom0_log(command,msg,rqnn):    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,        'node_id': nr,        'command': command,        'tilt':msg['Tilt'],        'pan':msg['Pan'],        'zoom':msg['Zoom'],        'rqnn': rqnn    }    jsonobj = json.dumps(payload, sort_keys=True, indent=4)    mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)    print('Sent:')    print(jsonobj)def get_ip_address(ifname):    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    try:        return socket.inet_ntoa(fcntl.ioctl(            s.fileno(),            0x8915,  # SIOCGIFADDR            struct.pack('256s', ifname[:15])        )[20:24])    except:        return ""## Reset this device.def system_reboot():    server_log('a035', '1')    time.sleep(5)    os.system('sudo reboot')    time.sleep(10)def system_update_code():    os.system('sudo su')    os.system('rm -rf /home/pi/KDAIS')    os.system('git clone -b KDAIS10 --single-branch http://60.250.156.230:3000/fatwolf/KDAIS.git /home/pi/KDAIS')    time.sleep(5)    os.system('cp /home/pi/KDAIS/aisky-mqttd /usr/sbin/')    time.sleep(2)    os.system('sudo chmod 777 /usr/sbin/aisky-mqttd')    time.sleep(5)    server_log('a033', '1')    os.system('sudo reboot')    time.sleep(10)def stream0(msg):    os.system('sudo su')    os.system('cd /hmoe/pi')    os.system('sudo nohup python3.5 /home/pi/udp_client.py>/home/pi/nohup.out 2>&1 &')    time.sleep(2)    server_log('a053', '1')def stream1(msg):    os.system('sudo su')    os.system("ps aux | grep /home/pi/udp_client.py | awk '{print $2}' | xargs kill -9")    time.sleep(2)    server_log('a054', '1')## Receive the system action  to this device .def call(msg):    print("call  ok")    call_log('a000',msg, '1')def parameter_setting(msg):    print(msg['Pan'])    print(msg['Tilt'])    print(msg['Zoom'])    print(msg['position'])    pan(msg)    tilt(msg)    zoom(msg)    time.sleep(2)    print("NDVI 1 angle  ok")    parameter_log('a050',msg,'1')def take_preview_photo(msg):    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 = picture_path                nr = '10'                values = {'data': str, 'name': f,'nr':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(respData)                #os.remove(os.path.join(root, f))                print("ok")    preview_photo_log('a018',msg,'1')    print("take_preview_photo ok")def preview_photo(msg):    print("ok")    req = requests.get(camera_ircut_low)    fileName = datetime.datetime.now().strftime("/home/pi/p"+msg['position']+"/"+msg['position']+".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/p'+msg['position']+'/'    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 = picture_path                nr = '10'                values = {'p': str, 'p_name':msg['position'],'nr':nr}                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")    preview_photo_log('a018',msg,'1')    print("preview_photo ok")def tilt(msg):    Tilt(int(msg['Tilt']))    tilt_log('a014',msg,'1')def pan(msg):    if(0<=int(msg['Pan'])<30):       Pan((int(msg['Pan'])+330))    if(int(msg['Pan'])==30):       Pan(359)    if(30<int(msg['Pan'])<=355):       Pan((int(msg['Pan'])-30))    pan_log('a012',msg,'1')def zoom(msg):    Zoom(int(msg['Zoom']))    zoom_log('a016',msg,'1')def zoom0(msg):    Tilt(0)    Pan(330)    Zoom(-5)    zoom0_log('a052',msg,'1')##  device action.def Pan(pan):    if 0<pan<=359:       a = pan       a1 = 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 + 76)       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=10)       Pan = [0xFF, 0x01, 0x00,0x4B, str_10, str_10_2, str_10_sum]       print(Pan)       ser.write(array.array('B', Pan).tostring())       print('left')    elif a == 0:        SERIAL_PORT = '/dev/ttyS0'        ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=10)        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]        print(Pan)        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]        print(Pan)        ser.write(array.array('B', Pan).tostring())        print('down')    if 0 <= 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(a):            time.sleep(1)            for j in range(10):                   Zoom1()    else:        a=-1*a        for i in range(a):            time.sleep(1)            for j in range(10):                   Zoom_1()def manual_ndvi(msg):    req = requests.get(camera_ircut_high)    time.sleep(2)    fileName = datetime.datetime.now().strftime("/home/pi/ir_image1/"+msg['filename']+"a.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    path1 = '/home/pi/ir_image1/'+msg['filename']+'a.tif'    size1 = os.path.getsize(path1)    print(size1)    req = requests.get(camera_ircut_low)    time.sleep(2)    fileName = datetime.datetime.now().strftime("/home/pi/n_image1/"+msg['filename']+"b.tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    path2 = '/home/pi/n_image1/'+msg['filename']+'b.tif'    size2 = os.path.getsize(path2)    print(size2)    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 = picture_path                    nr = '10'                    values = {'data_ira': str, 'name_ira': f, 'nr': 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 = picture_path                    nr = '10'                    values = {'c_na': str, 'name_na': f, 'nr': 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()    print("NDVI  ok")    ndvi_log('a051',msg,size1,size2,'1')def ndvi(msg):    req = requests.get(camera_ircut_high)    time.sleep(2)    fileName = datetime.datetime.now().strftime("/home/pi/a"+msg['position']+"/"+msg['filename']+"a"+msg['position']+".tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    path1 = '/home/pi/a'+msg['position']+'/'+msg['filename']+'a'+msg['position']+'.tif'    size1 = os.path.getsize(path1)    print(size1)    req = requests.get(camera_ircut_low)    time.sleep(2)    fileName = datetime.datetime.now().strftime("/home/pi/b"+msg['position']+"/"+msg['filename']+"b"+msg['position']+".tif")    req = requests.get(camera_image)    file = open(fileName, 'wb')    for chunk in req.iter_content(100000):        file.write(chunk)    file.close()    path2 = '/home/pi/b'+msg['position']+'/'+msg['filename']+'b'+msg['position']+'.tif'    size2 = os.path.getsize(path2)    print(size2)    def main_n():        dress = '/home/pi/a'+msg['position']+'/'        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 = picture_path                    nr = '10'                    values = {'data_ira': str, 'name_ira': f, 'nr': 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/b'+msg['position']+'/'        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 = picture_path                    nr = '10'                    values = {'c_na': str, 'name_na': f, 'nr': 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()    print("NDVI  ok")    ndvi_log('a051',msg,size1,size2,'1')## 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('a035', '1')    logging.info('system running')    data = {'nr': nr, 'status': 'reboot'}    data = urllib.parse.urlencode(data)    data = data.encode('utf-8')    req = urllib.request.Request(reboot_path, data)    req.add_header('User-Agent', 'Magic Browser')    resp = urllib.request.urlopen(req)    respData = resp.read()    print("reboot check  ok")## 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'] == 'a035'):        system_reboot()    elif (jsonmsg['command'] == 'a033'):        system_update_code()    elif (jsonmsg['command'] == 'vpn_connect'):        vpn_connect()    elif (jsonmsg['command'] == 'vpn_disconnect'):        vpn_disconnect()    elif (jsonmsg['node_id'] == "GTW009002010"):        if (jsonmsg['command'] == 'a000'):            call(jsonmsg)        elif (jsonmsg['command'] == 'a050'):            parameter_setting(jsonmsg)        elif (jsonmsg['command'] == 'a051'):            if (jsonmsg['position'] == '0'):                manual_ndvi(jsonmsg)            else:                ndvi(jsonmsg)        elif (jsonmsg['command'] == 'a014'):            tilt(jsonmsg)        elif (jsonmsg['command'] == 'a012'):            pan(jsonmsg)        elif (jsonmsg['command'] == 'a016'):            zoom(jsonmsg)        elif (jsonmsg['command'] == 'a052'):            zoom0(jsonmsg)        elif (jsonmsg['command'] == 'a053'):            stream0(jsonmsg)        elif (jsonmsg['command'] == 'a054'):            stream1(jsonmsg)        elif (jsonmsg['command'] == 'a018'):            if (jsonmsg['position'] == '0'):                take_preview_photo(jsonmsg)            else:                preview_photo(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()
 |