#!/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 array
import numpy
import base64
import datetime
import numpy as np
import pymysql.cursors
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 = "b8:27:eb:b4:59:3e"

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

## 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.
#串口設定

#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)


               
## 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 creat_hex(msg):
     f=open("/home/gitc/桌面/CTO20220622/Src/main.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 "i2c.h"\n'
       +'#include "time.h"\n'
       +'#include "gpio.h"\n')
     f.write(header)
#參數變數宣告說明-----------------------------------------------------------------------------------------------
     f.write("\n"
       +"/* Private variables ---------------------------------------------------------*/\n"
       +"#define VECT_TAB_OFFSET  0x10000\n"
       +'int tankstatus = 0;\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):
         if(i==3 or i==4 or i==6): 
           PH("M"+str(i+1),row[i+26])
           f.write(pin_variables)
           DO("M"+str(i+1),row[i+26])
           f.write(pin_variables)
           ORP("M"+str(i+1),row[i+26]) 
           f.write(pin_variables) 
         if(i==13):
           SHT11("M"+str(i+1),row[i+26])
           f.write(pin_variables) 
         if(i==14):
           BMP280("M"+str(i+1),row[i+26])
           f.write(pin_variables) 
         if(i==5 or i==12):
           SEN0189("M"+str(i+1),row[i+26])
           f.write(pin_variables) 
         if(i==0):
           SonicESMUS07("M"+str(i+1),row[i+26])
           f.write(pin_variables) 
         if(i==7):
           SOIL("M"+str(i+1),row[i+26])
           f.write(pin_variables) 
         if(i==8 or i==11 or i==18 or i==10): 
           WATERLEVEL("M"+str(i+1),row[i+26])
           f.write(pin_variables)  
           feedback("M"+str(i+1),row[i+26])
           f.write(pin_variables)  
         if(i==15):
           EC("M"+str(i+1),row[i+26])
           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"
       +"void MX_GPIO_Input1(unsigned long pin);\n"
       +"void sensor(void);\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):
         if(i==13):
           SHT11("M"+str(i+1),row[i+26])
           f.write(sensor_code) 
         if(i==14):
           BMP280("M"+str(i+1),row[i+26])
           f.write(sensor_code) 
         if(i==9):
           motor("M"+str(i+1),row[i+26])
           f.write(sensor_code) 
     f.write("/* 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"
       +"  SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET;\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")
     f.write(enable)
     #連接資料庫
     #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):
         if(i==14):
           BMP280("M"+str(i+1),row[i+26])
           f.write(init_code)
         if(i==9):
           motor("M"+str(i+1),row[i+26])
           f.write(init_code)      
#---------------------------------------------------------------------------------------------     
     code=("  while (1)\n"
     +"  {\n"
     +"    sensor();\n")
     f.write(code)
#MQTT條件分析寫入--------------------------------------------------------------------------------
     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[1]
         m[2]=m[2]
         m[3]=m[3]
         m[4]=m[4]
      m=""+m[0]+"("+m[1]+m[2]+m[3]
      f.write("    "+m)
      if(m[0]==" "):
        m=""
      else:
       print(len(msg['cond'][i]['cond_add']))
       if(len(msg['cond'][i]['cond_add'])==0):
             add=")\n"
             f.write(add)
       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("_")
             comm=msg['cond'][i]['cond_com'][j].split(" ")
             if(comm[0]=="sleep"):
                com[0]=comm[0]
             com="     "+GPIO(com[0],comm[1])+"\n    }\n"
             f.write(com) 
        else:
            if(msg['cond'][i]['cond_com'][j]==" "):
             com=""
            else:
             com=msg['cond'][i]['cond_com'][j].split("_")
             comm=msg['cond'][i]['cond_com'][j].split(" ")
             if(comm[0]=="sleep"):
                com[0]=comm[0]
             com="     "+GPIO(com[0],comm[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)
#馬達和伺服馬達副函式------------------------------------------------------------------------------
     add_code2=("void user_pwm_setvalue(uint16_t value)\n"
                      +"{\n"
                      +"    TIM_OC_InitTypeDef sConfigOC;\n"
                      +"    sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
                      +"    sConfigOC.Pulse = value;\n"
                      +"    sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
                      +"    sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
                      +"    HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);\n"
                      +"    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);\n" 
                      +"}\n"
                      +"void user_pwm_setvalue2(uint16_t value)\n"
                      +"{\n"
                      +"    TIM_OC_InitTypeDef sConfigOC;\n"
                      +"    sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
                      +"    sConfigOC.Pulse = value;\n"
                      +"    sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
                      +"    sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
                      +"    HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2);\n"
                      +"    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);\n"  
                      +"}\n")
     f.write(add_code2)
#感測器程式-----------------------------------------------------------------------------------------------------
     sensor=("void sensor(void)\n"
                      +"{\n")
     f.write(sensor)
     
     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): 
         if(i==3 or i==4 or i==6): 
           PH("M"+str(i+1),row[i+26])
           f.write(pin_code)
           DO("M"+str(i+1),row[i+26])
           f.write(pin_code)
           ORP("M"+str(i+1),row[i+26]) 
           f.write(pin_code) 
         if(i==13):
           SHT11("M"+str(i+1),row[i+26])
           f.write(pin_code) 
         if(i==14):
           BMP280("M"+str(i+1),row[i+26])
           f.write(pin_code) 
         if(i==5 or i==12):
           SEN0189("M"+str(i+1),row[i+26])
           f.write(pin_code) 
         if(i==0):
           SonicESMUS07("M"+str(i+1),row[i+26])
           f.write(pin_code) 
         if(i==7):
           SOIL("M"+str(i+1),row[i+26])
           f.write(pin_code) 
         if(i==8 or i==11 or i==18 or i==10): 
           WATERLEVEL("M"+str(i+1),row[i+26])
           f.write(pin_code)  
           feedback("M"+str(i+1),row[i+26])
           f.write(pin_code)  
         if(i==15):
           EC("M"+str(i+1),row[i+26])
           f.write(pin_code)
     sensor=("    HAL_Delay(10000);\n"  
                      +"}\n") 
     f.write(sensor)    
     
#加入感測器副函式程式碼-------------------------------------------------------------------------------
     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):   
         if(i==13):
           SHT11("M"+str(i+1),row[i+26])
           f.write(pin_add_code) 
         if(i==14):
           BMP280("M"+str(i+1),row[i+26])
           f.write(pin_add_code)
         if(i==0):
           SonicESMUS07("M"+str(i+1),row[i+26])
           f.write(pin_add_code) 
         if(i==7):
           SOIL("M"+str(i+1),row[i+26])
           f.write(pin_add_code) 
         if(i==15):
           EC("M"+str(i+1),row[i+26])
           f.write(pin_add_code)  
