#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
import sys
import urllib
import json
import threading
import os
import shutil
import uuid
import hashlib
import serial
import array
import numpy
import base64
import datetime
import requests
import numpy as np
import pymysql.cursors
import sqlite3
import subprocess
""" 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 = "Coffee"
model_name = "MK-G"
#device_id = open('/sys/class/net/eth0/address').readline().strip()
device_id = "b8:27:eb:7e:24:78"
""" 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

# @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"


validation = 0
number = 1
r_humidity = 0
r_air_temp = 0
r_ph = 0
r_TDS1 = 0
r_CO2 = 0
r_sonic = 0
r_atmospheric = 0
i=0
j=0
count=0
vacuum_value=0
threewayvalve_value=0
diskvalve_value=0
solenoid_disinfect_value=0
solenoid_water_value=0
motor_value=0
blower_value=0
heater1_value=0
heater2_value=0
vacuum_value1=0
vacuum_value2=0

input_vacuum_value1=0
input_vacuum_value2=0
air_temp1_value=0
air_temp1_enable_value=0
arr=[]
x=0

#乾燥槽狀態
dryer_motor_value=[0,0,0,0,0,0,0,0,0,0,0,0]
dryer_diskvalve_value=[0,0,0,0,0,0,0,0,0,0,0,0]
dryer_temp_value=[0,0,0,0,0,0,0,0,0,0,0,0]
dryer_temp_enable_value=[0,0,0,0,0,0,0,0,0,0,0,0]
dryer_blower_value=[0,0,0,0,0,0,0,0,0,0,0,0]
dryer_heater1_value=[0,0,0,0,0,0,0,0,0,0,0,0]
dryer_heater2_value=[0,0,0,0,0,0,0,0,0,0,0,0]
dryer_solenoid_disinfect=[0,0,0,0,0,0,0,0,0,0,0,0]
dryer_solenoid_water_value=[0,0,0,0,0,0,0,0,0,0,0,0]
dryer_vacuum_value=[0,0,0,0,0,0,0,0,0,0,0,0]
#發酵槽狀態
ferment_temp=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_temp_enable=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_motor_value=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_diskvalve_value=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_solenoid_disinfect=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_pump_sensor=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_solenoid_tank_pump=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_solenoid_water_in=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_outer_solenoid_water=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_tank_solenoid_water_out=[0,0,0,0,0,0,0,0,0,0,0,0]
ferment_outer_threewayvalve_float=[0,0,0,0,0,0,0,0,0,0,0,0]
#清洗槽狀態
clean_stepping_motor_value=[0,0,0,0,0,0,0,0,0,0,0,0]
clean_pump_waterL2L3_value=[0,0,0,0,0,0,0,0,0,0,0,0]
clean_pump_waterL4L5_value=[0,0,0,0,0,0,0,0,0,0,0,0]
clean_pump_waterInput_value=[0,0,0,0,0,0,0,0,0,0,0,0]
clean_solenoid_waterL3_value=[0,0,0,0,0,0,0,0,0,0,0,0]
clean_solenoid_waterL5_value=[0,0,0,0,0,0,0,0,0,0,0,0]
clean_vacuum_value=[0,0,0,0,0,0,0,0,0,0,0,0]
#脫皮機狀態
peel_motor_value=[0,0,0,0,0,0,0,0,0,0,0,0]
peel_vacuum_value=[0,0,0,0,0,0,0,0,0,0,0,0]
#path = "http://13.113.114.87/20200312/tofitolab.php"

## 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 used_com1port():
    global ser
    #UART串口設定
    ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
    #ZIGBEE串口設定
    #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
def used_com2port():
    global ser
    #UART串口設定
    #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
    #ZIGBEE串口設定
    #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
def used_com3port():
    global ser
    #UART串口設定
    ser = serial.Serial('/dev/ttyUSB2', 115200, timeout=1)
    #ZIGBEE串口設定
    #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
def used_com4port():
    global ser
    #UART串口設定
    #ser = serial.Serial('/dev/ttyUSB1', 115200, timeout=1) 
    #ZIGBEE串口設定
    #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)   
#MQTT回覆
def server_log(command,number,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,
        'tank_number':number,
        '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)

def sql_local_upload(command):
     conn = sqlite3.connect('/home/pi/coffee.db')
     c = conn.cursor()
     c.execute("UPDATE coffee set command = '%s' where sn=1"\
          %(command))
     conn.commit()
     conn.close()

def sql_local_pin_configuration_upload(msg):
     conn = sqlite3.connect('/home/pi/coffee.db')
     c = conn.cursor()
     c.execute("UPDATE pin_configuration set M4 = '%s' ,M10 = '%s', M16 = '%s', M5 = '%s',M2 = '%s',M17 = '%s',M7 = '%s',M3 = '%s',M18 = '%s',M6 = '%s',M9 = '%s',M14 = '%s',M15 = '%s',M13 = '%s',M12 = '%s',M11 = '%s',M8 = '%s',M1 = '%s',M19 = '%s',zigbee = '%s',wifi = '%s',ethernet = '%s',SD = '%s',relay1 = '%s',relay2 = '%s',relay3 = '%s',relay4 = '%s',relay5 = '%s',relay6 = '%s',relay7 = '%s',relay8 = '%s',relay9 = '%s',relay10 = '%s',relay11 = '%s',relay12 = '%s',relay13 = '%s',relay14 = '%s',relay15 = '%s',relay16 = '%s',relay17 = '%s',relay18 = '%s',relay19 = '%s',relay20 = '%s' where sn=1"\
          %(msg['M4'] , msg['M10'] ,msg['M16'] , msg['M5'], msg['M2'], msg['M17'], msg['M7'], msg['M3'], msg['M18'], msg['M6'], msg['M9'], msg['M14'], msg['M15'], msg['M13'], msg['M12'], msg['M11'], msg['M8'], msg['M1'], msg['M19'], msg['zigbee'], msg['wifi'], msg['ethernet'], msg['SD'], msg['relay1'], msg['relay2'], msg['relay3'], msg['relay4'], msg['relay5'], msg['relay6'], msg['relay7'], msg['relay8'], msg['relay9'], msg['relay10'], msg['relay11'], msg['relay12'], msg['relay13'], msg['relay14'], msg['relay15'], msg['relay16'], msg['relay17'], msg['relay18'], msg['relay19'], msg['relay20']))
     conn.commit()
     conn.close()


def sql_local_pin_configuration(msg):
     localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
     for i in range (len(msg['pin'])):
      conn = sqlite3.connect('/home/pi/coffee.db')
      c = conn.cursor()
      c.execute("INSERT INTO pin (time,pin_nr,pin_position,pin_type) \
      VALUES ('%s','%s','%s','%s')"
      %(localtime,msg['pin'][i]['pin_nr'],msg['pin'][i]['pin_position'], msg['pin'][i]['pin_type']))
      conn.commit()
      conn.close()
     print("end")
     server_log(msg['command'],"D1","ok")

def sql_local_add_cond_code_upload(msg):
     for i in range (len(msg['cond'])):
      for j in range (len(msg['cond'][i]['cond_add'])):
       add=msg['cond'][i]['cond_add'][j].split(" ")
       conn = sqlite3.connect('/home/pi/coffee.db')
       c = conn.cursor()
       c.execute("INSERT INTO add_cond_code (time,cont,cond_d1_2,cond_a1_2,cond_b1_2,cond_c1_2) \
       VALUES ('%s','%d','%s','%s', '%s', '%s')"
       %(localtime,i+1,add[0],add[1], add[2],add[3]))
       conn.commit()
       conn.close()
     print("end")
     server_log('cond_add_code_upload',msg['cond_tank1_1'],"ok")
     
     
def sql_local_act_code_upload(msg):
     for i in range (len(msg['cond'])):
      for j in range (len(msg['cond'][i]['cond_com'])):
       com=msg['cond'][i]['cond_com'][j].split(" ")
       conn = sqlite3.connect('/home/pi/coffee.db')
       c = conn.cursor()
       c.execute("INSERT INTO act_code (time,cont,do_obj1_1,act) \
       VALUES ('%s','%d','%s','%s')"
       %(localtime,i+1,com[0],com[1]))
       conn.commit()
       conn.close()
     print("end")
     server_log('act_code_upload',msg['cond_tank1_1'],"ok")



def sql_local_code_upload(msg):
     print(msg['cond'])
     print(msg['cond'][0]['cond_main'])
     print(msg['cond'][0]['cond_add'])
     print(len(msg['cond'][0]['cond_add']))
     print(msg['cond'][0]['cond_com'][0])
     print(len(msg['cond'][0]['cond_com']))
     localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
     for i in range (len(msg['cond'])):
      m=msg['cond'][i]['cond_main'].split(" ")
      print(m[0])
      print(m[1])
      if(m[0]=="else" and m[1]=="if"):
         print("ok")
         m[0]=m[0]+" "+m[1]
         m[1]=m[2]
         m[2]=m[3]
         m[3]=m[4]
         m[4]=m[5]
      conn = sqlite3.connect('/home/pi/coffee.db')
      c = conn.cursor()
      c.execute("INSERT INTO cond_code (time,cont,cond_tank1_1,cond_z1_1,cond_a1_1,cond_b1_1,cond_c1_1) \
      VALUES ('%s','%d','%s','%s', '%s', '%s', '%s')"
      %(localtime,i+1,m[1],m[0],m[2], m[3], m[4]))
      conn.commit()
      conn.close()
     for i in range (len(msg['cond'])):
      for j in range (len(msg['cond'][i]['cond_add'])):
       add=msg['cond'][i]['cond_add'][j].split(" ")
       conn = sqlite3.connect('/home/pi/coffee.db')
       c = conn.cursor()
       c.execute("INSERT INTO add_cond_code (time,cont,cond_d1_2,cond_a1_2,cond_b1_2,cond_c1_2) \
       VALUES ('%s','%d','%s','%s', '%s', '%s')"
       %(localtime,i+1,add[0],add[1], add[2],add[3]))
       conn.commit()
       conn.close()
     for i in range (len(msg['cond'])):
      for j in range (len(msg['cond'][i]['cond_com'])):
       com=msg['cond'][i]['cond_com'][j].split(" ")
       conn = sqlite3.connect('/home/pi/coffee.db')
       c = conn.cursor()
       c.execute("INSERT INTO act_code (time,cont,do_obj1_1,act) \
       VALUES ('%s','%d','%s','%s')"
       %(localtime,i+1,com[0],com[1]))
       conn.commit()
       conn.close()
     print("end")
     server_log(msg['command'],"D1","ok")
     
     
     

     

def sql_upload(command,value):
    global vacuum_value
    global threewayvalve_value
    global diskvalve_value
    global solenoid_disinfect_value
    global solenoid_water_value
    global motor_value
    global blower_value
    global heater1_value
    global heater2_value
    global air_temp1_value
    global air_temp1_enable_value
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print (datetime)
    conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
                           charset='utf8')
    a = conn.cursor()
 
    if (command == 'temp1'):
        temp1_value = value
    elif (command == 'temp1_enable'):
        temp1_enable_value = value
    elif (command  == 'tank_motor_status'):
        motor_value = value
    elif (command  == 'tank_diskvalve_status'):
        diskvalve_value = value
    elif (command  == 'tank_blower_status'):
        blower_value = value
    elif (command == 'tank_heater1_status'):
        heater1_value = value
    elif (command  == 'tank_heater2_status'):
        heater2_value = value
    elif (command  == 'tank_threewayvalve_status'):
        threewayvalve_value = value
    elif (command  == 'tank_solenoid_disinfect_status'):
        solenoid_disinfect_value = value
    elif (command  == 'outer_solenoid_water_status'):
        solenoid_water_value = value
    elif (command  == 'outer_threewayvalve_float_status'):
        vacuum_value = value
    print(
        datetime, vacuum_value, threewayvalve_value, diskvalve_value, solenoid_disinfect_value, solenoid_water_value,
        motor_value, blower_value, heater1_value, heater2_value,air_temp1_enable_value,air_temp1_value)
    sqlStuff = "INSERT INTO  dry_tank_brake (datetime,vacuum,threewayvalve,diskvalve,solenoid_disinfect,solenoid_water,motor,blower,heater1,heater2,temp1_enable,temp1) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    data = [(datetime, vacuum_value, threewayvalve_value, diskvalve_value, solenoid_disinfect_value,
             solenoid_water_value, motor_value, blower_value, heater1_value, heater2_value,air_temp1_enable_value,air_temp1_value)]
    a.executemany(sqlStuff, data)
    conn.commit()

