#!/usr/bin/env python3.5
import paho.mqtt.client as mqtt
import time
import sys
import http.client, urllib
import json
import threading
import os
import shutil
import uuid
import hashlib
import serial
import array
import base64
import urllib.request
import datetime
import requests
import logging



""" Device Information - the information about this device
These device information is used for the MQTT topic. This program will subscribe and publish to
the 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. The
commands 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 AppleFarm
Setup the 'model' variable: The following command sets the 'model' variable to MK-G.
    root@mylinkit:~# fw_setenv model MK-G
Then, the following command can be used to display the u-boot environment variables.
    root@mylinkit:~# fw_printenv
"""

""" MQTT Server
If you don't have your own MQTT server, you can use the public MQTT server 'iot.eclipse.org'. But
with 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 = 1883
mqtt_alive = 60
# camera API command
camera_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 path
picture_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_id
mqtt_pub_topic = mqtt_sub_topic + "/Log"

##nr
nr = "GTW009002014"

##angle
Tilt_old = 0
Pan_old = 0
Zoom_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 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 KDAIS14 --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')

def timecheck(msg):
    x = datetime.datetime.now()
    x.year
    x.month
    x.day
    x.hour
    x.minute
    x.second
    print(x.year,x.month,x.day,x.hour,x.minute,x.second)
    req = requests.get('http://169.254.185.181/cgi-bin/date_cgi?action=set&user=admin&pwd=abcd1234&year=%d&month=%d&day=%d&hour=%d&minute=%d&second=%d&timezone=31'%(x.year,x.month,x.day,x.hour,x.minute,x.second))
    server_log('a055', 'timecheck')

## 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 = '14'
                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 ='14'
                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)
    server_log('a052','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 = '14'
                    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 = '14'
                    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 = '14'
                    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 = '14'
                    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['command'] == 'a055'):
        timecheck(jsonmsg)
    elif (jsonmsg['node_id'] == "GTW009002014"):
        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 messages
mqtt_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 server
mqtt_subscribe_thread = threading.Thread(target=thread_job)
mqtt_subscribe_thread.start()

mqtt_client.loop_forever()