#ADC程式宣告----------------------------------------------------------------------------------
     gpio=("void MX_ADC1_Init1(char pin)\n"
+"{\n"
+"  ADC_ChannelConfTypeDef sConfig = {0};\n"
+"  hadc1.Instance = ADC1;\n"
+"  hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;\n"
+"  hadc1.Init.Resolution = ADC_RESOLUTION_12B;\n"
+"  hadc1.Init.ScanConvMode = DISABLE;\n"
+"  hadc1.Init.ContinuousConvMode = DISABLE;\n"
+"  hadc1.Init.DiscontinuousConvMode = DISABLE;\n"
+"  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;\n"
+"  hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;\n"
+"  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;\n"
+"  hadc1.Init.NbrOfConversion = 1;\n"
+"  hadc1.Init.DMAContinuousRequests = DISABLE;\n"
+"  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;\n"
+"    if (HAL_ADC_Init(&hadc1) != HAL_OK)\n"
+"    {\n"
+"      Error_Handler();\n"
+"    }\n"
+"  sConfig.Channel = pin;\n"
+"  sConfig.Rank = 1;\n"
+"  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;\n"
+"  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)\n"
+"  {\n"
+"    Error_Handler();\n"
+"  }\n"
+"}\n")
     f.write(gpio)  
#GPIO input程式宣告----------------------------------------------------------------------------------
     gpio2=("void MX_GPIO_Input1(unsigned long pin)\n"
+"{\n"
+"  GPIO_InitTypeDef GPIO_InitStruct = {0};\n"
+"  __HAL_RCC_GPIOE_CLK_ENABLE();\n"
+"  GPIO_InitStruct.Pin = pin;\n"
+"  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;\n"
+"  GPIO_InitStruct.Pull = GPIO_PULLDOWN;\n"
+"  HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);\n"
+"}\n")
     f.write(gpio2)  