#發酵槽資料表
def ferment_sql_upload(command,tank_num,number,value):
    global ferment_temp
    global ferment_temp_enable
    global ferment_motor_value
    global ferment_diskvalve_value
    global ferment_solenoid_disinfect
    global ferment_pump_sensor
    global ferment_solenoid_tank_pump
    global ferment_solenoid_water_in
    global ferment_outer_solenoid_water
    global ferment_tank_solenoid_water_out
    global ferment_outer_threewayvalve_float
           
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print (datetime)
    conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
                           charset='utf8')
    a = conn.cursor()
    if (command == 'tank_temp'):
        ferment_temp[number-1] = value
    if (command == 'tank_temp_enable'):
        ferment_temp_enable[number-1] = value
    if (command == 'tank_motor_status'):
        ferment_motor_value[number-1] = value
    elif (command  == 'tank_diskvalve_status'):
        ferment_diskvalve_value[number-1] = value
    elif (command  == 'tank_solenoid_disinfect_status'):
        ferment_solenoid_disinfect[number-1] = value
    elif (command  == 'tank_pump_sensor_status'):
        ferment_pump_sensor[number-1] = value
    elif (command  == 'solenoid_tank_pump_status'):
        ferment_solenoid_tank_pump[number-1] = value
    elif (command  == 'tank_solenoid_water_in_status'):
        ferment_solenoid_water_in[number-1] = value
    elif (command  == 'outer_solenoid_water_status'):
        ferment_outer_solenoid_water[number-1] = value
    elif (command  == 'outer_threewayvalve_float_status'):
        ferment_outer_threewayvalve_float[number-1] = value  
    elif (command  == 'tank_solenoid_water_out_status'):
        ferment_tank_solenoid_water_out[number-1] = value      
    sqlStuff = "INSERT INTO   ferment_tank_actuator (datetime,tank_num,vacuum,threewayvalve_input,diskvalve,solenoid_tank_pump,solenoid_tank_disinfect,solenoid_outer_water,solenoid_tank_water_in,solenoid_tank_water_out,pump_sensor,threewayvalve_outer_float,motor,heater1,heater2,temp_enable,temp) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    data = [(datetime,tank_num,0,0,ferment_diskvalve_value[number-1],ferment_solenoid_tank_pump[number-1],ferment_solenoid_disinfect[number-1],ferment_outer_solenoid_water[number-1],ferment_solenoid_water_in[number-1],ferment_tank_solenoid_water_out[number-1],ferment_pump_sensor[number-1],ferment_outer_threewayvalve_float[number-1],ferment_motor_value[number-1],0,0,ferment_temp_enable[number-1],ferment_temp[number-1])]
    a.executemany(sqlStuff, data)
    conn.commit()
#乾燥槽資料表
def dryer_sql_upload(command,tank_num,number,value):
    global dryer_temp_value
    global dryer_temp_enable_value
    global dryer_motor_value
    global dryer_diskvalve_value
    global dryer_blower_value
    global dryer_heater1_value
    global dryer_heater2_value
    global dryer_solenoid_disinfect
    global dryer_solenoid_water_value
    global dryer_vacuum_value

    
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print (datetime)
    conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
                           charset='utf8')
    a = conn.cursor()
    if (command == 'tank_temp'):
        dryer_temp_value[number-1] = value
    elif (command == 'tank_temp_enable'):
        dryer_temp_enable_value[number-1] = value
    elif (command == 'tank_motor_status'):
        dryer_motor_value[number-1] = value
    elif (command  == 'tank_diskvalve_status'):
        dryer_diskvalve_value[number-1] = value
    elif (command  == 'tank_blower_status'):
        dryer_blower_value[number-1] = value
    elif (command == 'tank_heater1_status'):
        dryer_heater1_value[number-1] = value
    elif (command  == 'tank_heater2_status'):
        dryer_heater2_value[number-1] = value
    elif (command  == 'tank_solenoid_disinfect_status'):
        dryer_solenoid_disinfect[number-1] = value
    elif (command  == 'tank_solenoid_water_status'):
        dryer_solenoid_water_value[number-1] = value
    elif (command  == 'tank_vacuum_status'):
        dryer_vacuum_value[number-1] = value
        print(datetime,tank_num,dryer_motor_value[number-1],dryer_diskvalve_value[number-1])
    sqlStuff = "INSERT INTO  dry_tank_brake (datetime,tank_num,vacuum,threewayvalve,diskvalve,solenoid_disinfect,solenoid_water,motor,blower,heater1,heater2,temp1_enable,temp1) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    data = [(datetime,tank_num,dryer_vacuum_value[number-1],0,dryer_diskvalve_value[number-1],dryer_solenoid_disinfect[number-1],dryer_solenoid_water_value[number-1],dryer_motor_value[number-1],dryer_blower_value[number-1],dryer_heater1_value[number-1],dryer_heater2_value[number-1],dryer_temp_enable_value[number-1],dryer_temp_value[number-1])]
    a.executemany(sqlStuff, data)
    conn.commit()
#清洗槽資料表
def clean_sql_upload(command,tank_num,number,value):
    global clean_stepping_motor_value
    global clean_pump_waterL2L3_value
    global clean_pump_waterL4L5_value
    global clean_pump_waterInput_value
    global clean_solenoid_waterL3_value
    global clean_solenoid_waterL5_value
    global clean_vacuum_value

    
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print (datetime)
    conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
                           charset='utf8')
    a = conn.cursor()
    if (command == 'step_motor_status'):
        clean_stepping_motor_value[number-1] = value
    elif (command == 'tank_pump_waterL4L5_status'):
        clean_pump_waterL4L5_value[number-1] = value
    elif (command == 'tank_pump_waterInput_status'):
        clean_pump_waterInput_value[number-1] = value
    elif (command  == 'tank_pump_waterL2L3_status'):
        clean_pump_waterL2L3_value[number-1] = value
    elif (command  == 'tank_solenoid_waterL2L3_status'):
        clean_solenoid_waterL3_value[number-1] = value
    elif (command == 'tank_solenoid_waterL4L5_status'):
        clean_solenoid_waterL5_value[number-1] = value
    elif (command  == 'tank_vacuum_status'):
        clean_vacuum_value[number-1] = value
    sqlStuff = "INSERT INTO  clean_tank_actuator (datetime,tank_num,vacuum,pump_waterInput,pump_waterL2L3,pump_waterL4L5,solenoid_waterL2L3,solenoid_waterL4L5,stepping_motor) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    data = [(datetime,tank_num,clean_vacuum_value[number-1],clean_pump_waterInput_value[number-1],clean_pump_waterL2L3_value[number-1],clean_pump_waterL4L5_value[number-1],clean_solenoid_waterL3_value[number-1],clean_solenoid_waterL5_value[number-1],clean_stepping_motor_value[number-1])]
    a.executemany(sqlStuff, data)
    conn.commit()
#脫皮機資料表
def peel_sql_upload(command,tank_num,number,value):
    global peel_motor_value
    global peel_vacuum_value
    
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print (datetime)
    conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
                           charset='utf8')
    a = conn.cursor()
    if (command == 'tank_motor_status'):
        peel_motor_value[number-1] = value
    elif (command  == 'tank_vacuum_status'):
        peel_vacuum_value[number-1] = value
    sqlStuff = "INSERT INTO  peel_tank_actuator (datetime,tank_num,vacuum,motor) VALUES (%s,%s,%s,%s)"
    data = [(datetime,tank_num,peel_vacuum_value[number-1],peel_motor_value[number-1])]
    a.executemany(sqlStuff, data)
    conn.commit()           
#乾燥槽入料儲豆槽資料表   
def sql_dry_input_brake(command,number,value):
        global vacuum_value1
        datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print (datetime)
        conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',database='Coffee', charset='utf8')
        a = conn.cursor()
        vacuum_value1 = int(value)
        sqlStuff = "INSERT INTO  dry_input_brake (datetime,vacuum) VALUES (%s,%s)"
        data = [(datetime,vacuum_value1)]
        a.executemany(sqlStuff, data)
        conn.commit()
#乾燥槽出料儲豆槽資料表         
def sql_dry_output_brake(command,number,value):
        global vacuum_value2
        datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print (datetime)
        conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',database='Coffee', charset='utf8')
        a = conn.cursor()
        vacuum_value2 = int(value)
        sqlStuff = "INSERT INTO  dry_output_brake (datetime,vacuum) VALUES (%s,%s)"
        data = [(datetime,vacuum_value2)]
        a.executemany(sqlStuff, data)
        conn.commit()
#發酵槽入料儲豆槽資料表
def sql_ferment_input_brake(command,tank_num,number,value):
        global input_vacuum_value1
        datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print (datetime)
        conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',database='Coffee', charset='utf8')
        a = conn.cursor()
        vacuum_value1 = int(value)
        sqlStuff = "INSERT INTO  ferment_input_actuator (datetime,tank_num,vacuum) VALUES (%s,%s,%s)"
        data = [(datetime,tank_num,vacuum_value1)]
        a.executemany(sqlStuff, data)
        conn.commit()
#發酵槽出料儲豆槽資料表
def sql_ferment_output_brake(command,tank_num,number,value):
        global input_vacuum_value2
        datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print (datetime)
        conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',database='Coffee', charset='utf8')
        a = conn.cursor()
        vacuum_value2 = int(value)
        sqlStuff = "INSERT INTO  ferment_output_actuator (datetime,tank_num,vacuum) VALUES (%s,%s,%s)"
        data = [(datetime,tank_num,vacuum_value2)]
        a.executemany(sqlStuff, data)
        conn.commit()
#桶槽編號轉換       
def typecomtonum(command):
        global  type_num
        tank_type=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        type_number=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
        for c in range(26):
           if (tank_type[c]==command):
               print(type_number[c])
               type_num=type_number[c]
           
 
               
               
## Reset this device.
def system_reboot():
    server_log('reboot', 'Restarting system')
    time.sleep(5)
    os.system('reboot -f')
    time.sleep(10)

## Reset this device to factory default.
def factory_reset():
    server_log('factory_reset', 'Resetting to factory default')
    time.sleep(5)
    os.system('firstboot -y')
    os.system('reboot -f')
    time.sleep(10)
## 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)
## 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')
        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')
            # start to upgrade the system firmware
            os.system('sysupgrade -n ' + filepath)
        else:
            server_log('system_update', 'ERROR: SHA256 checksum is wrong')
            shutil.rmtree(dirname, ignore_errors=True)

#馬達轉速設定
def stir(msg):
 if(msg['tank_num']=="D1"):
        rpm=int(msg['value'])
        if(rpm<0):
            direction=1
            rpm=-rpm
        else:
            direction=0   
        pwm=int(round((1.8088*rpm)+11))
        if(rpm==0):
            pwm=0
        if(pwm>99):
            pwm=99
        used_com3port()
        print("ok")
        typecomtonum(msg['tank_num'][0:1])
        print(int(msg['tank_num'][1:]))
        #commandarray = [0xFF,0xF1,0x02,0x01,0x01,direction,rpm,0x0D]
        commandarray = [0xFF,pwm,direction,0x00,0x00,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_upload(msg['command'],int(msg['value']))
        if(msg['tank_num']=="P1"):
           peel_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),int(msg['value']))
        elif(msg['tank_num']=="F1"):
           ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),int(msg['value']))
        elif(msg['tank_num']=="D1"):
           dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),int(msg['value']))
        if(direction==1):
            rpm=-rpm
        server_log('tank_motor_status',msg['tank_num'],rpm)

