def on_connect(client, userdata, flags, rc): global gConnected global status if rc == 0: cor = Color.F_Blue else: cor = Color.F_Red print(cor + "MQTT connected with result code " + str(rc) + Color.F_Default) log().debug("MQTT connected with result code " + str(rc)) if rc == 0: print("Connected to " + MQTT_HOST) gConnected = True status['mqtt'] = "on" client.connected_flag = True # Mostra clientes status['publish_time'] = dl.strDateTimeZone('now').isoformat() send_clients_status() else: gConnected = False status['mqtt'] = "off" if rc > 5: rc = 100 #print (str(rc) + str(tp_c[rc])) print(str(rc) + dl.MQTT_STATUS_CODE[rc]) log().error(str(rc) + str(dl.MQTT_STATUS_CODE[rc])) # tratar quando for 3 e outros if rc == 4 or rc == 5: # senha errada print(Color.F_Magenta + "APP EXIT" + str(rc) + Color.F_Default) time.sleep(60000)
def mqttStart(): ''' Start MQTT ''' global client global clientOk # MQTT Start client = mqtt.Client() log().info("Starting MQTT " + MQTT_HOST) print(Color.B_LightYellow + "Starting MQTT " + MQTT_HOST + Color.B_Default) if DEVELOPERS_MODE: log().debug("mqttStart MQTT_USERNAME: "******"mqttStart MQTT_PASSWORD: "******"Can't start MQTT") print(Color.F_Red + "Can't start MQTT" + Color.F_Default) # e.errno = 51 - 'Network is unreachable' mostraErro(e, 20, "MQTT Start") else: clientOk = False mostraErro(e, 30, "MQTT Start") if clientOk: client.loop_start() # start the loop
def on_disconnect(client, userdata, rc): global gConnected global gDevices_enviados global status gConnected = False log().info("disconnecting reason " + str(rc)) print("disconnecting reason " + str(rc)) client.connected_flag = False client.disconnect_flag = True gDevices_enviados['b'] = False # Force sending again status['mqtt'] = "off" # mostra cliente desconectado try: send_clients_status() except Exception as e: mostraErro(e, 30, "on_disconnect")
def substitui_secrets(): "No HASS.IO ADD-ON substitui os dados do secrets.ini pelos do options.json" global HOYMILES_USER global HOYMILES_PASSWORD global HOYMILES_PLANT_ID global MQTT_HOST global MQTT_PASSWORD global MQTT_USERNAME global DEVELOPERS_MODE log().debug("Loading env data....") HOYMILES_USER = dl.pegaEnv("HOYMILES_USER") HOYMILES_PASSWORD = dl.pegaEnv("HOYMILES_PASSWORD") HOYMILES_PLANT_ID = dl.pegaEnv("HOYMILES_PLANT_ID") MQTT_HOST = dl.pegaEnv("MQTT_HOST") MQTT_PASSWORD = dl.pegaEnv("MQTT_PASSWORD") MQTT_USERNAME = dl.pegaEnv("MQTT_USER") DEVELOPERS_MODE = dl.pegaEnv("DEVELOPERS_MODE") DEVELOPERS_MODE = dl.onOff(DEVELOPERS_MODE, True, False) log().debug("Env data loaded.")
def on_connect(client, userdata, flags, rc): global gConnected global status if rc == 0: cor = Color.F_Blue else: cor = Color.F_Red print(cor + "MQTT connected with result code " + str(rc) + Color.F_Default) log().debug("MQTT connected with result code " + str(rc)) if rc == 0: print("Connected to " + MQTT_HOST) gConnected = True status['mqtt'] = "on" client.connected_flag = True # Mostra clientes status['publish_time'] = datetime.today().strftime('%Y-%m-%d %H:%M:%S') send_clients_status() else: tp_c = { 0: "Connection successful", 1: "Connection refused – incorrect protocol version", 2: "Connection refused – invalid client identifier", 3: "Connection refused – server unavailable", 4: "Connection refused – bad username or password", 5: "Connection refused – not authorised", 100: "Connection refused - other things" } gConnected = False status['mqtt'] = "off" if rc > 5: rc = 100 #print (str(rc) + str(tp_c[rc])) print(str(rc) + dl.MQTT_STATUS_CODE(rc)) log().error(str(rc) + str(dl.MQTT_STATUS_CODE(rc))) # tratar quando for 3 e outros if rc == 4 or rc == 5: # senha errada print(Color.F_Magenta + "APP EXIT" + str(rc) + Color.F_Default) time.sleep(60000)
def send_hass(): ''' Envia parametros para incluir device no hass.io ''' global sensor_dic global gDevices_enviados # var comuns varComuns = { 'sw_version': VERSAO, 'model': SOLAR_MODEL, 'manufacturer': MANUFACTURER, 'device_name': APP_NAME, 'identifiers': SHORT_NAME + "_" + str(HOYMILES_PLANT_ID), 'via_device': SOLAR_MODEL, 'sid': SID, 'plant_id': HOYMILES_PLANT_ID, 'last_reset_topic': 'home/$sid/json_$plant_id', 'uniq_id': UUID } if DEVELOPERS_MODE: log().debug('Sensor_dic: ' + str(len(sensor_dic))) if len(sensor_dic) == 0: for k in json_hass.items(): json_file_path = k[0] + '.json' if dl.IN_HASSIO(): json_file_path = '/' + json_file_path # to run on HASS.IO if not os.path.isfile(json_file_path): log().error(json_file_path + " not found!") printC(Color.F_Cyan, json_file_path) json_file = open(json_file_path) if not json_file.readable(): printC(Color.B_Red, "I can't read file") json_str = json_file.read() sensor_dic[k[0]] = json.loads(json_str) if len(sensor_dic) == 0: printC(Color.B_Red, "Sensor_dic error") rc = 0 for k in sensor_dic.items(): # print('Componente:' + k[0]) rc = monta_publica_topico(k[0], sensor_dic[k[0]], varComuns) if not rc == 0: printC(Color.B_LightRed, 'Hass publish error: ' + str(rc)) if rc == 0: gDevices_enviados['b'] = True gDevices_enviados['t'] = datetime.now() log().debug('Hass Sended')
status['ip'] = dl.get_ip() print(Color.B_Cyan + "IP: " + Color.B_Default + Color.F_Magenta + status['ip'] + Color.F_Default) if DEVELOPERS_MODE: print(Color.B_Red, "DEVELOPERS_MODE", Color.B_Default) get_secrets() if dl.IN_HASSIO(): print(Color.B_Blue, "IN HASS.IO", Color.B_Default) if not DEVELOPERS_MODE or 1 == 1: # teste substitui_secrets() if DEVELOPERS_MODE: print(Color.B_Red, "DEVELOPERS_MODE", Color.B_Default) if DEFAULT_MQTT_PASS == MQTT_PASSWORD: log().warning("YOU SHOUD CHANGE DE DEFAULT MQTT PASSWORD!") print(Color.F_Red + "YOU SHOUD CHANGE DE DEFAULT MQTT PASSWORD!" + Color.F_Default) if DEVELOPERS_MODE or MQTT_HOST == '192.168.50.20': print(Color.F_Green + "HOYMILES_USER: "******"HOYMILES_PASSWORD: "******"HOYMILES_PLANT_ID: " + Color.F_Default + str(HOYMILES_PLANT_ID)) print(Color.F_Green + "MQTT_HOST: " + Color.F_Default + str(MQTT_HOST)) print(Color.F_Green + "MQTT_PASSWORD: "******"MQTT_USERNAME: " + Color.F_Default + str(MQTT_USERNAME))
def mqttStart(): ''' Start MQTT ''' global client global clientOk # MQTT Start # client = mqtt.Client(transport="tcp") # "websockets" client = mqtt.Client(client_id='', clean_session=True, userdata=None, protocol=MQTTversion, transport="tcp") # mqtt.MQTTv31 log().info("Starting MQTT " + MQTT_HOST) printC(Color.B_Blue, "Starting MQTT Client " + MQTT_HOST) if DEVELOPERS_MODE: printC(Color.F_Blue, "SSL: " + ssl.OPENSSL_VERSION) log().debug("mqttStart External: " + str(External_MQTT_Server) + ' ' + str(type(External_MQTT_Server))) log().debug("mqttStart TLS: " + str(External_MQTT_TLS) + ' ' + str(type(External_MQTT_TLS))) log().debug("mqttStart MQTT_USERNAME: "******"mqttStart MQTT_PASSWORD: "******"mqttStart MQTT_PORT: " + str(MQTT_PORT) + ' ' + str(type(MQTT_PORT))) client.username_pw_set(username=MQTT_USERNAME, password=MQTT_PASSWORD) client.on_connect = on_connect # client.on_message = on_message client.on_disconnect = on_disconnect client.on_publish = on_publish if DEVELOPERS_MODE: client.on_log = on_log #v.0.22 TLS if (External_MQTT_TLS): log().debug("Trying TLS: " + str(MQTT_PORT)) printC(Color.F_Green, "Trying TLS: " + str(MQTT_PORT) + " " + str(type(MQTT_PORT))) # ssl._create_default_https_context = ssl._create_unverified_context if DEVELOPERS_MODE: printC(Color.F_Magenta, "TLS_protocol_version: " + str(TLS_protocol_version)) context = ssl.SSLContext( protocol=TLS_protocol_version ) # ssl.PROTOCOL_TLSv1 , ssl.PROTOCOL_TLS_CLIENT #context.check_hostname = False client.tls_set_context(context) #ssl._create_default_https_context = ssl._create_unverified_context #ssl.create_default_context() #client.tls_set() #client.tls_set_context(ssl._create_unverified_context) #client.tls_insecure_set(True) #import certifi #client.tls_set(certifi.where()) try: clientOk = True #rc = client.connect(MQTT_HOST, MQTT_PORT, 60) # 1883 rc = client.connect(host=MQTT_HOST, port=int(MQTT_PORT), keepalive=60) # 1883 except Exception as e: # OSError if e.__class__.__name__ == 'OSError': clientOk = False log().warning("Can't start MQTT") print(Color.F_Red + "Can't start MQTT" + Color.F_Default) # e.errno = 51 - 'Network is unreachable' mostraErro(e, 20, "MQTT Start") else: clientOk = False mostraErro(e, 30, "MQTT Start") if clientOk: client.loop_start() # start the loop
def substitui_secrets(): "No HASS.IO ADD-ON substitui os dados do secrets.ini pelos do options.json" global HOYMILES_USER global HOYMILES_PASSWORD global HOYMILES_PLANT_ID global MQTT_HOST global MQTT_PASSWORD global MQTT_USERNAME global MQTT_PORT global DEVELOPERS_MODE global FILE_COMM global WEB_SERVER global Use_kW_instead_W global External_MQTT_Server global External_MQTT_Host global External_MQTT_User global External_MQTT_Pass global External_MQTT_TLS global External_MQTT_TLS_PORT global HASS_TIMEZONE log().debug("Loading env data....") HOYMILES_USER = dl.pegaEnv("HOYMILES_USER") HOYMILES_PASSWORD = dl.pegaEnv("HOYMILES_PASSWORD") HOYMILES_PLANT_ID = dl.pegaEnv("HOYMILES_PLANT_ID") MQTT_HOST = dl.pegaEnv("MQTT_HOST") MQTT_PASSWORD = dl.pegaEnv("MQTT_PASSWORD") MQTT_USERNAME = dl.pegaEnv("MQTT_USER") DEVELOPERS_MODE = dl.pegaEnv("DEVELOPERS_MODE") DEVELOPERS_MODE = dl.onOff(DEVELOPERS_MODE, True, False) if dl.IN_HASSIO(): WEB_SERVER = True FILE_COMM = '/data/' + comum.FILE_COMM #Use_kW_instead_W = dl.pegaEnv("Use_kW_instead_W") External_MQTT_Server = dl.pegaEnv("External_MQTT_Server") External_MQTT_Server = dl.onOff(External_MQTT_Server, True, False) External_MQTT_Host = dl.pegaEnv("External_MQTT_Host") External_MQTT_User = dl.pegaEnv("External_MQTT_User") External_MQTT_Pass = dl.pegaEnv("External_MQTT_Pass") #v0.22 External_MQTT_TLS = dl.pegaEnv("External_MQTT_TLS") External_MQTT_TLS = dl.onOff(External_MQTT_TLS, True, False) External_MQTT_TLS_PORT = dl.pegaEnv("External_MQTT_TLS_PORT") printC(Color.B_Red, "MQTT Server: " + str(MQTT_HOST)) printC(Color.B_Green, "Using External MQTT Server: " + str(External_MQTT_Server == True)) HASS_TIMEZONE = dl.pegaEnv("HASS_TIMEZONE") if (External_MQTT_Server): MQTT_HOST = External_MQTT_Host MQTT_PASSWORD = External_MQTT_Pass MQTT_USERNAME = External_MQTT_User printC(Color.B_Green, "Using External MQTT Server: " + str(MQTT_HOST)) if (External_MQTT_TLS): MQTT_PORT = External_MQTT_TLS_PORT printC(Color.B_Green, "Using External MQTT TLS PORT: " + str(MQTT_PORT)) #printC(Color.B_Red, "mqtt_extenal: " + str(External_MQTT_Host)) #printC(Color.B_Red, "Use_kW_instead_W: " + str(Use_kW_instead_W)) #printC(Color.B_Red, "External_MQTT: " + str(External_MQTT_User)) log().debug("Env data loaded.")