#錯誤程式-------------------------------------------------------------------------------------            
     f.write("void Error_Handler(void)\n{\n}\n")          
     f.close()
     f=open("/home/gitc/桌面/CTO20220622/Src/main.c", mode='r')
     words=f.read()
     print(words)
     f.close()
#程式轉檔成hex檔-----------------------------------------------------------------------------------
     n=subprocess.call(["make"],cwd="/home/gitc/桌面/CTO20220622/")
     if n>0:
       server_log(msg['command'],"D1","error")
     else:
       server_log(msg['command'],"D1","success")
 
 
#致動器功能程式定義
def GPIO(relay,status):
       if relay=="R1":
        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=="R2":
        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=="R3":
        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=="R4":
        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=="R5":
        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=="R6":
        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=="R7":
        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=="R8":
        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=="R9":
        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=="R10":
        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=="R11":
        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=="R12":
        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=="R13":
        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=="R14":
        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=="R15":
        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=="R16":
        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=="R17":
        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=="R18":
        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=="R19":
        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=="R20":
        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=="sleep":
            act="    HAL_Delay("+status+"000);\n"
       elif relay=="M10":
        if int(status)>0:
            act=("    user_pwm_setvalue2(0);\n"
                +"         user_pwm_setvalue("+status+");\n")
        elif int(status)<0:
            status=-1*int(status)
            act=("    user_pwm_setvalue(0);\n"
                +"         user_pwm_setvalue2("+str(status)+");\n")
        else: 
            act=""
       elif relay=="M2":
        if status=="on":
            act="    user_pwm_setvalue3(50);\n"
        elif status=="off":
            act="    user_pwm_setvalue3(180);\n"
        else: 
            act=""
       elif relay=="M3":
        if  status=="on":
            act="    user_pwm_setvalue4(50);\n"
        elif status=="off":
            act="    user_pwm_setvalue4(180);\n"
        else: 
            act=""          
       else: 
            act=""  
       return act   

       