#入料儲豆槽真空吸引機
def input_vacuum(msg):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com2port()
        commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x02,0x00,0x0D]
        #commandarray = [0xFF,0x01,0x02,0x03,0x01,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_dry_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        sql_ferment_input_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('input_vacuum_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com2port()
        commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x02,0x01,0x0D]
        #commandarray = [0xFF,0x01,0x02,0x03,0x01,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_dry_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        sql_ferment_input_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('input_vacuum_status',msg['tank_num'], "off")  
    
#真空吸料機設定
def vacuum(msg):
  if(msg['tank_num']=="D1"):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com2port()
        #commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x01,0x00,0x0D]
        #print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        #time.sleep(0.2)
        #commandarray = [0xFF,0xF1,0x02,0x02,0x01,0x02,0x01,0x0D]
        commandarray = [0xF1,0x01,0x02,0x03,0x02,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        if(msg['tank_num']=="P1"):
           peel_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        elif(msg['tank_num']=="F1"):
           ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        elif(msg['tank_num']=="D1"):
           dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        elif(msg['tank_num']=="C1"):
           clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_vacuum_status',msg['tank_num'],"on")
    elif(msg['value'] == 'off'):
        used_com2port()
        #commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x01,0x01,0x0D]
        #print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        #time.sleep(0.2)
        #commandarray = [0xFF,0xF1,0x02,0x02,0x01,0x02,0x00,0x0D]
        commandarray = [0xF1,0x01,0x02,0x03,0x02,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        if(msg['tank_num']=="P1"):
           peel_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        elif(msg['tank_num']=="F1"):
           ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        elif(msg['tank_num']=="D1"):
           dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        elif(msg['tank_num']=="C1"):
           clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_vacuum_status',msg['tank_num'],"off")

#出料儲豆槽真空吸引機        
def output_vacuum(msg):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com2port()
        commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x03,0x00,0x0D]
        #commandarray = [0xFF,0x01,0x02,0x03,0x03,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_dry_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        sql_ferment_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('output_vacuum_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com2port()
        commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x03,0x01,0x0D]
        #commandarray = [0xFF,0x01,0x02,0x03,0x03,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_dry_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        sql_ferment_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('output_vacuum_status',msg['tank_num'], "off") 
                