#感測器功能程式定義
def PH(pin_position,pin_type):
  global pin_variables,pin_code
  if pin_position=="M4":
     pin="ADC_CHANNEL_0"
  elif pin_position=="M5":
     pin="ADC_CHANNEL_3"
  elif pin_position=="M7":
     pin="ADC_CHANNEL_4"
  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 "+pin_position+"_pH_mid = 1.500;\n"
             +"float "+pin_position+"_pH_low = 2.030;\n"
             +"float "+pin_position+"_pH_high =0.975;\n"
             +"float "+pin_position+"_"+pin_type+"=0;\n")
       pin_code=("    MX_ADC1_Init("+pin+");\n"
     +"    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"
     +"          "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +"          "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
     +"          if ("+pin_position+"_voltage_V > "+pin_position+"_pH_mid)\n" 
     +"           {\n"
     +"               "+pin_position+"_"+pin_type+" = 7.0 - 3.0 / ("+pin_position+"_pH_low - "+pin_position+"_pH_mid) * ("+pin_position+"_voltage_V - "+pin_position+"_pH_mid);\n"
     +"           }\n"
     +"          else\n" 
     +"           {\n"
     +"               "+pin_position+"_"+pin_type+" = 7.0 - 3.0 / ("+pin_position+"_pH_mid - "+pin_position+"_pH_high) * ("+pin_position+"_voltage_V - "+pin_position+"_pH_mid);\n"
     +"           }\n"
     +"      }\n"
     +"    HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
    
  else:
     pin_variables=""
     pin_code=""

  
def DO(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_position=="M4":
     pin="ADC_CHANNEL_0"
 elif pin_position=="M5":
     pin="ADC_CHANNEL_3"
 elif pin_position=="M7":
     pin="ADC_CHANNEL_4"
 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 "+pin_position+"_DO_offset =0.44;\n"
             +"float "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    MX_ADC1_Init("+pin+");\n"
     +"    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"
     +"          "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +"          "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
     +"          "+pin_position+"_"+pin_type+"= ((("+pin_position+"_AD_Value*3.3f/4096)*100)/"+pin_position+"_DO_offset);\n"
     +"      }\n"
     +"      HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
   
 else:
     pin_variables=""
     pin_code=""

def WATERLEVEL(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_position=="M9":
     pin="GPIO_PIN_9"
 elif pin_position=="M11":
     pin="GPIO_PIN_7"
 elif pin_position=="M12":
     pin="GPIO_PIN_8"
 elif pin_position=="M19":
     pin="GPIO_PIN_10"
 if pin_type =="WATERLEVEL":
       print("WATERLEVEL ok")
       pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    MX_GPIO_Input1("+pin+");\n"
             +"    if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
             +"    {\n"  
             +"       "+pin_position+"_"+pin_type+" =1;\n"
						 +"       HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
             +"    }\n"	
	           +"    else\n" 
	           +"    {\n"
             +"       "+pin_position+"_"+pin_type+" =0;\n"
             +"       HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
             +"    }\n")
 else:
     pin_variables=""
     pin_code="" 

def feedback(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_position=="M9":
     pin="GPIO_PIN_9"
 elif pin_position=="M11":
     pin="GPIO_PIN_7"
 elif pin_position=="M12":
     pin="GPIO_PIN_8"
 elif pin_position=="M19":
     pin="GPIO_PIN_10"
 if pin_type =="feedback":
       print("feedback ok")
       pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    MX_GPIO_Input1("+pin+");\n"
     +"    if (HAL_GPIO_ReadPin(GPIOE, "+pin+" == GPIO_PIN_SET)\n"
     +"    {\n"
     +"       "+pin_position+"_"+pin_type+" =1;\n"
     +"       HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
     +"    }\n"
     +"    else\n"
     +"    {\n"
     +"       "+pin_position+"_"+pin_type+" =0;\n"
     +"       HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
     +"    }\n")
 else:
     pin_variables=""
     pin_code="" 

def butterflyvalvefeedback(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_position=="M9":
     pin="GPIO_PIN_9"
 elif pin_position=="M11":
     pin="GPIO_PIN_7"
 elif pin_position=="M12":
     pin="GPIO_PIN_8"
 elif pin_position=="M19":
     pin="GPIO_PIN_10"
 if pin_type =="butterflyvalvefeedback":
       print("butterflyvalvefeedback ok")
       pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    MX_GPIO_Input1("+pin+");\n"
     +"    if (HAL_GPIO_ReadPin(GPIOE, "+pin+" == GPIO_PIN_SET)\n"
     +"    {\n"
     +"       "+pin_position+"_"+pin_type+" =1;\n"
     +"       HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
     +"    }\n"
     +"    else\n"
     +"    {\n"
     +"       "+pin_position+"_"+pin_type+" =0;\n"
     +"       HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
     +"    }\n")
 else:
     pin_variables=""
     pin_code="" 
           
def ORP(pin_position,pin_type):
 global pin_variables,pin_code
 if pin_position=="M4":
     pin="ADC_CHANNEL_0"
 elif pin_position=="M5":
     pin="ADC_CHANNEL_3"
 elif pin_position=="M7":
     pin="ADC_CHANNEL_4"
 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 "+pin_position+"_ORP_offset =0;\n"
             +"float "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    MX_ADC1_Init("+pin+");\n"
     +"    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"
     +"          "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +"          "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
     +"          "+pin_position+"_"+pin_type+"= ((("+pin_position+"_AD_Value*3.3f/4096)-(1.5+"+pin_position+"_ORP_offset)));\n"
     +"      }\n"
     +"      HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")       
   
 else:
     pin_variables=""
     pin_code=""

def SonicESMUS07(pin_position,pin_type):
 global pin_variables,pin_code,pin_add_code
 if pin_position=="M1":
     pin="ADC_CHANNEL_6"
 if pin_type =="SonicESMUS07":
       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=("    MX_ADC1_Init("+pin+");\n"
     +"    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"
     +"          "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +"          "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*5.3f/4096;\n"
     +"          if  ("+pin_position+"_voltage_V==0)\n"
     +"          {\n"
     +"             "+pin_position+"_"+pin_type+ " = 100;\n"
     +"          }\n" 
     +"          else\n"     
     +"          {\n"     
     +"             "+pin_position+"_"+pin_type+ " = ("+pin_position+"_voltage_V*180)+100;\n"
     +"          }\n"
     +"      }\n"
     +"      HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")            
 else:
     pin_variables=""
     pin_code=""
     pin_add_code=""

def SEN0189(pin_position,pin_type):
 global pin_variables,pin_code,pin_add_code
 if pin_position=="M6":
     pin="ADC_CHANNEL_13"
 elif pin_position=="M13":
     pin="ADC_CHANNEL_5"
 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=("    MX_ADC1_Init("+pin+");\n"
     +"    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"
     +"          "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
     +"          "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*5.0f/4096;\n"
     +"          if  ("+pin_position+"_voltage_V>4.2)\n"
     +"          {\n"
     +"             "+pin_position+"_"+pin_type+ " = 0;\n"
     +"          }\n" 
     +"          else if ("+pin_position+"_voltage_V<2.5)\n"    
     +"          {\n"         
     +"             "+pin_position+"_"+pin_type+ " = 3000;\n"
     +"          }\n"
     +"          else\n"
     +"          {\n"
     +"             "+pin_position+"_"+pin_type+"=(-1120.4*"+pin_position+"_voltage_V*"+pin_position+"_voltage_V)+(5742.3*"+pin_position+"_voltage_V)-4352.9;\n"
     +"          }\n"
     +"      }\n"
     +"      HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")       
       print(pin_variables)
       print(pin_code)       
 else:
     pin_variables=""
     pin_code=""  
     pin_add_code=""

def SOIL(pin_position,pin_type):
 global pin_variables,pin_code,pin_add_code
 if pin_type =="Soil":
       print("SOIL ok")
       pin_variables=("uint8_t soil[8] ={0x01,0x03,0x00,0x00,0x00,0x03,0x05,0xCB};\n"
       +"uint8_t data[11] ={0,0,0,0,0,0,0,0,0,0,0};\n"
       +"float "+pin_position+"_"+pin_type+" =0;\n"
       +"int rh=0;\n"
       +"int temp=0;\n"
       +"int ec=0;\n")
       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"
                    +"     }\n"      
                    +"   }\n" 
                    +"}\n")                         
       print(pin_code) 
       print(pin_add_code)    
 else:
     pin_variables=""
     pin_code=""
     pin_add_code=""
              
def EC(pin_position,pin_type):
 global pin_variables,pin_code,pin_add_code
 if pin_type =="EC":
       print("EC ok")
       pin_variables=("uint8_t data[4] ={0,0,0,0};\n"
       +"float "+pin_position+"_"+pin_type+" =0;\n")
       pin_code=("    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]==0x30 && data[1]==0x2E)\n"
                    +"     {\n"
                    +"       HAL_UART_Transmit(&huart4, (uint8_t *)data,sizeof(data),50);\n"
                    +"     }\n"      
                    +"   }\n" 
                    +"}\n")                         
       print(pin_variables)
       print(pin_code) 
       print(pin_add_code) 
 else:
     pin_variables=""
     pin_code=""
     pin_add_code=""
     
def SHT11(pin_position,pin_type):
 global pin_variables,pin_code,pin_add_code
 global sensor_code
 if pin_type =="SHT11":
       print("SHT11 ok")
       pin_variables=("uint8_t cmd[7]={0xFF,0x00,0x00,0x00,0x00,0x00,0x0D};\n"
             +"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"
             +"float "+pin_position+"_"+pin_type+" =0;\n")
       sensor_code=("void SHT10_TransStart(void);\n"
             +"void SHT10_WriteByte(void);\n"
             +"void SHT10_WriteByte2(void);\n"
             +"void SHT10_ReadByte(void);\n"
             +"void SHT10_Calculate(void);\n"
             +"void MX_GPIO_Input(void);\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(GPIOB,GPIO_PIN_0)==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(GPIOB,GPIO_PIN_0)==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")  
     
       pin_add_code=("   void SHT10_TransStart(void)\n"
                    +"{\n"       
                    +"   MX_GPIO_Init();\n"
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0,GPIO_PIN_SET);\n"
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_SET);\n"
                    +"   HAL_Delay(10);\n"                                                          
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"                       
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_RESET);\n"   
                    +"   HAL_Delay(10);\n"   
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_SET);\n"
                    +"   HAL_Delay(10);\n"      
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0,GPIO_PIN_SET);\n" 
                    +"   HAL_Delay(10);\n"     
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,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(GPIOB,GPIO_PIN_0,GPIO_PIN_SET);\n"
                    +"      else\n"    
                    +"          HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"                                                          
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_SET);\n"
                    +"   HAL_Delay(10);\n"                       
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_RESET);\n"   
                    +"   HAL_Delay(10);\n"   
                    +"   }\n" 
                    +"   MX_GPIO_Input();\n"                   
                    +"   HAL_Delay(10);\n"      
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_SET);\n" 
                    +"   HAL_Delay(10);\n"  
                    +"   error=HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0);\n"   
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,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(GPIOB,GPIO_PIN_0,GPIO_PIN_SET);\n"
                    +"      else\n"    
                    +"          HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0,GPIO_PIN_RESET);\n"
                    +"   HAL_Delay(10);\n"                                                          
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_SET);\n"
                    +"   HAL_Delay(10);\n"                       
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_RESET);\n"   
                    +"   HAL_Delay(10);\n"   
                    +"   }\n" 
                    +"   MX_GPIO_Input();\n"                   
                    +"   HAL_Delay(10);\n"      
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_SET);\n" 
                    +"   HAL_Delay(10);\n"  
                    +"   error=HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0);\n"   
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,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(GPIOB,GPIO_PIN_1,GPIO_PIN_SET);\n"
                    +"      HAL_Delay(10);\n"
                    +"      if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0))\n"
                    +"          val=( val | i );\n"   
                    +"      HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_RESET);\n"
                    +"   }\n"
                    +"   MX_GPIO_Init();\n"                   
                    +"   if (1)\n"                                                          
                    +"      HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0,GPIO_PIN_RESET);\n"
                    +"   else\n"                                            
                    +"      HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0,GPIO_PIN_SET);\n"   
                    +"   HAL_Delay(10);\n"                         
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,GPIO_PIN_SET);\n" 
                    +"   HAL_Delay(10);\n"  
                    +"   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_1,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")    
 else:
     pin_variables=""
     pin_code="" 
     pin_add_code=""
     sensor_code="" 
     