#吸料機三通閥設定
def threewayvalve_input(msg):
     typecomtonum(msg['tank_num'][0:1])
     if (msg['value'] == 'on'):
        #used_com4port()
        commandarray = [0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_threewayvalve_status',msg['tank_num'],"on")
     elif (msg['value'] == 'off'):
        #used_com4port()
        commandarray = [0xFF, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_threewayvalve_status',msg['tank_num'],"off")
#蝴蝶閥設定
def diskvalve(msg):
  if(msg['tank_num']=="D1"):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com2port()
        #commandarray = [0xFF,0x02,0x00,0x00,0x01,0x00,0x0D]
        commandarray = [0xF1,0x01,0x02,0x03,0x03,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_upload(msg['command'],1)
        if(msg['tank_num']=="F1"):
          ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        elif(msg['tank_num']=="D1"):
          dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_diskvalve_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com2port()
        #commandarray = [0xFF,0x02,0x00,0x00,0x01,0x01,0x0D]
        commandarray = [0xF1,0x01,0x02,0x03,0x03,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_upload(msg['command'],0)
        if(msg['tank_num']=="F1"):
          ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        elif(msg['tank_num']=="D1"): 
          dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_diskvalve_status',msg['tank_num'], "off")
                       
#消毒閥設定
def disinfect(msg):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com2port()
        commandarray = [0xFF, 0x02, 0x00, 0x00, 0x03, 0x00, 0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_solenoid_disinfect_status',msg['tank_num'], "on")
    elif (msg['value'] == 'off'):
        used_com2port()
        commandarray = [0xFF, 0x02, 0x00, 0x00, 0x03, 0x01, 0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_solenoid_disinfect_status',msg['tank_num'], "off")
                
#加熱管1設定
def heater1(msg):
  if(msg['tank_num']=="D1"):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com1port()
        commandarray = [0xF1,0x02,0x02,0x03,0x01,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_heater1_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com1port()
        commandarray = [0xF1,0x02,0x02,0x03,0x01,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_heater1_status',msg['tank_num'], "off")
#加熱管2設定        
def heater2(msg):
  if(msg['tank_num']=="D1"):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com1port()
        commandarray = [0xF1,0x01,0x02,0x03,0x02,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_heater2_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com1port()
        commandarray = [0xF1,0x01,0x02,0x03,0x02,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_heater2_status',msg['tank_num'], "off")
                        
#控制溫度設定
def air_temp(msg):
    typecomtonum(msg['tank_num'][0:1])
    temp1=int(float(msg['value'])//10)
    temp2=int(((float(msg['value'])%10)*10)//10)
    temp3=int(((float(msg['value'])%10)*10)%10)
    used_com1port()
    commandarray = [0xFF,temp1,temp2, temp3,0x01,0x01,0x0D]
    print(commandarray)    
    ser.write(array.array('B', commandarray).tostring())
    dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),float(msg['value']))
    server_log(msg['command'],msg['tank_num'], msg['value'])
#控制溫度持續時間設定  
def temp_time(msg):
    typecomtonum(msg['tank_num'][0:1])
    #used_com3port()
    if msg['day']=='':
       msg['day']=0
    if msg['hr']=='':
       msg['hr']=0
    if msg['min']=='':
       msg['min']=0
    commandarray = [0xF4,int(msg['day']),int(msg['hr']),int(msg['min']),0x01,0x01,0x0D]
    print(commandarray)    
    #ser.write(array.array('B', commandarray).tostring())
    sql_upload(msg['command'],int(msg['value']))
    server_log(msg['command'],msg['tank_num'], msg['value'])
    
#溫度控制功能啟用與否
def air_temp_enable(msg):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com1port()
        commandarray = [0xF2,0x01,0x03, 0x03, 0x01, 0x01, 0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log(msg['command'],msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com1port()
        commandarray = [0xF3,0x03,0x03, 0x03, 0x01, 0x01, 0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log(msg['command'],msg['tank_num'], "off")   
        
 
#雙核水泵設定
def pump(msg,con):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com1port()
        commandarray = [0xFF,0x01,0x02,0x03,0x03,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_pump_sensor_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com1port()
        commandarray = [0xFF,0x01,0x02,0x03,0x03,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_pump_sensor_status',msg['tank_num'], "off")
         
#發酵槽廢水排水閥      
def water_out(msg):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com1port()
        commandarray = [0xFF,0x02,0x02,0x03,0x01,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log(msg['command'],msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com1port()
        commandarray = [0xFF,0x02,0x02,0x03,0x01,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log(msg['command'],msg['tank_num'], "off")

#內桶進水電磁閥
def water_in(msg):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com1port()
        commandarray = [0xFF,0x01,0x02,0x03,0x01,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_upload(msg['command'],1)
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_solenoid_water_in_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com1port()
        commandarray = [0xFF,0x01,0x02,0x03,0x01,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_upload(msg['command'],0)
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_solenoid_water_in_status',msg['tank_num'], "off")
#外桶進水電磁閥
def water(msg):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        used_com1port()
        commandarray = [0xFF,0x01,0x02,0x03,0x02,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_upload(msg['command'],1)
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_solenoid_water_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com1port()
        commandarray = [0xFF,0x01,0x02,0x03,0x02,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        #sql_upload(msg['command'],0)
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_solenoid_water_status',msg['tank_num'], "off")
#逆洗閥
def solenoid_tank_pump(msg): 
     typecomtonum(msg['tank_num'][0:1])
     if (msg['value'] == 'on'):
        used_com2port()
        commandarray = [0xFF, 0x02, 0x01, 0x00, 0x02, 0x00, 0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log(msg['command'],msg['tank_num'],"on")
     elif (msg['value'] == 'off'):
        used_com2port()
        commandarray = [0xFF, 0x02, 0x00, 0x00, 0x02, 0x01, 0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log(msg['command'],msg['tank_num'],"off")
        
#浮選三通閥
def threewayvalve_float(msg): 
     typecomtonum(msg['tank_num'][0:1])
     if (msg['value'] == 'on'):
        #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
        commandarray = [0xFF, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('outer_threewayvalve_float_status',msg['tank_num'],"on")
     elif (msg['value'] == 'off'):
        #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
        commandarray = [0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('outer_threewayvalve_float_status',msg['tank_num'],"off")
        
#加壓幫浦
def pump1(msg,con):
    typecomtonum(msg['tank_num'][0:1])
    if (msg['value'] == 'on'):
        #ser = serial.Serial('/dev/ttyUSB3', 115200, timeout=1)
        commandarray = [0xF1,0x01,0x02,0x03,con,0x00,0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log(msg['command'],msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        #ser = serial.Serial('/dev/ttyUSB3', 115200, timeout=1)
        commandarray = [0xF1,0x01,0x02,0x03,con,0x01,0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log(msg['command'],msg['tank_num'], "off") 
        
#乾燥槽排水閥         
def  drain(msg):
    if (msg['value'] == 'on'):
        #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
        commandarray = [0xF1,0x01,0x02,0x03,0x02,0x00,0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring()) 
        server_log('tank_solenoid_water_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
        commandarray = [0xF1,0x01,0x02,0x03,0x02,0x01,0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        server_log('tank_solenoid_water_status',msg['tank_num'], "off")
#鼓風機
def blower(msg):
  if(msg['tank_num']=="D1"):
    if (msg['value'] == 'on'):
        used_com1port()
        commandarray = [0xF1,0x01,0x02,0x03,0x03,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log('tank_blower_status',msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        used_com1port()
        commandarray = [0xF1,0x01,0x02,0x03,0x03,0x01,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log('tank_blower_status',msg['tank_num'], "off") 
                                                     

def valve5(msg):
    if (msg['value'] == 'on'):
        #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
        commandarray = [0xFF,0xF1,0x01,0x03,0x01,0x02,0x00,0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log(msg['command'],msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
        commandarray = [0xFF,0xF1,0x01,0x03,0x01,0x02,0x01,0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log(msg['command'],msg['tank_num'], "off")

def valve6(msg):
    if (msg['value'] == 'on'):
        #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
        commandarray = [0xFF,0xF1,0x01,0x03,0x01,0x01,0x00,0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
        server_log(msg['command'],msg['tank_num'], "on")
    elif(msg['value'] == 'off'):
        #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
        commandarray = [0xFF,0xF1,0x01,0x03,0x01,0x01,0x01,0x0D]
        print(commandarray)
        #ser.write(array.array('B', commandarray).tostring())
        clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
        server_log(msg['command'],msg['tank_num'], "off")  


def otatest(msg):
     ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
     ser.flushOutput()
     commandarray = [0xFF,0x03,0x00,0x00, 0x00, 0x00, 0x0D]
     print(commandarray)
     ser.write(array.array('B', commandarray).tostring())
     print('Send OK')
     server_log('otatest',msg['tank_num'],'success')
      

def otastart(msg):
     ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
     ser.flushOutput()
     arr=[]
     i=0
     global j
     j=0
     file = '/home/pi/ISP/newtest.hex'
     with open(file, "rb") as f:
         for line in f.readlines():
          if (line[1:2])==b'1':
               j=j+1
         j1=int(j/100)
         j2=j%100
     #print(j)
     commandarray = [0xFF,0x01,j1,j2, 0x00, 0x00, 0x0D]
     #print(commandarray)
     ser.write(array.array('B', commandarray).tostring())
     try:
       e=0
       rcv = ser.read(1)
       print (hex(ord(rcv)))  
       if (hex(ord(rcv)) == "0x79"):
        file = '/home/pi/ISP/newtest.hex'
        with open(file, "rb") as f:
         for line in f.readlines():
            i=i+1
            if(i>1 and i<j+2 and e==0):
            
              num1 =int(line[9:11],16)
              num2 =int(line[11:13],16)
              num3 =int(line[13:15],16)
              num4 =int(line[15:17],16)
              
              num5 =int(line[17:19],16)
              num6 =int(line[19:21],16)
              num7 =int(line[21:23],16)
              num8 =int(line[23:25],16)
              
              num9 =int(line[25:27],16)
              num10 =int(line[27:29],16)
              num11=int(line[29:31],16)
              num12=int(line[31:33],16)
              
              num13 =int(line[33:35],16)
              num14 =int(line[35:37],16)
              num15 =int(line[37:39],16)
              num16 =int(line[39:-4],16)
         
              checksum=0x0F^num4^num3^num2^num1^num8^num7^num6^num5^num12^num11^num10^num9^num16^num15^num14^num13
              arr= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]+[checksum]
              #print(arr)
              #print(checksum)
              #time.sleep(0.1)
              ser.write(array.array('B', arr).tostring())
              ser.flushOutput()
              try:
                  rcv = ser.readline()
                  rcv1 = ser.readline()
                  rcv2 = ser.readline()
                  rcv3 = ser.readline()
                  rcv4 = ser.readline()
                  rcv5 = ser.readline()
                  if(str(checksum)==rcv4[:-2]):
                      e=0
                      print("success")
                  else:
                     if(rcv5=="error"):
                         print("error")
                         arr= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]+[checksum]
                         ser.write(array.array('B', arr).tostring())
                         rcv = ser.readline()
                         rcv1 = ser.readline()
                         rcv2 = ser.readline()
                         rcv3 = ser.readline()
                         rcv4 = ser.readline()
                         rcv5 = ser.readline()
                         if(str(checksum)==rcv4[:-2]):
                            e=0
                            print("success")
                         else:
                            e=1
                            print("error again")
              except:
                  server_log('OTA',msg['tank_num'], 'no reply')
       else:
        e=1
       if(e==0):
        server_log('ota',msg['tank_num'], 'success')
       else:
        server_log('OTA',msg['tank_num'], 'upload error')                  
     except:  
          server_log('OTA',msg['tank_num'], 'no reply')  


def ota(msg):
    os.system('sudo su')
    os.system('rm -rf /home/pi/OTA')
    os.system('git clone '+msg['url']+' /home/pi/OTA')
    ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
    ser.flushOutput()
    arr=[]
    i=0
    global j
    j=0
    file = '/home/pi/OTA/OTASTM32F4.hex'
    with open(file, "rb") as f:
         for line in f.readlines():
          print(line[1:2])
          if (line[1:2])==b'1':
               j=j+1
         j1=int(j/100)
         j2=j%100
         print(j*4)
    commandarray = [0xFF,0x01,j1,j2, 0x00, 0x00, 0x0D]
    print(commandarray)
    ser.write(array.array('B', commandarray).tostring())
    try:
       e=0
       rcv = ser.read(1)
       print (hex(ord(rcv)))  
       if (hex(ord(rcv)) == "0x79"):
        file = '/home/pi/OTA/OTASTM32F4.hex'
        with open(file, "rb") as f:
         for line in f.readlines():
            i=i+1
            if(i>1 and i<j+2 and e==0):
            
              num1 =int(line[9:11],16)
              num2 =int(line[11:13],16)
              num3 =int(line[13:15],16)
              num4 =int(line[15:17],16)
              
              num5 =int(line[17:19],16)
              num6 =int(line[19:21],16)
              num7 =int(line[21:23],16)
              num8 =int(line[23:25],16)
              
              num9 =int(line[25:27],16)
              num10 =int(line[27:29],16)
              num11=int(line[29:31],16)
              num12=int(line[31:33],16)
              
              num13 =int(line[33:35],16)
              num14 =int(line[35:37],16)
              num15 =int(line[37:39],16)
              num16 =int(line[39:-4],16)
              
              checksum=0x0F^num4^num3^num2^num1^num8^num7^num6^num5^num12^num11^num10^num9^num16^num15^num14^num13
              arr= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]+[checksum]
              #print(arr)
              #print(checksum)
              #time.sleep(0.1)
              ser.write(array.array('B', arr).tostring())
              ser.flushOutput()
              try:
                  rcv = ser.readline()
                  rcv1 = ser.readline()
                  rcv2 = ser.readline()
                  rcv3 = ser.readline()
                  rcv4 = ser.readline()
                  rcv5 = ser.readline()
                  if(str(checksum)==rcv4[:-2]):
                      e=0
                  else:
                      if(rcv5=="error"):
                         arr= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]+[checksum]
                         ser.write(array.array('B', arr).tostring())
                         rcv = ser.readline()
                         rcv1 = ser.readline()
                         rcv2 = ser.readline()
                         rcv3 = ser.readline()
                         rcv4 = ser.readline()
                         rcv5 = ser.readline()
                         if(str(checksum)==rcv4[:-2]):
                            e=0
                         else:
                            e=1
              except:
                  server_log('OTA',msg['tank_num'], 'no reply')
       else:
        e=1
       if(e==0):
        server_log('ota', msg['tank_num'],'success')
       else:
        server_log('OTA',msg['tank_num'], 'upload error')                  
    except:  
          server_log('OTA',msg['tank_num'], 'no reply')
    
 
def ICP(msg):
     ser.flushOutput()
     arr=[]
     i=0
     global j
     file = '/home/pi/OTA/OTA.hex'
     with open(file, "rb") as f:
         for line in f.readlines():
            i=i+1
            if(i>1 and i<j+2):
              num1 =int(line[9:11],16)
              num2 =int(line[11:13],16)
              num3 =int(line[13:15],16)
              num4 =int(line[15:17],16)
              
              num5 =int(line[17:19],16)
              num6 =int(line[19:21],16)
              num7 =int(line[21:23],16)
              num8 =int(line[23:25],16)
              
              num9 =int(line[25:27],16)
              num10 =int(line[27:29],16)
              num11=int(line[29:31],16)
              num12=int(line[31:33],16)
              
              num13 =int(line[33:35],16)
              num14 =int(line[35:37],16)
              num15 =int(line[37:39],16)
              num16 =int(line[39:-4],16)
              arr+= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]
     print(arr)
     ser.write(array.array('B', arr).tostring())
     print('Send OK')
     server_log('icp',msg['tank_num'], '1') 

def clear(msg):
    ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
    ser.flushOutput()
    commandarray = [0x7F]
    ser.write(array.array('B', commandarray).tostring())
    ser.flushOutput()
    try:
       rcv = ser.read(1)
       print(hex(ord(rcv)))
       if (hex(ord(rcv)) =="0x79"):
         commandarray = [0x02,0xFD]
         ser.write(array.array('B', commandarray).tostring())
         try:
            rcv1 = ser.read(1)
            rcv2 = ser.read(1)
            rcv3 = ser.read(1)
            rcv4 = ser.read(1)
            rcv5 = ser.read(1)
            print (hex(ord(rcv4)))
            if (hex(ord(rcv4)) =="0x17"):
                commandarray = [0x44,0xBB]
                ser.write(array.array('B', commandarray).tostring())
                ser.flushOutput()
                try:
                   rcv = ser.read(1)
                   print (hex(ord(rcv))) 
                   checksum=[]
                   commandarray = [0x00,0xFE]
                   sum=0
                   if (hex(ord(rcv)) =="0x79"):
                     for x in range (510):
                            addr1=x/255
                            addr2=x%255
                            commandarray += [int(addr1),int(addr2)]
                            sum=sum^x
                            checksum=[int(sum/255),int(sum%255)]
                            commandarray += checksum
                            ser.write(array.array('B', commandarray).tostring())
                            try:
                               rcv = ser.read(1)
                               print (hex(ord(rcv)))
                               if (hex(ord(rcv)) =="0x79"):
                                      server_log('clear',msg['tank_num'], 'success')
                               else:
                                 server_log('clear',msg['tank_num'], 'upload failed')
                            except:
                                 server_log('clear',msg['tank_num'], 'upload failed')
                   else:
                     server_log('clear',msg['tank_num'], 'erase memory error')
                except:
                     server_log('clear',msg['tank_num'], 'erase memory error')
            elif(hex(ord(rcv4)) =="0x13"):
                       commandarray = [0x44,0xBB]
                       ser.write(array.array('B', commandarray).tostring())
                       ser.flushOutput()
                       try:
                          rcv = ser.read(1)
                          print (hex(ord(rcv))) 
                          if (hex(ord(rcv)) =="0x79"):
                               commandarray = [0xFF,0xFF,0x00]
                               ser.write(array.array('B', commandarray).tostring())
                               ser.flushOutput()
                               try:
                                  time.sleep(20)
                                  rcv = ser.read(1)
                                  print (hex(ord(rcv)))
                                  if (hex(ord(rcv)) =="0x79"):
                                         server_log('clear',msg['tank_num'], 'success')
                                  else:
                                    server_log('clear',msg['tank_num'], 'upload failed')
                               except:
                                    server_log('clear',msg['tank_num'], 'upload failed')
                          else:
                            server_log('clear',msg['tank_num'], 'erase memory failed')                    
                       except:
                            server_log('clear',msg['tank_num'], 'erase memory failed')
            else:
              server_log('clear', msg['tank_num'],'recognition failed')
         except:
              server_log('clear', msg['tank_num'],'recognition failed')
       else:
         server_log('clear',msg['tank_num'], 'no ready')
    except:
         server_log('clear',msg['tank_num'], 'no ready')
         
def ISP(msg):
    ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
    ser.flushOutput()
    commandarray = [0x7F]
    ser.write(array.array('B', commandarray).tostring())
    ser.flushOutput()
    try:
       rcv = ser.read(1)
       print(hex(ord(rcv)))
       if (hex(ord(rcv)) =="0x79"):
         commandarray = [0x02,0xFD]
         ser.write(array.array('B', commandarray).tostring())
         try:
            rcv1 = ser.read(1)
            rcv2 = ser.read(1)
            rcv3 = ser.read(1)
            rcv4 = ser.read(1)
            rcv5 = ser.read(1)
            print (hex(ord(rcv4)))
            if (hex(ord(rcv4)) =="0x17"):
                commandarray = [0x44,0xBB]
                ser.write(array.array('B', commandarray).tostring())
                ser.flushOutput()
                try:
                   rcv = ser.read(1)
                   print (hex(ord(rcv))) 
                   checksum=[]
                   commandarray = [0x00,0xFE]
                   sum=0
                   if (hex(ord(rcv)) =="0x79"):
                     for x in range (510):
                            addr1=x/255
                            addr2=x%255
                            commandarray += [int(addr1),int(addr2)]
                            sum=sum^x
                            checksum=[int(sum/255),int(sum%255)]
                            commandarray += checksum
                            ser.write(array.array('B', commandarray).tostring())
                            try:
                               rcv = ser.read(1)
                               print (hex(ord(rcv)))
                               if (hex(ord(rcv)) =="0x79"):
                                      server_log('clear',msg['tank_num'], 'success')
                            except:
                                 server_log('clear',msg['tank_num'], 'upload failed')
                except:
                     server_log('clear',msg['tank_num'], 'erase memory error')
            elif(hex(ord(rcv4)) =="0x13"):
                       commandarray = [0x44,0xBB]
                       ser.write(array.array('B', commandarray).tostring())
                       ser.flushOutput()
                       try:
                          rcv = ser.read(1)
                          print (hex(ord(rcv))) 
                          if (hex(ord(rcv)) =="0x79"):
                               commandarray = [0xFF,0xFF,0x00]
                               ser.write(array.array('B', commandarray).tostring())
                               ser.flushOutput()
                               try:
                                  time.sleep(20)
                                  rcv = ser.read(1)
                                  print (hex(ord(rcv)))
                                  if (hex(ord(rcv)) =="0x79"):
                                    s=1
                               except:
                                    server_log('clear',msg['tank_num'], 'upload failed')
                       except:
                            server_log('clear',msg['tank_num'], 'erase memory failed')
         except:
              server_log('clear',msg['tank_num'], 'recognition failed')
    except:
         server_log('clear',msg['tank_num'], 'no ready')
    if (s==1):
     s=0      
     ser.flushOutput()
     arr=[]
     j=0
     i=0
     file = '/home/pi/ISP/OTA.hex'
     with open(file, "rb") as f:
       for line in f.readlines():
        if (line[1:2])==b'1':
              j=j+1
     print(j)
     file = '/home/pi/ISP/OTA.hex'
     with open(file, "rb") as f:
           for line in f.readlines():
             i=i+1
             if(i>1 and i<j+2):
              addr1=int(line[3:5],16)
              addr2=int(line[5:7],16)
         
              num1 =int(line[9:11],16)
              num2 =int(line[11:13],16)
              num3 =int(line[13:15],16)
              num4 =int(line[15:17],16)
              
              num5 =int(line[17:19],16)
              num6 =int(line[19:21],16)
              num7 =int(line[21:23],16)
              num8 =int(line[23:25],16)
              
              num9 =int(line[25:27],16)
              num10 =int(line[27:29],16)
              num11=int(line[29:31],16)
              num12=int(line[31:33],16)
              
              num13 =int(line[33:35],16)
              num14 =int(line[35:37],16)
              num15 =int(line[37:39],16)
              num16 =int(line[39:-4],16)
              commandarray = [0x31,0xCE]
              #print(commandarray)
              ser.write(array.array('B', commandarray).tostring())
              try:
                    rcv = ser.read(1)
                    #print (hex(ord(rcv)))  
                    if (hex(ord(rcv)) =="0x79"):
                      commandarray = [0x08,0x00,addr1,addr2,(0x08^0x00^addr1^addr2)]
                      ser.write(array.array('B', commandarray).tostring())
                      try:
                        rcv = ser.read(1)
                        #print (hex(ord(rcv)))  
                        if (hex(ord(rcv)) =="0x79"):
                          checksum=0x0F^num1^num2^num3^num4^num5^num6^num7^num8^num9^num10^num11^num12^num13^num14^num15^num16
                          commandarray = [0x0F]+[num1]+[num2]+[num3]+[num4]+[num5]+[num6]+[num7]+[num8]+[num9]+[num10]+[num11]+[num12]+[num13]+[num14]+[num15]+[num16]+[checksum]
                          #print(commandarray)
                          ser.write(array.array('B', commandarray).tostring())
                          try:
                             rcv = ser.read(1)
                             #print (hex(ord(rcv))) 
                             if (hex(ord(rcv)) !="0x79"):
                               con=1
                               server_log('isp',msg['tank_num'], 'upload error')
                             else:
                               con=0
                          except:
                               server_log('isp',msg['tank_num'], 'upload error')
                      except:
                           server_log('isp',msg['tank_num'], 'addr error')
              except:
                      server_log('isp',msg['tank_num'], 'write memory failed')
     if (con==0):
         server_log('isp',msg['tank_num'], 'success')    


def sht11(msg):
        ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
        commandarray = [0xFF,0xF1,0x01,0x01,0x03,0x00,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        temp=0
        humidity=0
        tank=0
        ser.flushOutput()
        time.sleep(1)
        if ser.inWaiting():
            x = ser.readline()
            if (hex(ord(x[0])) == "0xff" and  hex(ord(x[10])) == "0xd"):
               if int(ord(x[2])) == 2:
                tank="D1"
                if int(ord(x[3])) == 1:
                    print (-1*(int(ord(x[4]))+ (0.1 * int(ord(x[5])))))
                    temp=-1 * (int(ord(x[4])) + (0.1 * int(ord(x[5]))))
                    print (int(ord(x[6]))+(0.1 * int(ord(x[7]))))
                    humidity=int(ord(x[6])) + (0.1 * int(ord(x[7])))
                if int(ord(x[3])) == 0:
                    print(int(ord(x[4])) + 0.1 * int(ord(x[5])))
                    temp=int(ord(x[4])) + 0.1 * int(ord(x[5]))
                    print (int(ord(x[6])) + 0.1 * int(ord(x[7])))
                    humidity=int(ord(x[6])) + 0.1 * int(ord(x[7]))
               print(tank)
               datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
               conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',
               database='Coffee', charset='utf8')
               a = conn.cursor()
               sqlStuff = "INSERT INTO  dry_tank_SHT11 (datetime,tank_num,SHT11_Temp,SHT11_Humidity) VALUES (%s,%s,%s,%s)"
               data = [(datetime,tank,temp,humidity)]
               a.executemany(sqlStuff, data)
               conn.commit()   
        server_log(msg['command'],msg['tank_num'], temp)  

def sht12(msg):
        ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
        commandarray = [0xFF,0xF1,0x02,0x01,0x03,0x00,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        temp=0
        humidity=0
        tank=0
        ser.flushOutput()
        time.sleep(1)
        if ser.inWaiting():
            x = ser.readline()
            if (hex(ord(x[0])) == "0xff" and  hex(ord(x[10])) == "0xd"):
               if int(ord(x[2])) == 3:
                tank="D2"
                if int(ord(x[3])) == 1:
                    print (-1*(int(ord(x[4]))+ (0.1 * int(ord(x[5])))))
                    temp=-1 * (int(ord(x[4])) + (0.1 * int(ord(x[5]))))
                    print (int(ord(x[6]))+(0.1 * int(ord(x[7]))))
                    humidity=int(ord(x[6])) + (0.1 * int(ord(x[7])))
                if int(ord(x[3])) == 0:
                    print(int(ord(x[4])) + 0.1 * int(ord(x[5])))
                    temp=int(ord(x[4])) + 0.1 * int(ord(x[5]))
                    print (int(ord(x[6])) + 0.1 * int(ord(x[7])))
                    humidity=int(ord(x[6])) + 0.1 * int(ord(x[7]))
               print(tank)
               datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
               conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',
               database='Coffee', charset='utf8')
               a = conn.cursor()
               sqlStuff = "INSERT INTO  dry_tank_SHT11 (datetime,tank_num,SHT11_Temp,SHT11_Humidity) VALUES (%s,%s,%s,%s)"
               data = [(datetime,tank,temp,humidity)]
               a.executemany(sqlStuff, data)
               conn.commit()   
        server_log(msg['command'],msg['tank_num'], temp) 

def sonic(msg):
        ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
        commandarray = [0xFF,0xF1,0x02,0x01,0x03,0x00,0x00,0x0D]
        print(commandarray)
        ser.write(array.array('B', commandarray).tostring())
        temp=0
        humidity=0
        tank=0
        ser.flushOutput()
        time.sleep(1)
        if ser.inWaiting():
            x = ser.readline()
            if (hex(ord(x[0])) == "0xff" and  hex(ord(x[10])) == "0xd"):
               if int(ord(x[2])) == 1:
                tank="F1"
                if int(ord(x[3])) == 1:
                    print (-1*(int(ord(x[4]))+ (0.1 * int(ord(x[5])))))
                    temp=-1 * (int(ord(x[4])) + (0.1 * int(ord(x[5]))))
                    print (int(ord(x[6]))+(0.1 * int(ord(x[7]))))
                    humidity=int(ord(x[6])) + (0.1 * int(ord(x[7])))
                if int(ord(x[3])) == 0:
                    print(int(ord(x[4])) + 0.1 * int(ord(x[5])))
                    temp=int(ord(x[4])) + 0.1 * int(ord(x[5]))
                    print (int(ord(x[6])) + 0.1 * int(ord(x[7])))
                    humidity=int(ord(x[6])) + 0.1 * int(ord(x[7]))
               print(tank)
               datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
               conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',
               database='Coffee', charset='utf8')
               a = conn.cursor()
               sqlStuff = "INSERT INTO  ferment_tank_SHT11 (datetime,tank_num,SHT11_Temp,SHT11_Humidity) VALUES (%s,%s,%s,%s)"
               data = [(datetime,tank,temp,humidity)]
               a.executemany(sqlStuff, data)
               conn.commit()   
        server_log(msg['command'],msg['tank_num'], temp)   
        
        
def ferment(msg):
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.0.py | awk '{print $2}' | xargs kill -9")
    os.system('sudo nohup python /home/pi/coffee5.0.py>/home/pi/nohup.out 2>&1 &')
    server_log('ferment','ferment_all', 'open')

def ferment_close(msg):
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.0.py | awk '{print $2}' | xargs kill -9")
    server_log('ferment','ferment_all', 'close')


def valve(msg):
    #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
    #commandarray = [0xFF,0xF1,0x01,0x02,int(msg['value']),0x02,0x00,0x0D]
    #print(commandarray)
    #ser.write(array.array('B', commandarray).tostring())
    conn = sqlite3.connect('home/pi/coffee.db')
    c = conn.cursor()
    c.execute("UPDATE coffee set command = '%s',open_time = '%s',close_time = '%s',tank_num = '%s',temp = '%s',rpm = '%s',water_high_level = '%s',water_low_level = '%s',coffee_level = '%s',ferment_date = '%s',ferment_hr = '%s',ferment_min = '%s',ferment_sec = '%s',sensor_time = '%s',disinfect_time = '%s' where sn=1"\
          %(msg['command'],msg['open_time'],msg['close_time'],msg['tank_num'],msg['temp'],msg['rpm'],msg['water_high_level'],msg['water_low_level'],msg['coffee_level'],msg['ferment_date'],msg['ferment_hr'],msg['ferment_min'],msg['ferment_sec'],msg['sensor_time'],msg['disinfect_time']))
    conn.commit()
    conn.close()
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
    os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
    server_log(msg['command'],'F1', 'success')
    
def ferment_input(msg):
    if int(msg['Ferment_Input_1'])==1 :
      ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
      commandarray = [0xFF,0xF1,0x02,0x02, 0x01, 0x02,0x00, 0x0D]
      print(commandarray)
      ser.write(array.array('B', commandarray).tostring())
    else:
      ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
      commandarray = [0xFF,0xF1,0x02,0x02, 0x01, 0x02,0x01, 0x0D]
      print(commandarray)
      ser.write(array.array('B', commandarray).tostring())
    server_log('Ferment_Input','ferment_input_1', 'success')
       
def ferment_upload(msg):
    os.system('sudo su')
    os.system('rm -rf /home/pi/ferment_ota')
    os.system('rm -rf /home/pi/coffee.db')
    os.system('sudo python /home/pi/coffee8.0.py')
    os.system(msg['upload_url']+' /home/pi/ferment_ota')
    time.sleep(3)
    os.system('cp /home/pi/ferment_ota/coffee3.0.py /home/pi/')
    time.sleep(1)
    os.system('sudo chmod 777 /home/pi/coffee3.0.py')
    time.sleep(2)
    server_log(msg['command'],msg['tank_num'], 'success')
    os.system('sudo reboot')
    
def ferment_input_bean(msg):
    sql_local_upload(msg['command'])
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
    os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
    server_log(msg['command'],'F1', 'success')
    
def ferment_add_outer_water(msg):
    sql_local_upload(msg['command'])
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
    os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
    server_log(msg['command'],'F1', 'success')
    
def ferment_add_inner_water(msg):
    sql_local_upload(msg['command'])
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
    os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
    server_log(msg['command'],'F1', 'success')


def ferment_heat(msg):
    sql_local_upload(msg['command'])
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
    os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
    server_log(msg['command'],'F1', 'success')
 
def ferment_drain_inner_water(msg):
    sql_local_upload(msg['command'])
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
    os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
    server_log(msg['command'],'F1', 'success')
    
def ferment_out_bean(msg):
    sql_local_upload(msg['command'])
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
    os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
    server_log(msg['command'],'F1', 'success')   
    
def ferment_disinfect(msg):
    sql_local_upload(msg['command'])
    os.system('sudo su')
    os.system('cd /home/pi')
    os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
    os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
    server_log(msg['command'],'F1', 'success')

def ferment_ota(msg):
    sql_local_upload(msg['command'])
    os.system('sudo su')
    os.system('cd /home/pi')
    #os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
    #os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
    server_log(msg['command'],'F1', 'success')

def ferment_pin_configuration(msg): 
     os.system('sudo su')
     os.system('cd /home/pi')
     os.system("python /home/pi/CTO20220419.py")
     os.system('cd /home/pi/newtest2;make')
     os.system('cp /home/pi/newtest2/newtest.hex /home/pi/OTA')
     n = subprocess.call(["git", "add","newtest.hex"],cwd="/home/pi/OTA/")
     if (n==0):
       n = subprocess.call(["git", "commit","-m","OTA"],cwd="/home/pi/OTA/")
       if(n==0):
         n = subprocess.call(["git", "push"],cwd="/home/pi/OTA/")
         if(n==0):
           server_log(msg['command'],'F1',"success")
         elif(n==1):
           server_log(msg['command'],'F1',"no change")
         else:
           server_log('git push','F1',"error")
       elif(n==1):
         server_log('git commit','F1',"no change") 
       else:
         server_log('git commit','F1',"error")
     elif(n==1):
         server_log('git add','F1',"no change")     
     else:
       server_log('git add','F1',"error")

def OTA_UPLOAD(msg):
     m=msg['url']
     m=m.replace("\\r\\n", "\r\n")
     file = '/home/pi/CTO/SDIO.hex'
     f = open(file, 'w')
     f.write(m)
     ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=0.2)
     ser.flushOutput()
     arr=[]
     i=0
     global j
     j=0
     file = '/home/pi/CTO/SDIO.hex'
     with open(file, "rb") as f:
         for line in f.readlines():
          if (line[8:9])==b'0':
              j=j+1
              j1=int(line[3:5],16)
              j2=int(line[5:7],16)
     #print(j1)
     #print(j2)
     commandarray = [0xFF,0x01,j1,j2, 0x00, 0x00, 0x0D]
     #print(commandarray)
     ser.write(array.array('B', commandarray).tostring())
     try:
       e=0
       rcv = ser.read(1)
       print (hex(ord(rcv)))  
       if (hex(ord(rcv)) == "0x79"):
        file = '/home/pi/CTO/SDIO.hex'
        with open(file, "rb") as f:
         for line in f.readlines():
            i=i+1
            #print(i)
            if(i>1 and i<j+2 and e==0 and line[8:9]=='0'):
              #print(i)
              checksum=0x0F
              arr=[int(line[1:3],16)]
              arr+=[int(line[3:5],16)]
              arr+=[int(line[5:7],16)]
              for x in range (0,int(line[1:3],16)):
                 checksum^=int(line[9+(2*x):11+(2*x)],16)
                 arr+=[int(line[9+(2*x):11+(2*x)],16)]
              arr+=[checksum]
              for x in range (0,(16-int(line[1:3],16))):
                 arr+=[0]
              print(arr)
              ser.write(array.array('B', arr).tostring())
              ser.flushOutput()
              try:
                  rcv = ser.readline()
                  if(rcv=="success"):
                      e=0
                      print("success")
                      arr=[]
                  elif(rcv=="error"):
                         for z in range (10):
                           print("error")
                           ser.write(array.array('B', arr).tostring())
                           rcv = ser.readline()
                           if(rcv=="success"):
                              e=0
                              print("success")
                              arr=[]
                              break
                           else:
                              e=1
                              print("upload error")
                  else:  
                      for z in range (10):
                           print("error")
                           ser.write(array.array('B', arr).tostring())
                           rcv = ser.readline()
                           if(rcv=="success"):
                              e=0
                              print("success")
                              arr=[]
                              break
                           else:
                              e=1
                              print("upload error")
              except: 
                  server_log(msg['command'],msg['tank_num'], 'no reply')
       else:
        e=1
       if(e==0):
        server_log(msg['command'],msg['tank_num'], 'success')
       else:
        server_log(msg['command'],msg['tank_num'], 'upload error')                  
     except:  
          server_log(msg['command'],msg['tank_num'], 'no reply')           

def OTA_hex(msg):
     print("ok")
     file = '/home/pi/newtest/SDIO.hex'
     f = open(file, 'r')
     ota_hex=f.read()
     print(f.read())
     server_log('OTA',msg['tank_num'],ota_hex) 

def OTA_hex_save(msg):
     print(msg['url'])
     m=msg['url']
     m=m.replace("\\r\\n", "\r\n")
     print(m)
     file = '/home/pi/newtest/SDIO.hex'
     f = open(file, 'w')
     f.write(m)
     server_log('OTA',msg['tank_num'],"ok")  

def creat_hex(msg):
     f=open("/home/pi/newtest/test.c", mode='w')
     
     f.write("/* USER CODE BEGIN Header */\n"
       +"/**\n"
       +"  ******************************************************************************\n"
       +"  * @file           : main.c\n"
       +"  * @brief          : Main program body\n"
       +"  * @attention\n"
       +"  *\n"
       +"  * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics.\n"
       +"  * All rights reserved.</center></h2>\n"
       +"  *\n"
       +"  * This software component is licensed by ST under BSD 3-Clause license,\n"
       +"  * the License; You may not use this file except in compliance with the\n"
       +"  * License. You may obtain a copy of the License at:\n"
       +"  *                        www.st.com/SLA0044\n"
       +"  *\n"
       +"  ******************************************************************************\n"
       +"  */\n"
       +"/* USER CODE END Header */\n"
       +"\n"
       +"/* Includes ------------------------------------------------------------------*/\n")
       #添加標題檔
     header=('#include"main.h"\n'
       +'#include "adc.h"\n'
       +'#include "usart.h"\n'
       +'#include "gpio.h"\n'
       +'#include "stdio.h"\n')
     f.write(header)
     #變數宣告說明
     f.write("\n"
       +"/* Private variables ---------------------------------------------------------*/\n")
     #連接資料庫
     #conn = sqlite3.connect('/home/pi/coffee.db')
     conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage',
                       charset='utf8')
     c = conn.cursor()
     print ("connect success")
     #搜尋最新腳位配置時間
     c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
     results=c.fetchall()
     for row in results:
        time = row[1]
       #腳位配置加入     
     c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
            %(time))
     results=c.fetchall()
     for row in results:
       for i in range (19): 
              row[i+26]
     for i in range (19): 
         PH("M"+str(i+1),row[i+26])
         f.write(pin_variables)
         DO("M"+str(i+1),row[i+26])
         f.write(pin_variables)
         WATERLEVEL("M"+str(i+1),row[i+26])
         f.write(pin_variables)  
         ORP("M"+str(i+1),row[i+26]) 
         #ESMUS07(pin_position,pin_type) 
         #SEN0189(pin_position,pin_type)
         #SOIL(pin_position,pin_type)
         #SERVO(pin_position,pin_type)
         #MOTOR(pin_position,pin_type)
         #SHT11(pin_position,pin_type)            
         #BMP280(pin_position,pin_type)
         f.write(pin_variables)
     #變數宣告
     #f.write(pin_variables)
     #副函式宣告
     f.write("/* USER CODE BEGIN PV */\n"
       +"typedef  void (*pFunction)(void);\n"
       +"/* USER CODE END PV */\n"
       +"/* Private function prototypes -----------------------------------------------*/\n"
       +"void SystemClock_Config(void);\n"
       +"/* USER CODE BEGIN PFP */\n"
       +"/* USER CODE END PFP */\n"
       +"/* Private user code ---------------------------------------------------------*/\n"
       +"/* USER CODE BEGIN 0 */\n"
       +"/* USER CODE END 0 */\n"
       +"/**\n"
       +"* @brief  The application entry point.\n"
       +"* @retval int\n"
       +"*/\n")
     #主程式撰寫
     #main宣告
     f.write("int main(void)\n"
       +"{\n")


#致能週邊
     enable=("  HAL_Init();\n"
       +"  SystemClock_Config();\n"
       +"  MX_GPIO_Init();\n"
       +"  MX_USART2_UART_Init();\n"
       +"  MX_UART4_Init();\n"
       +"  MX_USART1_UART_Init();\n"
       +"  MX_ADC1_Init();\n")

     f.write(enable)
     code=("  while (1)\n"
     +"  {\n")
     f.write(code)
     #連接資料庫
     conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage',
                       charset='utf8')
     #conn = sqlite3.connect('/home/pi/coffee.db')
     c = conn.cursor()
     print ("connect success")
     #搜尋最新腳位配置時間
     c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
     results = c.fetchall()
     for row in results:
        time = row[1]
       #腳位配置加入     
     c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
            %(time))
     results = c.fetchall()
     for row in results:
         for i in range (19): 
                 row[i+26]
     for i in range (19): 
         PH("M"+str(i+1),row[i+26])
         f.write(pin_code)
         DO("M"+str(i+1),row[i+26])
         f.write(pin_code)
         WATERLEVEL("M"+str(i+1),row[i+26])
         f.write(pin_code)  
         ORP("M"+str(i+1),row[i+26]) 
         #ESMUS07(pin_position,pin_type) 
         #SEN0189(pin_position,pin_type)
         #SOIL(pin_position,pin_type)
         #SERVO(pin_position,pin_type)
         #MOTOR(pin_position,pin_type)
         #SHT11(pin_position,pin_type)            
         #BMP280(pin_position,pin_type)
         f.write(pin_code)
     for i in range (len(msg['cond'])):
      m=msg['cond'][i]['cond_main'].split(" ")
      if(m[0]=="else" and m[1]=="if"):
         m[0]=m[0]+" "+m[1]
         m[1]=m[2]
         m[2]=m[3]
         m[3]=m[4]
         m[4]=m[5]
      m=""+m[0]+"("+m[2]+m[3]+m[4]
      f.write("    "+m)
      if(m[0]==" "):
        m=""
      else:
       for j in range (len(msg['cond'][i]['cond_add'])):
         if(j==len(msg['cond'][i]['cond_add'])-1):
            if(msg['cond'][i]['cond_add'][j]=="   "):
             add=")\n"
            else: 
             add=" "+str(msg['cond'][i]['cond_add'][j])+")\n"
             f.write(add) 
         else:
            if(msg['cond'][i]['cond_add'][j]=="   "):
             add=""
            else: 
             add=" "+str(msg['cond'][i]['cond_add'][j])
             f.write(add)
       f.write("    {\n")  
       for j in range (len(msg['cond'][i]['cond_com'])): 
        if(j==len(msg['cond'][i]['cond_com'])-1):
            if(msg['cond'][i]['cond_com'][j]==" "):
             com="\n}\n"
            else: 
             com=msg['cond'][i]['cond_com'][j].split(" ")
             com="     "+GPIO(com[0],com[1])+"\n    }\n"
             f.write(com) 
        else:
            if(msg['cond'][i]['cond_com'][j]==" "):
             com=""
            else:
             com=msg['cond'][i]['cond_com'][j].split(" ") 
             com="     "+GPIO(com[0],com[1])+"\n"
             f.write(com)     
     f.write("  }\n")
     f.write("}\n")
#系統時鐘宣告
     time=("void SystemClock_Config(void)\n"
     +"{\n"
     +"  RCC_OscInitTypeDef RCC_OscInitStruct = {0};\n"
     +"  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};\n"
     +"  __HAL_RCC_PWR_CLK_ENABLE();\n"
     +"  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);\n"
     +"  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;\n"
     +"  RCC_OscInitStruct.HSIState = RCC_HSI_ON;\n"
     +"  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;\n"
     +"  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
     +"  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;\n"
     +"  RCC_OscInitStruct.PLL.PLLM = 8;\n"
     +"  RCC_OscInitStruct.PLL.PLLN = 72;\n"
     +"  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;\n"
     +"  RCC_OscInitStruct.PLL.PLLQ = 3;\n"
     +"  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
     +"  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)\n"
     +"  {\n"
     +"    Error_Handler();\n"  
     +"  }\n"
     +"  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK\n"
     +"                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;\n"
     +"  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;\n"
     +"  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;\n"
     +"  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;\n"
     +"  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;\n"
     +"  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)\n"
     +"  {\n"
     +"    Error_Handler();\n"
     +"  }\n"
     +"}\n")
     f.write(time)
     f.write("void Error_Handler(void)\n{\n}\n")          
     f.close()
     f=open("/home/pi/newtest/test.c", mode='r')
     words=f.read()
     print(words)
     f.close()
     server_log(msg['command'],"D1","ok")
 
 
def GPIO(relay,status):
       if relay=="relay1":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_RESET);\n"    
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay2":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_SET);\n"
        else: 
            act=""
       elif relay=="relay3":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_SET);\n"
        else: 
            act=""
       elif relay=="relay4":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay5":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_SET);\n"
        else: 
            act=""
       elif relay=="relay6":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay7":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay8":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay9":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_SET);\n"
        else: 
            act=""
       elif relay=="relay10":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_SET);\n"
        else: 
            act=""
       elif relay=="relay11":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay12":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay13":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay14":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay15":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="relay16":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_SET);\n"
        else: 
            act=""
       elif relay=="relay17":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_SET);\n"
        else: 
            act=""
       elif relay=="relay18":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_SET);\n"
        else: 
            act=""
       elif relay=="relay19":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_SET);\n"
        else: 
            act=""
       elif relay=="relay20":
        if status=="on":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_RESET);\n"
        elif status=="off":
            act="    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_SET);\n"
        else: 
            act="" 
       elif relay=="timesleep":
        if status=="5":
            act="    HAL_Delay(500);\n"
        elif status=="10":
            act="    HAL_Delay(1000);\n"
        else: 
            act=""
       elif relay=="tank_motor_status":
        if status=="5":
            act="    PWM(500);\n"
        elif status=="10":
            act="    PWM(1000);\n"
        else: 
            act=""  
       else: 
            act=""  
       return act   

       

def PH(pin_position,pin_type):
  global pin_variables,pin_code
  if pin_type =="PH":
       print("PH ok")
       pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
             +"float "+pin_position+"voltage_V =0;\n"
             +"float pH_mid = 1.500;\n"
             +"float pH_low = 2.030;\n"
             +"float pH_high =0.975;\n"
             +"float "+pin_position+"_"+pin_type+"=0;\n")
       pin_code=("    HAL_ADC_Start(&hadc1);\n"
     +"    HAL_ADC_PollForConversion(&hadc1, 50);\n"
     +"    if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
     +"      {\n"
     +"          AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +'          printf("voltage : %1.3fV\\n",(AD_Value*3.3f/4096));\n'
     +"          voltage_V = AD_Value*3.3f/4096;\n"
     +"          if (voltage_V > pH_mid)\n" 
     +"           {\n"
     +"               "+pin_position+"_"+pin_type+" = 7.0 - 3.0 / (pH_low - pH_mid) * (voltage_V - pH_mid);\n"
     +"           }\n"
     +"          else\n" 
     +"           {\n"
     +"               "+pin_position+"_"+pin_type+" = 7.0 - 3.0 / (pH_mid - pH_high) * (voltage_V - pH_mid);\n"
     +"           }\n"
     +'	       printf("'+pin_position+"_"+pin_type+': %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
     +"      }\n"
     +"    HAL_Delay(10000);\n")
      
  else:
     pin_variables=""
     pin_code=""
def DO(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="DO":
       print("DO ok")
       pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
             +"float "+pin_position+"voltage_V =0;\n"
             +"float DO_offset =0.44;\n"
             +"float "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    HAL_ADC_Start(&hadc1);\n"
     +"    HAL_ADC_PollForConversion(&hadc1, 50);\n"
     +"    if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
     +"      {\n"
     +"          AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +'          printf("voltage : %1.3fV\\n",(AD_Value*3.3f/4096));\n'
     +"          voltage_V = AD_Value*3.3f/4096;\n"
     +"          "+pin_position+"_"+pin_type+"= (((AD_Value*3.3f/4096)*100)/DO_offset);\n"
     +'          printf("'+pin_position+"_"+pin_type+' : %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
     +"      }\n"
     +"      HAL_Delay(10000);\n")
   
 else:
     pin_variables=""
     pin_code=""

def WATERLEVEL(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="WATERLEVEL":
       print("WATERLEVEL ok")
       pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
             +"float "+pin_position+"voltage_V =0;\n"
             +"float "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    HAL_ADC_Start(&hadc1);\n"
     +"    HAL_ADC_PollForConversion(&hadc1, 50);\n"
     +"    if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
     +"      {\n"
     +"          AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +"          voltage_V = AD_Value*3.3f/4096;\n"
     +"          "+pin_position+"_"+pin_type+"= (((AD_Value*3.3f/4096)*10));\n"
     +'          printf("'+pin_position+"_"+pin_type+' : %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
     +"      }\n"
     +"      HAL_Delay(10000);\n")
 else:
     pin_variables=""
     pin_code="" 
 
def ORP(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="ORP":
       print("ORP ok")
       pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
             +"float "+pin_position+"voltage_V =0;\n"
             +"float ORP_offset =0;\n"
             +"float "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    HAL_ADC_Start(&hadc1);\n"
     +"    HAL_ADC_PollForConversion(&hadc1, 50);\n"
     +"    if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
     +"      {\n"
     +"          AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +"          voltage_V = AD_Value*3.3f/4096;\n"
     +"          "+pin_position+"_"+pin_type+"= (((AD_Value*3.3f/4096)-(1.5+ORP_offset)));\n"
     +'          printf("'+pin_position+"_"+pin_type+' : %1.3f\\n",'+pin_position+"_"+pin_type+');\n'
     +"      }\n"
     +"      HAL_Delay(10000);\n")       
   
 else:
     pin_variables=""
     pin_code=""

def ESMUS07(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="ESMUS07":
       print("ESMUS07 ok")
       pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
             +"float "+pin_position+"voltage_V =0;\n"
             +"float "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    HAL_ADC_Start(&hadc1);\n"
     +"    HAL_ADC_PollForConversion(&hadc1, 50);\n"
     +"    if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
     +"      {\n"
     +"          AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +"          voltage_V = AD_Value*5.3f/4096;\n"
     +"          if  (voltage_V==0)\n"
     +"          {\n"
     +'             printf("'+pin_position+"_"+pin_type+':100\\n");\n'
     +"          }\n" 
     +"          else\n"     
     +"          {\n"     
     +"             "+pin_position+"_"+pin_type+ " = (voltage_V*180)+100;\n"
     +'             printf("'+pin_position+"_"+pin_type+' : %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
     +"          }\n"
     +"      }\n"
     +"      HAL_Delay(10000);\n")            
 else:
     pin_variables=""
     pin_code=""

def SEN0189(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="SEN0189":
       print("SEN0189 ok")
       pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
             +"float "+pin_position+"voltage_V =0;\n"
             +"float "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    HAL_ADC_Start(&hadc1);\n"
     +"    HAL_ADC_PollForConversion(&hadc1, 50);\n"
     +"    if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
     +"      {\n"
     +"          AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +"          voltage_V = AD_Value*5.0f/4096;\n"
     +"          if  (voltage_V>4.2)\n"
     +"          {\n"
     +'             printf("'+pin_position+"_"+pin_type+': 0\\n");\n'
     +"          }\n" 
     +"          else if (voltage_V<2.5)\n"    
     +"          {\n"         
     +'             printf("'+pin_position+"_"+pin_type+' : 3000\\n");\n'
     +"          }\n"
     +"          else\n"
     +"          {\n"
     +"             "+pin_position+"_"+pin_type+"=(-1120.4*voltage_V*voltage_V)+(5742.3*voltage_V)-4352.9;\n"
     +'             printf("'+pin_position+"_"+pin_type+' : %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
     +"          }\n"
     +"      }\n"
     +"      HAL_Delay(10000);\n")       
       print(pin_variables)
       print(pin_code)       
 else:
     pin_variables=""
     pin_code=""


def SERVO(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="Servo":
       print("Servo ok")
       pin_code=("    HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n")
       
       pin_add_code=("     void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
                    +"{\n"
                    +"   if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
                    +"   {\n"
                    +"     direction=checkfeedback[1];\n"
                    +"     if(direction==0)\n"
                    +"     {\n"
                    +"       HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
                    +"       HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_SET);\n"
                    +"       user_pwm_setvalue(50);\n"
                    +"     }\n"      
                    +"     else if(direction==1)\n"
                    +"     {\n"
                    +"       HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
                    +"       HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
                    +"       user_pwm_setvalue(50);\n"
                    +"     }\n" 
                    +"     else\n"
                    +"     {\n"
                    +"       HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);\n"
                    +"       HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
                    +"       user_pwm_setvalue(0);\n"
                    +"     }\n"
                    +"   }\n" 
                    +"}\n")                         
       print(pin_code) 
       print(pin_add_code) 
 else:
     pin_variables=""
     pin_code=""   
 
def MOTOR(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="Servo":
       print("Servo ok")
       pin_code=("    HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n"
                +"    HAL_Delay(100);\n"
                +"    if(direction==0)\n"
                +"       {\n"
                +"           user_pwm_setvalue2(0);\n"
                +"           user_pwm_setvalue(pwm_value);\n"
                +"       }\n"
                +"     else\n"
                +"       {\n"
                +"            user_pwm_setvalue2(pwm_value);\n"
                +"            user_pwm_setvalue(0);\n"
                +"       }\n")
       
       pin_add_code=("     void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
                    +"{\n"
                    +"   if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
                    +"   {\n"
                    +"     pwm_value=checkfeedback[1];\n"
                    +"     direction=checkfeedback[2];\n"
                    +'     printf("%d",pwm_value);\n'
                    +"   }\n" 
                    +"}\n")                         
       print(pin_code) 
       print(pin_add_code) 
 else:
     pin_variables=""
     pin_code=""   

def SOIL(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="Soil":
       print("SOIL ok")
       pin_code=("    HAL_UART_Transmit(&huart2, (uint8_t *)soil,sizeof(soil),50);\n"
                +"    HAL_UART_Receive_IT(&huart2, (uint8_t *)data,sizeof(data));\n")
       
       pin_add_code=("   void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart);\n"
                    +"{\n"       
                    +"   if(huart->Instance == USART2);\n"
                    +"   {\n"
                    +"     if(data[0]==0x01 && data[1]==0x03)\n"
                    +"     {\n"
                    +"       rh = (data[3] << 8) + data[4];\n"
                    +"       temp = (data[5] << 8) + data[6];\n"
                    +"       ec = (data[7] << 8) + data[8];\n"
                    +'       printf("%4d\\n",rh);\n'
                    +'       printf("%4d\\n",temp);\n'
                    +'       printf("%4d\\n",ec);\n'
                    +"     }\n"      
                    +"   }\n" 
                    +"}\n")                         
       print(pin_variables)
       print(pin_code) 
       print(pin_add_code) 
         


def SHT11(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="SHT11":
       print("SHT11 ok")
       pin_variables=("uint16_t i,val,value_H,value_L,Cvalue,Hvalue;\n"
             +"int error;\n"
             +"float C1=-2.0468;\n"
             +"float C2=0.0367;\n"
             +"float C3=-0.0000015955;\n"
             +"float RH_Lin;\n"
             +"float RH_Ture;\n"
             +"float d1=-39.6;\n"
             +"float d2=0.01;\n"
             +"float T1=0.01;\n"
             +"float T2=0.00008;\n"
             +"float temp_C=0;\n"
             +"int temp;\n"
             +"int RH;\n")
       pin_code=("    Cvalue=0;\n"
     +"    Hvalue=0;\n"
     +"    value_H=0;\n"
     +"    value_L=0;\n"
     +"    SHT10_TransStart();\n"
     +"    SHT10_WriteByte();\n"
     +"    MX_GPIO_Input();\n"
     +"    HAL_Delay(250);\n"
     
     +"    if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)\n"
     +"      {\n"
     +"          SHT10_ReadByte();\n"
     +"          value_H=val;\n"
     +"          SHT10_ReadByte();\n"
     +"          value_L=val;\n"
     +"          Cvalue = (value_H<< 8 | value_L)\n"
     +"      }\n"
     +"    SHT10_TransStart();\n"
     +"    SHT10_WriteByte2();\n"
     +"    MX_GPIO_Input();\n"
     +"    HAL_Delay(250);\n"
     +"    if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)\n"
     +"      {\n"
     +"          SHT10_ReadByte();\n"
     +"          value_H=val;\n"
     +"          SHT10_ReadByte();\n"
     +"          value_L=val;\n"
     +"          Hvalue = (value_H<< 8 | value_L)\n"
     +"      }\n"
     +"    SHT10_Calculate();\n"   
     +"    HAL_Delay(10000);\n")  
     
       pin_add_code=("   void SHT10_TransStart(void)\n"
                    +"{\n"       
                    +"   MX_GPIO_Init();\n"
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n"
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
                    +"   HAL_Delay(10);\n"                                                          
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"                       
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"   
                    +"   HAL_Delay(10);\n"   
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
                    +"   HAL_Delay(10);\n"      
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n" 
                    +"   HAL_Delay(10);\n"     
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"      
                    +"}\n"                                       
                    +"   void SHT10_WriteByte(void)\n"
                    +"{\n"       
                    +"   MX_GPIO_Init();\n"
                    +"   for (i=0x80;i>0;i/=2)\n"
                    +"   {\n"
                    +"      if(i & 0x03)\n"
                    +"          HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n"
                    +"      else\n"    
                    +"          HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"                                                          
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
                    +"   HAL_Delay(10);\n"                       
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"   
                    +"   HAL_Delay(10);\n"   
                    +"   }\n" 
                    +"   MX_GPIO_Input();\n"                   
                    +"   HAL_Delay(10);\n"      
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n" 
                    +"   HAL_Delay(10);\n"  
                    +"   error=HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_4);\n"   
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"      
                    +"}\n"                         
                    +"   void SHT10_WriteByte2(void)\n"
                    +"{\n"       
                    +"   MX_GPIO_Init();\n"
                    +"   for (i=0x80;i>0;i/=2)\n"
                    +"   {\n"
                    +"      if(i & 0x05)\n"
                    +"          HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n"
                    +"      else\n"    
                    +"          HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"                                                          
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
                    +"   HAL_Delay(10);\n"                       
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"   
                    +"   HAL_Delay(10);\n"   
                    +"   }\n" 
                    +"   MX_GPIO_Input();\n"                   
                    +"   HAL_Delay(10);\n"      
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n" 
                    +"   HAL_Delay(10);\n"  
                    +"   error=HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_4);\n"   
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"      
                    +"}\n"                   
                    +"   void SHT10_ReadByte(void)\n"
                    +"{\n"  
                    +"   val=0;\n"     
                    +"   MX_GPIO_Input();\n"
                    +"   for (i=0x80;i>0;i/=2)\n"
                    +"   {\n"
                    +"      HAL_Delay(10);\n"
                    +"      HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
                    +"      HAL_Delay(10);\n"
                    +"      if(HAL_GPIO_ReadPin(GPIOA,GPIO_Pin_4))\n"
                    +"          val=( val | i );\n"   
                    +"      HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
                    +"   }\n"
                    +"   MX_GPIO_Init();\n"                   
                    +"   if(1)\n"                                                          
                    +"      HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);\n"
                    +"   else\n"                                            
                    +"      HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n"   
                    +"   HAL_Delay(10);\n"                         
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n" 
                    +"   HAL_Delay(10);\n"  
                    +"   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"      
                    +"}\n"                  
                    +"   void SHT10_Calculate(void)\n"
                    +"{\n"  
                    +"   temp_C=d1+d2*Cvalue;\n"     
                    +"   RH_Lin = C1+C2*Hvalue+C3*Hvalue*Hvalue;\n"
                    +"   RH_Ture= (temp_C-25)*(T1+T2*Hvalue)+RH_Lin;\n"
                    +"   if(RH_Ture>100)\n"
                    +"     RH_Ture= 100;\n"
                    +"   if(RH_Ture<0.1)\n"
                    +"     RH_Ture=0.1;\n"
                    +"   if(temp_C<0)\n"
                    +"   {\n"
                    +"      cmd[1]=1;\n"
                    +"      cmd[2]=-1*temp_C;\n"
                    +"      temp=(-10*temp_C);\n"
                    +"      cmd[3]=temp%10;\n"
                    +"      cmd[4]=RH_Ture;\n"   
                    +"      RH=RH_Ture*10;\n"
                    +"      cmd[5]=RH%10;\n"
                    +"   }\n"
                    +"   else\n"
                    +"   {\n"                  
                    +"      cmd[1]=0;\n"                                                          
                    +"      cmd[2]=temp_C;\n"
                    +"      temp=(10*temp_C);\n"                                            
                    +"      cmd[3]=temp%10;\n"   
                    +"      cmd[4]=RH_Ture;\n"                         
                    +"      RH=RH_Ture*10;\n" 
                    +"      cmd[5]=RH%10;\n"  
                    +"    }\n"                  
                    +"}\n")        
       print(pin_variables)
       print(pin_code) 
       print(pin_add_code)      


def BMP280(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_type =="BMP280":
       print("BMP280 ok")
       pin_variables=("HAL_StatusTypeDef Status;\n"
             +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC;\n"
             +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC;\n"
             +"#define ADDR_AT24C04_READ 0xED;\n"
             +"#define AT24C04_PAGE_SIZE 16;\n"
             +"#define AT24C04_TIMEOUT 0xED;\n"
             +"#define BUFFER_SIZE 1;\n"
             +"uint16_t dig_T1;\n"
             +"uint16_t dig_T2;\n"
             +"uint16_t dig_T3;\n"
             +"uint16_t dig_P1;\n"
             +"uint16_t dig_P2;\n"
             +"uint16_t dig_P3;\n"
             +"uint16_t dig_P4;\n"
             +"uint16_t dig_P5;\n"
             +"uint16_t dig_P6;\n"
             +"uint16_t dig_P7;\n"
             +"uint16_t dig_P8;\n"
             +"uint16_t dig_P9;\n"
             +"uint32_t adc_P=0;\n"
             +"uint32_t adc_T=0;\n"
             +"uint8_t WriteBuffer[BUFFER_SIZE]={0xb6};\n"
             +"uint8_t WriteBuffer1[BUFFER_SIZE]={0xff};\n"  
             +"uint8_t WriteBuffer2[BUFFER_SIZE]={0x00};\n"  
             +"uint8_t ReadBuffer[BUFFER_SIZE];\n"               
             +"int RH;\n")
       pin_code=("    Cvalue=0;\n"
     +"    Hvalue=0;\n"
     +"    value_H=0;\n"
     +"    value_L=0;\n"
     +"    SHT10_TransStart();\n"
     +"    SHT10_WriteByte();\n"
     +"    MX_GPIO_Input();\n"
     +"    HAL_Delay(250);\n"
     
     +"    if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)\n"
     +"      {\n"
     +"          SHT10_ReadByte();\n"
     +"          value_H=val;\n"
     +"          SHT10_ReadByte();\n"
     +"          value_L=val;\n"
     +"          Cvalue = (value_H<< 8 | value_L)\n"
     +"      }\n"
     +"    SHT10_TransStart();\n"
     +"    SHT10_WriteByte2();\n"
     +"    MX_GPIO_Input();\n"
     +"    HAL_Delay(250);\n"
     +"    if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)\n"
     +"      {\n"
     +"          SHT10_ReadByte();\n"
     +"          value_H=val;\n"
     +"          SHT10_ReadByte();\n"
     +"          value_L=val;\n"
     +"          Hvalue = (value_H<< 8 | value_L)\n"
     +"      }\n"
     +"    SHT10_Calculate();\n"   
     +"    HAL_Delay(10000);\n") 
           
## 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')

## 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):
    msg.payload = msg.payload.decode('utf-8')
    jsonmsg = json.loads(msg.payload)
    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'] == 'a061'):
        download(jsonmsg)
    elif (jsonmsg['command'] == 'a060'):
        ota(jsonmsg)
    elif (jsonmsg['command'] == 'a058'):
        otastart(jsonmsg)
    elif (jsonmsg['command'] == 'a059'):
        #download(jsonmsg)
        otatest(jsonmsg)
    elif (jsonmsg['command'] == 'a062'):
        ICP(jsonmsg)
    elif (jsonmsg['command'] == 'a063'):
        ISP(jsonmsg)
    elif (jsonmsg['command'] == 'a064'):
        clear(jsonmsg)
    elif (jsonmsg['command'] == 'tank_solenoid_waterL2L3_status'):
        valve5(jsonmsg)
    elif (jsonmsg['command'] == 'tank_solenoid_waterL4L5_status'):
        valve6(jsonmsg)
    elif (jsonmsg['command'] == 'tank_pump_waterL4L5_status'):
        count=1
        pump1(jsonmsg,count)  
    elif (jsonmsg['command'] == 'tank_pump_waterInput_status'):
        count=3
        pump1(jsonmsg,count) 
    elif (jsonmsg['command'] == 'tank_pump_waterL2L3_status'):
        count=2
        pump1(jsonmsg,count)
    elif (jsonmsg['command'] == 'system_update'):
        system_update(jsonmsg)
    elif (jsonmsg['command'] == 'tank_vacuum_status'): 
        vacuum(jsonmsg)
    elif (jsonmsg['command'] == 'tank_threewayvalve_input_status'):
        threewayvalve_input(jsonmsg)
    elif (jsonmsg['command'] == 'tank_diskvalve_status'):
        diskvalve(jsonmsg)
    elif (jsonmsg['command'] == 'tank_solenoid_disinfect_status'):
        disinfect(jsonmsg)
    elif (jsonmsg['command'] == 'tank_motor_status'):
        stir(jsonmsg)
    elif (jsonmsg['command'] == 'tank_heater1_status'):
        heater1(jsonmsg)
    elif (jsonmsg['command'] == 'tank_heater2_status'):
        heater2(jsonmsg)
    elif (jsonmsg['command'] == 'tank_temp'):
        air_temp(jsonmsg)
    elif (jsonmsg['command'] == 'temptime'):
        temp_time(jsonmsg)
    elif (jsonmsg['command'] == 'tank_temp_enable'):
        air_temp_enable(jsonmsg)
    elif (jsonmsg['command'] == 'input_vacuum_status'):
        input_vacuum(jsonmsg)
    elif (jsonmsg['command'] == 'output_vacuum_status'):
        output_vacuum(jsonmsg)
    elif (jsonmsg['command'] == 'tank_pump_sensor_status'):
        count=0
        pump(jsonmsg,count)   
    elif (jsonmsg['command'] == 'solenoid_tank_pump_status'):
        solenoid_tank_pump(jsonmsg)
    elif (jsonmsg['command'] == 'tank_solenoid_water_in_status'):
        water_in(jsonmsg)
    elif (jsonmsg['command'] == 'outer_solenoid_water_status'):
        water(jsonmsg)     
    elif (jsonmsg['command'] == 'outer_threewayvalve_float_status'):
        threewayvalve_float(jsonmsg)            
    elif (jsonmsg['command'] == 'tank_solenoid_water_out_status'):
        water_out(jsonmsg)     
    elif (jsonmsg['command'] == 'tank_solenoid_water_status'):
        drain(jsonmsg)  
    elif (jsonmsg['command'] == 'tank_blower_status'):
        blower(jsonmsg) 
    elif (jsonmsg['command'] == 'SHT11'):
        sht11(jsonmsg) 
    elif (jsonmsg['command'] == 'SHT12'):
        sht12(jsonmsg) 
    elif (jsonmsg['command'] == 'sonic'):
        sonic(jsonmsg) 
    elif (jsonmsg['command'] == 'ferment'):
        ferment(jsonmsg)
    elif (jsonmsg['command'] == 'ferment_close'):
        ferment_close(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_schedule'):
        valve(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_Input'):
        ferment_input(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_Upload'):
        ferment_upload(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_input_bean'):
        ferment_input_bean(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_add_outer_water'):
        ferment_add_outer_water(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_add_inner_water'):
        ferment_add_inner_water(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_heat'):
        ferment_heat(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_drain_inner_water'):
        ferment_drain_inner_water(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_out_bean'):
        ferment_out_bean(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_disinfect'):
        ferment_disinfect(jsonmsg)
    elif (jsonmsg['command'] == 'Ferment_restart'):
        ferment(jsonmsg)
    elif (jsonmsg['command'] == 'Condition_setting'):
        #sql_local_pin_configuration(jsonmsg)
        sql_local_code_upload(jsonmsg)
        ferment_pin_configuration(jsonmsg)
    #elif (jsonmsg['command'] == 'Dry_OTA'):
        #creat_hex(jsonmsg)
    #elif (jsonmsg['command'] == 'Pin_assignment'):
        #sql_local_pin_configuration(jsonmsg)
    elif (jsonmsg['command'] == 'Code_upload'):
        OTA_UPLOAD(jsonmsg)
        #OTA_hex(jsonmsg)
        #OTA_hex_save(jsonmsg)
    #else:
        #server_log(jsonmsg['command'],jsonmsg['tank_num'],'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()