def BMP280(pin_position,pin_type):
 global pin_variables,pin_code,pin_add_code,init_code
 global sensor_code
 if pin_type =="BMP280":
       print("BMP280 ok")
       pin_variables=("uint8_t cmd[7]={0xFF,0x00,0x00,0x00,0x00,0x00,0x0D};\n"
             +"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_TIMEOUT 0xED\n"
             +"#define AT24C04_PAGE_SIZE 16\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")
       sensor_code=("HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);\n"
             +"HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);\n"
             +"long bmp280_T_MultipleReadThree();\n"
             +"long bmp280_P_MultipleReadThree();\n"
             +"short bmp280_MultipleReadTwo(uint16_t addr);\n")
       init_code=("  AT24C04_Write(&hi2c1,0xe0,WriteBuffer);\n"
	           +"  AT24C04_Write(&hi2c1,0xf4,WriteBuffer1);\n"
	           +"  AT24C04_Write(&hi2c1,0xf5,WriteBuffer2);\n"
             +"  dig_T1 = bmp280_MultipleReadTwo(0x88);\n"
             +"  dig_T2 = bmp280_MultipleReadTwo(0x8A);\n"
             +"  dig_T3 = bmp280_MultipleReadTwo(0x8C);\n"
             +"  dig_P1 = bmp280_MultipleReadTwo(0x8E);\n"
             +"  dig_P2 = bmp280_MultipleReadTwo(0x90);\n"
             +"  dig_P3 = bmp280_MultipleReadTwo(0x92);\n"
             +"  dig_P4 = bmp280_MultipleReadTwo(0x94);\n"
             +"  dig_P5 = bmp280_MultipleReadTwo(0x96);\n"
             +"  dig_P6 = bmp280_MultipleReadTwo(0x98);\n"
             +"  dig_P7 = bmp280_MultipleReadTwo(0x9A);\n"
             +"  dig_P8 = bmp280_MultipleReadTwo(0x9C);\n"
             +"  dig_P9 = bmp280_MultipleReadTwo(0x9E);\n")
             
       pin_code=("    adc_T=bmp280_T_MultipleReadThree();\n"
     +"    adc_P=bmp280_P_MultipleReadThree();\n"
     +"    double var1, var2,temperature,t_fine;\n"
     +"    var1 = (((double) adc_T) / 16384.0 - ((double) dig_T1) / 1024.0)* ((double) dig_T2);\n"
     +"    var2 = ((((double) adc_T) / 131072.0 - ((double) dig_T1) / 8192.0)* (((double) adc_T) / 131072.0 - ((double) dig_T1) / 8192.0))* ((double) dig_T3);\n"
     +"    t_fine = (int32_t) (var1 + var2);\n"
     +"    temperature = (var1 + var2) / 5120.0;\n"
     +"    double pressure;\n"
     +"    var1 = (t_fine / 2.0) - 64000.0;\n"
     +"    var2 = var1 * var1 * ((double) dig_P6) / 32768.0;\n"
     +"    var2 = var2 + var1 * ((double) dig_P5) * 2.0;\n"
     +"    var2 = (var2 / 4.0) + (((double) dig_P4) * 65536.0);\n"
     +"    var1 = (((double) dig_P3) * var1 * var1 / 524288.0+ ((double) dig_P2) * var1) / 524288.0;\n"
     +"    var1 = (1.0 + var1 / 32768.0) * ((double) dig_P1);\n"
     +"      if (var1 == 0.0)\n"
     +"      {\n"
     +"         var1 = 0;\n"
     +"      }\n"
     +"    pressure = 1048576.0 - (double) adc_P;\n"
     +"    pressure = (pressure - (var2 / 4096.0)) * 6250.0 / var1;\n"
     +"    var1 = ((double) dig_P9) * pressure * pressure / 2147483648.0;"
     +"    var2 = pressure * ((double) dig_P8) / 32768.0;\n"
     +"    pressure = pressure + (var1 + var2 + ((double) dig_P7)) / 16.0;\n"
     +"    cmd[1]=pressure/10000; \n"
     +"    int pa =pressure;\n"
     +"    cmd[2]=(pa%10000)/100;\n"
     +"    cmd[3]=(pa%10000)%100;\n"
     +"    HAL_UART_Transmit(&huart1, (uint8_t *)cmd, sizeof(cmd),1);")  
       pin_add_code=("HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)\n"
     +"{\n"     
	   +"       Status = HAL_I2C_Mem_Write(&hi2c1, ADDR_AT24C04_WRITE_FIRST_16_PAGES, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, AT24C04_PAGE_SIZE, AT24C04_TIMEOUT);\n"
     +"       return Status;\n"
     +"}\n"
     +"HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)\n"
     +"{\n"
     +"   Status = HAL_I2C_Mem_Read(&hi2c1, ADDR_AT24C04_READ, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, BUFFER_SIZE, AT24C04_TIMEOUT);\n"
     +"   return Status;\n"
     +"}\n"
     +"  long bmp280_T_MultipleReadThree()\n"
     +"{\n"
     +"     uint8_t msb, lsb, xlsb;\n"
	   +"     int32_t temp = 0;\n"
     +"     AT24C04_Read(&hi2c1,0xfa,ReadBuffer);\n"
	   +"     msb=ReadBuffer[0];\n"
     +"     AT24C04_Read(&hi2c1,0xfb,ReadBuffer);\n"
	   +"     lsb=ReadBuffer[0];\n"
     +"     AT24C04_Read(&hi2c1,0xfc,ReadBuffer);\n"
	   +"     xlsb=ReadBuffer[0];\n"
     +"     temp = ((msb << 12)|(lsb << 4)|(xlsb >> 4));\n"
     +"     return temp;\n"
     +"}\n"
     +"long bmp280_P_MultipleReadThree()\n"
     +"{\n"
     +"   uint8_t msb, lsb, xlsb;\n"
     +"   int32_t pressure = 0;\n"
     +"   AT24C04_Read(&hi2c1,0xf7,ReadBuffer);\n"
	   +"   msb=ReadBuffer[0];\n"
     +"   AT24C04_Read(&hi2c1,0xf8,ReadBuffer);\n"
	   +"   lsb=ReadBuffer[0];\n"
     +"   AT24C04_Read(&hi2c1,0xf9,ReadBuffer);\n"
	   +"   xlsb=ReadBuffer[0];\n"
     +"   pressure = ((msb << 12)|(lsb << 4)|(xlsb >> 4));\n"
     +"   return pressure;\n"
     +"}\n"
     +"  short bmp280_MultipleReadTwo(uint16_t addr )\n"
     +"{\n"
     +"   uint8_t msb, lsb;\n"
     +"   uint16_t temp = 0;\n"
     +"   AT24C04_Read(&hi2c1,addr,ReadBuffer);\n"
     +"   lsb = ReadBuffer[0];\n"
     +"   AT24C04_Read(&hi2c1,addr+1,ReadBuffer);\n"
     +"   msb = ReadBuffer[0];\n"
     +"   temp = msb << 8|lsb;\n"
     +"   return temp;\n"
     +"}\n")
 else:
     pin_variables=""
     pin_code=""  
     pin_add_code=""  
     init_code=""  
     

def motor(pin_position,pin_type):
 global act_code,init_code
 global sensor_code
 if pin_type =="Motor":
       print("motor ok")
       sensor_code=("void user_pwm_setvalue(uint16_t value);\n"
                   +"void user_pwm_setvalue2(uint16_t value);\n")
       act_code=("void user_pwm_setvalue(uint16_t value)\n"
               +"{\n"
               +"   TIM_OC_InitTypeDef sConfigOC;\n"
               +"   sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
               +"   sConfigOC.Pulse = value;\n"
               +"   sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
               +"   sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
               +"   HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);\n"
               +"   HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);\n"  
               +"}\n")
               
       init_code=("  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);\n"
                 +"  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);\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'] == 'Dry_OTA'):
        creat_hex(jsonmsg)

## 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()
